﻿/// <reference path="jquery-1.3.1.min-vsdoc.js" />
var topMostPage;
var welcomePage;

var organizationCollegeValue = 2;
var organizationMediaValue = 10;

var heardFromOtherValue = 999;

var countryCanadaValue = '046';
var countryUnitedStatesValue = '248';

var statesLowIndex = 1;
var statesCount = 59;

var provincesLowIndex = 60;
var provincesCount = 12;

var KAISER_GLOBAL_HEALTH_POLICY_REPORT = "Kaiser Global Health Policy Report";
var WEEKLY = "Weekly";
var HEADLINES_WITH_LINKS = "Headlines with links";

jQuery(document).ready(function() {

	topMostPage = jQuery('#hiddenTopMost').length > 0 ? jQuery('#hiddenTopMost').val() : location.href;
	welcomePage = jQuery('#welcomePageUrl').val();

	if (jQuery('#loginWrapper').length == 0) {
		jQuery('#subscriptions').show();
		jQuery('.introduction').show();
	}
	else {
		if (!(jQuery.browser.msie && jQuery.browser.version == 6.0))
			jQuery('#subscriptions').show();
	}

	if (location.search.length > 0) {

		// ?nav=a
		var search = location.search.split('?');

		if (search.length > 0) {
			// nav=a
			var querystring = search[1];
			var params = querystring.split('=');
			// nav
			var key = params[0];
			if (params.length > 0 && key == 'nav') {
				// a
				var value = params[1];

				if (value == 'b')
					ShowSubscriptions(false);
			}
		}
	}

	SetEventHandling();
	PopulateForm();
	ValidateAndSubmitForm();
	SetOrganizationAutoComplete();
});

/* ---------------------------------------------- AUTHENTICATION --------------------------------------------- */
function Login(emailAddress, password, messages) {

	var url = 'Login';
	var data = "{'username':'" + emailAddress + "', 'password':'" + password + "'}";
	var callback = function(data) {
		if (data.d)
			location.href = topMostPage;
		else
			messages.text("Incorrect password. Did you forget your password?");
	}
	AjaxHelper(url, data, callback);
}

function Logout() {

	var url = 'Logout';
	var data = '{}';
	var callback = function() {
		location.href = topMostPage;
	};
	AjaxHelper(url, data, callback);
}

function IsPasswordValid(password, callback) {

	var url = 'IsPasswordValid';
	var data = "{'password':'" + password + "'}";
	AjaxHelper(url, data, callback);
}

function ChangePassword(currentPassword, newPassword, callback) {

	var url = 'ChangePassword';
	var data = "{'currentPassword':'" + currentPassword + "', 'newPassword':'" + newPassword + "'}";
	AjaxHelper(url, data, callback);
}

function EmailAddressExists(emailAddress, callback) {

	var url = 'EmailAddressExists';
	var data = "{'emailAddress':'" + emailAddress + "'}";
	AjaxHelper(url, data, callback);
}

