var TRUEWIDTH,TRUEHEIGHT;
var BOXWIDTH, BOXHEIGHT; 
var SNWIDTH, SNHEIGHT; 
var MOBILE_WIDTH=176, MOBILE_HEIGHT=144;
var RATIO_X, RATIO_Y;
var JcropObj = null; 
var VIDEO_JPG; //="/cgi-bin/viewer/video.jpg?streamid=3&resolution=400x300&quality=5";
var g_bSmooth = false;

// Interval for refreshImage()
var INTERVAL_snapshot=1000;
var INTERVAL_ROI=5000;

$.ajaxSetup({ async: false }); 
$.getJSON("/cgi-bin/viewer/getparam.cgi?capability_videoin_resolution")
var aResolutionTbl_4x3 = capability_videoin_resolution.split(',').reverse();

function initEPTZParams(type)
{
    if (type == "global_view")
    {
        SNWIDTH=BOXWIDTH=160;
        SNHEIGHT=BOXHEIGHT=120;
    }
    else //cropping_setting & viewing_window
    {
        //in order to let RATIO_X00x1200 mapping to 400x300 correctly, we use 400x300(RATIO_X=4) rather than 320x240(RATIO_X=5)
        SNWIDTH=BOXWIDTH=400;
        SNHEIGHT=BOXHEIGHT=300;
    }
    
    if (type == "cropping_setting")  //cropping setting always use fullsize
    {
        TRUEWIDTH=1600;
        TRUEHEIGHT=1200;
    }
    else
    {
        if (videoin_c0_options == "framerate") 
        {
            TRUEWIDTH=800;
            TRUEHEIGHT=600;
        }
        else if (videoin_c0_options == "quality") 
        {
            TRUEWIDTH=1600;
            TRUEHEIGHT=1200;
        }
        else if (videoin_c0_options == "crop") //normalize BOXWIDTH & BOXHEIGHT to fit the window
        {
            TRUEWIDTH=videoin_c0_crop_size.split('x')[0];
            TRUEHEIGHT=videoin_c0_crop_size.split('x')[1];
            if (BOXWIDTH * TRUEHEIGHT <= BOXHEIGHT * TRUEWIDTH)
            {
                SNHEIGHT=BOXHEIGHT=parseInt(BOXWIDTH * TRUEHEIGHT / TRUEWIDTH);
            } 
            else
            {
                BOXWIDTH=parseInt(BOXHEIGHT * TRUEWIDTH / TRUEHEIGHT);
                if (type == "viewing_window")  //cropping setting always use fullsize
                {
                    SNWIDTH = 400
                    SNHEIGHT=parseInt(SNWIDTH * TRUEHEIGHT / TRUEWIDTH);
                }
                else
                {
                    SNWIDTH=160;
                    SNHEIGHT=parseInt(SNWIDTH * TRUEHEIGHT / TRUEWIDTH);
                }
            }
        }
    }
    VIDEO_JPG="/cgi-bin/viewer/video.jpg?streamid=3&resolution="+ SNWIDTH +"x"+ SNHEIGHT +"&quality=5";

    RATIO_X = TRUEWIDTH/BOXWIDTH;
    RATIO_Y = TRUEHEIGHT/BOXHEIGHT;
}

var bImgLoaded = true;
function refreshImage(video_jpg)
{
    //Ensure GV show image in the order of timestamp
    if (bImgLoaded == false) return;
    var img = new Image();
    var date = new Date();

    img.onload = function(){
        bImgLoaded = true;
        $('.jcrop-hline:eq(0)').prev().attr('src', img.src);
        $("#cropbox").attr('src', img.src);
        //Log("Snapshot completed on : %s",date);
        imgComplete();
    };
    img.onerror = function(){ imgComplete(); };
    img.onabort = function(){ imgComplete(); };

    imgComplete = function(){
        img.onload=null;
        img.onerror=null;
        img.onabort = null;
        img = null; //add this line to prevent memory leak?
        bImgLoaded = true;
        //Log("Snapshot completed on : %s",date);
    };

    img.src = video_jpg + "&date=" + date;
    bImgLoaded = false;
}

