/*=====================================================
Wizard Configurations
=====================================================*/
var _Wireless         =   1;  // the camera has wireless function? 1 or 0
var _ModelName        =   "DCS-942L";
var _DevTitle         =   _ModelName+"&nbsp;"+((_Wireless)?" Wireless N":"")+" Network Camera";
var _isUTF8Decoding   =   1;  // is UTF8 decoding? the default value is 1
var _isDebug          =   0;
var _isMydlink        =   1;
var _WizardVersion    =   "v1.01.1622";
var _BuildDate        =   "2010.*";
var _DefaultLanguage  =   "english";
var _IconFilename     =   _ModelName+".ico";

/*=====================================================
DLDP_Driver/DLDP_Control Configurations
=====================================================*/
var _DLDPDriver_Version =   "1,0,7,2"; //DLDPDriver Version
var _DLDPDriver_Classid =   "13361CAF-F1AD-4999-9BF2-15941E5B"+_DLDPDriver_Version.replace(/,/g, ""); //DLDPDriver Class ID
var _DLDPDriver_ProgID  =   "DLDPDriverProj1.DLDPDriver"; //DLDP Driver Program ID

var _DLDP_Version       =   "1,0,8,2"; //DLDP Version
var _DLDP_Classid       =   "0D01426C-EA09-42EC-9F5E-B3798530"+_DLDP_Version.replace(/,/g, ""); //DLDP Class ID
var _DLDP_ProgID        =   "DLDP.DLDP"; //DLDP Program ID


var _DCP_Version       =   "1,0,1,1"; //DCP Version
var _DCP_Classid       =   "12193C65-F0E1-4DD1-AD4E-DB73C691"+_DCP_Version.replace(/,/g, ""); //DCP Class ID
var _DCP_ProgID        =   "DCP.DCPForm"; //DCP Program ID


/*---- "Next Button" control ----*/
var is_enable_next;
function enable_next()
{
	is_enable_next = 1;
	$("#btn_next_arrow").attr("src","../images/arror-right.gif");
	$('#btn_next').attr("class", "btn floatr");
	parseStylesheets();
}
function disable_next()
{
	is_enable_next = 0;
	$("#btn_next_arrow").attr("src","../images/arror-rightd.gif");
	$('#btn_next').attr("class", "btnbd floatr");
	parseStylesheets();
}


function get_html_page_progress(page, total)
{
  var p, html = "", img_base = "../images";
  var sImg = [
    ["sa_on.gif","sa_off.gif"],
    ["sb_on.gif","sb_off.gif"],
    ["sc_on.gif","sc_off.gif"],
    ["sd_on.gif","sd_off.gif"],
    ["se_on.gif","se_off.gif"],
    ["sf_on.gif","sf_off.gif"],
    ["sg_on.gif","sg_off.gif"]
  ];
  for(p=0;p<total;p++)
  {
    html+="<img src='"+img_base+"/"+sImg[p][((p < page)?0:1)]+"'>";
  }
  return html;
}
function DLDP_Test()
{
  try{
    DLDP.str1 = cmd_add_length("START DLDP");
//   	DLDP.str1 = cmd_add_length("CHECK DLDP");
//   	if(DLDP.str2 != "LIVE")
//   	{
//       DLDP.str1 = cmd_add_length("STOP DLDP");
//       if(_isDebug)DLDP.str1 = cmd_add_length("START DEBUG");
//       DLDP.str1 = cmd_add_length("START DLDP");
//     }
    DLDP.str1 = cmd_add_length((_isUTF8Decoding?"START":"STOP")+" UTF8"); // start/stop utf8 decoding ...
    msg.value = "DLDP initialized.";
    return true;
  }catch(e)
  {
    //alert(e.desc);
    msg.value = "DLDP isn't initialized.";
    window.location.href = "../home/notice.html";
    return false;
  }
}

function cmd_add_length(cmd)
{
  return cmd.getBytes()+","+cmd;
}




function mLang(Language)
{
  Language = (Language)?Language:_DefaultLanguage;
  this.xmlsrc = "../language/"+Language+".xml";
  try //Internet Explorer
    {
      this.xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
      this.xmlDoc.async = false;
      this.xmlDoc.load(this.xmlsrc);
    }
  catch(e)
    {
    try //Firefox, Mozilla, Opera, etc.
      {
        //this.xmlDoc=document.implementation.createDocument("","",null);
        //this.xmlDoc.async=false;
        //this.xmlDoc.loadxmlsrc();

        this.xmlhttp = new window.XMLHttpRequest();
        this.xmlhttp.open("GET",this.xmlsrc,false);
        this.xmlhttp.send(null);
        this.xmlDoc = this.xmlhttp.responseXML.documentElement;

      }
    catch(e)
      {
        //alert(e.message);
        //return;
      }
    }
}

