//also know as the 'main' funciton if this was C, or C++, or Java, or .......
$(document).ready(
	function(){
		
		/*$("#checkGCBalance").click(function(){
				popChat();
				return false;
			});*/

	//navigation highlighting
		$('a.nav').hover(
			function(){ $(this).removeClass('nav').addClass('navOver');
						$(this).parent().removeClass('nav').addClass('navOver');	},
			function(){ $(this).removeClass('navOver').addClass('nav');	
						$(this).parent().removeClass('navOver').addClass('nav');	}
		);
		
		
		//get those modals going
			var modal = $('#dialog');

			modal.dialog({
				modal: true, 	//disables the page behind it
				overlay: {
					opacity: 0.5,
					background: "black"
				//	backgroundImage: "url('imgs/tmnt.jpg')"  //turtle power
				},
				draggable: false,  //stay in the middle
				resizable: false,  //stay the same sime
				autoOpen: false, //needs to wait to be clicked
				close: function(){
					//reset values when close
					$('.ui-dialog-content').css({width: 0, height: 0});
					$('.dialogWindow').css({left: 'auto', right: 'auto',opacity:0});
				},
				open: openModal
			});//end of modal definition
		
		//modal link binding
		$('.modalLink').attr("target", "_blank").click(function(){
			var image = $(this).attr('href');			
			$('.ui-dialog-content').html('<img id="modalImage" src="'+image+'"/>');				
			modal.dialog("open");				
			return false;										
		});

		var location = window.document.location.toString();
		//show them what the popup is going to look like

		if(location.search("mailOrder") != -1)
		{
			mailOrderInit();
		}else if(location.match("deals.php"))
		{
				$('.cityDealPicker').click(function(){
				
					var id = $(this).attr('id');

					$('.cityDealPicker').remove();
					
					if(id == 'lincoln'){
						$('.lincoln').show();
					}else{
						$('.omaha').show();					
					}
					
					return false;
				});
		
		}else if(location.match("index.php") || location == "http://www.valentinos.com/"){

		
			if(readCookie('hasSeen')!='true')
			{
				//they don't have to see the popup for the rest of the day
				createCookie('hasSeen', 'true');
				modal.dialog("open");
				
				openModalNoLoad();//remove after 
			
			}
		}
		else if(location.match('giftCards.php'))
		{
			//trigger the toggles to check for validity
			$('.toggle').blur(function(){
				cardFormActivate();
			});
			
			//reset button resets form and activates fields
			$('#cardFormClear').click(
				function(){
					document.forms[0].reset();
					$('.toggle').removeAttr('disabled');
					$('#cardFormSend').attr('disabled', "disabled");
					
					
			});
		}
		
		else if(location.match('contact.php'))
		{
			//bind text fields
			$('input:not(:radio)').blur(function(){
				validateContact($(this));
			});
			
			//bind radios
			$(":radio").click(function(){
				validateContact($(this));				
			});
						
			//disable submission button
			$('#conFormSubBut').attr('disabled', "disabled")
			.css('opacity', 0.25)
			.css('background-color', '#AAAAAA');
			
			//clear button functionallity
			$('#conFormClearBut').click(function(){
				clearContactForm();
			});
		}
		
		else if(location.match('locations.php'))
		{			
			
			//see if you should prox load right from load
			if($('#zipCode').val() != "")
			{
				proxLoader();
			}
			
			//show them what they selected on the index page
			var firstTab = $('#firstTab').val();
			
			//if they didn't select anything, show them nebrasak
			if(firstTab == "")
			{
				firstTab = "NE";
			}			
			
			$('.tabPane:not(#'+firstTab+')').hide();
						
			typeLoader();	//show an hide at load time. reuse code 

			//bind the nebraska city links to hide/show content without reload
			$('#nebraskaCityLinks>a').click(
				//show hide cities and litalsdkjflkasj
				function(){
					neCityHideShow(this);					
					return false;
				}
			);
		}
		//quality rotator not on the menu page
		if(!location.match("menu.php")){
			qualityRotator();
		}else if(location.match('menu.php'))
		{
			//this is what the quality rotator says on the menu page
			$('#rotatorTarget').html('Online Ordering Coming Soon in Lincoln, NE!');
			
			//pizza accordion
			$('#acCont').accordion({
				alwaysOpen: false,
				autoHeight: false,
				header:     "h2.acToggle"				
			});
			
			var category = $('#category').val();
			
			//only if a category is selected, display the carry out menu
			if(category != '')
			{
				initializeMenu(category);
			}				

			//what does the use want to see (selected on main menu)
			var openTab =$('#firstTab').val();
			//if they don't care, give them the first tab in the visible menu pane
			if(openTab != ""){

				$('.tabPane:not(#'+openTab+')').hide(); //hide other tabs
				$('#'+openTab).show();
			}else{
				var menuName = $('.menu:visible').attr('id');
				
				toggleTabs($('#'+menuName+' a.tabs:first'));
			}
							
			//switch tabs
			$('.tabs').click(function(){
				toggleTabs($(this));
				return false;
			});
			
			//radio buttons to change the menu
			$('.menu_switch').click(function(){
				toggleMenu($(this));
			});
			
		}
		
		
	
			//switch tabs
			$('.locTabs').click(function(){
				toggleTabs($(this));
				return false;
			});
			
			
		
		
}); 

