/**
 * @created 2010-01-11
 * @author Christoffer Lejdborg
 * @author Jon Gotlin
 */
function Widget(widget_dom_id)
{
	// Initializes widget object, pushing the id of the widget container.
	this.widget_dom_id = widget_dom_id;
	this.widget_type = widget_dom_id.split('_')[0];
	this.widget_key = widget_dom_id.split('_')[1];

	/**
	 * Reload this widget
	 *
	 * @param params hashmap Parameters to send via AJAX-POST to the widget.
	 * @param return_function function Unnamed function to be run on callback.
	 * @return void
	 */
	this.refresh = function(params, return_function)
	{
		var widget = this;
		if ( params == undefined ) params = {};

		$('#'+this.widget_dom_id).load('/' + this.widget_type + '/show_widget/' + this.widget_key + '/#' + new Date().getTime(),
		             params,
		             function() {
						if ( return_function != undefined )
						{
							return_function();
						}
						widget.widgetLoadedCallback();
					 }
		);
	}

	/**
	 * Callback that will occur when a widget has finished loading.
	 *
	 * @return void
	 */
	this.widgetLoadedCallback = function()
	{
		/**/
	}
}

function initializeWidgets()
{
	var available_widgets = ['shoppingcart', 'login', 'loggedin', 'categories',
	                         'cartsize', 'editcart', 'totalsum', 'freight', 'payment',
	                         'newsletter', 'customerdetails', 'tellafriend', 'addsubscriber'];
	$('.widget').each(function() {
		var widget_dom_id = $(this).attr('id');
		if (widget_dom_id.indexOf('_') > 0) {
			if ($.inArray(widget_dom_id.split('_')[1], available_widgets) >= 0) {
				var widget = new Widget(widget_dom_id);
				switch (widget_dom_id) {
					case 'shoppingcart_customerdetails':
						initCustomerDetailsWidget(widget);
						break;
					case 'products_tellafriend':
						initTellAFriendWidget(widget);
						break;
					default:
						widget.refresh();
				}
			}
		}
	});
}

/**
 * Save customer details form in user object.
 * The reason is that the form is refreshed whenever another form is posted
 * on the checkout page.
 *
 * @param widget Widget object
 */
function initCustomerDetailsWidget(widget)
{
	$('#order_form input:not([id="customer_details_unique_string"]), #order_form select, #order_form textarea').each(function() {
		var form_name = $(this).attr('name');
		var form_val = $(this).val();
		var check_type = $(this).is('[type="checkbox"]');
		var select_type = $(this).get(0).tagName == 'SELECT';

		// Set readonly value, but ONLY if it hasn't already been set
		var readonly_value = $(this).attr('readonly')||$(this).attr('disabled') ? form_val : null;
		if ( user.customer_details[form_name] != undefined && user.customer_details[form_name].readonly_value != null ) {
			readonly_value = user.customer_details[form_name].readonly_value;
		}

		var data = { value: form_val, check_type: check_type, select_type: select_type, is_checked: $(this).is(':checked'), readonly_value: readonly_value }
		user.customer_details[form_name] = data;
	});
	widget.refresh({}, function() {

		// Trigger a "light" refresh to force the fields to be updated
		$('#customer_details_unique_string').trigger('change');
	});
}

/**
 * Init listeners for tell-a-friend function.
 *
 * @param widget Widget
 */
function initTellAFriendWidget(widget)
{
	widget.refresh({}, function() {
		$("A#tell_a_friend").unbind('click');
		$("A#tell_a_friend").click(function(event) {
			event.preventDefault();
			if ( $("#tell_a_friend_form").css('display') == 'none' ) {
				$("#tell_a_friend_form").show('slow');
			} else {
				$("#tell_a_friend_form").hide('slow');
			}
		});

		tellAFriendLogic(function(data) {
			$('#tell_a_friend_form_message').hide().text(data.message);
			$('#tell_a_friend_form_message').slideDown().animate({opacity: 1.0}, 3000).slideUp();
		});
	});
}

/**
 * Isolated logic for tell-a-friend.
 *
 * @param callback function
 */
function tellAFriendLogic(callback)
{
	$("#tell_a_friend_form").unbind('submit');
	$("#tell_a_friend_form").submit(function(event) {
		event.preventDefault();

		$.post('/form/tell_a_friend/',
			{
			   product_id: $('.product_id:first').val(),
			   teller_name: $('.teller_name:first').val(),
			   teller_email: $('.teller_email:first').val(),
			   friend_email: $('.friend_email:first').val()
			}, function(data) {
				if ( data.success == true) {
					 $('.teller_name:first').val('');
					 $('.teller_email:first').val('');
					 $('.friend_email:first').val('');
				}

				callback(data);
			},
			'json');
	});
}

$(document).ready(function() {
	initializeWidgets();
});