mLang.prototype = {
  get_word:function(id)
  {
    var words = this.xmlDoc.getElementsByTagName("word");
    var w;
    var wID = "";  
    for(w=0;w<words.length;w++)
    {
      wID = words[w].attributes.getNamedItem("id").nodeValue;
      if(wID == id)
      {
        // remove "\n" at the head and tail ...
        return words[w].childNodes[0].nodeValue.replace(/^\s*([\S\s]*?)\s*$/, '$1');
      }
    }    
    return null;
  },
  get_word_type:function(id)
  {
    var num = -1;
    var words = this.xmlDoc.getElementsByTagName("word");
    var w;
    var wID = "";
    for(w=0;w<words.length;w++)
    {
      wID = words[w].attributes.getNamedItem("id").nodeValue;
      if(wID == id)
      {
        if(words[w].attributes.getNamedItem("type")!=undefined)
        {
          return words[w].attributes.getNamedItem("type").nodeValue;
        }else
        {
          return "";
        }
      }
    }    
    return null;
  },
  translate:function()
  {
    var ml = this;
    var words = this.xmlDoc.getElementsByTagName("word");
    var wID = "";  
    var m, w;
    var arr_word = [];
    var temp;
    for(w=0;w<words.length;w++)
    {
      wID = words[w].attributes.getNamedItem("id").nodeValue;
//       if(
//         words[w].attributes.getNamedItem("page")==undefined ||
//         words[w].attributes.getNamedItem("page").nodeValue!="lan"
//       )
//       {
//         continue;
//       }else
//       {
        temp = {
          value:"",
          page:"",
          type:""
        };

        if(words[w].childNodes[0]!=undefined)
        {
          temp["value"] = words[w].childNodes[0].nodeValue.replace(/^\s*([\S\s]*?)\s*$/, '$1');
        }
        if(words[w].attributes.getNamedItem("page")!=undefined)
        {
          temp["page"] = words[w].attributes.getNamedItem("page").nodeValue;
        }
        if(words[w].attributes.getNamedItem("type")!=undefined)
        {
          temp["type"] = words[w].attributes.getNamedItem("type").nodeValue;
        }
        arr_word[wID] = temp;
//       }

      if(m = arr_word[wID]["type"].match(/^@(.+)$/))
      {
        $("#"+wID).attr(m[1], arr_word[wID]["value"]);
      }else if(arr_word[wID]["type"] == "text")
      {
        $("#"+wID).text(arr_word[wID]["value"]);
      }else
      {
        $("#"+wID).html(arr_word[wID]["value"]);
      }
    }    

  }
}












function array_eq(a1, a2)
{
  if(typeof(a1)!="object" || typeof(a2)!="object")
  {
    return false;
  }
  if(a1.length != a2.length)
  {
    return false;
  }else
  {
    for(a in a1)
    {
      if(typeof(a1[a]) == "object")
      {
        if(!array_eq(a1[a], a2[a])) return false;
      }else if(a1[a] != a2[a])
      {
        return false;
      }
    }
  }
  
  return true;
}

String.prototype.trim = function()
{
  return this.replace(/^\s*([\S\s]*?)\s*$/, '$1');
}

String.prototype.getBytes = function()
{
    var cArr = this.match(/[^\x00-\xff]/ig);    
    return this.length + (cArr == null ? 0 : cArr.length);    
}  

String.prototype.substr2 = function(start_index, substr_byte_length) {
  for(c=0;c<this.length;c++)
  {
    if(this.substr(start_index, c+1).getBytes() > substr_byte_length)
    {
      if(c > 0)
      {
        return this.substr(start_index, c); 
      }
    }
  }
  return this;
}  

function urldecode(str)
{
  return Cls_Url.decode(str);
}



var Cls_Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // 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 array_dump(arr)
{
  var str = "";
  for(a in arr)
  {
    str+="["+a+"]"+String(arr[a])+"\n";
  }
  return str;
}

// no drop...
$("*").bind('dragstart',function( event ){
  return false;
});


/**
 *	Whatever:hover - V2.02.060206 - hover, active & focus
 *	------------------------------------------------------------
 *	(c) 2005 - Peter Nederlof
 *	Peterned - http://www.xs4all.nl/~peterned/
 *	License  - http://creativecommons.org/licenses/LGPL/2.1/
 *
 *	Whatever:hover is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU Lesser General Public
 *	License as published by the Free Software Foundation; either
 *	version 2.1 of the License, or (at your option) any later version.
 *
 *	Whatever:hover is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *	Lesser General Public License for more details.
 *
 *	Credits and thanks to:
 *	Arnoud Berendsen, Martin Reurings, Robert Hanson
 *
 *	howto: body { behavior:url("csshover.htc"); }
 *	------------------------------------------------------------
 */

