﻿var weightedIndex = -1;
var alertTimerId = 0;
var initDuration = 0;
var finalDuration = 500;
var imgloc = "images/promos/banners/";

window.addEvent('domready', function() {
    new SlideList($('fancymenu').getElement('ul'));
});

var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if (sPage == "Main.aspx" || sPage == "") {
    var MainPromo = {
        currentPromoElement: null,
        currentNavElement: null,
        count: 0,
        autoPlay: true,
        settings: {
            parent: 'promo-navigator-wrapper',
            navIDFormat: 'promoNav',
            promoNavs: 'promo-navs',
            promoBoxes: 'promo-navs-boxes',
            promoClass: '.primary-promo',
            navClass: 'promo-nav',
            selectedClass: 'selected',
            hoverClass: 'hover',
            navWidth: 51,
            effect: { transition: 'bounce:out' }
        },
        initialize: function() {
            this.currentPromoElement = $$(this.settings.promoClass)[0];
            this.count = $$(this.settings.promoClass).length;

            //var weightedIndex = -1;
            $$(this.settings.promoClass).each(function(el, index) {
                if ($chk(el.get('weight'))) {
                    weightedIndex = index;
                }
            });
            if (weightedIndex == -1) {
                weightedIndex = $random(0, this.count - 1);
                //			weightedIndex = 0;
            }

            var spacer = new Element('div', { 'class': 'promo-nav-spacer' });
            for (var loop = 0; loop < this.count; loop++) {
                var div = new Element('div', {
                    'class': this.settings.navClass,
                    'id': this.settings.navIDFormat + loop,
                    'events': {
                        'mouseover': function() {
                            if (this.hasClass(MainPromo.settings.selectedClass)) {
                                return;
                            }
                            this.addClass(MainPromo.settings.hoverClass);
                            var bkg = 'images/promos/' + this.id + '.gif';
                            this.style.backgroundImage = "url('" + bkg + "')";
                            //alert(this.style.backgroundImage);
                            this.style.backgroundRepeat = "no-repeat";
                        },
                        'mouseout': function() {
                            if (this.hasClass(MainPromo.settings.selectedClass)) {
                                return;
                            }
                            this.removeClass(MainPromo.settings.hoverClass);
                            this.style.backgroundImage = "";
                        },
                        'click': function(force) {
                            if (alertTimerId > 0) {
                                clearTimeout(alertTimerId);
                            }
                            weightedIndex = parseInt(this.id.substring(8, 9));
                            alertTimerId = setTimeout('MovePromo()', 5000);
                            if (this.hasClass(MainPromo.settings.selectedClass)) {
                                return;
                            }
                            (function() { MainPromo.currentNavElement.removeClass(MainPromo.settings.selectedClass); }).delay(0);
                            MainPromo.change($$(MainPromo.settings.promoClass)[parseInt(this.id.substring(8, 9))]);
                            MainPromo.currentNavElement.style.backgroundImage = "";
                            MainPromo.currentNavElement = this;
                            MainPromo.currentNavElement.removeClass(MainPromo.settings.hoverClass);
                            MainPromo.currentNavElement.addClass(MainPromo.settings.selectedClass);
                            var bkg = 'images/promos/' + this.id + '.gif';
                            this.style.backgroundImage = "url('" + bkg + "')";
                            this.style.backgroundRepeat = "no-repeat";
                            (function() {
                            }).delay(force ? 0 : initDuration);
                            if (initDuration == 0) {
                                initDuration = finalDuration;
                            }
                        }
                    }
                });
                if (loop != 0) {
                    $(this.settings.promoBoxes).adopt(new Element('div', { 'class': 'promo-nav-spacer' }));
                }
                $(this.settings.promoBoxes).adopt(div);
            }
            this.currentNavElement = $(this.settings.navIDFormat + 0);
            $(this.settings.promoNavs).setStyle('width', this.settings.navWidth * this.count + (this.count - 1));
            $(this.settings.parent).setStyles({
                'left': (537 - (this.settings.navWidth * this.count + 18 + (this.count - 1))) / 2
            });
            this.buffer.init();
            this.showNavigator();

            if (weightedIndex > -1) {
                $$('.promo-nav')[weightedIndex].fireEvent('click', true);
            }
        },
        buffer: {
            bufferID: 'primary-promo-buffer',
            bufferObj: null,
            init: function() {
                this.bufferObj = $(this.bufferID);
                this.bufferObj.set('morph', MainPromo.settings.effect);
                this.bufferObj.setStyles({
                    'opacity': '0',
                    'visibility': 'visible'
                });
            },
            hide: function() {
                this.bufferObj.fade('out');
            },
            show: function() {
                this.bufferObj.fade('in');
            }
        },
        showNavigator: function(force) {
            $(this.settings.parent).tween('top', 246, 216);
        },
        change: function(element, force) {
            MainPromo.buffer.show();
            (function() {
                MainPromo.currentPromoElement.removeClass(MainPromo.settings.selectedClass);
                MainPromo.currentPromoElement = element;
                MainPromo.currentPromoElement.addClass(MainPromo.settings.selectedClass);
                MainPromo.loadImage();
                if (element.hasClass('promo2')) MainPromo.animate(element);
                MainPromo.buffer.hide();
            }).delay(force ? 0 : initDuration);
        },
        animate: function(element) {
            var t = new PromoTemplate2(element);
            t.animate();
            return;
        },
        loadImage: function() {
            var img = this.currentPromoElement.getElement('div.promo-background img');
            var id = img.get('id');
            if (id != '_') {
                img.set('src', imgloc + id + ".jpg");
                img.set('id', '_');
            }
        }

    };

    PromoTemplate2 = new Class({
        Implements: [Chain],
        effects: [],
        duration: initDuration,
        initialize: function(el) {
            el.getElement('.promo-content-wrapper').setStyle('height', '0px');
            this.chain(
			function() {
			    var rule1 = el.getElement('.top-rule');
			    rule1.set('tween', { duration: 'long', onComplete: (function() { this.callChain(); }).bind(this) });
			    rule1.set('opacity', 0.35);

			    var rule2 = el.getElement('.bottom-rule');
			    rule2.set('tween', { duration: 'long' });
			    rule2.set('opacity', 0.35);

			    rule1.tween('top', 0, 246 / 2);
			    rule2.tween('top', 246, 246 / 2);
			},
			function() {
			    el.getElement('.promo-content-wrapper').setStyles({
			        'visibility': 'visible'
			    });
			    this.callChain();
			},
			function() {
			    var rule1 = el.getElement('.top-rule');
			    rule1.set('tween', { duration: this.duration, onComplete: (function() { this.callChain(); }).bind(this) });

			    var rule2 = el.getElement('.bottom-rule');
			    rule2.set('tween', { duration: this.duration });

			    var rule3 = el.getElement('.promo-content-wrapper');
			    rule3.set('morph', { duration: this.duration });

			    var rule4 = el.getElement('.promo-text');
			    rule4.set('morph', { duration: this.duration });

			    var rule5 = el.getElement('.black-background-bar');
			    rule5.set('morph', { duration: this.duration });

			    rule1.tween('top', 90);
			    rule2.tween('top', 150);
			    var effects = {
			        'height': [0, 59]
					, 'top': [246 / 2, 91]
			    };
			    rule3.morph(effects);
			},
			function() { }
		);
        },
        animate: function() {
            this.callChain();
        }
    });

    window.addEvent('domready', function() {
        MainPromo.initialize();
        //setTimeout('MovePromo()', 3000);
    });
}

