﻿var $j = jQuery.noConflict();

$j.ajaxSetup({
	cache: false
});

if ($j.cookie('showLoggedOutMessageOption') == 'true')
	startKeepAlive();

//--------------------------------------------------------------------------------------------------------------------

$j(document).ready(function ()
{

	$j('.Popup').live('click', function (event)
	{
		event.preventDefault();
		window.open(this.href);
	});

	$j('.PopupGallery').live('click', function (event)
	{
		event.preventDefault();
		window.open(this.href, '_blank', 'toolbar=no,scrollbars=yes,resizable=yes');
	});

	$j('#LoginButton.LoggedOut').live('click', function (event)
	{
		event.preventDefault();
		displayLoginForm();
	});

	$j('#ForgotPasswordLink').live('click', function (event)
	{
		event.preventDefault();
		$j('#LoginForm').dialog('destroy').remove();
		displayForgotPasswordForm();
	});

	$j('#LoginForm').live('submit', function (event)
	{
		event.preventDefault();
		$j.post(
			'/login/login_xhr.aspx',
			$j('#LoginForm').serialize(),
			loginResponse
		);
	});

	$j('a[href="/membership"]').click(Preferences.ShowPreferences);

});

//--------------------------------------------------------------------------------------------------------------------

function startKeepAlive() 
{
	loginInterval = window.setInterval(KeepAlive, 900000);
}



function KeepAlive() 
{
	$j.get(
		'/login/login_xhr.aspx?cmd=KeepAlive',
		function (Data) {
			if (!Data.LoggedIn) {
				if ($j.cookie('showLoggedOutMessageOption') == 'true') {
					clearInterval(loginInterval);
					displayLoginForm()
				}
			}
		}
	);
}


function displayLoginForm()
{
	$j('<form>', {id: 'LoginForm', action: '#', method: 'post'})
		.append($j('<p>')
			.append($j('<label>').text('Username:'))
			.append($j('<input>', {type: 'text', id:'Username', name: 'Username'}))
			.append($j('<input>', {type: 'hidden', name: 'cmd', value: 'Login'}))
		)
		.append($j('<p>')
			.append($j('<label>').text('Password:'))
			.append($j('<input>', {type: 'password', id:'Password', name: 'Password'}))
			.append($j('<input>', {type: 'checkbox', id: 'RememberPassword'}))
			.append($j('<span>', {id: 'RememberPasswordText'}).text('Remember Password'))
		)
		.append(
			$j('<p>').append(
				$j('<a>', { id: 'ForgotPasswordLink', href: '#', 'class': 'ui-corner-all' }).text('Forgot Your Password?')
			)
		)
		.appendTo($j(document.body))
		.dialog({
			title: 'Login',
			modal: true,
			width:440,
			buttons: {
				Cancel: destroyDialog,
				Login: function() { $j(this).submit() }
			},
			close: destroyDialog 
		})
		.keyup(function(event) {
			if(event.keyCode == 13)
				$j(this).submit()
		});
		if($j.cookie('Password') !=  null){
			$j('#Password').val($j.cookie('Password'));
			$j('#RememberPassword')[0].checked = true;
		}
		$j('#Username').val($j.cookie('Username')).select();
}



function loginResponse(Data)
{
	$j('.FormError').remove();

	if (Data.Success) {
		$j.cookie('showLoggedOutMessageOption', true, { path: '/' });
		startKeepAlive();
		$j.cookie('Username', $j('#Username').val(), { expires: 360, path: '/' });
		if($j('#RememberPassword')[0].checked)
			$j.cookie('Password', $j('#Password').val(), { expires: 360, path: '/' });
		else
			$j.cookie('Password', '', { expires: -1, path: '/' });

		$j('#LoginForm').dialog('destroy').remove();
		$j('#LoginButton').attr('class', 'LoggedIn').attr('href', '/logout/?Logout=1').text('Logout');
		$j('.NotLoggedIn').unbind();
		showLoginWelcome(Data);

		
	}else{
		$j('#LoginForm').append(
			$j('<p>', {'class':'FormError ui-state-highlight ui-corner-all'})
			.text(Data.Error.Message)
			.prepend($j('<span>', {'class': 'ui-icon ui-icon-alert'}))
		)
	}
}


