/**
 * @author bradleyc
 * @projectDescription
 */

// Global vars
var mainColorMap = [];
var mainSizemap = [];
var prodId = '';
var swatchIds = '';
var swatchSize = 0;
var sizeAvail = "true";
var newCartProducts = [];
var allItemArray =[];

//	Set the classpath for the javascript includes
GSI.NameSpace.setClassPath("/include/common/");

//	Register the application with GSI Core API 
GSI.Application.create("GSI.Application.Dockers.ExpressShop");

//	Set the requirements for this application
//	The associated scripts will be dynamically imported into the DOM
GSI.Application.Dockers.ExpressShop.requires = [ "GSI.LightBox", "GSI.Dimensions", "GSI.Position" ];

// Divs used by the application
GSI.Application.Dockers.ExpressShop.expressShopDiv = undefined;
GSI.Application.Dockers.ExpressShop.buttonDiv = undefined;
GSI.Application.Dockers.ExpressShop.buttonImg = undefined;
GSI.Application.Dockers.ExpressShop.introDiv = undefined;
GSI.Application.Dockers.ExpressShop.introBGDiv = undefined;
GSI.Application.Dockers.ExpressShop.introDivAni = undefined;
GSI.Application.Dockers.ExpressShop.introBGDivAni = undefined;

GSI.Application.Dockers.ExpressShop.loadingHTML = '\
	<div style="margin-bottom:6px;font-size:14px;font-weight:bold">Loading Express Shop</div>\
	<img src="/images/prodDetails/loader.gif" />';

GSI.Application.Dockers.ExpressShop.introHTML = '\
	<div id="expressShopText">\
	<strong>Dockers Express Shop has Arrived!</strong>\
	<ul>\
		<li>Mouse over any one of the products below.</li>\
		<li>When the Express Shop button pops up, click on it!</li>\
		<li>Product close-ups and details pop up instantly on the page.</li>\
	</ul>\
	It\'s just like grabbing something off the rack!\
	</div>';

/**
 * Initialize the application
 */
GSI.Application.Dockers.ExpressShop.initialize = function( )
{
//	This variable is set in prodloop.js
	if( expressShopActive ) this.createExpressShop();
}

/** 
 * Reset the variables
 */
var resetVars = 
GSI.Application.Dockers.ExpressShop.resetVars = function()
{
	mainColorMap = new Array();
  mainSizeMap = new Array();
  prodId = '';
  swatchIds= '';
  swatchSize = 0;
  sizeAvail = "true";
	newCartProducts = new Array();
	allItemArray = new Array();	
}
 
/**
 * Create the express shop
 */
GSI.Application.Dockers.ExpressShop.createExpressShop = function( )
{
//	*************************************************
//	Note: expressShopData should be defined in 
//	a script tag within prodloop.js
//	*************************************************
//	this.shopInstance = new GSI.ExpressShop();
	
	var prods = expressShopData.products;
	var catId = expressShopData.categoryId;
	var pre 	=	expressShopData.divPrefix;
	var cp = expressShopData.cp;
	
	for( var i=0,len=prods.length; i<len; i++ )
	{
		var el = $( pre + i );
		Event.observe( el, "mouseover", this.showButton.bindAsEventListener(el) );
		Event.observe( el, "mouseout", this.hideButton.bindAsEventListener(el) );
		this.createElements(el, prods[i].productId, catId,cp, i );
	}

	//this.showIntroBG();
}

/**
 * Create the elements necessary for express shop on
 * the div (first argument)
 * @param {Object} div	The div to create elements on
 * @param {Number} pid	The product id
 * @param {Number} cat	The category id
 * @param {Number} i		The index for the item
 */
