/**
 * The TableOfContents module is a source of contextual information and
 * articles, and will persist through much of the site as the left navigation
 */
wwd.toc =
{
    currentPage:1,
    batchSize:15,
    totalResults:0,
    searchQuery:"",
    section:"",
    searchPrompt:"Search by Kewword",

    /**
     * start 'er up
     */
    initialize:function()
    {
        wwd.logger.log("ToC.initialize()");

        this.totalResults = $("#total-results").val();

        this.updateButtons();

        var checkboxes = $("#flyout-inner-container :input");
        if ( checkboxes.length <= 0 && $(".drop-down").length <= 0 ) {
            $("#toc-advanced-search").hide();
        }
        else {
            $("#toc-advanced-search").show();
        }

        // setup checkboxes
        $("#toc :input[type=checkbox]").each( function() { (new GraphicalInput(this)); });

        this.setFilters();

        //
        this.updateLinks();
    },

    reset:function()
    {
        this.currentPage = 1;
        this.searchQuery = "";
        this.totalResults = 0;
        $("#searchField").val( this.searchPrompt );
    },

targetFirst:function() {
           var FirstLink = $("#tocResults:first-child a").attr("href");
           window.location.hash="#/article" + FirstLink;
           $("#tocResults li:first").addClass("on");
},

    updateLinks:function()
    {

     // if ($("#landing-toc").html() == ("yes") ) {

      //}
      //Safari 2 does not handle the jQuery Ajax well - so we just set it up so the links are hard coded
      if ($.browser["safari"] == true && ($.browser.version.indexOf("418")!= -1 || $.browser.version.indexOf("419")!= -1 )){
          $(".tocContainer").show();
      //}
      //if (($.browser["msie"] == true) && ($.browser.version <= 6)) {
       //   $(".tocContainer").show();
      } else {
        $("#tocResults a").each( function() {
            var href = $(this).attr("href");
        if ( href.indexOf("navSection") != -1 ){
            //wwd.logger.log( href );
            $(this).click( function(e) {
                    wwd.toc.triggerLink( this, href );
                    return false;
            });
            $(".tocContainer").show();
            //$(this).attr("href","javascript:void(0);");
       }
        });
      }

    },

    triggerLink:function( anchor, href )
    {
        wwd.logger.log( "Toc.triggerLink()");
        //wwd.logger.log( anchor );

        //href = $(anchor).attr("href");
        //alert( "1" );

        // clear all on states
        $("#tocResults a").each( function() { $(this).parent().removeClass("on"); } );

        // set the on state for this the clicked anchor
        $(anchor).parent().addClass("on");

        // dynamically load -
        if ( href.indexOf("http") != -1 ) {
            href = href.substr( ("http://").length );
            href = href.substr( href.indexOf("/") );
        }

        wwd.content.paginate( href );
    },

    toggleFlyout:function()
    {
        wwd.logger.log( "ToC.toggleFlyout()");
        $("#flyout-container").show();
        if ( $("#flyout").css("left") == "0px" ) {
            this.closeFlyout();
        }
        else {
            $("#flyout").animate( {"left":"0px"} );
        }

        var offset = $("#toc").offset();
        $("#flyout-container").css( "left", 204 );
        $("#flyout-container").css( "top", -20 );
    },

    closeFlyout:function()
    {
        wwd.logger.log( "ToC.closeFlyout()");
        $("#flyout").animate( {"left":"-420px"}, function() { $("#flyout-container").hide(); } );
    },

    setFilters:function()
    {
        // filter names for display on toc module
        var filters = new Array();
        // params object for holding filters going to ajax service
        var params = {section:[]};

        // get all the checked options
        var inputs = $("#flyout-inner-container [type=hidden]");
        var total = ((inputs.length) - 1);
        for ( var i=0;i<=total;i++ ) {
            if ( $(inputs[i]).val() == "true" ) {
                params.section.push( $(inputs[i]).attr("name") );
                filters.push( $.trim( $(inputs[i]).parents("li:first").children(":last").text() ) );
            }
        }

        // get any values from drop down
        var dropboxes = $(".drop-down");
        var name,dspvalue,value;
        for (i=0; i<dropboxes.length;i++) {
            name = $(dropboxes[i]).attr("id");
            name = name.substr( ("drop-down-").length );

            dspvalue = $.trim( $("#"+dropboxes[i].id+" .drop-down-title").text() );
            value = $.trim( $("#"+dropboxes[i].id+" .drop-down-value").val() );

            if ((value != null) && (value != "")) {
                params[name] = [value];
                filters.push( dspvalue );
            }
        }

        // save the params for paging later
        this.searchParams = params;

        // if there are filters display them in the module
        $(".toc-show-filter").hide();
        if ( filters.length > 0 ) {
            var filterStr = filters.toString()
                filterStr = filterStr.replace( /,/g,", " );
             $(".toc-sub-title span").empty();
            $(".toc-sub-title span").append( filterStr );
            $(".toc-show-filter").show();
        }
        else {
            $(".toc-sub-title-cat").text( "" );
        }
    },

    search:function()
    {

        this.closeFlyout();

        // reset to page one for filter queries
        // TAB: should this be this.reset();
        this.currentPage = 1;

        this.searchQuery = $("#searchField").val();
        this.searchSection = $("#search-section").html();
        if ( this.searchQuery == this.searchPrompt || this.searchQuery == this.searchSection ) {
            this.searchQuery = "";
        }

        this.setFilters();

        // do it
        this.performSearch();
    },

    performSearch:function()
    {
        var url = $("#currentURL").val();
        var section = $("#currentSection").val();

        wwd.logger.verbose(section);
        wwd.logger.verbose(url);
        wwd.logger.verbose(this.searchQuery);
        wwd.logger.verbose(this.currentPage);
        wwd.logger.verbose(this.searchParams);

        $(".toc-results-buttons").hide();
        $("#tocResults").empty();
        $("#totalResults").empty();

        var img = $("<img>");
        img.attr("src","/images/icons/loader-grey.gif");
        img.css( "margin", "20px 0px 30px 90px" );
        $("#resultsContainer").append( img );

        filterStr = $(".toc-sub-title-cat").text();
        if ( this.searchQuery.length > 0 ) {
            if (filterStr != null && filterStr != "") {
                wwd.stats.track2Actions( "query", this.searchQuery, "advancedFilter", section+":"+filterStr );
            }
            else {
                wwd.stats.trackAction( "query", this.searchQuery );
            }
        }
        else if (filterStr != null && filterStr != "") {
            wwd.stats.trackAction( "advancedFilter", section+":"+filterStr );
        }

        TocController.performSearch( section, url,
                                     this.searchQuery, this.currentPage, this.searchParams,
                                     function(r) { wwd.toc.handleResult(r); } );
    },

    updateButtons:function()
    {
        var numPages = Math.ceil( this.totalResults / this.batchSize );

        $(".toc-results-buttons").hide();
        if ( numPages > 1 ) {
            $(".toc-results-buttons").show();
        }

        // back button
        var back = $(".toc-results-button li:first");
        if ( this.currentPage == 1 ) {
            back.addClass("disabled");
        }
        else {
            back.removeClass("disabled");
        }

        // next button
        var next = $(".toc-results-button li:last");
        if ( this.currentPage == numPages ) {
            next.addClass("disabled");
        }
        else {
            next.removeClass("disabled");
        }
    },

    handleResult:function( result )
    {
        $("#resultsContainer").empty();
        $("#resultsContainer").append( $("<ul></ul>").attr("id","tocResults") );
        //$("#tocResults").empty();
        $("#totalResults").empty();

        var pageResults ="";
        var pageCount = (result.entries.length);
        this.totalResults = (result.totalResults);

        this.updateButtons();

        if (pageCount < this.batchSize) {
            pageResults = (pageCount - 1);
        } else {
            pageResults = this.batchSize -1;
        }

        var months = new Array("Jan", "Feb", "Mar", "Apr",
                               "May", "June", "July", "Aug", "Sept",
                               "Oct", "Nov", "Dec");

        var html="";
        var i=0;
        for (i=0;i<=pageResults;i++) {
            var headline = (result.entries[i].headline);
            var articleDate = (result.entries[i].postDate);
            var formattedArticleDate = months[articleDate.getMonth()] + ' ' + articleDate.getDate() + ', ' + articleDate.getFullYear();
            var date = toString(articleDate);
            var articleUrl = (result.entries[i].url);
            var articleVid = (result.entries[i].hasVideo);
            var articleSS = (result.entries[i].hasSlideshow);
            var articleClass ="";

            if (articleVid == "true") {
                articleClass = ("toc-results-video");
            }
            if (articleSS == true) {
                articleClass = ("toc-results-slideshow");
            }
            else {
                articleClass = ("toc-results-article");
            }
            html += "<li class='" + articleClass + "'><a href='" + articleUrl +  "' onclick='wwd.toc.clearCloseFlyout();'><div class='articleTitle'>" + headline +  "</div><div class='articleDate'>Posted " + formattedArticleDate + "</div></a></li>";

            $("#tocResults").html( html );
        }

        $("#totalResults").empty();
                if (this.totalResults == 0) {
            $("#totalResults").append( $("<span>Your search for '"+this.searchQuery+"' returned 0 results.<br />Try searching again.</span>") );
            }
            else {
                $("#totalResults").append( $("<span>"+this.totalResults+" articles by Most Recent</span>") );
                this.targetFirst();
            }

        this.updateLinks();

        // if scroll farther down than top, move the page up -
        var top = Math.min( $('html,body').scrollTop(), $("#toc").offset().top );
        $('html,body').animate( {scrollTop: top }, 500 );
    },

    dropVal:function( name, value, displayValue )
    {
        $("#drop-down-"+name+" .drop-down-title-text").html( displayValue );
        $("#drop-down-"+name+" .drop-down-value").val( value );
        $(".drop-down-box").hide();
    },

    next:function()
    {
        var totalPages = Math.ceil( this.totalResults / this.batchSize );
        if ( this.currentPage < totalPages ) {
            this.currentPage++;
            this.performSearch();
        }
    },

    previous:function()
    {
        if ( this.currentPage > 1 ) {
            this.currentPage--;
            this.performSearch();
        }
    },

    clearFilters:function()
    {

        $(".flyout-list-item :input[type=image]").each ( function() { $(this).val("false"); } );
        $(".flyout-list-item :input[type=image]").each ( function() { $(this).removeClass("checked"); } );
        $(".flyout-list-item :input[type=hidden]").each ( function() { $(this).val("false"); } );
        $("#drop-down-regions .drop-down-title-text").html( "All Regions" );
        $("#drop-down-year .drop-down-title-text").html( "All Years" );
        $(".remove-button").each( function() {$(this).hide() });
        $(".filter-name").each( function() {$(this).attr("style", "color:#ffffff; cursor:default;") });

        //this.toggleFlyout();
    },

     clearCloseFlyout:function()
    {
        this.closeFlyout();
    }
}
