var ShowCamCtrl = true;
setCookie("activatedmode", "mechanical");
function loadCurrentSetting()
{
	resizeLogo();
	$("#sidebar-footer").corners("10px bottom-right");
	$("#control-area").corners("10px top-right");
	$("#video-area-wrapper").corners("10px");
	$('.rounded_frame, .rounded_outter').corners();

	document.getElementById("StreamSelector").value = getCookie("streamsource");

	loadvalue_MultiLangList();
	//document.getElementById("digitalOutPut-bar").style.overflow = "visible"; // buggy IE? still don't know why
	document.title = system_hostname;
	document.getElementById("page_title").innerHTML = "<span></span>" + system_hostname;

	SpecicalCaseHandle();

	loadlanguage();				
	loadvalue();

	initButton();	
	VIButtonStatusUpdate(true, 0);
	VIButtonStatusUpdate(true, 1);
	VIButtonStatusUpdate(true, 2);	
	//CheckCamCtrl();    
	//DOButtonStatusUpdate(true);

	if (document.all)  //for buggy IE6
		document.execCommand("BackgroundImageCache", false, true);

	showimage_innerHTML('0', 'showimageBlock', capability_naudioin);

	//This way also workable.
	//if ((typeof(RtspVapgCtrl) != "undefined") && (RtspVapgCtrl.Language != undefined)) // for IE
	try
	{
		if (bIsWinMSIE)
		{
			initPluginCallbackFn();
		}
		else
		{
            $("#RtspCtrlBtn-bar").show();
            //$("#RtspCtrlBtn-bar, #viewsizeCtrlBlk").show();
			Mpeg4_MJpeg_Switch();
			loadRtspCtrlBtnValue();
		}
	}
	catch (err)
	{
		Log(err.description);
	}


	$("#btn_ptz_zoomWide").html("&nbsp;");
	$("#btn_ptz_zoomTele").html("&nbsp;");
	if (bIsWinMSIE)
	{
		$("#btn_ptz_zoomWide").css("margin-right", "-2px");
		$("#btn_ptz_zoom_text").text(translator("zoom")).css("padding-left", $("#btn_ptz_zoom").width() / 2 - $("#btn_ptz_zoom_text").width() / 2 +"px");
	}
	else
	{
		$("#btn_ptz_zoom").text(translator("zoom"));
	}

	$("#btn_ptz_focusNear").html("&nbsp;");
	$("#btn_ptz_focusAuto").html(translator("focus"));
	$("#btn_ptz_focusFar").html("&nbsp;");

	konami(function(){
			if (document.getElementById("Konami").style.display == "block")
			document.getElementById("Konami").style.display = "none";
			else
			document.getElementById("Konami").style.display = "block";
			});

    $("#ctrl-panel-toggle-icon").attr("title", translator("hide_control_panel"));
    $("#ctrl-panel-toggle-icon").click(function(){
        if( !$(this).hasClass("clicked"))
        {
            $("#sidebar, #logo").fadeOut(function(){
                $("#ctrl-panel-toggle-icon").css("border-width", "5px 0 5px 5px").css("margin-left", "0px").addClass("clicked").attr("title", translator("show_control_panel"));
            });
        }
        else
        {
            $("#sidebar, #logo").fadeIn(function(){
                $("#ctrl-panel-toggle-icon").css("border-width", "5px 5px 5px 0").css("margin-left", "-6px").removeClass("clicked").attr("title", translator("hide_control_panel"));
            });
        
        }
    });

    //Init viewsizemode button state.
    //var viewsizemode = getCookie("viewsizemode");
    //if(0 != viewsizemode)
    //{
    //    switchView($("button.viewstyle:[title*='"+ viewsizemode  +"']")[0], viewsizemode, true);
	//}
    //else
    //{
	//	setCookie("viewsizemode", "100");
    //    switchView($("button.viewstyle:[title*='100%']")[0], "100", true);
    //}

    //set cookie "4x3" default value = false;
    /*if ( 0 == getCookie("4x3"))
    {
        setCookie("4x3", "false");
    }
    else if ( "true" == getCookie("4x3"))
    {
        setCookie("4x3", "false");
        Toggle4x3();
    }*/

    setTimeout("layoutAdjudement();", 1000);
}

function VIButtonStatusUpdate(firstLoad, vipin)
{
	var VIValue = eval("status_vi_i"+vipin);

	if(layout_custombutton_manualtrigger_show == 1)
	{
		document.getElementById("manual_trigger_ctrl").style.display = "";
	}

	if (VIValue == "0")
	{
		if (firstLoad != undefined && firstLoad == true)
		{
			document.getElementById("btn_vi"+vipin+"_on").style.backgroundPosition = "0px 0px";
			document.getElementById("btn_vi"+vipin+"_off").style.backgroundPosition = "-24px -36px";
			document.getElementById("btn_vi"+vipin+"_on").disabled = false;
			document.getElementById("btn_vi"+vipin+"_off").disabled = true;
		}
		else
		{
			switch(vipin)
			{
				case 0:
					status_vi_i0="1";
					break;
				case 1:
					status_vi_i1="1";
					break;
				case 2:
					status_vi_i2="1";
					break;
			}
			document.getElementById("btn_vi"+vipin+"_on").style.backgroundPosition = "0px -36px";
			document.getElementById("btn_vi"+vipin+"_off").style.backgroundPosition = "-24px 0px";
			document.getElementById("btn_vi"+vipin+"_on").disabled = true;
			document.getElementById("btn_vi"+vipin+"_off").disabled = false;
			XMLHttpRequestObject.open("GET", "/cgi-bin/admin/setvi.cgi?vi"+vipin+"=1");
			XMLHttpRequestObject.setRequestHeader("If-Modified-Since","0");
			XMLHttpRequestObject.send(null);
		}
	}
	else
	{
		if (firstLoad != undefined && firstLoad == true)
		{
			document.getElementById("btn_vi"+vipin+"_on").style.backgroundPosition = "0px -36px";
			document.getElementById("btn_vi"+vipin+"_off").style.backgroundPosition = "-24px 0px";
			document.getElementById("btn_vi"+vipin+"_on").disabled = true;
			document.getElementById("btn_vi"+vipin+"_off").disabled = false;
		}
		else
		{
			switch(vipin)
			{
				case 0:
					status_vi_i0="0";
					break;
				case 1:
					status_vi_i1="0";
					break;
				case 2:
					status_vi_i2="0";
					break;
			}
			document.getElementById("btn_vi"+vipin+"_on").style.backgroundPosition = "0px 0px";
			document.getElementById("btn_vi"+vipin+"_off").style.backgroundPosition = "-24px -36px";
			document.getElementById("btn_vi"+vipin+"_on").disabled = false;
			document.getElementById("btn_vi"+vipin+"_off").disabled = true;
			XMLHttpRequestObject.open("GET", "/cgi-bin/admin/setvi.cgi?vi"+vipin+"=0");
			XMLHttpRequestObject.setRequestHeader("If-Modified-Since","0");
			XMLHttpRequestObject.send(null);
		}
	}
}

function initGlobalView()
{
	if (streamsource < FULLVIEW_STREAM_INDEX)
	{
		$("#ptz_goto").show();
		$("#ptz_globalview").show();
		$("#ptz_control").show();
	}
	else
	{
		$("#ptz_goto").hide();//stream3 is not capable of preset-feature
		if ($("#ROI_Cropbox").css("display") == "block") toggleGV();    
		$("#ptz_control").hide();
	}
}

