﻿
var origQty = 0.0; // BH Change 20110121

function msieVersion() {
    var ua = window.navigator.userAgent, msie = ua.indexOf("MSIE ");

    if (msie > 0)      // If Internet Explorer, return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)));
    else                 // If another browser, return 0
        return 0;
}
// Adds event to object, can add multiple
function addEvent(o, evt, func) {
    if (o.attachEvent) o.attachEvent('on' + evt, func);
    else if (o.addEventListener) {
        o.addEventListener(evt, func, false);
    }
}
function reloadPage() {
    window.location.reload();
}

function reposCart(leftMin, mode) {
    var minWidth = 840; ;
    var minHeight = 600;

    if (typeof (leftMin) == 'undefined') leftMin = 645; /* 684 /* 765 */

    var c = document.getElementById("FullCart")

    //alert(c.style.display);

    // don't do anything if cart not visible at server or client level
    if (c == null || c.style.display == 'none') return;

    if (typeof (mode) == 'undefined') mode = c.className;  // Use the current class
    if (mode == '') mode = 'Std';

    var left, ie, ieVer;
    if (window.innerWidth) {
        // Good browsers
        left = (document.documentElement.offsetWidth < minWidth ? leftMin : document.documentElement.offsetWidth - 215);  /* 215 */
        ie = false;
    }
    else {
        // IE
        ie = true;
        ieVer = msieVersion();
        if (msieVersion() > 6)
            left = (document.documentElement.clientWidth < minWidth ? leftMin : document.documentElement.clientWidth - 218); // IE7/8
        else {
            left = (document.body.clientWidth < minWidth ? leftMin : document.body.clientWidth - 223); // IE6
        }
    }

    //alert(mode);
    // Javascript/jquery specific stuff with the different modes
    if (mode == 'Max') {
        // Expanded mode
        if (ie && ieVer <= 7) {
            c.style.left = "255px";
        }
        else {
            // IE8+ and other browsers
            c.style.left = "131px";
        }
    }
    else if (mode == 'Min') {
        // Minimum mode
        c.style.left = left + "px";
    }
    else {
        // Normal mode
        c.style.left = left + "px";
    }

    c.style.display = "block";
}

function resizeMainCenter() {
    var d = document;
    var ifShopPage = d.getElementById("ifShopPage");
    var oDoc = (ifShopPage.contentWindow || ifShopPage.contentDocument);
    if (oDoc.document) oDoc = oDoc.document;
    var iframeContentHeight = oDoc.body.scrollHeight;
    var mainCenter = d.getElementById("PageMainCenter");
    var windowHeight = d.body.offsetHeight;
    var topHeight = d.getElementById("PageHeader").offsetHeight;
    var mainLeftHeight = d.getElementById("PageMainLeft").offsetHeight;
    var mainRightHeight = d.getElementById("PageMainRight").offsetHeight;
    if (iframeContentHeight >= mainLeftHeight && iframeContentHeight >= mainRightHeight && iframeContentHeight >= (windowHeight - topHeight)) {
        mainCenter.style.height = iframeContentHeight;
    } else if (mainLeftHeight >= mainRightHeight && mainLeftHeight > windowHeight) {
        mainCenter.style.height = mainLeftHeight;
    } else if (mainRightHeight >= mainLeftHeight && mainRightHeight > windowHeight) {
        mainCenter.style.height = mainRightHeight;
    } else {
        mainCenter.style.height = windowHeight - topHeight;
    }
}
function hasValue(field, message) {
    // Checks to see that a field has a value and displays a message and returns true/false to cancel an event
    // Todo: use a nice dialog box
    var result = false;
    if (typeof (message) == 'undefined') { message = 'Please enter a value' }
    if (field.value == '') { alert(message); field.focus() } else { result = true; }
    return result;
}
function printPage() {
    window.print();
}

function onlyNumsNew(txtbox, allowZero) {
    var i = 0;
    var chr = "";
    var strRtn = "";
    var txtval = txtbox.value;
    if (IsNumeric(txtval)) {
        if ((txtval == '0') && (allowZero != true)) {
            alertModal('This field can not be 0');
            txtbox.focus();
            return false;
        }
        else {
            txtbox.focus();
            return true;
        }
    }
    else {
        alertModal('Please enter a value greater than 0 <br /> and make sure there are no spaces <br /> or extra characters in your entry.<br/>If you wish to remove this item from the order<br/>use the DEL button in the order basket next to<br/>the description.');
        return false;
    }
}

function onlyDecNumsNew(txtbox, allowZero) {
    var i = 0;
    var chr = "";
    var strRtn = "";
    var dec = false;
    var txtval = txtbox.value;
    for (i = 0; i < txtval.length; i++) {
        chr = txtval.charAt(i)
        if ((chr == "." && dec == false) || ((isNaN(chr) == false) && (chr != " "))) {
            strRtn += chr;
            if (chr == ".") {
                dec = true;
            }
        }
    }

    if (strRtn.length == 0 || strRtn == ".") {
        if (allowZero == true) {
            strRtn = "0";
            return true;
        }
        else {
            strRtn = "";
            alertModal('Please enter a value greater than 0 <br /> and make sure there are no spaces <br /> or extra characters in your entry.<br/>If you wish to remove this item from the order<br/>use the DEL button in the order basket next to<br/>the description.');
            //alertModal('Please enter an valid product code');
            return false;
        }
    }

    if (allowZero != true) {
        if (strRtn == '0') {
            alertModal('This field can not be 0');
            strRtn = "";
            return false;
        }
    }
    txtbox.value = strRtn;
    return true;
}


function onlyDecNums(txtbox, allowZero) {
    var i = 0;
    var chr = "";
    var strRtn = "";
    var dec = false;
    var txtval = txtbox.value;
    for (i = 0; i < txtval.length; i++) {
        chr = txtval.charAt(i)
        if ((chr == "." && dec == false) || ((isNaN(chr) == false) && (chr != " "))) {
            strRtn += chr;
            if (chr == ".") {
                dec = true;
            }
        }
    }
    if (strRtn.length == 0 || strRtn == ".") {
        if (allowZero == true) {
            strRtn = "0";
        } else {
            strRtn = "";
        }
    }
    if (allowZero != true) {
        if (strRtn == '0') {
            alertModal('This field can not be 0');
            strRtn = "";
        }
    }
    txtbox.value = strRtn;

}

function onlyDecNumsAllowZeroAndBlank(txtbox) {
    var i = 0;
    var chr = "";
    var strRtn = "";
    var dec = false;
    var txtval = txtbox.value;
    for (i = 0; i < txtval.length; i++) {
        chr = txtval.charAt(i)
        if ((chr == "." && dec == false) || ((isNaN(chr) == false) && (chr != " "))) {
            strRtn += chr;
            if (chr == ".") {
                dec = true;
            }
        }
    }

    txtbox.value = strRtn;
}

