﻿//Author : kingthy
//Date	 : 2008/05/30
//*************************************************************

String.prototype.repeated = function(count){
	var v = '';
	for(var i=0; i<count; i++){
		v += this;
	}
	return v;
};
String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g,'');
};
String.prototype.padleft = function(){
	var l,c;
	if(arguments.length == 1){
		l = arguments[0];
		c = '0';
	}else if(arguments.length == 2){
		c = arguments[0];
		l = arguments[1];
	}else{
		return this;
	}
	var v = this;
	for(var i=this.length; i < l; i++){
		v = c + v;
	}
	return v;
}
String.prototype.format = function(){
	var p1 = 0, p2 = 0;
	var s = '';
	var args = arguments;
	while(p1 < this.length){
		p2 = this.indexOf('{',p1);
		if(p2 != -1){
			s += this.substring(p1, p2).replace(/}}/g,'}');
			p1 = p2 + 1;
			if(p2 < (this.length - 1)){
				if(this.charAt(p1) == '{'){
					//escape {{
					s += '{';
					p1++;
				}else{
					p2 = this.indexOf('}', p1);
					if(p2 == -1 || p2 == p1){
						throw 'String.format error in position ' + p1;
					}else{
						var n = this.substring(p1, p2);
						if(isNaN(n))throw 'String.format error in position ' + p1;
						n = parseInt(n);
						if(n < args.length){
							s += args[n] + '';
						}
						p1 = p2 + 1;
					}
				}
			}else{
				throw 'String.format error in position ' + p2;
			}
		}else{
			break;
		}
	}
	if(p1 < this.length)s += this.substring(p1).replace(/}}/g,'}');
	return s;
}
Array.prototype.foreach = function(f){
	if(typeof(f) != 'function')return;
	for(var index=0; index<this.length; index ++){
		f(this[index],index);
	}
};
Array.prototype.exist = function(f){
	for(var index=0; index<this.length; index ++){
		if(f(this[index],index))return true;
	}
	return false;
}
Array.prototype.clone = function(){
	var o = [];
	this.foreach(function(item){o.push(item);});
	return o;
};

//*************************************************************
//jslib

