/*

Shopping cart helper script

*/

// Requires Prototype
(function() {
	if ((typeof Prototype == 'undefined') || 
		(typeof Prototype.Version == 'undefined') || 
		parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]) < 1.5)
	{
		throw("SlidingCart requires the Prototype JavaScript framework >= 1.5.0");
	}
})();

var SlidingCart = Class.create();
SlidingCart.prototype = {
	element: null,
	images: null,
	
	initialize: function(id, options)
	{
		this.element = $(id);
		this.images = $$('#' + id + ' table img');
		this.images.each(function(img)
		{
			img._factor = img.height/img.width;
		});
		
		this.options = Object.extend({
			maxImageSize: 25,
			closeSlidingCart: "CloseSlidingCart",
			openSlidingCart: "OpenSlidingCart"
		}, options || {});
		
		this.setMaxImageSize(this.options.maxImageSize);
		
		// initialize open/close state
		var isOpen = Cookie.get("SlideCartControl" + id);
		if (isOpen == "true")
		{
			this.open(false);
		}
		else
		{
			this.close(false);
		}
	},

	setMaxImageSize: function(max)
	{
		this.images.each(function(img)
		{
			var w = (img._factor < 1) ? max : max * img._factor;
			var h = (img._factor > 1) ? max : max * img._factor;
			Element.setStyle(img, {width:w+'px',height:h+'px'});
			if (typeof ImagePreview != "undefined")
			{
				new ImagePreview(img);
			}
		});
	},
	
	/**
	* @param inputClass 
	*/
	updateContent: function(inputClass, updateUrl)
	{
		var re = new RegExp("\\b" + inputClass + "\\b");
		var htmlInputTexts = this.element.getElementsByTagName("input");
		for (var htmlInputText, i = 0; (htmlInputText = htmlInputTexts[i]); i++)
		{
			if (htmlInputText.getAttribute("type") == "text" && re.exec(htmlInputText.className))
			{
				var productID = htmlInputText.id;
				var quantity = htmlInputText.value;

				new Ajax.Updater(
					htmlInputText.id,
					updateUrl,
					{
						method: 'get',
						onFailure: function(req) { alert(req.responseText); },
						parameters:'id=' + productID + '&quantity=' + quantity
					});

				Element.removeClassName(htmlInputText, inputClass);
				
				if(quantity == 0 || quantity == '')
				{
				    $(htmlInputText.id).up(1).remove();
				}				
			}
		}
	},

	open: function(withEffect)
	{
		Cookie.set('SlideCartControl' + this.element.id, true, {path: '/'});
		Element.show(this.options.closeSlidingCart);
		Element.hide(this.options.openSlidingCart);
		if (withEffect && !Element.visible(this.element)) Effect.SlideDown(this.element, {duration:.50});
		else Element.show(this.element);
	},

	close: function(withEffect)
	{
		Cookie.set('SlideCartControl' + this.element.id, false, {path: '/'});
		Element.hide(this.options.closeSlidingCart);
		Element.show(this.options.openSlidingCart);
		if (withEffect && Element.visible(this.element)) Effect.SlideUp(this.element, {duration:.50});
		else Element.hide(this.element);
	}
};
