var workingArea = null;
var prevCodes = new Array();
var totalElementsInList = 0;
var addIfLessThan = 2;
var addCount = 2;

  function GoNextBox(curID, e) {
    var keynum;
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }

    if ((keynum == 13) && (curID >= 0)) {
      ExecuteNextBoxJump(curID, 0);
    }
    return true;
  }
  
  function ExecuteNextBoxJump(curID, recCall) {
    newIdx = curID + 1;
    var targetObj = document.getElementById('qosID_' + newIdx);
    if (targetObj != null) {
      var targetRow = document.getElementById('quick_row_2_' + newIdx);
      if ((targetRow != null) && (targetRow.style.display == "none")) {
        ExecuteNextBoxJump(newIdx, recCall);
        return;
      }
      else {
        targetObj.focus();
      }
    }
    else {
      newIdx = curID - 1;
      var prevBox = document.getElementById('qosID_' + newIdx);
      var currBox = document.getElementById('qosID_' + curID);
      if ((prevBox != null) && (currBox != null) && (recCall != 1)) {
        prevBox.focus();
        currBox.focus();
        setTimeout("ExecuteNextBoxJump(" + curID + ", 1)", 30);
      }
    }
  }

function SetWorkingArea(areaName)
{
    if (areaName != '')
    {
        workingArea = document.getElementById(areaName);
    }
}

function ExpandMe()
{
    var elem = null;

    if (workingArea == null)
    {
        return;
    }

    elem = workingArea;

    var lastRow = elem.rows.length;
    var offset = lastRow % 1;
    var iteration = ((lastRow - offset)/ 1) + 0;
    
    totalElementsInList = iteration;

/*    var linerow = elem.insertRow(lastRow);
    linerow.id = "quick_row_1_" + iteration;

    var tdLine = linerow.insertCell(0);
    tdLine.colSpan = 4;
    tdLine.className = "emptyCell";
    var elSpacer = document.createElement('img');
    elSpacer.src = "images/spacer.gif";
    elSpacer.width = "1";
    elSpacer.height = "1";
    tdLine.appendChild(elSpacer);
    
    lastRow = lastRow + 1;*/

    var row = elem.insertRow(lastRow);
    row.id = "quick_row_2_" + iteration;

    var tdStyle = row.insertCell(0);
    var elQos = document.createElement('input');
    elQos.type = "text";
    elQos.name = "qos";
    elQos.id = "qosID_" + iteration;
    elQos.size = 6;
    elQos.value = "";
    elQos.setAttribute('autocomplete', "off");
    elQos.onblur = function() {ProcessEnteredStyle(this);}
    if (navigator.appName.indexOf("Microsoft") != -1) {
      elQos.onkeydown = function() {return GoNextBox(iteration, event);}
    }
    else { // Firefox, Opera, Safari etc.
      elQos.setAttribute("onkeydown", "GoNextBox(" + iteration + ", event);");
    }
    elQos.className = "stylenr";
    var elHid = document.createElement('span');
    elHid.innerHTML = "&nbsp;"
    elHid.id = "placeholder_hidden_" + iteration;
//    tdStyle.className = "cellStyle";
//    tdStyle.width = "100";
    tdStyle.appendChild(elQos);
    tdStyle.appendChild(elHid);

    var tdProduct = row.insertCell(1);

    var elProduct = document.createElement('span');
    elProduct.innerHTML = "&nbsp;"
    elProduct.id = "placeholder_prod_" + iteration;
//    tdProduct.className = "cellCartDescription";
    tdProduct.appendChild(elProduct);

    var tdColourSize = row.insertCell(2);
    var elColourSize = document.createElement('span');
    elColourSize.innerHTML = "&nbsp;";
    elColourSize.id = "placeholder_coloursize_" + iteration;
//    tdColourSize.className = "cellCartDescription";
    tdColourSize.appendChild(elColourSize);

    var tdDescription = row.insertCell(3);
    var elDescription = document.createElement('span');
    elDescription.innerHTML = "&nbsp;";
    elDescription.id = "placeholder_description_" + iteration;
//    tdDescription.className = "cellCartDescription";
    tdDescription.appendChild(elDescription);

}

