var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var tree;
var statusButtonGroup;
var modeButtonGroup;
var modifyButtonGroup = new Array();;
var tableView;
//var weekStr = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var weekStr = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var wsTypes = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var MaxIPCam;
var CameraInfo;
var MotionInfo;
var IOInfo;
var currData = {};
var preHighlight;
var confDlg;
var hasMotion = false;
var MotionIds = new Array();
var hasIO = false;
var IOIds = new Array();

var ScheduleStatus = false;

var COLOR_ALWAYS = "#FF0000";
var COLOR_EVENT = "#0000FF";
var ONEDALENGTH = 24 * 3 * 5; // 24hr, 4 cells every hour, 5px every cell

var StatusOnNormal = 0;
var StatusOnDrag = 1;

var ScheduleMode;

// additional object helper function
Date.prototype.getDayTimeStr = function()
{
try {
    var s;
    var d;

    d = this.getHours();
    if (d>9)
        s = "" + d;
    else
        s = '0' + d;
    s += ':';

    d = this.getMinutes();
    if (d>9)
        s += "" + d;
    else
        s += '0' + d;

    //alert(this.getHours() + ":" + this.getMinutes() + " => " + s);
    return s;
} catch (e) {errorReport(e);}
}

function createDate(h, m, s)
{
try {
    var d = new Date();
    d.setHours(h, m, s, 0);
    return d;
} catch (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});
};
//////////////////////////////////////////////////////////////////////////////////////

// validation functions
function checkTimeValid(rs)
{
    try
    {
        if (rs == undefined)
            return false;

        var records = rs.getRecords();
        if (records == undefined)
            return false;

        for (var j=0; j<records.length-1; j++)
        {
            var currEnd = records[j].getData('endTime');
            var nextStart = records[j+1].getData('startTime');
            if ((currEnd == undefined) || (nextStart == undefined))
            {
                return false;
            }
            var x = currEnd.getHours() * 60 + currEnd.getMinutes();
            var y = nextStart.getHours() * 60 + nextStart.getMinutes();
            if (x>y)
                return false;
        }
    }
    catch (e)
    {
        errorReport(e);
        return false;
    }
    return true;
}

function SetButtonStatusCorrectly()
{
    try {
        if (tableView)
        {
            var selectedRows = tableView.getSelectedRows();
            if (selectedRows == undefined || selectedRows.length<1)
            {
                SetModifyButtonState(1);
                return;
            }
            else
            {
                SetModifyButtonState(7);
            }
        }
        else
        {
            SetModifyButtonState(0);
        }
    } catch (e) { errorReport(e); }
}
//////////////////////////////////////////////////////////////////////////////////////

// submitted data helper functions
function genMotionStr(motion)
{
try {
    if (motion == undefined)
    {
        return '';
    }

    var s = '';
    var elem = new Array();

    for (var k=0; k<motion.length; k++)
    {
        if (motion[k])
        {
            var item = 'C' + ((k>9) ? ""+k : "0"+k) + 'M00';
            elem.push(item);
        }
    }
    if (elem.length>0)
    {
        for (var k=0; k<elem.length; k++)
        {
            s += elem[k];
            if (k != (elem.length -1))
            s += ',';
        }
    }

    //alert(s);
    return s;
} catch (e) {errorReport(e);}
}

function genIOStr(io)
{
    if (io == undefined)
    {
        return '';
    }

    var s = '';
    var elem = new Array();

    for (var k=0; k<io.length; k++)
    {
        if (io[k])
        {
            for (var l=0; l<io[k].length; l++)
            {
                if (io[k][l])
                {
                    var item = 'C' + ((k>9) ? ""+k : "0"+k) + 'I' + ((l>9) ? ""+l : "0"+l);
                    elem.push(item);
                }
            }
        }
    }
    if (elem.length>0)
    {
        for (var k=0; k<elem.length; k++)
        {
            s += elem[k];
            if (k != (elem.length -1))
            s += ',';
        }
    }

    //alert(s);
    return s;
}
//////////////////////////////////////////////////////////////////////////////////////

// date setting/getting helper functions
function setMIField(o)
{
    try
    {
        var t = Dom.get("MIField");
        if (t != undefined)
        {
            if (o)
            {
                Dom.setStyle(t, "visibility", "visible");
                Dom.setStyle(t, "display", "block");
            }
            else
            {
                Dom.setStyle(t, "visibility", "hidden");
                Dom.setStyle(t, "display", "none");
            }
        }
    }
    catch (e)
    {
        errorReport(e);
    }
}

function setCurrDataIntoDlg(currCH, currMode, currWeek)
{
    try
    {
        var dlgCh = Dom.get("DlgCh");
        var dlgMode = Dom.get("DlgMode");
        var dlgWeek = Dom.get("DlgWeek");

        if (dlgCh == undefined || dlgMode == undefined  || dlgWeek == undefined)
        {
            //alert("error in setCurrDataIntoDlg()!" + dlgMode + ", " + dlgWeek + ", " + dlgCh);
            return;
        }
        if (dlgCh != undefined)
        {
            dlgCh.value = currCH;
        }
        if (dlgMode != undefined && dlgWeek != undefined)
        {
            dlgMode.value = currMode;
            dlgWeek.value = currWeek;
        }
    }
    catch (e)
    {
        errorReport(e);
    }
}

function setDialogData(data)
{
    try
    {
        var obj, node;
        var d, d2;

        d = d2 = undefined;
        obj = data['startTime'];
        if (obj)
        {
            d = obj.getHours();
            d2 = obj.getMinutes();
            if (d<10)
                d = "0" + d;
            if (d2<10)
                d2 = "0" + d2;
        }
        node = Dom.get("SHField");
        if ((node != undefined) && (d != undefined)) node.value = d;
        node = Dom.get("SMField");
        if ((node != undefined) && (d2 != undefined))  node.value = d2;

        d = d2 = undefined;
        obj = data['endTime'];
        if (obj)
        {
            d = obj.getHours();
            d2 = obj.getMinutes();
            if ((23 == d) && (59 == d2))
            {
                d = 24;
                d2 = 0;
            }
            if (d<10)
                d = "0" + d;
            if (d2<10)
                d2 = "0" + d2;
        }
        node = Dom.get("EHField");
        if ((node != undefined) && (d != undefined))  node.value = d;
        node = Dom.get("EMField");
        if ((node != undefined) && (d2 != undefined))  node.value = d2;

        d = 5;
        obj = data['preSec'];
        if (obj != undefined)
        {
            d = obj;
        }
        node = Dom.get("preSecField");
        if ((node != undefined) && (d != undefined))  node.value = d;

        d = 5;
        obj = data['postSec'];
        if (obj != undefined)
        {
            d = obj;
        }
        node = Dom.get("postSecField");
        if ((node != undefined) && (d != undefined))  node.value = d;

        d = false;
        obj = data['audio'];
        if (obj != undefined)
        {
            d = obj;
        }
        node = Dom.get("audioEnable");
        if ((node != undefined) && (d != undefined))  node.checked = d;

        d = 0;
        obj = data['recorderType'];
        if (obj != undefined)
        {
            d = obj;
        }
        if (1 == d)
        {
            node = Dom.get("recordEvent");
            if (node != undefined)
                node.click();
            obj = data['motion'];
            if (obj != undefined && obj.length>0)
            {
                //for (var j=0; j<obj.length; j++)
                for (var j in obj)
                {
                    if (obj[j])
                    { // motionDectX
                        var mid = 'motionDect' + j;
                        //alert("Try to find " + mid);
                        node = Dom.get(mid);
                        if (node != undefined)
                        node.checked = true;
                    }
                }
            }
            obj = data['io'];
            if (obj != undefined && obj.length>0)
            {
                //for (var j=0; j<obj.length; j++)
                for (var j in obj)
                {
                    if (obj[j] && obj[j].length>0)
                    {
                        //for (var k=0; k<obj[j].length; k++)
                        for (var k in obj[j])
                        {
                            if (obj[j][k])
                            { // 'ioInputX-Y, ch-pinnum
                                var ioid = 'ioInput' + j + '-' + k;
                                //alert("Try to find " + ioid);
                                node = Dom.get(ioid);
                                if (node != undefined)
                                    node.checked = true;
                            }
                        }
                    }
                }
            }
            setMIField(true);
        }
        else
        {
            node = Dom.get("recordAlways");
            if (node != undefined)
                node.click();
            setMIField(false);
        }
    }
    catch (e)
    {
        errorReport(e);
    }
}

function SetDDLabel(mode)
{
    try
    {
        if (mode)
        {
            for (var i=0; i<weekStr.length; i++)
            {
                Dom.get("dl"+i).innerHTML = weekStr[i];
            }
            for (var i=weekStr.length; i<8; i++)
            {
                Dom.get("dl"+i).innerHTML = "";
            }
        }
        else
        {
            for (var i=0; i<MaxIPCam; i++)
            {
                Dom.get("dl"+i).innerHTML = 'Cam'+(i+1);//CameraInfo[i]['CameraName'];
                var zz = CameraInfo[i]['CameraFullName'];

                if (zz==undefined)
                    zz = CameraInfo[i]['CameraName'];
                if (zz!=undefined)
                    Dom.get("dl"+i).setAttribute("title", zz);
            }
            for (var i=MaxIPCam; i<8; i++)
            {
                Dom.get("dl"+i).innerHTML = "";
            }
        }
        // D-Link only
        var ddx = Dom.get("yui-dt0-labellink1");
        if (ddx!=undefined && ddx.click!=undefined)
            ddx.click();
        var ddy = Dom.get("yui-dt0-labellink0");
        if (ddy!=undefined && ddy.click!=undefined)
            ddy.click();
        // D-Link only end
    }
    catch (e)
    {
        errorReport(e);
    }
}

