//=============================================================================
// Cookie Utils
//=============================================================================

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split( ';' );
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for ( i = 0; i < a_all_cookies.length; i++ )
        {
                // now we'll split apart each name=value pair
                a_temp_cookie = a_all_cookies[i].split( '=' );


                // and trim left/right whitespace while we're at it
                cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

                // if the extracted name matches passed check_name
                if ( cookie_name == check_name )
                {
                        b_cookie_found = true;
                        // we need to handle case where cookie has no value but exists (no = sign, that is):
                        if ( a_temp_cookie.length > 1 )
                        {
                                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                        }
                        // note that in cases where cookie is initialized but no value, null is returned
                        return cookie_value;
                        break;
                }
                a_temp_cookie = null;
                cookie_name = '';
        }
        if ( !b_cookie_found )
        {
                return null;
        }
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

//=============================================================================
// Shopping cart
//=============================================================================

// An array of shop-item-id as strings.
var cart = new Array();

function saveCart() {
    Set_Cookie('cart', cart.join(","));
}

function restoreCart() {
    var cart_cookie = Get_Cookie('cart');
    if (cart_cookie) {
	cart = cart_cookie.split(",");
    }
}

function flashMiniCart() {
    var cart = $('.mini-cart');
    for (var i=0; i<3; i++) {
        cart.fadeOut(100);
        cart.fadeIn(100);
    }
}

function updateCart() {
    if (cart.length > 0) {
	if (cart.length == 1) {
	    $('.mini-cart .cart-single-item-label').show();
	    $('.mini-cart .cart-multi-items-label').hide();
	} else {
	    $('.mini-cart .cart-single-item-label').hide();
	    $('.mini-cart .cart-multi-items-label').show();
	}
	$('.mini-cart').show();
	$('.mini-cart .item-count').text(cart.length);
    }
}

function buyItem(shopItemId) {
    // Make sure items in cart always is strings to simplify duplicate check.
    shopItemId = shopItemId.toString();
    // Only add item if it's not already in cart
    if ($.inArray(shopItemId, cart) == -1) {
        cart.push(shopItemId);
    }
    saveCart();
    updateCart();
    flashMiniCart();
}

$(document).ready(function() {
    restoreCart();
    updateCart();
});

//=============================================================================
// Customer toolbar / "session"
//=============================================================================

function getCustomer() {
    var name = Get_Cookie("customer");
    if (name) {
	return {name: name};
    } else {
	return undefined;
    }
}

function updateCustomerToolbar() {
    var customer = getCustomer();
    if (customer) {
	$('#customer-name').text(customer.name);
	$('.customer-toolbar').show();
	$('.sign-in-button').hide();
      	$('.sign-out-button').show();
    }
}

$(document).ready(function() {
    if (getCustomer()) {
        updateCustomerToolbar();
    } else if (Get_Cookie("rememberme")) {
        // Customer is known might be known. Doing an ajax request to an
	// uncached page to update customer cookie.
	$.get("/mypage", function () {
 	    updateCustomerToolbar();
        });
    }
});

//=============================================================================
// Favorites
//=============================================================================

function storeFavorites(favorite) {
    Set_Cookie("favorites", '{"tracks":[' + favorite.tracks.join(",") + '],' +
	                    '"albums":[' + favorite.albums.join(",")  + '],' +
	                    '"artists":[' + favorite.artists.join(",") + ']}');
}

function restoreFavorites() {
    try {
	var favorite = eval('(' + Get_Cookie("favorites") + ')');
	if (favorite) {
	    updateFavorites(favorite);
	} else {
	    $.post("toggle-favorite.do", updateFavorites, "json");
	}
    } catch (err) {};
}

function updateFavorites(favorite) {
    storeFavorites(favorite);
    $(".track-favorite").removeClass("selected");
    for (var i = 0; i < favorite.tracks.length; i++) {
	$(".track-" + favorite.tracks[i] +" .track-favorite").addClass("selected");
    }
    $(".favorite-album").removeClass("selected");
    for (var i = 0; i < favorite.albums.length; i++) {
	$(".favorite-album-" + favorite.albums[i]).addClass("selected");
    }
    for (var i = 0; i < favorite.artists.length; i++) {
	$(".favorite-artist-" + favorite.artists[i]).addClass("selected");
    }
}

function toogleFavorite(data) {
    if (!getCustomer()) {
	// User is not logged in
	window.location = "/login";
	return;
    }
    $.post("toggle-favorite.do", data, function (favorite) {
       updateFavorites(favorite);
    }, "json");
}

