﻿// does vsworx exist? if not set empty constructor
var vsworx = vsworx ? vsworx : {};
// does vsworx.breezeERP exist? if not set empty constructor
vsworx.siteERP = vsworx.siteERP ? vsworx.siteERP : { title: "", subTitle: "", navOptions: "", pid: "" };

$(function () {
    $.ajaxSetup({
        error: function (xhr, msg) { vsworx.global.AjaxErrorPopup(xhr, msg) },
        type: "POST",
        url: "/Ajax.aspx"
    });

    //binding tabdiv click to show teh appropriate div in the overview page
    $(".tabnav>li>a").livequery('click', function () { vsworx.siteERP.showSelectedOverviewTab(this); });

    if ($(".hdnTheme").val() != "") {
        if ($(".hdnTheme").val() == "custom") {
            vsworx.siteERP.setCss();

        }
    }

    //Binding For Main Product Serach
    $(".txtProductSerach").livequery(function (el) { $(this).watermark($(".hdnKeyword").val()); });
    $(".txtExpData").livequery(function (el) { $(this).watermark("MMYY"); });
    $(".btnMainProductSerach").livequery('click', function () { vsworx.siteERP.mainProductsSerach(this); });
    $(".txtProductSerach").livequery('keyup', function (e) { if (e.keyCode == 13) { vsworx.siteERP.mainProductsSerach(this); }; });
    $(".lnkChangeLogo").livequery('click', function () { vsworx.siteERP.changeBranchImageLogo(this); });
    //$(".lnkChangeLogo").hover(function (el) { vsworx.siteERP.showChangeBranchImageLogo(this); });
    $(".lnkChoseBest").livequery('click', function () { vsworx.siteERP.ChoseBestAvailable(this); });
    vsworx.siteERP.checkIsEditSetting();
    $(".lnkSliderShopNow").livequery('click', function (el) { location.href = $(this).attr("link"); });
    $(".lnkPublisWidget").livequery('click', function (el) { vsworx.siteERP.publishWidget(this); });
    $("#fileLogo").livequery('change', function () { vsworx.siteERP.changeBranchLogo(this); })

    //    if ($("#hdnAdmin").val() != 0) {
    //        if (thm.length > 10) {
    //            vsworx.siteERP.setCss();
    //        }
    //        $("body").css("background-color", $("#themeContainer").css("background-color"));
    //        vsworx.siteERP.setCssImt();
    //        if (!(thm.length > 10)) {
    //            $(".theme_menu").find("a").livequery('mouseover', function (el) { $(this).addClass("active"); });
    //            $(".theme_menu").find("a").livequery('mouseout', function (el) { $(this).removeClass("active"); });
    //        }

    //    }
    if ($(".hdnBgImage").val() > "") {
        vsworx.siteERP.setBackgroundImg();
    }
    $("ul.top_right_link").find("li:last").css("border-right", "0px");

    $(".btnSavePopReg").livequery('click', function (el) { vsworx.siteERP.createAccount(this); });
    $(".btnSavePopLogin").livequery('click', function (el) { vsworx.siteERP.userLogin(this); });
    $(".btnPopOpenLogin").livequery('click', function (el) { vsworx.siteERP.userOpenLogin(this); });

});
vsworx.siteERP.userOpenLogin = function (el) {
    var log = $("#txtPopOpenLoginId").val();
    window.location.href = '/LogonUser.aspx?uname=' + log;
};
vsworx.siteERP.userLogin = function (el) {
    if(!vsworx.siteERP.validatePopLogin())
        return;

    var email = $("#txtPopLUName").val();
    var pwd = $("#txtPopLPwd").val();
    $.ajax({
        beforeSend: function () { },
        data: { method: 'UserLogin', email: email, pwd: pwd },
        success: function (msg) {
            var data = JSON.parse(msg);
            if (data.IsValid) {
                window.location.href = window.location.href;
            } else {
                $("#divPopLErr").html('Sorry, the credentials provided do not seem to be correct !').show();
            }
        },
        complete: function () { }
    }); //Close ajax */
};
vsworx.siteERP.validatePopLogin = function () { 
    vsworx.validator.clearRules();
    vsworx.validator.rules = ["txtPopLUName:required:Please Enter Email.", "txtPopLPwd:required:Please Enter Password."];
     vsworx.validator.errorContainer = "#divPopLErr";
    vsworx.validator.validate();   
    return (vsworx.validator.failedElements.length == 0);
};
vsworx.siteERP.createAccount = function (el) {
    if (!vsworx.siteERP.ValidatePopAccountInfo())
        return;
    var email = $("#txtPopRUName").val();
    var fname = $("#txtPopRRName").val();
    var dname = $("#txtPopRDName").val();
    var pwd = $("#txtPopRPwd").val();
    var cpwd = $("#txtPopRCPwd").val();
    $.ajax({
        beforeSend: function () { },
        data: { method: 'CreateAccount', email: email, fname: fname, dname: dname, pwd: pwd, cpwd: cpwd },
        success: function (msg) {
            var data = JSON.parse(msg);
            if (data.IsValid) {
                window.location.href = window.location.href;
            } else {
                $("#divPopRErr").html(data.Message).show();
            }
        },
        complete: function () { }
    }); //Close ajax */
};
vsworx.siteERP.ValidatePopAccountInfo = function () {
    vsworx.validator.clearRules();
    vsworx.validator.rules = ["txtPopRDName:required:Please Enter Display Name", "txtPopRUName:required:Please Enter Email Id", "txtPopRUName:email:Please Enter valid Email Id", "txtPopRPwd:required:Please Enter Password", "txtPopRCPwd:required:Please Enter Confirm Password", "txtPopRPwd:minlength[6]:Minimum 6 character allow in Password", "txtPopRPwd:maxlength[20]:Max 20 character allow in Password"];
    vsworx.validator.errorContainer = "#divPopRErr";
    vsworx.validator.validate();
    var errMsg = '';
    if (!vsworx.validator.failedElements.length == 0) {
        return false;
    }
    var regPassword = /^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/
    if (!$("#txtPopRPwd").val().match(regPassword)) {
        if (vsworx.validator.failedElements.length > 0) {
            errMsg = "<li>Password contain at least one letter and one number</li>"
            $("#divPopRErr").find("ul").append(errMsg);
            return false;
        } else {
            errMsg = "<ul>"
            errMsg = errMsg + "<li>Password must contain at least one letter and one number</li>"
            errMsg = errMsg + "</ul>"
            $(vsworx.validator.errorContainer).show().empty().append(errMsg);
            return false;
        }
    }
    if ($("#txtPopRPwd").val() != $("#txtPopRCPwd").val()) {
        if (vsworx.validator.failedElements.length > 0) {
            errMsg = "<li>Password and Confirm Password must have to be same</li>"
            $("#divPopRErr").find("ul").append(errMsg);
            return false;
        } else {
            errMsg = "<ul>"
            errMsg = errMsg + "<li>Password and Confirm Password must have to be same</li>"
            errMsg = errMsg + "</ul>"
            $(vsworx.validator.errorContainer).show().empty().append(errMsg);
            return false;
        }
    }

    if (!vsworx.validator.failedElements.length == 0) {
        return false;
    }
    
};
vsworx.siteERP.setBackgroundImg = function () {
   
    if ($(".hdnBgImage").val() != "/Images/Widget/") {
        $("body").css("background-image", "url(" + $(".hdnBgImage").val() + ")").css("background-repeat", "repeat").css("background-position", "top left");
    }
};

vsworx.siteERP.setCssImt = function () {
    $(".quick_item").css("background-color", $("#themeContainer").css("background-color"));
    $("#themeFooterContainer").find(".footer_link").find("span").css("color", $("#themeFooterContainer").find(".footer_link").find("a").css("color"));
}
vsworx.siteERP.setCss = function () {
    $("body").css("background-color", thm[0]);
    $("ul.top_right_link").find("li").css("color", thm[1]);
    $("ul.top_right_link").find("li").find("a").css("color", thm[2]);
    $("ul.top_right_link").find("li").css("border-color", thm[2]);

    $(".nav").css("background-color", thm[2]);
    $(".nav").find("li").find("a").css("border-color", thm[4]);
    $(".nav").find("li").find("a").css("color", thm[3]);
    $(".nav").find("li").find("a.active").css("background-color", thm[5]);
    $(".jsMenuChild").find("li").find("a").css("background-color", "#" + thm[5].replace("#", ""));
    $(".nav").find("li[class!='selected']").find("a").livequery('mouseover', function (el) { $(this).css("background-color", "#" + thm[5].replace("#", "")); });
    $(".nav").find("li[class!='selected']").find("a").livequery('mouseout', function (el) { $(this).css("background-color", ""); $(".jsMenuChild").find("li").find("a").css("background-color", "#" + thm[5].replace("#", "")); });
  
    $(".nav").find("li.selected").find("a").css("background-color", thm[6]);

    $("#body_container").find("h2").css("background-color", thm[7]);
    $("#body_container").find("h2").css("color", thm[8]);
    $("#body_container").find("h2").css("border-color", thm[9]);

    $(".shoppingCart").css("background-color", thm[10]);
    $(".divOrderBox").css("background-color", thm[10]);
    $(".quick_item").find("h3").css("background-color", thm[10]).css("color", thm[11]);
    $(".shoppingCart").find("a,span").css("color", thm[11]);
    // $(".shoppingCart").find("a.hover").css("color",  thm[11]);
    $(".quickAdd").find("h3").css("background-color", thm[10]).css("color", thm[11]);
    $(".quickAdd").find("ul.tab").find("li").find("a[class!='active']").livequery('mouseover', function (el) { $(this).css("background-color", "#" + thm[10].replace("#", "")).css("color", "#" + thm[11].replace("#", "")); });
    $(".quickAdd").find("ul.tab").find("li").find("a[class!='active']").livequery('mouseout', function (el) { $(".quickAdd").find("ul.tab").find("li").find("a[class!='active']").css("background-color", "#DDDDDD").css("color", "#000000"); $(".quickAdd").find("ul.tab").find("li").find("a.active").css("background-color", "#" + thm[10].replace("#", "")).css("color", "#" + thm[11].replace("#", "")); });
    $(".quickAdd").find("ul.tab").find("li").find("a.active").css("background-color", thm[10]).css("color", thm[11]);
    $(".quickAdd").find("div.box").css("background-color", thm[10]);
    $(".quickAdd").find("div.box").find("li").css("color", thm[11]);
    $(".quickAdd").find("div.box").find("li").find("a").css("color", thm[11]);
    $(".mostElectric_img").find("h6").css("background-color", thm[10]).css("color", thm[11]);

    $(".btn").livequery(function(el) {$(this).css("background-color", thm[12]).css("color", thm[13]).css("border-color", thm[14])});

    $("ul.productBox").find("a.cartLink").css("background-color", thm[15]).css("color", thm[16]);
    $("ul.productBox").find("a.details").css("background-color", thm[17]).css("color", thm[18]);

    $("#footer").find("li").find("a").css("color", thm[19]);
    $("#footer").find("li").find("a").css("border-color", thm[19]);
    // $("#footer").find("li").find("a:hover").css("color", $(".txtFooterText").val());
    $("#footer").find("span").css("color", thm[19]);

    $(".forumLink").css("color", thm[20]);
    $(".coommenttext").css("color", thm[21]);

    //    $(".theme_menu").find("a").livequery('mouseover', function (el) { $(this).css("background-color", thm[6]).css("color", thm[7]); });
    //    $(".theme_menu").find("a").livequery('mouseout', function (el) { $(this).css("background-color", thm[4]).css("color", thm[5]).css("border-right-color", thm[8]); });


};
vsworx.siteERP.manageSiteSetting = function () {  
    if ($(".hdnShowManuf").val() == 'False') {
        $(".manufBlock").hide()
    }
    if ($(".hdnStoreClose").val() == 'True') {
        $(".addCartBlock").hide();
        $(".btnAddOrder").hide();
        $(".priceBlock").hide();
    }
}
vsworx.siteERP.publishWidget = function (el) {
    var pageId = $(".hdnPageId").val();
    var widgetId = $(el).attr("pageWidgetId")
    var isEnable = false;
    if ($(el).find("span").html() == 'Publish') {
        isEnable = true;
    }
    $.ajax({
        beforeSend: function () { },
        data: { method: 'PublishWidget', pageId: pageId, widgetId: widgetId, isEnable: isEnable },
        success: function (msg) {
            if (isEnable) {
                $(el).find("span").html('Unpublish');
            } else {
                $(el).find("span").html('Publish');
            }
           
        },
        complete: function () { }
    }); //Close ajax */

};
vsworx.siteERP.checkIsEditSetting = function () {
    if ($(".hdnCheckIsDefault").val() == "1") {
        $(".notEditLogo").hide();
    } else {
        $(".profile-picture").hide();
    }
};
vsworx.siteERP.changeBranchLogo = function () {

    var branchLogoConfig = 'Branch.ImageLogo';
    var FileId = "fileLogo";
    var qsParams = "Method=ChangeBranchLogo&branchLogoConfig=" + branchLogoConfig;
    $.ajaxFileUpload({
        secureuri: false,
        fileElementId: FileId,
        beforeSend: function () { },
        type: "GET",
        dataType: "json",
        url: "/Ajax.aspx?" + qsParams,
        complete: function () { },
        success: function (data, status) {
            $(".imgLogo").attr("src", "/Images/Widget/" + data.AdditionalInfo1 + "?" + Math.random());
            $(".divLogo").toggle();

        },
        error: function (data, status, e) { }
    })

}
vsworx.siteERP.changeBranchImageLogo = function (el) {
    if ($(".hdnCheckIsDefault").val() != "1") {
        return;
    }
    $("div#branchLogoPopup").modal({
        close: true,
        persist: false,
        overlay: 20,
        onShow: function (dialog) {

            dialog.data.find("input[field=save]").click(function () {
                var el = dialog.data.find("input[field=save]");

                var branchLogoConfig = dialog.data.find(".hdnBranchLogoCofig").val();
                var FileId = "inptBranchLogoFile";
                var qsParams = "Method=ChangeBranchLogo&branchLogoConfig=" + branchLogoConfig;
                $.ajaxFileUpload({
                    secureuri: false,
                    fileElementId: FileId,
                    beforeSend: function () { },
                    type: "GET",
                    dataType: "json",
                    url: "/Ajax.aspx?" + qsParams,
                    complete: function () { },
                    success: function (data, status) {
                        vsworx.global.CloseModalPopup('branchLogoPopup');
                        location.href = location.href;

                    },
                    error: function (data, status, e) { location.href = location.href; }
                })

            });
        } //onShow of modal
    });
};
vsworx.siteERP.mainProductsSerach = function (el) {
    if ($(".txtProductSerach").val() != '' && $(".txtProductSerach").val() != $(".hdnKeyword").val()) {
        if ($(".hdnIsForum").val() == "0") {
            location.href = '/ProductSearchResult.aspx?qry=' + $(".txtProductSerach").val();
        } else {
            location.href = '/ForumSearchResult.aspx?qry=' + $(".txtProductSerach").val();
        }
       
    }
};
//change the current "Overview tab" depending upon the selection
vsworx.siteERP.showSelectedOverviewTab = function (el) {
    var contentId = $(el).parents("li:first").attr("contentId");
    // var status = $(el).parents("li:first").attr("status");
    $(".tabdiv").hide();
    $(".selected").removeClass("selected"); ;
    $("#" + contentId).show();
    $(el).parents("li:first").addClass("selected");
    try {
        Autocomplete.updateViews();
    }
    catch (err) {
        //Hello

    }
}
//**** Start Site Default ****//