function SetDataTable(ch, mode, week, noRestore)
{
    try
    {
        //alert("aaa");
        var ret = -1;
        var rs = tableView.getRecordSet();
        if (rs)
        {
            if (!noRestore && currData['ch'] != undefined)
            {
                var target = undefined;
                var rhs;
                if (currData['mode'])
                {
                    var wss = CameraInfo[currData['ch']]['WeekSchedule'];
                    if (wss!=undefined && wss.length>0)
                    {
                        for (var x=0; x<wss.length; x++)
                        {
                            if (wss[x]!=undefined && wss[x].length>0)
                            {
                                if (wss[x][0]['week'] == currData['week'])
                                {
                                    target = wss[x];
                                    break;
                                }
                            }
                        }
                    }
                    if (wss!=undefined && target == undefined)
                    {
                        if (wss.length<7)
                        {
                            wss.push([]);
                            target = wss[ wss.length-1 ];
                        }
                        else
                        {
                            for (var x=0; x<wss.length; x++)
                            {
                                if (wss[x]!=undefined)
                                {
                                    if (wss[x].length == 0)
                                    {
                                        target = wss[x];
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    //target = CameraInfo[currData['ch']]['WeekSchedule'][currData['week']];
                    rhs = rs.getRecords();
                    //CameraInfo[currData['ch']]['WeekSchedule'][currData['week']] = rs.getRecords();
                }
                else
                {
                    target = CameraInfo[currData['ch']]['DaySchedule'];
                    rhs = rs.getRecords();
                    //CameraInfo[currData['ch']]['DaySchedule'] = rs.getRecords();
                }
                if (target != undefined && rhs != undefined)
                {
                    while (target.length)
                    {
                        target.pop();
                    }
                    for (var j=0; j<rhs.length; j++)
                    {
                        target.push(rhs[j].getData());
                    }
                }
            }
    
            var d = undefined;
            if (mode)
            {
                var ws = CameraInfo[ch]['WeekSchedule'];
                for (var x=0; x<ws.length; x++)
                {
                    if (ws[x]!=undefined && ws[x].length>0 && ws[x][0]['week'] !=undefined)
                    {
                        if (ws[x][0]['week'] == week)
                            d = ws[x];
                    }
                }
            }
            else
            {
                d = CameraInfo[ch]['DaySchedule'];
            }

            rs.reset();
            if (d!=undefined)
            {
                rs.addRecords(d, 0);
                rs.sortRecords(sortRecords, false);
            }
            tableView.refreshView();
            //handleResizeMe();
        }
        currData['ch'] = ch;
        currData['mode'] = mode;
        currData['week'] = week;
    }
    catch (e)
    {
        errorReport(e);
    }
    return ret;
}

function SetScheduleStatusButtons()
{
    if (statusButtonGroup == undefined)
        return;

    var buttons = statusButtonGroup.getButtons();
    if (buttons == undefined)
    {
        //alert("SetScheduleStatusButtons() can't get the buttons!\n");
        return;
    }

    if (ScheduleStatus) // schedule is starting!
    {
        try
        {
            for (var i=0; i<buttons.length; i++)
            {
                if (0 == parseInt(buttons[i].get("value"))) // button for starting
                {
                    buttons[i].set("disabled", false);
                    buttons[i].set("clicked", true);
                }
                else
                {
                    buttons[i].set("disabled", false);
                    buttons[i].set("clicked", false);
                }
            }
        }
        catch (e)
        {
            errorReport(e);
        }
    }
    else // schedule is not starting
    {
        try
        {
            for (var i=0; i<buttons.length; i++)
            {
                if (0 == parseInt(buttons[i].get("value"))) // button for starting
                {
                    buttons[i].set("disabled", false);
                    buttons[i].set("clicked", false);
                }
                else
                {
                    buttons[i].set("disabled", true);
                    buttons[i].set("clicked", true);
                }
            }
        }
        catch (e)
        {
            errorReport(e);
        }
    }
}

function SetModifyButtonState(st)
{
    try
    {
        if (modifyButtonGroup == undefined || modifyButtonGroup.length<3)
            return;
    
        // disable all buttons
        modifyButtonGroup[0].set('disabled', true);
        modifyButtonGroup[1].set('disabled', true);
        modifyButtonGroup[2].set('disabled', true);
    
        if (st & 1)
        {
            modifyButtonGroup[0].set('disabled', false);
        }
    
        if (st & 2)
        {
            modifyButtonGroup[1].set('disabled', false);
        }
    
        if (st & 4)
        {
            modifyButtonGroup[2].set('disabled', false);
        }
        //alert("SetModifyButtonState ok!");
    }
    catch (e)
    {
        errorReport(e);
    }
}
function getDialogData()
{
    try
    {
        var lang = YAHOO.lang;
        var data = new Array();
        var node;
        var d, d2;
    
        d = d2 = 0;
        node = Dom.get("SHField");
        if (node != undefined)
        {
            if (!myIsNumber(node.value))
            {
                alert("Your start time is not correct.");
                return {error: node};
            }
            d = parseInt(node.value, 10);
            if (d>24 || d<0)
            {
                alert("Your start time is not correct.");
                return {error: node};
            }
        }
        else
        {
            alert("Your start time is not correct.");
            return {error: true};
        }
        node = Dom.get("SMField");
        if (node != undefined)
        {
            if (!myIsNumber(node.value))
            {
                alert("Your start time is not correct.");
                return {error: node};
            }
            d2 = parseInt(node.value, 10);
            if (d2>59 || d2<0)
            {
                alert("Your start time is not correct.");
                return {error: node};
            }
        }
        else
        {
            alert("Your start time is not correct.");
            return {error: true};
        }
        data['startTime'] = createDate(d, d2, 0);
    
        d = d2 = 0;
        node = Dom.get("EHField");
        if (node != undefined)
        {
            if (!myIsNumber(node.value))
            {
                alert("Your end time is not correct.");
                return {error: node};
            }
            d = parseInt(node.value, 10);
            if (d>24 || d<0)
            {
                alert("Your end time is not correct.");
                return {error: node};
            }
        }
        else
        {
            alert("Your end time is not correct.");
            return {error: true};
        }
        node = Dom.get("EMField");
        if (node != undefined)
        {
            if (!myIsNumber(node.value))
            {
                alert("Your end time is not correct.");
                return {error: node};
            }
            d2 = parseInt(node.value, 10);
            if (d2>59 || d2<0)
            {
                alert("Your end time is not correct.");
                return {error: node};
            }
        }
        else
        {
            alert("Your end time is not correct.");
            return {error: true};
        }
        if ((24 == d) && (00 == d2))
        {
            d = 23;
            d2 = 59;
        }
        else if ((24 == d) && (00 != d2))
        {
            alert("Your end time is not correct.");
            return {error: node};
        }
        data['endTime'] = createDate(d, d2, 0);
    
        // check time valid
        var x = data['startTime'].getHours() * 60 + data['startTime'].getMinutes();
        var y = data['endTime'].getHours() * 60 + data['endTime'].getMinutes();
        if (x >= y)
        {
            alert("The start time is not small than end time!");
            return {error: true};
        }
    
        d = undefined;
        node = Dom.get("recordAlways");
        if (node != undefined && node.checked)
        {
            d = 0;
        }
        else
        {
            node = Dom.get("recordEvent");
            if (node != undefined && node.checked)
            {
                d = 1;
                data['motion'] = new Array();
                if (hasMotion)
                {
                    for (var j=0; j<MotionIds.length; j++)
                    {
                        var node = Dom.get(MotionIds[j]);
                        if ((node != undefined) && node.checked && (node.value != undefined))
                        {
                            data['motion'][parseInt(node.value, 10)] = true;
                        }
                    }
                }

                if (hasIO)
                {
                    var m = new Array();
                    for (var j=0; j<MaxIPCam; j++)
                    {
                        m.push([]);
                    }
                    var re = new RegExp(/ioInput(\d+)-(\d+)/);
                    for (var j=0; j<IOIds.length; j++)
                    {
                        var node = Dom.get(IOIds[j]);
                        if ((node != undefined) && node.checked)
                        { // 'ioInputX-Y, ch-pinnum
                            var res = re.exec(IOIds[j]);
                            if (res != null)
                            {
                                m[parseInt(res[1], 10)][parseInt(res[2], 10)] = true;
                                //alert(parseInt(res[1], 10) + ", " + parseInt(res[2], 10));
                            }
                        }
                    }
                    data['io'] = m;
                }
                else
                {
                    data['io'] = [];
                }
            }
        }
        if (d !== undefined)
        {
            data['recorderType'] = d;
            if (0 == d)
            {
                data['motion'] = [];
                data['io' ] = [];
            }
        }
        else
        {
            //alert("Can't decide recorderType!");
            return {error: true};
        }
    
        d = 0;
        node = Dom.get("audioEnable");
        if (node != undefined && node.checked)
            d = 1;
        data['audio'] = d;
    
        d = 5;
        node = Dom.get("preSecField");
        if (node != undefined)
        {
            if (!myIsNumber(node.value))
            {
                alert("Your pre-recording time is not correct");
                return {error: node};
            }
            d = parseInt(node.value, 10);
            if (d>60 || d<1)
            {
                alert("Your pre-recording time is not correct");
                return {error: node};
            }
        }
        data['preSec'] = d;
    
        d = 5;
        node = Dom.get("postSecField");
        if (node != undefined)
        {
            if (!myIsNumber(node.value))
            {
                alert("Your post-recording time is not correct");
                return {error: node};
            }
            d = parseInt(node.value, 10);
            if (d>60 || d<1)
            {
                alert("Your post-recording time is not correct");
                return {error: node};
            }
        }
        data['postSec'] = d;

        d = -1;
        node = Dom.get("DlgWeek");
        if (node != undefined) d = parseInt(node.value, 10);
        if (d != NaN) data['week'] = d;
    }
    catch (e)
    {
        errorReport(e);
    }

    return data;
}
//////////////////////////////////////////////////////////////////////////////////////

// tree view helper functions
function removeWeekNodes()
{
    try
    {
        var cameraNameNodes = tree.getNodesByProperty("cameraNameNode", 1);
        if (! cameraNameNodes || cameraNameNodes.length <1)
        {
            //alert("! cameraNameNodes || cameraNameNodes.length <1");
            return;
        }
    
        for (var i=0; i<cameraNameNodes.length; i++)
        {
           tree.removeChildren(cameraNameNodes[i]);
        }
        tree.draw();
        //alert("removeWeekNodes() ok!");
    }
    catch (e)
    {
        errorReport(e);
    }
}

function addWeekNodes()
{
    try
    {    
        var cameraNameNodes = tree.getNodesByProperty("cameraNameNode", 1);
        if (! cameraNameNodes || cameraNameNodes.length <1)
        {
            //alert("! cameraNameNodes || cameraNameNodes.length <1");
            return;
        }
    
        for (var i=0; i<cameraNameNodes.length; i++)
        {
            for (var j=0; j<weekStr.length; j++)
            {
                var tmpNode = new YAHOO.widget.MenuNode({label: weekStr[j], nodeType: true}, cameraNameNodes[i], true);
                tmpNode.nodeType = true;
                tmpNode.cameraIndex = i;
                tmpNode.week = j;
            }
        }
        tree.draw();
        //alert("addWeekNodes() ok!");
    }
    catch (e)
    {
        errorReport(e);
    }
}
//////////////////////////////////////////////////////////////////////////////////////

// table view helper functions
function formatTime(elCell, oRecord, oColumn, oData)
{
    var tt;
    var z;
    z = oData.getHours();
    tt = (z>9) ? z + ":" : "0" + z + ":";
    zz = oData.getMinutes();
    tt += (zz>9) ? zz : "0" + zz;
    if (z == 23 && zz == 59)
    {
        tt = "24:00";
    }
    elCell.innerHTML = '<div class="timeRep">' + tt + '</div>';
}

function formatAudio(elCell, oRecord, oColumn, oData)
{
    var isAudio = parseInt(oRecord.getData("audio"), 10);
    if (isAudio != 0)
        elCell.innerHTML = "Enable";
    else
        elCell.innerHTML = "Disable";
}

function sortRecords(a, b, desc)
{
    if(!YAHOO.lang.isValue(a))
    {
        return (!YAHOO.lang.isValue(b)) ? 0 : 1;
    }
    else if(!YAHOO.lang.isValue(b))
    {
        return -1;
    }

    var comp = YAHOO.util.Sort.compare;
    var compState = 0;
    var tmpA, tmpB;
    tmpA = parseInt(a.getData("week"), 10);
    tmpB = parseInt(b.getData("week"), 10);
    if (tmpB>=0 && tmpA>=0)
    {
        compState = comp(tmpA, tmpB, desc);
    }
    if (compState!=0)
    {
        return compState;
    }

    var da = a.getData("startTime");
    var db = b.getData("startTime");
    compState = comp(da.getHours(), db.getHours(), desc);
    if (compState != 0)
    {
        return compState;
    }
    compState = comp(da.getMinutes(), db.getMinutes(), desc);
    if (compState != 0)
    {
        return compState;
    }
    da = a.getData("endTime");
    db = b.getData("endTime");
    compState = comp(da.getHours(), db.getHours(), desc);
    if (compState != 0)
    {
        return compState;
    }
    return comp(da.getMinutes(), db.getMinutes(), desc);
};

function formatType(elCell, oRecord, oColumn, oData)
{
    var sType;
    switch (parseInt(oRecord.getData("recorderType"), 10))
    {
        case 0:
            sType = "Always";
            break;
        case 1:
            sType = "Event";
            break;
        default:
            sType = "";
            break;
    }
    elCell.innerHTML = "<div class=\"recordType\">" + sType + "</div>";
}
//////////////////////////////////////////////////////////////////////////////////////

// dialog helper functions
function clearDialog(deepest)
{
    try
    {
        var node;
    
        node  = Dom.get("SHField");
        if (node != undefined)  node.value = "00";
    
        node  = Dom.get("SMField");
        if (node != undefined)  node.value = "00";
    
        node = Dom.get("EHField");
        if (node != undefined)  node.value = "00";
    
        node = Dom.get("EMField");
        if (node != undefined)  node.value = "00";
    
        node = Dom.get("preSecField");
        if (node != undefined)  node.value = "5";
    
        node = Dom.get("postSecField");
        if (node != undefined)  node.value = "5";
    
        node = Dom.get("audioEnable");
        if (node != undefined)  node.checked = false;
    
        node = Dom.get("recordAlways");
        if (node != undefined)  node.clicked = false;
    
        node = Dom.get("recordEvent");
        if (node != undefined)  node.clicked = false;
        if (hasMotion)
        {
            var x=0;
            for (var j=0; j<MotionIds.length; j++)
            {
                var node = Dom.get(MotionIds[j]);
                if (node != undefined)
                {
                    node.checked = false;
                    x++;
                }
            }
            //alert("MotionIds.length: " + MotionIds.length + ", x: " + x);
        }
        if (hasIO)
        {
            var x = 0;
            for (var j=0; j<IOIds.length; j++)
            {
                var node = Dom.get(IOIds[j]);
                if (node != undefined)
                {
                    node.checked = false;
                    x++;
                }
            }
            //alert("IOIds.length: " + IOIds.length + ", x: " + x);
        }
    
        setMIField(false);
    
        if (deepest)
        {
            setCurrDataIntoDlg("-1", "-1", "-2");
        }
    }
    catch (e)
    {
        errorReport(e);
    }
}
//////////////////////////////////////////////////////////////////////////////////////
function setInitializeScheduleMode()
{
    if (ScheduleMode == 1)
    {
        var xdd = Dom.get("modeSelect1");
        if (xdd!=undefined)
        {
            xdd.checked = false;
        }
        var xd = Dom.get("modeSelect2");
        if (xd!=undefined)
        {
            xd.checked = true;
        }

        removeWeekNodes();
        addWeekNodes();
        SetDDLabel(1);
        SetDDItem(0);

        try{
            var nodes = tree.getNodesByProperty("nodeType", true);
            if (nodes!=undefined && nodes.length>0)
            {
                for (var x=0; x<nodes.length; x++)
                {
                    var chAttr = nodes[x].cameraIndex;
                    var weekAttr = nodes[x].week;
                    if (   chAttr!=undefined && parseInt(chAttr,10) == 0
                        && weekAttr!=undefined && parseInt(weekAttr,10) == 0)
                    {
                        nodes[x].parent.expand();
                        onLabelClick(nodes[x]);
                        break;
                    }
                }
            }
        } catch (e) {errorReport(e);}
    }
    else
    {
        var xdd = Dom.get("modeSelect2");
        if (xdd!=undefined)
        {
            xdd.checked = false;
        }
        var xd = Dom.get("modeSelect1");
        if (xd!=undefined)
        {
            xd.checked = true;
        }

        removeWeekNodes();
        SetDDLabel(0);
        SetDDItem(1);

        try
        {
            var nodes = tree.getNodesByProperty("nodeType", true);
            if (nodes!=undefined && nodes.length>0)
            {
                for (var x=0; x<nodes.length; x++)
                {
                    var chAttr = nodes[x].cameraIndex;
                    if (chAttr!=undefined && parseInt(chAttr,10) == 0)
                    {
                        onLabelClick(nodes[x]);
                        break;
                    }
                }
            }
        } catch (e) {errorReport(e);}
    }
}

// remote schedule data handler functions
function handleSuccess(o)
{
    if (o.status == "401")
    {
        handleSessionTimeout();
        return;
    }
    if(o.responseText !== undefined)
    {
        try {
            INFO = eval(o.responseText);
            MaxIPCam = INFO[0];

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

                }
                hasMotion = false;
            }

            IOInfo = INFO[1][1];
            if (IOInfo != undefined)
            {
                //for (var j=0; j<IOInfo.length; j++)
                for (var j in IOInfo)
                {
                    //for (var k=0; k<IOInfo[j].length; k++)
                    for (var k in IOInfo[j])
                    {
                        hasIO |= IOInfo[j][k];
                    }
                }
            }
            else
            {
                IOInfo = new Array();
                for (var j=0; j<MaxIPCam; j++)
                {
                    IOInfo[j] = new Array();
                }
                hasIO = false;
            }

            CameraInfo = INFO[2];
            if (CameraInfo == undefined)
                CameraInfo = new Array();
            for (var j=0; j<MaxIPCam; j++)
            {
                if (CameraInfo[j] == undefined)
                    CameraInfo[j] = new Array();

                if (CameraInfo[j]['CameraName'] == undefined || CameraInfo[j]['CameraName'] == '')
                    CameraInfo[j]['CameraName'] = "Camera " + (j+1);

                if (CameraInfo[j]['DaySchedule'] == undefined)
                    CameraInfo[j]['DaySchedule'] = new Array();

                if (CameraInfo[j]['WeekSchedule'] == undefined)
                    CameraInfo[j]['WeekSchedule'] = new Array();
            }

            SetDDItem(1);
            InitializeCameraList();
            InitializeConfigurationDialog();

            //ScheduleStatus = INFO[3];
            //SetScheduleStatusButtons();
            //SetGraphicLayout(0, 0, -1);

            ScheduleMode = INFO[3];
            setInitializeScheduleMode();

            /*var nodes = tree.getNodesByProperty("nodeType", true);
            if (nodes!=undefined && nodes.length>0)
            {
                for (var x=0; x<nodes.length; x++)
                {
                    var chAttr = nodes[x].cameraIndex;
                    if (chAttr!=undefined && parseInt(chAttr,10) == 0)
                    {
                        onLabelClick(nodes[x]);
                        break;
                    }
                }
            }*/
        } catch (e) { errorReport(e); }
        //alert("OK!");
        //alert("hasMotion: " + hasMotion + ", hasIO: " + hasIO);
    }
    else
    {
        //alert("o.responseText == undefined");
    }

/*    if (window.top != self)
    {
        try {
            if (parent.frames[0].parent != undefined && typeof parent.frames[0].parent.resizeMe == 'function')
                parent.frames[0].parent.resizeMe();
        } catch (e) { errorReport(e); }
    }*/
}

function handleFailure(o)
{
    if (o.status == "401")
    {
        handleSessionTimeout();
        return;
    }
    //alert("handleFailure:\nHTTP status: " + o.status + "\nStatus code message: " + o.statusText);
    InitializeCameraList();
}
//////////////////////////////////////////////////////////////////////////////////////
function clearAllHighlightDDElem()
{
    var x = Dom.get("graphicLayoutW");
    var xxx = undefined;
    if (x!=undefined)
        xxx = Dom.getElementsByClassName('dd-panel-selected', 'div', x);
    else
        xxx = Dom.getElementsByClassName('dd-panel-selected', 'div');
    
    if (xxx!=undefined)
    {
        for (var i=0;i<xxx.length; i++)
        {
            Dom.removeClass(xxx[i], 'dd-panel-selected');
        }
    }
}
// event handler functions
function onModifySchedule(ev)
{
/*    var x = Dom.get("graphicLayoutW");
    var xxx = undefined;
    if (x!=undefined)
    {
        xxx = Dom.getElementsByClassName('dd-panel-selected', 'div', x);
    }
    else
    {
        xxx = Dom.getElementsByClassName('dd-panel-selected', 'div');
    }
    if (xxx!=undefined)
    {
        for (var i=0;i<xxx.length; i++)
        {
            Dom.removeClass(xxx[i], 'dd-panel-selected');
        }
    }*/
    clearAllHighlightDDElem();

    try {
        if (currData!=undefined)
        {
            var targetInfo = undefined;
            if (currData['week']>=0)
            {
                if (   CameraInfo[ currData['ch'] ] != undefined
                    && CameraInfo[ currData['ch'] ]['WeekSchedule'] != undefined)
                {
                    for (var i=0; i<CameraInfo[ currData['ch'] ]['WeekSchedule'].length; i++)
                    {
                        if (   CameraInfo[ currData['ch'] ]['WeekSchedule'][i]!=undefined
                            && CameraInfo[ currData['ch'] ]['WeekSchedule'][i].length>0)
                        {
                            
                            if (CameraInfo[ currData['ch'] ]['WeekSchedule'][i][0]['week'] == currData['week'])
                            {
                                targetInfo = CameraInfo[ currData['ch'] ]['WeekSchedule'][i];
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                if (   CameraInfo[ currData['ch'] ] != undefined
                    && CameraInfo[ currData['ch'] ]['DaySchedule'] != undefined)
                {
                    targetInfo = CameraInfo[ currData['ch'] ]['DaySchedule'];
                }
            }

            if (targetInfo!=undefined)
            {
                var record;
                if (typeof ev == 'string' && ev == "")
                {
                    var rows = tableView.getSelectedRows();
                    if (rows!=undefined && rows.length>0)
                    {
                        record = tableView.getRecord(rows[0]);
                    }
                }
                else
                {
                    var target = Event.getTarget(ev);
                    var column = this.getColumn(target);
                    record = this.getRecord(target);
                }

                var tSH = record.getData('startTime').getHours();
                var tSM = record.getData('startTime').getMinutes();
                var tEH = record.getData('endTime').getHours();
                var tEM = record.getData('endTime').getMinutes();

                for (var i=0; i<targetInfo.length; i++)
                {
                    var xSH = targetInfo[i]['startTime'].getHours();
                    var xSM = targetInfo[i]['startTime'].getMinutes();
                    var xEH = targetInfo[i]['endTime'].getHours();
                    var xEM = targetInfo[i]['endTime'].getMinutes();
                    if ((tSH == xSH) && (tSM == xSM) && (tEH == xEH) && (tEM == xEM))
                    {
                        Dom.addClass(targetInfo[i]['relatedDDEl'].el, 'dd-panel-selected');
                        break;
                    }
                }
            }
        }
    } catch (e) {errorReport(e);}

    SetModifyButtonState(7);
}

function SelectDataTableItem(idx)
{
    try {
        if (tableView!=undefined)
        {
            tableView.unselectAllRows();
            tableView.selectRow(idx);
            tableView.refreshView();

            //var selectedRecord = tableView.getSelectedRows()[0];
            onModifySchedule("");
        }
    } catch (e) { errorReport(e); }
}

function onLabelClick(node)
{
    try
    {
        if (node.nodeType == undefined)
            return;
        var rb = Dom.get('modeSelect2');
        if (rb.checked)
        {
            // week mode
            if (node['cameraNameNode']!=undefined && node['cameraNameNode'])
            { // click camera name node
                SetDataTable(node.cameraIndex, 1, 0);
                SetModifyButtonState(1);
                if (preHighlight)
                {
                    Dom.removeClass(preHighlight, 'highlightTreeElem');
                }
                SetGraphicLayout(1, node.cameraIndex, -1);
                SelectDataTableItem(0);
            }
            else if (node.week != undefined)
            { // click the week labe
                if (node.nodeType)
                {
                    SetDataTable(node.cameraIndex, 1, node.week);
                    SetModifyButtonState(1);
                    if (preHighlight)
                    {
                        Dom.removeClass(preHighlight, 'highlightTreeElem');
                    }
                    Dom.addClass(node.getEl(), 'highlightTreeElem');
                    preHighlight = node.getEl();
                    SetGraphicLayout(1, node.cameraIndex, -1);
                    SelectDataTableItem(0);
                }
            }
        }
        else
        {
            // day mode
            if (node.nodeType)
            {
                SetDataTable(node.cameraIndex, 0, -1);
                SetModifyButtonState(1);
                if (preHighlight)
                {
                    Dom.removeClass(preHighlight, 'highlightTreeElem');
                }
                Dom.addClass(node.getEl(), 'highlightTreeElem');
                preHighlight = node.getEl();
                SetGraphicLayout(0, node.cameraIndex, -1);
                SelectDataTableItem(0);
            }
        }
    }
    catch (e) { errorReport(e); }
}

function onInsert()
{
    try
    {
        currCH = currData['ch'];
        currMode = currData['mode'];
        currWeek = currData['week'];
    
        if (currCH == undefined || currMode == undefined || currWeek == undefined)
        {
            //alert("error in onInsert!");
            return;
        }
    
        // popup a clear dialog
        clearDialog(true);
        var act = Dom.get("DlgAction");
        if (act != undefined)
        {
            act.value = 1;
            //alert("act=1");
        }
        //alert(currCH + ", " + currMode + ", " + currWeek);
        setCurrDataIntoDlg(currCH, currMode, currWeek);
        setMIField(false); // hide motion and io panel
        Dom.get("recordAlways").click();
        confDlg.moveTo(10, 10);
        confDlg.show();
        //alert("onInsert() ok!");
    }
    catch (e)
    {
        errorReport(e);
    }
}

function onDelete()
{
    try
    {
        currCH = currData['ch'];
        currMode = currData['mode'];
        currWeek = currData['week'];
    
        if (currCH == undefined || currMode == undefined || currWeek == undefined)
        {
            //alert("error in onDelete!");
            return;
        }
    
        // delete from datatable
        var selectedRow = tableView.getSelectedRows();
        var rs = tableView.getRecordSet();
        var record = rs.getRecord(selectedRow[0]);
        if (rs == undefined || selectedRow == undefined)
        {
            //alert("error in onDelete: can't get the record set or the selected row!");
            return;
        }
        var record = rs.getRecord(selectedRow[0]);
        rs.deleteRecord(rs.getRecordIndex(record));
        tableView.unselectAllRows();
        tableView.refreshView();
        //handleResizeMe();
        if ((currCH != undefined) && (currMode != undefined) && (currWeek != undefined))
        {
            SetDataTable(currCH, currMode, currWeek);
        }
        SetGraphicLayout(currMode, currCH, currWeek);
        //alert("delete ok!");
        SetButtonStatusCorrectly();
    }
    catch (e)
    {
        errorReport(e);
    }
}

function onConfigure()
{
    try
    {
        currCH = currData['ch'];
        currMode = currData['mode'];
        currWeek = currData['week'];
    
        if (currCH == undefined || currMode == undefined || currWeek == undefined)
        {
            //alert("error in onConfigure!");
            return;
        }
    
        clearDialog(true);
        var act = Dom.get("DlgAction");
        if (act != undefined)
        {
            act.value = 2;
            //alert("act=2");
        }
        setCurrDataIntoDlg(currCH, currMode, currWeek);
        // fetch current selected schedule
        var selectedRows = tableView.getSelectedRows();
        var rs = tableView.getRecordSet();
        var data;
        if (selectedRows && selectedRows.length>0 && rs)
        {
            var record = rs.getRecord(selectedRows[0]);
            if (record)
            {
                data = record.getData();
            }
        }
        setDialogData(data);
        confDlg.moveTo(10, 10);
        confDlg.show();
    }
    catch (e)
    {
        errorReport(e);
    }
}

function onConfOk()
{
    try
    {
        var dlgCh = Dom.get("DlgCh");
        var dlgMode = Dom.get("DlgMode");
        var dlgWeek = Dom.get("DlgWeek");
        var act = Dom.get("DlgAction");
    
        if (act == undefined || dlgMode == undefined || dlgWeek == undefined || dlgCh == undefined)
        {
            //alert("Error in onConfOk()!" + act + ", " + dlgMode + ", " + dlgWeek + ", " + dlgCh);
            setMIField(false);
            confDlg.hide();
            return;
        }
    
        var newData = getDialogData();
        if (newData['error'] != undefined)
        {
            if (typeof newData['error'] !== 'boolean')
                try { newData['error'].focus(); newData['error'].select(); } catch (e) {}
            return;
        }
        if (newData['startTime'] == undefined)
        {
            alert("Your setting data is not correct!\n");
            return;
        }
        //alert("conf ok with " + act.value + "!\nCH: " + dlgCh.value + "\nMode: " + dlgMode.value + "\nWeek: " + dlgWeek.value);
        if (2 == act.value)
        {
            // modify
            var selectedRows = tableView.getSelectedRows();
            var rs = tableView.getRecordSet();
            if (selectedRows && selectedRows.length>0 && rs)
            {
                var record = rs.getRecord(selectedRows[0]);
                if (record)
                {
                    // backupdata
                    //var backupData = record.getData();
                    //var zBackupData = new Array();
                    //for (var key in backupData)
                    //{
                    //    zBackupData[key] = backupData[key];
                    //}
                    //var msg = '';
                    //for (var key in newData)
                    //{
                    //    msg += key + ", ";
                    //}
                    //alert(msg);
                    for (var key in newData)
                    {
                        //alert("Update " + key + "in record!");
                        rs.updateKey(record, key, newData[key]);
                    }
                    rs.sortRecords(sortRecords, false);
                    if (! checkTimeValid(rs))
                    {
                        alert("Your time setting is not correct!");
                        //for (var key in zBackupData)
                        //{
                        //    rs.updateKey(record, key, zBackupData[key]);
                        //}
                        //tableView.refreshView();
                        if ((currData['ch'] != undefined) && (currData['mode'] != undefined) && (currData['week'] != undefined))
                        {
                            SetDataTable(currData['ch'], currData['mode'], currData['week'], true);
                        }
                        SetGraphicLayout(parseInt(dlgMode.value, 10), parseInt(dlgCh.value, 10), parseInt(dlgWeek.value, 10));
                        return;
                    }
                    tableView.refreshView();
                    //handleResizeMe();
                    /*var ddelem = undefined;
                    if (parseInt(dlgMode.value, 10) == 1)
                    { // week mode
                        ws = CameraInfo[parseInt(dlgCh.value, 10)]['WeekSchedule'][parseInt(dlgWeek.value, 10)];
                    }
                    setDDEl(record.getData('relatedDDEl'), record.getData('startTime'), record.getData('endTime'), record.getData('recorderType'));*/
                    if ((currData['ch'] != undefined) && (currData['mode'] != undefined) && (currData['week'] != undefined))
                    {
                        SetDataTable(currData['ch'], currData['mode'], currData['week']);
                    }
                    SetGraphicLayout(parseInt(dlgMode.value, 10), parseInt(dlgCh.value, 10), parseInt(dlgWeek.value, 10));
                    //alert("modify ok!"); 
                }
            }
        }
        else
        {
            // insert
            var rs = tableView.getRecordSet();
            if (rs != undefined)
            {
                var res = rs.addRecord({});
                if (res == undefined)
                {
                    alert("Insert failed!");
                    return;
                }
                for (var key in newData)
                {
                    rs.updateKey(res, key, newData[key]);
                }
                rs.sortRecords(sortRecords, false);
                if (! checkTimeValid(rs))
                {
                    alert("Your time setting is not correct!");
                    if ((currData['ch'] != undefined) && (currData['mode'] != undefined) && (currData['week'] != undefined))
                    {
                        SetDataTable(currData['ch'], currData['mode'], currData['week'], true);
                    }
                    SetGraphicLayout(parseInt(dlgMode.value, 10), parseInt(dlgCh.value, 10), parseInt(dlgWeek.value, 10));
                    return;
                }
                tableView.refreshView();
                //handleResizeMe();
                /* Generate related graphic elem */
                //var chIdx = parseInt(dlgCh.value, 10);
                //var panelIdx = rs.getLength();
                //var ddelem = new DDElement("dd"+ chIdx, "dd-panel-d-" + panelIdx + "-", undefined, "scheduleGroup");
                //setDDEl(ddelem, newData['startTime'], newData['endTime'], newData['recorderType']);
                //ddelem.show();
                //rs.updateKey(res, 'relatedDDEl',ddelem);
                /* *******************************/
                //alert("Insert ok!");
                if ((currData['ch'] != undefined) && (currData['mode'] != undefined) && (currData['week'] != undefined))
                {
                    SetDataTable(currData['ch'], currData['mode'], currData['week']);
                }
                SetGraphicLayout(parseInt(dlgMode.value, 10), parseInt(dlgCh.value, 10), parseInt(dlgWeek.value, 10));
            }
        }
        setMIField(false);
        confDlg.hide();
        SetModifyButtonState(1);
    }
    catch (e)
    {
        errorReport(e);
    }
}

function onConfCancel()
{
    //alert("conf cancel!");
    setMIField(false);
    confDlg.hide();
}

function onRecordAlwaysClick()
{
    setMIField(false);
}

function onRecordEventClick()
{
    setMIField(true);
}

function onStatusChange(p_oEvent)
{
    try
    {
        if(p_oEvent.newValue)
        {
            if (1 == parseInt(p_oEvent.newValue.get("value")))
            {
                alert("Stop schedule!");
            }
            else
            {
                alert("Start schedule!");
            }
        }
    }
    catch (e)
    {
        errorReport(e);
    }
}

function SetDDItem(m)
{
try {
    if (1==m) // change to day mode
    {
        for (var ch=0; ch<MaxIPCam; ch++)
        {
            var ddm = Dom.get('divch'+ch);
            if (ddm!=undefined)
            {
                Dom.setStyle(ddm, "display", "block");
                Dom.setStyle(ddm, "visibility", "visible");
            }
        }
        if (MaxIPCam<8)
        {
            for (var j=MaxIPCam; j<8; j++)
            {
                var ddm = Dom.get('divch'+j);
                if (ddm!=undefined)
                {
                    Dom.setStyle(ddm, "display", "none");
                    Dom.setStyle(ddm, "visibility", "hidden");
                }
            }
        }
    }
    else // change to week mode
    {
        for (var i=0; i<7; i++)
        {
            var ddm = Dom.get('divch'+i);
            if (ddm!=undefined)
            {
                Dom.setStyle(ddm, "display", "block");
                Dom.setStyle(ddm, "visibility", "visible");
            }
        }
        var ddm = Dom.get('divch'+7);
        Dom.setStyle(ddm, "display", "none");
        Dom.setStyle(ddm, "visibility", "hidden");
    }
    tableView.refreshView();
    //handleResizeMe();
} catch (e) {errorReport(e);}
}

function onModeChange(ev)
{
    var target = Event.getTarget(ev);
    if (target.id == "modeSelect1")
    {
        // week -> day
        removeWeekNodes();
        SetDDLabel(0);
        //SetGraphicLayout(0, 1, -1);
        SetDDItem(1);

        try{
            var nodes = tree.getNodesByProperty("nodeType", true);
            if (nodes!=undefined && nodes.length>0)
            {
                for (var x=0; x<nodes.length; x++)
                {
                    var chAttr = nodes[x].cameraIndex;
                    if (chAttr!=undefined && parseInt(chAttr,10) == 0)
                    {
                    onLabelClick(nodes[x]);
                    break;
                }
            }
        }
        } catch (e) {errorReport(e);}
    }
    else
    {
        removeWeekNodes();
        // day -> week
        addWeekNodes();
        SetDDLabel(1);
        //SetGraphicLayout(1, 1, 0);
        SetDDItem(0);

        try{
            var nodes = tree.getNodesByProperty("nodeType", true);
            if (nodes!=undefined && nodes.length>0)
            {
                for (var x=0; x<nodes.length; x++)
                {
                    var chAttr = nodes[x].cameraIndex;
                    var weekAttr = nodes[x].week;
                    if (   chAttr!=undefined && parseInt(chAttr,10) == 0
                        && weekAttr!=undefined && parseInt(weekAttr,10) == 0)
                    {
                        nodes[x].parent.expand();
                        onLabelClick(nodes[x]);
                        break;
                    }
                }
            }
        } catch (e) {errorReport(e);}
    }
}

function onSaveSchedule()
{
    try
    {
        var schedule = Dom.get("schedule_data");
        if (schedule == undefined)
        {
            //alert("error in onSaveSchedule()!");
            return;
        }
    
        if ((currData['ch'] != undefined) && (currData['mode'] != undefined) && (currData['week'] != undefined))
        {
            SetDataTable(currData['ch'], currData['mode'], currData['week']);
        }
    
        var sched = "";
    
        for (var i=0; i<MaxIPCam; i++)
        {
            var sectionName = "[Camera" + ((i>9) ? ""+i : "0"+(i+1)) + "]\r\n";
            sched += sectionName;
            var ds = CameraInfo[i]['DaySchedule'];
            var ws = CameraInfo[i]['WeekSchedule'];
            if (ds != undefined)
            {
                sched += '<DaySchedule>\r\n<Type>Day</Type>\r\n';
                for (var j=0; j<ds.length; j++)
                {
                    sched += '<Slice>' + ds[j]['startTime'].getDayTimeStr() + "-" + ds[j]['endTime'].getDayTimeStr() + '=';
                    if (ds[j]['recorderType'] == 1)
                    {
                        sched += 'E:';
                        var motionEvent = ds[j]['motion'];
                        if (motionEvent)
                        {
                            sched += genMotionStr(motionEvent);
                        }
                        else
                        {
                            ;//alert("no motion event");
                        }
                        sched += ':';
                        var ioEvent = ds[j]['io'];
                        if (ioEvent)
                        {
                            sched += genIOStr(ioEvent);
                        }
                        else
                        {
                            ;//alert("no io event");
                        }
                        sched += ':';
                    }
                    else
                    {
                        sched += 'A:::';
                    }
    
                    if (ds[j]['audio'])
                    {
                        sched += '1,';
                    }
                    else
                    {
                        sched += '0,';
                    }
                    sched += ds[j]['preSec'] + ',' + ds[j]['postSec'];
                    sched += '</Slice>\r\n';
                }
                sched += '</DaySchedule>\r\n';
            }
            if (ws != undefined)
            {
                for (var j=0; j<7; j++)
                {
                    var wss = ws[j];
                    if (wss != undefined && wss.length>0)
                    {
                        sched += '<DaySchedule>\r\n<Type>' + wsTypes[ wss[0]['week'] ] + '</Type>\r\n';
                        for (var k=0; k<wss.length; k++)
                        {
                            sched += '<Slice>' + wss[k]['startTime'].getDayTimeStr() + "-" + wss[k]['endTime'].getDayTimeStr() + '=';
                            if (wss[k]['recorderType'] == 1)
                            {
                                sched += 'E:';
                                var motionEvent = wss[k]['motion'];
                                if (motionEvent)
                                {
                                    sched += genMotionStr(motionEvent);
                                }
                                else
                                {
                                    ;//alert("no motion event");
                                }
                                sched += ':';
                                var ioEvent = wss[k]['io'];
                                if (ioEvent)
                                {
                                    sched += genIOStr(ioEvent);
                                }
                                else
                                {
                                    ;//alert("no io event");
                                }
                                sched += ':';
                            }
                            else
                            {
                                sched += 'A:::';
                            }
    
                            if (wss[k]['audio'])
                            {
                                sched += '1,';
                            }
                            else
                            {
                                sched += '0,';
                            }
                            sched += wss[k]['preSec'] + ',' + wss[k]['postSec'];
                            sched += '</Slice>\r\n';
                        }
                        sched += '</DaySchedule>\r\n';
                    }
                }
            }
        }
    
        schedule.value = sched;


        var schedule_mode_node = Dom.get("schedule_mode");
        if (schedule_mode_node!=undefined)
        {
            var d1 = Dom.get("modeSelect1");
            var d2 = Dom.get("modeSelect2");
            if (d1!=undefined && d1.checked)
            {
                schedule_mode_node.value = "day";
            }
            else if (d2!=undefined && d2.checked)
            {
                schedule_mode_node.value = "week";
            }
        }

        //alert(schedule.value);
        document.submit_schedule.submit();
    }
    catch (e)
    {
        errorReport(e);
    }
}

function onSchedSliceClick(e)
{
    //alert("slice clicked!");
}
//////////////////////////////////////////////////////////////////////////////////////

// initialize functions
function InitializeCameraList()
{
    try
    {
        var contextElementsID = new Array();
        var contextElementsTitle = new Array();
        //alert("CameraListInitialize() with " + MaxIPCam);
        /* Initialize Camera List as Tree-view */
        tree = new YAHOO.widget.TreeView("CameraList");
        var rootCameraList = new YAHOO.widget.MenuNode({label: "Camera List", nodeType: false}, tree.getRoot(), true);
        rootCameraList.nodeType = false;
        for (var i=0; i<MaxIPCam; i++)
        {
            var camerName = (CameraInfo[i]['CameraName'] && CameraInfo[i]['CameraName'] != '' ? CameraInfo[i]['CameraName'] : "Camera " + (i+1));
            var tmpNode = new YAHOO.widget.MenuNode({label: camerName, title: CameraInfo[i]['CameraFullName'], cameraNameNode: 1, nodeType: true}, rootCameraList, false);
            tmpNode.nodeType = true;
            tmpNode.cameraIndex = i;
            tmpNode.cameraNameNode = 1;
            contextElementsID.push(tmpNode.labelElId);
            contextElementsTitle.push(CameraInfo[i]['CameraFullName']);
        }
        tree.subscribe("labelClick", onLabelClick);
        tree.draw();
        for (var x=0; x<contextElementsID.length; x++)
        {
            if (contextElementsTitle[x]!=undefined)
                Dom.get(contextElementsID[x]).setAttribute("title", contextElementsTitle[x]);
        }  
        SetDDLabel(0);
    }
    catch (e)
    {
        errorReport(e);
    }
}
function InitializeStatusButtons()
{
    try
    {
        // Initialize Mode Button
        statusButtonGroup = new YAHOO.widget.ButtonGroup({id: "ScheduleStatusBtnGrp", name: "ScheduleStatus", container: "ScheduleStatus"});
        var buttons = statusButtonGroup.addButtons([
            {label: "Start Schedule", value: 0, checked: false, disabled: true},
            {label: "Stop Schedule", value: 1, checked: false, disabled: true}
        ]);
        statusButtonGroup.on("checkedButtonChange", onStatusChange);
    }
    catch (e)
    {
        errorReport(e);
    }
}

function InitializeModeButtons()
{
    try
    {
        Dom.get("modeSelect1").checked = true;
        Dom.get("modeSelect2").checked = false;
        Event.addListener(["modeSelect1", "modeSelect2"], 'click', onModeChange);
        /* Initialize Mode Button */
/*        modeButtonGroup = new YAHOO.widget.ButtonGroup({id: "ModeSelectBtnGrp", name: "ModeSelect", container: "ModeSelect"});
        var buttons = modeButtonGroup.addButtons([
            {label: "Day", value: 0, checked: true},
            {label: "Week", value: 1}
        ]);
        buttons[0].addClass("dayButton");
        buttons[1].addClass("weekButton");
        modeButtonGroup.on("checkedButtonChange", onModeChange); */
    }
    catch (e)
    {
        errorReport(e);
    }
}

function InitializeModifyButtons()
{
    try
    {
        /* Initialize Modify Buttons */
        var insertButton = new YAHOO.widget.Button({
            label:"Insert",
            id:"insertButton",
            value: "1",
            container:"ModifyButtons",
            onclick: {fn: onInsert}});
        var deleteButton = new YAHOO.widget.Button({
            label:"Delete",
            id:"deleteButton",
            value: "2",
            container:"ModifyButtons",
            onclick: {fn: onDelete}});
        var configureButton = new YAHOO.widget.Button({
            label:"Configure",
            id:"configureButton",
            value: "3",
            container:"ModifyButtons",
            onclick: {fn: onConfigure}});
        modifyButtonGroup.push(insertButton, deleteButton, configureButton);
        SetModifyButtonState(0);
    }
    catch (e)
    {
        errorReport(e);
    }
}

function InitializeSaveButton()
{
    try
    {
        var saveButton = new YAHOO.widget.Button({
            label:"Save Schedule",
            id:"saveButton",
            value:"1",
            container:"SaveSchedule",
            onclick: {fn: onSaveSchedule}});
    }
    catch (e)
    {
        errorReport(e);
    }
}

function InitializeDataTable()
{
    try
    {
        /* Initialize Datatable */
        this.myDayDataSource = new YAHOO.util.DataSource([]);
        this.myDayDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        this.myDayDataSource.responseSchema = { fields: 
            ["week", "startTime", "endTime", "recorderType",
             "motion", "io", "preSec", "postSec", "audio",
             "relatedDDEl"/*, "eventSetting"*/] };

        this.myDayColumnDefs = [
            {key:"startTime", label: "Start Time", formatter:this.formatTime, sortable:true, sortOptions:{sortFunction:sortRecords}},
            {key:"endTime", label: "End Time", formatter:this.formatTime, sortable:true, sortOptions:{sortFunction:sortRecords}},
            {key:"recorderType", label: "Record", formatter:this.formatType},
            {key:"audio", label: "Audio", formatter:this.formatAudio}
        ];
        tableView = new YAHOO.widget.DataTable("TableView", this.myDayColumnDefs, this.myDayDataSource);
        tableView.set("selectionMode", "single");
        tableView.subscribe("rowClickEvent", tableView.onEventSelectRow);
        tableView.subscribe("rowDblclickEvent", onConfigure);
        tableView.subscribe("cellClickEvent", onModifySchedule);
    }
    catch (e)
    {
        errorReport(e);
    }
}

function InitializeConfigurationDialog()
{
    try
    {
        // Initialize Configuration Dialog
        var buttonsCfg = [
            {text: 'Ok', handler: {fn: onConfOk}},
            {text: 'Cancel', handler: {fn: onConfCancel}}
        ];
        confDlg = new YAHOO.widget.Dialog("confDlg", {width:"480px", visible:false, draggable:false, close:false, modal:true, fixedcenter:true, buttons: buttonsCfg} );
        confDlg.setHeader("Schedule Configuration");
        var bodyHTML = '<div class="dialog-left">';
        // indicate action: 1 -> insert, 2 -> modify
        bodyHTML += '<input type="hidden" value="0" id="DlgAction" />';
        // 0 ~ MaxIPCam-1
        bodyHTML += '<input type="hidden" value="-1" id="DlgCh" />';
        // 0 for day mode, 1 for week mode
        bodyHTML += '<input type="hidden" value="-1" id="DlgMode" />';
        // -1 for day mode, 0~6 for week mode
        bodyHTML += '<input type="hidden" value="-2" id="DlgWeek" />';
        bodyHTML += '<fieldset id="timeField"><legend>Time</legend>';
        bodyHTML += '<label for="startTime" class="panelLabel">Start Time:</label>';
        bodyHTML += '<input type="text" class="timeField" id="SHField" maxlength="2" value="00" />:';
        bodyHTML += '<input type="text" class="timeField" id="SMField" maxlength="2" value="00" />';
        bodyHTML += '<div class="clear">';
        bodyHTML += '<label for="endTime" class="panelLabel">End Time:</label>';
        bodyHTML += '<input type="text" class="timeField" id="EHField" maxlength="2" value="00" />:';
        bodyHTML += '<input type="text" class="timeField" id="EMField" maxlength="2" value="00" />';
        bodyHTML += '<div class="clear">';
        bodyHTML += '<label for="prerecord" class="panelLabel">Pre-record</label>';
        bodyHTML += '<input type="text" name="prerecord" class="timeField" maxlength="2" id="preSecField" value="5" /> sec. (Max: 60)';
        bodyHTML += '<div class="clear">';
        bodyHTML += '<label for="postrecord" class="panelLabel">Post-record</label>';
        bodyHTML += '<input type="text" name="postrecord" class="timeField" maxlength="2" id="postSecField" value="5" /> sec. (Max: 60)';
        bodyHTML += '<div class="clear">';
        bodyHTML += '</fieldset>';
        bodyHTML += '<fieldset id="audioField"><legend>Audio</legend><input type="checkbox" name="audio" value="enable" id="audioEnable" />Enable audio<br /></fieldset>';
        bodyHTML += '</div><div class="dialog-right">';
        bodyHTML += '<fieldset id="modeField"><legend>Mode</legend>';
        bodyHTML += '<input type="radio" name="recordmode" id="recordAlways" value="A" />Always Record<br />';
        // setting motion and io element
        if (hasMotion || hasIO)
        {
            bodyHTML += '<input type="radio" name="recordmode" id="recordEvent" value="E" />Record on Event<br />';
            bodyHTML += '<div id="MIField">';
            if (hasMotion && MotionInfo)
            {
                bodyHTML += '<fieldset id="motionField"><legend>Motion</legend>';
                for (var j=0; j<MotionInfo.length; j++)
                {
                    if (MotionInfo[j])
                    {
                        var s = 'motionDect' + j;
                        bodyHTML += '<input type="checkbox" name="motionDect" id="' + s + '" value="' + j + '" />Motion on ' + CameraInfo[j]['CameraName'] + '<br />';
                        MotionIds.push(s);
                    }
                }
                bodyHTML += '</fieldset>';
            }
            if (hasIO && IOInfo)
            {
                bodyHTML += '<fieldset id="motionField"><legend>Digital Input</legend>';
                for (var i=0; i<IOInfo.length; i++)
                {
                    for (var j=0; j<IOInfo[i].length; j++)
                    {
                        if (IOInfo[i][j])
                        {
                            var idV = 'ioInput' + i + '-' + j; // ch-pinnum
                            var val = ((i>9) ? ""+i : "0"+i) + ((j>9) ? ""+j : "0"+j); // XXYY XX: ch with leading zero padding, YY: pin num with leading zero padding
                            bodyHTML += '<input type="checkbox" name="ioInput" id="' + idV + '" value="' + val + '" />Input #' + (j+1) + ' on ' + CameraInfo[i]['CameraName'] + '<br />';
                            IOIds.push(idV);
                        }
                    }
                }
                bodyHTML += '</fieldset>';
            }
            bodyHTML += '</div>';
        }
        else
        {
            bodyHTML += '<input type="radio" name="recordmode" id="recordEvent" value="E" disabled />Record on Event<br />';
        }
        Event.on("recordAlways", "click", onRecordAlwaysClick);
        Event.on("recordEvent", "click", onRecordEventClick);
        bodyHTML += '</div>';

        confDlg.setBody(bodyHTML);
        confDlg.render("ScheduleSetting");
        confDlg.moveTo(50, 50);
    }
    catch (e)
    {
        errorReport(e);
    }
}

function ipcam_schedule_init()
{
    try
    {
        var sUrl = "/CGI/cgi_main?cmd=schedule&rand="+Math.floor(Math.random()*1000);
        var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, {success:handleSuccess, failure:handleFailure});
    }
    catch (e)
    {
        errorReport(e);
    }
    InitializeStatusButtons();
    InitializeModeButtons();
    InitializeModifyButtons();
    //InitializeSaveButton();
    InitializeDataTable();
}
//////////////////////////////////////////////////////////////////////////////////////

// graphic layout functions
DDResize = function(panelElId, handleElId, sGroup, config) {
    this.parentPanel;
    DDResize.superclass.constructor.apply(this, arguments);
    if (handleElId) {
        this.setHandleElId(handleElId);
    }
    Event.on(this, 'click', onSchedSliceClick);
};

YAHOO.extend(DDResize, YAHOO.util.DragDrop, {

    onMouseDown: function(e) {
        try
        {        
            var panel = this.getEl();
            this.startWidth = panel.offsetWidth;
            this.startHeight = panel.offsetHeight;
    
            this.startPos = [Event.getPageX(e),
                             Event.getPageY(e)];
        }
        catch (e)
        {
            errorReport(e);
        }
    },

    onDrag: function(e) {
        try
        {
            this.myStatus = StatusOnDrag;
            var newPos = [Event.getPageX(e),
                          Event.getPageY(e)];

            var offsetX = Math.floor( (newPos[0] - this.startPos[0]) / 5 ) * 5;
            var offsetY = newPos[1] - this.startPos[1];

            //var region = Dom.getRegion(this.parentPanel.cont);
            var region = this.parentPanel.cont;
            var el = this.parentPanel.getEl();
            var xy = Dom.getXY(el);
            //this.setXConstraint(left-7, right-2, 5);

            var newWidth = Math.max(this.startWidth + offsetX, 10);
            if ( (newWidth + xy[0] + 7 ) > region.right)
            {
                newWidth = region.right - xy[0] - 3;
            }
            var panel = this.getEl();
            panel.style.width = newWidth + "px";
            this.resetConstraints();
        }
        catch (e)
        {
            errorReport(e);
        }
    },

    endDrag: function(e) {
        try
        {
            //this.resetConstraints();
            //this.parentPanel.initConstraints();
            this.parentPanel.endDrag(e);
            this.myStatus = StatusOnNormal;
        }
        catch (e)
        {
            errorReport(e);
        }
    }
});

function clickDDElem()
{
try {
    var ddelem = arguments[1];
    if (ddelem!=undefined)
    {
        myStatus = ddelem.myStatus;
        if (myStatus != StatusOnNormal)
            return;
    }
    else
        return;

    var id = this.getAttribute("id");
    var ch = this.getAttribute("info_chidx");
    var mode = this.getAttribute("info_mode");
    var week = this.getAttribute("info_week");
    //SetDataTable(ch, mode, week);
    SetModifyButtonState(1);

    var nodes = tree.getNodesByProperty("nodeType", true);
    if (nodes!=undefined)
    {
        for (var x=0; x<nodes.length; x++)
        {
            if (week>=0)
            {
                var chAttr = nodes[x].cameraIndex;
                var weekAttr = nodes[x].week;
                if (   chAttr != undefined && parseInt(chAttr) == ch
                    && weekAttr != undefined && parseInt(weekAttr) == week)
                    targetNode = nodes[x];
            }
            else
            {
                var chAttr = nodes[x].cameraIndex;
                if (chAttr != undefined && parseInt(chAttr) == ch)
                    targetNode = nodes[x];
            }
        }
    }
    
    var targetIPCamInfo = undefined;
    var tSH = undefined;
    var tSM = undefined;
    var tEH = undefined;
    var tEM = undefined;
    if (week>=0)
    {
        if (   CameraInfo!= undefined && CameraInfo[ch] != undefined
            && CameraInfo[ch]['WeekSchedule'] != undefined)
        {
            if (CameraInfo[ch]['WeekSchedule'].length>0)
            {
                for (var x=0; x<CameraInfo[ch]['WeekSchedule'].length; x++)
                {
                    if (CameraInfo[ch]['WeekSchedule'][x]!=undefined && CameraInfo[ch]['WeekSchedule'][x].length>0)
                    {
                        if (   CameraInfo[ch]['WeekSchedule'][x][0]!=undefined
                            && CameraInfo[ch]['WeekSchedule'][x][0]['week']!=undefined
                            && CameraInfo[ch]['WeekSchedule'][x][0]['week'] == week)
                        {
                            targetIPCamInfo = CameraInfo[ch]['WeekSchedule'][x];
                            break;
                        }
                    }
                }
            }
        }
    } else
    {
        if (   CameraInfo!= undefined && CameraInfo[ch] != undefined
            && CameraInfo[ch]['DaySchedule'] != undefined)
                targetIPCamInfo = CameraInfo[ch]['DaySchedule'];
    }

    var targetRecord = undefined;
    var targetIPCamInfoIndex = undefined;
    if (targetIPCamInfo != undefined && targetIPCamInfo.length>0)
    {
        for (var x=0; x<targetIPCamInfo.length; x++)
        {
            if (targetIPCamInfo[x]['relatedDDEl'] == ddelem)
            {
                targetRecord = targetIPCamInfo[x];
                targetIPCamInfoIndex = x;
                break;
            }
        }
        if (targetRecord != undefined)
        {
            var targetStart = targetRecord['startTime'];
            var targetEnd = targetRecord['endTime'];
            if (targetStart!=undefined && targetEnd!=undefined)
            {
                tSH = targetStart.getHours();
                tSM = targetStart.getMinutes();
                tEH = targetEnd.getHours();
                tEM = targetEnd.getMinutes();
            }
        }
    }
                
    if (targetNode!=undefined)
        onLabelClick(targetNode);

    if (tSH == undefined || tSM == undefined || tEH == undefined || tEM == undefined)
        return true;

    var rs = tableView.getRecordSet();
    if (rs!=undefined)
    {
        var records = rs.getRecords();
        if (records!=undefined && records.length>0)
        {
            for (var x=0; x<records.length; x++)
            {
                var trStart = records[x].getData('startTime');
                var trEnd = records[x].getData('endTime');
                if (trStart!=undefined && trEnd!=undefined)
                {
                    if (   trStart.getHours() == tSH && trStart.getMinutes() == tSM
                        && trEnd.getHours() == tEH && trEnd.getMinutes() == tEM)
                    {
                        tableView.unselectAllRows();
                        tableView.selectRow(records[x]);
                        tableView.refreshView();
                        //handleResizeMe();
                        SetModifyButtonState(7);
                        break;
                    }
                }
            }
        }
    }
    clearAllHighlightDDElem();
    Dom.addClass(targetIPCamInfo[targetIPCamInfoIndex]['relatedDDEl'].el, 'dd-panel-selected');

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

DDElement = function(parent, prefix, shiftRegion, sGroup)
{
    this.el;
    this.parentEl;
    this.resizerId;
    this.resizerR;
    this.elId;
    this.type = 0;
    this.cont;
    this.myStatus = StatusOnNormal;
    this.setLeft = function(l) {Dom.setStyle(this.el, "left", l);};
    this.setWidth = function(w) {Dom.setStyle(this.el, "width", w);};
    this.setRect = function(l, w) {this.setLeft(l); this.setWidth(w);};
    this.hide = function() {Dom.setStyle(this.el, "display", "none"); Dom.setStyle(this.el, "visibility", "hidden");};
    this.show = function() {Dom.setStyle(this.el, "display", "block"); Dom.setStyle(this.el, "visibility", "visible"); this.initConstraints();};
    this.setAsAlways = function() {Dom.setStyle(this.el, "backgroundColor", COLOR_ALWAYS); this.type = COLOR_ALWAYS};
    this.setAsEvent = function() {Dom.setStyle(this.el, "backgroundColor", COLOR_EVENT); this.type = COLOR_EVENT};
    this.resetStyle = function() {
        Dom.setStyle(this.el, "backgroundColor", this.type);
        // this maybe dangerous when using js compression, but yui compression maybe ok
        /*@cc_on if (false) @*/ this.el.style["top"] = "8px"; // move back to normal position for non-ie
        this.el.style["borderWidth"] = "0px";
        this.el.style["borderColor"] = "#FFFFFF";
        this.el.style["borderStyle"] = "none";
    };
    this.setHightlight = function() {
        // this maybe dangerous when using js compression, but yui compression maybe ok
        /*@cc_on if (false) @*/ this.el.style["top"] = "6px"; // move up for border for non-ie
        this.el.style["borderWidth"] = "2px";
        this.el.style["borderColor"] = "#000000";
        this.el.style["borderStyle"] = "solid";
    };
    this.setLocked = function(lock) {this.locked = lock; this.resizerR.locked = true; };
    this.setElInfo = function(data)
    {
        if (this.el==undefined)
            return;
        if (data!=undefined)
        {
            if (data['chidx']!=undefined)
                this.el.setAttribute('info_chidx', data['chidx']);
            if (data['mode']!=undefined)
                this.el.setAttribute('info_mode', data['mode']);
            if (data['week']!=undefined)
                this.el.setAttribute('info_week', data['week']);
        }
    };

    if (typeof parent == "string")
    {
        this.parentEl = Dom.get(parent);
    }
    else
    {
        this.parentEl = parent;
    }

    try
    {
        this.cont = Dom.getRegion( this.parentEl );
        //alert(this.cont);
        if (shiftRegion != undefined)
        {
            this.cont.left = parseInt(this.cont.left, 10) + shiftRegion[0];
            this.cont.right = parseInt(this.cont.right, 10) - ONEDALENGTH + shiftRegion[1];
        }
        //alert(this.cont);
    }
    catch (e)
    {
        errorReport(e);
    }

    var prefixID = prefix;
    if (prefixID == undefined)
    {
        prefixID = "dd-panel-unknown-";
    }

    if (this.parentEl != undefined)
    {
        try{
            this.el = document.createElement("div");
            this.elId = Dom.generateId(this.el, prefixID);
            this.el.setAttribute("class", "dd-panel");
            this.el.setAttribute("className", "dd-panel");
            //this.el.setAttribute("onclick", clickDDElem);
            //this.el.setAttribute("ondbclick", dbclickDDElem);
            this.parentEl.appendChild(this.el);
            this.hide();
            Event.on(this.el, 'click', clickDDElem, this);

            var ddElem = document.createElement("div");
            var resizerPrefix = prefixID.replace(/-panel-/, "-resize-handle-");
            this.resizerId = Dom.generateId(ddElem, resizerPrefix);
            ddElem.setAttribute("class", "dd-resize-handlerR");
            ddElem.setAttribute("className", "dd-resize-handlerR");
            this.el.appendChild(ddElem);
            this.resizerR = new DDResize(this.elId, this.resizerId, "scheduleGroup");
            this.resizerR.setXTicks(0, 5);
            this.resizerR.parentPanel = this;
            this.resizerR.setYConstraint(0, 0);
        }
        catch (e)
        {
            errorReport(e);
        }
    }
    
    try
    {
        DDElement.superclass.constructor.apply(this, [this.elId, sGroup, {cont: this.cont}]);
        this.addInvalidHandleId(this.resizerId );
        this.initConstraints();
    }
    catch (e)
    {
        errorReport(e);
    }
};

YAHOO.extend(DDElement, YAHOO.util.DD, {
    cont: null,
    init: function(id, sGroup, config) {
        //Call the parent's init method
        DDElement.superclass.init.apply(this, arguments);
            //this.initConstraints();
    },

    initConstraints: function() {
        try
        {
            //Get the top, right, bottom and left positions
            //var region = Dom.getRegion(this.cont);
            var region = this.cont;

            //Get the element we are working on
            var el = this.getEl();

            //Get the xy position of it
            var xy = Dom.getXY(el);

            //Get the width and height
            var width = parseInt(Dom.getStyle(el, 'width'), 10);
            //var height = parseInt(Dom.getStyle(el, 'height'), 10);

            //Set left to x minus left
            var left = xy[0] - region.left;

            //Set right to right minus x minus width
            var right = region.right - xy[0] - width;

            //Set top to y minus top
            //var top = xy[1] - region.top;

            //Set bottom to bottom minus y minus height
            //var bottom = region.bottom - xy[1] - height;

            //Set the constraints based on the above calculations
            this.clearConstraints();
            this.setXConstraint(left-7, right-2, 5);
            this.setXTicks(0, 5);
            //this.setXConstraint(0, 0);
            this.setYConstraint(0, 0);
            //this.setYConstraint(top, bottom);
            //myLog("el: " + el + ", this.cont: " + this.cont + ", region: " + region);

            this.resizerR.clearConstraints();
            this.resizerR.setYConstraint(0, 0);
            this.resizerR.setXConstraint(left-7, right-2, 5);
            this.resizerR.clearTicks();
            this.resizerR.setXTicks(0, 5);

            //Event.on(window, 'resize', function() { this.initConstraints(); }, this, true);
        }
        catch (e)
        {
            errorReport(e);
        }
    },

    endDrag: function(e)
    {
        try
        {
            var el = this.getEl();
            var left = parseInt(Dom.getStyle(el, 'left'), 10);
            var width = parseInt(Dom.getStyle(el, 'width'), 10);

            var g = (left - 7) / 5;
            var sh = Math.floor(g / 3);
            var sm = (g - sh * 3) * 20;

            var gg = Math.ceil(width / 5) + g;
            var eh = Math.floor(gg / 3);
            var em = (gg - eh * 3) * 20;
            if (eh == 24 && em == 0)
            {
                eh = 23;
                em = 59;
            }

            var rs = tableView.getRecordSet();
            var re = new RegExp(/dd-panel-(\w)-/);
            var res = re.exec( this.getEl().id );
            if (res != undefined)
            {
                for (var ch=0; ch<MaxIPCam; ch++)
                {
                    if (res[1] == 'd') // day mode
                    {
                        if (CameraInfo[ch] != undefined && CameraInfo[ch]['DaySchedule'] != undefined)
                        {
                            var xd = CameraInfo[ch]['DaySchedule'];
                            for (var j=0; j<xd.length; j++)
                            {
                                if (xd[j]['relatedDDEl'] == this)
                                {
                                    SetDataTable(ch, 0, -1);
                                    xd[j]['startTime'] = createDate(sh, sm, 0);
                                    xd[j]['endTime'] = createDate(eh, em, 0);
                                    SetDataTable(ch, 0, -1, true);
                                    SetGraphicLayout(0, ch, -1);
                                    this.resetConstraints();
                                    this.initConstraints();
                                    SetModifyButtonState(1);
                                    return;
                                }
                            }
                        }
                    }
                    else if (res[1] == 'w')
                    {
                        if (CameraInfo[ch] != undefined && CameraInfo[ch]['WeekSchedule'] != undefined)
                        {
                            var xd = CameraInfo[ch]['WeekSchedule'];
                            for (var j=0; j<xd.length; j++)
                            {
                                for (var k=0; k<xd[j].length; k++)
                                {
                                    if (xd[j][k]['relatedDDEl'] == this)
                                    {
                                        SetDataTable(ch, 1, xd[j][k]['week']);
                                        xd[j][k]['startTime'] = createDate(sh, sm, 0);
                                        xd[j][k]['endTime'] = createDate(eh, em, 0);
                                        SetDataTable(ch, 1, xd[j][k]['week'], true);
                                        SetGraphicLayout(1, ch, xd[j][k]['week']);
                                        this.resetConstraints();
                                        this.initConstraints();
                                        SetModifyButtonState(1);
                                        return;
                                    }
                                }
                            }
                        }
                        //else
                            //;//alert(".................");
                        //alert(",,,,,,,,,,,,,,,");
                    }
                    /*else
                    {
                        //alert("bad panel id!");
                    }*/
                }
            }
            /*else
            {
                alert("bad panel id!");
            }*/
            //var record = rs.addRecord({});
            //rs.updateKey(record, "startTime", createDate(sh, sm, 0));
            //rs.updateKey(record, "endTime", createDate(eh, em, 0));
            //alert("width: " + width + ", height: " + height);
            //alert("endDrag: x: " + xy[0] + ", y: " + xy[1]);
            //tableView.refreshView();

            this.resetConstraints();
            this.initConstraints();
            SetModifyButtonState(1);
        }
        catch (e)
        {
            errorReport(e);
        }
    },

    onDragOver: function(e , id)
    {
        //alert("onDragOver");
    },

    onDragEnter: function(e , id)
    {
        //alert("onDragEnter");
    }
});

function SetGraphicLayout(mode, ch, week)
{
//    if ((currData['ch'] != undefined) && (currData['mode'] != undefined) && (currData['week'] != undefined))
//    {
//        if ((currData['mode'] == 0) && (currData['mode'] == ch))
//        { // day mode is not need to refresh graphic layout
//            return;
//        }
//        if ((1 == mode) && (currData['ch'] == ch) && (currData['week'] == week))
//        { // week mode and ch and week is not changed
//            return;
//        }
//    }
    //alert("AAA");
    // clear old graphic
    try
    {
        for (var i=0; i<8; i++)
        { // ddX
            var ddParent = Dom.get("dd" + i);
            if (ddParent != undefined)
            {
                var children = Dom.getElementsByClassName('dd-panel', 'div', ddParent);
                if (children != undefined && children.length>0)
                {
                    //alert("find " + children.length + " target elements to remove!")
                    for (var j=0; j<children.length; j++)
                    {
                        ddParent.removeChild(children[j]);
                    }      
                }
            }
        }
    
        // just clear graphic layout
        if ((ch == -2) && (week == -2))
        {
            return;
        }
    
        //alert("BBB");
        if (1 == mode)  // week mode
        {
            var ws = CameraInfo[ch]['WeekSchedule'];
            if (ws == undefined)
                ws = new Array();
            for (var j=0; j<7; j++)
            {
                var shiftRegion = [0, ONEDALENGTH];
                if (ws[j] == undefined)
                    ws[j] = new Array();
                if (ws[j].length>1)
                {
                    shiftRegion[1] = (ws[j][1]['startTime'].getHours() * 3 + Math.floor( ws[j][1]['startTime'].getMinutes() / 15 ) ) * 5;
                }
                for (var k=0; k<ws[j].length; k++)
                {
                    var ddelem = new DDElement("dd"+ ws[j][k]['week'], "dd-panel-w-" + k + "-", shiftRegion, "scheduleGroup");
                    ddelem.setElInfo({chidx:ch, mode:1, week:ws[j][k]['week']});
                    setDDEl(ddelem, ws[j][k]['startTime'], ws[j][k]['endTime'], ws[j][k]['recorderType']);
                    ddelem.show();
                    ws[j][k]['relatedDDEl'] = ddelem;
                    shiftRegion[0] = ( ws[j][k]['endTime'].getHours() * 3 + Math.floor( ws[j][k]['endTime'].getMinutes() / 15 ) ) * 5;
                    if (k == (ws[j].length-2))
                    {
                        shiftRegion[1] = ONEDALENGTH;
                    }
                    else if (k < (ws[j].length-2))
                    {
                        shiftRegion[1] = ( ws[j][k+2]['startTime'].getHours() * 3 + Math.floor( ws[j][k+2]['startTime'].getMinutes() / 15 ) ) * 5;
                    }
                }
            }
        }
        else // day mode
        {
            for (var chIdx=0; chIdx<MaxIPCam; chIdx++)
            {
                var ds = CameraInfo[chIdx]['DaySchedule'];
                if (ds==undefined)
                    ds = new Array();
                if ((ds != undefined) && (ds.length>0))
                {
                    var shiftRegion = [0, ONEDALENGTH];
                    if (ds.length>1)
                    {
                        shiftRegion[1] = (ds[1]['startTime'].getHours() * 3 + Math.floor( ds[1]['startTime'].getMinutes() / 15 ) ) * 5;
                    }
                    //alert("chIdx: " + chIdx);
                    for (var j=0; j<ds.length; j++)
                    {
                        //alert("WXYZ");
                        var ddelem = new DDElement("dd"+ chIdx, "dd-panel-d-" + j + "-", shiftRegion, "scheduleGroup");
                        ddelem.setElInfo({chidx: chIdx,mode: 0, week: -1});
                        setDDEl(ddelem, ds[j]['startTime'], ds[j]['endTime'], ds[j]['recorderType']);
                        ddelem.show();
                        ds[j]['relatedDDEl'] = ddelem;
                        //alert(ds[j]['relatedDDEl']);
                        // re-calculate const shift
                        shiftRegion[0] = ( ds[j]['endTime'].getHours() * 3 + Math.floor( ds[j]['endTime'].getMinutes() / 15 ) ) * 5;
                        if (j == (ds.length-2))
                        {
                            shiftRegion[1] = ONEDALENGTH;
                        }
                        else if (j < (ds.length-2))
                        {
                            shiftRegion[1] = ( ds[j+2]['startTime'].getHours() * 3 + Math.floor( ds[j+2]['startTime'].getMinutes() / 15 ) ) * 5;
                        }
                    }
                }
            }
        }
        //alert("SetGraphicLayout() ok!!");
    }
    catch (e)
    {
        errorReport(e);
    }
}

function setDDEl(el, sd, ed, type)
{
    try
    {
        if (el != undefined && sd != undefined && ed != undefined)
        {
            var width;
            var left = sd.getHours() * 15 + Math.floor(sd.getMinutes()/20) *5;
            if (ed.getHours() == 23 && ed.getMinutes() == 59)
            {
                width = 24 * 15 + Math.floor( 0 / 20 ) *5 -left;
            }
            else
            {
                width = ed.getHours() * 15 + Math.floor(ed.getMinutes()/20) *5 - left;
            }
            if (width<2)
            {
                width = 2;
            }
            if (width<5)
            {
                el.setLocked(true);
            }
            el.setRect(left+7, width-1);
            if (type == 1)
            {
                el.setAsEvent();
            }
            else
            {
                el.setAsAlways();
            }
            //myLog("Try to setYConstraint(" + typeof el.setYConstraint + ")...", true);
            el.setYConstraint(0, 0);
            //myLog("ok!");
        }
    }
    catch (e)
    {
        errorReport(e);
    }
};
//////////////////////////////////////////////////////////////////////////////////////
