﻿/*
数据操作类
*/
Array.prototype.remove = function(index){
    if(index < 0 || index >= this.length){
        return;
    }
    var f = false;
    for(var i=0,n=0;i<this.length;i++){
        if(i != index){
            this[n++] = this[i];
        }
        else{
            f = true;
        }
    }
    if(f){
        this.length -= 1;
    }
}

Array.prototype.exists = function(str){
    var store = false;
    for(var i=0;i<this.length;i++){
        if(this[i] == str){
            store = true;
            break;
        }
    }
    return store;
}

/*
排序专用(同一时间只用有一个数组使用)
DESC:降序
ASC:升序
*/
var ArraySort = {
    Index : 0,
    Key : "",
    FloatSortByIndexDESC : function(x, y){
        if(parseFloat(x[ArraySort.Index]) < parseFloat(y[ArraySort.Index])) { return 1; } else { return -1; }
    },
    
    ChineseSortByIndexDESC : function(x, y){
        return y[ArraySort.Index].localeCompare(x[ArraySort.Index]);
    },
    
    FloatSortByKeyDESC : function(x, y){
        if(parseFloat(x[ArraySort.Key]) < parseFloat(y[ArraySort.Key])) { return 1; } else { return -1; }
    },
    
    ChineseSortByKeyDESC : function(x, y){
        return y[ArraySort.Key].localeCompare(x[ArraySort.Key]);
    },
    
    FloatSortByIndexASC : function(x, y){
        if(parseFloat(x[ArraySort.Index]) < parseFloat(y[ArraySort.Index])) { return -1; } else { return 1; }
    },
    
    ChineseSortByIndexASC : function(x, y){
        return x[ArraySort.Index].localeCompare(y[ArraySort.Index]);
    },
    
    FloatSortByKeyASC : function(x, y){
        if(parseFloat(x[ArraySort.Key]) < parseFloat(y[ArraySort.Key])) { return -1; } else { return 1; }
    },
    
    ChineseSortByKeyASC : function(x, y){
        return x[ArraySort.Key].localeCompare(y[ArraySort.Key]);
    }
}

/*
字符串操作类
*/
String.prototype.Deal = function(){
    var str = this.replace(/\n/gi, "<br />");
    return str;
}

String.prototype.DeDeal = function(){
    var str = this.replace(/\<br \/\>/gi, "\n");
    str = str.replace(/\<br\/\>/gi, "\n");
    return str;
}

this.json = typeof JSON != "undefined" ? JSON : null;

String.prototype.decode = function(){
   if(this == "")
        return;
   var text = this;
   if (this.json != null ) {
        return this.json.parse(text);
   }
   if (Browser.gecko) {
       return new Function( "return " + text )();
   }
   return eval( "(" + text + ")" )
}

String.prototype.AddZero = function(){
    var num = this;
    if(this.length == 1){
        num = "0" + this;
    }
    return num;
}

String.Format = function(template, data){
    var exp;    
    for(var i=0;i<data.length;i++){
        exp = new RegExp("\\{"+i+"\\}", "ig");
        template = template.replace(exp, data[i]);
    }
    return template;
}

String.prototype.Trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

/*
Float操作类
*/
function FormatNumber(srcStr,nAfterDot)
{
　  srcStr = parseFloat(srcStr);
    return srcStr.toFixed(nAfterDot);
}

/*
日期操作类
*/
Date.prototype.formate = function(){
    var array = [];
    array.push(this.getFullYear());
    array.push("/");
    array.push((this.getMonth()+1).toString().AddZero());
    array.push("/");
    array.push(this.getDate().toString().AddZero());
    array.push(" ");
    array.push(this.getHours().toString().AddZero());
    array.push(":");
    array.push(this.getMinutes().toString().AddZero());
    array.push(":");
    array.push(this.getSeconds().toString().AddZero());
    return array.join('');
}

/*
浏览器
*/
var Browser = function() {
    var o = {
        ie: 0,
        opera: 0,
        gecko: 0,
        webkit: 0
    };
    var ua = navigator.userAgent, m;
    if ( ( /KHTML/ ).test( ua ) ) {
        o.webkit = 1;
    }
    // Modern WebKit browsers are at least X-Grade
    m = ua.match(/AppleWebKit\/([^\s]*)/);
    if (m&&m[1]) {
        o.webkit=parseFloat(m[1]);
    }

    if (!o.webkit) { // not webkit
        // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
        m=ua.match(/Opera[\s\/]([^\s]*)/);
        if (m&&m[1]) {
            o.opera=parseFloat(m[1]);
        } else { // not opera or webkit
            m=ua.match(/MSIE\s([^;]*)/);
            if (m&&m[1]) {
                o.ie=parseFloat(m[1]);
            } else { // not opera, webkit, or ie
                m=ua.match(/Gecko\/([^\s]*)/);
                if (m) {
                    o.gecko=1; // Gecko detected, look for revision
                    m=ua.match(/rv:([^\s\)]*)/);
                    if (m&&m[1]) {
                        o.gecko=parseFloat(m[1]);
                    }
                }
            }
        }
    }
    return o;
}();

