﻿// Javascript document
var Shopping = {
    cityId: 0, // Toàn quốc
    pageId: 0,
    Init: function (cityId) {
        this.cityId = cityId;
        $("#CitySelecteBox").val(cityId.toString());
        ShoppingCart.GetTotalInCart();
    }
}
// CategoryDataList
function CategorySort(a, b) {
    return parseInt(b.CateOrder) - parseInt(a.CateOrder);
}
function getTopMenu() {
    var htmlContent = '';
    //data = CategoryDataList.sort(CategorySort);
    var count = 0;
    for (var i = 0; i < CategoryDataList.length; i++) {
        var Cate = CategoryDataList[i];
        if (Cate.CateParentId == 0 && Cate.CateIsMenu) {
            htmlContent += '<li id="topmnuitem_{1}"><a href="/{0}/c{1}/p0/z1/">{2}</a></li>'.format(Cate.CateUrl, Cate.CateId, Cate.CateName.toUpperCase());
            count++;
        }
        if (count == 10) i = CategoryDataList.length;
    }
    $("#topcategorymenu").html(htmlContent);
}
function getBottomMenu() {
    var htmlContent = '';
    //data = CategoryDataList.sort(CategorySort);
    var n = CategoryDataList.length;
    var count = 0;
    for (var i = 0; i < n; i++) {
        var Cate = CategoryDataList[i];
        if (Cate.CateParentId == 0 && Cate.CateIsMenu) {
            htmlContent += '<li><a href="/{0}/c{1}/p{2}/z1/">{3}</a></li>'.format(Cate.CateUrl, Cate.CateId, Cate.CateParentId, Cate.CateName);
            count++;
        }
        if (count == 4) i = n;
    }
    $(".l2info1").html(htmlContent);
    count = 0;
    for (var j = 0; j < n; j++) {
        var Cate = CategoryDataList[j];
        if (Cate.CateParentId != 0 && Cate.CateIsMenu) {
            if (count < 4) {
                $(".l2info2").append('<li><a href="/{0}/c{1}/p{2}/z1/">{3}</a></li>'.format(Cate.CateUrl, Cate.CateId, Cate.CateParentId, Cate.CateName));
            } else if (count > 4) {
                $(".l2info3").append('<li><a href="/{0}/c{1}/p{2}/z1/">{3}</a></li>'.format(Cate.CateUrl, Cate.CateId, Cate.CateParentId, Cate.CateName));
            }
            count++;
        }
        if (count > 8) j = n;
    }
}
function activeTopMenuItem(cid) {
    var cateid = cid;
    if (cid > 0) {
        $("#topcategorymenu").find(".active").removeClass("active");
        var pid = cid;
        var index = 0;
        var continuedId = 0;
        while (pid != 0 && continuedId < CategoryDataList.length) {
            for (var i = 0; i < CategoryDataList.length; i++) {
                if (CategoryDataList[i].CateId == pid) {
                    pid = CategoryDataList[i].CateParentId;
                    index = i;
                    i = CategoryDataList.length;
                }
            }
            continuedId++;
        }
        cateid = CategoryDataList[index].CateId;
    }
    $("#topmnuitem_" + cateid).addClass("active");
}
function getPathCategory(cid) {
    if (cid > 0) {
        var pid = cid;
        var continuedId = 0;
        var arrayPath = [];
        while (pid != 0 && continuedId < CategoryDataList.length) {
            for (var i = 0; i < CategoryDataList.length; i++) {
                if (CategoryDataList[i].CateId == pid) {
                    pid = CategoryDataList[i].CateParentId;
                    arrayPath.push(CategoryDataList[i]);
                    i = CategoryDataList.length;
                }
            }
            continuedId++;
        }
        var htmlContent = "<a href=\"/\">Trang chủ</a>";
        while (arrayPath.length > 0) {
            var category = arrayPath.pop();
            htmlContent += "&nbsp;>&nbsp;<a href=\"/{0}/c{1}/p{2}/z1/\" >{3}</a>".format(category.CateUrl, category.CateId, category.CateParentId, category.CateName);
        }
        $("#pathcategory").html(htmlContent);
    }
}

