$(document).ready(function () {

    $(".top-mini-content");

    $("#cart").hover(
        function () {
            $('.top-mini-content').toggleClass('inspectcart');
        }, function () {
            $('.top-mini-content').toggleClass('inspectcart');
        }
    );

    $(".top-mini-content").hover(
        function () {
            $('.top-mini-content').toggleClass('inspectcart');
        }, function () {
            $('.top-mini-content').toggleClass('inspectcart');
        }
    );

    $('.productList').on("click", "a.productOptionLink", function () {
        var isPrimaryProduct = false;

        var variantRow = $(this).closest('.variantrow');

        if (variantRow.hasClass('primaryProduct')) {
            isPrimaryProduct = true;
        }

        var productUniqueCodeRegex = /.+\[(.+)\]/g;
        var match = productUniqueCodeRegex.exec($(this).text());
        if (match != null) {
            // Replace main image with the variant image.
            var newimagesrc = $('.prodOptionImdDiv' + match[1] + ' > a').attr("href");
            $('#prodImgDiv #prodImgSubLightboxLink').attr('href', newimagesrc);
            $('#prodImgDiv #prodImg').attr('src', newimagesrc);
            $('#prodImgDiv .zoomImg').attr('src', newimagesrc);
        }
    });
});

function CleanQuickCart() {
    $('.top-mini-content').remove();
}

function ShowQuickCartBriefly() {

    $("html, body").animate({ scrollTop: 0 }, 1000);

    $('.top-mini-content').toggleClass('inspectcart');
    setTimeout(function () {
        $('.top-mini-content').toggleClass('inspectcart');
    }, 3500);
}


function ReorderAllItems(reorderButton) {

    var itemRows = $(reorderButton).closest('tr.orderHeaderRow').next().find('tr.orderItemRow');

    var items = "";

    $.each(itemRows, function (index, itemRow) {

        var productid = $(itemRow).find('input[name="itemNo_orderhistory"]').val();

        var quantity = $(itemRow).find('input[name="qty_orderhistory"]').val();

        if (isNaN(quantity)) {
            quantity = 0;
        }

        if (quantity > 0) {

            items += productid + ":" + quantity + "|";
        }

    });

    // remove trailing pipe
    items = items.substring(0, items.length - 1);

    DoAjaxRequest("/addcart.aspx?items=" + items + "&action=addCart", function () {

        CleanQuickCart();

        DoAjaxRequest("/quickcart.aspx", function (response) {
            document.getElementById("cart").innerHTML = response;
            ShowQuickCartBriefly();
        });
    });

}
function MakePayment(makePaymentButton) {
    var orderRow = $(makePaymentButton).closest('tr');
    var OrderID = $(orderRow).find('input[id="Order_ID"]').val();
    //alert("MakePayment Called.." + OrderID);
    DoAjaxRequest("/addcart.aspx?orderid=" + OrderID + "&action=addOrderToCart", function () {
        CleanQuickCart();
        DoAjaxRequest("/quickcart.aspx", function (response) {
            document.getElementById("cart").innerHTML = response;
            ShowQuickCartBriefly();
        });
        window.location.replace("/checkout.aspx");
    });
}


function ReorderIndividualItem(addToCartButton) {

    var itemRow = $(addToCartButton).closest('tr.orderItemRow');

    var productId = $(itemRow).find('input[name="itemNo_orderhistory"]').val();

    var quantity = $(itemRow).find('input[name="qty_orderhistory"]').val();

    addToCart(productId, quantity);

}


function addToCart_Short(productId, quantity, minValue) {
    addToCart(productId, 1, false);
}
function addAllToCart() {
    var itemQuantities = $("input.ItemQty");
    var length = itemQuantities.length;
    var items = "";

    itemQuantities.each(function (index) {
        var productid = $(this).attr('id');
        var quantity = $(this).val();

        if (productid.indexOf('itemqty') !== -1) {
            productid = productid.replace("itemqty", "");
        }

        if (isNaN(quantity)) {
            quantity = 0;
        }

        if (quantity > 0) {
            items += productid + ":" + quantity + "|";
        }

    });
    if (items.length > 0) {
        $("span.qtyalert").hide();
        // remove trailing pipe
        items = items.substring(0, items.length - 1);

        DoAjaxRequest("/addcart.aspx?items=" + items + "&action=addCart", function () {

            CleanQuickCart();

            DoAjaxRequest("/quickcart.aspx", function (response) {
                document.getElementById("cart").innerHTML = response;
                ShowQuickCartBriefly();
            });
        });
    } else {
        $("span.qtyalert").show();
    }

}
function removeFromCart(productId) {
    //alert("addcart.aspx?DelAction=" + productId + "&action=DelCart");
    $("input#itemqty" + productId).val("");
    DoAjaxRequest("/addcart.aspx?DelAction=" + productId + "&action=DelCart", function () {

        CleanQuickCart();

        DoAjaxRequest("/quickcart.aspx", function (response) {
            document.getElementById("cart").innerHTML = response;
            ShowQuickCartBriefly();
        });
    });
}

function addToCart(productId, quantity) {
    if ($("input#itemqty" + productId).val() != quantity) {
        quantity = $("input#itemqty" + productId).val();
    }
    DoAjaxRequest("/addcart.aspx?itemNo=" + productId + "&qty=" + (quantity == null || quantity == "" ? 1 : quantity) + "&action=addCart", function () {
        var prodImg = document.getElementById("prodImg" + productId);
        if (prodImg == null) {
            prodImg = document.getElementById("prodImg");
        }
        DoAjaxRequest("/quickcart.aspx", function (response) {

            CleanQuickCart();

            document.getElementById("cart").innerHTML = response;
            ShowQuickCartBriefly();
        });
    });

}

function UpdateProductTotalPrice() {

    var debuginfo = "";
    var itemQuantities = $("input.ItemQty");
    var length = itemQuantities.length;
    var TotalPrice = 0;
    itemQuantities.each(function (index) {
        var productid = $(this).attr('id');
        var quantity = $(this).val();
        if (productid.indexOf('itemqty') !== -1) {
            productid = productid.replace("itemqty", "");
        }
        if (isNaN(quantity)) {
            quantity = 0;
        }
        var optionprice = $("input#" + productid).val();
        optionprice = optionprice.replace('$', '');
        //debuginfo += "|" + optionprice + "*" + quantity;
        TotalPrice += optionprice * quantity;
    });
    if (isNaN(TotalPrice)) {
        TotalPrice = $("p.price span.price").text();
    } else {
        TotalPrice = "$" + TotalPrice.toFixed(2);
    }
    $("p.price span.price").text(TotalPrice);
    $("p.price span.pricelabel").text("Total:");
    $("span.qtyalert").hide();
}

if (!window.XMLHttpRequest) {
    XMLHttpRequest = function () {
        try { return new ActiveXObject("MSXML3.XMLHTTP") } catch (ex) { }
        try { return new ActiveXObject("MSXML2.XMLHTTP.3.0") } catch (ex) { }
        try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (ex) { }
        try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (ex) { }
    }
}

function MM_openBrWindow(theURL, winName, features) { //v2.0
    window.open(theURL, winName, features);
}
function MM_findObj(n, d) { //v3.0
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document); return x;
}
function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2) ; i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}
function MM_swapImgRestore() { //v3.0
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}
function changeImages() {
    if (document.images) {
        for (var i = 0; i < changeImages.arguments.length; i += 2) {
            document[changeImages.arguments[i]].src = changeImages.arguments[i + 1];
        }
    }
}
function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; }
    }
}
function confPass() {
    if (document.RegisterMe.thePass.value == document.RegisterMe.CPass.value) {
        if (document.RegisterMe.thePass.value == "") {
            alert("Please enter a password");
            return false;
        } else {
            if (document.RegisterMe.UName.value == "") {
                alert("Please enter a Username");
                return false;
            } else {
                if (document.RegisterMe.theEmail.value == "") {
                    alert("Please enter a valid email address");
                    return false;
                } else {
                    return true;
                }
            }
        }
    } else {
        alert("Your password and confirmation of password are different. Please re-enter these details");
        document.RegisterMe.thePass.value = "";
        document.RegisterMe.CPass.value = "";
        return false;
    }
}

function giveWarningAndFixValue(field) {
    //removes all non-numeric value and replaces
    var value = parseInt(field.value);
    if (!isNaN(value)) field.value = value;
    else field.value = "0";
    //used for NS4.7 because when changing value the cursor is placed in front of the value, instead of behind
    if (document.layers) field.select();
}

function isNumericValue(str) {
    var isValid = true;
    if (str.search(/^[0-9]+$/) == -1) {
        isValid = false;
    }
    return isValid;
}
function checkValue(field) {
    if (!isNumericValue(field.value)) {
        giveWarningAndFixValue(field);
    }
}
/*
function confirmdel()
{
return window.confirm("If you delete this page all data in it will be lost. Are you sure you wish to continue?");
}

function confirmdelCont()
{
return window.confirm("Are you sure you wish to delete this content?");
}*/

function CheckPrice(obj) {
    //validate the price is a positive integer
    if (obj.value == "") {
        alert("You must enter a price.");
        return false;
    }
    else {

        if (obj.value.search(/[^\d]/) > -1) {
            alert("The price must be whole dollars in numbers only with no other characters.");
            obj.value = '0';
            return false;
        }
        else {
            return true;
        }
    }
}
function CheckQuantity(obj) {
    if (obj.value == "") {
        alert("You must enter a quantity.");
        return false;
    }
    else {
        if (obj.value.search(/[^\d]/) > -1) {
            alert("The quantity must be a positive number and contain numbers only with no other characters.");
            obj.value = '1';
            return false;
        }
        else {
            return true;
        }
    }
}
function CheckDiscontinuedStockLevel(obj, stockLevel) {
    if (obj.value > stockLevel) {
        alert("There is only " + stockLevel + " units available in stock.");
        obj.value = stockLevel;
    }
}
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
    if (init == true) with (navigator) {
        if ((appName == "Netscape") && (parseInt(appVersion) == 4)) {
            document.MM_pgW = innerWidth; document.MM_pgH = innerHeight; onresize = MM_reloadPage;
        }
    }
    else if (innerWidth != document.MM_pgW || innerHeight != document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
    var i, p, v, obj, args = MM_showHideLayers.arguments;
    for (i = 0; i < (args.length - 2); i += 3) if ((obj = MM_findObj(args[i])) != null) {
        v = args[i + 2];
        if (obj.style) { obj = obj.style; v = (v == 'show') ? 'visible' : (v == 'hide') ? 'hidden' : v; }
        obj.visibility = v;
    }
}

