function addPseudoClasses($) {
	$("form div:has(label)").addClass('has_label');
}

function initFormSubmitLinks($) {
	$("a.form_submit_link").click(function() {
		if (!this.title || confirm(this.title)) {
			$(this).closest("form").submit();
		}
	});
}

function initFormsWithoutSubmit($) {
	$(".submit_link:not(.cancel)").each(function() {
		var $this = $(this);
		var form = $this.closest("form");

		$this.click(function() {
			form.submit();
			return false;
		});
		form.find("input[type=text], input[type=password]").keypress(function(e) {
			if (e.keyCode == 13)
				form.submit();
		});
	});
}

function initTableSorter($) {
	$("table.data:has(thead):has(tbody)").tablesorter({
		sortList: [[0, 0]]
	}).bind("sortEnd", function() {
		$(this).find("tr:even").removeClass('even').addClass('odd');
		$(this).find("tr:odd").removeClass('odd').addClass('even');
	});
}

function initMessage($) {
	if ($("#message").html()) {
		$("#message_wrapper").delay(2000).fadeOut();
	} else {
		$("#message_wrapper").hide();
	}
}

function initLoginForm($) {
	$("#loginform").validateAjaxForm({
		validateOpts: {
			rules: {
				email: {
					required: true,
					email: true
				},
				password: "required"
			}
		},
		success: function(response) {
			if (response.url != 'index.php') {
				location = response.url;
				return;
			}

			if (response.data) {
				$("#current_user_name").html(response.data.first_name + " " + response.data.last_name);
			}

			showMessage(response.message);
			$("#loginBox").slideUp();
			$("#logoutBox").slideDown();

			$("#subMenu").load("bottom_nav.php");
		},
		error: function(message) {
			showMessage(message);
		}
	});

	$("#logout_link").click(function() {
		$.get("logout.php", function(response) {
			if (response.message) {
				showMessage(response.message);
				if (response.success) {
					$("#logoutBox").slideUp();
					$("#loginBox").slideDown();
					$("#subMenu").load("bottom_nav.php");
				}
			}
		}, "json")
		return false;
	});
}

function initTireSearch(form, $) {
	$.fn.fillSelect = function(field) {
		if (!this[0])
			return;

		var serialization = form.serialize(),
			value = this.val();

		showLoader(form);

		return this.load("search_fill.php?field=" + field + "&" + serialization, function() {
			hideLoader(form);

			if (this.options.length == 2) {
				this.selectedIndex = 1;
			} else {
				$(this).val(value);
			}
			if (this.value) {
				$(this).change();
			}
		});
	};

	if (form.find("select[name=manufacturer_id]").attr('selectedIndex') <= 0) {
		form.find("select[name=manufacturer_id]").fillSelect('manufacturer');
	}
	if (form.find("select[name=type_id]").attr('selectedIndex') <= 0) {
		form.find("select[name=type_id]").fillSelect('type');
	}

	form.find("select[name=manufacturer_id]").change(function() {
		form.find("select[name=width]").fillSelect('width');
	});
	form.find("select[name=type_id]").change(function() {
		form.find("select[name=width]").fillSelect('width');
	});

	form.find("select[name=width]").change(function() {
		form.find("select[name=aspect_ratio]").fillSelect('aspect_ratio');
	});
	form.find("select[name=aspect_ratio]").change(function() {
		form.find("select[name=diameter]").fillSelect('diameter');
	});
	
	$(".colorbox").colorbox();
}