GSI.Application.Dockers.ExpressShop.createElements = function( div, pid, cat,cp, i )
{
//	Create the div for the expressShop button
	var buttonDiv = this.buttonDiv = GSI.$e( "div", div.id + "_expressShopButton", "expressShopButtonDiv" );
	Element.setStyle( buttonDiv, { display: "none", position: "absolute" } );
	
	buttonDiv["productId"] = pid;
	buttonDiv["categoryId"] = cat;
	buttonDiv["productIndex"] = i;
	buttonDiv["cp"] = cp;
	
//	Create the image for the expressShop button
	var buttonImg = this.buttonImg = GSI.$e( "img", div.id + "_expressShopImage", false, false, buttonDiv, false );
	buttonImg.src = "/images/prodDetails/expressShop_button.png";
	buttonImg.border = 0;
	
//	Create the "introduction" clip for expressShop
	var introDiv = this.introDiv = GSI.$e( "div", "expressShopIntro", false, this.introHTML, document.body );
	Element.setStyle( introDiv, { opacity: 0 } );
	Element.observe( introDiv, "click", this.hideIntro.bindAsEventListener(this) )
	
	GSI.Position.hCenterWindow(introDiv);
	GSI.Position.keepTop(introDiv);

//	Create the introduction background div
	var introBGDiv = this.introBGDiv = GSI.$e("div", "expressShopIntroBackground", false, false, document.body );
	var w = parseInt(introDiv.offsetWidth + 2) + "px";
	var h = parseInt(introDiv.offsetHeight + 1) + "px";
	Element.setStyle( introBGDiv, { width: w, height: h, opacity: 0 } );
	
	GSI.Position.hCenterWindow(introBGDiv);
	GSI.Position.keepTop(introBGDiv);

	
//	Create the "expressShop" div
	var esDiv = this.expressShopDiv = GSI.$e( "div", "expressShopDiv", false, false, document.body );
	Element.setStyle( esDiv, { display: "none" })
	
//	Observe the image click to show the expressShop
	Element.observe( buttonImg, "click", this.showProductPopup.bindAsEventListener( buttonDiv ) );
	div.insertBefore( buttonDiv, div.firstChild );
}


/**
 * Show the intro bg div
 */
GSI.Application.Dockers.ExpressShop.showIntroBG = function()
{
	var el = $("expressShopIntroBackground");
	Element.setStyle( el, { opacity: 0,display: "" } );

	
	if( this.introBGAni === undefined )
	{
		var h = parseInt(el.offsetHeight) + "px";
		
		this.introBGAni = new Animator({
			duration: 400,
	    interval: 32
		});
		
		this.introBGAni.addSubject( new CSSStyleSubject( el, "height: 2px; opacity: 0", "height:" + h + "; opacity: 0.95" ));
	}
	setTimeout( GSI.Application.Dockers.ExpressShop.showIntro.bind(this), 400 );
	this.introBGAni.play();
}

/**
 * Hide the intro bg div
 **/
GSI.Application.Dockers.ExpressShop.hideIntroBG = function()
{
	this.introBGAni.reverse();
	setTimeout( function() { 
		this.introDiv.style.display = "none";
		this.introBGDiv.style.display = "none";
	}.bind(this), 400 );
}

/**
 * Close the product popup
 */
GSI.Application.Dockers.ExpressShop.closeProductPopup = function()
{
	GSI.LightBox.close();
}

/**
 * Show the intro div
 */
GSI.Application.Dockers.ExpressShop.showIntro = function()
{
	var el = $("expressShopIntro");
	Element.setStyle( el, { opacity: 0,display: "" } );
	
	if( this.introAni === undefined )
	{
		this.introAni = new Animator({
			duration: 400,
	    interval: 32
		});
		this.introAni.addSubject( new NumericalStyleSubject( el, "opacity", 0, 1 ) );
	}

	this.introAni.play();
	setTimeout( this.hideIntro, 15000 );
}

/**
 * Hide the intro div
 */
GSI.Application.Dockers.ExpressShop.hideIntro = function()
{	
	var es = GSI.Application.Dockers.ExpressShop;
	es.introAni.reverse();
	setTimeout( es.hideIntroBG.bind(es), 400 );
}

/**
 * Event handler for product hover
 * @param {Object} evt
 */
GSI.Application.Dockers.ExpressShop.showButton = function( evt )
{
	var el = this.buttonDiv = this; 
	var buttonDiv = $( el.id + "_expressShopButton");
	var buttonImg = $( el.id + "_expressShopImage");
	buttonDiv.style.display = "";
}

/**
 * Event handler for product hover
 * @param {Object} evt
 */
GSI.Application.Dockers.ExpressShop.hideButton = function( evt )
{
	this.buttonDiv = null;
 	var el = this;
	var buttonDiv = $( el.id + "_expressShopButton");
	var buttonImg = $( el.id + "_expressShopImage");
	buttonDiv.style.display = "none";
}

/**
 * Show the product popup for the express shop
 * Fires on the click event from the button image
 * @context	{HTMLElement} buttonDiv
 * */