vsworx.siteERP.InitSiteDefault = function () {
    $(".lnkNew").livequery('click', function () { vsworx.siteERP.createNew(this); });

};
vsworx.siteERP.createNew = function (el) {
    $("div#addNewPopup").modal({
        close: true,
        persist: false,
        overlay: 20,
        onShow: function (dialog) {

            dialog.data.find("input[field=Next]").click(function () {
                var rows = dialog.data.find(".newRadio");
                $.each(rows, function () {
                    if ($(this).attr("checked")) {
                        if ($(this).attr("createNew") == "page") {
                            dialog.data.find("div#pageDivPopup").show();
                        } else if ($(this).attr("createNew") == "floder") {
                            dialog.data.find("div#folderDivPopup").show();
                        } else if ($(this).attr("createNew") == "content") {
                            dialog.data.find("div#contentDivPopup").show();
                        } else if ($(this).attr("createNew") == "menu") {
                            dialog.data.find("div#menuDivPopup").show();
                        }
                    }

                });
                dialog.data.find("div#createNewPopUp").hide();
            }); //closing of Savebuton click  */
            dialog.data.find("input[field=pageBack]").click(function () {
                dialog.data.find("#pageDivPopup").hide();
                dialog.data.find("#createNewPopUp").show();
            });
            dialog.data.find("input[field=pageSave]").click(function () {

                var el = dialog.data.find("input[field=pageSave]");
                var pageId = "";
                var pageName = dialog.data.find("#txtPageName").val();
                if (pageName.toLowerCase() == "default.aspx") {
                    dialog.data.find(".divNewPageErrorMsg").empty().append("You can't create page with Default.aspx name");
                    dialog.data.find(".divNewPageErrorMsg").show();
                    return false;
                }
                var pageTitle = dialog.data.find("#txtPageTitle").val();
                var metaTags = dialog.data.find("#txtPageMetaTags").val();
                var parentFolderId = dialog.data.find("#cmbPageLocation").val();
                var friendlyURL = dialog.data.find("#txtPageUserFriendlyUrl").val();
                var layoutType = "";
                var rows = dialog.data.find(".pageLayout");
                $.each(rows, function () {
                    if ($(this).attr("checked")) {
                        layoutType = $(this).val();
                    }

                });
                var layoutwidth = dialog.data.find("#txtPageLayoutWidth").val();
                var allowAnonymouse = dialog.data.find("#chkPageAnonymous").attr("checked");
                var isUserDefine = dialog.data.find("#chkPageIsUserDefine").attr("checked");

                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveSitePage', pageId: pageId, pageTitle: pageTitle, metaTags: metaTags, parentFolderId: parentFolderId, friendlyURL: friendlyURL, layoutType: layoutType, layoutwidth: layoutwidth, allowAnonymouse: allowAnonymouse, isUserDefine: isUserDefine, pageName: pageName },
                    success: function (msg) {
                        //                        var data = JSON.parse(msg);
                        //                        alert(data.Message);
                        vsworx.global.CloseModalPopup('addNewPopup');
                        __doPostBack('__Page', '');
                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                }); //Close ajax */
            });
            dialog.data.find("input[field=folderBack]").click(function () {
                dialog.data.find("#folderDivPopup").hide();
                dialog.data.find("#createNewPopUp").show();
            });
            dialog.data.find("input[field=folderSave]").click(function () {
                var el = dialog.data.find("input[field=folderSave]");
                var folderId = "";
                var folderName = dialog.data.find("#txtFolderTitle").val();
                var parentFolderId = dialog.data.find("#cmbFolderLocation").val();
                var allowAnonymouse;
                if (dialog.data.find("#rbtnFloderAnonymous").attr("checked")) {
                    allowAnonymouse = 1;
                } else {
                    allowAnonymouse = 0;
                }
                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveSiteFolder', folderId: folderId, folderName: folderName, parentFolderId: parentFolderId, allowAnonymouse: allowAnonymouse },
                    success: function (msg) {
                        //                        var data = JSON.parse(msg);
                        //                        alert(data.Message);
                        vsworx.global.CloseModalPopup('addNewPopup');
                        __doPostBack('__Page', '');
                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                }); //Close ajax */ 
            });
            dialog.data.find("input[field=menuBack]").click(function () {
                dialog.data.find("#menuDivPopup").hide();
                dialog.data.find("#createNewPopUp").show();
            });
            dialog.data.find("input[field=menuSave]").click(function () {
                var el = dialog.data.find("input[field=menuSave]");
                var menuId = "";
                var caption = dialog.data.find("#txtMenuCaption").val();
                var htmlAttribute = dialog.data.find("#txtMenuAttribute").val();
                var url = dialog.data.find("#txtMenuLink").val();
                if (dialog.data.find("#cmbMenuLink").val() != '') {
                    url = dialog.data.find("#cmbMenuLink").val();
                }
                var imgRollOver = dialog.data.find("#txtMenuImgRollOver").val();
                var imgNormal = dialog.data.find("#txtMenuImgNormal").val();
                var parentMenuId = dialog.data.find("#cmbMenuLocation option:selected").val();
                var alternetText = dialog.data.find("#txtMenuAlternateText").val();
                var displayOrder = dialog.data.find("#txtMenuDisplayOrder").val();
                var target = dialog.data.find("#cmbMenuTarget option:selected").val();
                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveSiteMenu', menuId: menuId, caption: caption, htmlAttribute: htmlAttribute, url: url, imgRollOver: imgRollOver, imgNormal: imgNormal, parentMenuId: parentMenuId, alternetText: alternetText, displayOrder: displayOrder, target: target },
                    success: function (msg) {
                        //                        var data = JSON.parse(msg);
                        //                        alert(data.Message);
                        vsworx.global.CloseModalPopup('addNewPopup');
                        __doPostBack('__Page', '');
                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                }); //Close ajax */
            });
            dialog.data.find("input[field=contentBack]").click(function () {
                dialog.data.find("#contentDivPopup").hide();
                dialog.data.find("#createNewPopUp").show();
            });
            dialog.data.find("input[field=contentSave]").click(function () {
                vsworx.global.CloseModalPopup('addNewPopup');
            });

        } //onShow of modal
    });
};
//**** End Site Default ****//

//**** Start Site Page Detail ****//

vsworx.siteERP.InitSitePageDetail = function () {
    $("#cmbPageLocation").livequery('change', function () { vsworx.siteERP.setParentFolderId(this); });
    vsworx.siteERP.setParentFolderId("#cmbPageLocation");
};
vsworx.siteERP.setParentFolderId = function (el) {
    var folderId = $(el).val();
    if (folderId > 1) {
        $(".hdnParentForderId").val(folderId);
    }

};


//**** End Site Page Detail ****//

//**** Start Site Menu Detail ****//

vsworx.siteERP.InitSiteMenuDetail = function () {
    $("#cmbMenuLocation").livequery('change', function () { vsworx.siteERP.setParentMenuId(this); });
    vsworx.siteERP.setParentMenuId("#cmbMenuLocation");
    $(".lnkDeleteMenu").livequery('click', function () { vsworx.siteERP.deleteSiteMenu(this); });
};
vsworx.siteERP.deleteSiteMenu = function (el) {
    if (!confirm("Are you sure to delete this Menu?")) {
        return;
    }
    var menuId = $(".hdnMenuId").val();
    $.ajax({
        beforeSend: function () { },
        data: { method: 'DeleteSiteMenu', menuId: menuId },
        success: function (msg) {
            var data = JSON.parse(msg);
            alert(data.Message);
            parent.location.href = parent.location.href;
        },
        complete: function () {

        }
    });
};
vsworx.siteERP.setParentMenuId = function (el) {
    var menuId = $(el).val();
    if (menuId > 1) {
        $(".hdnParentMenuId").val(menuId);
    }

};


//**** End Site Menu Detail ****//

//******** Start Site Settings ********//
vsworx.siteERP.InitSiteSettings = function () {
    $(".chkEnableAdsense").livequery('click', function () { vsworx.siteERP.showHideAdsense(this); });
    $(".chkIsEnableSms").livequery('click', function () { vsworx.siteERP.showHideSms(this); });
    vsworx.siteERP.checkEnable();
};
vsworx.siteERP.checkEnable = function () {
    vsworx.siteERP.showHideAdsense(".chkEnableAdsense");
    vsworx.siteERP.showHideSms(".chkIsEnableSms");
};
vsworx.siteERP.showHideAdsense = function (el) {
    if ($(el).attr("checked")) {
        $(".isEnabledAdsense").show();
    } else {
        $(".isEnabledAdsense").hide();
    }
};
vsworx.siteERP.showHideSms = function (el) {
    if ($(el).attr("checked")) {
        $(".isEnableSms").show();
    } else {
        $(".isEnableSms").hide();
    }
};
//**** End Site Settings ****//

//*** Start Product Serach ***//
vsworx.siteERP.InitProductSerach = function (el) {
    $(".customPaging,.btnGoToPage").livequery('click', function () { vsworx.siteERP.searchProduct(this); });
    $(".cmbPageSite").livequery('change', function () { vsworx.siteERP.searchProduct(this); });
    $(".txtProductSerach").val($(".hdnSearchText").val());
    $(".lnkAddToOrder").livequery('click', function () { vsworx.siteERP.saveProductToOrder(this); });
    $(".lnkViewType").livequery('click', function () { vsworx.siteERP.searchProduct(this); });
    if ($(".hdnViewType").val() == 2) {
        $(".list").addClass("activeViewType");
    } else {
        $(".grid").addClass("activeViewType");
    }
   
    $(".btnCompare").livequery('click', function () { vsworx.siteERP.compareProduct(this); });

    $(".lnkSortProduct").livequery('click', function () { vsworx.siteERP.searchProduct(this); });
    $(".onHand").addClass("activeSortType");
    $(".imgProd").aeImageResize({ height: 75, width: 75 });
    $(".imgProdG").aeImageResize({ height: 150, width: 200 });
    $(".lnkProductPhoto,.imgProdG").livequery('click', function () { vsworx.siteERP.enlargeProductImage(this); });
    $(".lnkSerializedPhotos").livequery('click', function () { vsworx.siteERP.getSerializedProductImages(this); });
    $(".lnkImgProdPhoto").livequery('click', function (el) { window.open($(this).attr('src'), "", "width=700,height=750,toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=1"); });
    vsworx.siteERP.manageSiteSetting();
};
vsworx.siteERP.ChoseBestAvailable = function (el) {
    if ($(el).attr("avlQty") < 1) {
        alert("Item not available");
        return;
    } else {
        location.href = '/SerializedItem.aspx?PId=' + $(el).attr("productId")
    }
};
vsworx.siteERP.compareProduct = function (el) {
    var chk = $(".chkCompare");
    var productId = "";
    var count = 0;
    $.each(chk, function () {
        if ($(this).attr("checked")) {
            count++;
            if (productId == "") {
                productId = $(this).attr("productid");
            } else {
                productId = productId + "," + $(this).attr("productid");
            }
        }
    });
    if (count < 2) {
        alert("Please select more then 1 items to compare");
        return;
    } else if (count > 3) {
        alert("Please select at max 3 items to compare");
        return;
    }
    $("div#divCompareProductPopup").modal({
        close: true,
        persist: false,
        overlay: 20,
        onShow: function (dialog) {
            $.ajax({
                beforeSend: function () { vsworx.global.showLoader(el); },
                data: { method: 'CompareProducts', productId: productId },
                success: function (msg) {
                    var data = JSON.parse(msg);
                    dialog.data.find("#divCompareProduct").empty().html(data.HTML);
                },
                complete: function () { vsworx.global.hideLoader(el); }
            });    // ajax call from modal            
        } //onShow of modal
    });
};
vsworx.siteERP.saveProductToOrder = function (el) {
    var rows = [];
    var StockCode = $(el).attr("stockCode");
    var Unit = $(el).prev(".inputQty").val();
    var price = $(el).attr("price");
    var tprice =  parseFloat( Unit) * parseFloat(price)
    //extnPrice
    rows.push({ StockCode: StockCode, Unit: Unit });
    if (Unit.length < 1) {
        alert("Please enter atleast 1 qty");
        focus($(el).prev(".inputQty"));
        return;
    }
    var imgSrc = $(el).attr("src");
    var json = JSON.stringify(rows);
    $("div#addToOrder").modal({
        close: true,
        persist: false,
        overlay: 20,
        onShow: function (dialog) {
            dialog.data.find("span.spanItem").html(StockCode);
            dialog.data.find("span.spanQty").html(Unit);
            dialog.data.find("span.spanPrice").html(price);
            dialog.data.find("span.extnPrice").html(tprice);
            dialog.data.find("img").attr('src',imgSrc);
            var hit = 1;
            dialog.data.find("input#btnPopAddtoOrder").click(function () {
                hit = 2;
                var el = dialog.data.find("input[field=btnPopAddtoOrder]");
                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveUserCart', json: json },
                    success: function (msg) {
                        vsworx.global.CloseModalPopup('addToOrder');
                        if ($(".hdnAddOrderType").val() == 1) {
                            location.href = '../../Carts.aspx'
                        } else if ($(".hdnAddOrderType").val() == 0) {
                            location.href = 'Carts.aspx'
                        }

                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                });

            }); //closing of Savebuton click  */
            dialog.data.find("input#btnPopCont").click(function () {
                if (hit == 2)
                    return;
                var el = dialog.data.find("input[field=btnPopCont]");
              
                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveUserCart', json: json },
                    success: function (msg) {
                        location.href = location.href;
                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                });
            });
        } //onShow of modal
    });
};

