﻿var g_itemCache = new Array();
var stockStatusCache;
var itemSizeCache;
var itemPriceCache;
var highlightColourCache;
var strItemCode = "";
var firstitemPriceCache;

function getCorrespondingItemSize(itemCode) {
	// prevent dom walking: use assumption that a select with id itemCodeX has corresponding select with id itemSizeX.
	var itemCodeId = itemCode.id;
	if (itemCodeId) {
		var correspondingItemSizeId = itemCodeId.replace('Code', 'Size');
		return document.getElementById(correspondingItemSizeId);
	}
	return null;
}

/* Returns the select element that the user has clicked */
function GetItemSizeSelectElement(selectedItemSize) 
{
	var selectedItemSizeId = selectedItemSize.id;
	if (selectedItemSizeId) 
	{
		var correspondingItemNoId = selectedItemSizeId.replace('Size', 'Code');
		return document.getElementById(correspondingItemNoId);
	}
	return null;
}

function showSizeData(itemSize, options) {
	if (options) {
		var optionsLen = options.length;
		for (var i = 0; i < optionsLen; i++) {
			itemSize.options[i] = options[i];
		}
		itemSize.selectedIndex = 0;
	}
}

/*  Updates drop down of size options with any supplied stock status and highlights the options accordingly.
    This method is called when the  size option drop down has a corresponding item code drop down. */
function UpdatePresentationMultipleItemCode(itemNumber, itemSizeId, itemnewprice) 
{
	var iBagBtnIndex;
	var btnBag;
	var selectElement;
	var itemprice
	var url = document.location.href.toLowerCase();
	itemprice = '£' + itemnewprice
    iBagBtnIndex = itemSizeId.substring(itemSizeId.length, itemSizeId.length - 1);
	selectElement = document.getElementById(itemSizeId);
	selectElement.options[0].text = '--';
	for (var i = 1; i < selectElement.options.length; i++) 
	{
		if (stockStatusCache[i])
		{
			switch (stockStatusCache[i])
            {
				
                //todo: When other stock status'(other than Sold Out) are to be displayed, there will
                //      be no need to test here. Just append short user friendly message stored in
                //      stockStatusCache[i] and set selectElement.options[i].style.backgroundColor
                //      to the supplied colour code stored in highlightColourCache[i].                
					case 'Sold Out':
					if ((url.indexOf("girls") != "-1") || (url.indexOf("boys") != "-1"))
					{
                    selectElement.options[i].text = firstitemPriceCache[i] + ' - ' + stockStatusCache[i];
					}
					else
					{
					selectElement.options[i].text = itemSizeCache[i] + ' - ' + stockStatusCache[i];
					}
                    selectElement.options[i].style.backgroundColor = highlightColourCache[i];
                    btnBag = document.getElementById('btnBag' + iBagBtnIndex);
                //	btnBag.focus();
                    break;
            }
		}
		else
		{
					if ((url.indexOf("girls") != "-1") || (url.indexOf("boys") != "-1"))
					{
                    selectElement.options[i].text = firstitemPriceCache[i];
                    selectElement.options[i].style.backgroundColor = highlightColourCache[i];
                    btnBag = document.getElementById('btnBag' + iBagBtnIndex);
                //	btnBag.focus();
					}

		}
	}
	itemNumber.selectedIndex = 0;
}

/*  Updates drop down of size options with any supplied stock status and highlights the options accordingly.
    This method is called when the  size option drop down NOT have a corresponding item code drop down. */
