// @codekit-prepend "gui.js"

(function($) {

MaterioSearchApiAjax = function(){
  var _isloadingresults = false;
  var _$content = $('#content');
      // TODO:  define $content by module settings  
  /**
  * init()
  */
  function init(){
    //trace('init MaterioSearchApiAjax');

    initSearchAjax();
    initViewMode();
  };

  /**
  * searchAjax
  */
  function initSearchAjax(){
    // trace('initSearchAjax');

    $('#materio-search-api-search-form').bind('submit', function(event) {
      // trace('search submited', event);
      var $this = $(this);
      setTimeout(function(){
        loadResults(getSearchKeys());
      },10);
      return false;
    });

    // /!\ AUTOCOMPLETE SELECT EVENT need a patch http://drupal.org/node/365241#comment-5374686
    $("#edit-searchfield")
      .bind('autocompleteSelect', function(event) {
        $(this).parents('.form').trigger('submit');
      })
      .bind('focus', function(event){
        $(this).select();
      });

    $(document)
      .bind('init-scroller-pager', onInitScrollerPager)
      .bind('load-scroller-pager', onLoadScrollerPager)
      .bind('view-mode-changed', onViewModeChanged)
      .bind('history-state-change', onHistoryStateChange);
    
    // trigger updated event for direct html loading
    if( isActuality() || isExplore() ){
      setTimeout(function(){
        //trace('MaterioSearchApiAjax :: initSearchAjax :: triggering resultschanged')
        $.event.trigger({
          type : 'resultschanged',
          container : isActuality() ? '#content .actuality-items' : '#content .search-results'
        });  
      }, 10);
    }
  };
  
  function getSearchKeys(){
    return $('#materio-search-api-search-form').find('input[name*="searchfield"]').val();
  };

  function loadResults(keys){
    trace('keys', keys);
    if(keys !== undefined && keys !== ''  && keys.length >= 2){
      keys = keys.replace('/', ' ');

      var types = {}, stringTypes = [];
      $('#edit-bundles-filter', '#materio-search-api-search-form').find('input[type*="checkbox"]').each(function(i){
        $this = $(this);
        if ( $this.attr('checked') )
          stringTypes.push($this.val());
        types[$this.val()] = $this.attr('checked');
      });
      //trace('types', types);


      if(!_isloadingresults){
        $.event.trigger('loading-content');
        _isloadingresults = true;
        $('#materio-search-api-search-form').addClass('loading');
        // trace('window.location.href',window.location.href);
        // TODO:  record ajax path in a variable from materio_search_api_ajax_init
        $.getJSON(Drupal.settings.basePath+Drupal.settings.pathPrefix+'materio_search_api_ajax/search/', 
          {'types':types,'current_path':document.location.href, keys:keys},
          function(json){
            //trace('json', json);
            
            // google analytics
            $.event.trigger({
              type : "record-stat",
              categorie : 'Search',
              action : keys,
              label : 'filters : '+ stringTypes.join(' ,'),
              value : json.count
            });

            if(json.redirect){
              window.location = json.redirect;
            }else{
              $.event.trigger('loaded-content');      
              _isloadingresults = false;
              $('#materio-search-api-search-form').removeClass('loading');
              changeContent(json);  
            }
            
        });
      }
    }
  };

  function loadActuality(){
    if(!_isloadingresults){
      $.event.trigger('loading-content');
      _isloadingresults = true;
      $('#materio-search-api-search-form').addClass('loading');

      var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materio_search_api_ajax/actuality';
      $.getJSON(url, 
        function(json){
          //trace('json', json);
          $.event.trigger('resultsloaded');      
          _isloadingresults = false;
          $('#materio-search-api-search-form').removeClass('loading');
          changeContent(json);
      });
    }
  };

  function changeContent(json){
    trace('MaterioSearchApiAjax changeContent | json', json);

    if(json.return){
      $.event.trigger('loaded-content');
      $('.inner-content',_$content).html(json.return).find('ul.pager').hide();
      triggerContentChanged();
    }else{
      //trace('no results');
    }

    $.event.trigger({
      type : 'new-history-page',
      path : Drupal.settings.basePath + Drupal.settings.pathPrefix + json.path,
      title : json.title,
      content : json.return
    });
    
    for (language in Drupal.settings.materio_search_api_ajax.languages) {
      var l = Drupal.settings.materio_search_api_ajax.languages[language];
      $('#block-locale-language li.'+language+' a').attr('href', Drupal.settings.basePath + l.prefix+'/' + json.search_path + '/' + json.keys)        
    };
  };

  function triggerContentChanged(){
    //trace('MaterioSearchApiAjax :: triggerContentChanged');
    $.event.trigger({
      type : 'resultschanged',
      container : '#content .search-results, #content .actuality-items'
    });
  };

  function onInitScrollerPager(event){
    if(isActuality() || isExplore())
      event.pager.hide();
  };

  function onLoadScrollerPager(event){
    if(!_isloadingresults){
      if (isExplore())
        loadNextResultsPage(event.href);

      if(isActuality())
        loadNextActualityPage(event.href);
    }
  };

  function loadNextResultsPage(href){
    // trace('loadNextResultsPage');
    var keys = href.match(/explore\/([^\/|\?]+)/);
    var page = href.match(/\?page=([0-9]+)/);
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materio_search_api_ajax/search/'+page[1];
    
    loadNextPage(url, keys[1], $('.materiobase-results', _$content), '.search-results');
  };

  function loadNextActualityPage(href){
    // trace('loadNextActualityPage');
    var page = href.match(/\?page=([0-9]+)/);
    var url = Drupal.settings.basePath+Drupal.settings.pathPrefix+'materio_search_api_ajax/actuality/'+page[1];

    loadNextPage(url, '', $('.materiobase-actuality', _$content), '.actuality-items');
  };

  function loadNextPage(url, keys, $container, target){
    //trace('MaterioSearchApiAjax :: loadNextPage()');
    _isloadingresults = true;
    $container.addClass('loading');
    $.getJSON(url, {'keys':keys}, function(json){
      //trace('json', json);
      $container.removeClass('loading');
      addNextpage(json, target);
      // addNextpageItemByItem($(json.return), target);
    });
  };

  function addNextpage(json, container_class){
    var $newcontent = $(json.return),
        $newitems = $(container_class, $newcontent).children('article'), //.addClass('just-added'),
        $newpager = $('ul.pager', $newcontent);

    $(container_class, _$content).append($newitems);
    $('ul.pager', _$content).replaceWith($newpager.hide());

    // TODO: animation, this should be on theme side
    $(container_class, _$content).children('.just-added').each(function(i){
      var $this = $(this);
      setTimeout(function(){
        $this.removeClass('just-added');
      }, 150*i);
    });

    $.event.trigger({
      type : 'resultscompleted',
      container : $(container_class, _$content)
    });
    _isloadingresults = false;
  };

  // TEST not used 
  function addNextpageItemByItem($newcontent, container_class){
    //trace('MaterioSearchApiAjax :: addNextpageItemByItem()');
    $('ul.pager', _$content).remove();
    $(container_class, _$content).append($(container_class, $newcontent).children('article').eq(0));

    if($(container_class, $newcontent).children('article').length){
      setTimeout(function(){
        addNextpageItemByItem($newcontent, container_class);
      }, 200);
    }else{
      _isloadingresults = false;
      $('ul.pager', _$content).replaceWith($('ul.pager', $newcontent).hide());
      $.event.trigger({
        type : 'resultscompleted',
        container : $(container_class, _$content)
      });  
    }
  };  

  /**
  * viewmode
  */
  function initViewMode(){
    $('.viewmode-link').click(function(event){
      event.preventDefault();
      
      if(!$(this).is('.active'))
        changeViewMode($(this).attr('rel'), $(this));

      return false;
    });
  };

  function changeViewMode(vm, $btn){
    if(!_isloadingresults){
      _isloadingresults = true;
      $.getJSON(Drupal.settings.basePath+'materio_search_api_ajax/viewmode/change/'+vm, function(json){
        //trace('viewmode json', json);
      _isloadingresults = false;
        if (json.statut == "saved"){
          
          // google analytics
          $.event.trigger({
            type : "record-stat",
            categorie : 'Viewmode',
            action : vm,
            label : isActuality() ? 'Actualities' : 'Search results'
          });

          $.event.trigger('view-mode-changed');
          $('.viewmode-link, .viewmode-link i').removeClass('active');
          $btn.addClass('active').find('i').addClass('active');
        }
          
      });
    }
  };

  function onViewModeChanged(event){
    if (isExplore())
      loadResults(getSearchKeys());

    if(isActuality())
      loadActuality();
  };

  /**
  * history
  */
  function onHistoryStateChange(event){
    if(isExplore() || isActuality())
      triggerContentChanged();
    // TODO:  pushstate trogger state change, so we have a retriggerring here on loading new results … how to avoid this  
  };

  /**
  * helpers
  */
  function isExplore(){
     return $('.search-results', '#content').length;
  };

  function isActuality(){
    return $('.actuality-items', '#content').length;
  };
    
  init();
};

  var materiosearchapiajax = new MaterioSearchApiAjax();
  
})(jQuery);