﻿//首先，有个公共js文件，用于加载所有js文件（jquery库优先）、核心代码、以及包含htm代码段
//分析语言，更改语言，显示（去掉loading图标）

/**
判断是否顶层，
如果不是用index.htm替代
*/
 //debugger;

/**
初始化系统变量
PreJsModule -- 数组，预加载js文件，不定义默认为["system/jquery.js"];
JsModule -- 数组，后加载js文件，主要为自定义组件、frame core
IncludeFile -- 对象，包含的htm文件，{id1:html1, id2:html2, .......}
包含html文件,注意，包含的html片段可以含有js脚本，但js脚本不能放在开始位置！
*/

if(!window.SystemPath)SystemPath="system/";//路径最后必须有/
//    if(!window.ControlsPath)ControlsPath="controls/";//路径最后必须有/
//    if(!window.PreJsModule)PreJsModule=["system/jquery.js"];
if(!window.JsModule)JsModule=[];
if(!window.IsMultiLanguage)IsMultiLanguage=false;
if(!window.IncludeFile)IncludeFile={};

/**
设置IncludeFile的length属性
*/
//(function()
//{
//    var j=0;
//    for(var i in IncludeFile)
//        j++;
//    IncludeFile.length=j;
//})();

/* 初始化EhaiFW对象 */
if(!window.EhaiFW)EhaiFW={};
EhaiFW.Lang={};
EhaiFW.Config={};

/**
EhaiFW.WebLoad -- 规范各js调用顺序，保证页面的正确、准确加载，加载顺序：init.js->预加载js->其他js文件和html文档
*/
EhaiFW.WebLoad=
{
    LoadJs : function(file,load)//,id
    /*
    加载js文档
    @file js文档位置
    @load 加载后执行
    */
    {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');  
        script.type = 'text/javascript';  
//        if(id)//如果有id，删除id所在标签，这样可以防止document的dom树太大，特别是如果多次点击语言切换时。
//        {
//            var jsTag = document.getElementById(id);
//            if(jsTag) head.removeChild(jsTag);
//            script.id=id;
//        }
        if (load)  
        {
            script.onload = script.onreadystatechange = function() 
            {  
                //debugger;
                if (script.readyState && script.readyState != 'loaded' && script.readyState != 'complete')  
                    return;  
                script.onreadystatechange = script.onload = null;  
//                alert(script.id+":"+script.readyState);
                load();  
            };  
        }
        script.src = file;  
        head.appendChild(script);//与JQuery冲突
    },
    run : function()
    {
        if(!window.jQuery)
        {
            setTimeout("EhaiFW.WebLoad.run();",10);
        }else
        {
            var t=EhaiFW.WebLoad;
            t.LoadModule(JsModule,t.jsLoaded);
            if(t.winLoadedFlag==0)t.winJsLoaded();
        }
    },
    jsLoaded : function()
    /**
    保证所有加载js文档、html文档正确加载完成后，继续执行
    @必须在所有加载js文档后添加：EhaiFW.WebLoad.JsLoaded();
    */
    {
        //debugger;
        //alert("JsLoaded");
        var t=EhaiFW.WebLoad;
        t.loadedNum--;
        if(t.loadedNum<=0)
        {//全部加载完成，所有js文档已加载完成
            //alert("Over!");
            //debugger;
            if(parent && parent.hideLoading)parent.hideLoading();
            jQuery.GetPageParameter([
                    {
                        name : "lang",
                        defVal : EhaiFW.Config["Environment"]["DefaultLang"],
                        cookieName : "lang"
                    },
                    {
                        name : "auth",
                        defVal : EhaiFW.Config["Environment"]["DefaultUser"],
                        cookieName : "auth"
                    }
                    ]);     
            if(EhaiFW)
            {
                //debugger;
                if(EhaiFW.ChangeLang && IsMultiLanguage==true)
                    EhaiFW.ChangeLang(null,['lang_zh','lang_en'],{'text-decoration':'underline'},{'text-decoration':'none'},true);
                else
                {
                    EhaiFW.Msg$(function(){
                        EhaiFW.ReplaceUrl("A","href"); 
                        EhaiFW.ReplaceUrl("IFRAME","src"); 
                    });

                    if(window.WebMain)WebMain();
                    EhaiFW.PostPageLoad.Run();
                    $.Start();
                }
//                if(EhaiFW.WebMain)EhaiFW.WebMain();
            }
        }
    },
    /**
    标志系统托管window.onload是否加载执行，不影响自定义window.onload事件
    @false -- 默认值，window.onload未被执行
    @true -- window.onload已被执行
    */
    winLoadedFlag : -1,//-1：初始状态，0为window.onload已加载，1：为window.onload已加载，但winJsLoaded已执行，
    //2为消息队列在onload加载完后已执行完
    
    WinOnload : function()
    {
        var t=EhaiFW.WebLoad;
        if(window.jQuery)
        {
            t.winJsLoaded();
        }
        t.winLoadedFlag=0;
    },
    /**
    系统托管window.onload事件执行
    在这里 加载 html文档，此时已经可以使用jquery的资源
    */
    winJsLoaded:function()
    {
        //debugger;
//            var t=EhaiFW.WebLoad;
//            if(t.bPreLoaded==false)return;
//            if(t.winLoadedFlag==false)return;
        if(this.winLoadedFlag>=1)return;
        this.winLoadedFlag=1;
        for(var id in IncludeFile)
        {
//            if(id=="length")continue;
            if(typeof(IncludeFile[id])!="string")continue;
            this.loadedNum++;
            eval('$.get(IncludeFile[id],null,function(data){$("#"+"'+id+'").html(data);EhaiFW.WebLoad.jsLoaded();});');
        }
        //debugger;
//        EhaiFW.WebLoad.WinJsLoadedFlag=true;
        this.jsLoaded();
    },
    
    loadedNum : 1,
//        needNum : 1,
    /**
    加载模块
    @jm，数组，需要加载的js文档位置数组
    */
    LoadModule:function(jm,load)
    {
        //window.onload=JsLoaded;//加载window.onload也加载
        for(var i=0; i<jm.length; i++)
        {
//                alert(jm[i]);
            this.loadedNum++;
            this.LoadJs(jm[i],load);//所有js文件也加载
            if(jm[i].indexOf('system/jqframe.js')>=0){
                window.SystemPath=jm[i].replace('jqframe.js','');
            }
        }
    }
};