vsworx.siteERP.searchProduct = function (el) {
    var searchText = $(".hdnSearchText").val();
    var pageSize = $(".cmbPageSite").val();
    var sortBy;
    var pageIndex = 1;
    var viewType;
    if ($(el).attr("PageIndex") != null) {
        pageIndex = $(el).attr("PageIndex");
    }
    if ($(el).attr("pageSize") != null) {
        pageIndex = 1;
    }
    if ($(el).attr("GoTo") != null) {
        pageIndex = $(el).parents("li:first").find(".txtGoto").val()

    }
    if ($(el).attr("viewType") != null) {
        viewType = $(el).attr("viewType");
        pageIndex = $("a.customPaging[class=active customPaging]").attr("pageindex");
    } else {
        viewType = $(".activeViewType").attr("viewType");
        //el = $(".spnaLodder");
    }
    sortBy=1
    if ( $(".lnkSortProduct").attr("sortType") != null)
        sortBy = $(".lnkSortProduct").attr("sortType");

    if ($(el).attr("sortType") != null){
        sortBy = $(".lnkSortProduct").attr("sortType");
        if (sortBy==1)
            sortBy=2
        else
             sortBy=1
     }
   
   
    //    if ($(el).attr("sortType") != null) {
    //        sortBy = $(el).attr("sortType");
    //    } else {
    //        sortBy = $(".activeSortType").attr("sortType");
    //        //el = $(".spnaLodder");
    //    }
    var catId = $(".hdnCategoryId").val();
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'GetProductSearch', catId: catId, pageIndex: pageIndex, pageSize: pageSize, sortBy: sortBy, searchText: searchText, pageIndex: pageIndex, viewType: viewType },
        success: function (msg) {
            var data = JSON.parse(msg);
            $(".divData").empty().append(data.HTML);
            vsworx.siteERP.manageSiteSetting();
            $(".imgProd").aeImageResize({ height: 75, width: 75 });
            $(".imgProdG").aeImageResize({ height: 150, width: 200 });
            $(".cmbPageSite").val(pageSize);
            $(".lnkViewType").removeClass("activeViewType");
            if (viewType == 0) {
                $(".list").addClass("activeViewType");
            } else {
                $(".grid").addClass("activeViewType");
            }           
            if (sortBy == 2) {
                $(".lnkSortProduct").attr("sortType", "2");
                $(".lnkSortProduct").removeClass("sort_open");
                $(".lnkSortProduct").addClass("sort_close");
            } else {
                $(".lnkSortProduct").attr("sortType", "1");
                $(".lnkSortProduct").removeClass("sort_close");
                $(".lnkSortProduct").addClass("sort_open");
            }

        },
        complete: function () {
            vsworx.global.hideLoader(el);
        }
    });
};
//*** End Product Serach ***//

//*** Default Site Page ****//
vsworx.siteERP.InitDefaultPage = function (el) {
    $(".btnAddOrder").livequery('click', function () { vsworx.siteERP.saveUserCart(this); });
    $(".btnAddOrderPaste").livequery('click', function () { vsworx.siteERP.addBulkOrder(this); });
    $(".StockItem").livequery(function (el) { $(this).watermark("Item #"); });
    $(".StockQty").livequery(function (el) { $(this).watermark("Qty"); });
    $(".lnkLineOrder").livequery('click', function (el) { vsworx.siteERP.showLineOrder(this); });
    $(".lnkBulkOrder").livequery('click', function (el) { vsworx.siteERP.showBulkOrder(this); });
    $(".txtBulkOrder").livequery(function (el) { $(this).watermark("Example:--------3   9001ka1 3,9001ka1"); });
};
vsworx.siteERP.showBulkOrder = function (el) {
    $(".divOrderBox").hide();
    $(".divPasteBox").show();
    $(el).addClass("active");
    $(".lnkLineOrder").removeClass("active");
   
};
vsworx.siteERP.showLineOrder = function (el) {
    $(".divOrderBox").show();
    $(".divPasteBox").hide();
    $(el).addClass("active");
    $(".lnkBulkOrder").removeClass("active");
};
vsworx.siteERP.addBulkOrder = function (el) {
    var lineItem = $(".txtBulkOrder").val();
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'AddBulkOrder', lineItem: lineItem },
        success: function (msg) {
            location.href = 'Carts.aspx'
        },
        error: function () {
            alert("Invalid input");
        },
        complete: function () { vsworx.global.hideLoader(el); }
    });
};

vsworx.siteERP.saveUserCart = function (el) {
    var rows = [];
    var data = $("ul.ulOrderBox").find("li");
    $.each(data, function () {
        var StockCode = $(this).find(".StockItem").val();
        var Unit = $(this).find(".StockQty").val();
        if (StockCode != 'Item #') {
            rows.push({ StockCode: StockCode, Unit: Unit});
        }
    });
    var json = JSON.stringify(rows);
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'SaveUserCart', json: json},
        success: function (msg) {
            location.href='Carts.aspx'
        },
        complete: function () { vsworx.global.hideLoader(el); }
    });
};

//** End Defualt Site Page


//**** Start Carts ****//
vsworx.siteERP.InitCarts = function () {
    $(".StockItem").livequery(function (el) { $(this).watermark("Item #"); });
    $(".StockQty").livequery(function (el) { $(this).watermark("Qty"); });
    $(".txtPersonalList").livequery(function (el) { $(this).watermark("Enter a new list name"); });
    $(".btnAddOrder").livequery('click', function () { vsworx.siteERP.AddCartProduct(this); });
    $(".btnUpdateCart").livequery('click', function () { vsworx.siteERP.UpdateCartProduct(this); });
    $(".lnkDeleteProduct").livequery('click', function () { vsworx.siteERP.DeleteCartProduct(this); });
    $(".lnkProductPhoto").livequery('click', function () { vsworx.siteERP.enlargeSerializedProductImage(this); });

    $("form").submit(function () { return false; });
    $(".btnXpressCheckout").attr("onclick", "");

    $(".btnCheckout").livequery('click', function () { vsworx.siteERP.ValidatePayPalCheckout('ctl00$CPHContent$btnCheckout'); });
    $(".btnCheckout").attr("onclick", "");

    $(".chkShippingAddress").livequery('click', function () { vsworx.siteERP.setShippingAddress(this); });
    vsworx.siteERP.manageSiteSettingStoreClose();
    $(".btnContinueShopping").livequery('click', function () { window.location.href = 'default.aspx' });
    $(".btnClearOrder").livequery('click', function () { vsworx.siteERP.clearOrder(this) });
    $(".lnkCalculateShip").livequery('click', function () { vsworx.siteERP.calculateShipCharge(this) });
};
vsworx.siteERP.calculateShipCharge = function (el) {
    $("#divError").hide();
    var ship = $("#cmbShipping").find("option[selected]").html();
    var zip = $(".txtPayPalShipZip").val();
    var isreg = $(".chkIsPayPalR").is(":checked");
    var ordertotal = $(".jsSubTotal").html();
    $.ajax({
        beforeSend: function () {  },
        data: { method: 'CALCULATESHIPCHARGE', ship: ship, zip: zip, isreg: isreg, ordertotal: ordertotal },
        success: function (msg) {
            var data = JSON.parse(msg);
            if (data.IsValid) {
                $(".jsShipCharge").html(data.Message);
                $(".jsOrderTotal").html(data.AdditionalInfo1);
            } else {
                $("#divError").show().empty().append('<ul><li>' + data.Message + '</li></ul>');               
            }

        },
        complete: function () {  }
    });
};
vsworx.siteERP.ValidateNormalCheckout = function (btnname) {
    $(".hdnShipMethod").val($("#cmbShipping").val());
    $(".hdnShipName").val($("#cmbShipping").find("option[selected]").html());
    $(".hdnSipZip").val($(".txtPayPalShipZip").val());
    $(".hdnIsRes").val($(".chkIsPayPalR").is(":checked"));
    $(".hdnShipCharge").val($(".jsShipCharge").html());
    __doPostBack(btnname, '')
};
vsworx.siteERP.ValidatePayPalCheckout = function (btnname) {
    $(".hdnShipMethod").val($("#cmbShipping").val());
    $(".hdnShipName").val($("#cmbShipping").find("option[selected]").html());
    $(".hdnSipZip").val($(".txtPayPalShipZip").val());
    $(".hdnIsRes").val($(".chkIsPayPalR").is(":checked"));
    $(".hdnShipCharge").val($(".jsShipCharge").html());

    vsworx.validator.clearRules();
    vsworx.validator.rules = [$(".cmbChekOut").attr("id") + ":required:Please chekout type.", "cmbShipping:required:Please select shipping method."];
    vsworx.validator.errorContainer = "#divError";
    vsworx.validator.validate();
    if (!($("#cmbShipping").val().toLowerCase() == "pickup" || $("#cmbShipping").val().toLowerCase() == "will call" || $("#cmbShipping").val().toLowerCase() == "")) {
        if ($(".txtPayPalShipZip").val() == '') {
            if (vsworx.validator.failedElements.length > 0) {
                errMsg = "<li>Please enter zip code.</li>"
                $("#divError").find("ul").append(errMsg);
                return false;
            } else {
                errMsg = "<ul>"
                errMsg = errMsg + "<li>PPlease enter zip code.</li>"
                errMsg = errMsg + "</ul>"
                $(vsworx.validator.errorContainer).show().empty().append(errMsg);
                return false;
            }
        } else {
            if (vsworx.validator.failedElements.length > 0) {
                return false;
            }
        }

    } else {
        if (vsworx.validator.failedElements.length > 0) {
            return false;
        }
    }

    //    if (!vsworx.validator.failedElements.length == 0) {
    //        return false;
    //    }
    __doPostBack(btnname, '')

};
vsworx.siteERP.clearOrder = function (el) {
    if (!confirm("Are you sure to clear this Cart Item?"))
        return;

    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'CLEARCARTITEM' },
        success: function (msg) {
            var data = JSON.parse(msg);
            if (data.IsValid) {
                alert(data.Message);
                window.location.href = window.location.href;
               // $(".table_order_form").empty().append(data.HTML);
            }

        },
        complete: function () { vsworx.global.hideLoader(el); }
    });
};
vsworx.siteERP.setShippingAddress = function (el) {
    if ($(el).attr("checked")) {
        $(".txtShipAddress1").val($(".txtBillAddress1").val());
        $(".txtShipAddress2").val($(".txtBillAddress2").val());
        $(".txtShipCity").val($(".txtBillCity").val());
        $(".cmbShipState").val($(".cmbBillState").val());
        $(".txtShipCountry").val($(".txtBillCountry").val());
        $(".txtShipZip").val($(".txtBillZip").val());
    } else {
        $(".txtShipAddress1").val("");
        $(".txtShipAddress2").val("");
        $(".txtShipCity").val("");
        $(".cmbShipState").val("");
        $(".txtShipCountry").val("");
        $(".txtShipZip").val("");
    }
  
};
vsworx.siteERP.ValidateCheckout = function (btnname) {
    vsworx.validator.clearRules();
    vsworx.validator.rules = [$(".txtBillAddress1").attr("id") + ":required:Please Enter Bill Address1", $(".txtBillCity").attr("id") + ":required:Please Enter Bill City", $(".cmbBillState").attr("id") + ":required:Please Enter Bill State", $(".txtBillCountry").attr("id") + ":required:Please Enter Bill Country", $(".txtBillZip").attr("id") + ":required:Please Enter Bill Postal Code", $(".txtShipAddress1").attr("id") + ":required:Please Enter Ship Address1", $(".txtShipCity").attr("id") + ":required:Please Enter Ship City", $(".cmbShipState").attr("id") + ":required:Please Enter Ship State", $(".txtShipCountry").attr("id") + ":required:Please Enter Ship Country", $(".txtShipZip").attr("id") + ":required:Please Enter Ship Postal Code"];
    vsworx.validator.errorContainer = "#divError";
    vsworx.validator.validate();
    if ($(".cmbShipping").val()=="") {
        if (vsworx.validator.failedElements.length > 0) {
            errMsg = "<li>Please select shipping method</li>"
            $("#divError").find("ul").append(errMsg);
            return false;
        } else {
            errMsg = "<ul>"
            errMsg = errMsg + "<li>Please select shipping method</li>"
            errMsg = errMsg + "</ul>"
            $(vsworx.validator.errorContainer).show().empty().append(errMsg);
            return false;
        }
    }

    if (!vsworx.validator.failedElements.length == 0) {
        return false;
    }
    __doPostBack(btnname, '')

};
vsworx.siteERP.DeleteCartProduct = function (el) {
    if (!confirm("Are you sure to delete this Cart Item?"))
        return;
    var shipId = $("#cmbShipping").val();
    var zip = $(".txtPayPalShipZip").val();
    var cartItemId = $(el).attr("productId");
    var productId = $(el).attr("pId");
    var serialNo = $(el).attr("serialNo");
    var isSerialized = $(el).attr("isSerialized");
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'DeleteCartProduct', cartItemId: cartItemId, productId: productId, serialNo: serialNo, isSerialized: isSerialized },
        success: function (msg) {
            var data = JSON.parse(msg);
            if (data.IsValid) {
                alert(data.Message);

                $(".table_order_form").empty().append(data.HTML);
                if ($(".trJsprod").size() == 0) {
                    window.location.href = window.location.href;
                    return;
                }
                $(".txtPayPalShipZip").val(zip);
                $("#cmbShipping").val(shipId);
            }

        },
        complete: function () { vsworx.global.hideLoader(el); }
    });
};
vsworx.siteERP.UpdateCartProduct = function (el) {
    var shipId = $("#cmbShipping").val();
    var zip = $(".txtPayPalShipZip").val();
    var isreg = $(".chkIsPayPalR").is(":checked");
    var rows = [];
    var data = $("table.products").find("tr.product");
    $.each(data, function () {
        var ID = $(this).attr("productId");
        var Unit = $(this).find(".inputQty").val();
        rows.push({ ID: ID, Unit: Unit });
    });
    var json = JSON.stringify(rows);
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'UpdateCartProduct', json: json },
        success: function (msg) {
            var data = JSON.parse(msg);
            if (data.IsValid) {
                $(".table_order_form").empty().append(data.HTML);
                $(".txtPayPalShipZip").val(zip);
                $("#cmbShipping").val(shipId);
                if (isreg) {
                    $(".chkIsPayPalR").attr("checked", "checked");
                }
                vsworx.siteERP.calculateShipCharge(el);
            }

        },
        complete: function () { vsworx.global.hideLoader(el); }
    });
};
vsworx.siteERP.AddCartProduct = function (el) {
    var rows = [];
    var data = $("ul.ulOrderBox").find("li");
    $.each(data, function () {
        var StockCode = $(this).find(".StockItem").val();
        var Unit = $(this).find(".StockQty").val();
        if (StockCode != 'Item #') {
            rows.push({ StockCode: StockCode, Unit: Unit });
        }
    });
    var json = JSON.stringify(rows);
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'AddCartProduct', json: json },
        success: function (msg) {
            var data = JSON.parse(msg);
            if (data.IsValid) {
                window.location.href = window.location.href;
//                $(".table_order_form").empty().append(data.HTML);
//                $(".StockItem").val("");
//                $(".StockQty").val("");
//                $(".StockItem").watermark("Item #");
//                $(".StockQty").watermark("Qty");
            }

        },
        complete: function () { vsworx.global.hideLoader(el); }
    });
};
//**** End Carts ****//
//**** Start Bulk Order ****//
vsworx.siteERP.InitBulkOrder = function () {
    $("#btnSaveBulk").livequery('click', function () { vsworx.siteERP.saveBulkUserCart(this); });
    $(".lnkAddFields").livequery('click', function () { vsworx.siteERP.appendItem(this); });
    $(".StockItem").livequery(function (el) { $(this).watermark("Item #"); });
    $(".StockQty").livequery(function (el) { $(this).watermark("Qty"); });
    $(".lnkAddToPersonalList").livequery('click', function () { vsworx.siteERP.addBulkProductToPersonalList(this); });
    vsworx.siteERP.manageSiteSettingStoreClose();
};
vsworx.siteERP.addBulkProductToPersonalList = function (el) {
    var row = $(".txtStockCode");
    var stockCodes = "";
    if ($(".hdnUserLogin").val() == 0) {
        alert("Please sign in or register fist to add these stock to personal list");
        return;
    }
    var count = 0;
    $.each(row, function () {
        if ($(this).val() != 'Item #') {
            if (stockCodes == "") {
                stockCodes = $(this).val();
            } else {
                stockCodes = stockCodes + "," + $(this).val();
            }

        } else {
            count++;
        }
    });
    if (count == 4) {
        alert("Please enter atleast one stock code");
        return;
    }
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'AddBulkProductToPersonalList', stockCodes: stockCodes },
        success: function (msg) {
            var data = JSON.parse(msg);
                alert(data.Message);
        },
        complete: function () { vsworx.global.hideLoader(el); }
    });    // a
};
vsworx.siteERP.saveBulkUserCart = function (el) {
    var rows = [];
    var data = $("dl");
    $.each(data, function () {
        var StockCode = $(this).find(".StockItem").val();
        var Unit = $(this).find(".StockQty").val();
        if (StockCode != 'Item #') {
            rows.push({ StockCode: StockCode, Unit: Unit });
        }
    });
    var json = JSON.stringify(rows);
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'SaveUserCart', json: json },
        success: function (msg) {
            location.href = 'Carts.aspx'
        },
        complete: function () { vsworx.global.hideLoader(el); }
    });
};
vsworx.siteERP.appendItem = function (el) {
    $("#hdnItemAppend").val(parseInt($("#hdnItemAppend").val()) + 1);
    for (var x = 1; x <= 10; x++) {
        $("ul.left").find("li").append($("#itemAppend").html());
        $("ul.right").find("li").append($("#itemAppend").html());
    }


    if ($("#hdnItemAppend").val() == 2) {
        $(".lnkAddFields").hide();
    }
};
//**** End Bulk Order ****//