GSI.Application.Dockers.ExpressShop.showProductPopup = function( evt )
{
	resetVars();

//	Hide the button div
	this.style.display = "none";

//	Get the expressShop div
	var div = GSI.Application.Dockers.ExpressShop.expressShopDiv;

//	Optional Loading Message
	div.innerHTML = "";
	
//	Create the LightBox
	GSI.LightBox.create( {
		dataElement: div,
		color: "#808080",
		maxOpacity: .30
	});

	if( !div.isCentered )
	{
		GSI.Position.hCenterWindow( div );
		GSI.Position.vCenterWindow( div );
		div["isCentered"] = true;
	}
	GSI.Position.recenter();
	
	var url = "/include/productInfo.jsp";
	setProdId( this["productId"] );
	
	var qs  =	"?productId=" + this["productId"];
			qs +=	"&currentCategoryId=" + this["categoryId"];
			qs +=   "&currentCp=" + this["cp"];
			qs +=	"&currentProduct=" + this["productIndex"];
//	if( GSI.Browser.is("IE") ) 
			qs += "&ts=" + new Date().getTime();
	
	var req = new Ajax.Request( url + qs, {	
		method: 'get', 
		onSuccess: GSI.Application.Dockers.ExpressShop.showExpressShop,
		onFailure: function() { alert("Unable to retrieve a response from the server.") },
		requestHeaders: {"If-Modified-Since": "Wed, 15 Nov 1995 00:00:00 GMT"}
	});
	
}

/**
 * Show the express shop (HTML data from /include/productDetails.jsp)
 */
GSI.Application.Dockers.ExpressShop.showExpressShop = function( transport )
{
	var div = GSI.Application.Dockers.ExpressShop.expressShopDiv;
	
//	Get a reference to the response text
	var resp = new String( transport.responseText ); 
	
//	Append the inner HTML from the response
	div.innerHTML = resp;

//	Show the "info" tab for the express shop
	GSI.Application.Dockers.ExpressShop.showInfo()

//	Maintain centered position to window
	if( !div.isCentered )
	{
		GSI.Position.hCenterWindow( div );
		GSI.Position.vCenterWindow( div );
		div["isCentered"] = true;
	}
	
	GSI.Position.recenter();
//	If there is any script within the new HTML...
	try
	{
		resp.evalScripts();
	}
	catch(e)
	{
		alert(e.message||e);
	}

}


/**
 * Show the features section of the Express Shop
 **/
GSI.Application.Dockers.ExpressShop.showFeatures = function()
{
	$("es_prodFeatures").style.display = "block";
	$("es_prodInfo").style.display = "none";
	this.activateTab("es_prodFeaturesLink");
}

/**
 * Show the info section of the express shop
 */
GSI.Application.Dockers.ExpressShop.showInfo = function()
{

	$("es_prodFeatures").style.display = "none";
	$("es_prodInfo").style.display = "block";
	this.activateTab("es_prodInfoLink");
}

/**
 * Activate a tab within the express shop based on its id
 */
GSI.Application.Dockers.ExpressShop.activateTab = function( strId )
{
	if(strId =="es_prodInfoLink")
	{
		$("es_prodInfoLink").addClassName("active");
		$("es_prodFeaturesLink").removeClassName("active");			
	}
	else
	{
		$("es_prodInfoLink").removeClassName("active");
		$("es_prodFeaturesLink").addClassName("active");
	}
}

/**
 * Change the color of the product
 * -- called when the user clicks on a swatch or when they change the color drop down
 * @param {String} colorId	The id of the selected color 
 */	
GSI.Application.Dockers.ExpressShop.colorChange = function(colorId)
{   
	var colorDropDown = $('drpCustomTagProductColor_0');
	colorDropDown.value = colorId;
//	change the big image to what is showing.  update the size dropdown as well.
//	also update the border around the swatching
  if( colorId != "-1" && swatchSize > 0)
  {
    for (i=0; i< mainColorMap.length; i++)
    {
		//	If the current item in the color map is the selected color
		//	We will update the size drop down and set the "selected" style for the element
      if (mainColorMap[i].colorId == colorId)
      {           
			if (mainColorMap[i].mainImg != "")
            {
	          updateMainImage(mainColorMap[i].mainImg);                                                       
            }
			
			if (mainColorMap.length >  1)	updateSizeDropDown(mainColorMap[i].sizes);
				if (swatchIds.indexOf(mainColorMap[i].colorId) > 0)
        {
          $('swatchColor_'+mainColorMap[i].colorId+'_top').style.background="#00255C";
					$('swatchColor_'+mainColorMap[i].colorId+'_left').style.background="#00255C";
          $('swatchColor_'+mainColorMap[i].colorId+'_right').style.background="#00255C";
          $('swatchColor_'+mainColorMap[i].colorId+'_bottom').style.background="#00255C";
          $('swatchColor_'+mainColorMap[i].colorId+'_arrow').style.display='block';                            
        }
 			}
		//	Otherwise clear the "selected" style for the associated element 
      else if (swatchIds.indexOf(mainColorMap[i].colorId) > 0)
      {                                   
 	      $('swatchColor_'+mainColorMap[i].colorId+'_top').style.background="";
				$('swatchColor_'+mainColorMap[i].colorId+'_left').style.background="";
        $('swatchColor_'+mainColorMap[i].colorId+'_right').style.background="";
        $('swatchColor_'+mainColorMap[i].colorId+'_bottom').style.background="";
        $('swatchColor_'+mainColorMap[i].colorId+'_arrow').style.display='none';
      }
		}
	}
	this.mainColorMap = mainColorMap;
}
// Alias the function for access
var colorChange = GSI.Application.Dockers.ExpressShop.colorChange;