function MM_timelinePlay(tmLnName, myID) { //v1.2
    //Copyright 1997, 2000 Macromedia, Inc. All rights reserved.
    var i, j, tmLn, props, keyFrm, sprite, numKeyFr, firstKeyFr, propNum, theObj, firstTime = false;
    if (document.MM_Time == null) MM_initTimelines(); //if *very* 1st time
    tmLn = document.MM_Time[tmLnName];
    if (myID == null) { myID = ++tmLn.ID; firstTime = true; } //if new call, incr ID
    if (myID == tmLn.ID) { //if Im newest
        setTimeout('MM_timelinePlay("' + tmLnName + '",' + myID + ')', tmLn.delay);
        fNew = ++tmLn.curFrame;
        for (i = 0; i < tmLn.length; i++) {
            sprite = tmLn[i];
            if (sprite.charAt(0) == 's') {
                if (sprite.obj) {
                    numKeyFr = sprite.keyFrames.length; firstKeyFr = sprite.keyFrames[0];
                    if (fNew >= firstKeyFr && fNew <= sprite.keyFrames[numKeyFr - 1]) {//in range
                        keyFrm = 1;
                        for (j = 0; j < sprite.values.length; j++) {
                            props = sprite.values[j];
                            if (numKeyFr != props.length) {
                                if (props.prop2 == null) sprite.obj[props.prop] = props[fNew - firstKeyFr];
                                else sprite.obj[props.prop2][props.prop] = props[fNew - firstKeyFr];
                            } else {
                                while (keyFrm < numKeyFr && fNew >= sprite.keyFrames[keyFrm]) keyFrm++;
                                if (firstTime || fNew == sprite.keyFrames[keyFrm - 1]) {
                                    if (props.prop2 == null) sprite.obj[props.prop] = props[keyFrm - 1];
                                    else sprite.obj[props.prop2][props.prop] = props[keyFrm - 1];
                                }
                            }
                        }
                    }
                }
            } else if (sprite.charAt(0) == 'b' && fNew == sprite.frame) eval(sprite.value);
            if (fNew > tmLn.lastFrame) tmLn.ID = 0;
        }
    }
}

function MM_timelineGoto(tmLnName, fNew, numGotos) { //v2.0
    //Copyright 1997, 2000 Macromedia, Inc. All rights reserved.
    var i, j, tmLn, props, keyFrm, sprite, numKeyFr, firstKeyFr, lastKeyFr, propNum, theObj;
    if (document.MM_Time == null) MM_initTimelines(); //if *very* 1st time
    tmLn = document.MM_Time[tmLnName];
    if (numGotos != null)
        if (tmLn.gotoCount == null) tmLn.gotoCount = 1;
    else if (tmLn.gotoCount++ >= numGotos) { tmLn.gotoCount = 0; return }
    jmpFwd = (fNew > tmLn.curFrame);
    for (i = 0; i < tmLn.length; i++) {
        sprite = (jmpFwd) ? tmLn[i] : tmLn[(tmLn.length - 1) - i]; //count bkwds if jumping back
        if (sprite.charAt(0) == "s") {
            numKeyFr = sprite.keyFrames.length;
            firstKeyFr = sprite.keyFrames[0];
            lastKeyFr = sprite.keyFrames[numKeyFr - 1];
            if ((jmpFwd && fNew < firstKeyFr) || (!jmpFwd && lastKeyFr < fNew)) continue; //skip if untouchd
            for (keyFrm = 1; keyFrm < numKeyFr && fNew >= sprite.keyFrames[keyFrm]; keyFrm++);
            for (j = 0; j < sprite.values.length; j++) {
                props = sprite.values[j];
                if (numKeyFr == props.length) propNum = keyFrm - 1 //keyframes only
                else propNum = Math.min(Math.max(0, fNew - firstKeyFr), props.length - 1); //or keep in legal range
                if (sprite.obj != null) {
                    if (props.prop2 == null) sprite.obj[props.prop] = props[propNum];
                    else sprite.obj[props.prop2][props.prop] = props[propNum];
                }
            }
        } else if (sprite.charAt(0) == 'b' && fNew == sprite.frame) eval(sprite.value);
    }
    tmLn.curFrame = fNew;
    if (tmLn.ID == 0) eval('MM_timelinePlay(tmLnName)');
}

function MM_initTimelines() { //v4.0
    //MM_initTimelines() Copyright 1997 Macromedia, Inc. All rights reserved.
    var ns = navigator.appName == "Netscape";
    var ns4 = (ns && parseInt(navigator.appVersion) == 4);
    var ns5 = (ns && parseInt(navigator.appVersion) > 4);
    document.MM_Time = new Array(1);
    document.MM_Time[0] = new Array(1);
    document.MM_Time["Timeline1"] = document.MM_Time[0];
    document.MM_Time[0].MM_Name = "Timeline1";
    document.MM_Time[0].fps = 15;
    document.MM_Time[0][0] = new String("sprite");
    document.MM_Time[0][0].slot = 1;
    if (ns4)
        document.MM_Time[0][0].obj = document["Layer2"];
    else if (ns5)
        document.MM_Time[0][0].obj = document.getElementById("Layer2");
    else
        document.MM_Time[0][0].obj = document.all ? document.all["Layer2"] : null;
    document.MM_Time[0][0].keyFrames = new Array(1, 45);
    document.MM_Time[0][0].values = new Array(4);
    if (ns5)
        document.MM_Time[0][0].values[0] = new Array("625px", "614px", "604px", "593px", "583px", "572px", "562px", "551px", "541px", "530px", "520px", "509px", "498px", "488px", "477px", "467px", "456px", "446px", "435px", "425px", "414px", "404px", "393px", "382px", "372px", "361px", "351px", "340px", "330px", "319px", "309px", "298px", "288px", "277px", "266px", "256px", "245px", "235px", "224px", "214px", "203px", "193px", "182px", "172px", "161px");
    else
        document.MM_Time[0][0].values[0] = new Array(625, 614, 604, 593, 583, 572, 562, 551, 541, 530, 520, 509, 498, 488, 477, 467, 456, 446, 435, 425, 414, 404, 393, 382, 372, 361, 351, 340, 330, 319, 309, 298, 288, 277, 266, 256, 245, 235, 224, 214, 203, 193, 182, 172, 161);
    document.MM_Time[0][0].values[0].prop = "left";
    if (ns5)
        document.MM_Time[0][0].values[1] = new Array("121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px");
    else
        document.MM_Time[0][0].values[1] = new Array(121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121);
    document.MM_Time[0][0].values[1].prop = "top";
    if (!ns4) {
        document.MM_Time[0][0].values[0].prop2 = "style";
        document.MM_Time[0][0].values[1].prop2 = "style";
    }
    document.MM_Time[0][0].values[2] = new Array("hidden", "visible");
    document.MM_Time[0][0].values[2].prop = "visibility";
    if (!ns4)
        document.MM_Time[0][0].values[2].prop2 = "style";
    document.MM_Time[0][0].values[3] = new Array("1", "1");
    document.MM_Time[0][0].values[3].prop = "zIndex";
    if (!ns4)
        document.MM_Time[0][0].values[3].prop2 = "style";
    document.MM_Time[0].lastFrame = 45;
    for (i = 0; i < document.MM_Time.length; i++) {
        document.MM_Time[i].ID = null;
        document.MM_Time[i].curFrame = 0;
        document.MM_Time[i].delay = 1000 / document.MM_Time[i].fps;
    }
}

//-------- menu ---------
function initialiseMenu(menutype) {
    if (menutype == 'True') {
        document.visibleMenu = null;
        document.checkMenuTimer = null;
        document.closeMenuTimer = null;
        var menu = document.getElementById("header-nav");
        if (menu == null) menu = document.getElementById("mainmenu");
        if (menu != null) {
            var objLICollection = menu.getElementsByTagName("LI");
            for (var i = 0; i < objLICollection.length; i++) {

                var objLI = objLICollection[i];

                if (objLI.className == "rootitem") {
                    processNodes(objLI);
                }
            }
            objLICollection = menu.getElementsByTagName("TD");
            for (var i = 0; i < objLICollection.length; i++) {

                var objLI = objLICollection[i];

                if (objLI.className == "rootitem") {
                    processNodes(objLI);
                }
            }
            objLICollection = menu.getElementsByTagName("LI");
            for (var i = 0; i < objLICollection.length; i++) {
                var objLI = objLICollection[i];

                if (objLI.className == "menuitem") {
                    processNodes(objLI);
                }
            }
        }
    }
    else {
        //nothing required
    }
}

function initialiseAdminMenu(menutype) {
    if (menutype == 'True') {
        document.visibleMenu = null;
        document.checkMenuTimer = null;
        document.closeMenuTimer = null;
        var menu = document.getElementById("adminmainmenu");
        if (menu != null) {
            var objLICollection = menu.getElementsByTagName("TD");
            for (var i = 0; i < objLICollection.length; i++) {
                var objLI = objLICollection[i];

                if (objLI.childNodes.length > 0 && objLI.childNodes[0].tagName.toLowerCase() == 'div')
                    objLI = objLI.childNodes[0];

                processNodes(objLI);
            }
            objLICollection = menu.getElementsByTagName("LI");
            for (var i = 0; i < objLICollection.length; i++) {
                var objLI = objLICollection[i];
                processNodes(objLI);
            }
        }
    }
    else {
        //nothing required
    }
}

function processNodes(objLI) {
    objLI.onmouseover = hideSubMenu;

    objLI.onmouseout = menuLostFocus;

    var subMenus = objLI.getElementsByTagName("UL");
    for (var j = 0; j < subMenus.length; j++) {
        var child = subMenus.item(j);
        if (child.nodeName == "UL") {
            objLI.onmouseover = showSubMenu;
            objLI.onmouseout = menuLostFocus;
            if (objLI.className != "rootitem") {
                for (var k = 0; k < objLI.childNodes.length; k++) {
                    var link = objLI.childNodes.item(k);
                    if (link.nodeName == "A") {
                        link.style.backgroundImage = "url(/wmsimages/arrows.gif)";
                        link.style.backgroundRepeat = "no-repeat";
                        link.style.backgroundPosition = "140px center"; //controls postition of arrow
                        link.style.paddingRight = "12px";
                    }
                }
            }
            child.onmouseover = menuGotFocus;
        }
    }
}

function menuGotFocus() {
    resetCloseTimer();
}

function menuLostFocus() {
    startCloseTimer();
}

function startCloseTimer() {
    resetCloseTimer();
    document.closeMenuTimer = window.setInterval("hideAllMenus()", 500);
}

function resetCloseTimer() {
    if (document.closeMenuTimer != null) {
        window.clearInterval(document.closeMenuTimer);
    }
}

function showSubMenu() {
    showSubMenuCore(this);
}

