/**
 * Usage:
 * - 
 * Required fields in the page:
 * element with id = this.id + registrationFields that contains input and select elements in it's child hierarchy.
				   Each input and select value will be added as an account parameter incase the id does not start with "DONT_SEND"
				   The input and select element id's will be used as such to name the corresponding account parameter.
 * element with id = this.id + inviteFriendsEmails. A comma separated list of recipients for invitation mail
 * element with id = this.id + inviteFriendsName. Element's value is used as the sender name
 */

					

/** */
var ACCOUNT_ACTIVATION_MESSAGE_TYPE="text/plain";

/** */
RegistrationWidget.prototype.signupCommands = null;
/** */
RegistrationWidget.prototype.createAccountCommand = null;
/** */
RegistrationWidget.prototype.createProfileCommand = null;
/** */
RegistrationWidget.prototype.activationEmailCommand = null;
/** */
RegistrationWidget.prototype.accountId = null;
/** */
RegistrationWidget.prototype.login = null;
/** */
RegistrationWidget.prototype.email = null;
/** */
RegistrationWidget.prototype.password = null;
/** */
RegistrationWidget.prototype.showContactUsInAccountActivationMessage = null;


/** */
function RegistrationWidget(id,domContainer,parentWidget){
    //
    //
    RegistrationWidget.prototype.superClass.constructor.call(this,id,domContainer,parentWidget);
    //
    //
    this.accountParameters	=	null;
    this.events.registrationComplete=new Delegate();
}
//
//
copyPrototype(RegistrationWidget,Widget);
//
//
RegistrationWidget.prototype.superClass=Widget.prototype;

/** 
 * Handler for register button clicked
 */
RegistrationWidget.prototype.registerButtonClicked = function(){
    //
    //
    var accountDataOK = this.initializeAccountData();
    var profileDataOK = this.initializeProfileData();
    if(true==accountDataOK && true==profileDataOK) {
        var registerOK = this.completeRegistration();
        if(true == registerOK) {
            this.sendActivationEmail();
        }
    }
}

/** 
 * @return true for success
 */
