// Method added onto the string constructor.  Allows for all strings to have the .trim() function
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

mydomain = location.host;
//mydomain = mydomain.replace(/www/,'');

// Object that holds all the files that need to be loaded and the methods to load those.
var loader = {
	loadCSS :function(){ /// Loads the CSS File
		cssName = "/wwwroot/Lib/login/login.css";
		document.write('<link rel="stylesheet" href="'+cssName+'">');	
	},
	loadPrototypeJS:function(){
		libraryName = "/wwwroot/Lib/prototype/1.6.1/prototype.js";
		document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
	},
	loadMD5JS:function(){ /// Loads the MD5 encryption functions
		libraryName = "/wwwroot/Lib/md5.js";
		document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
	},
	loadCSIToolsJS:function(){ /// Loads the CSI Tools Functions
		libraryName = "/wwwroot/remaint/js/CSITools.js";
		document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
	},
	loadPushForm:function(){
		libraryName = "/wwwroot/Lib/pushform/pushform.js";
		document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
	}
}

/// -------- Pre Loading ---------
loader.loadCSS();
if (!window.Prototype){
	loader.loadPrototypeJS();
}
loader.loadMD5JS();
loader.loadCSIToolsJS();
loader.loadPushForm();
/// -------- Pre Loading ---------


// Check the wiki for documentation on how to use this object
// http://wiki.comsoftinc.com/index.php/Login_Object

// Function used to pop up a window if something requires a login.  If the user is logged in, it will skip ahead to any onSuccess that is passed.
function requireLogin(obj){
	
	
	// If the login object doesn't exist, create it.
	if (!window.loginObj){
		loginObj = new createLogin(obj);
	} else {
		Object.extend(loginObj,obj);
	}

	// Check to see if the user is logged in.  If so, go ahead to their onSuccess.  Otherwise, pop up the menu.
	if (loginObj.isLoggedIn()){
		loginObj.onSuccess();	
	} else {
		loginObj.show(); 
	} 
}