function isChild(parent, child) {
    var par = child;
    while (par != null) {
        if (parent == par) {
            return true;
        }
        par = par.parentNode;
    }
    return false;
}

function showSubMenuCore(objThis) {

    if (objThis.className == "rootitem") {
        // objThis.style.backgroundImage="url(images/rollover.gif)";
    }
    resetCloseTimer();
    if (document.visibleMenu != null) {
        if (document.visibleMenu.owner == objThis | isChild(objThis, document.visibleMenu.owner)) {
            return;
        }
        else {
            if (!isChild(document.visibleMenu.owner, objThis)) {
                if (objThis.className == "rootitem") {
                    hideMenuCore(document.visibleMenu, true);
                }
                else {
                    hideMenuCore(document.visibleMenu, false);
                }
            }
        }
    }
    for (var i = 0; i < objThis.childNodes.length; i++) {
        var menu = objThis.childNodes.item(i);
        if (menu.nodeName == "UL") {
            var style = menu.style;
            style.display = "block";
            if (objThis.className == "rootitem") {
                //style.left = getAbsoluteLeft(objThis) + "px"; //controls the x offset of the rollouts
                //style.top = (getAbsoluteTop(objThis) + objThis.offsetHeight) + "px";
            }
            else {
                //style.left = objThis.offsetWidth + "px";
                //style.top = (objThis.offsetTop -1) + "px";
            }
            menu.parentMenu = document.visibleMenu;
            document.visibleMenu = menu;
            document.visibleMenu.has_focus = 1;
            menu.owner = objThis;
            if (document.checkMenuTimer != null) {
                window.clearInterval(document.checkMenuTimer);
                document.checkMenuTimer = null;
            }
            document.checkMenuTimer = window.setInterval("checkMenu()", 3000);

            resetCloseTimer();
            break;
        }
    }
}

function checkMenu() {
    if (document.visibleMenu != null) {
        if (!(document.visibleMenu.has_focus == 1)) {
            hideMenuCore(document.visibleMenu, true);
        }
    }
}

function hideAllMenus() {
    resetCloseTimer();
    hideMenuCore(document.visibleMenu, true);
}

function hideSubMenu() {
    hideMenuCore(document.visibleMenu, false);
}


function hideMenuCore(menu, hideAll) {
    if (hideAll & document.checkMenuTimer != null) {
        window.clearInterval(document.checkMenuTimer);
        document.checkMenuTimer = null;
    }
    if (hideAll) {
        var p = menu;
        while (p != null) {
            if (p.className == "rootitem") {
                // p.style.backgroundImage="url(images/button.gif)";
                break;
            }
            p = p.parentNode;
        }
        while (menu != null) {
            menu.style.display = "none";
            menu = getParentMenu(menu);
        }
        document.visibleMenu = null;
    }
    else {
        if (menu != null) {
            if (menu.className == "rootitem") {
                // menu.style.backgroundImage="url(images/button.gif)";
            }
            menu.style.display = "none";
            document.visibleMenu = menu.parentMenu;
        }
    }
}

function getParentMenu(menu) {
    var element = menu.parentNode;
    while (element != null) {
        if (element.className == "rootitem") {
            return null;
        }
        if (element.nodeName == "UL") {
            return element;
        }
        element = element.parentNode;
    }
    return null;
}

function getAbsoluteLeft(element) {
    if (element == null) {
        return 0;
    }
    var pos;
    if (element.offsetParent == null) {
        pos = 0;
    }
    else {
        pos = 0; //element.offsetParent.clientLeft;
    }
    return pos + element.offsetLeft + getAbsoluteLeft(element.offsetParent);
}

function getAbsoluteTop(element) {
    if (element == null) {
        return 0;
    }
    var pos;
    if (element.offsetParent == null) {
        pos = 0;
    }
    else {
        pos = 0; //element.offsetParent.clientTop;
    }
    return pos + element.offsetTop + getAbsoluteTop(element.offsetParent);
}

function showStandard() {
    var layerToShow = document.getElementById("StandardPanel");
    var layerToHide = document.getElementById("AdvancedPanel");


    layerToShow.style.display = 'inline';
    layerToHide.style.display = 'none';
}


function showAdvanced() {
    var layerToShow = document.getElementById("AdvancedPanel");
    var layerToHide = document.getElementById("StandardPanel");


    layerToShow.style.display = 'inline';
    layerToHide.style.display = 'none';
}

function openNewWindow(sURL, sName, iWidth, iHeight, bResizable, bScrollbars) {
    var iTop = (screen.height - iHeight) / 2;
    var iLeft = (screen.width - iWidth) / 2;

    var sOptions = "toolbar=no";
    sOptions += ",width=" + iWidth;
    sOptions += ",height=" + iHeight;
    sOptions += ",resizable=" + (bResizable ? "yes" : "no");
    sOptions += ",scrollbars=" + (bScrollbars ? "yes" : "no");
    sOptions += ",left=" + iLeft;
    sOptions += ",top=" + iTop;

    var oWindow = window.open(sURL, sName, sOptions)
    oWindow.focus();

    return oWindow;
}

// --- upload images
function OpenImageUpload(ownerWindow, strImageElement, strElementName, strImageFolder, parameters, renameTo) {
    var oWindow = dialog("/components/imageuploader.aspx?ImageElement=" + strImageElement + "&ElementName=" + strElementName + "&ImageLocation=" + strImageFolder + "&parameters=" + parameters + "&renameTo=" + renameTo, 'UploadWindow', "width=320,height=200,resizable=0", false);
    /*var oWindow = openNewWindow("/components/imageuploader.aspx?ImageElement="+strImageElement+"&ElementName="+strElementName+"&ImageLocation="+strImageFolder+"&parameters="+parameters, 'UploadWindow', 300, 150, false, false);*/
    oWindow.mainWindow = ownerWindow;
    oWindow.opener = ownerWindow;
}
function cloneElement(elementID) {
    var imgIndex = document.imageUploadIndex;
    var element = document.getElementById(elementID);
    if (element != null) {
        var elements = document.getElementsByTagName(element.nodeName);
        for (var i = 0; i < elements.length; i++) {
            if (elementID != null && elementID != '' && elements[i].id == elementID) {
                element = elements[i];
                break;
            }
        }

        if (element != null) {
            if (imgIndex == null) {
                imgIndex = 0;
            }
            // the element to be cloned is hidden, 0 is reserved for it
            imgIndex++;
            var clone = cloneOne(element, imgIndex);
            element.parentNode.parentNode.appendChild(clone);
            document.imageUploadIndex = imgIndex;
            return clone;
        }
    }
    return null;
}
function cloneOne(element, index) {
    var clone = document.createElement(element.nodeName);
    var oldText = "btnDeleteImage')";
    var oldText2 = "btnDeleteImage|productImage|0')";
    var newText = "btnDeleteImage|productImage|" + index + "')";
    var newHtml = element.innerHTML.replace(oldText, newText).replace(oldText, newText).replace(oldText2, newText).replace(oldText2, newText);
    clone.innerHTML = newHtml;
    clone.controlIndex = index;
    var oAttrColl = element.attributes;
    for (i = 0; i < oAttrColl.length; i++) {
        oAttr = oAttrColl.item(i);
        bSpecified = oAttr.specified;
        sName = oAttr.nodeName;
        vValue = oAttr.nodeValue;
        if (bSpecified) {
            clone.setAttribute(sName, vValue);
        }
    }
    clone.style.cssText = element.style.cssText;
    clone.style.display = 'block';

    return clone;
}
function setImage(file, imageUrl, elementID, imageElementID, parameters) {
    // parameters: width|height|delete_image_button_id|index_if_multiple_controls_used
    var width = null;
    var height = null;
    var deleteBtnID = null;
    var controlIndex = null;
    var parentID = null;
    if ($('#ImageNames').length > 0) {
        var existingImage = $('#' + elementID).val();
        existingImage = existingImage.replace(/&ticks=.+/, "");
        $('#ImageNames').val($('#ImageNames').val().replace(',' + existingImage, ''));
        $('#ImageNames').val($('#ImageNames').val().replace(existingImage, ''));
        alert('removed' + existingImage);
        alert($('#ImageNames').val());
    }

    if (parameters != null) {
        var tmp = parameters.split("|");
        if (tmp.length > 0) {
            width = tmp[0];
        }
        if (tmp.length > 1) {
            height = tmp[1];
        }
        if (tmp.length > 2) {
            deleteBtnID = tmp[2];
        }
        if (tmp.length > 3) {
            parentID = tmp[3];
        }
        if (tmp.length > 4) {
            controlIndex = tmp[4];
            controlIndex = parseInt(controlIndex);
        }
    }

    var root;
    if (parentID == null || parentID == '' || controlIndex != null) {
        root = document;
    }
    else {
        root = document.getElementById(parentID);
    }

    var elements;
    var fields = new Array();
    var btns = new Array();
    var index = 0;
    elements = root.getElementsByTagName('input');
    for (var i = 0; i < elements.length; i++) {
        if (elementID != null && elementID != '' && elements[i].id == elementID) {
            fields[index] = elements[i];
            index++;
        }
    }
    index = 0;
    for (var i = 0; i < elements.length; i++) {
        if (deleteBtnID != null && deleteBtnID != '' && elements[i].id == deleteBtnID) {
            btns[index] = elements[i];
            index++;
        }
    }
    elements = root.getElementsByTagName('img');
    var images = new Array();
    index = 0;
    for (var i = 0; i < elements.length; i++) {
        if (imageElementID != null && imageElementID != '' && elements[i].id == imageElementID) {
            images[index] = elements[i];
            index++;
        }
    }

    var objelement = null;
    var objimageElement = null;
    var deleteBtn = null;
    if (controlIndex != null) {
        if (fields.length > controlIndex) {
            objelement = fields[controlIndex];
        }
        if (images.length > controlIndex) {
            objimageElement = images[controlIndex];
        }
        if (btns.length > controlIndex) {
            deleteBtn = btns[controlIndex];
        }
    }
    else {
        if (fields.length > 0) {
            objelement = fields[0];
        }
        if (images.length > 0) {
            objimageElement = images[0];
        }
        if (btns.length > 0) {
            deleteBtn = btns[0];
        }
    }

    if (objelement == null) objelement = document.getElementById(elementID);
    if (objelement != null) {
        objelement.value = file;
    }
    if (objimageElement == null) objimageElement = document.getElementById(imageElementID);
    if (objimageElement != null) {
        objimageElement.src = imageUrl + "?_r!=" + Math.random();
    }
    if (deleteBtn != null) {
        deleteBtn.disabled = file == null || file == '';
    }
    /*if (objimageElement != null)
    {
    if (objimageElement.onimagechanged != null) 
    {
    objimageElement.parentNode.onimagechanged(objimageElement, true, controlIndex);
    }
    }*/
    if (parentID != null && parentID != '') {
        var pr = document.getElementById(parentID);
        if (pr != null && pr.onimagechanged != null) {
            pr.onimagechanged(pr, true, controlIndex);
        }
    }
}
function OpenImageUploadPublic(strImageSrcName, strElementName, strImagePath, strProdID) {
    var oWindow = openNewWindow("/imageUpload.aspx?imageLocation=" + strImagePath + "&ElementName=" + strElementName + "&ImagePath=" + strImageSrcName + "&prodID=" + strProdID + "&serial=3r8g89a2d-gjmvb98jf", 'UploadWindow2', 300, 150, false, false);
}

