﻿/*
函数名：getHostIP()
创建者：linzc
创建时间：2007,3,26
输入：
输出：输出服务器主机IP
描  述：
*/
function getHostIP(){
	var ip=location.href;
	var first,end;
	var result;
	first=ip.indexOf("\/\/"); 
	ip=ip.substring(first+2);
	end=ip.indexOf("\/");
	ip=ip.substring(0,end);
	//ip = "192.168.45.220" or "192.168.45.220:port";
	return ip;
}

var auth = top.$.cookie('auth'), user = top.$.cookie('user');

/*
	当没有认证成功时，只能访问index.htm页面，访问其他页面后跳转到index.htm
*/
var frame_url = document.URL.substring(document.URL.lastIndexOf("\\") + 1);

if (frame_url.substring(frame_url.lastIndexOf("\/") + 1) != "index.htm" && (auth == "" || auth==null)) {
	top.document.location = "index.htm";
}


function checkMove(e) {
	e = e || window.event;

	var x, y;
	if (e.clientX || e.clientY) {
		x = e.clientX;
		y = e.clientY;
	}
	else {
		x = e.screenX;
		y = e.screenY;
	}
	if (top._oldPos && (top._oldPos.x != x || top._oldPos.y != y)) {
		top.offset=0;
	}
	top._oldPos = {
		x	:	x,
		y	:	y
	};
}
/*function checkUsing() {
	var getC = top.$.cookie || $ && $.cookie;
	if (top.offset > LIMIT || !getC("auth")) {
		clearTimeout(_timeout);
		if(window.dialogArguments) {
			window.opener = null;
			window.close();
		} else {
			top.window.location = "index.htm";
			$.cookie("auth", "");
			$.cookie("user", "");
		}
	}
	top.offset++;
	_timeout = setTimeout(checkUsing, 1 * 1000);
}*/
function isFrame(url, pages) {
	var temp = "", temp1 = "";
	for (var i = 0, l = pages.length; i < l; i++) {
		temp = url.slice(url.lastIndexOf('/') + 1);
		temp1 = temp.slice(temp.lastIndexOf('\\') + 1);
		if(temp1 == pages[i]) {
			return i;
		}	
	}
	return -1;
}


/*
	对不是__pages中的页面进行监测，如果10分钟鼠标不动，就跳转会index.htm页面
*/
var __url = document.URL, __pages = ['alltree.htm', 'index.htm', 'main.htm', 'cache.htm'];
if (isFrame(__url, __pages) == -1) {
	//var LIMIT = 10*60, _oldPos, _timeout;	
	/*checkUsing();*/
	document.onmousemove = checkMove;
}

/*
函数名：parseResult()
创建者：linzc
创建时间：2007,3,26
输入：
strCLIMode:命令运行模式（exec/config）
strCLICommand:配置命令	
输出：服务器响应的原始数据（未解晰）
描  述：
*/
function parseResult(strResult){
	// 获得利用<OPTION>\r\n作分隔的串,去掉数据的最前一个<OPTION>\r\n
	var startch = "<OPTION>\r\n";
	var delim = "<OPTION>";
	var nBegin = strResult.indexOf(startch);
	var nEnd = strResult.lastIndexOf(startch);
	if (/WEB_VMS\/LEVEL15/i.exec(strResult)==null){
		strResult=['无网络连接，请检查网络。'];
		return strResult;	
	}
	strResult = strResult.substring(nBegin + startch.length, nEnd + startch.length);
	
	if (strResult.indexOf(delim)==-1){
		strResult=[];
	}else{
		strResult = strResult.split(delim);	
	}

	return strResult;
}

function _getRequest() {
	if(window.ActiveXObject) {
        var aVersions = ["Msxml2.XMLHttp.6.0", "Msxml2.XMLHttp.5.0", "Msxml2.XMLHttp.4.0", "Msxml2.XMLHttp.3.0", "Msxml2.XMLHttp", "Msxml2.XMLHTTP.2.6", "Microsoft.XMLHTTP.1.0", "Microsoft.XMLHttp"];
        for (var i = 0; i < aVersions.length; i++){
            try{
                return new ActiveXObject(aVersions[i]);
            }catch (e) {
            }
        }
    }
    else {
        return new XMLHttpRequest();
    }
}

function _getProtocol() {
	var p = location.protocol.toLowerCase();
	
	if (p != "http:" && p != "https:") {
		return "http:";	
	}
	return p;
}