function onlyNumsAndNotGreaterThenOrignal(txtboxID, allowZero, OrignalVal) {
    var i = 0;
    var chr = "";
    var strRtn = "";
    var txtbox = txtboxID
    var txtval = txtbox.value;
    for (i = 0; i < txtval.length; i++) {
        chr = txtval.charAt(i)
        if ((isNaN(chr) == false) && (chr != " ")) {
            strRtn += chr;
        }
    }
    if (strRtn.length == 0) {
        if (allowZero == true) {
            strRtn = parseInt(OrignalVal);
        } else {
            strRtn = parseInt(OrignalVal); ;
        }
    }
    if (allowZero != true) {
        if (strRtn == '0') {
            alertModal('This field can not be 0');
            strRtn = parseInt(OrignalVal);
            txtbox.focus();
            return false;
        }
    }

    if (parseInt(strRtn) > parseInt(OrignalVal)) {
        alertModal('Invalid quantity entered (amended quantity cannot be greater than the original quantity)');
        strRtn = parseInt(OrignalVal);
        txtbox.focus();
        return false;
    }

    txtbox.value = strRtn;
    return true;

}

function onlyDecNumsAndNotGreaterTheOrignal(txtboxID, allowZero, OriginalVal) {
    var i = 0;
    var chr = "";
    var strRtn = "";
    var dec = false;
    var txtbox = txtboxID
    OriginalVal = (Math.round(OriginalVal * 100)) / 100;
    var txtval = txtbox.value;
    for (i = 0; i < txtval.length; i++) {
        chr = txtval.charAt(i)
        if ((chr == "." && dec == false) || ((isNaN(chr) == false) && (chr != " "))) {
            strRtn += chr;
            if (chr == ".") {
                dec = true;
            }
        }
    }
    if (strRtn.length == 0 || strRtn == ".") {
        if (allowZero == true) {
            strRtn = OriginalVal;
        } else {
            strRtn = OriginalVal;
        }
    }
    if (allowZero != true) {
        if (strRtn == '0') {
            alertModal('This field can not be 0');
            strRtn = OriginalVal;
            txtbox.focus();
            return false;
        }
    }
    if (parseFloat(strRtn) > parseFloat(OriginalVal)) {
        alertModal('Invalid quantity entered (amended quantity cannot be greater than the original quantity)');
        strRtn = OriginalVal;
        txtbox.focus();
        return false;
    }

    txtbox.value = strRtn;
    return true;
}
function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

function formatCurrency(strValue) {
    strValue = strValue.toString().replace(/\$|\,/g, '');
    dblValue = parseFloat(strValue);

    blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
    dblValue = Math.floor(dblValue * 100 + 0.50000000001);
    intCents = dblValue % 100;
    strCents = intCents.toString();
    dblValue = Math.floor(dblValue / 100).toString();
    if (intCents < 10)
        strCents = "0" + strCents;
    for (var i = 0; i < Math.floor((dblValue.length - (1 + i)) / 3); i++)
        dblValue = dblValue.substring(0, dblValue.length - (4 * i + 3)) + ',' +
		dblValue.substring(dblValue.length - (4 * i + 3));
    return (((blnSign) ? '' : '-') + '$' + dblValue + '.' + strCents);
}

function showhide(id, id2) {
    obj = document.getElementById(id);
    obj2 = document.getElementById(id2);
    if (obj.style.display == "none") {
        obj.style.display = "block";
        if (obj2) {
            obj2.style.display = "none";
        }
    }
    else {
        obj.style.display = "none";
        if (obj2) {
            obj2.style.display = "block";
        }
    }
}

function MaxLength(field, maxLength) {
    if (field.value.length > maxLength) {
        field.value = field.value.substring(0, maxLength);
        var alteMSG = 'Only ' + maxLength + ' characters allowed';
        alertModal(alteMSG);
        field.focus();

    }
}

function IsNumeric(input) {
    var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    return (RE.test(input));
}

//Usage: on an input onkeypress="return isNumberKey(event)" 
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
        return false;
    return true;
}

//Usage: on an input onkeyup="setFocus(this,'txtCardNumber2', 4)"
function setFocus(inputNow, inputNextID, nowAllowedLength) {
    var next_control = document.getElementById(inputNextID);
    if (inputNow.value.length == nowAllowedLength)
        next_control.focus();
}

function onlyValidChars(txtbox) {

    txtbox.value = txtbox.value.replace(/[^a-zA-Z 0-9]+/g, '');
}
function queryString(parameter) {
    var loc = location.search.substring(1, location.search.length);
    var param_value = false;

    var params = loc.split("&");
    for (i = 0; i < params.length; i++) {
        param_name = params[i].substring(0, params[i].indexOf('='));
        if (param_name == parameter) {
            param_value = params[i].substring(params[i].indexOf('=') + 1)
        }
    }
    if (param_value) {
        return param_value;
    }
    else {
        return false; //Here determine return if no parameter is found
    }
}




/********************************** Ajax Cart *****************************/
//Ajax
function SendAjax(urlMethod, jsonData, returnFunction) {
    jQuery.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: urlMethod,
        data: jsonData,
        dataType: "json",
        success: function (msg) {
            // Do something interesting here.
            if (msg != null) {
                returnFunction(msg);
            }
            else {
                alertModal('Nothing returned from server');
            }
        },
        error: function (xhr, status, error) {
            //alert(status)
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");
            // Display the specific error raised by the server
            alertModal(err.Message, 1, 'ERROR');    //TODO: Need to return validation messages in the normal JSON and check for it.
            //alert(err.Message + "\n" + err.StackTrace);
        }
    });
}

function GetCurrentSortOrder() {
    return document.getElementById('ctl00_cart1_ddlSortOrder').value;
}
function GetBasket(mode, sortorder) {
    ResetCartProgressBar(mode);
    mode = getModeIfReqd(mode);

    if (mode == 'Max') {
        if (typeof (sortorder) == 'undefined') sortorder = GetCurrentSortOrder();   // Default order
    }
    else { sortorder = '' }

    jQuery.noConflict();

    var urlMethod = "/WebService/Cart.asmx/GetBasket";
    var jsonData = '{"mode":"' + mode + '","sort":"' + sortorder + '"}';
    SendAjax(urlMethod, jsonData, ReturnGetBasket);
}

function tryToLogout() {
    var go = true;
    if (!BasketIsEmpty()) {
        confirmModal(function () { logout(); }, 'You have items in your order basket. Do you wish to logout?', null, 1, 'FindFoodFast', null, null);
    }
    else { logout(); }
    return false;
}
function logout() {
    self.location = "/logout.aspx";
}
/************** render cart ********************/
//var BasketIsEmpty = Boolean();
function BasketIsEmpty() {
    return jQuery("#hdnBasketIsEmpty").val() == "true";
}

