﻿$().ready(function() {
    $("#cb_games").change(function() {
        $("#pro_list").empty();
        $.getJSON(g_.code, { procls: "", gid: $("#cb_games>option:selected").val() }, function(data) {
            var arr = [];
            for (var i in data) {
                var obj = data[i];
                arr.push(String.format("<option value=\"{1}\" >{0}</option>", obj.ClassName, obj.ID));
                bindItemsCls(obj);
            }
            $("#cb_products").empty().append(arr.join(''));
        });
    });
    if ($(".search").length) {
        var removeSubCls = function(id) {
            if ($("#" + id + "a").length) {
                removeSubCls(id + "a");
            }
            $("#" + id).remove();
        };
        var addSubCls = function(id, obj, pid) {
            if (parseInt(pid)) {
                $.getJSON(g_.code, { procls: "", cid: pid }, function(data) {
                    if (data.length) {
                        if (!$("#" + id).length) {
                            $(obj).after(String.format("<select id=\"{0}\"></select>", id));
                            $("#" + id).change(function() {
                                var id = this.id + "a";
                                var obj = $(this);
                                var pid = $(this).val();
                                addSubCls(id, obj, pid);
                            });
                        }
                        else {
                            removeSubCls(this.id + "a");
                        }
                        var arr = [];
                        arr.push("<option value=\"0\">All</option>");
                        for (var i in data) {
                            var o = data[i];
                            arr.push(String.format("<option value=\"{1}\">{0}</option>", o.ClassName, o.ID));
                        }
                        $("#" + id).empty().append(arr.join(''));
                    }
                });
            }
            else {
                removeSubCls(id);
            }
        };
        $(".search>select").change(function() {
            var id = this.id + "a";
            var obj = $(this);
            var pid = $(this).val();
            addSubCls(id, obj, pid);
        });
    }
    if ($("#bt_search").length) {
        //load search
        $("#bt_search").click(function() {
            if ($("#tb_search_key").val().trim().length) {
                var cls = $(".search>select:last").val();
                if ($(".search>select:last").val() == "0") {
                    if ($(".search>select").length > 1) {
                        cls = $(".search>select:last").prev().val();
                    }
                }
                window.location = String.format("product_search.aspx?q={0}&c={1}", escape($("#tb_search_key").val().trim()), cls);
            }
        });
    }
    if ($("#bt_ok").length) {
        $("#bt_ok").click(function() {
            if (validate("tb_usrinfo")) {
                if ($("#tb_content").val().trim().length < 1) {
                    alert("comment info must fill out!");
                    return;
                }
                var str = String.format("{NickyName:'{0}',Mail:'{1}',Rank:{2},Content:'{3}',ItemID:{4}}", escape($("#tb_usr").val()), escape($("#tb_mail").val()), $("#i_rank>input[@name=comment_rank]:checked").val(), escape($("#tb_content").val()), $("#hdn_item_id").val());
                $.get(g_.code, { comadd: "", comment: str }, function(data) {
                    if (data.toLowerCase() == 'true') {
                        $(".feed").prepend(String.format("<dt><span class=\"date\">{0}</span>user: <font class=\"orange\">{1}</font></dt><dd>{2}</dd><dt>", "just a moment ago", $("#tb_usr").val(), $("#tb_content").val()));
                        alert("success!");
                    }
                    else {
                        alert("fail!");
                    }
                });
            }
        });

    }
    if ($(".feed").length && window.location.href.indexOf("product-detail.aspx")>0) {
        $("#tb_usr").focus(function() { $("#tb_usr").val(""); });
        $("#tb_mail").focus(function() { $("#tb_mail").val(""); }); changefeedpage();
    }
    if ($("input[name=ra_currency]").length) { $("input[name=ra_currency]:first").attr("checked", true); }
    if ($("#cb_games").length) { $("#cb_games>option:first").attr("selected", true); }
    if ($("#tb_pro_list").length) {
        bindItemsList({ ID: $("#hdn_cls_id").val(), start: 0, limit: ItemList.pagesize, order: $("#sel_sort>option:selected").val(), desc: $("#sel_order>option:selected").val(),race:'' });
    }
    if ($("#ul_pro_list").length) {
        //bindItemsList({ ID: $("#hdn_cls_id").val(), start: 0, limit: ItemList.pagesize, order: $("#sel_sort>option:selected").val(), desc: $("#sel_order>option:selected").val() });
    }
    if ($("#btn_reset").length) {
        $("#btn_reset").click(function() {
            bindItemsList({ ID: $("#hdn_cls_id").val(), start: 0, limit: ItemList.pagesize, order: $("#sel_sort>option:selected").val(), desc: $("#sel_order>option:selected").val(),race:'' });
        });
    }
    if ($("#h_switch").length) {
        $("#h_switch>span").mouseover(function() {
            $("#div_switch>div").hide();
            $(String.format("#p_{0}", this.id)).show();
        });
    }
    if ($("#navigation").length) {
        $("#navigation>li").mouseover(function() {
            var offset = $(this).offset();
            var w = $(this).width() / 2;
            $("#" + (this.id.replace("li_", "ul_sub_"))).css("left", w + "px").css("top", "0px"); //.show();

            //.mouseout(function() {$("#" + (this.id.replace("li_", "ul_sub_"))).hide();});
        });
        $(".menu_sub").mouseout(function(e) {
            //$(this).hide();
        });
    }

    if ($(".dv_currency").length) {
        changecurrency(0);
        $("input[name='ra_currency']:first").show().next().show();
    }
    if ($("#p_goods").length) {
        $("#p_goods").html(unescape($("#p_goods").html()))
    }
    if (window.location.href.toString().startsWith(g_host + "/product-detail.aspx")) {
        $.get(g_.code, { hits: "1", id: $("#hdn_item_id").val() }, function(data) { });
    }
    
    /*back to top*/
    $("<div class=\"center backtop\" id=\"dv_btop\"><img src=\"images/top.gif\" alt='top'/> <a href=\"#\">Back to Top</a></div>").appendTo("body").css("left",$().width()-130);
    $(window).scroll(function(evt){
        var vh = 0;
        if(document.documentElement&&document.documentElement.scrollTop){
            vh = document.documentElement.scrollTop
        }
        else{
            vh = $(window).scrollTop();
        }
        if(vh){
        
            $("#dv_btop").css("top",vh + $(window).height()-30).show(); 
        }
        else{
            $("#dv_btop").hide();
        }
    });

    var prompt = "data";
    if(window.location.href.indexOf("products-list.aspx")>0){
        prompt = "products list";
    }
    else if(window.location.href.indexOf("default.aspx")>0){
        prompt = "product class list";
    }
    else if(window.location.href.indexOf("product-detail.aspx")>0){
        prompt = "product infomation";
    }
    else if(window.location.href.indexOf("product-order.aspx")>0){
        prompt = "order and discount infomation";
    }
    
    if(!$.browser.msie){
        $(String.format("<div class=\"dv_load\"><img src=\"images/{0}\" /><p>please wait for {1} loading...</p></div>", "load.gif",prompt)).appendTo("#container").css("left", ($().width() - $(".dv_load").width()) / 2 + "px").css("top", ($().height() - $(".dv_load").height()) / 2 - 200 + "px").ajaxStart(function() {
            $(this).css("left", ($().width() - $(".dv_load").width()) / 2 + "px").css("top", ($().height() - $(".dv_load").height()) / 2 - 200 + "px").show();
        }).ajaxStop(function() { $(this).hide() });
    }
});

