// JScript File
    var itemList;
    var GROUP_DELIMITER = "&";
    var SUB_DELIMITER = "=";
    
    
//block for adding items to order in general pages by creating a separate layer containing the textboxes enabling customers to enter the quanties

    var timer;  //used with variables "interval" and "step" to control the movement of the cart container containing the textbox used to enter the quantities of items
    var targetLeft;  //targetLeft and y decides the location to which the container will move
    var targetTop;
    var pCode;  //pCode = productCode;
    var interval = 10; //
    var step;   //how far the cart container go in a certain interval
    var containerWidth = 0; // the width and the height of the cart container, used with targetLeft and targetTop to determine the exact position to where the cart container will go
    var containerHeight = 0;
    var searchBy = "psid";

    function selectSearchCriteria()
    {
        if (document.getElementById("rdCriteriaByPSID").checked)
        {
            searchBy = "psid";
        }
        
        if (document.getElementById("rdCriteriaBySKU").checked)
        {
            searchBy = "sku";
        }
    }

    function retrievePriceBreaks(psid)
    {
        if (isPriceBreaksRetrieved(psid))
        {
            displayPriceBreaks(getPriceBreaksById(psid));
        }
        else
        {
            displayLoader();
            Holdfast3.OnlineOrdering.GetPriceBreaks(psid,displayPriceBreaks, blockItem, "");
        }
    }
    
    
    function blockItem(result)
    {
        var msg = result.get_message();
        if ((msg.indexOf("timed") > 0) && (msg.indexOf("out") > 0))
        {
            if (msg.indexOf("session") > -1)
            {
                displayPriceBreaks("You session has timed out. Please login and try again.");
            }
            else
            {
                displayPriceBreaks("Connection timed out. Service may be unavailable.");
            }
        }
        else
        {
            if (msg.indexOf("cannot") > -1 && msg.indexOf("sold") > -1)
            {
                displayPriceBreaks("");
            }
            else
            {
                displayPriceBreaks("Service temporarily unavailable.<br />Please try again later.")
            }
        }
    }
    
    function isPriceBreaksRetrieved(psid)
    {
        if (!itemList) return false;
        
        for (var i = 0; i < itemList.length; i++)
        {
            if (itemList[i].id == psid)
            {
                return itemList[i].pbRetrieved;
            }
        }
    }
    
    function displayPriceBreaks(result)
    {
        hideLoader();
        document.getElementById("price-result").style.display = "inline";
        var content = "";
        
        savePriceBreaks(result);
        
        //no price breaks for the product
        if (result.length == 0) 
        {
            content = "Product not available online";
            
            if (document.getElementById("quantity")) document.getElementById("quantity").disabled = true;
            
            if (document.getElementById("txtItemQuantity")) document.getElementById("txtItemQuantity").disabled = true;
            if (document.getElementById("btnOOAdd")) document.getElementById("btnOOAdd").disabled = true;
       }
       else
       {
            if (result.indexOf("=") > 0) //price breaks retrieved
            {
                var prices = result.split("&");
                var count = 0;
                
                content +="<table class=\"order-items\" cellpadding=0 cellspacing=0><tr class=\"new-sub-heading\" style=\"display:table-row\"><td style=\"padding:2px 3px; text-align: right;\">Min Qty</td><td style=\"padding:2px 3px; text-align: right;\">Unit Price</td></tr>";
                for (var i = 0; i < prices.length; i++)
                {
                    var bg = "F0F0F0";
                    if (count % 2 == 1) bg = "F4F4F4";
                    
                    content += "<tr style=\"background-color:" + bg + "\">";
                    content += "<td style=\"padding:2px 3px; text-align: right;\">";
                    content += QuantityFormatted(prices[i].split("=")[0]);
                    content += "</td>";
                    content += "<td style=\"padding:2px 3px; text-align: right;\">$";
                    content += CurrencyFormatted(prices[i].split("=")[1]);
                    content += "</td>";
                    content += "</tr>";
                    
                    count++;
                }
                content += "</table>";
                
                if (document.getElementById("quantity"))
                {
                    document.getElementById("quantity").disabled = false;
                    document.getElementById("quantity").focus();
                }
                else
                {
                    if (document.getElementById("txtItemQuantity"))
                    {
                        document.getElementById("btnOOAdd").disabled = false;
                        document.getElementById("txtItemQuantity").disabled = false;
                        document.getElementById("txtItemQuantity").focus();
                    }
                }
            }
            else    //error occurred. Display the message
            {
                content = "<div class=\"reminder\">" + result + "</div>";
            }
        }

        document.getElementById("price-result").innerHTML = content;

    }
    
    function savePriceBreaks(pb)
    {
        if (pb == "!") return;  //"!" indicates a communication problem with server
        
        if (document.getElementById("hdnPriceBreaks"))
        {
            document.getElementById("hdnPriceBreaks").value = pb;
        }
        
        if (!itemList) return; 
        
        var id = document.getElementById("productId").value;
        if (searchBy == "sku")
        {
            id = getIdBySKU(id);
        }
        
        for (var i = 0; i < itemList.length; i++)
        {
            if (itemList[i].id == id)
            {
                itemList[i].priceBreaks = pb;
                itemList[i].pbRetrieved = true;
                return;
            }
        }
    }
    
    function hidePriceBreaks()
    {
        document.getElementById("price-result").style.display = "none";
    }
    
    function displayLoader()
    {
        document.getElementById("ajax-loader-container").style.display = "inline";
        hidePriceBreaks();
    }
    
    function hideLoader()
    {
        document.getElementById("ajax-loader-container").style.display = "none";
    }
    
    function getUnitPrice(priceBreakData, quantity)
    {
    
        var pb = priceBreakData.trim();

        var prices = pb.split("&");
        
        if (prices.length == 1) 
        {
            return prices[0].split("=")[1];
        }
        else
        {
            for (var i = 0; i < prices.length; i++)
            {
                if (i == prices.length -1)
                {
                    return prices[i].split("=")[1];
                }
                
                var first = Number(prices[i].split("=")[0]);
                var next = Number(prices[i + 1].split("=")[0]);
               
                if (first <= quantity && next > quantity)
                {
                    return prices[i].split("=")[1];
                }
            }
        }
    }

    //makes the container visible and sets the speed at which the cart move in
    function _showCartContainer(evnt, pid)
    {
        if (timer) clearInterval(timer);
        
        //creates the container if it is not created
        if (!document.getElementById("oo-single-order-container")) _createShoppingCart();
        
        if (containerWidth == 0) 
        {
            containerWidth = document.getElementById("oo-single-order-container").offsetWidth;
        }
        if (containerHeight == 0) 
        {
            containerHeight = document.getElementById("oo-single-order-container").offsetHeight;
        }
        
        
        step = 3;   //initial speed
        _setPosition(evnt); //set the point of destination
        document.getElementById("txtItemCode").value = pid; //assign the product code to the text box
        document.getElementById("txtItemQuantity").value = getItemQuantity(document.getElementById("txtItemCode").value); //gets the quantity of the item(if the custoemr has ordered this item)

        var cart = document.getElementById("oo-single-order-container");
        cart.style.visibility = "visible";
        cart.style.top = targetTop + "px"; //vertically align the container to the mouse
        cart.style.left = targetLeft + "px";
        
        document.getElementById("btnOOAdd").disabled = true;
        
        retrievePriceBreaks(pid);
        
        return;
        timer = setInterval("_moveCart()", interval)
    }

    //moves the container to a position where the click event happened
    function _moveCart()
    {
        var cart = document.getElementById("oo-single-order-container");
        
        if (step > 0)
        {
            if (cart.offsetLeft < targetLeft + 5) //move the container to a position farer than it should to create a reversing effect
            {
                cart.style.left = (cart.offsetLeft + step) + "px";
                step = step + 1;
            }
            else    //prepare to reverse the container
            {
                step = -1;
            }
        }
        else
        {
            if (cart.offsetLeft > targetLeft) //reverse the container
            {
                cart.style.left = (cart.offsetLeft + step) + "px";
            }
            else //stop the container
            {
                //document.getElementById("txtItemQuantity").focus();
                clearInterval(timer);
            }
        }
    }

    //sets the speed at which the interface move to the right side of the screen 
    function _hideCartContainer()
    {
        if (timer) clearInterval(timer);
        
        step = 3;
        timer = setInterval("_hideCart()", interval);
    }

    //moves the interface to the right side of the screen and makes it invisible
    function _hideCart()
    {
        var cart = document.getElementById("oo-single-order-container");
        
        if ((cart.offsetLeft + cart.offsetWidth) < (document.body.offsetWidth - 50))
        {
            cart.style.left = (cart.offsetLeft + step) + "px";
            step = step + 1; //accelerate the movement of the container
        }
        else
        {
            cart.style.visibility = "hidden"; //hide the container
            clearInterval(timer);
        }
    }

    //sets the position to which the container will move
    function _setPosition(evnt)
    {
        var evnt = evnt || window.event;
        if (evnt.pageY)
        {
            targetTop = evnt.pageY;
            targetLeft = evnt.pageX;
        }
        else
        { 
            if (evnt.clientY)
            {
                targetTop = evnt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
                targetLeft = evnt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
            }
            else 
            {
                return null;
            }
        }
        targetLeft = targetLeft - containerWidth/2;
        targetTop = targetTop - containerHeight/2;

    }

    //makes the interface invisible
    function _fastHide()
    {
        document.getElementById("oo-single-order-container").style.visibility = "hidden";
    }
    
    //adds the item with the quantity customer has entered through the interface
    function _add()
    {
        var code = document.getElementById("txtItemCode").value;
        

        //checks if customers have entered a proper number
        var quantity = document.getElementById("txtItemQuantity");
        if (!isNumber(quantity.value))
        {
            alert("Please enter a proper number for the product you selected.");
            quantity.focus();
            quantity.select();
            return false;
        }
        if (parseInt(quantity.value, 10) == "0")
        {
            alert("The minimum quantity for an item is 1");
            quantity.focus();
            quantity.select();
           return false;
        }
        
        var price = getUnitPrice(document.getElementById("hdnPriceBreaks").value, quantity)
        
        _fastHide();
        addItemToCart(code, quantity.value, price, "");        
    }
    
    
    //creates a dynamic interface enabling customer to order an item
    function _createShoppingCart()
    {
        if (document.getElementById("oo-single-order-container")) return;

        if (document.getElementById("txtItemQuantity")) return;

        var content = "";
        content += '<div id="oo-single-order-container">';
        content += '<table cellpadding="0" cellspacing="0" border="0">';
        content += '<tr>';
        content += "<th colspan=\"3\" onmousedown=\"dragStart(event,'oo-single-order-container');\">";
        content += 'Add Product To Order';
        content += '</th>';
        content += '</tr>';
        content += '<tr style="background-color:#E0E0E0;font-weight:bold;">';
        content += '<td style="text-align:left; width: 80px;">';
        content += 'Item Code';
        content += '</td>';
        content += '<td style="text-align:left;">';
        content += 'Quantity';
        content += '</td><td>Price Breaks</td>';

        content += '</tr>';
        content += '<tr>';
        content += '<td style="text-align:left; width: 80px;">';
        content += '<input id="txtItemCode" type="text" style="width: 70px;" disabled />';
        content += '</td>';
        content += '<td style="text-align:left;">';
        content += "<input id=\"txtItemQuantity\" type=\"text\" disabled=\"disabled\" maxlength=\"9\" style=\"width: 40px;\" onkeypress=\"handleCr(event,'btnOOAdd');\" />";
        content += '</td>';
        content += '<td rowspan=2 style="vertical-align:top;width:130px;padding:0 3px;">';
        content += '<div id="price-break-container">';
        content += '<div id="ajax-loader-container" style="display:none;" class="ajax-loader">';
        content += 'Enquiring price..';
        content += '</div>';
        content += '<div id="price-result">';
        content += '</div>';
        content += '</div></td>';

        content += '</tr>';
        content += '<tr>';
        content += '<td style="text-align:left; width: 80px;">';
        content += '<input id="btnOOCancel" type="button" value="Cancel" onclick="_fastHide();" style="width: 55px;" />&nbsp;&nbsp;&nbsp;';
        content += '</td>';
        content += '<td style="text-align:left;padding:5px 3px;">';
        content += '<input id="btnOOAdd" type="button" value="Add" onclick="_add();" style="width: 45px;" />';
        content += '<input id="hdnPriceBreaks" type="hidden" value=""/>';
        content += '</td>';
        content += '</tr>';
        content += '</table>';
        content += '<br />';
        content += '</div>';
        document.write(content);
    }
