var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var currRecord;
var oriFormat;
var oriAudio;
var oriFormatList;
var isZavio = false;
var isAxis = false;
var isVivo = false;
var isActi = false;
var isAlpha2 = false;
var isPanasonic = false;
var isSony = false;
var excCode;
var extraData = new Array();
var actiDialog;

var PTZType = { acti: [ ["Fixed", "0"], ["5xxx(Kampro)", "1"], ["6100(Pelco-D)", "2"], ["6100(Pelco-P)", "3"], ["6100(VCL)", "4"], ["6200(EyeView)", "5"], ["6200(Pelco-D)", "6"], ["6200(Pelco-P)", "7"], ["65xx(DynaColor)", "8"], ["66xx(DynaColor)", "9"], ["Pelco-D", "10"], ["Pelco-P", "11"], ["DynaColor", "12"] ] };
var PTZBaudRate = { acti: [ ["1200", "1200"], ["2400", "2400"], ["4800", "4800"], ["9600", "9600"], ["19200", "19200"], ["38400", "38400"], ["57600", "57600"], ["115200", "115200"], ["230400", "230400"] ] };
var PTZAddress = { acti: [ ["00", "00"], ["01", "01"], ["02", "02"], ["03", "03"], ["04", "04"], ["05", "05"], ["06", "06"], ["07", "07"], ["08", "08"], ["09", "09"], ["10", "10"], ["11", "11"], ["12", "12"], ["13", "13"], ["14", "14"], ["15", "15"], ["16", "16"] ] };