function showLoginWelcome(Data) {
	var Message = $j('<div>', {id: 'LoginWelcome'}).append($j('<p>').text('Now lets explore some cracks.'));
	$j(Data.Messages).each(function (index) {
		Message.append($j('<h1>').text(Data.Messages[index].Title));
		Message.append($j('<p>').html(Data.Messages[index].MessageText.replace(/\n/gi, '<br />')));
	});

	if (Data.Surveys.length)
		Message.load('/surveys/survey.aspx?IDSurvey=' + Data.Surveys[0].IDSurvey)

	Message.dialog({
		title: 'Logged in - Welcome ' + Data.Member.FirstName,
		modal: true,
		width: 700,
		buttons: { Continue: function () {
			Message.remove();
			if (Data.Member.ContentAccess) {
				if (window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1) == 'logout.aspx')
					document.location = '/collections';
			} else {
				Message.remove();
				document.location = '/noaccess';
			}
		}
		}
	});

	if (Data.Surveys.length)
	{
		Message.dialog("option","buttons",{
			'Skip Survey': function ()
			{
				Message.remove()
				if (window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1) == 'logout.aspx')
					document.location = '/collections';
			},
			Submit: submitSurvey
		})
	}
}



function destroyDialog() 
{
	$j(this).dialog('destroy').remove();
}



function displayForgotPasswordForm()
{
	$j('<form>', {id: 'ForgotPasswordForm', action: '#', method: 'post'})
		.append($j('<p>')
			.append($j('<label>').text('Email Address:'))
			.append($j('<input>', {type: 'text', id:'Email', name: 'Email'}))
			.append($j('<input>', { type: 'hidden', name: 'cmd', value: 'ResetPasswordRequest' }))
		)
		.append($j('<p>')
			.append($j('<label>').text('-or- Username:'))
			.append($j('<input>', { type: 'text', id: 'Username', name: 'Username' }))
		)
		.append($j('<p>',{ 'class': 'ui-state-highlight ui-corner-all' })
			.html('Enter the e-mail address you signed up with -or- your username.  A <b>new</b> password e-mailed to you.')
			.prepend($j('<span>', { 'class': 'ui-icon ui-icon-info' }))
		)
		.append($j('<p>', { 'class': 'ui-state-highlight ui-corner-all' })
			.text('For security purposes, your current password is encrypted and cannot be retrieved - you will receive a new one.')
			.prepend($j('<span>', { 'class': 'ui-icon ui-icon-info' }))
		)
		.append($j('<p>', { 'class': 'ui-state-highlight ui-corner-all' })
			.text('Repeated use of this feature will create multiple passwords. Login with the latest password.')
			.prepend($j('<span>', { 'class': 'ui-icon ui-icon-info' }))
		)
		.appendTo($j(document.body))
		.dialog({
			title: 'Retrieve a New Password',
			modal: true,
			width: 320,
			buttons: {
				Continue: submitPasswordResetRequest,
				Cancel: destroyDialog
			},
			close: destroyDialog
		})
		.keyup(function(event) {
			if(event.keyCode == 13)
				submitLogin();
		});

		$j('#Email').focus();
}


function submitPasswordResetRequest()
{
	$j.post(
		'/login/login_xhr.aspx',
		$j('#ForgotPasswordForm').serialize(),
		resetPasswordResponse
	);
}


function resetPasswordResponse(Data)
{
	
	$j('#ForgotPasswordForm .FormError').remove();

	if (Data.Success)
	{
		$j('#ForgotPasswordForm').dialog('close');

		if (Data.ShowOnscreenOption)
			showResetChoice(Data.Username, Data.Email);
		else
			resetResponse();

	}else{
		$j('<p>', {'class':'FormError ui-state-highlight ui-corner-all'})
			.text(Data.Error.Message).css('color','red')
			.prepend($j('<span>', {'class': 'ui-icon ui-icon-alert'}))
			.appendTo($j('#ForgotPasswordForm'));
	}
}



function showResetChoice(Username, Email)
{
	var resetChoiceDiv = $j('<div>', { id: 'ResetChoice' })
		.append(
			$j('<p>').text('You have recently requested that a new password be sent to your e-mail address.  If you are not receiving the reset e-mails, you may try to reset your password on-screen.')
		)
		.dialog({
			title: 'Password Reset Option Available',
			modal: true,
			width: 430,
			buttons: {
				'Send Reset Email': function ()
				{
					resubmitPasswordResetRequest(Username, Email);
					resetChoiceDiv.remove();
				},
				'Reset Password OnScreen': function ()
				{
					showOnscreenReset(Username, Email);
					resetChoiceDiv.remove();
				}
			},
			cancel: function () { resetChoiceDiv.remove() }
		})
}


function resubmitPasswordResetRequest(Username, Email)
{
	var queryString = {cmd: 'ResetPasswordRequest', Username: Username, Email: Email, SendEmail:true }

	$j.post(
		'/login/login_xhr.aspx',
		$j.param(queryString),
		resetPasswordResponse
	);
}



