﻿String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

function IsNullOrBlank(val) {
    return (val == null) || /^\s*$/.test(val);
} 
//是否整型数据
function IsInt(val, minVal) {
    var retval = /^\s*\d{1,8}\s*$/.test(val);
    if (retval && (minVal != null)) {
        if (parseInt(val, 10) < minVal) {
            retval = false;
        }
        else {
            retval = true;
        }
    }
    return retval;
}

String.prototype.IsNullOrBlank = function () {
    return IsNullOrBlank(this);
}

function hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

 function addClass(ele, cls) {
     if (!this.hasClass(ele, cls)) ele.className += " " + cls;
 }

 function GetAjaxRequest() {
     var request = null;
     try {
         request = new XMLHttpRequest();
     }
     catch (trymicrosoft) {
         try {
             request = new ActiveXObject("Msxml2.XMLHTTP");
         }
         catch (othermicrosoft) {
             try {
                 request = new ActiveXObject("Microsoft.XMLHTTP");
             }
             catch (failed) {
                 request = null;
             }
         }
     }
     return request;
 }

/******************************无限级目录树脚本：QQ 759922422 2010-12-08 ****************************************/
var LastShowMenuItem = null;
function TreeMenu_Click(event, hiddenLast) {
    var obj = event.srcElement ? event.srcElement : event.target;
    if (obj.tagName != "A") {
        if (obj.tagName != "LI") {
            if (obj.parentNode.tagName == "LI") {
                obj = obj.parentNode;
            }
            else {
                obj = null;
            }
        }
        if (obj != null) {
            toggleMenu(obj);
            if (hiddenLast == true) {
                var level = getMenuLevel(obj);
                if ((LastShowMenuItem != null) && (LastShowMenuItem != obj)) {
                    if (level == 0) {
                        toggleMenu(LastShowMenuItem, "none");
                    }
                }
                if (level == 0) {
                    LastShowMenuItem = obj;
                }
            }
        }
    }
}
//menuItem:li对象
//display：显示block,隐藏none;
//showOnlyChildren,是否只显示直接子节点
function toggleMenu(menuItem, display, showOnlyChildren) {
    var parentLevel = getMenuLevel(menuItem);
    var nextNode = menuItem.nextSibling;
    var childLevel = null;
    if (nextNode != null) {
        childLevel = getMenuLevel(nextNode);
        if (display == null) {
            if (isDisplayNone(nextNode)) {
                display = "block";
            }
            else {
                display = "none";
            }
        }
    }
    while ((nextNode != null) && (childLevel > parentLevel)) {
        if ((childLevel - parentLevel) == 1) {
            nextNode.style.display = display;
            nextNode.setAttribute("display", display);
        } 
        else {
            if (showOnlyChildren) {
                nextNode.style.display = "none";
                nextNode.setAttribute("display", "none");
            }
            else {
                var displayState = nextNode.getAttribute("display");
                if (displayState == null) {
                    if (isDisplayNone(nextNode)) {
                        nextNode.style.display = "none";
                        nextNode.setAttribute("display", "none");
                    }
                    else {
                        nextNode.style.display = display;
                        nextNode.setAttribute("display", display);
                    }
                }
                else {
                    if (display == "none") {
                        nextNode.style.display = "none";
                    }
                    else {
                        nextNode.style.display = displayState;
                    }
                }
            }
        }
        nextNode = nextNode.nextSibling;
        if (nextNode != null) {
            childLevel = getMenuLevel(nextNode);
        }
    }
}
//获取从顶级类别到当前类别的路径
function GetParentRoot(menuItem) {
    var root = new Array();
    root.push(menuItem);
    var currLevel = getMenuLevel(menuItem);
    var prevNode = menuItem.previousSibling
    var prevLevel = null;
    if (prevNode != null) {
        prevLevel = getMenuLevel(prevNode);
    }
    while (prevNode != null) {
        if (currLevel > prevLevel) {
            root.push(prevNode);
            currLevel = prevLevel;
        }
        prevNode = prevNode.previousSibling;
        if (prevNode != null) {
            prevLevel = getMenuLevel(prevNode);
        }
    }
    return root;
}
//保存目录树展开状态
function LoadTreeViewState() {
    var selectedItem = getSelectedMenuItem();
    if (selectedItem != null) {
        addClass(selectedItem, "selected");  
        //*      
        var root = GetParentRoot(selectedItem);
        if (root != null) {
            for (var i = root.length - 1; i >= 0; i--) {
                toggleMenu(root[i], "block", true);
            }
        }
        //*/
    }
}
//通过当前节点url，查找对应于目录树中的节点
function getSelectedMenuItem() {
    var retval = null;
    var currentCategory = document.getElementById("CurrentCategory");
    if (currentCategory != null) {
        var categoryTree = document.getElementById("CategoryTree");
        if (categoryTree != null) {
            var items = categoryTree.getElementsByTagName("a");
                var currUrl = currentCategory.getAttribute("href");
            if ((items != null) && (items.length > 0)) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].getAttribute("href") == currUrl) {
                        retval = items[i].parentNode;
                        while ((retval.tagName != "LI") && (retval != null)) {
                            retval = retval.parentNode;
                        }
                        break;
                    }
                }
            }
        }
    }
    return retval;
}

function getMenuLevel(menuItem) {
    return parseInt(menuItem.getAttribute("class").substr(5, 2), 10);
}

function isDisplayNone(item) {
    return ((item.style.display == "none") || (item.offsetWidth == 0));
}
/******************************无限级目录树脚本：QQ 759922422 2010-12-08 ****************************************/


/*****************************cookie 操作脚本********************************************************************/
var HttpCookie = function (name, value, expires, path, domain) {
    if (name) this.Name = name;
    if (value) this.Value = value;
    if (expires) this.Expires = expires;
    if (path) this.Path = path;
    if (domain) this.Domain = domain;
};

