/* 
 * JS for FCFC-CI
 * Author: rbrown
 * Date: Mar 2011
 */

/**
     * Forces all external links to open in new window.
     */
$("a[href*='http://']:not([href*='"+location.hostname+"'])").attr("target","_blank");


$(function() {
    
    $(".top-link").click(function(){
        $('html, body').animate({
            scrollTop: 0
        });
    })


    // add new widget called repeatHeaders 
    $.tablesorter.addWidget({ 
        // give the widget a id 
        id: "repeatHeaders", 
        // format is called when the on init and when a sorting has finished 
        format: function(table) { 
            // cache and collect all TH headers 
            if(!this.headers) { 
                var h = this.headers = [];  
                $("thead th",table).each(function() { 
                    h.push( 
                        "" + $(this).text() + "" 
                        ); 
                 
                }); 
            } 
         
            // remove appended headers by classname. 
            $("tr.repated-header",table).remove(); 
         
            // loop all tr elements and insert a copy of the "headers"     
            for(var i=0; i < table.tBodies[0].rows.length; i++) { 
                // insert a copy of the table head every 10th row 
                if((i%5) == 4) { 
                    $("tbody tr:eq(" + i + ")",table).before( 
                        $("").html(this.headers.join("")) 
                 
                        );     
                } 
            } 
        } 
    }); 

    /**
     * Handles sorting search results table.
     */

    $("table").tablesorter({ 
        widgets: ['zebra','repeatHeaders'] 
    }); 

    /* ------------------------------------------- */


    /**
     * Checks whether selected items are > 9
     * then toggles downlaod/search
     */
    
    $("#years").live("click", function(){
        $("#nothing-years").attr("checked","");
        $("#all-years").attr("checked","");
        if (num_checkboxes_selected("#years") > 9) {
            switch_to_download();
        } else {
            switch_to_search();
        }
    });
    $("#counties").live("click", function(){
        $("#nothing-counties").attr("checked","");
        $("#all-counties").attr("checked","");
        if (num_checkboxes_selected("#counties") > 16) {
            switch_to_download();
        } else {
            switch_to_search();
        }
    });
    $("#juris").live("click", function(){
        $("#nothing-juris").attr("checked","");
        $("#all-juris").attr("checked","");
        if (num_checkboxes_selected("#juris") > 16) {
            switch_to_download();
        } else {
            switch_to_search();
        }
    });
    $("#zipcodes").live("click", function(){
        $("#nothing-zipcodes").attr("checked","");
        $("#all-zipcodes").attr("checked","");
        if (num_checkboxes_selected("#zipcodes") > 16) {
            switch_to_download();
        } else {
            switch_to_search();
        }
    });
    $("#tracts").live("click", function(){
        $("#nothing-tracts").attr("checked","");
        $("#all-tracts").attr("checked","");
        if (num_checkboxes_selected("#tracts") > 16) {
            switch_to_download();
        } else {
            switch_to_search();
        }
    });
    $("#sch_districts").live("click", function(){
        $("#nothing-sch_districts").attr("checked","");
        $("#all-sch_districts").attr("checked","");
        if (num_checkboxes_selected("#sch_districts") > 16) {
            switch_to_download();
        } else {
            switch_to_search();
        }
    });
    $("#sch_bldgs").live("click", function(){
        $("#nothing-sch_bldgs").attr("checked","");
        $("#all-sch_bldgs").attr("checked","");
        if (num_checkboxes_selected("#sch_bldgs") > 16) {
            switch_to_download();
        } else {
            switch_to_search();
        }
    });
    $("#community").live("click", function(){
        $("#nothing-community").attr("checked","");
        $("#all-community").attr("checked","");
        if (num_checkboxes_selected("#community") > 16) {
            switch_to_download();
        } else {
            switch_to_search();
        }
    });
    $("#race").live("click", function(){
        $("#nothing-race").attr("checked","");
        $("#all-race").attr("checked","");
        if (num_checkboxes_selected("#race") > 16) {
            switch_to_download();
        } else {
            switch_to_search();
        }
    });
    $("#neighborhood").live("click", function(){
        $("#nothing-neighborhood").attr("checked","");
        $("#all-neighborhood").attr("checked","");
        if (num_checkboxes_selected("#neighborhood") > 16) {
            switch_to_download();
        } else {
            switch_to_search();
        }
    });
    
    /* --------------------------------------- */
    
    
    /**
     * Checks number of options selected
     * and swicths between 'Search' and
     * 'Download' action of data type form.
     */
    
    function select_all(which) {
        if (($("#years :selected").length) > 9 ) {
            var value = $("form").attr("action");
            value = value.replace("search", "download");
            $("form").attr("action", value)

            var value = $("#submit-button").val();
            value = value.replace("Display Results", "Download");
            $("#submit-button").val(value);
        } else {
            if (($(which + " :selected").length) > 16 ) {
                alert("Too many items selected.  \n Display will be affected.  \n Limit your selections to 16 or less.");
                document.forms[0].reset(); // reset form 
            }
        }
    }
    
    function select_none(which) {
        if (($(" :selected").length) == 0 ) {
            var value = $("form").attr("action");
            value = value.replace("download", "search");
            $("form").attr("action", value)
            
            var value = $("#submit-button").val();
            value = value.replace("Download", "Display Results");
            $("#submit-button").val(value);
        }        
    }
    
    /* --------------------------------------- */
        
        
    /**
         * Toggles from search to download
         */
    
    function switch_to_download() {
        
        if ($("form").attr("action") != "download"){
            var value = $("form").attr("action");
            value = value.replace("search", "download");
            $("form").attr("action", value)

            var value = $("#submit-button").val();
            value = value.replace("Display Results", "Download");
            $("#submit-button").val(value);
        }
    }
    
    /**
         * Toggles from download to search
         */
    
    function switch_to_search() {
        
        if (num_checkboxes_selected("#years") < 10){
            var value = $("form").attr("action");
            value = value.replace("download", "search");
            $("form").attr("action", value)
            
            var value = $("#submit-button").val();
            value = value.replace("Download", "Display Results");
            $("#submit-button").val(value);  
        }
    }
    
    /* --------------------------------------- */
        
    
    /**
         * Checks how many items are selected
         */
    
    function num_checkboxes_selected(which) {
        var num =  $(which +" :selected").length;
        return num;
    }
    
    /**
         * Checks for total selected items
         */
    
    $("select").livequery("change",function () {
        var total = 0;
        if(this.id != "years") {
            $("select option:selected").each(function () {
                total++;

            });
            if (total - $("#years :selected").length > 16){ // 16 is limit
                alert("Too many items selected.  \n Display will be affected.  \n Limit your selections to 16 or less.");
                document.forms[0].reset(); // reset form 
            }
        }
    });


    /**
         * Handles toggle of select all / none
         * checkboxes.
         */
    
    $("#all-years").live("click", function(){
        $("#years option").attr("selected","selected");
        $("#nothing-years").attr("checked","");
        select_all("#years");
    });

    $("#nothing-years").live("click", function(){
        $("#years option").attr("selected","");
        $("#all-years").attr("checked","");
        select_none("#years");
        switch_to_search();
    });

    $("#all-counties").live("click", function(){
        $("#counties option").attr("selected","selected");
        $("#nothing-counties").attr("checked","");
        select_all("#counties");
    });

    $("#nothing-counties").live("click", function(){
        $("#counties option").attr("selected","");
        $("#all-counties").attr("checked","");
        select_none("#counties");
        switch_to_search();
    });

    $("#all-juris").live("click", function(){
        $("#juris option").attr("selected","selected");
        $("#nothing-juris").attr("checked","");
        select_all("#juris");
    });

    $("#nothing-juris").live("click", function(){
        $("#juris option").attr("selected","");
        $("#all-juris").attr("checked","");
        select_none("#juris");
        switch_to_search();
    });
    
    $("#all-zipcodes").live("click", function(){
        $("#zipcodes option").attr("selected","selected");
        $("#nothing-zipcodes").attr("checked","");
        select_all("#zipcodes");
    });

    $("#nothing-zipcodes").live("click", function(){
        $("#zipcodes option").attr("selected","");
        $("#all-zipcodes").attr("checked","");
        select_none("#zipcodes");
        switch_to_search();
    });

    $("#all-tracts").live("click", function(){
        $("#tracts option").attr("selected","selected");
        $("#nothing-tracts").attr("checked","");
        select_all("#tracts");
    });

    $("#nothing-tracts").live("click", function(){
        $("#tracts option").attr("selected","");
        $("#all-tracts").attr("checked","");
        select_none("#tracts");
        switch_to_search();
    });
    
    $("#all-sch-districts").live("click", function(){
        $("#sch-districts option").attr("selected","selected");
        $("#nothing-sch-districts").attr("checked","");
        select_all("#sch-districts");
    });

    $("#nothing-sch-districts").live("click", function(){
        $("#sch-districts option").attr("selected","");
        $("#all-sch-districts").attr("checked","");
        select_none("#sch-districts");
        switch_to_search();
    });
    
    $("#all-sch-bldgs").live("click", function(){
        $("#sch-bldgs option").attr("selected","selected");
        $("#nothing-sch-bldgs").attr("checked","");
        select_all("#sch-bldgs");
    });

    $("#nothing-sch-bldgs").live("click", function(){
        $("#sch-bldgs option").attr("selected","");
        $("#all-sch-bldgs").attr("checked","");
        select_none("#sch-bldgs");
        switch_to_search();
    });
    
    $("#all-community").live("click", function(){
        $("#community option").attr("selected","selected");
        $("#nothing-community").attr("checked","");
        select_all("#community");
    });

    $("#nothing-community").live("click", function(){
        $("#community option").attr("selected","");
        $("#all-community").attr("checked","");
        select_none("#community");
        switch_to_search();
    });
    
    $("#all-race").live("click", function(){
        $("#race option").attr("selected","selected");
        $("#nothing-race").attr("checked","");
        select_all("#race");
    });

    $("#nothing-race").live("click", function(){
        $("#race option").attr("selected","");
        $("#all-race").attr("checked","");
        select_none("#race");
        switch_to_search();
    });
    
    $("#all-neighborhood").live("click", function(){
        $("#neighborhood option").attr("selected","selected");
        $("#nothing-neighborhood").attr("checked","");
        select_all("#neighborhood");
    });

    $("#nothing-neighborhood").live("click", function(){
        $("#neighborhood option").attr("selected","");
        $("#all-neighborhood").attr("checked","");
        select_none("#neighborhood");
        switch_to_search();
    });
    
    /* --------------------------------------- */


    /**
         * Ajax handler for bringing in search forms
         * -----------------------------------------
         */
    
    $('#ci li.indicator-btn').click(function(){

        // Get title for passing via uri segment
        var str = $(this).attr("rel");
        //var outcome = "main-bg" + str.substr(-1);
        var searcher = str.substr(0,str.indexOf("|"));
        //alert(searcher);
        // Construct path
        var path_front = "http://" + $.url.attr("host") + "/"; // domain

        //var dir = $.url.segment(0);        // installed dir, if any
        //alert(dir);
        //if (dir != '') {
        //    path_front += dir + "/";  //add installed dir
        //}
        // FOR MULTI DIR INSTALL
        //        var dir = $.url.segment(1);        // installed dir, if any
        //        if (dir != '') {
        //            path_front += dir + "/";  //add installed dir
        //        }
        //        var dir = $.url.segment(2);        // installed dir, if any
        //        if (dir != '') {
        //            path_front += dir + "/";  //add installed dir
        //        }


        $.ajax({
            type: "POST",
            url: path_front + "outcomes/build_search_form/" + searcher,
            data: "id="+$(this).prev().text(),
            success: function(html){
                $("#indicator-search").html(html);
                $('#indicator-search').removeClass("bg-white")
                $('#indicator-search').addClass("indicator-section-bg");
                

            },
            error:function(e, xhr, settings, exception){
                alert(path_front + "outcomes/build_search_form/" + searcher);
            }
        });
     
        // Toggle bg color of selected element
        $('#ci li.indicator-btn').removeClass("selected-indicator-btn");
        $('#other-data li.other-btn').removeClass("selected-indicator-btn");
        $(this).addClass("selected-indicator-btn");

        return false

    });
    
    // -------------------------------------------


    /**
         * Ajax handler for bringing in other data forms
         * ---------------------------------------------
         */
    
    $('#other-data li.other-btn').click(function(){

        // Get title for passing via uri segment
        var str = $(this).attr("rel");
        //var outcome = "main-bg" + str.substr(-1);
        var searcher = str.substr(0,str.indexOf("|"));

        // Construct path
        var path_front = "http://" + $.url.attr("host") + "/"; // domain
        //var dir = $.url.segment(0);        // installed dir, if any
        //if (dir != '') {
        //    path_front += dir + "/";  //add installed dir
        //}
        // FOR MULTI DIR INSTALL
        //        var dir = $.url.segment(1);        // installed dir, if any
        //        if (dir != '') {
        //            path_front += dir + "/";  //add installed dir
        //        }
        //        var dir = $.url.segment(2);        // installed dir, if any
        //        if (dir != '') {
        //            path_front += dir + "/";  //add installed dir
        //        }


        $.ajax({
            type: "POST",
            url: path_front + "outcomes/build_other_search_form/" + searcher,
            data: "id="+$(this).prev().text(),
            success: function(html){
                $("#indicator-search").html(html);
                $('#indicator-search').removeClass("bg-white")
                $('#indicator-search').addClass("indicator-section-bg");

            },
            error:function(e, xhr, settings, exception){
                alert(path_front + "outcomes/build_other_search_form/" + searcher);
            }
        });
     
        // Toggle bg color of selected element
        $('#ci li.indicator-btn').removeClass("selected-indicator-btn");
        $('#other-data li.other-btn').removeClass("selected-indicator-btn");
        $(this).addClass("selected-indicator-btn");

        return false

    });
 
    // -------------------------------------------

    $('#delete-button').click(function(){
    
        $('#deletefromtable').show(); 
        $('#delete-button').hide();
    
    });
  
    $('#delete-no').click(function(){
    
        $('#deletefromtable').hide(); 
        $('#delete-button').show();
    
    });

// --------------------------------------------

});

