﻿///<reference path="jquery-vsdoc.js" />

String.prototype.format = function() {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g, function(m, i) {
        return args[i];
    });
}
//V2 static
String.format = function() {
    if (arguments.length == 0)
        return null;
    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}


//对jquery基础功能和对象功能的扩展

//$.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); } var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };

$.extend({
    loadScriptDom: function(src) {
        if (!src) return;
        var head = document.getElementsByTagName("head")[0];
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = src;
        head.appendChild(script);
    },
    loadStyleDom: function(href) {
        if (!href) return;
        var head = document.getElementsByTagName("head")[0];
        css = document.createElement('link');
        css.type = 'text/css';
        css.href = href;
        css.rel = "stylesheet"
        head.appendChild(css);
    }
});

$.fn.pressEnter = function(fun) {
    // http://www.cssrain.cn/article.asp?id=1167
    this.keypress(function(e) {
        if (e.which == "13") {
            fun();
        }
    });
};

$.fn.clearLink = function(href) {
    var a = $("a[href]", this);

    a.each(function(idx) {
        var lnk = $(this);
        var att = lnk.attr("href");
        if (href == att)
            lnk.attr("href", "#");
    });
};

/**
* Clears the form data.  Takes the following actions on the form's input fields:
*  - input text fields will have their 'value' property set to the empty string
*  - select elements will have their 'selectedIndex' property set to -1
*  - checkbox and radio inputs will have their 'checked' property set to false
*  - inputs of type submit, button, reset, and hidden will *not* be effected
*  - button elements will *not* be effected
*/
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
* Resets the form data.  Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

$.fn.reload = function() {
    //重新载入
    var url = this.attr("url");
    if (url)
        this.load(url);
};

//默认的验证函数
$.fn.extend({
    isValid: function() {
        return true;
    }
});

$.fn.extend({
    //ajaxInit
    ajaxInit: function() {

        var a = $("a", this);
        //去掉超链接虚线框
        a.bind("focus", function() {
            if (this.blur) {
                this.blur();
            }
        });

        //去掉超链接下划线
        a.css("text-decoration", "none");

        //对class包含ajax并且有正确的url标签的对象自动执行ajax内容请求
        var ajax = $("div[url]", this);

        ajax.each(function(i) {
            var u = this.url;
            if (u && u != "") {
                $(this).load(u, null, function() {
                    eval("$(this).ajaxInit();$(this).show();");
                });
            }
        });

        var lnkAjax = $("a[class=ajax][href][target]", this);

        lnkAjax.each(function(idx) {
            var target = $("#" + this.target + ":first");
            if (target.size() != 0) {
                var href = this.href;
                $(this).click(function() {
                    if (href && href != "") {
                        target.load(href, null, function() {
                            eval("$(this).ajaxInit()");
                        });
                    }
                    return false;
                });
            } else {
                $(this).click(function() {
                    return false;
                });
            }
        });
    },
    //ajaxFormInit
    ajaxFormInit: function(cb) {

        var btnSub = $("input[type=submit],button[type=submit],a[class=submit],img[class=submit]", this);

        btnSub.each(function(idx) {
            var me = $(this);
            var f = me.parents("form");

            if (f.length != 0) {

                f.ajaxStart(function() {
                    $(this).fadeOut("slow");
                });

                f.ajaxStop(function(cb) {
                    $(this).fadeIn("fast");
                });

                if (me.is("a img")) {

                    me.attr("href", "#");

                    $(this).click(function() {
                        f.submit();
                        return false;
                    });
                }

                me.removeAttr("onclick");

                f.attr("SubmitDisabledControls", true);

                f.submit(function() {

                    if (!f.isValid()) { return false; }

                    if (f.attr("class") == "ajax") {

                        var serializedForm = f.serialize();

                        var act = f.attr("action") || window.location.toString();

                        var callback = (cb && typeof (cb) == "function") ? cb : function(res) {
                            var success = typeof (res.Success) == "undefined" ? true : res.Success;

                            if (res.Msg) {
                                alert(res.Msg);
                            }
                        }

                        $.post(act, serializedForm, callback, "json");

                        return false;
                    }
                    return true;
                });
            }
        });
    }
});

function overrideSerializeArray() {
    // if (typeof (Ext) == "object" && typeof (Ext.getCmp) == "function") {
    // alert("has Ext");
    // override begin
    $.fn.extend({
        // Keep a copy of the old param
        _serializeArray: jQuery.fn.serializeArray,
        // Serialize an array of form elements or a set of
        // key/values into a query string
        serializeArray: function() {
            // Coolite 的Form控件 含有serverID属性 使用中我们需要调用serverID属性作为Name来序列化将要提交的数据
            return this.map(function() {
                return this.elements ? $.makeArray(this.elements) : this;
            })
		.filter(function() {
		    return this.name && !this.disabled &&
				(this.checked || /select|textarea/i.test(this.nodeName) ||
					/text|hidden|password/i.test(this.type));
		})
		.map(function(i, elem) {

		    //add
		    var extObj = Ext.getCmp(this.name);

		    if (extObj && extObj.serverID) {
		        var extId = extObj.serverID;
		    }

		    var tp = $(this).attr("type");

		    if (tp && (tp == "radio" || tp == "checkbox")) {
		        var val = $(this).attr("checked");
		    }

		    if (!val)
		        var val = $(this).val();

		    //add end

		    /* old
		    return val == null ? null :
		    val.constructor == Array ?
		    jQuery.map(val, function(val, i) {
		    return { name: elem.name, value: val };
		    }) :
		    { name: elem.name, value: val };
		    */

		    //new
		    return val == null ? null :
				val.constructor == Array ?
					$.map(val, function(val, i) {
					    return { name: extId ? extId : elem.name, value: val };
					}) :
					{ name: extId ? extId : elem.name, value: val };

		    //end new
		}).get();
        },
        // 验证表单 调用ExtJs Form 控件的isValid函数验证表单
        isValid: function() {
            var isValid = true;
            var f = $(this);
            var v = f.find("input[type!=button],select,textarea")
                            .filter(function() {
                                return this.name && true;
                            });

            v.each(function(idx) {

                var extObj = Ext.getCmp(this.name);
                if (extObj && typeof (extObj.isValid) == "function") {
                    isValid = extObj.isValid() && isValid;
                }
            });
            //alert(isValid);
            return isValid;
        }
    });
}

$(document).ready(function() {
    $(this).ajaxInit();
    if ($("form[class=ajax]").length != 0)
        $(this).ajaxFormInit();

    if (typeof (Ext) == "object" && typeof (Ext.getCmp) == "function") {
        overrideSerializeArray();
    }
});


function GetRadioVal(name) {
    var val = "";
    $("input[type=radio][name=" + name + "]").each(function() {
        if ($(this).attr("checked") == true) {
            val = $(this).val();
            return;
        }
    });
    return val;
}

function GetCheckedVal(name) {
    var val = "";
    $("input[type=checkbox][name=" + name + "]").each(function() {
        if ($(this).attr("checked") == true) {
            if (val != "") {
                val += ",";
            }
            val += $(this).val();
        }
    });
    return val;
}