function showOnscreenReset(Username, Email)
{
	var onscreenResetForm = $j('<form>', { id: 'OnScreenResetForm' })
		.append(
			$j('<p>').html('You may reset your password and view it on-screen by providing your <b>last name</b> and at least <b>two</b> of the the remaning 3 fields.')
		)
		.append(
			$j('<p>')
				.append($j('<label>').text('Username:'))
				.append($j('<input>', { id: 'OnScreenUsername', name: 'Username' }).val(Username))
				.append($j('<input>', {name: 'cmd', type: 'hidden' }).val('SubmitOnScreenReset'))
			)
			.append(
				$j('<p>')
					.append($j('<label>').text('Email:'))
					.append($j('<input>', { id: 'OnScreenEmail', name: 'Email' }).val(Email))
			)
			.append(
				$j('<p>')
					.append($j('<label>').text('First Name:'))
					.append($j('<input>', { id: 'OnScreenFirstName', name: 'FirstName' }))
			)
			.append(
				$j('<p>')
					.append($j('<label>').text('Last Name:'))
					.append($j('<input>', { id: 'OnScreenLastName', name: 'LastName' }))
			)
			.dialog({
				title: 'Reset Password OnScreen',
				modal: true,
				width: 375,
				buttons: {
					'Reset Password Onscreen': submitOnscreenReset,
					Close: function () { onscreenResetForm.remove() }
				},
				cancel: function () { onscreenResetForm.remove() }
			});
}


function submitOnscreenReset(){
	$j.post(
		'/login/login_xhr.aspx',
		$j('#OnScreenResetForm').serialize(),
		onScreenResetResponse
	);
}


function onScreenResetResponse(Data)
{
	$j('.FormError').remove();
	
	if(Data.Success)
	{
		$j('#OnScreenResetForm').remove();
		
		var showPasswordDiv = $j('<div>')
			.html('Your password has been reset.<br /><br>Your username is: <b>' + Data.Username + '</b><br />Your new password is: <b>' + Data.Password + '<b>')
			.dialog({
				title: 'Password Reset',
				modal: true,
				width:300,
				buttons: { Close: function() { showPasswordDiv.remove() }},
				cancel: function() { showPasswordDiv.remove() }
			});
	} 
	else 
	{
		$j('<p>', {'class':'FormError ui-state-highlight ui-corner-all'})
			.text(Data.Error.Message).css('color','red')
			.prepend($j('<span>', {'class': 'ui-icon ui-icon-alert'}))
			.appendTo($j('#OnScreenResetForm'));
	}
}


function resetResponse()
{
	$j('<div>', { id: 'ResetResponse' })
		.append(
			$j('<p>', { 'class': 'ui-state-highlight ui-corner-all' })
				.text('A new password has been created and sent to the e-mail address you provided.')
				.prepend($j('<span>', { 'class': 'ui-icon ui-icon-info' }))
			)
			.append(
			$j('<p>', { 'class': 'ui-state-highlight ui-corner-all' })
				.html('If you did not receive the e-mail, please check your junk mail folder.  Some internet providers may filter the e-mail as suspected spam.  If you do not receive it within one hour, <a href="mailto:info@inthecrack.com?subject=Cannot Reset Password&body=I need to reset my password, but the I am not receiving the reset e-mail from the website.">contact us</a>.')
				.prepend($j('<span>', { 'class': 'ui-icon ui-icon-info' }))
			)
		.dialog({
			title: 'New Password Sent',
			modal: true,
			width: 300,
			buttons: {
				OK: destroyDialog
			}
			});
	}


	var Preferences = {

		ShowPreferences: function (event)
		{
			event.preventDefault();
			var prefContainer = $j('<div>', { id: 'PreferencesContainer' })
			.load('/membership/')
			.dialog({
				modal: true,
				title: 'Member Preferences',
				width: 330,
				buttons: {
					Cancel: function () { prefContainer.remove() },
					Submit: Preferences.SubmitPreferences
				},
				cancel: function () { prefContainer.remove() }
			})

		},



		SubmitPreferences: function ()
		{
			$j.post(
				'/membership/membership_xhr.aspx?cmd=SubmitPreferences',
				$j('#PreferencesForm').serialize(true),
				Preferences.PreferencesSubmitted
			);
		},



		PreferencesSubmitted: function (Data)
		{
			if (Data.Success)
			{
				$j('#PreferencesContainer').remove();
				if (location.pathname.search(/gallery.aspx/) || location.pathname.search(/collection.aspx/))
					location.href = location.href;
			}
		}

	};    // End Preferences


	