RegistrationWidget.prototype.initializeAccountData = function() {
    //
    //
    var retValue = false;
    //
    //
    var preCondition = false;
   
    //
    //
    this.accountParameters = getAccountParamsToSubmit( document.getElementById(this.id+"_registrationFields") ,this.id+"_");
    //
    //
    var tcsAccepted = this.accountParameters.accountParamsHashtable.getEntry("ACCEPT_TCS");
    this.accountId = randomUUID();
    this.accountParameters.accountParamsHashtable.putEntry("ACCOUNT_ID", this.accountId);
    var accountIdParameterAsArray = new Array();
    accountIdParameterAsArray[0] = "ACCOUNT_ID";
    accountIdParameterAsArray[1] = this.accountId;
    this.accountParameters.accountParamsArray[this.accountParameters.accountParamsArray.length] = accountIdParameterAsArray;
    //
    //
    var principalName = this.accountParameters.accountParamsHashtable.getEntry("primaryPrincipal"); 
    if(principalName) {
        if(caseSensitivePrincipalName==false){
        	principalName=principalName.toLowerCase();
        	this.accountParameters.accountParamsHashtable.putEntry("primaryPrincipal",principalName);
        	for (var i=0; i<this.accountParameters.accountParamsArray.length; i++){
		    	if(this.accountParameters.accountParamsArray[i][0] && this.accountParameters.accountParamsArray[i][0]=="primaryPrincipal"){
		    		this.accountParameters.accountParamsArray[i][1]=principalName;
		    		break;
		    	}
		    }
        }
        this.login = principalName;
    }
    var password = this.accountParameters.accountParamsHashtable.getEntry("PASSWORD");
    this.password = password;
    var passwordConfirmed = this.accountParameters.accountParamsHashtable.getEntry("PASSWORD_CONFIRMED");
    var email = this.accountParameters.accountParamsHashtable.getEntry("EMAIL");
    this.email = email;
    var dob = this.accountParameters.accountParamsHashtable.getEntry("DOB");
    var country = this.accountParameters.accountParamsHashtable.getEntry("COUNTRY");
    //
    //
    var errMsg = "Sorry, you cannot sign up because:\r\n";
    preCondition = true;
    /*
    if(tcsAccepted && tcsAccepted=="true") {
        preCondition = true;
        errMsg = "Sorry, you cannot sign up because:\r\n";
        var d=document.getElementById(this.id+"_ACCEPT_TCS");
    	if(d){
    		var s=d.className;
    		s=s.replace(/error/g,"");
    		d.className=s;
    	}
    }
    else{
    	errMsg = "Sorry, you cannot sign up because:\r\n- You must accept terms and conditions!\r\n";
    	var d=document.getElementById(this.id+"_ACCEPT_TCS");
    	if(d){
    		d.className+=" error";
    	}
    	
    }
    */
    var reservedIdUsed=false;
    for(var i=0; i<RESERVED_ACCOUNT_IDS.length; i++){
        if(principalName.indexOf(RESERVED_ACCOUNT_IDS[i])!=-1){
            preCondition = false;
            errMsg += "- The selected user name is not allowed!\r\n";
            break;
        }
    }
    if(reservedIdUsed==false){
    	var d=document.getElementById(this.id+"_primaryPrincipal");
    	if(d){
    		var s=d.className;
    		s=s.replace(/error/g,"");
    		d.className=s;
    	}
    }
    else{
    	var d=document.getElementById(this.id+"_primaryPrincipal");
    	if(d){
    		var s=d.className;
    		s=s.replace(/error/g,"");
    		d.className=s;
    	}
    }
    /*
     * Validation for password, email, firstName and lastName.
     * firstName and lastName validated with STRING_REG_EX, for now.
     */
    if(password!=passwordConfirmed) {
        preCondition = false;
        errMsg += "- Passwords do not match!\r\n";
        var d=document.getElementById(this.id+"_PASSWORD");
        var d2=document.getElementById(this.id+"_PASSWORD_CONFIRMED");
    	if(d){
    		d.className+=" error";
    	}
    	if(d2){
    		d2.className+=" error";
    	}
    }
    else{
    	var d=document.getElementById(this.id+"_PASSWORD");
        var d2=document.getElementById(this.id+"_PASSWORD_CONFIRMED");
    	if(d){
    		var s=d.className;
    		s=s.replace(/error/g,"");
    		d.className=s;
    	}
    	if(d2){
    		var s=d.className;
    		s=s.replace(/error/g,"");
    		d.className=s;
    	}
    }
    if(validateEmail(email)==false) {
        preCondition = false;
        errMsg += "- The email address does not qualify!\r\n";
        var d=document.getElementById(this.id+"_EMAIL");
    	if(d){
    		d.className+=" error";
    	}
    }
    else{
    	var d=document.getElementById(this.id+"_EMAIL");
    	if(d){
    		var s=d.className;
    		s=s.replace(/error/g,"");
    		d.className=s;
    	}
    }
    /*
    var dobErrMessage = validateDateOfBirth(dob);
    if(dobErrMessage){
        preCondition = false;
        errMsg += dobErrMessage;
    	var d_m=document.getElementById(this.id+"_DONT_SEND_DOB_MONTH");
    	var d_y=document.getElementById(this.id+"_DONT_SEND_DOB_YEAR");
    	var d_d=document.getElementById(this.id+"_DONT_SEND_DOB_DAY");
    	if(d_m){
    		d_m.className+=" error";
    	}
    	if(d_y){
    		d_y.className+=" error";
    	}
    	if(d_d){
    		d_d.className+=" error";
    	}
    }
    else{
    	var d_m=document.getElementById(this.id+"_DONT_SEND_DOB_MONTH");
    	var d_y=document.getElementById(this.id+"_DONT_SEND_DOB_YEAR");
    	var d_d=document.getElementById(this.id+"_DONT_SEND_DOB_DAY");
    	if(d_m){
    		var s=d_m.className;
    		s=s.replace(/error/g,"");
    		d_m.className=s;
    	}
    	if(d_y){
    		var s=d_y.className;
    		s=s.replace(/error/g,"");
    		d_y.className=s;
    	}
    	if(d_d){
    		var s=d_d.className;
    		s=s.replace(/error/g,"");
    		d_d.className=s;
    	}
    }*/
    /*
    if(country==-1){
        preCondition = false;
        errMsg += "- You must enter your country!\r\n";
    	var d=document.getElementById(this.id+"_COUNTRY");
    	if(d){
    		
    		d.className+=" error";
    	}
    }
    else{
    	var d=document.getElementById(this.id+"_COUNTRY");
    	if(d){
    		var s=d.className;
    		s=s.replace(/error/g,"");
    		d.className=s;
    	}
    }
    */
    if(preCondition==true) {
    	var d=document.getElementById(this.id+"_DONT_SEND_ERROR_INFO");
    	if(d){
    		d.className+=" hidden";
    		d.innerHTML="";
    	}
        //
        //
        var argsArray = new Array();
        argsArray[argsArray.length] = this.accountParameters.accountParamsArray;
        //
        // old code:
        //argsArray[argsArray.length] = this.signupHandler;
        //createAccount.apply(this, argsArray);
        //
        // new code:
        this.createAccountCommand = getCreateAccountCommand(this.accountParameters.accountParamsArray);        
        retValue = true;
    }
    else {
    	var d=document.getElementById(this.id+"_DONT_SEND_ERROR_INFO");
    	if(d){
    		var s=d.className;
    		s=s.replace(/hidden/g,"");
    		d.className=s;
    		d.innerHTML=errMsg;
    	}
    	else{
	        alert(errMsg);
	    }
    }
    //
    //
    return retValue;
}

