/**
 * @author Claudio Cesar Sanchez Tejeda
 */

var skip_login = false;
var loginFormValidator = new validatorZ('log_system_form', false);
var redirect_href = '';
var call_back_function_before_loggin = false;
var ajax_file = 'hola';
var selected = '';
var show_message = false;
loginFormValidator.submit = false;	
loginFormValidator.alert = false;

dom_ready_functions[dom_ready_functions.length] = function () 
{
	if (!login)
	{
		$('a[@name=login]').click(function () {return call_log_system(this.href);});	
		
		loginFormValidator.addValidation('email', loginFormValidator.checkNull, 'Please, enter your e-mail.');	
		loginFormValidator.addValidation('email', loginFormValidator.checkEmail, 'Please, enter a vaild e-mail.');	
		loginFormValidator.addValidation('password', loginFormValidator.checkNull, 'Please, enter your password.');	
		loginFormValidator.addValidation('under13', loginFormValidator.checkChecked, 'Please, your must have almost 13 years.', 'under13');			
	}
	else 
		$('a[@name=logout]').click(function () {return to_logout();});
	
}	

function call_log_system(object_href, callback_function)
{
	call_back_function_before_loggin = false;
	newLightbox.setAjaxContent('/templates/ajax/log_system.html'); 
	prepare_log_system();
	activate_common_controls(object_href);
	if (!login && !skip_login)
	{
		set_log_system_content('signup');
		prepare_selected($('#left_area img.rollover')[0]);
		if (object_href) redirect_href = object_href;
		else redirect_href = '#';
	}
	if (callback_function)
		callback_function(object_href);
	return false;
}

function to_logout()
{
	$.ajax({url: '/libs/ajax/signout.php', //root_path + 
	     	type: 'post',
			dataType: 'json',
			success: callbackAjax
		   }); 
	redirect_href = '#';
	return false;
}

function set_log_system_content(module)
{
		change_to_normal();
		
		$.ajax({
				url: '/templates/ajax/' + module + '.xml', 
				dataType: 'xml',
				async: false
			});
			
		$('#content_system_login :input').keypress(function(e) {
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			if (key == 13)
			{
				if (!$('#password').size() || this.id == 'password')
					$('#log_system_form').submit();	
				return false;
			} 
				
			if (key == 9)
			{
				var elements = $('#content_system_login :input').get();
				for (var element in elements)
				{
					if (elements[element] == this && elements[parseInt(element) + 1])
					{
						$(elements[parseInt(element) + 1]).focus();
						return false;
					}
				}
				$(elements[0]).focus();
				
				return false;
			}
		});
}

function transition_set_log_system_content(module)
{
	$('#content_system_login').fadeOut('slow', function(){
		newLightbox.height('70', function() {
			$('#wait_system_login').fadeIn('slow', function() {
				set_log_system_content(module);
			});
		});
	});
}

function prepare_log_system()
{
	selected = '';
	newLightbox.show({color: '#43742C', borderColor: 'silver', height: '70px', width: '330px', cursor: 'default'});

	$('.blockMsg').css('top', '30%');
    $('.round_border').corner();
	$('#message_area').hide();
	$('#content_system_login').hide();
	$('#extra_div').hide();	
		
	$('#content_system_login img.rollover').hover(function()
	{
		this.src = this.src.replace('-noselected', '');				
	}, function()
	{
		if (this.parentNode.id != selected)
			this.src = this.src.replace('image.', 'image-noselected.');
	});
	
	activate_link_area_click();
	
	$('#content_system_login img.rollover').click(function() 
	{
		activate_area_click(this);
		prepare_selected(this);
		return false;
	});
	$('a').click(function(){$(this).blur();});
}

function activate_link_area_click()
{
	$('#content_system_login a.link_hover').click(function()
	{
		var img = $(this).parent().next()[0];
		if (img)
		{
			activate_area_click(img);
			prepare_selected(img);
		}
		return false;
	});
}

function prepare_selected(img)
{
	var position = {'left_area': {top: '130px', left: '10px'}, 'right_area': {top: '150px', left: '170px'}};
	$(img).attr('src', img.src.replace('-noselected', '-selected')).prev().css('color', '#00699E').each(function()
	{
		$(this).html($(this).html().replace(/<a.+Click here.+<\/a>/ig, ''));
	});
	selected = img.parentNode.id;
	$(img.parentNode).css('background-color', '#DFEBF9');
	$('#extra_div').show().css(position[selected]);

}

function activate_area_click(img)
{
	if (img.parentNode.id != selected)
	{
		transition_set_log_system_content(img.id.replace('_log_system', ''));
		initialize_up_area();
	}
}

