var Brushfire = Brushfire || { };

Brushfire.Login = // implements observer pattern (attach, detach and notify methods)
{
		
	BUYER: 'buyer',
	FIRESTARTER: 'firestarter',
	
	dashboard_url: '',
	redirect_dashboard: false,
	
    fb_perms: '',
    
    _observers: [],
    
    attach: function(observer)
    {
    	if (!observer.update) {
    		throw new Exception("The attached object does not implement the observer interface, update method is needed");
    	}
    	this._observers.push(observer);
    },

	detach: function(observer)
	{
		var observerTemp = [];
		for(var i in this._observers) {
			if (this._observers[i] === observer) {
				continue;
			}
			observerTemp.push(this._observers[i]);
		}
		this._observers = observerTemp;
	},
	
	notify: function()
	{
		for(var i in this._observers) {
			var observer = this._observers[i];
			observer.update(this);
		}
	},

    showLoggedUser: function(data)
    {
    	$('#logged_first_name').val(data.first_name);
    	$('#logged_last_name').val(data.last_name);
    	$('#logged_email').val(data.email);
    	
    	$('#logged_msg').css({'display': 'block'});
    	$('#mies5').css({'display': 'none'});
    	
    	//update menu header login 
    	$('#login_mainheader_logout').css({'display': 'inline'});
    	$('#login_mainheader_username').html(data.first_name + ' ' + data.last_name);
    	$('#login_mainheader_username').css({'display': 'inline'});
    	$('#loginbtn_mainheader5').css({'display': 'none'});
    	
    	//dashboard fb login if is buyer
    	if(data.loginType == Brushfire.Login.BUYER){
    		$('#logged').css({'display': 'none'});
    		$('#login_dialog5').css({'display': 'none'});
			$('#registration').css({'display': 'none'});    		
    		$('#dashboard_btn').bind('click', function(event){
    			event.preventDefault();
    			$('#mies5').css({'display': 'block'});
    			Brushfire.Login.redirect_dashboard = true;
    		});
    	}
    	if(data.loginType == Brushfire.Login.FIRESTARTER){
    		$('#dashboard_btn').unbind('click');
    		if(Brushfire.Login.redirect_dashboard){
    			window.location.href= Brushfire.Login.dashboard_url;
    		}
    	}
    	
    	$('#main-nav .user-nologged ').css({'display': 'none'});
    	$('#main-nav .user-logged').css({'display': 'block'});
    	
    	$('#bradcampaign_join_btn').unbind('click'); 
    },	    
    
   /* * * * * * * * * * * * * *
    * Quick Login
    * * * * * * * * * * * * * */		
		
	prepareQuickLogin: function()
	{
		var that = this;
		$('#login_btn').bind(
		    'click.login',
		    function(){
			$('#login_error_msg').hide();
			$.ajax({
				url: '/login2/user',
				type: 'POST',
				data: 
				{
					'login_email' : $('#login_email').val(),
					'login_password' : $('#login_password').val()
				},
				success: function(result) 
				{
					if(typeof(result.logged) != 'undefined'){
						//logged
						Brushfire.Login.showLoggedUser(result);
						//Brushfire.Login.loggedUserType = result.loginType;
					} else {
						//not logged
						$('#login_msg').html('');
						$('#login_msg').removeClass('success');
						$('#login_msg').addClass('error');
						for(var i = 0; i < result.error.length ; i++){
							$('#login_msg').append('<p><em>' + result.error[i].message + '</em>');
						}
						$('#login_msg').show();
					}
					Brushfire.Login.notify();
				},
				error: function(data)
				{
					$('#login_msg').removeClass('success');
					$('#login_msg').addClass('error');
					$('#login_msg').html('<p><strong>Error</strong>:<em>Connection problem</em>');
					$('#login_msg').show();
					
				}
			});
		});
	},
   
   /* * * * * * * * * * * * * *
    * Facebook Login
    * * * * * * * * * * * * * */
   
   enableFbLoginBtn: function()
   {
	   $('#fb_button_login').attr({
		  
	   });
	   $('#fb_button_login').css({'cursor': 'pointer'});
	   
	   //FB.login(function(){alert('zxc')});
	   
	   $('#fb_button_login').bind('click', function(){
		   //truchada porque facebook lo necesita
		   FB.init({
	        	appId:   	Tasks.php.facebook.id,
	        	session: 	JSON.stringify(Tasks.php.facebook.session),
	        	cookie:  	Tasks.php.facebook.cookie,
	        	status: 	Tasks.php.facebook.status,
	        	xfbml:   	Tasks.php.facebook.xfbml,
	        	domain:  	Tasks.php.app.url,
	            channelUrl: Tasks.php.app.url + '/public/channel.html'
	        });
		   FB.login(function(response) {
			   if (response.authResponse) {
				   var accessToken = response.authResponse.accessToken;
				   try {
					   FB.api('/me', function(response) {
						   if(typeof response == 'object'){
							    //logged
							   response.access_token = accessToken;
							   $('#fb_button_login').unbind('click');
							   $('#fb_button_login').attr({
									'src': '/public/img/fb_loader.gif'
								});	
							   Brushfire.Login.registerFirestarterByFbLogin(response);
						   }
					   });
				   } catch(e){
					   $('#fb_login_msg').html('<p><em>Internal Error</em></p>');
					   $('#fb_login_msg').show();
				   }
			   }
		   }, {scope: Brushfire.Login.fb_perms});
	   });
	   
   },

   registerFirestarterByFbLogin: function(data)
   {
	   $.ajax({
			url: '/login2/facebook',
			type: 'POST',
			data: data,
			success: function(response) 
			{
				if(typeof(response.logged) != 'undefined'){
					Brushfire.Login.showLoggedUser(response);
				} else {
					Brushfire.Login.enableFbLoginBtn();
					$('#fb_login_msg').html('');
					for(var i = 0; i < response.error.length ; i++){
						$('#fb_login_msg').append('<p><em>' +
								response.error[i]['message']  + '</em></p>');
					}
					$('#fb_login_msg').show();
				}
			},
			error: function(response)
			{
				Brushfire.Login.enableFbLoginBtn();	
				$('#fb_login_msg').html('<p><em>Internal Error</em></p>');
				$('#fb_login_msg').show();
			}
	   });
   },
   
   /* * * * * * * * * * * * * *
    * Registration
    * * * * * * * * * * * * * */   
   
   registerUser: function()
   {
	   $('#reg_btn').unbind('click', Brushfire.Login.registerUser);
	   $('#reg_ajax_loading').show();
	   $.ajax({
			url: '/login2/registration',
			type: 'POST',
			data: $('#form_registration').serializeArray(),
			success: function(response) 
			{
				$('#reg_msg').html('');
				if(typeof(response.logged) != 'undefined'){
					//logged
					$('#reg_msg').addClass('success');
					$('#reg_msg').removeClass('error');					
					$('#reg_msg').html('<p><em>Successfully Registered!</em></p>');
					Brushfire.Login.showLoggedUser(response);
					return;
				} else {
					//has errors
					$('#reg_msg').addClass('error');
					$('#reg_msg').removeClass('success');
					if(typeof(response.error.validation) != 'undefined'){
						for(var fieldId in response.error.validation){
							var parent = $('#' + fieldId).parent().parent()[0];
							var label = $('label', parent).html().trim();
							for(var errorType in response.error.validation[fieldId]){
								var msg = response.error.validation[fieldId][errorType];
							    break;
							}
							$('#reg_msg').append('<p><strong><em>' + label + '</strong></em> ' + msg  + '</p>');
						}
					} else {
						for(var i = 0; i < response.error.length ; i++){
							$('#reg_msg').append('<p><em>' + response.error[i]  + '</em></p>');
						}
					}
				}
				$('#reg_msg').show();
				$('#reg_ajax_loading').hide();
				$('#reg_btn').bind('click', Brushfire.Login.registerUser);
			},
			error: function(response)
			{
				//Connection error
				$('#reg_msg').addClass('error');
				$('#reg_msg').removeClass('success');
				$('#reg_msg').html('<p><em>Internal Error</em></p>');
				$('#reg_msg').show();
				$('#reg_ajax_loading').hide();
				$('#reg_btn').bind('click', Brushfire.Login.registerUser);				
			}
	   });
   },
  
   /* * * * * * * * * * * * * *
    * Twitter
    * * * * * * * * * * * * * */ 
   
   validationWindowEmail: function(user_data)
   {
        var EMAIL_NOT_VALID = 'It isn\'t a valid email';
        var INTERNAL_ERROR = 'Internal error';     
        
        $('#send').bind('click', function(){
            var email = $('#email').val();
            var emailRegex = /^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i;
            if (!emailRegex.test(email)) {
                //js not valid
                $('#message').html(EMAIL_NOT_VALID);
                $('#message').css({'display': 'block'});
            } else {
                //js valid
                $('#ajaxLoader').css({'display': 'block'});
                $.ajax({
                        url: '/login2/email-validator',
                        type: 'POST',
                        data: {'email' : email},
                        success: function(response) 
                        {
                            $('#ajaxLoader').css({'display': 'none'});
                            //ajax email validation
                            if(response.isValid){
                                var data = 
                                {
                                    'name': user_data.screen_name,
                                    'id': user_data.user_id,
                                    'email': email
                                };
                                window.opener.passTwitteUserName(data);
                                window.close();                                    
                            } else {
                                $('#message').html(EMAIL_NOT_VALID);
                                $('#message').css({'display': 'block'});                                    
                            }
                        },
                        error: function(response)
                        {
                            $('#ajaxLoader').css({'display': 'none'});
                            $('#message').html(INTERNAL_ERROR);
                            $('#message').css({'display': 'block'});
                        }
                });                    
            }
        });       
   },
   
   
   enableTwitterLogin: function()
   {
        $('#twitterLoginBtn').bind('click', function(){
            window.open('/twitter/login', 'mywindow','menubar=1,resizable=1,width=300,height=300');    
        });
        window.passTwitteUserName = function(data)
        {
            Brushfire.Login.loginTwitterUser(data)
        }       
   },
   
   loginTwitterUser: function(data)
   {
        //$('#login_error_msg').hide();
        $.ajax({
            url: '/login2/user',
            type: 'POST',
            data: 
            {
                'login_email' : data.email,
                'login_id' : data.id
            },
            success: function(result) 
            {
                if(typeof(result.logged) != 'undefined'){
                    
                    console.log('login ok');
                    
                    //logged
                    Brushfire.Login.showLoggedUser(result);
                    //Brushfire.Login.loggedUserType = result.loginType;
                } else {
                    
                    console.log('login not a user so register');
                    
                    //not a user, so need registration:
                    Brushfire.Login.registerTwitterUser(data);
                }
                Brushfire.Login.notify();
            },
            error: function(data)
            {
                console.log('login conection error');
                
                $('#login_msg').removeClass('success');
                $('#login_msg').addClass('error');
                $('#login_msg').html('<p><strong>Error</strong>:<em>Connection problem</em>');
                $('#login_msg').show();

            }
        });       
   },
   
   registerTwitterUser: function(data)
   {       
       ///register user
	   $('#reg_btn').unbind('click', Brushfire.Login.registerUser);
	   $('#reg_ajax_loading').show();
	   $.ajax({
			url: '/login2/registration',
			type: 'POST',
			data: 
            {
                'reg_first_name': data.name,
                'reg_last_name': 'nulll',	 
                'reg_email': data.email ,
                'reg_id': data.id,
                'reg_password': 'passwordFalso',
                'reg_password_confirm': 'passwordFalso'
            },
			success: function(response) 
			{
				$('#reg_msg').html('');
				if(typeof(response.logged) != 'undefined'){
                    
                    console.log('registered');
                    
					//logged
					$('#reg_msg').addClass('success');
					$('#reg_msg').removeClass('error');					
					$('#reg_msg').html('<p><em>Successfully Registered!</em></p>');
					Brushfire.Login.showLoggedUser(response);
					return;
				} else {
                    
                    console.log('registration error');
                    
					//has errors
					$('#reg_msg').addClass('error');
					$('#reg_msg').removeClass('success');
					if(typeof(response.error.validation) != 'undefined'){
						for(var fieldId in response.error.validation){
							var parent = $('#' + fieldId).parent().parent()[0];
							var label = $('label', parent).html().trim();
							for(var errorType in response.error.validation[fieldId]){
								var msg = response.error.validation[fieldId][errorType];
							    break;
							}
							$('#reg_msg').append('<p><strong><em>' + label + '</strong></em> ' + msg  + '</p>');
						}
					} else {
						for(var i = 0; i < response.error.length ; i++){
							$('#reg_msg').append('<p><em>' + response.error[i]  + '</em></p>');
						}
					}
				}
				$('#reg_msg').show();
				$('#reg_ajax_loading').hide();
				$('#reg_btn').bind('click', Brushfire.Login.registerUser);
			},
			error: function(response)
			{
                console.log('registration conection error');
                
				//Connection error
				$('#reg_msg').addClass('error');
				$('#reg_msg').removeClass('success');
				$('#reg_msg').html('<p><em>Internal Error</em></p>');
				$('#reg_msg').show();
				$('#reg_ajax_loading').hide();
				$('#reg_btn').bind('click', Brushfire.Login.registerUser);				
			}
	   });             
   }
   
};