function ProcessEnteredStyle(obj)
{
    if (obj != null)
    {
        var line_id = obj.id.replace('qosID_', '');
        var product_area = document.getElementById('placeholder_prod_' + line_id);

        if ((line_id >= 0) && (product_area != null))
        {
            var styleCode = obj.value;
            var product_text = product_area.innerHTML.replace('&nbsp;', '');
            
            if (styleCode == '')
//            if ((product_text != '') && (styleCode == ''))
            {
                ClearProductContent(line_id);
            }
            else if ((styleCode != '') && (prevCodes[line_id] != styleCode))
            {
                ClearProductContent(line_id);
                SetProductContent(product_area, styleCode, line_id);
                CheckForQtyAndExpandIfNeeded(line_id);
            }
            prevCodes[line_id] = styleCode;
        }
    }
}

function MyextractNumber()
{
    //extractNumber(this,0,false);
}

function MyblockNonNumbers(e, obj)
{
//    blockNonNumbers(obj, e, false, false);
}


function ClearProductContent(counter_id)
{
  if (counter_id >= 0) {
    InsertElementOnPage(document.getElementById('placeholder_hidden_' + counter_id), '&nbsp', 1)
    InsertElementOnPage(document.getElementById('placeholder_prod_' + counter_id), '&nbsp', 1)
    InsertElementOnPage(document.getElementById('placeholder_coloursize_' + counter_id), '&nbsp', 1)
    InsertElementOnPage(document.getElementById('placeholder_description_' + counter_id), '&nbsp', 1)
  }
}

function formatCurrency(num)
{
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10)
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function SetProductContent(obj, styleCode, counter_id)
{
    if (obj != null)
    {
        obj.innerHTML = 'Loading...';
        
        var url = "/support.aspx?iSAMS=ax&cs=" + styleCode + "&lc=" + counter_id;

        var xmlHttp = GetXmlHttpObject();
        if (xmlHttp==null)
        {
            alert ("Your browser does not support AJAX!");
            return;
        } 

          xmlHttp.onreadystatechange = function() {ProcessFeedBack(xmlHttp, counter_id)};
          xmlHttp.open("GET", url, true);
          xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
          xmlHttp.send(null); 
    }
}

function CheckForQtyAndExpandIfNeeded(curNo)
{
    if (totalElementsInList - curNo < addIfLessThan)
    {
        var i = 0;
        for (i = 0; i < addCount; i++)
        {
            ExpandMe();
        }
    }
}

function ProcessFeedBack(myxmlHttp, rowCode)
{
	var htmlProduct = "";
	var htmlColourSize = "";
	var htmlDescription = "";
	var htmlHidden = "";

	if(myxmlHttp.readyState == 4)
	{
		if(myxmlHttp.status == 200)
		{
			htmlProduct = '';

			var ajaxContentPlacholder = document.getElementById("ajax_feedback");

			if (ajaxContentPlacholder != null)
			{
				var fetchedHTML = myxmlHttp.responseText;

				ajaxContentPlacholder.innerHTML = fetchedHTML;

				InsertElementOnPage(document.getElementById('placeholder_hidden_' + rowCode), document.getElementById('quick_hidden').innerHTML, 1)
				InsertElementOnPage(document.getElementById('placeholder_coloursize_' + rowCode), document.getElementById('quick_coloursize').innerHTML, 1)
				InsertElementOnPage(document.getElementById('placeholder_description_' + rowCode), document.getElementById('quick_description').innerHTML, 1)
				InsertElementOnPage(document.getElementById('placeholder_prod_' + rowCode), document.getElementById('quick_product').innerHTML, 1)

				launchJavascript(fetchedHTML);

				if (navigator.userAgent.indexOf('Safari') != -1) {
					var jsObj = document.getElementById('proditms' + rowCode);
					if (jsObj != null) {execJS(jsObj);}
				}

				ShowPrice(rowCode);

				ajaxContentPlacholder.innerHTML = '&nbsp;';
			}

		}
		else
		{
			alert("Error: returned status code " + xmlHttp.status + " " + xmlHttp.statusText);
		}
	}
}