function IsEmailAddressValid(emailAddress, finalUrl, finalCallback) {

	var url = 'IsEmailAddressValid';
	var data = "{'emailAddress':'" + emailAddress + "'}";
	var callback = function(json) {
		var emailIsValid = json.d;

		if (!emailIsValid) {
			// create warning
			var warning = '<label id="DuplicateEmailWarning" class="error" for="EmailAddress">This email address is already taken. Please enter a new one.</label>';
			jQuery('#EmailAddress').after(warning);
		}
		else {
			// delete warning, if there is one
			jQuery('#DuplicateEmailWarning').remove();

			SubmitProfile(finalUrl, finalCallback);
		}
	};

	AjaxHelper(url, data, callback);
}
/* ---------------------------------------------- AUTHENTICATION --------------------------------------------- */
/*
-
-
-
-
-
-
-
-
*/
/* ---------------------------------------------- EVENT HANDLING --------------------------------------------- */
function SetEventHandling() {

	jQuery('#loginCurtain').fadeTo('normal', 0.6);

	ResizeLoginCurtain();
	jQuery(window).resize(function() {
		ResizeLoginCurtain();
	});

	jQuery('#loginForgotPassword').click(function() {
		ShowPasswordRetrieval(true);
		return false;
	});

	jQuery('#loginPasswordRetrievalContinue').click(function() {
		ShowPasswordRetrieval(false);
		return false;
	});

	jQuery('#loginPasswordRetrievalCancel').click(function() {
		ShowPasswordRetrieval(false);
		return false;
	});

	jQuery('.logout').click(function() {
		Logout();
		return false;
	});

	jQuery('#subscriptionsSave').click(function() {
		var dto = { 'profile': CreateProfileObject() };
		var url = 'SaveProfileSubscriptions';
		var data = JSON2.stringify(dto);
		var callback = function() {
			location.href = welcomePage;
		};
		AjaxHelper(url, data, callback);
		return false;
	});

	jQuery('#informationSave').click(function() {
		if (jQuery('#informationForm').valid()) {
			var emailAddress = jQuery('#EmailAddress').val();
			var finalUrl = 'SaveProfileInformation';
			var finalCallback = function() {
				location.href = welcomePage;
			};
			IsEmailAddressValid(emailAddress, finalUrl, finalCallback);
		}
		return false;
	});

	jQuery('#kaiserUpdateAllTopics').click(function() {
		var topics = jQuery('input', jQuery('#topics'));
		if (this.checked) {
			ShowTopics(jQuery('#topics'), jQuery('#showAllTopics'), true);
			topics.attr('checked', 'checked');
		}
		else {
			ShowTopics(jQuery('#topics'), jQuery('#showAllTopics'), false);
			topics.removeAttr('checked');
		}
	});

	jQuery('.showSubscriptions').click(function() {
		if (jQuery('#subscriptions').length > 0)
			ShowSubscriptions(true);
		else
			location.href = topMostPage + '?nav=a';
		return false;
	});

	jQuery('.showInformation').click(function() {
		if (jQuery('#information').length > 0) {
			ShowSubscriptions(false);
		}
		else
			location.href = topMostPage + '?nav=b';
		return false;
	});

	jQuery('#submitPasswordChangeCancel').click(function() {
		location.href = topMostPage;
		return false;
	});

	jQuery('#showAllTopics').click(function() {
		var topics = jQuery('#topics');
		var this0 = jQuery(this);
		ShowTopics(topics, this0, topics.css('display') == 'none');
		return false;
	});

	jQuery('#OrganizationType').change(function() {
		RenderMediaOutletAndOccupation(jQuery(this).val());
	});

	// disable "Format: Full Text" if we're on "Kaiser Global Health Policy Report"
	jQuery('input[type=radio][class="Frequency"]', jQuery('.frequencyAndFormat')).click(function() {

		// find the class='frequencyAndFormat' parent
		var parent;
		jQuery(this).parents().each(function() {
			if (this.className == 'frequencyAndFormat')
				parent = jQuery(this);
		});

		if (jQuery('label', parent.parent()).get(0).innerHTML == KAISER_GLOBAL_HEALTH_POLICY_REPORT) {
			if (jQuery(this).siblings().text() == WEEKLY) {
				jQuery('input[class="Format"]', parent).each(function() {
					var jThis = jQuery(this);
					if (jThis.siblings().text() == HEADLINES_WITH_LINKS) {
						jThis.get(0).checked = true;
					}
					else {
						jThis.get(0).disabled = true;
					}
				});
			}
			else {
				jQuery('input[class="Format"]', parent).each(function() {
					var jThis = jQuery(this);
					jThis.get(0).disabled = false;
				});
			}
		}
	});

	jQuery('input[type=checkbox]', jQuery('.frequencyAndFormat').parent()).click(function() {
		var ff = jQuery('.item', jQuery('.frequencyAndFormat', jQuery(this).parent()));
		var firstInput = jQuery('input:first', ff);
		var allInputs = jQuery('input', ff);

		if (this.checked) {
			firstInput.attr('checked', 'checked');
			allInputs.removeAttr('disabled');
		}
		else {
			allInputs.removeAttr('checked');
			allInputs.attr('disabled', 'disabled');
		}
	});

	jQuery('#HeardFrom').change(function() {
		Show(jQuery('#HeardFromOtherInput'), jQuery(this).val() == heardFromOtherValue);

		if (jQuery(this).val() == heardFromOtherValue) {
			Show(jQuery('#HeardFromOtherInput'), true);
		}
		else {
			Show(jQuery('#HeardFromOtherInput'), false);
			jQuery('#HeardFromOther').val('');
		}
	});

	jQuery('#Country').change(function() {
		RenderStateProvince(jQuery(this).val());
	});

	jQuery('#loginNewUserPasswordRetrieval').live('click', function() {

		PerformPasswordRetrieval(jQuery('#loginNewUser').get(0).EmailAddress.value);
		ShowPasswordRetrieval(true);
		ShowPasswordRetrievalContinue(); 
		return false;
	});
}

