/*** COPYRIGHT 2009  BY FDM4 INTERNATIONAL INC. - ALL RIGHTS RESERVED ********/
/*** CartHover.js -- Renders order info and provides add-to-cart           ***/ 
/*****************************************************************************/
/*C010002 08/13/10 APY- Change empty cart msg and remove $ subtotal.         */
/*C010001 08/02/10 APY- Add 'close' button to floatingAddedToCart.           */
/*C010000 05/24/10 APY- Add styleCode to "floatingAddedToCart" id multi-prod.*/
/*****************************************************************************/
/* 010100 02/24/10 APY- Split cartStub and added product display.            */
/* 010005 07/24/09 APY- Add proper relative path for xmlURL.                 */
/* 010004 06/25/09 APY- Correction for when in item mode.                    */
/* 010003 06/22/09 APY- Use jQuery to calc floating cart position.           */
/* 010002 05/19/09 APY- Correct FF border, add selector param for msg display*/
/* 010001 05/05/09 JB - Removed hard-coded paths, changed positioning logic. */
/* 010000 04/02/09 JB - Add to RTB, use product type, cart label.            */
/*****************************************************************************/
/* Variables */
var vParams2 = "?frames=no&target=main&sponsor="+fdmSponsor;
var xmlUrl = appPath + "/xml/cartRequest.w" + vParams2; /* 010005 */
var myCart = new Cart("0");
var CartShown = false;
var cartTimer, addedTimer;
var vAddedDispTime = 4000; /* 010100 */
var boundFloatingAdd = false; /* 010100 */
var orderType = "";  /* 010000 */
var vLeft=0;
var vTop=0;
/***vv 010000 vv***/
var vStartLoad = false;
var currTime = new Date();
var currSecs  = (((currTime.getHours() * 60) + currTime.getMinutes()) * 60) + currTime.getSeconds();
var nocache = "&nocache=" + currSecs;
var vProductMode="";
var vCartLabel="";
var vCartMsgSelector=""; /* 010002 */
var vTopScroll=false;    /* 010002 */
xmlUrl += nocache;
/***^^ 010000 ^^***/

function CartLine(style, styleVal, color, colorVal, size, sizeVal, price, qty, tot)
{
	this.Style = style;
	this.StyleVal = styleVal;
	this.Color = color;
	this.ColorVal = colorVal;
	this.Size = size;
	this.SizeVal = sizeVal;
	this.Price = price;
	this.Quantity = qty;
	this.LineTotal = tot;
}
function AddedItem(style, styleVal, color, size, qty, image)
{
	this.Style = style;
	this.StyleVal = styleVal;
	this.Color = color;
	this.Size = size;
	this.Quantity = qty;
	this.ImagePath = image;
}