var ItemList = {
    pagesize: 10,
    gotonext: function(pos) {
        if (!pos) pos = 1;
        if (Number($("#p_c").text()) + pos - 1 == Number($("#p_t").text())) { return; }
        ItemList.go(Number($("#p_c").text()) + pos - 1);
    },
    gotolast: function() {
        ItemList.go(Number($("#p_t").text()) - 1);
    },
    go: function(idx) {
        if (idx < 0) idx = 0;
        bindItemsList({ ID: $("#hdn_cls_id").val(), start: idx * ItemList.pagesize, limit: ItemList.pagesize, order: $("#sel_sort>option:selected").val(), desc: $("#sel_order>option:selected").val(),race:'' });
    }
};
var gotonext = function(pos) {
    if (!pos) pos = 1;
    if (Number($("#p_c").text()) + pos - 1 == Number($("#p_t").text())) { return; }
    changefeedpage(Number($("#p_c").text()) + pos - 1);
};
var gotolast = function() {
    changefeedpage(Number($("#p_t").text()) - 1);
};
var changefeedpage = function(idx) {
    var pagesize = 5;
    if (!idx || idx < 0) idx = 0;
    if (idx > Number($("#p_t").text())) idx = Number($("#p_t").text());
    $.getJSON(g_.code, { comlist: "", itemid: $("#hdn_item_id").val(), start: idx * pagesize, limit: pagesize }, function(data) {
        var arr = [];
        for (var i in data.obj) {
            var obj = data.obj[i];
            arr.push(String.format("<dt><span class=\"date\">{0}</span>user: <font class=\"orange\">{1}</font></dt><dd><div>{2}</div></dd><dt>", new Date(Number(obj.CreateDate.replace("/Date(", "").replace(")/", ""))).toLocaleString(), unescape(obj.NickyName), unescape(obj.Content)));
        }
        $(".feed").empty().html(arr.join(''));
        $("#span_pinfo").html(String.format("Total {0} records, divided into <label id=\"p_t\">{1}</label>  pages.current index <label id=\"p_c\">{2}</label> page", data.c, Math.ceil(data.c / pagesize), idx + 1));
    });
};