function initGVZoomHandle()
{
	$('#ROI_Cropbox').mousewheel(
			function(event, delta) {
			if (delta > 0)
			{
			if(value == "mechanical")
			CamControl('zoom','tele');
			else
			ePTZControl("zoom","tele");
			}
			else if (delta < 0)
			{
			if(value == "mechanical")
			CamControl('zoom','wide');
			else
			ePTZControl("zoom","wide");
			}
			return false; // prevent default
			}
			);
}

var bROI_Initialed = false;
var bGVOpen = false;
var refreshImgtimer, refreshROItimer;

var g_bReadyToSendNext = true;
var CGI_REQS_PER_SEC = 15;
var ROI_X, ROI_Y, ROI_W, ROI_H;

function toggleGV()
{
	switchBlock('ROI_Cropbox', 'stream1Icon'); 
	if(!bROI_Initialed)
	{
		$.ajax({
url: "/cgi-bin/viewer/getparam_cache.cgi?roi",
//url: "/cgi-bin/camctrl/eCamCtrl.cgi?stream=" + streamsource,
async: false,
dataType: "script",
success: function(data){
Log("getparam?roi: %s",data);
}
});

eval("ROI_X=roi_c0_s"+ streamsource+"_home.split(',')[0]");
eval("ROI_Y=roi_c0_s"+ streamsource+"_home.split(',')[1]");
eval("ROI_W=roi_c0_s"+ streamsource+"_size.split('x')[0]");
eval("ROI_H=roi_c0_s"+ streamsource+"_size.split('x')[1]");
ROI_X1 = ROI_X / RATIO_X;
ROI_Y1 = ROI_Y / RATIO_Y;
ROI_X2 = (parseInt(ROI_X) + parseInt(ROI_W)) / RATIO_X;
ROI_Y2 = (parseInt(ROI_Y) + parseInt(ROI_H)) / RATIO_Y;

JcropObj = $.Jcrop($('#cropbox'),{
onChange: showCoords,
onSelect: showCoords,
aspectRatio: ROI_W/ROI_H,
keySupport: true,
boxWidth: BOXWIDTH,
boxHeight: BOXHEIGHT,
minSize: [VideoSize.split('x')[0]/RATIO_X/4, VideoSize.split('x')[1]/RATIO_Y/4],  //devided by 4, for at most 4X digital-zoom
setSelect:   [ ROI_X1, ROI_Y1, ROI_X2, ROI_Y2 ],
trueSize: [TRUEWIDTH, TRUEHEIGHT]
});
bROI_Initialed = true;
}

bGVOpen = !bGVOpen;
if(bGVOpen)
{
	refreshROI();
	refreshImgTimer = setInterval("refreshImage(VIDEO_JPG)", INTERVAL_snapshot);
	refreshROITimer = setInterval("refreshROI()", INTERVAL_ROI);
}
else
{
	clearInterval(refreshImgTimer);
	clearInterval(refreshROITimer);
}
}

var pre_coords_x;
var pre_coords_y;
var pre_coords_x2;
var pre_coords_y2;
var g_bPreventResend = false; //prevent ePTZControl caused onChange event to resend CGI to camera.
var g_bUpdatedRencently = false;
var UPDATE_ROI_PERIOD = 10000;
var UpdateTimer = -1;

function showCoords(c)
{
	if(g_bPreventResend)
	{
		g_bPreventResend = false;
		return; 
	}

	//prevent send ePTZ.cgi to cause boa overhead when coordinate isn't changed, eg: click on ROI but doesn't drag!
	if( c.x == pre_coords_x &&
			c.y == pre_coords_y &&
			c.x2 == pre_coords_x2 &&
			c.y2 == pre_coords_y2    )
	{
		//Log("%s","Same coords as previous one");
		return;
	}
	else
	{
		pre_coords_x = c.x;
		pre_coords_y = c.y;
		pre_coords_x2 = c.x2;
		pre_coords_y2 = c.y2;  
	}

	$('#x_').val(c.x);
	$('#y_').val(c.y);
	$('#w_').val(c.w);
	$('#h_').val(c.h);

	if (bROI_Initialed)
	{
		if(!g_bReadyToSendNext)
		{
			Log("Not Ready To Send Next CGI");
			return;
		}

		if(g_bRefreshROI) //
		{ 
			//Log("g_bRefreshROI = %d, Animating", g_bRefreshROI); 
			return;
		} 

		// Add these 3 line to enable "refreshROI()" once idle for 10 secs.
		clearTimeout(UpdateTimer);
		g_bUpdatedRencently = true;
		UpdateTimer = setTimeout("g_bUpdatedRencently = false;", UPDATE_ROI_PERIOD);

		var coords = JcropObj.tellSelect();
		var RESOLUTION = TRUEWIDTH+"x"+TRUEHEIGHT;
		var CGICmd='/cgi-bin/camctrl/eCamCtrl.cgi?stream=' + streamsource + '&x=' + coords.x + '&y=' + coords.y + '&w=' + coords.w + '&h=' + coords.h + '&resolution=' + RESOLUTION;

		Log("Sent => %s",CGICmd);
		$.ajax({
url: CGICmd,      
cache: false, 
async: true, 
success: function(data){
//data example=> x=170&y=80&w=640&h=480
Log("Return value from ePTZ.cgi => %s",data);
DisplayZoomRatio(data);
}
});

//To limit cgi request per seconds, un-comment below 2 lines.
if(!g_bLimitFreq)
{
	g_bReadyToSendNext = false;
	setTimeout("g_bReadyToSendNext = true;", 1000/CGI_REQS_PER_SEC);
}
}
}

var g_bRefreshROI = false;
function refreshROI()
{
	if(!g_bUpdatedRencently)
	{
		$.ajax({
url: "/cgi-bin/camctrl/eCamCtrl.cgi?stream=" + streamsource,
async: true,
cache: false,
success: function(data){
//Log("refreshROI() Query-eCamctrl.cgi => %s",data);
g_bRefreshROI = true;
parseCoords(data);
}
});
}
}

var g_bLimitFreq = false;
function parseCoords(coordsData)
{
	//coordsData example=> x=170&y=80&w=640&h=480
	var coords = coordsData.split(',');

	//to round up or down
	ROI_X1 = parseInt((parseInt(coords[0].split('=')[1])+5) / RATIO_X);
	ROI_Y1 = parseInt((parseInt(coords[1].split('=')[1])+5) / RATIO_Y);
	ROI_X2 = parseInt((parseInt(coords[0].split('=')[1]) + parseInt(coords[2].split('=')[1]) +5) / RATIO_X);
	ROI_X2 = (ROI_X2 > BOXWIDTH) ? BOXWIDTH : ROI_X2;
	ROI_Y2 = parseInt((parseInt(coords[1].split('=')[1]) + parseInt(coords[3].split('=')[1]) +5) / RATIO_Y);
	ROI_Y2 = (ROI_Y2 > BOXHEIGHT) ? BOXHEIGHT : ROI_Y2;

	//if Global View is launched, update the window. 
	if(bROI_Initialed)
	{
		if(g_bSmooth || g_bRefreshROI)
			JcropObj.animateTo([ROI_X1, ROI_Y1, ROI_X2, ROI_Y2]);
		else
			JcropObj.setSelect([ROI_X1, ROI_Y1, ROI_X2, ROI_Y2]);

		DisplayZoomRatio(coordsData);
	} 
}

