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

var logDataTable;
var logDataSource;

var myDataTableMrg;

var logname;
var logtablename;
var LOGNAMES = {'system': 'system', 'event': 'NVR Event'};



DataTableMrg = function()
{
    this.tables = new Array();
    this.createTable = function(tablename)
    {
        var myLogColumnDefs = 
        [        	        	
            {key:"Date", label:'<span class="trans" title="Date">Date</span>', sortable: false},
            {key:"Time", label:'<span class="trans" title="Time">Time</span>', sortable: false},
            {key:"Log", label: '<span class="trans" title="Log">Log</span>', sortable: false}
        ];
        var preDataStr = '<?xml version="1.0" encoding="UTF-8" ?>\n';
        preDataStr += '<Root></Root>';
        var preData;
        if (window.ActiveXObject)
        {
            try {
                preData = new ActiveXObject("Microsoft.XMLDOM");
                preData.loadXML(preDataStr);
            } catch(e)
            {
                try {
                    preData = new ActiveXObject("Msxml2.XMLDOM");
                    preData.loadXML(preDataStr);
                } catch (e) {}
            }
        }
        else
        {
            try {
                var oParser = new DOMParser();
                preData = oParser.parseFromString(preDataStr,"text/xml");
            } catch (e) {}
        }


        this.tables[ tablename ] = new Array();
        this.tables[ tablename ]['datasource'] = new YAHOO.util.DataSource(preData);
        this.tables[ tablename ]['datasource'].responseType = YAHOO.util.DataSource.TYPE_XML;
        this.tables[ tablename ]['datasource'].responseSchema = { resultNode: "LogRecord", fields: ["LogIndex", "Date", "Time", "Log"]};

        var logDataConf = {
            paginated:true,
            paginator: {
                rowsPerPage: 15,
                pageLinks: 10
            }
        };
        this.tables[ tablename ]['datatable'] = new YAHOO.widget.DataTable(tablename, myLogColumnDefs, this.tables[ tablename ]['datasource'], logDataConf);
    };

    this.getDatatable = function(tablename)
    {
        if (this.tables[ tablename ]!=undefined && this.tables[ tablename ]['datatable']!=undefined)
            return this.tables[ tablename ]['datatable'];
        return null;
    };

    this.getDataSource = function(tablename)
    {
        if (this.tables[ tablename ]!=undefined && this.tables[ tablename ]['datasource']!=undefined)
            return this.tables[ tablename ]['datasource'];
        return null;
    };

    this.refreshAllView = function()
    {
        for (var x in this.tables)
        {
            try{
                this.tables[x]['datatable'].refreshView();
                var zzzxxx = this.tables[x]['datatable'].getTableEl();
                if (zzzxxx!=undefined)
                {
                    Dom.setStyle(zzzxxx, 'visibility', 'hidden');
                    Dom.setStyle(zzzxxx, 'display', 'none');
                }
            } catch (e) { errorReport(e); }
        }
        for (var x in this.tables)
        {
            try{
                var zzzxxx = this.tables[x]['datatable'].getTableEl();
                if (zzzxxx!=undefined)
                {
                    Dom.setStyle(zzzxxx, 'visibility', 'visible');
                    Dom.setStyle(zzzxxx, 'display', 'block');
                }
            } catch (e) { errorReport(e); }
        }
    };
}


function InsertLogIntoTable(xmldoc, bAlert)
{	
    if (xmldoc==undefined)
        return;

    var logs = xmldoc.getElementsByTagName("Logs");
	
    if (logs != undefined && logs.length>0)
    {
   
        //try 
        {        
        	
            var rs = logDataTable.getRecordSet();            
            logDataTable.deleteRows(0, rs.getLength());

            var nodes = logs[0].getElementsByTagName("LogRecord");
      	
            if (nodes!=undefined && nodes.length>0)
            {          
                       	    	   
                for (var x=0; x<nodes.length; x++)
                {

                   	var lognode = nodes[x].getElementsByTagName("Log");

                    if ((lognode == undefined) || lognode.length<1)
                        continue;

                    if (lognode[0].firstChild == undefined)
                        continue;
                    if (lognode[0].firstChild.nodeValue == undefined)
                        continue;


                       var timenode = nodes[x].getElementsByTagName("Time");
                    if ((timenode == undefined) || timenode.length<1)
                        continue;
                    if (timenode[0].firstChild == undefined)
                        continue;
                    if (timenode[0].firstChild.nodeValue == undefined)
                        continue;

    
                    var datenode = nodes[x].getElementsByTagName("Data");
                
                    if ((datenode == undefined) || datenode.length<1)
                        continue;
                    if (datenode[0].firstChild == undefined)
                        continue;
                    if (datenode[0].firstChild.nodeValue == undefined)
                        continue;
                                                                   
                    rs.addRecord({Date: datenode[0].firstChild.nodeValue, Time: timenode[0].firstChild.nodeValue, Log: lognode[0].firstChild.nodeValue});
                    
                }
            }
            
            logDataTable.refreshView();
            var page = Math.ceil(nodes.length/15);            
            logDataTable.showPage(page);
            myDataTableMrg.refreshAllView();
          
        }
        // catch (e) { errorReport(e); }
    }
    else
    {
        if (bAlert)
            alert("No logs");
    }
}



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

    if(o.responseText == undefined)
    {
        //alert("error, no responseText");
        return;
    }

    if (o.responseText.match(/90\d /) || o.responseText.match(/80\d /))
    {
        //alert("No logs???!");
        return;
    }
    InsertLogIntoTable(o.responseXML, true);
}

function handleQueryLogFail(o)
{
   
    var statusLine = new String(o.status);
    if (statusLine.match(/^401/))
    {
        handleSessionTimeout();
        return;
    }
    //alert("handleFailure:\nHTTP status: " + o.status + "\nStatus code message: " + o.statusText);
}

function doQuery()
{		
try {
	
	sUrl = "/goform/ShowLogFileDetail?rand=" + Math.floor(Math.random()*1000);	
    logDataTable = myDataTableMrg.getDatatable('logtable1');
    logDataSource = myDataTableMrg.getDataSource('logtable1');
        
    YAHOO.util.Connect.asyncRequest('GET', sUrl, {success:handleQueryLogSuccess, failure:handleQueryLogFail});
    disableQuery(true);
} catch (e) { errorReport(e); }
}



function systemlog_init()
{
    logname = 'system';
    logtablename = "logtable";    
    myDataTableMrg = new DataTableMrg(); 
    myDataTableMrg.createTable("logtable1");
    logDataTable = myDataTableMrg.getDatatable(logtablename);
    logDataSource = myDataTableMrg.getDataSource(logtablename);      
    doQuery();   
}




YAHOO.widget.DataTable.prototype.showTableMessage = function(sHTML, sClassName)
{
    if (sClassName == YAHOO.widget.DataTable.CLASS_LOADING)
    {
        sHTML = "Load " + LOGNAMES[ logname ] + " logs...";
    }
    else if (sClassName == YAHOO.widget.DataTable.CLASS_EMPTY)
    {
        sHTML = "There are no " + LOGNAMES[ logname ] + " logs yet...";
    }

    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});
    YAHOO.log("DataTable showing message: " + sHTML, "info", this.toString());
};

