﻿$(document).ready(function() {
    ReSetHeadInfo();
    $("#CustomerLogin").css("display", "");
});

function EmailValider(email) {
    var patrn = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    if (!patrn.exec(email)) {
        return false;
    }
    return true;
}
function GotoListPage(Index) {
    var txtPageIndex = document.getElementById("txtPageIndex" + Index);
    if (txtPageIndex.value == "") {
        txtPageIndex.focus();
        alert("Please input the page number.");
        return;
    }
    if (isNaN(txtPageIndex.value)) {
        txtPageIndex.focus();
        alert("The page number must be number.");
        return;
    }
    var HiddenCurrentPageCount = document.getElementById("HiddenCurrentPageCount" + Index);
    if (parseInt(txtPageIndex.value) > parseInt(HiddenCurrentPageCount.value)) {
        txtPageIndex.focus();
        alert("The page must be less than " + (parseInt(HiddenCurrentPageCount.value) + 1) + ".");
        return;
    }
    var HiddenPageUrl = document.getElementById("HiddenPageUrl" + Index);
    location.href = HiddenPageUrl.value + "_p" + txtPageIndex.value + ".aspx";
}

function FilterProductListPageIndex(Object) {
    if (window.event.keyCode == 13) {
        document.getElementById(Object).click();
    }
    if (!((window.event.keyCode >= 48) && (window.event.keyCode <= 57))) {
        window.event.keyCode = 0;
    }
}
function gb_showBG() {

    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
        $("body", "html").css({ height: "100%", width: "100%" });
        $("html").css("overflow", "hidden");
        if (document.getElementById("gb_HideSelect") === null) {//iframe to hide select elements in ie6
            $("body").append("<iframe id='gb_HideSelect'></iframe><div id='gb_overlay'></div><div id='gb_window'></div>");
        }
    } else {//all others
        if (document.getElementById("gb_overlay") === null) {
            $("body").append("<div id='gb_overlay'></div><div id='gb_window'></div>");
        }
        if ($.browser.opera) {
            $("html").css("overflow", "hidden");
            $("body", "html").css({ height: $("#gb_overlay").css("height"), width: "100%" });
        }
    }
    if (gb_detectMacXFF()) {
        $("#gb_overlay").addClass("gb_overlayMacFFBGHack"); //use png overlay so hide flash
    } else {
        $("#gb_overlay").addClass("gb_overlayBG"); //use background and opacity
    }
    if (!$.browser.mozilla) {
        $("body").append("<div id='gb_load'><img src='" + $("#HomeLink").val() + "/images/loadingAnimation.gif' /></div>"); //add loader to the page
        $('#gb_load').show(); //show loader
    } else {
        document.getElementById('ProcessingMessage').style.top = sGetScrollTop() + (window.screen.availHeight * 1 / 2) + 'px';
        $('#ProcessingMessage').css("display", "block");
    }
    document.onkeydown = function(e) {
        if (e == null) { // ie
            keycode = event.keyCode;
        } else { // mozilla
            keycode = e.which;
        }
        if (keycode == 27) { // close
            gb_remove();
        }
    };
}

//  Purpose:   Customer SignOut
//  Arguments: None.
function SignOut() {
    ShowBackground();
    $.get($("#HomeLink").val() + "/Ajax/SignOut.ashx", { time: (new Date()).getTime() }, function(data) {
        if (data == "Success") {
            $("#CustomerLogin").html("Welcome! <span style=\"color:#E3D11E;\">Guest</span>!");
            RemoveBackground();
            if ($("#hfIsLogin")) {
                $("#hfIsLogin").val("no");
            }
            if (location.href.indexOf("/Secure/") > 0) {
                location.href = $("#HomeLink").val() + "/JoinUs/Login.aspx"
            }
        }
    });
}

