/**
 * Compare.js - Compare functionality
 * 
 * @param {Mixed} form Selector or reference of the compare form
 */
function CompareForm(form) {
	this.form = $(form);
	this.defaults = null;
	this.init();
};

CompareForm.prototype = {
	/**
	 * Initialize
	 */
	init: function() {
		if(this.form.length) {
			this.defaults = {
				tableSelector: '#compare-table'
			};
			
			this.form.find('button').hide();
			this.addEventHandlers();
		}
	},
	
	/**
	 * Add event handlers
	 */
	addEventHandlers: function() {
		var self = this;
		
		this.form.find('select').change(function() {
			self.productSelectChangeHandler(this);
		});
	},
	
	/**
	 * When a product select fires onchange
	 * 
	 * @param {Object} el The HTMLSelectElement
	 */
	productSelectChangeHandler: function(el) {
		var self = this;
		
		$.ajax({
			url: self.form.action,
			cache: false,
			dataType: 'json',
			type: 'POST',
			data: self.form.serialize(),
			success: function(data) {
				self.updateView(data);
			}
		});
	},
	
	/**
	 * Update view
	 * 
	 * @param {Object} data The updated data in JSON format
	 */
	updateView: function(data) {
		/**
		 * JSON:
		 * 
			{
				"tableHtml": "Html for #compare-table"
			}
		 */
		
		$(this.defaults.tableSelector).replaceWith(data.tableHtml);
		$(this.defaults.tableSelector).effect('highlight', {}, 750);
	}
};

/**
 * Create compare form instance
 */
$(document).ready(function() {
	var cmpf = new CompareForm('#compare-form');
});
