/*
    Product Display JavaScript functions
*/

/*
 * Global var used for saicoswap
 */
//var selectedColor="";

/*
 * Change the image source when moused over
 *
 * The name of image element in the document must match the image file name.
 * A postfix of "_on" is added for an active/moused-over image.
 *
 */
function mouseOver(name)
{
    document[name].src = "/images/proddisplay/" + name + "_on.gif";
}

/*
 * Change the image source when moused out
 *
 * The name of image element in the document must match the image file name.
 *
 */
function mouseOut(name)
{
    document[name].src = "/images/proddisplay/" + name + ".gif";
}

/*
 * Called when an attribute select box is changed to see if its error status should be cleared.
 * Missing attribute select boxes are set to a yellow background.
 *
 */
function checkError(element)
{
    if (element.selectedIndex != 0)
    {
        element.style.background = "white";
    }
    else
    {
        element.style.background = "yellow";
    }
}

/*
 * Automatically populate the correct attributes for the item selected
 *
 * Elements in the form that start with "STYLE_" are select boxes containing a list of items.
 * After selecting one, this function is called to populate select boxes for attributes like color and size.
 * A combination of an item and its attributes is called a module.  Modules are numbered starting from zero.
 *
 */
function styleChange(moduleIndex)
{
    // find out which item the user just selected
    eval("style = document.form.style_" + moduleIndex);
    itemNumber = style.options[style.selectedIndex].value;

    // the user did not select an actual item, so we blank out the attribute select boxes
    if (itemNumber == "") {
        resetStyle(moduleIndex);
        return;
    }

    // get the distinct attributes (color, size, etc) for this item
    eval("distinctAttrs = distinctAttrs_" + itemNumber);

    // for each attribute that appears with the module, we will repopulate its select box
    for (i = 0; i < distinctAttrs.length; i++)
    {
        // get the select box for this attribute
        eval("selectBox = document.form." + distinctAttrs[i].toLowerCase() + "_" + moduleIndex);

        // get the list of values for this item and attribute
        eval("newValues = " + distinctAttrs[i] + "_" + itemNumber);

        // set the select box on the form to the correct length and select the first item
        selectBox.length = newValues.length + 1;
        selectBox.selectedIndex = 0;

        // if the attribute is color, we add a little extra text
        name = distinctAttrs[i].toLowerCase();
        if (name == "color") selectBox.options[0].text = "" + name;
        else selectBox.options[0].text = name;
		// copy the new values into the attribute select box
			for (j = 0; j < newValues.length; j++)
			{	
				if (name == "color" && getParameter("atp") != "a" && window.top.location.toString().indexOf("vsdcm01.limited.com")==-1 ){
					if (newValues[j].length > 4) {
						var startIndex =0;
						startIndex = newValues[j].indexOf("-")+1;
						newValues[j] = newValues[j].substring(startIndex,(newValues[j].length));
					}
				
				}
				selectBox.options[j + 1].text = newValues[j];
			}

    }
}

/*
 * Empty the attribute select boxes for this module
 *
 * Elements in the form that start with "STYLE_" are select boxes containing a list of items.
 * After selecting one, this function is called to populate select boxes for attributes like color and size.
 * A combination of an item and its attributes is called a module.  Modules are numbered starting from zero.
 *
 */
function resetStyle(moduleIndex)
{
    // get the select box for item
    eval("style = document.form.style_" + moduleIndex);
    style.selectedIndex = 0;

    // get the item number of the first item so we can get the distinct attributes
    itemNumber = style.options[1].value;
    eval("distinctAttrs = distinctAttrs_" + itemNumber);

    // each distinct attribute has a select box that needs emptied
    for (i = 0; i < distinctAttrs.length; i++)
    {
        // get the select box for this attribute
        eval("selectBox = document.form." + distinctAttrs[i].toLowerCase() + "_" + moduleIndex);

        // empty out the select box
        selectBox.length = 1;
        selectBox.selectedIndex = 0;

        // if the attribute is color, we add a little extra text
        name = distinctAttrs[i].toLowerCase();
        if (name == "color") selectBox.options[0].text = "" + name;
        else selectBox.options[0].text = name;
    }
}

/*
 * Display buttons next to AddToBag button
 *
 * displaying these buttons are based on different cookies
 */
function displayExtraButtons()
{
    fromSearch = getVSCookie("from_search");
    regCookie = getVSCookie("NC_Session_ID");

    // if we are going to display buttons, we add a little spacer image
    if (fromSearch.length > 0 || regCookie.length > 0)
    {
        //document.writeln('<tr> <td><img src="/images/common/clr_spcr.gif" width="1" height="3"></td> </tr>');

        // button labeled "Add to wish list"
        if (regCookie.length > 0) {
          //  displayViewWishListButton();
		  //alert('scott ATB test - wishlist button called');
        }

        // button labeled "Return to search results"
		if (fromSearch.length > 0) {
            displayReturnToSearchButton();
        }

    }
}

