var ShowCamCtrl = true;
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();
    CheckCamCtrl();    
    DOButtonStatusUpdate(true);

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

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

    //This way also workable.
    //if ((typeof(RtspVapgCtrl) != "undefined") && (RtspVapgCtrl.Language != undefined)) // for IE
    try
    {
        if (bIsWinMSIE)
        {
            initPluginCallbackFn();
            updateStatus("zoom"); //for ePTZ digital zoom
        }
        else
        {
            document.getElementById("RtspCtrlBtn-bar").style.display = "block";
            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;");

    layoutAdjudement();

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


function initGlobalView()
{
    if (streamsource >= 3)
    {
        if ($("#ROI_Cropbox").css("display") == "block") toggleGV();    
        $("#ptz_control").hide();
    }
    else
    {
        $("#ptz_globalview").show();
        $("#ptz_control").show();
    }
}

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)
{
    initGVZoomHandle(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
    {
        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;
        (streamsource == 3) ? $("#ptz_goto").hide() : $("#ptz_goto").show();
        ShowPresetSelction("digital");
        $("#customcmdBtn-bar").hide();
        initGlobalView(); // $("#ptz_globalview").show();
    }
    
    if(value != getCookie("activatedmode"))
    {
        setCookie("activatedmode", value);
    }
}



function SpecicalCaseHandle()
{
    if( lan >= 100 ) //custom language
           return -1;
    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") 
            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);
    }
}

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 == "mpeg4") 
    eval("AccessName=network_rtsp_s" + streamsource + "_accessname");
    else 
    eval("AccessName=network_http_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;
        STRETCH = "false";

        // The ActiveX plug-in
        RtspVapgCtrlObject.width = W;
        RtspVapgCtrlObject.height = H;

        var Instr = location.hostname;
        var i = Instr.indexOf(":");				
        if (codectype == "mpeg4") 
        {	
            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);
        updateStatus("zoom");
        if(streamsource >= 3)
        	RtspVapgCtrl.DisplayStringOnVideo("", 25, 1, 30, 30, 255, 255, 255, 0, 0, 0);

        setTimeout("RtspVapgCtrl.Connect()", 500);
        //RtspVapgCtrl.Connect();
        setTimeout('$("#StreamSelector").attr("disabled", false)', 3000);
    }
    else if (navigator.appName == "Netscape") 
    {
        if (codectype == "mjpeg") 
        {
            thisURL = document.URL;
            http_method = thisURL.split(":");
            if (http_method[0] == "https") 
            {
                str_innerHTML += "<img src=\"https://" + location.host + "/" + AccessName + "\" width=\"" + Width + "\" height=\"" + Height + "\"/>";
            }
            else 
            {
                str_innerHTML += "<img src=\"http://" + location.host + "/" + AccessName + "\" width=\"" + Width + "\" height=\"" + Height + "\"/>";
            }
        }
        else 
        {
            str_innerHTML += "<embed SCALE=\"ToFit\" 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();
}

function ShowEPTZPanel()
{
    if ($('select[name="ptz_panel_selector"]').selectedValues() == "digital")
    {
        initGlobalView();
        if(bROI_Initialed)
        {
            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");
        //stream3 is not capable of preset-feature
        (streamsource == 3) ? $("#ptz_goto").hide() : $("#ptz_goto").show();
    }
}

/* 
 * 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;
    // Show ZoomRatio after goto some presetlocation!
    setTimeout('updateStatus("zoom")', 1000);    
    Log("Send: %s",CGICmd);
}

function ShowPresetSelction(type)
{
    if (streamsource == 3) 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;
	}
}

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;

    for (var i = 0; i < 5; i++)
    {
        var speedlinkname = eval('uart_i0_speedlink_i' + i + '_name');
        if (speedlinkname)
        {
            document.write("<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>");
        }

    }
}
function layoutAdjudement()
{

    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");
    }    
}

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;
    }
    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 false;
    }
    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";
    }

    if (codectype == "mpeg4")
    {
        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";										
				}															
    }
    else 
    {
        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";     
    }

		
}


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";
}

/***************************************
	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;
		}
	}
}