//*** Start Category Detail ***//
vsworx.siteERP.InitCategoryDetail = function () {
    $(".customPaging,.btnGoToPage").livequery('click', function () { vsworx.siteERP.getCategoryProduct(this); });
    $(".cmbPageSite").livequery('change', function () { vsworx.siteERP.getCategoryProduct(this); });
    $(".lnkAddToOrder").livequery('click', function () { vsworx.siteERP.saveProductToOrder(this); });
};
vsworx.siteERP.getCategoryProduct = function (el) {
    var categoryId = $(".hdnCategoryId").val();
    var pageSize = $(".cmbPageSite option:selected").val();
    var sorBy = $(".cmbSortBY").val();
    var pageIndex = 1;
    if ($(el).attr("PageIndex") != null) {
        pageIndex = $(el).attr("PageIndex");
    }
    if ($(el).attr("pageSize") != null) {
        pageIndex = 1;
    }
    if ($(el).attr("GoTo") != null) {
        pageIndex = $(el).parents("li:first").find(".txtGoto").val()

    }
    el = $(".spnaLodder");
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'GetCategoryProduct', pageIndex: pageIndex, pageSize: pageSize, sorBy: sorBy, categoryId: categoryId },
        success: function (msg) {
            var data = JSON.parse(msg);
            $(".divData").empty().append(data.HTML);
            $(".cmbPageSite").val(pageSize);
        },
        complete: function () {
            vsworx.global.hideLoader(el);
        }
    });
};
//*** End Category Detail ***//

//**** Start Registration ****//
vsworx.siteERP.InitRegistration = function () {
    $(".btnContReg").livequery('click', function () { vsworx.siteERP.ValidateAccountInfo(); });
    $("form").submit(function () { return false; });
    $(".btnContReg").attr("onclick", "");
    //'$(".btnSaveUser").livequery('click', function (el) { vsworx.siteERP.SaveUser(this); });
};
vsworx.siteERP.ValidateAccountInfo = function () {
    vsworx.validator.clearRules();
    vsworx.validator.rules = [$(".txtDisplayName").attr("id") + ":required:Please Enter Display Name", $(".txtEmail").attr("id") + ":required:Please Enter Email Id", $(".txtEmail").attr("id") + ":email:Please Enter valid Email Id", $(".txtPassword").attr("id") + ":required:Please Enter Password", $(".txtConfirmPassword").attr("id") + ":required:Please Enter Confirm Password", $(".txtPassword").attr("id") + ":minlength[6]:Minimum 6 character allow in Password", $(".txtPassword").attr("id") + ":maxlength[20]:Max 20 character allow in Password", $(".txtCompanyName").attr("id") + ":required:Please Enter Company Name"];
    vsworx.validator.errorContainer = "#divError";
    vsworx.validator.validate();
    var errMsg = '';
    if (!vsworx.validator.failedElements.length == 0) {
        return false;
    }
    var regPassword = /^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/
    if (!$(".txtPassword").val().match(regPassword)) {
        if (vsworx.validator.failedElements.length > 0) {
            errMsg = "<li>Password contain at least one letter and one number</li>"
            $("#divError").find("ul").append(errMsg);
            return false;
        } else {
            errMsg = "<ul>"
            errMsg = errMsg + "<li>Password must contain at least one letter and one number</li>"
            errMsg = errMsg + "</ul>"
            $(vsworx.validator.errorContainer).show().empty().append(errMsg);
            return false;
        }
    }
    if ($(".txtPassword").val() != $(".txtConfirmPassword").val()) {
        if (vsworx.validator.failedElements.length > 0) {
            errMsg = "<li>Password and Confirm Password must have to be same</li>"
            $("#divError").find("ul").append(errMsg);
            return false;
        } else {
            errMsg = "<ul>"
            errMsg = errMsg + "<li>Password and Confirm Password must have to be same</li>"
            errMsg = errMsg + "</ul>"
            $(vsworx.validator.errorContainer).show().empty().append(errMsg);
            return false;
        }
    }

    if (!vsworx.validator.failedElements.length == 0) {
        return false;
    }
    __doPostBack('ctl00$CPHContent$btnContReg', '')

    //    $("#regFisrtStepDiv").hide();
    //    $("#regSecondStepDiv").show();
};
vsworx.siteERP.SaveUser = function (el) {
    var firstName = $(".txtFirstName").val();
    var lastName = $(".txtLastName").val();
    var email = $(".txtEmail").val();
    var password = $(".txtPassword").val();
    var address = $(".txtAddress").val();
    var address1 = $(".txtAddress1").val();
    var address2 = $(".txtAddress2").val();
    var address3 = $(".txtAddress3").val();
    var address4 = $(".txtAddress4").val();
    var city = $(".txtCity").val();
    var state = $(".txtState").val();
    var country = $(".txtCountry").val();
    var postalCode = $(".txtPostalCode").val();
    var shipAddress = $(".txtShippingAddress").val();
    var billAddress = $(".txtBillingAddress").val();
    var officePhone = $(".txtOfficePhone").val();
    var mobile = $(".txtMobile").val();
    var fax = $(".txtFax").val();
    var homePhone = $(".txtHomePhone").val();
    var userId = $(".hdnUserId").val();
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'SaveUser',userId:userId, firstName: firstName, lastName: lastName, email: email, password: password, address: address, address1: address1, address2: address2, address3: address3, address4: address4, city: city, state: state, country: country, postalCode: postalCode, shipAddress: shipAddress, billAddress: billAddress, officePhone: officePhone, mobile: mobile, fax: fax, homePhone: homePhone },
        success: function (msg) {
            var data = JSON.parse(msg);
             if (data.IsValid) {               
                alert(data.Message);
                location.href = 'Default.aspx'
            }
        },
        complete: function () {
            vsworx.global.hideLoader(el);
        }
    });
};
//**** End Registration ****//

