var FilteredSearch; // Globally scoped variable that can be used by other files
var Paginator;
var FilteredSearchFormatter;
(function($) {
	$(document).ready(function() {
        var ui = {
            method: 'blind',
            duration: 5000
        };

		var checkNoMatchingItems = function() {
			if ($("#filtered-product-list").find("li:visible").length == 0) {
				$(".no-matching-items").show();
			}
		};

		//iterate over each item and see if it matches at least one selection in each question group
		//if there are one or more question groups that this item does not match, then hide it
		var filter = function() {
			$(".no-matching-items").hide();
			//iterate over each product
            var list = $('#filtered-product-list');
			$.each(list.find("li"), function(i, item) {
				var matchesAllGroups = true;
				//iterate over each question and see if the product matches at least one selection in that question
				$("dd").each(function(j, group) {
					var matchesGroup = false;
					//check each selection within the group
					$(group).find("input:checked").each(function(k, input) {
						//the product matches at least one selection in the question so it does match the group
						if ($(item).hasClass($(input).val())) {
							matchesGroup = true;
						}
					});
					
					//handle exceptions
					//if wine cellar/bev center has a clear or fluted glass door, then selecting "Glass Door" 
					//for the "door style" question will match them
					if (!matchesGroup && $(group).ident() == "doorStyleQ" && $("#glassDoorStyleOption").attr("checked") 
							&& ($(item).hasClass("ClearGlass") || $(item).hasClass("FlutedGlass"))) {
						matchesGroup = true;		
					}
					//done handling exceptions
	
					//if the product does not match the group, then mark flag to hide this item
					if (!matchesGroup && matchesAllGroups) {
						matchesAllGroups = false;
					}
				});

				//determine if item needs to be hidden using the matchesAllGroups flag
				if (matchesAllGroups) {
                    $(item).removeClass("filtered").show();
				} else {
					$(item).addClass("filtered").hide();
				}
			});

            FilteredSearch.redraw(list);
            Paginator.update(list);
			//display "no matching items" message if there are no items to display
			checkNoMatchingItems();
		};

		FilteredSearch = function() {
			return {
                // Recalculates the number of "pages" in this list, removes the current set of page links,
                // adds a new set to reflect the new number, and then attaches new click listeners.
                redraw: function(list) {
                    var visible = list.find('li:visible');
                    if (visible.length < 12) {
                        var last = list.find('li:visible:last');
                        var unfiltered = last.nextAll(':not(.filtered)');
                        var limit = 12 - visible.length;
                        // If there aren't 12 items displayed on the current page, then try to get
                        // enough on following pages to fill this one up.
                        $.each(unfiltered, function(i, item) {
                            if (i >= limit) {
                                return false;
                            }
                            $(item).show();
                        });
                    } else {
                        // Hide everything past the 12th node
                        visible.each(function(i, item) {
                            if (i > 11) {
                                $(item).hide();
                            }
                        });
                    }
                },
				search: function() {
					$(":checkbox").change(function() {
						filter();
					}).click(function() {
                        $(this).change().blur();
                    });


				}

			};
		}();
		FilteredSearch.search();

        Paginator = function() {
            var per_page = 12;
            var current_class = "page-current";
            var previous_page = 0;
            var current_page = 1;
            var index = 0;
            var pivots = {
                first: null,
                last: null
            };
            var ui = {
                method: 'slide',
                duration: 100
            };
            
            var findIndexOfItem = function(list, id) {
            	var index = null;
            	for (var i = 0; i < list.length && !index; i++) {
            		if ($(list[i]).ident() == id) {
            			index = i;
            		}
            	}
            	return index;
            };

            // Code to run when one of the "page" links is clicked. This is harder than just moving
            // from one page to the next because you could jump back an arbitrary number of pages.
            var page_click = function() {
                if ($(this).hasClass(current_class)) {
                    return false;
                }
                var list = $('#filtered-product-list');
                var unfiltered = list.find('li:not(.filtered)');
                var visible = list.find('li:visible');
                pivots.first = visible[0];
                pivots.last = visible[visible.length - 1];
                previous_page = $(this).siblings(current_class.classPack()).removeClass(current_class).ident().split('-')[1];
                current_page = $(this).ident().split('-')[1];
                index = current_page - 1;
                var offset = Math.abs(current_page - previous_page);
                var forward = current_page > previous_page;
                var pivot = (forward) ? pivots.last : pivots.first;
                pivot = findIndexOfItem(unfiltered,$(pivot).ident());
                //pivot = Number($(pivot).ident().split('-')[1]);

                var results = (forward) ? unfiltered.filter(':gt(' + pivot + ')') : unfiltered.filter(':lt(' + pivot + ')');
                var start, end;
                if (forward) {
                    start = (offset - 1) * per_page;
                    end = start + per_page;
                    results = results.slice(start, end);
                    list.hide(ui.method, {direction: 'left'}, ui.duration, function() {
                        unfiltered.css({display: 'none'});
                        results.css({display: 'block'});
                        list.show(ui.method, {direction: 'right'}, ui.duration, position_links);
                    });
                } else {
                    start = (current_page - 1) * per_page;
                    end = start + per_page;
                    results = results.slice(start, end);
                    list.hide(ui.method, {direction: 'right'}, ui.duration, function() {
                        unfiltered.css({display: 'none'});
                        results.css({display: 'block'});
                        list.show(ui.method, {direction: 'left'}, ui.duration, position_links);
                    });
                }
                $(this).addClass(current_class);
                return false;
            };

            // Code to run when one of the side buttons is clicked. This will only move forward or backward
            // one page at a time.
            // Update: Now this just hands off to the page_click function.
            var side_button_click = function() {
                var pager = $('#paginator');
                var current_page = pager.find(current_class.classPack());
                var link = $(this);
                var other_page = null;
                if (link.ident().match(/next/)) {
                    other_page = current_page.next();
                } else {
                    other_page = current_page.prev();
                }
                if (other_page.length > 0) {
                    other_page.click();
                }
                return false;
            };

            var position_links = function() {
                var div = $('#filtered-search-results');
                var list = $('#filtered-product-list');
                var links = div.find('#media-previous, #media-next');
                var linkheight = links.eq(0).height();
                var boxheight = list.height();
                boxheight = (boxheight / 2) - (linkheight / 2);
                links.css({
                    top: boxheight
                });
                return false;
            };
            return {
                paginate: function(list) {
                    //LOKVIK-1628: Check for #paginator first before adding one
                    if ($('#paginator').exists()) {
                        return false;
                    }

//                  Uncomment the following to replace all of the elements with visibly identifiable and verifiable numbers
//                    list.find('li').each(function(i) {
//                        $(this).text(i + 1).css({fontWeight: 'bold', color: 'white', fontSize: '3em', backgroundColor: 'orange', textAlign: 'center'});
//                    });
                    var tail = list.find(['li:gt(', per_page - 1, ')'].pack());
                    tail.hide();
                    list.css({
                        height: list.outerHeight()
                    });
                    position_links();
                    var div = $('<div class="clear clearfix" id="paginator"><span>Page: </span></div>');
                    var span = div.find('span');
                    var pages = (tail.length / per_page) + 1;
                    for (var i = 0; i < pages; i++) {
                        var str = ['page', i + 1].join('-');
                        var a = $(['<a href="#', str, '" id="', str, '">', i + 1, '</a>'].pack());
                        span.append(a);
                    }
                    list.after(div);
                    $('#page-1').addClass(current_class);
                    var links = div.find('a');
                    if (links.length > 1) {
                        links.click(page_click);
                    }
                },
                update: function(list) {
                    $('#paginator a').remove();
                    var tail = list.find('li:not(.filtered)');
                    var pages = tail.length / per_page;
                    for (var i = 0; i < pages; i++) {
                        var str = ['page', i + 1].join('-');
                        var a = $(['<a href="#', str, '" id="', str, '">', i + 1, '</a>'].pack());
                        $('#paginator span').append(a);
                    }
                    $('#paginator a:first').addClass(current_class);
                    $('#paginator a').click(page_click);
                },
                scroll: function(div) {
                    var links = div.find('#media-previous, #media-next');
                    links.bind("click", side_button_click);
                }
            };
        }();
        Paginator.paginate($('#filtered-product-list'));

        FilteredSearchFormatter = function() {
            return {
                add_sliders: function() {
                     /* IE6 background flicker fix */
                    try {
                        document.execCommand('BackgroundImageCache', false, true);
                    } catch (e) {
                        
                    }
                    $('#filtered-search-form :checkbox:visible').each(function(i) {
                        var checkbox = $(this);
                        var span = $('<span class="checkbox-replacement"></span>');
                        checkbox.after(span);
                        if (this.checked) {
                            span[0].checked = true;
                            span.addClass("checked");
                        } else {
                            span[0].checked = false;
                        }
                        span[0].checkbox = this;

                        span.click(function() {
                            this.checked = !this.checked;
                            this.checkbox.checked = this.checked;
                            filter();

                            if ($.browser.msie && $.browser.version < 7) {
                                if (this.checked) {
                                    $(this).height(9);
                                    $(this).css('background', 'transparent url(../images/filtered_search/checkbox-replacement-checked.png) 0 0 no-repeat');
                                    var src = $(this).css('background-image').split('url("')[1].split('")')[0];
                                    var img = $(['<img src="', src, '" align="bottom" />'].pack());
                                    $(this).empty().append(img);
                                } else {
                                    $(this).height(9);
                                    $(this).css('background', 'transparent url(../images/filtered_search/checkbox-replacement-unchecked.png) 0 0 no-repeat');
                                    var src = $(this).css('background-image').split('url("')[1].split('")')[0];
                                    var img = $(['<img src="', src, '" align="bottom" />'].pack());
                                    $(this).empty().append(img);
                                }
                            } else {
                                if (this.checked) {
                                    $(this).addClass("checked");
                                } else {
                                    $(this).removeClass("checked");
                                }
                            }
                            return false;
                        });
                        // Make the <label> click the <span> instead of the checkbox.
                        checkbox.parents('label:first').click(function() {
                            $(this).find('span.checkbox-replacement').click();
                            return false;
                        });
                        checkbox.hide();

                    });
                    
                    
                    $('.become-slider').each(function(i) {
                        if ($(this).hasClass('has-sliders')) {
                            return false;
                        }

                        var dd = $(this);
                        dd[0].value = 0;
                        dd[0].range = 0;
                        var inputs = $(this).find(':checkbox');
                        var max = inputs.length - 1;

                        var div = $('<div>');
                        div.data("min", 0);
                        div.data("max", max);
                        $(this).append(div);

                        var options =  {
                            range: true,
                            handles: [
                                {start: 0, min: 0,  max: max, id: ['low-', i].pack()},
                                {start: max, min: 0, max: max, id: ['high-', i].pack()}
                            ],
                            value: 0,
                            min: 0,
                            max: inputs.length - 1,
                            step: 1,
                            start: function(event, ui) {
                                return false;    
                            },
                            slide: function(e, ui) {
                                dd[0].value = ui.value;
                            },
                            change: function(evt, ui) {
                                var handle = $(ui.handle);
                                var high = handle.ident().match(/high/) ? true : false;
                                var value = ui.value;
                                var minval = div.data('min');
                                var maxval = div.data('max');
                                if (!high) {
                                    minval = value;
                                } else {
                                    maxval = value;
                                }
                                div.data('min', minval);
                                div.data('max', maxval);
                                
                                var boxes = handle.parents('dd:first').find(':checkbox');
                                boxes.uncheck();

                                for (var j = minval; j <= maxval; j++) {
                                    $(boxes[j]).check();
                                }

                                filter();
                            }
                        };
                        $(this).find(':checkbox').click(filter);
                        // Sliders removed per client request
                        /*
                        div.slider(options);
                        var labelBox = $('<ol class="slider-labels">')
                        var labels = $(this).find('label');
                        $.each(labels, function() {
                            var label = $(this);
                            var li = $('<li>').text(label.text());
                            labelBox.append(li);
                        });
                        labels.hide();
                        $(this).append(labelBox);
                        if ($.browser.msie && $.browser.version > 6) {
                            // IE is dumb and won't respect the bottom margin of this <dd>
                            //$(this).next('dt:first').css('padding-top', '15px');
                        } else if ($.browser.msie && $.browser.version < 7) {
                            // IE6 is also dumb and won't position the handles correctly
                            $(this).find('.ui-slider-handle').css({
                                position: 'absolute',
                                top: '0px'
                            });
                        }
                        $(this).find('.ui-slider-handle').hover(function() {
                            $(this).css({cursor: 'pointer'});
                        }, function() {
                            $(this).css({cursor: 'normal'});
                        });
                        $.spreadItemsEvenly(labelBox);
                        $(this).addClass('has-sliders');
                        */
                    });
                }
            };
        }();
        FilteredSearchFormatter.add_sliders();

	});
}(jQuery));
