var tsLogin =  Class.create({

    initialize: function( config )
    {
        this.checkSecure();
        this.config = config;
        this.preloadImages();
        
        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();
       
        $('loginForm').observe( '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 = "../ui/images/login_images/login_loading.gif";
		  
		  var img2 = new Image();
		  img2.src = "../ui/images/login_images/login_buttons." + ext;
		  
		  var img3 = new Image();
		  img3.src = "../ui/images/tsNumberBubble/numberBubble_small." + ext;
		  
		  var img4 = new Image();
		  img4.src = "../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";
        }
    },
    
    forgotPassword:function() {
    	 new Effect.Fade( $('loginDiv'), {
            duration:.35,
            afterFinish:this.displayForgotPassword.bind( this )
        });

    },
    
    displayForgotPassword:function() {
    	$('forgotDiv').update( '' );
        $('forgotDiv').style.display = "none";
 
        
        var forgotHTML = '<table style="width:100%;margin-top:20px;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;">To retrieve your password please enter your email address</td></tr>' +
							'<tr><td id="getPasswordButton"></td></tr>' +
							'<tr><td id="cancelButton"></td></tr>' +
							'</table>';
       
        $('forgotDiv').update( forgotHTML );
        
        $('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, "Get Password", $("getPasswordButton"), { iconPosition:"right", icon:"continue_icon", margin:"25px 0px 10px 100px", onclick: this.requestPassword.bind(this) } );
        var deleteButton = new Button( CANCEL_BUTTON, "Cancel", $('cancelButton'), {onclick:this.cancelRetrieval.bindAsEventListener( this ), icon:"red_x_icon", margin: "0px 0px 0px 120px", align: "left"} );
        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" } );
       
        $('loginForm').observe( 'submit', this.requestPassword.bind( this ) );
       
		new Effect.Appear( $('forgotDiv'), { duration:.2 } );
       
    },
    
  	requestPassword:function(e) {
  		if( $('forgotDiv').style.display === "") {
	  		if( e ) e.stop();
	  		new Ajax.Request( 'https://' + this.config.url + '/servlet/PasswordResetServlet', {
		            method: 'POST',
		            parameters:{ "email": $('email').value },
		            onSuccess: this.showConfirmation.bind( this )
		        });
		}
    },
    
    passwordRetrievalFail:function() {
    	$( 'email' ).addClassName( 'login_failed' );
    	Effect.Shake( 'content_back', {distance:3, duration:.4} );
    },
   
   	showConfirmation:function( response ) {
 		var success = eval( '(' + response.responseText + ')' ).success;
   		if( success === "false" ) {
   			this.passwordRetrievalFail();
   		} else {
   			$('loginForm').observe( 'submit', this.showLoginPage.bind( this ) );
   			new Effect.Fade( $('forgotDiv'), { duration:.2 } );
	   		$('confirmationDiv').style.display = "none";
	   		var confirmationHTML = 	'<table style="width:100%;margin-top:45px;float:left;">' +
	        							'<tr><td align="right" style="width:205px;">' +
	        								'Request Sent</td>' +
	        								'<td><div class="icon icon-s green_check_icon"></div></td>'+
	        							'</tr>'+
	        							'<tr><td id="reloginButton" colspan="2"></td></tr>' +
	        							'</table>';
	        $('confirmationDiv').update( confirmationHTML );
	        new Effect.Appear( $('confirmationDiv'), { delay:.2, duration:.2 } );
	        var reloginButton = new Button( DEFAULT_BUTTON, "Login", $("reloginButton"), 
	        	{ onclick: function() { new Effect.Fade( $('confirmationDiv'), { duration:.2, afterFinish: function() { new Effect.Appear( $('loginDiv'), {duration:.2 } ); } } ); }
	        		, icon:"continue_icon", iconPosition:"right",  margin:"10px 0px 0px 127px" } );	
	        var buttonText = $('reloginButton').select( '.button_text' );
       		buttonText[0].setStyle( { fontSize:"12px", fontWeight:"normal" } );
        }						
   	},
   	
   	cancelRetrieval:function(){
        new Effect.Fade( $('forgotDiv'), {
            duration: .2,
            afterFinish:function(){
                new Effect.Appear( $('loginDiv'), {
                    duration:.35,
                    afterFinish:function(){
                        $( 'userName' ).select();
                    }
                });
            }
        });
    },
   	
   	showLoginPage:function( e ) {
   		if( $('confirmationDiv').style.display == "" ) {
   			if( e ) e.stop();
   			new Effect.Appear( $('loginDiv'), {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;
        }
    },
   
    login:function(e){
    	if( $('loginDiv').style.display == "" ) {
        	e.stop();
	        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
        var 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 } );
       
        $( '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' ) );
    },

    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' );
		}
    }
   
});

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();
    }
});