//used to update the main image when the color changes
function updateMainImage(mainImgTag)
{
	if (mainImgTag != null)
	{
		mainImg = $('dvCustomTagProductImage');
		mainImg.innerHTML = "<img " + mainImgTag + "/>";
	}
}

/**
 * Update the "size" select box on the form
 * -- called when a user changes the color of a product
 * @param {Object} sizes	An object of product sizes for the selected color
 */
GSI.Application.Dockers.ExpressShop.updateSizeDropDown = function( sizes )
{
	sizeDropDown = $('drpCustomTagProductSize_0');
	colorDropDown = $('drpCustomTagProductColor_0');

//	Set the size drop to default if color is at default
	if(colorDropDown.value == "-1")
	{
		sizeDropDown.value = "-1";
		return;
	}

//	Reset the size dropdown
	sizeDropDown.length = 1;
	firstSplit = sizes.split("~");

//	Add the size options to the select	
	if( sizeDropDown.type != "hidden" )
	{
		for (var i=0; i<firstSplit.length-1; i++)
		{
			secondSplit = firstSplit[i].split("|");
			var newOpt = document.createElement("OPTION");
			newOpt.value = secondSplit[0];
			newOpt.text = secondSplit[1];
			sizeDropDown.options[sizeDropDown.options.length] = newOpt;
		}
	}
}
// Alias the function for access
var updateSizeDropDown = GSI.Application.Dockers.ExpressShop.updateSizeDropDown;

/**
 * Append an item to the main color map
 * @param {Object} colorId
 * @param {Object} mainImg
 * @param {Object} sizes
 * @param {Object} colorTitle
 */
var loadMainColorMap = 
GSI.Application.Dockers.ExpressShop.loadMainColorMap = function( colorId, mainImg, sizes, colorTitle )
{
	mainColorMap.push({colorId:colorId, mainImg:mainImg, sizes:sizes, colorTitle:colorTitle});
}
 
/**
 * Append an item to the main size map
 * @param {Object} sku
 * @param {Object} price
 * @param {Object} colorId
 * @param {Object} sizeId
 * @param {Object} sizeDesc
 */
var loadMainSizeMap =
GSI.Application.Dockers.ExpressShop.loadMainSizeMap = function(sku, price, colorId, sizeId, sizeDesc)
{
	mainSizeMap.push({sku:sku, price:price, colorId:colorId, sizeId:sizeId, sizeDesc:sizeDesc} );
}


/**
 * Set the available size
 * @param {Object} flag
 */
var setSizeAvail = 
GSI.Application.Dockers.ExpressShop.setSizeAvail = function(flag)
{
	sizeAvail = flag;
};

/**
 * Update the swatch ids string
 * @param {String} id
 */
var updateSwatchIds = 
GSI.Application.Dockers.ExpressShop.updateSwatchIds = function(id)
{
    swatchIds += "|" + id;
}

/**
 * Set the swatch size
 * @param {Number} size
 */
var setSwatchSize = 
GSI.Application.Dockers.ExpressShop.setSwatchSize = function(size)
{
	swatchSize = size;
  if( size == 0)
  {
		$('dvCustomTagSwatch').style.display="none";
  }
}

/**
 * Set the size count
 * @param {Object} pSizeCount
 */
var setSizeCount =
GSI.Application.Dockers.ExpressShop.setSizeCount = function(pSizeCount)
{
	sizeCount = pSizeCount;
  if( sizeCount == 0)
  {
		$('drpCustomTagProductSize').style.display="none";
  }
}


