/**
 * author: chumahtung
 * createDate: 2016-05-18 17:14
 */

requirejs([], function () {

    SQ.alert = function (msg) {
        return window.alert(msg);
    };

    var Main = new SQ.Class();
    var utils = {
        _jsonP: function (url, callback, errorCallback) {
            var settings = {};
            if (typeof url === "string") {
                settings.url = url;
            }
            if (typeof url === "object") {
                settings = url;
            }

            $.ajax({
                url: settings.url,
                data: settings.data || {},
                dataType: 'jsonp',
                success: function (res) {
                    callback && callback(res);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    errorCallback && errorCallback(XMLHttpRequest, textStatus, errorThrown);
                },
                complete: function (XHR, TS) {
                    settings.completeCallback && settings.completeCallback(XHR, TS);
                }
            });
        }
    };

    Main.include({
        isLogin: false,
        /**
         * tab 切换效果
         * @param {object} option
         * @prop {string} tabBox tab标签容器
         * @prop {string} tabLi tab元素
         * @prop {string} tabDiv 内容元素
         * @prop {int} index 初始显示的tab
         * @prop {string} tabFocus tab按钮的样式
         * @prop {object} func tab切换的回调函数
         * @prop {string} eventType tab点击事件
         * @return {object} tab对象
         */
        _Tab: function (option) {
            var box = $(option.tabBox),
                tabs = $(option.tabBox + option.tabLi),
                divs = $(option.tabDiv);
            var obj = {
                /**
                 * 初始化
                 * @return {[type]} [description]
                 */
                init: function () {
                    var that = this;
                    //初始化
                    that.tabChange(tabs, option.index);
                    that.divChange(divs, option.index);
                },
                /**
                 * 标签状态切换函数
                 * @param  {jQuery} eles 全部的标签
                 * @param  {int} num  当前选中的标签
                 */
                tabChange: function (eles, num) {
                    for (var i = 0; i < eles.length; i++) {
                        eles.eq(i).removeClass(option.tabFocus);
                    }
                    ;
                    eles.eq(num).addClass(option.tabFocus);
                },
                /**
                 * 内容状态切换函数
                 * @param  {jQuery} eles 全部内容元素
                 * @param  {int} num  当前的内容块
                 */
                divChange: function (eles, num) {
                    for (var i = 0; i < divs.length; i++) {
                        divs.eq(i).addClass("hide");
                    }
                    ;
                    divs.eq(num).removeClass("hide");
                }
            }
            //给每个标签绑定事件
            box.on(option.eventType, option.tabLi, function (e) {
                e.preventDefault();
                var target = $(e.currentTarget),
                    num = target.parent().index(),
                    tabParent = tabs.eq(num).parent();
                if (tabParent.hasClass(option.tabFocus)) {  //如果点击的是同一个标签，不重新渲染
                    return false;
                }

                if (option.tabFocus !== "") {   //tabFocus为空时，不进行标签样式切换
                    obj.tabChange(tabs, num);
                }
                obj.divChange(divs, num);
                if (option.func !== "") {
                    option.func(target, num);
                }
            });
            obj.init();
            return obj;
        },
        /**
         * 登录
         *
         * @return {object} login对象
         */
        _login: function () {
            var that = this,
                tabDiv = $(".form"),
                logedDiv = $(".success_form"),
                nameBox = $("#username-span"),
                tabBox = $("#form-tab");

            /**
             * 修改页面显示
             * @param  {string} name 用户名
             */
            function logboxChange(flag) {
                if (flag === 1) {
                    tabDiv.addClass("hide");
                    logedDiv.removeClass("hide");
                    var username = login.userInfo.SHOW_NAME;
                    if (login.userInfo.AUTH_TYPE && !login.userInfo.ALIAS_ACCOUNT) {
                        username = "<img src='http://img1.37wanimg.com/www/css/images/game_site/ico-" + login.userInfo.AUTH_TYPE + ".png' alt=''/> " + username;
                    }
                    nameBox.html(username);
                    tabBox.addClass("hide");
                    that.isLogin = true;
                    //成功后领取激活码
                    utils._jsonP("http://hdapi.37.com/?c=c_get_gift&a=default&alias_info=zjzrss20160912&feature_key=get_gift&f=auto&class_key=gift_0", function (res) {
                        if (+res.result === 1 || +res.result === -32||+res.result === -70002) {
                            $("#code").val(res.val);
                            $("#copy").attr("data-clipboard-text", res.val);
                            $("#copy").removeClass("disabled");
                            SQ.clip(SQ.byId("copy"));
                        } else {
                            alert(res.msg);
                        }
                    });
                }
                if (flag === 2) {
                    logedDiv.addClass("hide");
                    tabBox.removeClass("hide");
                    that.tab.init();
                    that.isLogin = false;
                }
            }

            //初始化登录实例
            var login = this.login = new SQ.TgLogin({
                game_id: 393,
                dialog: true,  //是否需要实例化统一登录弹窗。
                dialogOpts: {
                    active: 0,  //弹窗默认打开的选项卡，0为登录，1为注册
                    hideId: true,  //是否显示身份证姓名，true：不显示；false：显示
                    zIndex: 1000    //修改z-index值
                }
            });
            login.bind("loged reged", function (u) {
                //绑定登录,注册成功事件
                return logboxChange(1);
            });
            login.bind("out", function () {
                //绑定注销事件
                return logboxChange(2);
            });
            login.bind("unlog", function (type, res) {
                type === "log" && res.message && SQ.alert(res.message);
            });
            login.bind("unreg", function (type, res) {
                type === "reg" && res.message && SQ.alert(res.message);
            });
            return login;
        },

        //切换角色
        _switchRole: function (leftSwitchSelector, rightSwitchSelector, rolesSelector) {
            var roles = $(rolesSelector);
            $(document)
            //往左切换
                .on("click", leftSwitchSelector, function (e) {
                    $.each(roles, function () {
                        var $this = $(this), $prev = $this.prev();
                        if (!$this.hasClass("hide")) {
                            $this.addClass("hide");
                            if (!$this.hasClass("hero_dc")) {
                                $prev.removeClass("hide");
                            } else {
                                roles.last().removeClass("hide");
                            }
                            return false;
                        }
                    });
                })
                //往右切换
                .on("click", rightSwitchSelector, function (e) {
                    $.each(roles, function () {
                        var $this = $(this), $next = $this.next();
                        if (!$this.hasClass("hide")) {
                            $this.addClass("hide");
                            if (!$this.hasClass("hero_zgl")) {
                                $next.removeClass("hide");
                            } else {
                                roles.first().removeClass("hide");
                            }
                            return false;
                        }
                    });
                })
        },

        //应用层初始化函数
        init: function () {
            var that = this;

            //设置游戏跳转-modify-content-start-2015-10-16,为进入游戏链接添加参数
            /*var gameRefer = SQ.getParam( "refer" );
             $( ".goto-game-btn-box" ).html( "<a href="http://game.37.com/server_list_275.html?refer=" + gameRefer + "\" target="_blank" class="btn">开始游戏</a>" );*/

            this.tab = this._Tab({
                tabBox: "#form-tab",
                tabLi: " li a",
                tabDiv: ".form",
                index: 0,
                tabFocus: "active",
                eventType: "mouseenter",
                func: ""
            });

            var login = this._login();

            login.getUserInfo()

            this._switchRole(".leftArrowToggle", ".rightArrowToggle", ".hero")

            var nameReg = $("#n-username"),
                pswReg = $("#n-password"),
                psw2Reg = $("#n-password1"),
                nameLog = $("#o-username"),
                pswLog = $("#o-password");

            var nameReg1 = $("#p-username"),
                pswReg1 = $("#p-password"),
                psw2Reg1 = $("#p-password1");
            //弹框注册
            nameReg1.on("keydown", function (e) {
                if (e.keyCode === 13) {
                    pswReg1.focus();
                }
            });
            pswReg1.on("keydown", function (e) {
                if (e.keyCode === 13) {
                    psw2Reg1.focus();
                }
            });
            psw2Reg1.on("keydown", function (e) {
                if (e.keyCode === 13) {
                    var username = nameReg1.val(),
                        password = pswReg1.val(),
                        password2 = psw2Reg1.val();
                    login.toReg(username, password, password2, true);
                }
            });
            //注册
            nameReg.on("keydown", function (e) {
                if (e.keyCode === 13) {
                    pswReg.focus();
                }
            });
            pswReg.on("keydown", function (e) {
                if (e.keyCode === 13) {
                    psw2Reg.focus();
                }
            });
            psw2Reg.on("keydown", function (e) {
                if (e.keyCode === 13) {
                    var username = nameReg.val(),
                        password = pswReg.val(),
                        password2 = psw2Reg.val();
                    login.toReg(username, password, password2, true);
                }
            });
            //登录
            nameLog.on("keydown", function (e) {
                if (e.keyCode === 13) {
                    pswLog.focus();
                }
            });
            pswLog.on("keydown", function (e) {
                if (e.keyCode === 13) {
                    var username = nameLog.val(),
                        password = pswLog.val();
                    login.toLog(username, password, 1, true);
                }
            });
            $(document)
            //弹框注册
                .on("click", ".pop-reg-btn", function (e) {
                    e.preventDefault();
                    var username = nameReg1.val(),
                        password = pswReg1.val(),
                        password2 = psw2Reg1.val();
                    login.toReg(username, password, password2, true);
                })
                //注册
                .on("click", ".reg-btn", function (e) {
                    e.preventDefault();
                    var username = nameReg.val(),
                        password = pswReg.val(),
                        password2 = psw2Reg.val();
                    login.toReg(username, password, password2, true);
                })
                //登录
                .on("click", ".log-btn", function (e) {
                    e.preventDefault();
                    var username = nameLog.val(),
                        password = pswLog.val();
                    login.toLog(username, password, 1, true);
                })
                //注销
                .on("click", "#logout", function (e) {
                    e.preventDefault();
                    login.toOut();
                })
                //下载
                .on("click", ".download", function (e) {
                    if (!that.isLogin) {
                        e.preventDefault();
                        SQ.alert('您还没有登录');
                    }
                });
                /*.on("click", ".close", function (e) {
                    e.preventDefault();
                    that.pop.addClass("hide");
                    that.shadow.addClass("hide");
                });*/
        },

        //底层初始化函数,自动在init之前执行
        initializer: function () {
            SQ.log("initializer");
        }
    });
    return new Main();
})