//**** Start Site Content Admin ****//
vsworx.siteERP.InitSiteContentAdmin = function () {
   
    $(".lnkEditPageWidget").livequery('click', function () { vsworx.siteERP.editPageWidget(this); });
    $(".lnkDeletePageWidget").livequery('click', function () { vsworx.siteERP.deletePageWidget(this); });
    $("#btnViewDetail").livequery('click', function () { window.open('PageDetails.aspx?pageid=' + $(".hdnPageId").val(), "", "width=700,height=385,toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=1"); });
    $("#btnDeletePage").livequery('click', function () { vsworx.siteERP.deleteSitePage(this); });
};
vsworx.siteERP.deleteSitePage = function (el) {
    if (!confirm("Are you sure to delete this Page?")) {
        return;
    }
    var PageId = $(".hdnPageId").val();
    $.ajax({
        beforeSend: function () { },
        data: { method: 'DeleteSitePage', PageId: PageId },
        success: function (msg) {
            var data = JSON.parse(msg);
            alert(data.Message);
            parent.location.href = parent.location.href;
        },
        complete: function () {

        }
    });
};
vsworx.siteERP.editPageWidget = function (el) {

    var PageWidgetId = $(el).attr("pageWidgetId")
    if ($(el).attr("widgetId") == 6 || $(el).attr("widgetId") == 2) {
        window.open('EditSliderPageWidget.aspx?pwid=' + PageWidgetId + '&wid=' + $(el).attr("widgetId"), "", "width=800,height=700,toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=1");
        return;
    }
    var IsHTMLWidget = $(el).attr("IsHTML")
    if (IsHTMLWidget == 'True') {
        window.open('WidgetConfigDetail.aspx?wid=' + PageWidgetId, "", "width=700,height=750,toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=1");
        return;
    }
    var dataHTML = '';
    $.ajax({
        beforeSend: function () { },
        data: { method: 'GetPageWidgetEditHTML', PageWidgetId: PageWidgetId },
        success: function (msg) {
            var data = JSON.parse(msg);
            dataHTML = data.HTML;
            $("div#editWidgetPopup").modal({
                close: true,
                persist: false,
                overlay: 20,
                onShow: function (dialog) {
                    dialog.data.find("li.liEditWidgetContent").html(dataHTML);

                    dialog.data.find("input[field=Save]").click(function () {
                        var title = dialog.data.find("input.txtTitle").val();
                        var desc = '';
                        if (dialog.data.find(".txtDesc").size() > 0) {
                            desc = dialog.data.find(".txtDesc").val();
                        }
                        if (dialog.data.find(".txtLocation").size() > 0) {
                            desc = dialog.data.find(".txtLocation").val();
                            desc = desc + "~" +dialog.data.find(".txtZoom").val();
                        }

                        $.ajax({
                            beforeSend: function () { },
                            data: { method: 'SAVEPAGEWIDGETCONFIG', pageWidgetId: PageWidgetId, title: title, desc: desc },
                            success: function (msg) {

                                location.href = location.href;
                            },
                            complete: function () {

                            }
                        });
                    });


                } //onShow of modal
            });
        },
        complete: function () {

        }
    });


};
vsworx.siteERP.deletePageWidget = function (el) {
    if (!confirm("Are you sure to delete this widget?")) {
        return;
    }
    var PageWidgetId = $(el).attr("pageWidgetId");
    $.ajax({
        beforeSend: function () { },
        data: { method: 'DeletePageWidget', PageWidgetId: PageWidgetId },
        success: function (msg) {
            var data = JSON.parse(msg);

            location.href = location.href;
        },
        complete: function () {

        }
    });
};
//**** End Site Content Admin ****//
//*** Default Init Site Content Page ****//
vsworx.siteERP.InitSiteContentPage = function (el) {
    $(".btnAddOrder").livequery('click', function () { vsworx.siteERP.saveUserCart(this); });
    $(".btnAddOrderPaste").livequery('click', function () { vsworx.siteERP.addBulkOrder(this); });
    $(".StockItem").livequery(function (el) { $(this).watermark("Item #"); });
    $(".StockQty").livequery(function (el) { $(this).watermark("Qty"); });
    $(".lnkLineOrder").livequery('click', function (el) { vsworx.siteERP.showLineOrder(this); });
    $(".lnkBulkOrder").livequery('click', function (el) { vsworx.siteERP.showBulkOrder(this); });
    $(".txtBulkOrder").livequery(function (el) { $(this).watermark("Example:--------3   9001ka1 3,9001ka1"); });
    vsworx.siteERP.manageSiteSettingStoreClose();

};
vsworx.siteERP.manageSiteSettingStoreClose = function () {
    if ($(".hdnStoreClose").val() == 'True') {
        $(".addCartBlock").hide();
        $(".priceBlock").hide();
        $(".btnAddOrder").hide();
    }
}

//**** End Init Site Content Page ****//

//**** Start Init Product Detail ****//

vsworx.siteERP.InitProductDetail = function () {
    $(".lnkProductPhoto").livequery('click', function () { vsworx.siteERP.enlargeProductImage(this); });
    $(".lnkAddToOrder").livequery('click', function () { vsworx.siteERP.addProductToOrder(this); });
    $(".lnkAddToPersonalList").livequery('click', function () { vsworx.siteERP.addProductToPersonalList(this); });
    $(".imgProdDetail").aeImageResize({ height: 201, width: 250 });
    vsworx.siteERP.showQuestionSection();
    $(".inputQty").livequery(function (el) { $(this).watermark("Qty."); });
};

vsworx.siteERP.showQuestionSection = function () {
    if ($(".hdnUserLogin").val() == 0) {
        $("#divQuestion").hide();
    } else {
        $("#divQuestion").show();
    }
    if ($(".hdnStoreClose").val() == 'True') {
        $(".addCartBlock").hide();
    }
        
};
vsworx.siteERP.addProductToPersonalList = function (el) {
    var productId;
    var iId;
    var productName;
    var stockCode;
    if ($(".hdnUserLogin").val() == 0) {
        alert("Please sign in or register fist to add this stock to personal list");
        return;
    }
    if ($(el).attr("callby") == 0) {
        productId = $("#spanProductId").html();
        iId = $("#spanIId").html();
        productName = $("#spanProductName").html();
        stockCode = $("#spanStockCode").html();
    } else {
        productId = $(el).attr("productId");
        iId = $(el).attr("iId");
        productName = $(el).attr("productName");
        stockCode = $(el).attr("stockCode");
    }

    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'AddProductToPersonalList', productId: productId, iId: iId, productName: productName, stockCode: stockCode },
        success: function (msg) {
            if ($(".hdnAddOrderType").val() == 1) {
                location.href = '../../PersonalList.aspx'
            } else if ($(".hdnAddOrderType").val() == 0) {
                location.href = 'PersonalList.aspx'
            }

        },
        complete: function () { vsworx.global.hideLoader(el); }
    });
};
vsworx.siteERP.addProductToOrder = function (el) {
    var rows = [];
    var StockCode ;
    var Unit ;
    var price ;
    if ($(el).attr("callby") == 0) {
        StockCode = $("#spanStockCode").html();
        Unit = $(el).parent().parent().parent().find(".inputQty").val();
        price = $("#spanPrice").html();
    } else { 
        StockCode = $(el).attr("stockCode");
        Unit = $(el).parent().parent().find(".inputQty").val();
        price = $(el).attr("price");
       
    }
    rows.push({ StockCode: StockCode, Unit: Unit });
    if (Unit.length < 1) {
        alert("Please enter atleast 1 qty");
        if ($(el).attr("callby") == 0) {
             $(el).parent().parent().parent().find(".inputQty").focus();
        }else{
             $(el).parent().parent().find(".inputQty").focus();
        }
        
        return;
    }
    var json = JSON.stringify(rows);
    $("div#addToOrder").modal({
        close: true,
        persist: false,
        overlay: 20,
        onShow: function (dialog) {
            dialog.data.find("span.spanItem").html(StockCode);
            dialog.data.find("span.spanQty").html(Unit);
            dialog.data.find("span.spanPrice").html(price);
            dialog.data.find("span.extnPrice").html(price);
            var hit = 1;
            dialog.data.find("input#btnPopAddtoOrder").click(function () {
                hit = 2;
                var el = dialog.data.find("input[field=btnPopAddtoOrder]");
                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveUserCart', json: json },
                    success: function (msg) {
                        vsworx.global.CloseModalPopup('addToOrder');
                        if ($(".hdnAddOrderType").val() == 1) {
                            location.href = '../../Carts.aspx'
                        } else if ($(".hdnAddOrderType").val() == 0) {
                            location.href = 'Carts.aspx'
                        }

                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                });

            }); //closing of Savebuton click  */
            dialog.data.find("input#btnPopCont").click(function () {
                if (hit == 2)
                    return;
                var el = dialog.data.find("input[field=btnPopCont]");

                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveUserCart', json: json },
                    success: function (msg) {
                        location.href = 'default.aspx';
                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                });
            });
        } //onShow of modal
    });
};
vsworx.siteERP.enlargeProductImage = function (el) {
    var src = $(el).parents().find("img:first").attr("src").replace("thumb","");
   // alert(src);
    window.open(src, "", "width=700,height=750,toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=1");
    /*$("div#productImgPopup").modal({
    close: true,
    persist: false,
    overlay: 20,
    onShow: function (dialog) {
    dialog.find(".imgProdDetail").aeImageResize({ height: 201, width: 250 });
           
    } //onShow of modal
    });*/
};
//**** End Init Product Detail ****//



//**** Start Site Footer Setting ****//

vsworx.siteERP.InitSiteFooterSetting = function () {
    $(".lnkAddEditFooternote").livequery('click', function () { vsworx.siteERP.addEditFooterNote(this); });
    $(".lnkAddEditFooterLink, .editLink").livequery('click', function () { vsworx.siteERP.addEditFooterLink(this); });
    $("table.footerLinks tr.footerLink").livequery(function () {
        $(this).hover(function () { vsworx.siteERP.showFooterLinkActions(this) },
                                                      function () { $(this).find("td.actionFooterLink[linkId=" + $(this).attr("linkId") + "]").empty(); });
    });
    $(".delLink").livequery('click', function () { vsworx.siteERP.deleteFooterLink(this); });
};
vsworx.siteERP.deleteFooterLink = function (el) {
    if (!confirm("Are you sure to delete this footer link?")) {
        return;
    }
    var linkId = $(el).attr("linkId");
    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'DeleteFooterLink', linkId: linkId },
        success: function (msg) {
            var data = JSON.parse(msg);
            alert(data.Message);
            location.href = location.href;
        },
        complete: function () { vsworx.global.hideLoader(el); }
    });
};
vsworx.siteERP.addEditFooterLink = function (el) {
    $("div#footerlinkPopup").modal({
        close: true,
        persist: false,
        overlay: 20,
        onShow: function (dialog) {
            var linkId = $(el).attr("linkId");
            if ($(el).attr("linkId") != "") {
                dialog.data.find(".txtLinkName").val($(el).attr("linkName"));
                dialog.data.find(".txtLinkurl").val($(el).attr("hyperlink"));
                dialog.data.find(".cmbTarget").val($(el).attr("target"));
                dialog.data.find(".addFormTitle").html("Edit Footer Link");
                dialog.data.find("#cmbMenuLink").val($(el).attr("hyperlink"));
                if (dialog.data.find("#cmbMenuLink").val() != '') {
                    dialog.data.find(".txtLinkurl").val("");
                }
            }
            dialog.data.find("input[field=save]").click(function () {
                var el = dialog.data.find("input[field=save]");

                var linkName = dialog.data.find("input.txtLinkName").val();
                var hyperlink = dialog.data.find("input.txtLinkurl").val();
                if (dialog.data.find("#cmbMenuLink").val() != '') {
                    hyperlink = dialog.data.find("#cmbMenuLink").val();
                }
                var target = dialog.data.find(".cmbTarget option:selected").val();
                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveFooterLink', linkId: linkId, linkName: linkName, hyperlink: hyperlink, target: target },
                    success: function (msg) {
                        var data = JSON.parse(msg);
                        alert(data.Message);
                        vsworx.global.CloseModalPopup('footerlinkPopup');
                        location.href = location.href;
                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                });

            });
        } //onShow of modal
    });
};
vsworx.siteERP.showFooterLinkActions = function (el) {
    var linkId = $(el).attr("linkId");
    var linkName = $(el).attr("linkName");
    var hyperlink = $(el).attr("hyperlink");
    var target = $(el).attr("target");
    $("td.actionFooterLink[linkId=" + linkId + "]").empty().append($("<span>" + $("div.footerLinkActions").html() + "</span>"));
    $(".footerLinkAction").attr("linkId", linkId);
    $(".footerLinkAction").attr("linkName", linkName);
    $(".footerLinkAction").attr("hyperlink", hyperlink);
    $(".footerLinkAction").attr("target", target); 
};
vsworx.siteERP.addEditFooterNote = function (el) {
    $("div#footerNotePopup").modal({
        close: true,
        persist: false,
        overlay: 20,
        onShow: function (dialog) {
            dialog.data.find("input.txtFooterNote").val($(".hdnFooterNote").val());
            dialog.data.find("input[field=save]").click(function () {
                var el = dialog.data.find("input[field=save]");
                var footerNote = dialog.data.find("input.txtFooterNote").val();
                var footerNoteConfig = $("input.hdnFooterConfig").val();
                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveFooterNote', footerNote: footerNote, footerNoteConfig: footerNoteConfig },
                    success: function (msg) {
                        var data = JSON.parse(msg);
                        alert(data.Message);
                        $(".hdnFooterNote").val(dialog.data.find("input.txtFooterNote").val());
                        vsworx.global.CloseModalPopup('footerNotePopup');
                        location.href = location.href;
                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                });

            });
        } //onShow of modal
    });
};

//**** End Site Footer Setting ****//

//**** Start Site Slider Setting ****//
vsworx.siteERP.InitSiteSliderSettings = function () {
    $(".spanDeleteFile").livequery('click', function () { vsworx.siteERP.deleteSliderFile(this); });
};
vsworx.siteERP.deleteSliderFile = function (el) {
    $(el).parent().find(".hdnFileName").val("");
    $(el).parent().find(".spanFileName").html("");
    $(el).hide();
};
//**** End Site Slider Setting ****//

//**** Start Site Question Setting ****//
vsworx.siteERP.InitSiteQuestion = function () {
    $(".btnSaveAnswer").livequery('click', function () { vsworx.siteERP.saveQuestionAnswers(this); });
};
vsworx.siteERP.saveQuestionAnswers = function (el) {
    var lineItems;
    $(".hdnQuestion").val('');
    var rows = $("table.quesAnswers").find("tr.quesAnswer");
    $.each(rows, function () {
        if ($(this).find(".chkIsApproved").attr("checked")) { 
            lineItems = $(this).attr("qId") + "^" + $(this).find(".txtAnswer").val() + "^" + $(this).find(".chkIsApproved").attr("checked");
            if ($(".hdnQuestion").val() == "") {
                $(".hdnQuestion").val(lineItems);
            }
            else {
                $(".hdnQuestion").val($(".hdnQuestion").val() + "~" + lineItems);
            }
        }
       
    });

    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'SaveQuestionAnswers', lineItems: lineItems },
        success: function (msg) {
            var data = JSON.parse(msg);
            alert(data.Message);
            location.href = location.href;
        },
        complete: function () { vsworx.global.hideLoader(el); }
    });
};
//**** End Site Question Setting ****//