//end of block for adding items to order in general pages by creating a separate layer containing the textboxes enabling customers to enter the quanties	
//********************************************************************************//    

//block for OrderSummary.aspx page
    var goingNext = false;
    
    function fail(error)
    {
        alert("Failed to get product information. Services are temporarily unavailable");
    }
    
    //this is the function initialize the page
    function storeProductInfo(products)
    {
        itemList = new Array();
        
        var allList = products.split("\t");
        //var t = "";

        for (var i = 0; i < allList.length; i++)
        {
            var item = new Object();
            item.id = allList[i].split("|")[0] + ""; 
            item.name = allList[i].split("|")[1] + "";
            item.sku = allList[i].split("|")[2] + "";
            item.priceBreaks = "";
            item.pbRetrieved = false;
            //t += allList[i].split("|")[0] + "-" + allList[i].split("|")[2] + "\t|\t"
            
            if (item.name.indexOf("HOLDFAST") == 0 )
            {
                item.name = item.name.substring(10);
            }
            
            itemList[i] = item;
        }
        
        
        //displays order information and other information related to this order if there is any
        displayOrderItems();
        loadOtherInfo();
        
    }
    
    //checks if it's necessary to hide the search result of products
    document.onclick = function(e)
    {
        var evnt = window.event? window.event : e;
        var element = evnt.srcElement? evnt.srcElement : evnt.target;
        
        //if the event occurs in the textboxes containing search conditions, do not hide the result
        if (element.id == "productId" || element.id == "productName") return;
        
        hideSearchResults();
    }
    
    //add the item selected to customers order
    function addItem()
    {
        //checks if the input is valid
        if (!check()) return;
        
        hideSearchResults();
  

        var id = document.getElementById("productId").value;
        var quantity = document.getElementById("quantity");
        var name = document.getElementById("productName");
        var sku;
        
        if (searchBy == "sku")
        {
            sku = id;
            id = getIdBySKU(id);
        }
        else
        {
            sku = getSKUById(id);
        }
        var pb = getPriceBreaksById(id);
        var price = getUnitPrice(pb, quantity.value);
        
        //checks if the product to be added is in the product list
        if (!isItemInList(id))
        {
            alert("Can NOT add the product to your order because the product code " + document.getElementById("productId").value + " is NOT in current product list.");
            return;
        }

        //checks if the product to be added is in current order
        if (isItemInCart(id))
        {
            //customer is editing the order
            if (document.getElementById("btnAdd").value == "Update")
            {
                
                updateItemInCart(id, quantity.value, price, sku);
                document.getElementById("btnAdd").value = "Add";
                resetInput();
                displayOrderItems();
                return;
            }
            else //customer is adding the item to his order
            {
                if(confirm("The item is already in your order!\r\nDo you want to edit it?"))
                {
                    editItem(id);
                    return;
                }
                else
                {
                    resetInput();
                    return;
                }
            }
        }

        var sku = getSKUById(id);
        addItemToCart(id, quantity.value, price, sku);
        resetInput();
        displayOrderItems();
    }
    
    //remove an item from current order
    function removeItem(id)
    {
        removeItemFromCart(id);
        displayOrderItems();
    }
    
    //remove all items from current order
    function removeAllItems()
    {
        if (confirm("All items in your current order will be removed.\r\nDo you still want to continue?"))
        {
            removeAllItemsFromCart();
            displayOrderItems();
        }
    }
    
    
    function hideRemoveAllButton()
    {
        document.getElementById("btnRemoveAll").style.visibility = "hidden";
    }
    
    function showRemoveAllButton()
    {
        document.getElementById("btnRemoveAll").style.visibility = "visible";
    }

    //edit an item in current order
    function editItem(id)
    {
        selectItem(id); //fill the text boxes with the item's information
        var items = getItemsInCart();
        
        retrievePriceBreaks(id);
                
        for (var i = 0; i < items.length; i++)
        {
            if (items[i].id == id)
            {
                document.getElementById("quantity").value = items[i].quantity;
            }
        }
        
        //change background color to cause attention
        document.getElementById("quantity").style.backgroundColor="yellow";
        document.getElementById("editMessage").style.visibility = "visible";
        document.getElementById("quantity").select();
        
        document.getElementById("btnAdd").value = "Update";
        document.getElementById("rdCriteriaByPSID").checked = true;
        selectSearchCriteria();
    }
    
    //checks the data to be stored in cookie, excluding order data, which is stored in another cookie, accords with requirements
    function checkOtherInfo()
    {
        var ref = document.getElementById("txtCustomerRef");
        var authority = document.getElementById("txtAuthority");
        var note = document.getElementById("txtNote");
        
        if(ref.value.length == 0)
        {
            alert("Please enter the order reference");
            ref.focus();
            ref.select();
            return false;
        }
        
        if (authority.value.length == 0)
        {
            alert("Please enter the order authority");
            authority.focus();
            authority.select();
            return false;
        }

        if (note.value.length > 500) 
        {
            alert("The length of note has exceeded the max length allowed(500 characters)");
            note.focus();
            note.select();
            return false;
        }
        
        
        return true;
    }
    
    
    //store the data, excluding order data in a cookie
    function saveOtherInfo()
    {
        var oldContent = getCookie("otherInfo");
        var content = "";
        
        if (oldContent.indexOf("ordRef=") > -1)
        {   
            content = oldContent;
            content = updateQueryValue(content, "ordRef", escape(document.getElementById("txtCustomerRef").value));
            content = updateQueryValue(content, "ordAut", escape(document.getElementById("txtAuthority").value));
            content = updateQueryValue(content, "ordNote", escape(document.getElementById("txtNote").value));
        }
        else
        {
            content += "ordRef=" + escape(document.getElementById("txtCustomerRef").value);
            content += GROUP_DELIMITER;
            content += "ordAut=" + escape(document.getElementById("txtAuthority").value);
            content += GROUP_DELIMITER;
            content += "ordNote=" + escape(document.getElementById("txtNote").value);
        }
            
        setCookie("otherInfo", content, 120);
        document.getElementById("btnSave").disabled = true;
    }
    
    //enables customers to save the data entered about order reference, order authority and note -- referred as "other data"
    function enableSaveButton()
    {
        if ((document.getElementById("txtCustomerRef").value.length + document.getElementById("txtAuthority").value.length + document.getElementById("txtNote").value.length) > 0)
        {
            document.getElementById("btnSave").disabled = false;
        }
        else
        {
            document.getElementById("btnSave").disabled = true;
        }
    }
    
    //stores data and move to next step of ordering
    function finishOrdering()
    {
        if (goingNext)
        {
            alert("Processing your request. Please wait...");
            return;
        }
        
        //data entered is invalid
        if (!checkOtherInfo())  return;
        
        //customer has not ordered any items
        if(!hasOrder()) 
        {
            alert("You are unable to progress to the next step as you havn't added any items to your order.\r\nNote: if your session has timed out, you will need to restart the order process.");
            document.getElementById("productId").focus();
            return;
        }
                
        saveOtherInfo();
        
        goingNext = true;
        
        window.location = "OrderConfirmation.aspx";
    }
    
    //gets the description of an item by its id
    function getNameById(id)
    {
        if (!itemList) return "";

        for (var i = 0; i < itemList.length; i++)
        {
            if (itemList[i].id == id) return itemList[i].name;
        }
    
        return "N/A";
    }
    
    function getSKUById(id)
    {
        if (!itemList) return "";
        
        for (var i = 0; i < itemList.length; i++)
        {
            if (itemList[i].id == id)
            {
                if (itemList[i].sku.length == 0) return "N/A";
                else return itemList[i].sku;
            } 
        }
    
        return "N/A";
    }
    
    function getIdBySKU(sku)
    {
        if (!itemList) return "";

        if (!sku) return "";
        
        if (sku.length == 0) return "";
        
        for (var i = 0; i < itemList.length; i++)
        {
            if (itemList[i].sku == sku)
            {
                return itemList[i].id;
            } 
        }
    }
    
    function getPriceBreaksById(id)
    {
        if (!itemList) return "";

        for (var i = 0; i < itemList.length; i++)
        {
            if (itemList[i].id == id)
            {   
                if (itemList[i].pbRetrieved) 
                {
                    return itemList[i].priceBreaks;
                }
                else
                {
                    return null;
                }
            } 
        }
    
        return "";
    }
    
    
    function blockCr(evt)
    {
        evt = (evt) ? evt : event;
        var charCode = (evt.charCode) ? evt.charCode :((evt.which) ? evt.which : evt.keyCode);
        if (charCode == 13) {
            return false;
        } else {
            return true;
        }   
    }


    //displays other information if there are any
    function loadOtherInfo()
    {
        var info = getCookie("otherInfo");
        document.getElementById("txtCustomerRef").value = unescape(getQueryValue(info, "ordRef"));
        document.getElementById("txtAuthority").value = unescape(getQueryValue(info, "ordAut"));
        document.getElementById("txtNote").value = unescape(getQueryValue(info, "ordNote"));
    }
   
   //displays order information if there are any
    function displayOrderItems()
    {
        var container = document.getElementById("orderDetail");
        var content = "";
        
        var items = getItemsInCart();
        var total = 0;
        var subTotal = 0;
        
        if (isArray(items))//there are items in current order
        {
            content += "<table cellspacing=0 border=0 cellpadding=0 class=\"order-items\" style=\"margin-top:2px;\"><tr class=new-sub-heading><td>No.</td><td>Code</td><td>SKU</td><td>Product Name</td><td style=\"width: 8%; text-align:right;\">Qty</td><td style=\"width: 4%; text-align:left;\">Units</td><td style=\"width: 8%; text-align:right;\">Unit Price</td><td style=\"width: 8%; text-align:right;\">Total</td><td style=\"text-align:left;width: 65;\">Action</td></tr>";
            for (var i = 0; i < items.length ; i++)
            {
                var id = items[i].id;
                var qnty = items[i].quantity;
                var unitPrice = items[i].unitPrice;
                var sku = items[i].sku;
                if (sku.length == 0)
                {
                    sku = getSKUById(id);
                    updateItemInCart(id, qnty, unitPrice, sku);
                }
                
                subTotal = Math.round(Number(qnty) * Number(unitPrice) * 100) / 100;
                total += subTotal;
                
                var name = getNameById(id);
                if (id.length == 0) continue;
                
                if (i % 2 == 1)
                {
                    content += "<tr class=order-items-normal>";
                }
                else
                {
                    content += "<tr class=order-items-normal2>";
                }
                content += "<td width=20>";
                content += (i + 1);
                content += "</td>";
                content += "<td>";
                content += id;
                content += "</td>";
                content += "<td>";
                content += sku;
                content += "</td>";
                content += "<td>";
                content += "<a href=\"javascript:showItemDetail('" + id +"');\" title=\"click to view the details of this product\">";
                if (name.length < 50) 
                {
                    content += name;
                }
                else
                {
                    content += name.substring(0, 48) + "..";
                }
                content += "</a>";
                content += "</td>";
                content += "<td  style=\"text-align:right;\">";
                content += QuantityFormatted(qnty);
                content += "</td>";
                content += "<td  style=\"text-align:left;\">EACH</td>";
                content += "<td  style=\"text-align: right;\">$";
                content += CurrencyFormatted(unitPrice);
                content += "</td>";
                content += "<td  style=\"text-align: right;\"><span>$";
                content += CurrencyFormatted(subTotal);
                content += "</span></td>";
                content += "<td>";
                content += "<a href=\"javascript:removeItem('" + id +"');\" title=\"remove this item from your order\">Remove</a>";
                content += "&nbsp;&nbsp;&nbsp;&nbsp;";
                content += "<a href=\"javascript:editItem('" + id +"');\" title=\"Edit the quantity of this item\">Edit</a>";
                content += "</td>";
                content += "</tr>";

        } 
        content += "</table>";   
        
        content += "<div style=\"padding:20px 0;font-size:11px;clear:both;display:block;\"><b>Please note:</b> Free freight for orders placed with a minimum purchase of $150 NZD</div>";

        
        if (total > 0)
        {
            var gst = Math.round(total * 12.5)/100;
            
            content += "<div style=\"float:right;text-align:right;font-size:11px;padding-right:5px;\">";
            content += "$" + CurrencyFormatted(Math.round(total * 100)/100) + "<br />";
            content += "$" + CurrencyFormatted(gst) + "<br />";
            content += "$" + CurrencyFormatted(Math.round((total + gst)*100)/100) + "<br />";
            content += "</div>";
            
            content += "<div style=\"float:right;text-align:right;padding-right:10px;font-size:11px;\">";
            content += "Order Subtotal (Excl GST)<br />";
            content += "GST&nbsp;<br />";
            content += "Order Total Balance<br />";
            content += "</div>";
            
           
        }
        
        showRemoveAllButton();
     }
     else //no items in current order
     {
        content = '<span class="new-sub-heading" style="margin-top:2px;display:block;">&nbsp;No item ordered</span>';
        hideRemoveAllButton();
     }
        
        container.innerHTML = content;
    }
    
    
    //checks if the data entered are valid order data (product id and qnantity)
    function check()
    {
        var id = document.getElementById("productId");
        var quantity = document.getElementById("quantity");
        
        if (quantity.value.length == 0)
        {
            alert("Please enter the quantity for the product you selected. (Product Code:" + id.value + ")");
            quantity.focus();
            return false;
        }
        if (!isNumber(quantity.value))
        {
            alert("Please enter a proper number for the product you selected. (Product Code:" + id.value + ")");
            quantity.focus();
            return false;
        }
        if (parseInt(quantity.value, 10) == "0")
        {
            alert("The minimum quantity for an item is 1");
            quantity.focus();
            return false;
        }
        
        
        if (id.value.length == 0)
        {
            alert("Please enter a product code");
            id.focus();
            return false;
        }
        
        if (id.value.length < 5)
        {
            alert("Please enter a proper product code");
            id.focus();
            id.select();
            return false;
        }
        
        return true;
    }
    
    //highlights a row
    function highlight(row)
    {
        row.className = "order-items-highlight";
    }
    
    //changes a row back to normal
    function involute(row)
    {
        if (row.sectionRowIndex % 2 == 1)
            row.className = "order-items-normal2";
        else
            row.className = "order-items-normal";
    }
    
    function showItemDetail(id)
    {
        openNewWindow('_ProductDetail.aspx?psid=' + id ,'Item_Details','width=500,height=450,status=no,left=20,top=30,scrollbars=yes,resizable=yes,toolbar=no');	    
    }
   
    //lists the products accord with the conditions entered by custoemrs
    function displaySearchResults()
    {
        if (itemList == null) return;
        
        var idPart = document.getElementById("productId").value.toUpperCase();
        var namePart = document.getElementById("productName").value.toLowerCase();
        
        //if customers do not enter anything, display nothing
        if ((idPart.length + namePart.length) == 0) 
        {
            hideSearchResults();
            return;
        }
        
        var dropdownContent = document.getElementById("dropdownContent");
        var counter = 0;
        var itemCounter = 0;
        var content = "";
        
        var pos = getObjectPos('productId');
        dropdownContent.innerHTML = "";
        dropdownContent.style.left = pos.left + "px";
        dropdownContent.style.top = (pos.top + 22) + "px";
        
        dropdownContent.style.display = "block";

        //find out all products accords with the conditions entered
        if (searchBy == "psid")
        {
            for (var i = 0; i < itemList.length; i++)
            {
                if (itemList[i].id.indexOf(idPart) == 0 && itemList[i].name.toLowerCase().indexOf(namePart) > -1)
                {
                    content += "<a href=\"javascript:selectItem('" + itemList[i].id +"')\" id=\"a" + itemList[i].id + "\" title=\"" + itemList[i].id + " - " + itemList[i].name + "\">&nbsp;" + itemList[i].id + " - " + itemList[i].name  + " - " + itemList[i].sku + "</a>";
                    itemCounter++;
                }
            }
        }
        else
        {
            for (var i = 0; i < itemList.length; i++)
            {
                if (itemList[i].sku.indexOf(idPart) == 0 && itemList[i].name.toLowerCase().indexOf(namePart) > -1)
                {
                    content += "<a href=\"javascript:selectItem('" + itemList[i].id +"')\" id=\"a" + itemList[i].id + "\" title=\"" + itemList[i].sku + " - " + itemList[i].name + "\">&nbsp;" + itemList[i].sku + " - " + itemList[i].name  + " - " + itemList[i].id + "</a>";
                    itemCounter++;
                }
            }
        }
        
        dropdownContent.innerHTML = content;
        
    }


    function resetInput()
    {
        enableSearch();
        
        document.getElementById("productId").value = "";
        document.getElementById("productName").value = "";
        document.getElementById("quantity").value = "";
        document.getElementById("quantity").style.backgroundColor = "";
        document.getElementById("quantity").disabled = true;
        document.getElementById("btnAdd").value = "Add";
        document.getElementById("editMessage").style.visibility = "hidden";
        document.getElementById("productId").focus();
        
        displayPriceBreaks("&nbsp;");
        
    }
    
    
    function disableSearch()
    {
        document.getElementById("productId").disabled = true;
        document.getElementById("productName").disabled = true;
    }
    
    function enableSearch()
    {
        document.getElementById("productId").disabled = false;
        document.getElementById("productName").disabled = false;
    }
    
    //selects an item from the list
    function selectItem(id)
    {
    
        retrievePriceBreaks(id);
        
        if (searchBy == "psid")
        { 
            document.getElementById("productId").value = id;
        }
        else
        {
            document.getElementById("productId").value = getSKUById(id);
        }
        
        for (var i = 0; i < itemList.length; i++)
        {
            if (itemList[i].id == id)
            {
                document.getElementById("productName").value = itemList[i].name;
                document.getElementById("productName").title = itemList[i].name;
                break;
            }
        }
        
        hideSearchResults();
        disableSearch();
        
        
        //document.getElementById("quantity").focus();
    }
    
    
    function hideSearchResults()
    {
        if (document.getElementById("dropdownContent"))
        {
            document.getElementById("dropdownContent").style.display = "none";
        }
    }    
    
    //checks if the item is in the product list
    function isItemInList(id)
    {
        for (var i = 0; i < itemList.length; i++)
        {
            if (itemList[i].id == id) return true;
        }
        
        return false;
    }
