var tsLogin =  Class.create({

    initialize: function( config )
    {
		
		
		$('loginForm').observe('submit', function(e){
			e.stop()
		} );
       	
		this.checkSecure();
        this.config = config;
        this.preloadImages();
        this.userEmail;
		
		this.eventManager = new tsEventManager();
		
        if( !browser.isIE ){
            $( 'password' ).type = "text";
        } else {
        	$( 'fakePassword' ).value = "Password";
        	$( 'fakePassword' ).observe( 'focus', this.fakeClick.bind(this) );
        	$( 'password' ).observe( 'blur', this.fakeBlur.bind(this) );
        }
       
        if( !this.config.hasCookie ){
            $( 'companyName' ).value = "Organization Name";
            $( 'companyName' ).observe( "focus", this.focusOrganization.bind(this) );
            $( 'companyName' ).observe( "blur", this.blurOrganization.bind(this) );
        }
       
        $( 'userName' ).value = "User Name";
        $( 'password' ).value = "Password";
       
        $( 'userName' ).observe( "focus", this.focusUsername.bind( this ) );
        $( 'password' ).observe( "focus", this.focusPassword.bind( this ) );
       
        $( 'userName' ).observe( "blur", this.blurUsername.bind( this ) );
        if( !browser.isIE ) {
       		$( 'password' ).observe( "blur", this.blurPassword.bind( this ) );
       	}
       
        loadButtons();
       
	  	this.eventManager.watch( $('loginForm'), 'submit', this.login.bind( this ) );
        $('submit_button').observe( 'click', this.login.bind( this ) );
        
      
        $('forgotPassword_button').observe( 'click', this.forgotPassword.bind( this ) );
      
       
        if ( $('clearLink') ) {
            $('clearLink').observe( 'click', this.clearOrg.bind( this ) );
        }
        this.registerTabKeyListener();
		
		
		
		
		
    },
    
    preloadImages: function() {
    	var ext = "png";
    	if (browser.isIE6x) ext = "gif";
    	if (document.images) {
		  var img1 = new Image();
		  img1.src = this.config.prefix + "/ui/images/login_images/login_loading.gif";
		  
		  var img2 = new Image();
		  img2.src = this.config.prefix + "/ui/images/login_images/login_buttons." + ext;
		  
		  var img3 = new Image();
		  img3.src = this.config.prefix + "/ui/images/tsNumberBubble/numberBubble_small." + ext;
		  
		  var img4 = new Image();
		  img4.src = this.config.prefix + "/ui/images/icons/icons-l." + ext;
		}
    },
    
    fakeToggle:function() {
    	$( 'password' ).toggle();
    	$( 'fakePassword' ).toggle();
    },
    
    fakeClick:function() {
    	if( $( 'fakePassword' ).style.display != "none" ) {
    		this.fakeToggle();
    		$( 'password' ).focus();
    	}
    },
    
    fakeBlur:function() {
    	if( $( 'password' ).value == '' ) {
    		this.fakeToggle();
    	}
    },
   
    registerTabKeyListener:function( force )
    {
        if( browser.isIE || force ){
            this.keyListener = this.firstFocus.bindAsEventListener( this );
            Event.observe(document, 'keydown', this.keyListener );
        }
    },
   
   
    firstFocus: function( e ){
        Event.stopObserving( document, "keydown", this.keyListener );
        var key = e.which || e.keyCode;
        if ( key == Event.KEY_TAB )
        {
            if( this.config.hasCookie ){
                $( 'userName' ).focus();
                $( 'userName' ).select();
            } else {
                $( 'companyName' ).focus();
                $( 'companyName' ).select();
            }
        e.stop();
        }
    },
   
    checkSecure:function(){
        if( window.location.href.startsWith( 'http://' ) ){
            window.location = 'https://' + window.location.href.substring( 7, window.location.href.length );
        }
    },
   
    focusOrganization: function() {
        this.setActive( 'companyName', 'Organization Name' );
    },
   
    focusUsername:function(){
        this.setActive( 'userName', 'User Name' );
        this.coverPassword();
    },
   
    focusPassword:function(){
        this.setActive( 'password', 'Password' );
        this.coverPassword();
    },
   
    coverPassword:function() {
        if ( $( 'password' ).type == "text" ) {
            $( 'password' ).type = "password";
        }
    },
   
    blurOrganization: function() {
        this.setInactive( 'companyName', 'Organization Name' );
    },
   
    blurUsername:function(){
        this.setInactive( 'userName', 'User Name' );
    },
   
    blurPassword:function(){
        if( this.setInactive( 'password', 'Password' ) && !browser.isIE ){
            $( 'password' ).type = "text";
        }
    },
    
	
/**	
 * 
 * Forgot Password Functionality
 * Author: Brad
 * Date: Jul 28, 2010
 * 
 * TODO: Someday this should be probably be placed into a separate javascript file.
 * 
 * This section of javascript runs the request password feature of trakstar, this includes
 * using a captcha in order to make the request.
 * 
**/
	//Fade the login div when the fogot password button is clicked
    forgotPassword:function() {
		
    	 new Effect.Fade( $('loginDiv'), {
            duration:.35,
            afterFinish:this.displayForgotPassword.bind( this )
        });
    },
    
    
	//Send the password request to the servlet for the change
  	requestPasswordByEmail:function(e) {
		this.userEmail = $("email").value;
		var params = { "email": $('email').value, "captchaUserAnswer":$('captchaUserAnswer').value, "step":"email", "action":"request" };
		this.requestToForgotPassword( params );
    },
	
	requestPasswordByUserCompany:function(e) {
  		var params =  {"email":this.userEmail ,"userName":$("userNameForgot").value, "companyName":$("companyNameForgot").value, "step":"username", "action":"request" };
		this.requestToForgotPassword( params );
	},
	
	requestToForgotPassword:function( params ) {
		new Ajax.Request( 'https://' + this.config.url + '/servlet/ForgotPasswordServlet', {
            method: 'POST',
            parameters: params, 
            onSuccess: this.handleForgotPasswordResponse.bind( this )
		});
	},
	
	/*Handles the reponse from the server and decides what div to show.
	If the email is unique show confirmation,
    If email is not unique show page with company and user name
   	else show an error*/
	handleForgotPasswordResponse:function( response ) {
		var status = eval( '(' + response.responseText + ')' ).status
		if( status == 'success' ) {
			this.showConfirmation();
		} else if ( status == 'notUnique' ) {
			this.showCompanyUserNameForm();
			this.currentView = "username";
		} else {
			this.showRequestPasswordError( status );
		}
	},
	
	showRequestPasswordError:function( status ) {
		if( status == "dne" ) {
			if( this.currentView == "email"  ) {
				$('errorDiv').update("Email not found.");
			} else if( this.currentView = "username" ) {
				$('errorDiv').update("Company/User Name combination not found.");
			}
		} else if( status == "captcha_error" ) {
			$('errorDiv').update("Characters do not match image")
		}
	
		if( this.currentView == "email") {
			this.setCaptcha();
		}
	},
    
	//If the email doesn't exist then let the user know that the request failed.
    passwordRetrievalFail:function() {
    	$( 'email' ).addClassName( 'login_failed' );
    	Effect.Shake( 'content_back', {distance:3, duration:.4} );
    },
	
	
	//Display the forgot password div where the user will enter an email address
    displayForgotPassword:function() {
		this.currentView = "email";
		
        var forgotHTML = '<table style="width:100%;float:left;">' +
        					'<tr><td align="left" colspan=2>' +
			      				'<input class="inactiveInput" type="text" name="email" id="email">' +
							'</td></tr>' +
							'<tr><td style="font-size:12px;text-align:center;" colspan=2>To retrieve your password please enter your email address</td></tr>' +
							'<tr><td id="captchaImageWrap" style="cursor:pointer;height:48px;width:150px;"></td><td id="captchaImageInputWrap" style="padding-left:10px;width:167px;"><input style="width: 160px;" type="text" name="captchaUserAnswer" id="captchaUserAnswer"></td></tr>' +
							'<tr><td colspan=2 style="font-size:12px;text-align:center;">Enter the characters in the picture into the box on the right <br/> or click the picture to get a new image.</td></tr>' +
							'<tr><td id="cancelButton"></td><td style="padding-left:10px;" id="getPasswordButton"></td></tr>' +
							'<tr><td id="errorDiv" style="color:red;text-align:center;" colspan=2></td></tr>' +
							'</table>';
       
       var callback = function(){
		   	$('email').value = "Email";
		   	$('email').observe('focus', function(){
		   		$('email').removeClassName('inactiveInput').addClassName('activeInput');
		   		if ($('email').value === "Email") {
		   			$('email').value = ""
		   		}
		   	});
		   	$('email').observe('blur', function(){
		   		if ($('email').value == "") {
		   			$('email').removeClassName('activeInput').addClassName('inactiveInput');
		   			$('email').value = "Email";
		   		}
		   	});
		   	var sendRequest = new Button(DEFAULT_BUTTON, "Send Reset Request", $("getPasswordButton"), {
		   		iconPosition: "right",
		   		icon: "continue_icon",
		   		margin: "0px 0px 0px 0px",
		   		align: "left"//,
		   		//onclick: this.requestPasswordByEmail.bind(this)
		   	});
		   	var deleteButton = new Button(CANCEL_BUTTON, "Cancel", $('cancelButton'), {
		   		onclick: this.showLoginPage.bindAsEventListener(this),
		   		icon: "red_x_icon",
		   		margin: "0px 0px 0px 0px",
		   		align: "right"
		   	});
		   	var buttonText = $('getPasswordButton').select('.button_text');
		   	buttonText[0].setStyle({
		   		fontSize: "12px",
		   		fontWeight: "normal"
		   	});
		   	buttonText = $('cancelButton').select('.button_text');
		   	buttonText[0].setStyle({
		   		fontSize: "12px",
		   		fontWeight: "normal",
		   		width: "100px"
		   	});
		   	
		   	//Set the capchaImage
			this.setCaptcha();
			$("captchaImageWrap").observe('click', this.setCaptcha ) ;
			
			
			//Create the form validator
			this.validator = new tsFormValidator( [ [$( 'getPasswordButton' ), this.requestPasswordByEmail.bind( this ) ] ], $( 'loginForm' ) );
			this.validator.add( {'object':$( 'email' ), 'name':"Email",'validationType':VALIDATE_EMAIL, 'validateOnBlur':false, 'noPopup': true } );
			this.validator.add( {'object':$('captchaUserAnswer'), 'name':"Empty captcha field", 'validationType':VALIDATE_FUNCTION, 'vaildateOnBlur':false, 'noPopup': true, 'validate': function() { if( $('captchaUserAnswer').value == "" ) return "Captcha field is empty"; } });
			
			
			
		}.bind( this );
       
		this.changeForgotDivContent( forgotHTML, callback );
    },
	
	setCaptcha:function() {
		var captchaImage = new Image();
			captchaImage.src = "/servlet/SimpleCaptchaImg#" + Math.floor(Math.random() * 1111);
			$('captchaImageWrap').update(captchaImage);		
			
				
	},
	
	showCompanyUserNameForm:function() {
		//If the table is showing already... don't show it again.
		if( $("companyUserTable") ) return;
		
		var forgotHTML = '<table id="companyUserTable" style="width:100%;float:left;margin-top:-6px;">' +
							'<tr><td colspan=2 style="text-align:center;">Please enter your company and user name to reset your password</td></tr>' +
							'<tr><td align="left" colspan=2>' +
			      				'<input class="inactiveInput" type="text" name="companyNameForgot" id="companyNameForgot">' +
							'</td></tr>' +
        					'<tr><td align="left" colspan=2 style="padding-bottom:4px;padding-top:10px;">' +
			      				'<input class="inactiveInput" type="text" name="userNameForgot" id="userNameForgot">' +
							'</td></tr>' +
							'<tr><td style="text-align:center;font-size:13px;" colspan=2>If you do not remember your user name, please contact your TrakStar administrator.</td></tr>' +
							'<tr><td id="cancelButton" style="width:145px;"></td><td style="padding-left:10px;" id="getPasswordButton2"></td></tr>' +
							'<tr><td id="errorDiv" style="color:red;text-align:center;padding-top:15px;" colspan=2></td></tr>' +
							'</table>';
							
		var callback = function() {
			$('userNameForgot').value = "User Name";
	        $('userNameForgot').observe( 'focus', function() { $('userNameForgot').removeClassName( 'inactiveInput' ).addClassName( 'activeInput' ); if( $('userNameForgot').value === "User Name" ) { $('userNameForgot').value = "" } } );
	        $('userNameForgot').observe( 'blur', function() { if( $('userNameForgot').value == "" ) { $('userNameForgot').removeClassName( 'activeInput' ).addClassName( 'inactiveInput' ); $('userNameForgot').value = "User Name"; } } );
			
			$('companyNameForgot').value = "Company Name";
	        $('companyNameForgot').observe( 'focus', function() { $('companyNameForgot').removeClassName( 'inactiveInput' ).addClassName( 'activeInput' ); if( $('companyNameForgot').value === "Company Name" ) { $('companyNameForgot').value = "" } } );
	        $('companyNameForgot').observe( 'blur', function() { if( $('companyNameForgot').value == "" ) { $('companyNameForgot').removeClassName( 'activeInput' ).addClassName( 'inactiveInput' ); $('companyNameForgot').value = "Company Name"; } } );
	        
	        var sendRequest = new Button( DEFAULT_BUTTON, "Get Password", $("getPasswordButton2"), { iconPosition:"right", icon:"continue_icon", margin:"0px 0px 0px 0px", align:"left" } );
	        var deleteButton = new Button( CANCEL_BUTTON, "Cancel", $('cancelButton'), {onclick:this.showLoginPage.bindAsEventListener( this ), icon:"red_x_icon", margin: "0px 0px 0px 0px", align: "right"} );
	        var buttonText = $('getPasswordButton2').select( '.button_text' );
	        buttonText[0].setStyle( { fontSize:"12px", fontWeight:"normal" } );
	        buttonText = $('cancelButton').select( '.button_text' );
	        buttonText[0].setStyle( { fontSize:"12px", fontWeight:"normal" } );
			
			//Create the form validator
			this.validator = new tsFormValidator( [ [$( 'getPasswordButton2' ), this.requestPasswordByUserCompany.bind( this ) ] ], $( 'loginForm' ) );
			this.validator.add( {'object':$( 'companyNameForgot' ), 'name':"Company Name",'validationType':VALIDATE_REQUIRED, 'validateOnBlur':false, 'noPopup': true } );
			this.validator.add( {'object':$('userNameForgot'), 'name':"User Name", 'validationType':VALIDATE_REQUIRED, 'vaildateOnBlur':false, 'noPopup': true });
			
			
		}.bind( this );
		
		this.changeForgotDivContent( forgotHTML, callback );
	},
   
   //Show the confirmation Div
   	showConfirmation:function() {
		
		var confirmationHTML = 	'<table style="width:100%;margin-top:28px;float:left;">' +
        							'<tr><td id="confirmationText" style="text-align:center;" colspan=2>' +
        								'Instructions to reset your password have been sent to your email address.</td>' +
        								'</tr><tr><td colspan=2><div style="margin:auto;" class="icon icon-s green_check_icon"></div></td></tr>'+
        							'</tr>'+
        							'<tr><td id="reloginButton" colspan="2"></td></tr>' +
        							'</table>';
		
		var callback = function() {
			var reloginButton = new Button(DEFAULT_BUTTON, "Login", $("reloginButton"), {
				onclick: this.showLoginPage.bind( this ),
				icon: "continue_icon",
				iconPosition: "right",
				margin: "10px 0px 0px 127px"
			});
			var buttonText = $('reloginButton').select('.button_text');
			buttonText[0].setStyle({
				fontSize: "12px",
				fontWeight: "normal"
			});
			
		}.bind( this );					
		this.changeForgotDivContent( confirmationHTML, callback, this.showLoginPage );
   	},
	
	//Takes new html content and a callback to execute before the new content is shown (which usually adds buttons and events)
	changeForgotDivContent:function( newContent, callback, formAction ) {
		if( this.validator ) {
			this.validator.destroy();
		}
		this.eventManager.clearAllListeners();
		if( !formAction ) {
			formAction = function() {};
		}
		this.eventManager.watch( $('loginForm'), 'submit', formAction.bind( this ) );
		
		new Effect.Fade( $('forgotDiv'), { 
				duration:.2, 
				afterFinish: function() {
					if( $("forgotDiv").down() ) {
						$("forgotDiv").down().remove();
					}
					$('forgotDiv').update( newContent );
					if( callback ) callback();
					new Effect.Appear( $('forgotDiv'), { delay:.2, duration:.2 } );
				}		
		});
	},
	
	showLoginPage:function( e ){
		if( this.validator ) {
			this.validator.destroy();
		}
		this.eventManager.clearAllListeners();
		this.eventManager.watch( $('loginForm'), 'submit', this.login.bind( this ) );
		
        new Effect.Fade( $('forgotDiv'), {
            duration: .2,
            afterFinish:function(){
				$('forgotDiv').update('');
                new Effect.Appear( $('loginDiv'), {
                    duration:.35,
                    afterFinish:function() {
                        $( 'userName' ).select();
                    }
                });
            }
        });
    },
   	
   	
	
/**
 * 
 * End Request Password Code
 * 
 */






    setActive:function( id, str ){
        if( $F( id ) == str || $F( id ).length == 0 ){
            $( id ).value = '';
        }
        $( id ).removeClassName( 'inactiveInput' ).addClassName( 'activeInput' );
    },
   
    setInactive:function( id, str ){
        if( $F( id ).length == 0 ){
            $( id ).value = str;
            $( id ).removeClassName( 'activeInput' ).addClassName( 'inactiveInput' );
            return true;
        }
    },
   
    login:function(e){
    	if( $('loginDiv').style.display == "" ) {
	        this.clearLoadingNotification();
	        this.showLoadingSpinner();
	        if ( $( "redirect_info" ) ) {
	            $( "redirect_info" ).style.display = "none";
	        }
			if ( $( "oldVersionLink" ) ) {
				$( "oldVersionLink" ).hide();
			}
	       
	        if( !this.config.hasCookie ){
	            this.config.orgname = $F( 'companyName' )
	        }
	        
	        var params = { "ie6":browser.isIE6x, "isIE":browser.isIE, "logout":this.config.logout, "companyName":this.config.orgname, "userName":$F('userName'), "password":$F('password') };
	        if( $( 'action' ) ){
	        	params.action = $F( 'action' ); 
	        }
	        if( $( 'id' ) ){
	        	params.id = $F( 'id' ); 
	        }
	        
	        if( $( 'passwordReset' ) ){
	        	params.passwordReset = $F( 'passwordReset' ); 
	        }
	        
	        new Ajax.Request( 'https://' + this.config.url + '/servlet/EmployeeLogin', {
	            method: 'POST',
	            parameters:params,
	            onSuccess: this.loginResult.bind( this )
	        });
	    }
       
    },
   
    loginResult:function( response ){
        var data = eval( '(' + response.responseText + ')' );
       
        if( data.success ){
        	if( data.passwordReset || data.passwordExpired ){
        		this.resetPassword( data );
        	}
        	else {
        		this.sendRedirect( data );
        	}
            
        } else {
			if (data.smb) {
				this.fadeInExpiredScreen();
			}
			else {
				this.showLoadingNotification("Login failed.");
				$('userName').addClassName("login_failed");
				$('password').addClassName("login_failed");
				this.registerTabKeyListener(true);
			}
		}
       
    },
	
	
	
	
	
	fadeInExpiredScreen: function() {
		new Effect.Fade( $('loginDiv'), {
            duration:.35,
            afterFinish:this.displayExpiredScreen.bind( this )
        });
    },
    
    displayExpiredScreen: function() {
    	$('expiredAccountDiv').update( '' );
        $('expiredAccountDiv').style.display = "none";
 
 
        // say something about why they must enter a new password TODO
        // say something about confirming the password with the second input TODO
        var expiredHtml = '<table style="width:100%;margin-top:0px;float:left;" cellpadding="5">' +
        					'<tr><td align="left" style="text-align:center;" colspan=2>' +
			      				'Sorry, your Trakstar Small Business account has been deactivated. <br/><br/>Please contact Trakstar support at support@promantek.com' +
							'</td></tr>' +
							'<tr><td id="okExpiredButton"></td></tr>' +
							'</table>';
       
        $('expiredAccountDiv').update( expiredHtml );
        
        var sendRequest = new Button( DEFAULT_BUTTON, "Back to Login Screen", $("okExpiredButton"), { iconPosition:"right", margin:"0px 0px 10px 92px", onclick: this.fadeOutExpiredScreen.bind(this) } );
        var buttonText = $('okExpiredButton').select( '.button_text' );
        buttonText[0].setStyle( { fontSize:"12px", fontWeight:"normal" } );

		new Effect.Appear( $('expiredAccountDiv'), { duration:.2 } );
    },
	
	fadeOutExpiredScreen: function() {
		$('login_spinner').hide();
		
		new Effect.Fade( $('expiredAccountDiv'), {
        duration:.35,
      	afterFinish:function() { new Effect.Appear( $('loginDiv'), { duration:.2 } ); } });
			
	},
	

	
    
    resetPassword:function( data ){
    	this.data = data;
    	this.showChangePassword();
    },
    
    passwordResetSuccess:function(){
    	new Effect.Fade( $('changePassDiv'), {
            duration:.35,
            afterFinish:function(){
    			$('changePassDiv').update( 
    			
    			'<div class="icon-s green_check_icon" style="float:right;margin: 51px 27px 0px 16px;"></div><div style="padding-top:50px;float:right;">' +
    			' Password successfully changed' +
    			'</div><div style="clear:both;">' +
    			 '<img style="padding:15px 0px 0px 0px;" src="../ui/images/login_images/login_loading.gif" alt="Loading..."/>' +
    			 '</div>'
    			 
    			
    			);
				
					new Effect.Appear( $('changePassDiv'), {
	            		duration:.35
	           		} );
	           		
	           		this.passwordResetSuccess2.bind( this ).delay( 2 );
    		}.bind( this )
        });
    },
    
    passwordResetSuccess2:function(){
		new Effect.Fade( $('changePassDiv'), {
        	duration:.35,
            afterFinish:this.sendRedirect.bind( this, this.data )
   		} );
    },
    
    sendRedirect:function( data ){
    	if( data.redirect ){
	        window.location = data.redirect;
	    }
	    else
	    {
	        this.showRoles( data );
	        $( "userName" ).removeClassName( "login_failed" );
	        $( "password" ).removeClassName( "login_failed" );
	    }
    },
    
    showRoles:function( data ){
        this.clearLoadingNotification();
       
        new Effect.Fade( $('loginDiv'), {
            duration:.35,
            afterFinish:this.displayRoles.bind( this, data )
        });
       
        this.roleTemplate = new Template(
            '<td style="padding-left:#{margin}px;width:#{width};">'+
                '<a class="login_role_button" href="/servlet/EmployeeLogin?loginType=#{link}">'+
                    '<div id="#{id}" style="display:none;height:78px;width:72px;" class="login_role_button">'+
                        '<div class="navbar_icon_wrapper role_inner"><div class="navbar_icon icon-l #{icon}"></div></div>'+
                        '<span class="navbar_text role_inner">#{text}</span>'+
                    '</div>'+
                '</a>'+
            '</td>'
        );
    },
   
    showLoadingSpinner: function() {
        $( "login_spinner" ).style.display = "inline";
    },
   
    showLoadingNotification: function(text) {
        $( "login_spinner" ).style.display = "none";
        $( "login_notification" ).style.display = "block";
        $( "login_notification" ).update(text);
       
        Effect.Shake( 'content_back', {distance:3, duration:.4} );
        Effect.Fade( $("login_notification"), { duration: .2, delay: 2 } );
    },
   
    clearLoadingNotification: function() {
        $( "login_notification" ).update("");
        $( "login_notification" ).style.display = "none";
        $( "login_spinner" ).style.display = "none";
    },
   
    displayRoles:function( data ){
        $('roleDiv').update( '' );
        $('roleDiv').style.display = "block";
        var width = "50%";
        var margin = "35";
        if( data.isManager && data.isAdmin ){
            width = "33%";
            margin = "10";
        }
        var s = this.roleTemplate.evaluate( { "id":"role_emp", "link":"Employee", "text":"<u>E</u>mployee", "width":width, "margin":margin, "icon":"role_icon" } );
        if( data.isManager ){
            s += this.roleTemplate.evaluate( { "id":"role_mgr", "link":"Manager", "text":"<u>M</u>anager", "width":width, "margin":margin, "icon":"manager_icon" } );
        }
        if( data.isAdmin ){
            s += this.roleTemplate.evaluate( { "id":"role_adm", "link":"admin", "text":"<u>A</u>dministrator", "width":width, "margin":margin, "icon":"admin_icon" } );
        }
        this.isManager = data.isManager;
        this.isAdmin = data.isAdmin;
       
        $('roleDiv').update( '<table style="width:100%;margin-top:20px;float:left;"><tr>' + s + '</tr><tr><td id="cancelDiv" style="display: none;" colspan=3></td></tr></table>' );
       
        var buttonMargin = "25px 0 0 120px";
        if (browser.isIE6x) {
            buttonMargin= "25px 0 0 61px";
        }
        var deleteButton = new Button( CANCEL_BUTTON, "Cancel", $('cancelDiv'), {onclick:this.cancelLogin.bindAsEventListener( this ), icon:"red_x_icon", margin: buttonMargin, align: "left"} );
       
        var buttons = [ $('role_emp') ];
       
        if ( data.isManager ) {
            buttons.push( $('role_mgr') );
        }
        if ( data.isAdmin ) {
            buttons.push( $('role_adm') );
        }
       
        if( data.isEmployeeTraining ){
        	this.createTrainingBubble( $("role_emp") );
        }
        else if (data.numEmployeeTasks > 0) {
            this.createNumberBubble( $("role_emp"), data.numEmployeeTasks );
        }
        if( data.isManagerTraining ){
        	this.createTrainingBubble( $("role_mgr") );
        }
        else if (data.numManagerTasks > 0) {
            this.createNumberBubble( $("role_mgr"), data.numManagerTasks );
        }

        this.registerRoleButtonListeners( buttons );
       
        this.registerKeystrokeListener();
       
        var showArr = [ 'role_emp', 'role_mgr' ];
        if( data.isAdmin ){
            showArr.push( 'role_adm' );
        }
       
        
        new Effect.Appear( $('role_emp'), { duration:.2,
            afterFinish:function(){
	            if( data.helpEnabled ){
	            	var eHelp = {"listenEvent":1,"animationSequence":0,"animationName":"empHelp","idType":0,"id":"role_emp","text":"The Employee Role allows you to:<br><ul><li>Complete your self appraisal</li><li>View your performance plan</li><li>View your information</li><li>Change your password</li></ul>","duration":2,"position":"left","className":"","margin":"0 10px 0 -10px;","invokeJavascript":""};
	            	new tsHelpAnimationPopup(
	    				 eHelp,
	    				'role_emp', 10 );
	
	            	new tsHelpObserver( eHelp );
	            }
	            
                if( data.isManager )
                {
                    new Effect.Appear( $('role_mgr'), { duration:.2,
                        afterFinish:function(){
                            if( data.isAdmin ){
                                new Effect.Appear( $('role_adm'), { duration:.2,
                                	afterFinish:function(){

                                    if( data.helpEnabled ){
	                                	var aHelp = {"listenEvent":1,"animationSequence":0,"animationName":"admHelp","idType":0,"id":"role_adm","text":"The Administrator Role allows you to:<br><ul><li>Create and edit employees</li><li>Manage appraisals</li><li>Adjust Preferences</li><li>Generate employee reports</li></ul>","duration":2,"position":"right","className":"","margin":"0 -10px 0 10px;","invokeJavascript":""};
	                                	new tsHelpAnimationPopup(
	                        				aHelp,
	                        				'role_adm', 10 );
	                                	new tsHelpObserver( aHelp );
                                    }
                            	} } );
                                
                            }

                            if( data.helpEnabled ){
                            	var mHelp = {"listenEvent":1,"animationSequence":0,"animationName":"mgrHelp","idType":0,"id":"role_mgr","text":"The Manager Role allows you to:<br><ul><li>View your employees</li><li>Complete appraisals</li><li>Set goals</li><li>Generate employee reports</li></ul>","duration":2,"position":( data.isAdmin ? "bottom" : "right") ,"className":"","margin":"0 -10px 0 10px;","invokeJavascript":""};
                            	new tsHelpAnimationPopup(
                    				mHelp,
                    				'role_mgr', 10 );
                            	new tsHelpObserver( mHelp );
                            }
                        }
                    });
                }
                else if( data.isAdmin ){
                    new Effect.Appear( $('role_adm'), { duration:.2,
                        afterFinish:function(){

	                    if( data.helpEnabled ){
	                    	var aHelp = {"listenEvent":1,"animationSequence":0,"animationName":"admHelp","idType":0,"id":"role_adm","text":"The Administrator Role allows you to:<br><ul><li>Create and edit employees</li><li>Manage appraisals</li><li>Adjust Preferences</li><li>Generate employee reports</li></ul>","duration":2,"position":"right","className":"","margin":"0 -10px 0 10px;","invokeJavascript":""};
	                    	new tsHelpAnimationPopup(
	            				aHelp,
	            				'role_adm', 10 );
	                    	new tsHelpObserver( aHelp );
	                    }
                    } } );
                }
            }
        });
       
        var cancelDelay = .2;
        new Effect.Appear( $('cancelDiv'), { delay: cancelDelay, duration: .2 } );
    },
   
    registerKeystrokeListener:function(){
        this.keyListener = this.handleKeystroke.bindAsEventListener( this );
        Event.observe(document, 'keydown', this.keyListener );
    },
   
    handleKeystroke:function( e ){
        var key = e.which || e.keyCode;
        if ( key == Event.KEY_ESC )
        {
            this.cancelLogin();
        } else {
            if ( key == 69 ){
                window.location = "/servlet/EmployeeLogin?loginType=Employee";
                $('role_emp').addClassName( "login_role_button_active" );
            }
            else if ( key == 77 && this.isManager ){
                window.location = "/servlet/EmployeeLogin?loginType=Manager";
                $('role_mgr').addClassName( "login_role_button_active" );
            }
            else if ( key == 65 && this.isAdmin ){
                window.location = "/servlet/EmployeeLogin?loginType=admin";
                $('role_adm').addClassName( "login_role_button_active" );
            } 
        }
    },
   
    createNumberBubble: function( element, number ) {
        if (browser.isIE6x) return;
        var className = "tsNumberBubble_small";
        if ( number > 9 ) {
            className = "tsNumberBubble_large";
        }
        var bubble = new Element( "div", { "class":"tsNumberBubble_button" } );
        bubble.update( '<div class="' + className + '">' + number + '</div>' );
        element.appendChild( bubble );
    },
    
    
    createTrainingBubble: function( element ) {
        if (browser.isIE6x) return;
        var bubble = new Element( "div", { "class":"tsNumberBubble_button" } );
        bubble.update( '<div class="tsNumberBubble_training">&nbsp;</div>' );
        element.appendChild( bubble );
    },
   
    registerRoleButtonListeners: function( buttons ) {
        this.buttonListeners = new Array();
       
        this.roleButtonManager = new tsEventManager();
        buttons.each( function(b) {
            this.buttonListeners.push( new tsRoleButton( b ) );
        }, this);
    },
   
    cancelLogin:function( ){
        Event.stopObserving(document, 'keydown', this.keyListener );
       
        new Effect.Fade( $('roleDiv'), {
            duration: .2,
            afterFinish:function(){
                new Effect.Appear( $('loginDiv'), {
                    duration:.35,
                    afterFinish:function(){
                        $( 'userName' ).select();
                    }
                });
            }
        });
    },
   
    clearOrg:function(){
        this.config.hasCookie = false;
        $( 'orgText' ).style.display = 'none';
        $( 'orgInput' ).style.display = 'block';
       
        $( 'companyName' ).value = "Organization Name";
        $( 'companyName' ).observe( "focus", this.focusOrganization.bind(this) );
        $( 'companyName' ).observe( "blur", this.blurOrganization.bind(this) );
    },
    
    showChangePassword: function() {
		new Effect.Fade( $('loginDiv'), {
            duration:.35,
            afterFinish:this.displayChangePassword.bind( this )
        });
    },
    
    displayChangePassword: function() {
    	$('changePassDiv').update( '' );
        $('changePassDiv').style.display = "none";
 
 		var msg = "";
        if( this.data.passwordReset ){
        	msg = "Please reset your password.";
        }
        else if( this.data.passwordExpired ){
        	msg = "Your password has expired.  <br/> Please enter a new one.";
        }
        // say something about why they must enter a new password TODO
        // say something about confirming the password with the second input TODO
		
		//different change pass html for ie and firefox... ugh
        var changePassHTML; 
		
		if( browser.isIE ) {
			changePassHTML = '<table style="width:100%;margin-top:0px;float:left;" cellpadding="5">' +
        					'<tr><td align="left" style="text-align:center;" colspan=2>' +
			      				msg +
							'</td></tr>' +
        					'<tr><td align="left" colspan=2>' +
								'<input type="password" name="changePass" id="changePass" style="display:none;" />' +
			      				'<input class="inactiveInput" type="text" name="fakeChangePass" id="fakeChangePass" value="New password">' +
							'</td></tr>' +
							'<tr><td align="left" colspan=2>' +
								'<input type="password" name="changePass2" id="changePass2" style="display:none;" />' +
			      				'<input class="inactiveInput" type="text" name="fakeChangePass2" id="fakeChangePass2" value="Repeat new password">' +
							'</td></tr>' +
							'<tr><td id="changePasswordButton"></td></tr>' +
							'</table>';
			
		} else {
			changePassHTML = '<table style="width:100%;margin-top:0px;float:left;" cellpadding="5">' +
        					'<tr><td align="left" style="text-align:center;" colspan=2>' +
			      				msg +
							'</td></tr>' +
        					'<tr><td align="left" colspan=2>' +
			      				'<input class="inactiveInput" type="text" name="changePass" id="changePass" value="New password">' +
							'</td></tr>' +
							'<tr><td align="left" colspan=2>' +
			      				'<input class="inactiveInput" type="text" name="changePass2" id="changePass2" value="Repeat new password">' +
							'</td></tr>' +
							'<tr><td id="changePasswordButton"></td></tr>' +
							'</table>';
			
		}
							
       
        $('changePassDiv').update( changePassHTML );
        
        var sendRequest = new Button( DEFAULT_BUTTON, "Change Password", $("changePasswordButton"), { iconPosition:"right", icon:"security_icon", margin:"0px 0px 10px 85px", onclick: this.changePassword.bind(this) } );
        var buttonText = $('changePasswordButton').select( '.button_text' );
        buttonText[0].setStyle( { fontSize:"12px", fontWeight:"normal" } );
       
        $('loginForm').observe( 'submit', this.changePassword.bind( this ) );
     
		this.passwordChecker = new tsPasswordChecker( { "input":$( 'changePass' ), 'minLevel':this.data.passwordLevel, 'minLength':this.data.passwordLength } );
       
	   if (browser.isIE) {
	   		$('fakeChangePass').observe("focus", this.focusFakePassword.bind(this) )
			$('fakeChangePass2').observe("focus", this.focusFakePassword.bind(this))
	   
	   } else {
		   $('changePass').observe("focus", this.focusNewPassword.bind(this));
		   $('changePass2').observe("focus", this.focusNewPassword2.bind(this));
	   }
		new Effect.Appear( $('changePassDiv'), { duration:.2 } );
    },
    
    
	focusNewPassword:function(){
        this.setActive( 'changePass', 'New password' );
        this.coverNewPassword( $( 'changePass' ) ); 
    },
   
	focusNewPassword2:function(){
        this.setActive( 'changePass2', 'Repeat new password' );
        this.coverNewPassword( $( 'changePass2' ) );
    },
	
	focusFakePassword:function( e ) { 
		var element = e.element();
		if( element.id == "fakeChangePass" ) {
			$( element.id ).hide();
			$("changePass").show();
			$("changePass").focus();
		} else {
			$( element.id ).hide();
			$("changePass2").show();
			$("changePass2").focus();
		}
	},

    coverNewPassword:function( element ) {
        if ( element.type == "text" ) {
            element.type = "password";
        }
    },
    
    changePassword: function(e) {
    	// first check if values of the two inputs match
  		if( e ) e.stop();
    	if( $('changePass').value == $('changePass2').value ) {
    	
    		if( this.passwordChecker.getPasswordLevel() < this.data.passwordLevel ){
				alert( "Your new password isn't strong enough." );
			} else if( !this.passwordChecker.lengthOK( this.passwordChecker.input.value ) ) {
				alert( "Your new password is too short." );
			} else {
		  		new Ajax.Request( 'https://' + this.config.url + '/servlet/ChangePasswordServlet', {
		            method: 'POST',
		            parameters:{ "pass": $('changePass').value },
		            onSuccess: this.passwordResetSuccess.bind( this )
		        });
		    }
		}
		else {
			alert( 'The two passwords do not match' );
		}
    }
   
});

