/*
1/. Read array
2/. set left margin to == width
3/. load image into background
4/. reduce left-margin to 0
5/. set background image of real back to that of slide
6/ repeat until array is empty
 
 
*/
 
var slideshow={
        counter: 0,
        repeat: true,   //true / false flag to set repeatability of cycle
        transition: 'fade',   //transition type  - currently 'fade' or 'slide'
        startState: 1, // 0=no image - transition to image 1; 1=1st image displayed from start - transition to image 2
        startdelay: 2000, //delay before slideshow starts
        transitiondelay: 2000,  //delay between transition starts
        transitiontime: 1800,   //time taken by transition - should be less than transition delay
 
        start: function()
        {
              if (document.getElementById("imageBoxSlideshow") && document.getElementById("bannerImages") && jQuery("#bannerImages img").length>0)
              {
                  /*window.setTimeout("slideshow[slideshow.transition]()",slideshow.startdelay);  - this is too clever for IE to parse*/
                  slideshow.div = jQuery("#imageBoxSlideshow");
                  slideshow.imageArray=jQuery("#bannerImages img");
                  //set first image
                  if (slideshow.startState==1)
                  {
                      slideshow.div.parent().css("background","url("+slideshow.imageArray[0].src+") 0 0 no-repeat");
                      if (slideshow.imageArray.length>1) slideshow.counter++;
                  }
                  if (slideshow.transition=='slide')
                  {
                      window.setTimeout("slideshow.slide()",slideshow.startdelay);
                  }
                  else if (slideshow.transition=='fade')
                  {
                      window.setTimeout("slideshow.fade()",slideshow.startdelay);
                  }
 
              }
        },
 
    fade: function()
    {
        var array=slideshow.imageArray;
        var div=slideshow.div;
        div.css("opacity",0);
        div.css("backgroundImage","url("+array[slideshow.counter].src+")");
        div.animate({opacity: 1},slideshow.transitiontime,slideshow.next);
    },
 
    reset: function(div)
    {
        if (slideshow.transition=='slide')
        {
            div.style.marginLeft=imagebx.clientWidth;
        }
        else if (slideshow.transition=='fade')
        {
             jQuery(div).css("opacity",0);
        }
    },
 
    next: function()
    {
        var imagebx=document.getElementById("imageBox");
        var slideshw=document.getElementById("imageBoxSlideshow");
        imagebx.style.backgroundImage=slideshw.style.backgroundImage;
        imagebx.style.backgroundPosition="0 0";
        imagebx.style.backgroundRepeat="no-repeat";
        slideshow.reset(slideshw);
        slideshow.counter++;
        if (slideshow.counter>=slideshow.imageArray.length && slideshow.repeat==true)
        {
 
                slideshow.counter=0;
         }
         else if (slideshow.counter>=slideshow.imageArray.length && slideshow.repeat==false)
        {
 
                return;
        }
 
             if (slideshow.transition=='slide')
            {
                 window.setTimeout("slideshow.slide()",slideshow.startdelay);
            }
            else if (slideshow.transition=='fade')
             {
                  window.setTimeout("slideshow.fade()",slideshow.startdelay);
            }
 
    }
 
 
};
var imageZoom = function(){
	jQuery("#wrap").anythingZoomer({
        	   expansionSize: 60,
        	   speedMultiplier: 1.3
    });
    //capturing events that need to hide the zoom box
    jQuery("#page").mouseleave(function(){jQuery("#mover").hide();});
    jQuery("#header-container").mouseover(function(){jQuery("#mover").hide();});
}

/*-------------------------------

configuring active nav links
--------------------------------*/

var configNavLinks=function()
{
	var pagelink=window.location.href;
	jQuery("#header-container a").each(function(){
		if (this.href==pagelink)
		{
			this.parentNode.className+=" active";
			
		}
		jQuery(this).append('<b></b>');
	});
}