function ReturnDeleteItem(msg) {

    if (msg.d.ErrorNumber == 500) {
        document.location = '/Login.aspx';
    }

    deleteCartItem(msg);
}
function ReturnGetBasket(msg) {

    if (msg.d.ErrorNumber == 500) {
        document.location = '/Login.aspx';
    }

    BindBasketAndTotal(msg);
}
function BindBasketAndTotal(msg) {

    //BasketIsEmpty = msg.d.BasketTotal == 0;
    jQuery("#hdnBasketIsEmpty").val(msg.d.ItemCount == 0)

    updateTotals(msg);

    BindBasket(msg.d.Basket);

}
function getModeIfReqd(mode) {
    // If mode is undefined or blank then set to default
    if (typeof (mode) == 'undefined' || mode == null) mode = getCookie('bkmode');
    if (mode == null || mode == '') mode = 'Std';
    return mode;
}

function WriteBasket(mode) {
    // Writes the html table version of the basket to the document
    mode = getModeIfReqd(mode);
    if (mode == 'Max') mode = 'Std';  // Do not allow this on the page load
    var tbl = BuildBasket(GetCurrentBasketValue(), mode);
    document.write(tbl);
    changeCart(mode, true);
}
function showHideBasket() {
    var c = document.getElementById("FullCart");
    if (c != null) {
        if (c.style.display == 'none') showBasket(); else hideBasket();
    }
}
function hideBasket() { document.getElementById("FullCart").style.display = "none"; jQuery("#ctl00_DivPage").addClass("Full"); }
function showBasket() { document.getElementById("FullCart").style.display = "block"; jQuery("#ctl00_DivPage").removeClass("Full"); }
function hideBasketMode() {
    document.getElementById("CartMode").style.display = "none";
    // For IE6
    document.getElementById("CartMode").style.visibility = "hidden";
    document.getElementById("OFButtons").style.visibility = "hidden";
    document.getElementById("divCartTop").style.visibility = "hidden";
}
function GetCurrentBasketValue() {
    return document.getElementById("ctl00_cart1_cartdata").value;
}
function SetCurrentBasketValue(value) {
    document.getElementById("ctl00_cart1_cartdata").value = value;
}
function BindBasket(basket, mode) {
    // Uses jQuery to update the contents of the basket
    BindBasketHeader();
    jQuery("#Cart").html(BuildBasket(basket, mode));
}

function RefreshBasket(mode) {
    // Uses the existing data but refreshs based on the mode
    BindBasketHeader();
    jQuery("#Cart").html(BuildBasket(GetCurrentBasketValue(), mode));
}

function BindBasketHeader() {
    var mode = getModeIfReqd(mode);
    if (mode == 'Max')
        jQuery("#DivCartHeader").html(BuildTableForFullBasketHeader());
    else
        jQuery("#DivCartHeader").html("");
}
function GetCurrentBasketMode() {
    mode = getModeIfReqd(document.getElementById("FullCart").className);
    return mode;
}
function BuildBasket(basket, mode) {
    // Gets the html text for the basket based on the mode passed in

    // Keep this up to date
    SetCurrentBasketValue(basket);
    if (typeof (mode) == 'undefined') mode = document.getElementById("FullCart").className;
    if (mode == 'Max')
        result = BuildTableForFullBasket(basket);
    else
        result = BuildTableForStdBasket(basket);
    return result;
}

function ResetCartProgressBar(mode) {
    if (mode != 'Min' && isPBOn(parseInt(document.getElementById("ctl00_cart1_hdnLines").value))) {
        myJsProgressBarHandler.setPercentage('pbCart', 5);
        ShowCartProgressBar();
    }
}
function HideCartProgressBar() {
    //document.getElementById("spnPB").style.visibility = "hidden";
    jQuery('#spnPB').fadeOut('medium', function () {
        // Animation complete.
    });
}
function ShowCartProgressBar() {
    //    document.getElementById("spnPB").style.visibility = "";
    jQuery('#spnPB').fadeIn('medium', function () {
        // Animation complete.
    });
}
function isPBOn(recs) {
    return (typeof (myJsProgressBarHandler) != 'undefined' && recs >= 50);  // Only show if at least 50 lines
}
function BuildTableForStdBasket(basket) {
    // This is called for standard/min modes on the ajax calls and the page load. The basket is a JSON formatted string
    if (basket != '') basket = JSON.parse(basket);  // Convert to JSON

    var cellclass = 'obc', pbOn, x = 1, pct, recs = (basket == null) ? 0 : basket.length;

    pbOn = isPBOn(recs);
    if (pbOn) UpdateCartProgressBar('+20');
    var li = '<center><span id="EmptyBasket">Your current order basket <br /> is empty</span></center>';

    if (!BasketIsEmpty()) {
        li = '<table id="tCart" class="tCart" cellspacing=0 cellpadding=0>';
        jQuery.each(basket, function (key, val) {
            var rowclass;
            if (val.ProductDisplayCssClass == 'A') {
                rowclass = 'cartHeader-Alert';
            } else if (val.ProductDisplayCssClass == 'B') {
                rowclass = 'cartHeader-BackOrder';
            } else {
                rowclass = 'cartHeader';
            }

            li += '<tr><td><table class="tCart" cellspacing=0><tr title="' + (val.AlertMessage == '' ? '' : val.AlertMessage) + '"><td class="' + rowclass + '" ';

            li += 'colspan="4"><a class="CartProductLink" href="javascript:showProdDetail(\'';
            li += val.ItemCode;
            li += '\',\''+val.Account+'\');" title="">';
            li += val.CartItemDescription;
            li += '</a></td></tr><tr><td colspan="3"><span style="font-weight:bold;">';
            li += val.UOMDesc
            li += '&nbsp;&nbsp;</span><span>'

            li += val.Warehouse;
            li += '</span></td><td class="CartDel" align="right"><input type="button" value="Del" onclick="DeleteBasketItem(this,';
            li += val.ItemCode;
            li += ', \'';
            li += val.UOM;
            li += '\');" title="Delete from current order" class="btn_cartDelete" /></td></tr>'
            li += '<tr><td style="width:25%;" class="' + cellclass + '"><input type="text" value="';
            li += val.Quantity;
            li += '" maxlength="';
            li += val.MaxLength;
            li += '" id="txtQty';
            li += val.ItemCode;

            //BH Change 20110121
            li += '" class="TextBox" tabindex=' + (x + 10) + ' onfocus="origQty=this.value; this.select();" ';

            //BH Change 20110121
            //  li += 'onchange="return UpdateCartItem(event, this, ';
            li += 'onblur="return UpdateCartItem(event, this, ';
            li += val.ItemCode;
            li += ',\'';
            li += val.UOM;
            li += '\',';
            li += val.AllowDecimalQty;
            li += ');"';

            li += 'onkeydown="return CheckReturnAndUpdateCartItem(event, this, ';
            li += val.ItemCode;
            li += ',\'';
            li += val.UOM;
            li += '\',';
            li += val.AllowDecimalQty;
            li += ');"';

            li += ' style="width:35px;" /></td><td align="right" style="width:30%;" class="' + cellclass + '"><span>';
            li += val.Price;
            li += '</span></td><td align="right" colspan="2" style="width:45%;" class="' + cellclass + '"><span style="font-weight:bold;">';
            li += val.TotalExclGST;
            li += '</span></td></tr></table></td></tr>'

            if (pbOn) {
                pct = x / recs * 100;
                //myJsProgressBarHandler.setPercentage('pbCart', pct);
                UpdateCartProgressBar(pct);
            }
            x++;
        }
	    );
        li += '</table>';
    }
    setTimeout(HideCartProgressBar, 100);  // Let things catch up
    return li;
}