//*** Start Serialized Item  ***//
vsworx.siteERP.InitSerializedItem = function (el) {
    $(".customPaging,.btnGoToPage").livequery('click', function () { vsworx.siteERP.getSerializedItem(this); });
    $(".lnkAddToOrder").livequery('click', function () { vsworx.siteERP.saveSerializedItemToOrder(this); });
    $(".onHand").addClass("activeSortType");
    $(".lnkSortProduct").livequery('click', function () { vsworx.siteERP.getSerializedItem(this); });
    $(".lnkProductPhoto").livequery('click', function () { vsworx.siteERP.enlargeProductImage(this); });
    $(".lnkSerializedPhotos").livequery('click', function () { vsworx.siteERP.getSerializedProductImages(this); });
    $(".lnkImgProdPhoto").livequery('click', function (el) { window.open($(this).attr('src'), "", "width=700,height=750,toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=1"); });
    $(".imgProd").aeImageResize({ height: 75, width: 75 });    
};
vsworx.siteERP.getSerializedProductImages = function (el) {
    var serialNo = $(el).attr("serialNo");
    var productId = $(el).attr("productId");
    $.ajax({
        beforeSend: function () {  },
        data: { method: 'GetSerializedProductImages', serialNo: serialNo, productId: productId },
        success: function (msg) {
            var data = JSON.parse(msg);
            $(".divProductPhoto").empty().append(data.HTML);
            $(".imgProduct").aeImageResize({ height: 120, width: 120 });
            $("div#divProductPhotoPopup").modal({
                close: true,
                persist: false,
                overlay: 20,
                onShow: function (dialog) {
                } //onShow of modal
            });
        },
        complete: function () { }
    });
};
vsworx.siteERP.enlargeSerializedProductImage = function (el) {
    var src = $(el).attr("imgSrc");
    window.open(src, "", "width=700,height=750,toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=1");
//    var imagePath = $(el).attr("imgSrc");
//  
//    $("div#productImgPopup").modal({
//        close: true,
//        persist: false,
//        overlay: 20,
//        onShow: function (dialog) {
//            dialog.data.find(".imgProduct").attr("src",imagePath);
//        } //onShow of modal
//    });
};
vsworx.siteERP.saveSerializedItemToOrder = function (el) {
    var rows = [];
    var StockCode = $(el).attr("stockCode");
    var Unit = 1;
    var price = $(el).attr("price");
    var SerialNo = $(el).attr("serialno");
    var imgSrc = $(el).attr("imgSrc");
    rows.push({ StockCode: StockCode, Unit: Unit, SerialNo: SerialNo });

    var json = JSON.stringify(rows);
    $("div#addToOrder").modal({
        close: true,
        persist: false,
        overlay: 20,
        onShow: function (dialog) {
            dialog.data.find(".productImg").attr("src", imgSrc);
            dialog.data.find("span.spanItem").html(StockCode);
            dialog.data.find("span.spanQty").html(Unit);
            dialog.data.find("span.spanPrice").html(price);
            dialog.data.find("span.extnPrice").html(price);
            dialog.data.find("input[field=btnPopAddtoOrder]").click(function () {
                var el = dialog.data.find("input[field=btnPopAddtoOrder]");
                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveUserCart', json: json },
                    success: function (msg) {
                        vsworx.global.CloseModalPopup('addToOrder');
                        location.href = 'Carts.aspx'
                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                });

            }); //closing of Savebuton click  */
            dialog.data.find("input[field=btnPopCont]").click(function () {
                vsworx.global.CloseModalPopup('addToOrder');
            });
        } //onShow of modal
    });
};
vsworx.siteERP.getSerializedItem = function (el) {
    var productId = $(".hdnProductId").val();
    var pageSize = 5;
    var sortBy;
    var pageIndex = 1;
    if ($(el).attr("PageIndex") != null) {
        pageIndex = $(el).attr("PageIndex");
    }
    if ($(el).attr("pageSize") != null) {
        pageIndex = 1;
    }
    if ($(el).attr("GoTo") != null) {
        pageIndex = $(el).parents("li:first").find(".txtGoto").val()

    }

    if ($(el).attr("sortType") != null) {
        sortBy = $(el).attr("sortType");
    } else {
        sortBy = $(".activeSortType").attr("sortType");
        //el = $(".spnaLodder");
    }

    $.ajax({
        beforeSend: function () { vsworx.global.showLoader(el); },
        data: { method: 'GetSerializedItem', pageIndex: pageIndex, pageSize: pageSize, sortBy: sortBy,  productId: productId },
        success: function (msg) {
            var data = JSON.parse(msg);
            $(".divData").empty().append(data.HTML);
            $(".imgProd").aeImageResize({ height: 75, width: 75 });
            vsworx.siteERP.manageSiteSetting();
            if (sortBy == 1) {
                $(".onHand").addClass("activeSortType");
            } else {
                $(".notOnHand").addClass("activeSortType");
            }
        },
        complete: function () {
            vsworx.global.hideLoader(el);
        }
    });
};
//**** End Serialized Item  ****//

//*** Start Translation Management  ***//
vsworx.siteERP.InitSiteTranslation = function (el) {
    $(".btnSave").attr("onclick", "");
    $(".btnSave").livequery('click', function (el) { vsworx.siteERP.saveLocalization(this); });
};
vsworx.siteERP.saveLocalization = function (el) {
   
    var resourceLine = "";
    $(".hdnTransMangement").val("");
    var rows = $(".resourceValue");
    $.each(rows, function () {
        resourceLine = $(this).attr("resourceName") + "^" + $(this).val() + "^" + $(this).attr("contentBlock");
        if ($(".hdnTransMangement").val() == "") {
            $(".hdnTransMangement").val(resourceLine);
        }
        else {
            $(".hdnTransMangement").val($(".hdnTransMangement").val() + "~" + resourceLine);
        }
    });
    if ($(".hdnTransMangement").val().length > 0) {
        __doPostBack('ctl00$CPHContent$btnSave', '')
    }

};
//**** End Translation Management  ****//

//**** Start Order Confirmation ****//
vsworx.siteERP.InitOrderConfirmation = function () {
    $(".btnAuthorizeNet").livequery('click', function () { vsworx.siteERP.ValidateCartDetail('ctl00$CPHContent$btnAuthorizeNet'); });
    $(".btnPayPal").livequery('click', function () { vsworx.siteERP.ValidateCartDetail('ctl00$CPHContent$btnPayPal'); });
    $("form").submit(function () { return false; });
    $(".btnAuthorizeNet").attr("onclick", "");
    $(".btnPayPal").attr("onclick", "");
};
vsworx.siteERP.ValidateCartDetail = function (btnId) {
    vsworx.validator.clearRules();
    vsworx.validator.rules = [$(".txtNameOnCard").attr("id") + ":required:Please enter name on card", $(".txtCardNo").attr("id") + ":required:Please enter card no.", $(".txtCVV2").attr("id") + ":required:Please enter cvv2", $(".txtExpData").attr("id") + ":required:Please enter exp date", $(".txtExpData").attr("id") + ":number:Please enter exp date in MMYY format", $(".txtExpData").attr("id") + ":maxlength[4]:Please enter exp date in MMYY format"];
    vsworx.validator.errorContainer = "#divError";
    vsworx.validator.validate();
    if ($(".cmCardType").val() == "0") {
        if (vsworx.validator.failedElements.length > 0) {
            errMsg = "<li>Please select card type</li>"
            $("#divError").find("ul").append(errMsg);
            return false;
        } else {
            errMsg = "<ul>"
            errMsg = errMsg + "<li>Please select card type</li>"
            errMsg = errMsg + "</ul>"
            $(vsworx.validator.errorContainer).show().empty().append(errMsg);
            return false;
        }
    }
    if (parseInt($(".txtExpData").val().toString().substr(0, 2)) > 12 || parseInt($(".txtExpData").val().toString().substr(2, 3)) > 31) {
        if (vsworx.validator.failedElements.length > 0) {
            errMsg = "<li>Please enter exp date in MMYY format</li>"
            $("#divError").find("ul").append(errMsg);
            return false;
        } else {
            errMsg = "<ul>"
            errMsg = errMsg + "<li>Please enter exp date in MMYY format</li>"
            errMsg = errMsg + "</ul>"
            $(vsworx.validator.errorContainer).show().empty().append(errMsg);
            return false;
        }
    }
    if (!vsworx.validator.failedElements.length == 0) {
        return false;
    }
    __doPostBack(btnId, '')

};
//**** End Order Confirmation  ****//
vsworx.siteERP.InitUserDetail = function () {
    $(".chkShippingAddress").livequery('click', function () { vsworx.siteERP.setShippingAddress(this); });
    $(".btnSaveUser").livequery('click', function () { vsworx.siteERP.ValidateUserDetail('ctl00$CPHContent$btnSaveUser'); });
    $("form").submit(function () { return false; });
    $(".btnSaveUser").attr("onclick", "");

};
vsworx.siteERP.ValidateUserDetail = function (el) {
    $("#divError").hide();
    if($(".txtPassword").val()!=''){
    var regPassword = /^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/
        if (!$(".txtPassword").val().match(regPassword)) {
            if (vsworx.validator.failedElements.length > 0) {
                errMsg = "<li>Password contain at least one letter and one number</li>"
                $("#divError").show().find("ul").empty().append(errMsg);
                return false;
            } else {
                errMsg =  "<li>Password must contain at least one letter and one number</li>"
         
                $("#divError").show().find("ul").empty().append(errMsg);
                return false;
            }
        }
    }

    __doPostBack(el, '')

};


//*** Start Document Search  ***//

vsworx.siteERP.InitDocumentSearch = function (el) {


    $("#cmbDocParentCat").livequery('change', function (el) { vsworx.siteERP.GetSubCatCombo(this); });

    $(".jsDocTag").livequery('click', function (el) { vsworx.siteERP.GetDocumentTagResult(this); });

    $(".expand_icon,.collapse_icon").livequery('click', function (el) { vsworx.siteERP.toggleSearchDiv(this); });

    $("#cmdSubcategory").livequery('change', function (el) { vsworx.siteERP.GetSubCatComboVal(this); });

    $(".txtManufacturer").livequery('focus', function (el) { vsworx.siteERP.searchManuf(); });
  
    var comboHTML = ""
    $.ajax({
        beforeSend: function () { },
        data: { method: 'GetDocCategoryCombo', catid: 'cmbDocParentCat' },
        success: function (msg) {
            var data = JSON.parse(msg);
            comboHTML = data.HTML;
            $("td.jsTDDocCatCombo").html(comboHTML);
            $("#cmbDocParentCat").val($(".hdnCategory").val());
            vsworx.siteERP.GetSubCatCombo($("#cmbDocParentCat"));
            
            //            $(".hdnCategory").val("");
            //            $(".hdnSubcategory").val("");
            //   $(".cmbDocParentCat").val($(".hdnCategory").val())
            // vsworx.siteERP.GetSubCatCombo("cmbDocParentCat");

        }
    });
    $(".divtbSearch").hide();
    $(".lnkAddToOrder").livequery('click', function () { vsworx.siteERP.saveTagProductToOrder(this); });
};

vsworx.siteERP.GetSubCatCombo = function (el) {
    var catid = $(el).val();
    //$(".hdnSubcategory").val("");
    $(".hdnCategory").val(catid);   
    var comboHTML = ""
    $.ajax({
        beforeSend: function () { },
        data: { method: 'GetSubCatCombo', catid: catid },
        success: function (msg) {
            var data = JSON.parse(msg);
            comboHTML = data.HTML;

            $(".jsTDSubCatCombo").html(comboHTML);
            $("#cmdSubcategory").val($(".hdnSubcategory").val());
        }
    });
}
vsworx.siteERP.saveTagProductToOrder = function (el) {
    var rows = [];
    var StockCode = $(el).attr("stockCode");

    var price = $(el).attr("price");

    //extnPrice

    var imgSrc = $(el).attr("src");

    $("div#addToOrder").modal({
        close: true,
        persist: false,
        overlay: 20,
        onShow: function (dialog) {
            dialog.data.find("span.spanItem").html(StockCode);
            dialog.data.find("span.spanPrice").html(price);
            if (imgSrc != "")
                dialog.data.find("img").attr('src', imgSrc);
            var hit = 1;
            dialog.data.find("input#btnPopAddtoOrder").click(function () {
               var Unit = dialog.data.find("input#txtCQty").val();
                if (Unit.length < 1) {
                    alert("Please enter atleast 1 qty");
                    return;
                }
                var tprice = parseFloat(Unit) * parseFloat(price)
                hit = 2;
                var el = dialog.data.find("input[field=btnPopAddtoOrder]");

                rows.push({ StockCode: StockCode, Unit: Unit });
                var json = JSON.stringify(rows);
                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveUserCart', json: json },
                    success: function (msg) {
                        vsworx.global.CloseModalPopup('addToOrder');
                        location.href = 'Carts.aspx'

                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                });

            }); //closing of Savebuton click  */
            dialog.data.find("input#btnPopCont").click(function () {
             
                var Unit = dialog.data.find("input#txtCQty").val();
                if (Unit.length < 1) {
                    alert("Please enter atleast 1 qty");
                    return;
                }
                var tprice = parseFloat(Unit) * parseFloat(price)
                if (hit == 2)
                    return;
             
                var el = dialog.data.find("input[field=btnPopCont]");
                rows.push({ StockCode: StockCode, Unit: Unit });
                var json = JSON.stringify(rows);
                $.ajax({
                    beforeSend: function () { vsworx.global.showLoader(el); },
                    data: { method: 'SaveUserCart', json: json },
                    success: function (msg) {
                        location.href = location.href;
                    },
                    complete: function () { vsworx.global.hideLoader(el); }
                });
            });
        } //onShow of modal
    });
};
vsworx.siteERP.searchManuf = function () {
    new Autocomplete($(".txtManufacturer").attr("name"), function () {
        this.setValue = function (id) {
            $(".hdnManufacturer").val(id);
        }
        if (this.isModified)
            this.setValue("");
        if (this.value.length < 1 && this.isNotClick)
            return;
        return "../Ajax.aspx?q=" + $(this).val() + '&method=GetSearchList&objType=5';

    });
};
vsworx.siteERP.toggleSearchDiv = function (el) {
    if ($(el).attr("class") == "expand_icon") {
        $(el).removeClass("expand_icon").addClass("collapse_icon");
    } else {
        $(el).removeClass("collapse_icon").addClass("expand_icon");

    };

    $(".defaultTable3").toggle("slow");
};
vsworx.siteERP.GetDocumentTagResult = function (el) {

    var docid = $(el).attr("docID");
    window.location.href = 'DocumentSearchResult.aspx?docid=' + docid;
    //alert(docid);
//    var DocumetTagResult = "";
//    $.ajax({
//        beforeSend: function () { },
//        data: { method: 'GetDocumentTagResult', docid: docid },
//        success: function (msg) {
//            var data = JSON.parse(msg);
//            DocumetTagResult = data.HTML;

//            $("#tdDocumetTagResult").html(DocumetTagResult);
//            $(".fotoEtiket").aeImageResize({ height: 600, width: 800 });
//            $("#tag-wrapper").css({ width: $(".fotoEtiket").outerWidth(), height: $(".fotoEtiket").outerHeight() });
//        } //
//    });
}