// --------- for textarea control --------
// Keep user from entering more than maxLength characters
function doKeypress(control) {
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
    if (maxLength && value.length > maxLength - 1) {
        event.returnValue = false;
        maxLength = parseInt(maxLength);
    }
}
// Cancel default behavior
function doBeforePaste(control) {
    maxLength = control.attributes["maxLength"].value;
    if (maxLength) {
        event.returnValue = false;
    }
}
// Cancel default behavior and create a new paste routine
function doPaste(control) {
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
    if (maxLength) {
//        event.returnValue = false;
//        maxLength = parseInt(maxLength);
//        var oTR = control.document.selection.createRange();
//        var iInsertLength = maxLength - value.length + oTR.text.length;
//        var sData = window.clipboardData.getData("Text").substr(0, iInsertLength);
//        oTR.text = sData;
    }
}
function ValidContent() {
    if (MyReplace(document.form1.frmtitle.value, ' ', '') == '') {
        alert('You must provide a title for this content');
        document.form1.frmtitle.focus();
        return false;
    }
    else {
        showLoad();
        document.form1.action = '';
        document.form1.target = '';

        return true;
    }
}
// -------- end textarea ----------

// -------- modal window ----------
String.prototype.isArgument = function() {
    return /^([a-zA-Z]){1,}=([0-9]){1,}$/.test(this);
}

/*
call this function just work like window.open(url,name,feature);
however, for IE5.0+, it will open a showModelessDialog window;
and For Gecko(Mozilla or Netscape), the child window will stay on top focus untill user close it.
programmed by hedger
hedger@yahoo-inc.com
*/

function dialog(url, name, feature, isModal) {
    if (url == null) { return false; }
    url = url
    if (name == null) { name = "" }
    if (feature == null) { feature = "" };
    if (window.showModelessDialog) {
        var WindowFeature = new Object();
        WindowFeature["width"] = 400;
        WindowFeature["height"] = 400;
        WindowFeature["left"] = "";
        WindowFeature["top"] = "";
        WindowFeature["resizable"] = "";

        if (feature != null && feature != "") {
            feature = (feature.toLowerCase()).split(",");

            for (var i = 0; i < feature.length; i++) {
                if (feature[i].isArgument()) {
                    var featureName = feature[i].split("=")[0];
                    var featureValue = feature[i].split("=")[1];

                    if (WindowFeature[featureName] != null) { WindowFeature[featureName] = featureValue; }
                }
            }
        }

        if (WindowFeature["resizable"] == 1 || WindowFeature["resizable"] == "1" || WindowFeature["resizable"].toString().toLowerCase() == "yes") { WindowFeature["resizable"] = "resizable:1;minimize:1;maximize:1;" }
        if (WindowFeature["left"] != "") { WindowFeature["left"] = "dialogLeft:" + WindowFeature["left"] + "px;"; }
        if (WindowFeature["top"] != "") { WindowFeature["top"] = "dialogTop:" + WindowFeature["Top"] + "px;"; }
        if (window.ModelessDialog == null) { window.ModelessDialog = new Object(); };
        if (name != "") {
            if (window.ModelessDialog[name] != null && !window.ModelessDialog[name].closed) {
                window.ModelessDialog[name].focus();
                return window.ModelessDialog[name];
            }
        }
        var F = WindowFeature["left"] + WindowFeature["top"] + "dialogWidth:" + WindowFeature["width"] + " px;dialogHeight:" + WindowFeature["height"] + "px;center:1;help:0;" + WindowFeature["resizable"] + "status:0;unadorned:0;edge: raised; ;border:thick;"
        if (isModal) {
            window.showModalDialog(url, self, F);
            return false;
        }
        else {
            window.ModelessDialog[name] = window.showModelessDialog(url, self, F);
            return window.ModelessDialog[name];
        }
    }
    else {
        if (document.getBoxObjectFor) {


            if (isModal) {
                var Modal = window.open(url, name, "modal=1," + feature);
                var ModalFocus = function() {
                    if (!Modal.closed) { Modal.focus(); }
                    else { Modal = null; window.removeEventListener(ModalFocus, "focus"); ModalFocus = null; };
                }
                window.addEventListener("focus", ModalFocus, false);
                return false;
            }
            else {
                return window.open(url, name, "modal=1," + feature);
            }
        }
        else {
            return window.open(url, name, feature);
        }
        //
    }
    return null;
}

function modal(url, feature) {
    dialog(url, "", feature, true);
    return false;
}
//-------- end ------------

function PopulateForm(arrElements) {
    PopulateForm2(arrElements, true);
}

function PopulateForm2(arrElements, loadChildren) {
    for (i = 0; i < arrElements.length; i++) {
        //index of js arrays not always sequential
        if (arrElements[i] != null) {
            var elementObj = document.getElementById(arrElements[i][0]);
            if (elementObj != null) {
                if (elementObj.nodeName.toUpperCase() == "INPUT" && elementObj.type.toUpperCase() == "RADIO") {
                    elementObj.checked = elementObj.value == arrElements[i][1];
                }
                else if (elementObj.nodeName.toUpperCase() == "INPUT" && elementObj.type.toUpperCase() == "CHECKBOX") {
                    elementObj.checked = arrElements[i][1].toUpperCase() == "TRUE";
                }
                else if (elementObj.nodeName.toUpperCase() == "INPUT" && elementObj.type.toUpperCase() == "HIDDEN") {
                    elementObj.value = arrElements[i][1];
                    var img = document.getElementById(arrElements[i][0] + '_src');
                    if (img != null) {
                        if (arrElements[i][1] == null || arrElements[i][1] == '') {
                            img.src = '/wmsimages/no_image_supplied.jpg';
                        }
                        else {
                            img.src = arrElements[i][1];
                        }
                    }
                }
                else {
                    elementObj.value = arrElements[i][1];
                }
                if (loadChildren && elementObj.onchange != null) {
                    elementObj.onchange();
                    elementObj.upldateCallback = function(element) {
                        element.upldateCallback = null;
                        PopulateForm2(arrElements, false);
                    }
                }
                if (arrElements[i][2] == 'False') {
                    elementObj.disabled = true;
                    elementObj.Title = "Editing this field is not allowed.";
                }
            }
        }
    }
}

// ------------------
function trackChanges(parentTable, change, childTable, update) {
    if (change != null && update != null) {
        var prev = change.onchange;
        change.onchange = function() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open('POST', '/options.aspx', true);
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 || xmlhttp.readyState == "complete") {
                    if (xmlhttp.status == 200) {
                        updateOptions(xmlhttp.responseXML, update);
                    }
                    if (change.upldateCallback != null) {
                        change.upldateCallback(change);
                    }
                }
            }
            xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            var data = 'table=' + childTable + '&parentTable=' + parentTable + '&parentValue=' + change.value;
            xmlhttp.send(data);
            if (prev != null) {
                prev();
            }
        }
    }
}

function updateOptions(xml, el) {
    var special = null;
    if (el.options.length > 0 && (el.options[0].value == null || el.options[0].value == "")) {
        special = el.options[0];
    }
    el.innerHTML = "";
    while (el.options.length > 0) {
        el.remove(0);
    }
    if (special != null) {
        el.options.add(special);
    }
    var opts = xml.getElementsByTagName("option");
    for (var j = 0; j < opts.length; j++) {
        var option = document.createElement("OPTION");
        el.options.add(option);
        if (opts[j].firstChild == null) {
            option.appendChild(document.createTextNode(opts[j].text));
            option.value = opts[j].getAttribute("value");
        }
        else {
            option.appendChild(document.createTextNode(opts[j].firstChild.nodeValue));
            option.value = opts[j].getAttribute("value");
        }
    }
    if (el.onchange != null) {
        el.onchange();
    }
}

//Old form validation function

//function CheckRequiredFields(formObject) {
//    var missingFields = _CheckRequiredFields_Recurse(formObject);

//    if (missingFields && missingFields != "") {
//        missingFields = "The following fields are required:\r\n\r\n" + missingFields;

//        alert(missingFields);

//        return false;
//    }

//    return true;
//}

function CheckRequiredFields(formObject) {

    var isValid = true;

    //The main validation check
    var missingFields = _CheckRequiredFields_Recurse(formObject);

    if (missingFields && missingFields != "") {
        missingFields = "The following fields are required:\r\n\r\n" + missingFields;

        alert(missingFields);

        isValid = false;
    }

    //Validate the file input (less than 5 files at a time)
    if (document.getElementById("290_FileUpload") != null) {
        var fileInput = document.getElementById("290_FileUpload");

        if (fileInput.files.length > 5) {
            alert("You may only upload up to 5 images");
            isValid = false;
        }
    }

    //Validation code goes here, set isValid to false if your validation code detects incorrect form data

    //if (isValid)
    //{
    //    //If the form is valid, disable the button to prevent it from clicked more than once
    //    document.getElementById("contact_us_enq_submit").disabled = "true";
    //    document.getElementById("contact_us_enq_submit").value = "Please wait";
    //}

    return isValid;
}
//End of modified code for file upload form validation

function _CheckRequiredFields_Recurse(element) {
    var missingFields = "";

    for (var i = 0; i < element.childNodes.length; i++) {
        var childNode = element.childNodes[i];

        if (childNode.tagName && childNode.getAttribute("required") && childNode.getAttribute("required").toLowerCase() == "true") {
            var tagName = childNode.tagName.toLowerCase();

            if (tagName == "input") {
                if (childNode.type == "text") {
                    if (childNode.value == "")
                        missingFields += (missingFields == "" ? "" : "\r\n") + _CheckRequiredFields_FormatFieldName(childNode.name);
                }
                else if (childNode.type == "radio") {
                }
                else if (childNode.type == "checkbox") {
                }
            }
            else if (tagName == "textarea") {
                if (childNode.value == "")
                    missingFields += (missingFields == "" ? "" : "\r\n") + _CheckRequiredFields_FormatFieldName(childNode.name);
            }
            else if (tagName == "select") {
                if (childNode.selectedIndex == -1 || childNode.options[childNode.selectedIndex].value == "")
                    missingFields += (missingFields == "" ? "" : "\r\n") + _CheckRequiredFields_FormatFieldName(childNode.name);
            }
        }

        var childMissingFields = _CheckRequiredFields_Recurse(childNode);

        if (childMissingFields && childMissingFields != "")
            missingFields += (missingFields == "" ? "" : "\r\n") + childMissingFields;
    }

    return missingFields;
}

