﻿var currentPage = 0;
//=============================================================
// Fixing problem with Array.indexOf not working in IE
//
// Code from : 
// http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
//=============================================================
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++) {
            if (from in this &&
          this[from] === elt)
                return from;
        }
        return -1;
    };
}
//===========================================================
// SORTING THE TABLE
//===========================================================
function sortTable() {
    $('table.sortable').each(function() {
        var $table = $(this);

        $('th', $table).each(function(column) {
            var findSortKey;

            if ($(this).is('.sort-alpha')) {
                findSortKey = function($cell) {
                    return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
                };

            } else if ($(this).is('.sort-numeric')) {
                var strSearch = new RegExp("[^-^0-9^.^,]", "gi");
                findSortKey = function($cell) {
                    //var key = parseFloat($cell.text().replace(/^[^d.]*/, ''));
                    var key = parseFloat($cell.text().replace(strSearch, '').replace(/\,/, '.'));
                    return isNaN(key) ? 0 : key;
                };
            } else if ($(this).is('.sort-date')) {
                findSortKey = function($cell) {
                    return Date.parse('1 ' + $cell.text());
                };
            }

            if (findSortKey) {
                $(this).addClass('clickable').hover(function() {
                    $(this).addClass('hover');
                }, function() {
                    $(this).removeClass('hover');
                }).click(function() {
                    var newDirection = 1;

                    if ($(this).is('.sorted-asc')) {
                        newDirection = -1;
                    }

                    var rows = $table.find('tbody > tr').get();

                    $.each(rows, function(index, row) {
                        row.sortKey = findSortKey($(row).children('td').eq(column));
                    });

                    rows.sort(function(a, b) {
                        if (a.sortKey < b.sortKey) return -newDirection;
                        if (a.sortKey > b.sortKey) return newDirection;
                        return 0;

                    });

                    $.each(rows, function(index, row) {
                        $table.children('tbody').append(row);
                        row.sortKey = null;
                    });

                    $table.find('th').removeClass('sorted-asc').removeClass('sorted-desc');

                    var $sortHead = $table.find('th').filter(':nth-child(' + (column + 1) + ')');

                    if (newDirection == 1) {
                        $sortHead.addClass('sorted-asc');

                    } else {
                        $sortHead.addClass('sorted-desc');
                    }

                    $table.find('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
                    $table.trigger('filter');
                });
            }
        });
    });
    //===========================================================
    // FILTER FUNCTIONS
    //===========================================================
    $('table.filterable').each(function() {
        var $table = $(this);
        var selection = {};
        var selectionOrg = {};
        var iFilterCols = 0;

        $table.find('th').each(function(column) {
            selection[column] = [];
            selectionOrg[column] = [];

            if ($(this).is('.filter-column')) {
                //-------------------------------------------------
                // Build a list of keywords
                //-------------------------------------------------
                //var $filterBox = $("#filters table tr td:last");
                var $filterBox = $('#filters td.filterHeader').next('td');
                var keywords = {};
                var str = '';

                iFilterCols++;

                $table.find('tbody tr td').filter(':nth-child(' + (column + 1) + ')').each(function() {
                    keywords[$(this).text()] = { val: $(this).text(), col: column };
                    var pos = selection[column].indexOf($(this).text());
                    if (pos == -1) {
                        selection[column].splice(0, 0, $(this).text());
                        selectionOrg[column].splice(0, 0, $(this).text());
                    }
                });
                //-------------------------------------------------
                // Build all the filter checkboxes
                //-------------------------------------------------
                var $filterType = $(this).text();
                keywords = sortKeywords(keywords);

                str = str + '<table border="0" cellspacing="0" cellpadding="0" class="subFilter" width="100%">';
                str = str + '	<tr>';
                str = str + '		<td width="100">' + $filterType + '</td>';
                str = str + '		<td>';
                str = str + '			<span class="filterAll"><input type="checkbox" value="all" name="' + $filterType + '" checked> Visa alla</span>';

                $.each(keywords, function(index, keyword) {
                    var it = keyword.val.toString();

                    if (it.indexOf("function(") < 0) {
                        str = str + '<span class="filterItem"><input type="checkbox" value="' + keyword.val + '" name="' + $filterType + '"> ' + keyword.val + '</span>';
                    }
                });

                str = str + '       </td>';
                str = str + '	</tr>';
                str = str + '</table>';

                $filterBox.append(str);
                //-------------------------------------------------
                // Add functionality to the checkboxes
                //-------------------------------------------------
                $('input:checkbox[name=' + $filterType + '][value=all]').bind('click', function() {
                    $('input:checkbox:checked[name=' + $filterType + ']').not('[value=all]').each(function() {
                        this.checked = !this.checked;
                        selection[column] = selectionOrg[column];
                        $table.trigger('filter');
                    });
                });

                $.each(keywords, function(index, keyword) {
                    var it = keyword.val.toString();

                    if (it.indexOf("function(") < 0) {
                        $('input:checkbox[name=' + $filterType + '][value=' + keyword.val + ']').bind('click', { 'keyword': keyword }, function(event) {
                            $(':checkbox:checked[name=' + $filterType + '][value=all]').each(function() {
                                this.checked = !this.checked;
                            });
                            //-------------------------------------------------
                            // Fixing the selection variable to see what is
                            // selected from the filters
                            //-------------------------------------------------
                            var temp = [];
                            $(':checkbox[name=' + $filterType + ']').not('[value=all]').each(function() {
                                if ($(this).attr('checked') == true) {
                                    temp.splice(0, 0, $(this).attr('value'));
                                }
                            });

                            selection[keyword.col] = temp

                            if ($(':checkbox:checked[name=' + $filterType + ']').length == 0) {
                                $(':checkbox[name=' + $filterType + '][value=all]').attr('checked', true);
                                selection[keyword.col] = selectionOrg[keyword.col];
                            }
                            //-------------------------------------------------
                            // Set the current page back to the first page
                            //-------------------------------------------------
                            currentPage = 0;
                            $table.trigger('filter');
                        });
                    }
                });

            }
        });
        $('.subFilter:last').css('border-bottom', '0');
        //-------------------------------------------------
        // This will redraw the table and only show selected
        // filters
        //-------------------------------------------------
        $table.bind('filter', function() {
            $table.find('tbody tr').each(function() {
                var i = 0;
                var j = 0;

                $('td', $(this)).each(function() {
                    if (selection[i].indexOf($(this).text()) > -1) {
                        j++;
                    }
                    i++;
                });

                if (j == iFilterCols) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
            $table.trigger('repaginate');
        });

    });
    //===========================================================
    // BUILDING PAGING FUNCTION
    //===========================================================
    $('table.paginated').each(function() {
        var numPerPage = 10;
        var $table = $(this);
        var $pager = $('#pager');
        var $Sizer = $('.pageSize');
        //-------------------------------------------------
        // Fixing number of results per page
        //-------------------------------------------------
        $('#paging').bind('change', function() {
            if ($('#paging').val() == "all") {
                numPerPage = 999999999999;
            } else {
                numPerPage = $('#paging').val();
            }
            currentPage = 0;
            $table.trigger('filter');
        });
        //-------------------------------------------------
        // Repaginate
        //-------------------------------------------------
        $table.bind('repaginate', function() {
            var numRows = $table.find('tbody tr:visible').length;
            var numPages = Math.ceil(numRows / numPerPage);

            $pager.attr('innerHTML', '');

            // Calculate what is showing
            strMax = (currentPage + 1) * numPerPage;
            strRows = $table.find('tbody tr:visible').length;

            if (strMax > numRows) {
                strEnd = numRows;
            } else {
                strEnd = strMax;
            }

            strExtra = 'Visar ' + ((currentPage * numPerPage) + 1) + ' - ' + strEnd + ' av ' + numRows + '&nbsp;:&nbsp;&nbsp;';

            // Print it to the screen
            $pager.append(strExtra);

            if (currentPage > 0) {
                $('<span style="font-size: 18px;"><b>&laquo;</b>&nbsp;</span>').bind('click', function() {
                    currentPage = currentPage - 1;
                    $table.trigger('filter');
                }).appendTo($pager).addClass('clickable');
            }

            $table.find('tbody tr:visible').show().slice(0, currentPage * numPerPage).hide().end().slice((currentPage + 1) * numPerPage).hide().end();

            for (var page = 0; page < numPages; page++) {
                $('<span class="page-number">' + (page + 1) + '</span>').bind('click', { 'newPage': page }, function(event) {
                    currentPage = event.data['newPage'];
                    $table.trigger('filter');
                }).appendTo($pager).addClass('clickable');
            }

            if ((currentPage + 1) < numPages) {
                $('<span style="font-size: 18px;">&nbsp;<b>&raquo;</b></span>').bind('click', function() {
                    currentPage = currentPage + 1;
                    $table.trigger('filter');
                }).appendTo($pager).addClass('clickable');
            }

            // Set active page visible
            $('.page-number').each(function(i) {
                if (i == currentPage) {
                    $(this).addClass('active');
                }
            });
        });

        $table.trigger('repaginate');
    });
}
//===========================================================
// Function to sort the keywords
//===========================================================
function sortKeywords(oAssoc) {
    var idx; var key; var arVal = []; var arCol = []; var arValKey = []; var oRes = {};

    for (key in oAssoc) {
        arVal[arVal.length] = oAssoc[key].val;
        arCol[arCol.length] = oAssoc[key].col;
        arValKey[oAssoc[key].val] = key;
    }

    arVal.sort();

    for (idx in arVal)
        oRes[arValKey[arVal[idx]]] = { val: arVal[idx], col: arCol[idx] };

    return oRes;
}