// The Login constructor object.  Create a new CreateLogin will give you an object with all of the methods below
function createLogin(obj){
	
	// Sets the defaults for the passable parameters 
	this.parentElm = '';
	this.className = '';
	this.onSuccess = function (){}
	this.noLabel = true;
	this.createLink = true;
	
	// Extends the login object to add on any parameters passed to it in JSON/Object format. 
	Object.extend(this,obj);
	
	///  Create the form divs
	this.div = $(document.createElement("div"));
	this.loginForm = $(document.createElement("div"));
	this.loginForm.className = 'w_thisLoginForm';
	this.reqPassForm = $(document.createElement("div"));
	this.reqPassForm.className  = 'w_thisReqPassForm';
	this.loggedInMenu = $(document.createElement("div"));
	this.loggedOutMenu = $(document.createElement("div"));
	this.changePasswordMenu = $(document.createElement("div"));
	this.changePasswordMenu.className = 'w_thisChangePasswordMenu';
	this.errorRow = $(document.createElement("div"));
	this.errorRow.className = 'errorRow';
	///  Create the form divs

	// Sets the className for this.div.  This allows the programmer to pass any 
	// className (that's already defined in their css files) and make it apply to
	// this object
	// tim o'brien
	//if (this.parentElm.tagName > ''){
	if (this.parentElm && this.parentElm.tagName > ''){
		if (this.className > ''){
			this.div.className = this.className;
		} else {
			this.div.className = 'main';			
		}
	} else {
		if (this.className > ''){
			this.div.className = this.className;
		} else {
			this.div.className = 'pop';
		}
	}

	// This method is used to put the text into the various 
	// input boxes if NoLabel is true.
	this.insertInput = function(e){
		if (e.srcElement){
			elm = e.srcElement;			
		} else {
			elm = e.currentTarget;		
		}
		
		// Because you can't change an elements type in IE,
		// we just alternate between showing two different
		// input boxes with the types we want.
		// This only applies to input type=password		
		if (elm.value.length == 0){
			if (elm.className == 'resendEmail'){
				elm.value = 'Email';
			} else if (elm.className == 'loginUsername'){
				elm.value = 'Username';
			} else if (elm.className == 'loginPWordText' || elm.className == 'loginPWord'){
				this.pwordinput.style.display = 'none';
				this.pwordinputText.style.display = '';
				//this.pwordinputText.focus();
			}

			if (elm.className =='oldPassword'){
				this.oldPasswordInputText.style.display = '';
				this.oldPasswordInput.style.display = 'none';
			} else if (elm.className == 'newPassword') {
				this.newPasswordInputText.style.display = '';
				this.newPasswordInput.style.display = 'none';
			} else if (elm.className == 'confirmPassword') {
				this.confirmPasswordInputText.style.display = '';
				this.confirmPasswordInput.style.display = 'none';
			}
		}		
	}
	
	// This is the method to clear the text from the input boxes
	// if noLabel is true
	this.clearInput = function(e){
		if (e.srcElement){
			elm = e.srcElement;			
		} else {
			elm = e.currentTarget;		
		}

		// Because you can't change an elements type in IE,
		// we just alternate between showing two different
		// input boxes with the types we want.
		// This only applies to input type=password
		if (elm.value == 'Email' || elm.value == 'Password' || elm.value == 'Username'){
			if (elm.className == 'resendEmail' || elm.className == 'loginUsername'){
				elm.value = '';	
			} else if (elm.className == 'loginPWordText' || elm.className == 'loginPWord'){
				this.pwordinputText.style.display = 'none';
				this.pwordinput.style.display = '';
				this.pwordinput.focus();
			}
		}
		
		if (elm.value == 'Current Password' || elm.value == 'New Password'){
			if (elm.className =='oldPasswordText'){
				this.oldPasswordInputText.style.display = 'none';
				this.oldPasswordInput.style.display = '';
				this.oldPasswordInput.focus();
			} else if (elm.className == 'newPasswordText') {
				this.newPasswordInputText.style.display = 'none';
				this.newPasswordInput.style.display = '';
				this.newPasswordInput.focus();			
			} else if (elm.className == 'confirmPasswordText') {
				this.confirmPasswordInputText.style.display = 'none';
				this.confirmPasswordInput.style.display = '';
				this.confirmPasswordInput.focus();
			}
		}
	}
	
	// If a parentElement was passed, it appends this.div onto it.
	// tim o'brien
	//if (this.parentElm.tagName > ''){
	if (this.parentElm && this.parentElm.tagName > ''){
		this.parentElm.appendChild(this.div);	
	}

// --------------------      FORM CODE AND POINTERS ------------------------------------------------------------------------
	/// Password request form
		a=[];
		a[a.length]='<div class="w_changePass">';
		a[a.length]='<div class="w_changePassText">Please enter your email address to have your username/password sent to you.</div>';
		if (this.noLabel){
			a[a.length]='<div class="w_passwordEmail"><input type="text" class="resendEmail" value="Email"></div>';
		} else {
			a[a.length]='<div class="w_passwordEmail"><label>Email:</label><input type="text" class="resendEmail"></div>';			
		}
		a[a.length]='<button class="sendPass">Resend</button>';
		a[a.length]='<button class="cancelPass">Cancel</button>';
		a[a.length]='</div>';
		
		this.reqPassForm.innerHTML = a.join("");
		
		/// Pointer assignment
		this.sendPassButton = Element.select(this.reqPassForm,'.sendPass')[0];
		this.cancelPassButton = Element.select(this.reqPassForm,'.cancelPass')[0];
		this.resendEmailInput = Element.select(this.reqPassForm,'.resendEmail')[0];
		this.changePassDiv = Element.select(this.reqPassForm,'.w_changePass')[0];
		//this.sendPassButton = this.reqPassForm.getElementsByClassName('sendPass')[0];
		//this.cancelPassButton = this.reqPassForm.getElementsByClassName('cancelPass')[0];
		//this.resendEmailInput = this.reqPassForm.getElementsByClassName('resendEmail')[0];
		//this.changePassDiv = this.reqPassForm.getElementsByClassName('w_changePass')[0];
	/// Password request form
		
		
	/// Login information form
		b=[];
		b[b.length]='<div class="w_login"><div class="w_loginUsername"><form name="login" onsubmit="return false">';
		
		if (this.noLabel){
			b[b.length]='<input type="text" class="loginUsername" value="Username" name="username"></div>';			
		} else {
			b[b.length]='<label>Username:</label><input type="text" class="loginUsername" name="username"></div>';
		}
		
		if (this.noLabel){
			b[b.length]='<div class="w_loginPass"><input type="password" name="password" class="loginPWord" style="display:none"></div>';
			b[b.length]='<div class="w_loginPassText"><input type="text" class="loginPWordText" value="Password"></div>';			
		} else {
			b[b.length]='<div class="w_loginPass"><label>Password:</label><input type="password" name="password" class="loginPWord"></div>';				
		}
		b[b.length]='<div class="w_rememberMe"><label class="l_rememberMe">Remember me:</label><input class="rememberMe" type="checkbox"></div>';
		b[b.length]='<input type="button" class="bLogin" value="Login">';
		b[b.length]='<button class="bCancel">Cancel</button></form>';
		b[b.length]='<div class="w_forgotlink"><span class="forgotlink">Forgot Password?</span></div>';
		b[b.length]='</div>';	
		
		this.loginForm.innerHTML = b.join("");
	
		/// Pointer assignment
		this.loginButton = Element.select(this.loginForm,'.bLogin')[0];
		this.cancelButton = Element.select(this.loginForm,'.bCancel')[0];
		this.usernameinput = Element.select(this.loginForm,'.loginUsername')[0];
		this.pwordinput = Element.select(this.loginForm,'.loginPWord')[0];
		this.pwordinputText = Element.select(this.loginForm,'.loginPWordText')[0];
		this.forgotLink = Element.select(this.loginForm,'.forgotlink')[0];
		this.loginDiv = Element.select(this.loginForm,'.w_login')[0];
		this.rememberMeCheck = Element.select(this.loginForm,'.rememberMe')[0]; 
		
		//this.loginButton = this.loginForm.getElementsByClassName('bLogin')[0];
		//this.cancelButton = this.loginForm.getElementsByClassName('bCancel')[0];
		//this.usernameinput = this.loginForm.getElementsByClassName('loginUsername')[0];
		//this.pwordinput = this.loginForm.getElementsByClassName('loginPWord')[0];
		//this.pwordinputText = this.loginForm.getElementsByClassName('loginPWordText')[0];
		//this.forgotLink = this.loginForm.getElementsByClassName('forgotlink')[0];
		//this.loginDiv = this.loginForm.getElementsByClassName('w_login')[0];
		//this.rememberMeCheck = this.loginForm.getElementsByClassName('rememberMe')[0];
	/// Login information form

	/// Logged In Links Form		
		c=[];
		c[c.length]='<div class="loggedInLinks">';
		c[c.length]='<div class="w_welcomeText"></div>';
		c[c.length]='<div class="w_logOutLink"><a href="javascript://" class="logOutLink">Log Out</a></div>';
		c[c.length]='<div class="w_editProfileLink"><a href="javascript://" class="editProfileLink">Edit Profile</a></div>';
		c[c.length]='<div class="w_changePasswordLink"><a href="javascript://" class="changePasswordLink">Change Password</a></div>';
		
		this.loggedInMenu.innerHTML = c.join("");
	
		// Pointer Assignment
		this.logoutLink = Element.select(this.loggedInMenu,'.logOutLink')[0];
		this.editProfileLink = Element.select(this.loggedInMenu,'.editProfileLink')[0];
		this.changePasswordLink = Element.select(this.loggedInMenu,'.changePasswordLink')[0];
		this.welcomeMessage = Element.select(this.loggedInMenu,'.w_welcomeText')[0];
		//this.logoutLink = this.loggedInMenu.getElementsByClassName('logOutLink')[0];
		//this.editProfileLink = this.loggedInMenu.getElementsByClassName('editProfileLink')[0];
		//this.changePasswordLink = this.loggedInMenu.getElementsByClassName('changePasswordLink')[0];
		//this.welcomeMessage = this.loggedInMenu.getElementsByClassName('w_welcomeText')[0];
	/// Logged In Links Form


	/// Logged Out Links Form
		d=[];
		d[d.length]='<div class="w_loggedOutLinks">';
		d[d.length]='<div class="w_logInLink"><a href="#"><span class="logInLink">Login</span></a></div>';
		
		if (this.createLink){
			d[d.length]='<div class="w_createAccountLink"><a href="#"><span class="createAccountLink">Create Account</span></a></div>';		
		}
		
		d[d.length]='</div>';
		
		this.loggedOutMenu.innerHTML = d.join("");
		
		// Pointer Assignment
		if (this.createLink){
			this.createAccountLink = Element.select(this.loggedOutMenu,'.createAccountLink')[0];
			//this.createAccountLink =  this.loggedOutMenu.getElementsByClassName('createAccountLink')[0];
		}
		
		this.loginLink = Element.select(this.loggedOutMenu,'.logInLink')[0];
		//this.loginLink = this.loggedOutMenu.getElementsByClassName('logInLink')[0];
	/// Logged Out Links Form
	
	
	/// Change Password Form
		e=[];
		e[e.length]='<div class="w_changePassword">';

		if (this.noLabel){
			e[e.length]='<div class="w_oldPasswordText"><input type="text" class="oldPasswordText" value="Current Password"></div>';
			e[e.length]='<div class="w_oldPassword"><input type="password" class="oldPassword" style="display:none"></div>';			
			e[e.length]='<div class="w_newPasswordText"><input type="text" class="newPasswordText" value="New Password"></div>';		
			e[e.length]='<div class="w_newPassword"><input type="password" class="newPassword" style="display:none"></div>';		
			e[e.length]='<div class="w_confirmPasswordText"><input type="text" class="confirmPasswordText" value="New Password"></div>';
			e[e.length]='<div class="w_confirmPassword"><input type="password" class="confirmPassword" style="display:none"></div>';			
		} else {
			e[e.length]='<div class="w_oldPassword"><label>Current Password:</label><input type="password" class="oldPassword"></div>';
			e[e.length]='<div class="w_newPassword"><label>New Password:</label><input type="password" class="newPassword"></div>';		
			e[e.length]='<div class="w_confirmPassword"><label>Confirm:</label><input type="password" class="confirmPassword"></div>';			
		}

		e[e.length]='<div class="w_changePassButtons"><button class="changePassButton">Submit</button>';
		e[e.length]='<button class="cancelChangePassButton">Cancel</button></div>';
		e[e.length]='</div>';
		
		this.changePasswordMenu.innerHTML = e.join("");
		
		// Pointer Assignment
		this.oldPasswordInput = Element.select(this.changePasswordMenu,'.oldPassword')[0];
		this.newPasswordInput = Element.select(this.changePasswordMenu,'.newPassword')[0];
		this.confirmPasswordInput = Element.select(this.changePasswordMenu,'.confirmPassword')[0];
		this.oldPasswordInputText = Element.select(this.changePasswordMenu,'.oldPasswordText')[0];
		this.newPasswordInputText = Element.select(this.changePasswordMenu,'.newPasswordText')[0];
		this.confirmPasswordInputText = Element.select(this.changePasswordMenu,'.confirmPasswordText')[0];
		this.changePassButton = Element.select(this.changePasswordMenu,'.changePassButton')[0];
		this.cancelChangePassButton = Element.select(this.changePasswordMenu,'.cancelChangePassButton')[0];
		//this.oldPasswordInput = this.changePasswordMenu.getElementsByClassName('oldPassword')[0];
		//this.newPasswordInput = this.changePasswordMenu.getElementsByClassName('newPassword')[0];
		//this.confirmPasswordInput = this.changePasswordMenu.getElementsByClassName('confirmPassword')[0];
		//this.oldPasswordInputText = this.changePasswordMenu.getElementsByClassName('oldPasswordText')[0];
		//this.newPasswordInputText = this.changePasswordMenu.getElementsByClassName('newPasswordText')[0];
		//this.confirmPasswordInputText = this.changePasswordMenu.getElementsByClassName('confirmPasswordText')[0];
		//this.changePassButton = this.changePasswordMenu.getElementsByClassName('changePassButton')[0];
		//this.cancelChangePassButton = this.changePasswordMenu.getElementsByClassName('cancelChangePassButton')[0];
	/// Change Password Form
	
// --------------------      FORM CODE WITH POINTERS ------------------------------------------------------------------------


	// Ajax boolean call to see if a user is logged in or not.
	// Asynchronous is set to false because we want to wait to 
	// see if they're logged in before proceeding
	this.checkLogin = function(){
		if (readCookie('REMEMBERME')){
			remember = readCookie('REMEMBERME');
			if (remember == 1){
				this.rememberMeCheck.checked = 1;
				this.usernameinput.value = readCookie('CFO_USERNAME')
			}
		}

		if (!readCookie('CFO_ST')){
			return false;
		}
		url ='/wwwroot/Lib/login/ajax/cookiecheck.cfm';
		//var ajax = new Ajax.Request(url,{method: 'post',asynchronous: false, onSuccess: this.transportJSON.bind(this)});
		var ajax = new Ajax.Request(url,{method: 'post',asynchronous: false});
		if (userInfo.user_id > ''){
			return true;
		} else {
			return false;
		}
	}

	// Checks to see if the user is logged in based on the userInfo object or cookies.  Returns true or false.
	this.isLoggedIn = function(){
		if (!window.userInfo){
			//userInfo = new userObj();
			userInfo = new Object();			
			this.checkLogin();
		}
		if (!window.userInfo.user_id){		
			return false;
		} else {
			return true;
		}
	}

	// Removes all the children of this.div
	this.removeChildren = function(){
		if (this.div.hasChildNodes()){
			while (this.div.childNodes.length >= 1){
				this.div.removeChild(this.div.firstChild);       
			} 
		}	
	}

	// puts the links for when the user is logged out into this.div
	this.loggedOutLinksMenu = function(username){
		this.removeChildren();
		this.div.appendChild(this.loggedOutMenu);
	}
	
	// Puts the links for when the user is logged in into this.div
	this.loggedInLinksMenu = function(){
		this.removeChildren();
		
		this.loginMessage = "Welcome,<br>" + userInfo.firstName + ' ' + userInfo.lastName;
	
		this.setWelcomeMessage(this.loginMessage);
		this.div.appendChild(this.loggedInMenu);
	}
	
	// Sets the welcome div with whatever string is passed
	this.setWelcomeMessage = function(string){
		this.welcomeMessage.innerHTML = string;
	}

	/// Puts the login form back into the container div
	this.loginInfoForm = function(){
		this.removeChildren();		
		this.loginDiv.appendChild(this.errorRow);
		this.div.appendChild(this.loginForm);
		this.resetForm();
	}
	

	/// Puts the password request form back into the container div
	this.forgotPasswordForm = function(){
		this.removeChildren();		
		this.changePassDiv.appendChild(this.errorRow);
		this.div.appendChild(this.reqPassForm);
		this.resetForm();
	}
	
	// Places the change password form into this.div
	this.changePasswordForm = function(){
		this.removeChildren();		
		this.changePasswordMenu.appendChild(this.errorRow);
		this.div.appendChild(this.changePasswordMenu);
		this.resetForm();
	}

	// Either inserts or pops the login form (only if the user is not logged in);
	this.show = function(){	

		if (!this.isLoggedIn()){
			// tim o'brien
			if (this.parentElm && this.parentElm.tagName > ''){
			//if (this.parentElm.tagName > ''){ // Insert the login
				this.loginInfoForm();
			} else { // Pop the login
				this.loginInfoForm();
				
				this.div.style.visibility = 'visible';
				this.div.style.position = 'absolute';
				document.body.appendChild(this.div);
				pushForm(this.div);
			}
		} else {
			this.loggedInLinksMenu();
			this.parentElm.appendChild(this.div);
		}
	}
	
	/// Clears the input boxes on all the forms
	this.resetForm = function(){
		if (this.noLabel){
			this.usernameinput.value = 'Username';
			this.resendEmailInput.value = 'Email';
			this.pwordinput.style.display = 'none';
			this.pwordinputText.style.display = '';
			this.oldPasswordInputText.style.display = '';
			this.oldPasswordInput.style.display = 'none';
			this.newPasswordInputText.style.display = '';
			this.newPasswordInput.style.display = 'none';
			this.confirmPasswordInputText.style.display = '';
			this.confirmPasswordInput.style.display = 'none';			
		} else {
			//this.usernameinput.value = '';
			this.resendEmailInput.value = '';		
		}
		this.pwordinput.value = '';

		this.oldPasswordInput.value = '';
		this.newPasswordInput.value = '';
		this.confirmPasswordInput.value = '';
		this.resetError();
	}
	
	/// Closes the popup window
	this.hidePop = function(){
		if (this.parentElm == ''){
			popForm();
		} else {
			this.loggedOutLinksMenu();
			this.resetError();
		}
	}

	/// Displays whatever login error happens to the user
	this.displayLoginError = function(msg){	
		this.errorRow.innerHTML = msg;
		this.errorRow.style.display = '';
	}
	
	// Resets the error div and hides it.
	this.resetError = function(){ 
		this.displayLoginError('');
		this.errorRow.style.display = 'none';	
	}

	// Calls the ajax script to request a resend of the password to the user
	this.sendPass = function(){ 
		this.resendEmail = this.resendEmailInput.value;
		
		if (testEmail(this.resendEmail)){
			var url = '/wwwroot/Lib/login/ajax/passwordResend.cfm?';
			var ajax = new Ajax.Request(url,{method: 'post', onComplete:this.passwordonSuccess(),	parameters: {email: this.resendEmail}});
		} else {
			this.displayLoginError('Invalid Email');
		}
	}

	// Changes the form back to the logged out links
	this.passwordonSuccess = function(){
		this.loggedOutLinksMenu();
		alert('Password sent!');
	}

	//  Manually logs a user in when "login_username" and "login_password" are passed through the url.
	this.manualLogin = function(uname, pword){
		if (!this.isLoggedIn()){
			this.usernameinput.value = uname;
			this.pwordinput.value = pword;
			this.checkLoginForm();
		}
	}

	/// Checks the login form to verify things are correct before making the ajax request to log the user in.
	this.checkLoginForm = function(){	
		this.rememberMe = this.rememberMeCheck.checked;
		this.username = this.usernameinput.value;
		this.password = this.pwordinput.value;

		if (this.username == ""){
			this.displayLoginError('Invalid Username');
		} else if(this.password == ""){
			this.displayLoginError('Invalid Password');	
		}
		
		if (this.password.length > 0 && this.username.length > 0){
			this.resetError();
			var url = '/wwwroot/Lib/login/ajax/loginmatch.cfm';

			if (this.rememberMe){
				var rememberMe = 1;
			} else {
				var rememberMe = 0;
			}
			var ajax = new Ajax.Request(url,{method: 'post', 
										onComplete: this.jsonLoginResponse.bind(this),
										onException: function(t,e){alert(e.message)},
										parameters: {username: this.username, pword: this.password, rememberMe: rememberMe}
										});
		}

	}
	
	// Grabs the JSON response from the login and checks to see if they were logged in.
	this.jsonLoginResponse = function(transport, json){ 
		if (json.MESSAGE > ''){ /// The user wasn't logged in
			this.displayLoginError(json.MESSAGE);	
		} else { /// The user was logged in
			//eval(transport.responseText);
			if (!this.parentElm.tagName){
				this.hidePop();
			}
			
			for(var x=0; x<loginObjs.length; x++){
				loginObjs[x].loggedInLinksMenu();	
			}
			
			this.onSuccess();
		}
	}
	
	// Delete the cookies and switch the links menu
	this.logOut = function(){
		createCookie('CFO_ST','0', -1, mydomain);
		createCookie('CFO_USER_ID','0', -1, mydomain);
		createCookie('CFO_USERNAME','0', -1, mydomain);

		createCookie('CFO_ST','0', -1);
		createCookie('CFO_USER_ID','0', -1);
		createCookie('CFO_USERNAME','0', -1);						

		
		for(var x=0; x<loginObjs.length; x++){
			loginObjs[x].loggedOutLinksMenu();
		}
		
		userInfo = null;		
	}
	
	// Calls the editProfile object
	this.editProfile = function(){
		this.profile = new createEditProfile();
	}

	// Checks the form for the password change before submitting it via Ajax
	this.changePassCheck = function(){
		this.oldPass = this.oldPasswordInput.value;
		this.newPass = this.newPasswordInput.value;
		this.confirmPass = this.confirmPasswordInput.value;
		
		if (hex_md5(hex_md5(this.oldPass)) == userInfo.password && this.newPass == this.confirmPass){
			this.resetError();
			url = '/wwwroot/Lib/login/ajax/changepassword.cfm';
			
			var ajax = new Ajax.Request(url,{method: 'post', 
										onComplete: this.jsonPassChangeResponse.bind(this),
										parameters: {user_id: userInfo.user_id, newpass: this.confirmPass}
										});
			
		} else if(hex_md5(hex_md5(this.oldPass)) != userInfo.password){
			this.displayLoginError('Incorrect Password');	
		} else if(this.newPass != this.confirmPass){
			this.displayLoginError('Passwords Do Not Match');	
		}
	}

	//  Passes the json object to the userInfo object
	this.jsonPassChangeResponse = function(transport,json){
		if (json.MESSAGE > ''){
			this.displayLoginError(json.MESSAGE);
		} else {
			//eval(transport.responseText);
			this.loggedInLinksMenu();
		}
	}

	// Places the change password form in this.div
	this.changePassword = function(){
		this.changePasswordForm();	
	}
	
	// Changes the page location to the register page
	this.createAccountRedirect = function(){
		window.location = '/wwwroot/custmaint/register.cfm';
	}
	
	// Allows the user to press enter to submit forms
	this.checkKeyPressed = function(e){
		var form = this.div.firstChild.className;
		if (window.event)
			var keycode = event.keyCode
		else
			var keycode = e.which;
			
		if (keycode == 13){
			if (form == 'w_thisLoginForm'){
				this.checkLoginForm();
			} else if (form == 'w_thisReqPassForm'){
				this.sendPass();
			}
		} 
	}
	
	//Assigning event triggers for the buttons on the forms ----------------------------
	Event.observe(this.sendPassButton,'click',this.sendPass.bindAsEventListener(this));
	Event.observe(this.cancelPassButton,'click',this.loginInfoForm.bindAsEventListener(this));



	Event.observe(this.cancelButton,'click',this.hidePop.bindAsEventListener(this));
	Event.observe(this.forgotLink,'click',this.forgotPasswordForm.bindAsEventListener(this));
	Event.observe(this.logoutLink,'click',this.logOut.bindAsEventListener(this));
	Event.observe(this.editProfileLink,'click',this.editProfile.bindAsEventListener(this));
	Event.observe(this.changePasswordLink,'click',this.changePassword.bindAsEventListener(this));
	Event.observe(this.loginLink,'click',this.show.bindAsEventListener(this));
	Event.observe(this.changePassButton,'click',this.changePassCheck.bindAsEventListener(this));
	Event.observe(this.cancelChangePassButton,'click',this.loggedInLinksMenu.bindAsEventListener(this));

	if (this.createLink){
		Event.observe(this.createAccountLink,'click',this.createAccountRedirect.bindAsEventListener(this));
	}
	
	//Event.observe(this.loginButton,'click',this.checkLoginForm.bindAsEventListener(this));
	Event.observe(this.loginButton,'click',function(event){
		if (!this.checkLoginForm.keyPressed){
			this.checkLoginForm(this);
		}
	}.bindAsEventListener(this));
	Event.observe(this.loginForm,'keypress',function(event){
		var kc = event.keyCode || event.which;
		if (kc == 13){
			this.checkLoginForm.keyPressed = true;
			this.checkLoginForm(this);
			var f = this.checkLoginForm;
			setTimeout(function(){f.keyPressed = false},250);
		}
	}.bindAsEventListener(this));
	
	
	//this.checkKeyPressed.bindAsEventListener(this));
	
	
	
	Event.observe(this.sendPassButton,'keypress',this.checkKeyPressed.bindAsEventListener(this));
	if (this.noLabel){ // These event handlers change the input boxes with text if noLabel is true
		Event.observe(this.resendEmailInput,'focus',this.clearInput.bindAsEventListener(this));
		Event.observe(this.resendEmailInput,'blur',this.insertInput.bindAsEventListener(this));

		Event.observe(this.usernameinput,'focus',this.clearInput.bindAsEventListener(this));
		Event.observe(this.usernameinput,'blur',this.insertInput.bindAsEventListener(this));

		Event.observe(this.pwordinputText,'focus',this.clearInput.bindAsEventListener(this));
		Event.observe(this.pwordinput,'blur',this.insertInput.bindAsEventListener(this));

		Event.observe(this.oldPasswordInputText,'focus',this.clearInput.bindAsEventListener(this));
		Event.observe(this.oldPasswordInput,'blur',this.insertInput.bindAsEventListener(this));

		Event.observe(this.newPasswordInputText,'focus',this.clearInput.bindAsEventListener(this));
		Event.observe(this.newPasswordInput,'blur',this.insertInput.bindAsEventListener(this));

		Event.observe(this.confirmPasswordInputText,'focus',this.clearInput.bindAsEventListener(this));
		Event.observe(this.confirmPasswordInput,'blur',this.insertInput.bindAsEventListener(this));
	}
	//Assigning event triggers for the buttons on the forms ----------------------------
	

	// Creates an array of pointers to the login objects on the screen.  It's used to update each one and make sure their menus are the same.
	if (!window.loginObjs){
		loginObjs = []
		loginObjs[0] = this;
	} else {
		loginObjs[loginObjs.length] = this;		
	}

	// If the element is being inserted, check to see if they're logged in.  Then choose the appropriate menu for inserting.
	// tim o'brien
	//if (this.parentElm.tagName > ''){
	if (this.parentElm && this.parentElm.tagName > ''){
		if (!this.isLoggedIn()){
			this.loggedOutLinksMenu();
		} else {
			this.onSuccess();
			this.loggedInLinksMenu();
		}
	}
}

