﻿/// <reference path="jquery.vsdoc.js" />

// Note: ShowPrice should be customised depending on required price display.

// Globals
var handler = "/default.aspx";
var checkQty = false;
var ex_format = "$";

/// # Helpers #

// Wrapper around older function
function InsertElementOnPage(target, data, cleanUp) {
    if (cleanUp == 1) {
        $(target).html("&nbsp;");

        if (data != '') {
            $(target).empty();
        }
    }
    $(target).append(data);
}


/// # Legacy QuickOrder # ///

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, exFormat)
{
    if (areaName != '')
    {
        workingArea = document.getElementById(areaName);
    }

    if (exFormat != null) {
        ex_format = exFormat;  
    }
}

function ExpandMe()
{
    var elem = null;

    if (workingArea == null)
    {
        return;
    }

    elem = workingArea;

    var lastRow = elem.rows.length - 1;
    var offset = lastRow % 2;
    var iteration = ((lastRow - offset)/ 2) + 0;
    
    totalElementsInList = iteration;

    var linerow = elem.insertRow(lastRow);
    linerow.id = "quick_row_1_" + iteration;
    linerow.style.display = "none";

    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 = 10;
    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 = "search";
    var elHid = document.createElement('span');
    elHid.innerHTML = "&nbsp;"
    elHid.id = "placeholder_hidden_" + iteration;
    tdStyle.className = "StyleNumber";
    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 = "Image";
    tdProduct.appendChild(elProduct);

    var tdColourSize = row.insertCell(2);
    var elColourSize = document.createElement('span');
    elColourSize.innerHTML = "&nbsp;";
    elColourSize.id = "placeholder_coloursize_" + iteration;
    tdColourSize.className = "Description";
    tdColourSize.appendChild(elColourSize);

    var tdDescription = row.insertCell(3);
    var elDescription = document.createElement('span');
    elDescription.innerHTML = "&nbsp;";
    elDescription.id = "placeholder_description_" + iteration;
    tdDescription.className = "Pricing";
    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 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)?'':'-') + ex_format + num + '.' + cents);
}

function SetProductContent(obj, styleCode, counter_id)
{
    if (obj != null)
    {
        obj.innerHTML = 'Loading...';
        
        var url = handler;
        var data = { "z": "quickorder", "action": "ax", "cs": styleCode, "lc": counter_id }
        jQuery.ajax({
            "url" : url,
            "data" : data,
            "success" : function(data) { ProcessFeedBack(data, counter_id); },
            "cache": false
        });
    }
}

function CheckForQtyAndExpandIfNeeded(curNo)
{
    if (totalElementsInList - curNo < addIfLessThan)
    {
        var i = 0;
        for (i = 0; i < addCount; i++)
        {
            ExpandMe();
        }
    }
}

function ProcessFeedBack(responseText, rowCode)
{
	var htmlProduct = "";
	var htmlColourSize = "";
	var htmlDescription = "";
	var htmlHidden = "";

	var ajaxContentPlacholder = document.getElementById("ajax_feedback");

	if (ajaxContentPlacholder != null)
	{
		var fetchedHTML = 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)

		ShowPrice(rowCode);

		ajaxContentPlacholder.innerHTML = '&nbsp;';
	}
}

var ProductCombinations = new Array();
var ProdItemIDs = new Array();
var itemsCounter = 0;

function AddProdItemDet (pdpID, pdID, pdColour, pdSize, pdPrice, pdDiscount, pdSoftDeleted, pdInStock, pdMaxQty, pdDelayed)
{
  //      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;
		ProductCombinations [pdID] = DetObj;
		ProdItemIDs [itemsCounter] = pdID;
		itemsCounter++;
	}
}

function AddProductWithoutItems(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 ((parseInt(clr)) >= 0 && (parseInt(sz) >= 0) && (item.Colour == clr) && (item.Size == sz)) {
						result = item;
						break;
					}
				}
			}
		}
	}

	if ((currProductID > 0) && (result == null))
	{
		result = -1;
		if ((clr == '') || (sz == '')) {
			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 /><span class="specials">was ' + formatCurrency(locatedItem.Price) + ' save ' + formatCurrency(locatedItem.Discount) + '</span>';
			        discountText = '<p class="PriceSave">You Save ' + formatCurrency(locatedItem.Discount) + '</p>';
			        priceText = '<p class="PriceNow">Our Special Price ' + formatCurrency(locatedItem.Price - locatedItem.Discount); +'</p>'
			    } else {
    			    priceText = '<p class="Price">' + formatCurrency(locatedItem.Price); + '</p>'
			    }

			    if ((specialsElement != null) && (specialsElement.innerHTML != '')) {
			        discountText = discountText + '<p class="Offer">' + specialsElement.innerHTML + '</p>';
			    }

			    if (locatedItem.SoftDeleted == '1' || locatedItem.SoftDeleted == '2') {
			        stockText = '<span class="errormsgsm">This item is not currently available</span>';
			    }
			    else if (locatedItem.InStock == '0') {
			        stockText = '<span class="errormsgsm">This item is not in stock</span>';
			    }
			    else if (locatedItem.Delayed == '1') {
			        stockText = '<span class="errormsgsm">Delayed Delivery</span>';
			    }
			    else {
			        stockText = 'In Stock';
			    }

			}
			else if (locatedItem == -1) {
			    stockText = '<span class="errormsgsm">Size colour combination not in stock</span>';
			}
			else if (locatedItem == 0) {
			    stockText = '<span>Please choose size/selection</span>';
			    if (locatedItem.SoftDeleted == '1' || locatedItem.SoftDeleted == '2') {
			        stockText = '<span class="errormsgsm">This item is not currently available</span>';
			    }
			} else {

			}
			if (priceElement != null) {
			    priceElement.innerHTML = priceText + discountText;
			}

			if (stockElement != null) {
    			stockElement.innerHTML = stockText + '&nbsp;';
			}
			
			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 = 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;
			    } else {
                    result = true;
			    }
			}
			i++;
		}
	}
	return result;
}

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 <= 0) {
    		qtyObj.value = 1; 	
		} else if (qtyEntered <= qtyMax || checkQty === false) {
			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){}   			
		}		
	}
}