function UpdateCartProgressBar(pct) {
    //setTimeout(function() { myJsProgressBarHandler.setPercentage('pbCart', pct); }, 1);
    myJsProgressBarHandler.setPercentage('pbCart', pct);
}

function BuildTableForFullBasketHeader() {

    var cellclass = 'ob';
    li = '<table id="tCartHd" class="tCart" cellpadding="0" cellspacing="0" border="0">';
    li += '<tr><th class="' + cellclass + ' bc1">Description (Brand) [Code]</th><th class="' + cellclass + ' bc2">Size/Unit</th><th class="' + cellclass + ' calign bc3">Qty B/O</th><th class="' + cellclass + ' bc4">Qty</th><th class="' + cellclass + ' ralign bc5">Price</th><th class="' + cellclass + ' ralign bc6">Sub Total</th><th class="' + cellclass + ' bc7">UOM</th><th class="' + cellclass + ' calign bc8">Stock</th><th class="' + cellclass + ' calign bc9">Whse</th><th class="' + cellclass + ' bc10">ETA</th><th class="' + cellclass + ' bc11">&nbsp;</th></tr>';
    li += "</table>";

    return li;
}

function BuildTableForFullBasket(basket) {
    // This is called on the ajax calls and the page load. The basket is a JSON formatted string
    if (basket != '') basket = JSON.parse(basket);  // Convert to JSON

    var cellclass = 'obc', pbOn, x = 1, pct, recs = (basket == null) ? 0 : basket.length;

    pbOn = isPBOn(recs);
    if (pbOn) UpdateCartProgressBar('+10');

    var hasUAItems = false, hasBOItems = false;
    var li = '<center><span id="EmptyBasket">Your current order basket <br /> is empty</span></center>';

    if (!BasketIsEmpty()) {

        li = '<table id="tCart" class="tCart" cellpadding="0" cellspacing="0" border="0">';
        jQuery.each(basket, function (key, val) {

            var rowclass;
            if (val.ProductDisplayCssClass == 'A') {
                rowclass = 'cartHeader-Alert';
                hasUAItems = true;
            } else if (val.ProductDisplayCssClass == 'B') {
                rowclass = 'cartHeader-BackOrder';
                hasBOItems = true;
            } else {
                rowclass = 'cartHeader';
            }
            li += '<tr class="' + rowclass + '" title="' + ((val.AlertMessage == '') ? '' : val.AlertMessage) + '">';

            li += '<td class="' + cellclass + ' bc1" >';

            li += '<a class="CartProductLink" href="javascript:showProdDetail(\'';
            li += val.ItemCode;
            li += '\',\'' + val.Account + '\');" title="">';
            li += val.CartItemDescription;
            li += '</a></td>';
            li += '<td class="' + cellclass + ' bc2">' + val.DisplaySizeAndUnit + '</td>';
            li += '<td class="' + cellclass + ' calign bc3">' + val.BOQty + '</td>';

            li += '<td class="' + cellclass + ' bc4"><input type="text" value="' + val.Quantity + '" maxlength="' + val.MaxLength + '" id="txtQty' + val.ItemCode;

            //BH Change 20110121
            li += '" class="TextBox" tabindex=' + (x + 10) + ' onfocus="origQty=this.value; this.select()" ';

            //BH Change 20110121
            // li += 'onchange="return UpdateCartItem(event, this, ';
            li += 'onblur="return UpdateCartItem(event, this, ';
            li += val.ItemCode;
            li += ',\'';
            li += val.UOM;
            li += '\',';
            li += val.AllowDecimalQty;
            li += ');"';
            li += 'onkeydown="return CheckReturnAndUpdateCartItem(event, this, ';
            li += val.ItemCode;
            li += ',\'';
            li += val.UOM;
            li += '\',';
            li += val.AllowDecimalQty;
            li += ');"';
            li += ' style="width:35px;" /></td>';

            li += '<td class="' + cellclass + ' ralign bc5"><span>';
            li += val.Price;
            li += '</span></td><td class="' + cellclass + ' ralign bc6"><span style="font-weight:bold;">';
            li += val.TotalExclGST;
            li += '</span></td>';

            li += '<td class="' + cellclass + ' bc7">' + val.UOMDesc + '</td>';

            li += '<td class="' + cellclass + ' calign bc8">' + val.QtyOnHand + '</td>';

            li += '<td class="' + cellclass + ' calign bc9">' + val.Warehouse + '</td>';

            li += '<td class="' + cellclass + ' bc10">' + (val.ETADate == null ? '&nbsp;' : val.ETADate.toString()) + '</td>';

            // Delete button
            li += '<td class="' + cellclass + ' bc11" align="center"><input id="Del"' + x + ' type="button" value="Del" onclick="DeleteBasketItem(this,';
            li += val.ItemCode;
            li += ', \'';
            li += val.UOM;
            li += '\');" title="Delete from current order" class="btn_cartDelete" /></td>';

            li += '</tr>';

            if (pbOn) {
                pct = x / recs * 100;
                UpdateCartProgressBar(pct);
                //myJsProgressBarHandler.setPercentage('pbCart', pct);
            }
            x++;
        }
	    );
        li += '</table>';

    }
    showHideBulkDelOptions(document.getElementById('ddlDelOpts'), hasUAItems, hasBOItems);
    setTimeout(HideCartProgressBar, 100);  // Let things catch up
    return li;
}

