$(document).ready(function() {
	formHandler();
});

/**
 *	Handles submission off the form
 *
 */
function formHandler() {
	if ( $('#user_form').length == 0 )
		return false;

	$('#user_form').submit(function() {
		var data 	= $(this).serialize();
		var url		= document.location.href;
		
		// send the request
		$.ajax({
			url: url,
			dataType: 'json',
			data: data,
			type: "POST",
			success: function(r) {
			
				// show messages
				$('#global_message').css('display', 'block');
				
				// show validation status
				if (r.status == 1) {
					$('#global_message').removeClass('error');
					$('#global_message').addClass('no_error');
				} else {
					$('#global_message').removeClass('no_error');
					$('#global_message').addClass('error');
				}

				for(i in r.data) {
					// handle redirects
					if (i == 'goto') {
						redirectTo('goto', r.data[i]);
					} else {
					// handle messages

						// check for current error
						if ( $('#' + i + '_error').length == 0 ) {
							var el = $( document.createElement('div') ); 
							$(el).attr('id', i + '_error');
						} else {
							var el = $('#' + i + '_error');
						}

						el.html('- ' + r.data[i]);
												
						el.prependTo('#global_message');
					}
				}
				
				// remove errors
				$('#global_message div').each( function(index, e) {
					var found = false;
					
					for(i in r.data) {						
						if (i + '_error' == $(e).attr('id'))
							found = true;
					}

					if (!found) {
						$(e).detach();
					}
				});
			}
		});

		return false;
	});
}

/**
 *	Redirects
 *
 */
function redirectTo(id, url) {
	var now		= parseInt( $('#goto').html() );
	status		= { counter: now };

	// set timeout
	var decreaseCount = function(){ 	
		status.counter--; 
				
		$('#goto').html(status.counter);

		if (status.counter == 0)
			location.href = url;
	};
		
	setInterval(decreaseCount, 1000);
}