/*-------------------------------

Social media
--------------------------------*/


function load_twitter_author(author)
{
	jQuery(document).ready(function($) {
        jQuery("#tweets").tweet({
          join_text: "auto",
          query: "from:"+author,
          avatar_size: 0,
          count: 2,
          auto_join_text_default: "", 
          auto_join_text_ed: "",
          auto_join_text_ing: "",

          auto_join_text_reply: "",
          auto_join_text_url: "",
          loading_text: "loading tweets..."
        });
      })
}

function get_rss_feed() {
	maxArticles=1;
	maxArticleLength=125;
	
	//clear the content in the div for the next feed.
	jQuery("#blogfeed").empty();
 
	//use the JQuery get to grab the URL from the selected item, put the results in to an argument for parsing in the inline function called when the feed retrieval is complete
	jQuery.get('/bridge/proxy.php?url=http://feeds.feedburner.com/oneforyouoneforme', function(d) {
		//find each 'item' in the file and parse it
		jQuery(d).find('item').each(function(i) {
			 if (i>=maxArticles) {
			 	return;
			 }
			//name the current found item this for this particular loop run
			var $item = jQuery(this);
			// grab the post title
			var title = $item.find('title').text();
			// grab the post's URL
			var link = $item.find('comments').text();
			// next, the description
			var description = $item.find('description').text();
			description=description.substr(0,maxArticleLength);
			description=description.replace(/(.*?)\s\S*$/,"$1...");
			//don't forget the pubdate
			var pubDate = $item.find('pubDate').text();
 
			// now create a var 'html' to store the markup we're using to output the feed to the browser window
			var html = "<div class=\"entry\"><h4 class=\"postTitle\"><a href='"+link+"'  target=\"_blank\">" + title + "</a><\/h4>";
			//html += "<em class=\"date\">" + pubDate + "</em>";
			html += "<p class=\"description\">" + description + " <a href='"+link+"'>Read more &raquo;</a></p>";
			//html += "<a href=\"" + link + "\" target=\"_blank\">Read More >><\/a><\/div>";
			html += "<\/div>";
 
			//put that feed content on the screen!
			jQuery('#blogfeed').append(jQuery(html));  
		});
	});
 
};

/*-------------------------------

Popup box
--------------------------------*/

var configurePopUpBox = function(){
 
jQuery("#openGiftPopup a").click(function(){
 	jQuery("#popupOverlay").show();
 	jQuery("#giftPopup").show(); 
 	return false;
}); //click handler
 
jQuery("#giftPopup a.close").click(function(){
 	jQuery("#giftPopup").hide();
 	jQuery("#popupOverlay").hide();
 	return false;
}); //close popup

jQuery("div.popup-block a.close").click(function(){
 	jQuery("div.popup-block").hide();
 	jQuery("#popupOverlay").hide();
 	return false;
}); //close all popup
 
};

/*-------------------------------

Shop cart and Gift Card functionality
--------------------------------*/
var acornCardCounter=0,acornWrappingCounter=0;
var acornWrapList= new Array();
var acornCardList= new Array();
function countGiftCardsInShopcart()
{
	var cell,a,input,title, testTitle;
	jQuery.cookie('card_counter', '0',{ path: '/'});
	jQuery.cookie('wrap_counter', '0',{ path: '/'});
	jQuery("#shopping-cart-table tbody tr").each(function(){
		cell=this.cells[1];
		a=jQuery("a",cell);
		title=a.attr("title");
		if (!title || title=="undefined")
		{
			return;
		}
		testTitle=title.toLowerCase();
		if (testTitle.indexOf("gift wrap")>-1)
		{
			jQuery(":text",this).blur(function(){updateCountGiftCardsInShopcart(); });
			acornWrapList.push(title);
		}
		else if (testTitle.indexOf("card")>-1)
		{
			jQuery(":text",this).blur(function(){updateCountGiftCardsInShopcart(); });
			acornCardList.push(title);
		}
	});
	updateCountGiftCardsInShopcart();
}

