// $Id: front_ajax_list.js,v 1.11 2009/12/27 3:29:00 jodarove Exp $
// @todo: should be optimized!!!

var ajaxlist = {
  // Hide views' exposed widgets, convert into other types
  init: function() {
    $('div.view-dom-id-1:first').remove();
    if (!$.browser.msie || $.browser.version >= 8) {
      $('body.front #list-category-select').selectbox({debug: false});
    }
    
    // hide any views exposed forms
    $(".views-exposed-form").hide();
    
    // Add onclick event to links
    $("#list-tabs a").click( function(evt) {
      evt.preventDefault();
      ajaxlist.handleClickExclusive("#list-tabs", this);
    });
    $("#list-sort a").click( function(evt) {
      evt.preventDefault();
      ajaxlist.handleClickExclusive("#list-sort", this);
    });
    
    $("#list-category-select").change(function() {
      ajaxlist.doQuery(this);
    });
    /*
    $("#list-category-select").change( function() {
      ajaxlist.doQuery(this);
    });
    */
    /*
    // Add show/hide behavior to category header
    $("#list-category .header").click( function () {
      var element = this;
      $("#list-category ul").slideToggle("normal", function() {
        $(element).toggleClass("opened");
      });
    });
    $("#list-category a").click( function() {
      //ajaxlist.handleClickMultiple("#list-category", this);
      ajaxlist.handleClickExclusive("#list-category", this);
    });
    $("#list-category ul").hide();
    */
    
    // Run query to populate listing
    ajaxlist.doQuery();
  },
  handleClickExclusive: function(container, element) {
    // Must remove other elements first
    if (container == "#list-tabs") {
      // The All Tab
      if ($(element).attr("rel") == '#') {
        $("#maincolumn").removeClass("top-left-round-corner"); //("background", "#FFFFFF url(images/wrap-top-left.png) no-repeat scroll left top");
      } else {
        $("#maincolumn").addClass("top-left-round-corner");
      }
    };
    
    $(container + " a").each( function() {
      $(this).removeClass("active");
      $(this).parent("li").removeClass("active");
    });
    $(element).addClass("active");
    $(element).parent("li").addClass("active");
    ajaxlist.doQuery(element);
  },
  
  /**
   * This function handles multiple-choice elements along with an "All"
   * option that will automatically get selected when all other items are
   * unselected
   */
  handleClickMultiple: function(container, element) {
    // Is the clicked element the "all" option?
    if ($(element).attr("class").indexOf("all")>-1) {
      // Clear all elements
      $(container + " a").each(function () {
        $(this).removeClass("active");
      });
      $(element).addClass("active");
      $(container + " .header").html("Categories: All");
    } else {    
      $(element).toggleClass("active");
      // Check if no remaining links are active. If so, set "All" to active.
      var count = 0;
      $(container + " a.active").each( function() {
        if ($(this).attr("rel") != "#") {
          count++;
        }
      });
      if (count == 0) {
        $(container + " a.all").addClass("active");
        $(container + " .header").html("Categories: All");
      } else {
        $(container + " a.all").removeClass("active");
        $(container + " .header").html("Categories: " + count);
      }
    }
    // Run the query with the new values
    ajaxlist.doQuery();
  },
  previousUrl: "",
  // Collect the current information and send out the query
  doQuery: function (throbElement) {
    // Get the tids
    var tabs = ajaxlist.getActiveValuesFromDiv("#list-tabs");
    var sort = ajaxlist.getActiveValuesFromDiv("#list-sort");
    
    //var category = ajaxlist.getActiveValuesFromDiv("#list-category");
    var category = $("#list-category-select").val();
    var vArgs = "";
    
    if (tabs.length > 0) { vArgs = tabs; } else { vArgs = 'all'; };
    
    if (category.length > 0) {
      vArgs = vArgs+"/"+category;
    }
    
    
    var ajax_path = Drupal.settings.views.ajax_path;
    if (ajax_path.constructor.toString().indexOf("Array") != -1) {
      ajax_path = ajax_path[0];
    };
    
    var jsVurl = ajax_path + "?js=1&page=0&view_args=" + vArgs +"&view_name=" + sort + "&view_display_id=default&view_dom_id=1";
    var url = "/" + sort + "/" + tabs + "/" + category + "?page=" + ajaxlist.currentpage;
        
    // Special case, favorites
    if (tabs == "Favorites") {
      url = "/bookmarks" + "?page=" + ajaxlist.currentpage;
      jsVurl = ajax_path + "?js=1&page=0&view_args=&view_name=flag_bookmarks&view_display_id=default&view_dom_id=1";
      // Hide sorter
      $("#list-sort").hide();
      $("#list-category-select-container").hide();
    } else {
      $("#list-sort").show();
      $("#list-category-select-container").show();
    }
    
    var srcContainer = 'div.view-content';
    var destContainer = '#list-results';
    if (ajaxlist.previousUrl != url) {
      //$("#debugdiv").html(url);
      //$(destContainer).html("<img src='/sites/all/modules/popups/ajax-loader.gif'>");
      
      // Drupal.popups.addOverlay();
      // Drupal.popups.addLoading();
      
      Drupal.Views.Ajax.blockView('.view-dom-id-1', 200);
      
      $("#pager").html("");
      //$(throbElement).addClass("ubercart-throbber");
	  //$('#update-li-icons').addClass("ubercart-throbber");
	  $('#update-li-icons').addClass("ubercart-throbber-views");
      $.ajax({
        type: 'GET',
        url: jsVurl,
        //data: '',
        success: function(response){
          // Main list
        
        /* como el mago! */
        
        var view = '.view-dom-id-1';
        if (response.__callbacks) {
          $.each(response.__callbacks, function(i, callback) {
            eval(callback)(view, response);
          });
          // $('.views-throbbing', object).remove();
        }
        
        Drupal.Views.Ajax.unBlockView('.view-dom-id-1');
        
        
        
        
        
         /* ajaxlist.updateElementsFromResponse(response, srcContainer, destContainer);

		      ajaxlist.updateElementsFromResponse(response, "div.view-empty", "div#list-empty");
          
          // Pager element
          // ajaxlist.updateElementsFromResponse(response, ".page-views .item-list", "#pager");
		      ajaxlist.updateElementsFromResponse(response, "div.page-views div.item-list:not(:first)", "#pager");
		      
		      // ajaxlist.updateElementsFromResponse(response, ".page-views ul.pager", "#pager", ":parent(div.item-list)");
		      // ajaxlist.updateElementsFromResponse(response, "div.page-views ul.pager", "#pager", ":parent(div.item-list)");
          // Activate pager elements
          ajaxlist.attachPagerBehavior();
          ajaxlist.currentpage = 0;
          Drupal.popups.removeOverlay();
          
          //$(throbElement).removeClass("ubercart-throbber");
			//$('#update-li-icons').removeClass("ubercart-throbber");
			$('#update-li-icons').removeClass("ubercart-throbber-views");

          // $(destContainer).fadeTo('fast', 1);
          //$(destContainer).removeClass("ubercart-throbber");
          */
          // Drupal.attachBehaviors();
          // Drupal.popups.removeOverlay();
          // Drupal.popups.removeLoading();
        },
        failure : function () {
          Drupal.popups.removeOverlay();
          // ERROR !!! 
        },
        dataType: 'json'
      });
      // $(destContainer).fadeTo('fast', 0.2);
    }
    ajaxlist.previousUrl = url;
  },
  currentpage: 0,
  attachPagerBehavior: function () {
    // If pager was recieved, rewrite it to be Ajax-y
    //if (pager_html) {
    $("#pager").find('a').each(function () {
      var reg = /.*page=([0-9]+).*/;
      var page = reg.exec(this.href);
      var pagenum = 0;
      if (page) {
        pagenum = page[1];
      }
      $(this).click(function () {
        $(this).addClass('ubercart-throbber');
        ajaxlist.currentpage = pagenum;
        ajaxlist.doQuery(this);
        //alert('page = ' + this.href);
        return false;
      });
    });
  },
  /**
   * Recieves an HTML ajax response, extracts an element from it and updates the
   * same element in the current page.
   */ 
  updateElementsFromResponse : function(response, srcElementId, destElementId, queryFilter) {
    if (queryFilter) {
      var htmlFragment = $(srcElementId, response).filter(queryFilter).html();
    } else {
      var htmlFragment = $(srcElementId, response).html();
    }
    if (htmlFragment) {
      $(destElementId).html(htmlFragment);
    } else {
      //alert("Internal error! Element id " + elementId + " not found. Response = " + response);
      $(destElementId).html("");
    }
    //$(destElementId).fadeTo('fast', 1);
  },
  // Gathers the href values from id's children links that have the "active" class
  getActiveValuesFromDiv: function(id) {
    var values = "";
    $(id + " a.active").each( function () {
      var tmp = $(this).attr("rel");
      if (values != "") values += "%2B";
      values += tmp.substr(1);
    });
    // Strip off leading "#" char
    return values;
  }
};