if(typeof(jslib) == 'undefined'){
    jslib = {};

    jslib.eval = function(){
	    for(var i=0; i<arguments.length;i++){
		    switch(typeof(arguments[i])){
			    case "string":
				    eval(arguments[i]);
				    break;
			    case "function":
				    arguments[i]();
				    break;
		    }
	    }
    };

    jslib.namespace = function(namespace){
	    var spaces = namespace.split('.');
	    var ns = "";
	    spaces.foreach(function(s){
		    if(ns.length != 0){
			    ns += ".";
		    }
		    ns += s;
		    jslib.eval("if(typeof({0})=='undefined'){0} = {{}};".format(ns));
	    });
    }

    jslib._jsscripts = [];
    jslib.importjsfile = function(){
        if(arguments.length < 1)return;

        var scripts = jslib.$tag("SCRIPT");
        for(var i=0; i<scripts.length; i++){
		    if(scripts[i].src.toLowerCase().lastIndexOf(arguments[0].toLowerCase()) != -1)return;
        }
        for(var i=0; i<jslib._jsscripts.length; i++){
              if(jslib._jsscripts[i].src.toLowerCase().lastIndexOf(arguments[0].toLowerCase()) != -1)return;
        }    
        var code = document.createElement("SCRIPT");
        code.language = arguments.length > 1 ? arguments[1] : "javascript";
        code.type = "text/" + (arguments.length > 1 ? arguments[1] : "javascript");
        code.src = arguments[0];
        jslib.$tag("HEAD")[0].appendChild(code);
        jslib._jsscripts.push(code);
    }

    jslib.$ = function(){
	    var o,id;
        switch(arguments.length){
            case 2:
			    o = arguments[0];
			    id = arguments[1];
                break;
            default:
			    o = document;
			    id = arguments[0];
			    break;
        }
	    if(typeof(id) == 'string')return o.getElementById(id);
	    return id;
    }
    jslib.$$ = function(){
	    var sector, id;
        switch(arguments.length){
            case 2:
				sector = arguments[0];
				id = arguments[1];
			    break;
            default:
				sector = document;
				id = arguments[0];
			    break;
        }
		var o;
		if(sector.all || sector.getElementsByTagName){
			var items = sector.all ? sector.all : sector.getElementsByTagName("*");
			o = [];
			for(var i=0; i<items.length; i++){
				var item = items[i];
				var name = item.name || item.getAttribute('name');
				if(name){
					if(name == id)o.push(item);
				}
			}
		}else{
			o = sector.getElementsByName(id);
			o.foreach = Array.prototype.foreach;
		}	    
		o.show = function(){for(var i=0; i<this.length; i++){this[i].style.display='';}};
		o.hide = function(){for(var i=0; i<this.length; i++){this[i].style.display='none';}};
		o.html = function(html){for(var i=0; i<this.length; i++){this[i].innerHTML = html;}};
		o.text = function(text){for(var i=0; i<this.length; i++){document.all ? this[i].innerText = text : this[i].textContent = text;}};
	    return o;
    }
    jslib.$tag = function(){
	    var o;
        switch(arguments.length){
            case 2:
                o = jslib.$(arguments[0]).getElementsByTagName(arguments[1]);
			    break;
            default:
                o = document.getElementsByTagName(arguments[0]);
			    break;
        }
	    o.foreach = Array.prototype.foreach;
		o.show = function(){for(var i=0; i<this.length; i++){this[i].style.display='';}};
		o.hide = function(){for(var i=0; i<this.length; i++){this[i].style.display='none';}};
		o.html = function(html){for(var i=0; i<this.length; i++){this[i].innerHTML = html;}};
		o.text = function(text){for(var i=0; i<this.length; i++){document.all ? this[i].innerText = text : this[i].textContent = text;}};
	    return o;
    }

    jslib.namespace("jslib.dom");
    jslib.dom.swapnode =function(id1,id2){
	    var node1 = jslib.$(id1);
	    var node2 = jslib.$(id2);
	    if(document.all){	//IE
		    node1.swapNode(node2);
	    }else{
		    var parent = node1.parentNode;
		    var t1 = node1.nextSibling;
		    var t2 = node2.nextSibling;
		    if(t1){
			    parent.insertBefore(node2,t1);
		    }
		    else{
			    parent.appendChild(node2);
		    }
		    if(t2){
			    parent.insertBefore(node1,t2);
		    }
		    else{
			    parent.appendChild(node1);
		    }
	    }
    }
    jslib.dom.removenode = function(id){
	    var node = jslib.$(id);
	    if(document.all){	//IE
		    node.removeNode(true);
	    }else{
		    if(node.parentNode)node.parentNode.removeChild(node);
	    }
	    return node;
    }
    jslib.dom.getchilds = function(id){
	    var childs;
	    var o = jslib.$(id);
	    if(document.all){	//IE
		    childs = o.childNodes;
	    }else{
		    childs = [];
		    for(var i=0; i<o.childNodes.length; i++){
			    if(o.childNodes[i].tagName){
				    childs.push(o.childNodes[i]);
			    }
		    }
	    }
	    return childs;
    }
    jslib.dom.clearchilds = function(id){
	    var o = jslib.$(id);
	    for(var i=o.childNodes.length-1; i>=0; i--){
		    o.removeChild(o.childNodes[i]);
	    }
    }
    jslib.dom.position = function(id){
	    var o = jslib.$(id);
	    var p = {left:0,top:0,width:0,height:0};
	    if(o != null){
		    if(o.style.width){
			    p.width = o.style.width;
		    }else{
			    p.width = o.offsetWidth;
		    }
		    if(o.style.height){
			    p.height = o.style.height;
		    }else{
			    p.height = o.offsetHeight;
		    }
		    p.left = o.offsetLeft;
		    p.top = o.offsetTop;
		    while(o = o.offsetParent){
			    p.left += o.offsetLeft;
			    p.top += o.offsetTop;
		    }
	    }
	    return p;
    }

    jslib.namespace("jslib.event");
    jslib.event.__loadedfunctionlist = [];
    jslib.event.__readyfunctionlist = [];
    jslib.event.__readyfunctiontimer = null;
    jslib.event.__runloadedfunction = function(){
	    if(jslib.event.__loadedfunctionlist.length > 0){
		    jslib.event.__loadedfunctionlist.foreach(function(func){
			    jslib.eval(func);
		    });
		    jslib.event.__loadedfunctionlist.splice(0,jslib.event.__loadedfunctionlist.length);
	    }
    }
    jslib.event.__runreadyfunction = function(){
	    if(jslib.event.__readyfunctionlist.length == 0){
		    clearInterval(jslib.event.__readyfunctiontimer);
		    return;
	    }else{
		    var funs = jslib.event.__readyfunctionlist.clone();
		    jslib.event.__readyfunctionlist = [];
		    funs.foreach(function(item){
			    var o = jslib.$(item.o);
		        if(o != null && (o.readyState == 'loaded' || o.readyState == 'complete')){
				    jslib.eval(item.f);
			    }else{
				    jslib.event.__readyfunctionlist.push(item);
			    }
		    });
		    funs = null;
	    }
    }
    jslib.event.onready = function(){
	    var id, o, f;
        switch(arguments.length){
            case 2:
                o = jslib.$(arguments[0]);
			    id = arguments[0];
			    f = arguments[1];
			    break;
            default:
                id = o = document;
			    f = arguments[0];
			    break;
        }
        if(document.all){ //IE
	        if(o != null && (o.readyState == 'loaded' || o.readyState == 'complete')){
		        jslib.eval(f);
	        }else{
			    jslib.event.__readyfunctionlist.push({o : id,f : f});
			    if(!jslib.event.__readyfunctiontimer)jslib.event.__readyfunctiontimer = setInterval(jslib.event.__runreadyfunction,10);
		    }
	    }else{  //Orther
	        jslib.event.onload(f);
	    }
    }
    jslib.event.onload = function(func){
	    if(window.onload != jslib.event.__runloadedfunction){
		    if(window.onload)jslib.event.__loadedfunctionlist.push(window.onload);
		    window.onload = jslib.event.__runloadedfunction;
	    }
	    jslib.event.__loadedfunctionlist.push(func);
    }
	jslib.event.attach = function(id,e,f){
		var o;
		o = jslib.$(id);

		if(!o || !e || !f)return;
		var body = jslib.$tag("body");
		if(body.length > 0 && o == body[0]){
			if((/load$/gi).test(e))o = window;  //load or unload
		}
		if(typeof(f) != 'function'){
			var code = f;
			f = function(){
				eval(code);
			};
		}
		if(document.all && o.attachEvent){
			if(!(/^on/gi).test(e))e = "on" + e;
			o.attachEvent(e,f);
		}else{
			o.addEventListener(e.replace(/^on/i,""),f,false);
		}
	}

	jslib.namespace("jslib.json");
	jslib.json.get = function(url, complete, error){
		var d = {
			   url : url, 
			   method : 'GET',
			   type : 'json'
		};
		jslib.ajax.load(d, complete, error);		
	}
	jslib.json.post = function(url, content, complete, error){
		var d = {
			   url : url, 
			   method : 'POST',
			   contentType : 'application/x-www-form-urlencoded',
			   data : content,
			   type : 'json'
		};
		jslib.ajax.load(d, complete, error);		
	}
	jslib.namespace("jslib.ajax");
	jslib.ajax.post = function(url, content, complete, error){
		var d = {
			   url : url, 
			   method : 'POST',
			   contentType : 'application/x-www-form-urlencoded',
			   data : content
		};
		jslib.ajax.load(d, complete, error);
	}
    jslib.ajax.load = function(d,complete,error){
	    var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
	    if(typeof(d) == 'string')d = {url : d};
	    if(d.method == undefined)d.method = "GET";
	    if(d.async == undefined)d.async = true;
	    if(d.username == undefined)d.username = null;
	    if(d.password == undefined)d.password = null;
		if(d.type == undefined)d.type = '';
	    request.open(d.method, d.url, d.async, d.username, d.password);
	    if(d.data){
			if(d.contentType == undefined)d.contentType = 'application/x-www-form-urlencoded';
			request.setRequestHeader("Content-Type", d.contentType);
			request.setRequestHeader("Content-Length", d.data.length);
		}
	    request.setRequestHeader("X-Agent", "kingthy's jslib version 1.0.0");
	    request.setRequestHeader("X-Ajax", "true");
	    request.onreadystatechange = function(){
		    if(request.readyState == 4){
			    if(request.status == 200){
				    if(typeof(complete) == 'function'){
						switch(d.type.toLowerCase()){
							case 'json':
								complete(window.eval('(' + request.responseText + ')'));
								break;
							case 'xml':
								complete(request.responseXML);
								break;
							case 'text':
								complete(request.responseText);
								break;
							default:
								complete(request);
								break;
						}						
					}
			    }else{
				    if(typeof(error) == 'function')error(request.statusText);
			    }
		    }
	    };
	    try{
		    request.send(d.data);
	    }catch(e){
		    if(typeof(error) == 'function')error(e);
	    }
    }
}