/** 
 * @return true for success
 */
RegistrationWidget.prototype.initializeProfileData = function(){
    //
    //
    var retValue = false;
    //
    // get registered params
    var principalName = this.accountParameters.accountParamsHashtable.getEntry("primaryPrincipal"); 
    if(principalName) {
    	if(caseSensitivePrincipalName==false){
	        principalName=principalName.toLowerCase();
	        this.accountParameters.accountParamsHashtable.putEntry("primaryPrincipal",principalName);
	    }
    }
    var gender = this.accountParameters.accountParamsHashtable.getEntry("GENDER"); 
    if(!gender) {
        gender="undefined";
    }
    var dob = this.accountParameters.accountParamsHashtable.getEntry("DOB");
    var email = this.accountParameters.accountParamsHashtable.getEntry("EMAIL");
    var mobilePhone = this.accountParameters.accountParamsHashtable.getEntry("MOBILE_PHONE");
    var firstName = this.accountParameters.accountParamsHashtable.getEntry("FIRST_NAME");
    var lastName = this.accountParameters.accountParamsHashtable.getEntry("LAST_NAME");
    var country = this.accountParameters.accountParamsHashtable.getEntry("COUNTRY");
    var city = this.accountParameters.accountParamsHashtable.getEntry("CITY");
    var postalCode = this.accountParameters.accountParamsHashtable.getEntry("POSTAL_CODE");
    var state = this.accountParameters.accountParamsHashtable.getEntry("STATE");
    var displayName = this.accountParameters.accountParamsHashtable.getEntry("DISPLAY_NAME");
    if(!displayName){
        displayName = firstName + " " + lastName;
    }
    //
    // profile basic data
    var primaryProfileData = new Properties();
    primaryProfileData.setParametersAreEncoded(true);
    primaryProfileData.setRootElementName("PROFILE");
    primaryProfileData.setValue("DISPLAY_NAME", displayName);
    primaryProfileData.setValue("SHORT_NAME", principalName);
    primaryProfileData.setValue("IS_PUBLIC", "true");
    primaryProfileData.setValue("GENDER", gender);
    primaryProfileData.setValue("IMG_URL", "undefined");
    primaryProfileData.setValue("BIRTHDAY", dob);
    var profileId = randomUUID();
    primaryProfileData.setValue("PROFILE_ID", profileId);
    primaryProfileData.setValue("ACCOUNT_ID", this.accountId);
    //
    // contacts entry initialization		
    // 1. create the top level contact props
    var contactProperties = new ContactProperties();
    contactProperties.basic.setParametersAreEncoded(true);
    contactProperties.basic.setRootElementName("BASIC");
    contactProperties.basic.setValue("FORMATTED_NAME", firstName + " " + lastName);
    contactProperties.basic.setValue("FAMILY_NAME", lastName);
    contactProperties.basic.setValue("GIVEN_NAME", firstName);
    contactProperties.basic.setValue("PROFILE_ID", profileId);
    var contactDetailsID=randomUUID();
    contactProperties.basic.setValue("CONTACT_DETAILS_ID", contactDetailsID);
    //
    // 2. email fields initialied by the primary email registered by
    var emailEntryProps = new Properties();
    emailEntryProps.setParametersAreEncoded(true);
    emailEntryProps.setRootElementName("EMAIL_ADDRESS");
    emailEntryProps.setValue("EMAIL", email);
    emailEntryProps.setValue("IS_PREFERED", "true");
    emailEntryProps.setValue("CONTACT_DETAILS_ID", contactDetailsID);
    var emailID=randomUUID();
    emailEntryProps.setValue("EMAIL_ADDRESS_ID", emailID);
    contactProperties.emails.putEntry(email, emailEntryProps);
    //
    //
    if(mobilePhone) {
        contactProperties.mobilePhone.setRootElementName("TELEPHONE_NUMBER");
        contactProperties.mobilePhone.setValue("VALUE", mobilePhone);
        contactProperties.mobilePhone.setValue("IS_PREFERED", "true");
        contactProperties.mobilePhone.setValue("CONTACT_DETAILS_ID", contactDetailsID);
        var mobileID=randomUUID();
        contactProperties.mobilePhone.setValue("TELEPHONE_NUMBER_ID", mobileID);
        contactProperties.mobilePhone.setValue("TELEPHONE_NUMBER_TYPE", "4");
    }
    //
    // 3. postal props initialized with country asked in reg form
    contactProperties.postalAddress.setParametersAreEncoded(true);
    contactProperties.postalAddress.setRootElementName("POSTAL_ADDRESS");
    contactProperties.postalAddress.setValue("CONTACT_DETAILS_ID", contactDetailsID);
    var postalID=randomUUID();
    contactProperties.postalAddress.setValue("POSTAL_ADDRESS_ID", postalID);
    if(country){
        contactProperties.postalAddress.setValue("COUNTRY", country);
    }
    if(city){
        contactProperties.postalAddress.setValue("CITY", city);
    }
    if(state){
        contactProperties.postalAddress.setValue("STATE", state);
    }
    if(postalCode){
        contactProperties.postalAddress.setValue("POSTAL_CODE", postalCode);
    }
    //
    //		
    var profileGroup = this.accountParameters.accountParamsHashtable.getEntry("GROUP");
    //
    // old code:
    //createOrUpdateProfile.call(this, profileId, primaryProfileData, contactProperties, null,profileGroup, this.createOrUpdateHandler);
    //
    // new code:
    this.createProfileCommand = getCreateOrUpdateProfileCommand.call(this, profileId, primaryProfileData, contactProperties, null, profileGroup);
    retValue = true;
    //
    //
    return retValue;
}

