// Global variables
var CONST_addToBagImagePath = '/img/COM_img/addtobag_btn.gif';
var CONST_preorderAddToBagImagePath = '/img/COM_img/addtobag_btn.gif';
var CONST_backorderAddToBagImagePath = '/img/COM_img/addtobag_btn.gif';

var newWindow

function openPopup(url, popupWidth, popupHeight) {
	if (newWindow && !newWindow.closed)	{
		newWindow.close()
	}	
		
	var winl = (screen.width - popupWidth) / 2;
	var wint = (screen.height - popupHeight) / 2;
		
	newWindow = open(url, 'popup', ("toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,top=" + wint + ",left=" + winl + ",width=" + popupWidth + ",height=" + popupHeight + "\""));
	newWindow.focus();
}

function openPopup2(url, name, param) { 
	newWindow=open(url, name, param);
}

// Given an image and a state, swap out the existing off/on state.
// ASSUME: the image name will be for the form *_[off | on].*
function swapImage(img, imgState)
{
	var imgStateOn = "_on.";
	var imgStateOff = "_off.";
	var imgSrc = img.src;
	var imgPathAndFileName = imgSrc.slice(0, imgSrc.lastIndexOf(".") + 1)
	var imgFileExtension = imgSrc.slice(imgSrc.lastIndexOf(".") + 1, imgSrc.length);

	if (imgPathAndFileName.indexOf(imgStateOn) > 0 && imgState == 'off')
	{
		imgSrc = imgPathAndFileName.slice(0, imgPathAndFileName.indexOf(imgStateOn)) + imgStateOff + imgFileExtension;
	}
	if (imgPathAndFileName.indexOf(imgStateOff) > 0 && imgState == 'on')
	{
		imgSrc = imgPathAndFileName.slice(0, imgPathAndFileName.indexOf(imgStateOff)) + imgStateOn + imgFileExtension;
	}
	
	img.src = imgSrc;
}

/*
 * Catalog Product Functions
 */

function loadshade(backorderMessageID)
{
	var mf = GetMainFormName();
	if (mf==null) return;
	// Get the Quantity Drop Down; if not found, exit
	var firstitem = GetElementName("varlist",mf);
	if (firstitem == null) return;
	// Get the hidden static size display			
	var labelName = GetElementName("staticSizeDisplay",mf)
	if (labelName== null) return;
	var labelForSize = document.forms[mf].elements[labelName];
	var ddlVarList = document.forms[mf].elements[firstitem];	
	// Set the text box appropriately
	labelForSize.value = ddlVarList.options[0].text;
	// change the display if the drop down only contains more than one element.
	if (ddlVarList.options.length > 1)
	{
		// Hide the label & show the drop down;
		labelForSize.className = 'A_meddrkgrey07R hidden';
		ddlVarList.className = 'A_meddrkgrey07R';
	}
	var first = ddlVarList.options[0].value;
	selectshade(first, backorderMessageID);
}

function selectshade(sku, backorderMessageID)
{
	var mf = GetMainFormName();
	if (mf==null) return;
	if (sku==null || sku=="") return;
	if (sku.indexOf("#") != -1){
		sku=sku.slice(0,sku.indexOf("#"));
	}
	var x = GetElementName("varlist",mf);
	if (x != null) {
		for (var i=0; i< document.forms[mf].elements[x].options.length; i++)	{
			str = document.forms[mf].elements[x].options[i].value
			str = str.slice(0,str.indexOf("#"));
			if (str==sku) {
				document.forms[mf].elements[x].selectedIndex=i;
				strprice = document.forms[mf].elements[x].options[i].value;
				setEanPrice(document.forms[mf].eanprice, strprice);
				setBackorderMessage(sku, backorderMessageID);
				return;
			}
		}
	}
}