function deleteCartItem(result) {
    // Remove the chosen row html from the order basket and update the totals
    var cbody = document.getElementById("tCart").tBodies[0];
    var index = result.d.ClientID;
    cbody.deleteRow(index);
    // Update cart total
    updateTotals(result);
}
function removeAllItemsInList(list) {
    var len = list.length;
    for (i = len; i >= 1; i--) {
        list.remove(i - 1);
    }
}
function showHideBulkDelOptions(o, hasUAItems, hasBOItems) {
    // o is the drop down list.
    removeAllItemsInList(o);
    if (window.innerWidth) {
        // Good browsers
        if (hasUAItems) o.appendChild(createOption(null, "Delete all unavailable items", "ua"));     // First item
        if (hasBOItems) o.appendChild(createOption(null, "Delete all backorder items", "bo"));
    }
    else {
        // IE
        if (hasUAItems) o.add(createOption(null, "Delete all unavailable items", "ua"));     // First item
        if (hasBOItems) o.add(createOption(null, "Delete all backorder items", "bo"));
    }
    document.getElementById("DivBulkDel").style.visibility = ((o.length == 0) ? 'hidden' : '');

}
function createOption(id, text, value) {
    var opt = document.createElement("option")
    if (id != null) { opt.id = id; }
    opt.text = text;
    opt.value = value;
    return opt;
}

function GetUpdateCall(code, unit, AllowDecimalQty) {
    var cs = '';
    cs += 'UpdateCartItem(event, this, ';
    cs += code;
    cs += ',\'';
    cs += unit;
    cs += '\',';
    cs += (AllowDecimalQty == 0 ? 'false' : 'true');
    cs += ');"'
    return cs;
}

function ButtonOnClick() {
    if (BasketIsEmpty()) {
        alertModal('There are no items in your current order.');
        return false;
    }
    else {
        return true;
    }
}

/************* insert ***************/
function AddItemToBasket(cartErrorNumber) {
    var txtItemCode = jQuery('[id*="txtItemCode"]')[0];
    if (!onlyNums2(txtItemCode, false)) {
        return;
    }

    var txtqty = jQuery('[id*="txtqty"]')[0];
    if (!validateNumberAndDisplayError(txtqty, false, true)) {
        return;
    }

    var itemCode = jQuery('[id*="txtItemCode"]').val();
    var quantity = jQuery('[id*="txtqty"]').val();
    var uom = jQuery('input[name=UOM]:checked').val()

    _itemCode = itemCode;
    _quantity = quantity;
    _uom = uom;

    AddToBasket(cartErrorNumber);
}

function cancel() {
    jQuery('[id*="txtItemCode"]').focus();
}
function AddItemToBasketOnEnter(evt) {
    var evt = (evt) ? evt : ((event) ? event : null);

    if (evt.keyCode == 13) {
        AddItemToBasket(0);
        return false;
    }
}

function ResetQuickEntry() {
    jQuery('[id*="txtItemCode"]').val('');
    jQuery('[id*="txtqty"]').val('1');
    jQuery('[id*="txtItemCode"]').focus();
    jQuery('#rdoUnit').attr('checked', true);
}



/****** update ******/
function CheckReturnAndUpdateCartItem(evt, txtQty, itemCode, uomCode, allowDecimal) {
    var evt = (evt) ? evt : ((event) ? event : null);
    if (evt.keyCode != 13) {
        return true;    //effectively do nothing when not enter
    }


    return UpdateCartItem(evt, txtQty, itemCode, uomCode, allowDecimal);
}
function UpdateCartItem(evt, txtQty, itemCode, uomCode, allowDecimal) {//ignore evt - here to keep same sig
    if (!validateNumberAndDisplayError(txtQty, false, allowDecimal)) {

        // BH Change 20110121
        if (origQty) {
            txtQty.value = origQty;
        }

        return false;
    }

    var quantity = txtQty.value;

    var urlMethod = "/WebService/Cart.asmx/UpdateBasketItem";
    var jsonData = '{"mode":"' + GetCurrentBasketMode() + '","itemCode":' + itemCode + ',"quantity":' + quantity + ', "uomCode":"' + uomCode + '"}';
    SendAjax(urlMethod, jsonData, ReturnGetBasket);

    return false;
}

/*************** delete ****************/
function DeleteBasketItem(o, itemCode, uom) {
    // o = del input button
    var rowindex, curmode;
    curmode = GetCurrentBasketMode();

    if (curmode == 'Max')
        rowindex = o.parentNode.parentNode.rowIndex;  // Find the appropriate row
    else
        rowindex = o.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.rowIndex; // horrible, but need to get the parent tables rowIndex, must be easier way!

    var urlMethod = "/WebService/Cart.asmx/DeleteBasketItem";

    var jsonData = '{"mode":"' + curmode + '","rowNum":' + rowindex + ',"itemCode":' + itemCode + ',"uom":"' + uom + '"}';

    var returnMethod;

    // Refresh whole list in min mode or remove one row
    returnMethod = (curmode == 'Min') ? ReturnGetBasket : ReturnDeleteItem;

    confirmModal(function () { SendAjax(urlMethod, jsonData, returnMethod); }, 'Are you sure you want to delete this item?', null, 1, 'FindFoodFast', null, cancel);
}

function BulkDeleteBasketItems(o) {
    // o = drop down list object
    var delmode = o.value;
    var deltext = o[o.selectedIndex].text.toLowerCase();
    var urlMethod = "/WebService/Cart.asmx/BulkDeleteBasketItems";
    var jsonData = '{"mode":"' + GetCurrentBasketMode() + '","sort":"' + GetCurrentSortOrder() + '","delmode":"' + delmode + '"}';

    confirmModal(function () { SendAjax(urlMethod, jsonData, ReturnGetBasket); }, 'Are you sure that you want to ' + deltext + '?', null, 1, 'FindFoodFast', null, cancel);
}
/*************** empty entire basket ****************/
function EmptyBasket() {

    var urlMethod = "/WebService/Cart.asmx/EmptyBasket";
    var jsonData = '{"mode":"' + GetCurrentBasketMode() + '"}';

    confirmModal(function () { SendAjax(urlMethod, jsonData, ReturnGetBasket); }, 'This will delete all the items from your current order. Continue?', null, 1, 'FindFoodFast', null, cancel);
}