function SetOrganizationAutoComplete() {

	jQuery('#Organization').autocomplete('OrgSearch', {
		minChars: 3,
		max: 200,
		delay: 0
	});
}
/* ---------------------------------------------- EVENT HANDLING --------------------------------------------- */
/*
-
-
-
-
-
-
-
-
*/
/* ---------------------------------------------- HELPER FUNCTIONS --------------------------------------------- */
function SetTopicsMasterCheckbox() {
	var masterCheckbox = jQuery('#kaiserUpdateAllTopics');
	var topics = jQuery('input', '#topics');
	masterCheckbox.attr('checked', 'checked');

	topics.each(function() {
		if (!this.checked) {
			masterCheckbox.removeAttr('checked');
			return false;
		}
	});
}

function RenderHeardFrom(heardFrom) {
	Show(jQuery('#HeardFromOtherInput'), heardFrom == heardFromOtherValue);
}

function RenderSubscriptions(subscriptions) {
	if (subscriptions) {
		for (var i = 0; i < subscriptions.length; i++) {

			var input = jQuery('#' + subscriptions[i].Id);
			input.attr('checked', 'checked');
			jQuery('input[type=radio]', input.parent()).removeAttr('disabled');

			for (property in subscriptions[i]) {
				if (property != 'Id') {
					var parent = input.parent();
					var frequencyAndFormat = jQuery('.frequencyAndFormat', parent);
					var radioButton = jQuery('input[class=' + property + '][value=' + subscriptions[i][property] + ']', frequencyAndFormat);
					radioButton.attr('checked', 'checked');
				}
			}
		}
	}
}

function RenderStateProvince(country, stateProvince) {
	var stateProvinceDiv = jQuery('#StateProvinceInput');
	var options = jQuery('option', stateProvinceDiv);
	var select = jQuery('select', stateProvinceDiv);
	var body = jQuery('body');

	// save stateProvinces in memory
	if (!body.data('stateProvinces')) {
		body.data('stateProvinces', options.clone());
	}

	// clear stateProvinces
	select.empty();

	if (country == countryCanadaValue || country == countryUnitedStatesValue) {
		Show(stateProvinceDiv, true);
		select.append(body.data('stateProvinces').get(0));

		if (country == countryUnitedStatesValue) {
			for (var i = statesLowIndex; i < statesCount; i++) {
				select.append(body.data('stateProvinces').get(i));
			}
		}
		else {
			for (var i = provincesLowIndex; i < (provincesLowIndex + provincesCount); i++) {
				select.append(body.data('stateProvinces').get(i));
			}
		}

		select.get(0).value = stateProvince ? stateProvince : 0;
	}
	else {
		Show(stateProvinceDiv, false);
	}
}

function RenderFrequencyAndFormat() {

	var parent;

	jQuery('.frequencyAndFormat').each(function() {
		var jThis = jQuery(this);
		if (jQuery('label', jThis.parent()).get(0).innerHTML == KAISER_GLOBAL_HEALTH_POLICY_REPORT) {
			parent = jThis;
		}
	});

	var frequency = jQuery('input[type=radio][class="Frequency"][checked]', parent);

	if (frequency.siblings().text() == WEEKLY) {
		jQuery('input[class="Format"]', parent).each(function() {
			var jThis = jQuery(this);
			if (jThis.siblings().text() == HEADLINES_WITH_LINKS) {
				jThis.get(0).checked = true;
			}
			else {
				jThis.get(0).disabled = true;
			}
		});
	}
}
	