var ProductCombinations = new Array();
var ProdItemIDs = new Array();
var itemsCounter = 0;

function AddProdItemDet (pdpID, pdID, pdColour, pdSize, pdPrice, pdDiscount, pdSoftDeleted, pdInStock, pdMaxQty, pdDelayed, pdDelayedDate)
{
  //      alert('insert ' + pdID);
	if (ProductCombinations[pdID] == null)
	{
		var DetObj = new Object();
		DetObj.ProductID = pdpID;
		DetObj.ItemID = pdID;
		DetObj.Colour = pdColour;
		DetObj.Size = pdSize;
		DetObj.Price = pdPrice;
		DetObj.Discount = pdDiscount;
		DetObj.SoftDeleted = pdSoftDeleted;
		DetObj.InStock = pdInStock;
		DetObj.MaxQty = pdMaxQty;
		DetObj.Delayed = pdDelayed;
		DetObj.DelayedDate = pdDelayedDate;
		ProductCombinations [pdID] = DetObj;
		ProdItemIDs [itemsCounter] = pdID;
		itemsCounter++;
	}
}

function AddDroductWithoutItems(pdID)
{
	ProdItemIDs [itemsCounter] = pdID;
}

function GetProductByLine(lineCode)
{
	var arr = ProductCombinations;
	var arrID = ProdItemIDs;
	var pricePlace = document.getElementById('placeholder_description_' + lineCode);
	var colourSrc = document.getElementById('clid_' + lineCode);
	var sizeSrc = document.getElementById('szid_' + lineCode);
	var productLocated = false;
	var currProductIDSrc = document.getElementById('pid_' + lineCode);
	var currProductID = -1;

	if (currProductIDSrc != null) {
		currProductID = currProductIDSrc.value;
	}

	var result = null;
	if ((colourSrc != null) && (sizeSrc != null)) { //(pricePlace != null) &amp;&amp;
		var clr = colourSrc.value;
		var sz = sizeSrc.value;
		var item = null;
		var prID = null;
		for (idx in arrID) {
			prID = arrID[idx];
			item = ProductCombinations[prID];
			if (item != null)
			{
				if (item.ProductID == currProductID) {
					productLocated = true; // for distinguish between "product not found"/"no size and colour"
					if ((clr > 0) && (sz > 0) && (item.Colour == clr) && (item.Size == sz)) {
						result = item;
						break;
					}
				}
			}
		}
	}

	if ((currProductID > 0) && (result == null))
	{
		result = -1;
		if ((clr == 0) || (sz == 0)) {
			result = 0;
		}
	}
	return(result);
}

