﻿
//数米名称空间
var Shumi = {
    //创建代理
    createProxy: function (url) {
        return new this.ServiceProxy(url);
    },

    //实例化登录表单
    createLoginForm: function (config) {

        //初始化配置文件
        if (!config)
            config = this.LoginControl.config;

        //设置domain
        document.domain = config.domain;

        var lf = new this.LoginForm(config);
        lf.loginBySina = function () {
            window.open("http://login.fund123.cn/open/RequestToken.aspx?action=login&s=1&ReturnUrl=" + window.encodeURIComponent(window.location), "_self");
        };
        this.lf = { $: { $: { $: { loginBySina: lf.loginBySina}}} };
        return lf;
    },
    
    //实例化登录控件
    createLoginControl: function (config) {

        //初始化配置文件
        if (!config)
            config = this.LoginControl.config;

        //设置domain
        document.domain = config.domain;

        //创建登录服务
        var loginService = new this.LoginService(this.createProxy(config.loginService.proxy), config.loginService.service, config.loginService.type);

        //创建登录UI对象
        var loginUI = new this.Screen(this.createProxy(config.control.proxy), config.control.container, config.control.document, config.control.type);

        //创建登录控件对象
        var loginControl = new this.LoginControl(loginUI, loginService);

        //一个中间对象(引用当前声明的控件对象)
        this.$ = { $: { $: { $: loginControl}} };

        //添加用户登录方法
        loginControl.login = function () {
            if (window.validate($("#login_txtname").val(), $("#login_txtpwd").val(), $("#login_txtverifyCode").val()))
                this.onlogin({ username: $("#login_txtname").val(), password: $("#login_txtpwd").val(),
                    remember: $("#login_auto").attr("checked"), verifyCode: $("#login_txtverifyCode").val(), r: Math.random()
                });
        };

        //利用新浪账号登陆
        loginControl.loginBySina = function () {
            window.open("http://login.fund123.cn/open/RequestToken.aspx?action=login&s=1&ReturnUrl=" + window.encodeURIComponent(window.location), "_self");
        };

        //注册登录完成时事件
        loginControl.event_complete.add(

        //开启验证码机制
           function () {
               if (this.captcha) {
                   $("#login_VerifyCodePanel").show();
                   $("#login_txtverifyCode").val('');
                   $("#login_imgVerifyCode").attr("src", this.captcha.url + "&r=" + Math.random());
               }
           });

        //注册登录失败事件
        loginControl.event_failure.add(function () {
            alert(this.message.body);
        });

        //注册登录成功事件
        loginControl.event_success.add(function () {
            loginControl.close();               //关闭窗口
            loginControl.dispose();          //销毁代理
        });

        //注册通信失败事件
        loginControl.event_error.add(function (status, ex) {
            alert("通信失败（状态：" + status + "信息：" + ex + ")");
        });
        return loginControl;
    },

    //登陆表单类
    LoginForm: function (config) {

        //载入表单对象
        this.loadTo = function (container, returnUrl, index) {

            //如果不是容器对象，则重新实现容器对象
            if (typeof container != 'object') {
                var id = "#" + container;
                container = new Shumi.IContainer();

                //实现了登陆表单的呈现
                container.show = function () {
                    var obj = $(id);
                    obj.text('');
                    obj.append(this.content);
                };
            }
            this.form = new Shumi.Screen(Shumi.createProxy(config.control.proxy),
            container, config.control.document, config.control.type);
            this.form.show({ f: index || '002', ReturnURL: returnUrl || "http://i.fund123.cn", r: Math.random() });
        };
    },

    //登录控件类
    LoginControl: function (_window, _service) {
        this.window = _window;              //登陆窗体
        this.service = _service;                 //登录业务逻辑处理

        this.load = function () {              //显示弹出框
            if (this.checkCookie())
                this.window.show({ r: Math.random() });
            else {
                alert("您已经登录，请勿重复登录");
            }
        };

        this.close = function () {             //关闭弹出框
            this.window.close();
        };

        this.checkCookie = function () {   //检测用户的登录状态
            return (new Page.Cookie("user")).value == "";
        };

        this.dispose = function () {         //释放登录对象
            this.window.proxy.dispose();
            this.service.proxy.dispose();
        };

        //用户登录
        this.onlogin = function (_data) {
            this.service.onLogin(_data);
        };
        this.event_success = this.service.event_success;                           //注册成功事件池
        this.event_failure = this.service.event_failure;                               //注册失败事件池
        this.event_complete = this.service.event_complete;                   //登录完成事件池
        this.event_error = this.service.event_error;                                   //注册错误事件
    },

    //登录业务处理中心
    LoginService: function (_proxy, _url, _requestMethod) {
        var _this = this;
        this.url = _url;
        this.requestMethod = _requestMethod;
        this.proxy = _proxy;                                                        //初始化代理iframe

        this.event_success = new Shumi.Event();                       //登录成功事件池
        this.event_failure = new Shumi.Event();                         //登录失败事件池
        this.event_complete = new Shumi.Event();
        this.event_error = new Shumi.Event();                           //发生错误时将引发改事件

        this.onLogin = function (_data) {    //登录方法
            if (!this.proxy.window) {
                setTimeout(function () {
                    _this.onLogin(_data);
                }, 50);
            }
            else {
                if (!this.service) {
                    this.service = new this.proxy.window.Shumi.proxy(this.url);

                    //注册通信错误事件
                    this.service.event_error.add(function (ajax, status, er) {
                        for (var fun_er in _this.event_error.pool) {
                            var error_delegate = function () {
                                _this.event_error.pool[arguments.callee.methodIndex].apply(ajax, [status, er]);
                            };
                            error_delegate.methodIndex = fun_er;
                            setTimeout(error_delegate, 1);
                        }
                    });

                    //注册通信成功事件
                    this.service.event_success.add(function (data, status) {
                        eval(data);                           //得到Json对象
                        if (loginResult.message.code == 20000) {
                            for (var fun_su in _this.event_success.pool) {
                                var success_delegate = function () {
                                    _this.event_success.pool[arguments.callee.methodIndex].apply(loginResult);
                                }
                                success_delegate.methodIndex = fun_su;
                                setTimeout(success_delegate, 1);
                            }
                        }
                        else {
                            for (var fun_fa in _this.event_failure.pool) {
                                var failure_delegate = function () {
                                    _this.event_failure.pool[arguments.callee.methodIndex].apply(loginResult);
                                };
                                failure_delegate.methodIndex = fun_fa;
                                setTimeout(failure_delegate, 1);
                            }
                        }

                        for (var fun_co in _this.event_complete.pool) {
                            var complete_delegate = function () {
                                _this.event_complete.pool[arguments.callee.methodIndex].apply(loginResult);
                            };
                            complete_delegate.methodIndex = fun_co;
                            setTimeout(complete_delegate, 1);
                        }
                    });
                }

                this.service.type = this.requestMethod;
                this.service.data = _data;
                this.service.ajax();                      //发出ajax请求
            }
        };
    },

    //登录控件UI类
    Screen: function (_proxy, _window, _url, _requestMethod) {
        var _this = this;
        this.window = _window;
        this.proxy = _proxy;
        this.url = _url;
        this.requestMethod = _requestMethod;

        this.show = function (_data) {
            if (!this.proxy.window) {
                setTimeout(function () { _this.show(_data); }, 50);
            }
            else {
                if (!this.service) {
                    this.service = new this.proxy.window.Shumi.proxy(this.url);
                    this.service.event_success.add(function (data, status) {
                        _this.window.content = data;
                        _this.window.show();
                    });
                }
                this.service.type = this.requestMethod;
                this.service.data = _data;
                this.service.ajax();
            }
        };

        this.close = function () {                    //关闭登陆窗口
            this.window.close();
        };
    },

    //服务代理类
    ServiceProxy: function (url) {
        var _this = this;
        this.event_complete = new Shumi.Event();                //初始化事件池

        this.event_complete.add(function () {                        //引入iframe中的window对象
            _this.window = _this.Proxy.contentWindow ||
             _this.Proxy.contentDocument.parentWindow;
        });

        this.Proxy = Page.tool.Dom.$C("iframe");                   //载入iframe对象
        this.Proxy.hide();
        this.Proxy.src = url;
        this.Proxy.name = "ServiceProxy" + Page.unique();

        if (this.Proxy.attachEvent) {
            this.Proxy.attachEvent("onload", function () {         //IE浏览器的onload事件注册方式
                for (var fun in _this.event_complete.pool)
                    setTimeout(_this.event_complete.pool[fun], 1);
            });
        }
        else {
            this.Proxy.onload = function () {
                for (var fun in _this.event_complete.pool)
                    setTimeout(_this.event_complete.pool[fun], 1);
            };
        }

        document.body.appendChild(this.Proxy);            //加载代理

        this.dispose = function () {                                    //释放代理
            for (var fun in this.event_complete.pool)
                this.event_complete.remove(this.event_complete.pool[fun]);
            document.body.removeChild(this.Proxy);
        };
    },

    //事件对象
    Event: function () {
        this.pool = [];       //事件池
    },

    //资源预加载（css或script）
    Preload: function (_path, _fileName) {
        $.includePath = _path;
        $.include(_fileName);
    },

    //容器接口
    IContainer: function () {

        //内容
        this.content = '';
    }
};

