/**
 * Created by lenovo on 2015/7/31.
 */
var domain = 'xiaohua.feimao88.com';
var names = '飞猫笑话系统';
(function(){
    function confirmChangePass(){
        if (window.hiddenCommit) {
            window.hiddenCommit.setAttribute('value', this.value);
        } else {
            hiddenCommit = this.cloneNode(false);
            hiddenCommit.setAttribute('type', 'hidden');
            this.form.appendChild(hiddenCommit);
        }
        this.setAttribute('originalValue', this.value);
        this.disabled = true;
        this.value = '正在提交...';
        result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());
        if (result == false) {
            this.value = this.getAttribute('originalValue');
            this.disabled = false;
        }
        return result;
    }

    /**
     * 蒙层
     */
    function showMask(){
        $("#bg").show();
    }

    /**
     * 关闭蒙层与弹出层
     */
    function hidePop(){
        $("#bg").hide();
        $("#popDiv").hide();
    }


    /**
     * 展示email绑定修改界面
     */
    function showBindEmail(){
        showMask();
        var type=$(this).attr("bind-type");

        var seg = $($("#bind_email_tpl").html());
        if (type=="new"){
            seg.find("[name='email_addr']").val("绑定邮箱").attr("value", "绑定邮箱");
            seg.find("label").text("绑定邮箱");
            seg.find(".txt_passwd").val("设置您的糗百登录密码").attr("value", "设置您的糗百登录密码");
        }
        $("#popDiv").html(seg).show();
    }

    function showUnBindDiv(type){
        showMask();
        var html = $("#unbind_tpl").html()
        var seg = $(html)
        if(type==2){
            seg.find("label").text("输入密码，解除微博帐号绑定")
        }
        else if(type==1){
            seg.find("label").text("输入密码，解除QQ帐号绑定");
        }
        seg.find("a[action_unbind]").attr('data-type',type)
        $("#popDiv").html(seg).show();
    }

    function showEmailVerifySended(email){
        showMask();
        var html =$("#email_sended_tpl")
        html.find("[email]").text(email)
        var url = getEmailLoginUrl(email)
        if(url){
            html.find("a[action_go_verify]").attr("href",url)
        }
        else{
            html.find("a[action_go_verify]").hide();
        }
        $("#popDiv").html(html.html())
    }

    function getEmailLoginUrl(email){
        var parts = email.split("@");
        var mailDomain = parts[parts.length-1].toLowerCase();
        var normalMailList = [
            "qq.com",
            "163.com",
            "sina.com",
            "sohu.com",
            "tom.com",
            "21cn.com",
            "126.com",
            "foxmail.com",
            "sina.com.cn",
            "vip.qq.com",
            "139.com",
            "163.net"
        ];

        var specificMail = {
            "gmail.com":"mail.google.com",
            "hotmail.com":"login.live.com"
        };
        if(normalMailList.indexOf(mailDomain)>=0){
            return "http://mail."+  mailDomain;
        }
        if(!!specificMail[mailDomain]){
            return "http://"+specificMail[mailDomain];
        }
    }

    $("#popDiv").on("click","[action_unbind]",function(){
        var type= $(this).attr('data-type')
        var passwdObj = $(this).closest("form").find("input")
        if(!passwdObj.val()){
            passwdObj.focus();
            return alert("请输入糗事百科密码")
        }
        unbind_user(type,passwdObj.val())
    }).on("click","[action_bind_email]",function(){
        var form =  $(this).closest("form")
        var email = form.find("input[name='email_addr']").val()
        var password = form.find("input[name='email_passwd']").val()
        if(!isEmail(email)){
            return alert("请输入正确的邮箱格式");
        }
        $.ajax({
            url:"/my/edit",
            cache:false,
            dataType:"json",
            data:{"user[email]":email,"user[password]":password},
            type:"post",
            success:function(r){
                if(r && r.err==0){
                    showEmailVerifySended(email);
                }
                else if(r.err){
                    alert(r.err_msg)
                }
                else{
                    alert("请求服务器失败，请稍候再试")
                }
            },
            error:function(){
                alert("请求服务器失败，请稍候再试")
            }
        });
    });

    function isEmail(email) {
        var szReg = /^([a-zA-Z0-9]+[-|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[-|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        return szReg.test(email);
    }

    function unbind_user(type,password){
        $.ajax({
            url:"/my/unbond",
            type:"post",
            cache:false,
            dataType:"json",
            data:{type:type,password:password},
            success:function(r){
                if(r.err==0){
                    error("解除绑定成功")
                    window.location.reload();
                }
                else{
                    error(r.err_msg)
                }
            },
            error:function(r){
                error("连接服务器失败，请重试")
            }
        })
    }

    $(function(){
        
        // $("[action_change_pass]").click(function(){
        //     var old_password = $(this).closest("form").find("input[name='old_password']").val()
        //     var new_password = $(this).closest("form").find("input[name='password']").val()
        //     var password_confirmation= $(this).closest("form").find("input[name='password_confirmation']").val()
        //     if(!old_password){
        //         return alert("请输入原密码！")
        //     }

        //     if(!new_password || !password_confirmation || new_password!=password_confirmation){
        //         return alert("新密码设置为空或者不一致！")
        //     }

        //     $.ajax({
        //         url:"/my/editpass?async=true",
        //         type:"post",
        //         cache:false,
        //         dataType:"json",
        //         data:{old_password:old_password,password:new_password,password_confirmation:password_confirmation},
        //         success: function(r){
        //             if(r){
        //                 if(r && r.msg){
        //                     return error(r.msg)
        //                 }
        //                 else{
        //                     return error("修改密码失败，请稍后再试!")
        //                 }
        //             }
        //         },
        //         error:function(){
        //             return error("修改密码失败，请稍后再试!")
        //         }

        //     });
        // })

        $("[oauth_href]").each(function(i,x){
            $(x).attr("href",$(x).attr("href").replace(""+ domain +"",window.location.host))
        })

        $("[act_bind_email]").click(showBindEmail);

        $("#bg").click(hidePop)

        $(".mask").height($("body").height()+50);

        $(".unbind").click(function(){
            var type=$(this).attr("data-type")
            if(!type){
                return;
            }
            var email = $(".social-email").attr("data-email")
            if(!email){
                return alert("请先绑定邮箱，再解除第三方帐号绑定。")
            }
            showUnBindDiv(type);
        })

        //超过字符就自动在中间截断
        $(".email_value").each(function(){
            var str = $(this).html();
            if(str.length<=14) return ;
            str = str.substr(0,6)+"**"+str.substr(str.length-6);
            $(this).html(str);
        })

        //绑定第三方
        var src  = getUrlParam("src");//来源
        var code = getUrlParam("code");//授权令牌
        if(!code) return ;//没有授权令牌直接返回
        $.ajax({
            url:"/my/bond",
            type:"post",
            cache:false,
            dataType:"json",
            data:{src:src,code:code},
            success: function(r){
                if(r){
                    if(r.err!=0){
                        return error(r.err_msg);
                    }
                    else{
                        window.location.reload();
                    }
                }
            }
        });
        //替换当前页面链接，以免用户复制链接给其他人
        if(typeof(window.history.replaceState) != "undefined"){
            window.history.replaceState(null, document.title, "http://"+window.location.host+"/my/edit");
        }
        function getUrlParam(paramName,url){
            url = url ? url : window.location.href;
            var reg = new RegExp('(\\?|&)' + paramName + '=([^&?]*)', 'i');
            var arr = url.match(reg);
            return arr ? arr[2] : null;
        }

    })

    function error(msg){
        alert(msg);
    }

})();