$(function() {
		
		var email = $("#email"),
			password = $("#password"),
			allFields = $([]).add(email).add(password),
			tips = $("#validateTips"),
			forgotPasswordEmail = $("#forgotPasswordEmail");

		function updateTips(t) {
			tips.text(t).effect("highlight",{},1500);
		}

		function checkLength(o,n,min,max) {

			if ( o.val().length > max || o.val().length < min ) {
				o.addClass('ui-state-error');
				updateTips("Length of " + n + " must be between "+min+" and "+max+".");
				return false;
			} else {
				return true;
			}

		}

		function checkRegexp(o,regexp,n) {

			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass('ui-state-error');
				updateTips(n);
				return false;
			} else {
				return true;
			}

		}
		
		$("#loginDialog").dialog({
			bgiframe: true,
			autoOpen: false,
			//height: 275,
			modal: true,
			position: ["center",60],
			resizable: false,
			buttons: {
				'LOG IN TO MY CPR': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');
					/*
					bValid = bValid && checkLength(email,"email",6,80);
					bValid = bValid && checkLength(password,"password",5,16);

					// bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
					bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
					*/
					/*
					if (bValid) {
						$('#users tbody').append('<tr>' +
							'<td>' + email.val() + '</td>' + 
							'<td>' + password.val() + '</td>' +
							'</tr>');
						*/

						var email = $("#loginEmail").val();
						var password = $("#loginPassword").val();
						
						// Test the length of email and password to make they're not zero-length or only spaces:
						email_FLAG = 0;
						password_FLAG = 0;

						for (var i = 0; i < email.length; i++) {
							if (email.charAt(i) != " ") {
								email_FLAG++;
							}
						}

						if (email_FLAG==0) {
							alert("Please provide an email address.");
							return false;
						}

						for (var i = 0; i < password.length; i++) {
							if (password.charAt(i) != " ") {
								password_FLAG++;
							}
						}

						if (password_FLAG==0) {
							alert("Please provide a password.");
							return false;
						}

						var is_login = true;

						$.post("/lib/profile/loginProcessor.php", 
							{ 
								user_email: email, 
								user_password: password, 
								is_login: is_login 
							}, function(data) {
								
								global_session  = data;
								if (global_session.is_first_login == true)
								{
									//we know this is the first login, pop a dialog:
									alert('You may find that during this beta test, some of your profile information is out of date.\n\nIf you\'ve made changes to your contact or payment information lately, those changes may not be reflected here.\n\nIf you have questions about your membership, please call 1-800-722-4449.');
								}	
								
								loadProfile('load_profile', 'profileTemplate');
								
								// Change the links in the left nav in the profile tab:
								$('ul#profileNav li').remove();
								$('#profileNav').append('<li class="sidebarNavHeader profileHeader">YOUR CPR PROFILE</li>');
								$('#profileNav').append('<li class="profileLinks" id="profileLink0"><a href="/profile/profileTemplate">Account Overview</a></li>');

								// TODO: these "append" statements aren't as efficient as it would be to instead
								// put all this markup into string vars.  Mike's advice 20100305
								// if(data.pledge_history.length == 0) {
								if(!data.pledge_history || data.pledge_history.length == 0) {
									$('#profileNav').append('<li class="profileLinks" id="profileLink1"><a href="https://secure.cpr.org/">Become a Member</a></li>');
									$('#profileNav').append('<li class="profileLinks" id="profileLink2"><a href="/profile/contactInfoEdit">Change Contact Information</a></li>');
								} else {
									$('#profileNav').append('<li class="profileLinks" id="profileLink1"><a href="/profile/addGiftForm">Make an Additional Gift</a></li>');
									$('#profileNav').append('<li class="profileLinks" id="profileLink2"><a href="/profile/contactInfoEdit">Change Contact Information</a></li>');
									// $('#profileNav').append('<li class="profileLinks" id="profileLink3"><a href="/profile/billingInfoEdit">Change Billing Information</a></li>');
									$('#profileNav').append('<li class="profileLinks" id="profileLink4"><a href="#" onclick="return launchReceipt();" target="_self">Print 2009 Donation Receipt</a></li>');
								}
								$('#profileNav').append('<li class="profileLinks" id="profileLink3"><a href="/profile/contactCPR">Contact CPR</a></li>');
								$('#profileNav').append('<li class="profileLinks" id="profileLink6"><a href="/profile/memberInfo">Missing Information?</a></li>');

								cprWidgets.setLayout();
								$('#loginLinkLI').html('<a href="#" id="loginLink" class="topLogin" onclick="logout(); return false;">LOG OUT</a>');
								$('#registerLinkLI').html('<a href="#" onclick="alert(\'Please log out before registering a new profile.\'); return false;">REGISTER</a>');
							},
							"json"
						);

						$(this).dialog('close');
					// }
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
			}
		});
		
		
		
		// TODO: is this used any longer, or replaced when D&I's design was implemented? dl 20091119
/*
		$('#loginButton').click(function() {
			$('#loginDialog').dialog('open');
		})
		.hover(
			function(){ 
				$(this).addClass("ui-state-hover"); 
			},
			function(){ 
				$(this).removeClass("ui-state-hover"); 
			}
		).mousedown(function(){
			$(this).addClass("ui-state-active"); 
		})
		.mouseup(function(){
				$(this).removeClass("ui-state-active");
		});
*/

		$("#forgotPasswordDialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 275,
			modal: true,
			position: ["center",60],
			resizable: false,
			buttons: {
				'Send me my password!': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');

						var forgotPasswordEmail = $("#forgotPasswordEmail").val();
						
						// Test the length of email to make sure it's not zero-length or only spaces:
						email_FLAG = 0;

						for (var i = 0; i < forgotPasswordEmail.length; i++) {
							if (forgotPasswordEmail.charAt(i) != " ") {
								email_FLAG++;
							}
						}

						if (email_FLAG==0) {
							alert("Please provide an email address.");
							return false;
						}

						var is_login = false;
						var is_password_reminder = true;

						alert('An email has been sent.\n\nPlease check your email from instructions on how to reset your password.');

						$.post("/lib/profile/loginProcessor.php", 
							{ 
								user_email: forgotPasswordEmail, 
								is_login: is_login, 
								is_password_reminder: is_password_reminder
							}, function(data) {
								// $(this).dialog('close');
//								$("#myProfileTabHeader").hide();
//								$("#tabs").tabs("select", "mainTab");
						});

						$(this).dialog('close');
							
							

				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
			}
		});
		
		
		

	   	var dialogOpts = {
			modal: true,
			bgiframe: true,
			autoOpen: false,
			buttons: {
				'Continue': function() {
										
					$.post("/lib/survey/surveyLoader.php", 
						{ 
							formData: $(":input").serialize(), 
							survey_title: $("#survey_title").val(), 
							processSurveyResponse: $("#processSurveyResponse").val()
						}, 
						function(data) { 
							// alert(data); 
						}
					);
	
					$(this).dialog('close');
				},
				'Cancel': function() {
					$(this).dialog('close');
				}
			
			}
		};
		


		$("#surveyDialog").dialog(dialogOpts);	//end dialog
		
		function handler(e) {
			if ((loadedArticle) && (loadedArticle != '')) {

// TODO: temporary fakery for dev and testing and general holiday merriment:
var loadedTab = 'Survey 1';

				$.post("/lib/survey/surveyLoader.php", 
				{
					page: loadedArticle, 
					event: e, 
					loadedTab: loadedTab
				}, 
				function(data) {
					//change question text here from the return json ie data.question so $("#surveyDialogQuestion).html(data.question);
					$("#surveyDialog").dialog('open');
					
					theLength = data.questions.length;
					myString = '<form id=\'fooForm\'>';
					myString += '<fieldset>';

					for (i=0; i<theLength; i++) {
						if (data.questions[i].question_type == 2) {
							myString += data.questions[i].question + "<div id=\"question_" + data.questions[i].question_id + "_answers\" class=\"answers\">";
							theQuestionsLength = data.questions[i].possible_answers.length;
							for (p=0; p<theQuestionsLength; p++) {
								myString += "<input type=\"radio\" id=\"radio_" + data.questions[i].question_id + "\" name=\"radio_" + data.questions[i].question_id +"\" value=\"" + data.questions[i].possible_answers[p].id + "\">";
								myString += data.questions[i].possible_answers[p].answer;
							}
							myString += "</div>";
						} else if (data.questions[i].question_type == 4) {
							myString += data.questions[i].question + "<div id=\"question_" + data.questions[i].question_id + "_answers\" class=\"answers\">";
							myString += "<input type=\"text\" id=\"text_" + data.questions[i].question_id + "\" name=\"text_" + data.questions[i].question_id +"\" />";
							myString += "</div>";
						}
					}
					myString += "<input type=\"hidden\" id=\"processSurveyResponse\" value=1>";
					myString += "<input type=\"hidden\" id=\"survey_title\" value=\"" + loadedTab + "\">";
					myString += '</fieldset>';
					myString += '</form>';
					
					$("#surveyDialog").html(myString);
					$("#surveyDialog").dialog('option', 'title', 'Survey');
				}, 
				"json"
				);
			}

		}
		
		// TODO: temp set loadedArticle to '' if not defined.  This is set OK in the case of a direct URL load, but not yet figured this out
		// in cases of ajax navigation or direct to the landing page:
		if (typeof(loadedArticle) == 'undefined') {
			loadedArticle = '';
		}
		if (typeof(loadedTab) == 'undefined') {
			loadedTab = '';
		}