function switchPTZPanel(value)
{
	$("#ptz_control").css("visibility", "visible");
	if(value == 'mechanical') //mechanical
	{
		if(typeof(RtspVapgCtrl) != "undefined") $("#RtspVapgCtrl").attr("PtzURL","/cgi-bin/camctrl/camctrl.cgi");
		$("#ptz_globalview").hide();

		if (ShowCamCtrl == true)
		{
			$("table.CtrlArea tr[id=ptz_focus]").show();
			$("#ptz_control").show();
			$("#customcmdBtn-bar").show();
			ShowPresetSelction("mechanical");
			$("#ptz_goto").show();
		}
		else
		{
			$("table.CtrlArea tr[id=ptz_focus]").hide();
			$("#ptz_control").hide();
			$("#customcmdBtn-bar").hide();
			$("#ptz_goto").hide();
			switchPTZPanel('digital');
			return;
		}
		$("#camctrl_c0_panspeed option")[eval(parseInt(camctrl_c0_panspeed)+5)].selected = true;
		$("#camctrl_c0_tiltspeed option")[eval(parseInt(camctrl_c0_tiltspeed)+5)].selected = true;
		$("#camctrl_c0_zoomspeed option")[eval(parseInt(camctrl_c0_zoomspeed)+5)].selected = true;
	}
	else if(value == 'digital') //digital
	{
        initGVZoomHandle(value);
		if(typeof(RtspVapgCtrl) != "undefined") $("#RtspVapgCtrl").attr("PtzURL","/cgi-bin/camctrl/eCamCtrl.cgi");
		$("table.CtrlArea tr[id=ptz_focus]").hide();
		$("#camctrl_c0_panspeed option")[eval(parseInt(eptz_c0_panspeed)+5)].selected = true;
		$("#camctrl_c0_tiltspeed option")[eval(parseInt(eptz_c0_tiltspeed)+5)].selected = true;
		$("#camctrl_c0_zoomspeed option")[eval(parseInt(eptz_c0_zoomspeed)+5)].selected = true;
		ShowPresetSelction("digital");
		$("#customcmdBtn-bar").hide();
		initGlobalView(); // $("#ptz_globalview").show();
	}

	if(value != getCookie("activatedmode"))
	{
		setCookie("activatedmode", value);
	}
}



function SpecicalCaseHandle()
{
	if( lan >= 100 ) //custom language
		return;
	var LanguageSelected = eval('system_info_language_i'+lan);
	//By Kent, for Deutsch layout		
	if (LanguageSelected == "Deutsch")
	{			
		$("#sidebar,.wraptocenter_logo,#sidebar-footer").css("width","230px");
		if ($.browser.mozilla || $.browser.safari) $("#sidebar-footer").css("width","210px");
		$("#shadow_container").css("display","none");

	}		

	if (LanguageSelected == "Français" || LanguageSelected == "Italiano")
	{
		$("#btn_ptz_zoom, #btn_ptz_focusAuto, #btn_ptz_irisAuto").css("backgroundImage","url(/pic/wide_noword.gif)");
		$("#btn_ptz_zoom, #btn_ptz_focusAuto, #btn_ptz_irisAuto").css("backgroundPosition","0px 0px");
		$("#btn_ptz_zoom, #btn_ptz_focusAuto, #btn_ptz_irisAuto").css("width","100px");
	}
}


function initButton()
{
	var rtspBtnObj = document.getElementById("RtspCtrlBtn-bar").getElementsByTagName("button");
	for (i = 0; i < rtspBtnObj.length; i++) 
	{
		rtspBtnObj[i].title = translator(rtspBtnObj[i].title);
		addEventSimple(rtspBtnObj[i], 'mouseover', RtspCtrlBtnHandler);
		addEventSimple(rtspBtnObj[i], 'mouseout', RtspCtrlBtnHandler);
		addEventSimple(rtspBtnObj[i], 'mousedown', RtspCtrlBtnHandler);
		addEventSimple(rtspBtnObj[i], 'mouseup', RtspCtrlBtnHandler);
	}

	var BtnObj = document.getElementById("control-area").getElementsByTagName("button");
	for (i = 0; i < BtnObj.length; i++) 
	{
		if (BtnObj[i].id == "btn_ptz_zoom" || BtnObj[i].id == "btn_vi0" || BtnObj[i].id == "btn_vi1" || BtnObj[i].id == "btn_vi2") 
			continue;
		addEventSimple(BtnObj[i], 'mouseover', BtnHandler);
		addEventSimple(BtnObj[i], 'mouseout', BtnHandler);
		addEventSimple(BtnObj[i], 'mousedown', BtnHandler);
		addEventSimple(BtnObj[i], 'mouseup', BtnHandler);
	}

	var customcmdBtnObj = document.getElementById("customcmdBtn-bar").getElementsByTagName("button");
	for (var i = 0; i < customcmdBtnObj.length; i++) 
	{
		addEventSimple(customcmdBtnObj[i], 'mouseover', BtnHandler);
		addEventSimple(customcmdBtnObj[i], 'mouseout', BtnHandler);
		addEventSimple(customcmdBtnObj[i], 'mousedown', BtnHandler);
		addEventSimple(customcmdBtnObj[i], 'mouseup', BtnHandler);
	}

	/*var viewsizeBtnObj = document.getElementById("viewsizeCtrlBlk").getElementsByTagName("button");
	for (i = 0; i < viewsizeBtnObj.length; i++) 
	{
		addEventSimple(viewsizeBtnObj[i], 'mouseover', BtnHandler);
		addEventSimple(viewsizeBtnObj[i], 'mouseout', BtnHandler);
		addEventSimple(viewsizeBtnObj[i], 'mousedown', BtnHandler);
		addEventSimple(viewsizeBtnObj[i], 'mouseup', BtnHandler);
	}*/
}