/** 
 * @return true for success
 */
RegistrationWidget.prototype.completeRegistration = function(){
    //
    //
    var retValue = false;
    var cmdXML = this.compileSignupCommands();
    var createResult = multipleCommandRequest(cmdXML, 2);
    if(createResult==true) {
        //
        //
        retValue = true;
        //
        //
        var evtobj=new Object();
        evtobj.type	=	"registrationComplete";
        evtobj.code	=	0;
        evtobj.login	=	this.login;
        evtobj.password	=	this.password;
        this.events.registrationComplete.fireEvent(this, evtobj);
    }
    else {
        var evtobj=new Object();
        evtobj.type	=	"registrationComplete";
        evtobj.code	=	-1;
        if(createResult!=null && createResult instanceof Array && createResult.length>0 && createResult[0] && createResult[0].message) {
          evtobj.message	=	"Sign Up failed due to following error(s): \r\n" + createResult[0].message;
        }
        this.events.registrationComplete.fireEvent(this,evtobj);
    }
    //
    //
    return retValue;
}

/** */
RegistrationWidget.prototype.sendActivationEmail = function(){
    //
    //
    var invalidateAccount=false;
    var aSender = getResourceString(this,"ACCOUNT_ACTIVATION_MESSAGE_SENDER");
    var aSubject = getResourceString(this,"ACCOUNT_ACTIVATION_SUBJECT");
    var functionToGenerateAccountActivationMessage = getResourceString(this,"ACCOUNT_ACTIVATION_MESSAGE_FUNCTION");
    var aMessage = functionToGenerateAccountActivationMessage(null, null, this.showContactUsInAccountActivationMessage);
    var aMimeType = getResourceString(this,"ACCOUNT_ACTIVATION_MESSAGE_TYPE");
    sendActivationEmailToNamedRecipient(invalidateAccount, this.login, aSender, aSubject, aMessage, aMimeType);
}

/** */
RegistrationWidget.prototype.compileSignupCommands = function(){
    var cmdXML = "<COMMANDS PROPAGATE=\"true\">";
    cmdXML += this.createAccountCommand;
    cmdXML += this.createProfileCommand;
    cmdXML += "</COMMANDS>";
    return cmdXML;
}

/** */
RegistrationWidget.prototype.registration_login_resultHandler=function(arg) {
    if(arg==LOGIN_FAILED) {
        alert("Debug message: Authentication registering process failed...");
    }
}

/** */
RegistrationWidget.prototype.createOrUpdateHandler=function(statusCode, dbgMessage, failureCode){
	
}