//		$("#surveyDialog").bind('loadedContent', {loadedArticle: loadedArticle, loadedTab: loadedTab}, handler);

		if (typeof(loadedContentFromStart) != 'undefined') {
//		if (loadedContentFromStart) {
			$("#surveyDialog").trigger('loadedContent');
		}
		
		$('#forgotPasswordButton').click(function() {
			$('#forgotPasswordDialog').dialog('open');
		})
		.hover(
			function(){ 
				$(this).addClass("ui-state-hover"); 
			},
			function(){ 
				$(this).removeClass("ui-state-hover"); 
			}
		).mousedown(function(){
			$(this).addClass("ui-state-active"); 
		})
		.mouseup(function(){
				$(this).removeClass("ui-state-active");
		});
});

function logout()
{
	$.post("/lib/profile/loginProcessor.php?rnd=" + new Date().getTime(), 
			{ 
				is_logout: 'true'
			},
			function(data)
			{
				global_session=data;
				$("#myProfileTabHeader").hide();
				$("#tabs").tabs("select", "mainTab");
				$('#loginLinkLI').html('<a href="#" id="loginLink" class="topLogin" onclick="$(\'#loginDialog\').dialog(\'open\'); return false;">LOG IN</a>');
				$('#registerLinkLI').html('<a href="/profile/register">REGISTER</a>');
				$.cookie("cprWidgetLayout", null, {path: '/', expires: 10 });
				cprWidgets.setLayout();
				$('#loginEmail').val('');
				$('#loginPassword').val('');

			});
			


		
}
						
