$(document).ready(function() {
	$buttons = $('#navigation li a');

	$buttons.append('<span class="hover"></span>').css('zoom', 1);

	if($.browser.msie && $.browser.version >= 7)
	{
		$buttons.each(function() {
			$hover_element = $('.hover', this);
			$hover_element.stop().animate({'opacity': 0.00001}, 1);
			setTimeout(function() { $hover_element.stop().animate({'opacity': 0}, 1); }, 10);
		});
	}

	$buttons.hover(function()
	{
		$('.hover', this).stop().animate(
		{
			'opacity': 1
		}, 400)
	},function()
	{
		$('.hover', this).stop().animate(
		{
			'opacity': 0
		}, 400)
	});

	$form = $('form');
	if($form)
	{
		$form.submit(function(e) {
			if($(this).hasClass('paypal'))
			{
				return;
			}
			if($(this).hasClass('contact'))
			{
				return;
			}

			//e.preventDefault();
	
			var empty_elements = [];
			var all_elements = [];
			var all_values = [];
	
			$('form#' + this.id + ' input, form#' + this.id + ' textarea').each(function() {
				$this = $(this);
				$this.css('border-color', '#727272');
				all_elements.push($this.attr('id'));
				all_values.push($this.attr('value'));
				
				if($this.hasClass('required'))
				{
					if($this.attr('value') == '')
					{
						empty_elements.push($this.attr('id'));
					}
				}
			});
			if(empty_elements.length != 0)
			{
				for(var i = 0; i < empty_elements.length; i++)
				{
					$('#' + empty_elements[i]).css('border-color', '#FF6666');
				}
				showEmptyFieldsDialog();
				e.preventDefault();
				return false;
			}
			else
			{
				var error = false;
				if(this.id == 'apply')
				{
					if(!$('input#read_terms').attr('checked'))
					{
						showTermsAndConditionsDialog();
						error = true;
					}
				}
				else if(this.id == 'refer')
				{
					if(!$('input#confirm').attr('checked'))
					{
						showConfirmedPermissionDialog();
						error = true;
					}
				}

				if(error) { e.preventDefault(); return false; }

				if(!error)
				{
					var success_action;
	
					switch(this.id)
					{
						case 'apply':
							success_action = showApplySuccessDialog;
						break;
	
						case 'agents':
							success_action = showAgentsSuccessDialog;
						break;
	
						case 'refer':
							success_action = showReferSuccessDialog;
						break;
	
						case 'contact':
							success_action = showContactSuccessDialog;
						break;
					}

					var post_url = $(this).attr('action');
					var post_data = $('form#' + this.id + ' input, form#' + this.id + ' textarea').fieldSerialize();

					/*$.ajax({
					   type: 'POST',
					   url: post_url,
					   data: post_data,
					   error: function(y, x, z) { alert('Returned erorr: ' + x); }
					 });*/

					/*$.ajax({
					   type: "POST",
					   url: "/inc/WriteForm.php",
					   data: "fields=" + all_elements + "&values=" + all_values
					 });*/
				}
			}
	
			//return false;
		});
	}

});

/* in separate functions for easy editing of the content */
function showApplySuccessDialog() {
	showDialog('Thank You', 'Thank you for your application. Click "Ok" to go to the Purchase page.',
		{
			'Ok': function() {
				document.location = 'purchase.php'
			},
			'Cancel': function() {
				$(this).dialog('close');
			}
		}
	);
}

function showAgentsSuccessDialog() {
	showDialog('Thank You', 'Thank you.',
		{
			'Ok': function() {
				$(this).dialog('close');
			}
		}
	);
}

function showReferSuccessDialog() {
	showDialog('Thank You', 'Thank you for your referral.',
		{
			'Ok': function() {
				$(this).dialog('close');
			}
		}
	);
}

function showContactSuccessDialog() {
	showDialog('Thank You', 'Thank you.',
		{
			'Ok': function() {
				$(this).dialog('close');
			}
		}
	);
}

function showEmptyFieldsDialog() {
	showDialog('Error', 'One or more required fields was not filled out. Please go back and check that you have filled in all fields marked with a *.',
		{
			'Ok': function() {
				$(this).dialog('close');
			}
		}
	);
}