/*
ObjManaged类，将用户可以的操纵以对象的形式托管，以达到框架统一调用管理的目的。
函数名作为参数使用方法：
1、如果函数A没有参数即A()，EhaiFW.PostPageLoad.Add(A)；
2、如果函数A有参数即A(p1,p2...)，EhaiFW.PostPageLoad.Add(function(){A(p1,p2...)});

方法说明：
1、Add，用户向“托管队列”尾段添加函数，
   参数lf：被托管对象；
2、AddFirst，用户向托管队列前段添加函数，
   参数lf：被托管对象；
3、Run，运行所有用户托管处理程序，用户很少调研它，在框架中调研。
   ObjManaged类生产的对象，在调用Run();后一般要ObjManaged对象=null;以删除该对象。
4、bDelete false：Run后不删除托管中的对象，true：Run后删除托管中对象
*/
//debugger;
EhaiFW.ObjManaged=function(op,bDelete)//bDelete托管运行完是否删除
{
    //debugger;
    this.bDelete=bDelete==false ? false : true;
    this.db=[];
    this.Add=function(lf)
    {
        this.db.unshift(lf);//加入到第一个位置，因为最后读取从后向前
    };
    this.IsEmpty = function()
    {
        return this.db.length>0 ? false : true;
    };
    this.Empty=function()
    {
        this.db=[];
    };
    this.AddFirst=function(lf)
    {
        this.db.push(lf);//加入到最后一个位置，因为最后读取从后向前
    };
    this.Run = function(bDel)
    {
        //debugger;
        var i;
        if(bDel || this.bDelete)
            while(i=this.db.pop())//这样可以删除元素，因为PageLoad在Run后应该自动销毁
                op(i);
        else
        {
            var j=this.db.length;
            for(i=0;i<j;i++)
                op(this.db[j-i-1]);
        }
    }
};


