﻿(function($){
    $.urlParams = function(key){
        params = location.search.substr(1).split('&')
        paramObj = {};
        for(i = 0; i < params.length; i++){
            pair = params[i].split('=');
            paramObj[pair[0]] = pair[1];
        }
        return (key) ? paramObj[key] : paramObj;
    }
    
    // globally overridding isotope default options
    $.extend($.Isotope.prototype.options, {
        layoutMode : 'straightDown',
        containerClass: '', // current implementation does not require one.
        hiddenStyle : Modernizr.csstransforms && !$.browser.opera ? 
            { opacity : 0, scaleY : .001} : // browsers support CSS transforms, not Opera
            { opacity : 0 }, // other browsers, including Opera,
        visibleStyle : Modernizr.csstransforms && !$.browser.opera ? 
            { opacity : 1, scaleY : 1} : // browsers support CSS transforms, not Opera
            { opacity : 1 },  // other browsers, including Opera
        animationEngine : 'jquery', // disables animation in ie 6
        transformsEnabled: false, // turns off css transformations because they add serious complexity
        animationOptions: {
            duration: 800,
            queue: false
        },
        resizable: false // diables changing layout when browser resizes because it is unessessary overhead due to the pages layout.
    });
    $.Isotope.prototype.__init = $.Isotope.prototype._init
    $.extend($.Isotope.prototype, {
        forceFilter : function( $filteredAtoms ) {
            $atoms = this.$allAtoms;
            var hiddenClass    = this.options.hiddenClass,
                hiddenSelector = '.' + hiddenClass,
                $visibleAtoms  = $atoms.not( hiddenSelector ),
                $hiddenAtoms   = $filteredAtoms.filter( hiddenSelector ),
                $atomsToShow   = $hiddenAtoms;
            
            $atomsToShow = $hiddenAtoms.filter( $filteredAtoms );
            var $atomsToHide = $visibleAtoms.not( $filteredAtoms ).toggleClass( hiddenClass );
            $atomsToHide.addClass( hiddenClass );
            this.styleQueue.push({ $el: $atomsToHide, style: this.options.hiddenStyle });
        
            this.styleQueue.push({ $el: $atomsToShow, style: this.options.visibleStyle });
            $atomsToShow.removeClass( hiddenClass );
            this.$filteredAtoms = $filteredAtoms;
            this.reLayout();
        },
        reset : function(){
            this.forceFilter(this.$allAtoms);
        },
        _init : function(){
            this.__init(this.options.onInit || $.noop());
        }
    });
    $(document).ready(function(){
        if($.browser.msie && parseInt($.browser.version, 10) < 7){
            jQuery.fx.off = true;
        }
        
        // hides the <hr> in the first company in the listing if the letter list is on the page.
        if($('.letter-list').length > 0){
            $('.company-listing li:first hr').show();
        }
        
        var $companyContainer = $('.isotope');
        // initializes Company isotope widget
        $companyContainer.isotope({
            itemSelector: 'li, .product-category-description',
            animationOptions : {
                complete : function(){
                    $this = $(this);
                    if(!$this.is('.isotope-hidden')){
                        if ( $.browser.msie ){
                            this.style.removeAttribute('filter');
                        }
                    }
                }
            }
        });
        
        var $productCategoryContainer = $('#product-category-set');
        // initializes Company isotope widget
        $productCategoryContainer.isotope({
            itemSelector: 'li'
        });
        
        /* Division and product category filter elements click handler */
        $('.option-set a').click(function(event, dont_filter){
            event.preventDefault();
            $this = $(this);
            // remove the selected class from the old filter
            $this.parents('.option-set').eq(0).find('a').removeClass('current');
            // adds the selected class to the new filter
            $this.addClass('current');
        });
        
        /* Division filter element click handler */
        $('#division-set').find('a').click(function(event, dont_filter){
            var filter_selector = $(this).data('filter');
            // if division was changed to something other than all, reset category to all
            if(filter_selector != '*'){
                $productCategoryContainer.find('a[data-filter=""]').triggerHandler('click', true);
            }
            // filter product categories by the selected division
            $productCategoryContainer.isotope({ filter: filter_selector })
            
            if(dont_filter != true){
                filter_companies();
            }
        });
        
        /* Product category filter element click handler */
        $productCategoryContainer.find('a').click(function(event, dont_filter){
            var filter_selector = $(this).data('filter');
            
            if(filter_selector == '' || filter_selector == ':not(.category_description)'){
                //filter_selector = ':not(.category_description)';
                $('.letter-list, .company-listing-header').fadeIn(function(){
                    if ( $.browser.msie ){
                        this.style.removeAttribute('filter');
                    }
                })
                $('.category-descriptions, .product-category-description-header').hide();
                if($('.letter-list').length < 1){
                    $('.company-listing li:first hr').hide();
                }
            }
            else {
                $('.letter-list, .company-listing-header').hide()
                $('.category-descriptions, .product-category-description-header').show();
                if($('.letter-list').length < 1){
                    $('.company-listing li:first hr').show();
                }
            }
            showCompanyCategoryDescriptions(filter_selector);
            
            if(dont_filter != true){
                filter_companies();
            }
        });
        /* Builds an aggregated company filter selector for isotope to use */
        function filter_companies(){
            // builds a selector made up of all the data-filter attributes of currentely selected filter elements
            filter_selectors = $('.option-set .current').map(function(){
                return $(this).data('filter'); 
            }).get().join('');
            
            if(filter_selectors != ''){
                $companyContainer.isotope({filter : filter_selectors});
                
            }
        }
        /* Changes out company descriptions based on categories */
        function showCompanyCategoryDescriptions(category_selector){
            $company_summaries = $companyContainer.find('.company-summary');
            
            // if category_selector is empty use the 'all' category description
            if(category_selector == '' || category_selector == ':not(.category_description)'){
                category_selector = '.product-category-all';
            }
            
            $company_summaries.each(function(){
                var $category_summaries = $(this).children();
                    $new_desc = $category_summaries.filter(category_selector);
                
                // if company does not have a description for the selected category use the 'all' category description
                if($new_desc.length < 1){
                    $new_desc = $category_summaries.filter('.product-category-all');
                }
                
                // hide all category descriptions that arent the new one to show
                $category_summaries.not($new_desc).hide();
                $new_desc.show();
            });
        }
        /* Filters companies based on letter */
        function letter_click(event){
            event.preventDefault();
            $this = $(this);
            if(!$this.is('.disabled')){
                letter = $this.data('letter');
                
                $start_with = $('.company-listing li').filter(function(){
                    return $.trim($(this).find('h2').text()).substr(0, 1).toUpperCase() == letter;
                });
                $companyContainer.isotope('forceFilter', $start_with);
                $('.option-set a').removeClass('current');
                $('.letter-list a').removeClass('current');
                $this.addClass('current');
            }
        }
        $('.letter-list li:not(.reset) a').click(letter_click);
        
        $('.letter-list li.reset a').click(function(event){
            event.preventDefault();
            $companyContainer.isotope('reset');
            $('.letter-list a').removeClass('current');
            $('.option-set a[data-filter="*"], .option-set a[data-filter=""]').addClass('current');
        });
        
        function init_letter_list(){
            $letters = $('.letter-list li:not(.reset) a').addClass('disabled');
            $('.company-listing li h2').each(function(){
                letter = $.trim($(this).text()).substr(0, 1).toUpperCase();
                $letters.filter('[data-letter=' + letter + ']').removeClass('disabled');
            });
        }
        init_letter_list();
        
        // deep linkinking initialization
        var urlParams = $.urlParams();
        if(urlParams.division && urlParams.category){
            $('#division-set').find('a[data-filter=".division-' + urlParams.division + '"]').trigger('click', true);
            $productCategoryContainer.find('a[data-filter=".product-category-' + urlParams.category + '"]').trigger('click');
        }
        else if(urlParams.category){
            $productCategoryContainer.find('a[data-filter=".product-category-' + urlParams.category + '"]').trigger('click');
        }
    });
})(jQuery)