function initCartButtons($) {
	$(".cart_add_link").live('click', function() {
		var tire_id = this.rel.match(/^tire_(\d+)$/)[1];
		if (tire_id) {
			$.cart(tire_id, 1);
			$(this).removeClass('cart_add_link').addClass('cart_remove_link').find("img").attr({
				src: "images/cartRemove.gif",
				alt: "Remove",
				title: "Remove"
			});
			showMessage('This product has been added to your cart');
		}
		return false;
	});

	$(".cart_remove_link").live('click', function() {
		var tire_id = this.rel.match(/^tire_(\d+)$/)[1];
		if (tire_id) {
			$.cart(tire_id, 0);
			$(this).removeClass('cart_remove_link').addClass('cart_add_link').find("img").attr({
				src: "images/addtocart.gif",
				alt: "Add",
				title: "Add"
			});
			showMessage('This product has been removed from your cart');
		}
		return false;
	});

	$(".cart_quantity").live('blur', updateCart);
	$("#province").change(updateTotal);

	function updateCart() {
		var tire_id = $(this).next(".cart_single_price")[0].name.match(/^tire_(\d+)$/)[1];
		if (tire_id) {
			$.cart(tire_id, parseInt(this.value, 10));
			var total = getTotal();
			$("#cart_total_quantity").html(total.total_quantity);
			$("#cart_total_price").html("$" + total.total_price);
			updateTotal();
			showMessage('Your cart has been updated');
		}
	};
	
	function getTotal() {
		var total = {'total_quantity' : 0, 'total_price' : 0};
		
		$(".cart_quantity").each(function() {
			var quantity = parseInt(this.value, 10);
			total['total_quantity'] += quantity;
			var price_per_unit = parseInt($(this).next(".cart_single_price").val(), 10);
			var price = price_per_unit * quantity;
			
			total['total_price'] += price;
			$(this).closest("tr").find(".cart_price").html("$" + price);
			$(this).closest("tr").find(".cart_times").html(quantity);
		});
		
		return total;
	}
	
	function updateTotal(silent) {
		var provinces = {
			'Alberta': 52,
			'British Columbia': 64,
			'Manitoba': 52,
			'New Brunswick': 44,
			'Newfoundland and Labrador': 44,
			'Nova Scotia': 44,
			'Ontario': 36,
			'Prince Edward Island': 44,
			'Quebec': 30,
			'Saskatchewan': 52
		};
		var taxes = {
			'Alberta': 5,
			'British Columbia': 12,
			'Manitoba': 5,
			'New Brunswick': 13,
			'Newfoundland and Labrador': 13,
			'Nova Scotia': 15,
			'Ontario': 13,
			'Prince Edward Island': 5,
			'Quebec': 13.5,
			'Saskatchewan': 5,
			'Yukon': 5,
			'Nunavut': 5,			
			'Northwest Territories': 5
		};
		var total = getTotal();
		var shipping_cost = Math.round(provinces[$("#province").val()] * total['total_quantity'] / 4);
		$("#cart_shipping_price").html("$" + shipping_cost);
		$("#cart_subtotal_price").html("$" + Math.round( total['total_price'] ));
		var totalAndShipping = total['total_price'] + shipping_cost ;
		var special_tax = 0;
		$("#special_tax_row").hide();
		if($("#province").val())
		if ($("#province").val().toLowerCase() == 'alberta')
		{//
			$("#special_tax_row").show();
			$("#special_tax_name span").hide();
			$("#special_tax_name #tire_levy").show();
			special_tax = Math.round( total['total_quantity'] * 4 );
			$("#special_tax_price").html("$" + special_tax);
			
		}
		if($("#province").val())
		if ($("#province").val().toLowerCase() == "quebec")
		{
			$("#special_tax_name span").hide();
			$("#special_tax_name #tire_recycling").show();
			special_tax = Math.round( total['total_quantity'] * 3 );
			$("#special_tax_price").html("$" + special_tax);
			$("#special_tax_row").show();
			
		}
		
     	var tax = (totalAndShipping * taxes[$("#province").val()]) / 100;
		$("#cart_tax_price").html("$" + Math.round( tax ));
		$("#cart_total_price").html("$" + Math.round( totalAndShipping + tax  + special_tax));

		if (!silent) {
			showMessage('Your cart has been updated');
		}
	}
	updateTotal(true);
				
}

function showLoader(form) {
	form.find("select, input, textarea").attr('disabled', true);

	var submitButton = form.find(".submit_link"),
		initialValue = submitButton.html(),
		regex = new RegExp("^" + initialValue + "{1,3}$");

	submitButton.data('initialValue', initialValue);
	submitButton.data('loaderInterval', window.setInterval(function() {
		if (regex.test(submitButton.html())) {
			submitButton.html(submitButton.html() + "»");
		} else {
			submitButton.html(initialValue);
		}
	}, 200));
}
function hideLoader(form) {
	form.find("select, input, textarea").removeAttr('disabled');

	var submitButton = form.find(".submit_link");
	window.clearInterval(submitButton.data('loaderInterval'));
	submitButton.html(submitButton.data('initialValue'));
}

function showMessage(message) {
	jQuery("#message").html(message);
	jQuery("#message_wrapper").stop(true, true).fadeIn().delay(2000).fadeOut();
}

(function($) {
	$.fn.validateAjaxForm = function(opts) {
		this.validate($.extend({
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					dataType: "json",
					beforeSubmit: function(data, form) {
						if ($(form).valid()) {
							showLoader($(form));
							return true;
						}
						return false;
					},
					success: function(response, statusText, xhr, $form) {
						hideLoader($form);
						if (response.success && opts.success) {
							opts.success(response);
						} else if (!response.success && opts.error) {
							opts.error(response.message);
						}
					},
					error: function(xhr, textStatus, errorThrown) {
						hideLoader($(form));
						if (opts.error) {
							switch (textStatus) {
								case "timeout":
									opts.error("The request timed out.");
									break;

								default:
									opts.error("An error occurred. Please try again later.");
							}
						}
					}
				});
			}
		}, opts.validateOpts));

		return this;
	}
})(jQuery);

(function($) {
	$.animateScroll = function(element, delay, callback) {
		if ($.isFunction(delay)) {
			callback = delay;
			delay = undefined;
		}

		$("html, body").animate({
			scrollTop: $(element).offset().top
		}, {
			duration: delay || 1000,
			complete: callback
		});
	}
})(jQuery);