var bindItemsCls = function(obj) {
    $.getJSON(g_.code, { prolist: "", cid: obj.ID }, function(data) {
        var strTitle = String.format("<h6><a href=\"product-list.aspx?cls={1}\" class=\"more\"><img src=\"images/more.gif\" alt=\"click to view more items\" title=\"click to view more items\" /></a>{0}</h6>", obj.ClassName, obj.ID);
        $("#pro_list").append(strTitle);
        var strList = "<div class=\"p_list\"><ul>";

        var arr = [];
        for (var i in data.obj) {
            var xobj = data.obj[i];
            arr.push(String.format("<li><a href=\"product-detail.aspx?pid={3}\"><img src=\"images/items/{0}\" alt=\"{1}\" title=\"{1}\" />{1}</a><span class=\"price\">{2}</span></li>", xobj.PictureUrl, xobj.Title, xobj.Price, xobj.ID));
        }
        strList += arr.join('');
        strList += "<li class=\"clear\"></li></ul><div class=\"clear\"></div></div>";
        $("#pro_list").append(strList);
    });
};

var buynow = function() {
    window.location.href = String.format("product-order.aspx?gid={0}&cid={1}&qid={2}", $("#hdn_item_id").val(), $("input[name=ra_currency]:checked").attr("id"), $("#tb_item_quantity").val());
};

