define(function(require, exports, module) {
	// initUpgrade(); //登陆后，检测是否有新版本，若有就升级。

	var global = require("./global");
	var imgTimer = null;
	var INTERVAL = 60 * 60 * 1000;    //主动探测云端是否有推送消息的时间
	var latestNoticeTime = null; //界面上显示给用户看的最新消息的推送时间

	function _regNoticeEvent() {
		//未点击,显示为未读样式;点击后显示为已读样式并保存到数据库
		$("#cloudNoticeContent .unread").click(function() {
			var _this = $(this);
	    	var noticeId = $(this).attr('id').split('_')[1];
	    	global.noticeDbIns._updateNotice(noticeId, 1, function(err) {
	    		if (err == null) {
	    			_this.removeClass('unread');
	    		}
	    	});
	    });

		//为内链和外链注册事件
		$(".noticeBody a").unbind('click');
		$(".noticeBody a").click(function() {
			var href = $(this).attr("data-href");
			if (href.indexOf('http') != -1) { //外链
				var gui = window.require('nw.gui');
				gui.Shell.openExternal(href);
			} else { //内链
				if (href.indexOf('|') != -1) {
					$("#cloudNoticeModal").modal('hide');

					var ele = href.split('|')[0];
					var urlId = href.split('|')[1];
					var curElement = ele;
					var nextPageUrl = global.pageIdToUrl[ele][urlId];
    				global.enterPageCallback(curElement, nextPageUrl);
				}
			}
		});
	}

    function init() {
        global.envIns.init(global.devicesIns);

		initDom();
		initEvent();
		initGlobalEvent();

		function initDom() {
			$('#selfServiceRateModal').modal({
				backdrop: 'static',
				show: false
			});

            $("#showVersionModal .modal-body .version").text(set_page_info.localVer); // set_page_info定义在setcommon.js中

            // 读取当前用户
            var userInfo = global.userMgrIns.getUserInfo();
            var userText = userInfo.isOA ? userInfo.name : userInfo.userName;
            if (!userInfo.isOnline) {
                userText = '匿名用户';
            } else {
                // 会话保持,避免远程协助出现的问题
                //global.userMgrIns.keepOnline(300);
            }
            $('#user').text(userText);
            $('#user').attr("title", userText);

            ////////////////////////////TODO/////////////////////////////
            // // 权限管理
            // if (!global.userMgrIns.hasPermission('upgradeNormal')) {
            //     $('#oneUpgradeMenu').hide();
            // }
            ////////////////////////////TODO/////////////////////////////

            // 远程协助选项管理 (离线模式下，也不显示远程协助）
            // tunnelNew
            // tunnelConnect
            if (!global.userMgrIns.hasPermission('tunnelNew') || !userInfo.isOnline) {
                $('#requestAssistance').hide();
            }

            if (!global.userMgrIns.hasPermission('tunnelConnect') || !userInfo.isOnline) {
                $('#acceptAssistance').hide();
            }

            if ((!global.userMgrIns.hasPermission('tunnelNew') && !global.userMgrIns.hasPermission('tunnelConnect')) || !userInfo.isOnline) {
                $('#remoteAssistance').hide();
            }

            /* 云端推送消息 */
            var client_h = document.documentElement.clientHeight;
			var head_h = $(".main_menu").height();
			var body_h = client_h - head_h;
			$('#cloudNoticeContent').height(body_h - 55);

			// 是否显示工具升级按钮
			if (global.haveNerVersion) {
				$("#toolUpgrade").show();
			} else {
				$("#toolUpgrade").hide();
			}
		}
		function initEvent() {
			// 默认加载设备管理页面
//			$(".main_content").load("./deviceManage/html/deviceManage.html");

			// var curElement = ".main_content", nextPageUrl = "./onlineConfig/html/onlineConfig.html";
            var curElement = ".main_content", nextPageUrl = "./oneUpgrade/html/oneUpgradeMenu.html";
			global.enterPageCallback(curElement, nextPageUrl);

			// 注册菜单切换事件
		    $(".func_menu").on("click", function() {
		    	if (global.isLoadOnUpgrading == false) {
		    		$(".func_menu").removeClass("strong_func_menu");
					$(this).addClass("strong_func_menu");
		    	}
			});
			$("#deviceManageMenu").click(function() {
//				$(".main_content").load("./deviceManage/html/deviceManage.html");
				global.curClickPageId = ".main_content|#deviceManageMenu";
				var curElement = ".main_content", nextPageUrl = "./deviceManage/html/deviceManage.html";
				global.enterPageCallback(curElement, nextPageUrl);
			});
			$("#faultDiagMenu").click(function() {
//				$(".main_content").load("./faultDiagMenu/html/faultDiagMenu.html");
				global.curClickPageId = ".main_content|#faultDiagMenu";
				var curElement = ".main_content", nextPageUrl = "./faultDiagMenu/html/faultDiagMenu.html";
				global.enterPageCallback(curElement, nextPageUrl);
			});
			$("#logDiagMenu").click(function() {
//				$(".main_content").load("./logDiag/html/logDiag.html");
				global.curClickPageId = ".main_content|#logDiagMenu";
				var curElement = ".main_content", nextPageUrl = "./logDiag/html/logDiag.html";
				global.enterPageCallback(curElement, nextPageUrl);
			});
			$("#oneUpgradeMenu").click(function() {
//				$(".main_content").load("./oneUpgrade/html/selectDevice.html");
				global.curClickPageId = ".main_content|#oneUpgradeMenu";
				var curElement = ".main_content", nextPageUrl = "./oneUpgrade/html/oneUpgradeMenu.html";
				global.enterPageCallback(curElement, nextPageUrl);
			});
			$("#softCenterMenu").click(function() {
//				$(".main_content").load("./softCenter/html/softCenter.html");
				global.curClickPageId = ".main_content|#softCenterMenu";
				var curElement = ".main_content", nextPageUrl = "./softCenter/html/softCenter.html";
				global.enterPageCallback(curElement, nextPageUrl);
            });
            $("#hzMenu").click(function () {
                global.curClickPageId = ".main_content|#hzMenu";
                var curElement = ".main_content", nextPageUrl = "./batchStart/html/batchStart.html";
                global.enterPageCallback(curElement, nextPageUrl);
            });

            $("#cjMenu").click(function () {
                global.curClickPageId = ".main_content|#cjMenu";
                var curElement = ".main_content", nextPageUrl = "./cj/html/cj.html";
                global.enterPageCallback(curElement, nextPageUrl);
            });
			//小区管理
			$("#communityManage").click(function(){
				global.curClickPageId = ".main_content|#communityManage";
				var curElement = ".main_content", nextPageUrl = "./communityManage/html/communityManage.html";
				global.enterPageCallback(curElement, nextPageUrl);
			});
			//业主管理
			$("#ownerManage").click(function(event) {
				global.curClickPageId = ".main_content|#ownerManage";
				var curElement = ".main_content", nextPageUrl = "./ownerManage/html/ownerManage.html";
				global.enterPageCallback(curElement, nextPageUrl);
			});
            //上线配置
            $("#onlineConfig").click(function(event) {
                global.curClickPageId = ".main_content|#onlineConfig";
                var curElement = ".main_content", nextPageUrl = "./onlineConfig/html/onlineConfig.html";
                global.enterPageCallback(curElement, nextPageUrl);
            });

			//快速上线
			$("#quickGoneLive").click(function(event) {
				global.curClickPageId = ".main_content|#quickGoneLive";
				var curElement = ".main_content", nextPageUrl = "./quickGoneLive/html/quickGoneLive.html";
				global.enterPageCallback(curElement, nextPageUrl);
			});
			//远程协助
			$("#remoteAssistance").click(function() {
				$("#ulAssistance").toggle();
				return false;
			/*	global.curClickPageId = ".main_content|#softCenterMenu";
				var curElement = ".main_content", nextPageUrl = "./softCenter/html/softCenter.html";
				global.enterPageCallback(curElement, nextPageUrl);
				*/
			});

			//请求协助
			$("#requestAssistance").click(function() {
				global.curClickPageId = ".main_content|#requestAssistance";
				var curElement = ".main_content", nextPageUrl = "./remoteAssistance/html/requestAssistance.html";
				global.enterPageCallback(curElement, nextPageUrl);
			});

			//接受协助
			$("#acceptAssistance").click(function() {
				global.curClickPageId = ".main_content|#acceptAssistance";
				var curElement = ".main_content", nextPageUrl = "./remoteAssistance/html/acceptAssistance.html";
				global.enterPageCallback(curElement, nextPageUrl);
			});

//			$("#robot").click(function() {
//				var gui = window.require('nw.gui');
//				gui.Shell.openExternal("http://webchat.ruijie.com.cn/live800/chatClient/chatbox.jsp?companyID=8933&configID=17&enterurl=robot&live800_ud_invite=robot");
//			});

            $('#robot').click(function () {
                alert(undefined, 'TFTP端口已被占用,请关闭任何第三方的TFTP服务器，否则无法正常使用!');
            });
            var count = 0;
            setInterval(function () {
                if (count >= 1) {
                    if (global.envIns.tftpSrv.enable() == false) {
                        $('#robot').show();
                        
                    } else {
                        $('#robot').hide();
                    }
                    
                }
                count++;

            }, 5000);

			// 账户功能示例
			$(".userAccount").click(function() {
		    	if ($(".operate_menu").is(':visible') == false) {
		    		$(".toogle_menu").hide();
		    		$(".operate_menu").show();
		    	} else {
		    		$(".operate_menu").hide();
		    	}

		    	return false; //阻止事件冒泡
		    });
//		    $(".operate_subMenu").click(function() {
//		    	$(".operate_menu").hide();
//		    });
		    $("body").click(function() {
		    	$(".operate_menu").hide();
		    	$(".upgrade_menu").hide();
				$("#ulAssistance").hide();
		    });

		    // 工具升级功能
		    $("#toolUpgrade").click(function() {
		    	// if ($(".upgrade_menu").is(':visible') == false) {
		    	// 	$(".toogle_menu").hide();
		    	// 	$(".upgrade_menu").show();
		    	// } else {
		    	// 	$(".upgrade_menu").hide();
		    	// }

                $(".toogle_menu").hide();
                $("#newVersionModal").modal('show');

		    	return false; //阻止事件冒泡
		    });
			// 点击logo
            $("#openMacc").click(function () {
                var gui = window.require('nw.gui');
                gui.Shell.openExternal("http://cloud.ruijie.com.cn");
            })
		    /* 以下是通知栏功能 */
            // 先注释掉
		    //_regNoticeEvent();

		    //$("#cloudNotice").click(function() {
		    //	if (imgTimer != null) {
		    //		clearInterval(imgTimer);
		    //		imgTimer = null;
		    //		$("#cloudNoticeImg").show();
		    //	}
		    //});

		    //setInterval(function() {
		    //	global.noticeDbIns._getCloudNotice(function(err, rows) {
		    //		console.log("云端推荐的消息: ", rows);

		    //		if (err != null) {
		    //			console.error("获取云端推送消息失败,失败原因: ", err);
		    //			return;
		    //		}

		    //		//如果云端没有返回更新的消息,不做处理
		    //		if (latestNoticeTime != null) {
		    //			var lastTime = global.moment(latestNoticeTime);
			 		//    var thisTime = global.moment(rows[0].notice_time);
			 		//    var diffTime = thisTime.diff(lastTime);

						//if (parseInt(diffTime) <= 0) {
						//	return;
						//}
		    //		}
		    //		latestNoticeTime = rows[0].notice_time;

		    //		if (imgTimer != null) {
			   // 		clearInterval(imgTimer);
			   // 		imgTimer = null;
			   // 	}

		    //		imgTimer = setInterval(function() {
				  //  	$("#cloudNoticeImg").toggle();
				  //  }, 500);

		    //		//显示云端推送的消息
		    //		$("#cloudNoticeContent").html('');
		    //		for (var i = 0; i < rows.length; i++) {
		    //			var contentStr = rows[i].notice_content;
		    //			var contentJson = JSON.parse(contentStr);

		    //			var $div = '';
		    //			if (rows[i].isclick == 1) {
		    //				$div += '<div class="noticeContent" id="notice_' + rows[i].notice_id + '">';
		    //			} else {
		    //				$div += '<div class="noticeContent unread" id="notice_' + rows[i].notice_id + '">';
		    //			}

		    //			$div += '<div class="noticeHead clearfix">' +
						//			'<div class="noticeTitle">' + contentJson.title + '</div>' +
						//			'<div class="noticeTime">' + rows[i].notice_time + '</div>' +
						//		'</div>' +
						//		'<div class="noticeBody">' + contentJson.content + '</div>' +
						//		'</div>';

		    //			$("#cloudNoticeContent").append($div);
		    //		}

		    //		_regNoticeEvent();
		    //	});
		    //}, INTERVAL);
		}
		function initGlobalEvent() {
			global.exitPageCallback.exitFun = function () {
				return true;
			}
		}
	}
	exports.init = init;
});
