//set up all onload actions in this framework
$(document).ready(function() {
	//1) NAVIGATION FLYOUT CONTROLS						   
		$(".navigation_primary").mouseover(function() {
			$(this).css('background-image','url(images/navigation_primary_hover.jpg)');
			$(this).css('background-repeat','repeat-x');
			$(this).css('color','#1b1f19');
			
			id = ($(this).attr('id')).substr(19,1);
			
			for(i=0;i<=3;i++)
			{
				if(i!=id) { $("#navigation_flyout_"+i).removeClass('active_menu').slideUp(); $("#navigation_primary_"+i).removeAttr("style"); }
				else if(!$("#navigation_flyout_"+id).is('.active_menu')) { $("#navigation_flyout_"+id).addClass('active_menu').slideDown('fast'); }
			}
			
			$("#header,#content,#cart,#footer").mouseover(function() {
				$(".navigation_primary").removeAttr("style");
				$(".active_menu").removeClass('active_menu').slideUp();
			});
		});
		updateCart();
});

//update the cart banner
function updateCart()
{
	$.post('ajax/cart_banner.php',{ } , function(data) { $('#cart').html(data); });
}

/* MODAL WINDOW v1.1: Andrew Sauder, andrewsauder@gmail.com, 240.321.9009 */
function openModal(data)
{
	$('#modalData').html('<img src="images/ajax-loader.gif" alt="loading..." title="loading..." />');
	$('#modalWindow').show();
	$('#modalBK').fadeTo('slow',.4);
	if(isset(data))
	{
		$('#modalData').html(data);
	}
}
function closeModal()
{
	$('#modalWindow').fadeOut();
	$('#modalBK').fadeOut();
	$('#modalData').html('');
}
function updateModal(productID)
{
	$.post("ajax/product_info.php",{ productID:productID },function(data) { $('#modalData').html(data); })
}

function taxHelp()
{
	$.post("ajax/taxhelp.php",function(data) { $('#modalData').html(data); })
}

function sendHelp()
{
	$.post("ajax/sendhelp.php",function(data) { $('#modalData').html(data); })
}

//slideshow on home page
var currentSlide = 1;
function slideshow(action)
{
	if(!isset(action))
	{
		$("#slideshow_"+currentSlide).fadeOut();
		if(currentSlide<5)
		{
			currentSlide++;
		}
		else
		{
			currentSlide = 1;
		}
		$("#slideshow_"+currentSlide).fadeIn();
	}
	else
	{
		clearInterval(slideshowInterval)
		slideshowInterval = setInterval("slideshow()",10000);
		if(action=="next")
		{
			$("#slideshow_"+currentSlide).fadeOut();
			if(currentSlide<totalSlides)
			{
				currentSlide++;
			}
			else
			{
				currentSlide = 1;
			}
			
			$("#slideshow_"+currentSlide).fadeIn();
		}
		else if(action=="previous")
		{
			$("#slideshow_"+currentSlide).fadeOut();
			if(currentSlide==1)
			{
				currentSlide = totalSlides;
			}
			else
			{
				currentSlide = currentSlide-1;
			  }
			$("#slideshow_"+currentSlide).fadeIn();
		}
	}
	
	//replace the text (it looks smooth beacuse it happens in the middle of the image change
	$(".title").html($("#slideshow_"+currentSlide).attr('title'));
	//$("#textHolder").removeAttr('onclick');
	$(".text").html($("#slideshow_"+currentSlide).attr('alt'));
	$(".text, .title").click(function() { window.location=$('#slideshow_'+currentSlide).attr('href'); });
}

