var summaryInterval;
function initSummaryInterval()
{
    var firstCheck = new Date();
    var nowDate = new Date();
    if(summaryInterval != null){
        clearInterval(summaryInterval);
        summaryInterval = null;
    }
    $("#stopSummaryInterval").val(0);
    summaryInterval = window.setInterval(function(){
        if( $("#stopSummaryInterval").val() == 1)
        {
            clearInterval(summaryInterval);
            summaryInterval = null;
            return false;
        }
        var epoch = new Date(1970, 0, 1);
        nowDate = new Date();
		var timestampPost = Math.floor((nowDate - epoch) / 1000);
       $.ajax({
        type: 'POST',
        dataType: 'html',
        url: 'INTERFACEXML2.jsp',
        data: { 'timestamp': timestampPost },
        async: true,
        success: function(dataHtml){
            custom_push(dataHtml);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            alert('error');
            if (typeof(ErrorFunction)!='undefined')
                ErrorFunction(XMLHttpRequest, textStatus);
         }
        });
        if($("#stopSummaryInterval").val() == 1)
        {
            clearInterval(summaryInterval);
            summaryInterval = null;
            return false;
        }

    },10000);
}

function clearSummaryInterval()
{
    $("#stopSummaryInterval").val(1);
}

function isDupeContent(l, p)
{
        if(p != ""){
            var preID = p[0].childNodes[1].childNodes[1].rows[0].childNodes[1].childNodes[1].textContent;
            var newID = l[0].childNodes[1].childNodes[1].rows[0].childNodes[1].childNodes[1].textContent;
            var tempPreID = preID.split(':');
            var tempNewID = newID.split(':');

            if(tempNewID[1] > tempPreID[1])
            {
                $("#lastCID").val(tempNewID[1]);
                return false;
            }
            else if(tempNewID[1] < 10){
                $("#lastCID").val(tempNewID[1]);
                return false
            }else
                return true
        }
        else
        {
            //console.log("first time");
            var newCID = l[0].childNodes[1].childNodes[1].rows[0].childNodes[1].childNodes[1].textContent;
            var tempCID = newCID.split(':');
            $("#lastCID").val(tempCID[1]);
            return false;
        }
}
function custom_push(datahtml)
{
    //var tcpImg = eval(r.tcp.picture);

    $("#tcpBar").progressBar($(datahtml).find("#tcp_value").val(), {showText: true, barImage:$(datahtml).find("#tcp_picture").val()} );
    $("#udpBar").progressBar($(datahtml).find("#udp_value").val(), {showText: true, barImage:$(datahtml).find("#udp_picture").val()} );
    $("#icmpBar").progressBar($(datahtml).find("#icmp_value").val(), {showText: true, barImage:$(datahtml).find("#icmp_picture").val()} );

    //var sum = r.time[0].count + r.time[1].count + r.time[2].count + r.time[3].count + r.time[4].count + r.time[5].count;

    $("#Time1").progressBar(($(datahtml).find("#time0_percent").val()));
    $("#Time2").progressBar(($(datahtml).find("#time1_percent").val()));
    $("#Time3").progressBar(($(datahtml).find("#time2_percent").val()));
    $("#Time4").progressBar(($(datahtml).find("#time3_percent").val()));
    $("#Time5").progressBar(($(datahtml).find("#time4_percent").val()));
    $("#Time6").progressBar(($(datahtml).find("#time5_percent").val()));

    $("#Time1ValueText").html($(datahtml).find("#time0_count").val());
    $("#Time2ValueText").html($(datahtml).find("#time1_count").val());
    $("#Time3ValueText").html($(datahtml).find("#time2_count").val());
    $("#Time4ValueText").html($(datahtml).find("#time3_count").val());
    $("#Time5ValueText").html($(datahtml).find("#time4_count").val());
    $("#Time6ValueText").html($(datahtml).find("#time5_count").val());

    $("#Time1Text").html($(datahtml).find("#time0_value").val());
    $("#Time2Text").html($(datahtml).find("#time1_value").val());
    $("#Time3Text").html($(datahtml).find("#time2_value").val());
    $("#Time4Text").html($(datahtml).find("#time3_value").val());
    $("#Time5Text").html($(datahtml).find("#time4_value").val());
    $("#Time6Text").html($(datahtml).find("#time5_value").val());
    $("#todayText").html($(datahtml).find("#current_date").val());

    $("#sensorText").html($(datahtml).find("#sensers").val());
    $("#uniqueAlertText").html($(datahtml).find("#unique_alerts").val());
    $("#categoriesText").html("( "+$(datahtml).find("#categories").val()+" Categories ) ");

    $("#totalAlertText").html($(datahtml).find("#total_alerts").val());
    $("#sourceIPText").html($(datahtml).find("#source_ip").val());
    $("#destinationIPText").html($(datahtml).find("#destination_ip").val());
    $("#uniqueIPText").html($(datahtml).find("#unique_ip_links").val());
    $("#imgRiskText").html($(datahtml).find("#risk_event_text").val());
    $("#imgRisk").attr({"src":$(datahtml).find("#risk_event_img").val()});

    return false;
}