function MovePromo() {
    var index = weightedIndex + 1;
    if (index > 4) {
        index = 0;
    }
    weightedIndex = index;
    $$('.promo-nav')[index].fireEvent('click', true);
};

function MoveEnterNext(NextID) {
    if (event.which || event.keyCode) {
        if ((event.which == 13) || (event.keyCode == 13)) {
            document.getElementById(NextID).focus();
            return false;
        }
    }
    else {
        return true;
    }
};

function OpenProductDetail(stockno) {
    window.location = 'ProductDetails.aspx?stockno=' + stockno;
};

function pbyc(cid, scname) {
    window.location = "ProductByC.aspx?CID=" + cid + "&amp;Name=" + scname;
};

function sbc(cid, scname) {
    window.location = "CategoryByS.aspx?CID=" + cid + "&amp;Name=" + scname;
};

function setfocus(a_field_id) {
    $(a_field_id).focus()
};

function IsOnlyNumbers(strString)
//  check for valid only numbers strings	(example phone number)
{
    var strValidChars = "0123456789";
    var strChar;
    var blnResult = true;
    var sNumber = Trim(strString);
    if (sNumber.length == 0) return false;

    //  test strString consists of valid characters listed above
    for (i = 0; i < sNumber.length && blnResult == true; i++) {
        strChar = sNumber.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
};

function IsNumeric(strString)
//  check for valid numeric strings	
{
    var strValidChars = "0123456789.-";
    var strChar;
    var blnResult = true;

    if (strString.length == 0) return false;

    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
};

function Trim(strString) {
    var sTrim = strString.replace(/^\s+/, '');
    sTrim = sTrim.replace(/\s+$/, '');
    return sTrim;
};

function IsEmptyString(strString) {
    var blnResult = false;
    //    var sTrim=strString.replace(/^\s+/, '');
    //    sTrim=sTrim.replace(/\s+$/, '');
    sTrim = Trim(strString);
    if (sTrim == '') {
        blnResult = true;
    }
    return blnResult;
}

function IsMatching(strString1, strString2, isCaseSensitive) {
    var blnResult = true;
    if (isCaseSensitive) {
        if (strString1 != strString2) {
            blnResult = false;
        }
    }
    else {
        if (strString1.toUpperCase() != strString2.toUpperCase()) {
            blnResult = false;
        }
    }
    return blnResult;
};

function IsEmailFormat(strString) {
    var blnResult = true;

    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    if (strString.search(emailRegEx) == -1) {
        blnResult = false;
    }
    return blnResult;
};

function ValidateEmail(Email, message) {
    var EML = document.getElementById(Email);
    if (EML != null) {
        if (!IsEmailFormat(EML.value)) {
            alert(message);
            return false;
        }
    }
    else {
        alert(message);
        return false;
    }
    return true;
};

function IsEmailFormatMatching(strString1, strString2) {
    var blnResult = true;

    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    if (strString1.search(emailRegEx) == -1) {
        blnResult = false;
    }
    else if (strString1.toUpperCase().value != strString2.toUpperCase().value) {
        blnResult = false;
    }

    return blnResult;
};

function RangeValidator(nStart, nEnd, nCompare) {
    var blnResult = true;
    if (!IsOnlyNumbers(nStart) || !IsOnlyNumbers(nEnd) || !IsOnlyNumbers(nCompare)) {
        blnResult = false;
    }
    else {
        if (nCompare < nStart || nCompare > nEnd) {
            blnResult = false;
        }
    }
    return blnResult;
};

function MinLen(Min, Actual) {
    if (Actual < Min) {
        return false;
    }
    else {
        return true;
    }
}
//verify if date format is mm/dd/yyyy or mm-dd-yyyy
function IsDateFormat(strDate) {

    if (strDate == '')
        return true;
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = strDate.match(datePat);

    if (matchArray == null)
        return false;

    var month = matchArray[1];
    var day = matchArray[3];
    var year = matchArray[5];

    if (month < 1 || month > 12) {
        return false;
    }

    if (day < 1 || day > 31) {
        return false;
    }

    if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
        return false;
    }

    if (month == 2) {
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day == 29 && !isleap)) {
            return false;
        }
    }
    return true;
};

//function for save, get and delete cookies
//*****************************************************************************
function GetCookie(name) {
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1) return null;
    var end = document.cookie.indexOf(";", len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
};

