﻿var frame_url = document.URL.substring(document.URL.lastIndexOf("\\") + 1);
if (document.all){
window.attachEvent('onload',FuncName)
}
else{
window.addEventListener('load',FuncName,false);
}

//window.onload
function FuncName() {
    if (frame_url.substring(frame_url.lastIndexOf("\/") + 1) != "index.htm" && frame_url.substring(frame_url.lastIndexOf("\/") + 1) != "set_k.htm" && !top.__cache && !window.dialogArguments) {
        document.location = "index.htm";
    }
}

/*
函数名：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;
}


var auth = top.$.cookie('auth'), user = top.$.cookie('user');

/*
    当没有认证成功时，只能访问index.htm页面，访问其他页面后跳转到index.htm
*/

if (frame_url.substring(frame_url.lastIndexOf("\/") + 1) != "index.htm" && auth == "") {
    document.location = "index.htm";
}

var oop = 0;
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 (_oldPos && (_oldPos.x != x || _oldPos.y != y)) {
        _curTime = new Date();
    }
    _oldPos = {
        x   :   x,
        y   :   y
    };
}

function checkUsing() {
    var offset = new Date() - _curTime;
    var getC = top.$.cookie || $ && $.cookie;
    if (offset > LIMIT || !getC("auth")) {
        clearTimeout(_timeout);
        if(window.dialogArguments) {
            window.opener = null;
            window.close();
        } else {
            top.window.location = "index.htm";
            $.cookie("auth", "");
            $.cookie("user", "");
        }
    }
    _timeout = setTimeout(checkUsing, 2 * 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', 'eg.htm', 'eg_en.htm', 'cache.htm'];
if (isFrame(__url, __pages) == -1) {
    var LIMIT = 30 * 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.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 || result.indexOf("query error: interrupt") != -1) {
        alert(Note[1]);
        return 0;
    }

    if (result.indexOf('not enough memory!') != -1) {
        alert(Note[2]);
        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;
        }
        strCLICommand = encodeURIComponent(strCLICommand);
        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;
}
/*中文request,有汉字的返回结果需特殊处理，交由模块自己处理，此处返回原始数据*/
function request(strCLIMode, strCLICommand){
    var ip = getHostIP();
    if (!ip) return false;
    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 false;
        }
        strCLICommand = encodeURIComponent(strCLICommand);
        commandStr = "command=" + strCLICommand + "&strurl=" + strCLIMode + "%04&mode=%02PRIV_EXEC&signname=Red-Giant."

        try {
            req.send(commandStr);
        }
        catch(e) {
            return false;
        }

        resultall = req.responseText;
        if (resultall.indexOf("Authorization Required") != -1) {
            document.location.href.indexOf("index.htm") != -1 && (top.window.location = "index.htm");
            return null;
        }

        var c = _doCheck(resultall);

        if (c != 1) return false;

        return parseResult(resultall);
    }

    return false;
}

/*
*操作日志
*logstr : 要配置的日志字符串
*unRequest : 是否直接下发命令，true为不下发，返回字符串即可。false为直接下发。
*isSee : 是否是查看，true为查看，false为配置,如果为字符串则代表自定义
*isWirte：是否带上write
*/

function operateUserLog(logStr,unReqest,isSee,isWirte){
    var userName = top.$.cookie('user')||'',openerStr;
    if(typeof isSee == 'string'){
        openerStr = isSee;
    }else{
        openerStr = isSee ? '查看' : '配置';
    }
    var logValue = userName + '(' + openerStr  + ')，' + logStr;
    if(!unReqest){
        asy_request('exec','user-log ' + logValue + (isWirte ? '\r\n write \r\n' : ' ') );
    }else{
        return logValue + (isWirte ? '\r\n write \r\n' : ' ');
    }
}


/*
 * 释放内存
 * 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.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(u, p) {
    window.auth = make_auth(u, p);
    window.user = u;
    var passw = p;
    $.cookie("auth", auth);
    $.cookie("user", user);
    var res = request("exec", "show clock");
    if (res === null) {
        auth = "";
        user = "";
        $.cookie("auth", auth);
        $.cookie("user", user);
        return "fail";
    } else if (res === false) {
        return "nolink";
    }
    $.cookie("HOME_ALERT", '', $.extend({}, {expires: -1}));
    if (user == "admin" && passw == "admin") {
         $.cookie("HOME_ALERT", parseInt(100000 * Math.random()));     
    }
    return "success";
}