function _CheckRequiredFields_FormatFieldName(fieldName) {
    if (fieldName.match(/[0-9]+?_/))
        return fieldName.substring(fieldName.indexOf("_") + 1);

    return fieldName;
}




function Delegate(Instance, Method) {
    return function() {
        return Method.apply(Instance, arguments);
    }
}

function SetOpacity(Object, Percentage) {
    Object.style.filter = "alpha(opacity=" + Percentage + ")";
    Object.style.opacity = Percentage / 100;

    Object._Opacity = Percentage;
}

function FadeElement(element, start, stop, duration, callback) {
    var speed = Math.round(duration / 100);
    var opacity = start;

    if (start < stop) {
        for (var i = start, timer = 0; i <= stop; i++, timer++) {
            setTimeout(new Delegate(element, function() {
                SetOpacity(this, opacity);

                opacity++;
            }), (timer * speed));
        }
    }
    else {
        for (var i = start, timer = 0; i >= stop; i--, timer++) {
            setTimeout(new Delegate(element, function() {
                SetOpacity(this, opacity);

                opacity--;
            }), (timer * speed));
        }
    }

    if (callback)
        setTimeout(callback, duration);
}
// bubs
function updateProducts(items) {
    for (var i = 0; i < items.length; i++) {
        var sel = getElementsById("prodColour", "SELECT", items[i]);
        if (sel != null && sel.length > 0) {
            updateProduct(sel[0]);
        }
    }
}

function FindParent(parentID, child) {
    var current = child;
    while (current != null) {
        if (current.id == parentID) {
            return current;
        }
        current = current.parentNode;
    }
    return null;
}

function updateProduct(sel) {
    var item = FindParent("prodItem", sel);
    var data = sel.value.split('|');
    var el;
    var ProductUniqueCode;
   
    var ProductID = data[0];
    $('#itemNo').val(ProductID);

    var CodeData = data[1];
    $('#displayCode').html("Code: " + CodeData);

    var PriceData = data[2];
    $('#displayPrice').html(PriceData);      

    el = getElementsById("divSpecialText", "DIV", item);
    if (el.style != null) {
        if (data[5] == "") {
            el[0].style.display = "none";
        }
        else {
            el[0].style.display = "block";
            el[0].innerHTML = data[5];
        }
    }
    el = getElementsById("DiscontinuedCount", "SPAN", item);
    if (el != null) {
        for (var i = 0; i < el.length; i++) {
            el[i].innerHTML = data[6];
        }
    }
    	el = getElementsById("prodImgDiv", "DIV", item);
    //el = getElementsById("prodImgTD", "SPAN", item);
    for (var i = 0; i < el.length; i++) {
        if (data[3] == null || data[3] == '') {
            el[i].style.display = "none";
        }
        else {
            el[i].style.display = "";
            var imgs = getElementsById("prodImg", "IMG", item);
            for (var j = 0; j < imgs.length; j++) {
                var start = imgs[j].src.indexOf("src=");
                var end = imgs[j].src.indexOf("&", start);
                //imgs[j].src = imgs[j].src.substring(0, start + 4) + data[3] + imgs[j].src.substring(end);
                imgs[j].src = "/pi/" + encodeURIComponent(data[4].replace(/[\.\%\&\*\|\\\:\/\<\>\?]/g, " ")).replace(/\%20/g, "+") + "@" + data[3].replace(".jpg", "") + "@300x275.jpg";
            }

            var lblinks = getElementsById("prodImgLightboxLink", "A", item);
            for (var g = 0; g < lblinks.length; g++) {
                //lblinks[g].attributes["href"].value = "/adm/watermark.aspx?src=" + data[3] + "&bgcolor=ffffff&width=240&height=180";
                lblinks[g].attributes["href"].value = "/pi/" + encodeURIComponent(data[4].replace(/[\.\%\&\*\|\\\:\/\<\>\?]/g, " ")).replace(/\%20/g, "+") + "@" + data[3].replace(".jpg", "") + ".jpg";
                //alert(lblinks[g].outerHTML);
            }

            //			var links = getElementsById("enlargedphoto", "A", item);
            //			for (var j = 0; j < links.length; j++)
            //			{
            //				links[j].onclick = function(){
            //				window.open('/adm/thumbnailer.aspx?src=/prodimg/' + ProductUniqueCode + '.jpg&width=400&height=500&bgcolor=ffffff','Product_' + ProductUniqueCode ,'width=440,height=550,toolbars=false,resizable=yes');
            //				}
            //			}
        }
    }

    el = getElementsById("TheProductName", "SPAN", item);
    for (var i = 0; i < el.length; i++) {
        el[i].innerHTML = data[4];
    }

    el = getElementsById("TheTellAFriendLink", "A", item)
    {
        for (var j = 0; j < el.length; j++) {
            el[j].onclick = function() {
                showTellFriend(data[0], '"' + data[4] + '"'); return false;
            }
        }
    }

    el = document.getElementById("addtocart");
    if (el != null) {
        el.style.display = (data[7] == "True" ? "none" : "");
    }
    //Hide out of stock message
    el = document.getElementById("OSM");
    if (el != null) el.style.display = (data[7] == "True" ? "" : "none");

    el = document.getElementById("p_message");
    if (el != null) {
        el.innerHTML = data[8];
        if (data[7] == "True") {

            el.innerHTML += "<BR><span style='clear: both; color: rgb(255, 0, 0); display: block; font-size: 11px; font-weight: bold; line-height: 12px;'>This product is currently on backorder.</span>";
        }
    }
}

function updateProductMobile(sel) {
    var item = FindParent("prodItem", sel);
    var data = sel.value.split('|');
    var el;
    var ProductUniqueCode;
    el = getElementsById("itemNo", "INPUT", item);
    for (var i = 0; i < el.length; i++) {
        el[i].value = data[0];
    }

    el = getElementsById("prodUniqueCode", "SPAN", item);
    for (var i = 0; i < el.length; i++) {
        el[i].innerHTML = "Code: " + data[1];
        ProductUniqueCode = data[1];
    }

    el = getElementsById("prodPrice", "STRONG", item);
    for (var i = 0; i < el.length; i++) {
        //        el[i].innerHTML = "RRP: " + data[2];
        el[i].innerHTML = data[2];
    }

    el = getElementsById("prodRRP", "SPAN", item);
    for (var i = 0; i < el.length; i++) {
        //        el[i].innerHTML = "RRP: " + data[2];
        el[i].innerHTML = data[9];
    }

    el = getElementsById("prodSaving", "STRONG", item);
    for (var i = 0; i < el.length; i++) {
        //        el[i].innerHTML = "RRP: " + data[2];
        el[i].innerHTML = data[10];
    }

    el = getElementsById("divSpecialText", "DIV", item);
    if (data[5] == "") {
        el[0].style.display = "none";
    }
    else {
        el[0].style.display = "block";
        el[0].innerHTML = data[5];
    }

    el = getElementsById("DiscontinuedCount", "SPAN", item);
    for (var i = 0; i < el.length; i++) {
        el[i].innerHTML = data[6];
    }

    el = getElementsById("prodImg", "IMG", item);
    for (var i = 0; i < el.length; i++) {
        var start = el[i].src.indexOf("src=");
        var end = el[i].src.indexOf("&", start);

        //el[i].src = el[i].src.substring(0, start + 4) + data[3] + el[i].src.substring(end);
        el[i].src = "/pi/" + encodeURIComponent(data[4].replace(/[\.\%\&\*\|\\\:\/\<\>\?]/g, " ")).replace(/\%20/g, "+") + "@" + data[3].replace(".jpg", "") + "@240x180.jpg";
    }

    el = getElementsById("prodImgLightboxLink", "A", item);
    for (var i = 0; i < el.length; i++) {
        //el[i].attributes["href"].value = "/adm/watermark.aspx?src=" + data[3] + "&bgcolor=FFFFFF&width=-1&height=-1";
        el[i].attributes["href"].value = "/pi/" + encodeURIComponent(data[4].replace(/[\.\%\&\*\|\\\:\/\<\>\?]/g, " ")).replace(/\%20/g, "+") + "@" + data[3].replace(".jpg", "") + ".jpg";
    }

    el = getElementsById("TheProductName", "SPAN", item);
    for (var i = 0; i < el.length; i++) {
        el[i].innerHTML = data[4];
    }

    el = document.getElementById("addtocart");
    el.style.display = (data[7] == "True" ? "none" : "");

    el = document.getElementById("p_message");
    el.innerHTML = data[8];
}

function getElementsById(id, nodeName, parent) {
    var ret = new Array();
    var index = 0;
    var nodes;
    if (parent == null) {
        nodes = document.getElementsByTagName(nodeName);
    }
    else {
        nodes = parent.getElementsByTagName(nodeName);
    }
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].id == id) {
            ret[index] = nodes[i];
            index++;
        }
    }
    return ret;
}

function getElementsByTag(nodeName, parent) {
    var ret = new Array();
    var index = 0;
    var nodes;
    if (parent == null) {
        nodes = document.getElementsByTagName(nodeName);
    }
    else {
        nodes = parent.getElementsByTagName(nodeName);
    }
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].id == id) {
            ret[index] = nodes[i];
            index++;
        }
    }
    return ret;
}


function showTellFriend(link, name) {
    if (document.tellFriendEditor != null && document.tellFriendEditor.parentNode.nodeName.toUpperCase() == "BODY") {
        document.body.removeChild(document.tellFriendEditor);
        document.tellFriendEditor = null;
    }
    var html = "<table>";
    html += "<tr><td>Friend's name:</td><td align='right'><input type='text' id='recipientName' style='width: 300px;'></td></tr>";
    html += "<tr><td>Friend's email:</td><td align='right'><input type='text' id='recipientEmail' style='width: 300px;'></td></tr>";
    html += "<tr><td>Your name:</td><td align='right'><input type='text' id='senderName' style='width: 300px;'></td></tr>";
    html += "<tr><td>Your email:</td><td align='right'><input type='text' id='senderEmail' style='width: 300px;'></td></tr>";
    html += "<tr><td>Subject:</td><td align='right'><input type='text' id='msgSubject' style='width: 300px;'></td></tr>";
    html += "<tr><td colspan='2'>Your message<br><textarea id='msgBody' cols='60' rows='6'></textarea></td></tr>";
    html += "<input type='hidden' name='tafProductID' id='tafProductID' value='" + link + "'>";
    html += "<input type='hidden' name='tafProductName' id='tafProductName' value='" + name + "'>";
    html += "<tr><td colspan='2' align='center'><input type='button' id='btnSend' value='Send' onclick='tellFriend(this);'>&nbsp;&nbsp;&nbsp;<input type='button' id='btnCancel' value='Cancel' onclick='document.body.removeChild(document.tellFriendEditor); document.tellFriendEditor = null;'></td></tr>";
    html += "</table>";

    var el = document.createElement("div");
    el.innerHTML = html;
    el.style.cssText = "position: absolute; border: solid 2px #aaaaaa; left: 30%; top: " + (document.documentElement.scrollTop + 150) + "px; padding: 3px; background-color: #eeeeee; z-index: 500";
    document.body.appendChild(el);
    document.tellFriendEditor = el;
}