function gb_detectMacXFF() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
        return true;
    }
}
function sGetScrollTop() {
    if (document.documentElement.scrollTop != 0) { return document.documentElement.scrollTop }
    return document.body.scrollTop;
}
function gb_remove() {
    $("#gb_window").fadeOut("fast", function() { $('#gb_window,#gb_overlay,#gb_HideSelect').trigger("unload").unbind().remove(); });
    if (!$.browser.mozilla) {
        $("#gb_load").remove();
    } else {
        $('#ProcessingMessage').css("display", "none");
    }
    if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
        $("body", "html").css({ height: "auto", width: "auto" });
        $("html").css("overflow", "");
    }
    document.onkeydown = "";
    document.onkeyup = "";
    return false;
}

function gb_show(t, v) {//function called when the user clicks on a harveybox link
    try {
        if (t == "PageSize") {
            $("#ShoppingCartPageSize").val(v);
            PerPage(v);
            gb_getdata(v, 1);
        }
        else {
            var PageSizeTemp = $("#ShoppingCartPageSize").val();

            gb_getdata(PageSizeTemp, v);
        }
    } catch (e) {
        //nothing here
    }
}

//禁用其他按钮
function DisableOtherSubmit() {
    var objs = document.getElementsByTagName('INPUT');
    var btns = document.getElementsByTagName('button');
    for (var i = 0; i < objs.length; i++) {
        if (objs[i].type.toLowerCase() == 'submit' || objs[i].type.toLowerCase() == 'button') {
            objs[i].disabled = true;
        }
    }
    for (var i = 0; i < btns.length; i++) {
        btns[i].disabled = true;
    }
}

//启用其他按钮
function EnableOtherSubmit() {
    var objs = document.getElementsByTagName('INPUT');
    var btns = document.getElementsByTagName('button');
    for (var i = 0; i < objs.length; i++) {
        if (objs[i].type.toLowerCase() == 'submit' || objs[i].type.toLowerCase() == 'button') {
            objs[i].disabled = false;
        }
    }
    for (var i = 0; i < btns.length; i++) {
        btns[i].disabled = false;
    }
}

//验证是否数字
function FilterNum() {
    if (!((window.event.keyCode >= 48) && (window.event.keyCode <= 57))) {
        window.event.keyCode = 0;
    }
}

//验证是否数字
function CheckIsNumber(number) {
    var reg = /^-?\d+$/;
    if (number != "") {
        if (reg.test(number)) {
            return true;
        } else {
            return false;
        }
    }
}

function IsMsIE() {
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        return true;
    } else {
        return false;
    }
}

function IsFirefox() {
    if (navigator.userAgent.indexOf("Firefox") > 0) {
        return true;
    } else {
        return false;
    }
}

function IsSafari() {
    if (navigator.userAgent.indexOf("Safari") > 0) {
        return true;
    } else {
        return false;
    }
}

function IsIEOrFirefox() {
    if (navigator.userAgent.indexOf("MSIE") > 0 || navigator.userAgent.indexOf("Firefox") > 0) {
        return true;
    } else {
        return false;
    }
}

function GetQueryStringRegExp(name) {
    var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
    if (reg.test(location.href))
        return unescape(RegExp.$2.replace(/\+/g, " ")); return "";
}

function ReSetHeadInfo() {
    if ($.browser.mozilla) {
        if (getCookie("ShoppingItem")) {
            $("#ShoppingItem").html($.cookie("ShoppingItem"));
        } else {
            $("#ShoppingItem").html("0");
        }
        if (getCookie("Subtotal")) {
            $("#Subtotal").html("$" + $.cookie("Subtotal"));
        } else {
            $("#Subtotal").html("$0");
        }
    } else {
        if ($.cookie("ShoppingItem")) {
            $("#ShoppingItem").html($.cookie("ShoppingItem"));
        } else {
            $("#ShoppingItem").html("0");
        }
        if ($.cookie("Subtotal")) {
            $("#Subtotal").html("$" + $.cookie("Subtotal"));
        } else {
            $("#Subtotal").html("$0");
        }
    }

}

function getLeftPosition(Obj) {
    try {
        for (var sumLeft = 0; Obj != document.body; sumLeft += Obj.offsetLeft, Obj = Obj.offsetParent);
        return sumLeft;
    } catch (e) {

    }
}