/*
 * Display button for returning to search
 *
 */
function displayReturnToSearchButton(){
    fromSearch = getVSCookie("from_search");
	var url = (window.top.location).toString();
	var url_check = url.search(/\/Sale\/online/);
	var privateSale = false;
	if (url_check != -1) {
		privateSale = true;
	} 
	
	if (privateSale) {
		var ie6	= (navigator.appVersion.indexOf("MSIE 6.")!=-1);
		var ie7	= (navigator.appVersion.indexOf("MSIE 7.")!=-1);
		if (ie6) {
			document.write('<div class="from_search_ie6">');
		} else if (ie7) {
			document.write('<div class="from_search_ie7">');
		} else {
			document.write('<div class="from_search">');
		}
		document.write('<a href="'+ fromSearch + '" border="0">');
		document.write('<img src="/images/proddisplay/btn_return_to_search.gif" ');
		document.write('alt="return to search results" border="0"></a>');
		document.write('</div>');
	}
}

/*
 * Display button for viewing wish list
 *
 */
function displayViewWishListButton()
{
    document.write('<tr> <td>');
    document.write('<a href="/wishlist/" border="0">');
    document.write('<img src="/images/proddisplay/btn_view_wishlist.gif" border="0" ');
    document.write('alt="View your wishlist"></a><br>');
    document.writeln('</td> </tr>');
}

/*
 * Return the item number for a particular module
 *
 * The item number is either stored as a hidden field prefixed with a name of "ITEM_"
 * (for a single item) or a select box prefixed with a name of "STYLE_" (for a group of items).
 * The module number completes the name of the element.
 *
 */
function getItemNumber(moduleIndex)
{
    var itemNumber = null;

    // check if this module uses a hidden field
    eval("style = document.form.item_" + moduleIndex);

    if (style != null && typeof style != "undefined")
    {
        itemNumber = style.value;
    }
    else
    {
        // check if this module uses a select box
        eval("style = document.form.style_" + moduleIndex);

        if (style != null && typeof style != 'undefined')
        {
            itemNumber = style.options[style.selectedIndex].value;
        }
    }

    // if neither a hidden field or select box, we return null
    return itemNumber;
}

/*
 * Look at the item number of a module sets its value if it is a select box
 *
 * A module uses a hidden field for item number when it is a single item and a select box when it is a group
 * of items.  If the itemNumber passed in matches the item number of the module, a true is returned.
 * If the module is a group of items, the correct item in the select box is selected.
 * If the itemNumber passed in does not match, a false is returned.  If the module could not be found,
 * a null is returned.
 *
 */
function setItemNumber(moduleIndex, itemNumber)
{
    if (itemNumber == "") return null;

    // look for the hidden field single item
    eval("style = document.form.item_" + moduleIndex);

    if (style != null && typeof style != "undefined")
    {
        if (style.value == itemNumber)
        {
            return true;
        }
        return false;
    }

    // look for a select box of items
    eval("style = document.form.style_" + moduleIndex);

    if (style != null && typeof style != "undefined")
    {
        // go through the items in the list to find the one that matches the itemNumber passed in
        for (i = 0; i < style.options.length; i++)
        {
            if (style.options[i].value == itemNumber)
            {
                // we match the itemNumber passed in, so we select this item in the list
                style.options[i].selected = true;
                // cause the rest of the attribute select boxes to repopulate
                styleChange(moduleIndex);
                return true;
            }
        }
        return false;
    }

    return null;
}

/*
 * Save the select box settings in a cookie
 *
 * The format of the cookie is:
 *
 * page_key:item_number,attribute1,attribute2,quantity:item_number2,attribute1,quantity
 *
 * page_key is category name plus item number to ensure we restore settings only for this page.
 * item_number is the item number without catalog code
 * the selected index of the select box is stored for attributes and quantity.
 */
function saveForm(pageKey)
{
    maxModules = 40;
    cookieValue = pageKey;

    // loop through every module and get its attributes
    for (moduleIndex = 0; moduleIndex < maxModules; moduleIndex++)
    {
        itemNumber = getItemNumber(moduleIndex);

        if (itemNumber == "")
        {
            continue;
        }
        else if (itemNumber == null)
        {
            break;
        }

        cookieValue = cookieValue + ":" + itemNumber;
        eval("distinctAttrs = distinctAttrs_" + itemNumber);

        // save the value of each distinct attribute select box
        for (i = 0; i < distinctAttrs.length; i++)
        {
            eval("selectBox = document.form." + distinctAttrs[i].toLowerCase() + "_" + moduleIndex);
            cookieValue = cookieValue + "," + selectBox.selectedIndex;
        }

        // quantity is an attribute that is hardcoded
        eval("selectBox = document.form.quantity_" + moduleIndex);
        cookieValue = cookieValue + "," + selectBox.selectedIndex;
    }

    setVSCookie("selectedItems", cookieValue);
}