//tab controller
function toggleTabs(source){
	var tabName = source.attr('href');//get id from source 
	$('.tabPane:visible').hide();
	$('#'+tabName).show();
}

var w;
// this is for the deals page, print those cupons
function printImage (img) {
  img = img.src ? img.src : img;
  if (w && !w.closed)
  {
    w.close();
  }
  w = open ('', 'imagePrint', 
       'menubar=1,locationbar=0,statusbar=0,resizable=1,scrollbars=1,width=400,height=400');
  var html = '';
  html += '<HTML><BODY ONLOAD="if (window.print) window.print(); '+ 'setTimeout(\'window.close()\', 1200);">';
  html += '<IMG SRC="' + img + '">';
  html += '<\/BODY><\/HTML>';
  w.document.open();
  w.document.write(html);
  w.document.close();
}



//this changes that neat little information thing at the to 
function qualityRotator()
{
//what is going to be displayed
	var qualArr = new Array("The freshest and finest pizza ingredients available, piled high for a plentiful taste in every bite.","Pizza dough baked to 	perfection - the envy of the pizza industry - tender, light texture uniformly visible.","Pizza sauce so thick Valentino's has to spread it with a spoon, using pear shaped tomatoes in <br />pur&#232;e, a secret collection of traditional Italian spices, and slow-cooked for over two hours.","Award-Winning quality!");
	
	//let people know what day it is 
	var i = -1;
			
	//do it every 10 seconds
	$.periodic(function(){
		if(i>=0)
		{
			$('#rotatorTarget').html(qualArr[i])
			.css('background-color', 'yellow')
			.animate({backgroundColor: '#F4F4EC'}, 1000);
		}
		
		i = (i+1)%4; //don't go overboard
		return true;
		
	}, {frequency: 10});
	 
}

function openModal(){
	$("div.ui-widget-overlay").css({
		opacity: 0.5
	});
					//show ajax loading dialog
	$('#centBox').show();
	//alert($('#modalImage').height());
				
	$("#modalImage").load(function() {	//wait for image to finish loading to resize and center the dialog
						
		$('.ui-resizable-handle').remove();
						
						//get height
		var height = $('#modalImage').height();
		var width  = $('#modalImage').width();
		var winWidth = $(window).width();
		var winHeight = $(window).height();						
					
		//how far away are the sites, don't worry about scroll 
		//valentinos isn't long enough
		var heightMargin = winHeight/2 - height/2;
		var widthMargin  = winWidth/2  - width/2;
				
		//stay on the screen
		if(heightMargin < 0)
		{
			heightMargin = 0;
		}				
		//stay on the scree
		if(widthMargin < 0)
		{
			widthMargin = 0;
		}	
						
		//set width and height "dynamically"	
		$('.ui-dialog-content, #dialog').css({width: width, height: height});
		$('#dialog').closest(".ui-dialog").css({width: width+30, height: height+30});
		//let it show up, not that it looks ok
			
		$('#dialog').css({top: heightMargin, left: widthMargin}).animate({opacity: 1}, 'fast');
		$("#dialog").closest(".ui-dialog").css({top: heightMargin, left: widthMargin});
		$('#centBox').hide();
										
	});			
}//edn of 	open	

function openModalNoLoad(){
	$("div.ui-widget-overlay").css({
		opacity: 0.5
	});
	$('.ui-resizable-handle').remove();
	
	//get height
	var width = 475;
	var height  = 250;

	var winWidth = $(window).width();
	var winHeight = $(window).height();						
	
	//how far away are the sites, don't worry about scroll 
	//valentinos isn't long enough
	var heightMargin = winHeight/2 - height/2;
	var widthMargin  = winWidth/2  - width/2;
	
	//stay on the screen
	if(heightMargin < 0)
	{
	heightMargin = 0;
	}				
	//stay on the scree
	if(widthMargin < 0)
	{
		widthMargin = 0;
	}
									
	//set width and height "dynamically"	
	$('.ui-dialog-content, #dialog').css({width: width, height: height});
	$('#dialog').closest(".ui-dialog").css({width: width+30, height: height+30});
	//let it show up, not that it looks ok
			
	$('#dialog').css({top: heightMargin, left: widthMargin}).animate({opacity: 1}, 'fast');
	$("#dialog").closest(".ui-dialog").css({top: heightMargin, left: widthMargin});
	$('#centBox').hide();
	
}

/***************
Menu.php Functions
************/
//loads the menu to be display thanks to the pano links
function initializeMenu(category)
{
	//translate to radio name
	switch(category)
	{
		case 'co':
			category = 'Carry-outDelivery';
			break;
					
		case 'bu':
			category = 'Buffet';
			break;
					
		case 'ca':
			category = 'CateringTraditional';
			break;
				
		} 
			
		//select the radio
		$(':radio[value='+category+']').attr('checked', true);
		toggleMenu($(':radio[value='+category+']'));  	//trigger the radio button (something is up with the trigger command) can't do two in one call
}

//radio menu controller
function toggleMenu(source)
{
	var menuName = source.val();
	$('.menu:visible').hide();
	$('#'+menuName).show();			
	toggleTabs($('#'+menuName+' a.tabs:first')); 	//trigger the first tab button in this menu
	
}