//Use on forgotPassword.jsp (reset via token)
var tsResetPassword = Class.create({
	
	initialize: function( config ){
		this.checkSecure();
		this.config = config;
		this.token = config.token;
		
		if( !browser.isIE ){
            $( 'password1' ).type = "text";
			$( 'password2' ).type = "text";
        } else {
        	$( 'fakePassword1' ).value = "New Password";
        	$( 'fakePassword1' ).observe( 'focus', this.fakeClick.bind(this) );
			$( 'fakePassword2' ).value = "Confirm Password";
        	$( 'fakePassword2' ).observe( 'focus', this.fakeClick.bind(this) );
        	
			$( 'password1' ).observe( 'blur', this.fakeBlur.bind(this) );
			$( 'password2' ).observe( 'blur', this.fakeBlur.bind(this) );
        }
       
        $( 'password1' ).value = "New Password";
        $( 'password2' ).value = "Confirm Password";
       
        $( 'password1' ).observe( "focus", this.focusPassword.bind( this ) );
        $( 'password2' ).observe( "focus", this.focusPassword.bind( this ) );
       
       
	    if( !browser.isIE ) {
       		$( 'password1' ).observe( "blur", this.blurPassword.bind( this ) );
			$( 'password2' ).observe("blur", this.blurPassword.bind( this ));
       	}
		
		loadButtons();
		
		this.passwordLevel = config.passwordLevel;
		this.passwordLength = config.passwordLength; 
		
		//For some reason this is how tsFormValidator is implemented, the passwordLevel, and Checker have to be global vars
		passwordLevel = this.passwordLevel;
		passwordLength = this.passwordLength;
		passwordChecker = new tsPasswordChecker( { "input":$( 'password1' ), 'minLevel':this.passwordLevel, 'minLength':this.passwordLength } );
		
		passValidator = new tsFormValidator( [ [$( 'changePasswordButton' ), this.resetPassword.bind( this ) ] ], $( 'changePassForm' ) );
		passValidator.add( {'object':$( 'password1' ), 'name':"A valid password",'validationType':VALIDATE_PASSWORD, 'validateOnBlur':false, 'noPopup': true } );
		passValidator.add( {'object':$('password2'), 'name':"Passwords must match", 'validationType':VALIDATE_FUNCTION, 'vaildateOnBlur':false, 'noPopup': true, 'validate': function() { if( $('password1').value != $('password2').value ) return "Passwords do not match"; } });
		
		//Stop the form from actually submitting
		$('changePassForm').observe("submit", function( e ) { e.stop();});
		
	},
	
	focusPassword:function( event ){
		var element = Event.element(event);
        this.setActive( element.id, (element.id == 'password1') ? 'New Password':'Confirm Password' );
        this.coverPassword( element );
    },
   
    coverPassword:function( element ) {
        if ( element.type == "text" ) {
            element.type = "password";
        }
    },
	
	resetPassword:function(){
		new Ajax.Request( "https://" + this.config.url + "/servlet/ForgotPasswordServlet", {
			method:'POST',
			parameters: {"password":$('password1').value,"token": this.token, "action":"reset"},
			onSuccess: this.resetComplete.bind( this )
		});
		

	},
	
	resetComplete:function( response ) {
		var status = eval( '(' + response.responseText + ')' ).status
		
		
		if (status == "success") {
			new Effect.Fade( $("loginDiv"), {
			duration: .2,
			afterFinish:function() {
				new Effect.Appear( $("confirmationDiv"), {
					duration:.2
				});
			}
			});
		} else {
			new Effect.Fade( $("loginDiv"), {
			duration: .2,
			afterFinish:function() {
				new Effect.Appear( $("invalidDiv"), {
					duration:.2
				});
			}
			});
		}
		
		
	},
	
	setActive:function( id, str ){
        if( $F( id ) == str || $F( id ).length == 0 ){
            $( id ).value = '';
        }
        $( id ).removeClassName( 'inactiveInput' ).addClassName( 'activeInput' );
    },
   
    setInactive:function( id, str ){
        if( $F( id ).length == 0 ){
            $( id ).value = str;
            $( id ).removeClassName( 'activeInput' ).addClassName( 'inactiveInput' );
            return true;
        }
    },
    
	
	fakeToggle:function( element ) {
		element.toggle();
    	if( element.id == "fakePassword1" ) {
			$("password1").toggle();
		} else if( element.id == "fakePassword2"){
			$("password2").toggle();
		} else if( element.id == "password1") {
			$("fakePassword1").toggle();
		} else if( element.id == "password2") {
			$("fakePassword2").toggle();
		}
		
    	
    },
    
    fakeClick:function( event ) {
		var element = Event.element(event);
    	if( element.style.display != "none" ) {
    		this.fakeToggle( element );
    		if( element.id == 'fakePassword1' ) {
				$( 'password1' ).focus();
			} else {
				$( 'password2' ).focus();
			}
    	}
    },
    
	blurPassword:function( event ){
		var element = Event.element( event );
		var text = element.id == "password1" ? "New Password" : "Confirm Password";
        if( this.setInactive( element.id, text ) && !browser.isIE ){
            element.type = "text";
        }
    },
	
    fakeBlur:function( event ) {
		var element = Event.element(event);
    	if( element.value == '' ) {
    		this.fakeToggle( element );
    	}
    },
	
	checkSecure:function(){
        if( window.location.href.startsWith( 'http://' ) ){
            window.location = 'https://' + window.location.href.substring( 7, window.location.href.length );
        }
    }
	
	
});