function Cart(subtotal)
{
	if (subtotal.length < 1)
		subtotal = 0.00;

	this.SubTotal		= subtotal;
	this.CartLines		= new Array();
	this.JustAdded		= new Array();
	this.HiddenPages	= new Array();
	this.IsLoading		= false;
 /******v 010000 v******/
 if (orderType == "Q")
	   this.LoadingMessage = "Loading Wishlist...";
 else
    this.LoadingMessage = "Loading " + vCartLabel + "...";  /* 010000 */
 /******^ 010000 ^******/
	this.ToHtmlStub		= function()
	{
		var ret = "<a class=\"cartStubLink\" href=\"javascript:golink('b2c/retail-shop-list.w','main');\" />";  /* 010001 */ /* C010002 */
		if (this.CartLines.length < 1)
			   ret += "<div class='hdrCartLabel'>" + vCartLabel + "</div><div class='hdrCartItems'>0 Items</div>" ;  /* 010000 */ /* C010000 */ /* C010002 */
		else
		{
			var itemTotal = 0;
			for (var i=0; i<this.CartLines.length; i++)
			{
				var tItem = this.CartLines[i];
				if (isNaN(tItem.Quantity))
					itemTotal += 1;
				else
					itemTotal += parseInt(tItem.Quantity);
			}
  /** vv C010002 vv **/
			ret += "<div class='hdrCartLabel'>" + vCartLabel + "</div><div class='hdrCartItems'>" + itemTotal; 
   if (itemTotal > 1)
     ret += " Items";
   else
     ret += " Item";
   ret += "</div>";
  /** ^^ C010002 ^^ **/
		}
		ret += '</a>';
		return ret;
	}
	this.ToHtml		= function() 
	{
		if (this.CartLines.length < 1)
		{
			return "<table class=\"cartTable\"><tbody><tr>" +
				   "<td class=\"cartCell\" style=\"text-align: center\">No Items.</td>" + 
				   "</tr></table>";
		}

		var msg = "<table class=\"cartTable\"><tbody>";
		var itemTotal = 0;
		for (var i=0; i<this.CartLines.length; i++)
		{
			var tItem = this.CartLines[i];
			msg += "<tr><td class=\"cartCell\" style=\"text-align: left; width: 70%;\">" + 
							"<a href=\"javascript:golink('b2c/product.w?product=" + tItem.StyleVal + "','main');\">" + tItem.Style + "</a>" + 
						"</td>\n" +
					    "<td class=\"cartCell\" style=\"text-align: right; width: 30%;\">" + tItem.Quantity + "@ " + tItem.Price + "</td></tr>\n";
    if(vProductMode=="S")
     msg+="<tr><td class=\"cartSubCell\" style=\"text-align: left;\" colspan=\"2\">" + tItem.Size + ", " + tItem.Color + "</td></tr>\n";

			if (isNaN(tItem.Quantity))
				itemTotal += 1;
			else
				itemTotal += parseInt(tItem.Quantity);
		}
		msg += "<tr><td colspan=\"2\"><hr class=\"cartSep\"></td></tr>\n" +
			   "<tr><td class=\"cartFooter\" style=\"text-align: left;\">" + itemTotal + " Items</td>\n" + 
			   "<td class=\"cartFooter\" style=\"text-align: right; width: 75%;\">Subtotal: " + 
				this.SubTotal + "</td></tr></tbody></table>\n";
		return msg;
	}
	this.ErrorMessage	= function (msg)
	{
		return "<table class=\"cartTable\"><tbody><tr>" +
			   "<td class=\"cartCell\" style=\"text-align: center\">" + msg + "</td>" + 
			   "</tr></table>";
	}
	this.JustAddedHtml	= function ()
	{
		// This shouldn't ever really be called when there are no items, however on the off chance it was...
		if (this.JustAdded.length < 1)
		{
			return "<table class=\"cartTable\"><tbody><tr>" +
				   "<td class=\"cartCell\" style=\"text-align: center\">No items were recently added.</td>" + 
				   "</tr></table>";
		}

		var msg = "<table class=\"cartTable\"><tbody>";

		for (var i = 0; i<this.JustAdded.length; i++)
		{
			var tItem = this.JustAdded[i];
			msg += "<tr><td class=\"cartCell\" style=\"text-align: left;\">" + 
						"<a class=\"cartLink\" href=\"javascript:golink('b2c/product.w?product=" + tItem.StyleVal + "','main');\">" + 
							tItem.ImagePath + "</a></td><td class=\"cartCell\" style=\"text-align: center;\">" +
  						"<span class=\"cartAddedText\">Added ";
			if (tItem.Quantity > 1)
				msg += tItem.Quantity + " of ";
   
   /******v 010000 v******/
   if (orderType == "Q")
   			msg += "<br /><a href=\"javascript:golink('b2c/product.w?product=" + tItem.StyleVal + "','main');\">" + 
   						tItem.Style + "</a><br /> to your wishlist.</span><br /><br />" + 
   				   "<a href=\"javascript:golink('b2c/retail-wishlist.w','main');\">" + 
   				   "<img src=\""+imgPath+"/buttons/View-Wishlist.jpg\" alt=\"View Wishlist\" /></a>" +  /* 010001 */
          "<div class='closeRow'><span class='cartTableClose'>close</span><span class='cartTableX'>x</span></div>" + /* C010001 */
   				   "</td></tr>";
   else
   			msg += "<br /><a href=\"javascript:golink('b2c/product.w?product=" + tItem.StyleVal + "','main');\">" + 
   						tItem.Style + "</a><br /> to your " + vCartLabel + ".</span><br /><br />" +  /* 010000 */
   				   "<a href=\"javascript:golink('b2c/retail-shop-list.w','main');\">" + 
   				   "<img src=\""+imgPath+"/buttons/View-Bag.jpg\" alt=\"View "+vCartLabel+"\" /></a>" +  /* 010000 */  /* 010001 */
          "<div class='closeRow'><span class='cartTableClose'>close</span><span class='cartTableX'>x</span></div>" + /* C010001 */
   				   "</td></tr>";
   /******^ 010000 ^******/
		}

		return msg;
	}
	this.IsHiddenHere	= function (page)
	{
		// Loop through HiddenPages array and search the page string for it.
		if (this.HiddenPages.length < 1)
			return false;

		if (page == null)
			page = document.location.href;

		for (var i = 0; i<this.HiddenPages.length; i++)
		{
			var tPage = this.HiddenPages[i];
			// If we find it, return true (that it's hidden)
			if (page.toUpperCase().indexOf(tPage.toUpperCase()) >= 0)	
				return true;
		}
		return false;
	}
}