Drupal.behaviors.ajaxListPagers = function () {
  /* everithing cannot be perfect, cheat the wizzard (front view must not use ajax!) */
  
  var ajax_path = Drupal.settings.views.ajax_path;
  // If there are multiple views this might've ended up showing up multiple times.
  if (ajax_path.constructor.toString().indexOf("Array") != -1) {
    ajax_path = ajax_path[0];
  };
  
  $(".view-dom-id-1").filter(':not(.views-processed)')
      // Don't attach to nested views. Doing so would attach multiple behaviors
      // to a given element.
      .filter(function() {
        // If there is at least one parent with a view class, this view
        // is nested (e.g., an attachment). Bail.
        return !$(this).parents('.view').size();
      })
      .each(function() {
        // Set a reference that will work in subsequent calls.
        var target = this;
        $(this)
          .addClass('views-processed')
          // Process pager, tablesort, and attachment summary links.
          .find('ul.pager > li > a, th.views-field a, .attachment .views-summary a')
          .each(function () {
            var viewData = { 'js': 1 };
            // Construct an object using the settings defaults and then overriding
            // with data specific to the link.
            $.extend(
              viewData,
              Drupal.Views.parseQueryString($(this).attr('href'))
            );
            $(this).click(function () {
              $(this).parent().wrap('<span class="views-throbbing">&nbsp</span>');
              $(this).trigger("views-before-ajax", [ {
                tagetElement : target,
                requestData : viewData
              }]);
              
              var $this = this;
              $.ajax({
                url: ajax_path,
                type: 'GET',
                data: viewData,
                success: function(response) {
                
                $($this).trigger("views-after-ajax", [ 
                                                      {
                                                        tagetElement : target, 
                                                        responseData : response, 
                                                        status : 'ok' 
                                                      }
                                                    ]);
                  $(this).removeClass('views-throbbing');
                  // Scroll to the top of the view. This will allow users
                  // to browse newly loaded content after e.g. clicking a pager
                  // link.
                  var offset = $('#mainbar').offset();
                  // Only scroll upward
                  if (offset.top - 10 < $(window).scrollTop()) {
                    $('html,body').animate({scrollTop: (offset.top - 10)}, 500);
                  }
                  // Call all callbacks.
                  if (response.__callbacks) {
                    $.each(response.__callbacks, function(i, callback) {
                      eval(callback)(target, response);
                    });
                  }
                },
                error: function() { $(this).removeClass('views-throbbing'); alert(Drupal.t("An error occurred at @path.", {'@path': ajax_path})); },
                dataType: 'json'
              });

              return false;
            });
          }); // .each function () {
    }); // $view.filter().each
}

// Initialize
$(document).ready( function () {
  ajaxlist.init();
});