/*
HTML操作方法
*/
Object.prototype.insertAdjacentHTML = function(where, html) {
    try {
        var e = this.ownerDocument.createRange();
        e.setStartBefore(this);
        e = e.createContextualFragment(html);
        switch (where) {
            case 'beforeBegin': this.parentNode.insertBefore(e, this); break;
            case 'afterBegin': this.insertBefore(e, this.firstChild); break;
            case 'beforeEnd': this.appendChild(e); break;
            case 'afterEnd':
                if (!this.nextSibling) this.parentNode.appendChild(e);
                else this.parentNode.insertBefore(e, this.nextSibling); break;
        }
    } catch (e)
    { }
}

function insertHtml(where, el, html){
    where = where.toLowerCase();
    if(el.insertAdjacentHTML){
        switch(where){
            case "beforebegin":
                el.insertAdjacentHTML('BeforeBegin', html);
                return el.previousSibling;
            case "afterbegin":
                el.insertAdjacentHTML('AfterBegin', html);
                return el.firstChild;
            case "beforeend":
                el.insertAdjacentHTML('BeforeEnd', html);
                return el.lastChild;
            case "afterend":
                el.insertAdjacentHTML('AfterEnd', html);
                return el.nextSibling;
        }
    }
    var range = el.ownerDocument.createRange();
    var frag;
    switch(where){
         case "beforebegin":
            range.setStartBefore(el);
            frag = range.createContextualFragment(html);
            el.parentNode.insertBefore(frag, el);
            return el.previousSibling;
         case "afterbegin":
            if(el.firstChild){
                range.setStartBefore(el.firstChild);
                frag = range.createContextualFragment(html);
                el.insertBefore(frag, el.firstChild);
                return el.firstChild;
            }else{
                el.innerHTML = html;
                return el.firstChild;
            }
        case "beforeend":
            if(el.lastChild){
                range.setStartAfter(el.lastChild);
                frag = range.createContextualFragment(html);
                el.appendChild(frag);
                return el.lastChild;
            }else{
                el.innerHTML = html;
                return el.lastChild;
            }
        case "afterend":
            range.setStartAfter(el);
            frag = range.createContextualFragment(html);
            el.parentNode.insertBefore(frag, el.nextSibling);
            return el.nextSibling;
        }
}

//操作元素
function GetDom(id){
//    if(typeof id == "string"){
//        document.getElementById(""
//    }
}

/**
 * Bind Method
 */
Function.prototype.Bind = function() { 
	var __m = this, object = arguments[0], args = new Array(); 
	for(var i = 1; i < arguments.length; i++){
		args.push(arguments[i]);
	}
	
	return function() {
		return __m.apply(object, args);
	}
};

var isIE = false;
var userAgent = navigator.userAgent.toLowerCase();
if ((userAgent.indexOf('msie') != -1) && (userAgent.indexOf('opera') == -1)) {
	isIE = true;
}

var IO = {};
IO.Script = function(){
	this.Init.apply(this, arguments);
};

IO.Script.prototype = {
	_scriptCharset: 'gb2312',
	_oScript: null,
	
	/**
	 * Constructor
	 * 
	 * @param {Object} opts
	 */
	Init : function(opts){
		this._setOptions(opts);
	},
	
	_setOptions: function(opts) {
		if (typeof opts != 'undefined') {
			if (opts['script_charset']) {
				this._scriptCharset = opts['script_charset'];
			}
		}
	},
	
	_clearScriptObj: function() {
		if (this._oScript) {
			try {
				this._oScript.onload = null;
				if (this._oScript.onreadystatechange) {
					this._oScript.onreadystatechange = null;
				}
				
				this._oScript.parentNode.removeChild(this._oScript);
				//this._oScript = null;
			} catch (e) {
				// Do nothing here
			}
		}
	},
	
	_callbackWrapper: function(callback) {
		if (this._oScript.onreadystatechange) {
			if (this._oScript.readyState != 'loaded' && this._oScript.readyState != 'complete') {
				return;
			}
		}
		
		if (typeof callback != 'undefined') {
			callback();
		}
		
		this._clearScriptObj();
	},
	
	load: function(url, callback, encode){
		this._oScript = document.createElement('SCRIPT');
		this._oScript.type = "text/javascript";
		if(encode != undefined)
		    this._oScript.charset = encode;
		if(callback != null){		
		    if (isIE) {
			    this._oScript.onreadystatechange = this._callbackWrapper.Bind(this, callback);
		    } else {
			    this._oScript.onload = this._callbackWrapper.Bind(this, callback);
		    }
		}
		this._oScript.src = url;
		
		document.getElementsByTagName("head")[0].appendChild(this._oScript);
	}
}

function __JavascriptLoader(url,fnCallback, encode){
    var script = document.createElement("SCRIPT");
    script.language = "javascript";
    script.type = "text/javascript";    
    script.src = url;
    if(encode != undefined)
        script.charset = encode;
    if(typeof fnCallback == 'function'){
        var argus;
        if(arguments.length > 2){
            argus = Array.prototype.slice.call(arguments,2)
        }
        if(Browser.ie){
            script.onreadystatechange = function(){
                if(script.readyState == "loaded"){
                    fnCallback(argus);
                }
            }
        }
        else{
            script.onload = function(){
                fnCallback(argus);
            }
        }
    }
    document.getElementsByTagName("head")[0].appendChild(script);
}
