//
/**
 * Javascript code for the register action
 */
$.any.ui.action.js('register',
{
	init: function ()
    {
        var self = this;
		self.options['require_logon'] = false;
		self.user = {};
    },
    
    callRegister: function (opt, form)
    {   
        var self = this;
        var data = form.getData();

		if (data.goto_profile)
		{
			self.options.gotoprofile = true;
		}
        if(data.goto_next)
    	{
        	self.options.goto_url = data.goto_next;
    	}
        if(data.go_wizard)
        {
        	self.options.goWizard = 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('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)
						    		  {
						    	  		if(self.options.goWizard)
						    	  		{
							    	  		self.subscribe('wizard_complete', 
							    	  				   function(event, source, data)
									                   {
							    	  					   if(source.thing.kind == "PERSON" && source.thing.type.symbolic[0] == "__USER__")
                                                           {
							    	  						   source.doRedirect = false;
							    	  						   self.finish();
							    	  					   }
									                   });
							    	        if(self.options.register_for_external_party)
							    	    	{
							    	        	self.switchAction('add', false, 'callStart', {thg_id: $.any.rest.user.id, kind: 'PERSON', type: '__USER__', variant: 'register_for_external_party', step: 1}); // step one to overcome race condition problems in js.	
							    	    	}
							    	        else
							    	        {
												self.switchAction('add', false, 'callStart', {thg_id: $.any.rest.user.id, kind: 'PERSON', type: '__USER__', step: 1}); // step one to overcome race condition problems in js.
							    	        }
						    	  		}
						    	  		else
						    	  		{
						    	  			self.renderStage('complete');
						    	  		}
						    		  }
						      );
	                      }
	                      // Simple register flow. User does not want a visible profile
						  else
						  {
						      self.createUser(false,
	                        				function (result)
					                        {
										      self.renderStage('simple_complete');
	            				            });
	                      }
					  }
					  else
					  {
						  form.setError('email', 'A user with this email is already registered', true);
					  }
				  });
	},
    
    
    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');

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


    /**
     * callCancel: just close the dialog when cancelling logon/register flow.
     */
    callCancel: function ( vars )
    {
        var self = this;
        if (self.options.register_for_external_party)
        {
            history.go(-1);
        }
        else
        {
            $.any.dialog.close();
        }
    },

	callFinish: function (opt)
	{
	    this.finish();
	},

    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.goto_url)
        {
        	window.location.href = self.options.goto_url;
            return;
        }
        if (self.options.gotoprofile)
        {
        	window.location.href = "/"+$.any.rest.user.id;
            return;
        }
        
        if (self.options.logonpage)
        {
            window.location.href = '/?logon=' + $.any.rest.user.id;
            return;
        }
        self.close(
            function () 
            { 
                if (self._openedInDialog())
                {
                    self.element.remove();    
                }
                self.publish('logged-on');
            });
    },
	
    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();
                           }
                       });

    }
	
});

/**
 * 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', '');
		    });
	},

    /**
     * callCancel: just close the dialog when cancelling logon/register flow.
     */
    callCancel: function ( vars )
    {
        $.any.dialog.close();
    },
	
    callFinish: function (opt)
    {
        this.finish();
    },

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

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

	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;
        }
        

        self.close(
            function () 
            { 
                if (self._openedInDialog())
                {
                    self.element.remove();    
                }
                
                self.publish('logged-on');
            });
    }
        
});

//