// Used to retrieve the SKU from a value given the assumption
// that the format of the value is:
// SKU#PRICE
function getSKU(value)
{
	var sku = null;
	
	if (value==null || value=="") return;
	if (value.indexOf("#") != -1){
		sku=value.slice(0,value.indexOf("#"));
	}
	
	return sku;
}

// Used to set the back order message, if necessary.
function setBackorderMessage(sku, backorderMessageID)
{
	// Get a reference to the back order message object.
	divBackorderMessage = document.getElementById(backorderMessageID);		
	
	if (divBackorderMessage != null)
	{
		try
		{
			//get the back order information for the sku (if it exists)
			stock = eval('var'+sku);

			// if we get to this point, stock will hold a value:
			// <stock>#<backorder status>#<backorder date>
			// Seperate the values here.
			temp = stock.substring(stock.indexOf("#")+1,stock.length);
			isBackordered = temp.substring(0,temp.indexOf("#"));
			backorderedDate = temp.substring(temp.indexOf("#")+1,temp.length);
			stock = stock.substring(0,stock.indexOf("#"));
			
			// Only display the back order message if the stock is less than 1.
			if (stock<1)
			{
				// If the back order date is valid and the backorder status is <> 0, set the back/pre order message.
				if(backorderedDate != "" && isBackordered != 0)  // Has a valid backorder status and valid back order date.
				{
					divBackorderMessage.innerHTML = "This product will not be available to ship until approximately " + backorderedDate + " and will ship seperately from any other items you may have ordered.";
				}
				else
				{
					if (isBackordered == 1) // Backorder
					{
						divBackorderMessage.innerHTML = "This product is backordered and will ship seperately from any other items you may have ordered." ;
					}
					else if (isBackordered == 2) // Preorder
					{
						divBackorderMessage.innerHTML = "This product is preordered and will ship seperately from any other items you may have ordered.";
					}
				}
			}
		}
		catch (er) 
		{
			// If the variable containing back/pre order information is not found, exit normally and reset the backorder message.
			divBackorderMessage.innerHTML = "" ;
		}
	}
}

function setEanPrice(eanPriceTextBox, value)
{
	var start; // Holds the index of the '#'

	if (value != null) {
		if (value.indexOf("#") >= 0) 
		{
			var start = value.indexOf("#");
			value = value.slice(start+1);
		}		
		// strip off any leading zeros.
		if (value.indexOf("0") == 0) value = value.slice(1);
		eanPriceTextBox.value = "$" + value;
	}
}

// 
function setPriceForCollectionCategoryPage(variantList, variantListControlName, skuAndPrice, eanPriceControlName, hiddenVariantListControlName)
{
		
	var mf = GetMainFormName();
	if (mf!=null) {
		// Get the name from the variant list.
		var variantListID = new String(variantList.name);

		// Extract the unique ID
		var indexOfVariantListString = variantListID.indexOf(variantListControlName);
		
		// PURPOSELY removing the last character since it is not needed for the syncDropdown method
		// so that the uniqueID is formatted correctly
		var uniqueID = variantListID.substr(0, indexOfVariantListString - 1); 
			
		// call the sync dropdown method to keep the drop down list represented by 
		// variantListControlName in sync with hiddenVariantListControlName
		syncDropdowns(uniqueID, variantListControlName, hiddenVariantListControlName);
		
		// call the original method to keep the variant and price in sync.
		setPriceForCategoryPage(variantList, variantListControlName, skuAndPrice, eanPriceControlName);
	}
}

// Will set the ean price control text based on the variant list and name of the controls passed in.
function setPriceForCategoryPage(variantList, variantListControlName, skuAndPrice, eanPriceControlName)
{
	var mf = GetMainFormName();
	if (mf!=null) {
		var eanPriceControlID = new String(variantList.id);
		eanPriceControlID = eanPriceControlID.replace(variantListControlName, eanPriceControlName);	
		var txtEanPrice = document.forms[mf].elements[eanPriceControlID];
		setEanPrice(txtEanPrice, skuAndPrice);
	}
}