function parseParam(xml)
{
    oriFormat = undefined;
    oriFormatList = 0;
    oriAudio = false;
    isZavio = false;
    isAxis = false;
    isVivo = false;
    isActi = false;
    isPanasonic = false;
    isAlpha2 = false;
    isSony = false;

    excCode = undefined;
    try
    {
        disableSubmitButton(true);

        if (xml == undefined)
        {
            return false;
        }
    
        var xmlNode = xml.getElementsByTagName("IPCamera");
        if (xmlNode == undefined || xmlNode.length < 1)
        {
            return false;
        }
        var chNode = xmlNode[0].getElementsByTagName("ChannelIndex");
        if (chNode == undefined || chNode.length < 1 || chNode[0].firstChild == undefined)
        {
            return false;
        }
        var ch = parseInt(chNode[0].firstChild.nodeValue, 10);
        if (ch <0)
        {
            return false;
        }
        currRecord["ChannelIndex"] = ch;
    
        var videoNode = xmlNode[0].getElementsByTagName("VideoParam");
        if (videoNode == undefined || videoNode.length < 1)
        {
            return false;
        }
    
        if (videoNode[0].firstChild && videoNode[0].firstChild.nodeValue && videoNode[0].firstChild.nodeValue == "Empty")
        {
            //alert("VideoParam Empty!");
            resetForm();
            return false;
        }

        var vflNode = videoNode[0].getElementsByTagName("VideoFormatList");
        if (vflNode != undefined && vflNode.length >0 && vflNode[0].firstChild && vflNode[0].firstChild.nodeValue)
        {
            vflValue = parseInt(vflNode[0].firstChild.nodeValue, 10);

            if (vflValue == undefined)
            {
                //alert("error for videofmt");
            }
            if (0 == (vflValue & 1))
            {
                Dom.get("videoFmtJ").disabled = true;
                Dom.get("videoFmtJ").checked = false;
                oriFormatList = 0;
            }
            else
            {
                Dom.get("videoFmtJ").disabled = false;
                Dom.get("videoFmtJ").checked = false;
                oriFormatList = 1;
            }
            if (0 == (vflValue & 2))
            {
                Dom.get("videoFmtM").disabled = true;
                Dom.get("videoFmtM").checked = false;
            }
            else
            {
                Dom.get("videoFmtM").disabled = false;
                Dom.get("videoFmtM").checked = false;
                oriFormatList = oriFormatList | 2;
            }
        }
        var vfvNode = videoNode[0].getElementsByTagName("VideoFormatValue");
        if (vfvNode != undefined && vfvNode.length >0 && vfvNode[0].firstChild && vfvNode[0].firstChild.nodeValue)
        {
            var vfvValue = parseInt(vfvNode[0].firstChild.nodeValue, 10);
            if (1 == vfvValue)
            {
                Dom.get("videoFmtJ").checked = false;
                Dom.get("videoFmtM").checked = true;
                oriFormat = "videoFmtM";
            }
            else if (0 == vfvValue)
            {
                Dom.get("videoFmtJ").checked = true;
                Dom.get("videoFmtM").checked = false;
                oriFormat = "videoFmtJ";
            }
        }

        var fnlNode = videoNode[0].getElementsByTagName("FramerateNameList");
        if (fnlNode != undefined && fnlNode.length >0 && fnlNode[0].firstChild && fnlNode[0].firstChild.nodeValue)
        {
            Dom.get("frameRateSelect").disabled = false;
            var s = fnlNode[0].firstChild.nodeValue.split(";");
            var select = Dom.get("frameRateSelect");
            if (select != undefined && s != undefined)
            {
                select.options.length = s.length;
                for (var i=0; i<s.length; i++)
                {
                    select.options[i] = new Option(s[i], "-1");
                }
            }
        }
        else
        {
            var select = Dom.get("frameRateSelect");
            if (select != undefined && select.options != undefined)
            {
                if (select.options.length)
                {
                    select.options.length = 0;
                }
            }

            Dom.get("frameRateSelect").disabled = true;
        }

        var fvlNode = videoNode[0].getElementsByTagName("FramerateValueList");
        if (fvlNode != undefined && fvlNode.length >0 && fvlNode[0].firstChild && fvlNode[0].firstChild.nodeValue)
        {
            var s = fvlNode[0].firstChild.nodeValue.split(";");
            var select = Dom.get("frameRateSelect");
            if (select != undefined && s != undefined)
            {
                for (var i=0; i<select.options.length; i++)
                {
                    select.options[i].value = s[i];
                }
            }
        }
        var fvNode = videoNode[0].getElementsByTagName("FramerateValue");
        if (fvNode != undefined && fvNode.length >0 && fvNode[0].firstChild && fvNode[0].firstChild.nodeValue)
        {
            //var selectedIdx = parseInt(fvNode[0].firstChild.nodeValue, 10);
            var selectedIdx = fvNode[0].firstChild.nodeValue;
            var options = Dom.get("frameRateSelect").options;
            if (options != undefined)
            {
                for (var i=0; i<options.length; i++)
                {
                    if (selectedIdx == options[i].value)
                    {
                        Dom.get("frameRateSelect").selectedIndex = i;
                    }
                }
            }
        }

        var rnlNode = videoNode[0].getElementsByTagName("ResolutionNameList");
        if (rnlNode != undefined && rnlNode.length >0 && rnlNode[0].firstChild && rnlNode[0].firstChild.nodeValue)
        {
            Dom.get("resolutionSelect").disabled = false;
            var s = rnlNode[0].firstChild.nodeValue.split(";");
            var select = Dom.get("resolutionSelect");
            if (select != undefined && s != undefined)
            {
                select.options.length = s.length;
                for (var i=0; i<s.length; i++)
                {
                    select.options[i] = new Option(s[i], "-1");
                }
            }
        }
        else
        {
            var select = Dom.get("resolutionSelect");
            if (select != undefined && select.options != undefined)
            {
                if (select.options.length)
                {
                    select.options.length = 0;
                }
            }

            Dom.get("resolutionSelect").disabled = true;
        }

        var rvlNode = videoNode[0].getElementsByTagName("ResolutionValueList");
        if (rvlNode != undefined && rvlNode.length >0 &&  rvlNode[0].firstChild && rvlNode[0].firstChild.nodeValue)
        {
            var s = rvlNode[0].firstChild.nodeValue.split(";");
            var select = Dom.get("resolutionSelect");
            if (select != undefined && s != undefined)
            {
                for (var i=0; i<select.options.length; i++)
                {
                    select.options[i].value = s[i];
                }
            }
        }
        var rvNode = videoNode[0].getElementsByTagName("ResolutionValue");
        if (rvNode != undefined && rvNode.length >0 && rvNode[0].firstChild && rvNode[0].firstChild.nodeValue)
        {
            var selectedValue = rvNode[0].firstChild.nodeValue;
            var options = Dom.get("resolutionSelect").options;
            if (options != undefined)
            {
                for (var i=0; i<options.length; i++)
                {
                    if (selectedValue == options[i].value)
                    {
                        Dom.get("resolutionSelect").selectedIndex = i;
                    }
                }
            }
        }

        var qtnNode = videoNode[0].getElementsByTagName("QualityTagName");
        if (qtnNode != undefined && qtnNode.length >0 && qtnNode[0].firstChild && qtnNode[0].firstChild.nodeValue)
        {
            var tagNode = Dom.get("qualityTagName");
            if (tagNode!=undefined)
            {
                try {
                    var targetDisplay = qtnNode[0].firstChild.nodeValue;
                    tagNode.innerHTML = targetDisplay;
                } catch (e) {}
            }
        }

        var qnlNode = videoNode[0].getElementsByTagName("QualityNameList");
        if (qnlNode != undefined && qnlNode.length >0 && qnlNode[0].firstChild && qnlNode[0].firstChild.nodeValue)
        {
            Dom.get("compressionSelect").disabled = false;
            var s = qnlNode[0].firstChild.nodeValue.split(";");
            var select = Dom.get("compressionSelect");
            if (select != undefined && s != undefined)
            {
                select.options.length = s.length;
                for (var i=0; i<s.length; i++)
                {
                    select.options[i] = new Option(s[i], "-1");
                }
            }
        }
        else
        {
            var select = Dom.get("compressionSelect");
            if (select != undefined && select.options != undefined)
            {
                if (select.options.length)
                {
                    select.options.length = 0;
                }
            }
            Dom.get("compressionSelect").disabled = true;
        }

        var qvlNode = videoNode[0].getElementsByTagName("QualityValueList");
        if (qvlNode != undefined && qvlNode.length >0 && qvlNode[0].firstChild && qvlNode[0].firstChild.nodeValue)
        {
            var s = qvlNode[0].firstChild.nodeValue.split(";");
            var select = Dom.get("compressionSelect");
            if (select != undefined && s != undefined)
            {
                for (var i=0; i<select.options.length; i++)
                {
                    select.options[i].value = s[i];
                }
            }
        }
        var qvNode = videoNode[0].getElementsByTagName("QualityValue");
        if (qvNode != undefined && qvNode.length >0 && qvNode[0].firstChild && qvNode[0].firstChild.nodeValue)
        {
            var selectedValue = qvNode[0].firstChild.nodeValue;
            var options = Dom.get("compressionSelect").options;
            if (options != undefined)
            {
                for (var i=0; i<options.length; i++)
                {
                    if (selectedValue == options[i].value)
                    {
                        Dom.get("compressionSelect").selectedIndex = i;
                    }
                }
            }
        }

        var eaudioNode = videoNode[0].getElementsByTagName("EnableAudio");
        if (eaudioNode != undefined && eaudioNode.length >0)
        {
            Dom.get("audioChk").disabled = false;
            if (eaudioNode[0].firstChild && parseInt(eaudioNode[0].firstChild.nodeValue, 10)>0)
            {
                Dom.get("audioChk").checked = true;
                oriAudio = true;
            }
            else
            {
                Dom.get("audioChk").checked = false;
                oriAudio = false;
            }
        }
        else
        {
            Dom.get("audioChk").checked = false;
            oriAudio = false;
        }
        var audioNode = videoNode[0].getElementsByTagName("HasAudio");
        if (audioNode != undefined && audioNode.length >0)
        {
            if (audioNode[0] != undefined && audioNode[0].firstChild && parseInt(audioNode[0].firstChild.nodeValue, 10) > 0)
            {
                Dom.get("audioChk").disabled = false;
            }
            else
            {
                Dom.get("audioChk").disabled = true;
            }
        }
        else
        {
            Dom.get("audioChk").disabled = true;
        }

        var macodeNode = videoNode[0].getElementsByTagName("MACODE");
        if (macodeNode != undefined && macodeNode.length>0)
        {
            if (macodeNode[0] !=undefined && macodeNode[0].firstChild != undefined && macodeNode[0].firstChild.nodeValue != undefined)
            {
                var macode = parseInt(macodeNode[0].firstChild.nodeValue, 10);
                if (macode == 7)
                {
                    isZavio = true;
                }
                else if (macode == 1)
                {
                    isAxis = true;
                }
                else if (macode == 4)
                {
                    isVivo = true;
                }
                else if (macode == 11)
                {
                    isActi = true;
                }
                else if (macode == 10)
                {
                    isPanasonic = true;
                }
                else if (macode == 12)
                {
                    isAlpha2 = true;
                }
                else if (macode == 2)
                {
                    isSony = true;
                }
            }
        }
        else
        {
            isAxis = false;
            isZavio = false;
            isVivo = false;
            isActi = false;
            isPanasonic = false;
            isAlpha2 = false;
            isSony = false;
        }

        var exccodeNode = videoNode[0].getElementsByTagName("EXCCODE");
        if (exccodeNode != undefined && exccodeNode.length>0)
        {
            if (exccodeNode[0] !=undefined && exccodeNode[0].firstChild != undefined && exccodeNode[0].firstChild.nodeValue != undefined)
            {
                exccode = parseInt(exccodeNode[0].firstChild.nodeValue, 10);
            }
        }
        else
        {
            exccode = undefined;
        }

        extraData = [];
        if (isActi)
        {
            var extraDataNode = videoNode[0].getElementsByTagName("EXTRADATA");
            if (extraDataNode!=undefined && extraDataNode.length>0)
            {
                if (extraDataNode[0] !=undefined && extraDataNode[0].firstChild != undefined && extraDataNode[0].firstChild.nodeValue != undefined)
                {
                    extraData = extraDataNode[0].firstChild.nodeValue.split(";");
                }
            }
        }

        var mp4Radio = Dom.get('videoFmtM');
        var mjRadio = Dom.get('videoFmtJ');
        if (mp4Radio!=undefined && mp4Radio.checked)
        {
            mp4Radio.click();
        }
        else if (mjRadio!=undefined && mjRadio.checked)
        {
            mjRadio.click();
        }
    }
    catch(e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
        lockPannel.hide();
    }

    try {
        var ddm = Dom.get("showptzdialog");
        if (ddm!=undefined)
        {
            if (isActi)
            {
                Dom.setStyle(ddm, "display", "block");
                Dom.setStyle(ddm, "visibility", "visible");
            }
            else
            {
                Dom.setStyle(ddm, "display", "none");
                Dom.setStyle(ddm, "visibility", "hidden");
            }
        }
    } catch (e) { errorReport(e); }

    disableSubmitButton(false);
}

