var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
var bMoz = (navigator.appName == 'Netscape');

function execJS(node)
{
	var st = node.getElementsByTagName('SCRIPT');
  	var strExec;
  	for(var i=0;i<st.length; i++) 
  	{     
    	if (bSaf) { strExec = st[i].innerHTML; }
    	else if (bOpera) { strExec = st[i].text; }
    	else if (bMoz) { strExec = st[i].textContent; if (strExec==undefined){strExec = st[i].text;}}
    	else { strExec = st[i].text; }
    	try { eval(strExec); } 
		catch(e) { alert(e); }
  	}
}


function showProductPopup(showThisProdID, currentCategoryId, currentProduct, prodPromoId, layout)
{
	// addtocartsource deliniates orders by Finder app type
	// dw.config.addToCartSource defined in config.js
	
	if (layout == "wide")
	{
		$('holder2').className = "holder2_wide";
		$('other_matches_container').style.display = "none";
		$('returnLink').style.top = "275px";
	}
	else
	{
		$('holder2').className = "holder2";
		$('other_matches_container').style.display = "";
		$('returnLink').style.top = "192px";
	}
	
	var addToCartSource;
	
	if ( dw.config.addToCartSource == "mens" )
	{
		addToCartSource = "Mens Shoe Finder";
	}
	else if ( dw.config.addToCartSource == "womens" )
	{
		addToCartSource = "Womens Shoe Finder";
	}
	else
	{
		addToCartSource = "Shoe Finder";
	}
	
	var rec = Utility.valTest(dw.vars.pidList,showThisProdID)
	if(rec){
		es.getOmPids(Math.floor(rec.key/18));
	}
	
	resetVars();
	var queryString2 = "productId="+showThisProdID+"&currentCategoryId=1333120&currentProduct="+currentProduct+"&prodPromoId="+prodPromoId+"&addToCartSource="+addToCartSource;
		
	new Ajax.Request(dw.config.services.getExpressShop.href, {
	parameters: queryString2,
	method: 'get',
	onComplete:function(response)
		{
			$('expressShop').innerHTML = response.responseText;
			execJS($("expressShop"));
			$('returnLink').style.display = 'block';
			$('holder2').style.display = 'block';
			Opacity.full($('holder2'),{skip:.15});			
		}
	});	
}

var sizeAvail = "true";
function setSizeAvail(flag)
{
	sizeAvail = flag;
}
var swatchIds = '';
function updateSwatchIds(id)
{
    swatchIds = swatchIds + "|" + id;
}
var swatchSize = 0;
function setSwatchSize(size)
{
	swatchSize = size;
	//hide the lable for the swatching
    if(size == 0)
    {
		$('dvCustomTagSwatch').style.display="none";
    }
}
var sizeCount = 0;
function setSizeCount(pSizeCount)
{
	sizeCount = pSizeCount;
	//hide the lable for the size
    if(sizeCount == 0)
    {
		$('drpCustomTagProductSize').style.display="none";
    }
}
var colorCount = 0;
function setColorCount(pColorCount)
{
	colorCount = pColorCount;
	//hide the lable for the color
    if(colorCount == 0)
    {
		$('drpCustomTagProductColor').style.display="none";
    }
}
function resetVars()
{
	mainColorMap = new Array();
    mainSizeMap = new Array();
    prodId = '';
    swatchIds= '';
    swatchSize = 0;
    sizeAvail = "true";
	newCartProducts = new Array();
	grouping = 0;
	allItemArray = new Array();	
	img_counter = 0;
}
var newCartProducts = new Array();
//populate all the products added to cart using Buy Multiple
function loadNewCartProducts(productId, skuId)
{
	newCartProducts[newCartProducts.length] = {productId:productId, skuId:skuId};
}
var allItemArray = new Array();	
function loadAllCartProducts(productId, skuId)
{
	allItemArray[allItemArray.length] = {productId:productId, skuId:skuId};
}

var mainColorMap = new Array();

function loadMainColorMap(colorId, mainImg, sizes, colorTitle, minicartImg)
{	
	mainColorMap[mainColorMap.length] = {colorId:colorId, mainImg:mainImg, sizes:sizes, colorTitle:colorTitle, minicartImg:minicartImg};
}

mainSizeMap = new Array();
function loadMainSizeMap(sku, price, colorId, sizeId, sizeDesc)
{
	mainSizeMap[mainSizeMap.length] = {sku:sku, price:price, colorId:colorId, sizeId:sizeId, sizeDesc:sizeDesc};
}
var prodId = '';
function setProdId(id)
{
	prodId = id;
}