function UpdatePresentationSingleItemCode(itemSizeId)
{    
	var iBagBtnIndex;
	var btnBag;
	var selectElement
	var itemprice = '8.00'
	
	var url = document.location.href.toLowerCase();
	iBagBtnIndex = itemSizeId.substring(itemSizeId.length, itemSizeId.length - 1);
	selectElement = document.getElementById(itemSizeId);
	selectElement.options[0].text = '--';
	for (var i = 1; i < selectElement.options.length; i++) 
	{
		if (stockStatusCache[i])
		{
			switch (stockStatusCache[i])
            {
                //todo: When other stock status'(other than Sold Out) are to be displayed, there will
                //      be no need to test here. Just append short user friendly message stored in
                //      stockStatusCache[i] and set selectElement.options[i].style.backgroundColor
                //      to the supplied colour code stored in highlightColourCache[i].
                case 'Sold Out':
					if ((url.indexOf("girls") != "-1") || (url.indexOf("boys") != "-1"))
					{
                    selectElement.options[i].text = firstitemPriceCache[i] + ' - ' + stockStatusCache[i];
					}
					else
					{
					selectElement.options[i].text = itemSizeCache[i] + ' - ' + stockStatusCache[i];
					}
                    selectElement.options[i].style.backgroundColor = highlightColourCache[i];
	                btnBag = document.getElementById('btnBag' + iBagBtnIndex);
	               // btnBag.focus();  
	                break;
            }
		}
		else
		{
					if ((url.indexOf("girls") != "-1") || (url.indexOf("boys") != "-1"))
					{
                    selectElement.options[i].text = firstitemPriceCache[i];
                    selectElement.options[i].style.backgroundColor = highlightColourCache[i];
                    btnBag = document.getElementById('btnBag' + iBagBtnIndex);
                //	btnBag.focus();
					}

		}
	}
}

function createAndCacheOptions(xml, itemSize, itemCodeValue) {

	var memberNode = xml.firstChild;
	var url = document.location.href.toLowerCase();
	//alert(url.indexOf("Children"));
	if (memberNode) {
		sizeNodes = memberNode.getElementsByTagName("size");
		if (sizeNodes) {
			sizeNodesLen = sizeNodes.length;
			if (sizeNodesLen > 0) {
				var options = new Array(sizeNodesLen);
				sizeNode = sizeNodes[0];
				var option = new Option();
				option.text = '--';
				option.value = itemCodeValue + ':0';
				options[0] = option;
				for (var i = 0; i < sizeNodesLen; i++) {
					sizeNode = sizeNodes[i];
					var option = new Option();
					if ((url.indexOf("girls") != "-1") || (url.indexOf("boys") != "-1"))
					{
					option.text = sizeNode.getAttribute("text") + " - £" + sizeNode.getAttribute("price").replace('.00', '');
					}
					else
					{
					option.text = sizeNode.getAttribute("text");
					}
					option.text = option.text.replace('&frac12;','½ ');
					option.value = sizeNode.getAttribute("value");
					option.price = sizeNode.getAttribute("price");      
					options[i+1] = option;
				}
				showSizeData(itemSize, options);
				g_itemCache[itemCodeValue] = options;
			}
		}
	}
}

/*  Caches stock status (supplied by xml from InstantStockPopup.asp) of specified size options for instant stock popup when 
    the size drop down has a corresponding item code drop down. */
function CacheISPSingleItemCode(xml, itemSize, selectName) 
{
    var iEndPosOfSizeOption = 0;
    var strItemSize = ""
    var oMemberNode = xml.firstChild;
    var positionOfFullStop = 0;

    if (oMemberNode) {
	    sizeNodes = oMemberNode.getElementsByTagName("ItemArea");
	    if (sizeNodes) 
	    {
		    sizeNodesLen = sizeNodes.length;

		    if (sizeNodesLen > 0) {
			    for (var i = 0; i < sizeNodesLen; i++) 
			    {
				    for (var j = 0; j < itemSizeCache.length; j++)
				    {
					    sizeNode = sizeNodes[i];
					    strItemSize = String(sizeNode.getAttribute("ItemOption"));
					    iEndPosOfSizeOption = strItemSize.indexOf(" ",  0);
					    if (iEndPosOfSizeOption >= 0)
					    {
					        strItemSize = strItemSize.substring(0, iEndPosOfSizeOption);
					    }
    					
					    if (itemSizeCache[j] == strItemSize)
					    {
                            //Note: The following block removes a full stop from from any stock message ('Sold Out.' for e.g).
                            //      This will be remove when user friendly messages are used in phase 2 of the
                            //      instant stock popup project.
                            positionOfFullStop = String(sizeNode.getAttribute("StockMessage")).indexOf(".",  0)
                            if (positionOfFullStop >= 0)					        
					        {
                                stockStatusCache[j] = String(sizeNode.getAttribute("StockMessage")).substring(0, positionOfFullStop);
					        }
					        else
					        {
                                stockStatusCache[j] = String(sizeNode.getAttribute("StockMessage"));
					        }
                            highlightColourCache[j] = sizeNode.getAttribute("HighlightColour")
					    }				    
				    }
			    }
		    }
		    UpdatePresentationSingleItemCode(selectName);
	    }
    }
}

