/*****************************
Browse Plugin by
Raviv Murciano-Goroff
******************************/



(function ($) {
    $.fn.browse = function (options) {
        
        var defaults = {
            waitForTyping: 1000,
            selector: "#results",
            constructRows: function (hit) {
                title = hit.find("title").text();
                url = hit.find("url").text();
                title = "<a href=\"" + url + "\">" + title + "</a>";
                var row = $("<tr><td>" + title + "</td></tr>");
                return row;
            }
        };
        
        var options = $.extend(defaults, options);
        
        return this.each(function () {
            //set the variable obj to be the bounding div
            var obj = $(this);
            
            options.wait = setTimeout("", options.waitForTiming);
            options.pageNum = $("<input type='hidden' name='page' value='1' />");
            obj.append(options.pageNum);
            
            obj.find("label").append("<span></span>");
            
            
            //make it an ajax form
            obj.ajaxForm(function (xml) {
                clearTimeout(options.wait);
                
                $(options.selector).children().remove();
                
                var summary = $("<div id='summary'></div>");
                $(options.selector).prepend("<hr class='space' />");
                $(options.selector).prepend(summary);
                var info = $("<span id=\"summary_info\"></span>");
                summary.append(info);
                var paginator = $("<div id=\"paginator\"></div>");
                paginator.addClass("clearfix");
                summary.append(paginator);
                
                var numbernav = $("<div id=\"numbersnav\"></div>");
                numbernav.append($("<ul></ul>"));
                paginator.append(numbernav);
                
                
                var progressbar = $("<img src='images/volumebrowse/progress.gif' />");
                summary.prepend(progressbar);
                
                //make sure that the table is always clear before refreshing the data in it
                $(options.selector).append("<table>");
                
                var thead = $("<thead></thead>");
                $('head', xml).each(function (i) {
                    var th = $("<th>"+$(this).attr('name')+"</th>");
                    thead.append(th);
                });
                $(options.selector).find("table").append(thead);
                
                // Run the function for each hit in the XML
                //and construct and append the hit as a row to your table
                $('hit', xml).each(function (i) {
                    var row = options.constructRows($(this));
                    $(options.selector).find("table").append(row);
                });
                
                
                $('facet', xml).each(function (i) {
                    var name = $(this).attr("name");
                    var value = $(this).attr("key");
                    var count = $(this).attr("count");
                    var input = obj.find("input[name=" + name + "][value=" + value + "]");
                    var label = obj.find("label[for=" + input.attr("id") + "]");
                    label.find("span").text(" (" + count + ")");
                });
                
                
                //pull the totalHits, totalPages, onPage and place them in the summary area
                options.totalHits = parseInt($('summary', xml).find("hits").text());
                options.totalPages = Math.ceil((options.totalHits / parseInt($('summary', xml).find("perpage").text())));
                options.pageNum.val(parseInt($('summary', xml).find("page").text()));
                options.perPage = parseInt($('summary', xml).find("perpage").text());
                
                displayStart = (parseInt(options.pageNum.val() - 1) * options.perPage + 1);
                displayEnd = (parseInt(options.pageNum.val()) * options.perPage);
                if (displayEnd > options.totalHits) {
                    displayEnd = options.totalHits;
                }
                
                if (options.totalHits == 0) {
                    info.text("Sorry, no results found.");            
                    
                } else {
                    info.text("Results: Displaying " + displayStart + "-" + displayEnd + " of " + options.totalHits + " results.");            
                }
                
                
                var prev = $("<li id=\"prev\">Prev</li>");
                numbernav.children("ul").append(prev);
                
                if (parseInt(options.pageNum.val()) <= 10 && options.totalPages <= 10) {
                    var startnumber = 1;
                    var endnumber = options.totalPages;
                }
                
                if (options.totalPages > 10) {
                    var startnumber = (parseInt(options.pageNum.val()) - 10);
                    if (startnumber <= 0) {
                        startnumber = 1;
                    }
                    var endnumber = (parseInt(options.pageNum.val()) + 10);
                    if (endnumber > options.totalPages) {
                        endnumber = options.totalPages;
                    }
                }
                
                for (var i = startnumber; i <= endnumber; i++) {
                    numbernav.children("ul").append("<li><a href='#'>" + i + "</a></li>");
                }
                
                numbernav.find("li").eq((parseInt(options.pageNum.val()) - startnumber) + 1).addClass("active");
                
                var next = $("<li id=\"next\">Next</li>");
                numbernav.children("ul").append(next);
                
                numbernav.children("ul").children("li").children("a").unbind();
                numbernav.children("ul").children("li").children("a").click(function () {
                    options.pageNum.val(parseInt($(this).text()));
                    obj.submit();
                    return false;
                });
                
                
                
                //if we are on the first page then disable the previous button
                //if we are on the last page then disable the next button
                if (parseInt(options.pageNum.val()) <= 1) {
                    prev.remove();
                }
                if (parseInt(options.pageNum.val()) >= options.totalPages) {
                    next.hide();
                }
                
                //if there is only one page then do not display the numbers
                if (options.totalPages == 1) {
                    numbernav.hide();
                } else {
                    numbernav.show();
                }
                
                //on click of previous check to make sure taht you can go backward before submitting the form
                $("#prev").unbind();
                $("#prev").click(function () {
                    if (! $(this).hasClass("disabled")) {
                        options.pageNum.val(parseInt(options.pageNum.val()) - 1);
                        obj.submit();
                    }
                    return false;
                });
                
                //on click of next check to make sure taht you can go forward before submitting the form
                $("#next").unbind();
                $("#next").click(function () {
                    if (! $(this).hasClass("disabled")) {
                        options.pageNum.val(parseInt(options.pageNum.val()) + 1);
                        obj.submit();
                    }
                    return false;
                });
                
                progressbar.remove();
            });
            
            //for all the textboxes they should start a timer going when someone starts typing in them.
            //if someone keeps typing then just keep reseting the timer
            //if they stop then the timer will expire and then it will clear and submit
            //dont do this for the pageNum
            obj.find("input[type=text]").keypress(function (e) {
                if (e.which != 0) {
                    
                    
                    
                    if ($(this).val().length > 1) {
                        clearTimeout(options.wait);
                        options.wait = setTimeout(function () {
                            $.browse.clearAndSubmit(obj, options);
                        },
                        options.waitForTyping);
                    }
                }
            });
            
            obj.find("input:not([type=text])").change(function () {
                $.browse.clearAndSubmit(obj, options);
            });
            
            obj.find(".clear").click(function() {
                obj.find("div.bordered").not(".slider").find("input[type=text]").val("");
                obj.find("input[type=radio]").attr("checked","");
                obj.find("input[type=checkbox]").attr("checked","");
            });
        });
    };
    $.browse = function () {
    }
    $.browse.validatePageNum = function (obj, options) {
        if (parseInt(options.pageNum.val()) > options.totalPages) {
            parseInt(options.pageNum.val()) = options.totalPages;
        }
        if (parseInt(options.pageNum.val()) < 1) {
            parseInt(options.pageNum.val()) = 1;
        }
        obj.submit();
    }
    $.browse.clearAndSubmit = function (obj, options) {
        options.pageNum.val(1);
        obj.submit();
    }
})(jQuery);