//expires is in days
function CreateCookie(name, value, expires, path, domain, secure) {
    if (navigator.cookieEnabled == 1) {
        var today = new Date();
        today.setTime(today.getTime());
        var locpath = '/';
        if (path != null && path != '') {
            locpath = path;
        }
        if (expires) {
            //calculate the number of days in milliseconds
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date(today.getTime() + (expires));
        document.cookie = name + "=" + escape(value) +
        ((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
        ((locpath) ? ";path=" + locpath : "") +
        ((domain) ? ";domain=" + domain : "") +
        ((secure) ? ";secure=" + secure : "");
    }
};

function DeleteCookie(name, path, domain) {
    if (navigator.cookieEnabled == 1) {
        if (GetCookie(name)) {
            var today = new Date();
            var expires = (-100) * 1000 * 60 * 60 * 24;
            today.setTime(today.getTime());
            var expires_date = new Date(today.getTime() + (expires));
            document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=-1"; //expires_date.toGMTString();
        }
    }
};

function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
((expires) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : "");
};
//*****************************************************************************
//End cookie functions

function SaveCartID(ID) {
    if (ID != null) {
        CreateCookie("CARTID", ID, 30, "", "", "true");
    };

    function DeleteCartID(ID) {
        if (ID != null) {
            DeleteCookie("CARTID", "", "");
        }
    };
};

function OnChange(dropdown) {
    var myindex = dropdown.selectedIndex;
    var SelValue = dropdown.options[myindex].value;
    var sPath = window.location.pathname;
    //var sPage = sPath.substring(sPath.lastIndexOf('\\') + 1);
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);

    var baseURL = sPage + "?CULT=" + SelValue;
    top.location.href = baseURL;

    return true;
};

function ResizeBodyHeight() {
    var tdContent = document.getElementById("tdContent");
    var tdBody = document.getElementById("tdBody");
    if (tdContent != null && tdBody != null) {
        tdContent.style.height = (tdBody.style.posHeight - 32) + "px";
    }
};

function toggleGroup(host, numberOfRows, index) {
    //  get a reference to the table

    var table = $get('orders');
    var tag = host.style.height;
    var div = document.getElementById("divFiller");

    //  do some simple math to determine how many
    //  rows we need to hide/show
    var startIndex = index + 1;
    var stopIndex = startIndex + parseInt(numberOfRows);

    //  rows.  go ahead and remove the hidden class from the rows
    //  and update the host tag

    if (tag == '18px') {
        for (var i = startIndex; i < stopIndex; i++) {
            Sys.UI.DomElement.removeCssClass(table.rows[i], 'hidden');
        }
        if (div != null) {
            var nHeight = div.style.posHeight - (stopIndex - 1) * 19;
            if (nHeight <= 0) {
                nHeight = 100;
            }
            div.style.height = nHeight + "px";
        }
        tag = "19px";
    }
    else {
        for (var i = startIndex; i < stopIndex; i++) {
            Sys.UI.DomElement.addCssClass(table.rows[i], 'hidden');
        }

        if (div != null) {
            var nHeight = div.style.posHeight + (stopIndex - 1) * 18;
            if (nHeight <= 0) {
                nHeight = 100;
            }
            div.style.height = nHeight + "px";
        }
        tag = "18px";
    }

    //  update the tag height the new value
    host.style.height = tag;
};

/* fancy-Menu */

var SlideList = new Class({
    Implements: [Options, Events],

    options: {
        transition: Fx.Transitions.Sine.easeInOut,
        duration: 500,
        wait: false,
        onClick: $empty
    },

    initialize: function(menu, options) {
        this.setOptions(options);

        this.menu = $(menu), this.current = this.menu.getElement('li.current');

        $$(this.menu.getElements('li')).addEvents({
            'mouseover': this.moveBg.bind(this),
            'mouseout': this.moveBg.bind(this, false),
            'click': this.clickItem.bind(this)
        });

        this.back = new Element('li', {
            'class': 'background',
            morph: this.options
        }).adopt(new Element('div', { 'class': 'left' })).inject(this.menu);
        if (this.current) this.setCurrent(this.current);
    },

    setCurrent: function(el, effect) {
        this.back.setStyles({ left: (el.offsetLeft), width: (el.offsetWidth) });
        (effect) ? this.back.get('morph').start({ 'opacity': [0, 1] }) : this.back.setStyle('opacity', 1);
        this.current = el;
    },

    clickItem: function(event) {
        var item = $(event.target);
        this.setCurrent(item, true);
        this.fireEvent('onClick', [new Event(event), item]);
    },

    moveBg: function(to) {
        if (!this.current) return;
        if (to) {
            to = $(to.target);
        } else {
            to = this.current;
        }
        this.back.get('morph').start({
            left: to.offsetLeft,
            width: to.offsetWidth
        });
    }
});

/* basket */
/************************************************************************************************************
(C) www.dhtmlgoodies.com, March 2006

This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.	

Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.

Version:
1.0	Released	March. 3rd 2006

Thank you!

www.dhtmlgoodies.com
Alf Magne Kalleland

************************************************************************************************************/

var flyingSpeed = 25;

var shopping_cart_div = false;
var flyingDiv = false;
var currentProductDiv = false;

var shopping_cart_x = false;
var shopping_cart_y = false;

var slide_xFactor = false;
var slide_yFactor = false;

var diffX = false;
var diffY = false;

var currentXPos = false;
var currentYPos = false;

var ajaxObjects = new Array();


function shoppingCart_getTopPos(inputObj) {
    var returnValue = inputObj.offsetTop;
    while ((inputObj = inputObj.offsetParent) != null) {
        if (inputObj.tagName != 'HTML') returnValue += inputObj.offsetTop;
    }
    return returnValue;
};

function shoppingCart_getLeftPos(inputObj) {
    var returnValue = inputObj.offsetLeft;
    while ((inputObj = inputObj.offsetParent) != null) {
        if (inputObj.tagName != 'HTML') returnValue += inputObj.offsetLeft;
    }
    return returnValue;
};

function addMoreItemsToBasket(stockNo, controlName, productName) {
    var qtyCtrl;
    qtyCtrl = controlName.substring(0, controlName.indexOf("btnAddToCart")) + "txtQty";
    addToBasket(stockNo, document.getElementById(qtyCtrl).value, productName);
    return false;
};

function addToBasket(productId, quantity, productname) {
    AddProduct(productId, quantity, productname);
    var safename = productname.replace("'", " ");
    if (!shopping_cart_div) shopping_cart_div = document.getElementById('shopping_cart');
    if (!flyingDiv) {
        flyingDiv = document.createElement('DIV');
        flyingDiv.style.position = 'absolute';
        document.body.appendChild(flyingDiv);
    }

    shopping_cart_x = shoppingCart_getLeftPos(shopping_cart_div);
    shopping_cart_y = shoppingCart_getTopPos(shopping_cart_div);

    currentProductDiv = document.getElementById('slidingProduct' + productId);
    if (currentProductDiv == null) {
        currentProductDiv = document.getElementById('slidingProduct');
    }
    currentXPos = shoppingCart_getLeftPos(currentProductDiv);
    currentYPos = shoppingCart_getTopPos(currentProductDiv);

    diffX = shopping_cart_x - currentXPos;
    diffY = shopping_cart_y - currentYPos;

    var shoppingContentCopy = currentProductDiv.cloneNode(true);
    shoppingContentCopy.id = '';
    flyingDiv.innerHTML = '';
    flyingDiv.style.left = currentXPos + 'px';
    flyingDiv.style.top = currentYPos + 'px';
    flyingDiv.appendChild(shoppingContentCopy);
    flyingDiv.style.display = 'block';
    flyingDiv.style.width = currentProductDiv.offsetWidth + 'px';
    flyToBasket(productId, quantity, productname);
};

function flyToBasket(productId, quantity, productname) {
    var maxDiff = Math.max(Math.abs(diffX), Math.abs(diffY));
    var moveX = (diffX / maxDiff) * flyingSpeed; ;
    var moveY = (diffY / maxDiff) * flyingSpeed;

    currentXPos = currentXPos + moveX;
    currentYPos = currentYPos + moveY;

    flyingDiv.style.left = Math.round(currentXPos) + 'px';
    flyingDiv.style.top = Math.round(currentYPos) + 'px';


    if (moveX > 0 && currentXPos > shopping_cart_x) {
        flyingDiv.style.display = 'none';
    }
    if (moveX < 0 && currentXPos < shopping_cart_x) {
        flyingDiv.style.display = 'none';
    }

    //setTimeout('flyToBasket("' + productId + '")',10);

    if (flyingDiv.style.display == 'block') {
        setTimeout('flyToBasket("' + productId + '", "' + quantity + '", "' + productname + '")', 10);
    }
    //    else {
    //        AddProduct(productId, quantity, productname);
    //    }
};

function AddProduct(productid, quantity, productname) {
    var tkk = document.getElementById('ctl00_divTkk');
    if (tkk == null) {
        alert("Error adding to cart! Please try again");
    }
    else {
        var token = tkk.innerText;
        if (token == undefined || token == null) {
            token = tkk.textContent;
        }
        AddToCart(productid, quantity, productname, token);
    }
};

function updatePriceToZero() {
    document.getElementById('shopping_cart_totalprice').innerHTML = '';
    document.getElementById('lblEmptyCart').style.display = 'block';
    document.getElementById(shopCartTitleID).innerHTML = shopCartTitle + " (0)";
};

function updateTotalPrice(currency) {
    var itemBox = document.getElementById('shopping_cart_items');
    // Calculating total price and showing it below the table with basket items
    var totalPrice = 0;
    var totalQ = 0;
    if (document.getElementById('shopping_cart_totalprice')) {
        for (var no = 1; no < itemBox.rows.length; no++) {
            totalPrice = totalPrice + (itemBox.rows[no].cells[1].innerHTML.replace(/[^0-9]/g) * itemBox.rows[no].cells[2].innerHTML.replace(currency, ''));
            totalQ = totalQ + parseInt(itemBox.rows[no].cells[1].innerHTML.replace(/[^0-9]/g));

        }
        document.getElementById('shopping_cart_totalprice').innerHTML = currency + totalPrice.toFixed(2).toString();
        if (totalPrice.toFixed(2) > 0) {
            document.getElementById('lblEmptyCart').style.display = 'none';
        }
        else {
            document.getElementById('lblEmptyCart').style.display = 'block';
        }
        if (shopCartTitleID != null) {
            document.getElementById(shopCartTitleID).innerHTML = shopCartTitle + " (" + totalQ + ")";
        }
    }

};

function IsEmptyCart() {
    var itemBox = document.getElementById('shopping_cart_items');
    try {
        if (document.getElementById(shopCartTitleID).innerHTML.indexOf('(0)') == -1 && itemBox != null && itemBox.rows.length >= 1) {
            return false;
        }
        else {
            return true;
        }
    }
    catch (err) {
        return false;
    }
};

function ClearCart() {
    if (IsEmptyCart()) {
        return false;
    }
    else {
        return removeAllFromBasket();
    }
};
function CheckOut() {
    if (IsEmptyCart()) {
        alert('Your shopping cart is empty');
        return false;
    }
    else {
        window.location = 'CheckOutAs.aspx';
    }
};

function removeProductFromBasket(productId, quantity) {

    var cart = document.getElementById('shopping_cart_items');
    if (cart != null) {
        cart.disabled = true;
    }
    var tkk = document.getElementById('ctl00_divTkk');
    if (tkk != null) {
        var token = tkk.innerText;
        if (token == undefined || token == null) {
            token = tkk.textContent;
        }
        RemoveFromCart(productId, quantity, token);
    }

};

function removeAllFromBasket() {

    if (confirm(confirmcartremoval)) {
        var tkk = document.getElementById('ctl00_divTkk');

        if (tkk != null) {
            var token = tkk.innerText;
            if (token == undefined || token == null) {
                token = tkk.textContent;
            }
            RemoveCartItems(token);
            return false;
        }
    }
    else {
        return false;
    }
};

function AddRow(tableName, itemString) {
    if (itemString == null) {
        return false;
    }
    var itemBox = document.getElementById(tableName);
    if (itemBox == null) {
        return false;
    }
    var productItems = itemString.split('|||');
    var tr = itemBox.insertRow(-1);
    tr.id = 'shopping_cart_items_product' + productItems[0];

    var td = tr.insertCell(-1);
    td.vAlign = "top";
    td.style.textAlign = 'left';
    td.innerHTML = productItems[1]; 	// Description

    var td = tr.insertCell(-1);
    td.vAlign = "top";
    td.style.textAlign = 'left';
    td.style.paddingRight = '3px';
    td.innerHTML = productItems[3]; 	// Number of items

    var td = tr.insertCell(-1);
    td.vAlign = "top";
    td.style.textAlign = 'right';
    td.style.color = 'red';
    td.style.paddingRight = '3px';
    td.innerHTML = productItems[4] + productItems[2].toString(); 	// Price

    var td = tr.insertCell(-1);
    td.vAlign = "top";
    td.style.paddingRight = '3px';
    td.style.paddingBottom = '3px';
    var a = document.createElement('A');
    td.appendChild(a);
    a.href = '#';
    a.onclick = function() { removeProductFromBasket(productItems[0], 1); };
    var img = document.createElement('IMG');
    img.src = 'images/delete.jpg';
    img.onmouseover = function() { DelMouseOver(img); };
    img.onmouseout = function() { DelMouseOut(img); };
    img.title = "Remove one item";
    a.appendChild(img);
    updateTotalPrice(productItems[4]);
};

function GetVitaInfo(Vita, tkk) {
    try {
        PageMethods.GetVitaInfo(Vita, tkk, SucceededCallback);
    }
    catch (ex) {

    }
};

function AddToCart(ProductID, Quantity, productname, tkk) {
    try {
        PageMethods.AddToCart(ProductID, Quantity, productname, tkk, SucceededCallbackWithContext, FailedCallback, "AddToCart");
    }
    catch (ex) {
        alert(ex.toString());
    }
};

function RemoveFromCart(ProductID, Quantity, tkk) {
    try {
        PageMethods.RemoveFromCart(ProductID, Quantity, tkk, SucceededCallbackWithContext, FailedCallback, "RemoveFromCart");
    }
    catch (ex) {
        alert(ex.toString());
    }
};

function RemoveCartItems(tkk) {
    try {
        PageMethods.RemoveAllFromCart(tkk, SucceededCallbackWithContext, FailedCallback, "RemoveAllFromCart");
    }
    catch (ex) {
        alert(ex.toString());
    }
};

// This is the callback function invoked if the Web service
// succeeded.
// It accepts the result object, the user context, and the 
// calling method name as parameters.
function SucceededCallbackWithContext(result, userContext, methodName) {
    var output;
    // Page element to display feedback.
    var RsltElem = document.getElementById("ResultId");

    var readResult;
    switch (userContext) {
        case ("RemoveAllFromCart"):
            var cart = document.getElementById('shopping_cart_items');
            //            for (var i = 1; i < cart.rows.length; i++) {
            //                cart.deleteRow[i];
            //            }
            var len = cart.rows.length;
            for (i = len - 1; i != 0; i--) {
                cart.deleteRow(i);
            }
            updatePriceToZero();
            if (document.location.href.indexOf("CheckoutAs.aspx") != -1 || document.location.href.indexOf("Checkout.aspx") != -1) {
                window.location = "Main.aspx";
            }
            cart.disabled = false;
            break;

        case ("RemoveFromCart"):
            var cart = document.getElementById('shopping_cart_items');
            var itemString = result;  //"5|||1|||$|||";
            var productItems = itemString.split('|||'); // Breaking response from Ajax into tokens
            var productRow = document.getElementById('shopping_cart_items_product' + productItems[0]);

            var numberOfItemCell = productRow.cells[1];
            if (numberOfItemCell.innerHTML == '1') {
                productRow.parentNode.removeChild(productRow);
            } else {
                numberOfItemCell.innerHTML = productItems[1];
            }
            updateTotalPrice(productItems[2]);
            cart.disabled = false;
            break;

        case ("AddToCart"):
            var itemBox = document.getElementById('shopping_cart_items');
            var itemString = result;  //"5|||Week planner|||60|||";
            var productItems = itemString.split('|||'); // Breaking response from Ajax into tokens

            if (document.getElementById('shopping_cart_items_product' + productItems[0])) {	// A product with this id is allready in the basket - just add number items
                var row = document.getElementById('shopping_cart_items_product' + productItems[0]);
                var items = row.cells[1].innerHTML / 1;
                items = items + parseInt(productItems[3]);
                row.cells[1].innerHTML = items;
                updateTotalPrice(productItems[4]);
            } else {	// Product isn't allready in the basket - add a new row
                AddRow('shopping_cart_items', itemString)
                //td.innerHTML = '<a href="#" onclick="removeProductFromBasket("' + productItems[0] + '");return false;"><img src="images/remove.gif"></a>';	
            }
            break;
        case ("XmlDocument"):
            if (document.all)
                readResult =
		        result.documentElement.firstChild.text;
            else
            // Firefox
                readResult =
		        result.documentElement.firstChild.textContent;

            RsltElem.innerHTML = "XmlDocument content: " + readResult;
            break;
    }
};

// This is the callback function invoked if the Web service
// succeeded.
// It accepts the result object as a parameter.
function SucceededCallback(result, eventArgs) {
    // Page element to display feedback.
    var RsltElem = document.getElementById("ResultId");
    RsltElem.innerHTML = result;
    showpopup = 1;
};

// This is the callback function invoked if the Web service
// failed.
// It accepts the error object as a parameter.
function FailedCallback(error) {
    // Display the error.
    var cart = document.getElementById('shopping_cart_items');
    if (cart != null) {
        cart.disabled = false;
    }
    //    var RsltElem =
    //        document.getElementById("ResultId");
    //    RsltElem.innerHTML =
    //    "Service Error: " + error.get_message();
};

if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

//other functions
function DelMouseOver(img) {
    img.src = 'images/delete_over.jpg';
};

function DelMouseOut(img) {
    img.src = 'images/delete.jpg';
};

function GetBrowser() {
    var browser = navigator.appName;
    return browser;
};

function BuildHtmlProd(id, title, description) {
    var sHtml = "<table style='background-color:#E2E2E2; padding:0; font-size:8pt; font-family:Arial, Verdana, Tahoma' cellpadding='0' cellspacing='0' ><tr><td valign='top'><img src='images/products/1/" + id + ".jpg' alt='' /></td><td valign='top'><STRONG>" + title + "</STRONG><br />" + description + "</td></tr></table>";
    return sHtml;
};

function CheckCartChanged() {
    //    var nChk = PageMethods.CheckCartChanged();
    //    if (nChk == 1) {
    //    }
};

var ContentHeight = new Array();
ContentHeight[0] = 375;
ContentHeight[1] = 565;
var TimeToSlide = 250.0;
var openAccordion = '';

function runAccordion(index, tts) {
    var nID = "Accordion" + index + "Content";
    Set_Cookie("CtgType", index, 30);
    if (openAccordion == nID)
        nID = '';
    var nCurrIndex = index - 1;
    var loctts = 0;
    if (tts == 0) {
        loctts = tts;
    }
    else {
        loctts = TimeToSlide;
    }
    setTimeout("animate(" + new Date().getTime() + "," + loctts + ",'"
      + openAccordion + "','" + nID + "'," + nCurrIndex + ")", 33);

    openAccordion = nID;
};

function animate(lastTick, timeLeft, closingId, openingId, index) {
    var curTick = new Date().getTime();
    var elapsedTicks = curTick - lastTick;

    var opening = (openingId == '') ? null : document.getElementById(openingId);
    var closing = (closingId == '') ? null : document.getElementById(closingId);

    if (timeLeft <= elapsedTicks) {
        if (opening != null) {
            opening.style.display = 'block';
            opening.style.height = ContentHeight[index] + 'px';
        }
        //        if (closing != null) {
        //            closing.style.display = 'none';
        //            closing.style.height = '0px';
        //        }
        return;
    }

    timeLeft -= elapsedTicks;
    var newClosedHeight = Math.round((timeLeft / TimeToSlide) * ContentHeight[index]);

    if (opening != null) {
        if (opening.style.display != 'block')
            opening.style.display = 'block';
        opening.style.height = (ContentHeight[index] - newClosedHeight) + 'px';
    }

    //    if (closing != null)
    //        closing.style.height = newClosedHeight + 'px';

    setTimeout("animate(" + curTick + "," + timeLeft + ",'"
      + closingId + "','" + openingId + "'," + index + ")", 33);
};

var sPath = window.location.pathname;
//var sPage = sPath.substring(sPath.lastIndexOf('\\') + 1);
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
var startTimeStamp = new Date();
var reportUrl = "WS.ashx?text=page_load&link=" + escape(sPage) + "&stamp=" + startTimeStamp.valueOf() + "&inbound=true&screenwidth=" + window.screen.width + "&screenheight=" + window.screen.height;
var startImage = new Image();
startImage.src = reportUrl;
var startNow = new Date();
var startStopTime = startNow.getTime() + 500;
while (startNow.getTime() < startStopTime) {
    startNow = new Date();
};

// Search Suggest
var tSearch = 'txtSearch';
var searchType = '1';
var quickOrder = 0;
var qoLookup;
var maxDivId, currentDivId, strOriginal;
var sSearch = '';

//Our XmlHttpRequest object to get the auto suggestvar 
searchReq = getXmlHttpRequestObject();
var tmrSearch = 0;

function ClearTSearch() {
    clearTimeout(tmrSearch);
}

function StartTSearch() {
    tmrSearch = setTimeout("HideList()", 5000);
}

function keyPressHandler(e) {
    var kC = (window.event) ?    // MSIE or Firefox?
                 event.keyCode : e.keyCode;
    var Esc = (window.event) ?
                27 : e.DOM_VK_ESCAPE // MSIE : Firefox
    if (kC == Esc) {
        HideList();
    }
}

function HideList() {
    var ss = document.getElementById('search_suggest');
    ss.innerHTML = '';
    ss.style.visibility = 'hidden';
    if (tmrSearch > 0) {
        clearTimeout(tSearch);
    }
}

function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
        alert("Your Browser is outdated!\nIt's about time to upgrade don't you think?");
    }
}