/****************
GiftCard.php Functions
***************/

//this is for the giftcard page it activates and deactivates the form
function cardFormToggle()
{
	var yesno = $(':radio:checked').val();
	
	if(yesno == 'yes')
	{
		$('.toggle').attr('disabled', "disabled");
	}else
	{
		$('.toggle').removeAttr('disabled');	
	}
	
	cardFormActivate();
	
}

//see if you should allow them to purchase gift cards
function cardFormActivate()
{
	var cards25 = $('#num25').val();
	var cards50 = $('#num50').val();
	
	var quantity25 = Number(cards25);
	var quantity50 = Number(cards50);
	
	if(cards25 != 0)
	{
		$("#item_name_1").removeAttr('disabled').val("25_Gift_Card");
		$("#amount_1").removeAttr('disabled').val(25);
		$("#quantity_1").removeAttr('disabled').val(cards25);
	}else{
		$("#item_name_1").attr('disabled', "disabled");
		$("#amount_1").attr('disabled', "disabled");
		$("#quantity_1").attr('disabled', "disabled");
	}
	
	if(cards50 != 0 && cards25 != 0){
		$("#item_name_2").removeAttr('disabled');
		$("#amount_2").removeAttr('disabled');
		$("#quantity_2").removeAttr('disabled').val(cards50);
	}else if(cards50 !=0 ){
		$("#item_name_1").removeAttr('disabled').val("50_Gift_Card");
		$("#amount_1").removeAttr('disabled').val(50);
		$("#quantity_1").removeAttr('disabled').val(cards50);
		
		$("#item_name_2").attr('disabled', "disabled");
		$("#amount_2").attr('disabled', "disabled");
		$("#quantity_2").attr('disabled', "disabled");		
	}else{
		$("#item_name_2").attr('disabled', "disabled");
		$("#amount_2").attr('disabled', "disabled");
		$("#quantity_2").attr('disabled', "disabled");
	}
	
	var validate = true;
	
	//make surea ll the fields have something in them
	jQuery.each($('.toggle:enabled:not[id!=address2]'),
		function(){
			if($(this).val() == '')
			{
				validate = false;
			}		
		}
	
	);

	//if a real person is ordering more than 0 cards, let them
	if(cards25+cards50 != '00'&& validate)
	{
		$('#cardFormSend').removeAttr('disabled');			
	}else{
		$('#cardFormSend').attr('disabled', "disabled");
	}
}


/****************
Locations.php Functions
***************/

//the checkboxes on the location page just have to do something in real time,
// time to make them show and hide stuff.
function typeLoader()
{
	//make an or regular ex of the checkboxes
	var target = $(':checkbox:checked');
	var regex = "";
	jQuery.each(target,
		function(){

			regex += "|" + $(this).val();
				
		}
	
	);
	
	//this little thing checks if its not empty
	var isRegular = true;
	

	if(regex != '')
	{
		//format this betch
		regex = regex.substring(1);//get rid of that first pipe
		regex = "("+regex+")+";	//one or more of those
		var regularEx = RegExp(regex);
	}else{
		isRegular = false; //its empty
	}	
	

	//now loop through the rows
	var rows = $('tr');

	jQuery.each(rows, 
		function()
		{
			var dishRow = $(this);
			var value = dishRow.attr('class');
						
			//if it matches any of the checkboxes
			if(isRegular && value.match(regularEx))
			{
				dishRow.show();
			}else
			{
				dishRow.hide();
			}
		}
	);
		
}

//This is the prox loader for the locations page
//most of it jacked from teh old stuff
function proxLoader() {
	var zip = $('#zipCode').val();
	var url = 'jax/proxJax.php';
	var respUpdate = $('#searchBox');
	var lat = 0;
	var lon = 0;
	geoCode = new GClientGeocoder();		//have google do teh hard stuff
		geoCode.getLatLng(zip,
			function(point) {
				if (point) {
					lat = point.lat();
					lon = point.lng();
					
					$('#lat').val(lat);
					$('#lon').val(lon);
					var zipFormSer = $('#zipForm').serialize();

					$.ajax({		//get that data 
						type: 'POST',
						url: url,
						data: zipFormSer+'&random='+Math.random(),
						beforeSend: function(data){
							$('.locTabs').hide();
							$('#nebraskaCityLinks').hide();
							respUpdate.html("<div style=\"height:320px\"><h2>Loading...</h2></div>");	//tell the client whats up
							},
						success: function(data){
							respUpdate.html(data);
					
							//bind the new modal		
							$('.modalLink').click(function(){
		
								var image = $(this).attr('href');
									
								$('.ui-dialog-content').html('<img id="modalImage" src="'+image+'"/>');

								$('#dialog').dialog("open");
								return false;
							});	

						//this binding has to be here
						//this will allow you to see al the locations if you want
						$('#showAllLoc').click(
								function(){
								$('#showAllLoc').hide();
								$('tr').show(); //these are the only ts tags on the page hopefully.
								return false; //break that link
							});
						
						}	//put it in the slot
					
					});
				}
				else {
					var respTxt = 'Could not get coordinates';
					$(respUpdate).update(respTxt);
				}
			}
		);		
		
}