function RenderMediaOutletAndOccupation(organization, occupation) {
	var mediaOutletDiv = jQuery('#MediaOutletInput');
	var occupationDiv = jQuery('#OccupationInput');
	var options = jQuery('option', occupationDiv);
	var select = jQuery('select', occupationDiv);
	var body = jQuery('body');

	// save occupations in memory
	if (!body.data('occupations')) {
		body.data('occupations', options.clone());
	}

	// clear occupations
	select.empty();

	if ((organization == organizationCollegeValue) || (organization >= 10 && organization <= 16)) {
		Show(occupationDiv, true);
		select.append(body.data('occupations').get(0));

		if (organization == organizationCollegeValue) {
			select.append(body.data('occupations').get(1));
			select.append(body.data('occupations').get(14));
			select.append(body.data('occupations').get(15));
			mediaOutletDiv.show().css('visibility', 'hidden');
		}
		else {
			select.append(body.data('occupations').get(7));
			select.append(body.data('occupations').get(8));
			select.append(body.data('occupations').get(9));
			select.append(body.data('occupations').get(10));
			mediaOutletDiv.show().css('visibility', 'visible');
			jQuery('select', mediaOutletDiv).get(0).value = organization;
			jQuery('select', jQuery('#OrganizationTypeInput')).get(0).value = 10;
		}

		select.get(0).value = occupation ? occupation : 0;
	}
	else {
		Show(mediaOutletDiv, false);
		Show(occupationDiv, false);
	}
}

function ShowTopics(topics, link, show) {
	if (show) {
		link.css('background-image', "url('/images/profile/minus.gif')");
		link.text('Hide All Topics');
	}
	else {
		link.css('background-image', "url('/images/profile/plus.gif')");
		link.text('Show All Topics');
	}
	
	Show(topics, show);
}

function AjaxHelper(url, data, callback) {

	jQuery.ajax({
		type: "POST",
		url: '/services/ProfileService.asmx/' + url,
		data: data,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		beforeSend: function() {
			jQuery('#loadingMessage').show();
		},
		success: callback,
		error: function(xhr, status, error) {
		},
		complete: function() {
			jQuery('#loadingMessage').hide();
		}
	});
}

function PopulateForm() {

	if (jQuery('#information').length > 0) {
		var url = 'GetProfile';
		var data = '{}';
		var callback = function(data) {
			var json = data.d;
			if (json) {
				jQuery('input[type=text]', '#information').each(function() {
					this.value = json[this.id];
				});
				jQuery('select').each(function() {
					this.value = json[this.id];
				});
				RenderSubscriptions(json.Subscriptions);
				SetTopicsMasterCheckbox();
				RenderMediaOutletAndOccupation(json.OrganizationType, json.Occupation);
				RenderStateProvince(json.Country, json.StateProvince);
				RenderHeardFrom(json.HeardFrom);
				RenderFrequencyAndFormat();
			}
		}
		AjaxHelper(url, data, callback);
	}
}

function CreateProfileObject() {

	var profile = {};

	// Iterate over all the input fields and build an object
	// with their values as named properties.
	jQuery('input[type=text]').each(function() {
		profile[this.id] = this.value;
	});

	jQuery('input[type=password]').each(function() {
		profile[this.id] = this.value;
	});

	jQuery('select').each(function() {
		profile[this.id] = this.value;
	});

	profile.Subscriptions = [];
	var count = 0;

	jQuery('input[type=checkbox]').each(function() {

		if (this.checked) {
			var parent = jQuery(this).parent();
			var frequencyAndFormat = jQuery('.frequencyAndFormat', parent);

			profile.Subscriptions[count] = {
				Id: this.value,
				Frequency: GetDeliveryPreference(frequencyAndFormat, 'Frequency'),
				Format: GetDeliveryPreference(frequencyAndFormat, 'Format')
			};
			count++;
		}
	});

	if (profile.OrganizationType == 10)
		profile.OrganizationType = profile.MediaOutlet;

	return profile;
}

