$(document).ready(
	function() {
		$('a.buttons').hover(
			function() {
				$(this).addClass('ui-state-hover');
			},
			function() {
				$(this).removeClass('ui-state-hover');
			}
		);
//	icon mouseover effect
		$('td#mainNav img').mouseover(function() {
			var src = $(this).attr("src").match(/[^\.]+/) + "-pink.gif";
			$(this).attr("src", src);
		}).mouseout(function(){
			var src = $(this).attr("src").replace("-pink", "");
			$(this).attr("src", src);
		});
		$('ul#whatsavailSub a').mouseover(function() {
			$('a#whatsavailBtn img').attr("src", "images/nav-whatsavail-pink.gif");
		}).mouseout(function(){
			$('a#whatsavailBtn img').attr("src", "images/nav-whatsavail.gif");
		});
		$('ul#saleSub a').mouseover(function() {
			$('a#saleBtn img').attr("src", "images/nav-sale-pink.gif");
		}).mouseout(function(){
			$('a#saleBtn img').attr("src", "images/nav-sale.gif");
		});

//	Sign Up
		$('div#regDialog').dialog({
			autoOpen		: false,
			bgiframe		: true,
			resizable		: false,
			width			: 600,
			position		: 'center',
			modal			: true,
			buttons			: {
				'Cancel': function () {
					$(this).dialog('close');
				}, 'Submit': function () {
					$("form#regForm").submit();
				}
			}
		});
		$("form#regForm").validate({
			rules: {
				username: {
					required: true,
					maxlength: 10
				},
				password: {
					required: true,
					minlength: 8
				},
				confirm_password: {
					required: true,
					minlength: 8,
					equalTo: "#password"
				},
				name: "required",
				email: {
					required: true,
					email: true
				},
				address: "required",
				zip: {
					required: true,
					digits: true,
					minlength: 6,
					maxlength: 6
				},
				country: "required",
				phone: {
					digits: true,
					minlength: 8,
					maxlength: 8
				},
				vercode: "required"
			}, messages: {
				username: {
					maxlength: "Must not be longer than 10 characters."
				},
				password: {
					minlength: "Must be at least 8 characters."
				},
				confirm_password: {
					minlength: "Must be at least 8 characters.",
					equalTo: "Passwords do not match."
				},
				email: {
					email: "Email address not valid."
				},
				zip: {
					digits: "Zip code must be numeric.",
					minlength: "Zip code must be 6 digits.",
					maxlength: "Zip code must be 6 digits."
				},
				phone: {
					minlength: "Contact number must be 8 digits.",
					maxlength: "Contact number must be 8 digits.",
					digits: "Contact number must be numeric."
				}
			}, errorPlacement: function(error, element) {
				element.parent().next().html(error);
			}, submitHandler: function(form) {
				$.getJSON('register.php', $(form).serialize(), function(data){
					switch(data.code) {
						case 0:
							$('div#regDialog').dialog('close');
							alert('You have successfully created an account!');
							if(location.href.indexOf("checkout.php") > 0) {
								location.reload();
							} else {
								$('div#loginDialog').dialog('close');
								$('a#login').remove();
								$('a#register').remove();
								$('td#topNavigation').prepend("Logged in as " + $('input#loginId').val()  + ". <a class='ui-state-default ui-corner-all buttons' href='logout.php'>Logout</a> <a class='ui-state-default ui-corner-all buttons' href='account.php'>My Account</a>");
							}
						break;
						case 1:
							alert('System error. Please try again later!');
						break;
						case 2:
							alert('Please check you security code and try again!');
						break;
						case 3:
							alert('Your email or username is taken. Please try again!');
						break;
					}
				});
			}
		});

//	Login
		$('div#loginDialog').dialog({
			autoOpen		: false,
			bgiframe		: true,
			resizable		: false,
			width			: 400,
			position		: 'center',
			modal			: true,
			buttons			: {
				'Cancel': function () {
					$(this).dialog('close');
				}, 'Submit': function () {
					$.getJSON('login.php', {
						username: $('input#loginId').val(),
						password: $('input#loginPwd').val()
					}, function(data) {
						switch(data.code) {
							case 0:
								if(location.href.indexOf("checkout.php") > 0) {
									location.reload();
								} else {
									$('div#loginDialog').dialog('close');
									$('a#login').remove();
									$('a#register').remove();
									$('div.signup').prepend("<a href='account.php'>My Account</a>");
									$('div.login').prepend("<p>Logged in as " + $('input#loginId').val()  + "<a href='logout.php'> (Logout)</a></p>");
								}
							break;
							case 1:
								alert('Server error, please try again later!');
							break;
							case 2:
								alert('Wrong username or password!');
							break;
						}
					});
				}
			}
		});


//	Mailing List Components
		$("form#mailingListForm").validate({
			onkeyup: false,
			onclick: false,
			errorClass: '',
			rules: {
				mailingEmail: {
					required: true,
					email: true
				}
			}, messages: {
				mailingEmail: {
					email: "Email address not valid."
				}
			}, errorPlacement: function(error, element) {
				alert($(error).text());
			}, submitHandler: function(form) {
				$.getJSON('mailingList.php', $(form).serialize(), function(data){
					switch(data.code) {
						case 0:
							$('input#mailingEmail').val('');
							alert('You have successfully joined our mailing list!');
						break;
						case 1:
							alert('System error. Please try again later!');
						break;
						case 2:
							alert('Email address is already in our mailing list!');
						break;
					}
				});
			}, onfocusout: function() {}
		});


//	Contact Us Components
		$('div#contactDialog').dialog({
			autoOpen		: false,
			bgiframe		: true,
			resizable		: false,
			width			: 600,
			position		: 'center',
			modal			: true,
			buttons			: {
				'Cancel': function () {
					$(this).dialog('close');
				}, 'Submit': function () {
					$("form#contactForm").submit();
				}
			}
		});
		$('li#contactUs, a#contactUsAnchor').click(
			function(event) {
				event.preventDefault();
				$('div#contactDialog').dialog('open');
			}
		);
		$('a#waitinglist').click(
			function(event) {
				event.preventDefault();
				$('div#contactDialog').dialog('open');
				$('#contactSubject').val('Join Waiting List');
				$('#contactMessage').val('RE: '+$('.pName').text());
			}
		);
		$("form#contactForm").validate({
			rules: {
				contactName: "required",
				contactNumber: {
					required: false,
					digits: true
				},
				contactEmail: {
					required: true,
					email: true
				},
				contactMessage: "required"
			}, messages: {
				contactNumber: {
					digits: "Contact number must be numeric."
				},
				contactEmail: {
					email: "Email address not valid."
				}
			}, errorPlacement: function(error, element) {
				element.parent().next().html(error);
			}, submitHandler: function(form) {
				$.post('contact.php', $(form).serialize(), function(data){
					switch(data.code) {
						case 0:
							alert('Thank you for your time. We will get back to you shortly.');
							$('div#contactDialog').dialog('close');
						break;
						case 1:
							alert('System error. Please try again later!');
						break;
					}
				}, "json");
			}
		});


//	category.php





//Update Particulars Components
		$('a#update').click(
			function(event) {
				event.preventDefault();
				$("form#myAccountForm").submit();
			}
		);
		$("form#myAccountForm").validate({
			rules: {
				name: "required",
				email: {
					required: true,
					email: true
				},
				contact: {
					digits: true,
					minlength: 8,
					maxlength: 8
				},
				address: "required",
				zip: {
					required: true,
					digits: true,
					minlength: 6,
					maxlength: 6
				},
				country: "required"
			}, messages: {
				email: {
					email: "Email address not valid."
				},
				zip: {
					digits: "Zip code must be numeric.",
					minlength: "Zip code must be 6 digits.",
					maxlength: "Zip code must be 6 digits."
				},
				contact: {
					minlength: "Contact number must be 8 digits.",
					maxlength: "Contact number must be 8 digits.",
					digits: "Contact number must be numeric."
				}
			}, errorPlacement: function(error, element) {
				element.parent().next().html(error);
			}, submitHandler: function(form) {
				$.getJSON('accountSubmit.php', $(form).serialize(), function(data){
					switch(data.code) {
						case 0:
							alert('Particulars updated!');
						break;
						case 1:
							alert('System error. Please try again later!');
						break;
						case 2:
							alert('Your email address already exists under a different account. Please try again!');
						break;
						case 3:
							alert('Your passwords do not match!');
						break;
					}
				});
			}, onfocusout: function() {}
		});

//Forgot Password Components
		$('a#forgot').click(
			function(event) {
				event.preventDefault();
				$("form#forgotForm").submit();
			}
		);
		$("form#forgotForm").validate({
			onkeyup: false,
			onclick: false,
			errorClass: '',
			rules: {
				forgot: {
					required: true,
					email: true
				}
			}, messages: {
				forgot: {
					email: "Email address not valid."
				}
			}, errorPlacement: function(error, element) {
				alert($(error).text());
			}, submitHandler: function(form) {
				$.getJSON('forgotSubmit.php', $(form).serialize(), function(data){
					switch(data.code) {
						case 0:
							alert('Please check your email address for your new password!');
						break;
						case 1:
							alert('System error. Please try again later!');
						break;
						case 2:
							alert('Email address is not registered with us!');
						break;
					}
				});
			}, onfocusout: function() {}
		});

//Unsubscribe Components
		$('a#unsubscribe').click(
			function(event) {
				event.preventDefault();
				$("form#unsubscribeForm").submit();
			}
		);
		$("form#unsubscribeForm").validate({
			onkeyup: false,
			onclick: false,
			errorClass: '',
			rules: {
				unsubscribe: {
					required: true,
					email: true
				}
			}, messages: {
				unsubscribe: {
					email: "Email address not valid."
				}
			}, errorPlacement: function(error, element) {
				alert($(error).text());
			}, submitHandler: function(form) {
				$.getJSON('unsubscribeSubmit.php', $(form).serialize(), function(data){
					switch(data.code) {
						case 0:
							alert('You have been removed from our mailing list!');
						break;
						case 1:
							alert('System error. Please try again later!');
						break;
						case 2:
							alert('Email address is not in our mailing list!');
						break;
					}
				});
			}, onfocusout: function() {}
		});




//External Links
		$('li.extLink a').click(
			function(event) {
				event.preventDefault();
				window.open($(this).attr('href'));
			}
		);


	}
);