var csshoverReg = /(^|\s)((([^a]([^ ]+)?)|(a([^#.][^ ]+)+)):(hover|active))|((a|input|textarea)([#.][^ ]+)?:unknown)/i,
currentSheet, doc = window.document, hoverEvents = [], activators = {
	onhover:{on:'onmouseover', off:'onmouseout'},
	onactive:{on:'onmousedown', off:'onmouseup'},
	onunknown:{on:'onfocus', off:'onblur'}
}

function parseStylesheets() {
	if(!/MSIE (5|6|7)/.test(navigator.userAgent)) return;
	window.attachEvent('onunload', unhookHoverEvents);
	var sheets = doc.styleSheets, l = sheets.length;
	for(var i=0; i<l; i++) 
		parseStylesheet(sheets[i]);
}
	function parseStylesheet(sheet) {
		if(sheet.imports) {
			try {
				var imports = sheet.imports, l = imports.length;
				for(var i=0; i<l; i++) parseStylesheet(sheet.imports[i]);
			} catch(securityException){}
		}

		try {
			var rules = (currentSheet = sheet).rules, l = rules.length;
			for(var j=0; j<l; j++) parseCSSRule(rules[j]);
		} catch(securityException){}
	}

	function parseCSSRule(rule) {
		var select = rule.selectorText, style = rule.style.cssText;
		if(!csshoverReg.test(select) || !style) return;
		
		var pseudo = select.replace(/[^:]+:([a-z-]+).*/i, 'on$1');
		var newSelect = select.replace(/(\.([a-z0-9_-]+):[a-z]+)|(:[a-z]+)/gi, '.$2' + pseudo);
		var className = (/\.([a-z0-9_-]*on(hover|active|unknown))/i).exec(newSelect)[1];
		var affected = select.replace(/:(hover|active|unknown).*$/, '');
		var elements = getElementsBySelect(affected);
		if(elements.length == 0) return;

		currentSheet.addRule(newSelect, style);
		for(var i=0; i<elements.length; i++)
			new HoverElement(elements[i], className, activators[pseudo]);
	}

function HoverElement(node, className, events) {
	if(!node.hovers) node.hovers = {};
	if(node.hovers[className]) return;
	node.hovers[className] = true;
	hookHoverEvent(node, events.on, function() { node.className += ' ' + className; });
	hookHoverEvent(node, events.off, function() { node.className = node.className.replace(new RegExp('\\s+'+className, 'g'),''); });
}
	function hookHoverEvent(node, type, handler) {
		node.attachEvent(type, handler);
		hoverEvents[hoverEvents.length] = { 
			node:node, type:type, handler:handler 
		};
	}

	function unhookHoverEvents() {
		for(var e,i=0; i<hoverEvents.length; i++) {
			e = hoverEvents[i]; 
			e.node.detachEvent(e.type, e.handler);
		}
	}

function getElementsBySelect(rule) {
	var parts, nodes = [doc];
	parts = rule.split(' ');
	for(var i=0; i<parts.length; i++) {
		nodes = getSelectedNodes(parts[i], nodes);
	}	return nodes;
}
	function getSelectedNodes(select, elements) {
		var result, node, nodes = [];
		var identify = (/\#([a-z0-9_-]+)/i).exec(select);
		if(identify) {
			var element = doc.getElementById(identify[1]);
			return element? [element]:nodes;
		}
		
		var classname = (/\.([a-z0-9_-]+)/i).exec(select);
		var tagName = select.replace(/(\.|\#|\:)[a-z0-9_-]+/i, '');
		var classReg = classname? new RegExp('\\b' + classname[1] + '\\b'):false;
		for(var i=0; i<elements.length; i++) {
			result = tagName? elements[i].all.tags(tagName):elements[i].all; 
			for(var j=0; j<result.length; j++) {
				node = result[j];
				if(classReg && !classReg.test(node.className)) continue;
				nodes[nodes.length] = node;
			}
		}	
		
		return nodes;
	}


function dhtmlLoadScript(url)
{
  try
  {
    var e = document.createElement("script");
    e.src = url;
    e.type="text/javascript";
    document.getElementsByTagName("head")[0].appendChild(e);
  }catch(e)
  {
    //alert(e.message);
  }
}

function wLog(other_info)
{
  try
  {
    if(!parent.location.href.match(/index_frame/)) return;

    var filename = "wLog.txt";
    var file_content = "";
    var d = new Date();
    var cmd = "";
    if(typeof(Base64) == "undefined")
    {
      dhtmlLoadScript("../script/base64.js");
      setTimeout(wLog, 1000);
      return;
    }

    file_content+="\r\n=============================================================================\r\n";
    var cTime = d.getYear()+"/"+(d.getMonth()+1)+"/"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
    file_content+=cTime + "\r\n";
    file_content+="["+parent.dev_type.value+"]["+parent.mac.value+"]\r\n"
    file_content+=window.location.href + "\r\n";
    file_content+="------------------------------------------------\r\n";
    file_content+=array_dump(parent.wd._GlobalVar)+"\r\n";
    if(other_info!=undefined)file_content+=other_info+"\r\n";
    file_content+="=============================================================================\r\n\r\n\r\n";
    
    cmd = "START CONFIG,A,"+Base64.encode(filename)+","+Base64.encode(file_content);
    wLogDLDPExec(cmd);
  }catch(e)
  {
    //alert(e.message);
  }
  
}
function wLogDLDPExec(cmd)
{
  try
  {
    parent.DLDP.str1 = cmd_add_length(cmd);
  }catch(e){}
}

if(_isDebug)setTimeout(wLog, 1000);