function switchStream(selectedIndex)
{		
	var RtspVapgCtrlObject = document.getElementById(PLUGIN_ID);

	// plugindef.js  begin
	streamsource = selectedIndex;
	eval("VideoSize=videoin_c0_s" + streamsource + "_resolution");
	eval("codectype=videoin_c0_s" + streamsource + "_codectype");
	if (codectype == "mjpeg")
		eval("AccessName=network_http_s" + streamsource + "_accessname");
	else //(codectype == "mpeg4") || (codectype == "h264")
		eval("AccessName=network_rtsp_s" + streamsource + "_accessname");

	evalPluginSize();
	// showimage(0)  begin
	var str_innerHTML = "";

	if (bIsWinMSIE)
	{			
		//To avoid switch streaming source too fast.
		$("#StreamSelector").attr("disabled", true);

		RtspVapgCtrl.Disconnect();

		W = W + X_OFFSET;
		H = H + Y_OFFSET;
		//W=BaseWidth + X_OFFSET;
		//H=BaseHeight + Y_OFFSET;

		// The ActiveX plug-in

        $("#"+PLUGIN_ID).height(H);
        $("#"+PLUGIN_ID).width(W);
		//RtspVapgCtrlObject.width = W;
		//RtspVapgCtrlObject.height = H;

		var Instr = location.hostname;
		var i = Instr.indexOf(":");
		if ((codectype == "mpeg4") || (codectype == "h264"))
		{	
			if (i > 0)
			{
				RtspVapgCtrlObject.Url = "rtsp://" + "[" + location.hostname + "]" + "/" + AccessName;
			}
			else if (i == -1)
			{
				RtspVapgCtrlObject.Url = "rtsp://" + location.hostname + "/" + AccessName;
			}
		}
		else
		{
			thisURL = document.URL;
			http_method = thisURL.split(":");
			if (http_method[0] == "https")
			{
				if (i > 0)
				{
					RtspVapgCtrlObject.Url = "https://" + "[" + location.hostname + "]:" + location.port + "/" + AccessName;
				}
				else if (i == -1)
				{
					RtspVapgCtrlObject.Url = "https://" + location.host + "/" + AccessName;
				}
			}
			else 
			{
				if (i > 0)
				{
					RtspVapgCtrlObject.Url = "http://" + "[" + location.hostname + "]:" + location.port + "/" + AccessName;
				}
				else if (i == -1)
				{
					RtspVapgCtrlObject.Url = "http://" + location.host + "/" + AccessName;
				}
			}
		}

		RtspVapgCtrlObject.ViewStream  = streamsource;
		RtspVapgCtrlObject.Stretch = STRETCH;
		//alert(document.getElementById(PLUGIN_ID).ViewStream);
		//alert(document.getElementById(PLUGIN_ID).Url);				

		setTimeout("RtspVapgCtrl.Connect()", 500);
		//RtspVapgCtrl.Connect();
		setTimeout('$("#StreamSelector").attr("disabled", false)', 3000);
	}
	else if (navigator.appName == "Netscape") 
	{
		if (codectype == "mjpeg") 
		{
            Y_OFFSET = 0;
			thisURL = document.URL;
			http_method = thisURL.split(":");
			if (http_method[0] == "https") 
			{
				str_innerHTML += "<img id=\"" + PLUGIN_ID + "\" src=\"https://" + location.host + "/" + AccessName + "\" width=\"" + Width + "\" height=\"" + Height + "\"/>";
			}
			else 
			{
				str_innerHTML += "<img id=\"" + PLUGIN_ID + "\" src=\"http://" + location.host + "/" + AccessName + "\" width=\"" + Width + "\" height=\"" + Height + "\"/>";
			}
		}
		else 
		{
            Y_OFFSET = 16; // Quicktime contrlbar height
			str_innerHTML += "<embed SCALE=\"ToFit\" id=\"" + PLUGIN_ID + "\" width=\"" + Width + "\" height=\"" + Height + "\"";
			str_innerHTML += " type=\"video/quicktime\" qtsrc=\"rtsp://" + location.hostname + "/" + AccessName + "\"";
			str_innerHTML += " qtsrcdontusebrowser src=\"/realqt.mov\" autoplay=\"true\" controller=\"true\"\>";
		}

		// update Div(showimageBlock)  
		document.getElementById("showimageBlock").innerHTML = str_innerHTML;

	}
	else 
	{
		document.getElementById("showimageBlock").innerHTML = "Please use Firefox, Mozilla or Netscape<br>";
	}

	Mpeg4_MJpeg_Switch();
	loadRtspCtrlBtnValue();

	setCookie("streamsource", selectedIndex);

	layoutAdjudement();  
	//ShowEPTZPanel();

    //var viewsizemode = getCookie("viewsizemode");
    //if(0 != viewsizemode)
    //{
    //    switchView($("button.viewstyle:[title*='"+ viewsizemode  +"']")[0], viewsizemode, true);
	//}
}

function ShowEPTZPanel()
{
	if ($('select[name="ptz_panel_selector"]').selectedValues() == "digital")
	{
		initGlobalView();
		if(bROI_Initialed && streamsource < FULLVIEW_STREAM_INDEX)
		{
			JcropObj.setMinSize([VideoSize.split('x')[0]/RATIO_X/4, VideoSize.split('x')[1]/RATIO_Y/4]);
			g_bUpdatedRencently = false;
			refreshROI();
			eval("ROI_X=roi_c0_s"+ streamsource+"_home.split(',')[0]");
			eval("ROI_Y=roi_c0_s"+ streamsource+"_home.split(',')[1]");
			eval("ROI_W=roi_c0_s"+ streamsource+"_size.split('x')[0]");
			eval("ROI_H=roi_c0_s"+ streamsource+"_size.split('x')[1]");
			//set different aspectRatio for each stream
			JcropObj.setAspectRatio(ROI_W/ROI_H); 
		}
		ShowPresetSelction("digital");
	}
}

/* 
 * PTZ Control
 */

function SubmitPreset(selObj) 
{
	var ChannelNo = 0;

	if (getCookie("activatedmode") == "mechanical")
	{
		var CGICmd='/cgi-bin/camctrl/recall.cgi?channel=' + ChannelNo + '&index=' + $(selObj).selectedOptions().val();
	}
	else
	{
		var CGICmd='/cgi-bin/camctrl/eRecall.cgi?stream=' + streamsource + '&recall=' + encodeURIComponent($(selObj).selectedOptions().text());
	}
	parent.retframe.location.href=CGICmd;
	Log("Send: %s",CGICmd);
}

function ShowPresetSelction(type)
{
	//if (streamsource == FULLVIEW_STREAM_INDEX) return;
	$("#presetname").removeOption(/./);

	$("#presetname").addOption("-1", translator("select_one"));
	for (var i = 0; i < 20; i++)
	{
		var PreName;
		if (type == "mechanical")
		{
			PreName = eval('camctrl_c0_preset_i' + i + '_name');
		}
		else if (type == "digital")
		{
			PreName = eval('eptz_c0_s' + streamsource + '_preset_i' + i + '_name');
		}

		if (PreName != "")
		{
			$("#presetname").addOption(i, PreName, false);
		}	
	}
}

function CheckCamCtrl()
{
	if ((camctrl_c0_isptz == 0) || (uart_i0_ptzdriver == 128) || (camctrl_enableptztunnel == 1) || (uart_enablehttptunnel == 1))
	{
		ShowCamCtrl = false;
	}
	if (uart_i0_ptzdriver == 127)
	{
		document.getElementById("camctrl_c0_panspeed").disabled = true;
		document.getElementById("camctrl_c0_tiltspeed").disabled = true;
		document.getElementById("camctrl_c0_zoomspeed").disabled = true;
		document.getElementById("presetname").disabled = true;
	}

    if (ShowCamCtrl)
    {
        switchPTZPanel('mechanical');
        ShowCustomCmd();
    }

}

function initPTZPanel()
{
	initEPTZParams("global_view");
	$("#cropbox").attr("width",BOXWIDTH).attr("height",BOXHEIGHT).attr('src', VIDEO_JPG);
	$("#ROI_Cropbox").hide(); //move "style='display:none'" from index.html to here to prefetch a image!

	$('select[name="ptz_panel_selector"]').addOption('digital', translator('digital'));

	if (ShowCamCtrl == true)
	{
		$('select[name="ptz_panel_selector"]').addOption('mechanical', translator('mechanical'), false);        
	}

	if (activatedmode == 'digital')
	{
		switchPTZPanel('digital');
	}
	else
	{
		switchPTZPanel('mechanical');
		$("select[name='ptz_panel_selector']").val(activatedmode);
	}
}

