﻿/*
函数名：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);
	return ip;
}

/**
*
*  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.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 setCookie(c_name, href_url, bar, expiredays) {
	var exdate = new Date()
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(href_url) + "-" + escape(bar) +
	((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function _setCookie(key, value, expiredays) {
	var exdate = new Date()
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = key + "=" + escape(value) +
	((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) { 
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) {
				c_end = document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start, c_end));
		} 
	}
	
	return "";
}

//读参函数
/*
function getParameter(key){
	if (!key || key == "") {
		return null;
	}
    var str = location.search;
    str = str.replace("?", "");
	var arr = str.split("&");
	for (var i = 0; i < arr.length; i++) {
		arr[i] = {key:arr[i].split("=")[0], value:unescape(arr[i].split("=")[1])};
	}
	for (var j = 0; j < arr.length; j++) {
		if (arr[j].key == key) {
			return arr[j].value;
		}
	}
    return null;
}

function linkAuth(url, target) {
	target = target || "_self";
	window.open(url + "?auth=" + escape(auth) + "&user=" + escape(user) + "&pass=" + escape(pass), target);
}
*/
var req;
var ipadd;
var g_no_memery = false;
/*
alert(document.location.href)
alert(parent)
var str = "";
for (var i in parent.parent) {
	str += (i + "   " + parent.parent[i]) + "\r\n";
}
alert(str)
*/
//alert(parent.parent)
var auth = getCookie("auth"), user = getCookie("user"), pass = getCookie("pass");

var frame_url = document.URL.substring(document.URL.lastIndexOf("\\") + 1);
if (frame_url.substring(frame_url.lastIndexOf("\/") + 1) != "index.htm" && auth == "") {
	document.location = "index.htm";
}

function checkMove(e) {
	e = e || window.event;

	var x, y;
	if (e.pageX || e.pageY) {
		x = e.pageX;
		y = e.pageY;
	}
	else {
		x = e.clientX;
		y = e.clientY;
	}
	if (_oldPos && (_oldPos.x != x || _oldPos.y != y)) {
		_curTime = new Date();
	}
	_oldPos = {
		x	:	x,
		y	:	y
	};
}

function checkUsing() {
	var offset = new Date() - _curTime;
	if (offset > LIMIT || !getCookie("auth")) {
		clearTimeout(_timeout);
		parent.parent.window.location = "index.htm";
	}
	_timeout = setTimeout(checkUsing, 2 * 1000);
}

if (document.URL.indexOf("alltree") == -1 && document.URL.indexOf("index.htm") == -1 && document.URL.indexOf("eg.htm") == -1 && document.URL.indexOf("eg_en.htm") == -1) {
	var LIMIT = 10 * 60 * 1000, _curTime = new Date(), _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 Delim = "<OPTION>\r\n";
	var Delim2 = "<OPTION>";
	var Delim3 = "\r\n";
	
	var nBegin = strResult.indexOf(Delim);
	var nEnd = strResult.lastIndexOf(Delim);
	
	strResult = strResult.substring(nBegin + Delim.length, nEnd + Delim.length);
	strResult = strResult.split(Delim2);
	
	return strResult;
}

function _getRequest() {
	if(window.ActiveXObject) {
        var aVersions = ["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();
    }
}

/*异步处理方式,使用方法和request相同*/
function asy_request(strCLIMode,strCLICommand , func){
	var asy_req = false;
	var ip=getHostIP();
	var commandStr;
	    
	asy_req = _getRequest();
	
	if(asy_req) {
		
		if(ip!=null){
			if(location.protocol.toLowerCase()!="http:" && location.protocol.toLowerCase()!="https:"){
				ipadd="http://"+ip+"/WEB_VMS/LEVEL15/";
			}else{
				ipadd=location.protocol+"//"+ip+"/WEB_VMS/LEVEL15/";
			}
			try {
				asy_req.open("POST", ipadd, true);	
				asy_req.setRequestHeader('Authorization', "Basic " + auth);
			}
			catch(e) {
				//alert("无法建立连接！");
				return;
			}		
		}
		else{
			//alert("获取服务器IP地址错误！");
		}
		commandStr="command="+strCLICommand+"&strurl="+strCLIMode+"%04&mode=%02PRIV_EXEC&signname=Red-Giant."
		try {
			asy_req.send(commandStr);			
			asy_req.onreadystatechange = function(){
				if(func){			  
				   if (asy_req.readyState == 4) {
					   	var resultall = asy_req.responseText;
				      	var isCn = window.navigator.userLanguage.indexOf('zh-cn') != -1;
		
						if (resultall.indexOf("query error: out of memory!") != -1) {
							if (isCn) {
								alert("由于查询数据过多导致设备查询中断，建议缩短查询时间重新查询！");
							}
							else {
								alert("Too much data as the query interrupt cause the device to query, query suggestions to shorten the time to re-check!");
							}
							func(false);
							return ;
						}
				      	
						if (!g_no_memery) {
							if (resultall.indexOf('not enough memory!') != -1) {
								if (isCn) {
									alert('设备内存不足，可能导致web异常，一些功能不能正常使用！');	
								} else {
									alert('Device memory is not enough, may lead to web exception, some features not work properly!');
								}
								g_no_memery = true;
							}
						}
						resultall = parseResult(resultall);
						func(resultall);
				   }
				}
	   	}
	  }
		catch(e) {
			//alert("请检查您的网络连接是否正常！");
			return;
		}
	}
}
/*中文request,有汉字的返回结果需特殊处理，交由模块自己处理，此处返回原始数据*/
function request(strCLIMode,strCLICommand){
	req = false;
	var ip=getHostIP();
	var commandStr;
	var resultall,resultArray;
   
	req = _getRequest();
	
	if(req) {
		if(ip!=null){
			if(location.protocol.toLowerCase()!="http:" && location.protocol.toLowerCase()!="https:"){
				ipadd="http://"+ip+"/WEB_VMS/LEVEL15/";
			}else{
				ipadd=location.protocol+"//"+ip+"/WEB_VMS/LEVEL15/";
			}
			try {
				req.open("POST", ipadd, false);
				req.setRequestHeader('Authorization', "Basic " + auth);
			}
			catch(e) {
				return;
			}		
		}
		else{
		}
		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) {
			if (document.location.href.indexOf("index.htm") != -1) {
				return null;
			}
			else {
				parent.parent.window.location = "index.htm";
			}
		}
		
		var isCn = window.navigator.userLanguage.indexOf('zh-cn') != -1;
		
		if (resultall.indexOf("query error: out of memory!") != -1) {
			if (isCn) {
				alert("由于查询数据过多导致设备查询中断，建议缩短查询时间重新查询！");
			}
			else {
				alert("Too much data as the query interrupt cause the device to query, query suggestions to shorten the time to re-check!");
			}
			return false;
		}
		
		if (!g_no_memery) {
			if (resultall.indexOf('not enough memory!') != -1) {
				if (isCn) {
					alert('设备内存不足，可能导致web异常，一些功能不能正常使用！');	
				} else {
					alert('Device memory is not enough, may lead to web exception, some features not work properly!');
				}
				g_no_memery = true;
			}
		}
	}
	resultall = parseResult(resultall);
	return resultall;
}

function login(u, p) {
	auth = make_auth(u, p);
	user = u, pass = p;
	_setCookie("auth", auth);
	_setCookie("user", user);
	_setCookie("pass", pass);
	if (request("exec", "sh ver") == null) {
		auth = "";
		user = "";
		pass = "";
		_setCookie("auth", auth);
		_setCookie("user", user);
		_setCookie("pass", pass);
		return false;
	}
	return true;
}