HttpCookie.prototype = {
    Name: '', Value: '', Expires: '', Path: '/', Domain: '',
    toCookie: function () {
        var NewCookie = this.Name + '=' + this.Value;
        if (this.Expires) NewCookie += (';expires=' + this.Expires);
        if (this.Path) NewCookie += (';path=' + this.Path);
        if (this.Domain) NewCookie += (';domain=' + this.Domain);
        return NewCookie;
    }
}

var CookieHelper = function () { };

CookieHelper.ConvertToUTCString = function (hourNumber) {
    if (!hourNumber || hourNumber == 0) return null;
    var Timestamp = (new Date().getTime() + (hourNumber * 1000 * 60 * 60));
    return new Date(Timestamp).toUTCString();
};

CookieHelper.Set = function (cookieName, cookieValue, expireHour, path, domain) {
    var HC = new HttpCookie
    (
        cookieName,
        escape(cookieValue),
        CookieHelper.ConvertToUTCString(expireHour),
        path,
        domain
    );
    document.cookie = HC.toCookie();
};

CookieHelper.Get = function (cookieName) {
    var regex = new RegExp(("(^| )" + cookieName + "=([^;]*)(;|$)"));
    var Matchs = document.cookie.match(regex);
    if (Matchs) return unescape(Matchs[2]);
    return null;
};

CookieHelper.Delete = function (cookieName, path, domain) {
    if (!CookieHelper.Get(cookieName)) return;

    var HC =
    new HttpCookie
    (
        cookieName,
        null,
        CookieHelper.ConvertToUTCString(-100)
    );

    document.cookie = HC.toCookie();
};
/*****************************cookie 操作脚本********************************************************************/

//更新购物车数量
function SetQuantityToCart(obj) {
    if (IsInt(obj.value)) {
        var quantity = parseInt(obj.value, 10);
        if (quantity > 0) {
            if (obj.value != obj.getAttribute("quantity")) {
                var rowID = obj.getAttribute("rowid");
                document.location = "/cart/setquantity.htm?rowID="+rowID+"&quantity=" + quantity;
            }
        }
        else {
            alert("order quantity must be bigger than 0.");
        }
    }
    else {
        alert("order quantity must be a integer number!");
    }
}
function DeleteFromCart(obj) {
    if (confirm("Are you sure to delete it?")) {
        var rowID = obj.getAttribute("rowid");
        document.location = "/cart/delete.htm?rowID=" + rowID;
    }
}

function AddToCartBatch(obj) {
    var productID = obj.getAttribute("productid");
    var style = document.getElementById("Style");
    var styleIndex = 0;
    var quantity = 1;
    var size = "";
    if (style != null) {
        var tempIndex = style.getAttribute("index");
        if (IsInt(tempIndex)) {
            styleIndex = parseInt(tempIndex, 10);
        }
    }
    var sizeQuantityList = document.getElementsByName("ProductSizeQuantity");
    if ((sizeQuantityList != null) && (sizeQuantityList.length > 0)) {
        for (var i = 0; i < sizeQuantityList.length; i++) {
            if (IsInt(sizeQuantityList[i].value)) {
                quantity = parseInt(sizeQuantityList[i].value, 10);
                size = sizeQuantityList[i].getAttribute("title");
                break;
            }
        }
        if (IsNullOrBlank(size) && (document.getElementById("SizeSelector") != null)) {
            alert("Please select size!");
        }
        else {
            document.location = GetCartAddUrl(productID, styleIndex, quantity, size);
        }
    }
}

function Recalculated() {
    var couponCode = document.getElementById("CouponCode");
    if (!IsNullOrBlank(couponCode)) {
        var code = couponCode.value.replace(/\s/g, "");
        document.location = "/cart/recalculated.htm?couponCode=" + encodeURIComponent(code) + "&backUrl=" + encodeURIComponent(couponCode.getAttribute("backurl"));
    }
    else {
        alert("Please input coupon code!");
    }
}

function GetCartAddUrl(productRowID, styleIndex, quantity, size) {
    if (IsNullOrBlank(size)) {
        return "/cart/add.htm?productRowID=" + productRowID + "&styleIndex=" + styleIndex + "&quantity=" + quantity;
    }
    else {
        return "/cart/add.htm?productRowID=" + productRowID + "&styleIndex=" + styleIndex + "&quantity=" + quantity + "&size=" + encodeURIComponent(size);
    }
}

var keepOneClick = true;

function ClearCartCookie() {
    if (keepOneClick) {
        var request = GetAjaxRequest();
        if (request != null) {
            var cartID = CookieHelper.Get("NetShopCartID");
            var orderID = CookieHelper.Get("NetShopOrderID");
            var url = "/cart/sendmailandclearcart.htm?cartID=" + encodeURIComponent(cartID) + "&orderID=" + encodeURIComponent(orderID);
            request.open("GET", url, false); //true表示异步，但是ff浏览器有问题。
            request.onreadystatechange = updatePage;
            request.send(null);
        }
        CookieHelper.Delete("NetShopCartID");
        CookieHelper.Delete("NetShopOrderID");
        CookieHelper.Delete("NetShopCartCount");
        keepOneClick = false;
    }
}

function updatePage() {
    if (request.readyState == 4) {
        if (request.status == 200) {
            //alert(request.responseText);
        }
        else {
            //alert("status is " + request.status);
        }
    }
}


/*****************************购物车操作脚本*********************************************************************/

/*****************************加载事件***************************************************************************/
window.onload = function () {
    //加载目录树状态
    LoadTreeViewState();
};
/***************************************************************************************************************/
