﻿/*!
 * xcall.js For jQuery v1.0.0
 * http://www.luuho.com/xcall
 * Copyright 2011, Mixtheory
 * 
 * Email: Chenjian1984620@163.com,371490254@qq.com
 * Date: 2011-06-01
 */
 Array.prototype.Del=function(n){
  if(isNaN(n)){
    var j=-1;
    for(var i=0;i<this.length;i++){
        if(n==this[i]){
            j=i;
            break;
        }
    } 
    if(j!=-1){
        return this.Del(j);
    }else{
        return this;
    }
  }else{
    if(n<0)
        return this;
    else        
        return this.slice(0,n).concat(this.slice(n+1,this.length));
  }
};

Array.prototype.Distinct=function(){
    var a=[],b=[];
    for(var prop in this){
        var d = this[prop];
        if (d===a[prop]) continue;
        if (b[d]!=1){
            a.push(d);
            b[d]=1;
       }
    }
    return a;
}

;(function($){
    $.pluginPath="/js/";
    $.xcall={};
    $.xcall.version="x";
    $.xcall.rootpath="/js/";
    $.xcall.LoadedFiles=[];
    $.xcall.LoadingFiles=[];
    $.xcall.LoadedCallback={};
    $.xcall.ReadyFn=[];
    $.xcall.CallBackWithTime=function(_time,_callback){
        this.time=_time;
        this.callback=_callback;
        var _this=this;
        this.back=function(){
            _this.time-=1;
            if(_this.time==0){
                _this.callback();
            }
        }
    }
    $.xcall.xitemquere=function(list){
        var _this=this;
        this.childquere=[];
        this.childfinshed=0;
        this.files=[];
        this.callback=function(){
            
        };
        this.checkcallback=function(){
        	if(this.childfinshed==this.childquere.length){    
        		setTimeout(function(){
                		if(_this.files.length>0){
			            	new $.xcall.loadingitem(_this.files.reverse(),_this.callback).start();            
			            }else{
			            	_this.callback();            	
			            }  
        		},0);
            }
        }
        this.start=function(){
            if(_this.childquere.length>0){
                for(var i=0;i<_this.childquere.length;i++){
                    _this.childquere[i].start();
                }
            }else{
            	_this.checkcallback();            	
            }
        }

        for(var i=0;i<list.length;i++){
            if(list[i] instanceof Array){
                var q=new $.xcall.xitemquere(list[i]);
                q.callback=function(){
                	_this.childfinshed+=1;
                	_this.checkcallback();
                }
                this.childquere.push(q);
            }else{
                this.files.push(list[i]);
            }
        }
    }
    $.xcall.xitem=function(){
        var _this=this;
        this.loadedgroupcount=0;
        this.itemgroups=[];
        this.fn=null;
        if(arguments.length>1&&typeof arguments[arguments.length-1]=="string"){
            this.fn=arguments[arguments.length-1];
        };
        for(var i=0;i<arguments.length;i++){
            if(i==0||i!=arguments.length-1||arguments[i] instanceof Array||arguments[i].indexOf("item:")!=-1){
            	if(typeof arguments[i] =="string"&&arguments[i].indexOf("item:")==-1)
            		this.itemgroups.push(arguments[i]);
            }
        }
        for(var i=0;i<arguments.length;i++){
            if(i==0||i!=arguments.length-1||arguments[i] instanceof Array||arguments[i].indexOf("item:")!=-1){
            	if(arguments[i] instanceof Array||arguments[i].indexOf("item:")!=-1)
            		this.itemgroups.push(arguments[i]);
            }
        }
        this.clone=function(){
            var cloneitem=new $.xcall.xitem();
            cloneitem.itemgroups=_this.itemgroups;
            cloneitem.fn=_this.fn;
            return cloneitem;
        }
        this.load=function(_callback){  
            var q=new $.xcall.xitemquere(_this.getfiles());
            q.callback=_callback;
            q.start();
        };
        this.getfileby=function(item){
            var result=null;
            if(item instanceof Array){
                result=[];
                for(var i=0;i<item.length;i++){
                    result.push(_this.getfileby(item[i]));
                }
            }else{
                if(item.indexOf("item:")!=-1){
                    var xitem=$.xcall.Items[item.substring(item.indexOf("item:")+5)].clone();
                    if(xitem){
                        result=xitem.getfiles();
                    }
                }else{
                    return item;
                }
            }
            return result;
        }
        this.getfiles=function(){
            var filecoll=[];
            for(var i=0;i<_this.itemgroups.length;i++){
                var tmp=_this.getfileby(_this.itemgroups[i]);
                filecoll.push(tmp);
            }
            return filecoll.reverse();
        };
        return this;
    };
    $.xcall.Items={
        xcallbase:          new $.xcall.xitem("xcall.base.js"),
        prototype:          new $.xcall.xitem("prototype/_xlist.js"),
        ui:                 new $.xcall.xitem("ui/_xlist.js"),
        util:               new $.xcall.xitem("util/_xlist.js"),
        plugin:             new $.xcall.xitem("plugin/_xlist.js"),
        easyui:             new $.xcall.xitem("easyui/_xlist.js"),
        //all:                new $.xcall.xitem("item:plugin",["item:util",["item:ui",["item:prototype",["item:xcallbase"]]]])
        all:                new $.xcall.xitem("item:plugin","item:easyui","item:util","item:ui","item:prototype","item:xcallbase")
    };
    
    $.xcall.loadingitem=function(_files,_callback){
        var _this=this;
        this.files=[];
        this.loadedfiles=[];
        this.callback=null;
        this.callbackruned=false;
         if(_files){
            if(typeof _files=="string"){
                this.files.push(_files);
            }else if(_files instanceof Array){
                this.files=_files;
            }
        };
        this.files=this.files.Distinct();
        if(_callback){
            this.callback=_callback;
        };
        this.start=function(){
            for(var i=0;i<_this.files.length;i++)
                $.xcall.Xload.load(_this.files[i],_this.checkcallback);
        };
        this.checkcallback=function(_path){
            if($.inArray(_path,_this.loadedfiles)==-1){
                _this.loadedfiles.push(_path);
            }
            if(_this.files.length==_this.loadedfiles.length&&!_this.callbackruned){
               _this.callbackruned=true;
               if(_this.callback)_this.callback();
            }
        }
        return this;
    };
   
    $.xcall.Register=function(){
        if(arguments.length==1){
            if(typeof arguments[0]=="object"){
                for(var pro in arguments[0]){
                    $.xcall.Items[pro]=arguments[0][pro];
                }
            }
        }else if(arguments.length==2){
            if(arguments[1] instanceof $.xcall.xitem){
                $.xcall.Items[arguments[0]]=arguments[1];
            }else{
                $.xcall.Items[arguments[0]]=new $.xcall.xitem(arguments[1]);
            }
        }else if(arguments.length==3){
            $.xcall.Items[arguments[0]]=new $.xcall.xitem(arguments[1],arguments[2]);
        }
    };
    
    $.xcall.Using=function(_item,_callback){
        if(typeof _item=="string"){
            $.xcall.Items[_item].clone().load(_callback);
        }else if(_item instanceof Array){
            var files=[];
            var callbak=new $.xcall.CallBackWithTime(_item.length,function(){
                _callback();
            }).back;
            for(var i=0;i<_item.length;i++){          
                $.xcall.Items[_item[i]].clone().load(callbak);
            } ;
        }        
    };    
    $.xcall.Xload={
        load:function(_path,_callback){
            if($.inArray(_path, $.xcall.LoadedFiles)!=-1){
                if(_callback)_callback(_path);
            }else if($.inArray(_path, $.xcall.LoadingFiles)!=-1){
            	if($.xcall.LoadedCallback[_path]){
            		$.xcall.LoadedCallback[_path].push(_callback)
            	}else{
         			$.xcall.LoadedCallback[_path]=[_callback];            		
            	}
            }
            else{
            	$.xcall.LoadingFiles.push(_path);		
            	$.xcall.LoadedCallback[_path]=[_callback];            		
                var headerTag=document.getElementsByTagName('head')[0];
                var elmttype=$.xcall.Xload.getelmttype(_path);
                var realpath=$.xcall.rootpath+_path;
                if(/\:\/\//.test(_path)||/^\/.+/.test(_path)){
                    realpath=_path;
                }else if(/^\.\.\//.test(_path)){
                    var rootpath=$.xcall.rootpath;
                    var tpath=_path;
                    while(/^\.\.\//.test(tpath)){
                        rootpath =rootpath.replace(/[^\/]+\/$/, '');
                        tpath =tpath.replace(/^\.\.\//, '');
                    };
                    realpath=rootpath+tpath;
                }
                var elmt=$.xcall.Xload.createElement(realpath,elmttype);
                if(elmt){
                    headerTag.appendChild(elmt);
			        if($.browser.msie){
				        elmt.onreadystatechange=function(){
					        if(this.readyState==='loaded'||this.readyState==='complete'){
					        	elmt.onreadystatechange=function(){};
					            $.xcall.Xload.finishLoad(_path);
					        }
				        }
			        }if(elmttype=='link'){
				        $.xcall.Xload.finishLoad(_path);
				    }else{
					    elmt.onload=function(){
					        $.xcall.Xload.finishLoad(_path);
					    }
				    }			        
                }else{
                	$.xcall.Xload.finishLoad(_path);
                }
            }
        },
        finishLoad:function(path){
        	$.xcall.LoadedFiles.push(path);		
            if($.xcall.LoadedCallback[path]){
	            for(var i=0;i<$.xcall.LoadedCallback[path].length;i++){                        
	                $.xcall.LoadedCallback[path][i](path);
	            }
            };
            //alert($.xcall.LoadingFiles);
            var tmp=$.xcall.LoadingFiles.Del(path);
            $.xcall.LoadingFiles=tmp;		
            delete $.xcall.LoadedCallback[path];
        },
    	getelmttype:function(data){
		   data=data.replace(/^\s|\s$/g,"");
		   var jspaths=[
		        /.+\.js/i
		   ];
		   var csspaths=[
		        /.+\.css/i
		   ];
		   var result="script";
		   for(var i=0;i<jspaths.length;i++){
		        if(jspaths[i].test(data)){
		            result= 'script';
		            break;
		        }
		   }
		   for(var i=0;i<csspaths.length;i++){
		        if(csspaths[i].test(data)){
		            result='link';
		            break;
		        }
		   }
		   return result;
		},
		tagexist:function(path,filetype,attrCheck){
		    return $(filetype+"["+attrCheck+"='"+path+"']").size()>0;
	    },
        createElement:function(path,filetype){            
			switch(filetype){				
				case'link':
					if(!$.xcall.Xload.tagexist(path,filetype,'href')){		
					    return  $("<"+filetype+">")
					            .attr('type','text/css')
					    		.attr('rel','stylesheet')
					    		.attr('href',path+(path.indexOf("?")!=-1?"&":"?")+"v="+$.xcall.version)
					    	    .get(0)
					}else{
						return false
					}break;
				case'script':
					if(!$.xcall.Xload.tagexist(path,filetype,'src')){
					    return  $("<"+filetype+">")
					            .attr('language','javascript')
					    		.attr('type','text/javascript')
					    		.attr('src',path+(path.indexOf("?")!=-1?"&":"?")+"v="+$.xcall.version)
					    	    .get(0)
					}else{
						return false
					}break;
				default:
				    return  $("<"+filetype+">")
					            .attr('language','javascript')
					    		.attr('type','text/javascript')
					    		.attr('src',path+(path.indexOf("?")!=-1?"&":"?")+"v="+$.xcall.version)
					    	    .get(0)
					break;
			}
		}
    };
    $.xcall.Ready=function(fn){$.xcall.ReadyFn.push(fn);};
    $.xcall.OnLoadSuccess=function(){$(document).ready(function(){for(var i=0;i<$.xcall.ReadyFn.length;i++){$.xcall.ReadyFn[i]();}})};   
    $.Ready=$.xcall.Ready; 
    $.Register=$.xcall.Register;
    $.Using=$.xcall.Using;
    $.LoadFile=function(_files,_callback){        
        var files=[];
        if(_files){
            if(typeof _files=="string"){
                files.push(_files);
            }else if(_files instanceof Array){
                files=_files;
            }
        };                   
        new $.xcall.loadingitem(files,_callback).start();  
    };    
    $.fn.xcall=function(){

            var fns=$(this).attr("xcall");
            if(fns){
                fns=fns.split(",");
                var _thisx=this;
                $.xcall.Using(fns,function(){
                    for(var n=0;n<fns.length;n++){
                        if($.xcall.Items[fns[n]])
                        {
                            var fn=fns[n];
                            var fnattr=$(_thisx).attr(fn)||$(_thisx).attr("xcall_"+fn);
                            if(fnattr){
                                if(fnattr.indexOf("{")==0&&fnattr.indexOf("}")==fnattr.length-1){
                                    var xx="var args=["+fnattr+"];"  
                                                            
                                    eval(xx);
                                }else{
                                    var args=fnattr.split(",");
                                }				   
                                try{          
                                    $(_thisx)[$.xcall.Items[fn].fn].apply(_thisx,args);		
                                }catch(e){
                                    alert(fn);
                                    alert($.xcall.Items[fn].fn);
                                }	                      
                            }else{
                                $(_thisx)[$.xcall.Items[fn].fn]();
				            }    			                   
                        }
                    }
                });
            }

    };   
})(jQuery);
;(function($) {  
	var xs=$("head script[src*='xcall.js']");
	var loaditems=[];
	xs.each(function() {
	        if($(this).attr("version")){
	            $.xcall.version=$(this).attr("version");
	        }
	        var load=$(this).attr("load");
	        if(load&&load!=""){
	            loaditems=loaditems.concat(load.split(','));
	        }
	        var loadcomplate=$(this).attr("loadcomplate");
	        if(loadcomplate){
	            $.xcall.Ready(function(){
                    eval(loadcomplate);
                });
	        }
		});
    if(loaditems.length==0){
        $.xcall.Using(["all"],function(){    
            $(document).ready(function(){    
                $.xcall.OnLoadSuccess();
            })
        });
    }else{
        $.xcall.Using(["all"],function(){   
            $(document).ready(function(){        
           $.xcall.Using(loaditems,$.xcall.OnLoadSuccess);
           })
        });
    }
  })(jQuery);
;(function($){
    $.xcall.Ready(function(){
        	$("[xcall]").each(function(){
        		$(this).xcall();
        	})
    })
})(jQuery);