function GetListSubCateFinal(cid) {
    var htmlContent = '';
    var arraySubCategory = [];
    var index = 0;
    for (var i = 0; i < CategoryDataList.length; i++) {
        if (CategoryDataList[i].CateParentId == cid) {
            arraySubCategory.push(CategoryDataList[i]);
        }
        if (CategoryDataList[i].CateId == cid) index = i;
    }
    if (arraySubCategory.length <= 0) {
        cid = CategoryDataList[index].CateParentId;
        for (var i = 0; i < CategoryDataList.length; i++) {
            if (CategoryDataList[i].CateParentId == cid) {
                arraySubCategory.push(CategoryDataList[i]);
            }
        }
    }
    if (arraySubCategory.length > 0) {
        $("#subcatebox").show();
        htmlContent = '<ul>';
        while (arraySubCategory.length > 0) {
            var Category = arraySubCategory.pop();
            htmlContent += '<li><a href="/{0}/c{1}/p{2}/z1/">{3} <span>({4})</span></a></li>'.format(Category.CateUrl, Category.CateId, Category.CateParentId, Category.CateName, Category.ItemCounter);
        }
        htmlContent += '</ul>';
        $("#menuList").html(htmlContent);
    } else $("#subcatebox").hide();
}
$.fn.extend({
    GetSpecialBanner: function (data) {
        var objCon = $(this);
        var htmlContent = '';
        //CallAjax("/getrequest.ashx?m=cate&ac=getbypos&top=5", function (data) {
        if (data != null && data.CategoryList.length > 0) {
            $.each(data.CategoryList, function (i, Cate) {
                htmlContent += '<a href="/{0}/c{1}/p0/z1/\"><img alt="{2}" src="{3}.630.275.jpg" style="width:630px; height:275px;" />'.format(Cate.Link, Cate.Id, Cate.Name, domainImage + Cate.ImageUrl);
            });
            objCon.html(htmlContent);
            objCon.nivoSlider();
        }
        //});
    },
    GetTopBestDeal: function () {
        var objCon = $(this);
        CallAjax("/getrequest.ashx?m=product&ac=topbestdeal&top=2", function (data) {
            if (data != null && data.ProductList.length > 0) {
                var htmlContent = "";
                $.each(data.ProductList, function (idx, product) {
                    htmlContent += '<div class="item">';
                    htmlContent += '    <a href="/Product/{1}/{2}/"><img src="{0}.140.100.jpg" border="0" /></a> <a class="title" href="/Product/{1}/{2}/">{3}</a> <span class="price">Giá: {4} VNĐ</span>'.format(domainImage + product.ImageUrl, product.LinkUrl, product.Id, product.Name, CurrencyFormat(product.Price));
                    htmlContent += '</div>';
                });
                objCon.html(htmlContent);
            }
        });
    },
    GetTopLatestProduct: function () {
        var objCon = $(this);
        CallAjax("/getrequest.ashx?m=product&ac=toplatest&top=20&city=" + Shopping.cityId, function (data) {
            if (data != null && data.ProductList.length > 0) {
                var htmlContent = "";
                $.each(data.ProductList, function (idx, product) {
                    htmlContent += '<li>';
                    htmlContent += '<div class="item_thumbnail item_ssm">';
                    htmlContent += '    <div class="center">';
                    htmlContent += '        <div class="image">';
                    htmlContent += '            <a href="/Product/{0}/{1}/" title="{3}"><img src="{2}.160.125.jpg" border="0" /></a></div>'.format(product.LinkUrl, product.Id, domainImage + product.ImageUrl, product.Name);
                    htmlContent += '        <div class="title">';
                    htmlContent += '            <a href="/Product/{0}/{1}/">{2}</a><span class="productSpecialPrice">{3} VNĐ</span>'.format(product.LinkUrl, product.Id, SubString(product.Name, 20), CurrencyFormat(product.Price));
                    htmlContent += '        </div>';
                    htmlContent += '    </div>';
                    htmlContent += '</div>';
                    htmlContent += '</li>';
                });
                objCon.html(htmlContent);
                $("#slidelatestproduct").scrollShow({
                    view: "#latestproductbox",
                    content: "#latestproductbox>ul",
                    elements: "li",
                    btnPrev: "#btnleft_latest",
                    btnNext: "#btnright_latest",
                    auto: true,
                    start: 0
                });
            }
        });
    },
    GetTopSpecialProduct: function () {
        var objCon = $(this);
        var htmlContent = "";
        CallAjax("/getrequest.ashx?m=product&ac=topspecial&top=12", function (data) {
            if (data != null && data.ProductList.length > 0) {
                $.each(data.ProductList, function (idx, product) {
                    htmlContent += '<li>';
                    htmlContent += '<div class="item_thumbnail item_sm">';
                    htmlContent += '    <div class="center">';
                    htmlContent += '        <div class="image">';
                    htmlContent += '            <a href="/Product/{0}/{1}/" title="{3}"><img src="{2}.160.125.jpg" border="0" /></a></div>'.format(product.LinkUrl, product.Id, domainImage + product.ImageUrl, product.Name);
                    htmlContent += '        <div class="title">';
                    htmlContent += '            <a href="/Product/{0}/{1}/">{2}</a><span class="productSpecialPrice">{3} VNĐ</span>'.format(product.LinkUrl, product.Id, SubString(product.Name, 20), CurrencyFormat(product.Price));
                    htmlContent += '        </div>';
                    htmlContent += '    </div>';
                    htmlContent += '</div>';
                    htmlContent += '</li>';
                });
                objCon.html(htmlContent);
                $("#slidespecial").scrollShow({
                    view: "#specialproductbox",
                    content: "#specialproductbox>ul",
                    elements: "li",
                    btnPrev: "#btnleft_special",
                    btnNext: "#btnright_special",
                    auto: true,
                    start: 0
                });
            }
        });
    },
    GetTopFavoriteStore: function () {
        var objCon = $(this);
        CallAjax("/GetRequest.ashx?m=store&ac=topfavorite&top=4", function (data) {
            if (data != null && data.StoreList.length > 0) {
                var htmlContent = '';
                $.each(data.StoreList, function (idx, store) {
                    htmlContent += '<li>';
                    htmlContent += '    <a href="/shop/' + store.Id + '/' + store.LinkUrl + '/"><img src="' + domainImage + store.Logo + '.50.50.jpg" /></a>';
                    htmlContent += '    <p><a class="bold" href="/shop/' + store.Id + '/' + store.LinkUrl + '/">' + SubString(store.Name, 20) + '</a><br>';
                    //htmlContent += '    ' + CurrencyFormat(store.Likes) + ' người thích</p>';
                    htmlContent += '</li>';
                });
                objCon.html(htmlContent);
            }
        });
    },
    GetTopPopularCate: function (data) {
        var objCon = $(this);
        if (data != null && data.ProductList.length > 0) {
            var htmlContent = '<ul>';
            $.each(data.ProductList, function (idx, product) {
                htmlContent += '<li><a class="fl" href="/Product/{0}/{1}/"><img src="{3}{4}.120.120.jpg" alt="{2}" /></a><br /><a class="fl" href="/Product/{0}/{1}/">{2}</a><br /><span class="price fl">Giá: {5} VNĐ</span></li>'.format(product.LinkUrl, product.Id, product.Name, domainImage, product.ImageUrl, CurrencyFormat(product.Price));
            });
            htmlContent += '</ul>';
            objCon.html(htmlContent);
        }
    },
    GetTopPopularProduct: function (cid) {
        var objCon = $(this);
        CallAjax("/getrequest.ashx?m=product&ac=toppopular&top=10&cid=" + cid, function (data) {
            if (data != null && data.ProductList.length > 0) {
                var htmlContent = '<ul>';
                $.each(data.ProductList, function (idx, product) {
                    htmlContent += '<li><a class="fl" href="/Product/{0}/{1}/"><img src="{3}{4}.120.120.jpg" alt="{2}" /></a><br /><a class="fl" href="/Product/{0}/{1}/">{2}</a><br /><span class="price fl">Giá: {5} VNĐ</span></li>'.format(product.LinkUrl, product.Id, product.Name, domainImage, product.ImageUrl, CurrencyFormat(product.Price));
                });
                htmlContent += '</ul>';
                objCon.html(htmlContent);
            }
        });
    },
    GetTopRecommentView: function () {
        var objCon = $(this); var htmlContent = '';
        CallAjax("/getrequest.ashx?m=product&ac=getlatestview&timeview=" + Math.random(), function (data) {
            if (data != null && data.ProductList.length > 0) {
                $("#head_recommentbox").text('Sản phẩm bạn quan tâm');
                $.each(data.ProductList, function (idx, product) {
                    if (idx < 3) {
                        htmlContent += '<div class="item">';
                        htmlContent += '    <a href="/Product/' + product.Link + '/' + product.Id + '/" class="fl"><img src="' + domainImage + product.ImageUrl + '.150.50.jpg" /></a><br />';
                        //htmlContent += '    <a href="/shop/' + product.Link + '/' + product.Id + '/">' + SubString(product.Name, 20) + '</a><br>';
                        htmlContent += ' <span class="price">Giá ' + CurrencyFormat(product.Price) + ' VNĐ</span>';
                        htmlContent += '</div>';
                    }
                });
                htmlContent += '</div>';
                objCon.html(htmlContent);
            } else {
                $("#head_recommentbox").text('Giới thiệu shopxinhxinh');
                CallAjax("/GetRequest.ashx?m=news&ac=bycate&top=5&cid=27&t=2", function (dataNews) {
                    if (dataNews != null) {
                        htmlContent += '<div class="contentbox">';
                        $.each(dataNews.NewsList, function (newsIndex, News) {
                            htmlContent += "- <a href=\"/support/" + News.Id + "/" + News.Link + "/\">" + News.Title + "</a><br />" + SubString(News.Desc, 300);
                        });
                        htmlContent += '</div>';
                    }
                    objCon.html(htmlContent);
                });
            }
        });
    },
    GetTopNewsService: function () {
        var objCon = $(this);
        CallAjax("/GetRequest.ashx?m=news&ac=bycate&top=1&cid=75&t=2", function (data) {
            if (data != null) {
                var htmlContent = '<div class="contentbox">';
                $.each(data.NewsList, function (newsIndex, News) {
                    htmlContent += "- <a href=\"/support/" + News.Id + "/" + News.Link + "/\">" + News.Title + "</a><br />" +  SubString(News.Desc, 300);
                });
                htmlContent += '</div>';
                objCon.html(htmlContent);
            }
        });
    },
    GetTopLatestViewProduct: function () {
        var objCon = $(this);
        CallAjax("/getrequest.ashx?m=product&ac=getlatestview&timeview=" + Math.random(), function (data) {
            if (data != null && data.ProductList.length > 0) {
                var htmlContent = '';
                $.each(data.ProductList, function (idx, product) {
                    if (idx < 10) {
                        htmlContent += '<div class="item">';
                        htmlContent += '    <a href="/Product/{0}/{1}/"><img src="{2}{3}.120.120.jpg" border="0" /></a> <a class="title" href="/Product/{0}/{1}/">{4}.</a><br /><span class="price">Giá: {5} VNĐ</span>'.format(product.Link, product.Id, domainImage, product.ImageUrl, SubString(Base64.decode(product.Name), 30), CurrencyFormat(product.Price));
                        htmlContent += '</div>';
                    }
                });
                objCon.html(htmlContent);
            } else {
                objCon.html("<i>Bạn chưa xem sản phẩm nào.</i>");
            }
        });
    },
    CurentPage: 1,
    NumRow: 16,
    ObjPagging: new Pagging(1, 0, "#PageNaviButton", function () { }, "$().ObjPagging", 10, 5, "pages_m", false),
    GetProductFilter: function (cid, sid, tmp) {
        if (typeof tmp == "undefined") tmp = 0;
        //loading();
        var objCon = $(this);
        var pageIndex = this.CurentPage;
        var pageSize = this.NumRow;
        var ord = 2;
        var filter = "&page={0}&pagesize={1}&cateId={2}".format($().ObjPagging.currentPage, pageSize, cid);
        if (typeof (sid) == "undefined") sid = 0;
        if (sid > 0) filter += "&sid=" + sid;
        if ($("#sortSelected").length > 0 && $("#sortSelected").val() != "") ord = $("#sortSelected").val();
        filter += "&ord=" + ord;
        SendRequestAjax("/getrequest.ashx?m=product&ac=getbyfilter" + filter, $("#frm_filter").serialize(), function (data) {
            if (data != null && data.ProductList.length > 0) {
                if (tmp == 0) {
                    objCon.setTemplateURL("/Templates/ProductList.htm");
                    $("#view_as_list").addClass("active");
                    $("#view_as_grid").removeClass("active");
                    objCon.removeClass("cat_products").addClass("cat_products_list");
                }
                else {
                    objCon.setTemplateURL("/Templates/ProductThumb.htm");
                    $("#view_as_grid").addClass("active");
                    $("#view_as_list").removeClass("active");
                    objCon.removeClass("cat_products_list").addClass("cat_products");
                }
                objCon.processTemplate(data);
                $("#amountProduct").text(data.totalRow + " Sản phẩm");
                $().ObjPagging.handler = "";
                $().ObjPagging.totalRow = data.totalRow;
                $().ObjPagging.rowPerPage = pageSize;
                $().ObjPagging.callBack = function () { objCon.GetProductFilter(cid, sid, tmp); }
                $().ObjPagging.WrapPagging();

                $("#sortSelected").unbind("change").change(function () { objCon.GetProductFilter(cid, sid, tmp); });
                $("#sortSelected").val(ord);
                $("#view_as_list").unbind("click").click(function () { objCon.GetProductFilter(cid, sid, 0); });
                $("#view_as_grid").unbind("click").click(function () { objCon.GetProductFilter(cid, sid, 1); });
            } else {
                objCon.html("Chưa có dữ liệu.");
                $("#amountProduct").text("0 Sản phẩm");
                $("#PageNaviButton").empty();
            }
            //loadCompleted();
        });
    },
    ProductCategoryTogether: function (cid, id) {
        var objCon = $(this);
        var filter = "&deep=0&page=1&pagesize=15&cateId={0}&id={1}".format(cid, id);
        CallAjax("/getrequest.ashx?m=product&ac=getbyfilter" + filter, function (data) {
            if (data != null && data.ProductList.length > 0) {
                //                var htmlContent = '';
                //                $.each(data.ProductList, function (idx, product) {

                //                    htmlContent += '<div class="item">';
                //                    htmlContent += '    <a href="/Product/{0}/{1}/"><img src="{2}{3}.120.120.jpg" border="0" /></a> <a class="title" href="/Product/{0}/{1}/">{4}.</a><br /><span class="price">Giá: {5} VNĐ</span>'.format(product.Link, product.Id, domainImage, product.ImageUrl, SubString(product.Name, 30), CurrencyFormat(product.Price));
                //                    htmlContent += '</div>';
                //                });
                objCon.setTemplateURL("/Templates/ProductThumb.htm");
                objCon.processTemplate(data);
                //objCon.html(htmlContent);
            } else {
                objCon.html("<i>Dữ liệu đang được cập nhật.</i>");
            }
        });
    },
    GetProductRelatedList: function (cid, id) {
        var objCon = $(this);
        var pageIndex = this.CurentPage;
        var pageSize = this.NumRow;
        var ord = 0;
        objCon.loading();
        var filter = "&deep=0&page={0}&pagesize={1}&cateId={2}&id={3}".format(pageIndex, pageSize, cid, id);
        if ($("#txtFromPrice").length > 0 && Trim($("#txtFromPrice").val()) != "") filter += "&from=" + $("#txtFromPrice").val();
        if ($("#txtToPrice").length > 0 && Trim($("#txtToPrice").val()) != "") filter += "&to=" + $("#txtToPrice").val();
        if ($("#txtKey").length > 0 && Trim($("#txtKey").val()) != "") filter += "&key=" + $("#txtKey").val();
        if ($("#sortSelected").length > 0 && $("#sortSelected").length > 0 && $("#sortSelected").val() != "") ord = $("#sortSelected").val();
        filter += "&ord=" + ord;
        CallAjax("/getrequest.ashx?m=product&ac=getbyfilter" + filter, function (data) {
            if (data != null && data.ProductList.length > 0) {
                objCon.setTemplateURL("/Templates/ProductList.htm");
                objCon.processTemplate(data);
                $("#totalItem").text(data.totalRow);
                WrapPagging(data.totalRow, pageIndex, pageSize, function (page, size) {
                    objCon.CurentPage = page;
                    objCon.NumRow = size;
                    objCon.GetProductRelatedList(cid, id);
                }, "#PageNaviButton");
                $("#sortSelected").unbind("change").change(function () { objCon.GetProductRelatedList(cid, id); });
                $("#sortSelected").val(ord);
            } else {
                objCon.html("<i>Dữ liệu đang được cập nhật.</i>");
            }
            objCon.loadCompleted();
        });
    },
    GetStoreDetail: function (id) {
        var objCon = $(this);
        CallAjax("/GetRequest.ashx?m=store&ac=detail&id=" + id, function (store) {
            if (store != null) {
                var contentHTML = '';
                contentHTML += 'Nhà cung cấp: <a class="bold" href="/shop/{0}/{1}/">{2}</a>.<br />'.format(store.Id, store.Link, store.Name);
                contentHTML += store.Address != "" ? '<strong>Đ/c</strong>: {0}.<br />'.format(store.Address) : "";
                contentHTML += store.Tel != "" ? '<strong>ĐT</strong>: {0}.<br />'.format(store.Tel) : "";
                contentHTML += store.Email != "" ? '<strong>Email</strong>: <a href="mailto:{0}">{0}</a>.<br />'.format(store.Email) : "";
                contentHTML += store.Web != "" ? '<strong>Website</strong>:<a href="/redirect.aspx?url={0}>{0}</a>.'.format(store.Web) : "";
                objCon.html(contentHTML);
            }
        });
    },
    GetTopProductInStore: function (id, tmp) {
        var objCon = $(this);
        if (id && id > 0) {
            CallAjax("/getrequest.ashx?m=product&ac=topbystore&top=8&sid=" + id, function (data) {
                if (data != null && data.ProductList.length > 0) {
                    if (tmp == 0) {
                        objCon.setTemplateURL("/Templates/ProductList.htm");
                        $("#view_as_list").addClass("active");
                        $("#view_as_grid").removeClass("active");
                        $("#view_as_grid").unbind("click").click(function () { objCon.GetTopProductInStore(id, 1); });
                        objCon.removeClass("cat_products").addClass("cat_products_list");
                    }
                    else {
                        objCon.setTemplateURL("/Templates/ProductThumb.htm");
                        $("#view_as_grid").addClass("active");
                        $("#view_as_list").removeClass("active");
                        $("#view_as_list").unbind("click").click(function () { objCon.GetTopProductInStore(id, 0); });
                        objCon.removeClass("cat_products_list").addClass("cat_products");
                    }

                    objCon.processTemplate(data);
                }
            });
        } else {
            objCon.html("Chưa có dữ liệu");
        }
    },
    GetCategoryListInStore: function (storeId, cateId, cateIdList) {
        var objCon = $(this);
        CallAjax("/getrequest.ashx?m=cate&ac=cateinstore&id=" + storeId + "&cid=" + cateIdList, function (data) {
            if (data != null && data.CategoryList.length > 0) {
                var htmlContent = ""; // = "<a href=\"?view=all&chanel=0&cate=0\">Tất cả các chuyên mục</a><br>";
                htmlContent += objCon.BindCategoryListInstore(data.CategoryList, cateId, 0, "0");
                objCon.html(htmlContent);
            }
        });
    },
    BindCategoryListInstore: function (CategoryList, cateId, parentId, link) {
        var objCon = $(this);
        var htmlContent = "";
        var cateLink = link != "" ? link + "," : "";
        $.each(CategoryList, function (idx, cate) {
            if (parentId == cate.CateParentId) {
                if (cate.CateId == cateId) {
                    htmlContent += '<li class="actived"><a class="actived" href="?view=all&chanel={0}&cate={1}">- {2} ({3})</a>'.format(cate.CateId, cateLink + cate.CateId, cate.CateName, cate.ItemCounter);
                } else {
                    htmlContent += '<li><a href="?view=all&chanel={0}&cate={1}">- {2} ({3})</a>'.format(cate.CateId, cateLink + cate.CateId, cate.CateName, cate.ItemCounter);
                }
                htmlContent += objCon.BindCategoryListInstore(CategoryList, cateId, cate.CateId, cateLink + cate.CateId) + "</li>";
            }
        });
        if (htmlContent != "") htmlContent = "<ul>" + htmlContent + "</ul>";
        return htmlContent;
    },
    SetStoreInfo: function (store) {
        $("#imgStoreLogo").attr("src", domainImage + store.Logo + ".200.200.jpg");
        //$("#contentBox").GetTopProductInStore(store.Id);
        $("#contentBox").GetProductFilter(0, store.Id, 1);
        $("#linkViewAll").html("<a href=\"/shop/{0}/{1}/?view=all&chanel=0&cate=0\">Xem toàn bộ sản phẩm của gian hàng</a>".format(store.Id, store.LinkUrl));
    },
    BindCateToSelectBox: function (id) {
        if (typeof (id) == "undefined") id = -1;
        if (id.toString() == "") id = -1;
        var objCon = $(this);
        var htmlContent = "";
        if (id >= 0) {
            $(".selectboxcate").loading();
            CallAjax("/getrequest.ashx?m=cate&ac=getbyparent&pid=" + id, function (data) {
                if (data.CategoryList.length > 0) {
                    htmlContent += "<select id=\"sltCategory_" + id + "\" size=\"2\" name=\"cateidlist\" onchange=\"$('#selectboxcate_" + id + "').BindCateToSelectBox(this.value)\">";
                    $.each(data.CategoryList, function (idx, category) {
                        htmlContent += "<option value=\"" + category.Id + "\">" + category.Name + "</option>";
                    });
                    htmlContent += "</select>";
                    htmlContent += "<div id=\"selectboxcate_" + id + "\"></div>";
                }
                else if (id > 0) {
                    htmlContent = "<div style=\"width:200px; height:150px; padding-top:30px; background:#eaeaea; color:#333; text-align:justify;\">Bạn đã lựa chọn chuyên mục sản phẩm. Hãy nhấn nút 'Tiếp tục' bên dưới để đăng sản phẩm.</div>";
                }
                if ($("select[name='cateidlist']").length > 0) {
                    $("#btnContinue").removeAttr("disabled");
                } else {
                    $("#btnContinue").attr("disabled");
                }
                objCon.html(htmlContent);
                $(".selectboxcate").loadCompleted();
            }, "cache_CategoryByParent" + id);
        }
    },
    BindCateToSelectedBox: function (id, selectedCate) {
        if (typeof (id) == "undefined") id = -1;
        if (id.toString() == "") id = -1;
        var objCon = $(this);
        var htmlContent = "";
        if (id >= 0) {
            $(".selectboxcate").loading();
            CallAjax("/getrequest.ashx?m=cate&ac=getbyparent&pid=" + id, function (data) {
                if (data.CategoryList.length > 0) {
                    htmlContent += "<select id=\"sltCategory_" + id + "\" size=\"2\" name=\"cateidlist\" onchange=\"$('#selectboxcate_" + id + "').BindCateToSelectBox(this.value)\">";
                    $.each(data.CategoryList, function (idx, category) {
                        htmlContent += "<option value=\"" + category.Id + "\">" + category.Name + "</option>";
                    });
                    htmlContent += "</select>";
                    htmlContent += "<div id=\"selectboxcate_" + id + "\"></div>";
                }
                else if (id > 0) {
                    htmlContent = "<div style=\"width:200px; height:150px; padding-top:30px; background:#eaeaea; color:#333; text-align:justify;\">Bạn đã lựa chọn chuyên mục sản phẩm. Hãy nhấn nút 'Tiếp tục' bên dưới để đăng sản phẩm.</div>";
                }
                if ($("select[name='cateidlist']").length > 0) {
                    $("#btnContinue").removeAttr("disabled");
                } else {
                    $("#btnContinue").attr("disabled");
                }
                objCon.html(htmlContent);
                $.each(selectedCate, function (idx, cate) {
                    if (cate.Pid == id) {
                        $("#sltCategory_" + id).val(cate.Id);
                        $('#selectboxcate_' + id).BindCateToSelectedBox(cate.Id, selectedCate);
                    }
                });
                $(".selectboxcate").loadCompleted();
            }, "cache_CategoryByParent" + id);
        }
    },
    CategoryListSelected: function (data) {
        var htmlContent = "";
        if (data.CategoryList.length > 0) {
            $.each(data.CategoryList, function (idx, category) {
                htmlContent += '<a href="#">' + category.Name + '</a>';
                if (idx < data.CategoryList.length - 1)
                    htmlContent += " > ";
            });
        }
        else htmlContent = "<i>Bạn chưa chọn loại sản phẩm nào.</i>";
        $(this).html(htmlContent);
    },
    ShowPopupImage: function () {
        var src = $(this).attr("src").replace(".250.250.jpg", ".600.O.jpg");
        showPopupBlock("#blockPopupImage", 600, 500, "Xem ảnh cỡ lớn", function () {
            $("#blockPopupImage").html('<img onclick="$(\'#blockPopupImage\').dialog(\'close\')" src="' + src + '" id="_img_popup_view" />');
            $("#_img_popup_view").load(function () {
                $("#blockPopupImage").parent().width($("#_img_popup_view").width() + 28);
                var h = $("#_img_popup_view").height() < 610 ? $("#_img_popup_view").height() : 600;
                $("#blockPopupImage").height(h);
            });
        });
    },
    FocusTo: function (obj) {
        var imgThumb = $(this).attr("src").replace(".120.120.jpg", ".250.250.jpg");
        $(obj).attr("src", imgThumb);
        var imgZoomSrc = $(this).attr("src").replace(".120.120.jpg", "");
        $(".jqzoom").attr("href", imgZoomSrc);
        $(".zoomPad").attr("href", imgZoomSrc);
        $(".zoomWrapperImage>img").attr("src", imgZoomSrc);
        $(".zoomPup>img").attr("src", imgThumb);

        $("#imageproductlist>li.actived").removeClass("actived");
        $(this).parent().parent().addClass("actived");
    },
    GetImageProductList: function (pid) {
        var objCont = $(this);
        CallAjax("/GetRequest.ashx?m=image&ac=imageproduct&pid=" + pid, function (data) {
            if (data.ImageList.length > 0) {
                var htmlContent = '';
                $.each(data.ImageList, function (idx, image) {
                    //htmlContent += '<li><a href="javascript:void(0)"><img src="' + domainImage + image.ImageUrl + '.120.120.jpg" onmouseover="$(this).FocusTo(\'#ImgProduct\')"/></a></li>';
                    htmlContent += '<li><a href="javascript:void(0);" rel="{gallery: \'gal1\', smallimage: \'' + domainImage + image.ImageUrl + '.250.250.jpg\',largeimage: \'' + domainImage + image.ImageUrl + '\'}"><img src="' + domainImage + image.ImageUrl + '.120.120.jpg"></a></li>';
                });
                objCont.html(htmlContent);
            }
            else {
            }

            $('.jqzoom').jqzoom({
                zoomType: 'reverse',
                showEffect: 'fadein',
                hideEffect: 'hide',
                lens: true,
                preloadImages: false,
                alwaysOn: false,
                zoomWidth: 670,
                zoomHeight: 500
            });
        });
    }
});
var StoreImage = {
    SelectedImageList: [],
    SelecteImage: function (obj) {
        if ($(obj).hasClass("selected")) {
            $(obj).removeClass("selected");
            $('#_image_selected_' + $(obj).attr("rel")).remove();
        }
        else {
            if (typeof (limited) == "undefined") limited = 5;
            //if ($("#imageList>div.imageItem").length > 0) limited = selectNumber - $("#imageList>div.imageItem").length;
            var selectedNumber = $("._image_selected_").length > 0 ? $("._image_selected_").length : 0;
            if ($("#imageList>div.imageItem").length > 0) selectedNumber = selectedNumber + $("#imageList>div.imageItem").length;
            if (selectedNumber >= limited) {
                showMessageBox("Bạn chỉ được phép chọn {0} ảnh.".format(limited));
            }
            else {
                $(obj).addClass("selected");
                var offset = $(obj).offset();
                $(obj).after('<div class="_image_selected_" id="_image_selected_' + $(obj).attr("rel") + '" style="z-index:1002;position:relative;width:16px;height:16px;margin-top:-' + ($(obj).outerHeight() + 3) + 'px;margin-left:' + ($(obj).outerWidth() - 16) + 'px;background:url(\'/images/icons/ok.gif\') no-repeat right #fff;">&nbsp;</div>');
            }
        }
    },
    DeleteImageFromGallery: function () {
        var idList = [];
        if ($("._image_selected_").length > 0) {
            showConfirmBox("Bạn có chắc chắn xóa những ảnh đã chọn?", function () {
                $.each($("._image_selected_"), function (idx, item) {
                    idList.push($(item).attr("id").replace("_image_selected_", ""));
                });
                SendRequestAjax("/GetRequest.ashx?m=image&ac=delete", "idlist=" + idList, function (data) {
                    if (data.Result == "success") {
                        StoreImage.BindImageList();
                    }
                    else {
                        showMessageBox("Đã có lỗi xảy ra, hãy thử lại.");
                    }
                });
            });
        } else {
            showMessageBox("Bạn chưa chọn ảnh nào. Hãy chọn ít nhất một ảnh để xóa.");
        }
    },
    DeleteItem: function (i) {
        showConfirmBox("Bạn có chắc chắn xóa không?", function () {
            StoreImage.SelectedImageList.removeAt(i);
            StoreImage.BindImageToBox();
        });
    },
    SwappedItem: function (x, h) {
        if (h == 0)//move to left
            this.SelectedImageList.swapped(x - 1, x);
        else // move to right
            this.SelectedImageList.swapped(x, x + 1);
        this.BindImageToBox();
    },
    BindImageToBox: function (objCont) {
        if (typeof (objCont) == "undefined") objCont = "#imageList";
        $(objCont).html("");
        var htmlContent = "";
        if (StoreImage.SelectedImageList.length > 0) {
            $.each(StoreImage.SelectedImageList, function (idx, image) {
                htmlContent = '<div class="imageItem fl" style="width: 126px; height: 160px; padding: 2px; margin-right: 2px; border: solid 1px #ccc; text-align: center;">';
                htmlContent += '<span>' + (idx + 1) + '</span>';
                htmlContent += '<img src="' + image.Src + '" alt="default" style="padding: 2px; border: solid 1px #ccc; vertical-align: middle;" /><br />';
                htmlContent += (idx == 0 ? '<img src="/images/buttons/iconInactMoveLt_16x16.gif" class="noborder" />&nbsp;' : '<a href="javascript:void(0)" onclick="StoreImage.SwappedItem(' + idx + ',0)" title="Chuyển sang trái"><img src="/images/buttons/iconMoveLt_16x16.gif" /></a>&nbsp;');
                htmlContent += (idx == (StoreImage.SelectedImageList.length - 1) ? '<img src="/images/buttons/iconInactMoveRt_16x16.gif" class="noborder" />&nbsp;' : '<a href="javascript:void(0)" onclick="StoreImage.SwappedItem(' + idx + ',1)" title="Chuyển sang phải"><img src="/images/buttons/iconMoveRt_16x16.gif" /></a>&nbsp;');
                htmlContent += '<a href="javascript:void(0)" title="Xóa ảnh" onclick="StoreImage.DeleteItem(' + idx + ');"><img src="/images/buttons/iconTrashcan_16x16.gif" class="noborder" /></a>';
                htmlContent += '<input type="hidden" name="imageidlist" value="' + image.Id + '" />';
                if (idx == 0) {
                    htmlContent += '<input type="hidden" name="ImageUrl" value="' + StoreImage.SelectedImageList[0].Src.replace(domainImage, "").replace(".120.120.jpg", "") + '" />';
                }
                htmlContent += '</div>';
                $(objCont).append(htmlContent);
            });
        }
    },
    BindImageList: function (ctrl) {
        if (typeof (ctrl) == "undefined") ctrl = 0;
        loading();
        CallAjax("/GetRequest.ashx?m=image&ac=getListByAccount", function (data) {
            if (data != null && data.ImageList.length > 0) {
                var htmlContent = "<ul>";
                if (StoreImage.SelectedImageList.length <= 0 || ctrl != 0) {
                    $.each(data.ImageList, function (i, image) {
                        htmlContent += "<li><img id=\"imageItem_" + image.ImageId + "\" src=\"" + domainImage + image.ImageUrl + ".120.120.jpg\" rel=\"" + image.ImageId + "\" alt=\"" + image.OriginalName + "\" onclick=\"StoreImage.SelecteImage(this)\" title=\"" + image.OriginalName + "\" /></li>";
                    });
                }
                else {
                    $.each(data.ImageList, function (i, image) {
                        var ok = true;
                        $.each(StoreImage.SelectedImageList, function (idx, item) {
                            if (image.ImageId == item.Id) {
                                ok = false;
                            }
                        });
                        if (ok)
                            htmlContent += "<li><img id=\"imageItem_" + image.ImageId + "\" src=\"" + domainImage + image.ImageUrl + ".120.120.jpg\" rel=\"" + image.ImageId + "\" alt=\"" + image.OriginalName + "\" onclick=\"StoreImage.SelecteImage(this)\" title=\"" + image.OriginalName + "\" /></li>";
                    });
                }
                htmlContent += "</ul>";
                $("#ImageListBox").html(htmlContent);
            } else {
                $("#ImageListBox").html("<i>Chưa có ảnh nào</i>");
            }
            loadCompleted();
        });
    },
    ChoseImage: function (ctrl, objCont) {
        var fileUpload = "#FileUpload";
        if (typeof (ctrl) == "undefined") ctrl = 0;
        if (typeof (objCont) == "undefined") objCont = "#imageList";
        PopupFormDynamic("#popup_uploadimage", 720, 500, "Upload ảnh", {
            "Đóng": function () {
                $(this).dialog("close");
            },
            "Xóa ảnh": function () {
                StoreImage.DeleteImageFromGallery();
            },
            "Chèn ảnh": function () {
                var numSelectedImg = $("._image_selected_").length;
                if (numSelectedImg > 0) {
                    if (ctrl != 0) {// insert into content
                        $.each($("._image_selected_"), function () {
                            $(objCont).append('<img src="' + $("#imageItem_" + $(this).attr("id").replace("_image_selected_", "")).attr("src").replace(".120.120.jpg", ".600.O.jpg") + '" /><br />');
                        });
                    }
                    else { // select image to do avatar
                        var imageList = [];
                        $.each($("._image_selected_"), function () {
                            imageList.push({ Id: $(this).attr("id").replace("_image_selected_", ""), Src: $("#imageItem_" + $(this).attr("id").replace("_image_selected_", "")).attr("src") });
                        });
                        if (StoreImage.SelectedImageList.length > 0) {
                            StoreImage.SelectedImageList = StoreImage.SelectedImageList.concat(imageList);
                        }
                        else {
                            StoreImage.SelectedImageList = imageList;
                        }
                        StoreImage.BindImageToBox(objCont);
                    }
                }
                $(this).dialog('close');
            }
        }, function () {
            if ($("._image_selected_").length > 0)
                $("._image_selected_").remove();
        });
        $("#popup_uploadimage").html("Đang tải, xin đợi...");
        $("#popup_uploadimage").setTemplateURL("/Templates/UploadImage.aspx?ctrl=" + ctrl);
        $("#popup_uploadimage").processTemplate();
        $(fileUpload).uploadify({
            'uploader': '/Resources/uploadify.swf',
            'script': '/GetRequest.ashx%3Fm%3Dimage%26ac%3Dupload',
            'scriptData': { "ASPSESSID": ASPSESSID, "AUTHID": auth },
            'fileExt': '*.jpg;*.png;*.gif;*.bmp;*.jpeg',
            'fileDesc': '*.jpg;*.png;*.gif;*.bmp;*.jpeg',
            'buttonImg': "/images/buttons/Upload1.png",
            'cancelImg': "/images/icons/cancel.png",
            'rollover': true,
            'width': 78,
            'height': 22,
            'sizeLimit': 5242880, //~5MB
            'queueSizeLimit': 5,
            'auto': true,
            'multi': true,
            'onError': function (event, ID, fileObj, errorObj) {
            },
            'onProgress': function (event, ID, fileObj, data) {
            },
            'onComplete': function (event, ID, fileObj, response, data) {
            },
            'onAllComplete': function (event, data) {
                StoreImage.BindImageList(ctrl);
            }
        });
        StoreImage.BindImageList(ctrl);
    }
}