function GetPN(obj) {
    var stockno = obj.value;
    qoLookup = obj.id;
    var lblProdName = document.getElementById(qoLookup.replace('txtStock', 'lblProduct'));
    var objQty = document.getElementById(qoLookup.replace('txtStock', 'txtQty'));

    obj.value = Trim(obj.value);
    if (obj.value == '') {
        lblProdName.innerText = "";
        lblProdName.textContent = "";
        objQty.value = "";
        return false;
    }


    if (searchReq.readyState == 4 || searchReq.readyState == 0) {
        sSearch = escape(document.getElementById(qoLookup).value);
        sSearch = Trim(sSearch);
        if (sSearch.length >= 4) {
            if (sSearch != '') {
                strOriginal = sSearch;
                searchReq.open("GET", 'Result.aspx?stockno=' + Trim(stockno), true);
                searchReq.onreadystatechange = handleGetProdName;
                searchReq.send(null);
            }
        }
        else {
            if (sSearch.length == 0) {
                lblProdName.innerText = "";
                lblProdName.textContent = "";
                objQty.value = "";
            }
            else {
                lblProdName.innerText = "INVALID";
                lblProdName.textContent = "INVALID";
                lblProdName.style.color = "red";
            }
        }
    }
}

function handleGetProdName() {
    var brw = navigator.userAgent.toLowerCase();
    if (searchReq.readyState == 4) {
        var str = searchReq.responseText.split(")</span>");
        if (str.length > 0) {
            var lblProdName = document.getElementById(qoLookup.replace('txtStock', 'lblProduct'));
            if (brw.indexOf("firefox") != -1) {
                lblProdName.textContent = str[0];
            }
            else {
                lblProdName.innerText = str[0];
            }
            if (str[0] == "INVALID") {
                lblProdName.style.color = "red";
            }
            else {
                lblProdName.style.color = "blue";
            }
        }
    }
}