//EhaiFW.Util.g=function(i)
//{
//    i();
//};
//EhaiFW.Util.g1=function (i)
//{
//    var o=null;
//    if(typeof(i[0])=="string")
//        o=document.getElementById(i[0]);
//    else
//        o=i[0];
//    o[i[1]]=i[2];
//};

//var a=EhaiFW;
/*
PostPageLoad对象（页面加载队列），在页面代码各种用户自己静态元素编程中，可能也需要在window.onload中添加代码，
PostPageLoad封装了用户onload事件，保证了window.onload事件正确执行。其中维护了用户的onload
希望执行的各函数，用户可以通过在前、或者在后，来控制加载位置。
使用方法：
1、如果函数A没有参数即A()，EhaiFW.PostPageLoad.Add(A)；
2、如果函数A有参数即A(p1,p2...)，EhaiFW.PostPageLoad.Add(function(){A(p1,p2...)});

方法说明：
1、Add，用户向window.onload事件尾段添加函数，
   参数lf：无参数函数地址即函数名；
2、AddFirst，用户向window.onload事件前段添加函数，
   参数lf：无参数函数地址即函数名；
3、Run，运行所有用户自定义在window.onload的函数代码，用户很少调研它，在框架中调研。
   PageLoad.Run();PageLoad=null;
*/
//EhaiFW.PageLoad=new EhaiFW.ObjManaged(EhaiFW.Util.g,false);
EhaiFW.PostPageLoad=new EhaiFW.ObjManaged(function(i){i();},false);//在页面加载后执行托管代码
EhaiFW.PagePostMessage=new EhaiFW.ObjManaged(function(i){i();},false);//在页面消息处理完后执行代码
EhaiFW.PostMessage=new EhaiFW.ObjManaged(function(i){i();},true);//在消息处理完后执行代码
EhaiFW.$=function(f){EhaiFW.PostPageLoad.Add(f);};//给外部使用
EhaiFW.$f=function(f){EhaiFW.PostPageLoad.AddFirst(f);};//给外部使用
EhaiFW.Msg$=function(f){EhaiFW.PagePostMessage.Add(f);};//给外部使用
EhaiFW.Msg$f=function(f){EhaiFW.PagePostMessage.AddFirst(f);};//给外部使用


//debugger;

//例子
/*
function f1()
{
    alert(2);
}
function f11()
{
    alert("f11");
}
function f2(str)
{
    alert(str);
}
function f3(str)
{
    alert("f3:" + str);
}
EhaiFW.PostPageLoad.Add(f1);
EhaiFW.PostPageLoad.AddFirst(f11);
EhaiFW.PostPageLoad.AddFirst(function(){f2("zh");});
EhaiFW.PostPageLoad.Add(function(){f3("str");});
EhaiFW.PostPageLoad.Run();


*/

//首先加载预加载js文档
//debugger;
//    EhaiFW.WebLoad.LoadModule(PreJsModule,EhaiFW.WebLoad.jsPreLoaded);
//添加系统托管onload事件
//三个事件:PreJsModule加载完毕、JsModule加载完毕、window.onload加载完毕
/* 以下是每一个js文件必备的。*/
//JsLoaded();
//alert("init.js is loaded!"); //这里的alert在ie环境下可能出现出现错误
if (window.addEventListener)
    window.addEventListener("load", EhaiFW.WebLoad.WinOnload, false);
else
    window.attachEvent("onload", EhaiFW.WebLoad.WinOnload);

//如果预加载js文档为空也要保证后面文档被加载
//    if(PreJsModule.length<1)
EhaiFW.WebLoad.run();