function getTopPosition(Obj) {
    try {
        for (var sumTop = 0; Obj != document.body; sumTop += Obj.offsetTop, Obj = Obj.offsetParent);
        return sumTop;
    } catch (e) {

    }
}
function GotPage1() {
    top.location.href = "/FreeShipping.aspx";
}
function GetWindowLength(type, debug) {
    type = (typeof type == 'undefined') ? 'error' : type;
    type = type.toLowerCase();
    var w = 'width';
    var h = 'height';
    if (w.indexOf(type) == 0) {
        type = 'Width'
    } else if (h.indexOf(type) == 0) {
        type = 'Height'
    } else {
        alert('wrong parameter' + type)
    }
    var attrs = ['offset' + type, 'scroll' + type, 'client' + type, 'inner' + type];
    var db = document.body;
    var de = document.documentElement;
    var r = 0;
    var tmp_r = 0;
    var a = '';
    for (var i = 0; i < attrs.length; i++) {
        a = attrs[i];
        tmp_r = db[a] > de[a] ? db[a] : de[a];
        if (debug) {
            alert(a + ':' + tmp_r);
        }
        if (typeof tmp_r == 'undefined' || tmp_r < r) {
            continue
        }
        c_attr = a;
        r = tmp_r;
    }
    if (debug) {
        alert(c_attr + ':' + r);
    }
    return r;
}

function Obj1OverObj2(obj1, obj2) {
    var result = true;
    var obj1Left = getLeftPosition(obj1) - document.body.scrollLeft;
    var obj1Top = getTopPosition(obj1) - document.body.scrollTop;
    var obj1Right = obj1Left + obj1.offsetWidth;
    var obj1Bottom = obj1Top + obj1.offsetHeight;
    var obj2Left = getLeftPosition(obj2) - document.body.scrollLeft;
    var obj2Top = getTopPosition(obj2) - document.body.scrollTop;
    var obj2Right = obj2Left + obj2.offsetWidth;
    var obj2Bottom = obj2Top + obj2.offsetHeight;
    if (obj1Right <= obj2Left || obj1Bottom <= obj2Top || obj1Left >= obj2Right || obj1Top >= obj2Bottom) {
        result = false;
    }
    return result;
}

function CheckControl(selectctr, targ) {
    var sel = document.getElementsByName(selectctr);
    var tar = document.getElementsByName(targ);
    var n = tar.length;
    for (var i = 0; i < n; i++) {
        tar[i].checked = sel[0].checked;
    }
}

function getCookie(parameter) {
    var reg, allCookie, allCookie2, iLen, iStart, iEnd;
    allCookie = document.cookie;
    reg = new RegExp(parameter);
    if (allCookie.search(reg) == -1) {
        return "";
    }
    else {
        iLen = parameter.length;
        iStart = allCookie.search(reg) + iLen + 1;
        allCookie2 = allCookie.substr(iStart);
        iEnd = iStart + allCookie2.search(/;/i);
        if ((iStart - 1) == iEnd) {
            return allCookie.substr(iStart);
        }
        else {
            return allCookie.substr(iStart, iEnd - iStart);
        }
    }
}

//  Purpose:   Show Background
//  Arguments: None.
function ShowBackground() {
    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
        $("body", "html").css({ height: "100%", width: "100%" });
        $("html").css("overflow", "hidden");
        if (document.getElementById("gb_HideSelect") === null) {//iframe to hide select elements in ie6
            $("body").append("<iframe id='gb_HideSelect'></iframe><div id='gb_overlay'></div><div id='gb_window'></div>");
        }
    } else {//all others
        if (document.getElementById("gb_overlay") === null) {
            $("body").append("<div id='gb_overlay'></div><div id='gb_window'></div>");
        }
        if ($.browser.opera) {
            $("html").css("overflow", "hidden");
            $("body", "html").css({ height: $("#gb_overlay").css("height"), width: "100%" });
        }
    }
    if (gb_detectMacXFF()) {
        $("#gb_overlay").addClass("gb_overlayMacFFBGHack"); //use png overlay so hide flash
    } else {
        $("#gb_overlay").addClass("gb_overlayBG"); //use background and opacity
    }
    if (!$.browser.mozilla) {
        $("body").append("<div id='gb_load'><img src='" + $("#HomeLink").val() + "/images/loadingAnimation.gif' /></div>"); //add loader to the page
        $('#gb_load').show(); //show loader
    } else {
        document.getElementById('ProcessingMessage').style.top = sGetScrollTop() + (window.screen.availHeight * 1 / 2) + 'px';
        $('#ProcessingMessage').css("display", "block");
    }
    document.onkeydown = function(e) {
        if (e == null) { // ie
            keycode = event.keyCode;
        } else { // mozilla
            keycode = e.which;
        }
        if (keycode == 27) { // close
            gb_remove();
        }
    };
}