//Called from keyup on the search textbox.//Starts the AJAX request.
function searchSuggest(e) {
    var key = window.event ? e.keyCode : e.which;

    if (key == 40 || key == 38) {
        scrolldiv(key);
    }

    //    else if (key == 27)
    //    {
    //        var ss = document.getElementById('search_suggest');
    //        ss.innerHTML = '';
    //        ss.style.visibility = 'hidden';
    //    }
    else {
        if (searchReq.readyState == 4 || searchReq.readyState == 0) {
            sSearch = escape(document.getElementById(tSearch).value);
            if (sSearch != '') {
                strOriginal = sSearch;
                searchReq.open("GET", 'Result.aspx?search=' + Trim(sSearch) + '&st=' + Trim(searchType), true);
                searchReq.onreadystatechange = handleSearchSuggest;
                searchReq.send(null);
            }
            else {
                HideList();
            }
        }

    }
}

//Called when the AJAX response is returned.
function handleSearchSuggest() {
    if (searchReq.readyState == 4) {
        var ss = document.getElementById('search_suggest');
        ss.innerHTML = '';
        var str = searchReq.responseText.split("~");

        if (str.length > 1) {
            if (str.length > 20) {
                ss.style.height = "355px";
            }
            else {
                ss.style.height = ((str.length - 1) * 20 + 3) + "px";
            }
            var tSearchE = document.getElementById(tSearch);
            ss.style.position = "absolute";
            ss.style.left = getX(tSearchE) + 'px';
            ss.style.top = (getY(tSearchE) + 21) + 'px';

            ss.className = "s_box";
            for (i = 0; i < str.length - 1; i++) {
                //Build our element string.  This is cleaner using the DOM, but			
                //IE doesn't support dynamically added attributes.

                maxDivId = i;
                currentDivId = -1;
                var suggest = '<div ';
                suggest += 'id=div' + i;
                suggest += '  '
                suggest += 'onmouseover="javascript:suggestOver(this);" ';
                suggest += 'onmouseout="javascript:suggestOut(this);" ';
                //suggest += 'onclick="javascript:setSearch(this.innerText);" ';
                if (quickOrder == 0) {
                    suggest += 'onclick="javascript:OpenPDS(this);"';
                }
                else {
                    suggest += 'onclick="javascript:SetProdQO(this); return false;"';
                }
                suggest += 'class="suggest_link">' + "<span class='hl'>" + str[i].substring(0, sSearch.length) + "</span>" + str[i].substring(sSearch.length); +'</div>';
                ss.innerHTML += suggest;
                ss.style.visibility = 'visible';
                if (tmrSearch == 0) {
                    StartTSearch();
                }
            }
        }
        else {

            ss.style.visibility = 'hidden';
        }
    }
}