vsworx.siteERP.GetDocumentSearchResult = function (el) {

    var manufId = $(".hdnManufacturer").val();
    var catId = $("#cmbDocParentCat").val();
    var subcatId = $("#cmdSubcategory").val();
    var key = $(".txtKeywords").val();
    var doctitle = $(".txtDocumentTitle").val();
    var stockCode = $(".txtStockCode").val();
  //  alert(catId);
    var DocumentSearchResultHTML = ""
        $.ajax({
            beforeSend: function () { },
            data: { method: 'GetDocumentSearchResult', manufId: manufId, catId: catId, subcatId: subcatId, key: key, doctitle: doctitle, stockCode: stockCode },
            success: function (msg) {
                var data = JSON.parse(msg);
                DocumentSearchResultHTML = data.HTML;

                $("#DivDocumentSearchResultHTML").html(DocumentSearchResultHTML);
            }
        });
    }

    vsworx.siteERP.GetSubCatComboVal = function (el) {

        var subcatid = $(el).val();
      
        $(".hdnSubcategory").val(subcatid);
       
    }


    vsworx.siteERP.saveProductToOrder = function (el) {
        var rows = [];
        var StockCode = $(el).attr("stockCode");
        var Unit = $(el).prev(".inputQty").val();
        var price = $(el).attr("price");
        var tprice = parseFloat(Unit) * parseFloat(price)
        //extnPrice
        rows.push({ StockCode: StockCode, Unit: Unit });
        if (Unit.length < 1) {
            alert("Please enter atleast 1 qty");
            focus($(el).prev(".inputQty"));
            return;
        }
        var imgSrc = $(el).attr("src");
        var json = JSON.stringify(rows);
        $("div#addToOrder").modal({
            close: true,
            persist: false,
            overlay: 20,
            onShow: function (dialog) {
                dialog.data.find("span.spanItem").html(StockCode);
                dialog.data.find("span.spanQty").html(Unit);
                dialog.data.find("span.spanPrice").html(price);
                dialog.data.find("span.extnPrice").html(tprice);
                dialog.data.find("img").attr('src', imgSrc);
                var hit = 1;
                dialog.data.find("input#btnPopAddtoOrder").click(function () {
                    hit = 2;
                    var el = dialog.data.find("input[field=btnPopAddtoOrder]");
                    $.ajax({
                        beforeSend: function () { vsworx.global.showLoader(el); },
                        data: { method: 'SaveUserCart', json: json },
                        success: function (msg) {
                            vsworx.global.CloseModalPopup('addToOrder');
                            if ($(".hdnAddOrderType").val() == 1) {
                                location.href = '../../Carts.aspx'
                            } else if ($(".hdnAddOrderType").val() == 0) {
                                location.href = 'Carts.aspx'
                            }

                        },
                        complete: function () { vsworx.global.hideLoader(el); }
                    });

                }); //closing of Savebuton click  */
                dialog.data.find("input#btnPopCont").click(function () {
                    if (hit == 2)
                        return;
                    var el = dialog.data.find("input[field=btnPopCont]");

                    $.ajax({
                        beforeSend: function () { vsworx.global.showLoader(el); },
                        data: { method: 'SaveUserCart', json: json },
                        success: function (msg) {
                            location.href = location.href;
                        },
                        complete: function () { vsworx.global.hideLoader(el); }
                    });
                });
            } //onShow of modal
        });
    };
    //**** End Document Search ****//
    vsworx.siteERP.InitPostLink = function (el) {
        // $("input.autoCompleteSearch").livequery('focus', function (el) {  vsworx.siteERP.autoComplete(this) });
        $.facebooklist('#txtLinkCat', '#linkpreadded', '#txtLinkCat-auto', { url: '/Ajax.aspx', cache: 0 }, 10, { userfilter: 1, casesensetive: 0 });
        $.facebooklist('#txtTextCat', '#textpreadded', '#txtTextCat-auto', { url: '/Ajax.aspx', cache: 0 }, 10, { userfilter: 1, casesensetive: 0 });
        $(".btnSaveLink").livequery('click', function (el) { vsworx.siteERP.setForumLinkCat(this); });
        $(".btnSaveLink").attr("onclick", "");
        $(".rdoPostType").livequery('click', function (el) { vsworx.siteERP.setForumPostType(this); });

        $(".register").find("input").livequery('keyup', function (el) { if (el.keyCode == 13) { vsworx.siteERP.setForumLinkCat(this) } });
        $(".register").find("textarea").livequery('keyup', function (el) { if (el.keyCode == 13) { vsworx.siteERP.setForumLinkCat(this) } });

        $.ajax({
            beforeSend: function () { },
            data: { method: 'USERLOGREGISTER' },
            success: function (msg) {
                var data = JSON.parse(msg);
                if (!data.IsValid) {
                    $("div#commonPopup").modal({
                        close: true,
                        persist: false,
                        overlay: 20,
                        onShow: function (dialog) {
                            $("div#commonPopup").html(data.HTML);
                        }, //onShow of modal
                        onClose: function (dialog) {
                            window.location.href = '/default.aspx';
                        } //onShow of modal

                    });

                }
            },
            complete: function () { vsworx.global.hideLoader(el); }
        });

    };
    
    vsworx.siteERP.setForumPostType = function (el) {
        if ($(".rdoLink").is(":checked")) {
            $(".dlUrl").show();
            $(".dlText").hide();
        } else {
            $(".dlUrl").hide();
            $(".dlText").show();
        }
    }
    vsworx.siteERP.setForumLinkCat = function (el) {
        
        $(".hdnLinkCategory").val("")
        var rows = $(".bit-box");
        $.each(rows, function () {
            var catId = $(this).find("input").val();
            if ($(".hdnLinkCategory").val() == "") {
                $(".hdnLinkCategory").val(catId);
            }
            else {
                $(".hdnLinkCategory").val($(".hdnLinkCategory").val() + "~" + catId);
            }
        });

        vsworx.validator.clearRules();
        if ($(".rdoLink").is(":checked")) {
            vsworx.validator.rules = [$(".txtLinkTitle").attr("id") + ":required:Please Enter Title.", $(".txtLinkTitle").attr("id") + ":maxlength[150]:Max 150 character allow in Title", $(".txtLinkUrl").attr("id") + ":required:Please Enter Url.", $(".hdnLinkCategory").attr("id") + ":required:Please Select Category."];
        } else {
            vsworx.validator.rules = [$(".txtLinkTitle").attr("id") + ":required:Please Enter Title.", $(".txtLinkTitle").attr("id") + ":maxlength[150]:Max 150 character allow in Title", $(".txtTextText").attr("id") + ":required:Please Enter Text.", $(".hdnLinkCategory").attr("id") + ":required:Please Select Category."];
        }
       
        vsworx.validator.errorContainer = "#divErr";
        vsworx.validator.validate();
        if (!vsworx.validator.failedElements.length == 0) {
            return false;
        }

        __doPostBack($(el).attr("name"), '')
    };
    vsworx.siteERP.autoComplete = function (el) {
        new Autocomplete($(el).attr("name"), function () {
            var hdnId = $(el).attr("id").replace("txt", "hdn");
            this.setValue = function (id) {
                $("#" + hdnId).val(id);
            }

            // If the user modified the text but doesn't select any new item, then clean the hidden value.
            if (this.isModified)
                this.setValue("");
            //  alert("inside-4");
            // return ; will abort current request, mainly used for validation.

            // For example: require at least 1 char if this request is not fired by search icon click
            if (this.value.length < 1 && this.isNotClick)
                return;
            if (this.value.length < 3 && this.isNotClick && $(el).attr("searchType") == 11)
                return;
            //alert("inside-5");
            return "/Ajax.aspx?q=" + $(this).val() + '&method=GetSearchList&objType=' + $(el).attr("searchType");
        });
    };
    vsworx.siteERP.InitForumLinks = function () {
        $(".jsVoteUp,.jsVoteDown").livequery('click', function (el) { vsworx.siteERP.voteUpDown(this) });
        $(".jsVoteUp[oval=0]").livequery(function (el) { $(this).removeClass("up").addClass("upvoted") });
        $(".jsVoteUp[oval=1]").livequery(function (el) { $(this).addClass("up").removeClass("upvoted") });
        $(".jsVoteDown[oval=0]").livequery(function (el) { $(this).removeClass("down").addClass("downvoted") });
        $(".jsVoteDown[oval=-1]").livequery(function (el) { $(this).addClass("down").removeClass("downvoted") });
        $(".btnSaveComment").livequery('click', function (el) { vsworx.siteERP.saveForumComment(this) });
        $("#cmbCommentSort").livequery('change', function (el) { vsworx.siteERP.getForumComment(this) });

        $(".lnkforumLink").livequery('click', function (el) { vsworx.siteERP.showCommentReply(this) });
        $(".btnCancelReply").livequery('click', function (el) { vsworx.siteERP.hideCommentReply(this) });
        $(".btnReply").livequery('click', function (el) { vsworx.siteERP.saveCommentReply(this) });
        $(".lnkShareLink").livequery('click', function (el) { vsworx.siteERP.shareForumLink(this) });

        $(".jsLinksTab").find("a").livequery('click', function (el) { vsworx.siteERP.getForumLink(this) });
        $(".customPaging").livequery('click', function (el) { vsworx.siteERP.getForumLink(this) });

        $(".lnkReportLink").livequery('click', function (el) { vsworx.siteERP.reportForumLink(this) });
        $(".lnkDeleteLink,.lnkPublishLink").livequery('click', function (el) { vsworx.siteERP.udateForumLinkStatus(this) });
        $(".lnkMarkContLink").livequery('click', function (el) { vsworx.siteERP.markForumLinkControverisal(this) });
        $(".lnkSaveLink,.lnkHideLink").livequery('click', function (el) { vsworx.siteERP.saveHIdeForumLink(this) });
        $(".btnShareLink").livequery('click', function (el) { vsworx.siteERP.saveShareLink(this) });
        $(".lnkLike").livequery('click', function (el) { vsworx.siteERP.getLinkShare(this) });
        if ($(".hdnsort").size() > 0) {
            if ($(".hdnsort").val() == "1")
                $(".jsLinksTab").find("a.jshot").addClass("youarehere");
            if ($(".hdnsort").val() == "2")
                $(".jsLinksTab").find("a.jsnew").addClass("youarehere");
            if ($(".hdnsort").val() == "3")
                $(".jsLinksTab").find("a.jscontr").addClass("youarehere");
            if ($(".hdnsort").val() == "4")
                $(".jsLinksTab").find("a.jstop").addClass("youarehere");
            if ($(".hdnsort").val() == "6")
                $(".jsLinksTab").find("a.jsunpublish").addClass("youarehere");

        }
        if ($(".hdnCat").val() != "") {
            $.each($("div.jsLinksTab").find("a"), function () {
                $(this).attr("href", "/f/" + $(".hdnCat").val() + "/" + $(this).html());

            });
        }
    };
    vsworx.siteERP.getLinkShare = function (el) {
        var title = $(el).attr("tit");
        var url = $(el).parent().parent().parent().parent().parent().find(".lnkPostComment").attr("href");
       
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'GETLINKSHAREHTML', title: title, url: url },
            success: function (msg) {
                $(el).parent().empty().append(msg)
                FB.XFBML.parse();

            },
            complete: function () { vsworx.global.hideLoader(el); }
        });
    };
    vsworx.siteERP.getForumLink = function (el) {

        var cat = $(".hdnCat").val();
        var ds = $(".hdnDs").val();
        var status = 0;
        var sort = 1; // $(el).attr("sort");     
        if ($(el).attr("sort") != null) {
            $(".jsLinksTab").find("a").removeClass("youarehere");
            $(el).addClass("youarehere");
        }
        if ($(".jsLinksTab").find("a").size() > 0) {
            sort = $("a.youarehere").attr("sort");
            if ($("a.youarehere").attr("status") != null) {
                status = $("a.youarehere").attr("status");
            }
        }

        var pageindex = 1;
        if ($(el).attr("pageindex") != null) {
            pageindex = $(el).attr("pageindex");
            window.location.href = $(".hdnUrl").val() + "/" + pageindex;
        }

        //        $.ajax({
        //            beforeSend: function () { vsworx.global.showLoader(el); },
        //            data: { method: 'GetForumLinks', pageindex: pageindex, sort: sort, status: status, ds: ds, cat: cat },
        //            success: function (msg) {
        //                // var data = JSON.parse(msg);
        //                //  $("#divLinks").empty().append(data.HTML);
        //                $("#divLinks").empty().append(msg);
        //                FB.XFBML.parse();
        //            },
        //            complete: function () { vsworx.global.hideLoader(el); }
        //        });

    };
    vsworx.siteERP.udateForumLinkStatus = function (el) {
        var status = $(el).attr("status");
        var lid = $(el).parent().parent().attr("oid");

        if (status == 3) {
            if (!confirm("Are you sure to delete this link"))
                return;
        }
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'UPDATEFORUMLINKSTATUS', status: status, lid: lid },
            success: function (msg) {
                var data = JSON.parse(msg);
                $(".trLinks[oid=" + lid + "]").remove();

            },
            complete: function () { vsworx.global.hideLoader(el); }
        });

    };
    vsworx.siteERP.markForumLinkControverisal = function (el) {
        var status = $(el).attr("status");
        var lid = $(el).parent().parent().attr("oid");
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'UPDATEFORUMLINKSTATUS', status: status, lid: lid },
            success: function (msg) {
                var data = JSON.parse(msg);
                if ($(el).html() == "mark controversial") {
                    $(el).html("unmark controversial");
                } else {
                    $(".trLinks[oid=" + lid + "]").remove();
                }

            },
            complete: function () { vsworx.global.hideLoader(el); }
        });
    };
    vsworx.siteERP.saveShareLink = function (el) {
        vsworx.validator.clearRules();
        vsworx.validator.rules = ["txtPopSendEmailId:required:Please Enter Send to emailId."];
        vsworx.validator.errorContainer = "#divPopRErr";
        vsworx.validator.validate();
        if (!vsworx.validator.failedElements.length == 0) {
            return false;
        }
        var lid = $(".hdnShareLinkId").val();
        var semail = $("#txtPopSendEmailId").val();
        var sname = $(".txtpopYourName").val();
        var email = $(".txtPopYourEmail").val();
        var msg = $(".txtPopYourEmail").val();
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'SAVESHARELINK', lid: lid, semail: semail, sname: sname, email: email, msg: msg },
            success: function (msg) {
                var data = JSON.parse(msg);
                if (data.IsValid) {
                    alert("link has been shared");
                } else {
                    $("#divPopRErr").html(data.Message).show(); ;
                }
            },
            complete: function () { vsworx.global.hideLoader(el); }
        });
    };
    vsworx.siteERP.saveHIdeForumLink = function (el) {
          var lid = $(el).parent().parent().attr("oid");
        var acttype = $(el).attr("acttype");
        var actval = $(el).attr("actval");
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'SAVEUSERACTION', lid: lid, acttype: acttype, actval: actval },
            success: function (msg) {
                var data = JSON.parse(msg);
                if (acttype == "1" && actval == "1") {
                    $(el).attr("actval", "0")
                    $(el).html("unsave");
                }
                if (acttype == "1" && actval == "0") {
                    $(el).attr("actval", "1")
                    $(el).html("save");
                }
                if (acttype == "2") {
                    $(".trLinks[oid=" + lid + "]").remove();
                }               
            },
            complete: function () { vsworx.global.hideLoader(el); }
        });
    };
    vsworx.siteERP.reportForumLink = function (el) {
        if (!confirm("Are you sure to report this link"))
            return;
        var oid = $(el).parent().parent().attr("oid");
        var ot = $(el).parent().parent().attr("ot");
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'SaveForumAbuseReport', oid: oid, ot: ot },
            success: function (msg) {
                var data = JSON.parse(msg);
                alert("This link has been reported");
            },
            complete: function () { vsworx.global.hideLoader(el); }
        });
    };



   
    vsworx.siteERP.shareForumLink = function (el) {
        var lid = $(el).parent().parent().attr("oid");
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'USERLOGREGISTER' },
            success: function (msg) {
                var data = JSON.parse(msg);
                if (data.IsValid) {
                    $.ajax({
                        beforeSend: function () { vsworx.global.showLoader(el); },
                        data: { method: 'GetShareLink', lid: lid },
                        success: function (msg1) {
                            var data1 = JSON.parse(msg1);                           
                            $("div#commonPopup").modal({
                                close: true,
                                persist: false,
                                overlay: 20,
                                onShow: function (dialog) {

                                    $("div#commonPopup").html(data1.HTML);
                                } //onShow of modal
                            });
                        },
                        complete: function () { vsworx.global.hideLoader(el); }
                    });

                } else {
                    $("div#commonPopup").modal({
                        close: true,
                        persist: false,
                        overlay: 20,
                        onShow: function (dialog) {
                            $("div#commonPopup").html(data.HTML);
                        } //onShow of modal
                    });
                }
            },
            complete: function () { vsworx.global.hideLoader(el); }
        });
    }
    vsworx.siteERP.saveCommentReply = function (el) {
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'USERLOGREGISTER' },
            success: function (msg) {
                var data = JSON.parse(msg);
                if (data.IsValid) {
                    var lid = $(".hdnlinkId").val();
                    var pid = $(el).attr("pid");
                    var cnt = $(".pReply[oid=" + pid + "]").find(".txtReply").val();
                    var sorttype = $("#cmbCommentSort").val();
                    if (cnt == "") {
                        alert("Please enter comment");
                        return;
                    }
                    $.ajax({
                        beforeSend: function () { vsworx.global.showLoader(el); },
                        data: { method: 'SAVEFORUMCOMMENT', lid: lid, cnt: cnt, pid: pid, ischild: 1, sorttype: sorttype },
                        success: function (msg) {
                            var data = JSON.parse(msg);
                            $(".spanChildCount[oid=" + pid + "]").html(parseInt($(".spanChildCount[oid=" + pid + "]").html()) + 1);
                            $(".trComment[pid=" + pid + "]").remove();
                            $(".trComment[oid=" + pid + "]").after(data.HTML);
                            $(".pReply[oid=" + pid + "]").empty().hide();
                        },
                        complete: function () { vsworx.global.hideLoader(el); }
                    });

                } else {
                    $("div#commonPopup").modal({
                        close: true,
                        persist: false,
                        overlay: 20,
                        onShow: function (dialog) {
                            $("div#commonPopup").html(data.HTML);
                        } //onShow of modal
                    });
                }
            },
            complete: function () { vsworx.global.hideLoader(el); }
        });
        
    };
    vsworx.siteERP.hideCommentReply = function (el) {
        var oid = $(el).attr("pid");
        $(".pReply[oid=" + oid + "]").empty().hide();
    };
    vsworx.siteERP.showCommentReply = function (el) {
        var pid = $(el).parent().parent().parent().parent().attr("oid");
        var cnt = '<textarea class="txtReply" rows="5" cols="50" ></textarea> <br /><br /><input  type="button" class="btn btnReply" pid="' + pid + '" value="Save"/> <input  type="button" class="btnCancelReply btn" pid="' + pid + '" value="Cancel"/>'
        $(".pReply[oid=" + pid + "]").empty().append(cnt).show();
    };
    vsworx.siteERP.saveForumComment = function (el) {
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'USERLOGREGISTER' },
            success: function (msg) {
                var data = JSON.parse(msg);
                if (data.IsValid) {
                    if ($("#txtPostComment").val() == "") {
                        alert("Please enter comment");
                        return;
                    }
                    var sorttype = $("#cmbCommentSort").val();
                    var lid = $(".hdnlinkId").val();
                    var cnt = $("#txtPostComment").val();
                    var pid = 0;
                    $.ajax({
                        beforeSend: function () { vsworx.global.showLoader(el); },
                        data: { method: 'SAVEFORUMCOMMENT', lid: lid, cnt: cnt, pid: pid, ischild: 0, sorttype: sorttype },
                        success: function (msg) {
                            var data = JSON.parse(msg);
                            $("#divComments").find(".addComm").html(data.HTML);
                            $("#txtPostComment").val("");
                        },
                        complete: function () { vsworx.global.hideLoader(el); }
                    });

                } else {
                    $("div#commonPopup").modal({
                        close: true,
                        persist: false,
                        overlay: 20,
                        onShow: function (dialog) {
                            $("div#commonPopup").html(data.HTML);
                        } //onShow of modal
                    });
                }
            },
            complete: function () { vsworx.global.hideLoader(el); }
        });

        
    };
    vsworx.siteERP.getForumComment = function (el) {
        var sorttype = $("#cmbCommentSort").val();
        var lid = $(".hdnlinkId").val();
      
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'GETFORUMCOMMENT', lid: lid, sorttype: sorttype },
            success: function (msg) {
                var data = JSON.parse(msg);
                $("#divComments").find(".addComm").html(data.HTML);               
            },
            complete: function () { vsworx.global.hideLoader(el); }
        });
    };
    vsworx.siteERP.voteUpDown = function (el) {
        var oid = $(el).attr("oid")
        var ot = $(el).attr("ot");
        var oval = $(el).attr("oval");
        $.ajax({
            beforeSend: function () { vsworx.global.showLoader(el); },
            data: { method: 'USERLOGREGISTER' },
            success: function (msg) {
                var data = JSON.parse(msg);
                if (data.IsValid) {
                    $.ajax({
                        beforeSend: function () { vsworx.global.showLoader(el); },
                        data: { method: 'VoteUpDown', oid: oid, ot: ot, oval: oval },
                        success: function (msg) {
                            var data = JSON.parse(msg);
                            if (data.IsValid) {
                                $(el).attr("oval", "0");
                                if (oval == 0) {
                                    $(".jsVoteUp[oid=" + oid + "][ot=" + ot + "]").attr("oval", "1");
                                    $(".jsVoteDown[oid=" + oid + "][ot=" + ot + "]").attr("oval", "-1");
                                } else {
                                    if ($(el).hasClass("jsVoteUp")) {
                                        $(".jsVoteDown[oid=" + oid + "][ot=" + ot + "]").attr("oval", "-1")
                                    } else {
                                        $(".jsVoteUp[oid=" + oid + "][ot=" + ot + "]").attr("oval", "1");
                                    }
                                }

                                $(".score[oid=" + oid + "][ot=" + ot + "]").html(data.RecordId);

                            }

                        },
                        complete: function () { vsworx.global.hideLoader(el); }
                    });
                   
                } else {
                    $("div#commonPopup").modal({
                        close: true,
                        persist: false,
                        overlay: 20,
                        onShow: function (dialog) {
                            $("div#commonPopup").html(data.HTML);
                        } //onShow of modal
                    });
                }
            },
            complete: function () { vsworx.global.hideLoader(el); }
        });


    };