function _doCheck(result) {
	var o = window.navigator, lan = o.userLangeage || o.language || o.systemLanguage || o.browserLanguage;
	var isCn = lan == 'zh-cn' || lan == 'zh-CN';
	if (typeof SysLan != 'undefined') {
		isCn = SysLan == 'zh';	
	}
	
	var Note = isCn ? {
		1	:	"由于查询数据过多导致设备查询中断，建议缩短查询时间重新查询！",
		2	:	"设备内存不足，可能导致web异常，一些功能不能正常使用！"
	} : {
		1	:	"Too much data as the query interrupt cause the device to query, query suggestions to shorten the time to re-check!",
		2	:	"Device memory is not enough, may lead to web exception, some features not work properly!"
	}

	if (result.indexOf("query error: out of memory!") != -1) {
		return 0;
	}
	
	if (result.indexOf('not enough memory!') != -1) {
		return -1;
	}
	//some other check
	return 1;
}

/*异步处理方式,使用方法和request相同*/
function asy_request(strCLIMode, strCLICommand , func){
	var ip = getHostIP();
	if (!ip) return false;
	
	var commandStr;
	var asy_req = _getRequest();
	
	if(asy_req) {
		var ipadd = _getProtocol() + "//" + ip + "/WEB_VMS/LEVEL15/";

		try {
			asy_req.open("POST", ipadd, true);	

			asy_req.setRequestHeader('Authorization', "Basic " + auth);
		}
		catch(e) {
			return false;
		}
	
		commandStr = "command=" + strCLICommand + "&strurl=" + strCLIMode + "%04&mode=%02PRIV_EXEC&signname=Red-Giant.";
		try {
			asy_req.send(commandStr);
					
			asy_req.onreadystatechange = function(){
				if(func && asy_req.readyState == 4){		  
					var resultall = asy_req.responseText;
					var c = _doCheck(resultall);
					if (c == -1) return false;
					if (c == 0) {
						func(false);
						return false;
					} 
					func(parseResult(resultall));
					asy_req = null;
					return true;
				}
				
			}
		}
		catch(e) {
			//alert("请检查您的网络连接是否正常！");
			return false;
		}
	}
	return false;
}

function asy_request2(strCLIMode, strCLICommand , func,string){
	var ip = getHostIP();
	if (!ip) return false;
	
	var commandStr;
	var asy_req = _getRequest();
	
	if(asy_req) {
		var ipadd = _getProtocol() + "//" + ip + "/WEB_VMS/LEVEL15/";

		try {
			asy_req.open("POST", ipadd, true);
			asy_req.setRequestHeader('Authorization', "Basic " + auth);
		}
		catch(e) {
			return false;
		}
	
		commandStr = "command=" + strCLICommand + "&strurl=" + strCLIMode + "%04&mode=%02PRIV_EXEC&signname=Red-Giant.";
		try {
			asy_req.send(commandStr);
					
			asy_req.onreadystatechange = function(){
				if(func && asy_req.readyState == 4){		  
					var resultall = asy_req.responseText;
					var c = _doCheck(resultall);
					if (c == -1) return false;
					if (c == 0) {
						func(false);
						return false;
					} 
					func(parseResult(resultall),string);
					asy_req = null;
					return true;
				}
				
			}
		}
		catch(e) {
			return false;
		}
	}
	return false;
}

/*中文request,有汉字的返回结果需特殊处理，交由模块自己处理，此处返回原始数据*/
function request(strCLIMode, strCLICommand){
	var ip = getHostIP();
	if (!ip) return [];
	var commandStr;
	var req = _getRequest();
	
	if(req) {
		var ipadd = _getProtocol() + "//" + ip + "/WEB_VMS/LEVEL15/";
		try {
			req.open("POST", ipadd, false);
			req.setRequestHeader('Authorization', "Basic " + auth);
		}
		catch(e) {
			return [];
		}
		/*
		  原因：有些配置表单需要从特定的配置模式获取配置参数，并初始化配置表单，但若在命令跟保存命令，
		  	   则会导致无法从特定的配置模式获取配置参数，使配置表单参数不全。
		  解决方法：判断配置命令中是否有问号“?”，若有则不加保存配置命令，若无则加。
		  修改时间：2015.3.31
		  修改人：yongwenbing
		  同步项目：10.4(3B38)
		*/
		if (!(/[\?]+/g.test(strCLICommand))){
			strCLICommand+=(/config/i.test(strCLIMode))?('\r\nend\r\nwrite\r\n'):('');
		}

		commandStr = "command=" + strCLICommand + "&strurl=" + strCLIMode + "%04&mode=%02PRIV_EXEC&signname=Red-Giant.";
		
		try {
			req.send(commandStr);
		}catch(e) {
			return ['无网络连接，请检查网络。'];
		}

		resultall = req.responseText;
		if (resultall.indexOf("Authorization Required") != -1) {
			document.location.href.indexOf("index.htm") == -1 && (top.window.location = "index.htm");	
			return [];
		}
		
		/*var c = _doCheck(resultall);

		if (c != 1) {
			return [];
		}*/

		return parseResult(resultall);
	}
	return ['浏览器不支持对象ActiveXObject或XMLHttpRequest。'];
}