/*  Caches stock status (supplied by xml from InstantStockPopup.asp) of specified size options for instant stock popup when 
    the size drop down has a corresponding item code drop down. */
function CacheISPMultipleItemCode(xml, itemNumber, itemSize, selectName, itemnewprice) 
{
	var iEndPosOfSizeOption = 0;
	var strItemSize = ""
	var oMemberNode = xml.firstChild;
	var positionOfFullStop = 0;
	
	if (oMemberNode) {
		sizeNodes = oMemberNode.getElementsByTagName("ItemArea");
		//If ItemArea section of xml doc is populated, update cache and presentation of drop down
		if (sizeNodes) 
		{
			sizeNodesLen = sizeNodes.length;
			if (sizeNodesLen > 0) 
			{
				for (var i = 0; i < sizeNodesLen; i++) 
				{
				    for (var j = 0; j < itemSizeCache.length; j++)
				    {
					    sizeNode = sizeNodes[i];
					    strItemSize = String(sizeNode.getAttribute("ItemOption"));
					    iEndPosOfSizeOption = strItemSize.indexOf(" ",  0);
					    if (iEndPosOfSizeOption >= 0)
					    {
					        strItemSize = strItemSize.substring(0, iEndPosOfSizeOption);
					    }
					    
					    if (itemSizeCache[j] == strItemSize)
					    {
                            //Note: The following block removes a full stop from from any stock message ('Sold Out.' for e.g).
                            //      This will be remove when user friendly messages are used in phase 2 of the
                            //      instant stock popup project.
                            positionOfFullStop = String(sizeNode.getAttribute("StockMessage")).indexOf(".",  0)
                            if (positionOfFullStop >= 0)					        
					        {
                                stockStatusCache[j] = String(sizeNode.getAttribute("StockMessage")).substring(0, positionOfFullStop);
					        }
					        else
					        {
                                stockStatusCache[j] = String(sizeNode.getAttribute("StockMessage"));
					        }
					        highlightColourCache[j] = sizeNode.getAttribute("HighlightColour")
					    }				    
				    }
				}
			var itemnewprice
			itemnewprice = itemnewprice
            UpdatePresentationMultipleItemCode(itemNumber, selectName, itemnewprice);				
			}
		}
	}
}

function processResult(itemSizeId, itemCodeValue) {
	var itemSize = document.getElementById(itemSizeId);
	if (itemSize) {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				createAndCacheOptions(http_request.responseXML, itemSize, itemCodeValue);
			} 
		}
	}
}

/* Handler for AJAX call used for instant stock popup when the size drop down does NOT have a corresponding item code drop down*/
function ProcessISPSingleItemCode(itemSize, selectName, itemprice) 
{
    if (itemSize)
    {
        if (http_request.readyState == 4) 
        {
            // If HTTP request status is OK (200), update contents of drop down list
            if (http_request.status == 200) 
            {
                CacheISPSingleItemCode(http_request.responseXML, itemSize, selectName);
            } 
        }
    }
}

/* Handler for AJAX call used for instant stock popup when the size drop down has a corresponding item code drop down*/
function ProcessISPMultipleItemCode(itemNumber, itemSize, selectName, itemprice) 
{
    var itemNo = document.getElementById(itemSize);
    if (itemSize)
    {
        if (http_request.readyState == 4) 
        {
            // If HTTP request status is OK (200), update contents of drop down list
            if (http_request.status == 200) 
            {
				var itemnewprice
				itemnewprice = itemprice
                CacheISPMultipleItemCode(http_request.responseXML, itemNumber, itemSize, selectName, itemnewprice);
            } 
        }
    }
}

