/**
 * Avalanche for Magento 1.8+
 * Designed by Fast Division (http://fastdivision.com)
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the EULA
 * that is bundled with this package in the file license.txt.
 * It is also available through the world-wide-web at this URL:
 * http://fastdivision.com/legal/license.txt
 *
 * @author     Fast Division
 * @version    1.5.0
 * @copyright  Copyright 2013 Fast Division
 * @license    http://fastdivision.com/legal/license.txt
 */
(function($) {
    var currentPage = 1;
    var currentHash = '';
    
    $.fn.catalogAjax = function(l) {
        var plugin = {
          init: function(d) {
              if($('#last-page').data('config')) {
                  return;
              }
              
              config = {
                  gridColumn: '#results',
                  catalogPageSelector: '.catalog-page',
                  productlinkselector: '.item a',
                  contentheightselector: 'body',
                  onPageLoaded: null,
                  googleAnalytics: true,
                  showMoreTemplate: '<a class="show-more-link" href="#" data-nextpage="2">' + $('#show-more-loader').data('translate') + '</a>'
              };
              
              // On hash updates...
              $(window).bind('hashchange', function(e) {
                  if(currentHash !== window.location.hash) {
                      $(config.gridColumn).catalogAjax('getPage', true);
                      currentHash = window.location.hash;
                  }
              });
              
              // Get page on init...
              if($.deparam.fragment()['page']) {
                  $(config.gridColumn).catalogAjax('getPage', false);
              } else {
                currentPage = 1;
              }

              // Hide "Show More" if needed
              if($('#last-page').data('number') <= currentPage)
                    $('.show-more-link').hide();

              if(d) {
                  $.extend(config, d);
              }
              
              // Assign configuration data to #last-page div
              $("#last-page").data('config', config);
              
              // Special JS to call when a new page is loaded
              if(config.onPageLoaded) {
                  $('body').bind('productsloaded', config.onPageLoaded);
              }
              
              // Google Analytics
              if(config.googleAnalytics) {
                  $('body').bind('productsloaded', function(a, b, c) {
                      //_gaq.push(['_trackPageview', c.url]);
                      //_gaq.push(['_trackEvent', 'infinitescroll', 'loadpage', c.url]);
                      //_gaq.push(['_trackEvent', 'infinitescroll', 'numberLoaded', 'page-' + (c.number < 10 ? '0' : '') + c.number])
                  });
              }
              
              // Hide the pager
              $('.pager').each(function() {
                if(!$(this).hasClass('pager-visible')) {
                  $('.pager').hide();
                }
              });

              var catalogPageSet = null;
              catalogPageSet = $(document.createElement($(config.catalogPageSelector).get(0).nodeName))

              var showMoreLink = $(config.showMoreTemplate);
              showMoreLink.on('click', function(e) {
                  if($.deparam.fragment()['page']) {
                    currentPage++;
                  } else {
                    if($.deparam.querystring()['p'])
                      currentPage = parseInt($.deparam.querystring()['p']) + 1;
                    else
                      currentPage = 2;
                  }
                  window.location.hash = "page=" + currentPage;
                  e.preventDefault();
              });
              
              if(!$('.show-more-link').length) {
                  if($.deparam.querystring()['p'])
                    $('.catalog-page').first().attr('data-page', parseInt($.deparam.querystring()['p']));
                  else
                    $('.catalog-page').first().attr('data-page', 1);
                  catalogPageSet.append(showMoreLink);
              }

              $('.show-more-link').off('click').on('click', function(e) {
                  if($.deparam.fragment()['page']) {
                    currentPage++;
                  } else {
                    if($.deparam.querystring()['p'])
                      currentPage = parseInt($.deparam.querystring()['p']) + 1;
                    else
                      currentPage = 2;
                  }
                  window.location.hash = "page=" + currentPage;
                  e.preventDefault();
              });

              $(config.catalogPageSelector).parent().append(catalogPageSet);
              
              if($.deparam.querystring()['p']) {
                  currentPage = $.deparam.querystring()['p'];
              }
              
              // If last page, then hide show more link
              if(currentPage == $('#last-page').data('number')) {
                  showMoreLink.hide();
              }
          },

          prevPage: function(prevCurrentPage) {
            pages = $('.catalog-page').length
            for(var x = pages; x > prevCurrentPage; x--) {
              $('.catalog-page[data-page='+x+']').remove();
            }
            currentPage = prevCurrentPage;
            $('.show-more-link').removeClass('show-more-loading').html($('#show-more-loader').data('translate')).show();
            $('html, body').animate({ 'scrollTop': $('.catalog-page[data-page="'+prevCurrentPage+'"]').offset().top }, 500);
          },
          
          nextPage: function(rebound, reboundCurrentPage) {
              if(!rebound) {
                var nextUrl = $.param.querystring(document.location.href, 'p=' + currentPage);
              } else {
                var nextUrl = $.param.querystring(document.location.href, 'p=' + reboundCurrentPage);
              }
              
              $('.show-more-link').addClass('show-more-loading').html('<img src="' + $('#show-more-loader').data('src') + '"/>');
               
              $.ajax({
                   url: nextUrl,
                   success: function(data) {
                       var content = $(data).find('.catalog-page');

                       if(!rebound) {
                          $('.catalog-page[data-page="'+(currentPage-1)+'"]').after(content);
                          $('.catalog-page').last().attr('data-page', currentPage);
                       } else {
                          $('.catalog-page[data-page="'+(reboundCurrentPage-1)+'"]').after(content);
                          $('.catalog-page').last().attr('data-page', reboundCurrentPage);
                       }
                       
                       // If last page, then hide show more link
                       if(currentPage == $('#last-page').data('number')) {
                           $('.show-more-link').hide();
                       } else {
                           $('.show-more-link').removeClass('show-more-loading').html($('#show-more-loader').data('translate'));
                       }

                       // Trigger page loaded on success function
                       $('body').trigger('productsloaded');

                       if(!rebound)
                         $('html, body').animate({ 'scrollTop': $('.catalog-page[data-page='+currentPage+']').offset().top }, 500);
                       else
                         $('html, body').animate({ 'scrollTop': $('.catalog-page[data-page='+reboundCurrentPage+']').offset().top }, 500);
                   },
                   headers: {
                       "X_REQUESTED_WITH": "browser",
                       "X-Requested-With": "browser"
                   },
                   beforeSend: function (a, b) {
                       a.setRequestHeader("X_REQUESTED_WITH", "browser");
                       a.setRequestHeader("X-Requested-With", "browser")
                   }
               });
          },
          
          getPage: function(hashchange) {
              // If page hash available, set current page
              var catalogQuery = $.deparam.querystring();
              var catalogFragment = $.deparam.fragment();
              
              if(catalogFragment['page'] && !hashchange) {
                  currentPage = catalogFragment['page'];
              }

              // Scroll to current page if not 1
              if(currentPage !== 1 && !hashchange) {
                  // If catalog pages haven't been opened yet
                  for(var x = 2; x <= currentPage; x++) {
                      if(x <= $('#last-page').data('number')) {
                          $('#results').catalogAjax('nextPage', true, x);
                      }
                  }
              } else if(catalogFragment['page'] && hashchange) {
                if(!$('.catalog-page[data-page='+catalogFragment['page']+']').length)
                    $('#results').catalogAjax('nextPage', true, catalogFragment['page']);
                else
                    $('#results').catalogAjax('prevPage', catalogFragment['page']);
              }

              if(!catalogFragment['page'] && hashchange) {
                  plugin.resetCatalog();
              }
          },

          resetCatalog: function() {
              currentPage = 1;
              $(config.catalogPageSelector).not(':first').remove();
              $('.show-more-link').removeClass('show-more-loading').html($('#show-more-loader').data('translate')).show();
              $('html, body').animate({ 'scrollTop': $('.catalog-page:first').offset().top }, 500);
          },
        };
        
        if(plugin[l]) {
            return plugin[l].apply(this, Array.prototype.slice.call(arguments, 1))
        } else if(typeof l === 'object' || !l) {
            return plugin.init.apply(this, arguments)
        } else {
            $.error('Method ' + l + ' does not exist on jQuery.catalogAjax')
        }
    }
})(jQuery);