/*
 * Restore the select box settings from the cookie
 *
 * See the saveForm function for a description of the cookie
 *
 */
function restoreForm(pageKey)
{
    cookieValue = getVSCookie("selectedItems");
    // each module in the string is separated by a colon
    itemArray = cookieValue.split(":");

    // the page key is category name and item number so we only restore attributes on the right page
    if (itemArray[0] != pageKey) return;

    // loop through the values for each module
    for (itemIndex = 1, moduleIndex = 0; itemIndex < itemArray.length; moduleIndex++)
    {
        // the select box
        values = itemArray[itemIndex].split(",");
        itemNumber = values[0];

        // try to set the item number for this module
        result = setItemNumber(moduleIndex, itemNumber);

        // the item number does not match the module, so we try the next module
        if (result == false) continue;
        // this module was not even found, so we are done
        else if (result == null) break;

        eval("distinctAttrs = distinctAttrs_" + itemNumber);

        // set the index for the attributes select boxes
        for (i = 1; i < values.length - 1; i++)
        {
            eval("selectBox = document.form." + distinctAttrs[i-1].toLowerCase() + "_" + moduleIndex);
            selectBox.selectedIndex = values[i];
        }

        // quantity attribute is hardcoded
        eval("selectBox = document.form.quantity_" + moduleIndex);
        selectBox.selectedIndex = values[i];

        itemIndex++;
    }
}

function CoremetricsSelect(itemNumber,categoryDesc,sDesc){
		productDesc = sDesc + " (" + itemNumber + ")";
		cmCreateProductviewTag(itemNumber, productDesc, categoryDesc,1)
}



// localize URL variables
function getParams() {
	var idx = document.URL.indexOf('?');
	var params = new Array();
	if (idx != -1) {
		var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
		for (var i=0; i<pairs.length; i++) {
			nameVal = pairs[i].split('=');
			params[nameVal[0]] = nameVal[1];
		}
	}
	return params;
}
params = getParams();
//return var from URL
function getVal(name) {
	var rtnVar = " ";

	if (unescape(params[name]) != null && unescape(params[name]) != "undefined" ) { 
		var rtnVar = unescape(params[name]); 
	}
	return rtnVar;
}




function getModule(itemNbr){
	rtnVar=0;

	for (index = 0; index < document.form.length; index++) {
		element = document.form[ index ];

		if ( element.name.substr(0, 4)  == "item" )
		{
			if (element.value == itemNbr) {
			rtnVar = element.name.substr(5, element.name.length);
			
			break;
			}
		}
	}
	return rtnVar
}







function restoreFormFromURL()
{
    // each module in the string is separated by a colon
    var itemSet = getVal("setItems")
	items = itemSet.split(",");
	for (i = 0; i < items.length ; i++)
	{
	
		valueBlob = getVal(items[i]);
		valueSet = valueBlob.split(":");

		for (valueIndex = 0; valueIndex < valueSet.length; valueIndex++) {
			attrSet = valueSet[valueIndex].split(",");
			attribute = attrSet[0];
			
			for (ai = 1; ai < attrSet.length; ai++){
				atrIdx=(parseInt(getModule(items[i]))+(ai-1)  );
				doSet = false;
				
				if (i+1 < items.length) {
					nextItem = items[i+1];
					if (getModule(nextItem) > atrIdx) {
						doSet=true;
					}
				} else {
					doSet=true;
				}
				
				if (doSet) {
					eval("selectBox = document.form." + attribute.toLowerCase() + "_" + atrIdx);
					if (selectBox != null && selectBox.valueOf != "undefined"){
					
						for (sOpts=0; sOpts < selectBox.options.length; sOpts++) {
							
							inVar = attrSet[ai].toLowerCase();
							selVar = selectBox.options[sOpts].text.toLowerCase();
							if (selVar.length > 2) {
								
								selVar = selVar.substr(0, 3);
								inVar = inVar.substr(0, 3);
								//alert(selVar + " : " + inVar);
							}
							
							if(selVar == inVar){
								selectBox.selectedIndex = sOpts;
							}
						}
					}
				}
			}
		}
	}
}

function popMVM(itemNbr) {
		var w,h;
		w = 648;
		h = 560;

		searchString = null;
		categoryID = "My Virtual Model";
		pageID = "PRODUCT: MVM POPUP" ;
		cmCreatePageviewTag (pageID,searchString,categoryID);

		var avaImg = new Image();
		avaImg.src = "http://switch.atdmt.com/action/VirtualModel_PopUp_Window";
		var myWin =window.open('http://vs1.mvm.com/vs_ctx/jsp/handlers/main/mvmvdrhandler.jsp?param1=' + itemNbr + '&param2=0&param3=vs&roc=vs&pop=F', 'MVM', 'resizable=no,width=' + w + ',height=' + h + ',scrollbars=no,toolbars=no');
		myWin.focus();	



	
    

	return false;
}