//Mouse over function
function suggestOver(div_value) {
    if (div_value != null) {
        div_value.className = 'suggest_link_over';
    }
}

function scrollOver(div_value) {
    if (div_value == null) {
        return false;
    }
    div_value.className = 'suggest_link_over';
    var sIT;
    var brw = navigator.userAgent.toLowerCase();
    if (brw.indexOf("firefox") != -1) {
        sIT = div_value.textContent;
    }
    else {
        sIT = div_value.innerText;
    }
    if (quickOrder == 1) {
        SetValToQO(sIT);
    }
    else {
        document.getElementById(tSearch).value = sIT;
    }
}

//Mouse out function
function suggestOut(div_value) {
    if (div_value != null) {
        div_value.className = 'suggest_link';
    }
}

//Click function
function setSearch(value) {
    var ss = document.getElementById('search_suggest');

    document.getElementById(tSearch).value = value;
    ss.innerHTML = '';
    ss.style.visibility = 'hidden';
}

function scrolldiv(key) {
    var tempID;

    if (key == 40) {
        ClearTSearch();
        if (currentDivId == -1) {
            var divOver = document.getElementById("div0");
            scrollOver(divOver);
            currentDivId = 0;
        }
        else {
            if (currentDivId == maxDivId) {
                tempID = 'div' + maxDivId;
                var a = document.getElementById(tempID);
                currentDivId = -1;
                suggestOut(a)
                document.getElementById(tSearch).value = strOriginal;
            }
            else {
                tempID = currentDivId + 1;
                setScroll(currentDivId, tempID)
            }

        }
        StartTSearch();
    }
    else if (key == 38) {
        ClearTSearch();
        if (currentDivId == -1) {
            tempID = maxDivId;
            setScroll(maxDivId, maxDivId)
        }
        else {
            if (currentDivId == 0) {
                tempID = 'div' + currentDivId;
                var a = document.getElementById(tempID);
                currentDivId = -1;
                suggestOut(a)
                document.getElementById(tSearch).value = strOriginal;

            }
            else {
                tempID = currentDivId - 1;
                setScroll(currentDivId, tempID)

            }

        }
        StartTSearch();

    }
};
function setScroll(Old, New) {
    var tempDivId;
    currentDivId = New;

    tempDivId = 'div' + Old;
    var a = document.getElementById(tempDivId);
    suggestOut(a)

    tempDivId = 'div' + currentDivId;
    var b = document.getElementById(tempDivId);
    scrollOver(b);

};