function getSizes(e) {
	var itemCode = _getSource(e);
	var book = itemCode.id.replace('itemCode','bk');
	var page = itemCode.id.replace('itemCode','p');
	if (itemCode) {

		var itemSize = getCorrespondingItemSize(itemCode);
		if (itemSize) {
			// 2) delete the existing option tags
			var options = itemSize.options;
			var optionLength = options.length;
			for (var i = 0; i < optionLength; i++) {
				itemSize.remove(options[i]);
			}

			// 3) if the new data is already cached in local variable, use that
			var itemCodeValue = itemCode.options[itemCode.selectedIndex].value;
			var data = g_itemCache[itemCodeValue];
			if (data == null) {
				// 4.1) give user feedback
				var option = new Option();
				option.text = 'Please wait...';
				itemSize.options[0] = option;

				
				// 4.2) Get size data from web service
				AsyncUtils_makeRequest("/NXT-I/GENERAL/sizes.asp?b="+document.getElementById(book).value+"&p="+document.getElementById(page).value+"&i=" + itemCodeValue , new Function("processResult('" + itemSize.id + "', '" + itemCodeValue + "')"), "");
			}
			showSizeData(itemSize, data);
		}
	}
}

/* Determines if the stock availability of the selected size option is already known and displayed to the user */
function StockStatusIsKnown(highlightBackgroundColour)
{
    if (highlightBackgroundColour == "")
    {
        return false;
    }
    else
    {
        return true;
    }
}

/* Helper method to remove any appended text/colours indicating stock availability */
function ResetSizeOptions(options)
{
    for (var optionIndex = 1; optionIndex < options.length; optionIndex++) 
    {
	var itemprice = options[optionIndex].price
	if (itemprice === undefined)
	{
		//itemprice = selectedItemSize.options[selectedItemSize.selectedIndex].price;
		itemprice = firstitemPriceCache;
	}
        //options[optionIndex].text = itemSizeCache[optionIndex] + ' - £' + itemprice; 
		options[optionIndex].text = firstitemPriceCache[optionIndex];
        options[optionIndex].style.backgroundColor='';
    }
}

/*  Builds a query string used for Instant Stock Popup functionality. This method should only
    be called when the selected size option belongs to a drop down that has a corresponding 
    item code drop down. */
function CreateISPQueryStringMultipleItemCode(selectedItemSize, itemNoId)
{
    var queryString = "i=" + itemNoId;
    strItemCode = itemNoId;
    
    for (var i = 1; i < selectedItemSize.length; i++)  
    {                           
        queryString = queryString + "&o" + i + "=" + selectedItemSize.options[i].value;
    }
    return queryString;
}

/*  Builds a query string used for Instant Stock Popup functionality. This method should only
    be called when the selected size option belongs to a drop down that does NOT have a 
    corresponding item code drop down. */
function CreateISPQueryStringSingleItemCode(selectedItemSize, itemCodeAndSize, itemCode)
{
    var itemSizeOption;
    var queryString = 'i=' + itemCode;
    strItemCode = itemCode;
    
    for (var i = 1; i < selectedItemSize.length; i++)  
    {                           
        itemCodeAndSize = selectedItemSize.options[i].value;
        //Extract the size option from the string that contains item code and size option
        itemSizeOption = itemCodeAndSize.substring(12, itemCodeAndSize.length);
        queryString = queryString + "&o" + i + "=" + itemSizeOption;
    }
    return queryString;
}

/* Clears down the cache used for instant stock popup */
function ClearInstantStockPopupCache()
{
    stockStatusCache = null;
    itemSizeCache = null;
    itemPriceCache = null;
    firstitemPriceCache = null;
    highlightColourCache = null;    
    stockStatusCache = new Array();
    itemSizeCache = new Array();
    highlightColourCache = new Array();  
    itemPriceCache = new Array(); 
    firstitemPriceCache = new Array(); 
}