//end of block for orderSummary.aspx
    
//block for providing functions to ease ordering

    //checks if an item is in current order
    function isItemInCart(pId)
    {
        var items = getItemsInCart();
        for (var i = 0; i < items.length; i++)
        {
            if (items[i].id == pId)
            {
                return true;
            }
        }
        
        return false;
    }
    
    //gets the quantity of an item in current order
    function getItemQuantity(pId)
    {
        var items = getItemsInCart();
        for (var i = 0; i < items.length; i++)
        {
            if (items[i].id == pId)
            {
               return items[i].quantity;
            }
        }
        
        return "";
    }
    
    //checks if customers cookies have enough information to proceed ordering
    function hasNecessaryInfo()
    {
        return (hasOrder() && hasOtherInfo());   
    }
    
    function hasOtherInfo()
    {
        var otherInfo = getCookie("otherInfo");
        
        return (otherInfo.length > 26);
    }
    
    function hasOrder()
    {
        if (getItemsInCart() == "") return false;
        
        return true;
    }
    
    
    //gets all items in current order
    function getItemsInCart()
    {
        var order = getCookie("orderInfo");

        if (order == "") return "";
        
        if (order.length == 0) return "";

        if (order == "undefined") return "";
                
        var orderDetail = order.split(GROUP_DELIMITER);
        
        
        var temp = new Array();
        var itemCount = 0;
        for(var i = 0; i < orderDetail.length; i++)
        {
            var item = new Object();
            var str = orderDetail[i];
            
            item.id = str.split(SUB_DELIMITER)[0];
            item.quantity = str.split(SUB_DELIMITER)[1].split("|")[0];
            item.unitPrice = str.split(SUB_DELIMITER)[1].split("|")[1];
            item.sku = str.split(SUB_DELIMITER)[1].split("|")[2];
            
            temp[itemCount] = item;
            //temp[itemCount] = orderDetail[i];
            itemCount++;
        }
        
        return temp;
    }
    
    //adds an item to current order
    function addItemToCart(pId, qnty, unitPrice, sku)
    {
        if (!isCookieEnabled()) 
        {
            var msg = "Our system detects that cookies are not enabled in your browser. \r\nYou cann't user our online ordering system with cookies disabled.";
            msg += "\r\n\r\nPlease enable cookies before using our online ordering system";
            
            alert(msg);
            return false;
        }
        
        if (pId.length < 5) 
        {
            alert("Please enter a proper product code");
            return; //product code is not valid
        }
        if (qnty.length == 0)
        {
            alert("Please enter the quantity");
            return; // quantity is not valid
        }
        if (!isNumber(qnty))
        {
            alert("Please enter a proper number for the product you selected.");
            return false;
        }
        if (parseInt(qnty, 10) == 0)
        {
            alert("The minimum quantity for an item is 1");
           return false;
        }
        if (qnty.length > 9) 
        {
            alert("The quantity entered " + qnty + " has exceeded the max number allowed(1000000000)");
            return false;
        }
        
        //item already in current order
        if (isItemInCart(pId)) 
        {
            removeItemFromCart(pId);
        }

        var orderDetail = getCookie("orderInfo");
        
        //var pb = getPriceBreaksById(pId);
        //var price = getUnitPrice(pb, qnty);
        
        //there are items already added
        if (orderDetail.length > 5 && orderDetail.indexOf(SUB_DELIMITER) > 3) 
        {
            orderDetail = orderDetail + GROUP_DELIMITER + pId + SUB_DELIMITER + qnty + "|" + unitPrice + "|" + sku;
        }
        else    //first item added
        {
            orderDetail = pId + SUB_DELIMITER + qnty + "|" + unitPrice + "|" + sku;
        }
        
        saveOrder(orderDetail);
        
        return true;
    }
    
    //removes an item from current order
    function removeItemFromCart(pId)
    {
        var items = getItemsInCart();
        var newOrderInfo = "";
        for (var i = 0; i < items.length; i++)
        {
            if (items[i].id != pId && items[i].id.length > 1)
            {
                newOrderInfo += items[i].id + SUB_DELIMITER + items[i].quantity + "|" + items[i].unitPrice + "|" + items[i].sku + GROUP_DELIMITER;
            }
        }
        
        saveOrder(newOrderInfo.substring(0,newOrderInfo.length - 1));
    }
    
    //changes the quantity of an item added
    function updateItemInCart(pId, qnty, unitPrice, sku)
    {
        var orderDetail = getCookie("orderInfo");
        var newItem = qnty + "|" + unitPrice + "|" + sku;
        
        orderDetail = updateQueryValue(orderDetail, pId, newItem);
        
        saveOrder(orderDetail);
        
        displayOrderItems();
        
        
        //removeItemFromCart(pId);
        //addItemToCart(pId, qnty, unitPrice, sku);
    }
    
    
    //removes all items from current order
    function removeAllItemsFromCart()
    {
        saveOrder("");
    }
    
    //saves order information
    function saveOrder(orderInfo)
    {
        setCookie("orderInfo", orderInfo, 120);
    }
    
    //clear all cookies related to online ordering
    function clearOrderInfo()
    {
        var exp = new Date((new Date()).getTime() - 60 * 60 * 1000);
        setCookie("orderInfo", "", -60);
        setCookie("otherInfo", "", -60);
   }
  
   function CurrencyFormatted(amount)
    {
	    var i = Number(amount).toFixed(2);
	    return CommaFormatted(i);
    }
   function QuantityFormatted(amount)
    {
      var i = Number(amount).toFixed(0);
	    return CommaFormatted(i);
    }
    function CommaFormatted(amount)
    {
	    var delimiter = ","; // replace comma if desired
	    var a = amount.split('.',2)
	    var d = a[1];
	    var i = parseInt(a[0]);
	    if(isNaN(i)) { return ''; }
	    var minus = '';
	    if(i < 0) { minus = '-'; }
	    i = Math.abs(i);
	    var n = new String(i);
	    var a = [];
	    while(n.length > 3)
	    {
		    var nn = n.substr(n.length-3);
		    a.unshift(nn);
		    n = n.substr(0,n.length-3);
	    }
	    if(n.length > 0) { a.unshift(n); }
	    n = a.join(delimiter);
	    if(! d || d.length < 1) { amount = n; }
	    else { amount = n + '.' + d; }
	    amount = minus + amount;
	    return amount;
    }
    // end of function CommaFormatted()

    