function initialize_up_area()
{
	$('.area1 > div').css('background-color', '#E6E6E6');
	$('#extra_div').hide();
	
	$('#content_system_login img.rollover').each(function()
	{
		if (!this.src.match('-noselected'))
		{
			this.src = this.src.replace('image.', 'image-noselected.');
			this.src = this.src.replace('image-selected.', 'image-noselected.');
		}
	}).css('cursor', 'pointer');
	$('#content_system_login div h2').each(function()
	{
		$(this).css('color', '#00699E');
		if(!$(this).html().match(/<a.+Click here.+<\/a>/ig))
				$(this).html($(this).html().replace(/(already\.)|(yet\?)/ig, '$1$2 <a href="#" class="link_hover">Click here.</a>'));
		activate_link_area_click();
	});
}

function activate_common_controls()
{
	activate_cancel_button();
	activate_submit_button();

	loginFormValidator.messageCustomFunction = function (errorMessages) 
	{
		var stringErrorMessages = '';
		for (var i=0; i < errorMessages.length; i++)
			stringErrorMessages += '<p>' + errorMessages[i] + '</p>' ;
		error_message(stringErrorMessages);
	}

	loginFormValidator.submitCustomFunction = function ()
	{
		$('#content_system_login').fadeOut('slow', function(){
			newLightbox.height('70', function() {
				$('#wait_system_login').fadeIn('slow', function(){
					$.ajax({url: ajax_file, //root_path +  
		     				type: 'post',
							data: $('#log_system_form').formSerialize(),
							dataType: 'json',
							success: callbackAjax
						   }); 
				});
			});
		});
		return false;
   	}
}

function activate_cancel_button()
{
	$('.log_system_close').click(function () 
	{
		newLightbox.hide();
		return false;
	});
}

function activate_submit_button()
{
	$('#log_system_submit').click(function () 
	{
		$('#log_system_form').submit();
		return false;
	});
}

function change_to_normal()
{
	$('.button').show();
	$('.area1').show();
	$(".area1").insertBefore(".area2");
	$(".area1 > div").css('margin-top', '');
	$('.area2').hide();
	$('.area2').css('height', '100px');
}

function callbackAjax (data)
{
	if (data['message_type'] == 'signin')
	{
		if (call_back_function_before_loggin)
		{
			login = true;
			$('.log_system_close').unbind('click');
			$('.log_system_close').click(function() { 
				if (login) 
				{
					if ($('#link_watchdog_no_results')[0])
						location.href = location.href.replace(/\?.+/ig, ""); 
					else	
						location.reload(true); 
				}
			});
			call_back_function_before_loggin(data);
			return;
		}
		$('#wait_system_login').fadeOut('slow', function() {
			$('#wait_system_login h3').html('We are signing you in, please wait');
			$('#wait_system_login').fadeIn('slow', function() {
				page_reload();
			 });
		});
	}
	else if (data['message_type'] == 'signout')
		page_reload();
	else
	{
		if (data['message_type'] == 'error')
		{
			$('#wait_system_login').fadeOut(function(){
				newLightbox.height('305', function() {$('#content_system_login').fadeIn('slow');});		
				error_message(data['message']);
			});
		}
		else 
		{
			set_log_system_content('signup');
			$('#forgot_pass_link').click(function() {toggle_areas('.area2', '.area1');});
			ok_message(data['message']);
		}
	}
}

function page_reload()
{
	if(redirect_href.substr(redirect_href.length - 1, 1) != "#" )
		location.href = redirect_href;
	else 	
		location.reload(true);
}

function error_message(message)
{
	message = '<table><tr><td valign="middle" style="width: 20%"><img src="' + root_path + '/images/info-error.gif" /></td><td valign="middle">' + message + '</td></tr></table>';
	$('#message_area').removeClass("ok_message");
	$('#message_area').addClass("error_message");
	$('#message_area table tr td').html(message);
	if (!show_message)
	{
		show_message = true;
		if ($('.area2').css('display') != 'block')
		{
			toggle_areas('.area1', '.area2', function() {
				if ($('#extra_div').css('display') != 'none') $('#extra_div').fadeOut('slow');
			});
			setTimeout("toggle_areas('.area2', '.area1', false, function() { if ($('#extra_div').css('display') != 'none') $('#extra_div').fadeIn('slow'); }); show_message = false;", 10000);
		}
	}
}

function ok_message(message)
{
	$('#message_area').removeClass("error_message");
	$('#message_area').addClass("ok_message");
	$('#message_area table tr td').html(message);
	toggle_areas('.area1', '.area2', function() {
		$('#extra_div').fadeOut('slow');
	});
}

function toggle_areas(area1, area2, custom_function1, custom_function2)
{
	if (custom_function1)
		custom_function1();
	$(area1).fadeOut('slow', function(){
		if (custom_function2)
			custom_function2();
		$(area2).fadeIn('slow', function(){
			$('.safari_hack').html('d');
		});
	});
}

function end_loading(height)
{
	$('#wait_system_login').fadeOut('slow', function () { 
		newLightbox.height(height, function() {
			$('#content_system_login').fadeIn('slow', function() {
				$('.safari_hack').html('d');
				var inputs = $('#content_system_login :input');
				if (inputs.size() > 0)
					inputs.get(0).focus();
			});
		});
	});
}