function toggleFavoriteTrack(trackId) {
    toogleFavorite({"track-id": trackId});
}

function toggleFavoriteAlbum(albumId) {
    toogleFavorite({"album-id": albumId});
}

function toggleFavoriteArtist(artistId) {
    toogleFavorite({"artist-id": artistId});
}

$(document).ready(function() {
    if ($(".track-favorite").length || $(".favorite-album").length) {
        if (Get_Cookie("rememberme") || Get_Cookie("customer")) {
	    restoreFavorites();
	}
    }
});

//=============================================================================
// Other public stuff
//=============================================================================

function toggleTrackDetails(id) {
  var wasOpen = $('.track-' + id).hasClass('open');
  $('.track').removeClass('open');
  $('.track-details').slideUp(250);
  if (!wasOpen) {
    $('.track-' + id).addClass('open');
    $('.track-details-' + id).slideDown(250);
  }
}

function idSelector(id) {
  return "#" + id.replace(/\.|\[|\]/g, "\\$&");
}

var slidesIdCounter = 1;

function initSlides(slides) {
  if ($(".slides-images img", slides).length > 1) {
    var id = slidesIdCounter++;
    $(".slides-images", slides).attr("id", "slides-images-" + id);
    $(".slides-prev", slides).attr("id", "slides-prev-" + id);
    $(".slides-next", slides).attr("id", "slides-next-" + id);
    $("#slides-images-" + id).cycle({
      fx: 'fade',
      speed: 'fast',
      timeout: 15000,
      prev: '#slides-prev-' + id,
      next: '#slides-next-' + id
    });
  } else {
    $(".pager-buttons", slides).css("visibility", "hidden");
  }
}

$(document).ready(function() {
   /*
   $('[href^=toggle-favorite]').bind('click', function() {
       $.post(this.href, function(statusvalue) {
	   if (status == 'OK')
	     window.location.reload();
	   else
	     window.location = "/login?url=" + window.location;
     });
     return false;
   });
   */

   $(".slides").each(function () {
     initSlides(this);
   });

   $('.album-in-grid').hover(
     function () { $('.legend', this).slideUp(150); },
     function () { $('.legend', this).slideDown(150); }
   );

   $('.slides').bind('mousemove', function (event) {
     var y = event.pageY - $(this).offset().top;
     if (y < 310) {
       $('.legend', this).slideUp(150);
     } else {
       $('.legend', this).slideDown(150);
     }
   });
   $('.slides').bind('mouseout', function (event) {
     $('.legend', this).slideDown(150);
   });
});

//=============================================================================
// Admin stuff
//=============================================================================

function uploadCdImagePopup(albumID) {
  window.open(
    "upload-cd-image.do?album-id=" + albumID,
    "upload-cd-image-album-id" + albumID,
    "toolbar=no,location=no,directories=no,status=no,menubar=no," +
    "resizable=yes,copyhistory=yes,width=550,height=200");
}

function updateSystemMessage(msgid) {
  $('#' + msgid + '-STATUS').hide();
  var mce = tinyMCE.get(msgid);
  var value = mce ? mce.getContent() : document.getElementById(msgid).value;
  $.post('edit-system-messages.do', {
	   method: 'store',
	   msgid: msgid,
	   'new-message': value
	 }, function () {
	   $('#' + msgid + '-STATUS').show();
	   $('#' + msgid + '-STATUS').fadeOut(3000);
	 });
}

function makeAutoComplete(id_input, text_input, type) {
  $(idSelector(text_input)).autocomplete("search",
    {
      extraParams: {method: "auto-complete", type: type},
      formatResult: function(data) {
	return data[1];
      }
    }
  ).result(function(event, data, formatted) {
    $(idSelector(id_input))[0].value = data[2];
  });
}

function makeTrackMetaSearch(selector, params) {
  if ($.Autocompleter) {
    $(document).ready(function() {
      $(selector).autocomplete("search-track-meta.do",
	{
	  extraParams: params,
	  formatItem: function(item) {
	    item = eval("("+ item +")");
	    return item.title + " <i style='font-size: 80%'>(used on <b>"
	           + item.count + "</b> track"
    		   + ((item.count == 1) ? "" : "s")
		   + ")</i>";
	  },
	  formatResult: function(item) {
	    return eval("("+ item +")").title;
	  }
	}
      );
    });
  }
}