/* On change event handler for item size drop down that has a corresponding item code drop down */
function InstantStockPopupMultipleItemCode(e)
{
    var selectedItemSize = _getSource(e);
    var selectedItemSizeValue = selectedItemSize.options[selectedItemSize.selectedIndex].value;
    var itemNo = GetItemSizeSelectElement(selectedItemSize);
    var itemNoId = itemNo.options[itemNo.selectedIndex].value;
    var queryString = "";
    var options;
	var itemprice = selectedItemSize.options[selectedItemSize.selectedIndex].price;
    
    //If the selected item size value is not 0 (i.e. not "--", begin the instant stock popup process...
    if ((selectedItemSizeValue != "0") && (selectedItemSizeValue.indexOf(":0",  0) < 0))
    {
        if (itemNoId != strItemCode)
        {
            //If a different item code has been selected, clear the cache
            ClearInstantStockPopupCache()
        }
        if (selectedItemSize) 
        {
            //Only make AJAX call if the stock status for the selected item option is not known
            if (!StockStatusIsKnown(selectedItemSize.options[selectedItemSize.selectedIndex].style.backgroundColor))
            {
                options = selectedItemSize.options;
                //Set the array size for item sizes and stock status to to the same length (the 
                //number of size options available for the selected item.
                itemSizeCache.length = options.length;        
                itemPriceCache.length = options.length; 
                stockStatusCache.length = options.length;
                highlightColourCache.length = options.length;      
                firstitemPriceCache.length = options.length;     
                //Populate item size array with all available item sizes and initialise stock status array
                if (itemSizeCache[1] == null)
                {
                    for (var optionIndex = 1; optionIndex < options.length; optionIndex++) 
                    {
                        itemSizeCache[optionIndex] = options[optionIndex].value ;
                        itemPriceCache[optionIndex] = options[optionIndex].price ;
                        firstitemPriceCache[optionIndex] = options[optionIndex].text ;
                        stockStatusCache[optionIndex] = null;
                        highlightColourCache[optionIndex] = null;
						var itemprice = itemPriceCache[optionIndex];
						
                    }
                    ResetSizeOptions(options);
                }
                //Make AJAX call providing required data within query string to asp page. Also specify function to be used as 
                //handler for AJAX function 'AsyncUtils_makeRequest'. This returns xml (containing stock status for a set number 
                //of item sizes) from mainframe via the web server
                queryString = CreateISPQueryStringMultipleItemCode(selectedItemSize, itemNoId);  
                //append the selected size option to the query string
                queryString = queryString + "&s=" + selectedItemSizeValue
				
				if (itemprice === undefined)
				{
				itemprice = '8.01';
				}
				
                AsyncUtils_makeRequest("/NXT-I/GENERAL/InstantStockPopup.asp?" + queryString, new Function("ProcessISPMultipleItemCode('" + itemNoId + "', '" + selectedItemSizeValue + "', '" + selectedItemSize.id + "', '" + itemprice + "')"), "");
            }//if (!StockStatusIsKnown...
        }//if (selectedItemSize) 
    }//if (selectedItemSizeValue != "0")
}

