﻿(function($){

var panel, form, detail, queue, item_total, options;

var defaults = {
    image_base_href: "[IMGBASE]?wid=60&amp;hei=40&amp;fmt=jpeg",
    panel_queue_item_base: '<li id="[ID]"><img width="60" height="40" src="[IMG_SRC]"><a title="Remove This Item">[-] Remove</a></li>'
};

// Run on the panel containing the list of currently compared objects
// Provide both the form containing other items to compare,
// as well as the detail panel to popup details.
// The form should provide the URL for the ajax call to update the
// server when the comparison list changes.
// The detail panel should have a second url listed (href attribute)
// which will have a GET call with the current list as a query parameter.
$.compare = function(_panel, _form, _detail, _options) {
  // These two would be simple but IE won't let us read cookies in JS reliably :(
  var getCookie = function() {
    // Instead of getting the cookie we will just get the list of items and construct
    // what the cookie should look like
    return "," +
      $.makeArray(queue.find("li").map(function() { return this.id.replace("queue_item_",""); })).join(",");
  }
  this.getCookie = getCookie; // public
  var setCookie = function() {
    // Instead of being told what to do to make the new cookie, let's just use getCookie()
    $.cookie("compare", getCookie(), {path:location.pathname});
  }

  var form_change = function(e) {
    var target = e.target; // the thing that changed (checkbox)
    var id = target.id.replace("compare_", "");
    if( target.checked ) {
      add_item(id);
    } else {
      remove_item(id);
    }
  }
  
  var get_image_base = function(id) {
    var base_image = $('#'+id+' a img')[0];
    if( !base_image ) return "";
    var match = base_image.src.match(/([^?]*)\??/);
    return match && match[1] || "";
  }

  var add_item = function(id) {
    var image_base = get_image_base(id);
    var image_href = options.image_base_href.replace(/\[IMGBASE\]/g, image_base);
    var queue_item_id = "queue_item_"+id;
    var queue_item = options.panel_queue_item_base.
        replace(/\[IMG_SRC\]/g, image_href).
        replace(/\[ID\]/g, queue_item_id);
    queue.append(queue_item);

    // ensure the item is checked
    var compare_item_id = "compare_"+id;
    $('#'+compare_item_id).attr('checked',true);
    
    update();
  }

  var remove_item = function(id) {
    var queue_item_id = "queue_item_"+id;
    queue.find("#"+queue_item_id).remove();
    
    // ensure the item is unchecked
    var compare_item_id = "compare_"+id;
    $('#'+compare_item_id).attr('checked',false);
    
    update();
  }

  var remove_item_clicked = function(e) {
    var li = $(e.target).closest("li").get(0);
    var id = li.id.replace("queue_item_", "");
    remove_item(id);
    return false;
  }

  var remove_all_clicked = function(e) {
    queue.find('li').remove();
    form.find('input[type=checkbox]').attr('checked',false);
    update();
    return false;
  }

  var update = function() {
    setCookie();

    var i = queue.find('li').length;
    if( i == 1 ) {
        item_total.html("1 item");
    } else {
        item_total.html(i + " items");
    }
    if( i == 0 ) {
        panel.fadeOut(200);
    } else {
        panel.fadeIn(200);
    }

    options.onChange();
  }
  this.update = update; // make this public

  panel = _panel;
  form = _form;
  detail = _detail;
  queue = $(panel).find("#compare_queue");
  item_total = $(panel).find('h1');
    
  options = $.extend( {}, defaults, _options );
  
  // Would prefer to just use form's change event, but IE doesn't listen
  form.find("input[type=checkbox]").live("click", form_change);
  queue.find("a").live("click", remove_item_clicked);
  queue.find("li").each(function(i, li) {
    var id = $(li).attr('id').replace("queue_item_","compare_");
    $("#"+id).attr('checked',true);
  });
    
  panel.find("#remove_all").bind("click", remove_all_clicked);
  
  function kill() {
    form.find("input[type=checkbox]").die("click", form_change);
    queue.find("a").die("click", remove_item_clicked);
  }
  this.kill = kill; // make this public

  return this;    
};


$(function() {
  var compare, slider;
  function bindFilterEvents(responseText, textStatus, request) {
    if( textStatus == "error" ) {
        window.error = { text: responseText, status: textStatus, request: request };
        $.spinner.error();
        return;
    }
  
    $("select").enhanceSelect();

	$("a.dropdown_toggle").click(function() {
		$(this).closest('form')[0].reset();
		if( $(this).parent().parent('.activedropdown').length == 0){
			$(".multiSelect > fieldset.open").removeClass('open');
		}
	});
	
	$(".multiSelect .bttn_dropdown").click(function() {
		var fieldset = $(this).parent('.multiSelect > fieldset');
		$(this).closest('form')[0].reset();
		if( fieldset.hasClass('open')) {
			fieldset.removeClass('open');
		} else {
			$(".multiSelect > fieldset.open").removeClass('open');
			$(".activedropdown a.dropdown_toggle").trigger("click");
			fieldset.addClass('open');
		}
		return false;
	});

	$("a#view_compare_chart").fancybox({
		'overlayShow'			: true,
		'zoomOpacity'			: true,
		'frameWidth'			: 880,
		'frameHeight'			: 540,
		'padding'					: 0
	});
  
    if( $("#compare_queue")[0] ) {
      function updateLink() {
        var productList = compare.getCookie();
        if( productList.length == 1 ) {
          productList = "";
        } else {
          productList = productList.substring(1);
        }
        $("a#view_compare_chart").attr('href', baseHref + "&compare=" + productList );
      }
      function updateLinkAndSlider() {
        updateLink();
        slider.update();
      }
      function updateLinkSliderAndCompare() {
        updateLink();
        slider.update();
        compare.update();
      }

      $("#compare_queue").sortable({axis: 'x', update: updateLinkSliderAndCompare});
      compare = $.compare($('#compare_dock_wrapper'), $('#productListWrapper'), null, {onChange: updateLinkAndSlider});
      slider = $.slider( $("#compare_queue"), $("#arrow_left"), $("#arrow_right"), $("#compare_queue_mask"), { slideMethod: "scroll" });

      var baseHref = $("a#view_compare_chart").attr('href');

      updateLinkSliderAndCompare();
    }
    
    $("#product_filters input[type=text]").change(function() {
      $(this.form).find('select').each(function() {
        this.selectedIndex = 0;
      });
      location.hash = $(this.form).serialize();
      return false;
    });
    $("#product_filters select").change(function() {
      location.hash = $(this.form).serialize();
      return false;
    });
    $("#product_filters .multiSelect a.submit").click(function() {
      var fieldset = $(this).parent('.multiSelect > fieldset');
      var form = $(this).parents('form');
      fieldset.removeClass('open');
      location.hash = form.serialize();
      return false;
    });
    $(".pagination a").click(function() {
      var hash = /^.*\?(.*)/.exec( this.href )[1];
      location.hash = hash;
      return false;
    });
  }
  
  bindFilterEvents();
  
  function updateFilterResults(hash) {
    if( !hash || hash == "" ) {
      hash = location.search && location.search.substring(1) || "";
    }
    var values = "?ajax=1&" + hash;
    if( compare ) compare.kill();
    var base = location.pathname.replace(/ /g, "%20");
    $.spinner.show();
    $("#content").load(
        base + values,
        null,
        bindFilterEvents );
  }
  

  $(window).history(function(e, history) {
    if(!history) return;
    updateFilterResults( history.value );
  });
  if( location.hash ) {
    updateFilterResults( location.hash.substring(1) );
  }
  
})



})(jQuery);
