var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;

var eventTree;
var eventButtons = new Array();
var actionTable;
var actionButtons = new Array();
var actionsMenu = undefined;
var MaxIPCam;
var CameraInfo = undefined;
var SystemInfo = undefined;
var MotionInfo = undefined;
var hasMotion = false;
var INPUTInfo = undefined;
var OUTPUTInfo = undefined;
var hasINPUT = false;
var hasOUTPUT = false;
var ContactList = undefined;

var contactDialog = undefined;
var contactChkList = new Array();
var contactDDList = new Array();

var digitalOutputDialog = undefined;
var digitalOutputChkList = new Array();

var eventConfDialog = undefined;
var eventConfElements = new Array();
var activeTimeFields = new Array();

var NodeTypes = {camera:1, di: 2, system: 3, event: 4};
var EventTypes = {camera:1, system: 2};
var CameraEventTypes = {motion:1, io: 2, connlost: 3};
var SystemEventTypes = {disk: 1};
var ActionTypes = {output: 1, email: 2};

var preHighlightTreeNode = undefined;

var isAddAction = false;

YAHOO.widget.Dialog.prototype.relatedData = undefined;
YAHOO.widget.Dialog.prototype.relatedInfo = undefined;

function printDigital(num, padding)
{
    if (padding<2)
        return num;

    var s = '';
    for (var i=0; i<padding; i++)
        s += '0';
    s += num;
    return s.substr(s.length - padding);
}

function onAddEvent()
{
    if (preHighlightTreeNode != undefined)
    {
        var labelStr = 'Event for Camera#' + preHighlightTreeNode.cameraIndex;
        var tmpNode = new YAHOO.widget.MenuNode({label: labelStr, nodeType: NodeTypes['event']}, preHighlightTreeNode, true);
        tmpNode.nodeType = NodeTypes['event'];
        preHighlightTreeNode.expand();
        eventTree.draw();
    }
}

function onDelEvent()
{
    if (preHighlightTreeNode != undefined)
    {
        eventTree.removeNode(preHighlightTreeNode, true);
        preHighlightTreeNode = undefined;
        SetEventButtonsStatus(0);
    }
}

