// JavaScript Document

$(document).ready(function() {
	
	// Warn if cart is full and about to navigate away
	$('#primary-nav a, #logo a, #side-nav').click(function(event) {
		event.stopPropagation();
		if ($('#cartList p').is(':visible')) {
			if (!confirm('You are about to navigate away from this page. Any items on your shopping list will be lost.')) {
				event.preventDefault();
			}
		}
	});
	
	// CATAGORIES - Nesting and interaction
	$('.storeCategories li ul').each(function(i){
		$(this).parent().addClass('topsidenav');
	});
	$('.topsidenav > a').each(function(){
		$(this).append(' +');
	});
	$('li.topsidenav > a').click(function(event){
		event.preventDefault();
		if ($("ul",$(this).parent()).is(':visible')) {
			$("ul",$(this).parent()).hide('normal');
		} else {
			$('li.topsidenav ul:visible').hide('normal');
			$("ul",$(this).parent()).show('normal');
		}
	});
	$('.storeCategories a').click(function(event){
		event.preventDefault();
		if ($(this).parent().hasClass("topsidenav")) {
			return;
		}
		$html = $(this).attr('href');
		switchSubPage($html);
	});
	
	// SUBMITTING THE FORM
	$('#checkoutForm').submit(function(event) {
		event.stopPropagation();
		if ($('#name').val() == "" || $('#phone').val() == "" || $('#email').val() == "" || $('#address').val() == "" || $('#city').val() == "" || $('#state').val() == "" || $('#zip').val() == "") { // Validation
			alert('All fields (except comment) are required.');
			return false;
		}
		if ($('#email').val().indexOf('@') <= -1 || $('#email').val().indexOf('.') <= -1) { // Check for well-formed email
			alert('Please provide a valid email address.');
			return false;
		}
	});
	
	$('#helpDiv a').click(function(event){
		event.preventDefault();
		if (!$('.helpText').is(':visible')) {
			$('.helpText').animate({'height':'show','opacity':'show'},'normal');
			$(this).text('hide help');
		} else {
			$('.helpText').animate({'height':'hide','opacity':'hide'},'normal');
			$(this).text('help');
		}
	});
	
	// Hide checkout and continue shopping
	$('.cancelButton a').click(function(event){
		event.preventDefault();
		$('#checkoutForm').hide('fast',function() {
			$('#checkOutButton').show();
		});
	});	
	
	// INITIALIZE PAGE
	$('#checkoutForm').hide();
	$('#headerTextDiv').hide();
	switchSubPage("featured_products.html");
});

function totalPrice() { // Add up prices in cart
	var total = 0;
	$('#cartList p').each(function(i){
		myPrice = $(this).attr('price');
		myPrice = parseFloat(myPrice);
		total += myPrice;
	});
	$('#totalPrice b').text(total);
}

function checkout() { // Tally cart and submit order
	var cartContents_array = new Array();
	$('#cartList p').each(function(i){
		var contents = $(this).text();
		contents = contents.substring(2,contents.length); // Remove X from item lines
		cartContents_array[i] = contents;
	});
	$('#cartField').val(cartContents_array);
	$('#totalField').val($('#totalPrice b').text());
	if (!$('#cartField').val()) {
		alert('You have nothing on your shopping list!');
		return;
	}
	$('#checkOutButton').hide();
	$('#checkoutForm').show('fast');
}

function switchSubPage(html) { // Dynamically load the product lists
	$html = html;
	$('#productArea').load($html +' #productListing',function() {
		$('#productArea .product:first').css('border-top','none');
		$('.sku').prepend('[');
		$('.sku').append(']');
		$('.thumbnail img').each(function(i){ // Give title to thickbox popups
			$container = $(this).parents('.product');
			$title = $('.name',$container).text();
			$link = $(this).parents('a');
			$dink = $link.attr('href');
			if (!$dink) {
				alert($(this).attr('src')+" - "+$dink);
				return;
			}
			$link.attr('title',$title);
			$link.attr('rel','Gallery');
			var href = $link.attr('href');
			if (href.indexOf('.jpg') > -1 || href.indexOf('.gif') > -1 || href.indexOf('.png') > -1 || href.indexOf('.jpeg') > -1) { // If user forgets to link an image, don't thickbox!
				$link.addClass('thickbox');
			} else {
				$link.before($link.html()).remove();	
			}
		});
		$('.description a').click(function(event){
			event.preventDefault();
			$html = $(this).attr('href');
			switchSubPage($html);
		});
		$('.addToCart').click(function(event){
			event.preventDefault();
			if ($('#checkoutForm').is(':visible')) {
				alert('Close the "Submit Your Shopping List" form to add more items to your shopping list.');
				return;
			}
			$element = $(this).parent().parent().parent();
			$name = $('.name',$element).text();
			$sku = $('.sku',$element).text();
			$price = $('.price',$element).text();
			$price = $price.substring(1,$price.length);
			var newelement = document.createElement('p');
			var $newelement = $(newelement);
			$newelement.append(' ' + $name + ' - $' + $price + ' - ' + $sku);
			$newelement.attr("price",$price);
			var newlink = document.createElement('a');
			var $newlink = $(newlink);
			$newlink.text('X').attr('href','#');
			$newlink.click(function(event){
				event.preventDefault();
				if ($('#checkoutForm').is(':visible')) {
					alert('Close the "Submit Your Shopping List" form to remove items from your shopping list.');
					return;
				} else {
					$(this).parent().remove();
					totalPrice();
				}
			});
			$newelement.prepend($newlink);
			$('#cartList').append($newelement);
			totalPrice();
		});
		tb_init('a.thickbox, area.thickbox, input.thickbox');
	});
}