// The profile popup object
function createEditProfile(obj){

	// Create the divs
	this.div = $(document.createElement("div"));
	this.editProfileForm = $(document.createElement("div"));

	// Assign default variables
	this.className = '';
	
	Object.extend(this, obj);

	// Creating the form's HTML
	a=[];
	a[a.length]='<div class="w_editProfile" align="center">';
	a[a.length]='<table class="t_editTitle" width="100%" cellspacing="0" cellpadding="0"><tr><td class="EditTitleCell">Edit Profile</td></tr></table>';
	a[a.length]='<table class="t_editProfile" width="100%" cellpadding="0" cellspacing="0">';
	a[a.length]='<tr><td><span class="star">*</span> <label>Email:</label></td><td><input type="text" class="editEmail"></td></tr>';
	a[a.length]='<tr><td><span class="star">*</span> <label>First Name:</label></td><td><input type="text" class="editFirstName" maxlength="18"></td></tr>';
	a[a.length]='<tr><td><label>Last Name:</label></td><td><input type="text" class="editLastName" maxlength="18"></td></tr>';
	
	if (userInfo.country == 'USA'){
		a[a.length]='<tr><td><label>Address:</label></td><td><input maxlength="60" type="text" class="address" maxlength="30"></td></tr>';
		a[a.length]='<tr><td><label>City:</label></td><td><input type="text" maxlength="50" disabled="disabled" class="city"></td></tr>';
		a[a.length]='<tr><td><label>State:</label></td><td><input type="text" maxlength="2" disabled="disabled" class="state"></td></tr>';
		a[a.length]='<tr><td><span class="star">*</span> <label>Zip:</label></td><td><input type="text"  maxlength="5" class="zip"></td></tr>';
		a[a.length]='<tr><td><span class="star">*</span> <label>Country:</label></td><td><input type="text" maxlength="50" disabled="disabled" class="country"></td></tr>';				
	} else {
		a[a.length]='<tr><td><label>Address:</label></td><td><input type="text" maxlength="50" class="address"></td></tr>';
		a[a.length]='<tr><td><label>City:</label></td><td><input type="text" maxlength="40" class="city"></td></tr>';
		a[a.length]='<tr><td><label>State:</label></td><td><input type="text" maxlength="2" class="state"></td></tr>';					
		a[a.length]='<tr><td><span class="star">*</span> <label>Zip/Postal Code:</label></td><td><input type="text" maxlength="5" class="zip"></td></tr>';
		a[a.length]='<tr><td><span class="star">*</span> <label>Country:</label></td><td><input type="text" maxlength="50" class="country"></td></tr>';						
	}
	
	a[a.length]='<tr><td><label>Day Time Phone:</label></td><td><input type="text" class="editDayPhone"></td></tr>';
	a[a.length]='<tr><td><label>Night Time Phone:</label></td><td><input type="text" class="editNightPhone"></td></tr>';
	a[a.length]='<tr><td colspan="2" align="center" style="padding-top:5px"><center><button class="submitButton">Submit</button>&nbsp;&nbsp;<button class="cancelButton">Cancel</button></center></td></tr>';
	a[a.length]='</table>';
	a[a.length]='<div><span class="star">*</span> - Indicates required fields</div></div>';
	
	this.editProfileForm.innerHTML = a.join("");
	// Creating the forms HTML
	
	// Assigning pointers to various HTML elements
	this.emailInput = Element.select(this.editProfileForm,'.editEmail')[0];
	this.firstNameInput = Element.select(this.editProfileForm,'.editFirstName')[0];
	this.lastNameInput = Element.select(this.editProfileForm,'.editLastName')[0];
	this.dayPhoneInput = Element.select(this.editProfileForm,'.editDayPhone')[0];
	this.nightPhoneInput = Element.select(this.editProfileForm,'.editNightPhone')[0];
	this.zipInput = Element.select(this.editProfileForm,'.zip')[0];
	this.countryInput = Element.select(this.editProfileForm,'.country')[0];
	this.stateInput = Element.select(this.editProfileForm,'.state')[0];
	this.addressInput = Element.select(this.editProfileForm,'.address')[0];
	this.cityInput = Element.select(this.editProfileForm,'.city')[0];
	this.submitButton = Element.select(this.editProfileForm,'.submitButton')[0];
	this.cancelButton = Element.select(this.editProfileForm,'.cancelButton')[0];
	//this.emailInput = this.editProfileForm.getElementsByClassName('editEmail')[0];
	//this.firstNameInput = this.editProfileForm.getElementsByClassName('editFirstName')[0];
	//this.lastNameInput = this.editProfileForm.getElementsByClassName('editLastName')[0];
	//this.dayPhoneInput = this.editProfileForm.getElementsByClassName('editDayPhone')[0];
	//this.nightPhoneInput = this.editProfileForm.getElementsByClassName('editNightPhone')[0];
	//this.zipInput = this.editProfileForm.getElementsByClassName('zip')[0];
	//this.countryInput = this.editProfileForm.getElementsByClassName('country')[0];
	//this.stateInput = this.editProfileForm.getElementsByClassName('state')[0];
	//this.addressInput = this.editProfileForm.getElementsByClassName('address')[0];
	//this.cityInput = this.editProfileForm.getElementsByClassName('city')[0];
	//this.submitButton = this.editProfileForm.getElementsByClassName('submitButton')[0];
	//this.cancelButton = this.editProfileForm.getElementsByClassName('cancelButton')[0];
	
	// Assigning pointers to various HTML elements
	
	// Filling in the input fields with data based off the userInfo object
	this.emailInput.value = (userInfo.email.toString()).trim();
	this.firstNameInput.value = (userInfo.firstName.toString()).trim();
	this.lastNameInput.value = (userInfo.lastName.toString()).trim();
	this.dayPhoneInput.value = (userInfo.workPhone.toString()).trim();
	this.nightPhoneInput.value = (userInfo.homePhone.toString()).trim();
	this.zipInput.value = (userInfo.zip.toString()).trim();;
	this.countryInput.value = (userInfo.country.toString()).trim();
	this.stateInput.value = (userInfo.state.toString()).trim();
	this.addressInput.value = (userInfo.address1.toString()).trim();
	this.cityInput.value = (userInfo.city.toString()).trim();
	// Filling in the input fields with data based off the userInfo object	

	// Hides the popup
	this.hideForm = function(){
		popForm();
	}
	
	// Checks the form before submitting profile updates via ajax	
	this.checkForm = function(){
		this.country = (this.countryInput.value.toString()).trim();;
		this.zip = (this.zipInput.value.toString()).trim();;
		this.firstName = (this.firstNameInput.value.toString()).trim();
		this.emailAddress = (this.emailInput.value.toString()).trim();
		this.lastName = (this.lastNameInput.value.toString()).trim();
		this.dayPhone = (this.dayPhoneInput.value.toString()).trim();
		this.nightPhone = (this.nightPhoneInput.value.toString()).trim();
		this.state = (this.stateInput.value.toString()).trim();
		this.address = (this.addressInput.value.toString()).trim();
		this.city = (this.cityInput.value.toString()).trim();

		if (this.country == 'USA' && userInfo.country != 'USA'){
			alert('You cannot change your country to the United States.  Please enter something different or contact the administrators');
			return;
		}

		if (this.firstName > '' && this.country > '' &&  this.zip > '' && testEmail(this.emailAddress)){
				url = '/wwwroot/Lib/login/ajax/editprofile.cfm';
				var ajax = new Ajax.Request(url,{method: 'post', 
											onComplete: this.jsonProfileResponse.bind(this),
											parameters: {email: this.emailAddress, country: this.country, firstname: this.firstName, zip: this.zip, 
											lastname: this.lastName, dayphone: this.dayPhone, nightphone: this.nightPhone, state: this.state, 
											address: this.address, city: this.city, user_id: userInfo.user_id}
											});
	
		} else {
			alert('Please make sure all required forms are filled out.');
		} 

	}

	// Takes the json and passes it to the userObject to apply the new data
	this.jsonProfileResponse = function(transport, json){
		if (json.MESSAGE > ''){
			alert(json.MESSAGE);
		} else {
			//eval(transport.responseText);
			this.hideForm();
			if (window.loginObjs){
				for(var x=0; x<loginObjs.length; x++){
					loginObjs[x].loginMessage ='';
					loginObjs[x].loggedInLinksMenu();	
				}
			}
		}
	}

	// Allows only numerical characters to be typed in the profile
	// zip code field (if country is set to USA)
	this.onlyDigits = function(e){
		if (window.event)
			var keycode = event.keyCode
		else
			var keycode = e.which;


		if (keycode >= 48 && keycode <= 57 && !e.shiftKey)
			return true;
		if (keycode >= 96 && keycode <= 105)
			return true;
		if (keycode == 37 || keycode == 39 || keycode == 8 || keycode == 46 || keycode == 9 || keycode == 13 || keycode == 9)
			return true;
			
		Event.stop(e);
	}

	// Makes ajax call to look up the city and state name based on zipcode
	this.cityLookUp = function(){
		if (this.gZip && this.gZip == this.zipInput.value)
			return;
		if (this.zipInput.value.length == 5){
			if(window.XMLHttpRequest) 
				var myxmlhttp = new XMLHttpRequest();
			else if(window.ActiveXObject) 
				var myxmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
			myxmlhttp.open("POST", '/wwwroot/custmaint/ajax/ziplookup.cfm?zip='+parseInt(this.zipInput.value),false);
			myxmlhttp.send(null);
			if (trim(myxmlhttp.responseText)=='not found'){
				alert(this.zipInput.value+' is not a valid Zip Code')
				this.cityInput.value = '';
				this.stateInput.value = '';
				return false;
			}
			else {
				var a = myxmlhttp.responseText.split(',');
				this.cityInput.value = trim(a[0]);
				this.stateInput.value = trim(a[1]);
				this.countryInput.value = 'USA';
				this.gZip=this.zipInput.value;
			}
		}
		else {
			return false;
		}
	}

	this.tab = function(e){
		if (e.keyCode == 9)
			if (e.shiftKey){
				if (Event.element(e) == this.emailInput){
					this.nightPhoneInput.focus()
					Event.stop(e)
				}
			}
			else
				if (Event.element(e) == this.nightPhoneInput){
					this.emailInput.focus()
					Event.stop(e)
				}
	}

	Event.observe(this.div,'keydown',this.tab.bindAsEventListener(this))

	/// Assigning event handling
	if (userInfo.country == 'USA'){ // Allow for the US to do the zipcode lookup
		Event.observe(this.zipInput,'blur',this.cityLookUp.bindAsEventListener(this));
		Event.observe(this.zipInput,'keydown',this.onlyDigits.bindAsEventListener(this));		
	}
	Event.observe(this.submitButton,'click',this.checkForm.bindAsEventListener(this));
	Event.observe(this.cancelButton,'click',this.hideForm.bindAsEventListener(this));
	/// Assigning event handling
	
	// Add the profile form to this.div
	this.div.appendChild(this.editProfileForm);

	// Check for what className applies to this.div
	if (this.className > ''){
		this.div.className = this.className;
	} else {
		this.div.className = 'pop';	
	}
	
	this.div.style.visibility = 'visible';
	this.div.style.position = 'absolute';
	document.body.appendChild(this.div);
	pushForm(this.div); // Push the form onto the screen
}