/* On change event handler for item size drop down that doesn't have a corresponding item code drop down */
function InstantStockPopupSingleItemCode(e)
{
    var selectedItemSize = _getSource(e);
    var selectedItemSizeValue = selectedItemSize.options[selectedItemSize.selectedIndex].value;
    var itemNo = GetItemSizeSelectElement(selectedItemSize);
    var queryString = "";
    var options;    
    var itemCodeAndSize;
    var itemCode;
    
    //Extract the size option from the string that contains item code and size option
    selectedItemSizeValue = selectedItemSizeValue.substring(12, selectedItemSizeValue.length);
    //If the selected item size value is not 0 (i.e. not "--", begin the instant stock popup process...
    if (selectedItemSizeValue != "0")
    {
        if (selectedItemSize) 
        {
            itemCodeAndSize = selectedItemSize.options[0].value;
            itemCode = itemCodeAndSize.substring(0, 11);
            if (itemCode != strItemCode)
            {
                ClearInstantStockPopupCache()
            }
            //Only make AJAX call if the stock status for the selected item option is not known
            if (!StockStatusIsKnown(selectedItemSize.options[selectedItemSize.selectedIndex].style.backgroundColor))
            {
                options = selectedItemSize.options;
                //Set the array size for item sizes and stock status to to the same length (the 
                //number of size options available for the selected item.
                itemSizeCache.length = options.length;        
                stockStatusCache.length = options.length;
                highlightColourCache.length = options.length;         
                itemPriceCache.length = options.length;        
                firstitemPriceCache.length = options.length;       
                //Populate item size array with all available item sizes and initialise stock status array
                if (itemSizeCache[1] == null)
                {
                    for (var optionIndex = 1; optionIndex < options.length; optionIndex++) 
                    {
                        //Extract the size option from the string that contains item code and size option and insert
                        //it into the item size cache
                        itemSizeCache[optionIndex] = options[optionIndex].value.substring(12, options[optionIndex].value.length);
                        stockStatusCache[optionIndex] = null;
                        highlightColourCache[optionIndex] = null;
                        itemPriceCache[optionIndex] = options[optionIndex].price ;
						firstitemPriceCache[optionIndex] = options[optionIndex].text ;
						itemprice = itemPriceCache[optionIndex];
                    }
                    ResetSizeOptions(options);
                }//if (itemSizeCache[1] == null)
                queryString = CreateISPQueryStringSingleItemCode(selectedItemSize, itemCodeAndSize, itemCode);  
                queryString = queryString + "&s=" + selectedItemSizeValue
                //Make AJAX call providing required data within query string to asp page. Also specify function to be used as 
                //handler for AJAX function 'AsyncUtils_makeRequest'. This returns xml (containing stock status for a set number 
                //of item sizes) from mainframe via the web server
				if (itemprice === undefined)
				{
				itemprice = '8.01';
				}
                AsyncUtils_makeRequest("/NXT-I/GENERAL/InstantStockPopup.asp?" + queryString, new Function("ProcessISPSingleItemCode('" + selectedItemSizeValue + "', '" + selectedItemSize.id + "', '" + itemprice +  "')"), "");
            }//if (!StockStatusIsKnown...
        }//if (selectedItemSize) 
    }//if (selectedItemSizeValue != 0)
}

function getSelect(selects, nameToTest) {
	if (selects) {
		var selectsLength = selects.length;
		var selectList = new Array();
		var j = 0;
		for (var i=0; i< selectsLength; i++) {
			var select = selects[i];
			var selectName = select.getAttribute('name');
			var selectId = select.getAttribute('id');
			if (selectName) {
				if (selectName == nameToTest) {
					selectList[j++] = select;
				}
			}
		}
		return selectList.length > 0 ? selectList : null;
	}
	return null;
}

function initSize(e) {
	var selects = document.getElementsByTagName("select");
	var selectList = getSelect(selects, 'itemcode');
	//note: itemSizeSelectList is required for drop downs that don't have a corresponding item code drop down
	var itemSizeSelectList = getSelect(selects, 'i');
	if (selectList != null) {
		var selectListLength = selectList.length;
		for (var i = 0; i < selectListLength; i++) {
			var itemCode = selectList[i];
			var itemSize = getCorrespondingItemSize(itemCode);
			if (itemSize) 
			{
				// cache takes array of options, so need to walk through options collection
				if (itemSize.options != null)
			        {
					var numOptions = itemSize.options.length;
					var options = new Array(numOptions);
					for (var j = 0; j < numOptions; j++) 
					{
						options[j] = itemSize.options[j];
					}
					g_itemCache[itemCode.options[itemCode.selectedIndex].value] = options;
				}
			}
			addEvent(itemCode, 'change', getSizes);
            //If instant stock popup is enabled, add event to support it's functionality
            if (InstantStockPopupEnabled)
            {
                addEvent(itemSize, 'change', InstantStockPopupMultipleItemCode);
            }
		}
	}
	if (itemSizeSelectList != null)
	{
		var itemSizeSelectListLength = itemSizeSelectList.length;
		for (var i = 0; i < itemSizeSelectListLength; i++) 
		{
			var itemSize = itemSizeSelectList[i];
            //If instant stock popup is enabled, add event to support it's functionality
            if (InstantStockPopupEnabled)
            {   
                //If the item has fixed payments associated with it, do not run instantstockpopup
                if (itemSize.options[1].value.split(":")[1].toUpperCase()!="BUY NOW") //BUY NOW is 'Buy It Now' sizecode that will be the first item in the drop down.
                {
                    addEvent(itemSize, 'change', InstantStockPopupSingleItemCode);
                }
            }
		}
	}
}

addEvent(window, 'load', initSize);