/********************** insert from out side the cart ******************/
function addUnit(itemCode, QtyField, allowDecimal) {
    var uom = '1';
    GetItemCodeAndAddItemToBasketFromOutsideCart(itemCode, QtyField, uom, allowDecimal);
    return false;
}
function addCtn(itemCode, QtyField, allowDecimal) {
    var uom = '0';
    GetItemCodeAndAddItemToBasketFromOutsideCart(itemCode, QtyField, uom, allowDecimal);
    return false;
}
function addAlternative(aUOM, itemCode, QtyField, allowDecimal) {
    var uom = aUOM;
    GetItemCodeAndAddItemToBasketFromOutsideCart(itemCode, QtyField, uom, allowDecimal);
    return false;
}
/*
* Add a product to the basket.
* This method is only used on the ProductDisplay page
* with the intention of extending other basket inserts later.
* Will use Bidvest.BusinessObjects.ProductBase serialized into json 
*/
function addProductToBasket(jsonProductObject, inputBox, uomType, cartErrorNumber) {
    var quantity = jQuery("#" + inputBox.id).val();
    if (validateNumberAndDisplayError(inputBox, false, (jsonProductObject.AllowDecimalQty && (uomType === '0' || uomType === '1')))) {

        var cartErrorNumber = (cartErrorNumber == null) ? 0 : cartErrorNumber;

        var sortorder;
        var mode = GetCurrentBasketMode();
        if (mode == 'Max') sortorder = GetCurrentSortOrder();
        else sortorder = '';

        var jsonData = new Object();
        jsonProductObject.UomItems = null;
        jsonData.product = JSON.stringify(jsonProductObject);
        jsonData.mode = mode;
        jsonData.sort = sortorder;
        jsonData.quantity = quantity;
        jsonData.errorNumber = cartErrorNumber;
        jsonData.uomType = uomType;

        jQuery.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/WebService/Cart.asmx/AddProductToBasket",
            data: JSON.stringify(jsonData),
            dataType: "json",
            success: function (msg) {
                // Do something interesting here.
                if (msg != null) {
                    deliberateAddProductToBasket(jsonProductObject, inputBox, uomType, msg)
                } else { alertModal('Nothing returned from server'); }
            },
            error: function (xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                alertModal(err.Message, 1, 'ERROR');
            }
        });
    }
    return false;
}

function deliberateAddProductToBasket(jsonProductObject, inputBox, uomType, msg) {
    if (msg.d.ErrorNumber) {
        if (msg.d.ShowCancelButton) {
            confirmModal(function () {
                addProductToBasket(jsonProductObject, inputBox, uomType, msg.d.ErrorNumber) 
                }, msg.d.AlertMessage, null, null, null, function () { cancel(); });
            return;
        } else {
            alertModal(msg.d.AlertMessage, null, null, function () {
                ResetQuickEntry();
                BindBasketAndTotal(msg);    //WHY: only do this after OK hit
            });
            return;
        }

        if (msg.d.ErrorNumber == 500) {
            document.location = '/Login.aspx';
        }
    }

    BindBasketAndTotal(msg);
    ResetQuickEntry();
}

/************************************************************************************/

function GetItemCodeAndAddItemToBasketFromOutsideCart(itemCode, QtyField, uom) {
    var quantity = jQuery("#" + QtyField).val();
    if (onlyNumsNew(QtyField, false)) {
        return;
    }

    AddItemToBasketFromOutsideCart(itemCode, quantity, uom);
}

function GetItemCodeAndAddItemToBasketFromOutsideCart(itemCode, QtyField, uom, allowDecimal) {
    var quantity = QtyField.value;
    if (validateNumberAndDisplayError(QtyField, false, allowDecimal)) {
        AddItemToBasketFromOutsideCart(itemCode, quantity, uom);
    }
}

function AddItemToBasketFromOutsideCart(itemCode, quantity, uom) {
    _itemCode = itemCode;
    _quantity = quantity;
    _uom = uom;

    var cartErrorNumber = 0;
    AddToBasket(cartErrorNumber);
}

var _itemCode, _quantity, _uom;

function ReturnAddFromOutsideToBasket(msg) {
    if (msg.d.ErrorNumber) {
        if (msg.d.ShowCancelButton) {
            confirmModal(function () { AddToBasket(msg.d.ErrorNumber) }, msg.d.AlertMessage, null, null, null, function () { cancel(); });
            return;
        } else {
            alertModal(msg.d.AlertMessage, null, null, function () {
                ResetQuickEntry();
                BindBasketAndTotal(msg);    //WHY: only do this after OK hit
            });
            return;
        }

        if (msg.d.ErrorNumber == 500) {
            document.location = '/Login.aspx';
        }
    }

    BindBasketAndTotal(msg);
    ResetQuickEntry();
}

function plural(noun, count) {
    return noun + (count == 1 ? '' : 's');
}

function AddToBasket(cartErrorNumber) {
    var urlMethod = "/WebService/Cart.asmx/AddItemToBasket";
    var sortorder;
    var mode = GetCurrentBasketMode();
    if (mode == 'Max')
        sortorder = GetCurrentSortOrder();
    else
        sortorder = '';

    var jsonData = '{"mode":"' + mode + '","sort":"' + sortorder + '","itemCode":' + _itemCode + ',"quantity":' + _quantity + ', "uomType":"' + _uom + '", "errorNumber":' + cartErrorNumber + '}';
    SendAjax(urlMethod, jsonData, ReturnAddFromOutsideToBasket);
}

function updateTotals(result) {
    var min = 4;
    if (min > result.d.ProductCount) min = result.d.ProductCount;

    jQuery("#ctl00_cart1_lblContentHdr").text('Showing ' + min + ' of ' + result.d.ProductCount + ' entries:');
    //jQuery("#ctl00_cart1_lblItemCount").text(result.d.ItemCount + ' ' + plural('item',result.d.ItemCount));
    jQuery("#ctl00_cart1_lblItemCount").text(result.d.ProductCount + ' ' + plural('line', result.d.ProductCount));
    document.getElementById("ctl00_cart1_hdnLines").value = result.d.ProductCount;
    jQuery("#lblOrderTotal").text('$' + result.d.BasketTotal.toFixed(2));
    if (jQuery("#lblPointsTotal")) {
        jQuery("#lblPointsTotal").text(result.d.PointsTotal);
    }
}

function changeCart(mode, noload) {
    // Adjust the display of the shopping cart depending on the mode chosen 
    // Valid modes: Max, Min, Std
    var c = jQuery('#FullCart');
    if (typeof (c) == 'undefined')
        alert('There is a problem changing the cart mode. The cart is undefined.');
    else {
        // Get the contents from the server
        if (typeof (noload) == 'undefined') noload = false;
        if (!noload) { GetBasket(mode); }
        //alert('change cart to: ' + mode);

        if (mode == 'Max')
            sortOutIE6Items(true);
        else
            sortOutIE6Items(false);

        clearCartClass(c);
        c.addClass(mode);

        setCookie("bkmode", mode, null, '/');
    }
    // Reposition the cart
    reposCart();

}
function clearCartClass(c) {
    c.removeClass('Max');
    c.removeClass('Min');
    c.removeClass('Std');
}