function handleGetParameterSuccess(o)
{
    if(o.responseText !== undefined)
    {
        if (o.status == "200")
        {
            parseParam( o.responseXML );
        }
        else if (o.status == "401")
        {
            handleSessionTimeout();        
        }
        else
        {
            //alert(o.status);
            //alert(o.getAllResponseHeaders);
        }
    }
    lockPannel.hide();
}

function handleGetParameterFailure(o)
{
    if (o.status == "401")
    {
        handleSessionTimeout();
        return;
    }
    alert("Get video paramenters failed!");
    lockPannel.hide();
}

function setFrom(oRecord)
{
    try
    {
        disableSubmitButton(true);
        if (oRecord == undefined)
        {
            lockPannel.hide();
            return;
        }
    
        var oData = oRecord.getData();
        if (oData == undefined)
        {
            lockPannel.hide();
            return;
        }
    
        var x = Dom.get("form_ChannelIndex");
        if (x!=undefined)
        {
            x.value = oData["ChannelIndex"];
        }
    
        x = Dom.get("form_CameraName");
        if (x!=undefined)
        {
            x.innerHTML = oData["CameraName"];
        }
    
        var callback =
        {
            success: handleGetParameterSuccess,
            failure: handleGetParameterFailure
        };
    
        if (parseInt(oData["ChannelIndex"], 10) >0)
        {
            var url = "/CGI/cgi_main?cmd=videoparam&ChannelIndex=" + (parseInt(oData["ChannelIndex"], 10) -1) + "&rand=" + Math.floor(Math.random()*1000);
            YAHOO.util.Connect.asyncRequest("GET", url, callback);
        }
    
        currRecord = oRecord;
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }    
}

