/*** COPYRIGHT 2009  BY FDM4 INTERNATIONAL INC. - ALL RIGHTS RESERVED ********/
/*** CartHover.js -- Renders order info and provides add-to-cart           ***/ 
/*****************************************************************************/
/*R010001 11/12/09 APY- Click anywhere on window to close instead of just btn*/
/*R010000 11/02/09 APY- Updates for b2b wishlist.                            */
/*****************************************************************************/
/* 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 ajaxConn  = GetXmlHttpObject();
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 SuppressError = false;
var cartTimer, addedTimer;
var orderType = "";  /* 010000 */
/***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 ^^***/

// Get the XML HTTP Object

function GetXmlHttpObject()
{
	var xmlHttp;
	try	{ xmlHttp=new XMLHttpRequest(); }	// Firefox, Opera 8.0+, Safari
	catch (e) {
	    try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }		// Internet Explorer
	    catch (e) {
			try	{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }	// Internet Explorer
			catch (e) {												
				alert("Your browser does not support AJAX!");		// Unsupported
				return false; 
			}
		}
	}
	return xmlHttp;
}

/* Replace with AJAX calls to grab cart into (possibly into similar JS structures to this) */
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 = "<img src=\""+imgPath+"/1by1pix.gif\" border=\"0\" id=\"floatPosition\"><a class=\"cartStubLink\" href=\"javascript:golink('b2c/retail-shop-list.w','main');\">";  /* 010001 */
		if (this.CartLines.length < 1)
			   ret += "No items in your " + vCartLabel + ".";  /* 010000 */
		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);
			}

			ret += "Items: " + itemTotal + ", Subtotal: " + this.SubTotal;
		}
		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' onclick='hideCartNow()' style='cursor:pointer;'>"; /* R010001 */
		for (var i = 0; i<this.JustAdded.length; i++)
		{
			var tItem = this.JustAdded[i];
			msg += "<tr><td class=\"cartCell\" style=\"text-align: left;\">" + 
							tItem.ImagePath + "</td><td class=\"cartCell\" style=\"text-align: center;vertical-align:top;\">" + /* R010001 */
        "<div class='wishClose'><div id='wishCloseBtn' onclick='hideCartNow()'>"+
        "<img src=\""+imgPath+"/buttons/close.jpg\" alt=\"Close\" />" +
        "</div></div><div style='clear:both;'>" +
  						"<span class=\"cartAddedText\">Added ";
			if (tItem.Quantity > 1)
				msg += tItem.Quantity + " of ";
   
   /******v 010000 v******/
   if (orderType == "Q")
   			msg += "<br />" + 
   						tItem.Style + "<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></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></td></tr>";
   /******^ 010000 ^******/
   msg += "</table>";
		}

		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;

		//alert(page);	

		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 */
var vLeft=0;
var vTop=0;
/********************v 010001 v********************/
/********************v 010003 v********************
R010001 - Not using shopStub
function setFloat()
{
 var $vFloat=$("#floatPosition");
 var $floatingCart = $("#floatingCart");
 var $shopStub = $("#shopStub");

 vFloatPos=$shopStub.position();
 vFloatPos.top += $shopStub.outerHeight();
 vFloatPos.left += $shopStub.outerWidth();
 //Display offscreen to get width/height
 $floatingCart.css("left","-99999px");
 $floatingCart.css("top","-99999px");
 $floatingCart.show();
 vFloatPos.left -= $floatingCart.outerWidth();
 $floatingCart.hide();
 $floatingCart.css("top",vFloatPos.top);
 $floatingCart.css("left",vFloatPos.left);
}
********************^ 010003 ^********************/
/********************^ 010001 ^********************/

function cartInitialize()
{
 if(vStartLoad==false)
 loadMyCart();
}
function dataLoaded()
{
	if (ajaxConn.readyState == 4) 
	{
		myCart.IsLoading = false;
		if (ajaxConn.responseXML == null)
			return;

		var cart = ajaxConn.responseXML.documentElement;		
		if (! cart) // we got an invalid value back
			return;

  vError = cart.attributes.getNamedItem("error").value;

  if(vError.length>0) { alert(vError); return;}

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

		if (hiddenPages != null)
		{
			var tArr = hiddenPages.value.split(",");
			for (var i = 0; i< tArr.length; i++)
			{
				myCart.HiddenPages.push(tArr[i]);
			}
		}

		var errorMessage = cart.attributes.getNamedItem("error");
		// Check for the error attribute on the Cart element
		if (errorMessage != null && SuppressError == false)
		{
			// Show the cart display with a message in it.
			displayCart(myCart.ErrorMessage(errorMessage.value));
/* R010001 - don't show stub
			SuppressError = true; 

			// Hide the display just before loading
			setTimeout(function() 
				{ 
					hideCart(); 
					setTimeout( function() { updateShopStub(); }, 400);
				}, 4500); 
*/
		}

		SuppressError = false;

		hideCartNow();
		clearTimeout(addedTimer);

		/* <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.
			displayCartNow(myCart.JustAddedHtml());

   /***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 ^^***/
/* R010001 - dont show stub
			// Hide the display just before loading
			addedTimer = setTimeout(function() 
				{ 
					hideCart(); 
					setTimeout( function() { updateShopStub(); }, 400);
				}, 4500);
*/
		}
		/* </added> */

		/* <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();
	}
}

/* Methods */
function loadMyCart(mode,style,color,size,qty,vOrderType) /* 010000 */
{
	myCart.IsLoading = true;
 vStartLoad = true;
 orderType = vOrderType;                                  /* 010000 */
	var realUrl = xmlUrl;
	ajaxConn = GetXmlHttpObject();

	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 */
	}
	ajaxConn.onreadystatechange = dataLoaded;
	ajaxConn.open("GET", realUrl, true);
	ajaxConn.send(null);
}
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("shopStub").innerHTML = myCart.ToHtmlStub();
		document.getElementById("floatingCart").innerHTML = myCart.ToHtml();
	}
}

function displayCart(val)
{
	if (myCart.IsHiddenHere() || myCart.CartLines.length < 1) // Don't show
		return;
	displayCartNow(val);
}
function displayCartNow(val)
{
	clearTimeout(cartTimer);
	if (! CartShown && myCart.IsLoading == false)
	{
		if (val == null)
			val = myCart.ToHtml();

		var floatingCart = document.getElementById("floatingCart");
		floatingCart.innerHTML = val;
//R010001  setFloat()  /* 010001 */
		floatingCart.style.visibility = "visible";
		floatingCart.style.display = "block";
		CartShown = true;
	}
}

function hideCart()
{
	cartTimer = setTimeout(function() { hideCartNow() }, 250);
}
function hideCartNow()
{
	if (CartShown && SuppressError == false)
	{
		var floatingCart = document.getElementById("floatingCart");
		floatingCart.style.visibility = "hidden";
		floatingCart.style.display = "none";
		CartShown = false;
	}
}

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