//this function is for the locations page, shows and hides nebraska citys dynamically instead of with page relod
function neCityHideShow(neLink){
	var city = $(neLink).attr('href');

	switch(city)
	{
		case "All":
			$(".NEClass").show();
			break;
		case "Lincoln":
			$(".NEClass:not(.Lincoln)").hide();
			$(".Lincoln").show();
			break;
		case "Omaha":
			$(".NEClass:not(.Omaha)").hide();
			$(".Omaha").show();
			break;
		case "Other":
			$(".NEClass").show();
			$(".Lincoln").hide();
			$(".Omaha").hide();
			break;
	
	}
}


/*
	Contact.php 
*/

//validation of contact form, treats input as jquery objects
function validateContact(input)
{
	//radio
	if(input.attr('type') == 'radio')
	{
		$('#validRadio').html('Confirmed').css('color', 'green');
	}else
	{
		var className = input.attr('class');
		var value = input.attr('value');
		var id 	  = input.attr('id');
		var regEx;
				
		//change the regenx based on what your looking for
		switch(className)
		{
			case 'name':
				regEx = /^[a-zA-Z\']+$/;
			break;
			
			case 'email':
				regEx = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*@[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*\.[a-zA-Z\-_]{2,4}$/;
			break;

			case 'phone':
				regEx = /^\(?[0-9]{3}\)?[\- \.]?[0-9]{3}[\- \.]?[0-9]{4}$/;
			break;
		}
		
		//regulize that expression and cheer
		if(value.match(regEx)){
			$('#'+id+'Valid').html('Confirmed').css('color', 'green');
		}else{
			$('#'+id+'Valid').html('Invalid').css('color', 'red');		
		}
	}
	
	contactFormActivate();
	
}

//clear contact form
function clearContactForm()
{
	//clear form
	document.forms[0].reset();
	
	//reset valid box values
	$('.validBox').html('Required').css('color', 'green');
	
	//disable submission button
	$('#conFormSubBut').attr('disabled', "disabled")
	.css('opacity', 0.25)
	.css('background-color', '#AAAAAA');

}

//activate the submit button or dont'
function contactFormActivate()
{
	var validated = true;
	
	//see if all the input fields are confirmed
	jQuery.each($('.validBox'), function(){
		if($(this).html() != 'Confirmed')
		{
			validated = false;
		}
	});
			
	if(validated)
	{
		//enable submission button
		$('#conFormSubBut').removeAttr('disabled')
		.css('opacity', 1)
		.css('background-color', '#FFFFFF');
	}else
	{
		//disable submission button
		$('#conFormSubBut').attr('disabled', "disabled")
		.css('opacity', 0.25)
		.css('background-color', '#AAAAAA');
	}
	
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else{
		var expires = "";
	} 
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ')
		{
			 c = c.substring(1,c.length);
		}
		if (c.indexOf(nameEQ) == 0){
		 return c.substring(nameEQ.length,c.length);
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/***************
mailOrder
***************/

function mailOrderInit()
{
	//style the heart shaped pizza
	var par = $(".Heart_Shaped_Pizza:first").parent();
	par.css({backgroundColor:"red",padding:"0 10px 10px 10px",color:"white"});
	$(".Heart_Shaped_Pizza:first").siblings("h4").css({color:"white"});
	
	//style the special
	var html = 	$('#Seafest_Pizza').parent("td").html();
	$('#Seafest_Pizza').parent("td").html("<div id=\"featuredItems\">"+html+"</div>");

	$('.orderOptions').focus(function(){
		$(this).select();
	});

	//triggers a lot of things on the page to recalculate
	$('.orderOptions').keyup(function(){
		calculateItemCost();

		$('#shippingOptions').html('<option id="defaultOption">Please Enter your state and zip code</option>');
		$('#grandTotal').html("$0.00");
		$('#shippingCost').html("$0.00");
		$('#mailOrderSubmit').attr('disabled', 'disabled');
		$("#shipping_state").triggerHandler('change');
		//$("#shipping_zip:visible").triggerHandler('keyup');
	});
	$('.mailOrderInput').blur(function(){
		activateMailForm();
	});
	
	$('#shipping_state').change(function(){
		calculateItemCost();
		
		//reset shipping values
		$('#grandTotal').html("$0.00");
		$('#shippingCost').html("$0.00");
		$('#shippingOptions').attr('disabled', 'disabled');
		$('#mailOrderSubmit').attr('disabled', 'disabled');
		//and the shipping picker
		$("#shippingOptions").html('<option id="defaultOption">Enter your state</option>');
		
		//there is an IE6/8 inconsistency they process select boxes differently
		try{
			state = $("#shipping_state").val();

		}catch(e){
			state = $("#shipping_state").children("option[selected=selected]").val();		
		}
				
		//only calculate shipping if the zip and state and price are good
		if($('#totalPrice').html() != "$0.00" && state !== "" && $('#orderFormError').html() === "")
		{
			$('#shippingOptions').removeAttr('disabled');
			calculateShipping(68503, "shipping");
		}else if($('#orderFormError').html() !== ""){
			$("#defaultOption").html("Invalid Number of items selected");
		}
	
	});

	$("#shippingOptions").change(function(){
	
		//add to custom field
		$(".personalMessageInput:first").triggerHandler("blur");
		
		try{
			var shipping = Number($(this).val());	
		}catch(e){
			var shipping = Number($(this).children("option[selected=selected]").val());	
		}
		
		$('#shippingCost').html("$"+shipping.toFixed(2));//update shipping cost field
		$('#costOfShipping').val(shipping);
		
		var items = Number($('#costOfItems').val());
		$("#grandTotal").html("$"+(items+shipping).toFixed(2));
		
		var shippingMethod = $("#shippingOptions > option:selected").html();
		shippingMethod = shippingMethod.split("(");
		shippingMethod = shippingMethod[0];
		
		$("#shippingMethod").val(shippingMethod);
		
		//papal shipping
		$('#shipping_1').val(shipping.toFixed(2));
		
		activateMailForm();		
	});
	
	$('#reset').click(function(){
		$("#special_300").attr("checked", false);
		$("#pizzaList300").hide();
		
		$(".mailOrderInput").val("");
		$("#address2").val("");
		$(".orderOptions").val("0");
		$(".orderOptions:last").triggerHandler('keyup');
		$('#zip').triggerHandler('blur');
		
		if($("#personalMessage").html() != "Click To Add Personal Message"){
			$("#personalMessage").triggerHandler('click');
		}
		
		if($("#addShipping").html() == "Remove Shipping Address"){
			$("#addShipping").triggerHandler('click');
		}
		
		$(".personalMessageInput").val("");
		
	});
	
		//personal message form toggle
	$("#personalMessage").click(function(){
		//activate the fields and the input to send it to paypay
		if($(this).html() == "Click To Add Personal Message"){
			$(".personalMessageInput").slideDown();
			$(this).html("Remove Personal Message");
		//deactive the fields and the input ..
		}else{
			$(".personalMessageInput").slideUp().val("");
			$('#to').triggerHandler('blur');
			$(this).html("Click To Add Personal Message");
		}
		
		return false;
	});
	

	$(".personalMessageInput, .mailOrderInput, .phone").blur(function(){

		var early = false;
		if($("#earlyDeliver:checked").val()){
			early = true;
		}
		//fill in the input to send to paypal
		var shipping = $("#shippingOptions > option:selected").html();
		shipping = shipping.split("(");
		shipping = shipping[0];		
		var custom = $("#to").val()+";"+$("#from").val()+";"+$("#message").val()+";";
		custom += $("#first_name").val()+";";
		custom += $("#last_name").val()+";";
		custom += " ;";
		custom += " ;";
		custom += " ;";

		try{
			custom += $("#shipping_state").val()+";";	
		}catch(e){
			custom += $("#shipping_state").children(":selected").val()+";";	
		}
		custom += $("#zip").val()+";";
		custom += $("#orderID").val()+";";
		custom += $("#night_phone_a").val()+";";
		custom += $("#night_phone_b").val()+";";
		custom += $("#night_phone_c").val()+";"+shipping+";"+early+";";

		try{
			custom += $("#shipping_state").val()+";";	
		}catch(e){
			custom += $("#shipping_state").children(":selected").val()+";";	
		}

		custom += $("#shipping_state").is(":visible");

		$("#custom").val(custom);
	});

	$('#earlyDeliver').click(function(){
		$('.phone').triggerHandler('blur');
	});
	
	//adding shipping address
	$("#addShipping").click(function(){
		if($(".shipping").css('display') == 'none'){
			$('.shipping').slideDown(500, function(){
						$("#zip").triggerHandler('keyup');
					});
			$(this).html("Remove Shipping Address");		
		}else{
			$('.shipping').slideUp(500, function(){
						$("#zip").triggerHandler('keyup');
					}).val("");//reset fields
			$(this).html("Click here if you  are shipping to a different Address.");
		}
		$('.mailOrderInput').triggerHandler('blur'); //activate or deactivate the form
		
		return false;
	});

	activateMailForm();

}

function returnFalse(){
	return false;	
}

function activateMailForm(){
	
	//is true if there is a total price, otherwise its false dude.
	var activate = true;
	var current;
	var id;
	var validData; //stores result of the regex map 
	
	$(".mailOrderInput:visible").each(function(){

		current = $(this);		
		id = current.attr('id');
		
		var vall;
		
		try{
			vall = current.val();
		}catch(e){
			try{
				vall = current.children("option[selected=selected]").val();					
			}catch(e){
	//			alert("error line 995");	
			}
		}
		
		
		
		if(current.hasClass('numeric'))
		{
			validData = vall.match(/^[0-9]+$/);
		}else if(current.hasClass('email')){
			validData = vall.match(/^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*@[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*\.[a-zA-Z\-_]{2,4}$/);
		}else{
			try{
				validData = vall.match(/[a-zA-Z0-9]+/);	
			}catch(e){
//				alert(id+" "+vall);	
			}
		}
		
		//mark invalid input and unmark valid ones		
		if(!validData)
		{
			current.parent().prev().css('color','red');
			activate = false;
		}else{
			current.parent().prev().css('color','');
		}
	});
	
		
	//if everything is ok, we should allow a submission
	if(activate && $("#orderFormError").html() == "" && Number($("#costOfShipping").val()) > 0 && Number($("#costOfItems").val()) > 0){
		$('#mailOrderSubmit').removeAttr('disabled');
		$('#cardForm').unbind('submit', returnFalse);		
	}else{
		$('#mailOrderSubmit').attr('disabled', 'disabled');
		$('#cardForm').submit(returnFalse);		
	}
	
}


function calculateItemCost(){
	var error = ""; //will be thrown it it doesn't equal ""
	var totalPrice = 0;
	var quantity, price;
	var pizzas = Number(0);
	var lasagnes = Number(0);
	var sauces = Number(0);
	var heartPizzas = Number(0);
	var item, id;
	var before = false;//see if we need to add line breaks in the error return
	var itemHtml = "";
	var count = Number(0);

	//loop through all teh items geting the total price and other valueable info
	$('.orderOptions:not(.pizza300)').each(function(){
		
		item = $(this);
		
		quantity = Number(item.val());

		if(isNaN(quantity)){
			error = "Please enter numeric quantities only.";
			before = true;
		}

		if(quantity !== "" && quantity !== 0)
		{

			count ++;

			id  = item.attr('id');
			price = $("."+id+":first").val();//and price
			number = $("."+id+":last").val();//and itemNumebr
			id = id.replace("_", " ");
			//loop through and create these inputs for the paypal
			itemHtml += '<input type="hidden" id="item_name_'+count+'" name="item_name_'+count+'" value="'+id+'" />';
            itemHtml += '<input type="hidden" id="amount_'+count+'" name="amount_'+count+'" value="'+price+'"/>';
            itemHtml += '<input type="hidden" id="quantity_'+count+'" name="quantity_'+count+'" value="'+quantity+'"/>';
            itemHtml += '<input type="hidden" id="item_number_'+count+'" name="item_number_'+count+'" value="'+number+'"/>';
			
			//count up all the items

			if(item.hasClass("Pizza") || item.hasClass("Summer_Pizza") || item.hasClass("Dessert_Pizza") || item.hasClass("Holiday_Pizza") || item.hasClass("Regular_Shaped_Pizza")){
				pizzas += quantity;
			}else if(item.hasClass("Spaghetti_Sauce"))
			{
				sauces += quantity;
			}else if(item.hasClass("Lasagne"))
			{
				lasagnes += quantity;
			}else if(item.hasClass("Heart_Shaped_Pizza")){
				heartPizzas += quantity;
			}
			
			totalPrice += quantity*price;
		}
		
	});
	
	$('#itemInfo').html(itemHtml);
	
	//next test to see if the right number of items has been ordered
	$('#numPizzas').val(pizzas);
	$('#numLasagnes').val(lasagnes);
	$('#numSauces').val(sauces);
	$('#numHeartPizzas').val(heartPizzas);
	
	var totalPizzas = pizzas+heartPizzas;
	
	if(totalPizzas == 1){
		if(before){
				error += "<br/>";
		}
		error = "Must order two or more Pizzas.";
		before = true;
	}
	if(lasagnes < 0 || lasagnes%2 == 1){
		if(before){
			error += "<br/>";
		}
				
		error += "<br/>Lasagne may only be ordered in multiples of two.";
		before = true;
	}
	
	if(sauces > 0 && sauces < 4)
	{
	 	if(before){
			error += "<br/>";
		}
		
		error += "Must order four or more bottles of Spaghetti Sauce.";
		before = true;
	}
	
	
	$("#orderFormError").html(error);
		
	$("#costOfItems").val(totalPrice);	
	$("#totalPrice").html("$"+totalPrice.toFixed(2));
}

function calculateShipping(zip, mode){

var state;
		

		try{
			state = $("#shipping_state").val();
		}catch(e){
			state = $("#shipping_state").children("option[selected=selected]").val();
		}

		var options;
		
		var smallBoxes = 0; //boxes contain 2-4 Items
		var medBoxes = 0; //boxes containing 5-6 items
		var largeBoxes = 0; //boxes containing 7-8 items
		var shippingCost = 0;
		
		var largeCost, medCost, smallCost; //cost of shipping large med and small boxes
		
		var pizzas = Number($("#numPizzas").val());
		var heartPizzas = Number($("#numHeartPizzas").val());		
		var lasagnes = Number($("#numLasagnes").val()); 
		var sauces = Number($("#numSauces").val());
		

		//throw in the extra heart pizzas with regular pizzas
		// var leftOverPizzas = pizzas%7;
		// var leftOverLasagne = lasagnes%7;
		// var leftOverHeartPizzas = heartPizzas%4;		
		// var leftOverHeartPizzas;
		// largeBoxes = (pizzas-leftOverPizzas)/7;
		// largeBoxes += (lasagnes-leftOverLasagne)/6;
		// smallBoxes += (heartPizzas - leftOverHeartPizzas)/4;
		
		//get rid of heart pizzas first (sick pizzas and lasagnes in with them where they fit
		while(heartPizzas >= 4){
			if(lasagnes > 0){
				lasagnes -= 2;
				largeBoxes ++;
			}else{
				medBoxes ++;
			}
			heartPizzas -= 4;
		}
		
		switch(heartPizzas){
			case 3:
					if(pizzas > 0){
						if(lasagnes > 0){
							largeBoxes++;
							lasagnes -= 2;
							pizzas -= 1;
							heartPizzas -= 3;
						}
						else{
							medBoxes++;
							pizzas -= 1;
							heartPizzas -= 3;
						}
					}
					else if(lasagnes > 0){
						medBoxes++;					// 3 heart pizzas and 2 lasagnes in a medium box??
						lasagnes -= 2;
						heartPizzas -= 3;
					}
					else {
						smallBoxes++;					// 3 heart pizzas get a small box?? ln 1199, 1238
						heartPizzas -= 3;		
					}
					break;
			case 2:
					if(pizzas > 0){				// can fit 2 more pizzas in
						if(lasagnes > 0){
							largeBoxes++;
							lasagnes -= 2;
							pizzas -= 2;
							heartPizzas -= 2;
						}
						else{
							if(pizzas > 1){
								medBoxes++;
								pizzas -= 2 ;		
								heartPizzas -= 2;
							}
							else{
								smallBoxes++;		// 2 hearts and 1 pizza in a small box??
								pizzas -= 1;
								heartPizzas -= 2;
							}
							
						}
					}
					else {
						if(lasagnes >= 4){
							largeBoxes++;
							lasagnes -= 4;
							heartPizzas -= 2;
						}
						else if(lasagnes > 0){
							medBoxes++;
							lasagnes -= 2;
							heartPizzas -= 2;
						}
						else{
							smallBoxes++;
							heartPizzas -= 2;		// 2 heart pizzas in small box??
						}
					}
					break;
			case 1:
					if(pizzas >= 3){
						if(lasagnes > 0){
							largeBoxes++;
							lasagnes -= 2;
							pizzas -= 3;
							heartPizzas--;
						}
						else{
							medBoxes++;
							pizzas -= 3;
							heartPizzas--;
						}
					}
					else if (pizzas ===  2){
						if(lasagnes >= 2){
							medBoxes++;
							pizzas -= 2;
							lasagnes -= 2;
							heartPizzas--;
						}
						else {
							smallBoxes++;
							pizzas -= 2;
							heartPizzas--;
						}
					}
					else if (pizzas === 1){
						if(lasagnes >= 4){
							largeBoxes++;
							pizzas--;
							heartPizzas--;
							lasagnes -= 4;
						}
						else if (lasagnes >= 2){
							medBoxes++;
							pizzas--;
							heartPizzas--;
							lasagnes -= 2;
						}
						else{
							smallBoxes++;
							pizzas--;
							heartPizzas--;
						}
					}
						
						//smallBoxes++;				// 1 heart and 2 pizzas in a small box?
						//pizzas -= 2;
						//heartPizzas--;
					else{
						if(lasagnes >= 4){
							largeBoxes++;
							lasagnes -= 4;
							heartPizzas--;
						}
						else if (lasagnes > 0){
							smallBoxes++;
							lasagnes -= 2;
							heartPizzas--;
						}
						else{
							smallBoxes++;			// stick leftover heart in a box or make leftOverHeartPizzas = 1 ??
							heartPizzas--;
						}
					}
					break;
				
		}
		
		// after heart pizzas are gone,figure left over pizzas and lasagnes
		if (pizzas < 0){
			pizzas = 0;
		}
		if (lasagnes < 0){
			lasagnes = 0;
		}
		var leftOverPizzas = pizzas%7;
		var leftOverLasagne = lasagnes%6;
		
		// fill full boxes
		largeBoxes += (pizzas-leftOverPizzas)/7;
		largeBoxes += (lasagnes-leftOverLasagne)/6;
		
		switch(leftOverPizzas){
			case 6:
				largeBoxes++;
				break;
			case 5:
				if (leftOverLasagne > 0){
					largeBoxes++;
					leftOverLasagne -= 2;
					leftOverPizzas -= 5;
				}
				else {
					medBoxes++;
					leftOverPizzas -= 5;
				}
				break;
			case 4:
				if (leftOverLasagne > 0){
					largeBoxes++;
					leftOverLasagne -= 2;
					leftOverPizzas -= 4;
				}
				else {
					medBoxes++;
					leftOverPizzas -= 4;
				}
				break;
			case 3:
				if(leftOverLasagne >= 4){
					largeBoxes++;
					leftOverLasagne -= 4;
					leftOverPizzas -= 3;
				}
				else if (leftOverLasagne > 0){
					medBoxes++;
					leftOverLasagne -= 2;
					leftOverPizzas -= 3;
				}
				else {
					smallBoxes++;
					leftOverPizzas -= 3;
				}
				break;
			case 2:
				if(leftOverLasagne >= 4){
					largeBoxes++;
					leftOverLasagne -= 4;
					leftOverPizzas -= 2;
				}
				else if (leftOverLasagne > 0){
					medBoxes++;
					leftOverLasagne -= 2;
					leftOverPizzas -= 2;
				}
				else{
					smallBoxes++;
					leftOverPizzas -= 2;
				}
				break;
			case 1:
				if(leftOverLasagne >= 6){
					largeBoxes++;
					leftOverLasagne -= 6;
					leftOverPizzas -= 1;
				}
				else if (leftOverLasagne >= 4){
					medBoxes++;
					leftOverLasagne -= 4;
					leftOverPizzas -= 1;
				}
				else if (leftOverLasagne >= 2){
					smallBoxes++;
					leftOverLasagne -= 2;
					leftOverPizzas -= 1;
				}
				else {
					smallBoxes++;
					leftOverPizzas -= 1;
				}
				break;
		}
				
		// deal with leftover lasagne
		if (leftOverLasagne > 0){
			if (leftOverLasagne >= 4){
				medBoxes++;
				leftOverLasagne -= 4;
			}
			else if (leftOverLasagne >= 2){
				smallBoxes++;
				leftOverLasagne -= 2;
			}
		}
		
		// console.log("large boxes: "+largeBoxes+" Med: "+medBoxes+ " Small: "+smallBoxes);
		// console.log("pizzas: " + leftOverPizzas + " lasagne: " + leftOverLasagne + " hearts: " + heartPizzas);
				
		//how many boxes do you need for those sauces
		var sauceBoxes = Math.ceil(sauces/4);

		boxHandlingCost = (smallBoxes+medBoxes+largeBoxes)*10;
		sauceBoxHandling = 5*sauceBoxes;
		
		//zones don't make math sense so check out the attatchment from ted					
		//going to alaska/hawaii 
		if(state == "AK" || state == "HI"){	
		
			//set large med and small costs for each shipping scenario
			largeCost = 216.45; medCost = 190.76; smallCost = 184.01; sauceCost = 116.11;
			//calculate total cost of shipping this way 
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;
			
			//insert value
			options = "<option value='"+shippingCost+"'>Next-Day Air Shipping (M-Th) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 171.95; medCost = 147.07; smallCost = 139.24; sauceCost = 73.04; 			
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options += "<option value='"+shippingCost+"'>2-Day Shipping (M-W) $"+shippingCost.toFixed(2)+"</option>";								
			
		//go to chi shipping zone
		}else if(state == 'IL' || state == 'MO' || state == 'TN' ||state == 'WI' ||state == 'MO' ||state == 'IA' ||state == 'MN' ||state == 'OK' ||state == 'KS' ||state == 'NE' ||state == 'SD' ||state == 'ND' ||state == 'CO'){
			largeCost = 168.31; medCost = 148.19; smallCost = 142.25; sauceCost = 80.24;			
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options =  "<option value='"+shippingCost+"'>Next-Day Air (M-Th) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 67.96; medCost = 59.49; smallCost = 56.48; sauceCost = 31.32;			
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;			
			options += "<option value='"+shippingCost+"'>2-Day Shipping(M-W) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 27.24; medCost = 23.07; smallCost = 17.73; sauceCost = 13.26;			
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + 1.3*boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;	
			options += "<option value='"+shippingCost+"'>UPS-Ground (M-Tu) $"+shippingCost.toFixed(2)+"</option>";

		//go to california shipping zone
		}else if(state == 'WA' || state == 'OR' || state == 'NV' || state == 'CA' || state == 'AZ' || state == 'FL' || state == 'VA' || state == 'ME' || state == 'VT' || state == 'NH' || state == 'NJ' || state == 'CT' || state == 'NY' || state == 'RI' || state == 'MA' || state == 'ID' )
		{
			largeCost = 197.28; medCost = 169.43; smallCost = 162.23; sauceCost = 96.53;			
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options =  "<option value='"+shippingCost+"'>Next-Day Air (M-Th) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 153.45; medCost = 129.33; smallCost = 123.04; sauceCost = 63.23;			
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options += "<option value='"+shippingCost+"'>2-Day Shipping(M-W) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 100.89; medCost = 88.20; smallCost = 74.25; sauceCost = 39.88;			
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost*1.3 + sauceBoxes*sauceCost + sauceBoxHandling;		
			options += "<option value='"+shippingCost+"'>3-Day Shipping (M-Tu) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 39.92; medCost = 34.21; smallCost = 25.04; sauceCost = 15.31;
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost*1.3 + sauceBoxes*sauceCost + sauceBoxHandling;//multiply box handling by 1.3 because of extra dry ice cose			
			 options += "<option value='"+shippingCost+"'>UPS ground (Mon) $"+shippingCost.toFixed(2)+"</option>";

		//go to atlanta shipping zone
		}else{
			largeCost = 180.77; medCost = 158.49; smallCost = 151.43; sauceCost = 88.25;			
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options =  "<option value='"+shippingCost+"'>Next-Day Air (M-Th) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 97.34; medCost = 83.71; smallCost = 80.01; sauceCost = 42.84;			
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options += "<option value='"+shippingCost+"'>2-Day Shipping(M-W) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 72.81; medCost = 62.83; smallCost = 53.42; sauceCost = 29.35;		
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + 1.3*boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options += "<option value='"+shippingCost+"'>3-Day Shipping (M-Tu) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 32.16; medCost = 27.42; smallCost = 20.51; sauceCost = 14.03;			
			shippingCost = largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + 1.3*boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;	
			options += "<option value='"+shippingCost+"'>UPS-Ground (Mon) $"+shippingCost.toFixed(2)+"</option>";
		}
		
		$('#shippingOptions').html('<option id="defaultOption">Select a shipping Option</option>'+options);
		

}

/****************
check gift car popup
***************/
function popChat(url,boxname,w,h) 
{ 
	var w = 300;
	var h = 400;
	
	try{
		window.open("http://www.givex.com/Merchant_pages/500000020/index.html" , "" , 'width='+w+',height='+h+',left=0,top=0,menubar=0,toolbar=0,status =0,resizable=0'); 	
	}catch(e){
		window.location = "http://www.givex.com/Merchant_pages/500000020/index.html";
	}
	
	return false;
} 