var img_counter = 0;
function rotateAltViews(direction)
{	
	if (direction == 'previous')
	{
		if (img_counter > 0) 
		{
      		img_counter--;
        	$("es_altView_thumb1").src=alt_imgs[img_counter];
			$("es_altView_thumb2").src=alt_imgs[img_counter+1];
			$("es_altView_thumb3").src=alt_imgs[img_counter+2];
			if ($("1")) { $("1").href = "javascript:swapImages(alt_imgs_large["+img_counter+"]"+")"; }
			if ($("2")) { $("2").href = "javascript:swapImages(alt_imgs_large["+(img_counter+1)+"]"+")"; }
			if ($("3")) { $("3").href = "javascript:swapImages(alt_imgs_large["+(img_counter+2)+"]"+")"; }
   		}
	}
	else if (direction == 'next')
	{
		 if (img_counter < alt_imgs.length-3) 
		{
       		img_counter++;
        	$("es_altView_thumb1").src = alt_imgs[img_counter];
			$("es_altView_thumb2").src = alt_imgs[img_counter+1];
			$("es_altView_thumb3").src = alt_imgs[img_counter+2];
			if ($("1")) { $("1").href = "javascript:swapImages(alt_imgs_large["+img_counter+"]"+")"; }
			if ($("2")) { $("2").href = "javascript:swapImages(alt_imgs_large["+(img_counter+1)+"]"+")"; }
			if ($("3")) { $("3").href = "javascript:swapImages(alt_imgs_large["+(img_counter+2)+"]"+")"; }
   		}
	}
	
	if (img_counter == alt_imgs.length-3)
	{
		$("es_altView_arrow_right").style.visibility = 'hidden';
	}
	else if (img_counter == 0)
	{
		$("es_altView_arrow_left").style.visibility = 'hidden';
	}
	else
	{
		$("es_altView_arrow_right").style.visibility = 'visible';
		$("es_altView_arrow_left").style.visibility = 'visible';
	}
}

function swapImages(newLargeImage)  
{ 
	$("dvCustomTagProductImage").innerHTML = "<img src='" + newLargeImage + "'>";
}

function hideExpressShop()
{
	$('returnLink').style.display = 'none';
	if($('holder2').style.display == 'block')
	{
		Opacity.none($('holder2'),{skip:.15,onComplete:function(){
			$('holder2').style.display = 'none';
		}});
		
	}
}

//product id of the product displayed in the express shop
//var prodId = null

//should be updated whenever the user clicks on "buy more at a time"
var grouping = 0;

//called when the user clicks on a swatch or when they change the color drop down
function colorChange(colorId, groupNumber)
{   
	if(groupNumber == -1)
		groupNumber = grouping;

	colorDropDown = $('drpCustomTagProductColor_' + groupNumber);
    //change the color drop down
    
    colorDropDown.value = colorId;
    
    //change the big image to what is showing.  update the size dropdown as well.
    if(colorId != "-1")
    {
	    for (i=0; i<mainColorMap.length; i++)
        {
	        if (mainColorMap[i].colorId == colorId)
            {           
	            if (mainColorMap[i].mainImg != "")
                {
	                updateMainImage(mainColorMap[i].mainImg);                                                       
                }
                
                if (mainColorMap.length >  1)
                {
				 updateSizeDropDown(mainColorMap[i].sizes,groupNumber);
                }
 			}
		}
	}
}

//used to update the main image when the color changes
function updateMainImage(mainImgTag)
{
	if (mainImgTag != null)
	{
		mainImg = $('dvCustomTagProductImage');
		mainImg.innerHTML = "<img " + mainImgTag + "/>";
	}
}

//changes the size drop down so that it contains only sizes for the selected color.
function updateSizeDropDown(sizes,groupNumber)
{
	sizeDropDown = $('drpCustomTagProductSize_' + groupNumber);
	colorDropDown = $('drpCustomTagProductColor_' + groupNumber);
	//set the size drop to default if color is at default
	if(colorDropDown.value == "-1")
	{
		sizeDropDown.value = "-1";
	}
	else 
	{
		//reset the size drop
		sizeDropDown.length=1;
		firstSplit = sizes.split("~");
		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;
			}
		}
	}
}