function sortOutIE6Items(putBehind) {
    // Hide the items with specific class to hide in ie6
    var sel = jQuery('.BehindIE6');
    if (putBehind)
        sel.addClass('hide');
    else
        sel.removeClass('hide');
}


/********************** Cart Validation *********************************/
function checkValue(prmobjField) {
    var obj = document.getElementById(prmobjField);
    return checkTxtBoxValue(obj);
}

function checkTxtBoxValue(txtBox) {
    if (txtBox.value == '') {
        alertModal("Please enter a quantity");
        txtBox.focus()
        return false;
    } else if (txtBox.value <= 0) {
        modalAlert("Please enter a value greater than 0");
        txtBox.focus()
        return false;
    }
    return true;
}

function validateNumberAndDisplayError(txtbox, allowZero, allowDecimal) {
    var txtval = txtbox.value;

    if (txtval == '') {
        alertModal('Please enter a value greater than 0 and make sure\nthere are no spaces or extra characters in your entry.<br/>If you wish to remove this item from the order<br/>use the DEL button in the order basket next to<br/>the description.', null, null, function () {

            txtbox.focus()
        });
        return false;
    }

    if (allowDecimal == undefined) {
        allowDecimal = false;
    }

    var i = 0;
    var chr = "";
    var strRtn = "";
    var dec = false;
    for (i = 0; i < txtval.length; i++) {
        chr = txtval.charAt(i)
        if (chr == "." && !allowDecimal) {
            alertModal('Decimal values not allowed for this product.\nPlease enter a value greater than 0 and make sure\nthere are no spaces or extra characters in your entry.<br/>If you wish to remove this item from the order<br/>use the DEL button in the order basket next to<br/>the description.', null, null, function () {
                txtbox.focus()
            });
            return false;
        }
        if ((chr == "." && dec == false) || ((isNaN(chr) == false) && (chr != " "))) {
            strRtn += chr;
            if (chr == ".") {
                dec = true;
            }
        }
    }

    if (strRtn.length == 0) {
        if (allowZero == true) {
            strRtn = "0";
        } else {
            strRtn = "";
        }
    }

    if (allowZero != true) {
        if (strRtn == '0' || strRtn == '' || (parseFloat(strRtn) == 0 || parseFloat(strRtn) == NaN) || parseFloat(strRtn) < 0.001) {
            alertModal('Please enter a value greater than 0\n or if decimals are allowed then enter only 3 decimal places and make sure\nthere are no spaces or extra characters in your entry.<br/>If you wish to remove this item from the order<br/>use the DEL button in the order basket next to<br/>the description.', null, null, function () {
                strRtn = "";
                txtbox.focus();
            });
            return false;
        }
    }

    txtbox.value = strRtn;
    return true;
}

function onlyDecNums(txtbox, allowZero) {
    var i = 0;
    var chr = "";
    var strRtn = "";
    var dec = false;
    var txtval = txtbox.value;

    if (txtval == '') {
        alertModal('Please enter an valid product code');

        txtbox.focus()
        return false;
    }

    for (i = 0; i < txtval.length; i++) {
        chr = txtval.charAt(i)
        if ((chr == "." && dec == false) || ((isNaN(chr) == false) && (chr != " "))) {
            strRtn += chr;
            if (chr == ".") {
                dec = true;
            }
        }
    }
    if (strRtn.length == 0 || strRtn == ".") {
        if (allowZero == true) {
            strRtn = "0";
        } else {
            strRtn = "";
        }
    }
    if (allowZero != true) {
        if (strRtn == '0' || strRtn == '') {
            alertModal('Please enter an valid product code');
            strRtn = "";
            txtbox.focus();
            return false;
        }
    }
    txtbox.value = strRtn;
}

function onlyNums2(txtbox, allowZero) {
    var i = 0;
    var chr = "";
    var strRtn = "";
    var txtval = txtbox.value;

    if (txtval == '') {
        alertModal('Please enter an valid product code', null, null, function () {

            txtbox.focus()
        });
        return false;
    }

    for (i = 0; i < txtval.length; i++) {
        chr = txtval.charAt(i)
        if (chr == ".") {
            alertModal('Decimal values not allowed for this product.\nPlease enter an valid product code', null, null, function () {

                txtbox.focus()
            });
            return false;
        }
        if ((isNaN(chr) == false) && (chr != " ")) {
            strRtn += chr;
        }
    }


    if (strRtn.length == 0) {
        if (allowZero == true) {
            strRtn = "0";
        } else {
            strRtn = "";
        }
    }

    if (allowZero != true) {
        if (strRtn == '0' || strRtn == '') {
            // This old default error description, change it new description. MS 2011/07/01
            // Please enter a value greater than 0 and make sure<br/>there are no spaces or extra characters in your entry.<br/>If you wish to remove this item from the order<br/>use the DEL button in the order basket next to<br/>the description.
            alertModal('Please enter an valid product code', null, null, function () {
                strRtn = "";
                txtbox.focus();
            });
            return false;
        }
    }

    txtbox.value = strRtn;
    return true;
}
function getStartSplits(hdnItemCode, lblUOM, lblQty) {


    var ItemCode = document.getElementById(hdnItemCode).value;
    var UOM = document.getElementById(lblUOM).value;
    var qty = 0;
    var totQty = document.getElementById(lblQty).innerHTML;
    var dt = new Date();
    dt = '01-Jan-2010';

    var urlMethod = "/WebService/Cart.asmx/saveSplitNew";
    var jsonData = '{"itemCode":' + ItemCode + ',"UOM":"' + UOM + '","DeliveryDate":"' + dt + '","Qty":' + qty + ', "TotQty":' + totQty + '}';
    SendAjax(urlMethod, jsonData, ReturnGetSplitNVal);

}

function getValPending(hdnItemCode, lblUOM, lblQty) {
    var ItemCode = document.getElementById(hdnItemCode).value;
    var UOM = document.getElementById(lblUOM).value;
    var qty = 0;
    var totQty = document.getElementById(lblQty).innerHTML;
    var dt = new Date();
    dt = '01-Jan-2010';

    var urlMethod = "/WebService/Cart.asmx/saveSplit";
    var jsonData = '{"itemCode":' + ItemCode + ',"UOM":"' + UOM + '","DeliveryDate":"' + dt + '","Qty":' + qty + ', "TotQty":' + totQty + '}';
    SendAjax(urlMethod, jsonData, ReturnGetSplitNVal);
}