function ePTZControl(movetype, param)
{
    if(JcropObj && g_bSmooth) //used in Index.html
    {
        g_bPreventResend = false;
        var coordsData;
        var panspeed  = (parseInt($("#camctrl_c0_panspeed").val()) + 6)*RATIO_X;
        var tiltspeed = (parseInt($("#camctrl_c0_tiltspeed").val()) + 6)*RATIO_X;
        var zoomspeed = 1.05 + (parseInt($("#camctrl_c0_zoomspeed").val()) + 6)*0.05; // -5 ~ +5 : 1.05 ~ 1.55

        var now_coords = JcropObj.tellSelect(); 
        now_x = now_coords.x;
        now_y = now_coords.y;
        now_w = now_coords.w;
        now_h = now_coords.h;

        if (movetype == "move")
        {
            switch( param)
            {
                case "up":
                    correct_y = parseInt(now_y - tiltspeed);
                    if (correct_y <= 0 ) correct_y = 0;
                        coordsData = "x=" + now_x + "&y=" + correct_y + "&w=" + now_w + "&h=" + now_h;
                    break;
                case "down":
                    correct_y = parseInt(now_y + tiltspeed);
                    if ((correct_y + now_h) >= 1200) correct_y = 1200 - now_h; 
                        coordsData = "x=" + now_x + "&y=" + correct_y + "&w=" + now_w + "&h=" + now_h;
                    break;
                case "left":
                    correct_x = parseInt(now_x - panspeed);
                    if (correct_x <= 0 ) correct_x = 0;
                        coordsData = "x=" + correct_x + "&y=" + now_y + "&w=" + now_w + "&h=" + now_h;
                    break;
                case "right":
                    correct_x = parseInt(now_x + panspeed);
                    if ((correct_x + now_w) >= 1600) correct_x = 1600 - now_w; 
                        coordsData = "x=" + correct_x + "&y=" + now_y + "&w=" + now_w + "&h=" + now_h;
                    break;
                case "home":
                    coordsData = "x=" + ROI_X + "&y=" + ROI_Y + "&w=" + ROI_W + "&h=" + ROI_H;
                    break;
            } 
        }
        else if(movetype == 'zoom')
        {
            switch (param)
            {
                case "wide":
                    coordsData = "x=" + parseInt(now_x - now_w*(zoomspeed-1)/2) + 
                                "&y=" + parseInt(now_y - now_h*(zoomspeed-1)/2) + 
                                "&w=" + parseInt(now_w * zoomspeed) + 
                                "&h=" + parseInt(now_h * zoomspeed);
                        break;
                case "tele":
                    coordsData = "x=" + parseInt(now_x + now_w*(zoomspeed-1)/2) + 
                                "&y=" + parseInt(now_y + now_h*(zoomspeed-1)/2) + 
                                "&w=" + parseInt(now_w / zoomspeed) + 
                                "&h=" + parseInt(now_h / zoomspeed);
                    dZoomRatio = VideoSize.split('x')[0] / parseInt(now_w / zoomspeed);
                    if (dZoomRatio >= 4) { Log("dZoomRatio = %d >= 4",dZoomRatio); return; } //At most 4X digital-zoom
                    break;
            }
        }
        else if (movetype == "auto")
        {	
            var CGICmd='/cgi-bin/camctrl/eCamCtrl.cgi?stream=' + streamsource + '&auto=' + param;
            parent.retframe.location.href=CGICmd;
            Log("Send: %s", CGICmd);
            return;
        }
        Log("Smooth moving to %s", coordsData);
        g_bRefreshROI = false; //add this to force smooth moving work
        parseCoords(coordsData.replace(/&/g,",")); //coordsData example=> x=170&y=80&w=640&h=480
    }
    else //non-Smooth
    {
        g_bPreventResend = true;
        CGICmd='/cgi-bin/camctrl/eCamCtrl.cgi?stream=' + streamsource + '&' + movetype + '=' + param;

        Log("SEND: %s",CGICmd);
        $.ajax({
            url: CGICmd,
            cache: false,
            async: true, 
            success: function(data){
                Log("Return value from ePTZ.cgi => %s",data);
                if (JcropObj && movetype != 'auto')
                {
                    g_bRefreshROI = false; //add this to execute JcropObj.setSelect rather than JcropObj.animateTo
                    parseCoords(data); 
                }
                DisplayZoomRatio(data);
            }
        });
    }
}


var dZoomRatio = 1;
function DisplayZoomRatio(data)
{
    //if (eptz_c0_osdzoom == 0) return;
    if(typeof(RtspVapgCtrl) != "undefined" && eptz_c0_osdzoom == 1) // for IE
    {
        var coords = data.split(',');
        NewVideoSize_W = parseInt(coords[2].split('=')[1]);
        dZoomRatio = VideoSize.split('x')[0] / NewVideoSize_W;
        Log("dZoomRatio = %f", dZoomRatio);

        //RtspVapgCtrl.DisplayStringOnVideo param
        zoomText = "x" + dZoomRatio.toFixed(1);
        fonttSize = 25;
        eFontStyle = 1; //Regular:0, Bold:1, Italic:2, Underline:4, Strikeout:8
        X = 30;
        Y = 30;
        fontColorR = 255;
        fontColorG = 255;
        fontColorB = 255;
        outlineColorR = 0;
        outlineColorG = 0;
        outlineColorB = 0;

        if(dZoomRatio > 1) // for IE
        {
            RtspVapgCtrl.DisplayStringOnVideo(zoomText, fonttSize, eFontStyle, X, Y, fontColorR, fontColorG, fontColorB, outlineColorR, outlineColorG, outlineColorB);
        }
        else
        {
            RtspVapgCtrl.DisplayStringOnVideo("", fonttSize, eFontStyle, X, Y, fontColorR, fontColorG, fontColorB, outlineColorR, outlineColorG, outlineColorB);
        }
    }
}

function updateStatus(type)
{
   $.ajax({
       url: "/cgi-bin/camctrl/eCamCtrl.cgi?stream=" + streamsource,
       async: true,
       cache: false,
       success: function(data){
           Log("[updateStatus] return => %s",data);
           if (type == "zoom")
               DisplayZoomRatio(data);
           else
               parseCoords(data); //Also upate the latest ROI for GlobalView 
       }
    });
}

function Normalize(num, multiple)
{
    return parseInt(num/multiple)*multiple;
}