function verifyFields()
{           
	//check that a color, size, and qty have been entered.
    //check all color,size,qty groupings  
	document.getElementById('prodCounter').value = grouping + 1;        
    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();
	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;
		}
	}
	var prodSelected = false;
	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 != '')
		{
			loadNewCartProducts(prodId,skuId);
		}
	}
	//submit the form
    
	document.orderForm.submit();
    
}

function toggleProdInfo(showThis, hideThis1, hideThis2, deActivateLink, activateLink1, activateLink2)
{
	$(showThis).style.display = '';
	$(hideThis1).style.display = 'none';
	$(hideThis2).style.display = 'none';
	$(deActivateLink).className = 'prodDetailsInactive';
	activateLink1.className = 'prodDetailsActive';
	activateLink2.className = 'prodDetailsActive';
}

function getPrevAltImage(altImageArray)
{
	updateMainImage(altImageArray[altImageIndex].imageTag);
	altImageIndex--;
	if (altImageIndex < 0)
	{
		altImageIndex = altImageArray.length - 1;
	}
}

function getNextAltImage(altImageArray)
{
	updateMainImage(altImageArray[altImageIndex].imageTag);
	altImageIndex++;
	if (altImageIndex >= altImageArray.length)
	{
		altImageIndex = 0;
	}
}




var es = {

	parseOmPids: function(obj)
	{
		obj = Utility.evalJSON(obj.responseText)
		
		for (var a = 0; a < obj.products.length; a++)
		{
			var data = obj.products[a]
			//load in cache
			dw.cache.pids[data.productId] = data
			es.buildOtherMatches(data)
		}
	},
	
	getOmPids: function(page){
		
		$('om_inner').innerHTML = '';
		$('om_arrows').innerHTML = '';
		if (dw.vars.pidList.length == 1)
		{
			$('other_matches').style.display = 'none';
		}
		else
		{
			$('other_matches').style.display = '';
		}
		
		//var getThese2 = [];
		
		var omIncrement;
		// if pids remaining are >= 18, omImcrement = 18 else it's the remainder
		if (dw.vars.pidList.length - (page*dw.config.views[dw.vars.view].recSet) >= 18)
		{
			omIncrement = 18;
		}
		else
		{ 
			omIncrement = dw.vars.pidList.length - (page*dw.config.views[dw.vars.view].recSet);
		}
				
		//from the cache
		var getThese = []
		for(var i=0; i<18; i++){
			
			var pidId = dw.vars.pidList[(page*18)+i]
			if(pidId){
			
				//check cache for pids
				if(dw.cache.pids[pidId]){
					// add pids from cache to 'other matches'
					es.buildOtherMatches(dw.cache.pids[pidId])
					
				}else{
					getThese.push(pidId)
				}
			}
		}
		
		//from service
		if(getThese.length > 0)
		{
			Utility.callService({
				service:dw.config.services.getPids.href,
				method:dw.config.services.getPids.method,
				pars:Utility.getPars(dw.config.services.getPids.pars,{productId:getThese}), 
				onComplete:es.parseOmPids
			});
		}
		
		var omArrowLeft = document.createElement('div');
		
		omArrowLeft.className = 'omArrowLeft';
		if (page == 0)
		{
			omArrowLeft.className = omArrowLeft.className + 'Off';
		}
		
		if (page > 0)
		{
			omArrowLeft.onclick = function(){
				es.getOmPids(page-1);
			}
		}
		
		var omArrowRight = document.createElement('div');
		
		omArrowRight.className = 'omArrowRight';
		if (page+1 < dw.vars.pidList.length/18)
		{
			omArrowRight.onclick = function(){
				es.getOmPids(page+1);
			}
		}
		
		if (page+1 >= dw.vars.pidList.length/18 || omIncrement < 18)
		{
			omArrowRight.className = omArrowRight.className + 'Off';
		}
		
		$('om_arrows').appendChild(omArrowLeft);
		$('om_arrows').appendChild(omArrowRight);
		
	},
	
	buildOtherMatches: function(data){
		var omThumbContainer = document.createElement('div');
		omThumbContainer.className = 'omThumb'
		var omThumb = views.pullImage(data,'main','T50');
		omThumbContainer.style.backgroundImage = 'url(' + omThumb + ')'
		omThumbContainer.style.cursor = 'pointer';
		omThumbContainer.onclick = function(){
			showProductPopup(data.productId,dw.config.services.getExpressShop.pars.categoryID,'0', data.promoId, 'narrow');
		}
		$('om_inner').appendChild(omThumbContainer)
	}
}