//basket edit ajax requests
function updateProductList(basketID,categoryID)
{
	order = $('#sort').val();
	
	if(!isset(categoryID)) { categoryID="1"; }
	window.location="#"+categoryID;

	tempPrevURL = location.href;
	tempPrevCat = tempPrevURL.indexOf('#'); if(tempPrevCat==-1) { tempPrevCat="59"; }
	ProductList = tempPrevURL.substr((tempPrevCat+1),tempPrevURL.length);

	$('#current_product_list').html('<center><img src="images/ajax-loader.gif" /></center>');
	$.post('ajax/product_list.php',{ basketID:basketID, cat:ProductList, order:order } , function(data) { $('#current_product_list').html(data); });
}
function productToBasket(basketID,productID,requestFrom)
{
	if(requestFrom=="sidebar") 
	{ 
		ajaxAction="delete"; $('#product_holder_check_'+productID).removeAttr('checked'); 
	}
	else 
	{ 
		if($('#product_holder_check_'+productID).is(':checked')) 
		{ 
			ajaxAction="add";
		}
		else 
		{ 
			ajaxAction="delete"; 
		} 
	}
	$('#product_holder_'+productID).toggleClass('product_holder_selected');
	$('#current_basket_edit_products').html('<center><img src="images/ajax-loader.gif" /></center>');
	//basketsstatic is a global var set on the basket editor
	$.post('ajax/add_remove_product.php',{ action:ajaxAction, basketID:basketID, productID:productID, basketsstatic_id:basketsstatic_id } , function(data) { updateBasketItems(basketID); });
}
function deleteBasket(basketID)
{
	if(confirm("Remove this basket from your cart?"))
	{
		$.post('ajax/add_remove_product.php',{ action:"deleteBasket", basketID:basketID } , function(data) { window.location.reload(true); });
	}
}
function updateProductQuantity(basketID,productID,productQTY)
{
	$.post('ajax/add_remove_product.php',{ action:"updateProductQTY", basketID:basketID, productID:productID, productQTY:productQTY } , function(data) { updateBasketPrice(); });
	$.post('ajax/basket_items_cart_banner.php',{ basketID:basketID } , function(data) { $('#cart_banner_basket_'+basketID).html(data); });
}

function updateBasketCost(priceSum)
{
	$.post('ajax/add_remove_product.php',{  action:"updatePrice",priceSum:priceSum }, function(data) { total = Number(Number(data)+Number(priceSum)).toFixed(2); $('#basket_price').html("$"+total); });
}

function updateItemsCost(priceSum)
{
	total = Number(Number(priceSum)).toFixed(2); $('#itemTotal').html("item total: $"+total);
}

function updateWrapCost(priceSum)
{
	$.post('ajax/add_remove_product.php',{  action:"updateWrap",priceSum:priceSum }, function(data) { total = Number(Number(data)); 
	$('#wrapTotal').html("wrap price: $"+total); });
}

function updateBasketItems(basketID)
{
	//update the sidebar
	$.post('ajax/basket_items.php',{ basketID:basketID } , function(data) { $('#current_basket_edit_products').html(data); updateBasketPrice(); });
	//update the cart banner
	$.post('ajax/cart_banner.php',{ } , function(data) { $('#cart').html(data); });
}
function updateBasketPrice()
{
	price = 0; //set up our math
	productCount = $('#basketProductCount').val();
	for(i=0;i<=productCount;i++)
	{
		price += Number($('#price'+i).val())*Number($('#quantity'+i).val());
	}
	//add in the cost of the basket and wrap and display the value
	updateBasketCost(price)
	updateItemsCost(price)
	updateWrapCost(price)
}

//static basket category requests
function addToCart(basketID,action)
{
	$.post('ajax/add_static_basket_to_cart.php',{  basketID:basketID }, function(data) 
	{
		if(action=="customize")
		{
			window.location="basket_edit.php?id="+data;
		}
		else
		{
			updateCart();
		}
	});
}