function initshade(backorderMessageID)
{
	// Call at page load.
	loadshade(backorderMessageID);
	defaultshade = "";
	selectshade(defaultshade, backorderMessageID);
}

// Used to set the product display in order to show the proper back order messages and to hide
// certain features when the product is unavailable.
function setProductDisplay(uniqueID, varListID, eanPriceID, sizeLabelID, qtyLabelID, qtyListID, submitPurchaseID, staticSizeDisplayID)
{
	// Get the IDs for each of the controls that runs on the server.
	varlist = uniqueID + ':' + varListID;
	sizelabel = uniqueID + ':' + sizeLabelID;
	qtylabel = uniqueID + ':' + qtyLabelID;
	qtydropdown = uniqueID + ':' + qtyListID;

	// eanPrice may or may not run on the server; if the parameter begins with a colon, assume its running on the server.
	if (eanPriceID.indexOf(':') >= 0)
	{
		eanprice = uniqueID + eanPriceID;
	}
	else
	{
		eanprice = eanPriceID;
	}

	var mf = GetMainFormName();
	if (mf!=null) {
		// To get run at server controls
		var ddlVarList = document.forms[mf].elements[varlist];	
		var txtEanPrice = document.forms[mf].elements[eanprice];
		var ddlQty = document.forms[mf].elements[qtydropdown];

		// To get client side controls
		var lblSize = document.getElementById(sizelabel);
		var lblQuantity = document.getElementById(qtylabel);
		
		// The static size display is only used on the product detail page; if its specified, attempt to hide it
		if (staticSizeDisplayID != null && staticSizeDisplayID != '')
		{
			var txtStaticSizeDisplay = document.getElementById(staticSizeDisplayID);
		}
		
		if (ddlVarList.options.length > 0)
		{
			var strprice = ddlVarList.options[0].value;
			if (strprice == "")
			{
				// Out of stock - set the price label and hide other controls.
				txtEanPrice.value = ddlVarList.options[0].text;
				
				// Hide other values.
				lblSize.className = 'hidden';
				ddlVarList.className = 'hidden';
				lblQuantity.className = 'hidden';
				ddlQty.className = 'hidden';
				if (txtStaticSizeDisplay != null) txtStaticSizeDisplay.className = 'hidden';	
				
				// Disable add to bag button for this product.
				submitpurchaselink = uniqueID.replace(":", "_");
				while (submitpurchaselink.indexOf(':') >= 0) 
				{
					submitpurchaselink = submitpurchaselink.replace(":", "_");
				}
				submitpurchaselink = submitpurchaselink + '_' + submitPurchaseID;
				var hrefSubmitPurchase = document.getElementById(submitpurchaselink);
				hrefSubmitPurchase.removeAttribute("href");
			}
			else
			{
				setEanPrice(txtEanPrice, strprice);
			}
		}
	}
}

// Add a variant to the dropdown :
// uniqueID and varListID are used to get the dropdown list
//itemSKU and itemPrice will be used to generate the <OPTION> tag.
function addVariantToDropDownList(uniqueID, varListID, itemName, itemSKU, itemPrice)
{
	// Get the fully qualified name of the variant list drop down.
	var varlist = uniqueID + ':' + varListID;

	// Get the main form name. if found, add this variant to the variant drop down.
	var mf = GetMainFormName();
	if (mf!=null) {
		// Add the variant to the dropdown.
		var ddlVarList = document.forms[mf].elements[varlist];	
		var ddlVarListLength = ddlVarList.options.length;
		ddlVarList.options[ddlVarListLength] = new Option(itemName, itemSKU + "#" + itemPrice, false, false);
	}
}

