﻿/*
* Copyright (c) 2008 Justin Britten justinbritten at gmail.com
*
* Some code was borrowed from:
* 1. Greg Weber's uiTableFilter project (http://gregweber.info/projects/uitablefilter)
* 2. Denny Ferrassoli & Charles Christolini's TypeWatch project (www.dennydotnet.com)
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/


(function($) {
    $.extend({
        tablesorterFilter: new function() {

            function has_words(str, words, caseSensitive) {
                var text = caseSensitive ? str : str.toLowerCase();

                for (var i = 0; i < words.length; i++) {
                    if (text.indexOf(words[i]) === -1) return false;
                }

                return true;
            }


            function doFilter(table, phrase) {
                if (table.config.debug) { var cacheTime = new Date(); }

                var phrase_length = phrase.length;
                var caseSensitive = table.config.filterCaseSensitive;
                var words = caseSensitive ? phrase.split(" ") : phrase.toLowerCase().split(" ");
                var columns = table.config.filterColumns;
                var resultRows = [];

                var success = function(elem) {
                    elem.show();
                    resultRows.push(elem);
                }
                var failure = function(elem) { ; }


                if (columns) {
                    var findStr = "";
                    for (var i = 0; i < columns.length; i++) {
                        findStr += "td:eq(" + columns[i] + "),";
                    }

                    var search_text = function() {
                        var elem = jQuery(this);

                        has_words(elem.find(findStr).text(), words, caseSensitive) ? success(elem) : failure(elem);
                    }
                } else {
                    var search_text = function() {
                        var elem = jQuery(this);

                        has_words(elem.text(), words, caseSensitive) ? success(elem) : failure(elem);
                    }
                }

                // Walk through all of the table's rows and search.
                // Rows which match the string will be pushed into the resultRows array.
                var allRows = table.config.cache.row;

                for (var i = 0; i < allRows.length; i++) {
                    allRows[i].each(search_text);
                }

                // Clear the table
                $.tablesorter.clearTableBody(table);

                // Push all rows which matched the search string onto the table for display.
                for (var i = 0; i < resultRows.length; i++) {
                    $(table.tBodies[0]).append(resultRows[i]);
                }

                // Update the table by executing some of tablesorter's triggers
                // This will apply any widgets or pagination, if used.
                
                $(table).trigger("update");
                $(table).trigger("appendCache");

                if (table.config.debug) { $.tablesorter.benchmark("Apply filter:", cacheTime); }

                return table;
            };

            function clearFilter(table) {
                if (table.config.debug) { var cacheTime = new Date(); }

                var allRows = table.config.cache.row;

                $.tablesorter.clearTableBody(table);

                for (var i = 0; i < allRows.length; i++) {
                    $(table.tBodies[0]).append(allRows[i]);
                }

                $(table).trigger("update");
                $(table).trigger("appendCache");

                if (table.config.debug) { $.tablesorter.benchmark("Clear filter:", cacheTime); }

                return table;
            };
            
            function dropdownFromColumn(column, dropdown) {
                var findStr = "";
                var dropDownEntries = new Array();
                var labelDropDown = "";
                
                if (column == 1){
                    labelDropDown = labelDropDown1;
                } else if (column == 2){
                    labelDropDown = labelDropDown2;
                } else if (column == 3){
                    labelDropDown = labelDropDown3;    
                } else {
                    labelDropDown = labelDropDown4;
                }
               
                findStr += "td:eq(" + column + "),";
                
                $(dropdown).html("");

                var search_text = function() {
                    var elem = jQuery(this);
                    var isInDropdown = false;

                    for (var i = 0; i < dropDownEntries.length; i++) {
                        if(dropDownEntries[i] == elem.find(findStr).text()){
                            isInDropdown = true;
                        }    
                    }
                    if(isInDropdown == false){
                        dropDownEntries.push(elem.find(findStr).text());
                    }
                }
                
                var allRows = table.config.cache.row;

                for (var i = 0; i < allRows.length; i++) {
                    allRows[i].each(search_text);
                }
                
                $(dropdown).append(
                    $('<option></option>').val(" ").html(labelDropDown)
                );
                for (var i = 0; i < dropDownEntries.length; i++) {
                    $(dropdown).append(
                        $('<option></option>').val(dropDownEntries[i]).html(dropDownEntries[i])
                    );
                }
            };
            
            function dropdownFromSelection(column, dropdown) {
                var findStrAll = "";
                var findStr = "";
                var dropDownEntries = new Array();
                var labelDropDown = "";
                
                if (column == 1){
                    labelDropDown = labelDropDown1;
                } else if (column == 2){
                    labelDropDown = labelDropDown2;
                } else if (column == 3){
                    labelDropDown = labelDropDown3;    
                } else {
                    labelDropDown = labelDropDown4;
                }
                 
                var phrase1 = "";
                var phrase2 = "";
                var phrase3 = "";
                var phrase4 = "";
                
                if ($('#filterSelection0').val() != '')
                    phrase1 = $('#filterSelection0').val() + ' ';
                if (($('#filterSelection1').val() != '') && ($('#filterSelection1').length > 0))
                    phrase2 = $('#filterSelection1').val() + ' ';    
                if (($('#filterSelection2').val() != '') && ($('#filterSelection2').length > 0))
                    phrase3 = $('#filterSelection2').val()
                if (($('#filterSelection3').val() != '') && ($('#filterSelection3').length > 0))
                    phrase4 = $('#filterSelection3').val()    
                    
                phrase = phrase1 + phrase2 + phrase3 + phrase4;
                
                var phrase_length = phrase.length;
                var caseSensitive = table.config.filterCaseSensitive;
                var words = caseSensitive ? phrase.split(" ") : phrase.toLowerCase().split(" ");
                var columns = table.config.filterColumns;
                var resultRows = [];

                var success = function(elem) {
                    elem.show();
                    resultRows.push(elem);
                }
                var failure = function(elem) { ; }

                findStr = "td:eq(" + column + "),";
                for (var i = 0; i < columns.length; i++) {
                    findStrAll += "td:eq(" + columns[i] + "),";
                }
                var dropdownDefault = $(dropdown).val();
                $(dropdown).html("");
                
                var search_text_all_rows = function() {
                    var elem = jQuery(this);

                    has_words(elem.find(findStrAll).text(), words, caseSensitive) ? success(elem) : failure(elem);
                }
                
                var search_text = function() {
                    var elem = jQuery(this);
                    var isInDropdown = false;

                    for (var i = 0; i < dropDownEntries.length; i++) {
                        if(dropDownEntries[i] == elem.find(findStr).text()){
                            isInDropdown = true;
                        }    
                    }
                    if(isInDropdown == false){
                        dropDownEntries.push(elem.find(findStr).text());
                    }
                }

                // Walk through all of the table's rows and search.
                // Rows which match the string will be pushed into the resultRows array.
                var allRows = table.config.cache.row;
                for (var i = 0; i < allRows.length; i++) {
                    allRows[i].each(search_text_all_rows);
                }
                
                for (var i = 0; i < resultRows.length; i++) {
                    resultRows[i].each(search_text);
                }
                
                $(dropdown).append(
                    $('<option></option>').val(" ").html(labelDropDown)
                );
                for (var i = 0; i < dropDownEntries.length; i++) {
                    $(dropdown).append(
                        $('<option></option>').val(dropDownEntries[i]).html(dropDownEntries[i])
                    );
                }
                if ((resultRows.length == 0) && (dropdownDefault != ' ')){
                    $(dropdown).append(
                        $('<option></option>').val(dropdownDefault).html(dropdownDefault)
                    );
                }
                $(dropdown).val(dropdownDefault);
            };
            
            this.createDropdownFromColumn = function(column, dropdown) {
                dropdownFromColumn(column, dropdown);
            };
            
            this.createDropdownFromSelection = function(column, selectedValue) {
                var j = 0;
                for(var i = 0; i < filterDropDowns.length; i++){
                    if(filterDropDowns[i] != column){
                        dropdownFromSelection(filterDropDowns[i], '#filterSelection' + i);
                    } else {
                        if (selectedValue == ' '){
                            dropdownFromSelection(filterDropDowns[i], '#filterSelection' + i);
                        }
                    }
                }
            };
            
            this.initFilterOnLoad = function(value) {
                doFilter(table, value);
            };            

            this.defaults = {
                filterContainer: '#filter-box',
                filterClearContainer: '#filter-clear-button',
                filterColumns: null,
                filterCaseSensitive: false
            };

            this.construct = function(settings) {

                return this.each(function() {

                    config = $.extend(this.config, $.tablesorterFilter.defaults, settings);

                    var table = this;

                    // Create a timer which gets reset upon every keyup event.
                    //
                    // Perform filter only when the timer's wait is reached (user finished typing or paused long enough to elapse the timer).
                    //
                    // Do not perform the filter is the query has not changed.
                    //
                    // Immediately perform the filter if the ENTER key is pressed.

                    function checkInputBox(inputBox, override) {
                        var value = inputBox.value;

                        if ((value != inputBox.lastValue) || (override)) {
                            inputBox.lastValue = value;
                            doFilter(table, value);
                        }
                    };

                    var timer;
                    
                    var selectionString = '';
                    var selection1String = '';
                    var selection2String = '';
                    var selection3String = '';
                    var selection4String = '';
                    
                    $('#showResult').click(function(){
                        if ($('#filterSelection0').val() != '')
                            selection1String = $('#filterSelection0').val() + ' ';
                        if (($('#filterSelection1').val() != '') && ($('#filterSelection1').length > 0))
                            selection2String = $('#filterSelection1').val() + ' ';    
                        if (($('#filterSelection2').val() != '') && ($('#filterSelection2').length > 0))
                            selection3String = $('#filterSelection2').val()
                        if (($('#filterSelection3').val() != '') && ($('#filterSelection3').length > 0))
                            selection4String = $('#filterSelection3').val()    
                            
                        selectionString = selection1String + selection2String + selection3String + selection4String;    
                        
                        if (selectionString != ''){
                            $('#filterBox').val(selectionString);
                        } else {
                            return false;
                        }
                        
                        var timerWait = 500;
                        var overrideBool = false;
                        var inputBox = this;
                        
                        // Was ENTER pushed?
                        if (inputBox.keyCode == 13) {
                            timerWait = 1;
                            overrideBool = true;
                        }

                        var timerCallback = function() {
                            checkInputBox($('#filterBox').get(0), overrideBool)
                        }

                        // Reset the timer      
                        clearTimeout(timer);
                        timer = setTimeout(timerCallback, timerWait);

                        return false;
                    });

                    $(config.filterClearContainer).click(function() {
                        clearFilter(table);
                        $(config.filterContainer).val("").focus();
                    });

                    $(table).bind("clearFilter", function() {
                        clearFilter(table);
                    });
                });
            };

        }
    });

    // extend plugin scope
    $.fn.extend({
        tablesorterFilter: $.tablesorterFilter.construct
    });

})(jQuery);  
