/**
 * @author alexo 2009
 */
(function($)
{
  //
  // plugin jqLogin
  //
  $.fn.jqLogin = function(options)
  {
	/*
	* Variables globales
	*/
	var _this;
	
	/*
	* Opciones iniciales
	*/
	var Option = jQuery.extend(
	{
		/* Configuracion */
		action: '/mi-cuenta/inicio-de-sesion',
		redirect: '/mi-cuenta',
		errorContainer: jQuery('div#error_form_login'),
		form: 'form#top-login',
		formContainer:'#moduloInicioSesion',
		user:'input#Usuario',
		password:'input#Password',
		recordar:'input#recordarLogin',
		callback: false,
		ValidateErrorClass: 'errorLogin',

		/*
		* Mensajes
		*/
		msjErrorUserPassword: '<li>Usuario o Clave incorrecto</li>',
		msjUser: 'debe ingresar su usuario',
		msjPassword:'debe ingresar su clave'
	}, 
	options);

	/*
	* Login
	*/
	function login()
	{
		show();
		
		jQuery(Option.form).validate({
			errorContainer: Option.errorContainer,
			errorLabelContainer: jQuery("ul", Option.errorContainer),
			wrapper: 'li',
			meta: "validate",
			errorClass:Option.ValidateErrorClass,
			rules:
			{
				Usuario: {
					required: true
				},
				Password: {
					required: true
				}
			},
			messages:
			{
				Usuario:{
					required: Option.msjUser
				},
				Password:{
					required: Option.msjPassword
				}
			},
			submitHandler: function()
			{
				jQuery.post(Option.action, {
						Usuario: jQuery(Option.user,Option.form).val(),
						Password: jQuery(Option.password,Option.form).val(),
						Recordar: jQuery(Option.recordar+':checked',Option.form).val()
					}, function(data){
						
						if (data.estado)
						{		
							jQuery(Option.user,Option.form).val('');
							jQuery(Option.password,Option.form).val('');
							jQuery(Option.formContainer).fadeOut('fast');
							
							//boca mail redirect
							if(Option.redirect == '/mi-cuenta/email-login')
							{
								if(data.google)
								{
									jQuery(Option.form).attr('redirect',jQuery(Option.form).attr('redirect'));			
								}
								else
								{
									jQuery(Option.form).attr('redirect','/mi-cuenta');
								}
							}
										
							if(Option.callback)
							{
								Option.callback.call(this,data);
							}
							else
							{
								document.location.href = Option.redirect;	
							}
						}
						else
						{
							jQuery('ul',Option.errorContainer).html('');
							jQuery('ul',Option.errorContainer).append(Option.msjErrorUserPassword);
							jQuery(Option.errorContainer).show();
							jQuery('ul',Option.errorContainer).show();
						}
						
					},
					'json'
				);
			}
		});
	}
	
	function show()
	{
		jQuery(Option.formContainer).fadeIn('fast');	
	}

	/*
	 * Init
	 */
	return this.each(function()
	{
		/*	 
		* Objeto contenedor
		*/
		_this = this;
		
		login();
		
	});	
  };
})(jQuery);