function initMonitor()
{
    // INITIAL TAB IN Monitor TAB
    $("#monitor_menu_tab > ul").tabs({ fx: { height: 'toggle', opacity: 'toggle', duration: 500 }});
    //summary
    $("#monitor_menu_tab .ui-tabs-nav a:eq(0)").addClass("sum");
    //event
    $("#monitor_menu_tab .ui-tabs-nav a:eq(1)").addClass("evn");
    //map whois
    $("#monitor_menu_tab .ui-tabs-nav a:eq(2)").addClass("map");
    //correlation
    $("#monitor_menu_tab .ui-tabs-nav a:eq(3)").addClass("cor");

    $('#monitor_menu_tab .ui-tabs-nav').bind('tabsselect', function(m_event, m_ui) {

        ExitSpy("spyEventContainer");
        clearSummaryInterval();
        if(m_ui.index == 0)//sum tab
        {
            $(".evn_paging").hide();
            $(".sum_paging").show();
            initSummaryInterval();
        }
        if(m_ui.index == 1)//event tab
        {
            $(".evn_paging").show();
            $(".sum_paging").hide();
            $('#spyEventContainer > div:gt(20)').fadeEachDown(); // initial fade
            $('#spyEventContainer').spy({'ajax': 'INTERFACEXML.jsp','limit':25, 'fadeLast':20, 'timeout':5000,
                isDupe: isDupeContent,
                paramID : ["lastCID"]});

        }
        if(m_ui.index == 2)//correlation tab
        {
            $(".evn_paging").hide();
            $(".sum_paging").hide();
        }
        if(m_ui.index == 3)//correlation tab
        {
            $(".evn_paging").hide();
            $(".sum_paging").hide();
        }
    });
    //SRAN sensor paging
    $("#sran_paging .sum_paging li:eq(0)").click(function(){//SUM No. 1
        //$("#monitor_summary_page").load("monitor/MonitorPage_summary.jsp",function(){});
        //$("#monitor_summary_page").html("sum SRAN 1");
    });
    $("#sran_paging .sum_paging li:eq(1)").click(function(){//SUM No. 2
        //$("#monitor_summary_page").html("sum SRAN 2");
    });
    $("#sran_paging .sum_paging li:eq(2)").click(function(){//SUM No. 3
        //$("#monitor_summary_page").html("sum SRAN 3");
    });
    $("#sran_paging .sum_paging li:eq(3)").click(function(){//SUM No. 4
        //$("#monitor_summary_page").html("sum SRAN 4");
    });
    $("#sran_paging .evn_paging li:eq(0)").click(function(){//EVN No. 1
        //$("#monitor_summary_page").load("monitor/MonitorPage_summary.jsp",function(){});
        //$("#monitor_event_page").html("evn SRAN 1");
    });
    $("#sran_paging .evn_paging li:eq(1)").click(function(){//EVN No. 2
        //$("#monitor_event_page").html("evn SRAN 2");
    });
    $("#sran_paging .evn_paging li:eq(2)").click(function(){//EVN No. 3
        //$("#monitor_event_page").html("evn SRAN 3");
    });
    $("#sran_paging .evn_paging li:eq(3)").click(function(){//EVN No. 4
        //$("#monitor_event_page").html("evn SRAN 4");
    });

    // MAKE SUB_TAB of MONITOR PAGE

    $("#monitor_summary_page").load("FRMSRAN1S.jsp",function(){
    });

    $("#monitor_event_page").load("FRMSRAN1E.jsp",function(){
    });

    $("#monitor_correlation_page").load("monitor/MonitorPage_cor.jsp",function(){
        initMonitor_Correlation();
    });

    //to toggle class
    $("#sran_paging li a").bind("click", function() {
        $(this).addClass("current").parent().parent().find("a").not($(this)).removeClass("current"); // wow!
    });
}



function initMonitor_Event(){
    // INITIAL TAB IN Summary Monitor TAB
    $("#sub_menu_tab_event > ul").tabs({ fx: { height: 'toggle', opacity: 'toggle', duration: 500 }});
    //all
    $("#sub_menu_tab_event .ui-tabs-nav a:eq(0)").addClass("evn_all");
    //s1
    $("#sub_menu_tab_event .ui-tabs-nav a:eq(1)").addClass("evn_s1");
}

function initMonitor_Correlation(){
    $("#archive_cor h2").click(function(){
        $(this).next().slideToggle("slow");
        $(this).parent().parent().find("h2").not($(this)).next().hide("slow");
    });
    $("#archive_cor h2, #archive_cor a").click(function(){
        //choose month or year action:jmonth

    });
    $("#archive_cor h2, #archive_cor a").css("cursor","pointer");

    var options = {
        onMonthChanged: function(dateIn) {
            //this could be an Ajax call to the backend to get this months events
            var events = [ 	{ EventID: 1, "Date": new Date(2009, 1, 1), "Title": "10:00 pm - EventTitle1", URL: "http://www.pertnearsandstone.com/Events/1" },
                            { EventID: 2, "Date": new Date(2009, 1, 2), "Title": "9:30 pm - this is a much longer title", URL: "http://www.pertnearsandstone.com/Events/1" }
            ];
            $.jMonthCalendar.ReplaceEventCollection(events);
            return true;
        }
    };

    var events = [ 	{ EventID: 1, "Date": new Date(2009, 0, 1), "Title": "10:00 pm - EventTitle1", URL: "http://www.pertnearsandstone.com/Events/1" },
                    { EventID: 2, "Date": new Date(2009, 0, 2), "Title": "9:30 pm - this is a much longer title", URL: "http://www.pertnearsandstone.com/Events/1" }
    ];

    var newoptions = { };
    var newevents = [ ];
    $.jMonthCalendar.Initialize(newoptions, newevents);


    //$.jMonthCalendar.Initialize(options, events);


    var extraEvents = [	{ EventID: 1, "Date": new Date(2009, 0, 11), "Title": "10:00 pm - EventTitle1", URL: "" },
                        { EventID: 2, "Date": new Date(2009, 0, 20), "Title": "9:30 pm - this is a much longer title", URL: "" }
    ];

    $("#jMonth_button").click(function() {
        $.jMonthCalendar.AddEvents(extraEvents);
    });

}