var ShoppingCart = {
    AddToCart: function (id) {
        CallAjax("/GetRequest.ashx?m=cart&ac=set&id=" + id, function (data) {
            if (data.Result == "success") {
                $("#TotalInCart").text(data.ItemListInCart.length);
                //showMessageBox("Sản phẩm đã được thêm vào giỏ hàng.");
                return goTo("/ViewCart.aspx");
            }
        });
    },
    GetTotalInCart: function () {
        CallAjax("/GetRequest.ashx?m=cart&ac=get", function (data) {
            $("#TotalInCart").text(data.ItemListInCart.length);
            if (Shopping.pageId == 2) {
                ShoppingCart.BindCartInfoToHtml(data);
            }
        });
    },
    UpdateItem: function (id) {
        CallAjax("/GetRequest.ashx?m=cart&ac=update&q=" + $("#_quantity_" + id).val() + "&id=" + id, function (data) {
            if (data.Result == "success") {
                ShoppingCart.GetTotalInCart();
            }
            else
            { alert('error'); }
        });
    },
    DeleteItem: function (id) {
        CallAjax("/GetRequest.ashx?m=cart&ac=del&id=" + id, function (data) {
            if (data.Result == "success") {
                ShoppingCart.GetTotalInCart();
            }
            else
            { alert('error'); }
        });
    },
    DeleteAll: function () {
        showConfirmBox("Bạn có chắc chắn muốn xóa giỏ hàng không?", function () {
            CallAjax("/GetRequest.ashx?m=cart&ac=clear", function (data) {
                if (data.Result == "success") {
                    ShoppingCart.GetTotalInCart();
                }
                else
                { alert('error'); }
            });
        });
    },
    BindCartInfoToHtml: function (data) {
        if (data.ItemListInCart.length > 0) {
            var htmlContent = "";
            $("#cartInfo").setTemplateURL("/templates/cart.htm");
            $("#cartInfo").processTemplate(data);
        }
        else {
            $("#cartInfo").html('<h3><i>Giỏ hàng của bạn chưa có sản phẩm nào. Hãy click <a href="/">vào đây</a> để chọn sản phẩm ngay.</i></h3>');
        }
    },
    ViewOrder: function () {
        CallAjax("/GetRequest.ashx?m=cart&ac=get", function (data) {
            CallAjax("/GetRequest.ashx?m=cart&ac=get", function (data) {
                $("#cartInfo").setTemplateURL("/templates/ConfirmOrder.htm");
                $("#cartInfo").processTemplate(data);
            });
        });
    },
    FormCustomerInfo: function () {
        CallAjax("/GetRequest.ashx?m=cart&ac=getcustomerinfo", function (data) {
            $("#cartInfo").setTemplateURL("/templates/CustomerInfo.htm");
            $("#cartInfo").processTemplate(data);
            $("#chkSame").unbind("click").click(function () {
                $("#txtRecFullName").val($("#txtFullName").val());
                $("#txtRecAddress").val($("#txtAddress").val());
                $("#txtRecPhone").val($("#txtPhone").val());
                $("#txtRecEmail").val($("#txtEmail").val());
            });
        });
    },
    Payment: function () {
        if ($("#txtFullName").val() == "" || $("#txtAddress").val() == "" || $("#txtPhone").val() == "") {
            showMessageBox("Bạn cần nhập đủ các thông tin của người mua nhận hàng");
            return false;
        };
        if ($("#txtRecFullName").val() == "" || $("#txtRecAddress").val() == "" || $("#txtRecPhone").val() == "") {
            showMessageBox("Bạn cần nhập đủ các thông tin của người nhận hàng");
            return false;
        };
        SendRequestAjax("/getrequest.ashx?m=product&ac=pay", $("#frmPayment").serialize(), function (data) {
            if (data.Result == "success") {
                showMessageBox("Bạn đã thanh toán thành công. Bạn sẽ được hướng về trang chủ trong vài giây sau.");
                setTimeout(function () { return goTo("/") }, 3000);
            }
        });
    }
}