$.fn.extend({
	loadCart: function(operation, pid, qty) {
		$.getJSON('cart.php', {
			operation	: operation,
			pid			: pid,
			qty			: qty
		}, function(data) {
			switch(data.result) {
				case 0:
					$('table#cartPreview > tbody').empty();
					$.each(data.cart,
						function(index, item) {
							$('table#cartPreview > tbody').append(
								$(document.createElement('tr')).append(
									$(document.createElement('td')).attr('colspan', '3').addClass('item').html("<a href='product.php?pid=" + item[0] + "'>" + $().decodeString(item[1]) + "</a>")
								)
							);
							var priceString;
							if(item[4]) {
								priceString = '<span class="pDPrice">' + item[3] + '</span>';
							} else {
								priceString = item[3];
							}
							$('table#cartPreview > tbody').append(
								$(document.createElement('tr')).append(
									$(document.createElement('td')).addClass('qty').text('x' + item[2])
								).append(
									$(document.createElement('td')).addClass('rem').html('<a href="javascript:$().loadCart(1,'+item[0]+','+item[2]+');">Remove<\/a>')
								).append(
									$(document.createElement('td')).addClass('price').html(priceString)
								)
							);
						}
					);
				break;
				case 1:
					alert('Shopping cart is temporarily unavailable.\nPlease try again later!');
				break;
				case 2:
					alert('There is insufficient stock to fulfill this order.');
				break;
			}
		});
	},
	encodeString: function(source) {
		var result = source.replace(/\n/g, '%n');
		result = result.replace(/\\/g, '%b');
		result = result.replace(/'/g, '%s');
		result = result.replace(/"/g, '%d');
		return result;
	},
	decodeString: function(source) {
		var result = source.replace(/%n/g, '<br />');
		result = result.replace(/%b/g, '\\');
		result = result.replace(/%s/g, '\'');
		result = result.replace(/%d/g, '"');
		return result;
	}
});