//alert(2);
if(!EhaiFW.Config["Language"])EhaiFW.Config["Language"]={
    "zh":"中文",
    "en":"English"
};
EhaiFW.getLangJsFile=function(lang)
{
    return SystemPath+"lang/"+lang+".js"
};
EhaiFW.Config["Environment"]={
    "BaseUrl" : "Default.aspx",
    "NotAuthorUrl" : "/index.html",

    "DefaultLang" : "zh",
    "DefaultUser" : "anonymous",
//    "CurrentLang":null,//有没有必要存在？

    "DefaultWeight" : 10,
    
    "ThreadMax":3, //页面最大线程数目
    "MsgAmount":6,     //每个线程最大可同时处理消息数目，消息可以同时处理
    //"MustTreatMin" : 899,

    "splitChar" : "%16",//消息发送到后台的分隔符
    "splitMsg" : "%17",//消息发送到后台的分隔符
    "getThreshold" : 512, //get方式和post方式的阀值
    
    "DebugChar" : "<~~>" 
};

/*
将没有get和post方法区别，框架通过传输的数据大小自动判断，优先考虑get方式
*/

EhaiFW.analyze= function(loc,src) 
{ 
    var str="",t0=loc.search,t1; 
    if(t0 && t0.charAt(0)=="?")
        str=t0.substr(1);
    try
    { 
        eval('t1='+decodeURIComponent(str)); 
    }catch(e) 
    { 
        t1={}; 
    }
    t1.lang=jQuery.PageParam.lang; 
    t1.auth=jQuery.PageParam.auth;
    return loc.pathname ? ((loc.pathname.charAt(0)=="\/" ? loc.pathname : "\/"+loc.pathname)+ "?" + jQuery.toJSONString(t1,"object")) : src; 
}; 

EhaiFW.ReplaceUrl=function(tagName,attr) 
{ 
//    debugger;
    var links=document.getElementsByTagName(tagName);
    var l=links.length,t;
    var loc=window.location;
    var hosname=loc.protocol+"\/\/"+loc.host+loc.pathname+loc.search;
    for(var i=0;i<l;i++) 
    { 
        if(!links[i].href)continue;
        //debugger;
        if(links[i].href.substr(0,1)=="\/")links[i].href=loc.protocol+"\/\/"+loc.host+links[i].href;
        if(!links[i])continue;
        if(links[i].protocol.substr(0,4).toLowerCase()!="http")continue;
        t=links[i][attr].toString(); 
        t=t.replace(hosname,"");
        if(t.charAt(0)=="#")continue;
        if(!links[i][attr])continue;
        if(links[i].host!=loc.host)continue;
        links[i][attr]=EhaiFW.analyze(links[i],links[i][attr]); 
    } 
    //debugger;
}; 
EhaiFW.ReplaceSkin=function(toLang)
{
    function cl()
    {
        var u=EhaiFW.Lang["Value"];
        var l=u.length;
        for(var i=0;i<l;i++)
        {
            var j=2,v=u[i];
            while(v[j])
            {       // debugger;
                if(document.getElementById(v[j])) document.getElementById(v[j])[EhaiFW.Lang["Attribute"][v[0]]]=v[1];
                j++;
            }
        }
    };
    //debugger;
    jQuery.getScript(EhaiFW.getLangJsFile(toLang),cl);
};


EhaiFW.ChangeLang=function(newLang,arObj,cssM1,cssM2,bWebMain)//$("p").css({ color: "red", background: "blue" });
{
    if(typeof(newLang)=="string")
    {
        if(newLang==jQuery.PageParam.lang)return;
        jQuery.MsgResultDB.Empty(); 
        jQuery.PageParam.lang=newLang;
    }   
    jQuery.Cookie("lang",$.PageParam.lang);

    EhaiFW.ReplaceSkin($.PageParam.lang); 
    if(EhaiFW.WebLoad.winLoadedFlag==2)EhaiFW.WebLoad.winLoadedFlag=1;
    else
    {
        EhaiFW.Msg$(function(){
            EhaiFW.ReplaceUrl("A","href"); 
            EhaiFW.ReplaceUrl("IFRAME","src"); 
        });
    }
    if(window.WebMain && bWebMain==true)WebMain();
    EhaiFW.PostPageLoad.Run();
    $.Start();
    
    if(arObj)
    {
        for(var i=0,j=arObj.length; i<j; i++)
        {
            var t=$("#"+arObj[i]);
            if(t.attr("lang")==$.PageParam.lang)
                t.css(cssM1);
            else
                t.css(cssM2);
        }
    }
};