//  Purpose:   Remove Background
//  Arguments: None.
function RemoveBackground() {
    $("#gb_window").fadeOut("fast", function() { $('#gb_window,#gb_overlay,#gb_HideSelect').trigger("unload").unbind().remove(); });
    if (!$.browser.mozilla) {
        $("#gb_load").remove();
    } else {
        $('#ProcessingMessage').css("display", "none");
    }
    if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
        $("body", "html").css({ height: "auto", width: "auto" });
        $("html").css("overflow", "");
    }
    document.onkeydown = "";
    document.onkeyup = "";
    return false;
}

function FilterUserInputNum(Object) {
    if (window.event.keyCode == 13) {
        document.getElementById(Object).click();
    }
    if (!((window.event.keyCode >= 48) && (window.event.keyCode <= 57))) {
        window.event.keyCode = 0;
    }
}

function FilterUserInputFloat(Object) {
    if (window.event.keyCode == 13) {
        document.getElementById(Object).click();
    }
    if (!((window.event.keyCode >= 48) && (window.event.keyCode <= 57) || (window.event.keyCode == 46))) {
        window.event.keyCode = 0;
    }
}

function getAbsolutePosition(element) {
    var point = { x: element.offsetLeft, y: element.offsetTop };
    //Recursion
    if (element.offsetParent) {
        var parentPoint = this.getAbsolutePosition(element.offsetParent);
        point.x += parentPoint.x;
        point.y += parentPoint.y;
    }
    return point;
};