function showTellFriend2(link, name) {
    if (document.tellFriendEditor != null && document.tellFriendEditor.parentNode.nodeName.toUpperCase() == "BODY") {
        document.body.removeChild(document.tellFriendEditor);
        document.tellFriendEditor = null;
    }
    var html = "<table>";
    //html += "<tr><td>Friend's name:</td><td align='right'><input type='text' id='recipientName' style='width: 300px;'></td></tr>";
    html += "<tr><td>Friend's email:</td><td align='right'><input type='text' id='recipientEmail' style='width: 330px;'><br /><span style='font-size: 9px;'>NB: you can add multiple email addresses separated by a comma.</td></tr>";
    html += "<tr><td>Your name:</td><td align='right'><input type='text' id='senderName' style='width: 330px;'></td></tr>";
    html += "<tr><td>Your email:</td><td align='right'><input type='text' id='senderEmail' style='width: 330px;'></td></tr>";
    html += "<tr><td>Subject:</td><td align='right'><input type='text' id='msgSubject' style='width: 330px;'></td></tr>";
    html += "<tr><td colspan='2'>Your message<br><textarea id='msgBody' cols='60' rows='12'>Hi,\r\n\r\nI have started a gift registry at Babies Direct.\r\n\r\nClick this link to check it out:\r\n\r\n" + link + "\r\n\r\nSo far the list includes:\r\n" + name.replace(/~NEWLINE~/g, "\r\n") + "</textarea></td></tr>";
    html += "<tr><td colspan='2' align='center'><input type='button' id='btnSend' value='Send' onclick='tellFriend2(this);'>&nbsp;&nbsp;&nbsp;<input type='button' id='btnCancel' value='Cancel' onclick='document.body.removeChild(document.tellFriendEditor); document.tellFriendEditor = null;'></td></tr>";
    html += "</table>";

    var el = document.createElement("div");
    el.innerHTML = html;
    el.style.cssText = "position: absolute; border: solid 2px #aaaaaa; left: 30%; top: " + (document.documentElement.scrollTop + 150) + "px; padding: 3px; background-color: #eeeeee;";
    document.body.appendChild(el);
    document.tellFriendEditor = el;
}

function tellFriend(btn) {
    var val;
    val = document.getElementById("recipientName").value;
    if (val == null || val == '') {
        window.alert("Please enter your friend's name.");
        return;
    }
    var recipientName = escape(val);

    val = document.getElementById("recipientEmail").value;
    if (val == null || val == '') {
        window.alert("Please enter your friend's address.");
        return;
    }
    var recipientEmail = escape(val);

    val = document.getElementById("senderName").value;
    if (val == null || val == '') {
        window.alert("Please enter your name.");
        return;
    }
    var senderName = escape(val);

    val = document.getElementById("senderEmail").value;
    if (val == null || val == '') {
        window.alert("Please enter your address.");
        return;
    }
    var senderEmail = escape(val);

    val = document.getElementById("msgSubject").value;
    if (val == null || val == '') {
        window.alert("Please enter the subject.");
        return;
    }
    var msgSubject = escape(val);

    val = document.getElementById("msgBody").value;
    if (val == null || val == '') {
        window.alert("Please enter the message.");
        return;
    }
    var msgBody = escape(val);

    var tafProductID = escape(document.getElementById("tafProductID").value);
    var tafProductName = escape(document.getElementById("tafProductName").value);

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', '/tellfriend.aspx', true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 || xmlhttp.readyState == "complete") {
            if (xmlhttp.status == 200) {
                window.alert('Your message has been sent.');
                document.body.removeChild(document.tellFriendEditor);
                document.tellFriendEditor = null;
            }
            else {
                window.alert('An error occured.');
                btn.disabled = false;
            }
        }
    }
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var data = 'recipientName=' + recipientName + '&recipientEmail=' + recipientEmail + '&senderName=' + senderName + '&senderEmail=' + senderEmail + '&msgSubject=' + msgSubject + '&msgBody=' + msgBody + '&tafProductID=' + tafProductID + '&tafProductName=' + tafProductName;
    btn.disabled = true;
    xmlhttp.send(data);
}

function tellFriend2(btn) {
    var val;
    //val = document.getElementById("recipientName").value;
    //if (val == null || val == '')
    //{
    //	window.alert("Please enter your friend's name.");
    //	return;
    //}
    //var recipientName = escape(val);

    val = document.getElementById("recipientEmail").value;
    if (val == null || val == '') {
        window.alert("Please enter your friend's address.");
        return;
    }
    var recipientEmail = escape(val);

    val = document.getElementById("senderName").value;
    if (val == null || val == '') {
        window.alert("Please enter your name.");
        return;
    }
    var senderName = escape(val);

    val = document.getElementById("senderEmail").value;
    if (val == null || val == '') {
        window.alert("Please enter your address.");
        return;
    }
    var senderEmail = escape(val);

    val = document.getElementById("msgSubject").value;
    if (val == null || val == '') {
        window.alert("Please enter the subject.");
        return;
    }
    var msgSubject = escape(val);

    val = document.getElementById("msgBody").value;
    if (val == null || val == '') {
        window.alert("Please enter the message.");
        return;
    }
    var msgBody = escape(val);

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', '/tellfriend2.aspx', true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 || xmlhttp.readyState == "complete") {
            if (xmlhttp.status == 200) {
                window.alert('Your message has been sent.');
                document.body.removeChild(document.tellFriendEditor);
                document.tellFriendEditor = null;
            }
            else {
                window.alert('An error occured.');
                btn.disabled = false;
            }
        }
    }
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var data = 'recipientName=' + /*recipientName*/'' + '&recipientEmail=' + recipientEmail + '&senderName=' + senderName + '&senderEmail=' + senderEmail + '&msgSubject=' + msgSubject + '&msgBody=' + msgBody;
    btn.disabled = true;
    xmlhttp.send(data);
}
//function initialiseAdminMenu(menutype) {
//    if (menutype == 'True') {
//        document.visibleMenu = null;
//        document.checkMenuTimer = null;
//        document.closeMenuTimer = null;
//        var menu = document.getElementById("adminmainmenu");
//        if (menu != null) {
//            var objLICollection = menu.getElementsByTagName("TD");
//            for (var i = 0; i < objLICollection.length; i++) {
//                var objLI = objLICollection[i];
//                processNodes(objLI);
//            }
//            objLICollection = menu.getElementsByTagName("LI");
//            for (var i = 0; i < objLICollection.length; i++) {
//                var objLI = objLICollection[i];
//                processNodes(objLI);
//            }
//        }
//    }
//    else {
//        //nothing required
//    }
//}
////////////////////////////////////////AJAX BLOCK////////////////////////////////		

// XMLHttpRequest
//     FireFox and IE 7 have native XMLHttpRequest methods.
//     This function allows IE 6 and below to "work" the same way.
if (!window.XMLHttpRequest) {
    XMLHttpRequest = function() {
        try { return new ActiveXObject("MSXML3.XMLHTTP") } catch (ex) { }
        try { return new ActiveXObject("MSXML2.XMLHTTP.3.0") } catch (ex) { }
        try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (ex) { }
        try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (ex) { }
    }
}


// DoAjaxRequest
//     Sends an AJAX request, and calls "Callback" if successful.
//     "Callback" function is user-defined, and must have the following prototype:
//
//     function MyCallback(responseText) { ... }
//
//     Example usage:
//
//     function MyCallback(responseText) {
//         // do something with "responseText"
//     }
//
//     DoAjaxRequest("http://www.foobar.com/page.aspx", MyCallback);
function DoAjaxRequest(Address, Callback) {
    if (Address.indexOf("?") == -1)
        Address += "?r=";
    else
        Address += "&r=";

    for (var i = 0; i < 10; i++)
        Address += new String(Math.floor(Math.random() * 10));

    var Request = new XMLHttpRequest();

    Request.onreadystatechange = new Delegate(Request, function() {
        if (this.readyState == 4 && this.status == 200)
            Callback(this.responseText);
    });

    Request.open("GET", Address, true);

    Request.send(null);
}

////////////////////////////////////////END AJAX BLOCK////////////////////////////

//new checkout validation
function CheckTerms() {

}



function Delegate(Instance, Method) {
    return function() {
        return Method.apply(Instance, arguments);
    }
}

function SetOpacity(Object, Percentage) {
    Object.style.filter = "alpha(opacity=" + Percentage + ")";
    Object.style.opacity = Percentage / 100;

    Object._Opacity = Percentage;
}

function FadeElement(element, start, stop, duration, callback) {
    var speed = Math.round(duration / 100);
    var opacity = start;

    if (start < stop) {
        for (var i = start, timer = 0; i <= stop; i++, timer++) {
            setTimeout(new Delegate(element, function() {
                SetOpacity(this, opacity);

                opacity++;
            }), (timer * speed));
        }
    }
    else {
        for (var i = start, timer = 0; i >= stop; i--, timer++) {
            setTimeout(new Delegate(element, function() {
                SetOpacity(this, opacity);

                opacity--;
            }), (timer * speed));
        }
    }

    if (callback)
        setTimeout(callback, duration);
}

//hide slideshow if FF 2.x

if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
    var ffversion = new Number(RegExp.$1) // capture x.x portion and store as a number
    if (ffversion >= 3) {
        //document.write("You're using FF 3.x or above")
    }
    else if (ffversion >= 2) {
        //document.write("You're using FF 2.x")
        document.getElementById("BannerSlideShow").style.display = "none";
    }
    else if (ffversion >= 1) {
        //document.write("You're using FF 1.x")
    }
}
else {
    //document.write("n/a")
}

