
// /////////////////////
// communityModule class
// /////////////////////
//fields
pdLoginModule.prototype._transport;
pdLoginModule.prototype._user;
pdLoginModule.prototype._channelId = 'site.community';
pdLoginModule.prototype._redirectUrl = '';

function pdLoginModule(){}

pdLoginModule.prototype.initialize = function(transport, user){
  	//this function is called back during module registration
	this._transport = transport;
	this._user = user;
	
	//get the current location
	var location = window.location.toString();
	
	//if we're looking to logout then destroy the users cookie
	if(location.indexOf('logout.aspx') != -1){	
		this._user.destroy();
	}
	
	//if we have a search in the location then set the redirect url
	var queryParams = window.location.toString().toQueryParams();
	
	if(queryParams.rurl && queryParams.rurl.length > 0){
		this._redirectUrl = queryParams.rurl;
	}
	
	//configure browser notices if needed
	var browser = pd_globalSiteFramework.getBrowser();

	if(browser.isOutdated()){
		$('invalidOutdated').show();
		$('invalidPane').show();
	}
	
	if(!browser.hasCookies()){
		$('invalidCookies').show();
		$('invalidPane').show();
	}	

	//reset inputs
	$$('.community-main input').each(function(input){input.value = '';});	
	
	//default inputs
	$('loginUsername').value = 'username';
	$('loginPassword').value = 'password';
	$('forgotEmail').value = 'e-mail address';
	$('signupCaptcha').value = 'enter characters above';	
	$('signupCaptchaImage').src = '/2/framework/captchaservice.aspx';
	
	//input focus
	$('loginUsername').observe('focus', this.onInputFocus.bind(this));
	$('loginPassword').observe('focus', this.onInputFocus.bind(this));
	$('loginPassword').observe('keypress', this.watchForEnter.bindAsEventListener(this, 'loginLink'));
	$('forgotEmail').observe('focus', this.onInputFocus.bind(this));
	$('signupCaptcha').observe('focus', this.onInputFocus.bind(this));
	$('signupCaptcha').observe('keypress', this.watchForEnter.bindAsEventListener(this, 'signupLink'));
	
	//submit actions
	$('loginLink').observe('click', this.onLoginClick.bind(this));	
	$('forgotLink').observe('click', this.onForgotSendClick.bind(this));
	$('signupLink').observe('click', this.onSignupClick.bind(this));	
	
}

pdLoginModule.prototype.onInputFocus = function(event){$(Event.element(event)).value = '';}
pdLoginModule.prototype.watchForEnter = function(event, elementId){
    switch(event.keyCode){
        case Event.KEY_TAB:
        case Event.KEY_RETURN: {
            if(elementId == 'loginLink'){
                this.onLoginClick(event);
            }else if(elementId == 'signupLink'){
                this.onSignupClick(event);
            }
            return;
        }
    }    
};

pdLoginModule.prototype.onLoginClick = function(event){
	Event.stop(event);
	var error = $('loginError');
	error.update();
	error.hide();
	if($('loginUsername').value.length == 0){
		error.update('enter your username');
		error.show();
		$('loginUsername').focus();
		pd_globalSiteFramework.trackEvent('Community Login', 'Login - error', 'No username');
	}else if($('loginPassword').value.length == 0){
		error.update('enter your password');
		error.show();
		$('loginPassword').focus();
		pd_globalSiteFramework.trackEvent('Community Login', 'Login - error', 'No password');
	}else{
		//delegate to the framework		
		pd_globalSiteFramework.login($('loginUsername').value, $('loginPassword').value, this.onLoginResponse.bind(this));
	}
}
pdLoginModule.prototype.onLoginResponse = function(objResponse){
	if(objResponse.result == 'ok'){
		pd_globalSiteFramework.trackEvent('Community Login', 'Login - success');
		
		if(this._redirectUrl.length > 0){
			window.location = this._redirectUrl;
		}else{
			window.location = '/profiles/' + escape(objResponse.username) + '_edit_' + objResponse.id + '.aspx';
		}
	}else{
		$('loginError').update(objResponse.message);
		$('loginError').show();
		pd_globalSiteFramework.trackEvent('Community Login', 'Login - error', 'Invalid credentials');
	}
}