function ShowCustomCmd() {

	var ChannelNo = 0;
	var CamId = camctrl_c0_cameraid;
    var tmpStr = "";
	for (var i = 0; i < 5; i++)
	{
		var speedlinkname = eval('uart_i0_speedlink_i' + i + '_name');
		if (speedlinkname)
		{
			tmpStr += "<button class='customcmdBtn' style='background-Position: -533px 0px;' onclick=\"parent.retframe.location.href='/cgi-bin/camctrl/camctrl.cgi?channel="+ChannelNo+"&camid="+CamId+"&speedlink="+i+"'\">" + speedlinkname + "</button>";
		}
        $("#customcmdBtn-bar").html(tmpStr);
	}
}
function layoutAdjudement()
{

    $("#control-area").css("padding-bottom", "0px");
    $("#video-area").css("padding-bottom", "0px");

	if(W >= 720)    
	{
		$("#RtspCtrlBtnBlk").css("width","auto");
	}        
	else
	{
		$("#RtspCtrlBtnBlk").css("width","720px");     
	}
/*
	if ($.browser.mozilla && $("#video-area-wrapper").height() >= 528)
	{
		$("#control-area").css("padding-bottom", $("#video-area-wrapper").height() - 528 +'px');
	}     
	else if ($.browser.msie && $("#video-area-wrapper").height() >= 533)
	{
		$("#control-area").css("padding-bottom", $("#video-area-wrapper").height() - 533 +'px');
	}         
	else if ($.browser.safari && $("#video-area-wrapper").height() >= 524)
	{
		$("#control-area").css("padding-bottom", $("#video-area-wrapper").height() - 508 +'px');
	}
	else 
	{
		$("#control-area").css("padding-bottom","0px");
	}    */

    /*if (bIsWinMSIE)
        var leftRightOffset = $("#video-area-wrapper").height() - $("#sidebar").height();
    else
        var leftRightOffset = $("#video-area-wrapper").height() + 30 - $("#sidebar").height();

    if ( leftRightOffset >= 0 )
    {
        oriVal = parseInt($("#control-area").css("padding-bottom").split("px")[0], 10);
        $("#control-area").css("padding-bottom", oriVal + leftRightOffset + 'px');
	}    
    else
    {
        oriVal = parseInt($("#video-area-wrapper").css("padding-bottom").split("px")[0], 10);
        $("#video-area-wrapper").css("padding-bottom", oriVal - leftRightOffset + 'px');
    }*/

    oriVal = parseInt($("#control-area").css("padding-bottom").split("px")[0], 10);
    finalVal = $("#sidebar").parent().outerHeight() - $("#sidebar").outerHeight() + oriVal;
    if (finalVal >=0 ) $("#control-area").css("padding-bottom", finalVal + 'px');

    //oriVal = parseInt($("#video-area").css("padding-bottom").split("px")[0], 10);
    //$("#video-area").css("padding-bottom", $("#video-area-wrapper").parent().outerHeight() - $("#video-area-wrapper").outerHeight() + oriVal + 'px');
    
    // Workaround, to force Browser do vertical-align : middle again.
    $("#ctrl-panel-toggle").css("vertical-align", "").css("vertical-align", "middle");
}

function changlan(seleted_lan)
{
	if (seleted_lan == system_info_language_count) 
	{
		if (custom_translator_ok) 
		{
			setCookie("lan", 100);
		}
		else 
		{
			alert(translator(fail_to_load_custom_translator.xml));
			setCookie("lan", 0);
		}
	}
	else 
	{
		setCookie("lan", seleted_lan);
	}
	lan = getCookie("lan");
	location.reload();
}


function MM_preloadImages()
{ //v3.0
	var d = document;
	if (d.images) 
	{
		if (!d.MM_p) 
			d.MM_p = new Array();
		var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
		for (i = 0; i < a.length; i++) 
		{
			if (a[i].indexOf("#") !== 0) 
			{
				d.MM_p[j] = new Image;
				d.MM_p[j++].src = a[i];
			}
		}
	}
}	

function PreLoadImages()
{
	MM_preloadImages('/pic/plugin.png', '/pic/digitaloutput.png', '/pic/configuration-area.png');
}

function clientsidesnapshot(url)
{
	if (bIsWinMSIE)
    {
        url = RtspVapgCtrl.SnapshotUrl;
    }
	if (url != "")
        url += "?streamid=" + streamsource;
	var subWindow = window.open(url, "", "width=800, height=600, scrollbars=yes, resizable=yes, status=yes");
	subWindow.focus();
}

function BtnHandler(event)
{
	var object = event.srcElement ? event.srcElement : event.target;    
	if (object.clientWidth != object.offsetWidth || object.disabled == true) return;

	X = parseInt(object.style.backgroundPosition.split(" ")[0]).toString(10);
	if (event.type == "mousedown")
	{
		object.style.backgroundPosition = X + "px " + -2 * object.offsetHeight + "px";
		if (document.all) 
			object.hideFocus = true;
		else 
			return;
	}
	else if (event.type == "mouseover" || event.type == "mouseup") 
	{
		object.style.backgroundPosition = X + "px " + -object.offsetHeight + "px";
	}
	else//(e=="mouseout") 
	{
		object.style.backgroundPosition = X + "px " + "0px";
	}
}

function RtspCtrlBtnHandler(event)
{
	var object = event.srcElement ? event.srcElement : event.target;

	if (object.clientWidth != object.offsetWidth || object.disabled === true) 
		return;

	if (object.id == "btn_play" || bStopEnabled === false) 
	{
		X = parseInt(object.style.backgroundPosition.split(" ")[0]).toString(10);

		if (event.type == "mousedown") 
		{				
			if (object.id == "btn_talk") 
			{
				if (bTalkEnabled == false) 
					object.style.backgroundPosition = X + "px " + -2 * object.offsetHeight + "px";
			}
			else if (object.id == "btn_volume") 
			{
				if (bMuteEnabled == false) 
					object.style.backgroundPosition = X + "px " + -2 * object.offsetHeight + "px";
			}
			else if (object.id == "btn_mic_volume") 
			{
				if (bMicMuteEnabled == false) 
					object.style.backgroundPosition = X + "px " + -2 * object.offsetHeight + "px";
			}
			else 
				object.style.backgroundPosition = X + "px " + -2 * object.offsetHeight + "px";

			if (document.all) 
				object.hideFocus = true;
			else 
				return;
		}
		else if (event.type == "mouseover" || event.type == "mouseup") 
		{
			if (object.id == "btn_talk") 
			{
				if (bTalkEnabled == false) 
					object.style.backgroundPosition = X + "px " + -object.offsetHeight + "px";
			}
			else if (object.id == "btn_volume") 
			{
				if (bMuteEnabled == false) 
					object.style.backgroundPosition = X + "px " + -object.offsetHeight + "px";
			}
			else if (object.id == "btn_mic_volume") 
			{
				if (bMicMuteEnabled == false) 
					object.style.backgroundPosition = X + "px " + -object.offsetHeight + "px";
			}
			else 
			{
				object.style.backgroundPosition = X + "px " + -object.offsetHeight + "px";
			}

		}
		else//(e=="mouseout") 
		{
			if (object.id == "btn_talk") 
			{
				if (bTalkEnabled == false) 
					object.style.backgroundPosition = X + "px " + "0px";
				return;
			}
			else if (object.id == "btn_zoom") 
			{
				if (bZoomEnabled == true) 
				{
					object.style.backgroundPosition = X + "px " + -object.offsetHeight + "px";
					return;
				}
				else 
				{
					object.style.backgroundPosition = X + "px " + "0px";
					return;
				}
			}
			else if (object.id == "btn_volume") 
			{
				if (bMuteEnabled == false) 
				{
					if (bVolumeEnabled == true) 
					{
						object.style.backgroundPosition = X + "px " + -object.offsetHeight + "px";
						return;
					}
					else 
					{
						object.style.backgroundPosition = X + "px " + "0px";
						return;
					}
				}
			}
			else if (object.id == "btn_mic_volume") 
			{
				if (bMicMuteEnabled == false) 
				{
					if (bMicVolumeEnabled == true) 
					{
						object.style.backgroundPosition = X + "px " + -object.offsetHeight + "px";
						return;
					}
					else 
					{
						object.style.backgroundPosition = X + "px " + "0px";
						return;
					}
				}
			}
			else 
			{
				object.style.backgroundPosition = X + "px " + "0px";
			}
		}

	}
}