function txtPostCode_OnKeyUp() {
    if (window.__timeout != null)
        clearTimeout(window.__timeout);

    if (document.getElementById("txtPostCode").value.length < 3)
        return;

    window.__timeout = setTimeout(function() {
        document.getElementById("sidefreight_list").style.display = "";
        document.getElementById('sidefreight_list').innerHTML = "<img style=\"margin: 5px 10px;\" alt=\"\" src=\"/wmsimages/loading.gif\" />";

        DoAjaxRequest("/suburbs_list.aspx?txtPostCode=" + encodeURI(document.getElementById("txtPostCode").value), function(response) {
            var suburbs = eval(response);

            if (suburbs.length == 0) {
                document.getElementById('sidefreight_list').innerHTML = "<a class=\"suburb\" disabled=\"disabled\">No matching suburbs found</a>";
            }
            else {
                var output = "";

                for (var i = 0; i < suburbs.length - 1; i++) {
                    output += "<a class=\"suburb\" href=\"#\" onclick=\"SelectSuburb('" + suburbs[i].Postcode + "', '" + suburbs[i].Suburb + "'); void(0); return false;\">" + suburbs[i].Postcode + " - " + suburbs[i].Suburb + "</a>";
                }

                document.getElementById('sidefreight_list').innerHTML = output;
            }
        });
    }, 500);
}
function txtPostCodeProduct_OnKeyUp(pId) {
    if (window.__timeout != null)
        clearTimeout(window.__timeout);

    if (document.getElementById("txtPostCodeProduct").value.length < 3)
        return;

    window.__timeout = setTimeout(function() {
        document.getElementById("productshippingcost").style.display = "";
        document.getElementById('productshippingcost').innerHTML = "<img style=\"margin: 5px 10px;\" alt=\"\" src=\"/wmsimages/loading.gif\" />";

        DoAjaxRequest("/suburbs_list.aspx?txtPostCode=" + encodeURI(document.getElementById("txtPostCodeProduct").value), function(response) {
            var suburbs = eval(response);

            if (suburbs.length == 0) {
                document.getElementById('productshippingcost').innerHTML = "<a class=\"suburb\" disabled=\"disabled\">No matching suburbs found</a>";
            }
            else {
                var output = "";

                for (var i = 0; i < suburbs.length - 1; i++) {
                    output += "<a class=\"suburb\" href=\"#\" onclick=\"SelectSuburbProduct('" + suburbs[i].Postcode + "', '" + suburbs[i].Suburb + "','" + pId + "'); void(0); return false;\">" + suburbs[i].Postcode + " - " + suburbs[i].Suburb + "</a>";
                }

                document.getElementById('productshippingcost').innerHTML = output;
            }
        });
    }, 500);
}
function SelectSuburbProduct(postcode, suburb, pid) {
    document.getElementById("productshippingcost").innerHTML = "<img style=\"margin: 5px 10px;\" alt=\"\" src=\"/wmsimages/loading.gif\" />";

    DoAjaxRequest("/deliveryBoxProduct.aspx?txtPostCodeProduct=" + postcode + "&txtSuburb=" + suburb + "&pid=" + pid, function(response) {
        document.getElementById("deliveryBoxProduct").innerHTML = response;
        document.getElementById("productshippingcost").innerHTML = "";
    });

}
function txtPostCodeSingle_OnKeyUp(productId) {
    if (window.__timeout != null)
        clearTimeout(window.__timeout);

    if (document.getElementById("txtPostCodeSingle").value.length < 3)
        return;

    window.__timeout = setTimeout(function() {
        document.getElementById("sidefreight_listSingle").style.display = "";
        document.getElementById('sidefreight_listSingle').innerHTML = "<img style=\"margin: 5px 10px;\" alt=\"\" src=\"/wmsimages/loading.gif\" />";

        DoAjaxRequest("/suburbs_list.aspx?txtPostCode=" + encodeURI(document.getElementById("txtPostCodeSingle").value), function(response) {
            var suburbs = eval(response);

            if (suburbs.length == 0) {
                document.getElementById('sidefreight_listSingle').innerHTML = "<a class=\"suburb\" disabled=\"disabled\">No matching suburbs found</a>";
            }
            else {
                var output = "";

                for (var i = 0; i < suburbs.length - 1; i++) {
                    output += "<a class=\"suburb\" href=\"#\" onclick=\"SelectSuburbSingle(" + parseInt(productId) + ", '" + suburbs[i].Postcode + "', '" + suburbs[i].Suburb + "'); void(0); return false;\">" + suburbs[i].Postcode + " - " + suburbs[i].Suburb + "</a>";
                }

                document.getElementById('sidefreight_listSingle').innerHTML = output;
            }
        });
    }, 500);
}

function SelectSuburb(postcode, suburb) {
    document.getElementById("sidefreight_list").innerHTML = "<img style=\"margin: 5px 10px;\" alt=\"\" src=\"/wmsimages/loading.gif\" />";

    DoAjaxRequest("/deliveryBox.aspx?txtPostCode=" + postcode + "&txtSuburb=" + suburb, function(response) {
        document.getElementById("deliveryBox").innerHTML = response;
    });
}

function SelectSuburbSingle(productId, postcode, suburb) {
    document.getElementById("sidefreight_listSingle").innerHTML = "<img style=\"margin: 5px 10px;\" alt=\"\" src=\"/wmsimages/loading.gif\" />";

    DoAjaxRequest("/deliveryBoxSingle.aspx?ProductID=" + parseInt(productId) + "&txtPostCode=" + postcode + "&txtSuburb=" + suburb, function(response) {
        document.getElementById("deliveryBoxSingle").innerHTML = response;
    });
}

function imgCalculateSingle_OnClick(productId) {
    document.getElementById("sidefreight_listSingle").innerHTML = "<img style=\"margin: 5px 10px;\" alt=\"\" src=\"/wmsimages/loading.gif\" />";

    DoAjaxRequest("/deliveryBoxSingle.aspx?ProductID=" + parseInt(productId), function(response) {
        document.getElementById("deliveryBoxSingle").innerHTML = response;
    });
}

function addToWishlist(productId) {

    $.get("/addwishlist.aspx?add=" + productId, function (data) {
        if (data == "success") {
            alert('This item has been added to your wishlist, you can access your wishlist by selecting MY Account from the top menu bar.');
        } else {
            window.location = "/wishlist.aspx";
        }
    });
}
function addToWishlistAndNotify(productId) {
    $.get("/addwishlist.aspx?add=" + productId + "&n=true", function (data) {
        if (data == "success") {
            alert('You will be notified by email as soon as this item comes back into stock.');
        } else {
            window.location = "/wishlist.aspx";
        }
    });
}
function addToWishlistAndNotifyPO(productId) {
    $.get("/addwishlist.aspx?add=" + productId + "&n=true", function (data) {
        if (data == "success") {
            alert('Please note, when a pre-ordered item arrives you will be sent an email informing you that it is ready to ship. The pre-order item will added to your wishlist so you can checkout at your leisure. Please note no pre-order items will be charged until the item is ready to ship.');
        } else {
            window.location = "/wishlist.aspx";
        }
    });
}



//	function absoluteLocation(element) {
    //	var left = 0;
    //	var top = 0;
    //	while (element != null) {
    //	    left += element.offsetLeft;
    //	    top += element.offsetTop;
    //	    element = element.offsetParent;
    //	}
    //	return { left: left, top: top };
//	}

function Delegate(instance, method) {
    return function() {
        return method.apply(instance, arguments);
    };
}

var colors =
{
    aliceblue: "#F0F8FF",
    antiquewhite: "#FAEBD7",
    aqua: "#00FFFF",
    aquamarine: "#7FFFD4",
    azure: "#F0FFFF",
    beige: "#F5F5DC",
    bisque: "#FFE4C4",
    black: "#000000",
    blanchedalmond: "#FFEBCD",
    blue: "#0000FF",
    blueviolet: "#8A2BE2",
    brown: "#A52A2A",
    burlywood: "#DEB887",
    cadetblue: "#5F9EA0",
    chartreuse: "#7FFF00",
    chocolate: "#D2691E",
    coral: "#FF7F50",
    cornflowerblue: "#6495ED",
    cornsilk: "#FFF8DC",
    crimson: "#DC143C",
    cyan: "#00FFFF",
    darkblue: "#00008B",
    darkcyan: "#008B8B",
    darkgoldenrod: "#B8860B",
    darkgray: "#A9A9A9",
    darkgreen: "#006400",
    darkkhaki: "#BDB76B",
    darkmagenta: "#8B008B",
    darkolivegreen: "#556B2F",
    darkorange: "#FF8C00",
    darkorchid: "#9932CC",
    darkred: "#8B0000",
    darksalmon: "#E9967A",
    darkseagreen: "#8FBC8F",
    darkslateblue: "#483D8B",
    darkslategray: "#2F4F4F",
    darkturquoise: "#00CED1",
    darkviolet: "#9400D3",
    deepskyblue: "#00BFFF",
    dimgray: "#696969",
    dodgerblue: "#1E90FF",
    firebrick: "#B22222",
    floralwhite: "#FFFAF0",
    forestgreen: "#228B22",
    fuchsia: "#FF00FF",
    gainsboro: "#DCDCDC",
    ghostwhite: "#F8F8FF",
    gold: "#FFD700",
    goldenrod: "#DAA520",
    gray: "#808080",
    green: "#008000",
    greenyellow: "#ADFF2F",
    honeydew: "#F0FFF0",
    hotpink: "#FF69B4",
    indianred: "#CD5C5C",
    indigo: "#4B0082",
    ivory: "#FFFFF0",
    khaki: "#F0E68C",
    lavender: "#E6E6FA",
    lavenderblush: "#FFF0F5",
    lawngreen: "#7CFC00",
    lemonchiffon: "#FFFACD",
    lightblue: "#ADD8E6",
    lightcoral: "#F08080",
    lightcyan: "#E0FFFF",
    lightgoldenrodyellow: "#FAFAD2",
    lightgreen: "#90EE90",
    lightgrey: "#D3D3D3",
    lightpink: "#FFB6C1",
    lightsalmon: "#FFA07A",
    lightseagreen: "#20B2AA",
    lightskyblue: "#87CEFA",
    lightslategray: "#778899",
    lightsteelblue: "#B0C4DE",
    lightyellow: "#FFFFE0",
    lime: "#00FF00",
    limegreen: "#32CD32",
    linen: "#FAF0E6",
    magenta: "#FF00FF",
    maroon: "#800000",
    mediumauqamarine: "#66CDAA",
    mediumblue: "#0000CD",
    mediumorchid: "#BA55D3",
    mediumpurple: "#9370D8",
    mediumseagreen: "#3CB371",
    mediumslateblue: "#7B68EE",
    mediumspringgreen: "#00FA9A",
    mediumturquoise: "#48D1CC",
    mediumvioletred: "#C71585",
    midnightblue: "#191970",
    mintcream: "#F5FFFA",
    mistyrose: "#FFE4E1",
    moccasin: "#FFE4B5",
    navajowhite: "#FFDEAD",
    navy: "#000080",
    oldlace: "#FDF5E6",
    olive: "#808000",
    olivedrab: "#688E23",
    orange: "#FFA500",
    orangered: "#FF4500",
    orchid: "#DA70D6",
    palegoldenrod: "#EEE8AA",
    palegreen: "#98FB98",
    paleturquoise: "#AFEEEE",
    palevioletred: "#D87093",
    papayawhip: "#FFEFD5",
    peachpuff: "#FFDAB9",
    peru: "#CD853F",
    pink: "#FFC0CB",
    plum: "#DDA0DD",
    powderblue: "#B0E0E6",
    purple: "#800080",
    red: "#FF0000",
    rosybrown: "#BC8F8F",
    royalblue: "#4169E1",
    saddlebrown: "#8B4513",
    salmon: "#FA8072",
    sandybrown: "#F4A460",
    seagreen: "#2E8B57",
    seashell: "#FFF5EE",
    sienna: "#A0522D",
    silver: "#C0C0C0",
    skyblue: "#87CEEB",
    slateblue: "#6A5ACD",
    slategray: "#708090",
    snow: "#FFFAFA",
    springgreen: "#00FF7F",
    steelblue: "#4682B4",
    tan: "#D2B48C",
    teal: "#008080",
    thistle: "#D8BFD8",
    tomato: "#FF6347",
    turquoise: "#40E0D0",
    violet: "#EE82EE",
    wheat: "#F5DEB3",
    white: "#FFFFFF",
    whitesmoke: "#F5F5F5",
    yellow: "#FFFF00",
    green: "#9ACD32"
};