function addShadeToTable(varListID, itemSKU, VariantSelectID, VariantText)
{
	
	var varlist = uniqueID + ':' + varListID;

	var tbl = document.getElementById(varlist);

	var RowCount = tbl.rows.length;

	var CellCount = tbl.rows[RowCount - 1].cells.length;

	if(CellCount > 5)
	{

		tbl.insertRow(RowCount);
		RowCount = tbl.rows.length;

	}

	var x = tbl.rows[RowCount - 1]; 

	var y = x.insertCell(x.cells.length);

	y.innerHTML="<a href=\"javascript:SelectVariantShade('" + VariantSelectID + "','" + VariantText + "');\"><img src='/img/products/" + itemSKU + "_SW.gif' width='20'></a><img src='/img/COM_img/spacer.gif' height='1' width='2'><img src='/img/COM_img/spacer.gif' height='1' width='2'>";

}

function SelectVariantShade(VariantSelectID, VariantText)
{
		
	var ddlTargetList = document.getElementById(VariantSelectID);	
	
	for (i=0; i < ddlTargetList.options.length; i++)
	{

		if (trimAll(VariantText) == ddlTargetList.options[i].text)
		{

			ddlTargetList.options[i].selected = true;
			
			ddlTargetList.onchange();
			
			break;

		}

	}

}

// Given a uniqueID, a sourceDropDownListID and a targetDropDownListID, set the target selected item
// to whatever is the currently selected option in the source drop down list.
function syncDropdowns(uniqueID, sourceDropDownListID, targetDropDownListID)
{
	// Get the fully qualified name of the drop down lists.
	var sourceList = uniqueID + ':' + sourceDropDownListID;
	var targetList = uniqueID + ':' + targetDropDownListID;

	var mf = GetMainFormName();
	if (mf!=null) {
		// Get a reference to the source and target drop down lists.
		var ddlSourceList = document.forms[mf].elements[sourceList];	
		var ddlTargetList = document.forms[mf].elements[targetList];	
		
		// Check the selected item for the source list.
		var sourceSelectedItemIndex = ddlSourceList.selectedIndex;
		
		// Now get the actual option from this drop down list.
		var sourceSelectedOption = ddlSourceList.options[sourceSelectedItemIndex];
		
		// Now iterate over the target drop down and find the match on the option above.
		for (i=0; i < ddlTargetList.options.length; i++)
		{
			// Check to see if option values are equal. ASSUME - display values are irrelvant.
			if (sourceSelectedOption.value == ddlTargetList.options[i].value)
			{
				// Set the selected index here and exit.
				ddlTargetList.options[i].selected = true;
				break;
			}
		}
	}
}

/*
 * Navigation 
 */
function showDiv(id)
{
if (document.all(id).style.display == 'inline')
	{document.all(id).style.display = 'none';}
else
{document.all(id).style.display = 'inline';}
}

function CheckTextLength(textArea, maxLength)
{		
	if (maxLength == 0)
		maxLength = 150;

	if(textArea.value.length > maxLength )
	{
		alert("Please shorten your message to a maximum length of " + maxLength + " characters or about 15 - 20 words.");		
		//Commented by Sudeshna
		/*textArea.value = "";*/
		textArea.focus();
	}			
}

/*
 * Opacity
 */

function opacity(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++)
			{
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function shiftOpacity(id, millisec) {
	//if an element is invisible, make it visible, else make it ivisible
	if(document.getElementById(id).style.opacity == 0) {
		opacity(id, 0, 100, millisec);
	} else {
		opacity(id, 100, 0, millisec);
	}
}

function blendimage(divid, imageid, imagefile, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 0;
	
	//set the current image as background
	document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")";
	
	//make image transparent
	changeOpac(0, imageid);
	
	//make new image
	document.getElementById(imageid).src = imagefile;

	//fade in image
	for(i = 0; i <= 100; i++) {
		setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed));
		timer++;
	}
}