/**
 * set the colorCount
 * @param {Object} pColorCount
 */
var setColorCount = 
GSI.Application.Dockers.ExpressShop.setColorCount = function(pColorCount)
{
	colorCount = pColorCount;
	//hide the lable for the color
    if( colorCount == 0)
    {
		$('drpCustomTagProductColor').style.display="none";
    }
}

/**
 * Set the product id
 * @param {Object} id
 */
var setProdId = 
GSI.Application.Dockers.ExpressShop.setProdId = function(id)
{
	prodId = id;
}

/**
 * Verify the form fields and then submit the form
 */
GSI.Application.Dockers.ExpressShop.verifyFormFields = function()
{           
	//check that a color, size, and qty have been entered.
  //check all color,size,qty groupings  
	//document.getElementById('prodCounter').value = grouping + 1;        
  
	var grouping = 0;
	var colorDropArr = new Array();
	var sizeDropArr = new Array();
	var qtyArr = new Array();
	var prodSelectedArr = new Array();
	var colorSelectedArr = new Array();
	var sizeSelectedArr = new Array();
	var qtySelectedArr = new Array();
	var prodSelected = false;
	
	for (var i=0; i<=grouping; i++)
  {
		colorDropArr[i] = $('drpCustomTagProductColor_' + i);
  	sizeDropArr[i] = $('drpCustomTagProductSize_' + i);
		
		qtyArr[i] = $('qty_' + i);

		prodSelectedArr[i] = false;
		colorSelectedArr[i] = false;
		sizeSelectedArr[i] = false;
		qtySelectedArr[i] = false;

		if(colorDropArr[i].value != "-1" && sizeDropArr[i].value != "-1" && !isNaN(parseInt(qtyArr[i].value)) && qtyArr[i].value > 0)
		{
			prodSelectedArr[i] = true;
			colorSelectedArr[i] = true;
			sizeSelectedArr[i] = true;
			qtySelectedArr[i] = true;
			continue;
		}
		if(colorDropArr[i].value != "-1")	colorSelectedArr[i] = true;
		if(sizeDropArr[i].value != "-1") sizeSelectedArr[i] = true;
		if(!isNaN(parseInt(qtyArr[i].value)) && qtyArr[i].value > 0) qtySelectedArr[i] = true;
	}
	
	for (var i=0; i<=grouping; i++)
  {
		if(prodSelectedArr[i] == true)
		{
			prodSelected = true;
			continue;
		}
		
		if(colorSelectedArr[i] == true && sizeSelectedArr[i] == true)
		{
			$("errorMessages").innerHTML = "Please enter a valid quantity.";
			return;
		}
		else if(colorSelectedArr[i] == true)
		{
			$("errorMessages").innerHTML = "Please choose a size.";
			return;
		}
		else if(sizeSelectedArr[i] == true)
		{
			$("errorMessages").innerHTML = "Please choose a color.";
			return;
		}
	}

	if(prodSelected == false)
	{
			$("errorMessages").innerHTML = "Please choose a color.";
			return;
	}

//	if we got this far everything should be ok.  
//	before the form can be submitted the prod_N has to be set with prodId|sku                       
	for (var i=0; i<=grouping; i++)
  {
		colorDrop = $('drpCustomTagProductColor_' + i);
    sizeDrop = $('drpCustomTagProductSize_' + i);
		        
    skuId = "";
    for (var k=0; k<mainSizeMap.length; k++)
    {      
			if ( 	mainSizeMap[k].sizeId 	== sizeDrop.value && 
						mainSizeMap[k].colorId 	== colorDrop.value )
    	{
	    	skuId = mainSizeMap[k].sku;
        break;
      }
    }
		
		$('prod_' + i).value = prodId + "|" + skuId;

//	set global array of objects to show added products in minicart
		if(prodId != null && prodId != '' && skuId != null && skuId != '')
		{
			if( typeof loadNewCartProducts == "function" ) loadNewCartProducts(prodId,skuId);
		}
	}
	
	document.orderForm.slice_0.value = $('drpCustomTagProductColor_0').value;
	
	if( GSI.Minicart !== undefined )
	{
		GSI.Minicart.ajaxAddToCart( document.orderForm );
	}
	else
	{
		document.orderForm.submit();
	}
}

function setPriceStyle()
{
	if ($("salePriceLabelStyle_0"))
 	{
		$("regPriceLabelStyle_0").style.display = "none";
 		$("dvCustomTagRegularPrice_0").className = "regPriceLabelStyleStrike_0";
 	}
}