/* Events */
function cartInitialize()
{
 if(vStartLoad==false)
 loadMyCart();
}

/* Methods */
/***vv 010100 vv***/
function loadMyCart(mode,style,color,size,qty,vOrderType) /* 010000 */
{
	myCart.IsLoading = true;
 vStartLoad = true;
 orderType = vOrderType;                                  /* 010000 */
	var realUrl = xmlUrl;
 var vStyleCode = style;                                  /* C010000 */
	if (mode == "add") // Add something to cart mode.
	{
		realUrl +=  "&cartMode=add&product=" + style;
  if(color!=null) realUrl += "&color=" + color; 
  if(size!=null) realUrl += "&size=" + size;
  realUrl+="&qty=" + qty + "&ordertype=" + vOrderType; /* 010000 */
	}

 $.ajax({
   type: "GET",
   url: realUrl,  
   dataType: "xml",
   complete: function(data) {
       myCart.IsLoading = false;

       //XML Error Checking
       if (data.responseXML == null) return;
       var cart = data.responseXML.documentElement;		
       if (! cart) return; // we got an invalid value back
       vError = cart.attributes.getNamedItem("error").value;
       if(vError.length>0) { alert(vError); return;}

       myCart = new Cart(cart.attributes.getNamedItem("total").value);
       vProductMode = cart.attributes.getNamedItem("productMode").value;
       vCartLabel = cart.attributes.getNamedItem("cartLabel").value;

       //Set Pages that should not display cartHover
       var hiddenPages = cart.attributes.getNamedItem("hideOnPages");
       if (hiddenPages != null){
        var tArr = hiddenPages.value.split(",");
        for (var i = 0; i< tArr.length; i++){
         myCart.HiddenPages.push(tArr[i]);
        }
       }
       
       hideCartNow();
       clearTimeout(cartTimer);
       clearTimeout(addedTimer);       

       /* <cartLine> */
       var cartLines = cart.getElementsByTagName("cartLine");

       for (var i = 0; i<cartLines.length; i++)
       {
        var line = cartLines[i];

        /* <style /> Style */
        var styleEle = line.getElementsByTagName("style")[0];
        var style = styleEle.attributes.getNamedItem("desc").value;
        if(vProductMode=="S"&&styleEle.childNodes[0]!=null)  /* 010000 */
        {
         var styleVal = styleEle.childNodes[0].nodeValue; 
         /* <color /> Color */
         var colorEle = line.getElementsByTagName("color")[0];
         var color = colorEle.attributes.getNamedItem("desc").value;
         var colorVal=null;
         var sizeVal=null;
         var size="";
         if(colorEle.childNodes[0]!=null) colorVal=colorEle.childNodes[0].nodeValue;
        /* <size /> Size */
         var sizeEle = line.getElementsByTagName("size")[0];	
         if(sizeEle.attributes.getNamedItem("desc")!=null) size = sizeEle.attributes.getNamedItem("desc").value;
         if(sizeEle.childNodes[0]!=null) sizeVal = sizeEle.childNodes[0].nodeValue;
        }
        else if (styleEle.childNodes[0]!=null) {   // 010004
          var styleVal = styleEle.childNodes[0].nodeValue; // 010004 
        }
        /* <price /> Item Price */
        var price = line.getElementsByTagName("price")[0].childNodes[0].nodeValue;
        /* <qty /> Quantity */
        var quantity = line.getElementsByTagName("qty")[0].childNodes[0].nodeValue;
        /* <total /> Line Total */
        var lineTotal = line.attributes.getNamedItem("total").value;

        myCart.CartLines.push(new CartLine(style, styleVal, color, colorVal, size, sizeVal, price, quantity, lineTotal));
       }
       /* </cartLine> */
       if (orderType != "Q")                                   /* 010000 */
       document.getElementById("shopStub").innerHTML = myCart.ToHtmlStub();

       /* <added> */
       var added = cart.getElementsByTagName("added");
       myCart.JustAdded = new Array();
       if (added.length > 0)
       {
        for (var i = 0; i<added.length; i++)
        {
         var addItem = added[i];
         /* <style /> Style */
         var styleEle = addItem.getElementsByTagName("style")[0];
         var style = styleEle.attributes.getNamedItem("desc").value;
         
         if(vProductMode=="S"&&styleEle.childNodes[0]!=null)  /* 010000 */
         {
           var styleVal = styleEle.childNodes[0].nodeValue;  
           /* <color /> Color -- Unused atm. */	
           var color = addItem.getElementsByTagName("color")[0].childNodes[0].nodeValue;
           /* <size /> Size */
           var size = addItem.getElementsByTagName("size")[0].childNodes[0].nodeValue;
         }
         else if (styleEle.childNodes[0]!=null) {   // 010004
           var styleVal = styleEle.childNodes[0].nodeValue; // 010004 
         }
         /* <qty /> Quantity */
         var qty = addItem.getElementsByTagName("qty")[0].childNodes[0].nodeValue;
         /* <image /> Image */
         var imageEle = addItem.getElementsByTagName("image")[0];
         var image = null;
         if (imageEle.childNodes.length > 0)
          image = imageEle.childNodes[0].nodeValue;
         
         myCart.JustAdded.push(new AddedItem(style, styleVal, color, size, qty, image));
        }
        // Show the cart display with a message in it.
        displayAddedToCart(myCart.JustAddedHtml(),vStyleCode); /* C010000 */
	      }
       /* </added> */

       /***vv 010002 vv***/   
       //scroll to top is set
       if (vTopScroll&&$(document).scrollTop() > $("#shopStub").offset().top)
       { $(document).scrollTop($("#shopStub").offset().top); }
       // Show msg in selector element if set
       if (vCartMsgSelector != "") 
       {	$(vCartMsgSelector).html(qty + " " + style + " added to shopping cart."); }
       /***^^ 010002 ^^***/

   }
 });
}
/***^^ 010100 ^^***/
function addToCart(style,color,size,qty,vOrderType,vJQSelector) /* 010000 */ /* 010002 */
{
 /******vv 010002 vv******/
 if(vJQSelector){
   $(vCartMsgSelector).html(); 
   vCartMsgSelector = vJQSelector; 
 }
 /******^^ 010002 ^^******/
 loadMyCart("add",style,color,size,qty,vOrderType); /* 010000 */
}
function updateShopStub(){
	// Update the non-cart values now that the cart is built.
	if (myCart.IsLoading)
 		document.getElementById("shopStub").innerHTML = myCart.LoadingMessage;
	else
		 document.getElementById("floatingCart").innerHTML = myCart.ToHtml();
}
/***vv 010100 vv***/
function displayAddedToCart(val,styleCode){ /* C010000 */
  clearTimeout(addedTimer);
  var $floatingAdded = $("#floatingAddedToCart" + styleCode); /* C010000 */
  if ($floatingAdded.length){
     if(boundFloatingAdd==false){   
       $floatingAdded.mouseenter(function(){ 
           clearTimeout(addedTimer); 
       });
       $floatingAdded.mouseleave(function(){ 
          addedTimer = setTimeout(function() {  $("#floatingAddedToCart" + styleCode).hide(); }, vAddedDispTime); 
       });
       /****vv C010001 vv****/
       /* APY - set click event once with 'live' so it dosen't need to be bound each time */
       $floatingAdded.find('.closeRow span').live('click',function(){ 
          $("#floatingAddedToCart" + styleCode).hide();
          clearTimeout(addedTimer);
       });
       /****^^ C010001 ^^****/
       boundFloatingAdd = true;
     }
    $floatingAdded.html(val)
                  .show();
    addedTimer = setTimeout(function() {  $("#floatingAddedToCart" + styleCode).hide(); }, vAddedDispTime);

  }else{
   displayCart(val);
   cartTimer = setTimeout(function() {  $("#floatingCart").hide(); }, vAddedDispTime);
  }

}
function displayCart(val){
 //Return if empty or in hidden list
	if (myCart.IsHiddenHere() || myCart.CartLines.length < 1) return;
 //Clear hide delay timer
	clearTimeout(cartTimer);

	if (! CartShown && myCart.IsLoading == false)
	{
		if (val == null) val = myCart.ToHtml();

		var $floatingCart = $("#floatingCart");
  var $vFloat=$("#floatPosition");
  var $shopStub = $("#shopStub");

  $floatingCart.html(val);

  vFloatPos=$shopStub.position();
  vFloatPos.top += $shopStub.outerHeight();
  vFloatPos.left += $shopStub.outerWidth();
  //Display offscreen to get width/height
  $floatingCart.css("left","-99999px")
               .css("top","-99999px")
               .show();
  vFloatPos.left -= $floatingCart.outerWidth();
  $floatingCart.css("top",vFloatPos.top)
               .css("left",vFloatPos.left);
		CartShown = true;
	}
}
/***^^ 010100 ^^***/
//Hide Cart Functions, 1/4 second delay
function hideCart(){
	cartTimer = setTimeout(function() { hideCartNow() }, 250);
}
function hideCartNow(){
	if (CartShown){   
		$("#floatingCart").hide();
		CartShown = false;
	}
}

function setTopScroll(vSetting){
 if (vSetting==false||vSetting==true)
   vTopScroll = vSetting;
} /* 010002 */
