(function($) {

	$.fn.widget = function(widget_type, options) {

		switch( widget_type )
		{
			case 'shoppingcart':
				$.fn.widget.defaults.shoppingcart_container = this.selector;
				break;
			case 'categories':
				break;
			default:
				//alert('Undefined action');
		}


		var opts = $.extend({}, $.fn.widget.defaults, options);
		return this.each(function() {
			var o = $.meta ? $.extend({}, opts, $(this).data()) : opts;
			createWidget(this, widget_type, o);
		});
	};

	function createWidget( domContainer, widget_type, o ) {
		var $this = $(domContainer);
		$.post("/" + widget_type + "/show_widget", 
			function(data){
				$this.html(data);
				registerControls( widget_type, o );
			}
		);
	}

	function registerControls( widget_type, o ) {
		switch( widget_type )
		{
			case 'shoppingcart':
				$( o.shoppingcart_clear ).unbind().click(function(event) {
					$.post("/shoppingcart/clear", 
						function(data){
							//$(o.shoppingcart_container).html(data);
							$(o.shoppingcart_container).widget('shoppingcart', o);
						}
					);
				});
				$( o.product_form ).each(function() {
					var $thisForm = $(this);
					$thisForm.unbind().submit(function(event) {
						var $product_id = $thisForm.find( o.product_form_id ).val();
						var $product_quantity = $thisForm.find( o.product_form_quantity ).val();
						event.preventDefault();
						$.post("/shoppingcart/add", { product_id: $product_id, count: $product_quantity },
							function(data){
								$(o.shoppingcart_container).html(data);
								$(o.shoppingcart_container).widget('shoppingcart', o);
							}
						);
					});
				});
				break;
			case 'categories':
				break;
			case 'orders':
				break;

//		$('#widget_categories')
//		$('#widget_orders')

			default:
				//alert('Undefined action');
		}
	}

	$.fn.widget.defaults = {
		shoppingcart_container: '#widget_shoppingcart',
		shoppingcart_clear: '#widget_shoppingcart_clear',
		product_form: "form[name='product_form']", 
		product_form_id: "input[name='product_id']", 
		product_form_quantity: "input[name='quantity']"

	};
})(jQuery);
