//
/**
 * 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._inActionDialog())
		{
                    // 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'));
                    
                    }
		}
	    };

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

        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());
		    
                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}};
						      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', 'Dit e-mailadres is reeds in gebruik', true);
					  }
				  });
	},
	
    callFinish: function (opt)
    {
        var self = this;
        
        self.finish();
    },

    createUser: function(password, callback)
    {
        var self = this;
        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', parent);
		          });
    },

    callProfile: function ()
    {
        var self = this;

        self.subscribe('profile-changed', 
                       function ()
                       {
                           self.finish();
                       });

        self.switchAction('profile', false, 'callFirst');
    },

	callChangePassword: function (opt, form)
    {
		var self = this;
                       
		options = {
			'email'	: form.getData().username
		};
        
	    self.rest('authentication.user.reset.password',
	              options,
		          function (result)
		          {
					  self.goFullDialog('changepassword_onetime');
		          },
		          function (error)
		          {
		              //var parent = $('.dialog-content input[name=email]').parents('fieldset:eq(0)');
                      
		              //$.any.notification.formError('Could bot set password', parent);
		          }
		         );
    },

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

        // make sure the user_id is set
        $.any.rest.user.id = user_id;
        
        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'));
                       });

    },

    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)
        {
        	location.href = "/"+$.any.rest.user.id;
        }
        if (self.options.goto_url)
        {
        	location.href = self.options.goto_url;
        }

        self.close(
            function () 
            { 
                // Publish the logged on status so other actions can pick up on this.
                self.publish('logged-on');
                if (self._inActionDialog())
                {
                    $(self.element).remove();
                }
            });
            
    }
        
});

//