var Store = {
    TextAreaContent: "#txtContent",
    TextAreaContent_W: 670,
    TextAreaContent_H: 350,
    InitFormUpdate: function () {
        var editorWidth = typeof (this.TextAreaContent_W) == "undefined" ? "660px" : this.TextAreaContent_W;
        var editorHeight = typeof (this.TextAreaContent_H) == "undefined" ? "350px" : this.TextAreaContent_H;
        $(this.TextAreaContent).tinymce({
            // General options
            theme: "advanced",
            language: "en",
            // Theme options
            plugins: "table,fullscreen,media,print",
            theme_advanced_toolbar_location: "top",
            theme_advanced_buttons1: "bold,italic,underline,|,justifyleft, justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,blockquote,|,formatselect,fontselect,fontsizeselect,|,fullscreen",
            theme_advanced_buttons2: "undo,redo,|,link,unlink,anchor,cleanup,code|hr,removeformat,|,sub,sup,|,charmap,|,table,media,image",
            theme_advanced_buttons3: "",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "",
            theme_advanced_resizing: false,
            width: editorWidth,
            height: editorHeight,
            theme_advanced_resizing: true,
            setup: function (ed) {
                ed.onSubmit.add(function (ed, e_) {
                    tinyMCE.activeEditor.setContent("");
                });
            }
        });
        $("#btnSave").unbind("click").click(this.PostProduct);
    },
    BindCategoryToCommboBox: function (id) {
        if (typeof id == "undefined") id = -1;
        loading();
        var htmlContent = "";
        if (CategoryDataList.length > 0) {
            htmlContent += "<select size=\"9\" selected=\"selected\" id=\"Ctrl1_CategorySelected\" name=\"cateId\" >";
            htmlContent += "<option value=\"-1\">----Chọn chuyên mục----</option>";
            htmlContent += this._private_loop_category(CategoryDataList, 0, "", "", 0);
            htmlContent += "</select>";
        }
        $("#selectedCate").html(htmlContent);
        $("#Ctrl1_CategorySelected").val(id);
        $("#selectedCate option:selected").focus();
        loadCompleted();
    }, // private method
    _private_loop_category: function (categoryList, pid, space, relOption, level) {
        var stringItem = "";
        var space1 = "----";
        var relOption1 = "|" + pid + "|,";
        if (pid > 0) {
            space += space1;
            relOption += relOption1;
            level++;
        }
        $.each(categoryList, function (idx, item) {
            if (item.CateParentId == pid) {
                stringItem += "<option value=\"" + item.CateId + "\" rel=\"" + relOption + "\">" + space + item.CateName + "</option>";
                if (level < 2) {
                    stringItem += Store._private_loop_category(categoryList, item.CateId, space, relOption, level);
                }
            }
        });
        return stringItem;
    },
    GetImageProductList: function (productId) {
        var htmlContent = '';
        CallAjax("/GetRequest.ashx?m=image&ac=imageproduct&pid=" + productId, function (data) {
            if (data.ImageList.length > 0) {
                $.each(data.ImageList, function (idx, image) {
                    StoreImage.SelectedImageList.push({ Id: image.ImageId, Src: domainImage + image.ImageUrl + ".120.120.jpg" });
                    htmlContent += '<div class="imageItem fl" style="width: 126px; height: 160px; padding: 2px; margin-right: 5px; border: solid 1px #ccc; text-align: center;">';
                    htmlContent += '<span>' + (idx + 1) + '</span>';
                    htmlContent += '<img src="' + domainImage + image.ImageUrl + '.120.120.jpg" alt="default" style="padding: 2px; border: solid 1px #ccc; vertical-align: middle;" /><br />';
                    htmlContent += (idx == 0 ? '<img src="/images/buttons/iconInactMoveLt_16x16.gif" class="noborder" />&nbsp;' : '<a href="javascript:void(0)" onclick="StoreImage.SwappedItem(' + idx + ',0)" title="Chuyển sang trái"><img src="/images/buttons/iconMoveLt_16x16.gif" /></a>&nbsp;');
                    htmlContent += (idx == (data.ImageList.length - 1) ? '<img src="/images/buttons/iconInactMoveRt_16x16.gif" class="noborder" />&nbsp;' : '<a href="javascript:void(0)" onclick="StoreImage.SwappedItem(' + idx + ',1)" title="Chuyển sang phải"><img src="/images/buttons/iconMoveRt_16x16.gif" /></a>&nbsp;');
                    htmlContent += '<a href="javascript:void(0)" title="Xóa ảnh" onclick="StoreImage.DeleteItem(' + idx + ');"><img src="/images/buttons/iconTrashcan_16x16.gif" class="noborder" /></a>';
                    htmlContent += '<input type="hidden" name="imageIdlist" value="' + image.ImageId + '" />';
                    if (idx == 0) {
                        htmlContent += '<input type="hidden" name="ImageUrl" value="' + image.ImageUrl + '" />';
                    }
                    htmlContent += '</div>';
                });
                $("#imageList").html(htmlContent);
            }
            else {
            }
        });
    },
    UpdateProduct: function (id) {
        if (this.storeInfo == null || (this.storeInfo != null && this.storeInfo.Status == 0)) {
            $("#contentBox").html("<p>Bạn chưa kích hoạt gian hàng. Để kích hoạt, bạn soạn tin theo cú pháp <strong><b>" + ACTIVE_CODE + '&nbsp;' + memberInfo.Id + ' GỬI ' + HEAD_MOBILE + "</b></strong> </p>");
            return;
        } else if (this.storeInfo.MaxProductUp <= 0) {
            $("#contentBox").html("<p>Bạn không còn đủ lượt up sản phẩm. Để mua thêm lượt up, bạn soạn tin theo cú pháp <strong><b>" + UP_CODE + '&nbsp;' + memberInfo.Id + ' GỬI ' + HEAD_MOBILE + "</b></strong> </p>");
            return;
        }
        if (id > 0) {
            Member.TabOnClick('tab_upproduct');
            CallAjax("/getrequest.ashx?m=product&ac=getdetail&id=" + id, function (data) {
                if (data != null) {
                    $("#contentBox").setTemplateURL("/Templates/updateproduct.htm?v=1.0.2");
                    $("#contentBox").processTemplate(data);
                    Store.InitFormUpdate();
                    SetInputAmount();
                    $("#CitySelectBox").val(data.ManuId);
                    Store.GetImageProductList(data.ProductId);
                    Store.BindCategoryToCommboBox(data.CateId);
                    $("#storeShortInfo").html("Bạn có <strong>{0}</strong> lượt up trong tài khoản. Để mua thêm lượt up, bạn soạn tin theo cú pháp <strong><b>{1} {2} GỬI {3}</b></strong> </p>".format(Member.MaxProductUp, UP_CODE, memberInfo.Id, HEAD_MOBILE));
                }
            });
        } else {
            $("#contentBox").setTemplateURL("/Templates/updateproduct.htm?v=1.0.2");
            $("#contentBox").processTemplate();
            Store.BindCategoryToCommboBox(-1);
            Store.InitFormUpdate();
            SetInputAmount();
            $("#storeShortInfo").html("Bạn có <strong>{0}</strong> lượt up trong tài khoản. Để mua thêm lượt up, bạn soạn tin theo cú pháp <strong><b>{1} {2} GỬI {3}</b></strong> </p>".format(Member.MaxProductUp, UP_CODE, memberInfo.Id, HEAD_MOBILE));
        }
    },
    PostProduct: function () {
        var isValid = true;
        // Check valid form
        if ($("#Ctrl1_CategorySelected").val() == "-1") {
            $("#txtProductName").focus();
            showMessageBox("Bạn chưa nhập tên sản phẩm");
            isValid = false;
        }
        if (Trim($("#txtProductName").val()) == "") {
            $("#txtProductName").focus();
            showMessageBox("Bạn chưa nhập tên sản phẩm");
            isValid = false;
        }
        if (Trim($("#txtPrice").val()) == "") {
            $("#txtPrice").focus();
            showMessageBox("Giá sản phẩm không hợp lệ.");
            isValid = false;
        }
        if (StoreImage.SelectedImageList.length <= 0) {
            showMessageBox("Bạn phải chọn ảnh đại diện cho sản phẩm.");
            isValid = false;
        }
        if (Trim($("#txtContent").val()) == "") {
            showMessageBox("Bạn nên nhập nội dung cho sản phẩm.");
            isValid = false;
        }
        if (Trim($("#txtScode").val()) == "") {
            $("#txtScode").focus();
            showMessageBox("Mã xác nhận chưa chính xác.");
            isValid = false;
        }
        if (isValid) {
            // Process
            var categorylist = $("#selectedCate option:selected").attr("rel");
            //alert(categorylist);
            SendRequestAjax("/getrequest.ashx?m=product&ac=newlisting", $("#frmUpdateProduct").serialize() + "&cateidlist=" + categorylist, function (data) {
                if (data.Result == "success") {
                    showMessageBox("Bạn đã cập nhật sản phẩm thành công.");
                    Store.getMyProductList();
                }
                else {
                    switch (data.ErrorCode) {
                        case 1:
                            showMessageBox("Bạn đã mất quyền đăng nhập. Hãy đăng nhập và thử lại.");
                            break;
                        case 2:
                            showMessageBox("Bạn chưa chọn chuyên mục sản phẩm.");
                            break;
                        case 3:
                            showMessageBox("Bạn chưa nhập tên sản phẩm.");
                            break;
                        case 4:
                            showMessageBox("Mã xác nhận chưa chính xác. Hãy thử lại.");
                            break;
                        case 5:
                            showMessageBox("Đã có vấn đề xảy ra trong quá trình xử lý. Hãy kiểm tra thông tin nhập.");
                            break;
                        case 6:
                            showMessageBox("Đã có lỗi xảy ra từ hệ thống. Hãy thử lại. Nếu vẫn gặp vấn đề hãy liên hệ với admin.");
                            break;
                    }
                    //showMessageBox("Đã có lỗi xảy ra, hãy thử lại.");
                }
                $('#imgScode').attr('src', '/CaptchaImage.ashx?t=3&s=' + Math.random().toString());
            });
        }
    },
    CurentPage: 1,
    NumRow: 12,
    ObjPagging: new Pagging(1, 0, "#PageNaviButton", function () { }, "Store.ObjPagging", 10, 5, "pages_m", false),
    getMyProductList: function () {
        loading();
        var pageIndex = this.CurentPage;
        var pageSize = this.NumRow;
        var ord = 2;
        var filter = "&page={0}&pagesize={1}".format(Store.ObjPagging.currentPage, pageSize);
        if ($("#txtKey").length > 0 && $("#txtKey").val().trim() != "") filter += "&key=" + $("#txtKey").val();
        if ($("#sortSelected").length > 0 && $("#sortSelected").val() != "") ord = $("#sortSelected").val();
        filter += "&ord=" + ord;
        $("#lbl_numpage").html("&nbsp;&nbsp;-&nbsp;&nbsp;Trang " + Store.ObjPagging.currentPage);
        CallAjax("/getrequest.ashx?m=product&ac=myproductlist" + filter, function (data) {
            if (data != null && data.ProductList != null && data.ProductList.length > 0) {
                $("#contentBox").setTemplateURL("/Templates/myproductlist.htm?v=1.0.3");
                $("#contentBox").processTemplate(data);
                $("#totalItem").text(data.totalRow);

                Store.ObjPagging.handler = "";
                Store.ObjPagging.totalRow = data.totalRow;
                Store.ObjPagging.rowPerPage = pageSize;
                Store.ObjPagging.callBack = function () { Store.getMyProductList(); }
                Store.ObjPagging.WrapPagging();

                $("#sortSelected").unbind("change").change(function () { Store.getMyProductList(); });
                $("#sortSelected").val(ord);
                $("#storeShortInfo").html("Bạn có <strong>{0}</strong> lượt up trong tài khoản. Để mua thêm lượt up, bạn soạn tin theo cú pháp <strong><b>{1} {2} GỬI {3}</b></strong> </p>".format(Member.MaxProductUp, UP_CODE, memberInfo.Id, HEAD_MOBILE));
            } else {
                $("#contentBox").html("Chưa có dữ liệu.");
            }
            loadCompleted();
        });
    },
    UpProduct: function (id) {
        loading();
        CallAjax("/getrequest.ashx?m=product&ac=refresh&id=" + id, function (data) {
            loadCompleted();
            if (data.Result == "success") {
                Member.MaxProduct = Member.MaxProduct - 1;
                showMessageBox("Sản phẩm đã được làm mới thành công.");
                Store.getMyProductList();
            }
        });
    },
    DeleteProduct: function (id) {
        showConfirmBox("Bạn có chắc chắn xóa sản phẩm này không?", function () {
            loading();
            CallAjax("/getrequest.ashx?m=product&ac=delete&id=" + id, function (data) {
                loadCompleted();
                if (data.Result == "success") {
                    showMessageBox("Sản phẩm đã xóa thành công.");
                    Store.getMyProductList();
                }
            });
        });
    },
    templateUrl: "",
    storeInfo: {},
    permition: false,
    UpdateInfo: function () {
        $("#contentBox").setTemplateURL(this.templateUrl);
        $("#contentBox").processTemplate(this.storeInfo);
        var storeId = this.storeInfo != null ? this.storeInfo.Id : 0;
        if (this.permition) {
            $("#btn_RollbackLogo").click(function () {
                var oldavatar = $("#hdf_oldlogo").val();
                oldavatar = oldavatar != "" ? oldavatar : "photo/NoAvatarAvailable.png";
                $("#ImgStoreLogo").attr("src", domainImage + oldavatar + ".200.200.jpg");
                $("#hdf_logo").val(oldavatar);
            });
            $("#FileInputLogo").uploadify({
                'uploader': '/Resources/uploadify.swf',
                'script': '/GetRequest.ashx%3Fm%3Dimage%26ac%3Duploadavatar',
                'scriptData': { "ASPSESSID": $("#hdf_ASPSESSID").val(), "AUTHID": $("#hdf_AuthenticationId").val() },
                'fileExt': '*.jpg;*.png;*.gif;*.jpeg',
                'fileDesc': '*.jpg;*.png;*.bmp;*.jpeg',
                'buttonImg': "/images/buttons/Upload1.png",
                'cancelImg': "/images/icons/cancel.png",
                'sizeLimit': 5242880, //~5MB
                'queueSizeLimit': 5,
                'rollover': true,
                'width': 78,
                'height': 22,
                'auto': true,
                'multi': false,
                'onError': function (event, ID, fileObj, errorObj) {
                },
                'onProgress': function (event, ID, fileObj, data) {
                },
                'onComplete': function (event, ID, fileObj, response, data) {
                    $("#ImgStoreLogo").attr("src", domainImage + response + ".200.200.jpg");
                    $("#hdf_logo").val(response);
                    $("#btn_RollbackLogo").show();
                },
                'onAllComplete': function (event, data) {
                }
            });
        }
    },
    Save: function () {
        SendRequestAjax("/GetRequest.ashx?m=store&ac=update", $("#frmStoreInfo").serialize(), function (data) {
            if (data.Result == "success") {
                if (data.Code == 1) {
                    showMessageBox("Bạn đã cập nhật thông tin gian hàng thành công. Hệ thống sẽ tự động tải lại sau ít giây.");
                    setTimeout("window.location.reload()", 5000);
                }
                else {
                    showMessageBox(data.Message);
                }
            }
        });
    },
    getMyOrderList: function () {
        loading();
        CallAjax("/GetRequest.ashx?m=order&ac=orderlist&from=" + $("#fromDate").val() + "&to=" + $("#toDate").val(), function (data) {
            if (data.Result == null) {
                $("#contentBox").html("Bạn đã mất quyền đăng nhập.");
            } else if (data.Result == "error") {
                $("#contentBox").html("Đã có lỗi xảy ra.");
            } else {
                if (data.OrderList.length > 0) {
                    $("#contentBox").setTemplateURL("/templates/orderlist.htm?v=1.0.1");
                    $("#contentBox").processTemplate(data);
                } else {
                    $("#contentBox").html("Chưa có dữ liệu.");
                }
            }
            loadCompleted();
        });
    },
    getOrderDetail: function (id) {
        if (id > 0) {
            loading();
            CallAjax("/GetRequest.ashx?m=order&ac=orderdetails&id=" + id, function (data) {
                if (data.Result == null) {
                    $("#contentBox").html("Bạn đã mất quyền đăng nhập.");
                } else if (data.Result == "error") {
                    $("#contentBox").html("Đơn hàng không tồn tại.");
                } else if (data.Result == "fatal") {
                    $("#contentBox").html("Đã có lỗi xảy ra.");
                } else {
                    if (data.OrderInfo != null) {
                        $("#contentBox").setTemplateURL("/templates/orderdetail.htm?v=1.0.1");
                        $("#contentBox").processTemplate(data);
                    } else {
                        $("#contentBox").html("Đơn hàng không tồn tại hoặc đã bị xóa.");
                    }
                }
                loadCompleted();
            });
        }
    },
    DeleteOrderItem: function (id) {
        if (id > 0) {
            showConfirmBox("Bạn có chắc chắn xóa đơn hàng không?", function () {
                CallAjax("/GetRequest.ashx?m=order&ac=delete&id=" + id, function (data) {
                    switch (data.Result) {
                        case "fatal":
                            showMessageBox("Đã có lỗi xảy ra, hãy thử lại.");
                            break;
                        case "error":
                            showMessageBox("Đơn hàng không tồn tại");
                            break;
                        case "success":
                        default:
                            showMessageBox("Xóa đơn hàng thành công.");
                            Store.getMyOrderList();
                            break;
                    }
                });
            });
        } else {
            showMessageBox("Đơn hàng không tồn tại");
        }
    }
}