// Same as blendimage() but for 2 distinct div, image
function blend2images(divid1, imageid1, imagefile1, divid2, imageid2, imagefile2, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 0;
	
	//set the current image as background
	document.getElementById(divid1).style.backgroundImage = "url(" + document.getElementById(imageid1).src + ")";
	document.getElementById(divid2).style.backgroundImage = "url(" + document.getElementById(imageid2).src + ")";
	
	//make image transparent
	changeOpac(0, imageid1);
	changeOpac(0, imageid2);
	
	//make new image
	document.getElementById(imageid1).src = imagefile1;
	document.getElementById(imageid2).src = imagefile2;

	//fade in image
	for(i = 0; i <= 100; i++) {
		setTimeout("changeOpac(" + i + ",'" + imageid1 + "')",(timer * speed));
		setTimeout("changeOpac(" + i + ",'" + imageid2 + "')",(timer * speed));
		timer++;
	}
}

function currentOpac(id, opacEnd, millisec) {
	//standard opacity is 100
	var currentOpac = 100;
	
	//if the element has an opacity set, get it
	if(document.getElementById(id).style.opacity < 100) {
		currentOpac = document.getElementById(id).style.opacity * 100;
	}

	//call for the function that changes the opacity
	opacity(id, currentOpac, opacEnd, millisec)
}
function CheckTextLength(textArea, maxLength)
{		
	if (maxLength == 0)
		maxLength = 150;

	if(textArea.value.length > maxLength )
	{
		alert("Please shorten your message to a maximum length of " + maxLength + " characters or about 15 - 20 words.");		
		//Commented by Sudeshna
		/*textArea.value = "";*/
		textArea.focus();
	}			
}		

/* Added by Sudeshna
 * Prevents user from entering more than specific number of characters in a textbox/textarea
 */
function LimitTextLength(textArea, maxLength)
{		
	if (maxLength == 0)
		maxLength = 150;

	if(textArea.value.length > maxLength )
	{		
		textArea.value = textArea.value.substring(0, maxLength);
		textArea.focus();
	}			
}		

/*
 * Registration functions
 */
function Sethiddenloginvalue(val)
{
	var _f = document.forms[0];
	for (i=0;i<_f.elements.length;i++)
	{
		if (_f.elements[i].id.indexOf('hidden_login') != -1)
			_f.elements[i].value=val;

	}
}

//Sudeshna--JavaScript to validate zipcode: Zip should have 5 numeric characters
function ValidateZip()
{	
	document.all.divZipError.style.display = "none";
		
	var mf = GetMainFormName();				
	var zipTextboxRef =  GetElementName("address_zip", mf);
	var zipTextbox = document.forms[mf].elements[zipTextboxRef];
	
	//Check if zip code length is 5
	if(zipTextbox.value.length != 5)
	{
		document.all.tblcellZip.style.color = "#FFFFFF";
		document.all.divZipError.style.display = "block";
		return false;
	}				
	else			
	{
		//If zipcode length is 5, only allow 0-9 to be entered as the characters
		var checkOK = "0123456789";
		var allValid = true;
		for (var i=0; i < zipTextbox.value.length; i++) 
		{ 
			ch = zipTextbox.value.charAt(i);
			
			for (var j = 0;  j < checkOK.length;  j++)
			{							
				if (ch == checkOK.charAt(j))
					break;							
			}
			
			if (j == checkOK.length)
			{							
				allValid = false;
				break;
			}
		}
		if (!allValid) 
		{
			document.all.tblcellZip.style.color = "#ED950A";
			document.all.divZipError.style.display = "block";
			return false;
		}	
		else
		{
			validateDate();
			return true;
		}						
	}
}

function validateDate()
{
	var mf = GetMainFormName();
	var monthTextboxName = GetElementName("birthmonth", mf);
	var dayTextboxName = GetElementName("birthday", mf);
	var yearTextboxName = GetElementName("birthyear", mf);

	var monthTextbox =  document.forms[mf].elements[monthTextboxName];
	var dayTextbox =  document.forms[mf].elements[dayTextboxName];
	var yearTextbox =  document.forms[mf].elements[yearTextboxName];
											
	if (monthTextbox.value =='MM' && dayTextbox.value =='DD' && yearTextbox.value=='YYYY')
	{
		monthTextbox.value ='';
		dayTextbox.value ='';
		yearTextbox.value ='';
	}
}		