function resetData()
{
    lockPannel.show();
    setFrom(currRecord);
}

function disableSubmitButton(isDisabled)
{
    var btnEl = Dom.get("saveBTN");
    if (btnEl == undefined)
        return;

    if (isDisabled)
    {
        //Event.addListener("saveBTN", 'mouseout', function() {return false;});
        //Event.addListener("saveBTN", 'mouseover', function() {return false;});
        //Dom.removeClass(btnEl, "buttonOverShort");
        //Dom.removeClass(btnEl, "buttonNormalShort");
        //Dom.addClass(btnEl, "buttonDisableShort");
        //btnEl.style['cursor'] = 'default';
        btnEl.disabled = true;
    }
    else
    {
        //Event.addListener("saveBTN", 'mouseout', function() {replaceClass(this, 'buttonOverShort', 'buttonNormalShort');});
        //Event.addListener("saveBTN", 'mouseover',function() {replaceClass(this, 'buttonNormalShort', 'buttonOverShort');});
        //Dom.addClass(btnEl, "buttonNormalShort");
        //Dom.removeClass(btnEl, "buttonDisableShort");
        //btnEl.style['cursor'] = 'pointer';
        btnEl.disabled = false;
    }
}
function submitSave()
{
    var btnEl = Dom.get("saveBTN");
    if (btnEl == undefined)
        return;

    var isDisabled = btnEl.disabled; //Dom.hasClass(btnEl, 'buttonDisableShort');
    if (isDisabled)
    {
        alert('button disabled!');
        return;
    }

    if (document.form0.ChannelIndex.value < 0)
    {
        alert("You should select a camera to modyfy first!");
        return;
    }
    //alert("Try to submit~");
    var callback =
    {
        success: handleSuccess,
        failure: handleFailure
    };

    var theForm = document.form0;
    if (theForm == undefined)
    {
        //alert("Something error!");
        return;
    }
    var postData = "";
    var chidx = parseInt(theForm.ChannelIndex.value, 10) - 1;
    postData += "ChannelIndex=" + encodeURIComponent(chidx);
    var vfmt;
    if (theForm.videoFmt[0].checked)
        vfmt = 0;//theForm.videoFmt[0].value;
    else if (theForm.videoFmt[1].checked)
        vfmt = 1;//theForm.videoFmt[1].value;
    else
        vfmt = -1;
    if (vfmt!=-1)
        postData += "&VideoFormat=" + encodeURIComponent(vfmt);
    if (!theForm.frameRateSelect.disabled)
        postData += "&Framerate=" + encodeURIComponent(theForm.frameRateSelect.options[theForm.frameRateSelect.options.selectedIndex].value);
    if (!theForm.resolutionSelect.disabled)
        postData += "&Resolution=" + encodeURIComponent(theForm.resolutionSelect.options[theForm.resolutionSelect.options.selectedIndex].value);
    if (!theForm.compressionSelect.disabled)
        postData += "&Quality=" + encodeURIComponent(theForm.compressionSelect.options[theForm.compressionSelect.options.selectedIndex].value);
    if (! theForm.audio.disabled)
    {
        postData += "&EnableAudio=" + encodeURIComponent((theForm.audio.checked ? "1" : "0"));
    }
    //postData += "&xml=1";


    //document.getElementById("debugarea").innerHTML = postData;
    //alert(postData);
    //alert(document.form0.action);
    lockPannel.show();
    YAHOO.util.Connect.asyncRequest("POST", theForm.action, callback, postData);
    //document.form0.ChannelIndex.value = "-1";
    //myDataSource.flushCache();
    disableSubmitButton(true);
}

function handleSuccess(o)
{
    //alert("handleSuccess");
    if(o.responseText !== undefined)
    {
        if (o.status == "200")
        {
            //alert(o.responseText);
            if (o.responseText.match(/OK/))
            {
                alert("Update camera parameters successfully!");

                try {
                    var rs = myDataTable.getRecordSet();
                    if (rs!=undefined)
                    {
                        var selected = myDataTable.getSelectedRows();
                        if (selected!=undefined && selected.length>0)
                        {
                            var record = rs.getRecord(selected[0]);
                            if (record!=undefined)
                            {
                                lockPannel.show();
                                setFrom(record);
                            }
                        }
                    }
                } catch (e) { errorReport(e); }
            }
            else
            {
                //alert("Update camera parameters failed!(" + o.responseText  + ")");
                alert("Update camera parameters failed!");
            }
        }
        else if (o.status == "401")
        {
            handleSessionTimeout();
        }
        else
        {
            //alert(o.status);
            //alert(o.getAllResponseHeaders);
            alert("Update camera parameters failed!");
        }
    }
    lockPannel.hide();
}

function handleFailure(o)
{
    if (o.status == "401")
    {
        handleSessionTimeout();
        return;
    }
    alert("Update camera parameters failed!!!");
    lockPannel.hide();
    //alert("handleFailure");
    //alert("Submission failed: " + o.status);
    //alert(o.getAllResponseHeaders);
}