function showTermsAndConditionsDialog() {
	showDialog('Error', 'You must read and accept the Terms and Conditions.',
		{
			'Ok': function() {
				$(this).dialog('close');
			}
		}
	);
}

function showConfirmedPermissionDialog() {
	showDialog('Error', 'You must confirm that you have permission from the person you are referring.',
		{
			'Ok': function() {
				$(this).dialog('close');
			}
		}
	);
}

function showDialog(title, message, buttons) {
	$('<div></div>').attr('title', title)
					.html(message)
					.dialog({
						'modal': true,
						'resizable': false,
						'width': 450,
						'height': 100,
						'buttons': buttons
					});
}

function sendContact() {
	to = "mark_appleby@btinternet.com";
	contactName = $("#name").attr("value");
	contactEmail = $("#email").attr("value");
	contactMessage = $("#message").attr("value");
	
	if ((!contactEmail) || (!contactName) || (!contactMessage)) {
		showEmptyFieldsDialog();
		return false;
	}
	else {
		contactMessage = contactMessage.replace(/&nbsp;/gi,'');
	   $.ajax({
		 type: "POST",
		 url: "/inc/sendContact.php",
		 data: "to=" + to + "&contactEmail=" + contactEmail + "&contactName=" + contactName + "&contactMessage=" + contactMessage,
		 success: function(html){
			 showDialog("Thank You", html,
				{
					'Ok': function() {
						$(this).dialog('close');
					}
				}
			);
		 }
	   });
	}
	return false;
}

function checkLogin() {
	email = $("#email").attr("value");
	passsword = $("#passsword").attr("value");
	if ((!email) || (!passsword)) {
		showEmptyFieldsDialog();
		return false;
	}
	else {
	   $.ajax({
		 type: "POST",
		 url: "/ajax/checkLogin.php",
		 data: "Username=" + email + "&Password=" + passsword,
		 success: function(html){
			 switch (html) {
				 case "1": window.location.href = "agent_hidden.php"; break;
				 case "2": FirstPassword(); break;
				 case "": alert("Incorrect Password"); break;
			 }
		 }
	   });
	}
	return false;
}

function FirstPassword() {
	$.ajax({
	  url: "forms/FirstPassword.php",
	  cache: false,
	  success: function(html){
		$('<div></div>').attr('title', "New Password")
					.html("For security reasons please enter a new password." + html)
					.dialog({
			bgiframe: true,
			resizable: false,
			height: 200,
			width: 320,
			modal: true,
			buttons: {
				'Save': function() {
					if (!$("#FirstPassword").attr("value")) {
						alert("No Password!");
					}
					else {						
						$.ajax({
						   type: "POST",
						   url: "/ajax/changePassword.php",
						   data: "Username=" + $("#email").attr("value") + "&Password=" + $("#FirstPassword").attr("value"),
						   success: function(html){ window.location.href = "agent_hidden.php"; }
 						 });
					}
				}
			}
		});
	  }
	});
}

function NewPassword() {
	$.ajax({
	  url: "forms/ForgotPassword.php",
	  cache: false,
	  success: function(html){
		$('<div></div>').attr('title', "Reset Password")
					.html("Please enter your email address to receive a new password." + html)
					.dialog({
			bgiframe: true,
			resizable: false,
			height: 200,
			width: 320,
			modal: true,
			buttons: {
				'Reset Password': function() {
					if (!$("#ResetUser").attr("value")) {
						alert("No Password!");
					}
					else {						
						$.ajax({
						   type: "POST",
						   url: "/ajax/resetPassword.php",
						   data: "Username=" + $("#ResetUser").attr("value"),
						   success: function(html){ window.location.href = "thanks.php"; }
 						 });
					}
				}
			}
		});
	  }
	});
}

function createLogin(Username) {
	//Create Login Details Here!!
							
	$.ajax({
	   type: "POST",
	   url: "/ajax/createUser.php",
	   data: "Username=" + Username
	 });
}

function showCVV() {
	$('<div></div>').attr('title', "What's This?")
					.html("<img src='images/security_code.jpg' />")
					.dialog({
			bgiframe: true,
			resizable: false,
			height: 320,
			width: 380,
			modal: true,
			buttons: {
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});	
}