function loadRtspCtrlBtnValue()
{
	if (bIsWinMSIE)
	{      
		if(typeof(RtspVapgCtrl) == "undefined") // for IE
			return;

		bMicMuteEnabled = !RtspVapgCtrl.MicMute; // set NOT(inverse value) in order to make toggle true
		RtspVagpCtrlToggleMicMute();

		if(RtspVapgCtrl.GetSettings(1) == "3") //protocol = http, can't talk
		{
			document.getElementById("btn_talk").disabled = true;
			document.getElementById("btn_talk").title = translator("talk_disable");
			document.getElementById("btn_talk").style.backgroundPosition = "-280px -84px";
			document.getElementById("btn_mic_volume").disabled = true;
			document.getElementById("btn_mic_volume").style.backgroundPosition = "-308px -84px";
			document.getElementById("btn_mic_mute").disabled = true;
			document.getElementById("btn_mic_mute").style.backgroundPosition = "-336px -84px";										
		}
		else
		{
			if(bStopEnabled)
			{
				bTalkEnabled = false;
				document.getElementById("btn_talk").disabled = false;
				document.getElementById("btn_talk").title = translator("talk");
				document.getElementById("btn_talk").style.backgroundPosition = "-280px -0px";						
			}

			bMicMuteEnabled = !RtspVapgCtrl.MicMute;
			RtspVagpCtrlToggleMicMute();
			document.getElementById("btn_mic_mute").disabled = false;
		}

		if(RtspVapgCtrl.GetSettings(0) == "1") //audio only, cant't zoom
		{
			document.getElementById("btn_zoom").disabled = true;
			document.getElementById("btn_zoom").style.backgroundPosition = "-28px -84px";
		}
		else
		{
			document.getElementById("btn_zoom").disabled = false;
			document.getElementById("btn_zoom").style.backgroundPosition = "-28px -0px";					
		}

		if(RtspVapgCtrl.GetSettings(0) != '2' && bContainAudio == true) //Has Audio: not video only and streaming contains audio
		{          
			if(!bTalkEnabled)
			{
				document.getElementById("btn_volume").disabled = false;
				document.getElementById("btn_volume").style.backgroundPosition = "-196px 0px";
				document.getElementById("btn_mute").disabled = false;
				document.getElementById("btn_mute").style.backgroundPosition = "-252px 0px";

				bMuteEnabled = RtspVapgCtrl.PlayMute; // set RtspVapgCtrl.PlayMute as bMuteEnabled initial value
				bMuteEnabled = !bMuteEnabled; // set NOT(inverse value) in order to make toggle true
				RtspVapgCtrlMuteToggle();
			}
		}
		else
		{
			/*jsl:pass*/
			// Has no audio;
		}

		if (RtspVapgCtrl.IsPermissionSufficient)
		{
			document.getElementById("btn_record").disabled = false;
			document.getElementById("btn_record").style.backgroundPosition = "-140px 0px";
			document.getElementById("btn_fullscreen").disabled = false;
			document.getElementById("btn_fullscreen").style.backgroundPosition = "-392px 0px";
		}
		else
		{
			document.getElementById("btn_record").disabled = true;
			document.getElementById("btn_record").style.backgroundPosition = "-140px -84px";
			document.getElementById("btn_fullscreen").disabled = true;
			document.getElementById("btn_fullscreen").style.backgroundPosition = "-392px -84px";
		}
	}
	else //non-WindowsIE
	{
		document.getElementById("btn_zoom").disabled = true;
		document.getElementById("btn_zoom").style.backgroundPosition = "-28px -84px";
		document.getElementById("btn_play").disabled = true;
		document.getElementById("btn_play").style.backgroundPosition = "-84px -84px";
		document.getElementById("btn_stop").disabled = true;
		document.getElementById("btn_stop").style.backgroundPosition = "-112px -84px";
		document.getElementById("btn_record").disabled = true;
		document.getElementById("btn_record").style.backgroundPosition = "-140px -84px";
		document.getElementById("btn_volume").disabled = true;
		document.getElementById("btn_volume").style.backgroundPosition = "-196px -84px";
		document.getElementById("btn_mute").disabled = true;
		document.getElementById("btn_mute").style.backgroundPosition = "-252px -84px";
		document.getElementById("btn_talk").disabled = true;
		document.getElementById("btn_talk").style.backgroundPosition = "-280px -84px";
		document.getElementById("btn_mic_volume").disabled = true;
		document.getElementById("btn_mic_volume").style.backgroundPosition = "-308px -84px";
		document.getElementById("btn_mic_mute").disabled = true;
		document.getElementById("btn_mic_mute").style.backgroundPosition = "-364px -84px";
		document.getElementById("btn_fullscreen").disabled = true;
		document.getElementById("btn_fullscreen").style.backgroundPosition = "-392px -84px";
	}

}

function Mpeg4_MJpeg_Switch()
{
	if (bIsWinMSIE)
	{
		// fully initialization for Plugin
		bPlayEnabled = true;
		bStopEnabled = false;
		bRecEnabled = false;
		bTalkEnabled = false;
		document.getElementById("btn_snapshot").disabled = false;
		document.getElementById("btn_snapshot").style.backgroundPosition = "0px 0px";
		document.getElementById("btn_zoom").disabled = false;
		document.getElementById("btn_zoom").style.backgroundPosition = "-28px 0px";
		document.getElementById("btn_play").disabled = false;
		document.getElementById("btn_play").style.backgroundPosition = "-56px 0px";
		document.getElementById("btn_stop").disabled = false;
		document.getElementById("btn_stop").style.backgroundPosition = "-112px 0px";
		document.getElementById("btn_talk").disabled = false;
        document.getElementById("btn_talk").style.backgroundPosition = "-280px 0px";
        document.getElementById("btn_fullscreen").disabled = false;
        document.getElementById("btn_fullscreen").style.backgroundPosition = "-392px 0px";
	}
	//alert(RtspVapgCtrl.IsPermissionSufficient);
	if (codectype == "mjpeg")
	{
		document.getElementById('btn_play').style.display = "none";
		document.getElementById('btn_stop').style.display = "none";
		document.getElementById('btn_volume').style.display = "none";
		document.getElementById('btn_mute').style.display = "none";
		document.getElementById('btn_talk').style.display = "none";
		document.getElementById('btn_mic_volume').style.display = "none";
		document.getElementById('btn_mic_mute').style.display = "none";
		
		if (RtspVapgCtrl.IsPermissionSufficient)
		{
			document.getElementById("btn_record").disabled = false;
			document.getElementById("btn_record").style.backgroundPosition = "-140px 0px";
			document.getElementById("btn_fullscreen").disabled = false;
			document.getElementById("btn_fullscreen").style.backgroundPosition = "-392px 0px";
		}
		else
		{
			document.getElementById("btn_record").disabled = true;
			document.getElementById("btn_record").style.backgroundPosition = "-140px -84px";
			document.getElementById("btn_fullscreen").disabled = true;
			document.getElementById("btn_fullscreen").style.backgroundPosition = "-392px -84px";
		}
	}
	else //(codectype == "mpeg4") || (codectype == "h264")
	{
		document.getElementById('btn_play').style.display = "inline";
		document.getElementById('btn_stop').style.display = "inline";
		document.getElementById('btn_volume').style.display = "inline";
		document.getElementById('btn_mute').style.display = "inline";

		if ((user=="(null)")||(privilege=="4")||(privilege=="6")) //viewer can't talk
		{
			document.getElementById('btn_talk').style.display = "inline";
			document.getElementById('btn_mic_volume').style.display = "inline";
			document.getElementById('btn_mic_mute').style.display = "inline";
		}
		else
		{
			document.getElementById('btn_talk').style.display = "none";
			document.getElementById('btn_mic_volume').style.display = "none";
			document.getElementById('btn_mic_mute').style.display = "none";
		}
	}
}


