//
/**
 * Javascript code for the logon action
 */

$.any.ui.action.js('logon',
{
	init: function ()
    {
        var self = this;
		self.options['require_logon'] = false;
		self.user = {};
        
        self.stageReady = function(stage, containing_element)
	    {
		if (stage == 'logon' && !self._openedInDialog())
		{
                    // See if we can find the logon form in the original action
                    var form = $('.logon-form', self.element);
                    if (form.length > 0 && self.element.parent().length > 0)
                    {
                        // Replace the logon form with the original
                        form.data('ui').setAutoFocus();
                        $('.logon-form', containing_element).replaceWith(form.css('display', 'block'));
                    
                    }
		}
	    };

	},
    
    containerElement: function ()
    {
        var self = this;
        if (self.options.logonpage && !self.options.stage)
        {
            return self.element;
        }
        return self._openedInDialog() ? self.element : $.any.dialog.contentArea();
    },

	callLogon: function (opt, form)
    {
        var self = this;
        var data = form.getData();      

        var options = {
		    'username': data.username,
		    'password': data.password,
            'autologon': data.autologon
		};
            
        self.rest('authentication.user.logon',
            options,
		    function (result)
		    {
		        // handle the new logon state
		        self.handleLogon(result);
                self.finish();
            },
		    function (error)
		    {
				$.any.notification.formError(error.message, self.containerElement());
				
				// tried to logon but not confirmed yet
				if (error.code == 3)
				{
					$('#resend').live('click', function() {
					self.rest(
						'anymeta.resend.confirmation',
						{'email': data.username},
						function (result)
						{
							$.any.notification.formError(result, self.containerElement());
						},
						function (error)
						{
							$.any.notification.formError(error.message, self.containerElement());
						});
					});
				}


                form.setError('username', '', true);
                form.setError('password', '');
		    });
	},
    
    callLogonRegister: function (opt, form)
    {
        var self = this;
        
        // See if the user filled out the form.
        var logon_form = $('.logon-form:last', $.any.dialog.contentArea()).data('ui');

        if (logon_form)
        {
            var data = logon_form.getData();
            if (data.username && data.password)
            {
                self.callLogon(opt, logon_form);
                return;
            }
        }   
        
        if (opt.gotoprofile)
        {
        	self.options.gotoprofile = true;
	    }
        
        if (opt.simple)
        {
	        self.goFullDialog('register_simple');
        }
        else
        {
        	self.goFullDialog('register');
        }

    },

    /**
     * callCancel: just close the dialog when cancelling logon/register flow.
     */
    callCancel: function ( vars )
    {
        $.any.dialog.close();
    },
    
    callRegister: function (opt, form)
    {   
        var self = this;

        var data = form.getData();

		if (data.gotoprofile)
		{
			self.options.gotoprofile = true;
		}
		
        self.rest('authentication.user.exists',
                  {'email': data.email},
		          function (result)
				  {
					  if (!result)
					  {
						  self.user.email = data.email;
						  if (!data.mailinglist)
						  {
							  self.user['type'] = {symbolic: 'NOMAIL'};
						  }

						  // User comes from a simple register flow and request a visible profile. No user created so far
	                      if (data.visible_profile)
	                      {
						      self.renderStage('register_simple_register', '', {user: self.user, register_simple: true});
						  }
						  // Create user based on email, password text etc (normal register flow)
						  else if (data.password)
						  {  
							  var kind 	    = data.kind || 'person';
						      var password  = data.password;
						      var user_lang = data.user_lang;
		                      
		                      self.user.kind  = kind;
						      self.user.text  = {title: data.name};
						      self.user.trust = {view: {level : 'EVERYONE', predicate: false}};
						      
						      self.user.name = {
						          first: data.nameFirst, 
						          voorvoegsel: data.nameVoorvoegsel, 
						      	  last: data.nameLast
						      };
						      
						      if (user_lang)
						      {
						          self.user.user_lang = [user_lang];
						      }
						      
						      self.createUser(password,
						                      function (result)
						                      {
						                          self.renderStage('register_complete');
						                      });
	                      }
	                      // Simple register flow. User does not want a visible profile
						  else
						  {
						      self.createUser(false,
	                        				function (result)
					                        {
										      self.renderStage('register_simple_complete');
	            				            });
	                      }
					  }
					  else
					  {
						  form.setError('email', 'A user with this email is already registered', true);
					  }
				  });
	},
	
    callFinish: function (opt)
    {
        var self = this;
        
        self.finish();
    },

    callEmailToChangePass: function (opt,form)
    {
        var self = this;
        var data = form.getData();

        self.renderStage('changepassword', '', {email: data.username});
    },

    createUser: function(password, callback)
    {
        var self = this;
        var options = {
		    'email': self.user.email,
		    'logon': true
		};
		if (self.user.user_lang && self.user.user_lang[0])
		{
			options.lang = self.user.user_lang[0];
		}
        if (password)
        {
            options['password'] = password;
            options['fullname'] = self.user.text.title;
        }
        self.rest('authentication.user.register',
                  options,
		          function (result)
		          {
                              if (result.confirm_needed)
                              {
			          self.options.gotoprofile = false;
				  if (result.goto_url)
				  {
				      self.options.goto_url = result.goto_url;
				  }
			      }
			      else
			      {
				  options = {thing_id: result.thg_id, data: self.user};
			          self.rest('anymeta.thing.update', options);
                                  
			      }
				  
			      // publish the registered on status so other action can pick up on this.
		              self.publish('registered');

                              // handle the new logon state
		              self.handleLogon(result.thg_id);
                              
                      if (typeof callback == 'function')
                      {
                          callback();
                      }
                  },
		          function (error)
                  {
		              $.any.notification.formError('Could be: email already existed');
		          });
    },

    callProfile: function ()
    {
        var self = this;

        self.subscribe('profile-changed', 
                       function ()
                       {
                           self.finish();
                       });
        self.switchAction('profile', false, 'callFirst', {thg_id: $.any.rest.user.id});
    },
    

	callChangePassword: function (opt, form)
    {
		var self = this;

	    self.rest('authentication.user.reset.password',
	              {email: form.getData().username},
		          function (result)
		          {
					  self.goFullDialog('changepassword_onetime');
		          },
		          function (error)
		          {
		              $.any.notification.formError(error.message, form.element);
		              $.any.notification.loader.removeLoader();
		          }
		         );
    },
    

    handleLogon: function (user_id, callback)
    {
        var self = this;

        // make sure the user_id is set
        $.any.rest.user.id = user_id;

        if (self.options.logonpage)
        {
            return;
        }

        if (self.options.thg_id)
        {
            var thg_id = self.options.thg_id;
        }
        else
        {
            var thg_id = 0;
        }
        
        $.any.rest.get('anymeta.html.scomp',
                       {
                           'name': 'header',
                           'thg_id': thg_id
                       },
                       function (json)
                       {
                           $('#header').html(json.html);
                           $.any.ui.scan($('#header'));
                           if (typeof callback == "function")
                           {
                               callback();
                           }
                       });

    },

    finish: function()
    {
        var self = this;

        // Drop subscription on our own close. We are logged in and the logon action is not valid anymore.
        self.dropSubscriptions(self.priv.closePublishKey);

        if (self.options.gotoprofile)
        {
        	window.location.href = "/"+$.any.rest.user.id;
            return;
        }

        if (self.options.goto_url)
        {
        	window.location.href = self.options.goto_url;
            return;
        }
        
        if (self.options.logonpage)
        {
            window.location.href = '/?logon=' + $.any.rest.user.id;
            return;
        }
        
        if (self._openedInDialog())
        {
            self.publish('logged-on');
        }
        else
        {
            self.close(
                function () 
                { 
                    self.publish('logged-on');
                });
        }
            
    }
        
});

//