function ShowPrice(lineCode)
{
	var description_Obj = document.getElementById('placeholder_description_' + lineCode);
	var priceElement = document.getElementById('price_' + lineCode);
	var qtyElement = document.getElementById('qty_' + lineCode);
	var buyElement = document.getElementById('buy_' + lineCode);
	var stockElement = document.getElementById('stock_' + lineCode);
	var specialsElement = document.getElementById('special_' + lineCode);
	var itemIDElement = document.getElementById('piid_' + lineCode);

	var priceText = '&nbsp;';
	var stockText = '&nbsp;';
	var discountText = '&nbsp;';
	var piiID = '';

	if (buyElement != null){
		buyElement.disabled = true;
		if (description_Obj != null) {
			var locatedItem = GetProductByLine(lineCode);
			if ((locatedItem != null) && (locatedItem != 0) && (locatedItem != -1)) {
				buyElement.disabled = false;
				piiID = locatedItem.ItemID;

				if (locatedItem.Discount > 0) {
					discountText = '<br /><p class="PriceNow">was ' + formatCurrency(locatedItem.Price) + ' save ' + formatCurrency(locatedItem.Discount) + '</p>';
				}

				if ((specialsElement != null) && (specialsElement.value != '')) {
					discountText = discountText + '<br /><p class="PriceNow">' + specialsElement.value + '</p>';
				}

				if (locatedItem.SoftDeleted == '1') {
					stockText = '<span class="notInStock">This item is not currently available</span>';
				}
				else if (locatedItem.InStock == '0') {
					stockText = '<span class="notInStock">This item is not in stock</span>';
				}
				else if (locatedItem.Delayed == '1') {
				    var eta = '';
				    if (locatedItem.DelayedDate != null && locatedItem.DelayedDate != '') {
				        eta = ' - ETA: ' + locatedItem.DelayedDate;
				    }
					stockText = '<span class="notInStock">Delayed delivery' + eta + '</span>';
				}
				else {
					stockText = 'In Stock';
				}
				priceText = formatCurrency(locatedItem.Price - locatedItem.Discount);
			}
			else if (locatedItem == -1) {
				stockText = '<span class="notInStock">Size colour combination not in stock</span>';
			}
			else if (locatedItem == 0) {
				stockText = '<span>Please choose size and colour</span>';
				if (locatedItem.SoftDeleted == '1') {
					stockText = '<span class="notInStock">This item is not currently available</span>';
				}
			}
			if (priceElement != null) {
				priceElement.innerHTML = priceText + discountText + '&nbsp;';
			}
			if (stockElement != null) {
				stockElement.innerHTML = stockText;
			}
			if (itemIDElement != null) {
				itemIDElement.value = piiID;
			}

			if (qtyElement != null) {
//          qtyElement.disabled = buyElement.disabled;
			}

		}
	}
	SetQuickAddVisibility(lineCode);
};
  
  function SetQuickAddVisibility(lineCode)
  {
    var buyElement = document.getElementById('buy_' + lineCode);
    var quickAddElement = document.getElementById('quickadd_' + lineCode);
    if ((buyElement != null) && (quickAddElement != null)) {
      var visilibilityStatus = 'none';
      if (buyElement.checked && (buyElement.disabled == false)) {
        visilibilityStatus = 'inline';
      }
      
      quickAddElement.style.display = visilibilityStatus;
    }
  }
  
  function DeleteItem(linecode)
  {
    if ((linecode != NaN) && (linecode >= 0) && (linecode < 1000)) {
      var styleElement = document.getElementById('qosID_' + linecode);
      if (styleElement != null) {
        styleElement.value = '';
      }
      InsertElementOnPage(document.getElementById('placeholder_hidden_' + linecode), '&nbsp', 1);
      InsertElementOnPage(document.getElementById('placeholder_prod_' + linecode), '&nbsp', 1);
      InsertElementOnPage(document.getElementById('placeholder_coloursize_' + linecode), '&nbsp', 1);
      InsertElementOnPage(document.getElementById('placeholder_description_' + linecode), '&nbsp', 1);
      var rowElement1 = document.getElementById('quick_row_1_' + linecode);
      var rowElement2 = document.getElementById('quick_row_2_' + linecode);
      if (rowElement1 != null) {rowElement1.style.display = "none";}
      if (rowElement2 != null) {rowElement2.style.display = "none";}
      prevCodes[linecode] = '';
    }
  }

  var submitAllowed = false;