//shipping
function calculateOrderTotal()
{
	sum = 0;
	for(i = 1; i<basketTotal.length;i++)
	{
		localSum = Number(basketTotal[i]) + Number(shippingTotal[i]);
	    $('#'+i+'totalPrice').html(localSum.toFixed(2));
		sum += Number(localSum);
	}
	$('#OrderTotalAmount').html(sum.toFixed(2));
	return sum.toFixed(2);
}
function calculateShipping(count)
{
	id = basketID[count];
	stateVar  = $('#'+count+'state').val();
	priceVar  = basketTotal[count];
	methodVar = $('#'+count+'method').val();
	
	$.post('ajax/shipping.php', 
		   { action:"calculate_shipping", 
		   	 state:stateVar, 
			 price:priceVar, 
			 method:methodVar 
		   }, 
		   function(data) {
			   shippingTotal[count] = Number(data);
			   $('#'+count+'shippingPrice').html(shippingTotal[count].toFixed(2));
			   
				//update any other baskets that have the same shipping address as the one currently being edited
				for(i = 2; i<basketTotal.length;i++) //start on the second basket (counter = 2) because the first one will always have an address manually typed in
				{
					newid = basketID[i];
					radio = $("input[name='"+i+"shippingRadio']:checked").val();
					//if the radio button that is checked is equal to the value that we initially updated in the start of this function then update this daisy chained value too
					if(Number(radio)==Number(id))
					{
						shippingTotal[i] = shippingTotal[count];
						$('#'+i+'shippingPrice').html(shippingTotal[i].toFixed(2));
					}
				}
				
				//update each basket total and the grand total
				calculateOrderTotal();
			   
		   }
	);
}
function changeShippingRadio(count)
{
	radio = $("input[name='"+count+"shippingRadio']:checked").val();
	if(radio!="new")
	{
		//show the shipping form for that basket
		$('#'+count+'newShippingForm').slideUp();

		//set shipping cost to the shipping cost of the basket selected with the radio button
		shippingTotal[count] = shippingTotal[radio];
		
		//update the shipping price of any other baskets that use this basket's shipping info
		calculateShipping(radio);

		//remove any form validation for the address on this basket
		$('#'+count+'address').removeClass('required').removeAttr('minlength');
		$('#'+count+'city').removeClass('required').removeAttr('minlength');
		$('#'+count+'state').removeClass('required');
		$('#'+count+'zip').removeClass('required digits').removeAttr('minlength');
	}
	else
	{
		//show the shipping form for that basket
		$('#'+count+'newShippingForm').slideDown();
		
		//reset any shipping cost to zero until the address is entered and it calculates shipping
		shippingTotal[count] = 0;
		
		//update the shipping price of any other baskets that use this basket's shipping info
		calculateShipping(count);
		
		//add form validation for the address on this basket because it is a unique address entered by the user
		$('#'+count+'address').addClass('required').attr('minlength','2');
		$('#'+count+'city').addClass('required').attr('minlength','2');
		$('#'+count+'state').addClass('required');
		$('#'+count+'zip').addClass('required digits').attr('minlength','5');
	}
	//update each basket total and the grand total
	calculateOrderTotal();
}

//show static baskets
function sortBaskets(orderBy)
{
	//get the direction asc or desc to sort in
	direction = orderBy.substr(orderBy.indexOf('|')+1,orderBy.length);
	//what are we sorting by?
	orderBy = orderBy.substr(0,orderBy.indexOf('|'));
	
	//thanks to "one more take" - http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/
	var mylist = $('#baskets');
	var listitems = mylist.children('li').get();
	listitems.sort(function(a, b) {
		if(orderBy=="name")
		{
			var compA = $(a).attr(orderBy).toUpperCase();
			var compB = $(b).attr(orderBy).toUpperCase();
		}
		else
		{
			var compA = Number($(a).attr(orderBy));
			var compB = Number($(b).attr(orderBy));
		}
		
		if(direction=="asc")
		{
			return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
		}
		else
		{
			return (compA > compB) ? 1 : (compA < compB) ? 1 : 0;
		}
	})
	$.each(listitems, function(idx, itm) { mylist.append(itm); });
}
function refresh_page()
{
	location.reload(true);	
}
function incQuan(shopID,basketID, bcount)
{
	if(confirm("Increase the quantity of this basket?" + '\n\n' + "Please realize that increasing the quantity will call a page refresh and you may lose any 'Personalization' or 'Send Basket To' information you have filled out." + '\n\n' + "For help with sending multiple baskets cancel this window and click 'Send to more than one person' beneath the Increase Quantity icon."))
	{
		$.post('ajax/increase_quantity.php',{ shopID:shopID, basketID:basketID, bcount:bcount });
		setTimeout('refresh_page()', 500);
	}
}


//write more, do less - andrew sauder style - helpful for the PHP nuts
function isset(variable)
{
	if(typeof(variable) != "undefined")
	{
		return true;
	}
	else
	{
		return false;
	}
}