function AddItemsToCart(Obj, ItemsID) {
    var hfItemsListMinOrder = document.getElementById("hfItemsListMinOrder" + ItemsID);
    var hfItemsListIsForce = document.getElementById("hfItemsListIsForce" + ItemsID);
    var txtNum = document.getElementById("txtNum" + ItemsID);
    if (hfItemsListIsForce == "1") {
        if (parseInt(txtNum.value) < parseInt(hfItemsListMinOrder.value)) {
            alert("This item is only accepted to be ordered over the min.order.min.order is " + hfItemsListMinOrder.value);
            txtNum.focus();
            return;
        }
    }
    if (!isNaN(txtNum.value)) {
        if (txtNum.value == "" || parseInt(txtNum.value) < 1) {
            alert("The quantity should be not less than 1.");
            return;
        }
    } else {
        alert("The quantity must be number.");
        return;
    }
    var NewObj = Obj.offsetParent;
    $.ajax({
        url: $("#HomeLink").val() + '/Ajax/ProcessAddMiniCart.ashx',
        type: 'GET',
        dataType: 'xml',
        data: { txtNum: txtNum.value, ItemsID: ItemsID, time: (new Date()).getTime() },
        error: function(error) {
            location.href = $("#HomeLink").val() + "/Error/GenericErrorpage.aspx";
        },
        beforeSend: function(XMLHttpRequest) {
            NewObj.innerHTML = "<img style=\"margin-top: 15px;\" alt=\"\" src=\"" + $("#HomeLink").val() + "/images/loading.gif\" />";

        },
        complete: function() {
            NewObj.innerHTML = "<img style=\"margin-top: 5px;cursor: pointer\" onclick=\"javascript:GotoShoppingCart();\" alt=\"\" src=\"" + $("#HomeLink").val() + "/images/update_cart.jpg\" />";
        },
        success: function(data) {
            if ($(data).find("ShoppingCart").attr("Count")) {
                var TotalCount = $(data).find("ShoppingCart").attr("Count");
                var TotalPrice = $(data).find("ShoppingCart").attr("TotalPrice");
                $("#ShoppingItem").html(TotalCount);
                $("#Subtotal").html(TotalPrice);
                $("#MiniCartItems").html(TotalCount);
                $("#MiniCartSubtotal").html(TotalPrice);
                if (parseInt(TotalCount) <= 10) {
                    $("#MiniCartDisplaying").html(TotalCount);
                }
                var MiniCartStr = "";
                $(data).find("Item").each(function() {
                var ItemsStr = "<table style=\"padding:auto;margin:0 5px 0 5px;\"><tr><td align=\"left\" style=\"padding:0 4px 0 4px;\" colspan=\"2\"><a href=\"" + $("#HomeLink").val() + "/Items.aspx?id=" + $(this).attr("ItemsID") + "\">" + $(this).attr("ItemsEName") + "</a></td></tr><tr><td><a href=\"" + $("#HomeLink").val() + "/Items.aspx?id=" + $(this).attr("ItemsID") + "\"><img width=\"70\" src=\"http://img.gbeads.cn/" + $(this).attr("ImagePath") + "\" alt=\"\" /></a></td><td><table><tr><td>NO.:" + $(this).attr("Number") + "</td></tr><tr><td>Type: " + $(this).attr("ItemType") + "</td></tr><tr><td>Quantity:" + $(this).attr("Quantity") + "</td></tr><tr><td>At <span style=\"color:red;\">$" + $(this).attr("UnitPrice") + "</span> each</td></tr></table></td></tr></table>"
                    MiniCartStr += ItemsStr;
                });
                if (MiniCartStr == "") {
                    MiniCartStr = "<div style=\"margin:30px 0 30px 0;color:red;\">Your shopping cart is empty.</div>";
                }
                $("#MiniCartProductList").html(MiniCartStr);

            }
        }
    });
}

function GotoShoppingCart() {
    location.href = $("#HomeLink").val() + "/Shopping/ShoppingCart.aspx";
}

function AddItemsToFavorite(Obj, ItemsID) {
    var txtNum = document.getElementById("txtNum" + ItemsID);
    if (!isNaN(txtNum.value)) {
        if (txtNum.value == "" || parseInt(txtNum.value) < 1) {
            alert("The quantity should be not less than 1.");
            return;
        }
    } else {
        alert("The quantity must be number.");
        return;
    }
    $.ajax({
        url: $("#HomeLink").val() + '/Ajax/ProcessAddToFavorite.ashx',
        type: 'GET',
        dataType: 'xml',
        data: { ItemsDetailIDS: 0, Quantity: txtNum.value, ItemsID: ItemsID, time: (new Date()).getTime() },
        error: function(error) {
            location.href = $("#HomeLink").val() + "/Error/GenericErrorpage.aspx";
        },
        beforeSend: function(XMLHttpRequest) {
            ShowBackground();
        },
        success: function(data) {
            RemoveBackground();
            if ($(data).find("Success").attr("id")) {
                Obj.parentNode.innerHTML = "";
            } else if ($(data).find("Login").attr("message")) {
                alert("Please login first.");
            } else {
                location.href = $("#HomeLink").val() + "/Error/GenericErrorpage.aspx";
            }
        }
    });
}

function filterUserInputIsFloat(object) { 
    if(!object.value.match(/^[\+\-]?\d*?\.?\d*?$/))object.value=object.t_value;else object.t_value=object.value;if(object.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/))object.o_value=object.value;
    
}

function filterUserInputIsFloatOnblur(object) {
    if (!object.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?|\.\d*?)?$/)) object.value = object.o_value; else { if (object.value.match(/^\.\d+$/)) object.value = 0 + object.value; if (object.value.match(/^\.$/)) object.value = 0; object.o_value = object.value }
}

function filterUserInputIsNumber(object) {
    object.value = object.value.replace(/\D/g, '');
}