function getY(oElement) {
    var iReturnValue = 0;
    while (oElement != null) {
        iReturnValue += oElement.offsetTop;
        oElement = oElement.offsetParent;
    };
    return iReturnValue;
};

function getX(oElement) {
    var iReturnValue = 0;
    while (oElement != null) {
        iReturnValue += oElement.offsetLeft;
        oElement = oElement.offsetParent;
    };
    return iReturnValue;
};

function SetProdQO(obj) {
    var sIT;

    var brw = navigator.userAgent.toLowerCase();
    if (brw.indexOf("firefox") != -1) {
        sIT = obj.textContent;
    }
    else {
        sIT = obj.innerText;
    }
    SetValToQO(sIT);
    var txtQTY;
    if (searchType == 2) {
        txtQTY = document.getElementById(qoLookup.replace('txtStock', 'txtQty').replace('txtProdName', 'txtQty'));
    }
    else {
        txtQTY = document.getElementById(qoLookup.replace('txtProdName', 'txtQtyPN').replace('txtProdName', 'txtQtyPN'));
    }

    HideList();
    if (txtQTY != null) {
        txtQTY.focus();
    }
    return false;
};

function SetValToQO(sIT) {
    var sProdName;
    var brw = navigator.userAgent.toLowerCase();
    if (sIT.indexOf("(SN:") != -1) {
        sProdName = Trim(sIT.substring(0, sIT.indexOf("(SN:") - 1));
        sIT = sIT.substring(sIT.indexOf("(SN:") + 4);
        sIT = sIT.replace(")", "");
    }
    else {
        sProdName = sIT.substring(sIT.indexOf(" ") + 2);
        sProdName = sProdName.substring(0, sProdName.length - 1);
        sIT = sIT.substring(0, sIT.indexOf(" "));
    }

    if (searchType == 2) {
        document.getElementById(qoLookup).value = sIT;
        var lblProd = document.getElementById(qoLookup.replace('txtStock', 'lblProduct'));

        if (brw.indexOf("firefox") != -1) {
            lblProd.textContent = sProdName;
        }
        else {
            lblProd.innerText = sProdName;
        }
        lblProd.style.color = "blue";

    }
    else {
        document.getElementById(qoLookup).value = sProdName;
        var lblStock = document.getElementById(qoLookup.replace('txtProdName', 'lblStock'));

        if (brw.indexOf("firefox") != -1) {
            lblStock.textContent = sIT;
        }
        else {
            lblStock.innerText = sIT;
        }
        lblStock.style.color = "blue";
    }
};

function OpenPDS(obj) {
    var sIT;
    var brw = navigator.userAgent.toLowerCase();
    if (brw.indexOf("firefox") != -1) {
        sIT = obj.textContent;
    }
    else {
        sIT = obj.innerText;
    }
    if (sIT.indexOf("(SN:") != -1) {
        sIT = sIT.substring(sIT.indexOf("(SN:") + 4);
        sIT = sIT.replace(")", "");
    }
    else {
        sIT = sIT.substring(0, sIT.indexOf(" "));
    }
    window.location = 'ProductDetails.aspx?stockno=' + sIT;
};
function OpenPDST(txt) {
    var obj = document.getElementById(txt);
    obj.value = Trim(obj.value);
    var sIT = obj.value;
    if (sIT == "") {
        return false;
    }
    if (sIT.indexOf("(SN:") != -1) {
        sIT = sIT.substring(sIT.indexOf("(SN:") + 4);
        sIT = sIT.replace(")", "");
    }
    else {
        sIT = sIT.substring(0, sIT.indexOf(" "));
    }
    if (obj.value.length < 20) {
        window.location = 'SearchBy.aspx?kw=' + obj.value + '&to=1';
    }
    else {
        window.location = 'ProductDetails.aspx?stockno=' + sIT;
    }
};

function SelectAll(id) {
    document.getElementById(id).focus();
    document.getElementById(id).select();
};

