//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').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')
			{
				var image = 'imgs/mailOrder/ValsMailOrder-GenericIntroPopUp-0210.png';
				
				$('.ui-dialog-content').html('<a href="mailOrder.php"><img id="modalImage" src="'+image+'"/></a>');	
			
			//they don't have to see the popup for the rest of the day
				createCookie('hasSeen', 'true');
				modal.dialog("open");
			
			}
		}
		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').attr('disabled', false);
					$('#cardFormSend').attr('disabled', true);
					
					
			});
		}
		
		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', true)
			.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!');
			
			//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(){
					//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() + 35;
		var width  = $('#modalImage').width() + 10;
		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;
		}	
						
		var yMargin = String(heightMargin)+"px";
		var xMargin = String(widthMargin)+"px";
													
		//set width and height "dynamically"	
		$('.ui-dialog-content, .dialogWindow').css({width: width+'px', height: height+'px'});
		//let it show up, not that it looks ok
						
		$('.dialogWindow').css({top: yMargin, left: xMargin}).animate({opacity: 1}, 'fast');  
		$('#centBox').hide();
										
	});			
}//edn of 	open	


/***************
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', true);
	}else
	{
		$('.toggle').attr('disabled', false);	
	}
	
	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").attr('disabled', "").val("25_Gift_Card");
		$("#amount_1").attr('disabled', "").val(25);
		$("#quantity_1").attr('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").attr('disabled', "");
		$("#amount_2").attr('disabled', "");
		$("#quantity_2").attr('disabled', "").val(cards50);
	}else if(cards50 !=0 ){
		$("#item_name_1").attr('disabled', "").val("50_Gift_Card");
		$("#amount_1").attr('disabled', "").val(50);
		$("#quantity_1").attr('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').attr('disabled', false);			
	}else{
		$('#cardFormSend').attr('disabled', true);
	}
}


/****************
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', true)
	.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').attr('disabled', false)
		.css('opacity', 1)
		.css('background-color', '#FFFFFF');
	}else
	{
		//disable submission button
		$('#conFormSubBut').attr('disabled', true)
		.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()
{
	/*//add styling to holiday pizza
	var par = $(".Holiday_Pizza:first").parent();
	par.css({backgroundColor:"#00A75F",padding:"0 10px 10px 10px",color:"white"});
	$(".Holiday_Pizza:first").siblings("h4").css({color:"white"});
	*/
	
	//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();
	});

	$("#special_300").click(function(){
		if($("#special_300").is(":checked")){
			$("#pizzaList300").slideDown();		
		}else{
			$("#pizzaList300").slideUp();			
			$('#zip').triggerHandler('blur');
		}
		$('.orderOptions:last').triggerHandler("keyup");		
	});
	$("#spanCheckbox_300").show();
	//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();
	});
	
	/*$('#zip').focus(function(){
		if($(this).val() === "Enter your zip code"){
			$(this).val("");
		}
	});*/
	
	/* //again recalcualtes a lot of items on the page
	$('#zip').keyup(function(){
	if($(".shipping").css("display") == "none"){
		calculateItemCost();
		var zip = $(this).val();
		var zipSize = zip.length;
		
		//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 and zip code</option>');
		
		//there is an IE6/8 inconsistency they process select boxes differently
		var state;				
		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(zipSize == 5 && $('#totalPrice').html() != "$0.00" && state !== "" && $('#orderFormError').html() === "")
		{			
			
			$('#shippingOptions').attr('disabled', '');
			calculateShipping(zip, "normal");
		}else if($('#orderFormError').html() !== ""){
			$("#defaultOption").html("Invalid Number of items selected");
		}
	}
	});*/
	//	$('#zip').blur(function(){
	//		$(this).triggerHandler('keyup');	
	//	});
	
	/*$("#shipping_zip").keyup(function(){
		calculateItemCost();
		var zip = $(this).val();
		var zipSize = zip.length;
		
		//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 and zip code</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(zipSize == 5 && $('#totalPrice').html() != "$0.00" && state !== "" && $('#orderFormError').html() === "")
		{
			$('#shippingOptions').attr('disabled', '');
			calculateShipping(zip, "shipping");
		}else if($('#orderFormError').html() !== ""){
			$("#defaultOption").html("Invalid Number of items selected");
		}
	});
	
	$('#shipping_zip').blur(function(){
			$(this).triggerHandler('keyup');	
	});*/
	
	/*$('#state').change(function(){
		$("#zip").triggerHandler('blur');
	});*/
	
	$('#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').attr('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');
	});
	
	/*$(".shipping").blur(function(){
		var shipping = $("#shippingOptions > option:selected").html();
		shipping = shipping.split("(");
		shipping = shipping[0];
		alert(shipping);
		//fill in the input to send to paypal
		var val = $("#to").val()+";"+$("#from").val()+";"+$("#message").val()+";";
		val += $("#shipping_first_name").val()+";"+$("#shipping_last_name").val()+";"+$("#shipping_address1").val()+";"+$("#shipping_address2").val()+";"+$("#shipping_city").val()+";"+$("#shipping_state").val()+";"+$("#shipping_zip").val()+";"+$("#orderID").val()+";"+$("#night_phone_a").val()+";"+$("#night_phone_b").val()+";"+$("#night_phone_c").val();
		$("#custom").val(val);
	});
	
	$(".phone").blur(function(){
		var shipping = $("#shippingOptions > option:selected").html();
		shipping = shipping.split("(");
		shipping = shipping[0];
		alert(shipping);
		//fill in the input to send to paypal
		var val = $("#to").val()+";"+$("#from").val()+";"+$("#message").val()+";";
		val += $("#shipping_first_name").val()+";"+$("#shipping_last_name").val()+";"+$("#shipping_address1").val()+";"+$("#shipping_address2").val()+";"+$("#shipping_city").val()+";"+$("#shipping_state").val()+";"+$("#shipping_zip").val()+";"+$	("#orderID").val()+";"+$("#night_phone_a").val()+";"+$("#night_phone_b").val()+";"+$("#night_phone_c").val();
		$("#custom").val(val);
	});
*/
	//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').attr('disabled', '');
		$('#cardForm').unbind('submit', returnFalse);
		//$('#cardForm').attr('disabled', '');
	}else{
		$('#mailOrderSubmit').attr('disabled', 'disabled');
		$('#cardForm').submit(returnFalse);
		//$('#cardForm').attr('disabled', 'disabled');
	}
	
}


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);

	var num300Pizzas = 0;

	//make sure only two specials 300 pizzas were selected
	if($("#special_300").is(":checked")){
		
		//check extra posters
		var extraPosters = $("#extra_posters_300").val();
		
		if(extraPosters != "0" && extraPosters != ""){
			
			count++;
			
			posters = Number(extraPosters);
					
			
			if(isNaN(posters)){
					error += "Please enter numeric quantities for extra posters.";
					before = true;
			}else if(posters > 4){

				error += "You may only select up to four extra posters.";
				before = true;
			}else{
			//loop through and create these inputs for the paypal
				totalPrice += 2.99*posters;
				itemHtml += '<input type="hidden" class="pizza300hidden" id="item_name_'+count+'" name="item_name_'+count+'" value="Pizza and Poster Package - Extra Posters" />';
   		    	itemHtml += '<input type="hidden" class="pizza300hidden" id="amount_'+count+'" name="amount_'+count+'" value="2.99"/>';
	       		itemHtml += '<input type="hidden" class="pizza300hidden" id="quantity_'+count+'" name="quantity_'+count+'" value="'+posters+'"/>';
      			itemHtml += '<input type="hidden" class="pizza300hidden" id="item_number_'+count+'" name="item_number_'+count+'" value="mo_301:Posters"/>';		
			}		
					
		}
		
		
		
		$(".pizza300:not(#extra_posters_300)").each(function(){
			
			item = $(this);
			var quantity = item.val();			
			
			if(quantity != "0" && quantity != ""){
				
				num300Pizzas += Number($(this).val()); 
						
				if(isNaN(num300Pizzas)){
					error += "Please enter numeric quantities for Pizzas.";
					before = true;
				}else{
					count ++;					
					id  = item.attr('id');
				
					price = 0;
					number = $("."+id+":last").val();//and itemNumebr
					id = id.replace("_", " ");

					//loop through and create these inputs for the paypal
					itemHtml += '<input type="hidden" class="pizza300hidden" id="item_name_'+count+'" name="item_name_'+count+'" value="Pizza and Poster Package - '+quantity+' '+id+'" />';
        	    	itemHtml += '<input type="hidden" class="pizza300hidden" id="amount_'+count+'" name="amount_'+count+'" value="0"/>';
    	       		itemHtml += '<input type="hidden" class="pizza300hidden" id="quantity_'+count+'" name="quantity_'+count+'" value="'+quantity+'"/>';
	           		itemHtml += '<input type="hidden" class="pizza300hidden" id="item_number_'+count+'" name="item_number_'+count+'" value="'+number+'"/>';	
				}
			}		
			
		});
		if(num300Pizzas != 2){
				error += "Please choose 2 pizzas for your Pizza and The Poster Package";
				before = true;
		}else{
			count ++;
				
			itemHtml += '<input type="hidden" class="pizza300hidden" id="item_name_'+count+'" name="item_name_'+count+'" value="Pizza and Poster Package" />';
       	   	itemHtml += '<input type="hidden" class="pizza300hidden" id="amount_'+count+'" name="amount_'+count+'" value="33.49"/>';
	   	   	itemHtml += '<input type="hidden" class="pizza300hidden" id="quantity_'+count+'" name="quantity_'+count+'" value="1"/>';
          	itemHtml += '<input type="hidden" class="pizza300hidden" id="item_number_'+count+'" name="item_number_'+count+'" value="mo_300:Sellout_Special"/>';	
           		
           	totalPrice += 33.49;
           	pizzas += 2;
		}
		
	}else{
		$(".pizza300hidden").remove();
		totalPrice = 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%8;
		var leftOverLasagne = lasagnes%8;
		var leftOverHeartPizzas = heartPizzas%4;		
		largeBoxes = (pizzas-leftOverPizzas)/8;
		largeBoxes += (lasagnes-leftOverLasagne)/8;
		smallBoxes += (heartPizzas - leftOverHeartPizzas)/4;
					
		//where do we pu those left over pizzas and lasagnas
		if(leftOverPizzas == 7){
			largeBoxes++;		
		}else if(leftOverPizzas == 6){
							
			if(leftOverLasagne >= 2){
				largeBoxes++;
				leftOverLasagne -= 2;	
			}else{
				medBoxes++;				
			}
									
		}else if (leftOverPizzas == 5) {
			
			if(leftOverLasagne >= 2){
				leftOverLasagne -= 2;				
				largeBoxes++;
			}else{
				medBoxes++;
			}
		}else if (leftOverPizzas ==4) {
				//make sure to stuff lasagne in there			
				if(leftOverLasagne >= 4){
					largeBoxes++;
					leftOverLasagne -= 4;
				}else if(leftOverLasagne == 2){
					medBoxes++;
					leftOverLasagne = 0;
				}
				else {
					smallBoxes++;					
				}
		}else if (leftOverPizzas == 3){
			
			if(leftOverLasagne > 0){				
				if(leftOverLasagne >= 4){
					largeBoxes++;
					leftOverLasagne -= 4;				
				}else{
					medBoxes++;
					leftOverLasagne = 0;	
				}				
			}else{
				smallBoxes++;
				//we can one heart pizza in a box with only 
				if(leftOverHeartPizzas > 0){
					leftOverHeartPizzas--;
				}				
			}
		}			
		else if (leftOverPizzas > 0) {
			
			if (leftOverLasagne >= 6 && (leftOverPizzas == 2 || leftOverPizzas == 1) ) {
				largeBoxes++;
				leftOverLasagne -= 6;
			}
			else if (leftOverLasagne == 4 && leftOverPizzas >= 3) {
				largeBoxes++;
				leftOverlasagne = 0;
			}
			else if (leftOverLasagne == 4) {
				medBoxes++;
				leftOverLasagne = 0;
			}else if(leftOverHeartPizzas > 0){
				smallBoxes++;				
				leftOverHeartPizzas -= (4 - leftOverPizzas);				
				if(leftOverHeartPizzas < 0){
					leftOverHeartPizzas = 0;
				}
			}else if (leftOverLasagne == 2) {
				if (leftOverPizzas == 3) {
					medBoxes++;
				}
				else {
					smallBoxes++;										
				}
				leftOverLasagne = 0;
			}
			else {
				smallBoxes++;
			}
					
		}

		//deal with the heart shaped pizzas	
		if(leftOverHeartPizzas > 0){			
			smallBoxes++;						
		}
						
		//where do we put those left over lasagnas
		if(leftOverLasagne > 6){
			largeBoxes++;	
		}else if(leftOverLasagne > 4){
			medBoxes++;
		}else if (leftOverLasagne > 0){
			smallBoxes++;
		}

		
		//console.log("large boxes: "+largeBoxes+" Med: "+medBoxes+ " Small: "+smallBoxes);
		
		//console.log(smallBoxes+" "+medBoxes+" "+largeBoxes);		
		//how many boxes do you need for those sauces
		var sauceBoxes = Math.ceil(sauces/4);

		boxHandlingCost = (smallBoxes+medBoxes+largeBoxes)*10;
		sauceBoxHandling = 5*sauceBoxes;
		
		var shipping300 = 0;
		//add shipping for 300 posters
		if($("#special_300").is(":checked")){
			shipping300 = 4.95;						
		}
		//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 = 174.65; medCost = 155.04; smallCost = 142.04; sauceCost = 95.55;
			//calculate total cost of shipping this way 
			shippingCost = shipping300+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 = 155.96; medCost = 121.42; smallCost = 105.51; sauceCost = 61.06; 			
			shippingCost = shipping300+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 = 137.01; medCost = 120.09; smallCost = 108.15; sauceCost = 67.23;			
			shippingCost = shipping300+largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options =  "<option value='"+shippingCost+"'>Next-Day Air (M-Th) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 60.81; medCost = 53.29; smallCost = 46.63; sauceCost = 28.42;			
			shippingCost = shipping300+largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;			
			options += "<option value='"+shippingCost+"'>2-Day Shipping(M-W) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 20.66; medCost = 18.44; smallCost = 14.76; sauceCost = 10.26;			
			shippingCost = shipping300+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 = 155.34; medCost = 137.31; smallCost = 123.14; sauceCost = 80.86;			
			shippingCost = shipping300+largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options =  "<option value='"+shippingCost+"'>Next-Day Air (M-Th) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 125.48; medCost = 106.73; smallCost = 94.03; sauceCost = 52.89;			
			shippingCost = shipping300+largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options += "<option value='"+shippingCost+"'>2-Day Shipping(M-W) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 85.58; medCost = 75.97; smallCost = 57.91; sauceCost = 33.82;			
			shippingCost = shipping300+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 = 30.98; medCost = 27.52; smallCost = 21.48; sauceCost = 12.20;
			shippingCost = shipping300+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 = 153.41; medCost = 128.47; smallCost = 115.52; sauceCost = 73.91;			
			shippingCost = shipping300+largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options =  "<option value='"+shippingCost+"'>Next-Day Air (M-Th) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 82.55; medCost = 71.98; smallCost = 63.80; sauceCost = 37.32;			
			shippingCost = shipping300+largeCost*largeBoxes + medCost*medBoxes + smallCost*smallBoxes + boxHandlingCost + sauceBoxes*sauceCost + sauceBoxHandling;		
			options += "<option value='"+shippingCost+"'>2-Day Shipping(M-W) $"+shippingCost.toFixed(2)+"</option>";

			largeCost = 63.53; medCost = 55.82; smallCost = 43.38; sauceCost = 25.31;		
			shippingCost = shipping300+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 = 24.46; medCost = 21.62; smallCost = 17.09; sauceCost = 10.71;			
			shippingCost = shipping300+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;
} 