//修改了鉴权机制为sessionId，重启后，该session将失效
function reload_is_ok(){
	var ip = getHostIP();
	if (!ip) return -1;
	var commandStr;
	var req = _getRequest();
	
	if(req) {
		var ipadd = _getProtocol() + "//" + ip + "/WEB_VMS/LEVEL15/";
		try {
			req.open("POST", ipadd, false);
		}
		catch(e) {
			return -1;
		}
		
		var newCliCmd="show version\r\n";
		commandStr = "command=" + newCliCmd + "&strurl=exec%04&mode=%02PRIV_EXEC&signname=Red-Giant."

		try {
			req.send(commandStr);
		}
		catch(e) {
			return -1;
		}

		resultall = req.responseText;
	
		if (resultall.indexOf("Authorization Required") != -1) {
			return 100;
		}

		return 100;
	}

	return -1;
}
/*
 * 释放内存
 * date : 2011-12-13 auth:lyz
 */
function clearMouseMove(){
	window.document.onmousemove = null;
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 		
		input = (input==null)?'':input;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function make_auth(user, password) {
	var tok = user + ':' + password;
	var hash = Base64.encode(tok);
	return hash;
}

function login_x(u, p) {
	var retValue = '';
	var commandStr;
	var req = _getRequest();
	var ip = getHostIP();

	if (!ip) return "nolink";

	if(req) {
		var ipadd = _getProtocol() + "//" + ip + "/login.do";
		try {
			req.open("POST", ipadd, false);
		}
		catch(e) {
			return "nolink";
		}
	
		commandStr = "command=sh clock\r\n&strurl=exec%04&mode=%02PRIV_EXEC&signname=Red-Giant."

		try {
			req.send(commandStr);
		}
		catch(e) {
			return "nolink";
		}

		resultall = req.responseText;
		var regexp = /RUIJIEID=([a-z\d]+)/i;
		var ret=regexp.exec(resultall);
		if(ret != null) {
			var sessionId = ret[1]; //get session id
			$.cookie("auth", sessionId);
			return "success";
		} else {
			$.cookie("auth", '');
			$.cookie("user", '');
			return "fail";
		}	
	}

	return "nolink";
}

function login(u, p) {
	var res = '';
	window.auth = make_auth(u, p);
	window.user = u;
	$.cookie("auth", auth);
	$.cookie("user", user);
	
	res = request("exec", "sh clock");
	res = $.trim(res.toString());

	if (/\d+:\d+:\d+/i.test(res)) {
		return "success";	
	}else{
		return login_x();	
	}
}

function logout() {
	//向httpd后台发送消息，结束sessionid的生命周期
	$.ajax({
		type : "GET",
		url	 : 'logout.do' ,
		data : '',	
		async :false,	
		success : function(data,state){
			$.cookie("auth", "");
			$.cookie("user", "");
			$.cookie("currentURL", "");
			top.window.location = "index.htm";								
		},
		error	: function(e){
			$.cookie("auth", "");
			$.cookie("user", "");
			$.cookie("currentURL", "");
			window.location = "index.htm";
		}
	})
}


function showOpenDialog(url, config, argument) {
	var start = argument.indexOf("dialogWidth");
	var end = argument.indexOf("px");
	var width = argument.slice(start + 12, end);
	var returnValue=null;
	var height='';
	var nURL='';

	start = argument.indexOf("dialogHeight");
	end = argument.lastIndexOf("px");
	height = argument.slice(start + 13, end);
	
	nURL=url;
	returnValue=window.open(nURL,'','height='+height+'px,width='+width+'px,top=150px,left=200px,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no');
	return returnValue;
}

function prompt_error_msg(msg,act){
	if ((msg!=null)&&(msg.length==0)){
		switch(act){
			case 'new':
				alert(__LANGUAGE('newConfRespondTxt','成功创建一项条目。'));
				break;
			case 'delete':
				alert(__LANGUAGE('delConfRespondTxt','成功删除一项条目。'));
				break;
			case 'edit':
				alert(__LANGUAGE('modConfRespondTxt','成功修改一项条目。'));
				break;
			case 'config':
				alert(__LANGUAGE('appConfRespondTxt','配置保存成功。'));
				break;
			case 'clearall':
				alert(__LANGUAGE('clearAllConfRespondTxt','成功清除所有条目。'));
				break;
			case 'clear':
				alert(__LANGUAGE('clearOneConfRespondTxt','成功清除一项条目。'));
				break;
			default:
				break;
		}

		return true;
	}else if ((msg!=null)&&(msg.length!=0)){
		switch(act){
			case 'new':
				alert('创建失败：'+msg[0]+'');
				break;
			case 'delete':
				alert('删除失败：'+msg[0]+'');
				break;
			case 'edit':
				alert('修改失败：'+msg[0]+'');
				break;
			case 'config':
				alert('配置失败：'+msg[0]+'');
				break;
			default:
				break;
		}

		return false;
	}
	
	return false;
}