function Reset(ov) {
    if (ov == 1) {
        var pns = document.getElementById("ctl00_ContentPlaceHolder1_pnStock");
        if (pns != null) {
            pns.style.display = "none";
        }
        var pnsPN = document.getElementById("ctl00_ContentPlaceHolder1_pnStockPN");
        if (pnsPN != null) {
            pnsPN.style.display = "block";
        }
        return false;
    }

    if (confirm('Are you sure you want to clean up data?')) {
        CleanQO();
    }
    return false;
};

function CleanQO() {
    for (var i = 1; i < 11; i++) {
        var objStock = document.getElementById("ctl00_ContentPlaceHolder1_txtStock" + i);
        var objQty = document.getElementById("ctl00_ContentPlaceHolder1_txtQty" + i);
        objStock.value = "";
        objQty.value = "";
        var objP = document.getElementById("ctl00_ContentPlaceHolder1_lblProduct" + i);
        objP.innerText = "";
        objP.textContent = "";
    }
    return false;
};

function ResetPN(ov) {
    if (ov == 1) {
        var pns = document.getElementById("ctl00_ContentPlaceHolder1_pnStock");
        if (pns != null) {
            pns.style.display = "block";
        }
        var pnsPN = document.getElementById("ctl00_ContentPlaceHolder1_pnStockPN");
        if (pnsPN != null) {
            pnsPN.style.display = "none";
        }
        return false;
    }

    if (confirm('Are you sure you want to clean up data?')) {
        CleanQOPN()
    }
    return false;
};

function CleanQOPN() {
    for (var i = 1; i < 11; i++) {
        var objProd = document.getElementById("ctl00_ContentPlaceHolder1_txtProdName" + i);
        var objQty = document.getElementById("ctl00_ContentPlaceHolder1_txtQtyPN" + i);
        objProd.value = "";
        objQty.value = "";
        var objS = document.getElementById("ctl00_ContentPlaceHolder1_lblStock" + i);
        objS.innerText = "";
        objS.textContent = "";
    }
};

function GoToQtyPN() {
    for (var i = 1; i < 11; i++) {
        var objPN = document.getElementById("ctl00_ContentPlaceHolder1_txtProdName" + i);
        var objQty = document.getElementById("ctl00_ContentPlaceHolder1_txtQtyPN" + i);
        if (Trim(objPN.value) != "" && Trim(objQty.value) == "") {
            objQty.focus();
            HideList();
            return false;
        }
    }

    for (var i = 1; i < 11; i++) {
        var objPN = document.getElementById("ctl00_ContentPlaceHolder1_txtProdName" + i);
        var objQty = document.getElementById("ctl00_ContentPlaceHolder1_txtQtyPN" + i);

        var objStock = document.getElementById("ctl00_ContentPlaceHolder1_lblStock" + i);
        var sStock;
        if (document.all) {
            sStock = objStock.innerText;
        }
        else {
            // Firefox
            sStock = objStock.textContent;
        }

        if (objPN != null) {
            objPN.value = Trim(objPN.value);
        }
        if (objPN != null && objPN.value != "") {
            if (Trim(objPN.value) != "" && Trim(objQty.value) != "") {
                if (sStock == "" || Trim(sStock) == "" || Trim(sStock) == "INVALID") {
                    objStock.innerText = "INVALID";
                    objStock.textContent = "";
                    objStock.style.color = "red";
                }
                else {
                    if (!IsNumeric(objQty.value) || parseInt(objQty.value) <= 0) {
                        objQty.focus;
                        objQty.style.color = "red";
                        alert("Quantity must be greater than zero");
                        return false;
                    }
                    AddProduct(sStock, Trim(objQty.value), Trim(objPN.value))
                }
            }
        }
        else {
            objQty.value = "";
            objStock.innerText = "";
            objStock.textContent = "";
        }
    }
    HideList();
    CleanQOPN();
    return false;
};

function GoToQty() {
    for (var j = 1; j < 11; j++) {
        var objStockV = document.getElementById("ctl00_ContentPlaceHolder1_txtStock" + j);
        var objQtyV = document.getElementById("ctl00_ContentPlaceHolder1_txtQty" + j);
        if (Trim(objStockV.value) != "" && Trim(objQtyV.value) == "") {
            objQtyV.focus();
            HideList();
            return false;
        }
    }

    for (var i = 1; i < 11; i++) {

        var objStock = document.getElementById("ctl00_ContentPlaceHolder1_txtStock" + i);
        var objQty = document.getElementById("ctl00_ContentPlaceHolder1_txtQty" + i);

        var objProdName = document.getElementById("ctl00_ContentPlaceHolder1_lblProduct" + i);
        var ProdName;
        if (document.all) {
            ProdName = objProdName.innerText;
        }
        else {
            // Firefox
            ProdName = objProdName.textContent;
        }

        if (objStock != null) {
            objStock.value = Trim(objStock.value);
        }
        if (objStock != null && objStock.value != "") {

            if (Trim(objStock.value) != "" && Trim(objQty.value) != "") {
                if (ProdName == "" || Trim(ProdName) == "" || Trim(ProdName) == "INVALID") {
                    objProdName.innerText = "INVALID";
                    objProdName.textContent = "INVALID";
                    objProdName.style.color = "red";
                    return false;
                }
                else {
                    if (!IsNumeric(objQty.value) || parseInt(objQty.value) <= 0) {
                        objQty.focus;
                        objQty.style.color = "red";
                        alert("Quantity must be greater than zero");
                        return false;
                    }
                    AddProduct(Trim(objStock.value), Trim(objQty.value), ProdName)
                }
            }
        }
        else {
            objQty.value = "";
            objProdName.innerText = "";
            objProdName.textContent = "";
        }
    }
    HideList();
    CleanQO();
    return false;
};


function ResetPD(index) {
    document.getElementById("pdTB0").style.display = "none";
    document.getElementById("pdTB1").style.display = "none";
    document.getElementById("pdTB2").style.display = "none";
    document.getElementById("pdTB3").style.display = "none";
    document.getElementById("pdTB" + index).style.display = "block";
};

function PNCheckEmpty(obj) {
    var pnId = obj.id;
    var pnVal = Trim(obj.value);
    if (pnVal == "") {
        var objStock = document.getElementById(pnId.replace("txtProdName", "lblStock"));
        objStock.innerText = "";
        objStock.textContent = "";
        var objQty = document.getElementById(pnId.replace("txtProdName", "txtQtyPN"));
        objQty.value = "";
    }
};
