﻿var K2046 = {
    //页面是否已载入完成
    Loaded: false

    , $: function(el) {//取得指定id的dom元素.
        if (typeof (el) == "string") {
            return document.getElementById(el);
        }
        return el;
    }

    //一些特效，见Effect目录。
    , Effect: {}

    , $Name: function(name) {
        //        parent = parent ? K2046.$(parent) : document;
        return document.getElementsByName(name);
    }

    , $Tag: function(tag, parent) {
        parent = parent ? K2046.$(parent) : document;
        return parent.getElementsByTagName(tag);
    }

    //用于生成Guid唯一标识的对象.
    , Guid: {
        //生成一个空的Guid
        Empty: "00000000-0000-0000-0000-000000000000"

        //创建一个新的Guid.
        , NewGuid: function() {
            return (this.$4() + this.$4() + "-" + this.$4() + "-" + this.$4() + "-" + this.$4() + "-" + this.$4() + this.$4() + this.$4());
        }

        //随机生成4位16进制数字.
        , $4: function() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
    }

    , Round: function(number, length, endwithzero) {
        number = number * Math.pow(10, length);
        number = Math.round(number);
        number /= Math.pow(10, length);
        if (endwithzero && length > 0) {
            number += "";
            if (number.indexOf(".") == -1) {
                number += ".";
            }
            var begin = number.substring(number.indexOf("."), number.length).length - 1;
            for (; begin < length; begin++) {
                number += "0";
            }
        }
        return number;
    }

    , NameSpace: function(obj, name) {
        if (!obj[name]) {
            obj[name] = {};
        }
    }

    , NS: function(path) {
        if (path) {
            var n = path.split(".");
            if (!window[n[0]]) {
                window[n[0]] = {};
            }
            var t = window[n[0]];
            for (var x = 1; x < n.length; x++) {
                if (!t[n[x]]) {
                    t[n[x]] = {};
                }
                t = t[n[x]];
            }
        }
    }

    , OutputFlash: function(el, url, w, h) {
        el = K2046.$(el);
        if (!el)
            return;
        var str = '';
        str += '<object width="{0}" height="{1}" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0">';
        str += '<param name="movie" value="{2}">';
        str += '<param name="wmode" value="transparent">';
        str += '<param name="quality" value="autohigh">';
        str += '<param name="allowScriptAccess" value="always" > ';
        str += '<embed width="{0}" height="{1}" src="{2}" quality="autohigh" wmode="opaque" type="application/x-shockwave-flash" plugspace="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed>';
        str += '</object>';
        K2046.SetHtml(el, str.format(w, h, url));
    }

    , JsonParse: function(source) {//将字符串转换成js对象.
        var result = {};
        try {
            result = eval("(" + source + ")");
        }
        catch (error) {
            alert(error.message);
        }
        return result; ;
    }

    , SetValue: function(el, value) {
        el = this.$(el);
        if (el) {
            el.value = value;
            return true;
        }
        return false;
    }

    , GetValue: function(el) {
        var result = null;
        el = this.$(el);
        if (el) {
            result = el.value;
        }
        return result;
    }

    , SetHtml: function(el, html) {
        el = this.$(el);
        if (el) {
            el.innerHTML = html;
            return true;
        }
        return false;
    }

    , GetHtml: function(el) {
        var result = null;
        el = this.$(el);
        if (el) {
            result = el.innerHTML;
        }
        return result;
    }

    //对指定的对象附加事件方法(K2046.Events.On的简写).
    //参数说明:
    //element   :   string/dom,要附加方法的对象,可为id或对象本身.
    //action    :   string,要附加的事件.
    //func      :   function,要附加的方法.
    //options   :   object,要传递的参数
    , On: function(element, action, func, options) {
        return K2046.Events.On(element, action, func, options);
    }

    //该类用于替代WindowEvent,实现可以对任意元素的事件附加方法.
    , Events: {

        //已注册事件的对象集合
        Elements: []

        //已注册事件的方法集合
        , FunctionCollection: {}

        //对指定的对象附加事件方法.
        //参数说明:
        //element   :   string/dom,要附加方法的对象,可为id或对象本身.
        //action    :   string,要附加的事件.
        //func      :   function,要附加的方法.
        //options   :   object,要传递的参数
		, On: function(element, action, func, options) {
		    K2046.Events.Attach(element, "on" + action, func, options);
		}

        //对指定的对象附加事件方法.
        //参数说明:
        //element   :   string/dom,要附加方法的对象,可为id或对象本身.
        //action    :   string,要附加的事件.
        //func      :   function,要附加的方法.
        //options   :   object,要传递的参数.
        , Attach: function(element, action, func, options) {
            element = K2046.$(element);
            if (!element) {
                return;
            }
            var index = this.SetElement(element); //注册对象,取得对象注册的索引值.
            if (!this.FunctionCollection[index]) {
                this.FunctionCollection[index] = {};
            }
            if (!this.FunctionCollection[index][action]) {
                this.FunctionCollection[index][action] = [];
                //判断对象的指定事件是否已指定方法.
                var original = element[action];
                if (original && typeof (original) == 'function') {
                    this.Attach(element, action, original);
                }
                //将元素的指定事件方法引用到K2046.Events的Execute方法.
                element[action] = function(me, m) { return function(e) { return me.Execute(index, m, e || event) } } (this, action);
            }

            //将方法添加到集合.
            this.FunctionCollection[index][action].push({ func: func, options: options });
        }

        //移除指定元素指定事件的方法.
        , Remove: function(element, action, func) {
            element = K2046.$(element);
            if (!element) {
                return;
            }
            var index = this.GetEventsIndex(element);
            //检查索引/方法集合是否正确.
            if (index < 0 || !this.FunctionCollection || !this.FunctionCollection[index] || !this.FunctionCollection[index][action]) {
                return;
            }

            //检查方法集合,如找到注册的方法则设为null.
            for (var x = this.FunctionCollection[index][action].length - 1; x >= 0; x--) {
                if (this.FunctionCollection[index][action][x] && this.FunctionCollection[index][action][x].func == func) {
                    //this.FunctionCollection[index][action][x] = null;
                    this.FunctionCollection[index][action].splice(x, 1);
                }
            }
        }

        //检查指定对象是否已注册.返回对象注册的索引值.
        , SetElement: function(element) {
            var result = this.GetEventsIndex(element);
            if (result < 0) {
                this.Elements.push(element);
                result = (this.Elements.length - 1);
            }
            return result;
        }

        //取得指定元素的方法集合索引值.
        , GetEventsIndex: function(element) {
            for (var x = 0; x < this.Elements.length; x++) {
                if (this.Elements[x] === element) {
                    return x;
                }
            }
            return -1;
        }

        //内部调用方法,执行指定对象指定事件中的方法.
        //参数说明:
        //index     :   int,对象注册的索引值.
        //action    :   string,触发的事件.
        //options   :   object,要传递的参数.
        //e         :   object,window的event对象.
        //===================================================
        //返回值    :   返回所有方法执行后的返回值.
        //如果所有方法都没有返回值,则返回null.
        //如果有一个方法有返回值,则返回该方法的返回值.
        //如果有多个方法有返回值,则返回最后注册的方法的返回值.
        , Execute: function(index, action, e) {
            var result = undefined;
            var t = K2046.Events;
            if (t.FunctionCollection[index] && t.FunctionCollection[index][action]) {
                for (var x = 0; x < t.FunctionCollection[index][action].length; x++) {
                    try {
                        //检查指定索引的方法是否已被移除.
                        var f = t.FunctionCollection[index][action][x];
                        if (f && typeof (f.func) == "function") {
                            var v;
                            if (f.options != undefined) {
                                v = f.func(f.options, e);
                            }
                            else {
                                v = f.func(e);
                            }
                            //var v = f.func(f.options, e); //执行指定的方法,并传递参数和event对象.
                            if (v != undefined) {
                                result = v;
                            }
                        }
                    }
                    catch (err) {
                        alert(err.message);
                        continue;
                    }
                }
            }

            //如果执行的方法中有返回值,则执行返回.
            if (result != undefined) {
                return result;
            }
        }
    }

    //Collecter类的代理方法
    //使用该方法时必须在页面中引用XmlHelper.js和Collecter.js.
    //参数:
    //      form    :   要收集数据的表单ID.
    //返回值:
    //      返回一个包含form数据的Xml文档.
    , Collect: function(form) {
        return new Collecter(new XmlHelper(), this.$(form)).Collect();
    }

    , SD: function(el) {//切换dom可见状态.
        this.$(el).style.display = (this.$(el).style.display == 'none') ? '' : 'none';
    }

    , WindowEvent: {//window事件管理类.
        Events: {} //已注册的事件列表.
        , Attach: function(e, fun) {//附加指定的方法到事件列表.
            if (!this.Events[e]) {
                this.Events[e] = [];
                window[e] = function(me, m) { return function() { me.Execute(m) } } (this, e);
            }
            this.Events[e].push(fun);
        }
        , Execute: function(e) {//执行指定window事件列表中的方法.
            if (this.Events[e]) {
                for (var x = 0; x < this.Events[e].length; x++) {
                    try {
                        this.Events[e][x]();
                    }
                    catch (err) {
                        continue;
                    }
                }
            }
        }
    }

    , MsgBox: {
        Show: function(options) {
            options = options || {};
            if (!options.msg) {
                return;
            }
            this.InitContainer(options);
            this.Content.innerHTML = options.msg;
        }

        , Container: null

        , Content: null

        , Background: null

        , InitContainer: function(options) {
            if (options.bg) {
                if (!this.Background) {
                    this.Background = K2046.Helper.CreateIframe();
                }
                this.Background.style.display = "block";
            }
            if (this.Container) {
                this.Container.style.display = "block";
                return;
            }
            var container = this.Container = document.createElement("div");
            container.style.display = "none";
            document.body.appendChild(container);
            container.style.height = "50px";
            container.style.width = "320px";
            container.style.position = "absolute";
            container.style.left = "50%";
            container.style.top = "50%";
            container.style.marginTop = "-25px";
            container.style.marginLeft = "-160px";
            container.style.textIndent = "25px";
            container.style.backgroundImage = "url(/images/msg.gif)";
            container.style.display = "block";
            K2046.Float.Attach({ element: container, step: 1 });

            var content = this.Content = document.createElement("div");
            content.style.height = "20px";
            content.style.width = "295px";
            content.style.marginTop = "15px";
            content.style.marginLeft = "25px";
            content.style.lineHeight = "20px";
            content.style.fontSize = "12px";
            content.style.background = "url(/images/info.gif) no-repeat";
            container.appendChild(content);
        }

        , Close: function() {
            if (this.Background) {
                this.Background.style.display = "none";
            }
            if (this.Container) {
                this.Container.style.display = "none";
            }
        }
    }

    , Dom: {
        Remove: function(element) {
            element = K2046.$(element);
            element.parentNode.removeChild(element);
        }
    }

    //向页面注册脚本文件
    //参数:
    //      url         :   string,必须,脚本文件地址.
    //      container   :   dom,可选,注册脚本的容器
    //返回值:
    //      返回注册脚本的引用.
    , AppendScript: function(url, container, options) {
        var element = document.createElement('script');
        element.language = 'javascript';
        element.type = 'text/javascript';
        element.src = url;
        if (options && options.attr) {
            for (var c in options.attr) {
                element.setAttribute(c, options.attr[c]);
            }
        }
        if (options && options.callback && typeof (options.callback) == "function") {
            K2046.On(element, "readystatechange", function() { if (element.readyState == "complete") { options.callback(element); } });
        }
        if (!container) {
            container = K2046.$Tag("head");
            container = container.length ? container[0] : document.body;
        }
        if (container) {
            container.appendChild(element);
        }
        return element;
    }

    //检查当前页面是否被嵌入Iframe中,如果是则将顶层页面地址替换为本页地址.
    , NotIframe: function() {
        if (top.location != self.location) {
            top.location = self.location;
        }
    }

    , GetPosition: function(el) {//取得指定Dom的绝对位置
        var R = { x: 0, y: 0 };
        R.x = el.offsetLeft;
        R.y = el.offsetTop;
        while (el = el.offsetParent) {
            R.y += el.offsetTop;
            R.x += el.offsetLeft;
        }
        return R;
    }

    //在新窗口中预览html代码.
    , ViewCode: function(code) {
        window.open().document.write(code);
    }

    //根据指定checkbox或radio的选中状态切换指定dom的disabled状态.
    //o : checkbox或radio的id.
    //t : 指定dom的id.
    , SetDisabled: function(o, t) {
        t = K2046.$(t);
        o = K2046.$(o);
        if (o.checked) {
            t.disabled = "";
        } else {
            t.disabled = "disabled";
        }
    }

    , Users: {
        GetLoginUser: function(callback) {
            if (K2046.Users.User.IsLogin) {
                callback(K2046.Users.User);
                return;
            }
            K2046.Ajax.Request({
                url: "/Ajax/AjaxRequest.aspx?Action=GetNowCustomer"
                , method: "post"
                , callback: function(text) {
                    if (text) {
                        var result = K2046.JsonParse(text);
                        if (result) {
                            K2046.Users.User = result;
                            callback(result);
                        }
                        else {
                            callback(result);
                        }
                    }
                }
            });
        }

        , Logout: function() {
            K2046.MsgBox.Show({ msg: "正在为您退出登录,请稍候...", bg: 1 });
            K2046.Ajax.Request({
                url: "/Ajax/AjaxRequest.aspx?Action=Logout"
                , method: "post"
                , callback: function(text) {
                    if (text == "success") {
                        K2046.MsgBox.Close();
                        window.location.reload();
                    }
                }
            });
        }

        , User: {
            IsLogin: false
            , NickName: ''
        }
    }

    , Redirect: function(url, replace) {
        if (replace) {
            window.location.replace(url);
        }
        else {
            window.location = url;
        }
    }

    , Path: {
        GetExtension: function(path) {
            if (path) {
                return path.substring(path.lastIndexOf("."), path.length);
            }
            return path;
        }
    }

    , Helper: {
        CreateIframe: function(options) {
            options = options || {};
            options.opacity = options.opacity || 5;
            options.top = options.top || 0;
            options.left = options.left || 0;
            options.width = options.width || (document.documentElement.scrollWidth || document.body.scrollWidth);
            options.height = options.height || (document.documentElement.scrollHeight || document.body.scrollHeight);
            var frame = document.createElement("iframe");
            document.body.appendChild(frame);
            frame.src = "/resources/blank.htm";
            frame.style.width = options.width + "px";
            frame.style.height = options.height + "px";
            frame.style.position = "absolute";
            frame.frameBorder = 0;
            frame.style.top = options.top + "px";
            frame.style.left = options.left + "px";
            frame.style.filter = "alpha(opacity=" + options.opacity + ")";
            frame.style.opacity = options.opacity / 100;
            frame.zIndex = 9999;
            return frame;
        }
    }
};

K2046.On(window, "load", function() { K2046.Loaded = true; });

String.prototype.trim = function(c) {
    var reg = /^\s+|\s+$/ig;
    if (c) {
        reg = eval("/^" + c + "+|" + c + "$/ig");
    }
    return this.replace(reg, "");
};

String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {
        for (var x = 0; x < arguments.length; x++) {
            result = result.replace(eval("/\\{" + x + "\\}/g"), arguments[x]);
        }
    }
    return result;
};

function IsEmail(s) {
    return /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(s);
}

function IsInteger(s) {
    return parseInt(s) == s;
}

function IsNumber(s) {
    return parseFloat(s) == s;
}

var X = K2046;