
// Maximum number of items to display in the ticker
var maxTicker = 10;

// Frequency with which to refresh, in milliseconds
var timeout = tickerUpdateInterval;

// Semaphore to indicate whether we're currently fetching reports
var gettingReports = false;

// Reports to display in the ticker
var reports;

// The id of the latest (most recent) report displayed in the ticker
var mostRecentDate = 0;

// This is set to 0 after the first batch of reports in the ticker is loaded, to avoid
// doing the fade-in effect for those
var firstPageLoad = 1;

var SITES_MODE = "sites";
var DEFAULT_MODE = "";

$(document).ready(
	function ()
	{
        // Hide sections that can be revealed later
        $(".more-countries").hide();
        $("#site-reports-li-id").hide();

        // Hidden field to indicate what we're showing across page refreshes
        if ($("#displayModeId").val() == SITES_MODE)
        {
            toggleSitesDisplay();
            $("#explore-overview-items").toggleClass("no-background");            
        } 

        // View all countries
        $("#viewAllId").click(function()
            {
                $(".more-countries").show();
                $("#viewAllId").hide();
                return false;
            });

        // View more sites
        $("#viewMoreSitesId").click(function()
            {
                toggleSitesDisplay();
                $("#displayModeId").val(SITES_MODE);
                $("#explore-overview-items").toggleClass("no-background");
            })

        // Stop viewing more sites
        $("#closeSitesId").click(function()
            {
                toggleSitesDisplay();
                $("#displayModeId").val(DEFAULT_MODE);
                $("#explore-overview-items").toggleClass("no-background");
            })

        // Synchronize date range selection dropdowns
        $("#dummyTimeDateSpanId").change(function()
            {
                $("#selectedTimeDateSpanId")[0].selectedIndex = this.selectedIndex;
                $("#formId").submit();
            })
        $("#selectedTimeDateSpanId").change(function()
            {
                $("#dummyTimeDateSpanId")[0].selectedIndex = this.selectedIndex;
                $("#formId").submit();
            })

        // Get ticker reports, and start timer

        displayReports();

        window.setInterval(function(timeout) {
              displayReports();
          }, timeout);


    }
);

function toggleSitesDisplay()
{
    $("#herdometer-ticker-li-id").toggle();
    $("#reports-li-id").toggle();
    $("#site-reports-li-id").toggle();
    return false;
}

function addReport(r)
{
    try {
        var text;
        if (r.reportType.name == 'INACCESSIBLE')
        {
            text = exploreTickerInaccessibleTemplate.format(HTMLEncode(r.displayCountry));
        }
        else
        {
            text = exploreTickerAccessibleTemplate.format(HTMLEncode(r.displayCountry));
        }

        var siteLink = "<a href='{0}/explore/id/{1}'>{2}</a>".format(
                contextRoot,
                HTMLEncode(r.page.site.id),
                HTMLEncode(r.page.site.displayTitle));

        $('.site-details li:first-child').before("<li style='display:none'><span class='timestamp'>" +
                                                 r.reportDate.toLocaleString() +
                                                 "</span>" +
                                                 "\u200E" + /* See note below */
                                                 siteLink +
                                                 " <span class='url'>(" +
                                                 HTMLEncode(r.page.site.url) +
                                                 ") " +
                                                 "\u200E" + /* See note below */
                                                 "</span>" +
                                                 "<span class='status'>" +
                                                 text +
                                                 "</span>" +
                                                 "</li>");

        /* u200E is the Unicode control character U+200E (LRM, Left-to-Right MARK). LRM is a zero-width character
           with directionality. It's used to make the parenthesis work as expected.
           See http://www.antennahouse.com/support/qa/QA/2002102508.html and http://www.unicode.org/unicode/reports/tr9/
           for more discussion. 
         */

        $('.site-details li:first-child').show('slow');
        if (!firstPageLoad)
        {
            $('.site-details li:first-child').css("background-color","#efebea");
            $('.site-details li:first-child').animate({backgroundColor : "#c5deee"}, 5000);
        }
        $('.site-details li:visible:gt(9)').hide();
    } catch (err)
    {
        // Do nothing
    }
}


// Update ticker. The gettingReports variable ensures that we only have one request running at a time.
function displayReports() {
    if (!gettingReports) {
        gettingReports = true;
        $.ajax({
               type: "POST",
               dataType: "text",
               url: contextRoot + "/action/ajax/recentreports/true",
               success: function(data){
                   gettingReports = false;
                   var newReports = eval(data);
                   if (newReports != null)
                   {
                      for (var i = newReports.length - 1 ; i >= 0 ; i--)
                      {
                          // Assuming that report ids are sequential
                          if (newReports[i].reportDate > mostRecentDate)
                          {
                              addReport(newReports[i]);
                              mostRecentDate = newReports[i].reportDate;
                          }
                      }
                   }
                   firstPageLoad = 0;
               }
             });

    }
}
