﻿/// <reference path="../jquery.vsdoc.js" />
/// <reference path="../jquery.url.js" />

var client = new AJAXRPC_Client('/ajaxrpc/Server.aspx');

$(function () {
    //Menu项样式
    $(".MItem").mouseenter(function () {
        $(this).css("color", "#990042");
    });
    $(".MItem,#tdUser a").mouseleave(function () {
        $(this).css("color", "#4B5F79");
    });
    //Menu项Click
    $(".MItem").click(function () {
        //是否需要登录才可以打开
        if ("1" == $.url.setUrl($(this).attr("url")).param("isNeedLogin")) {
            //检查是否已经登录
            var result = client.Proxy.GetSession("User");
            if (result == "") {
                //必须是已登录
                alert("please login!");
                return;
            }
            window.open($(this).attr("url"), $(this).attr("target"));

        } else {
            window.open($(this).attr("url"), $(this).attr("target"));
        }
    });

    //用户状态
    userState();
    $("#tableUserInfo #btnClose").click(function () {
        $("#tableUserInfo").fadeOut(500);
    });
    //设置用户注册项目宽度
    $("#tableUserInfo :input:not([type='button'])").width(200);

    //用户信息提交
    $("#tableUserInfo #btnSubmit").click(function () {
        var items = $("#tableUserInfo :input[required='true'][value='']");
        if (0 < items.length) {
            alert("submit fail,please full you information!");
            return;
        }
        //两次密码必须相同
        if ($("#txtRegPwd").val() != $("#txtRegRePwd").val()) {
            alert("Two times input password must same!");
            return;
        }

        //账号是否重复
        var count = getScalar("select count(*) from Web_Users where UserID='" + $("#txtAccount").val() + "'");
        if (count != "0") {
            alert("Sorry,this account is registered!");
            return;
        }
        //进行提交
        $("#tableUserInfo #btnSubmit").attr("disabled", "disabled");
        var sql = "INSERT INTO" +
	                        "    [Web_Users]" +
                            "    ([GUID],[IsCustomer],[SeePrice],[UserID], [UserName], [Pwd], [IsAdmin], [IsTecher], [IsBuser],IsOperator, [Tel], [Email],Website, [Company], [Addr], [ZIP],SendMailBox, [Remarks], [RegTime])" +
                            " VALUES" +
                            "    ('" + NewGuid() + "',1,0, '" + $("#txtAccount").val() + "','" + $("#txtName").val() + "', '" + $("#txtRegPwd").val() + "',0, 0, 0,0,'" + $("#txtTel").val() +
                            "','" + $("#txtEmail").val() + "','" + $("#txtWebsite").val() + "', '" + $("#txtCompany").val() + "','" + $("#txtAddr").val() + "', '" + $("#txtZip").val() +
                            "', '" + $("#cboBuser").val() + "','" + $("#txtRemarks").val() + "',getDate())";
        client.Proxy.ExecuteNonQuery(
         sql, function (result) {
             if ("" == result.mess) {
                 //发送邮件
                 client.Proxy.SendMail("customer register", "account:" + $("#txtAccount").val() + ",name :" + $("#txtName").val(), $("#cboBuser").val());
                 result.mess = "submit success!";
                 //进行登录
                 var mess = client.Proxy.Login("User", $("#txtAccount").val(), $("#txtRegPwd").val());
                 if (mess != "") {
                     alert(mess);
                     return;
                 }
                 userState();
                 alert(result.mess);
                 $("#tableUserInfo #btnSubmit").removeAttr("disabled");
                 $("#tableUserInfo #btnClose").click();
             }
             else {
                 alert(result.mess);
                 $("#tableUserInfo #btnSubmit").removeAttr("disabled");
             }

         }
        );

    });

    //用户信息更新
    $("#tableUserInfo #btnUpdate").click(function () {
        var items = $("#tableUserInfo :input[required='true'][value='']");
        if (0 < items.length) {
            alert("submit fail,please full you information!");
            return;
        }
        //两次密码必须相同
        if ($("#txtRegPwd").val() != $("#txtRegRePwd").val()) {
            alert("Two times input password must same!");
            return;
        }

        //进行更新
        $("#tableUserInfo #btnUpdate").attr("disabled", "disabled");
        var sql = "UPDATE [Web_Users]" +
	                        "   SET " +
                            "   [UserName]='" + $("#txtName").val() +
                            "', [Pwd]='" + $("#txtRegPwd").val() +
                            "', [Tel]='" + $("#txtTel").val() +
                            "', [Email]='" + $("#txtEmail").val() +
                            "', Website='" + $("#txtWebsite").val() +
                            "', [Company]='" + $("#txtCompany").val() +
                            "', [Addr]='" + $("#txtAddr").val() +
                            "', [ZIP]='" + $("#txtZip").val() +
                            "', SendMailBox='" + $("#cboBuser").val() +
                            "', [Remarks]='" + $("#txtRemarks").val() +
                            "'  WHERE GUID='" + $("#tableUserInfo").data("GUID") + "'";
        client.Proxy.ExecuteNonQuery(
         sql, function (result) {
             if ("" == result.mess) {
                 result.mess = "update success!";
                 //进行登录
                 var mess = client.Proxy.Login("User", $("#txtAccount").val(), $("#txtRegPwd").val());
                 if (mess != "") {
                     alert(mess);
                     return;
                 }
                 userState();
                 alert(result.mess);
                 $("#tableUserInfo #btnUpdate").removeAttr("disabled");
                 $("#tableUserInfo #btnClose").click();
             }
             else {
                 alert(result.mess);
                 $("#tableUserInfo #btnUpdate").removeAttr("disabled");
             }

         }
        );

    });
    //产品搜索
    $("#Search a").mouseenter(function () {
        $(this).css("color", "#990042");
    });
    $("#Search a").mouseleave(function () {
        $(this).css("color", "#000");
    });

    $("#SearchWord").keydown(function (data) {
        if (13 == data.keyCode) {
            $("#doSearch").click();
        }
    });
    $("#doSearch").click(function () {
        if ($("#SearchWord").val() == "") {
            alert("please input search word!");
            return;
        }
        window.open("/Parts.htm" + "?title=Search&SearchType=Search&SearchBy=" + $("#cboSearchBy").val() + "&SearchByValue=" + $("#SearchWord").val(), "ContentWin");
    });
    //获取产品目录
    var setting = {
        showLine: true,
        isSimpleData: true,
        callback: { click: nodeOnClick },
        expandSpeed: "",
        treeNodeKey: "id",
        treeNodeParentKey: "pId"
    };

    client.Proxy.GetProTree(function (obj) {
        if (obj.mess != "") {
            alert(obj.mess);
        } else {
            var treeNodes = $.parseJSON(obj.result);
            var zTree = $("#tree").zTree(setting, treeNodes);
            //zTree.expandAll(true);

        }
    });

    function nodeOnClick(event, treeId, treeNode) {
        if (treeNode.toUrl) {
            window.open(treeNode.toUrl + "?title=" + treeNode.name + "&SearchType=" + treeNode.searchType + "&GUID=" + treeNode.id, "ContentWin");
            $("body").scrollTop(0);
        }
    };
    //调整内容区的尺寸
    function SetCwinHeight() {
        if (ContentWin.document.body != null) {
            $("#ContentWin").height(ContentWin.document.body.scrollHeight + 40);
            //$("#ContentWin").width(ContentWin.document.body.scrollWidth + 40);
        }
    }
    setInterval(SetCwinHeight, 50);
    //内容区
    $("#ContentWin").load(function () {
        if (null == $.url.setUrl(ContentWin.location.href).param("title"))
            $("#ContentTitile").hide();
        else
            $("#ContentTitile").show();
        $("#ContentTitile").html($.url.setUrl(ContentWin.location.href).param("title"));
    });

    //获取版权信息
    client.TxtDAO.GetWord("Copyright", function (info) {
        $("#divCopyright").html(info);
    });
});

