
;(function($){
    var MAINPAGE = function(o) {
        this.proName         = top.window.location.pathname.split("/")[1];
        this.proHost         = "http://"+window.location.host+"/"; 
        this.proUrl          = this.proHost+this.proName; 
        this.menuIdcache     = [];
        this.topUl           = $("#topmenucontainer");
        this.centerContainer = $("#commframe");
        this.currentTopMenu  = null; 
        this.fContent        = $('<div title="" style="height:100%;width:100%;"><iframe frameborder="0" src="" allowtransparency="false" style="height:100%; width: 100%; display: inline;"></iframe></div>');
        this.cachepageId     = {1000 : 'home',2000 : 'yw-video',3000 : 'yw-machine',4000 : 'yw-software',5000 : 'yw-count',6000 : 'yw-taskmanage',7000 : 'zygl',8000 : 'set',9000 : 'sssp',10000 : 'yw-software'};
//        this.pageInitOnLoad = [{pageId:2000,containerId:"videopage",pageUrl:"/im/webrtc/webrtc.jsp"}];
        this.pageInitOnLoad = [];
        this.newWinId     	 = {};
        this.newTopWinId     = {2000:'dp'};  //一级菜单弹出页面代码
    };
    
    MAINPAGE.prototype.loadSystemLogoTitle =function(){
//        $.startSync(); 
//        LoginAction.getSystemConfig(function(config){
//            $(".navbar-title:eq(0)").html(config.systemTitle || "");
//        });
//        $.endSync();
        return this;
    };
    
    MAINPAGE.prototype.initTabEvents = function(f){
        this.centerContainer.tabs({
              onSelect: function(title,index){
            	  if (!String.prototype.trim) {
            		  String.prototype.trim = function () {
            			  return this.replace(/^\s*|\s*$/g, "");
            		  }
            	  }
                  $("#westPanel .left-menu-three").each(function(){
                      if(($(this).text().trim()===title.trim())){
                          $("#westPanel").find("a").removeClass("menu-selected");
                          $(this).find("a").addClass("menu-selected"); 
                          if($(this).parent().parent().css("display")=="none"){
                                $(this).parent().parent().prev().click();
                          }
                      }
                  });
              },
              onContextMenu:function(e, title,index){
                    e.preventDefault();
                    if(index>0){
                        $('#mainmenu').fadeIn(300).menu('show', {
                            left: e.pageX,
                            top: e.pageY
                        }).data("tabTitle", index);
                    }
                }
        });
        return this;
    }
    
    //添加div模块
    MAINPAGE.prototype.addCacheDiv = function(f){
        var  ts= this, arr = [];
        for(var k in this.cachepageId){
            var  html = "<div id="+ this.cachepageId[k] +" style='display:none;border:none;width:100%;height:100%'></div>"
            $("#centerPanel").append(html);
        }
        
    	for(var k = 0 ;  k <  ts.pageInitOnLoad.length ; k++){
    		var o = ts.pageInitOnLoad[k];
	    	var page = $("#"+o.containerId ,"#centerPanel");
          	if(page){
          		var rpath = ts.proUrl+"/"+(o.pageUrl)+("?_=")+((new Date()).getTime());
          		page.css({"width":"1px","height":"1px","display":"block"}).html('<iframe frameborder="0" src='+ rpath+' allowtransparency="false" style="height:100%; width: 100%; display: inline;"></iframe>');
          	}
        }
    }
    
    MAINPAGE.prototype.initSysMenu =function(){
        var that = this ;
        (this.menuIdcache  && this.menuIdcache.length)||
        $.ajax({
		    type:'post',
		    url : 'menuRoleAction!getUserFirstMenuNode.do'
		}).done(function(rs){
			if(rs){
				$.each(rs,function(i,j){
					that.menuIdcache[i] = j.cdbh;
				});
                that.addCacheDiv();
                that.loadFirstMenu(rs);
            }
		}).fail(function(a,b,c){
			console.log(a)
			console.log(b)
			console.log(c)
			
		});
 
    };
    
    MAINPAGE.prototype.loadFirstMenu = function(f){
        var that = this ,a = [] ;
        $.ajax({
			type:'post',
	        async:false ,
	        url : 'menuRoleAction!getFirstMenuNode.do',
	        success : function(rs){
	        	//console.log("一级菜单集合：",rs);
	            if(rs && rs.length){
	                that.renderFirstMenu(rs);
	            }
	        } 
	  	});
    };

    MAINPAGE.prototype.renderFirstMenu = function(menu){
        if(!menu || !menu.length) return ;
        //一级菜单增加弹出页面 _that变量
		var that = _that = this,topmenu = [] ,firsmMenu,checkMenu = [],activeIndex=0,flag=true;
        for(var j = 0,leng  =  menu.length ; j < leng; j++){
        	if(that.checkMenuIn(menu[j].menuId ) >= 0 ){
        		checkMenu.push(menu[j]);
        	}
        	}
        for(var i = 0,leng  =  checkMenu.length ;i < leng; i++){
				topmenu[topmenu.length] = $("<a/>").data("item",checkMenu[i])
	    	  		.data("item",checkMenu[i])
	    	  		.attr({
			    		  id:checkMenu[i].menuId,
			    		  tag:(checkMenu[i].url ? checkMenu[i].url : null )
			    	 })
			    	.html('<span class="menuIcon '+ (checkMenu[i].iconCls ? checkMenu[i].iconCls : 'cs') +'"></span><span class="menuText">'+ checkMenu[i].menuName +'</span>')
			    	.wrap("<li class='liIcon'></li>").parent()[0];
				if(checkMenu[0].menuId=='2000'&&flag){
					if(checkMenu.length<=1){
						   window.location.href="about:blank";
					}
					firsmMenu = checkMenu[1];  
					window.open(_that.proHost+checkMenu[0].url);
					activeIndex=1;
					flag=false;
				}else if(flag){
					activeIndex=0;
					firsmMenu = checkMenu[0];  
				}
        };
        this.topUl.empty().append(topmenu).delegate("li>a","click",function(row){
        	/*  一级菜单弹出页面代码--start--  */
			var alarmId = _that.newTopWinId[$(this).attr('id')];
			if(alarmId){
				//$.proPath()
				//var abspath= (_that.proUrl+$(this).attr('tag'));
				var abspath= (_that.proHost+$(this).attr('tag'));
	            window.open(abspath);
	            return;
	        }
			/*  一级菜单弹出页面代码--end--  */
            $(this).parent().siblings().children('a').removeClass("current");
            $(this).addClass("current");
            if(that.currentTopMenu != $(this).attr('id')){
                that.clearAllTab($(this).attr('id')).loadSecondMenu($(this).data("item"));
            }
            
            that.currentTopMenu = $(this).attr('id');
            
          }).find("a").eq(activeIndex).addClass("current");
        firsmMenu && that.loadSecondMenu(firsmMenu);
    
    };
    
    MAINPAGE.prototype.checkMenuIn = function(menuId){
        return $.inArray(menuId,this.menuIdcache);
    };
    
    MAINPAGE.prototype.loadSecondMenu = function(menu){
        var that = this , west = $("#westMenu") ,pp  = $("#westMenu").accordion('panels'),len = pp.length, b = [];
        if(len){
            for(var i = len-1 ;i >= 0 ; i --){
                west.accordion('remove', pp[i].panel('options').title);
            }
        }
        if($.trim(menu.url)){
            that.collOrExpandWestPanel(0).clearAllTab().goSpecialUrl(menu);
            return ;
        }else{
            $.ajax({
    			type:'post',
    	        async:false ,
    	        data:{menuId:menu.menuId},
    	        url : 'menuRoleAction!getSecondMenuNodeByFirstId.do',
    	        success : function(rs){
                    that.collOrExpandWestPanel(1);
                    $("#westPanel").panel('setTitle',menu.menuName||'系统导航');
                    setTimeout(function(){
                        var k = 0;
                        $.each(rs,function(i,j){
                        	if(that.checkMenuIn(j.menuId) >= 0){
	                            $("#westMenu").accordion('add',{
	                                    title:j.menuName,
	                                    animate:false,
	                                    iconCls:j.iconCls,
	                                    selected:i==0?true:false,
	                                    content: that.loadThirdMenu(rs,j,k++),
	                            });
                          }
                        }) 
                    },0);
    	        } 
    	  	});
        }
    };
    
    MAINPAGE.prototype.loadThirdMenu = function(data ,current,currIndex){ 
        var that = this , html = [] , pnode =current.menuId , tempdata = current.list,hasload = false;
        html.push("<ul>");
        for(var k = 0 ; k < tempdata.length ; k++){
            var tempnode = tempdata[k];
            if(that.checkMenuIn(tempnode.menuId) >= 0){
                //var abspath= (this.proUrl+tempnode.url);
                var abspath= (that.proHost + tempnode.url);
                if(currIndex == 0 && !hasload){
                    that.menuClick(tempnode.menuId,(abspath),tempnode.menuName);
                    hasload = true;
                }
                html.push("<li class='left-menu-three'>");
                html.push("<a href=\"javascript:window.MainPage.menuClick(\'"+tempnode.menuId+"'\ ,\'"+(abspath)+"'\ ,\'"+tempnode.menuName+"'\);\" id="+tempnode.menuId+" url="+tempnode.url+" title="+tempnode.menuName +">");
                html.push(tempnode.menuName+" </a>" );
                html.push("</li> "); 
            }
        }
        html.push('</ul>');
        return html.join("");
    };
    
    MAINPAGE.prototype.initCurrUserInfo = function(f){
    	var that = this;
		$.ajax({
			type:'post',
		    async:false ,
		    url : 'loginAction!getUserInfo.do',
		    success : function(user){
	            if(!user){ 
	                top.window.location = that.proUrl+"/index.jsp";
	            } else {
	                $.extend(true,MainPage,user);
	                $("#user").text(user.yhmc||"");
	                that.regComp(user);
	            }
		    } 
		});
    };
    
    MAINPAGE.prototype.collOrExpandWestPanel = function(f){
        $('body').layout(f ? 'show' :'hidden' ,'west'); 
        return this; 
    };
    
    MAINPAGE.prototype.goSpecialUrl = function(menu){
        //<div id='recordpage' style="border:1px solid red;">recordpage</div>
        //this.centerContainer.hide().prev().show().html(menu.url || "链接地址出错");
        var abspath= (this.proHost+menu.url);
        var pageId = this.cachepageId[menu.menuId];
        if(pageId){
            var currpage =  $("#"+pageId).siblings().hide(1).end();
            var f = $("#"+pageId).children("iframe");
            if(f.length == 0){
                var html = '<iframe frameborder="0" src="'+(abspath)+'" allowtransparency="false" style="height:100%; width: 100%; display: inline;"></iframe>';
                $("#"+pageId).html(html);
            }
            currpage.css({"width":"100%","height":"100%","display":"block"});
        }  
    };
    
    MAINPAGE.prototype.menuClick = function(id,url,name){
        if(arguments.length >= 3){
            var that = this , alarmId = this.newWinId[id];
            this.centerContainer.siblings().hide(1).end().show(1);
            setTimeout(function(){
                if(alarmId){
                    window.open(url);
                    return;
                }
                if (!that.centerContainer.tabs('exists', name)) {
                    that.centerContainer.tabs('add',{
                        title       :   name || "",
                        id          :   $.uniqueId(),
                        index       :   that.centerContainer.tabs('tabs').length,
                        content     :   that.decorateContent(id,url,name),
                        onSelect:function(title){ 
                            //alert(title+' is selected'); 
                        }
                    });
                }else{
                    that.centerContainer.tabs('select',name);
                }
            },200);
        }
    };
    
    MAINPAGE.prototype.decorateContent = function(id,url,name){
        var content = this.fContent.clone();
        content.attr({title:name,id:id+"_container"}).find("iframe").prop("src",url);
        return content ;
    }
    
    MAINPAGE.prototype.clearAllTab = function(id){
        var tabs = this.centerContainer.tabs("tabs"),length = tabs.length;
       if(length){
    	   for(var i = length-1; i >=0; i--){
               var onetab = tabs[i];
               var title = onetab.panel('options').tab.text();
               this.centerContainer.tabs("close", title);
               //alert(title);
           }
    	   
       }
        return this;
    };
    
    MAINPAGE.prototype.logout = function(url,id){
    	var that = this ;
    	$.ajax({
			type:'post',
		    url : 'loginAction!logOut.do'
		}).always(function(){
			 top.window.location = that.proUrl;
		});
    };
    
    MAINPAGE.prototype.initPacConfig = function(){
//        LoginAction.getPacConfig(function(rs){
//            if(rs!=null){
//                top.MainPage.pacConfig = rs;
//            }
//        });
    };
     
    MAINPAGE.prototype.initPicProxy = function(){
    	var that = this;
        try {
        	$.ajax({
        		type:'post',
       	        async:false ,
       	        url : 'menuConfigAction!select_PicPorxy.do',
       	        success : function(proxyMap){
       	            if(proxyMap){
       	            	top.MainPage.picProxyMap = proxyMap;
       	            }  
       	        } 
       	  	});
        	var hasProxy = false;
        	for(var kk in top.MainPage.picProxyMap){
        		hasProxy = true;
	       	}
        	if(!hasProxy){
        		var proName = top.window.location.pathname.split("/")[1];
    			var sysUrl = "http://"+window.location.host+"/"+proName;	
        		var mm = {};
        		mm.picagent = sysUrl;
        		top.MainPage.picProxyMap = mm;
        	}
        } catch (a) {
            $.log("图片代理加载失败！");
        }
    };
    
    MAINPAGE.prototype.showLocalPicProxy = function(a){
        var d = location.href ,b = d.substring(d.indexOf("//") + 2, d.lastIndexOf(":"));
        top.MainPage.localProIp = b;
        if (a == "1") {
            var c = {};
            c.localProIp = b;
//            ChePicPorxyService.select_ChePicPorxy_check(c,function(m){
//                if(m!= null){
//                    top.MainPage.picProxyMap = m;
//                }
//            });
        }
    };
    
    MAINPAGE.prototype.regComp = function(data){
    	//var comp =["impyw","impc","impmap","impvc"];
    	var comp =["impnhyw"];
    	while(comp.length){
        	$.ajax({
                type:'post',
                url : "http://"+ window.location.host+"/"+comp[0]+'/loginAction!userloginValidation.do',
                data: {
					username :data.yhzh,
					password :data.yhmm,
					encode	 :"true"
                },
                error:function(_){
                	$.log(comp[0]+' reg fail..')
                }
            });
    		comp.shift();
    	}
    };
    MAINPAGE.prototype.loadMapConfig = function(f){
        var that = this ,a = [] ;
        $.ajax({
			type:'post',
	        async:false ,
	        url : 'menuConfigAction!getDitu.do',
	        success : function(rs){
	            if(rs){
	            	top.ditu = rs.ditu;
	                //that.renderFirstMenu(rs);
	            }
	        } 
	  	});
    };
    MAINPAGE.prototype.getConfig = function(f){
        var that = this ,a = [] ;
        $.ajax({
			type:'post',
	        async:false ,
	        url : 'menuConfigAction!getConfig.do',
	        success : function(rs){
	            if(rs && rs.length){
	                //that.renderFirstMenu(rs);
	            }
	        } 
	  	});
    };
    MAINPAGE.prototype.getCustomName = function(){
        $.ajax({
			type:'post',
	        async:false ,
	        url : 'menuConfigAction!getCustomName.do',
	        success : function(rs){
	            if(rs){
	            	$("#customName").html(rs.customName);
	            }
	        } 
	  	});
    };
    $.MAINPAGE = function(o){
        return new MAINPAGE(o||{});
    };
})(jQuery);

