/**
 * @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 = {};
     $.etagAjax({
       type: 'POST',
       url: '/' + widget.widget_type + '/show_widget/' + widget.widget_key + '/',
       data: params,
       success: function(data)
       {
         $('#'+widget.widget_dom_id).html(data);
         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;
					case 'newsletter_newsletter':
						initNewsletterWidget(widget);
						break;
					default:
						widget.refresh();
				}
			}
		}
	});
}

/**
 * Binds the newsletter widget to posting the entered e-mail address.
 *
 * @param widget Widget object
 */
function initNewsletterWidget(widget) 
{
	widget.refresh({}, function()
	{
		$('#form_newsletter_subscription').bind('submit', function(event) {
			event.preventDefault();

			$.ajax({
				data: {
					email: $('input[name=form_newsletter_subscription_email]').val()
				},
				dataType: 'json',
				success: function(data, textStatus, xhr) {
					var message = $('<div style="display:none" class="newsletter_response"></div>');
					if (!data.success)
					{
						message.addClass("error");
					}
					message.text(data.message);
					$('#form_newsletter_subscription').prepend(message);
					message.slideDown(400, function() {
						setTimeout(function() {
							message.slideUp();
						}, 5000);
					});
				},
				type: 'POST',
				url: '/newsletter/add_subscriber'
			});
		});
	});
}

/**
 * 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() {
		$("#tell_a_friend").unbind('click');
		$("#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('/products/send_to_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(),
			   success: $('.success:first').val(),
			   failure: $('.failure: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() {
    $.storage = new $.store();

	initializeWidgets();
});