function GetDeliveryPreference(frequencyAndFormatDiv, FrequencyOrFormat) {
	return frequencyAndFormatDiv.length > 0
			? jQuery('input[class=' + FrequencyOrFormat + '][checked]', frequencyAndFormatDiv).val()
			: 0;
}

function ResizeLoginCurtain() {

	var thisHeight = jQuery(window).height();
	var wrapperHeight = jQuery('#wrapper').height();
	jQuery('#loginCurtain').height(wrapperHeight > thisHeight ? wrapperHeight : thisHeight);
}

function ShowPasswordRetrieval(show) {
	if (show)
		ResetLogin();
	else
		ResetPasswordRetrieval();

	Show(jQuery('#loginPasswordRetrieval'), show);
	Show(jQuery('#loginExistingUser'), !show);
	Show(jQuery('#loginNewUser'), !show);
	Show(jQuery('.or', '#login'), !show);
}

function ResetForm(form) {
	form.validate().resetForm();
	jQuery("input[type='text']", form).val('');
	jQuery("input[type='password']", form).val('');
	jQuery('.messages', form).text('');
}

function ResetLogin() {
	ResetForm(jQuery('#loginExistingUser'));
	ResetForm(jQuery('#loginNewUser'));
}

function ResetPasswordRetrieval() {
	var form = jQuery('#loginPasswordRetrieval');
	ResetForm(form);
	jQuery('.part1', form).show();
	jQuery('.part2', form).hide();
}

function ShowPasswordRetrievalContinue() {
	var form = jQuery('#loginPasswordRetrieval');
	var part1 = jQuery('.part1', form);
	var part2 = jQuery('.part2', form);
	part1.hide();
	part2.show();
	var instructions = jQuery('.instructions', jQuery('.part2', form));
	instructions.text('Check your email inbox for further instructions on how to retrieve your password.');
}

function PerformPasswordRetrieval(emailAddress) {
	var url = 'SendPasswordEmail';
	var data = "{'emailAddress':'" + emailAddress + "'}";
	var innerCallback = function() {
		ShowPasswordRetrievalContinue();
	}
	AjaxHelper(url, data, innerCallback);
}

function ShowSubscriptions(show) {
	if (show) {
		jQuery('#menu li.subscriptionsOff').attr('class', 'subscriptionsOn showSubscriptions');
		jQuery('#menu li.informationOn').attr('class', 'informationOff showInformation');
	}
	else {
		jQuery('#menu li.informationOff').attr('class', 'informationOn showInformation');
		jQuery('#menu li.subscriptionsOn').attr('class', 'subscriptionsOff showSubscriptions');
	}

	Show(jQuery('#subscriptions'), show);
	Show(jQuery('#information'), !show);
	Show(jQuery('.subscriptionMessage'), show);
	Show(jQuery('.informationMessage'), !show);
}

