///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////// jquery ///////////////////////////////////
///////////////////////////////////////////////////////////////////////////////


jQuery.noConflict();

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////// declarations ////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

var backgroundcolors = ["#ffffc0", "#ff8080", "#bfbfff", "#b8ff82", "#FFCCCC", "#ffdb5d"];

var backHit = false;

var ajaxQueue = [];
var inAjax = false;
var ajaxResponseQueue = [];

var trackLists = new Array();

var selectedTL = -1;

var currentCat = null;

var mySound = null;
var soundid = 0;

var banners=new Array(
{url:'banner1',time:32000},
{url:'banner2',time:19000},
{url:'banner',time:12500},
//{url: 'x/4/banner',time:12500}
{url:'train/banner',time:12500}
);

var bannerPtr=0;

function getAnchor() {
return(window.location.hash.replace(/#/,''));
}



function goAnchor() {
      var anch = getAnchor();
      var a=anch.split('_');
      if (a[0]=='p') {
        product_click(a[1]);
      }
      if (a[0]=='c') {
        updateAndShowProducts(a[1]);
      }
}

function runAjax() {
 if (!inAjax&&ajaxQueue.length>0) {
   inAjax=true;
   var k = ajaxQueue.shift();
   eval(k.cmd);
   ajaxResponseQueue.push(k);
 }
}

function ajaxQueue_add(req) {
  ajaxQueue.push(req);
  if(!backHit) jQuery(req.selector).animate({"opacity": 0.3}, 500);
}

function updateAndShowProducts(category) {
  ajaxQueue_add({"selector": "#dnn_ctr405_ViewKSATProduct_pnlKSATPV", "after":"",
  "cmd": "postCategory(" + category + ")"});
  ajaxQueue_add({"selector": "#dnn_ctr384_SqlSharp_ctl00_upContent", "after":"",
  "cmd": "update_('category'," + category + ")"});
  runAjax();
  window.location.hash = "c_" + category;
}

function product_click(p) {
  ajaxQueue_add({"selector": "#dnn_ctr405_ViewKSATProduct_pnlKSATPV", "after":"",
  "cmd": "postProduct(" + p + ")"});
  runAjax();
  window.location.hash = "p_" + p;
}

function loadCD() {
	jQuery(".tracklistTitle").fadeOut("slow", function() {jQuery(this).html("CD contents").fadeIn("slow")});
	jQuery(".dvdContent").fadeOut("slow", function() { jQuery(".trackList").fadeIn("slow");
	jQuery(".trackListMenu").fadeIn("slow");
	jQuery(".tracklistPrompt").fadeIn("slow");
	});
	jQuery(".tabMenuItem").removeClass("sel"); 
	jQuery(".tabMenuClass .tabMenuItem:eq(0)").addClass("sel");
}

function loadDVD() {	
	jQuery(".trackList").fadeOut("slow", function() { jQuery(".dvdContent").fadeIn("slow"); });
	jQuery(".tabMenuItem").removeClass("sel"); 
	jQuery(".trackListMenu").fadeOut("slow");
	jQuery(".tracklistTitle").fadeOut("slow", function() {jQuery(this).html("DVD contents").fadeIn("slow")});
	jQuery(".tracklistPrompt").fadeOut("slow");
	jQuery(".tabMenuClass .tabMenuItem:eq(1)").addClass("sel");
}

function populateTracklists() {
for ( var i in trackLists ) {
if(i==0){selectedTL=i;}
jQuery(".trackListList").append("<div class=\"lozenge\"><div onmouseover=\"showTracklist("+i+")\" class=\"trackListChoice\" id=\"tl" + i + "\" onmouseout=\"hideTracklist()\"> " + (Number(i)+1) + "</div></div>");
}
if (selectedTL>=0){jQuery("#tl" + selectedTL).addClass("sel").parent().addClass("sel");}
  jQuery(".trackListChoice").each(function(i) {
    var k = i;
    jQuery(this).hover(function() {
      jQuery(this).parent().addClass("mouseOver");
      jQuery(this).addClass("mouseOver");
    },
    function() {
      jQuery(this).parent().removeClass("mouseOver");
      jQuery(this).removeClass("mouseOver");
    });
  });
}


function displayTracklist(tlID) {
  if ( trackLists[tlID] ) {
    jQuery(".tracklistTitle").html("Tracklist " + ( Number(tlID) + 1 ) );
	// strip trackIDs
    trackLists[tlID][2] = String(trackLists[tlID][2]).replace(/\[[0-9X]{5}\]/g, '');
    jQuery(".trackList").html(trackLists[tlID][2]);
  }
}

function showTracklist(tlID) {
//displayTracklist(tlID);
}

function hideTracklist() {if(selectedTL>-1){displayTracklist(selectedTL);}}


function ksatEndRequestHandler() {
if(ajaxResponseQueue.length>0){
   inAjax=false;
   var k = ajaxResponseQueue.shift();
   jQuery(k.selector).stop().animate({"opacity": 1.0}, 500);
   eval(k.after);
   }
if (ajaxQueue.length>0) {runAjax();}
}

function loadCategoryOnPage() {
var url = window.location.href;
var segments = url.split("/");
//alert(segments);
}


function tracklistRenew(tl) {
trackLists = tl;
populateTracklists();
displayTracklist(selectedTL);
}


function personalise(did) {
//var href = "/personalisation/DocumentID/" + escape(did) + "/TrackList/" + escape(trackLists[selectedTL][0]) + "/CartID/" + getCartID() + "/ProductID/" + escape(getMyProductID()) + ".aspx";
var href = "/personalisation.aspx?DocumentID=" + escape(did) + "&TrackList=" + escape(trackLists[selectedTL][0]) + "&CartID=" + escape(getCartID()) + "&ProductID=" + escape(getMyProductID());
window.location.href = href;
}

function backgroundStyleOut(elem,i) {
  elem.style.backgroundImage = elem.style.backgroundImage.replace(/\/selItem/, "/unselItem");
}

function backgroundStyleOver(elem,i) {
  elem.style.backgroundImage = elem.style.backgroundImage.replace(/\/unselItem/, "/selItem");
}


function animateCustomizeButton() {
jQuery(".customizeButton").each(function(i) {
    jQuery(this).hover(function() { // mouseover
      jQuery(this).parent().addClass("mouseOver");
      jQuery(this).addClass("mouseOver");
      backgroundStyleOver(this,0);
    },
    function() { // mouseout
      jQuery(this).parent().removeClass("mouseOver");
      jQuery(this).removeClass("mouseOver");
      backgroundStyleOut(this,0);
    });
    backgroundStyleOut(this,0);
  });
}

///////////////////////////////////////////////////////////////////////////////
//////////////////////////////// soundmanager2 ////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

function playUpdate(){
    jQuery(".media_player").css("background-image","url(http://images.kidsstuffandthings.com/k/icons/playing.png)");
}

function showControls() {
  jQuery("#stopbutton").show("slow");
}

function hideControls() {
  jQuery("#stopbutton").hide("slow");
}

function prehear(uri) {
  //alert('Playing: ' + uri);
  showControls();
  if ( mySound != null ) {
    soundManager.unload("mySound" + soundid); 
  }
  soundid++;
  mySound = soundManager.createSound({
              id: "mySound" + soundid,
              url: uri,
              autoPlay: true,
              onfinish: hideControls
            });
}

function stop_play() {
  soundManager.unload("mySound" + soundid);
  hideControls();
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////// banner code /////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

function draw500340() {
swfobject.embedSWF("http://images.kidsstuffandthings.com/k/banners/500_340/banner.swf", "centreBannerContainer", "500", "340", "8", false, {xml_path: 'http://images.kidsstuffandthings.com/k/front_500x340.xml'});
//swfobject.embedSWF("http://images.kidsstuffandthings.com/k/xmas09.swf", "centreBannerContainer", "500", "340", "8", false, {xml_path: 'http://images.kidsstuffandthings.com/k/front_500x340.xml'});
}
function fixAnchorTitleBug() { 
  if (jQuery.browser.msie) {
    document.title = document.originalTitle; 
  }
}


function runBanner() {
  if(banners&&swfobject){
  var b = banners[bannerPtr];
  swfobject.embedSWF('http://images.kidsstuffandthings.com/k/banners/' + b.url + '.swf', "bannerContainer", "970", "141", "9.0.0", false, {loop:"false", xml_path:'http://images.kidsstuffandthings.com/k/banners/' + b.url + '_data.xml'}, {loop:"false"}, {loop:"false"});
  setTimeout("runBanner()",b.time);
  bannerPtr++;
  if (bannerPtr==banners.length) {bannerPtr=0;}
  fixAnchorTitleBug();
  }
}

///////////////////////////////////////////////////////////////////////////////
//////////////////////////// KSATProduct module ///////////////////////////////
///////////////////////////////////////////////////////////////////////////////

function selectTracklist(tlID) {
  if(ksatProduct){
    jQuery("#" + ksatProduct.txtDesiredTracklist).attr("value",trackLists[tlID][0]);
    selectedTL = tlID;
    jQuery(".tick").addClass("unsel");
    jQuery(".trackListChoice").removeClass("sel").parent().removeClass("sel");
    jQuery("#tl" + tlID).addClass("sel").parent().addClass("sel");
    jQuery("#tlt" + tlID).removeClass("unsel");
    displayTracklist(tlID);
  }
}

function postCategory (catID) {
  if(ksatProduct){
    jQuery("#" + ksatProduct.txtCatID).attr("value",catID);
    __doPostBack(ksatProduct.btnLoadC.replace(/\_/g,"$"),"");
  }
}

function postProduct (prodID) {
  if(ksatProduct){
    jQuery("#" + ksatProduct.txtProdID).attr("value",prodID);
    __doPostBack(ksatProduct.btnLoadP.replace(/\_/g,"$"),"");
  }
}

function getCartID() {
  if(ksatProduct){
    return jQuery("#" + ksatProduct.txtCartID).attr("value");
  }
}

function getMyProductID() {
  if(ksatProduct){
    return jQuery("#" + ksatProduct.txtMyProductID).attr("value");
  }
}

function attachTracklistChoices() {
  jQuery(".trackListChoice").click(
    function() {
      selectTracklist(this.id.replace(/tl/,''));
    }
  );
}
///////////////////////////////////////////////////////////////////////////////
//////////////////////////// on DOM content loaded ////////////////////////////
///////////////////////////////////////////////////////////////////////////////

jQuery(document).ready(function(){

  jQuery(".CouponCode").change(function() {
	jQuery(this).val(String(jQuery(this).val()).toUpperCase());
  });
  if (jQuery.browser.msie) { // fix obscure bug with hashes appearing in page title
    document.originalTitle = document.title;
    window.attachEvent('onload', fixAnchorTitleBug); 
  }
  
  try { // sort out ajax
    var p = Sys.WebForms.PageRequestManager.getInstance();
  }
  catch(exc) {
  }
  if(p!=null && !p.get_isInAsyncPostBack()) {
    p.add_endRequest(ksatEndRequestHandler); 
  }
  animateCustomizeButton();

  jQuery(".checkoutLink").hover(function() {
      jQuery(this).parent().addClass("mouseOver");
      jQuery(this).addClass("mouseOver");
      jQuery(this).parent().css("backgroundColor", backgroundcolors[3]);
      backgroundStyleOver(this,0);
    0},
    function() {
      jQuery(this).parent().removeClass("mouseOver");
      jQuery(this).removeClass("mouseOver");
      jQuery(this).parent().css("backgroundColor", "transparent");
      backgroundStyleOut(this,0);
    }
  ).click(
    function() {
      window.location.href='http://www.kidsstuffandthings.com/Basket/tabid/64/Default.aspx';
    }
  );
      
  jQuery(".categoryChoice").each(function(i) {
    var k = i;
    jQuery(this).children(".arrow").css("backgroundPosition","-" + i*30 + "px -30px").fadeIn();
    jQuery(this).hover(function() {
      jQuery(this).parent().addClass("mouseOver");
      jQuery(this).addClass("mouseOver");
      jQuery(this).children(".arrow").css("backgroundPosition","-" + i*30 + "px 0px");
      jQuery(this).parent().css("backgroundColor", backgroundcolors[(i % backgroundcolors.length)]);
      backgroundStyleOver(this,k);
    },
    function() {
      if ( currentCat != this ) {
      jQuery(this).parent().removeClass("mouseOver");
      jQuery(this).removeClass("mouseOver");
      jQuery(this).parent().css("backgroundColor", "transparent");
      jQuery(this).children(".arrow").css("backgroundPosition","-" + i*30 + "px -30px");
      backgroundStyleOut(this,k);
      }
    });
  });
  
  if(window.location.href.match(/store\.aspx$/) || window.location.href.match(/default\.aspx$/i) || window.location.href.match(/\/$/)) {
    jQuery("#dnn_ctr384_SqlSharp_ctl00_upContent").load("/Portals/0/rightPane.html");
  }
  
  jQuery(".categoryChoice").click(function() {
    if (currentCat != null) {
      jQuery(currentCat).parent().removeClass("mouseOver");
      jQuery(currentCat).removeClass("mouseOver");
      jQuery(currentCat).parent().css("backgroundColor", "transparent");
      backgroundStyleOut(currentCat,0);
    }
    currentCat = this;
  });
  attachTracklistChoices();
  //jQuery("img[@src$=png]").pngfix();
  if(getAnchor() != '') {
    //backHit=true;
    setTimeout("goAnchor()",0);
  }
  
  setTimeout("runBanner()",2000);
  jQuery("#stopbutton").click(
    stop_play
  );
});


// play/mp3/mp4 buttons
var myMouseoverColour=0;
function newMouseoverColour () {
  myMouseoverColour = (myMouseoverColour + 1) % 7;
  return myMouseoverColour;
}
function setupAlphaBrowser() {
		jQuery(".alpha div").hover(function(){
		    jQuery(this).addClass("mo_" + newMouseoverColour());
		 },
		function(){
		jQuery(this).removeClass("mo_" + myMouseoverColour);
		});
}
          

jQuery(document).ready(function(){
	setupAlphaBrowser();

          jQuery(".eshresult .DiAZ").live("mouseover", function(){
                jQuery(".DiMP3E", this).addClass("DiMP3F");
                });
            jQuery(".eshresult .DiAZ").live("mouseout", function(){
                jQuery(".DiMP3E", this).removeClass("DiMP3F");
                });
          
          jQuery(".DiMP3").live("mouseover", function(){      
                jQuery(".DiMP3E", this).addClass("DiMP3F")
		jQuery(this).addClass("DiMP3D").addClass("mo_" + newMouseoverColour());
            });             
            jQuery(".DiMP3").live("mouseout", function(){        
                jQuery(".DiMP3E", this).removeClass("DiMP3F");
                jQuery(this).removeClass("DiMP3D").removeClass("mo_" + myMouseoverColour);
            });
});
///////////////////pageload funciton to make buttons work after asyncro post/////////////              