//用户状态
var userState = function () {
    //检查是否是登录状态
    var result = client.Proxy.GetSession("User");
    if (result == "") {
        $("#tdUser").html(
        "<nobr>Account<input id='txtUserID' type='text' style='width:80px;'  class='e-text'/>" +
        "Pwd<input id='txtPwd' type='password' style='width:80px;'  class='e-text'/>" +
        "<a id='login'>Login</a>|<a id='reg'>Register</a>|<a id='forgot'>Forgot</a></nobr>"
        );
    }
    else {
        var userInfo = $.parseJSON(result);
        $("#tdUser").html("Welcome " + userInfo[0].UserName + ",&nbsp;&nbsp;&nbsp;&nbsp;<a id='modi'>Modify</a>|<a id='logout'>Logout</a></nobr>");
    }

    //未登录下的状态
    $("#tdUser a").mouseenter(function () {
        $(this).css("color", "#990042");
    });
    $("#tdUser a").mouseleave(function () {
        $(this).css("color", "#000");
    });
    //登录
    $("#txtUserID,#txtPwd").keydown(function (data) {
        if (13 == data.keyCode) {
            $("#login").click();
        }
    });


    //修改
    $("#modi").click(function (event) {
        var user = $.parseJSON(client.Proxy.GetSession("User"));
        var speed = 500;
        event.stopPropagation();
        var offset = $(event.target).offset();
        $("#tableUserInfo").css({ top: offset.top + $(event.target).height() + "px", left: ($(document).width() - $("#tableUserInfo").width()) / 2 + "px" });
        $("#tableUserInfo :input:not([type='button'])").val("");
        $("#tableUserInfo").data("GUID", user[0]["GUID"]);
        $("#UserInfoTitle").text("User modify");
        $("#txtAccount").val(user[0]["UserID"]);
        $("#txtAccount").attr("disabled", "disabled");
        $("#txtName").val(user[0]["UserName"]);
        $("#txtTel").val(user[0]["Tel"]);
        $("#txtEmail").val(user[0]["Email"]);
        $("#txtWebsite").val(user[0]["Website"]);
        $("#txtCompany").val(user[0]["Company"]);
        $("#txtAddr").val(user[0]["Addr"]);
        $("#txtZip").val(user[0]["ZIP"]);
        $("#cboBuser").val(user[0]["SendMailBox"]);
        $("#txtRemarks").val(user[0]["Remarks"]);
        $("#btnSubmit").hide();
        $("#btnUpdate").show();
        $("#tableUserInfo").fadeIn(speed);
    });

    //注销
    $("#logout").click(function () {
        client.Proxy.SetSession("User", "");
        userState();
    });
    //单击登录
    $("#login").click(function () {
        if ($("#txtUserID").val() == "" || $("#txtPwd").val() == "") {
            alert("User id And password is required");
            $("#tdUser input[value='']:eq(0)").focus();
            return;
        }

        //登录
        $("#login").attr("disabled", "disabled");
        var mess = client.Proxy.Login("User", $("#txtUserID").val(), $("#txtPwd").val());
        if (mess != "") {
            alert(mess);
        }
        else {
            userState();
        }
        $("#login").removeAttr("disabled");

    });


    //忘记密码
    $("#forgot").click(function (event) {
        event.stopPropagation();
        var offset = $(event.target).offset();
        $("#tabFindPwd").css({ top: offset.top + $(event.target).height() + "px", left: offset.left - $("#tabFindPwd").width() });
        $("#tabFindPwd :input:not([type='button'])").val("");
        $("#tabFindPwd").show();
        $("#txtAccForPwd").focus();
    });

    $("#btnFindPwdClose").click(function (event) {
        $("#tabFindPwd").hide();
    });
    //找回密码
    $("#btnFindPwdOK").click(function (event) {
        if ($("#txtMailForPwd").val() == "") {
            alert("please input the email");
            return;
        } else {
            $("#btnFindPwdOK").attr("disabled", "disabled");
            client.Proxy.FindPwd($("#txtMailForPwd").val(), function (result) {
                alert(result.mess);
                $("#btnFindPwdOK").removeAttr("disabled");
            })
        }


    });

    //注册
    $("#reg").click(function (event) {
        var speed = 500;
        event.stopPropagation();
        var offset = $(event.target).offset();
        $("#tableUserInfo").css({ top: offset.top + $(event.target).height() + "px", left: ($(document).width() - $("#tableUserInfo").width()) / 2 + "px" });
        $("#tableUserInfo :input:not([type='button'])").val("");
        $("#txtAccount").removeAttr("disabled");
        $("#UserInfoTitle").text("User register");
        $("#btnSubmit").show();
        $("#btnUpdate").hide();
        $("#tableUserInfo").fadeIn(speed);
        $("#txtAccount").focus();
    });
};