function Show(element, show) {
	if (show)
		element.show();
	else
		element.hide();
}
/* ---------------------------------------------- HELPER FUNCTIONS --------------------------------------------- */
/*
-
-
-
-
-
-
-
-
*/
/* ---------------------------------------------- VALIDATION / SUBMISSION --------------------------------------------- */
function ValidateAndSubmitForm() {

	jQuery('#informationForm').validate({
		rules: {
			EmailAddress: { required: true, email: true },
			EmailAddressConfirm: { required: true, email: true, equalTo: '#EmailAddress' },
			Password: { required: true },
			PasswordConfirm: { required: true, equalTo: '#Password' },
			FirstName: { required: true },
			LastName: { required: true },
			Organization: { required: true },
			OrganizationType: { required: true },
			MediaOutlet: {
				required: function(element) {
					return jQuery('#OrganizationType').val() == organizationMediaValue;
				}
			},
			Occupation: {
				required: function(element) {
					return jQuery('#OrganizationType').val() == organizationCollegeValue || jQuery('#OrganizationType').val() == organizationMediaValue;
				}
			},
			Country: { required: true },
			StateProvince: {
				required: function(element) {
					return jQuery('#Country').val() == countryCanadaValue || jQuery('#Country').val() == countryUnitedStatesValue;
				}
			},
			HtmlOrText: { required: true }
		},
		messages: {
			EmailAddressConfirm: { equalTo: "Email addresses must match." },
			PasswordConfirm: { equalTo: "Passwords must match." },
			Organization: { required: 'If no organization, enter "none".' }
		},
		submitHandler: function(form) {
			var url = 'SubmitProfile';
			var callback = function() {
				location.href = welcomePage;
			};

			IsEmailAddressValid(form.EmailAddress.value, url, callback);
			return false;
		}
	});

	jQuery('#loginExistingUser').validate({
		rules: {
			EmailAddress: { required: true, email: true },
			Password: { required: true }
		},
		submitHandler: function(form) {
			var callback = function(data) {
				var messages = jQuery('.messages', form);
				if (data.d)
					Login(form.EmailAddress.value, form.Password.value, messages);
				else
					messages.text("We couldn't find your email address. Would you like to register as a new user?");
			}

			EmailAddressExists(form.EmailAddress.value, callback);
			return false;
		}
	});

	jQuery('#loginNewUser').validate({
		rules: {
			EmailAddress: { required: true, email: true }
		},
		submitHandler: function(form) {
			var callback = function(data) {
				if (data.d) {
					var messages = jQuery('.messages', form);
					messages.html("This email address is already in the Kaiser Family Foundation system. Please enter a new email address or <a id='loginNewUserPasswordRetrieval' href='#'>click here</a> to have your password emailed to you.");
				}
				else {
					jQuery('#loginCurtain').fadeOut('normal', ShowSubscriptions(true));
					jQuery('#loginWrapper').hide();
					jQuery('#EmailAddress').val(form.EmailAddress.value);
					jQuery('#EmailAddressConfirm').val(form.EmailAddress.value);
				}
			}

			EmailAddressExists(form.EmailAddress.value, callback);
			return false;
		}
	});

	jQuery('#loginPasswordRetrieval').validate({
		rules: {
			EmailAddress: { required: true, email: true }
		},
		submitHandler: function(form) {
			var callback = function(data) {
				if (data.d) {
					// send email
					PerformPasswordRetrieval(form.EmailAddress.value);
				}
				else {
					// email doesn't exist
					var instructions = jQuery('.messages', jQuery('.part1', form));
					instructions.text("We couldn't find your email address. You might want to go back and register as a new user.");
				}
			}

			EmailAddressExists(form.EmailAddress.value, callback);
			return false;
		}
	});

	jQuery('#passwordChangeForm').validate({
		rules: {
			CurrentPassword: { required: true },
			NewPassword: { required: true },
			ConfirmNewPassword: { required: true, equalTo: '#NewPassword' }
		},
		messages: {
			ConfirmNewPassword: { equalTo: "Passwords must match." }
		},
		submitHandler: function(form) {
			var callback = function(data) {
				if (data.d) {
					var innerCallback = function(data) {
						var messages = jQuery('.messages', form);
						if (data.d) {
							var cancelId = jQuery('#submitPasswordChangeCancelName').val();

							messages.text("Your password was changed successfully.");
							jQuery('#submitPasswordChange').hide();
							jQuery('#' + cancelId).val('Continue');
						}
						else {
							messages.text("An error occurred - please try again.");
						}
					}
					ChangePassword(form.CurrentPassword.value, form.NewPassword.value, innerCallback);
				}
				else {
					var messages = jQuery('.messages', form);
					messages.text("'Current password' is incorrect.");
				}
			}

			IsPasswordValid(form.CurrentPassword.value, callback);
			return false;
		}
	});
}

function SubmitProfile(url, callback) {
	// Create a data transfer object (DTO) with the proper structure.
	var dto = { 'profile': CreateProfileObject() };
	var data = JSON2.stringify(dto);

	AjaxHelper(url, data, callback);
}
/* ---------------------------------------------- VALIDATION / SUBMISSION --------------------------------------------- */