function updateHomepageColor()
{
	switch (layout_theme_option)
	{
		case "1":
			document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/blue_theme_home.css\" media=\"all\"/>");
		break;

		case "2":
			document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/gray_theme_home.css\" media=\"all\"/>");
		break;

		case "3":
			document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/black_theme_home.css\" media=\"all\"/>");
		break;

		case "4":
			createCSS("table.CtrlArea", "color: " + layout_theme_color_font);
		createCSS("#configuration-area table", "color:" + layout_theme_color_configfont);
		createCSS("#configuration-area td a", "color: " + layout_theme_color_configfont);
		createCSS("div#page_title", "color: " + layout_theme_color_titlefont);

		createCSS("table#frame-wrapper td", "background-color: " + layout_theme_color_case);
		createCSS("table#outter-wrapper td", "background: #fff");
		createCSS("#control-area table td", "background-color: " + layout_theme_color_controlbackground);
		createCSS("#video-area table td", "background-color: " + layout_theme_color_videobackground);            
		createCSS("#configuration-area table td", "background-color: " + layout_theme_color_configbackground);            
		createCSS("#video-area-wrapper", "background-color: " + layout_theme_color_videobackground);           

		createCSS("#control-area", "background-color: " + layout_theme_color_controlbackground);
		createCSS("#configuration-area", "background-color: " + layout_theme_color_configbackground);
		createCSS("#sidebar-footer", "background-color: " + layout_theme_color_configbackground);
		break;
		default:
		break;
	}
}

function btn_clientSetOver()
{
	document.getElementById("btn_clientSet").style.backgroundPosition = "0 -20px";
	var client_settings = document.getElementById("client_settings");
	client_settings.style.position = "relative";
	client_settings.style.top = "1px";
	client_settings.style.left = "2px";
}

function btn_clientSetOut()
{
	document.getElementById("btn_clientSet").style.backgroundPosition = "0 0";
	var client_settings = document.getElementById("client_settings");
	client_settings.style.position = "relative";
	client_settings.style.top = "0px";
	client_settings.style.left = "0px";

}

function btn_clientSetClick()
{
	location.href = "clientset.html";
}


function btn_configurationOver()
{
	document.getElementById("btn_configuration").style.backgroundPosition = "-20px -20px";
	var configuration = document.getElementById("configuration");
	configuration.style.position = "relative";
	configuration.style.top = "1px";
	configuration.style.left = "2px";

}

function btn_configurationOut()
{
	document.getElementById("btn_configuration").style.backgroundPosition = "-20px 0";
	var configuration = document.getElementById("configuration");
	configuration.style.position = "relative";
	configuration.style.top = "0px";
	configuration.style.left = "0px";
}

function btn_configurationClick()
{
	location.href = "/setup/system.html";
}


function btn_languageOver()
{
	document.getElementById("btn_language").style.backgroundPosition = "-40px -20px";
	var language = document.getElementById("language");
	language.style.position = "relative";
	language.style.top = "1px";
	language.style.left = "2px";

}

function btn_languageOut()
{
	document.getElementById("btn_language").style.backgroundPosition = "-40px 0";
	var language = document.getElementById("language");
	language.style.position = "relative";
	language.style.top = "0px";
	language.style.left = "0px";
}

function btn_languageClick()
{
	//SlideToggle(document.getElementById('LanguageSelectorDiv'), 'Auto', 'Slide');
	$('#LanguageSelectorDiv').slideToggle('slow');
	var trigger = setInterval("window.scrollBy(0,3)",1);				
	setTimeout('clearInterval('+trigger+')',2000);		
			}

			/***************************************
			  for onmoueleave() not support in Fx
			 ****************************************/
			function containsDOM(container, containee)
			{
			var isParent = false;
			do 
			{
			if ((isParent = container == containee)) 
			break;
			containee = containee.parentNode;
			}
			while (containee != null);
			return isParent;
			}

			function checkMouseEnter(element, evt)
			{
				if (element.contains && evt.fromElement) 
				{
					return !element.contains(evt.fromElement);
				}
				else if (evt.relatedTarget) 
				{
					return !containsDOM(element, evt.relatedTarget);
				}
			}

function checkMouseLeave(element, evt)
{
	if (element.contains && evt.toElement) 
	{
		return !element.contains(evt.toElement);
	}
	else if (evt.relatedTarget) 
	{
		return !containsDOM(element, evt.relatedTarget);
	}
}


function updatePluginState()
{
	if (bZoomEnabled) 
	{
		bZoomEnabled = false;
		document.getElementById("btn_zoom").style.backgroundPositionY = "0px";
	}
	if (bVolumeEnabled) 
	{
		bVolumeEnabled = false;
		document.getElementById("btn_volume").style.backgroundPositionY = "0px";
	}
	if (bMicVolumeEnabled) 
	{
		bMicVolumeEnabled = false;
		document.getElementById("btn_mic_volume").style.backgroundPositionY = "0px";
	}
}

/*
function DOButtonStatusUpdate(firstLoad)
{
	if (status_do_i0 == "0") 
	{
		if (firstLoad != undefined && firstLoad == true) 
		{
			document.getElementById("btn_do_on").style.backgroundPosition = "0px 0px";
			document.getElementById("btn_do_off").style.backgroundPosition = "-24px -36px";
			document.getElementById("btn_do_on").disabled = false;
			document.getElementById("btn_do_off").disabled = true;
		}
		else 
		{
			status_do_i0 = "1";
			document.getElementById("btn_do_on").style.backgroundPosition = "0px -36px";
			document.getElementById("btn_do_off").style.backgroundPosition = "-24px 0px";
			document.getElementById("btn_do_on").disabled = true;
			document.getElementById("btn_do_off").disabled = false;
		}
	}
	else 
	{
		if (firstLoad != undefined && firstLoad == true) 
		{
			document.getElementById("btn_do_on").style.backgroundPosition = "0px -36px";
			document.getElementById("btn_do_off").style.backgroundPosition = "-24px 0px";
			document.getElementById("btn_do_on").disabled = true;
			document.getElementById("btn_do_off").disabled = false;
		}
		else 
		{
			status_do_i0 = "0";
			document.getElementById("btn_do_on").style.backgroundPosition = "0px 0px";
			document.getElementById("btn_do_off").style.backgroundPosition = "-24px -36px";
			document.getElementById("btn_do_on").disabled = false;
			document.getElementById("btn_do_off").disabled = true;
		}
	}
}
*/

var g_offsetTop   = 120;
var g_offsetBtm   = 80;
var g_offsetLeft  = 240;
var g_offsetRight = 60;
//var g_4x3         = false;
var g_aspectRatio = 1;
var g_vsRatio     = 1;

//var fnAutoResize = function() {
//    switchView($("button.viewstyle:eq(1)")[0], 'Auto', true);
//};