function onAddActionClick(p_sType, p_aArgs, p_oItem)
{
    try{
        var addType = p_oItem.value;
        var ch = (preHighlightTreeNode.cameraIndex != undefined ? parseInt(preHighlightTreeNode.cameraIndex, 10) : undefined);
        var eventType = parseInt(preHighlightTreeNode.eventType, 10);
        var eventID = parseInt(preHighlightTreeNode.eventID, 10);
        var pinNum = (preHighlightTreeNode.pinNum != undefined ? parseInt(preHighlightTreeNode.pinNum, 10) : undefined);

        var relatedData = undefined;
        if (eventType == EventTypes['camera'])
        {
            if (eventID == CameraEventTypes['motion'])
            {
                if (CameraInfo[ch]['motion']['action'] == undefined)
                    CameraInfo[ch]['motion']['action'] = new Array();
                relatedData = CameraInfo[ch]['motion']['action'];
            }
            else if (eventID == CameraEventTypes['connlost'])
            {
                if (CameraInfo[ch]['connlost']['action'] == undefined)
                    CameraInfo[ch]['connlost']['action'] = new Array();
                relatedData = CameraInfo[ch]['connlost']['action'];
            }
            else if (eventID == CameraEventTypes['io'])
            {
                if (CameraInfo[ch]['io'][pinNum]['action'] == undefined)
                    relatedData = CameraInfo[ch]['io'][pinNum]['action'] = new Array();
                relatedData = CameraInfo[ch]['io'][pinNum]['action'];
            }
        }
        else if (eventType == EventTypes['system'])
        {
            if (eventID == SystemEventTypes['disk'])
            {
                if (SystemInfo['disk']['action'] == undefined)
                    SystemInfo['disk']['action'] = new Array();
                relatedData = SystemInfo['disk']['action'];
            }
        }

        var rs = actionTable.getRecordSet();
        var record = undefined;
        if (addType == ActionTypes['email'])
        {
            record = rs.addRecord({action: ActionTypes['email'], eventType: eventType, eventID: eventID}, 0);
            if (ch != undefined)
            {
                rs.updateKey(record, "channelIndex", ch);
            }
            if (pinNum != undefined)
            {
                rs.updateKey(record, "pinNum", pinNum);
            }
            relatedData.push({action: ActionTypes['email']});
        }
        else if (addType == ActionTypes['output'])
        {
            record = rs.addRecord({action: ActionTypes['output'], eventType: eventType, eventID: eventID}, 0);
            if (ch != undefined)
            {
                rs.updateKey(record, "channelIndex", ch);
            }
            if (pinNum != undefined)
            {
                rs.updateKey(record, "pinNum", pinNum);
            }
            relatedData.push({action: ActionTypes['output']});
        }
        else
        {
            //alert("???????????????");
        }

        actionTable.refreshView();
        SetActionTable(preHighlightTreeNode);
        if (record!=undefined)
        {
            isAddAction = true;
            actionTable.unselectAllRows();
            actionTable.selectRow(0);
            onConfAction();
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

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

    if (record == undefined)
        return;

//    var enableConfButton = false;
//    if (record.getData("action") == ActionTypes['email'])
//    {
//        enableConfButton = true;
//    }
    var rs = (actionTable ? actionTable.getRecordSet() : undefined);
    if (rs)
    {
        if (rs.getLength() > 1)
        {
//            if (enableConfButton)
                SetActionButtonsStatus(6);
//            else
//                SetActionButtonsStatus(2); // enable del and conf buttons
        }
        else
        {
//            if (enableConfButton)
                SetActionButtonsStatus(7);
//            else
//                SetActionButtonsStatus(3); // enable all buttons
        }
    }
    else
    {
        //alert('error in onModifyAction()!');
    }
}

function onConfEvent()
{
    onResetEventConfDialog();

    var data = undefined;
    try
    {
        if (preHighlightTreeNode != undefined)
        {
            var nType = parseInt(preHighlightTreeNode.nodeType, 10);
            if (nType == NodeTypes['event'])
            {
                var chIdx = parseInt(preHighlightTreeNode.cameraIndex, 10);
                var eventType = parseInt(preHighlightTreeNode.eventType, 10);
                var eventID = parseInt(preHighlightTreeNode.eventID, 10);
                var pinNum = undefined;

                if (eventType == EventTypes['camera'])
                {
                    if (CameraInfo == undefined)
                    {
                        //alert("CameraInfo == undefined!");
                        return;
                    }

                    if (eventID == CameraEventTypes['motion'])
                    {
                        if (CameraInfo[chIdx] == undefined)
                        {
                            CameraInfo[chIdx] = new Array();
                        }
                        if (CameraInfo[chIdx]['motion'] == undefined)
                        {
                            CameraInfo[chIdx]['motion']  = new Array();
                        }
                        data = CameraInfo[chIdx]['motion'];
                    }
                    else if (eventID == CameraEventTypes['io'])
                    {
                        pinNum = parseInt(preHighlightTreeNode.pinNum, 10);
                        if (CameraInfo[chIdx] == undefined)
                        {
                            CameraInfo[chIdx] = new Array();
                        }
                        if (CameraInfo[chIdx]['io'] == undefined)
                        {
                            CameraInfo[chIdx]['io'] = new Array();
                        }
                        if (CameraInfo[chIdx]['io'][pinNum] == undefined)
                        {
                            CameraInfo[chIdx]['io'][pinNum] = new Array();
                        }
                        data = CameraInfo[chIdx]['io'][pinNum];
                    }
                    else if (eventID == CameraEventTypes['connlost'])
                    {
                        if (CameraInfo[chIdx] == undefined)
                        {
                            CameraInfo[chIdx] = new Array();
                        }
                        if (CameraInfo[chIdx]['connlost'] == undefined)
                        {
                            CameraInfo[chIdx]['connlost'] = new Array();
                        }
                        data = CameraInfo[chIdx]['connlost'];
                    }
                    else
                    {
                        //alert("eventID is not a valid value!");
                        return;
                    }
                }
                else if (eventType == EventTypes['system'])
                {
                    if (SystemInfo == undefined)
                    {
                        SystemInfo = new Array();
                    }
                    if (SystemInfo['disk'] == undefined)
                    {
                        SystemInfo['disk'] = new Array();
                    }
                    data = SystemInfo['disk'];
                }
                else
                {
                    //alert("eventType is not a valid value!");
                    return;
                }
                eventConfDialog.relatedInfo = [chIdx, eventType, eventID, pinNum];
            }
            else
            {
                //alert("nodeType != NodeTypes['event']!");
                return;
            }
        }

        if (data == undefined)
        {
            //alert("data == undefined!");
            return;
        }

        if (eventConfDialog.relatedInfo[3] != undefined)
        {
            var d = Dom.get("iotype");
            if (d!=undefined)
            {
                Dom.setStyle(d, "visibility", "visible");
                Dom.setStyle(d, "display", "block");
            }
            eventConfElements[ eventConfElements.length - 1 ].disabled = false;
            eventConfElements[ eventConfElements.length - 2 ].disabled = false;
            if (data)
            {
                if (data['iotype'] != undefined)
                {// data['iotype']: true for N/O
                    eventConfElements[ eventConfElements.length - 2 ].checked = data['iotype']; // N/O radio button
                    eventConfElements[ eventConfElements.length - 1 ].checked = (! data['iotype']); // N/C radio button
                }
                else
                {
                    eventConfElements[ eventConfElements.length - 1 ].checked = false;
                    eventConfElements[ eventConfElements.length - 2 ].checked = false;
                }
            }
        }
        else
        {
            var d = Dom.get("iotype");
            if (d!=undefined)
            {
                Dom.setStyle(d, "visibility", "hidden");
                Dom.setStyle(d, "display", "none");
            }
            eventConfElements[ eventConfElements.length - 1 ].disabled = true;
            eventConfElements[ eventConfElements.length - 2 ].disabled = true;
        }

        eventConfElements[0].checked = (data ? data['enable'] : false);
        eventConfDialog.relatedData = data;

        if ((data != undefined) && (data['always'] != undefined))
        {
            eventConfElements[3].checked = (data ? data['always'] : false);
            eventConfElements[4].checked = !(eventConfElements[3].checked);
            if (eventConfElements[3].checked)
                eventConfElements[3].click();
            else
                eventConfElements[4].click();
        }
        else
        {
            eventConfElements[3].checked = false;
            eventConfElements[4].checked = false;
        }

        /*if ((data != undefined) && (data['manual'] != undefined))
        {
            eventConfElements[2].checked = (data ? data['manual'] : false);
            eventConfElements[1].checked = !(eventConfElements[2].checked);
        }
        else
        {
            eventConfElements[1].checked = false;
            eventConfElements[2].checked = false;
        }*/

        if ((data != undefined) && (data['activeTime'] != undefined))
        {
            activeTimeFields['startHour'].value = (data['activeTime']['startHour'] ? data['activeTime']['startHour'] : "00");
            activeTimeFields['startMinute'].value = (data['activeTime']['startMinute'] ? data['activeTime']['startMinute'] : "00");
            activeTimeFields['endHour'].value = (data['activeTime']['endHour'] ? data['activeTime']['endHour'] : "00");
            activeTimeFields['endMinute'].value = (data['activeTime']['endMinute'] ? data['activeTime']['endMinute'] : "00");
        }
        else
        {
            activeTimeFields['startHour'].value = "00";
            activeTimeFields['startMinute'].value = "00";
            activeTimeFields['endHour'].value = "00";
            activeTimeFields['endMinute'].value = "00";
        }

        eventConfDialog.moveTo(30, 120);
        eventConfDialog.show();
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

function onAddAction(ev)
{
    //alert('onAddAction()' + ev);
    actionsMenu.show();
}

function onDelAction(ev)
{
    if (actionTable == undefined)
        return;

    var selectedRows = actionTable.getSelectedRows();
    var rs = actionTable.getRecordSet();
    if ( (selectedRows == undefined) || (rs == undefined) || ! (selectedRows instanceof Array) )
        return;

    var record = rs.getRecord(selectedRows[0]);
    if (record == undefined)
        return;

    var data = record.getData();
    if (data == undefined)
        return;

    var ch = data['channelIndex'];
    var eventType = data['eventType'];
    var eventID = data['eventID'];
    var pinNum = data['pinNum'];
    var actionID = data['action'];

    var deleteData = false;
    if (eventType == EventTypes['system'])
    {
        if (eventID == SystemEventTypes['disk'] && SystemInfo && SystemInfo['disk'])
        {
            var actions = SystemInfo['disk']['action'];
            if (actions && (actions instanceof Array))
            {
                for (var i=0; i<actions.length; i++)
                {
                    if (actionID == actions[i]['action'])
                    {
                        actions.splice(i, 1);
                        deleteData = true;
                    }
                }
            }
        }
    }
    else if (eventType == EventTypes['camera'] && (ch != undefined))
    {
        var actions = undefined;
        var chIdx = parseInt(ch, 10);
        if (eventID == CameraEventTypes['connlost'])
        {
            if (CameraInfo && CameraInfo[chIdx] && CameraInfo[chIdx]['connlost'])
            {
                actions = CameraInfo[chIdx]['connlost']['action'];
                //alert("actions for connlost: " + actions);
            }
        }
        else if (eventID == CameraEventTypes['motion'])
        {
            if (CameraInfo && CameraInfo[chIdx] && CameraInfo[chIdx]['motion'])
            {
                actions = CameraInfo[chIdx]['motion']['action'];
                //alert("actions for motion: " + actions);
            }
        }
        else if (eventID == CameraEventTypes['io'])
        {
            var pinNumIdx = ((pinNum != undefined) ? parseInt(pinNum, 10) : undefined);
            if (CameraInfo && CameraInfo[chIdx] && CameraInfo[chIdx]['io'] && (pinNumIdx != undefined) && CameraInfo[chIdx]['io'][pinNumIdx])
            {
                actions = CameraInfo[chIdx]['io'][pinNumIdx]['action'];
                //alert("actions for io: " + actions);
            }
        }

        if (actions != undefined && (actions instanceof Array))
        {
            for (var i=0; i<actions.length; i++)
            {
                if (actionID == actions[i]['action'])
                {
                    actions.splice(i, 1);
                    deleteData = true;
                }
            }
        }
    }

    if (deleteData)
    {
        rs.deleteRecord(rs.getRecordIndex(record), 1);
        actionTable.refreshView();
        SetActionButtonsStatus(1); // enable add button
    }

}

function onConfAction(ev)
{
    try
    {
        var selectedRows = actionTable.getSelectedRows();
        var rs = actionTable.getRecordSet();
        var record = rs.getRecord(selectedRows[0]);
        var data = record.getData();

        if (data['action'] == ActionTypes['email'])
        {
            onResetContactList();
            var options = data['options'];
            for (var x in options)
            {
                contactChkList[ options[x] ].checked = true;
            }
            contactDialog.relatedData = record;
            contactDialog.moveTo(30, 120);
            contactDialog.show();
        }
        else if (data['action'] == ActionTypes['output'])
        {
            onResetDOList();

            var options = data['options'];
            if (options != undefined)
            {
                for (var i=0; i<options.length; i++)
                {
                    if ( digitalOutputChkList[ options[i][0] ][ options[i][1] ] != undefined)
                    {
                        digitalOutputChkList[ options[i][0] ][ options[i][1] ].checked = true;
                    }
                }
            }

            if (data['eventID'] == CameraEventTypes['connlost'])
            {
                disableDO(data['channelIndex']);
            }

            digitalOutputDialog.relatedData = record;
            digitalOutputDialog.moveTo(30, 120);
            digitalOutputDialog.show();
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

function onTreeLabelClick(node)
{
    if (node == undefined)
        return;
    
    if ((node.nodeType >= NodeTypes['camera']) && (node.nodeType <= NodeTypes['system']))
    {
        SetEventButtonsStatus(0); // disable event conf. button
/*        if (preHighlightTreeNode != undefined)
        {
            Dom.removeClass(preHighlightTreeNode.getEl(), 'highlightTreeElem');
        }
        preHighlightTreeNode = node;
        Dom.addClass(preHighlightTreeNode.getEl(), 'highlightTreeElem'); */

        // clear action table
        var rs = (actionTable ? actionTable.getRecordSet() : undefined);
        if (rs != undefined)
        {
            rs.deleteRecords(0, rs.getLength());
            actionTable.refreshView();
        }
    }
    else if (node.nodeType == NodeTypes['event'])
    {
        SetEventButtonsStatus(1); // enable event conf. button
        if (preHighlightTreeNode != undefined)
        {
            Dom.removeClass(preHighlightTreeNode.getEl(), 'highlightTreeElem');
        }
        preHighlightTreeNode = node;
        Dom.addClass(preHighlightTreeNode.getEl(), 'highlightTreeElem');

        SetActionTable(node);
    }
}

function onContactOk()
{
    try {
        var selectedContatctors = new Array();
        for (var i=0; i<contactChkList.length; i++)
        {
            if (contactChkList[i].checked)
            {
                selectedContatctors.push(i);
            }
        }

        if (contactDialog.relatedData != undefined)
        {
            // update table record
            var record = contactDialog.relatedData;
            actionTable.getRecordSet().updateKey(record, 'options', selectedContatctors);
            actionTable.refreshView();

            // update CameraInfo
            var data = record.getData();
            if (data['eventType'] == EventTypes['camera'])
            {
                if (data['eventID'] == CameraEventTypes['motion'])
                {
                    var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                    var mo = (x!=undefined ? x['motion'] : undefined);
                    var ac = (mo!=undefined ? mo['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['email'])
                            {
                                ac[k]['option'] = selectedContatctors;
                            }
                        }
                    }
                }
                else if (data['eventID'] == CameraEventTypes['connlost'])
                {
                    var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                    var co = (x!=undefined ? x['connlost'] : undefined);
                    var ac = (co!=undefined ? co['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['email'])
                            {
                                ac[k]['option'] = selectedContatctors;
                            }
                        }
                    }
                }
                else if (data['eventID'] == CameraEventTypes['io'])
                {
                    var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                    var ios = (x!=undefined ? x['io'] : undefined);
                    var iop = (ios!=undefined ? ios[ parseInt(data['pinNum'], 10) ] : undefined);
                    var ac = (iop!=undefined ? iop['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['email'])
                            {
                                ac[k]['option'] = selectedContatctors;
                            }
                        }
                    }
                }
            }
            else if (data['eventType'] == EventTypes['system'])
            {
                if (data['eventID'] == SystemEventTypes['disk'])
                {
                    var x = SystemInfo['disk'];
                    var ac = (x!=undefined ? x['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['email'])
                            {
                                ac[k]['option'] = selectedContatctors;
                            }
                        }
                    }
                }
            }
        }
        isAddAction = false;
        contactDialog.hide();
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

function onContactCancel()
{
    if (isAddAction)
    {
        isAddAction = false;
        var record = contactDialog.relatedData;
        if (record!=undefined)
        {
            var idx = actionTable.getRecordSet().getRecordIndex(record);
            if (idx!=undefined)
                actionTable.getRecordSet().deleteRecord(idx, 1);

            actionTable.refreshView();
           // revert CameraInfo
           var data = record.getData();
           if (data['eventType'] == EventTypes['camera'])
           {
               if (data['eventID'] == CameraEventTypes['motion'])
               {
                   var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                   var mo = (x!=undefined ? x['motion'] : undefined);
                   var ac = (mo!=undefined ? mo['action'] : undefined);
                   if (ac != undefined)
                   {
                       for (var k=0; k<ac.length; k++)
                       {
                           if (ac[k]['action'] == ActionTypes['email'])
                           {
                               ac.splice(k, 1);
                               break;
                           }
                       }
                   }
               }
               else if (data['eventID'] == CameraEventTypes['connlost'])
               {
                   var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                   var co = (x!=undefined ? x['connlost'] : undefined);
                   var ac = (co!=undefined ? co['action'] : undefined);
                   if (ac != undefined)
                   {
                       for (var k=0; k<ac.length; k++)
                       {
                           if (ac[k]['action'] == ActionTypes['email'])
                           {
                               ac.splice(k, 1);
                               break;
                           }
                       }
                   }
               }
               else if (data['eventID'] == CameraEventTypes['io'])
               {
                   var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                   var ios = (x!=undefined ? x['io'] : undefined);
                   var iop = (ios!=undefined ? ios[ parseInt(data['pinNum'], 10) ] : undefined);
                   var ac = (iop!=undefined ? iop['action'] : undefined);
                   if (ac != undefined)
                   {
                       for (var k=0; k<ac.length; k++)
                       {
                           if (ac[k]['action'] == ActionTypes['email'])
                           {
                               ac.splice(k, 1);
                               break;
                           }
                       }
                   }
               }
           }
           else if (data['eventType'] == EventTypes['system'])
           {
               if (data['eventID'] == SystemEventTypes['disk'])
               {
                   var x = SystemInfo['disk'];
                   var ac = (x!=undefined ? x['action'] : undefined);
                   if (ac != undefined)
                   {
                       for (var k=0; k<ac.length; k++)
                       {
                           if (ac[k]['action'] == ActionTypes['email'])
                           {
                               ac.splice(k, 1);
                               break;
                           }
                       }
                   }
               }
           }
        }
    }
    SetActionButtonsStatus(1);
    contactDialog.cancel();
}

function onDOOk()
{
    try
    {
        var selectedDO = new Array();
        for (var i=0; i<digitalOutputChkList.length; i++)
        {
            for (var j=0; j<digitalOutputChkList[i].length; j++)
            {
                if (digitalOutputChkList[i][j].checked)
                {
                    selectedDO.push([i, j]);
                }
            }
        }

        if (digitalOutputDialog.relatedData != undefined)
        {
            // update table record
            var record = digitalOutputDialog.relatedData;
            actionTable.getRecordSet().updateKey(record, 'options', selectedDO);
            actionTable.refreshView();

            // update CameraInfo
            var data = record.getData();
            if (data['eventType'] == EventTypes['camera'])
            {
                if (data['eventID'] == CameraEventTypes['motion'])
                {
                    var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                    var mo = (x!=undefined ? x['motion'] : undefined);
                    var ac = (mo!=undefined ? mo['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['output'])
                            {
                                ac[k]['option'] = selectedDO;
                            }
                        }
                    }
                }
                else if (data['eventID'] == CameraEventTypes['connlost'])
                {
                    var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                    var co = (x!=undefined ? x['connlost'] : undefined);
                    var ac = (co!=undefined ? co['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['output'])
                            {
                                ac[k]['option'] = selectedDO;
                            }
                        }
                    }
                }
                else if (data['eventID'] == CameraEventTypes['io'])
                {
                    var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                    var ios = (x!=undefined ? x['io'] : undefined);
                    var iop = (ios!=undefined ? ios[ parseInt(data['pinNum'], 10) ] : undefined);
                    var ac = (iop!=undefined ? iop['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['output'])
                            {
                                ac[k]['option'] = selectedDO;
                            }
                        }
                    }
                }
            }
            else if (data['eventType'] == EventTypes['system'])
            {
                if (data['eventID'] == SystemEventTypes['disk'])
                {
                    var x = SystemInfo['disk'];
                    var ac = (x!=undefined ? x['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['output'])
                            {
                                ac[k]['option'] = selectedDO;
                            }
                        }
                    }
                }
            }
        }
        isAddAction = false;
        digitalOutputDialog.hide();
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

function onDOCancel()
{
    if (isAddAction)
    {
        isAddAction = false;
        var record = digitalOutputDialog.relatedData;
        if (record!=undefined)
        {
            var idx = actionTable.getRecordSet().getRecordIndex(record);
            if (idx!=undefined)
                actionTable.getRecordSet().deleteRecord(idx, 1);

            actionTable.refreshView();
            // revert CameraInfo
            var data = record.getData();
            if (data['eventType'] == EventTypes['camera'])
            {
                if (data['eventID'] == CameraEventTypes['motion'])
                {
                    var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                    var mo = (x!=undefined ? x['motion'] : undefined);
                    var ac = (mo!=undefined ? mo['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['output'])
                            {
                                ac.splice(k, 1);
                                break;
                            }
                        }
                    }
                }
                else if (data['eventID'] == CameraEventTypes['connlost'])
                {
                    var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                    var co = (x!=undefined ? x['connlost'] : undefined);
                    var ac = (co!=undefined ? co['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['output'])
                            {
                                ac.splice(k, 1);
                                break;
                            }
                        }
                    }
                }
                else if (data['eventID'] == CameraEventTypes['io'])
                {
                    var x = CameraInfo[ parseInt(data['channelIndex'], 10) ];
                    var ios = (x!=undefined ? x['io'] : undefined);
                    var iop = (ios!=undefined ? ios[ parseInt(data['pinNum'], 10) ] : undefined);
                    var ac = (iop!=undefined ? iop['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['output'])
                            {
                                ac.splice(k, 1);
                                break;
                            }
                        }
                    }
                }
            }
            else if (data['eventType'] == EventTypes['system'])
            {
                if (data['eventID'] == SystemEventTypes['disk'])
                {
                    var x = SystemInfo['disk'];
                    var ac = (x!=undefined ? x['action'] : undefined);
                    if (ac != undefined)
                    {
                        for (var k=0; k<ac.length; k++)
                        {
                            if (ac[k]['action'] == ActionTypes['output'])
                            {
                                ac.splice(k, 1);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    SetActionButtonsStatus(1);
    digitalOutputDialog.cancel();
}

function checkActiveTime(a, b, c, d)
{
    if (a == NaN || a == undefined || a<0 || a>24) return false;
    if (b == NaN || b == undefined || b<0 || b>59) return false;
    if (c == NaN || c == undefined || c<0 || c>24) return false;
    if (d == NaN || d == undefined || d<0 || d>59) return false;

    if (a == 24 && b != 0) return false;
    if (c == 24 && d != 0) return false;

    var x = a * 60 + b;
    var y = c * 60 + d;
    if (x>y)  return false;
    return true;
}

function onEventConfOk()
{
    //alert(eventConfDialog.relatedData);
    try
    {
        var data = eventConfDialog.relatedData;
        var info = eventConfDialog.relatedInfo;
        if ((data != undefined) && (info != undefined))
        {
            data['enable'] = eventConfElements[0].checked;
            //data['manual'] = eventConfElements[2].checked;
            data['always'] = eventConfElements[3].checked;
            if (eventConfElements[ eventConfElements.length - 1].disabled != true)
            {// io, we should save io type
                data['iotype'] = eventConfElements[ eventConfElements.length - 2].checked; // true for N/O
            }

            if (!myIsNumber(activeTimeFields['startHour'].value))
            {
                alert("Your start time is not correct.");
                activeTimeFields['startHour'].focus();
                activeTimeFields['startHour'].select();
                return;
            }
            if (!myIsNumber(activeTimeFields['startMinute'].value))
            {
                alert("Your start time is not correct.");
                activeTimeFields['startMinute'].focus();
                activeTimeFields['startMinute'].select();
                return;
            }

            if (!myIsNumber(activeTimeFields['endHour'].value))
            {
                alert("Your end time is not correct.");
                activeTimeFields['endHour'].focus();
                activeTimeFields['endtHour'].select();
                return;
            }
            if (!myIsNumber(activeTimeFields['startMinute'].value))
            {
                alert("Your end time is not correct.");
                activeTimeFields['endMinute'].focus();
                activeTimeFields['endMinute'].select();
                return;
            }

            var shT = parseInt(activeTimeFields['startHour'].value, 10);
            if (shT>24 || shT<0)
            {
                alert("Your start time is not correct.");
                activeTimeFields['startHour'].focus();
                activeTimeFields['startHour'].select();
                return;
            }
            var smT = parseInt(activeTimeFields['startMinute'].value, 10);
            if (smT>59 || smT<0)
            {
                alert("Your start time is not correct.");
                activeTimeFields['startMinute'].focus();
                activeTimeFields['startMinute'].select();
                return;
            }
            var ehT = parseInt(activeTimeFields['endHour'].value, 10);
            if (ehT>24 || ehT<0)
            {
                alert("Your end time is not correct.");
                activeTimeFields['endHour'].focus();
                activeTimeFields['endtHour'].select();
                return;
            } 
            var emT = parseInt(activeTimeFields['endMinute'].value, 10);
            if (emT>59 || emT<0)
            {
                alert("Your end time is not correct.");
                activeTimeFields['endMinute'].focus();
                activeTimeFields['endMinute'].select();
                return;
            }
            if ((! data['always']) && (! checkActiveTime(shT, smT, ehT, emT)))
            {
                //shT = smT = ehT = emT = 0;
                alert("Active time settings are not valid!");
                activeTimeFields['startHour'].focus();
                activeTimeFields['startHour'].select();
                return;    
            }
            if (ehT==24 && emT == 0)
            {
                ehT = 23;
                ehM = 59;
            }

            if (data['activeTime'] == undefined)
                data['activeTime'] = new Array();
            data['activeTime']['startHour'] = shT;
            data['activeTime']['startMinute'] = smT;
            data['activeTime']['endHour'] = ehT;
            data['activeTime']['endMinute'] = emT;
        
            // update event status's checkbox
            if (EventTypes['camera'] == info[1])
            {
                if (CameraEventTypes['connlost'] == info[2])
                {
                    var gs = 'connlost-' + info[0];
                    Dom.get(gs).checked = eventConfElements[0].checked;
                }
                else if (CameraEventTypes['motion'] == info[2])
                {
                    var gs = 'motion-' + info[0];
                    Dom.get(gs).checked = eventConfElements[0].checked;
                }
                else if (CameraEventTypes['io'] == info[2])
                {
                    var gs = 'io-' + info[0] + '-' + info[3];
                    Dom.get(gs).checked = eventConfElements[0].checked;
                }
                else
                {
                    //alert("eventID is not a valid value!");
                }
            }
            else if (EventTypes['system'] == info[1])
            {
                if (SystemEventTypes['disk'] == info[2])
                {
                    Dom.get("diskexhausted").checked = eventConfElements[0].checked;
                }
            }
            else
            {
                //alert("EventTypes is not a valid value!");
            }
        }
        else
        {
            //alert("Related data or info is undefined!");
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
        isAddAction = false;
        eventConfDialog.hide();
    }

    try
    {
        var d = Dom.get("iotype");
        if (d!=undefined)
        {
            Dom.setStyle(d, "visibility", "hidden");
            Dom.setStyle(d, "display", "none");
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }

    isAddAction = false;
    eventConfDialog.hide();
}

function onEventConfCancel()
{
    try
    {
        var d = Dom.get("iotype");
        if (d!=undefined)
        {
            Dom.setStyle(d, "visibility", "hidden");
            Dom.setStyle(d, "display", "none");
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }

    eventConfDialog.cancel();
}

function onResetEventConfDialog()
{
    try
    {
        for (var x in eventConfElements)
        {
            if (eventConfElements[x] != undefined)
            {
                eventConfElements[x].checked = false;
            }
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

function onResetContactList()
{
    try
    {
        for (var x in contactChkList)
        {
            if (contactChkList[x] != undefined)
            {
                contactChkList[x].checked = false;
            }
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

function disableDO(idx)
{
    if (idx == undefined)
        return;

    if (idx<0 || idx >= MaxIPCam)
        return;
    try {
        if (digitalOutputChkList[idx] != undefined)
        {
            for (var y=0; y<digitalOutputChkList[idx].length; y++)
            {
                if (digitalOutputChkList[idx][y] != undefined)
                {
                    digitalOutputChkList[idx][y].disabled = true;
                    digitalOutputChkList[idx][y].checked = false;
                }
            }
        }
    } catch (e) { errorReport(e); }
}

function onResetDOList()
{
    try
    {
        for (var x in digitalOutputChkList)
        {
            if (digitalOutputChkList[x] != undefined)
            {
                for (var y=0; y<digitalOutputChkList[x].length; y++)
                {
                    if (digitalOutputChkList[x][y] != undefined)
                    {
                        digitalOutputChkList[x][y].checked = false;
                        digitalOutputChkList[x][y].disabled = false;
                    }
                }
            }
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

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

    var targetID = target.id;
    var ch = eventType = eventID = pinNum = undefined;
    var enableStatus = target.checked; // disable or enable this event

    try
    {
        if (targetID.indexOf('connlost-') == 0) // conn. lost event
        {
            ch = parseInt(targetID.substr(9), 10); // strlen('connlost-') = 9
            eventType = EventTypes['camera'];
            eventID = CameraEventTypes['connlost'];
        }
        else if (targetID.indexOf('motion-') == 0) // motion event
        {
            ch = parseInt(targetID.substr(7), 10);
            eventType = EventTypes['camera'];
            eventID = CameraEventTypes['motion'];
        }
        else if (targetID.indexOf('io-') == 0) // io event
        {
            ch = parseInt(targetID.substr(3), 10);
            pinNum = parseInt(targetID.substr(targetID.lastIndexOf('-')+1), 10);
            eventType = EventTypes['camera'];
            eventID = CameraEventTypes['io'];
        }
        else if (targetID == 'diskexhausted') // disk event
        {
            eventType = EventTypes['system'];
            eventID = SystemEventTypes['disk'];
        }
        //alert('(' + ch + ', ' + eventType + ', ' + eventID + ', ' + pinNum + ')');
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }

    var data = undefined;
    try
    {
        if (EventTypes['system'] == eventType)
        {
            for (var key in SystemEventTypes)
            {
                if (SystemEventTypes[key] == eventID)
                {
                    data = SystemInfo[key];
                }
            }
        }
        else if (EventTypes['camera'] == eventType)
        {
            for (var key in CameraEventTypes)
            {
                if (CameraEventTypes[key] == eventID)
                {
                    if (CameraEventTypes['io'] == eventID)
                    {
                        data = CameraInfo[ch][key][pinNum];
                    }
                    else
                    {
                        data = CameraInfo[ch][key];
                    }
                }
            }
        }
        else
        {
            //alert("error!");
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }

    if (data != undefined)
    {
        //alert("Event status: " + data['enable'] + " => " + enableStatus);
        data['enable'] = enableStatus;
    }
}

function InitializeEventTree()
{
try
{
    var contextElementsID = new Array();
    var contextElementsTitle = new Array();
    var listener = new Array();
    eventTree = new YAHOO.widget.TreeView("EventTree");
    for (var i=0; i<MaxIPCam; i++)
    {
        var cameraNameStr = (CameraInfo ? CameraInfo[i]['CameraName'] : undefined) || 'Camera ' + (i+1);
        var cameraFullName = (CameraInfo && CameraInfo[i]['CameraFullName'] ? CameraInfo[i]['CameraFullName'] : cameraNameStr);
        //var tmpNode = new YAHOO.widget.MenuNode({label: cameraNameStr, nodeType: NodeTypes['camera']}, eventTree.getRoot(), false);
        var tmpNode = new YAHOO.widget.TextNode({label: cameraNameStr, nodeType: NodeTypes['camera']}, eventTree.getRoot(), false);
        tmpNode.nodeType = NodeTypes['camera'];
        tmpNode.cameraIndex = i;
        contextElementsID.push(tmpNode.labelElId);
        contextElementsTitle.push(myEscape(cameraFullName));


        var connLostLabel = '<input name="eventStatus" id="connlost-' + i + '" type="checkbox"';
        if (CameraInfo && CameraInfo[i] && CameraInfo[i]['connlost'] && CameraInfo[i]['connlost']['enable'])
        {
            connLostLabel += ' checked';
        }
        connLostLabel += '> Connection Lost';
        listener.push('connlost-' + i);
        //var connLostNode = new YAHOO.widget.MenuNode({label: connLostLabel, nodeType: NodeTypes['event']}, tmpNode, false);
        var connLostNode = new YAHOO.widget.TextNode({label: connLostLabel, nodeType: NodeTypes['event']}, tmpNode, false);
        connLostNode.nodeType = NodeTypes['event'];
        connLostNode.cameraIndex = i;
        connLostNode.eventType = EventTypes['camera'];
        connLostNode.eventID = CameraEventTypes['connlost'];

        if (hasMotion && MotionInfo && MotionInfo[i])
        {
            var motionLabel = '<input name="eventStatus" id="motion-' + i + '" type="checkbox"';
            if (CameraInfo && CameraInfo[i] && CameraInfo[i]['motion'] && CameraInfo[i]['motion']['enable'])
            {
                motionLabel += ' checked';
            }
            motionLabel += '> Motion Detected';
            listener.push('motion-' + i);
            //var motionNode = new YAHOO.widget.MenuNode({label: motionLabel, nodeType: NodeTypes['event']}, tmpNode, false);
            var motionNode = new YAHOO.widget.TextNode({label: motionLabel, nodeType: NodeTypes['event']}, tmpNode, false);
            motionNode.nodeType = NodeTypes['event'];
            motionNode.cameraIndex = i;
            motionNode.eventType = EventTypes['camera'];
            motionNode.eventID = CameraEventTypes['motion'];
        }
        if (hasINPUT && INPUTInfo && INPUTInfo[i])
        {
            var ios = INPUTInfo[i];
            if ((ios != undefined) && (ios.length>0))
            {
                var evset = (CameraInfo && CameraInfo[i] && CameraInfo[i]['io'] ? CameraInfo[i]['io'] : undefined);
                for (var j=0; j<ios.length; j++)
                {
                    var ioLabel = '<input name="eventStatus" id="io-' + i + '-' + j + '" type="checkbox"';
                    if (evset && evset[j]['enable'])
                    {
                        ioLabel += ' checked';
                    }
                    ioLabel += '> ' + cameraNameStr + " Input#" + j;
                    listener.push('io-' + i + '-' + j);
                    //var ioNode = new YAHOO.widget.MenuNode({label: ioLabel, nodeType: NodeTypes['event']}, tmpNode, false);
                    var ioNode = new YAHOO.widget.TextNode({label: ioLabel, nodeType: NodeTypes['event']}, tmpNode, false);
                    ioNode.nodeType = NodeTypes['event'];
                    ioNode.cameraIndex = i;
                    ioNode.eventType = EventTypes['camera'];
                    ioNode.eventID = CameraEventTypes['io'];
                    ioNode.pinNum = j;
                }
            }
        }
    }

    //var systemNode = new YAHOO.widget.MenuNode({label: 'System', nodeType: NodeTypes['system']}, eventTree.getRoot(), false);
    var systemNode = new YAHOO.widget.TextNode({label: 'System', nodeType: NodeTypes['system']}, eventTree.getRoot(), false);
    systemNode.nodeType = NodeTypes['system'];
    var diskLabel = '<input name="eventStatus" id="diskexhausted" type="checkbox"';
    if (SystemInfo && SystemInfo['disk'] && SystemInfo['disk']['enable'])
    {
        diskLabel += ' checked';
    }
    diskLabel += '> Hard Disk Space Full';
    listener.push('diskexhausted');
    //var diskNode = new YAHOO.widget.MenuNode({label: diskLabel, nodeType: NodeTypes['event']}, systemNode, false);
    var diskNode = new YAHOO.widget.TextNode({label: diskLabel, nodeType: NodeTypes['event']}, systemNode, false);
    diskNode.nodeType = NodeTypes['event'];
    diskNode.eventType = EventTypes['system'];
    diskNode.eventID = SystemEventTypes['disk'];

    eventTree.subscribe("labelClick", onTreeLabelClick);
    eventTree.draw();

    for (var x=0; x<contextElementsID.length; x++)
    {
        if (contextElementsTitle[x]!=undefined)
            Dom.get(contextElementsID[x]).setAttribute("title", contextElementsTitle[x]);
    }

    // add listener on checkboxs
    for (var j=0; j<listener.length; j++)
    {
        Event.on(listener[j], 'click', onEventStatusClick);
    }

    eventTree.expandAll();

    if (window.top != self)
    {
        if (parent.frames[0].parent != undefined && typeof parent.frames[0].parent.resizeMe == 'function')
            parent.frames[0].parent.resizeMe();
    }
    eventTree.collapseAll();

} catch (e) {errorReport(e);}
}

function formatAction(elCell, oRecord, oColumn, oData)
{
    var oAction = oRecord.getData("action");
    if (oAction == ActionTypes['output'])
    {
        elCell.innerHTML = 'Output';
    }
    else if (oAction == ActionTypes['email'])
    {
        elCell.innerHTML = 'Email';
    }
    else
    {
        elCell.innerHTML = 'error: ' + oAction;
    }
    //alert(oAction);
}

function formatOptions(elCell, oRecord, oColumn, oData)
{
    try
    {
        var oAction = oRecord.getData("action");
        if (oAction == ActionTypes['email'])
        {
            elCell.innerHTML = '';
            var oContactors = oRecord.getData("options");
            if (oContactors && oContactors.length>0 && ContactList)
            {
                for (var i=0; i<oContactors.length; i++)
                {
                    if (ContactList[oContactors[i]])
                    {
                        elCell.innerHTML += ContactList[oContactors[i]]['name'];
                        if (i != (oContactors.length-1))
                           elCell.innerHTML += ',';
                    }
                }
            }
            else
            {
                //alert("formatOptions: " + oContactors);
                //alert("formatOptions: " + ContactList);
                //alert("formatOptions: " + oContactors.length);
                elCell.innerHTML += '&nbsp;';
            }
        }
        else if (oAction == ActionTypes['output'])
        {
            elCell.innerHTML = '';
            var oDO = oRecord.getData("options");
            if ((oDO != undefined) && oDO.length>0)
            {
                elCell.innerHTML = 'Trigger:<br>';
                for (var i=0; i<oDO.length; i++)
                {
                    var chIdx = oDO[i][0];
                    var pinNum = oDO[i][1];
                    if (chIdx != NaN && pinNum != NaN)
                    {
                        var cameraName = (CameraInfo[chIdx] ? CameraInfo[chIdx]['CameraName'] : 'Camera ' + (chIdx + 1));
                        if (cameraName == '')
                            cameraName = 'Camera ' + (chIdx + 1);
                        elCell.innerHTML += '&nbsp;&nbsp;&nbsp;&nbsp;Output#' + pinNum + ' on ' + cameraName + '<br>';
                    }
                }
            }
            else
            {
                elCell.innerHTML = '&nbsp;';
            }
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

function InitializeActionTable()
{
try
{
    this.myDayDataSource = new YAHOO.util.DataSource([]);
    this.myDayDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
    this.myDayDataSource.responseSchema = { fields: ["action", "options", "channelIndex", "enentType", "eventID", "pinNum"] };

    this.myDayColumnDefs = [
        {key:"action", label: "Action", formatter:this.formatAction},
        {key:"options", label: "Options", formatter:this.formatOptions}
    ];
    actionTable = new YAHOO.widget.DataTable("ActionList", this.myDayColumnDefs, this.myDayDataSource);
    actionTable.set("selectionMode", "single");
    actionTable.subscribe("rowClickEvent", actionTable.onEventSelectRow);
    actionTable.subscribe("cellClickEvent", onModifyAction);

    Event.on(window, 'resize', function() { actionTable.refreshView(); }, this, true);
    //alert("InitializeActionTable() OK!");
} catch (e) {errorReport(e);}
}

function InitializeButtons()
{
try
{
    /*
    var addEventButton = new YAHOO.widget.Button({label:"Add", id:"addEventButton", value: "1", container:"EventButtons", onclick: {fn: onAddEvent}});
    addEventButton.addClass("ltButton");
    eventButtons.push(addEventButton);

    var delEventButton = new YAHOO.widget.Button({label:"Del", id:"delEventButton", value: "2", container:"EventButtons", onclick: {fn: onDelEvent}});
    delEventButton.addClass("ltButton");
    eventButtons.push(delEventButton);
    */ 
    var confEventButton = new YAHOO.widget.Button({label:"Configure", id:"confEventButton", value: "3", container:"EventButtons", onclick: {fn: onConfEvent}});
    confEventButton.addClass("ltButton");
    eventButtons.push(confEventButton);

    var addActionButton = new YAHOO.widget.Button({label:"Add", id:"addActionButton", value: "1", container:"ActionButtons", onclick: {fn: onAddAction}});
    addActionButton.addClass("ltButton");
    actionButtons.push(addActionButton);

    actionsMenu = new YAHOO.widget.Menu("actionsMenu", { constraintoviewport: true, context: ["ActionButtons", "tr", "tl"] });
    actionsMenu.addItems([{text: "Output", value: ActionTypes['output'], onclick: { fn: onAddActionClick }}, {text: "E-Mail", value: ActionTypes['email'], onclick: { fn: onAddActionClick }}]);
    actionsMenu.render("ActionsMenu");
    actionsMenu.subscribe("show", actionsMenu.focus);
    //var actionMenus = [{text: 'Output', value: ActionTypes['output'], lazyloadmenu: false, disabled: true, onclick: { fn: onAddActionClick }}, {text: 'Email', value: ActionTypes['email'], disabled: true, onclick: { fn: onAddActionClick }}];
    //var addActionButton = new YAHOO.widget.Button({id:"addActionButton", container:"ActionButtons", label:"Add", type: "split", menu: actionMenus});
    //addActionButton.addClass("ltButton");
    //actionButtons.push(addActionButton);

    var delActionButton = new YAHOO.widget.Button({label:"Delete", id:"delActionButton", value: "2", container:"ActionButtons", onclick: {fn: onDelAction}});
    delActionButton.addClass("ltButton");
    actionButtons.push(delActionButton);

    var confActionButton = new YAHOO.widget.Button({label:"Configure", id:"confActionButton", value: "3", container:"ActionButtons", onclick: {fn: onConfAction}});
    confActionButton.addClass("ltButton");
    actionButtons.push(confActionButton);

    SetEventButtonsStatus(0);
    SetActionButtonsStatus(0);
} catch (e) {errorReport(e);}
}

function InitializeContractDialog()
{
    var buttonsCfg = [
        {text: 'Ok', handler: {fn: onContactOk}},
        {text: 'Cancel', handler: {fn: onContactCancel}}
    ];
    contactDialog = new YAHOO.widget.Dialog("ContactDialog", {width:"480px", visible:false, draggable:false, close:false, modal:true, fixedcenter:false, buttons: buttonsCfg} );
    contactDialog.setHeader("Contact List");

    var htmlBody = '';
    if (ContactList != undefined && ContactList.length>0)
    {
        htmlBody += '<table id="ContactListTable">';
        for (var i=0; i<ContactList.length; i++)
        {
            htmlBody += '<tr><td class="clt-checkbox"><input type="checkbox" name="chkCLT" id="chkCLT-' + i + '" value="' + i + '" /></td><td class="clt-name">' + ContactList[i]['name'] + '</td><td class="clt-email">&lt;' + ContactList[i]['email'] + '&gt;</td></tr>';
        }
        htmlBody += '</table>';
    }
    else
    {
    }

    contactDialog.setBody(htmlBody);
    contactDialog.render("ContactList");

    for (var i=0; i<ContactList.length; i++)
    {
        var x = Dom.get("chkCLT-"+i);
        contactChkList.push(x);
    }
}

function InitializeDigitalOutputDialog()
{
    var buttonsCfg = [
        {text: 'Ok', handler: {fn: onDOOk}},
        {text: 'Cancel', handler: {fn: onDOCancel}}
    ];

    digitalOutputDialog = new YAHOO.widget.Dialog("DODialog", {width:"480px", visible:false, draggable:false, close:false, modal:true, fixedcenter:false, buttons: buttonsCfg} );
    digitalOutputDialog.setHeader("Digital Output List");

    var htmlBody = '';
    if (hasOUTPUT && OUTPUTInfo)
    {
        htmlBody += '<table id="DigitalOutputListTable">';
        for (var i=0; i<OUTPUTInfo.length; i++)
        {
            var cameraName = (CameraInfo[i] && CameraInfo[i]['CameraName'] ? CameraInfo[i]['CameraName'] : 'Camera ' + (i+1));
            for (var j=0; j<OUTPUTInfo[i].length; j++)
            {
                if (OUTPUTInfo[i][j])
                {
                    htmlBody += '<tr><td class="dolt-checkbox"><input type="checkbox" name="chkDO" id="chkDO-' + i + '-' + j + '" value="' + i + '" /></td><td class="dolt-name">Digital Output#' + j + ' on ' + cameraName + '</td></tr>';
                }
            }
        }
        htmlBody += '</table>';
    }

    digitalOutputDialog.setBody(htmlBody);
    digitalOutputDialog.render("DigitalOutputDialog");

    try
    {
        if (hasOUTPUT && OUTPUTInfo)
        {
            for (var i=0; i<OUTPUTInfo.length; i++)
            {
                digitalOutputChkList[i] = new Array();
                for (var j=0; j<OUTPUTInfo[i].length; j++)
                {
                    digitalOutputChkList[i][j] = Dom.get('chkDO-' + i + '-' + j);
                }
            }
        }
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

function InitializeEventConfDialog()
{
    try {
        var buttonsCfg = [
            {text: 'Ok', handler: {fn: onEventConfOk}},
            {text: 'Cancel', handler: {fn: onEventConfCancel}}
        ];
        eventConfDialog = new YAHOO.widget.Dialog("EventConfDialog1", {width:"480px", visible:false, draggable:false, close:true, modal:true, fixedcenter:false, buttons: buttonsCfg} );
        eventConfDialog.setHeader("Event Configuration");
        eventConfDialog.subscribe("cancel", function()
            {
                var d = Dom.get("iotype");
                if (d!=undefined)
                {
                    Dom.setStyle(d, "visibility", "hidden");
                    Dom.setStyle(d, "display", "none");
                }
        });

        var htmlBody = '';

        htmlBody += '<input type="checkbox" id="enableEventChk" name="enableEvent" value="1" /> Enable Event<br/>';
        //htmlBody += '<fieldset id="lifecycle"><legend>Life Cycle</legend><input type="radio" id="automaticCancel" name="eventcancel" value="autoCancel" />Automatic cancel event when event disappear<br /><input type="radio" id="manualCancel" name="eventcancel" value="manualCancel" />Manual cancel event or event last triggered<br /></fieldset>';
        htmlBody += '<fieldset id="activeperiod"><legend>Activation Period</legend><input type="radio" id="alwaysActive" name="activeTimeType" value="always"/>Always Active<br /><input type="radio" id="periodActive" name="activeTimeType" value="period"/>Activate according to set schedule<br /><div id="periodTimeArea"><input type="text" name="activeSH" value="00" id="activeSH" class="timeField" />:<input type="text" name="activeSM" value="00" id="activeSM" class="timeField" /> to <input type="text" name="activeEH" value="00" id="activeEH" class="timeField" />:<input type="text" name="activeEM" value="00" id="activeEM" class="timeField" /></div></fieldset>';
        htmlBody += '<fieldset id="iotype"><legend>IO Type</legend><input type="radio" id="iotypeno" name="iotype" value="no" /> N/O<br><input type="radio" id="iotypenc" name="iotype" value="nc" /> N/C<br></field>';

        eventConfDialog.setBody(htmlBody);
        eventConfDialog.render("EventConfDialog");

        eventConfElements.push( Dom.get("enableEventChk") );
        eventConfElements.push( null ); //eventConfElements.push( Dom.get("automaticCancel") );
        eventConfElements.push( null ); //eventConfElements.push( Dom.get("manualCancel") );
        eventConfElements.push( Dom.get("alwaysActive") );
        eventConfElements.push( Dom.get("periodActive") );
        eventConfElements.push( Dom.get("iotypeno") );
        eventConfElements.push( Dom.get("iotypenc") );

        activeTimeFields['startHour'] = Dom.get("activeSH");
        activeTimeFields['startMinute'] = Dom.get("activeSM");
        activeTimeFields['endHour'] = Dom.get("activeEH");
        activeTimeFields['endMinute'] = Dom.get("activeEM")
        Event.addListener("alwaysActive", "click", function(ev) { for (var x in activeTimeFields) {activeTimeFields[x].disabled = true;} });
        Event.addListener("periodActive", "click", function(ev) { for (var x in activeTimeFields) {activeTimeFields[x].disabled = false;} });
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

function SetEventButtonsStatus(st)
{
/*    for (var i=0; i<eventButtons.length; i++)
    {
        if (eventButtons[i] == undefined)
            continue;

        if (st & Math.pow(2,i))
        {
            eventButtons[i].set('disabled', false);
        }
        else
        {
            eventButtons[i].set('disabled', true);
        }
    }
*/

    if (st)
        eventButtons[0].set('disabled', false);
    else
        eventButtons[0].set('disabled', true);
}

function SetActionButtonsStatus(st)
{
    for (var i=0; i<actionButtons.length; i++)
    {
        if (actionButtons[i] == undefined)
            continue;

        if (st & Math.pow(2,i))
        {
            actionButtons[i].set('disabled', false);
            if (0 == i)
            { // enable add action button
                try 
                {
                    var selectedRows = actionTable.getSelectedRows();
                    var rs = (actionTable ? actionTable.getRecordSet() : undefined);
                    var records = rs.getRecords();
                    var items = actionsMenu.getItems();
                    var curItems = items.length;
                    if (curItems>0)
                    {
                        for (;curItems>0; curItems--)
                        {
                            actionsMenu.removeItem(curItems-1);
                        }
                    }
                    var menuitems = undefined;
                    if (records.length == 0)
                    {// enable all actions
                        menuitems = [
                            {text: "Output", value: ActionTypes['output'], onclick: { fn: onAddActionClick }},
                            {text: "E-Mail", value: ActionTypes['email'], onclick: { fn: onAddActionClick }} ];
                    }
                    else if (records.length == 1)
                    {
                        var ac = records[0].getData("action");
                        if (ac == ActionTypes['output'])
                        {
                            menuitems = [ {text: "E-Mail", value: ActionTypes['email'], onclick: { fn: onAddActionClick }} ];
                        }
                        else if (ac == ActionTypes['email'])
                        {
                            menuitems = [ {text: "Output", value: ActionTypes['output'], onclick: { fn: onAddActionClick }} ];
                        }
                    }
                    else
                    {// ??? disable this button
                    }
                    actionsMenu.addItems(menuitems);
                    actionsMenu.render();
                }
                catch (e)
                {
                    //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
                    errorReport(e);
                }
            }
        }
        else
        {
            actionButtons[i].set('disabled', true);
        }
    }
}

function SetActionTable(node)
{
    if (actionTable == undefined || node == undefined)
        return;

    var ch = node.cameraIndex;
    var eventType = node.eventType;
    var eventID = node.eventID;
    var pinNum = undefined;

    var rs = (actionTable ? actionTable.getRecordSet() : undefined);

    if (eventType == EventTypes['camera'])
    {
        //alert("Camera Event#" + eventID + " with camera#" + ch);
        if (rs == undefined || CameraInfo[ch] == undefined)
            return;

        var chIdx = parseInt(ch, 10);
        var data = undefined;
        if (eventID == CameraEventTypes['connlost'])
        {
            data = (CameraInfo[chIdx]['connlost'] ? CameraInfo[chIdx]['connlost']['action'] : undefined);
        }
        else if (eventID == CameraEventTypes['motion'])
        {
            data = (CameraInfo[chIdx]['motion'] ? CameraInfo[chIdx]['motion']['action'] : undefined);
        }
        else if (eventID == CameraEventTypes['io'])
        {
            pinNum = node.pinNum;
            var pinNumIdx = ((pinNum != undefined) ? parseInt(pinNum, 10) : undefined);
            data = (( (pinNumIdx != undefined) && (CameraInfo[chIdx]['io']!=undefined) && (CameraInfo[chIdx]['io'][pinNumIdx]!=undefined) ) ? CameraInfo[chIdx]['io'][pinNumIdx]['action']: undefined);
        }

        if (data && data.length>0)
        {
            rs.deleteRecords(0, rs.getLength());
            for (var i=0; i<data.length; i++)
            {
                var record = rs.addRecord({action: data[i]['action'], channelIndex: ch, eventType: eventType, eventID: eventID, pinNum: pinNum}, 0);
                //if (data[i]['option'] != undefined)
                //{
                    rs.updateKey(record, 'options', data[i]['option']);
                //}
                //if (data[i]['action'] == ActionTypes['email'])
                //{
                    //rs.updateKey(record, 'options', data[i]['option']);
                //}
            }
            actionTable.refreshView();
        }
        else
        {
            rs.deleteRecords(0, rs.getLength());
            actionTable.refreshView();
        }
    }
    else if (eventType == EventTypes['system'])
    {
        //alert("System Event#" + eventID);
        if (eventID == SystemEventTypes['disk'])
        {
            var data = (SystemInfo['disk'] ? SystemInfo['disk']['action'] : undefined);
            if (rs)
            {
                rs.deleteRecords(0, rs.getLength());
            }
            if (rs && data && data.length>0)
            {
                for (var i=0; i<data.length; i++)
                {
                    var record = rs.addRecord({action: data[i]['action'], channelIndex: -1, eventType: eventType, eventID: eventID, pinNum: undefined}, 0);
                    //if (data[i]['option'] != undefined)
                    //{
                        rs.updateKey(record, 'options', data[i]['option']);
                    //}
                    //if (data[i]['action'] == ActionTypes['email'])
                    //{
                        // set contactor in the options field
                        //rs.updateKey(record, 'options', data[i]['option']);
                    //}
                }
            }
            actionTable.refreshView();
        }
        else
        {
            rs.deleteRecords(0, rs.getLength());
            actionTable.refreshView();
        }
    }

    if (rs)
    {
        switch (rs.getLength())
        {
            case 0: // the action table is empty so enable add button.
            case 1: // the action table has one action so users can add action
                SetActionButtonsStatus(1); // just enable add button
                break;
            case 2: // the action table has two action so users can't add any actions
                SetActionButtonsStatus(0); // disable all buttons
                break;
            default:
                //alert("error in rs.getLength()");
                break;
        }
    }
}

function handleSuccess(o)
{
    var statusLine = new String(o.status);
    if (statusLine.match(/^401/))
    {
        handleSessionTimeout();
        return;
    }

    if(o.responseText !== undefined)
    {
        try
        {
            INFO = eval(o.responseText);
        }
        catch (e)
        {
            //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
            errorReport(e);
        }
        MaxIPCam = INFO[0];
        if ((MaxIPCam == undefined) || (MaxIPCam == NaN))
        {
            MaxIPCam = 0;
        }

        MotionInfo = INFO[1][0];
        if (MotionInfo != undefined)
        {
            for (var j=0; j<MotionInfo.length; j++)
            {
                hasMotion |= MotionInfo[j];
            }
        }
        else
        {
            MotionInfo = new Array();
            for (var i=0; i<MaxIPCam; i++)
            {
                MotionInfo[i] = false;
            }
        }

        INPUTInfo = INFO[1][1][0];
        OUTPUTInfo = INFO[1][1][1];
        if (INPUTInfo != undefined)
        {
            for (var j=0; j<INPUTInfo.length; j++)
            {
                for (var k=0; k<INPUTInfo[j].length; k++)
                {
                    hasINPUT |= INPUTInfo[j][k];
                }
            }
        }
        else
        {
            INPUTInfo = new Array();
            for (var i=0; i<MaxIPCam; i++)
            {
                INPUTInfo[i] = new Array();
            }
            hasINPUT = false;
        }
        if (OUTPUTInfo != undefined)
        {
            for (var j=0; j<OUTPUTInfo.length; j++)
            {
                for (var k=0; k<OUTPUTInfo[j].length; k++)
                {
                    hasOUTPUT |= OUTPUTInfo[j][k];
                }
            }
        }
        else
        {
            OUTPUTInfo = new Array();
            for (var j=0; j<OUTPUTInfo.length; j++)
            {
                OUTPUTInfo[i] = new Array();
            }
            hasOUTPUT = false;
        }

        CameraInfo = INFO[2];
        if (CameraInfo == undefined)
        { // we don't have any data so prepare an empty data space
            CameraInfo = new Array();
        }

        // check data space
        for (var ch=0; ch<MaxIPCam; ch++)
        {
            if (CameraInfo[ch] == undefined)
                CameraInfo[ch] = new Array();

            if (CameraInfo[ch]['connlost'] == undefined)
            {
                CameraInfo[ch]['connlost'] = new Array();
                CameraInfo[ch]['connlost']['always'] = true;
                CameraInfo[ch]['connlost']['manual'] = false;
            }

            if (MotionInfo[ch])
            {// have MD
                if (CameraInfo[ch]['motion'] == undefined)
                {
                    CameraInfo[ch]['motion'] = new Array();
                    CameraInfo[ch]['motion']['always'] = true;
                    CameraInfo[ch]['motion']['manual'] = false;
                }
            }

            if (INPUTInfo[ch].length>0)
            {// have di info
            if (CameraInfo[ch]['io'] == undefined)
                    CameraInfo[ch]['io'] = new Array();

                for (var i=0; i<INPUTInfo[ch].length; i++)
                {
                    if (INPUTInfo[ch][i])
                    { // have io pin#i
                        if (CameraInfo[ch]['io'][i] == undefined)
                        {
                            CameraInfo[ch]['io'][i] = new Array();
                            CameraInfo[ch]['io'][i]['always'] = true;
                            CameraInfo[ch]['io'][i]['manual'] = false;
                            CameraInfo[ch]['io'][i]['iotype'] = true;
                        }
                    }
                }
            }
        }
        
        SystemInfo = INFO[3];
        if (SystemInfo == undefined)
        {
            SystemInfo = new Array();
        }
        if (SystemInfo['disk'] == undefined)
        {
            SystemInfo['disk'] = new Array();
            SystemInfo['disk']['always'] = true;
            SystemInfo['disk']['manual'] = false;
        }

        ContactList = INFO[4];
        if (ContactList == undefined)
        {
            ContactList = new Array();
        }

        InitializeEventTree();
        InitializeActionTable();
        InitializeContractDialog();
        InitializeDigitalOutputDialog();
        //alert("OK!");
        //alert("hasMotion: " + hasMotion + ", hasINPUT: " + hasINPUT + ", hasOUTPUT: " + hasOUTPUT);
    }
    /*else
    {
        //alert("o.responseText == undefined");
    } */   
}

function handleFailure(o)
{
    var statusLine = new String(o.status);
    if (statusLine.match(/^401/))
    {
        handleSessionTimeout();
        return;
    }

    //alert("handleFailure:\nHTTP status: " + o.status + "\nStatus code message: " + o.statusText);
    InitializeEventTree();
    InitializeActionTable();
}

function ipcam_event_init()
{
    var sUrl = "/CGI/cgi_main?cmd=event&rand=" + Math.floor(Math.random()*1000);
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, {success:handleSuccess, failure:handleFailure});

    InitializeButtons();
    InitializeActionTable();
    InitializeEventConfDialog();

    Event.addListener(["saveBTN"], "click", submitSave);
    //alert("Initialize ok!");
}

function submitSave()
{
    var submitData0 = Dom.get("submitData0");
    var submitData1 = Dom.get("submitData1");
    if (submitData0 == undefined || submitData1 == undefined)
    {
        //alert("Error: can't get submitData!!");
        return;
    }

    try
    {
        var s = '';
        // write from camera info
        if (CameraInfo)
        {
            var digitalInputCount = 0;
            for (var ch=0; ch<MaxIPCam; ch++)
            {
                var cd = CameraInfo[ch];
                if (cd != undefined)
                {
                    s += '[Camera' + printDigital(ch+1, 2) + ']\r\n';
                    var eventCount = 0;
                    var ss = '';
                    if (cd['motion'] != undefined)
                    {
                        var cdm = cd['motion'];
                        ss += '[Camera' + printDigital(ch+1, 2) + 'Event' + printDigital(eventCount, 2) + ']\r\n';
                        ss += 'Type=' + CameraEventTypes['motion'] + '\r\n';
                        var activeTimeRef = (cdm['activeTime'] != undefined ? cdm['activeTime'] : new Array());
                        ss += 'StartTimeHour=' + (activeTimeRef['startHour'] ? activeTimeRef['startHour'] : "" ) + '\r\n';
                        ss += 'StartTimeMinute=' + (activeTimeRef['startMinute'] ? activeTimeRef['startMinute'] : "" ) + '\r\n';
                        ss += 'EndTimeHour=' + (activeTimeRef['endHour'] ? activeTimeRef['endHour'] : "" ) + '\r\n';
                        ss += 'EndTimeMinute=' + (activeTimeRef['endMinute'] ? activeTimeRef['endMinute'] : "" ) + '\r\n';                
                        ss += 'AlwaysActivate=' + (cdm['always'] ? "1" : "0") + '\r\n';
                        //ss += 'ManualCancel=' + (cdm['manual'] ? "1" : "0") + '\r\n';
                        ss += 'ManualCancel=0\r\n';
                        ss += 'Enable=' + (cdm['enable'] ? "1" : "0") + '\r\n';
                        if ((cdm['action'] != undefined) && cdm['action'].length>0)
                        {
                            ss += 'ActionCount=' + cdm['action'].length + "\r\n";
                            for (var i=0; i<cdm['action'].length; i++)
                            {
                                ss += 'ActionType' + printDigital(i, 2) + '=' + cdm['action'][i]['action'] + '\r\n';
                                //var option = (cdm['action'][i]['option'] ? cdm['action'][i]['option'].join(';') : "");
                                var option = '';
                                if (cdm['action'][i]['action'] == ActionTypes['email'])
                                {
                                    var opArray = cdm['action'][i]['option'];
                                    if (opArray instanceof Array)
                                    {
                                        for (var x=0; x<opArray.length; x++)
                                        {
                                            option += ContactList[ opArray[x] ]['name'] + (x != (opArray.length-1) ? ";" : "");
                                        }
                                    }
                                }
                                else if (cdm['action'][i]['action'] == ActionTypes['output'])
                                {
                                    var opArray = cdm['action'][i]['option'];
                                    if (opArray instanceof Array)
                                    {
                                        for (var x=0; x<opArray.length; x++)
                                        {
                                            option += opArray[x][0] + "," + opArray[x][1] + ';';
                                        }
                                    }
                                }
                                ss += 'ActionOption' + printDigital(i, 2) + '=' + option + '\r\n';
                            }
                        }
                        else
                        {
                            ss += 'ActionCount=0\r\n';
                        }
                        eventCount++;
                    }

                    if (cd['connlost'] != undefined)
                    {
                        var cdc = cd['connlost'];
                        ss += '[Camera' + printDigital(ch+1, 2) + 'Event' + printDigital(eventCount, 2) + ']\r\n';
                        ss += 'Type=' + CameraEventTypes['connlost'] + '\r\n';
                        var activeTimeRef = (cdc['activeTime'] != undefined ? cdc['activeTime'] : new Array());
                        ss += 'StartTimeHour=' + (activeTimeRef['startHour'] ? activeTimeRef['startHour'] : "" ) + '\r\n';
                        ss += 'StartTimeMinute=' + (activeTimeRef['startMinute'] ? activeTimeRef['startMinute'] : "" ) + '\r\n';
                        ss += 'EndTimeHour=' + (activeTimeRef['endHour'] ? activeTimeRef['endHour'] : "" ) + '\r\n';
                        ss += 'EndTimeMinute=' + (activeTimeRef['endMinute'] ? activeTimeRef['endMinute'] : "" ) + '\r\n';
                        ss += 'AlwaysActivate=' + (cdc['always'] ? "1" : "0") + '\r\n';
                        //ss += 'ManualCancel=' + (cdc['manual'] ? "1" : "0") + '\r\n';
                        ss += 'ManualCancel=0\r\n';
                        ss += 'Enable=' + (cdc['enable'] ? "1" : "0") + '\r\n';
                        if ((cdc['action']!=undefined) && (cdc['action'].length>0))
                        {
                            ss += 'ActionCount=' + cdc['action'].length + "\r\n";
                            for (var i=0; i<cdc['action'].length; i++)
                            {
                                ss += 'ActionType' + printDigital(i, 2) + '=' + cdc['action'][i]['action'] + '\r\n';
                                //var option = (cdc['action'][i]['option'] ? cdc['action'][i]['option'].join(';') : "");
                                var option = '';
                                if (cdc['action'][i]['action'] == ActionTypes['email'])
                                {
                                    var opArray = cdc['action'][i]['option'];
                                    if (opArray instanceof Array)
                                    {
                                        for (var x=0; x<opArray.length; x++)
                                        {
                                            option += ContactList[ opArray[x] ]['name'] + (x != (opArray.length-1) ? ";" : "");
                                        }
                                    }
                                }
                                else if (cdc['action'][i]['action'] == ActionTypes['output'])
                                {
                                    var opArray = cdc['action'][i]['option'];
                                    if (opArray instanceof Array)
                                    {
                                        for (var x=0; x<opArray.length; x++)
                                        {
                                            option += opArray[x][0] + "," + opArray[x][1] + ';';
                                        }
                                    }
                                }
                                ss += 'ActionOption' + printDigital(i, 2) + '=' + option + '\r\n';
                            }
                        }
                        else
                        {
                            ss += 'ActionCount=0\r\n';
                        }
                        eventCount++;
                    }
                    s += 'EventCount=' + eventCount + "\r\n";
                    s += ss;

                    // processing io
                    if (cd['io'] != undefined)
                    {
                        for (var i=0; i<cd['io'].length; i++)
                        {
                            var cdio = cd['io'][i];
                            if (cdio != undefined)
                            {
                                s += '[DigitalInputEvent' + printDigital(digitalInputCount, 2) + ']\r\n';
                                s += 'Type=' + CameraEventTypes['io'] + '\r\n';
                                var activeTimeRef = (cdio['activeTime'] != undefined ? cdio['activeTime'] : new Array());
                                s += 'StartTimeHour=' + (activeTimeRef['startHour'] ? activeTimeRef['startHour'] : "" ) + '\r\n';
                                s += 'StartTimeMinute=' + (activeTimeRef['startMinute'] ? activeTimeRef['startMinute'] : "" ) + '\r\n';
                                s += 'EndTimeHour=' + (activeTimeRef['endHour'] ? activeTimeRef['endHour'] : "" ) + '\r\n';
                                s += 'EndTimeMinute=' + (activeTimeRef['endMinute'] ? activeTimeRef['endMinute'] : "" ) + '\r\n';
                                s += 'AlwaysActivate=' + (cdio['always'] ? "1" : "0") + '\r\n';
                                //s += 'ManualCancel=' + (cdio['manual'] ? "1" : "0") + '\r\n';
                                s += 'ManualCancel=0\r\n';
                                s += 'Enable=' + (cdio['enable'] ? "1" : "0") + '\r\n';
                                s += 'Pin=' + i + '\r\n';
                                s += 'Module=Camera ' + (ch+1) + '\r\n';
                                var iotypeStr = (cdio['iotype'] != undefined ? (cdio['iotype'] ? "0" : "1") : "0");
                                s += "IOType=" + iotypeStr  + '\r\n';
                                if ((cdio['action']!=undefined) && (cdio['action'].length>0))
                                {
                                    s += 'ActionCount=' + cdio['action'].length + "\r\n";
                                    for (var j=0; j<cdio['action'].length; j++)
                                    {
                                        s += 'ActionType' + printDigital(j, 2) + '=' + cdio['action'][j]['action'] + '\r\n';
                                        //var option = (cdio['action'][j]['option'] ? cdio['action'][j]['option'].join(';') : "");
                                        var option = '';
                                        if (cdio['action'][j]['action'] == ActionTypes['email'])
                                        {
                                            var opArray = cdio['action'][j]['option'];
                                            if (opArray instanceof Array)
                                            {
                                                for (var x=0; x<opArray.length; x++)
                                                {
                                                    option += ContactList[ opArray[x] ]['name'] + (x != (opArray.length-1) ? ";" : "");
                                                }
                                            }
                                        }
                                        else if (cdio['action'][j]['action'] == ActionTypes['output'])
                                        {
                                            var opArray = cdio['action'][j]['option'];
                                            if (opArray instanceof Array)
                                            {
                                                for (var x=0; x<opArray.length; x++)
                                                {
                                                    option += opArray[x][0] + "," + opArray[x][1] + ';';
                                                }
                                            }
                                        }
                                        s += 'ActionOption' + printDigital(j, 2) + '=' + option + '\r\n';
                                    }
                                }
                                else
                                {
                                    s += 'ActionCount=0\r\n';
                                }
                                digitalInputCount++;
                            }
                        }
                    }
                }
            }
            s += '[DigitalInput]\r\n';
            s += 'EventCount=' + digitalInputCount + '\r\n';
        }
        submitData0.value = s;

        s = '';
        // write from system info
        if (SystemInfo)
        {
            s += '[System]\r\n';
            var diskEvent = SystemInfo['disk'];
            var totalSystemEventCount = 0;
            if (diskEvent != undefined)
            {
                s += "EventCount=1\r\n";
                s += '[SystemEvent00]\r\n';
                s += 'Type=1\r\n';
                var activeTimeRef = (diskEvent['activeTime'] != undefined ? diskEvent['activeTime'] : new Array());
                s += 'StartTimeHour=' + (activeTimeRef['startHour'] ? activeTimeRef['startHour'] : "" ) + '\r\n';
                s += 'StartTimeMinute=' + (activeTimeRef['startMinute'] ? activeTimeRef['startMinute'] : "" ) + '\r\n';
                s += 'EndTimeHour=' + (activeTimeRef['endHour'] ? activeTimeRef['endHour'] : "" ) + '\r\n';
                s += 'EndTimeMinute=' + (activeTimeRef['endMinute'] ? activeTimeRef['endMinute'] : "" ) + '\r\n';
                s += 'AlwaysActivate=' + (diskEvent['always'] ? "1" : "0") + '\r\n';
                //s += 'ManualCancel=' + (diskEvent['manual'] ? "1" : "0") + '\r\n';
                s += 'ManualCancel=0\r\n';
                s += 'Enable=' + (diskEvent['enable'] ? "1" : "0") + '\r\n';
                if ((diskEvent['action']!=undefined) && (diskEvent['action'].length>0))
                {
                    s += 'ActionCount=' + diskEvent['action'].length + "\r\n";
                    for (var i=0; i<diskEvent['action'].length; i++)
                    {
                        s += 'ActionType' + printDigital(i, 2) + '=' + diskEvent['action'][i]['action'] + '\r\n';
                        //var option = (diskEvent['action'][i]['option'] ? diskEvent['action'][i]['option'].join(';') : "");
                        var option = '';
                        if (diskEvent['action'][i]['action'] == ActionTypes['email'])
                        {
                            var opArray = diskEvent['action'][i]['option'];
                            if (opArray instanceof Array)
                            {
                                for (var x=0; x<opArray.length; x++)
                                {
                                    option += ContactList[ opArray[x] ]['name'] + (x != (opArray.length-1) ? ";" : "");
                                }
                            }
                        }
                        else if (diskEvent['action'][i]['action'] == ActionTypes['output'])
                        {
                            var opArray = diskEvent['action'][i]['option'];
                            if (opArray instanceof Array)
                            {
                                for (var x=0; x<opArray.length; x++)
                                {
                                    option += opArray[x][0] + "," + opArray[x][1] + ';';
                                }
                            }
                        }
                        s += 'ActionOption' + printDigital(i, 2) + '=' + option + '\r\n';
                    }
                }
                else
                {
                    s += 'ActionCount=0\r\n';
                }
            }
            else
            {
                s += 'EventCount=0';
            }
        }
        submitData1.value = s;

        //alert(submitData0.value); alert(submitData1.value);
        //submitData.value = s;
        document.submitEventAction.submit();
    }
    catch (e)
    {
        //alert('error at ' + e.lineNumber + ' in ' + e.fileName + ": " + e);
        errorReport(e);
    }
}

YAHOO.widget.DataTable.prototype.showTableMessage = function(sHTML, sClassName)
{
    if (sClassName == YAHOO.widget.DataTable.CLASS_LOADING)
    {
        sHTML = "&nbsp;";
    }
    else if (sClassName == YAHOO.widget.DataTable.CLASS_EMPTY)
    {
        sHTML = "&nbsp;";
    }

    var elCell = this._elMsgTd;
    if(YAHOO.lang.isString(sHTML))
    {
        elCell.innerHTML = sHTML;
    }
    if(YAHOO.lang.isString(sClassName))
    {
        Dom.addClass(elCell, sClassName);
    }
    if (sClassName == YAHOO.widget.DataTable.CLASS_EMPTY)
    {
        Dom.removeClass(elCell, YAHOO.widget.DataTable.CLASS_LOADING);
    }
    this._elMsgTbody.style.display = "";
    this.fireEvent("tableMsgShowEvent", {html:sHTML, className:sClassName});
};