pdLoginModule.prototype.onForgotSendClick = function(event){
	Event.stop(event);
	if($('forgotEmail').value.length == 0){
		$('forgotError').update('Enter your email address');
		$('forgotError').show();
		pd_globalSiteFramework.trackEvent('Community Login', 'Forgot - error', 'No email');
	}else{
		var request = {email : $('forgotEmail').value}
		this._transport.transmitRequest('framework', 'forgotlogin', request, this.onForgotResponse.bind(this));
	}
}
pdLoginModule.prototype.onForgotResponse = function(objResponse){
	$('forgotError').update();
	$('forgotError').hide();

	if(objResponse.result == 'ok'){
		$('forgotSuccessPane').show();
		pd_globalSiteFramework.trackEvent('Community Login', 'Forgot - success');
	}else{
		$('forgotError').update(objResponse.message);
		$('forgotError').show();	
		pd_globalSiteFramework.trackEvent('Community Login', 'Forgot - error', 'Email not found');	
	}
}

pdLoginModule.prototype.onSignupClick = function(event){
	Event.stop(event);
	
	if(this.isValidUsername() && this.isValidPassword() && this.isValidEmail() && this.isValidCaptcha()){
		this.clearSignupError();
		
		//build the request to send
		var request = {
			username: $('signupUsername').value,
			password: $('signupPassword').value,
			email: $('signupEmail').value,
			captcha: $('signupCaptcha').value,
			receiveEmail: $('signupReceiveEmail').checked
		}
				
		this._transport.transmitRequest('site.shared', 'createaccount', request, this.onSignupResponse.bind(this));
	}
}
pdLoginModule.prototype.onSignupResponse = function(objResponse){
	if(objResponse.result == 'ok'){
		$('signupPane').hide();
		$('signupSuccessPane').show();
		pd_globalSiteFramework.trackEvent('Community Signup', 'Signup - success');	
	}else{
		this.setSignupError(objResponse.message);		
	}
}

pdLoginModule.prototype.isValidUsername = function(){
	var username = $('signupUsername');
	if(username.value.length == 0){
		this.setSignupError('Enter a username');
		username.focus();
		return false;
	}else if(username.value.length < 6){
		this.setSignupError('Username must be at least six characters');
		username.focus();
		return false;	
	}else{	
		var goodCharacters = ['@','_','-','.','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'];
		var usernameUpper = username.value.toUpperCase();
		var isValid = true;
		for(var x=0; x<usernameUpper.length; x++){
			if(goodCharacters.indexOf(usernameUpper.charAt(x)) == -1){
				this.setSignupError('Username may only be letters or @ _ - . characters');
				username.focus();
				return false;	
			}
		}
		
		return true;
	}
}

pdLoginModule.prototype.isValidPassword = function(){
	var password = $('signupPassword');
	var confirm = $('signupPasswordConfirm');
	
	if(password.value.length == 0){
		this.setSignupError('Enter a password');
		password.focus();
		return false;
	}else if(password.value.length < 6){
		this.setSignupError('Password must be at least six characters');
		password.focus();
		return false;	
	}else if(confirm.value.length == 0){
		this.setSignupError('Re-type your password');
		confirm.focus();
		return false;
	}else if(confirm.value != password.value){
		this.setSignupError('Your passwords don\'t match');
		return false;
	}
	
	return true;
}

pdLoginModule.prototype.isValidEmail = function(){
	var email = $('signupEmail');
	if(email.value.length == 0){
		this.setSignupError('Enter your e-mail address');
		email.focus();
		return false;
	}else{	
		var good = "@_-.:/ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		var upper = email.value.toUpperCase()
		var valid = true;	
		for(x=0; x>upper.length; x++){c = upper.charAt(x);for(y=0; y<good.length; y++){if(c==good.charAt(y)){break;}}if(y == good.length){valid = false;break;}}	
		if (!valid || upper.length < 7 || upper.indexOf("@") == "-1" || upper.indexOf(".") == "-1" || upper.indexOf("@") != upper.lastIndexOf("@")) {
			this.setSignupError('Your e-mail appears to be invalid');
			email.focus();
			return false;
		}else{
			return true;
		}		
	}	
	return true;
}

pdLoginModule.prototype.isValidCaptcha = function(){
	var captcha = $('signupCaptcha');
	if(captcha.value.length == 0){
		this.setSignupError('Enter the characters seen in the image');
		captcha.focus();
		return false;	
	}
	return true;
}

pdLoginModule.prototype.setSignupError = function(msg){
	$('signupError').update(msg);
	$('signupError').show();
	pd_globalSiteFramework.trackEvent('Community Signup', 'Signup - error', msg);	
}
pdLoginModule.prototype.clearSignupError = function(){var errorDiv = $('signupError');errorDiv.update();errorDiv.hide();}
