if (!window.ccs) {
   window.ccs = {};
}
 

ccs.Registration = function() {
   var self;
   var regModalBoxWidth;
   var regModalBoxTop;
   var primaryGroup;
   var otherGroups;
   var active; //Will the user be created active inactive?

   //var postRegisterPage; // Non needed for modal box (i reckon), but for a page when you want to say "click here to continute browsing" on the thankyou page.    //Impis can just put this link on the page..
   var usePage; // If a div with id 'registrationFormDiv' is placed on the page, then this will be used instead of modalbox.
   var activationLink;
   var registrationEnabled;

   function constructorFn() {
      self = this;
      active = false; //leave me

      Event.observe(window, 'load', function() {
         if ($('registrationFormDiv') != null) { //Div must be on page IF you want to have it old school, instead of modalbox. It allows for the div to be placed anywhere and not be constrained by this modlet.
            usePage = true;
            $('registrationLink').style.display='none'; //We don't need this if the form is loading automatically on this page!
            self.loadForm();
         } else {
            usePage = false;
         }
      });

   }

   constructorFn.prototype.isRegistrationEnabled = function() {
      if (registrationEnabled == true) {
         return true;
      } else {
         return false;
      }
   }

   constructorFn.prototype.setVar = function(name, value) {
      val = value + ""; //convert to string (may be boolean)
      if (val == "true" || val == "false") {
         eval(name + " = " + value + "");
      } else {
         value = value.replace(/'/g, "\\'");
         eval(name + " = '" + value + "'");
      }
   }

   constructorFn.prototype.hasLoginStatusBeenEstablished = function() {
      return loginStatusEstablished;
   }

   constructorFn.prototype.loadScript = function() {
      var url = ccs.contextPath + '/modletInclude/login_form/js/validation.js';

      var e = document.createElement("script");
      e.src = url;
      e.type = "text/javascript";
      document.getElementsByTagName("head")[0].appendChild(e);


   }

   constructorFn.prototype.loadForm = function() {
        self.loadScript();
        var delay = 0;
        if (ccs.login.isActive || $('MB_window') != null) {
            Modalbox.hide();
            ccs.login.setActive(false);
            delay=1000; //Allows the modalbox to close properly, before being reopened, else it gets into a funny state and modalboxes won't show anymore.
        }
        setTimeout(function() {
            var url = ccs.contextPath + '/shared/content/schemes/invokeScheme.jsp?objectTypeName=user profile&schemeName=registration&oid=-1&rnd=' + Math.random();
            self.setContents(url);
        }, delay);
   }
   constructorFn.prototype.submitForm = function(isUpdate) { //isUpdate, as opposed to when registering.

      //Call the normal submitEditForm, but pass it a callback function so it doesn't do a regular submit.
      submitEditForm(null, null, $('editForm'), function() {
         var parameters = Form.serializeElements(Form.getElements(document.forms['editForm']), true);
         parameters['uuid'] = ccs.login.uuid;
         var url = ccs.contextPath + '/shared/content/schemes/processScheme.jsp'
         new Ajax.Request(url, {
            parameters: parameters,
            onSuccess: function(transport) {
               var response = transport.responseText || "no response text";


               var json = eval('(' + response + ')');

               //We do the folling, incase an ajax form such as the registration, is opened on a page with an editform and conflicting objectid ids.
               var objectId = json.objectid;


               var objectIdElms = document.getElementsByName("objectid");
               var correctObjectIdElm;
               for (var i = 0; i < objectIdElms.length; i++) {
                  var ajax = objectIdElms[i].getAttribute("ajax");
                  if (ajax == "true") {
                     correctObjectIdElm = objectIdElms[i];
                  }
               }
               correctObjectIdElm.value = objectId;
               if (isUpdate) {
                  self.profileUpdated();
               } else {
                  self.thankYou();
               }
               self.stopSpinner();
            },
            onFailure: function() {
               alert('Something went wrong...');
               self.startSpinner();
            }
         });
      });

   }
   constructorFn.prototype.createUser = function() { //Because we want this ajax submitting feature to be generic, we don't submit everything together. The user is created in this call, then the the user profile id is returned, set as the objectId and then posted.. 

      if (ccsValidation($('editForm'))!=true) {
         return; //We have to ensure the user profile portion of the registration form is in order before creating the user!
      }

      //Username and email address validation will be done server side. An exception will be thrown by createUser.jsp which will alert the user.



      //Get all the variables and do some basic validation.
      var username = $('u_username').value;
      var password = $('u_password').value;
      var email = $('u_email').value;
      var firstName = $(firstNameAttributeId).value;


      var validated = true;
      if (!username || username.length == 0) {
         validated = false;
         alert("JS: Username is blank!")
      }
      if (!password || password.length == 0) {
         password = false;
         alert("JS: Password is blank!")
      }
      if (!email || email.length == 0) {
         validated = false;
         alert("JS: Email is blank!")
      }
      if (!primaryGroup || primaryGroup.length == 0) {
         validated = false;
         alert("JS: No Primary Group has been set!")
      }

      self.startSpinner();
      if (validated) {
         var parameters = new Object();
         parameters['first_name'] = firstName;
         parameters['username'] = username;
         parameters['password'] = password
         parameters['email'] = email;
         parameters['primary_group'] = primaryGroup;
         parameters['other_groups'] = otherGroups;
         parameters['active'] = active;
         parameters['from_address'] = ccs.login.fromAddress;
         parameters['activation_link'] = activationLink;

         var url = ccs.contextPath + '/json/' + ccs.appName + '/' + ccs.languageCode + '/modules/login_form/registration.createUser.json'
         new Ajax.Request(url, {
            parameters: parameters,
            onSuccess: function(transport) {
               var response = transport.responseText || "no response text";
               var json = eval('(' + response + ')');

               var success = json.success;
               var result = json.result;
               var userProfileObjectId;
               if (success == "true") {
                  ccs.login.upId = result.split(".")[0];
                  ccs.login.uuid = result.split(".")[1];
               } else {
                  alert(result);
                  self.stopSpinner();
                  return; // <---Early return, an error occured.

               }


               //We do the folling, incase an ajax form such as the registration, is opened on a page with an editform and conflicting objectid ids.
               var objectIdElms = document.getElementsByName("objectid");
               var correctObjectIdElm;
               for (var i = 0; i < objectIdElms.length; i++) {
                  var ajax = objectIdElms[i].getAttribute("ajax");
                  if (ajax == "true") {
                     correctObjectIdElm = objectIdElms[i];
                  }
               }
               correctObjectIdElm.value = ccs.login.upId;

               self.submitForm();

            },
            onFailure: function() {
               alert('Something went wrong...');
               self.stopSpinner();
            }
         });
      } else {
         self.stopSpinner();
      }
   }

   constructorFn.prototype.saveCredentials = function(mustSaveProfileNext) { //Because we want this ajax submitting feature to be generic, we don't submit everything together. The user is created in this call, then the the user profile id is returned, set as the objectId and then posted..
      if (ccsValidation($('editForm'))!=true) {
         return; //We have to ensure the user profile portion of the registration form is in order before creating the user!
      }
      
      
      var validated = true;
      var password = $('u_password').value;
      var password_conf = $('u_password_confirm').value;
      var email = $('u_email').value;
      var email_conf = $('u_email_confirm').value;
      if (password!=password_conf) {
         validated=false;
         alert("Your passwords do not match");
      }
      if (email!=email_conf) {
         validated=false;
         alert("Your email addresses do not match");
      }

      self.startSpinner();
      if (validated) {
         var parameters = new Object();
         parameters['password'] = password
         parameters['email'] = email;

         var url = ccs.contextPath + '/json/' + ccs.appName + '/' + ccs.languageCode + '/modules/login_form/registration.updateCredentials.json'
         new Ajax.Request(url, {
            parameters: parameters,
            onSuccess: function(transport) {
               var response = transport.responseText || "no response text";
               var json = eval('(' + response + ')');
               var success = json.status;

               if (success == "true") {
	               if (mustSaveProfileNext) {
                  		self.submitForm(true);
              		} else {
	              		self.profileUpdated();
              		}

               } else {
                  alert(json.message);
                  self.stopSpinner();
                  return; // <---Early return, an error occured.

               }

            },
            onFailure: function() {
               alert('Something went wrong...');
               self.stopSpinner();
            }
         });
      } else {
         self.stopSpinner();
      }
   }

   constructorFn.prototype.activateUser = function(activationCode) {
      var parameters = new Object();
      parameters['activationCode'] = activationCode;
      parameters['fromAddress'] = ccs.login.fromAddress;
      self.startSpinner();
      var url = ccs.contextPath + '/json/' + ccs.appName + '/' + ccs.languageCode + '/modules/login_form/registration.activateUser.json'
      new Ajax.Request(url, {
         parameters: parameters,
         onSuccess: function(transport) {
            var response = transport.responseText || "no response text";
            var json = eval('(' + response + ')');
            var result = json.result;
            if (result != "true") {
               if ($('userMessage') != null) {
                  $('userMessage').innerHTML = "This account has already been activated, or you entered an invalid code.";
               } else {
                  alert(result);
               }
            } else {
               self.complete(activationCode);
            }
            self.stopSpinner();
         },
         onFailure: function() {
            alert('Something went wrong...');
            self.stopSpinner();
         }
      });
   }


   constructorFn.prototype.thankYou = function() {
      var firstname = $(firstNameAttributeId).value;
      var email = $('u_email').value;
      var url = 'thankyou.jsp?email=' + email + "&firstname=" + firstname + '&use_page=' + usePage + '&post_register_page='; //Impis can just but the link into the html!
      self.setContents(url);
   }

   constructorFn.prototype.profileUpdated = function() {
      var firstname = $(firstNameAttributeId).value;
      var email = $('u_email').value;
      var url = 'profileUpdated.jsp';
      self.setContents(url);
   }

   constructorFn.prototype.complete = function(activationCode, success) {
      var url = 'complete.jsp?success=' + success + '&activation_code=' + activationCode + '&use_page=' + usePage + '&post_register_page=';
      self.setContents(url);
      ccs.login.getLoggedInUser();
   }

   constructorFn.prototype.updateProfile = function() {
      var upId = ccs.login.upId * 1;
      if (upId == -1) {
         alert("User Profile Id is -1!");
         return;
      }
      var url = ccs.contextPath + '/shared/content/schemes/invokeScheme.jsp?objectTypeName=user profile&schemeName=modify&uuid=' + ccs.login.uuid + '&oid=' + upId + '&rnd=' + Math.random();
      self.setContents(url);


   }

   constructorFn.prototype.resendActivationEmail = function() {
      var upId = ccs.login.upId * 1;
      if (upId == -1) {
         alert("User Profile Id is -1!");
         return;
      }
      var parameters = new Object();
      parameters['upId'] = upId;
      parameters['from_address'] = ccs.login.fromAddress;
      parameters['activation_link'] = activationLink;
      var url = ccs.contextPath + '/json/' + ccs.appName + '/' + ccs.languageCode + '/modules/login_form/registration.resendActivationEmail.json'
      new Ajax.Request(url, {
         parameters: parameters,
         onSuccess: function(transport) {
            var response = transport.responseText || "no response text";
            var json = eval('(' + response + ')');
            var success = json.success;
            var result = json.result;

            if (success == "true") {
               alert("A new email has been sent.")
            } else {
               alert(result);
               self.stopSpinner();
               return; // <---Early return, an error occured.

            }
            self.stopSpinner();
         },
         onFailure: function() {
            alert('Something went wrong...');
            self.stopSpinner();
         }
      });
   }

   constructorFn.prototype.setContents = function(url, callback) {
      var url = ccs.contextPath + '/modletInclude/login_form/jsp/frame.jsp?url=' + escape(url);
      if (!usePage) {
         Modalbox.show(url,
         {title: "", width: regModalBoxWidth * 1, afterLoad: function() {
            $('MB_window').style.top=regModalBoxTop;
            $('MB_content').innerHTML.evalScripts();

            if (callback) callback();
         }});

      } else {
         new Ajax.Request(url, {
            method:'get',
            onSuccess: function(transport) {
               var response = transport.responseText || "no response text";
               $('registrationFormDiv').innerHTML = response
               $('registrationFormDiv').innerHTML.evalScripts();
               if (callback) callback();
            },
            onFailure: function() {
               // alert('Something went wrong...')
            }
         });
      }
   }

   constructorFn.prototype.startSpinner = function() {
      if ($('regSpinner')) {
         $('regSpinner').style.display = "inline";
      }
   }


   constructorFn.prototype.stopSpinner = function() {
      if ($('regSpinner')) {
         $('regSpinner').style.display = "none";
      }
   }

   constructorFn.prototype.showModifyProfile = function() {
      $('modifyProfile').style.display = "block";
      $('modifyProfileTab').className = "modifyActive"
      $('modifyLogin').style.display = "none";
      $('modifyLoginTab').className = "modifyInactive";
   }

   constructorFn.prototype.showModifyLogin = function() {
      $('modifyProfile').style.display = "none";
      $('modifyProfileTab').className = "modifyInactive"
      $('modifyLogin').style.display = "block";
      $('modifyLoginTab').className = "modifyActive";
   }
   constructorFn.prototype.getActivationLink = function() {
      return activationLink;
   }


   return new constructorFn();
}