/*
//use bForce = true for switchView(Auto) onresize
function switchView(obj, param, bForce)
{
    // 1: 100%, 2: Best-fit, 3: 50%, 4: 25%
    // +------------------------------+
    // | $(window).height();          |
    // | $(window).width();           |
    // | $(document).height();        |
    // | $(document).wdith();         |
    // +------------------------------+
    

    if ("4x3" != param)
    {
        if(0 == getCookie("viewsizemode"))
        {
            setCookie("viewsizemode", param);
        }
        else
        {
            if (param == getCookie("viewsizemode") && bForce == false)
            {
                return; 
            }
            else
            {
                if (param != getCookie("viewsizemode"))
                   setCookie("viewsizemode", param);
            }
        }

        // Reset default state, except "4:3" btn
        $(".viewstyle:gt(0)").attr("disabled", false).each(function(){
            posObj = $(this).css("backgroundPosition").split(" ");
            $(this).css("backgroundPosition", posObj[0] + " 0px");
        });

        // set selected state
        var posObj = $(obj).css("backgroundPosition").split(" ");
        $(obj).css("backgroundPosition", posObj[0] + " -36px").attr("disabled", true);
    }
    
    Log("$(window).height()=" + $(window).height()       +
        ", $(window).width()=" + $(window).width()       +
        ", $(document).height()=" + $(document).height() +
        ", $(document).wdith()=" + $(document).width());

    //Video Server, use D1, 4CIF.. as VideoSize param, so we need to do some modification here.
    if (system_info_firmwareversion.match(/VS/) != null)
    {
        var VideoSizeW = Width;
        var VideoSizeH = Height;
    }
    else
    {
        var VideoSizeW = VideoSize.split('x')[0];
        var VideoSizeH = VideoSize.split('x')[1];
    }

    var bStretch = true;
    var bShowLeftPanel = true;

    // default value: 100%
    var tmpHeight = Height + Y_OFFSET;
    var tmpWidth = Width + X_OFFSET;

    //Got more space when "Control Panel" is hidden
    ($("#ctrl-panel-toggle-icon").hasClass("clicked")) ? g_offsetLeft = 60 : g_offsetLeft = 240;

    // Mainly used for Video Server 4:3 mode! Other models don't need this!
    
    var evalByAspectRatio = function(destVar, srcVar1, srcVar2)
    {
        if (destVar.match(/tmpWidth/) != null)
        {
            if (g_aspectRatio == 1)
            {
                tmpWidth = srcVar1 + X_OFFSET;
            }
            else
            {
                tmpWidth = srcVar2 * g_aspectRatio + X_OFFSET;
            }
        }
        else
        {
            if (g_aspectRatio == 1)
            {
                tmpHeight = srcVar1 + Y_OFFSET;
            }
            else
            {
                tmpHeight = srcVar2 / g_aspectRatio + Y_OFFSET;
            }
        }
    };
    
    switch(param)
    {
        case 'max':
            bStretch = true;
            bShowLeftPanel = false;
            tmpHeight = $(window).height() - g_offsetTop - g_offsetBtm + Y_OFFSET;
            tmpWidth = (tmpHeight - Y_OFFSET) * (Width/Height) + X_OFFSET;
            $(window).unbind("resize");
            break;
        
        case 'Auto':
            bShowLeftPanel = true;

            reserveH = $(window).height() - g_offsetTop - g_offsetBtm;
            reserveW = $(window).width() - g_offsetLeft - g_offsetRight;
            diffH = VideoSizeH - reserveH;
            diffW = VideoSizeW - reserveW;
            
            //Decide to do best-fit according to Width or Height
            if (diffH > 0 && diffH > diffW)
            {
                tmpHeight = reserveH + Y_OFFSET;
                evalByAspectRatio("tmpWidth", (tmpHeight - Y_OFFSET) * (Width/Height), reserveH);

                if (tmpWidth > reserveW)
                {
                    tmpWidth = reserveW + X_OFFSET;
                    evalByAspectRatio("tmpHeight", (tmpWidth - X_OFFSET) * (Height/Width), reserveW);
                }
            }
            else if (diffW > 0 && diffW > diffH)
            {
                tmpWidth = reserveW + X_OFFSET;
                evalByAspectRatio("tmpHeight", (tmpWidth - X_OFFSET) * (Height/Width), reserveW);

                if (tmpHeight > reserveH)
                {
                    tmpHeight = reserveH + Y_OFFSET;
                    evalByAspectRatio("tmpWidth", (tmpHeight - Y_OFFSET) * (Width/Height), reserveH);
                }
            }
            else // availble region is large enough, need not to auto adjust!
            {
                tmpWidth = Width + X_OFFSET;
                evalByAspectRatio("tmpHeight", Height, Width);
            }
            setTimeout("$(window).resize(fnAutoResize);", 500);

        break;

        case '100':
            g_vsRatio = 1;
            bShowLeftPanel = true;
            tmpWidth = Width + X_OFFSET;
            evalByAspectRatio("tmpHeight", Height, Width);
            $(window).unbind("resize");
            break;

        case '50':
            g_vsRatio = 1/2;
            bShowLeftPanel = true;
            tmpWidth = Width/2 + X_OFFSET;
            evalByAspectRatio("tmpHeight", Height/2, Width/2);
            $(window).unbind("resize");
            break;

        case '25':
            g_vsRatio = 1/4;
            bShowLeftPanel = true;
            tmpWidth = Width/4+ X_OFFSET;
            evalByAspectRatio("tmpHeight", Height/4, Width/4);
            $(window).unbind("resize");
            break;
        
        case '4x3':
            bShowLeftPanel = true;
             
            if ("Auto" == getCookie("viewsizemode"))
            {
                tmpHeight = $("#"+PLUGIN_ID).height();
                if (g_aspectRatio == 1) 
                {
                    tmpWidth = (tmpHeight - Y_OFFSET) * (Width/ Height);
                }
                else
                {
                    tmpWidth = parseInt((tmpHeight - Y_OFFSET)* 4 / 3, 10) + X_OFFSET;
                }
            }
            else
            {
                tmpWidth = Width*g_vsRatio + X_OFFSET;
                if (g_aspectRatio == 1) 
                {
                    tmpHeight = Height*g_vsRatio + Y_OFFSET;
                }
                else
                {
                    tmpHeight = parseInt(tmpWidth * 3 / 4, 10) + Y_OFFSET;
                }
            }

            break;
        
        default:
            alert('Do nothing now');
            break;
    }

    if(bIsWinMSIE)
    {
        $("#"+PLUGIN_ID)[0].Stretch = bStretch;
    }

    //(true == bShowLeftPanel) ? $("#sidebar, #logo").show() : $("#sidebar, #logo").hide();
    $("#"+PLUGIN_ID).height(tmpHeight);
    $("#"+PLUGIN_ID).width(tmpWidth);

    layoutAdjudement();
}
*/

function toggleBtnHandler (obj, arg) 
{
    if (arg == "bind")
    {
        addEventSimple(obj, 'mouseover', BtnHandler);
        addEventSimple(obj, 'mouseout', BtnHandler);
        addEventSimple(obj, 'mousedown', BtnHandler);
        addEventSimple(obj, 'mouseup', BtnHandler);
    }
    else if (arg == "unbind")
    {
        removeEventSimple(obj, 'mouseover', BtnHandler);
        removeEventSimple(obj, 'mouseout', BtnHandler);
        removeEventSimple(obj, 'mousedown', BtnHandler);
        removeEventSimple(obj, 'mouseup', BtnHandler);
    }
}

/*
function Toggle4x3()
{
    var object = $("button.viewstyle:eq(0)")[0];
    if ("true" == getCookie("4x3")) 
	{
		object.style.backgroundPosition = "0px 0px";	
        object.title = "Enable 4:3";
        setCookie("4x3", "false");
        g_aspectRatio = 1;

        // bind event handler
        toggleBtnHandler(object, "bind");
        switchView($("button.viewstyle:eq(0)")[0], '4x3', false);
	} 
	else
	{
		object.style.backgroundPosition = "0px -36px";	
        object.title = "Restore default";
        setCookie("4x3", "true");
        g_aspectRatio = 4/3;

        // unbind event handler
        toggleBtnHandler(object, "unbind");
        switchView($("button.viewstyle:eq(0)")[0], '4x3', false);
	}				
}
*/

jQuery.fn.slideLeftHide = function( speed, callback ) { 
    this.animate( { width: "hide", paddingLeft: "hide", paddingRight: "hide", marginLeft: "hide", marginRight: "hide" }, speed, callback ); 
};
jQuery.fn.slideLeftShow = function( speed, callback ) { 
    this.animate( { width: "show", paddingLeft: "show", paddingRight: "show", marginLeft: "show", marginRight: "show" }, speed, callback ); 
};