function TimeLine() {
    this.animations = new Array();
    this.busy = false;

    this.append = function(element, duration, animationObject) {
        var start = 0;

        for (var i = 0; i < this.animations.length; i++) {
            var animation = this.animations[i];

            if (start < animation.start + animation.duration)
                start = animation.start + animation.duration;
        }

        this.animations.push({ element: element, start: start, duration: duration, animationObject: animationObject });
    };

    this.schedule = function(element, start, duration, animationObject) {
        this.animations.push({ element: element, start: start, duration: duration, animationObject: animationObject });
    };

    this.play = function(callback) {
        if (this.busy)
            return;

        this.busy = true;

        var start = new Date().getTime();

        for (var i = 0; i < this.animations.length; i++)
            this.animations[i].complete = false;

        function _() {
            var now = new Date().getTime() - start;

            var more = false;

            for (var i = 0; i < this.animations.length; i++) {
                var animation = this.animations[i];

                if (now < animation.start)
                    continue;

                if (now >= animation.start + animation.duration) {
                    if (!animation.complete) {
                        animation.animationObject._step(animation.element, 1);

                        animation.complete = true;

                        more = true;
                    }

                    continue;
                }

                more = true;

                animation.animationObject._step(animation.element, (now - animation.start) / animation.duration);
            }

            if (more) {
                setTimeout(new Delegate(this, _), 1);
            }
            else {
                this.busy = false;

                if (callback != null)
                    callback();
            }
        }

        setTimeout(new Delegate(this, _), 1);
    };
}

function BackColorAnimation(from, to) {
    this.from = from;
    this.to = to;

    this._step = function(element, percent) {
        if (this.from == null) {
            var color = (element.currentStyle != null ? element.currentStyle.backgroundColor : document.defaultView.getComputedStyle(element, "").getPropertyValue("background-color"));

            if (colors[color] != null)
                color = colors[color];

            if (color.match(/^rgb/)) {
                var components = color.replace(/rgb\((.+)\)/, "$1").replace(/\s/g, "").split(",");

                this.from =
				{
				    red: parseInt(components[0]),
				    green: parseInt(components[1]),
				    blue: parseInt(components[2])
				};
            }
            else {
                this.from =
				{
				    red: parseInt(color.substring(1, 3), 16),
				    green: parseInt(color.substring(3, 5), 16),
				    blue: parseInt(color.substring(5, 7), 16)
				};
            }
        }

        if (this.to == null) {
            var color = (element.currentStyle != null ? element.currentStyle.backgroundColor : document.defaultView.getComputedStyle(element, "").getPropertyValue("background-color"));

            if (colors[color] != null)
                color = colors[color];

            if (color.match(/^rgb/)) {
                var components = color.replace(/rgb\((.+)\)/, "$1").replace(/\s/g, "").split(",");

                this.to =
				{
				    red: parseInt(components[0]),
				    green: parseInt(components[1]),
				    blue: parseInt(components[2])
				};
            }
            else {
                this.to =
				{
				    red: parseInt(color.substring(1, 3), 16),
				    green: parseInt(color.substring(3, 5), 16),
				    blue: parseInt(color.substring(5, 7), 16)
				};
            }
        }

        element.style.backgroundColor = "RGB(" + parseInt(this.from.red + (this.to.red - this.from.red) * percent) + ", " + parseInt(this.from.green + (this.to.green - this.from.green) * percent) + ", " + parseInt(this.from.blue + (this.to.blue - this.from.blue) * percent) + ")";
    };
}

function HeightAnimation(from, to) {
    this.from = from;
    this.to = to;

    this._step = function(element, percent) {
        if (this.from == null)
            this.from = element.offsetHeight;

        if (this.to == null)
            this.to = element.offsetHeight;

        element.style.height = parseInt(this.from + (this.to - this.from) * percent) + "px";
    };
}

function LeftAnimation(from, to) {
    this.from = from;
    this.to = to;

    this._step = function(element, percent) {
        if (this.from == null)
            this.from = absoluteLocation(element).left;

        if (this.to == null)
            this.to = absoluteLocation(element).left;

        element.style.left = parseInt(this.from + (this.to - this.from) * percent) + "px";
    };
}

function LocationAnimation(from, to) {
    this.from = from;
    this.to = to;

    this._step = function(element, percent) {
        if (this.from == null)
            this.from = absoluteLocation(element);

        if (this.to == null)
            this.to = absoluteLocation(element);

        element.style.left = parseInt(this.from.left + (this.to.left - this.from.left) * percent) + "px";
        element.style.top = parseInt(this.from.top + (this.to.top - this.from.top) * percent) + "px";
    };
}

function OpacityAnimation(from, to) {
    this.from = from;
    this.to = to;

    this._step = function(element, percent) {
        // FIXME

        element.style.filter = "alpha(opacity = " + parseInt(this.from + (this.to - this.from) * percent) + ")";
        element.style.opacity = (this.from + (this.to - this.from) * percent) / 100;
    };
}

function OrbitAnimation(from, to, radius, revolutions) {
    this.from = from;
    this.to = to;
    this.radius = radius;
    this.revolutions = revolutions;

    this._step = function(element, percent) {
        if (this.from == null)
            this.from = absoluteLocation(element);

        if (this.to == null)
            this.to = absoluteLocation(element);

        element.style.left = parseInt((this.from.left + (this.to.left - this.from.left) * percent) + Math.sin(percent * Math.PI * 2 * this.revolutions) * this.radius) + "px";
        element.style.top = parseInt((this.from.top + (this.to.top - this.from.top) * percent) - Math.cos(percent * Math.PI * 2 * this.revolutions) * this.radius) + "px";
    };
}

function RotateAnimation(from, to) {
    this.from = from;
    this.to = to;

    this._step = function(element, percent) {
        if (this.from == null)
            ;  // FIXME

        if (this.to == null)
            ;  // FIXME

        element.style.transform = "rotate(" + parseInt(this.from + (this.to - this.from) * percent) + "deg)";
        element.style.MozTransform = "rotate(" + parseInt(this.from + (this.to - this.from) * percent) + "deg)";
        element.style.msTransform = "rotate(" + parseInt(this.from + (this.to - this.from) * percent) + "deg)";
        element.style.oTransform = "rotate(" + parseInt(this.from + (this.to - this.from) * percent) + "deg)";
        element.style.webkitTransform = "rotate(" + parseInt(this.from + (this.to - this.from) * percent) + "deg)";
    };
}

function SizeAnimation(from, to) {
    this.from = from;
    this.to = to;

    this._step = function(element, percent) {
        if (this.from == null)
            this.from = { width: element.offsetWidth, height: element.offsetHeight };

        if (this.to == null)
            this.to = { width: element.offsetWidth, height: element.offsetHeight };

        element.style.width = parseInt(this.from.width + (this.to.width - this.from.width) * percent) + "px";
        element.style.height = parseInt(this.from.height + (this.to.height - this.from.height) * percent) + "px";
    };
}

function TopAnimation(from, to) {
    this.from = from;
    this.to = to;

    this._step = function(element, percent) {
        if (this.from == null)
            this.from = absoluteLocation(element).top;

        if (this.to == null)
            this.to = absoluteLocation(element).top;

        element.style.top = parseInt(this.from + (this.to - this.from) * percent) + "px";
    };
}

function WidthAnimation(from, to) {
    this.from = from;
    this.to = to;

    this._step = function(element, percent) {
        if (this.from == null)
            this.from = element.offsetWidth;

        if (this.to == null)
            this.to = element.offsetWidth;

        element.style.width = parseInt(this.from + (this.to - this.from) * percent) + "px";
    };
}


/// LB - JQuery to add support for html5 element: 'placeholder' on input fields in IE 9 and below (27/06/14)

// This adds 'placeholder' to the items listed in the jQuery .support object. 
jQuery(function() {
   jQuery.support.placeholder = false;
   test = document.createElement('input');
   if('placeholder' in test) jQuery.support.placeholder = true;
});
// This adds placeholder support to browsers that wouldn't otherwise support it. 
$(function() {
   if(!$.support.placeholder) { 
      var active = document.activeElement;
      $(':text').focus(function () {
         if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
            $(this).val('').removeClass('hasPlaceholder');
         }
      }).blur(function () {
         if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
            $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
         }
      });
      $(':text').blur();
      $(active).focus();
      $('form:eq(0)').submit(function () {
         $(':text.hasPlaceholder').val('');
      });
   }
});

$(document).ready(function () {

    $('input:radio[name="pmethod"]').change(function () { $("#paymentmethodtext").html($(this).data("itemdescription")); CalcSurcharge(); });

    $('.trackFbGa').click(function () {
        FB();
        GA(this);
    });

    function FB() {
        try {
            fbq('track', 'Lead', {});
        } catch (err) {
        }
    }

    function GA(sender) {
        try {
            var label = $(sender).data('label');
            var category = $(sender).data('category');
            ga('send', 'event', category, 'Click', label);
        } catch (err) {
        }
    }
});


//end