// NOTE: This file depends on:
//       ajaxForm.js for PopupFormData
//       flash.js for getSWF()
var RegisterFormData = Class.create(PopupFormData, {
   // redefine the processSuccess method
   processSuccess: function($super, htmlText) {
      this.close();
	   var navTools = document.getElementById('nav_tools');
	   if (navTools) {
	      navTools.innerHTML = htmlText;
	   }
	   var swf = getCreatorLoaderSWF();
	
	   if (swf) {
	      swf.registerNotification();
	   }
   },
   // redefine the processError method
   processError: function($super, htmlText) {
      this.parseErrors(htmlText);
      var keys = this.errorHash.keys();
      if (keys && keys.length > 0) {
         clearTooltips();
         for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (key == "account.email") {
               updateTooltip('email_tip', 'error', this.errorHash.get(key));
            } else if (key == "repeatedNewEmail") {
               updateTooltip('repeatEmail_tip', 'error', this.errorHash.get(key));
               showElementAppearEffect('repeatEmail');
            } else if (key == "account.password") {
               updateTooltip('password_tip', 'error', this.errorHash.get(key));
            } else if (key == "repeatedPassword") {
               updateTooltip('repeatPassword_tip', 'error', this.errorHash.get(key));
               showElementAppearEffect('repeatPassword');
            } else if (key == "account.username") {
               updateTooltip('username_tip', 'error', this.errorHash.get(key));
            } else if (key == "termsAgreed") {
               updateTooltip('termsAgreed_tip', 'error', this.errorHash.get(key));
            } else {
               logAjaxError(this.action, "AJAX ERROR: register.processError: UNKNOWN PROPERTY RECEIVED: " + key + ', value: ' + this.errorHash.get(key));
            }
            this.errorHash.unset(key);
         }
         this.updateStatus('');
         resetVisibility(this.formId);
      } else {
         $super(htmlText);
      }
   },
   // override the validateForm method
   validateForm: function($super) {
      var form = document.getElementById(this.formId);
      if (form) {
         if (form.termsAgreed.checked == false) {
            updateTooltip('termsAgreed_tip', 'error', 'You must agree with our Terms of Service to use our web site');
            return false;
         }
	 
	 var usernameField = document.getElementById('account.username');
	 if (usernameField) {
            var username = usernameField.value;
	    var usernamePat = /^[a-zA-Z0-9_]*$/;
	    var matchArray = username.match(usernamePat)
	    if (matchArray==null) {
               updateTooltip('username_tip', 'error', 'Only letters, digits or \'_\' allowed.');
	       usernameField.focus();
               return false;
	    }
	 }
      }
      return true;
   }
});


var curRegSelection;

function clearTooltips() {
	resetTooltip('email_tip');
	resetTooltip('repeatEmail_tip');
	resetTooltip('password_tip');
	resetTooltip('repeatPassword_tip');
	resetTooltip('username_tip');
	resetTooltip('termsAgreed_tip');
}

function initRegisterForm() {
   hideElement('repeatEmail');
   hideElement('repeatPassword');
   curRegSelection = '';
}

function usernameSelected() {
   hideRepeatEmail();
   hideRepeatPassword();
   curRegSelection = 'username';
}

function checkUsername(blur) {
   var pattern = /^[a-zA-Z0-9_]*$/;
   var elem = document.getElementById('account.username');
   if (elem) {
      var value = elem.value;
      if (!value.match(pattern)) {
         updateTooltip('username_tip', 'error', 'Only letters, digits or \'_\' allowed.');
      } else if (blur && value == '') {
         updateTooltip('username_tip', 'error', 'Required.');
      } else {
         updateTooltip('username_tip', 'info', '');
      }
   }
}

function emailSelected() {
   if (curRegSelection != 'email') {
      showElementAppearEffect('repeatEmail');
      hideRepeatPassword();
      curRegSelection = 'email';
      checkEmail(false);
   }
}

function checkEmail(blur) {
   var elem = document.getElementById('account.email');
   var repeat = document.getElementById('repeatedNewEmail');
   if (repeat && (repeat.value != '')) {
      checkRepeatEmail(false);
   }
   if (elem.value == '') {
      if (blur) {
         updateTooltip('email_tip', 'error', 'Required.');
      } else {
         updateTooltip('email_tip', 'info', 'Must be valid');
      }
   }
}

function validateEmail() {
   var elem = document.getElementById('account.email');
   if (elem) {
      var value = elem.value;
      if (value == '') {
         updateTooltip('email_tip', 'info', 'Must be valid');
      } else if (!isEmailValid(value)) {
         updateTooltip('email_tip', 'error', emailError);
      } else {
         updateTooltip('email_tip', 'success', 'OK');
      }
      var repeat = document.getElementById('repeatedNewEmail');
      if (repeat && repeat.value != '') {
         checkRepeatEmail(false);
      }
   }
}

function repeatEmailSelected() {
   curRegSelection = 'email';
   checkRepeatEmail(false);
}