function updateCountGiftCardsInShopcart()
{
	acornCardCounter=0;
	acornWrappingCounter=0;
	var cell,a,input,title, testTitle;
	jQuery("#shopping-cart-table tbody tr").each(function(){
		cell=this.cells[1];
		a=jQuery("a",cell);
		title=a.attr("title");
		if (!title || title=="undefined")
		{
			return;
		}
		testTitle=title.toLowerCase();
		if (testTitle.indexOf("gift wrap")>-1)
		{
			input=jQuery(":text",this);
			acornWrappingCounter+=(input.val()/1);
		}
		else if (testTitle.indexOf("card")>-1)
		{
			
			input=jQuery(":text",this);
			acornCardCounter+=(input.val()/1);
		}
	});
	jQuery.cookie('wrap_counter', acornWrappingCounter,{ path: '/'});
	jQuery.cookie('card_counter', acornCardCounter,{ path: '/'});
	jQuery.cookie('wrap_names', acornWrapList.join("||"),{ path: '/'});
	jQuery.cookie('card_names', acornCardList.join("||"),{ path: '/'});
}



function pollCardWrappingDetails()
{
	var div=document.getElementById("opc-shipping_method");
	var div2=document.getElementById("allow-gift-message-container");
	if (div && div.className.indexOf("active")!=-1 &&  (div2 && div2.offsetWidth>0) )
	{
		configureCardWrappingDetails();
	}
	else
	{
		window.setTimeout("pollCardWrappingDetails()",500);
	}
}

var ActiveTextArea;