/* COMMENT */
var Comment = {
    currentPage: 1,
    productId: 0,
    permition: false,
    checkPermition: function () {
        if (dataLog.Id > 0 && dataLog.Name != "") {
            $("#div_sender_user_name").hide();
        } else {
            $("#div_sender_user_name").show();
        }
    },
    showCommentForm: function (id, pid) {
        //        if ($("#_form_feedback_" + id).length > 0) {
        //            $("#frmFeedback_" + id).remove();
        //        } else {
        $("._comment_form_").remove();
        $("#_form_feedback_" + id).remove();
        var data = { LoginId: dataLog.Id, CommentId: id, ParentId: pid, ProductId: this.productId };
        $("#box_reply_" + id).after('<div align="right" style="width: 520px;" class="fast_reply_class" id="_form_feedback_' + id + '"></div>');
        $("#_form_feedback_" + id).setTemplateURL("/templates/CommentForm.htm");
        $("#_form_feedback_" + id).processTemplate(data);
        //        }
    },
    getList: function () {
        $("#CommentList").empty();
        CallAjax("/GetRequest.ashx?m=comment&ac=get&number=30&productId=" + this.productId + "&page=" + this.currentPage, function (data) {
            if (data.CommentList.length > 0) {
                $("#CommentList").setTemplateURL("/templates/CommentList.htm?v=1.0.1");
                $("#CommentList").processTemplate(data);
                $("#total_fb_all>label").text(data.TotalComment);
            } else {
            }
        });
    },
    post: function (pid) {
        if (typeof pid == "undefined") pid = 0;
        if (dataLog.Id < 0) {
            if ($("#sender_user_name_" + pid).val() == "" || $("#sender_user_name_" + pid).val() == "Số điện thoại") {
                showMessageBox("Bạn cần phải nhập số điện thoại hoặc username.");
                return false;
            }
            if ($("#sender_email_" + pid).val() == "" || !IsValidEmail($("#sender_email_" + pid).val())) {
                showMessageBox("Bạn cần phải nhập email đúng định dạng.");
                return false;
            }
        }
        if ($("#content_comment_" + pid).val() == "") {
            showMessageBox("Bạn cần phải nhập nội dung phản hồi.");
            return false;
        }
        if ($("#captcha_comment_" + pid).val() == "" || $("#captcha_comment_" + pid).val() == "Mã bảo mật") {
            showMessageBox("Bạn cần phải nhập mã an toàn.");
            return false;
        }
        SendRequestAjax("/GetRequest.ashx?m=comment&ac=pos", $("#frmFeedback_" + pid).serialize(), function (data) {
            switch (data.Error) {
                case 0:
                default:
                    Comment.getList();
                    break;
                case 1:
                    showMessageBox("Sai mã bảo mật, hãy thử lại.");
                    $('#captcha_img_' + pid).attr('src', '/CaptchaImage.ashx?t=3&s=' + Math.random().toString());
                    break;
                case 2:
                    showMessageBox("Có lỗi xảy ra, hãy thử lại.");
                    break;
            }
        });
        $("._comment_form_").remove();
    },
    Delete: function (i) {
        if (dataLog.Id > 0) {
            showConfirmBox("Bạn có chắc chắn xóa không?", function () {
                loading();
                CallAjax("/GetRequest.ashx?m=comment&ac=delete&id=" + i, function (data) {
                    switch (data.Result) {
                        case "success":
                            $("#tr" + i).remove();
                            $("._sub_comment_" + i).remove();
                            break;
                        case "error":
                            showMessageBox("Đã có lỗi xảy ra, hãy thử lại.");
                            break;
                        case "fatal":
                            showMessageBox("Lỗi server. Hãy thử lại sau.");
                            break;
                        case "null":
                            showMessageBox("Bạn cần <a href=\"/Register.aspx?p=login\">đăng nhập</a> để sử dụng chức năng này.");
                            break;

                    }
                    loadCompleted();
                });
            });
        } else {
            showMessageBox("Bạn cần <a href=\"/Register.aspx?p=login\">đăng nhập</a> để sử dụng chức năng này.");
        }
    }
}