function onAudioClick(ev)
{
    if (!isActi)
        return;

    var target = Event.getTarget(ev);
    if (target == undefined)
        return;

    if (target.disabled)
        return;
try {
    if (target.checked == oriAudio)
    {
        Dom.get("frameRateSelect").disabled = false; Dom.get("resolutionSelect").disabled = false; Dom.get("compressionSelect").disabled = false;
        Dom.get("videoFmtJ").disabled = true; Dom.get("videoFmtM").disabled = true;
        if (oriFormatList & 1)
        {
            Dom.get("videoFmtJ").disabled = false;
        }
        if (oriFormatList & 2)
        {
            Dom.get("videoFmtM").disabled = false;
        }
    }
    else
    {
        Dom.get("frameRateSelect").disabled = true; Dom.get("resolutionSelect").disabled = true; Dom.get("compressionSelect").disabled = true;
        Dom.get("videoFmtJ").disabled = true; Dom.get("videoFmtM").disabled = true;
    }
} catch (e) { errorReport(e); }    
}

function onFormatClick(ev)
{
    if (!isZavio && !isAxis && !isVivo && !isActi && !isPanasonic && !isAlpha2 && !isSony)
        return;

    var target = Event.getTarget(ev);

    if (target == undefined)
        return;
try {
    // please refer to cgi to know why to do so
    if (isZavio)
    {
        if (exccode == 1)
        {
            if (oriFormat == undefined)
                return;

            if (target.id == oriFormat)
            {
                Dom.get("frameRateSelect").disabled = false;
                Dom.get("resolutionSelect").disabled = false;
                Dom.get("compressionSelect").disabled = false;
                Dom.get("audioChk").disabled = false;
            }
            else
            {
                Dom.get("frameRateSelect").disabled = true;
                Dom.get("resolutionSelect").disabled = true;
                Dom.get("compressionSelect").disabled = true;
                Dom.get("audioChk").disabled = true;
            }
        }
    } else if (isAxis)
    {
        if (exccode == 1)
        {
            if (target.id == 'videoFmtJ')
            {
                Dom.get("audioChk").disabled = false;
                Dom.get("audioChk").checked = false;
                Dom.get("audioChk").disabled = true;
            }
            else
            {
                Dom.get("audioChk").disabled = false;
                Dom.get("audioChk").checked = oriAudio;
            }
        }
    } else if (isVivo)
    {
        if (exccode == 1) // ip7138/ip7139/DCS-3110 no mega in mpeg4
        {
            var resSelect = document.form0.resolutionSelect;
            var resOptions = document.form0.resolutionSelect.options;
            if (resSelect == undefined || resOptions == undefined || resOptions.length<1)
                return;
            if (target.id == 'videoFmtJ')
            {
                var hasMega = false;
                for (var x=0; x<resOptions.length; x++)
                {
                    if (resOptions[x].text == "1280x1024")
                    {
                        hasMega = true;
                        break;
                    }
                }
                if (!hasMega)
                {
                    resOptions[resOptions.length] =  new Option("1280x1024", "5");
                }
            }
            else
            {
                for (var x=0; x<resOptions.length; x++)
                {
                    if (resOptions[x].text == "1280x1024")
                    {
                        resOptions[x] = null;
                        break;
                    }
                }
            }
        }
        if (exccode == 1 || exccode == 2) // iz7151/IP7138/IP7139/DCS-3110/DCS-5610/DCS-3415
        {
            if (target.id == 'videoFmtJ')
            {
                Dom.get("audioChk").disabled = false;
                Dom.get("audioChk").checked = false;
                Dom.get("audioChk").disabled = true;
            }
            else
            {
                Dom.get("audioChk").disabled = false;
                Dom.get("audioChk").checked = oriAudio;
            }
        }
    } else if (isActi)
    {
        if (oriFormat == undefined)
            return;

        if (target.id == oriFormat)
        {
            Dom.get("frameRateSelect").disabled = false;
            Dom.get("resolutionSelect").disabled = false;
            Dom.get("compressionSelect").disabled = false;
            Dom.get("audioChk").disabled = false;
        }
        else
        {
            Dom.get("frameRateSelect").disabled = true;
            Dom.get("resolutionSelect").disabled = true;
            Dom.get("compressionSelect").disabled = true;
            Dom.get("audioChk").disabled = true;
        }
    } else if (isPanasonic)
    {
        if (target.id == 'videoFmtJ')
        {
            Dom.get("frameRateSelect").disabled = false;
        }
        else
        {
            Dom.get("frameRateSelect").disabled = true;
        }
    } else if (isAlpha2)
    {
        if (exccode == 1)
        {
            if (oriFormat == undefined)
                return;

            if (target.id == oriFormat)
            {
                Dom.get("compressionSelect").disabled = false;
            }
            else
            {
                Dom.get("compressionSelect").disabled = true;
            }
        }
        else if (exccode == 2)
        {
            if (oriFormat != undefined)
            {
                if (target.id == oriFormat)
                {
                    Dom.get("compressionSelect").disabled = false;
                }
                else
                {
                    Dom.get("compressionSelect").disabled = true;
                }
            }

            var resSelect = document.form0.resolutionSelect;
            var resOptions = document.form0.resolutionSelect.options;
            if (resSelect == undefined || resOptions == undefined || resOptions.length<1)
                return;
            if (target.id == 'videoFmtJ')
            {
                var hasMega = false;
                for (var x=0; x<resOptions.length; x++)
                {
                    if (resOptions[x].text == "1280x1024")
                    {
                        hasMega = true;
                        break;
                    }
                }
                if (!hasMega)
                {
                    resOptions[resOptions.length] =  new Option("1280x1024", "1280x1024");
                }
            }
            else
            {
                for (var x=0; x<resOptions.length; x++)
                {
                    if (resOptions[x].text == "1280x1024")
                    {
                        resOptions[x] = null;
                        break;
                    }
                }
            }
        }
    } else if (isSony)
    {
        if (exccode >=1 && exccode <=4)
        {
            if (oriFormat != undefined)
            {
                if (target.id == oriFormat)
                {
                    Dom.get("compressionSelect").disabled = false;
                }
                else
                {
                    Dom.get("compressionSelect").disabled = true;
                }
            }
        }

        if (exccode<4)
        {
            var resSelect = document.form0.resolutionSelect;
            var resOptions = document.form0.resolutionSelect.options;
            if (resSelect == undefined || resOptions == undefined || resOptions.length<2)
                return;

            if (exccode == 2)
            {
                if (target.id == 'videoFmtJ')
                {
                    var hasElem1 = false;
                    var hasElem2 = false;
                    var hasElem3 = false;
                    for (var x=0; x<resOptions.length; x++)
                    {
                        if (resOptions[x].text == "768x576")
                        {
                            hasElem3 = true;
                        } else if (resOptions[x].text == "960x720")
                        {
                            hasElem2 = true;
                        } else if (resOptions[x].text == "1280x960")
                        {
                            hasElem1 = true;
                        }
                    }
                    if (!hasElem3)
                    {
                        resOptions[resOptions.length] =  new Option("768x576", "768,0");
                    }
                    if (!hasElem2)
                    {
                        resOptions[resOptions.length] =  new Option("960x720", "960,0");
                    }
                    if (!hasElem1)
                    {
                        resOptions[resOptions.length] =  new Option("1280x960", "1280,0");
                    }
                }
                else
                {
                    for (var x=resOptions.length-1; x>=0; x--)
                    {
                        if (   resOptions[x].text == "1280x960"
                            || resOptions[x].text == "960x720"
                            || resOptions[x].text == "768x576" )
                        {
                            resOptions[x] = null;
                        }
                    }
                }
            }
            else if (exccode == 3)
            {
                if (target.id == 'videoFmtJ')
                {
                    var hasMega = false;
                    for (var x=0; x<resOptions.length; x++)
                    {
                        if (resOptions[x].text == "768x576")
                        {
                            hasMega = true;
                            break;
                        }
                    }
                    if (!hasMega)
                    {
                        resOptions[resOptions.length] =  new Option("768x576", "768,0");
                    }			
                }
                else
                {
                    for (var x=0; x<resOptions.length; x++)
                    {
                        if (resOptions[x].text == "768x576")
                        {
                            resOptions[x] = null;
                            break;
                        }
                    }
                }
            }
        }
        else if (exccode == 4)
        {
            var frameSelect = document.form0.frameRateSelect;
            var frameOptions = document.form0.frameRateSelect.options;
            if (frameSelect == undefined || frameOptions == undefined || frameOptions.length<1)
                return;

            if (target.id == 'videoFmtJ')
            {
                for (var x=frameOptions.length-1; x>=0; x--)
                {
                    if (   frameOptions[x].text == "1"
                        || frameOptions[x].text == "2"
                        || frameOptions[x].text == "3"
                        || frameOptions[x].text == "4" )
                    {
                        frameOptions[x] = null;
                    }
                }
            }
            else
            {
                var hasElem1 = false;
                var hasElem2 = false;
                var hasElem3 = false;
                var hasElem4 = false;
                for (var x=0; x<frameOptions.length; x++)
                {
                    if (frameOptions[x].text == "1")
                    {
                        hasElem1 = true;
                    } else if (frameOptions[x].text == "2")
                    {
                        hasElem2 = true;
                    } else if (frameOptions[x].text == "3")
                    {
                        hasElem3 = true;
                    } else if (frameOptions[x].text == "4")
                    {
                        hasElem4 = true;
                    }
                }
                if (!hasElem4)
                {
                    frameOptions[frameOptions.length] =  new Option("4", "4");
                }
                if (!hasElem3)
                {
                    frameOptions[frameOptions.length] =  new Option("3", "3");
                }
                if (!hasElem2)
                {
                    frameOptions[frameOptions.length] =  new Option("2", "2");
                }
                if (!hasElem1)
                {
                    frameOptions[frameOptions.length] =  new Option("1", "1");
                }
            }
        }
    }
} catch (e) {errorReport(e);}
}