//Start View Usr
    vsworx.siteERP.InitForumUserView = function () {
        $(".divUMenu").find("a").livequery('click', function (el) { vsworx.siteERP.manageUmenu(this) });
        $(".jsVoteUp,.jsVoteDown").livequery('click', function (el) { vsworx.siteERP.voteUpDown(this) });
        $(".jsVoteUp[oval=0]").livequery(function (el) { $(this).removeClass("up").addClass("upvoted") });
        $(".jsVoteUp[oval=1]").livequery(function (el) { $(this).addClass("up").removeClass("upvoted") });
        $(".jsVoteDown[oval=0]").livequery(function (el) { $(this).removeClass("down").addClass("downvoted") });
        $(".jsVoteDown[oval=-1]").livequery(function (el) { $(this).addClass("down").removeClass("downvoted") });
        $(".lnkShareLink").livequery('click', function (el) { vsworx.siteERP.shareForumLink(this) });
        $(".lnkReportLink").livequery('click', function (el) { vsworx.siteERP.reportForumLink(this) });
        $(".lnkMarkContLink").livequery('click', function (el) { vsworx.siteERP.markForumLinkControverisal(this) });
        (".btnShareLink").livequery('click', function (el) { vsworx.siteERP.saveShareLink(this) });   
    };
    vsworx.siteERP.manageUmenu = function (el) {
        cntid = $(el).attr("contenid");
        $(".divUMenu").find("a").removeClass("youarehere");
        $(el).addClass("youarehere");
        $(".divUsrArea").hide();
        $("#" + cntid).show();
    };
    ///Star Edit Usr
    vsworx.siteERP.InitForumUserEdit = function () {
        $("#lnkChangePhoto").livequery('click', function (el) { $("#divBrowseFile").toggle(); });
        $(".userBox").find("input").livequery('keyup', function (el) { if (el.keyCode == 13) { vsworx.siteERP.validateSiteUserEdit(this) } });
        $(".btnSaveUser").livequery('click', function (el) { vsworx.siteERP.validateSiteUserEdit(this) });
        $("form").submit(function () { return false; });
        $(".btnSaveUser").attr("onclick", "");
    };
    vsworx.siteERP.validateSiteUserEdit = function (el) {

        vsworx.validator.clearRules();
        vsworx.validator.rules = [$(".txtDisplayName").attr("id") + ":required:Please Enter Display Name."];
        vsworx.validator.errorContainer = "#divErr";
        vsworx.validator.validate();
        if (!vsworx.validator.failedElements.length == 0) {
            return false;
        }
        __doPostBack($(".btnSaveUser").attr("name"), '')
    };
   
