var ProductFinder; // globally scoped object that can be used by other files as long as they're included after this one
(function($) {
    $(document).ready(function() {

        var Urls = function() {
            var root = '/consumer';
            var data = {
                finder: '/util/ajax/finder.jsp'
            };
            return {
                get: function(key) {
                    return [root, data[key]].pack();
                }
            };
        }();

        var listen = function(list) {

            try {
                var product_finder = list.parents('.product-finder:first');
                var bottom = product_finder.data("baseline");

                var reposition2 = function() {
                    Log.dir(this);    
                };

                var reposition = function(speed) {
                    if (product_finder.exists()) {
                        var opts = {
                            duration: (speed) ? 0 : 300,
                            easing: 'swing'
                        };
                        var height = product_finder.height();
                        var scrollTop = $(window).scrollTop();
                        if (height > bottom) {
                            var diff = -1 * (height - bottom + scrollTop + 20);
                            product_finder.animate({"bottom": diff.pixelate()}, opts.duration, opts.easing);
                        } else {
                            product_finder.animate({"bottom": 0}, opts.duration, opts.easing);
                        }
                    }
                };

                list.find('.expanded').slideUp('fast', function() {
                    $(this).removeClass('expanded');
                });
                //var tier = list.ident().split('finder-tier-')[1];
                var tier = list[0].className.split(' ')[0].split('tier-')[1];
                tier = Number(tier);
                var nextTier = tier + 1;
                list.find(' > li > a').each(function() {
                    this.clicked = false;
                });
                list.find(' > li > a').click(function() {
                    var anchor = $(this);
                    anchor.parents(':first').siblings('li').find('ul').hide();
                    var listItem = anchor.parent(':first');
                    listItem.siblings().removeClass('open');
                    listItem.toggleClass('open');
                    if (anchor.siblings('ul').length > 0) {
                        var ret = true;
                        anchor.siblings('ul:visible').slideUp('fast', function() {
                            reposition('fast');
                            $(this).removeClass('expanded');
                        });
                        anchor.siblings('ul:hidden').slideDown('slow', function() {
                            reposition();
                        });
                        return false;
                    }

                    //listItem.toggleClass('open');
                    // collapse everybody else
                    listItem.siblings('li').find('ul').slideUp('slow');
                    var id = anchor.ident().split('-')[1];
                    var followLink = false;
                    
                    //LOKVIK 1464 - Needed for the Support Page Filtering
                    var filterByDocs = product_finder.find('a:first').attr("id");
                    
                    if (tier < 3) {
                        $.get(Urls.get('finder'), {id: id, depth: tier, docFilter: filterByDocs}, function(data) {
                            if (!data || anchor.hasClass("noChildren")) {
                                window.location = anchor.attr('href');
                                return false;
                            } else {
                                var array = JSON.parse(data);
                                var ul = $('<ul>').ident(['finder-tier-', nextTier].pack()).css({display: 'none'}).addClass(['finder-tier-', nextTier].pack()).addClass(['finder-tier-', nextTier, 'closed'].pack());
                                var sortedList = [];
                                if (tier < 2) {
                                    // The array might not contain elements with the sortOrder property.
                                    // This is true with countertop appliances, so make sure it's there
                                    // before operating on it.
                                    if (array.length > 0 && array[0].sortOrder) {
                                        // Re-order the array since the original list on the server didn't take advantage of the automatic
                                        // sorting provided by a list
                                        $.each(array, function(i, json) {
                                           sortedList[json.sortOrder] = json;
                                        });
                                    } else {
                                        // These are products since they do not have a sort order.
                                        sortedList = array;
                                    }
                                } else {
                                    // These are just products
                                    sortedList = array;
                                };

                                $.each(sortedList, function(i, json) {
                                    if (json) {

										// Put .product on any item that is a product.
										if (json.id.substr(0,4) == "prod") {
											var li = $('<li class="product">');
										} else {
											var li = $('<li>');
										}

                                        var url = ['/consumer', json.url, '?id=', json.id].pack();
                                        var displayName = (json.navName) ? json.navName : json.displayName;
                                        var a = $(['<a href="', url, '" id="', ['category-', json.id].pack(), '">', displayName, '</a>'].pack());
                                        li.append(a);
                                        ul.append(li);
                                    }

                                });
                                listItem.append(ul);

                                ul.slideDown(50, function() {
                                    $(this).addClass('expanded');
                                    reposition();
                                });

                                listen(ul);
                            }
                        });
                    } else {
                        if (product_finder[0].target) {
                            anchor[0].href = [anchor[0].href, '#', product_finder[0].target].pack();
                        }
                        return true;
                    }
                    return followLink;
                });
            } catch(ex) {
                alert('exception: ' + ex);
            }
        };


        // Initial step: listen for clicks on the first link
        ProductFinder = function() {
            var initialized = false;
            return {
                find: function(o) {


                    initialized = true;
                    var options = o || {
                        openRight: true,
                        openLeft: false
                    };
                    var finders = $('.product-finder-box .product-finder');
                    finders.each(function() {
                        var product_finder = $(this);
                        product_finder.data("baseline", product_finder.offset().top + product_finder.height());
                        

                        if (product_finder.hasClass('openLeft')) {
                            options.openRight = false;
                            options.openLeft = true;
                        }
                        if (product_finder.hasClass('openRight')) {
                            options.openRight = true;
                            options.openLeft = false;
                        }
                        if (product_finder.hasClass('product-specs')) {
                            product_finder[0].target = 'product-specs';
                        }

                        if (product_finder.length > 0 && !product_finder.hasClass('initialized')) {

                            product_finder.parents('.product-finder-box:first').height(product_finder.height() +2);
                            product_finder.css({
                                position: 'absolute',
                                bottom: '0px',
                                right: '0px'
                            })[0].clicked = false;
                            product_finder.data('originalWidth', product_finder.width());
                            product_finder.data('originalLeft', product_finder.offset().left);
                            product_finder.addClass('initialized');
                        }
                        product_finder.data('locked', false);
                        var finder = function() {
                            if (product_finder.data('locked')) {
                                return false;
                            }
                            product_finder.data('locked', true);
                            try {
                                var anchor = $(this);
                                var pfinder = $(this).parents('.product-finder:first');

                                anchor.siblings('ul').remove();
                                var listItem = anchor.parent(':first');
                                
								//LOKVIK 1464 - Needed for the Support Page Filtering
                   				 var filterByDocs = product_finder.find('a:first').attr("id");
                               
                                $.get(Urls.get('finder'), {docFilter: filterByDocs}, function(data) {
                                    var array = JSON.parse(data);
                                    var ul = $('<ul class="finder-tier-1 finder-tier-1-closed">').css({display: 'none'});
                                    var sortedList = [];
                                    // Re-order the array since the original list on the server didn't take advantage of the automatic
                                    // sorting provided by a list
                                    $.each(array, function(i, json) {
                                        sortedList[json.sortOrder] = json;
                                    });
                                    $.each(sortedList, function(i, json) {
                                        if (json) {
                                            var li = $('<li>');
                                            var displayName = (json.navName) ? json.navName : json.displayName;
                                            var url = ['/consumer', json.url, '?id=', json.id, '&depth=1'].pack();
                                            var a = $(['<a href="', url, '" id="', ['category-', json.id].pack(), '" class="', json.children, '">', displayName, '</a>'].pack());
                                            li.append(a);
                                            ul.append(li);
                                        }
                                    });
                                    listItem.append(ul);

                                    var width = pfinder.width() * 1.5;
                                    var left = width - pfinder.width(); // 10 = 5px padding on both sides

                                    if (options.openRight && !options.openLeft) {
                                        left = 0;
                                    }

                                    pfinder.animate({
                                        width: width,
                                        left: -1 * left
                                    }, 200, function() {
                                        ul.slideDown('slow', function() {

                                            $(this).addClass('expanded');
                                            pfinder.find('.product-finder-closer').slideDown('slow').click(function() {
                                                var closer = $(this);
                                                var lists = product_finder.find('ul');
                                                lists.hide();
                                                closer.hide();
                                                anchor.show();
                                                pfinder.css({
                                                    bottom: 0,
                                                    width: pfinder.data('originalWidth'),
                                                    left: 0

                                                });
                                            });
                                        });
                                    });


                                    anchor.hide();
                                    listen(ul);
                                    product_finder.data('locked', false);
                                    return false;
                                });
                                return false;
                            } catch(e) {
                                Log.info(e);
                            } finally {
                                return false;
                            }
                        };
                        product_finder.find('a:first').click(finder);

                    });


                }
            };
        }();
        ProductFinder.find();
    });
})(jQuery);