Shumi.IContainer.prototype.show = function () { };
Shumi.IContainer.prototype.close = function () { };

//添加事件处理方法
Shumi.Event.prototype.add = function () {
    for (var i = 0; i < arguments.length; i++)
        this.pool.push(arguments[i]);
};

//移除事件处理方法
Shumi.Event.prototype.remove = function () {
    for (var i = 0; i < arguments.length; i++)
        this.pool.pop(arguments[i]);
};

//动态加载资源（css或script）
$.extend({
    includePath: '',
    include: function (file) {
        var files = typeof file == "string" ? [file] : file;
        for (var i = 0; i < files.length; i++) {
            var name = files[i].replace(/^\s|\s$/g, "");
            var att = name.split('.');
            var ext = att[att.length - 1].toLowerCase();
            var isCSS = ext == "css";
            var tag = isCSS ? "link" : "script";
            var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' ";
            var link = (isCSS ? "href" : "src") + "='" + $.includePath + name + "'";
            if ($(tag + "[" + link + "]").length == 0) $("head").append("<" + tag + attr + link + "></" + tag + ">");
        }
    }
});

//登录控件的配置
Shumi.LoginControl.config =
 {
     //登录服务配置
     loginService:
     {
         //登录业务的代理地址
         proxy: 'http://login.fund123.cn/proxy.htm',

         //登录服务的地址
         service: 'http://login.fund123.cn/login/IntegrateLogin.aspx',

         //登录方式（post或get）
         type: 'post'
     },

     //控件的UI配置
     control:
     {
         //获取UI的代理地址
         proxy: 'http://login.fund123.cn/proxy.htm',

         //提供UI文档内容的地址
         document: 'http://login.fund123.cn/login/LoginFace.ashx',

         //承载UI文档内容的容器对象
         container: new Page.Control.Pop(true, Page.Control.MODEL.DEFAULT, true),

         //获取UI的方式（get或post）
         type: 'get',

         //其他UI资源（css和js）的路径
         resourcePath: 'http://login.fund123.cn/Styles/',

         //其他UI资源（css和js）的文件名（多项如：['login.css','xy.js']）
         resourceFiles: ['loginControl.css']
     },

     //当前文档的domain和代理的domain一致
     domain: 'fund123.cn'
 };

//注册图片切换验证码方法
(function () {

    //预加载资源（css或js）
    Shumi.Preload(Shumi.LoginControl.config.control.resourcePath, Shumi.LoginControl.config.control.resourceFiles);

    //添加图片反转方法
    if (!this.FreshVerifyCode)
        this.FreshVerifyCode = function () {
            $("#login_imgVerifyCode").attr("src",
                $("#login_imgVerifyCode").attr("src") + "&rr=" + Math.random());
        };

    //表单验证控件
    if (!this.validate)
        this.validate = function (name, password, verifyCode) {
            if (name == '') {
                alert('请填写帐号信息');
                return false;
            }
            else if (password == '') {
                alert('请填写密码信息');
                return false;
            }
            else if (verifyCode == '') {
                alert('请填写验证码信息');
                return false;
            }
            else {
                return true;
            }
        };
    })();