function ipcam_recordsetting_init()
{
    var myFormatIdx = function(el, oRecord, oColumn, oData)
    {
        /*var disIdx;
        if (oData == undefined)
            disIdx = 0;
        else
            disIdx = eval(oData + "+1");*/
        el.innerHTML = '<div align="center">' + oData + '</div>';
    };

    var myFormatUrl = function(el, oRecord, oColumn, oData)
    {
        el.innerHTML = '<a href="' + oData + '" target="_blink">Go to Web</a>';
    };

    var  myFormatLongText = function(el, oRecord, oColumn, oData)
    {
        if (typeof oData == 'string')
        {
            var s = oData;
            s = s.replace(/&/g, "&amp;");
            s = s.replace(/"/g, "&quot;");
            s = s.replace(/</g, "&lt;");
            s = s.replace(/>/g, "&gt;");

            el.innerHTML = '<div title="' + s + '" style="top: -4px;">' + s + '</div>';
        }
        else
        {
            el.innerHTML = '<div title="' + oData + '" style="top: -4px;">' + oData + '</div>';
        }
    };

    modifyIPCamera = function(ev)
    {
        var target = Event.getTarget(ev);
        var column = this.getColumn(target);
        var record = this.getRecord(target);

        lockPannel.show();

        currRecord = record;
        resetForm();
        setFrom(record);

        //document.getElementById("form_CameraName").focus();
    };

    myFormatBrand = function(el, oRecord, oColumn, oData)
    {
        if (oRecord == undefined)
        {
            el.innerHTML = "-- none --";
            return;
        }
        var bn = oRecord.getData("CameraVendor");
        if (bn==undefined || bn == "" || bn == "None")
            el.innerHTML = "-- none --";
        else
            el.innerHTML = bn;
    };

    myFormatModelName = function(el, oRecord, oColumn, oData)
    {
        if (oRecord == undefined)
        {
            el.innerHTML = "-- none --";
            return;
        }
        var mn = oRecord.getData("CameraModel");
        if (mn==undefined || mn == "")
            el.innerHTML = "-- none --";
        else
            el.innerHTML = mn;
    };

    var myColumnDefs =
    [
        {key:"ChannelIndex", label:'<span class="trans" title="Camera Index">Index</span>', sortable: true, formatter:myFormatIdx},
        {key:"CameraName", label: '<span class="trans" title="Camera Name">Camera Name</span>', formatter:myFormatLongText},
        {key:"CameraAddr", label: '<span class="trans" title="Address">Address</span>', formatter:myFormatLongText},
        {key:"CameraVendor", label: '<span class="trans" title="Vendor">Vendor</span>', formatter:myFormatBrand},
        {key:"CameraModel", label: '<span class="trans" title="Model">Model</span>', formatter:myFormatModelName},
        {key:"CameraOriUrl", label: '<span class="trans" title="Original Web">Original Web</span>', formatter:myFormatUrl}
    ];
    this.myDataSource = new YAHOO.util.DataSource("/CGI/cgi_main?cmd=rec_setting&xml=1&rand=" + Math.floor(Math.random()*1000));
    this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_XML;
    this.myDataSource.responseSchema = {resultNode: "IPCamera", fields: ["ChannelIndex", "CameraName", "CameraAddr", "CameraVendor", "CameraModel", "CameraOriUrl"] };

    this.myDataTable = new YAHOO.widget.DataTable("ipcam_recordsetting", myColumnDefs, this.myDataSource, {sortedBy:{key:"ChannelIndex", dir:"asc"}, initialRequest:""});
    this.myDataTable.set("selectionMode", "single");
    this.myDataTable.subscribe("rowClickEvent", this.myDataTable.onEventSelectRow);
    this.myDataTable.subscribe("cellClickEvent", modifyIPCamera);
    this.myDataTable.subscribe("initEvent", function() {
            if (parent.frames[0].parent != undefined && typeof parent.frames[0].parent.resizeMe == 'function')
                parent.frames[0].parent.resizeMe();
    });
    this.myDataTable.doBeforeLoadData = function(sRequest, oResponse)
    {
        if (oResponse)
        {
            var statusLine = new String(oResponse.status);
            if (statusLine.match(/^401/))
            {
                handleSessionTimeout();
                return false;
            }
        }
        return true;
    };

    Event.addListener(["saveBTN"], "click", submitSave);
    disableSubmitButton(true);
    //Event.addListener(["resetBTN"], "click", resetData);
    Event.addListener(["videoFmtJ", "videoFmtM"], 'click', onFormatClick);
    Event.addListener("audioChk", 'click', onAudioClick);

    this.lockPannel = new YAHOO.widget.Panel("lockpanel", { width:"320px", visible:false, draggable:false, close:false, constraintoviewport:true, modal:true, fixedcenter:true } );
    this.lockPannel.setBody('<img src="../imgs/nuuo-loader.gif" />Load Camera Parameters...');
    this.lockPannel.render("mainbody");

    resetForm();
}

function resetForm()
{
    try
    {
        var elem = Dom.get("form_ChannelIndex");
        if (elem != undefined)  elem.value = -1;

        elem = Dom.get("form_CameraName");
        if (elem != undefined)  elem.innerHTML = "";

        elem = Dom.get("videoFmtJ");
        if (elem != undefined)
        {
            elem.disabled = true;
            elem.checked = false;
        }

        elem = Dom.get("videoFmtM");
        if (elem != undefined)
        {
            elem.disabled = true;
            elem.checked = false;
        }

        elem = Dom.get("frameRateSelect");
        if (elem != undefined)
        {
            elem.disabled = true;
        }

        elem = Dom.get("resolutionSelect");
        if (elem != undefined)
        {
            elem.disabled = true;
        }

        elem = Dom.get("compressionSelect");
        if (elem != undefined)
        {
            elem.disabled = true;
        }

        elem = Dom.get("audioChk");
        if (elem != undefined)
        {
            elem.disabled = true;
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

function handleActiPTZSuccess(o)
{
    if(o.responseText !== undefined) {
        if (o.status == "200")
        {
            if (o.responseText.match(/200 OK/))
            {
                alert("PTZ Setting successfully!");
            }
            else
            {
                alert("PTZ Setting failed!");
            }
            actiDialog.destroy();
            return;
        }
        else if (o.status == "401")
        {
            actiDialog.destroy();
            handleSessionTimeout();
            return;
        }
        else
        {
            actiDialog.destroy();
            alert("PTZ Setting failed!");
            return;
        }
    }
    actiDialog.destroy();
}

function handleActiPTZFailure(o)
{
    if (o.status == "401")
    {
        handleSessionTimeout();
        return;
    }
    alert('Send PTZ Setting failed!');
    actiDialog.destroy();
}

function onActiOk()
{
try {

    var answer = confirm('After Setting PTZ, the camera should be restartd. Are you sure?');
    if (answer == null || !answer)
        return;

    disableSubmitButton(true);

    var postData = "";

    var chidx = parseInt(document.form0.ChannelIndex.value, 10) - 1;
    postData += "ChannelIndex=" + encodeURIComponent(chidx);
    postData += "&PTZBRAND=Acti";

    var ptzType = Dom.get("actiptztype");
    if (ptzType!=undefined)
    {
        postData += "&PTZTYPE=" + ptzType.options.selectedIndex;
    }
    else
    {
        postData += "&PTZTYPE=0";
    }

    var ptzBaudRate = Dom.get("actibaudrate");
    if (ptzBaudRate!=undefined)
    {
        postData += "&PTZBAUDRATE=" + ptzBaudRate.options.selectedIndex;
    }
    else
    {
        postData += "&PTZBAUDRATE=0";
    }

    var ptzAddress = Dom.get("actiaddress");
    if (ptzAddress!=undefined)
    {
        postData += "&PTZADDRESS=" + ptzAddress.options.selectedIndex;
    }
    else
    {
        postData += "&PTZADDRESS=0";
    }

    var callback =
    {
        success: handleActiPTZSuccess,
        failure: handleActiPTZFailure
    };
    var cgiPATH = document.form0.action.replace(/cmd=[A-Za-z0-9_]+/, "cmd=ptzsetting");
    YAHOO.util.Connect.asyncRequest("POST", cgiPATH, callback, postData);
} catch (e) {errorReport(e); alert('Send PTZ Setting failed!'); actiDialog.destroy();}
}

function onActiCancel()
{
    actiDialog.destroy();
}

function showPTZSettingDialog()
{
    if (isActi)
    {
        var buttonsCfg = [
            {text: 'Save', handler: {fn: onActiOk}},
            {text: 'Cancel', handler: {fn: onActiCancel}}
        ];

        actiDialog = new YAHOO.widget.Dialog("actidialog",
            { width: "250px",
              visible: false,
              constraintoviewport: true,
              draggable: false,
              close: false,
              buttons: buttonsCfg,
              modal: true });

        var htmlBody = '';

        htmlBody += '<div class="panelRow"><label class="panelLabel">';
        htmlBody += 'PTZ Type';
        htmlBody += '</label><select id="actiptztype" class="panelSelect"';
        var ptztype = PTZType['acti'];
        if (ptztype!=undefined && ptztype.length>0)
        {
            htmlBody += '>';
            for (var x=0; x<ptztype.length; x++)
            {
                htmlBody += '<option value="' + ptztype[x][1] + '"';
                if (x == extraData[0])
                {
                    htmlBody += ' selected';
                }
                htmlBody += '>' + ptztype[x][0] + '</option>';
            }
        }
        else
        {
            htmlBody += ' disabled>';
        }
        htmlBody += '</select></div>';

        htmlBody += '<div class="panelRow"><label class="panelLabel">';
        htmlBody += 'BaudRate';
        htmlBody += '</label><select id="actibaudrate" class="panelSelect"';
        var ptzbaudrate = PTZBaudRate['acti'];
        if (ptzbaudrate!=undefined && ptzbaudrate.length>0)
        {
            htmlBody += '>';
            for (var x=0; x<ptzbaudrate.length; x++)
            {
                htmlBody += '<option value="' + ptzbaudrate[x][1] + '"';
                if (x == extraData[1])
                {
                    htmlBody += ' selected';
                }
                htmlBody += '>' + ptzbaudrate[x][0] + '</option>';
            }
        }
        else
        {
            htmlBody += ' disabled>';
        }
        htmlBody += '</select></div>';

        htmlBody += '<div class="panelRow"><label class="panelLabel">';
        htmlBody += 'PTZ Address';
        htmlBody += '</label><select id="actiaddress" class="panelSelect"';
        var ptzaddress = PTZAddress['acti'];
        if (ptzaddress!=undefined && ptzaddress.length>0)
        {
            htmlBody += '>';
            for (var x=0; x<ptzaddress.length; x++)
            {
                htmlBody += '<option value="' + ptzaddress[x][1] + '"';
                if (x == extraData[2])
                {
                    htmlBody += ' selected';
                }
                htmlBody += '>' + ptzaddress[x][0] + '</option>';
            }
        }
        else
        {
            htmlBody += ' disabled>';
        }
        htmlBody += '</select></div>';
        
        actiDialog.setHeader('Acti PTZ Setting');
        actiDialog.setBody(htmlBody);

        actiDialog.render('actidialogdiv');
        actiDialog.center();
        actiDialog.show();
    }
}