var tsRoleButton = Class.create({
   
    initialize: function( element ) {
        this.element = element;
        this.eventManager = new tsEventManager();
        this.baseClassName = "login_role_button";
        this.registerListeners();
    },
   
    registerListeners: function() {
        this.eventManager.watch( this.element, 'mouseover', this.roleButtonOver.bind( this ) );
        this.eventManager.watch( this.element, 'mouseout', this.roleButtonOut.bind( this ) );
        this.eventManager.watch( this.element, 'mousedown', this.roleButtonDown.bind( this ) );
        this.eventManager.watch( this.element, 'mouseup', this.roleButtonUp.bind( this ) );
    },
   
    roleButtonOver: function( element ) {
        element.addClassName( this.baseClassName + "_hover" );
    },
   
    roleButtonOut: function( element ) {
        element.removeClassName( this.baseClassName + "_hover" );
        element.removeClassName( this.baseClassName + "_active" );
    },
   
    roleButtonDown: function( element ) {
        element.removeClassName( this.baseClassName + "_hover" );
        element.addClassName( this.baseClassName + "_active" );
    },
   
    roleButtonUp: function( element ) {
        element.removeClassName( this.baseClassName + "_active" );
        element.addClassName( this.baseClassName + "_hover" );
    },
   
    destroy: function() {
        this.eventManager.clearAllListeners();
    }
});