function checkRepeatEmail(blur) {
   var elem = document.getElementById('account.email');
   var repeat = document.getElementById('repeatedNewEmail');
   if (elem && repeat) {
      var value = repeat.value;
      if (value == '') {
         if (!blur) {
            updateTooltip('repeatEmail_tip', 'info', 'Must match');
         } else {
            updateTooltip('repeatEmail_tip', 'error', 'Required');
         }
      } else if (value != elem.value) {
         updateTooltip('repeatEmail_tip', 'error', 'Does not match');
      } else {
         updateTooltip('repeatEmail_tip', 'success', 'OK');
      }
   }
}

function passwordSelected() {
   if (curRegSelection != 'password') {
      showElementAppearEffect('repeatPassword');
      hideRepeatEmail();
      curRegSelection = 'password';
      checkPassword(false);
   }
}

function checkPassword(blur) {
   var elem = document.getElementById('account.password');
   if (elem) {
      var value = elem.value;
      if (value == '') {
         if (blur) {
            updateTooltip('password_tip', 'error', 'Required.');
         } else {
            updateTooltip('password_tip', 'info', 'At least 6 characters');
         }
      } else if (value.length < 6) {
         updateTooltip('password_tip', 'error', 'At least 6 characters');
      } else if (value.length > 20) {
         updateTooltip('password_tip', 'error', 'At most 20 characters');
      } else {
         updateTooltip('password_tip', 'success', 'OK');
      }
      var repeat = document.getElementById('repeatedPassword');
      if (repeat && repeat.value != '') {
         checkRepeatPassword(false);
      }
   }
}

function repeatPasswordSelected() {
   curRegSelection = 'password';
   checkRepeatPassword(false);
}

function checkRepeatPassword(blur) {
   var elem = document.getElementById('account.password');
   var repeat = document.getElementById('repeatedPassword');
   if (elem && repeat) {
      var value = repeat.value;
      if (value == '') {
         if (!blur) {
            updateTooltip('repeatPassword_tip', 'info', 'Must match');
         } else {
            updateTooltip('repeatPassword_tip', 'error', 'Required');
         }
      } else if (value != elem.value) {
         updateTooltip('repeatPassword_tip', 'error', 'Does not match');
      } else {
         updateTooltip('repeatPassword_tip', 'success', 'OK');
      }
   }
}

function termsSelected() {
   hideRepeatEmail();
   hideRepeatPassword();
   curRegSelection = 'terms';
}

function hideRepeatEmail() {
   var elem = document.getElementById('repeatEmail_tip');
   if (elem && elem.className != 'error') {
      hideElementFadeEffect('repeatEmail');
   }
}

function hideRepeatPassword() {
   var elem = document.getElementById('repeatPassword_tip');
   if (elem && elem.className != 'error') {
      hideElementFadeEffect('repeatPassword');
   }
}

function updateTooltip(elemId, type, text) {
   var elem = document.getElementById(elemId);
   if (elem) {
      elem.className = type;
      elem.innerHTML = text;
   }
}

function resetTooltip(elemId) {
   var elem = document.getElementById(elemId);
   if (elem && (elem.className == 'error')) {
      elem.className = 'info';
      elem.innerHTML = '';
   }
}

function showRegisterForm() {
   var swf = getCreatorLoaderSWF();

   if (swf) {
      swf.flashRegister();
   } else {
      logAjaxError("showRegisterForm", "AJAX ERROR: showRegisterForm: UNABLE TO FIND CreatorLoader SWF");
   }
}

function validateUsername(username) {
   var usernamePat = /^[a-zA-Z0-9_]*$/;
   var matchArray = username.match(usernamePat)
   if (matchArray==null) {
      return false;
   }
   return true;
}

function validateEmail(emailStr) {
   return isEmailValid(emailStr);
}

function getEmailError(emailStr) {
   return emailError;
}

var emailError;
/**
 * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com),
 * http://javascript.internet.com
 */
function isEmailValid (emailStr) {
	if (emailStr==null) {
	   return false;
	}
        /* The following pattern is used to check if the entered e-mail address
	   fits the user@domain format.  It also is used to separate the username
	   from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	   characters.  We don't want to allow special characters in the address. 
	   These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
	   username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	   which case, there are no rules about which characters are allowed
	   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	   is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	   e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	   non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
	   Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	
	
	/* Finally, let's start trying to figure out if the supplied address is
	   valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
	     even fit the general mould of a valid e-mail address. */
	   emailError = "Invalid address. Check @ and .'s";
//		alert("Email address seems incorrect (check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {
	    // user is not valid
	    emailError = "Invalid address. Check your username";
//	    alert("The username doesn't seem to be valid.")
	    return false
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	    // this is an IP address
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        emailError = "Invalid address. Check your IP address";
//		        alert("Destination IP address is invalid!")
			return false
		    }
	    }
	    return true
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
	    emailError = "Invalid domain name!";
//		alert("The domain name doesn't seem to be valid.")
	    return false
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding 
	   the domain or country. */
	
	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	    emailError = "Invalid domain name!";
//	   alert("The address must end in a three-letter domain, or two letter country.")
	   return false
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   emailError = "Hostname missing!"
//	   var errStr="This address is missing a hostname!"
//	   alert(errStr)
	   return false
	}
	
	// If we've gotten this far, everything's valid!
	return true;
}