function getSavedSplits(hdnItemCode, lblUOM, lblQty) {


    var ItemCode = document.getElementById(hdnItemCode).value;
    var UOM = document.getElementById(lblUOM).value;
    var qty = 0;
    var totQty = document.getElementById(lblQty).innerHTML;
    var dt = new Date();
    dt = '01-Jan-2010';

    getSavedDeliverySplits(hdnItemCode, lblUOM);
    //var urlMethod2 = "/WebsService/Cart.asmx/EmptySessionSplit";
    //SendAjax2(urlMethod2);
    //var urlMethod = "/WebService/Cart.asmx/saveSplitNew";
    //var jsonData = '{"itemCode":' + ItemCode + ',"UOM":"' + UOM + '","DeliveryDate":"' + dt + '","Qty":' + qty + ', "TotQty":' + totQty + '}';
    //SendAjax(urlMethod, jsonData, ReturnGetSplitValue);
    getValPending(hdnItemCode, lblUOM, lblQty);
}

function saveSplits(hdnItemCode, lblUOM, lblDelDate, txtQty, lblQty) {

    var ItemCode = document.getElementById(hdnItemCode).value;
    var UOM = document.getElementById(lblUOM).value;
    var qty = document.getElementById(txtQty).value;
    var hdVal = document.getElementById('hdVal').value
    var totQty = document.getElementById(lblQty).innerHTML;
    var allowDec = document.getElementById("hdnAllowDec").value

    var isTrueSet = (allowDec === 'true');


    if (!validateNumberAndDisplayError(document.getElementById(txtQty), false, isTrueSet))
        return false;

    if (allowDec == 'true') {
        if (!onlyDecNumsAndNotGreaterTheOrignal(document.getElementById(txtQty), false, hdVal))
            return false
    }
    else {
        if (!onlyNumsAndNotGreaterThenOrignal(document.getElementById(txtQty), false, hdVal))
            return false;
    }

    var dt = new Date();
    //dt = '01-Jan-2010';
    dt = document.getElementById(lblDelDate).value
    if (dt == '') {
        alertModal('Enter a valid date to split line!');
        return false;
    }
    if (dt < new Date()) {
        alertModal("You cannot select a day earlier than today!");
        return false;
    }

    var urlMethod = "/WebService/Cart.asmx/saveSplit";
    var jsonData = '{"itemCode":' + ItemCode + ',"UOM":"' + UOM + '","DeliveryDate":"' + dt + '","Qty":' + qty + ', "TotQty":' + totQty + '}';
    SendAjax(urlMethod, jsonData, ReturnGetSplitNVal);
    //getDeliverySplits();

}

function ReturnGetSplitValue(msg) {

    if (IsNumeric(msg.d) && parseFloat(msg.d) > 0) {
        if (parseFloat(msg.d) == -999) {
            modalAlert('Your session has expired.');
            return;
        }
        document.getElementById('txtVal').value = msg.d;
        document.getElementById('hdVal').value = msg.d;
        jQuery('#dinput').show();
    }
    else {
        document.getElementById('txtVal').visible = false;
        jQuery('#dinput').hide();
    }


}

function ReturnGetSplitNVal(msg) {

    if (IsNumeric(msg.d.Balance) && parseFloat(msg.d.Balance) > 0) {
        if (parseFloat(msg.d.Balance) == -999) {
            modalAlert('Your session has expired.');
            return;
        }
        document.getElementById('txtVal').value = msg.d.Balance;
        document.getElementById('hdVal').value = msg.d.Balance;
        jQuery('#dsplts').html(msg.d.displaySplits);
        jQuery('#dinput').show();

    }
    else {
        jQuery('#dsplts').html(msg.d.displaySplits);
        document.getElementById('txtVal').visible = false;
        jQuery('#dinput').hide();
    }


}

function getDeliverySplits() {
    var urlMethod = "/WebService/Cart.asmx/displaySplits";
    var jsonData = '';
    SendAjax(urlMethod, jsonData, displayDeliverySplits);
}

function getSavedDeliverySplits(hdnItemCode, lblUOM) {
    var ItemCode = document.getElementById(hdnItemCode).value;
    var UOM = document.getElementById(lblUOM).value;
    var urlMethod = "/WebService/Cart.asmx/displaySavedSplits";
    var jsonData = '{"itemCode":' + ItemCode + ',"UOM":"' + UOM + '"}';
    SendAjax(urlMethod, jsonData, displayDeliverySplits);
}

function deleteDelSplits(hdnItemCode, lblUOM) {
    var ItemCode = document.getElementById(hdnItemCode).value;
    var UOM = document.getElementById(lblUOM).value;
    var urlMethod = "/WebService/Cart.asmx/DeleteSplit";
    var jsonData = '{"itemCode":' + ItemCode + ',"uom":"' + UOM + '"}';
    SendAjax(urlMethod, jsonData, dummy);
}

function dummy(msg) {
}
function displayDeliverySplits(msg) {
    jQuery('#dsplts').html(msg.d);
}

function SaveSplits() {
    SendAjax2("saveSplits");
    return false;
}

function SendAjax2(urlMethod) {
    jQuery.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: urlMethod,
        data: "{}",
        dataType: "json"
    });
}

//******************************************************************************************
//
// A CGI program uses the following syntax to add cookie information to the HTTP header:
// 
// Set-Cookie:   name=value   
// [;EXPIRES=dateValue]   
// [;DOMAIN=domainName]   
// [;PATH=pathName]   
// [;SECURE]
//
// This function sets a client-side cookie as above.  Only first 2 parameters are required
// Rest of the parameters are optional. If no szExpires value is set, cookie is a session cookie.
//
// Prototype : setCookie(szName, szValue [,szExpires] [,szPath] [,szDomain] [,bSecure])
//******************************************************************************************
function setCookie(szName, szValue, szExpires, szPath, szDomain, bSecure) {
    var szCookieText = escape(szName) + '=' + escape(szValue);
    szCookieText += (szExpires ? '; EXPIRES=' + szExpires.toGMTString() : '');
    szCookieText += (szPath ? '; PATH=' + szPath : '');
    szCookieText += (szDomain ? '; DOMAIN=' + szDomain : '');
    szCookieText += (bSecure ? '; SECURE' : '');

    document.cookie = szCookieText;
}

//******************************************************************************************
// This functions reads & returns the cookie value of the specified cookie (by cookie name) 
//
// Prototype : getCookie(szName)
//******************************************************************************************

function getCookie(szName) {
    var szValue = null;
    if (document.cookie)	   //only if exists
    {
        var arr = document.cookie.split((escape(szName) + '='));
        if (2 <= arr.length) {
            var arr2 = arr[1].split(';');
            szValue = unescape(arr2[0]);
        }
    }
    return szValue;
}

//******************************************************************************************
// To delete a cookie, pass name of the cookie to be deleted
//
// Prototype : deleteCookie(szName)
//******************************************************************************************

function deleteCookie(szName) {
    var tmp = getCookie(szName);
    if (tmp)
    { setCookie(szName, tmp, (new Date(1))); }
}


