String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

U.User = $extend({
	set : function(props) {
		$extend(this, props);
	},
	showLogin : function() {
		//new U.Request().send(U.Request.Manager.getConfig('getLoginHtml'), this._showLogin.bind(this));
		new U.Request().send(U.Request.Manager.getConfig('getLoginForm'), this._showLogin.bind(this));
	},
	_showLogin : function(html) {
		this._showInTaskbar(html);
		new U.Form('login-form');
		if($('pd-login-form')) {
			new U.Form('pd-login-form');
		}
		//window.location = '#u-login'; //temporary till redesign
	},
	showLoginSuccess : function(html) {
		//redirect to html instead of show in task bar
		//this._showInTaskbar(html);
		window.location = html;
	},
	showBdayQuestion : function(containerId) {
		if (!document.getElementById(containerId + '_c')) {
			bdayQuestionModal = openModal(containerId);
		}
		bdayQuestionModal.render(document.body);
		bdayQuestionModal.show();
		this.hideTaskBar();
	},
	executeGoogleJS: function() {
		var googDiv = $('google_div');
		var script = googDiv.innerHTML;
		eval(script);
	},
	hideTaskBar : function () {
		$usocial.hide();
	}, 
	showTaskBar : function () {
		$usocial.unHide();
	}, 
	showSignUp : function() {
		//new U.Request().send(U.Request.Manager.getConfig('getSignUpHtml'), this._showSignUp.bind(this));
		new U.Request().send(U.Request.Manager.getConfig('getSignUpForm'), this._showSignUp.bind(this));
		//window.location = '#u-login'; //temporary till redesign
	},
	_showSignUp : function(html) {
		this._showInTaskbar(html);
		this.signUp = new U.User.SignUp();
		this.cbsSignUp = new U.User.CBSLogin();
	},
	showSignUpSuccess : function(html) {
		newDiv = document.createElement("div");
		newDiv.innerHTML = html;
		children = newDiv.childNodes;
		
		// if the signup was by invite, redirect because we skip the confirmation step
		// also now used for redirecting to login from signup
		if(children[0] && children[0].id == "signup-by-invite") {
			redirect = children[0].firstChild.nodeValue;
			window.location = redirect;
			return;
		}
		this._showInTaskbar(html);
	},
	setRedirectAfterSignUp : function(redirectUrl, expiredays) {
		var name = 'customSignUpRedirect';
		U.setCookie(name, redirectUrl, expiredays);
		U.User.showSignUp();
	},
	setRedirectAfterLogin : function(redirectUrl, expiredays) {
		var name = 'customLoginRedirect';
		U.setCookie(name, redirectUrl, expiredays);
		U.User.showLogin();
	},
	showLostPwd : function() {
		new U.Request().send(U.Request.Manager.getConfig('getLostpwForm'), this._showLostPwd.bind(this));
	},
	_showLostPwd : function(html) {
		this._showInTaskbar(html);
		new U.User.LostPassword();
	},
	showLostPasswordSuccess : function() {
		$log('about to request')
		new U.Request().send(U.Request.Manager.getConfig('getLostPwdSuccessHtml'), this._showInTaskbar.bind(this));
	},
	showProfile : function(user_id) {
		var config = U.Request.Manager.getConfig('getProfile', {userid:user_id});
		new U.Request().send(config, this._showProfile.bind(this));
	},
	_showProfile : function(html) {
		this._showInTaskbar(html);
	},
	showRequests : function(user_id) {
		var config = U.Request.Manager.getConfig('getRequests', {userid:user_id});
		new U.Request().send(config, this._showRequests.bind(this));
	},
	_showRequests : function(html) {
		this._showInTaskbar(html);
	},
	showNotifications : function(user_id) {
		var config = U.Request.Manager.getConfig('getNotifications', {userid:user_id});
		new U.Request().send(config, this._showNotifications.bind(this));
	},
	_showNotifications : function(html) {
		this._showInTaskbar(html);
	},
	showMessages : function(user_id) {
		var config = U.Request.Manager.getConfig('getMessages', {userid:user_id});
		new U.Request().send(config, this._showMessages.bind(this));
	},
	_showMessages : function(html) {
		this._showInTaskbar(html);
	},
	showSearch : function() {
		var config = U.Request.Manager.getConfig('getSearch');
		new U.Request().send(config, this._showSearch.bind(this));
	},
	_showSearch : function(html) {
		this._showInTaskbar(html);
	},
	showInvite : function() {
		var config = U.Request.Manager.getConfig('getInvite');
		new U.Request().send(config, this._showInvite.bind(this));
	},
	_showInvite : function(html) {
		this._showInTaskbar(html);
	},
	_showInTaskbar : function(html) {
		$usocial.loadHtml(html).maximize();
	},
	doAction : function(options) {
		$log(options.action);
		this.fireEvent(options.action, options.message);
	},
	getCrossSiteDomain : function()
	{
		var domainDiv = $('eqal_callback_base_url');
		return domainDiv.innerHTML;
	},
	getConfigUrl : function(action_string)
	{
		var crossSiteDomain = this.getCrossSiteDomain();
		var ajaxCallbackUrl = "/eqal-xd-ajax.php" + '?forwarding_url=' + crossSiteDomain;
		var eqalSessionCookie = U.getCookie('eqal_sso_session');
		var eqalSessionCookieString = "&external_session_cookie=" + eqalSessionCookie;
		return ajaxCallbackUrl + action_string + eqalSessionCookieString;
	}
}, new Events);
U.User.SignUp = new Class({
	SIGNUP_FORM_VIEW_1 : 1,
	SIGNUP_FORM_VIEW_2 : 2,
	initialize : function()
	{
		this.view1Validated = false;
		// this.recaptchaValidated = false;		// not needed unless we have captcha
		
		this.form = new U.Form('signup-form', {doSubmit:false}).addEvent('submit', this._send.bind(this));

		this.toggle = $('signup_form_toggle_to_recaptcha');
		this.toggle.addEvent('click', this._toggle.bind(this, this.SIGNUP_FORM_VIEW_2));
		/*
		// this code is only needed if we incorporate captcha and have 2 views in the signup
		this.backLink = $('signup_form_back_link');
		this.backLink.addEvent('click', this._toggle.bind(this, this.SIGNUP_FORM_VIEW_1));
		
		this.validateRecaptcha = $('signup_form_validate_recaptcha');
		this.validateRecaptcha.addEvent('click', this._validateRecaptcha.bind(this));
		
		this.recaptcha = $('signup_form_recaptcha');
		
		// put the elements of the signup form view 1 into an array: email, password, birthday and toggle button
		try
		{
			this.view1Elements = new Array($('signup_form_item_email'), $('signup_form_item_password'), $('signup_form_item_bday'), this.toggle);
		}
		catch (e)
		{
			// alert(e.toString());
		}
		
		// put the elements of the signup form view 1 into an array: recaptcha div, back link, validate/submit button
		try
		{
			this.view2Elements = new Array(this.recaptcha, $('signup_form_tos'), this.backLink, this.validateRecaptcha);
		}
		catch (e)
		{
			// alert(e.toString());
		}
		*/
		//U.User.addEvent('signUpOk', this._signUpOk.bind(this)).addEvent('signUpFailed', this._signUpFailed.bind(this));
	},
	_signUpOk : function() {
		$log('calling : showSignUpSuccess')
		U.User.showSignUpSuccess();
	},
	_signUpFailed : function() {
		// handle errors here;
	},
	_send : function() {
		// we need to handle user submissions by hitting the return key; seems like only one return key press per form display actually starts the submission process, can be from either view 1 or view 2, so handle both
		if (!this.view1Validated)
		{
			this._toggle(this.SIGNUP_FORM_VIEW_2);
			return;
		}
		/*
		if (!this.recaptchaValidated)
		{
			this._validateRecaptcha();
			return;
		}
		*/
		var config = U.Request.Manager.getFormConfig('signup-form');
		new U.Request().send(config, this._sendResponse.bind(this));
	},
	_sendResponse : function(responseText) {
		//hack for testing js remove
		//responseText = responseText.replace(" = ",":");
		eval('var r = '+responseText.getTagContent('eval'));
		if (r.success)
		{
			try
			{
				U.User.showSignUpSuccess(responseText.getTagContent('html'));
			}
			catch (e)
			{
			}
		}
		else
		{
			U.User.showSignUpSuccess(responseText.getTagContent('html'));
			try
			{
				this.initialize();
			}
			catch (e)
			{
			}
		}
	},
	_validateView1 : function()
	{
		var view1IsValid = true;
		try
		{
			var submitButtonElement = $('signup_form_submit');
			var rules = submitButtonElement.get('validate');
			eval("rules = "+rules);
			var groups = rules.group.split(',');
			for (var i=0,nL=groups.length,group;i<nL;i++)
			{
				group = this.form.groups[groups[i]];
				for(var item in group)
				{
					view1IsValid = this.form._validateItem(group[item]);
					if (!view1IsValid) 
					{
						return false;
					}
				}
			}
		}
		catch (e)
		{
			return false;
		}
		return view1IsValid;
	},
	_toggle : function(viewOption)
	{
		if (this.view1Validated = this._validateView1())
		{
			// for now, submit the form if everything is valid
			var submitButtonElement = $('signup_form_toggle_to_recaptcha');
			submitButtonElement.addClass('processing')
			submitButtonElement.value = 'Please wait..';
			submitButtonElement.disabled = true;
			this.form.fireEvent('submit');
		}
		/*
		this._clearSignupMessage(); // removing for now
		switch (viewOption)
		{
			case this.SIGNUP_FORM_VIEW_1:
				this.view1Validated = false;
				// hide all view 2 items, display all view 1 items
				for (elemIndex in this.view2Elements)
				{
					try
					{
						this.view2Elements[elemIndex].hide();
					}
					catch (e)
					{
					}
				}
				for (elemIndex in this.view1Elements)
				{
					try
					{
						this.view1Elements[elemIndex].show();
					}
					catch (e)
					{
					}
				}
				break;
			case this.SIGNUP_FORM_VIEW_2:
				// we first want to perform validation on all the view 1 items; if there's a problem, do not advance
				if (this.view1Validated = this._validateView1())
				{
					// get the public key, then populate the recaptcha
					if (!this._generateRecaptcha())
					{
						this._displaySignupMessage("Sorry, there was a problem processing your signup.");
						break;	
					}
					// hide all view 1 items, display all view 2 items
					for (elemIndex in this.view1Elements)
					{
						try
						{
							this.view1Elements[elemIndex].hide();
						}
						catch (e)
						{
						}
					}
					for (elemIndex in this.view2Elements)
					{
						try
						{	
							this.view2Elements[elemIndex].show();
						}
						catch (e)
						{
						}
					}
				}
				break;
			default:
				break;
		}
		*/
	}/*,
	_generateRecaptcha : function() {
		try
		{
			var recaptchaPublicKeyElement = $('signup_form_recaptcha_public_key');
			Recaptcha.create(recaptchaPublicKeyElement.value, this.recaptcha, {
				theme: 'clean',
				tabindex: 0,
				callback: Recaptcha.focus_response_field
			});
		}
		catch (e)
		{
			return false;
		}
		return true;
	},
	_validateRecaptcha : function() {
		// we need to do an ajax post to the recaptcha url with the challenge and response
		try
		{
			var validateURLElement = $('signup_form_validate_recaptcha_url');
			var thisCallback = {
				success : this._validateCaptchaResponseSuccess.bind(this),
				failure : this._validateCaptchaResponseFailure.bind(this),
				argument : {
				}
			}
			if ((userResponse = Recaptcha.get_response()) != "")
			{
				this._displaySignupMessage("Validating...");
				// change the label on the sign up button
				this._changeSignupButtonText("Please wait...");
				var transaction = YAHOO.util.Connect.asyncRequest('POST', validateURLElement.value, thisCallback, 'challenge=' + Recaptcha.get_challenge() + '&response=' + userResponse);
			}
			else
			{
				this._displaySignupMessage("Please enter a response to the captcha.");	
			}
		}
		catch (e)
		{
			this._displaySignupMessage("Sorry, there was a problem validating the text you entered. Please try again.");
			this._changeSignupButtonText("Sign up");
		}
	},
	_validateCaptchaResponseSuccess : function (o) {
		try
		{
			this._changeSignupButtonText("Sign up");
			var result = "";
			try
			{
				result = YAHOO.lang.JSON.parse(o.responseText.trim());
			}
			catch (e)
			{
				this._validateCaptchaResponseFailure();
				return;
			}
			if (result["isCaptchaValid"] && result["isCaptchaValid"] == "true")
			{
				this.recaptchaValidated = true;
				this._clearSignupMessage();
				// proceed with form submission
				try
				{
					// this.form.submit();
					// var submitButton = $('signup_form_submit');
					// submitButton.submit();
					// this.form._validate('signup', $('signup_form_submit'));
					this.form.fireEvent('submit');
				}
				catch (e)
				{
					this._displaySignupMessage("Sorry, there was a problem submitting your signup. Please try again later.");
				}
			}
			else
			{
				this.recaptchaValidated = false;
				this._generateRecaptcha();
				this._displaySignupMessage("Sorry, the captcha you entered was invalid. Please try again.");
			}
		}
		catch (e)
		{
			this._displaySignupMessage("Sorry, there was a problem submitting your signup. Please try again later.");
		}
	},
	_validateCaptchaResponseFailure : function () {
		this._changeSignupButtonText("Sign up");
		this._generateRecaptcha();
		this._displaySignupMessage("Sorry, there was a problem validating the text you entered. Please try again.");
	},
	_displaySignupMessage : function(errorText) {
		if (signupMessageDiv = document.getElementById("signup_form-ajax-error"))
		{
			signupMessageDiv.innerHTML = errorText;
		}
	},
	_clearSignupMessage : function() {
		this._displaySignupMessage("");
	},
	_changeSignupButtonText : function(displayText) {
		try
		{
			this.validateRecaptcha.value = displayText;
		}
		catch (e)
		{
		}
	}
	*/
});
U.User.Login = new Class({
	initialize : function() {
		this.form = new U.Form('login-form', {doSubmit:false}).addEvent('submit', this._send.bind(this));
		this.email = U.UI.GetTextBox('login-form-input-email');
		this.password = U.UI.GetTextBox('login-form-input-password');
		//this.form_name = $('form_name');
		
		//U.User.addEvent('signUpOk', this._signUpOk.bind(this)).addEvent('signUpFailed', this._signUpFailed.bind(this));
	},
	_signUpOk : function() {
		$log('calling : showLoginSuccess')
		U.User.showLoginSuccess();
	},
	_signUpFailed : function() {
		// handle errors here;
	},
	_send : function() {
		var config = U.Request.Manager.getFormConfig('login-form');

		new U.Request().send(config, this._sendResponse.bind(this));
	},
	_sendResponse : function(responseText) {
		$log('we got the response');
		eval('var r = '+responseText.getTagContent('eval'));
		if (r.success) {
			U.User.showLoginSuccess(responseText.getTagContent('html'));
		} else {
			this.form.showErrors(r.errors);
		}
	}
});
U.User.CBSLogin = new Class({
	initialize : function() {
		this.form = new U.Form('cbs-signup-form', {doSubmit:true});
		this.email = U.UI.GetTextBox('cbs_signup_form_input_email');
		this.password = U.UI.GetTextBox('cbs_signup_form_password');
	}
});
U.User.LostPassword = new Class({
	initialize : function() {
		this.form = new U.Form('lostpw-form', {doSubmit:false}).addEvent('submit', this._send.bind(this));
		this.email = U.UI.GetTextBox('lostpw-form-email');
		$log('got here')
		U.User.addEvent('lostPasswordOk', this._lostPasswordOk.bind(this))
	},
	_lostPasswordOk : function() {
		$log('calling : showSignUpSuccess')
		U.User.showLostPasswordSuccess();
	},
	_send : function() {
		var config = U.Request.Manager.getConfig('lostpw');
		config.data.email = this.email.getValue();
		new U.Request().send(config, this._sendResponse.bind(this));
	},
	_sendResponse : function(responseText) {
		eval(responseText.getTagContent('eval'));
	}
});