function quickOrderSubmit() {
	result = submitAllowed;
	if (result) {
                result = CheckColourSizeSelections();
                if (!result) return false;

		var i = 0;
		while (document.getElementById('qosID_' + i) != null) {
			var buyObj = document.getElementById('buy_' + i);
			if ((buyObj != null) && (buyObj.checked) && (buyObj.disabled == false)) {
				if (IsQtyCorrect(i) == false) {result = false; break;}
			}
			i++;
		}
	}
	return result;
}

// For each item with a checked buy field, make sure colour/size is selected
function CheckColourSizeSelections() {
    if ($('input[name=buy]:checked:disabled').length > 0) {
        alert('Please ensure you have selected a colour and size combination for all items.');
        return false;
    }

    return true;
}

function IsQtyCorrect(linecode)
{
	result = false;
	var qtyObj = document.getElementById('qty_' + linecode);
	var buyObj = document.getElementById('buy_' + linecode);
	var locatedItem = GetProductByLine(linecode);
	if ((qtyObj != null) && (buyObj != null) && (buyObj.checked == true) && (locatedItem != null)) {
		var qtyEntered = qtyObj.value;
		var qtyMax = locatedItem.MaxQty;
		if (qtyEntered <= qtyMax) {
			result = true;
		}
		else {
			alert('The maximum available quantity for this item is ' + qtyMax);
			qtyObj.value = qtyMax;
		}
	}
	return result;
}

function QuickAdd(linecode, evt)
{
	if(linecode.toString() != 'NaN' || linecode >= 0) {
		var addObj = document.getElementById('quickadd_' + linecode);
		var qtyObj = document.getElementById('qty_' + linecode);
		var buyObj = document.getElementById('buy_' + linecode);
		if ((addObj != null) && (qtyObj != null) && (buyObj != null)) {
			var qty = qtyObj.value;
			if ((qty > 0) && (buyObj.disabled == false) && (buyObj.checked == true)) {
				if (IsQtyCorrect(linecode) == false) {
					return false;
				}
				var oHttp = GetXmlHttpObject();
				try {
					var P = document.getElementById('pid_' + linecode).value;
					var T = 0;
					var clID = document.getElementById('clid_' + linecode).value;
					var szID = document.getElementById('szid_' + linecode).value;
					var qty = qtyObj.value;
					oHttp.onreadystatechange = function() { fQuickOrderRenderCart(oHttp, linecode); }
					var url = location.protocol + "//" + location.hostname + "/default" + "." + "a" + "spx?Z=C&action=addx&qs=8&P=" + P + "&T=" + T + "&clID=" + clID + "&szID=" + szID + "&qty=" + qty + "&source=4";
					oHttp.open("POST", url, true);
					oHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					oHttp.setRequestHeader("Content-length", url.length);
//                oHttp.setRequestHeader("Connection", "close");
					LockForXActionAnimated(evt);
					oHttp.send("");
					return false;
				}catch(e){
					return true;
				}
			}
		}
	}
}
  
function fQuickOrderRenderCart(oHttp, linecode){
	if (oHttp.readyState == 4) {	
		if (oHttp.status == 200) {		    
			try{
				UnlockAfterXAction();
				var rtn = oHttp.responseText;   			    
				var cartDiv = document.getElementById("CartSummaryPopUp");
				if (cartDiv != null) {
					cartDiv.style.visibility = "hidden";
					var targetDiv = document.getElementById('ajax_feedback');
					InsertElementOnPage(targetDiv, rtn, 1);
					var cartContentDiv = document.getElementById('cartContent');
					if (cartContentDiv != null) {
						InsertElementOnPage(cartDiv, cartContentDiv.innerHTML, 1);
					}
					InsertElementOnPage(targetDiv, '&nbsp', 1);
					updateCartQty();

					switchResizing('cart');
					cartDiv.style.visibility = "visible";	 
					setTimeout("fHide()", 10000);

					document.getElementById('buy_' + linecode).checked = false;
					SetQuickAddVisibility(linecode);
				}
			}catch(e){}   			
		}		
	}
}