function ValidateForm()
{
	var mf = GetMainFormName();
	var Addtxtbox = GetElementName("address_displayname", mf);			
	var Addtxtboxobj =  document.getElementById(Addtxtbox);	
	
	var HiddenAddtxtbox = GetElementName("address_displaynamedefault", mf);			
	var HiddenAddtxtboxobj =  document.getElementById(HiddenAddtxtbox);	
	
	if(Addtxtboxobj.value == "")
		Addtxtboxobj.value = HiddenAddtxtboxobj.value;
	
	return(ValidateZip());
}

//--------------------------------------------------------------------------//
//Function Name	:	setCookie												//
//Argument(s)	:	name (String name of cookie)							//
//Description	:	This function is used to set value from the cookie.		//
//					It's expires time is set to 1 day						//
//Author		:															//
//Date			:	05/25/2005												//
//--------------------------------------------------------------------------//

function setCookie (name) {
var expires = new Date ();
expires.setTime (expires.getTime() + (1000 * 60 * 60 * 24 * 1));
    
document.cookie = name + "=" + escape (location.href) +     
"; expires=" + expires.toGMTString() +  "; path=/"; 
}

function setEmailCookie (name,value) {
var expires = new Date ();
expires.setTime (expires.getTime() + (1000 * 60 * 60 * 24 * 364));
    
document.cookie = name + "=" + escape (value) +     
"; expires=" + expires.toGMTString() +  "; path=/"; 
}

//--------------------------------------------------------------------------//
//Function Name	:	getCookie												//
//Argument(s)	:	name (String name of cookie)							//
//Description	:	This function is used to get value from the cookie.		//
//Author		:															//
//Date			:	05/25/2005												//
//--------------------------------------------------------------------------//

function getCookie (name) 
{
    var dcookie = document.cookie; 
    var cname = name + "=";
    var clen = dcookie.length;
    var cbegin = 0;
        while (cbegin < clen) 
        {
        var vbegin = cbegin + cname.length;
            if (dcookie.substring(cbegin, vbegin) == cname) 
            { 
            var vend = dcookie.indexOf (";", vbegin);
                if (vend == -1) vend = clen;
            return unescape(dcookie.substring(vbegin, vend));
            }
        cbegin = dcookie.indexOf(" ", cbegin) + 1;
            if (cbegin == 0) break;
        }
    return document.referrer;
   }
   
function getEmailCookie (name) 
{
    var dcookie = document.cookie; 
    var cname = name + "=";
    var clen = dcookie.length;
    var cbegin = 0;
        while (cbegin < clen) 
        {
        var vbegin = cbegin + cname.length;
            if (dcookie.substring(cbegin, vbegin) == cname) 
            { 
            var vend = dcookie.indexOf (";", vbegin);
                if (vend == -1) vend = clen;
            return unescape(dcookie.substring(vbegin, vend));
            }
        cbegin = dcookie.indexOf(" ", cbegin) + 1;
            if (cbegin == 0) break;
        }
    return "";
   }
   
   
   function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) 
	if ((obj=MM_findObj(args[i]))!=null) 
	{ 
		v=args[i+2];
		if (obj.style) 
		{ 
			obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; 
		}
		obj.visibility=v; 		
	}
	//If there's a popup...
	if(args[3] != null)
	{
		var layer = MM_findObj(args[0]);	
		var popuptxt = MM_findObj(args[3]);	
		var oBo = cBB (popuptxt);
		var oBp = cBB (layer);			
		layer.style.left = oBo.l + popuptxt.offsetWidth - 40;
		//Layer1.style.top = oBo.t - 200;
		layer.style.top = oBo.t - layer.offsetHeight + 5;		
	}
}

function MM_findObj(n, d) { //v4.01
var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}