function configureCardWrappingDetails()
{
	var cardCounter=jQuery.cookie('card_counter');
	var wrapCounter=jQuery.cookie('wrap_counter');
	var cardNames=jQuery.cookie('card_names').split("||");
	var wrapNames=jQuery.cookie('wrap_names').split("||");
	//card management
	if (cardCounter<1 && wrapCounter<1)
	{
		jQuery("div.gift-messages-form").hide();
		//jQuery("#allow-gift-message-container").hide();
		return;
	}
	jQuery("#allow-gift-message-container textarea.giftmessage-area").each(function(){
		if (this.value=="")
		{
			this.value="[card][/card]\n[wrapping][/wrapping]\n[message][/message]";
		}
		//this.className+=" hidden";
	});
	
	jQuery("div.gift-messages-form input.choose_card, div.gift-messages-form a.cardChangeLink").click(function(){
		var checkset=jQuery("div.gift-messages-form input.choose_card:checked");
		ActiveTextArea=jQuery("textarea.giftmessage-area",this.parentNode.parentNode);
		if (checkset.length>cardCounter)
		{
			alert("You have only purchased "+cardCounter+" gift cards. Please update the QTY field in your cart to purchase more." );
			return false;
		}
		if (this.nodeName=="A" || (this.nodeName=="INPUT" && this.checked==true) )
		{
			jQuery("#cardPopup").show();
		}
		else
		{
			var value=ActiveTextArea.val();
			value=value.replace(/\[card\].*?\[\/card\]/,"[card][/card]");
			ActiveTextArea.val(value);
			//hide thumbnail
			jQuery("img.cardThumbnail",this.parentNode.parentNode).hide();
			jQuery("a.cardChangeLink",this.parentNode.parentNode).hide();
		}
		if (this.nodeName=="A")
		{
			return false;
		}
		
	});
	
	
jQuery("#cardPopup ul.form-list a").click(function(){
		var card=this.href.replace(/^.*?#(.*?)$/,"$1");
		card=card.replace(/_/g," ");
		var value=ActiveTextArea.val();
		if (value=="")
		{
			ActiveTextArea.val("[card][/card]\n[wrapping][/wrapping]\n[message][/message]");
			value="[card][/card]\n[wrapping][/wrapping]\n[message][/message]";
		}
		value=value.replace(/\[card\].*?\[\/card\]/,"[card]"+card+"[/card]");
		ActiveTextArea.val(value);
		//update the wrap image
		var thumb=jQuery("img.cardThumbnail",ActiveTextArea[0].parentNode.parentNode.parentNode);
		var imgSrc=jQuery("img",this).attr("src");
		thumb.attr("src",imgSrc).show();
		jQuery("a.cardChangeLink",ActiveTextArea[0].parentNode.parentNode.parentNode).show();
		//hide the overlay
		jQuery("div.popup-block").hide();
 		jQuery("#popupOverlay").hide();
		return false;
	});

	
	//wrapping management
	jQuery("div.gift-messages-form input.choose_wrap, div.gift-messages-form a.wrapChangeLink").click(function(){
		var checkset=jQuery("div.gift-messages-form input.choose_wrap:checked");
		ActiveTextArea=jQuery("textarea.giftmessage-area",this.parentNode.parentNode);
		if (checkset.length>wrapCounter)
		{
			alert("You have only purchased "+wrapCounter+" gift wrapping. Please update the QTY field in your cart to purchase more." );
			return false;
		}
		
		if (this.nodeName=="A" || (this.nodeName=="INPUT" && this.checked==true) )
		{
			jQuery("#wrapPopup").show();
		}
		else
		{
			var value=ActiveTextArea.val();
			value=value.replace(/\[wrapping\].*?\[\/wrapping\]/,"[wrapping][/wrapping]");
			ActiveTextArea.val(value);
			//hide thumbnail
			jQuery("img.wrapThumbnail",this.parentNode.parentNode).hide();
			jQuery("a.wrapChangeLink",this.parentNode.parentNode).hide();
		}
		if (this.nodeName=="A")
		{
			return false;
		}
		
	});
	
	jQuery("#wrapPopup ul.form-list a").click(function(){
		var wrap=this.href.replace(/^.*?#(.*?)$/,"$1");
		wrap=wrap.replace(/_/g," ");
		var value=ActiveTextArea.val();
		if (value=="")
		{
			ActiveTextArea.val("[card][/card]\n[wrapping][/wrapping]\n[message][/message]");
			value="[card][/card]\n[wrapping][/wrapping]\n[message][/message]";
		}
		value=value.replace(/\[wrapping\].*?\[\/wrapping\]/,"[wrapping]"+wrap+"[/wrapping]");
		ActiveTextArea.val(value);
		//update the wrap image
		var thumb=jQuery("img.wrapThumbnail",ActiveTextArea[0].parentNode.parentNode.parentNode);
		var imgSrc=jQuery("img",this).attr("src");
		thumb.attr("src",imgSrc).show();
		jQuery("a.wrapChangeLink",ActiveTextArea[0].parentNode.parentNode.parentNode).show();
		//hide the overlay
		jQuery("div.popup-block").hide();
 		jQuery("#popupOverlay").hide();
		return false;
	});
	
	//message management
	jQuery("#allow-gift-message-container textarea.userMessageField").blur(function(){
		ActiveTextArea=jQuery("textarea.giftmessage-area",this.parentNode.parentNode);
		var value=ActiveTextArea.val();
		if (value=="")
		{
			ActiveTextArea.val("[card][/card]\n[wrapping][/wrapping]\n[message][/message]");
			value="[card][/card]\n[wrapping][/wrapping]\n[message][/message]";
		}
		value=value.replace(/\[message\].*?\[\/message\]/,"[message]"+this.value+"[/message]");
		ActiveTextArea.val(value);
	});
	
}


/****************************************
* GIFT CARD AND WRAP SELECTION AT PRODUCT LEVEL
*****************************************/

function configureGiftCardUI()
{
	cardNames=jQuery.cookie('card_names');
	if (cardNames)
	{
		cardNames=cardNames.split("||");
	}
	else
	{
		cardNames=new Array();
	}
	wrapNames=jQuery.cookie('wrap_names');
	if (wrapNames)
	{
		wrapNames=wrapNames.split("||");
	}
	else
	{
		wrapNames=new Array();
	}
	var links=jQuery("#cardPopup ul.form-list a").each(function(){
		var card=this.href.replace(/^.*?#(.*?)$/,"$1");
		card=card.replace(/_/g," ");
		matchGiftCardUI(this,card);
	});
	if (!(document.getElementById("checkoutSteps")||document.getElementById("shipping_method_table")))
	{
		links.click(function(){
			selectGiftCardUI(this);
			return false;
		});
	}
}

function configureGiftWrapUI()
{
	
	var links=jQuery("#wrapPopup ul.form-list a").each(function(){
		var card=this.href.replace(/^.*?#(.*?)$/,"$1");
		card=card.replace(/_/g," ");
		matchGiftCardUI(this,card);
	});
	if (!(document.getElementById("checkoutSteps")||document.getElementById("shipping_method_table")))
	{
		links.click(function(){
			selectGiftWrapUI(this);
			return false;
		});
	}
	
}

function matchGiftCardUI(a,card)
{
	var i,id,displaystate,test,flag_product=false, flag_checkout=(document.getElementById("checkoutSteps")||document.getElementById("shipping_method_table"));
	if (flag_checkout)
	{
		displaystate="none";
		var fullList=cardNames.concat(wrapNames);
		for (i=0; i<fullList.length; i++)
		{
			if (card==fullList[i])
			{
				displaystate="block";
			}
		}
		a.parentNode.style.display=displaystate;
		return;
	}
	else
	{
		jQuery("#block-related label").each(function(){
			test=this.innerHTML.indexOf(card);
			if (test>-1) 
			{
				flag_product=true;
				id=jQuery("input",this.parentNode).attr("id");
			}
		});
	}
	
	if (flag_product)
	{
		a.chkbox=id;
	}
	else
	{
		a.className="inactive";
	}
}

function selectGiftCardUI(a)
{
	cancelSelectedGiftWrapUI("cardPopup");
	var id=a.chkbox;
	jQuery("#"+id).attr("checked",true);
	jQuery("#related-checkbox-Card").attr("checked",true);
	//Update the list of associated items in core code!!
	if (!window.addRelatedToProduct)
	{
		alert("notify developer: change in system code [addRelatedToProduct()]");
	}
	else
	{
		addRelatedToProduct();
	}
	
	//hide the overlay
	jQuery("div.popup-block").hide();
	jQuery("#popupOverlay").hide();
}

function selectGiftWrapUI(a)
{
	cancelSelectedGiftWrapUI("wrapPopup");
	var id=a.chkbox;
	jQuery("#"+id).attr("checked",true);
	jQuery("#related-checkbox-Wrap").attr("checked",true);
	//Update the list of associated items in core code!!
	addRelatedToProduct();
	//hide the overlay
	jQuery("div.popup-block").hide();
	jQuery("#popupOverlay").hide();
}

function cancelSelectedGiftWrapUI(divId)
{
	jQuery("#"+divId+" a").each(function(){
		jQuery("#"+this.chkbox).attr("checked",false);
	});
}



 
jQuery(window).ready(function(){
configurePopUpBox();
slideshow.start();
imageZoom();
configNavLinks();
 if (document.getElementById("blogfeed")) get_rss_feed();
jQuery("#shopping-cart-table").each(function(){countGiftCardsInShopcart();});

var singleDeliveryAddress=document.getElementById("checkoutSteps");
var cardWrappingDetails=document.getElementById("allow-gift-message-container");
if (singleDeliveryAddress && cardWrappingDetails)
{
	pollCardWrappingDetails();

}
else if (cardWrappingDetails)
{
	configureCardWrappingDetails();
}

});