var addcart = function(id, count, fn) {
    /*add item to cart*/
    if (!count) { count = 1; }
    $.getJSON(g_.code, { cart: "", id: id, c: count }, function(data) {
        if (data.length) {
            var total = 0;
            for (var index = 0, len = data.length; index < len; index++) {
                total += data[index].Value;
            }
            if (total) {
                $("#sp_cart").html(String.format("Your cart has {0} items,total {1}. you can <a href='{2}'>check out</a> now,or <a href='javascript:void(0);' onclick='emptycart()'>empty cart</a>", data.length, total, "product-order.aspx"));
            }
            else {
                $("#sp_cart").html("Your cart is empty.");
            }
            if (fn) {
                fn.call();
            }
            else {
                alert("cart operation is successed,please go on buy item");
            }
        }
        else {
            alert(data);
        }
    });
};
var deleteitem = function(id) {

    $.getJSON(g_.code, { removecart: "", id: id }, function(data) {
        if (data.length) {
            var total = 0;
            for (var index = 0, len = data.length; index < len; index++) {
                total += data[index].Value;
            }
            if (total) {
                $("#sp_cart").html(String.format("Your cart has {0} items,total {1}. you can <a href='{2}'>check out</a> now,or <a href='javascript:void(0);' onclick='emptycart()'>empty cart</a>", data.length, total, "product-order.aspx"));
            }
            else {
                $("#sp_cart").html("Your cart is empty.");
            }
            $(String.format("#tr{0}", id)).remove();
            alert("cart operation is successed.");
        }
        else {
            if (parseInt(data)) {
                $(String.format("#tr{0}", id)).remove();
                $("#sp_cart").html("Your cart is empty.");
                alert("cart operation is successed,but your cart is empty now,plz go on buy others.");
                window.location.href = "default.aspx";
            }
            else {
                alert("opration fail!");
            }
        }
    });
};
var emptycart = function() {
    /*get item from cart*/
    $.getJSON(g_.code, { cart: "", id: 0, empty: "true" }, function(data) {
        if (data) {
            $("#sp_cart").html("Your cart is empty.");
            alert("cart operater successed,please go on buy items");
            if (window.location.href.indexOf("product-order.aspx")) {
                window.location.href = "default.aspx";
            }
        }
        else {
            alert(data);
        }
    });
};
var bindItemsList = function(obj) {
    $.getJSON(g_.code, { prolist: "", cid: obj.ID, start: obj.start, limit: obj.limit, order: obj.order, desc: obj.desc,race:obj.race }, function(data) {
        var arr = [];
        var flag = false;
        for (var i = 0, l = data.obj.length; i < l; i++) {
            var xinfo = data.obj[i];
            if (i % 2) {
                arr.push(String.format("<div><a href=\"product-detail.aspx?pid={0}\" class=\"img_a\"><img src=\"images/items/{1}\" alt=\"{2}\" title=\"{2}\"></a><ul><li><span>Name:</span><span class=\"orange\">{2}</span></li><li>Race:<font class=\"orange\">{4}</font></li><li><span>Price:</span><font class=\"orange\">${3}</font></li><li><a href=\"product-detail.aspx?pid={0}\"><img src=\"images/detail.gif\" alt=\"click me to view detail\" title=\"click me to view detail\" style=\"border:0px;\" /></a><img src=\"images/addto.gif\" alt=\"click for add it to cart\" title=\"click for add it to cart\" style=\"border:0px;cursor:pointer;\" onclick=\"addcart('{0}')\" /><a href=\"product-order.aspx?gid={0}\"><img src=\"images/buynow.gif\" alt=\"click to buy it now\" title=\"click to buy it now\" style=\"border:0px;\" /></a></li></ul></div><br class=\"clear\"/></li>", xinfo.ID, xinfo.PictureUrl, xinfo.Title, xinfo.Price, xinfo.Race));
                flag = true;
            }
            else {
                arr.push(String.format("<li><div><a href=\"product-detail.aspx?pid={0}\" class=\"img_a\"><img src=\"images/items/{1}\" alt=\"{2}\" title=\"{2}\"></a><ul><li><span>Name:</span><span class=\"orange\">{2}</span></li><li>Race:<font class=\"orange\">{4}</font></li><li><span>Price:</span><font class=\"orange\">${3}</font></li><li><a href=\"product-detail.aspx?pid={0}\"><img src=\"images/detail.gif\" alt=\"click me to view detail\" title=\"click me to view detail\" style=\"border:0px;\" /></a><img src=\"images/addto.gif\" alt=\"click for add it to cart\" title=\"click for add it to cart\" style=\"border:0px;cursor:pointer;\" onclick=\"addcart('{0}')\" /><a href=\"product-order.aspx?gid={0}\"><img src=\"images/buynow.gif\" alt=\"click to buy it now\" title=\"click to buy it now\" style=\"border:0px;\" /></a></li></ul></div>", xinfo.ID, xinfo.PictureUrl, xinfo.Title, xinfo.Price, xinfo.Race));
                flag = false;
            }

        }
        if (!flag)
            arr.push("<br class=\"clear\"/></li>");
        var str = arr.join('');
        $("#ul_pro_list").empty().append(str);
        //$("#tb_pro_list>tbody").empty().append(str);
        //$("#pro_list").append(strList);
        $("#span_pinfo").html(String.format("Total {0} records, divided into <label id=\"p_t\">{1}</label>  pages.current index <label id=\"p_c\">{2}</label> page", data.c, Math.ceil(data.c / obj.limit), obj.start / obj.limit + 1));
    });
};

var changecurrency = function(id) {
    $("input[name='ra_currency']").each(function() {
        if ($(this).attr("id") != id) {
            $(this).hide().next().hide();
        }
        else {
            $(this).show().attr("checked", true).next().show();
        }
    });
};

var changerace = function(race){
    $.post(g_.code,{crace:'',race:race,clsid:/cls=(\d+)$/ig.exec(window.location.href)[1]},function(data){window.location = window.location.href;});
};