$(document).ready(function() {
	//$('div.content').css('display', 'block'); 
	function doPopup(str)
	{
		$(str).lightbox_me();
	}
	
	////////////////////////////////////////
	// FUNCTIONS FOR HOME PAGE 
	////////////////////////////////////////
	/*
	$('#quickQuote').submit(function(){
		var adults = $('#adultsQuick').val();
		var kids = $('#kidsQuick').val();
		var days = $('#daysQuick').val();
		$.ajax({
			type:'POST',
			url:'getQuickQuote.php',
			data: {'adults':adults,'kids':kids,'days':days},
			success:function(data){
				$('.qqCost').html(data);
			}					   
		});	
		return false;
	});
	*/
	$('a.pdf').click(function(){
		helpStr = '<div class="helpBoxSmall">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295" height="100">';
		helpStr += '<tr><td>';
		helpStr += '<h2 style="margin-top:0">PDF - data collection form</h2>';
		helpStr += "<p>Download and print <a href=\"printable_pdf3.1.pdf\" target=\"_blank\">this PDF</a> to collect your party's information.</p>";	
		helpStr += '</td></tr>';
		helpStr += '<tr><td><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);	
		return false;
	});
	
	$('a.pricematch').click(function(){
		helpStr = '<div class="helpBoxLong">';
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295" height="300">';
		helpStr += '<tr><td>';
		helpStr += '<h2>Our price match guarantee</h2>';
		helpStr += '<p>We aim to be the best value for money in the Meribel valley. We\'re so confident you\'ll get the best rental equipment at the best price with slidecandy; we offer a price match guarantee. If you find the same ski and snowboard rental products at a lower price, delivered to your door, we WILL refund you the difference. The rental product must be available in the same make, model, year and size and for the same rental period.</p>';
		helpStr += '<p>See our <a href="terms.php">terms and conditions</a> for full details.</p>';
		helpStr += '</td></tr>';
		helpStr += '<tr><td><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';	
		doPopup(helpStr);		
		return false;
 	});
	
	$('a.privateservicing').click(function(){
		helpStr = '<div class="helpBox">';
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295" height="200">';
		helpStr += '<tr><td>';
		helpStr += '<h2>Private Servicing</h2>';
		helpStr += '<p>If you have your own equipment and would like a full service or wax and edge just give us a call when you arrive. We will arrange for your equipment to be collected, serviced and delivered ready for your next day on the mountain.</p>';
		helpStr += '<p>Please see price guide for private servicing prices.</p>';
		helpStr += '</td></tr>';
		helpStr += '<tr><td><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';	
		doPopup(helpStr);		
		return false;
 	});
	
	$('a.janoffer').click(function(){
		helpStr = '<div class="helpBoxLong">';
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295" height="300">';
		helpStr += '<tr><td>';
		helpStr += '<h2>Looking for quality ski rental at a great price?</h2>';
		helpStr += '<p>Book now with slidecandy using this promo code SCWP3LCE3J to benefit from a further 10% OFF our online prices!  A 20% saving on our in resort prices!</p>';
		helpStr += '<p><a href="terms.php">Terms and conditions</a> apply.</p>';
		helpStr += '</td></tr>';
		helpStr += '<tr><td><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';	
		doPopup(helpStr);		
		return false;
 	});
	
	$('a.payless').click(function(){
		helpStr = '<div class="helpBoxLonger">';
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295" height="300">';
		helpStr += '<tr><td>';
		helpStr += '<h2>Pay less and ski the best!</h2>';
		helpStr += '<p>Ski on the latest equipment with slidecandy – At a great price – Free delivery and professionally fitted in the comfort of your chalet, hotel or apartment with our exceptional customer service.</p>';
		helpStr += '<p>Why ski on old tired rental skis when you can ski on Slide Candy\'s new kit?</p>';
		helpStr += '<p>Rather than putting your feet in to seasons old rental boots, slip in to a pair of this seasons new boots for that extra comfort and performance!</p>';
		helpStr += '<p>Why pay more when you can have the best for less?</p>';
		helpStr += '<p>Rent your equipment from slidecandy and you won\'t be disappointed!</p>';
		helpStr += '<p>We aim to be the best value for money ski rental in the Meribel valley. We\'re so confident you\'ll get the best rental equipment at the best price with slidecandy; we offer a price match guarantee.</p>';
		helpStr += '<p>See our <a href="terms.php">terms and conditions</a> for full details.</p>';
		helpStr += '</td></tr>';
		helpStr += '<tr><td><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';	
		doPopup(helpStr);	
		return false;
 	});
	
	////////////////////////////////////////						   
	// FUNCTIONS FOR PRICE GUIDE:
	////////////////////////////////////////
	
	$('#resortpriceslink').click(function(){
		$('#priceguideholder').hide();
		$('#priceguideresort').show();	
		$('#resortpriceslinkholder').height('41px');
		$('#onlinepriceslinkholder').height('36px');
		$('#resortpriceslinkholder').css('background','#CCCCCC');
		$('#onlinepriceslinkholder').css('background','#EBEFF3');
		return false;
	});
	
	$('#onlinepriceslink').click(function(){
		$('#priceguideholder').show();
		$('#priceguideresort').hide();	
		$('#resortpriceslinkholder').height('36px');
		$('#onlinepriceslinkholder').height('41px');	
		$('#resortpriceslinkholder').css('background','#EBEFF3');
		$('#onlinepriceslinkholder').css('background','#CCCCCC');							  
		return false;
	});
	
	////////////////////////////////////////						   
	// FUNCTIONS FOR BOOKING STEP 1:
	////////////////////////////////////////

	function setConfirmUnload(on) {
   
   		if (on) {
			window.onbeforeunload = unloadMessage;
		} else {
			window.onbeforeunload = null;
		}
     	//window.onbeforeunload = (on) ? unloadMessage : null;
	}
	
	function unloadMessage() {
	   
		 return 'You have entered new data on this page. If you navigate away from this page, the changes will be lost and you will need to re-enter your data.';
	
	}
	
	//$(':input',document.bookingForm1).bind("change", function() { setConfirmUnload(true); }); // Prevent accidental navigation away
	//$('#bookingForm2').load(function() { alert('loaded'); window.onbeforeunload = unloadMessage; setConfirmUnload(true); }); // Prevent accidental navigation away

	$('#bookingForm1').submit(function(){
		//window.onbeforeunload = null;								   
	});
	$('#bookingForm2').submit(function(){
		//window.onbeforeunload = null;								   
	});
	
	var tomorrow = new Date();
	var today = new Date();
	tomorrow.setTime(tomorrow.getTime() + (1000*3600*24));
	today.setTime(today.getTime());

	$.validator.addMethod( 
	  "selectNone", 
	  function(value, element) { 
	    if (element.value == 0) 
	    { 
	      return false; 
	    } 
	    else return true; 
	  }, 
	  "Please select an option." 
	);
	
	$.validator.addMethod(
		"checkArriveDate",
		function(value, element) {
			var adate = $('#arrivedate').datepicker('getDate').toDateString();
			var atime = $('#arrivetime').val();
			var late = $('#late').val();
			//console.log(adate);
			//if (adate == today.toDateString()) return false;
			//if (adate == tomorrow.toDateString() && atime == 7) return false;
			//if ($('#thisdaywarning').is(":visible")) 
			if (adate == today.toDateString() && late != '1')
			{ 
				//console.log('this day is visible'); 
				return false; 
			} else if ($('#nextdaywarning').is(":visible") && late != '1') 
			{ 
				return false;
			} else {
				return true;	
			}
		},
		""
	);
	
	$.validator.addMethod(
		"checkDateFormat",
		function(value, element) {
			return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
		},
		"Format is dd/mm/yyyy"
	);


	$('#tourop').change(function(){
		var value = $(this).val();					 
		if (value == 'Chalet owners' || value == 'Not known' || value == 'Not applicable')
		{
			$('#otherhotel').addClass('required');
			$('#otherreq').show();
		} else {
			$('#otherhotel').removeClass('required');
			$('#otherreq').hide();
		}
	});

	$('#returningCustomerForm').validate({
	});	
	
	var depends = function() {
        return !$("#chaletdd").is(':hidden');
    };
	$('#bookingForm1').validate({
		rules: {
			tourop: {
				selectNone: true
			},
			arrivedate: {
				checkDateFormat: true,
				checkArriveDate: true
			},
			arrivetime: {
				selectNone: true
			},
			days: {
				selectNone: true
			},
			people: {
				selectNone: true
			},
			chalet: {
				selectNone: { depends: depends }
			}
		}
	});	
	
	$('input.newcustomer').click(function(){						   
		var newCustomer = $(this).filter(':checked').val();
		if (newCustomer == 'true') {
			$('tr.returninglogin').hide();
		} else {
			$('tr.returninglogin').show();
		}
    });
	
	// People dropdown change:
	
	$('#people').change(function(){
		// get drop-down value 
		var people = $(this).val();	
		// get current number of people in party -- add one to include leader
		var currentPeople = $('#otherpeople').children().size()+1;
		// update hidden 'people' field
		$('#numpeople').val(people);
		// if drop-down specifies more than currently displayed:
		if (people > currentPeople) {
			var peopleForm = ''
			for (var i = currentPeople+1; i <= people; i++) {
				peopleForm += '<div id="additionalPerson'+i+'">';
				peopleForm += '<h3 style="margin-left:14px">Person '+i+'</h3>';
				peopleForm += '<table cellpadding="0" cellspacing="5" border="0" id="person'+i+'" style="margin-left:10px">';
				peopleForm += '<tr><td width="250"><span class="label">Title:</span></td><td>';
				peopleForm += '<select name="title'+i+'" id="title'+i+'">';
				peopleForm += '<option value="Mr">Mr</option>';
				peopleForm += '<option value="Mrs">Mrs</option>';
				peopleForm += '<option value="Miss">Miss</option>';
				peopleForm += '<option value="Ms">Ms</option>';
				peopleForm += '<option value="Dr">Dr (male)</option>';
				peopleForm += '<option value="DrF">Dr (female)</option>';
				peopleForm += '</select><em>*</em></td></tr>';
				peopleForm += '<tr><td width="180"><span class="label">First name:</span></td><td><input type="text" name="firstname'+i+'" id="firstname'+i+'"  size="20" class="required"  /><em>*</em></td></tr>';
				peopleForm += '<tr><td width="180"><span class="label">Last name:</span></td><td><input type="text" name="lastname'+i+'" id="lastname'+i+'"  size="20" class="required"  /><em>*</em></td></tr>';
				peopleForm += '</table>';
				peopleForm += '</div>';
			}
			$(peopleForm).appendTo('#otherpeople');
		}
		
		// if drop-down specifies less than currently displayed:
		if (people < currentPeople) {
			for (var i = currentPeople; i >= people-1; i--) {
				$('#otherpeople').children().eq(i).remove();	
			}
		}	
	});
	
	var currentTime = new Date();
	var currentYear = currentTime.getFullYear();
	var currentMonth = currentTime.getMonth() + 1;
	var currentDay = currentTime.getDate();
	var minDatePick;
	// if we're now after April
	if (currentMonth > 4) { 
		minDatePick = new Date(currentYear,12 - 1,3);
		maxDatePick = new Date(currentYear+1,4 - 1,30);
	}
	if (currentMonth > 11 && currentDay > 3) {
		minDatePick = 0;	
		maxDatePick = new Date(currentYear+1,4 - 1,30);
	}
	if (currentMonth < 5) {
		minDatePick = 0;
		maxDatePick = new Date(currentYear,4 - 1,30);
	}
	$('#arrivedate').datepicker({
		//minDate:0,
		minDate:minDatePick,
		maxDate:maxDatePick,
		showOn: 'both',
		buttonImage: 'images/date.jpg',
		buttonImageOnly: true,
		dateFormat:'dd/mm/yy',
		onSelect:function(dateText,inst){
			$('#thisdaywarning').hide();
			$('#nextdaywarning').hide();
			var arriveday = $('#arrivedate').datepicker('getDate');
			var time = $('#arrivetime').val();
			if ((time > 0) && (time < 3)) { // up to 3pm, set first day same as arrive day
				$('#firstday').val($(this).val());
				$('#firstday').datepicker('option','minDate',$('#arrivedate').val());
			} else if (time > 0) { // otherwise set first day as arrive day + one day
				var firstday = new Date();
				firstday.setDate(arriveday.getDate()+1);
				$('#firstday').datepicker('setDate',firstday);
				$('#firstday').datepicker('option','minDate',firstday);	
			}
			//console.log(arriveday.toDateString());
			//console.log(tomorrow.toDateString());
			//console.log(today.toDateString());
			if (arriveday.toDateString() == today.toDateString() && $('#late').val() != '1') {	
				$('#thisdaywarning').show();
			} else if (arriveday.toDateString() == tomorrow.toDateString()) {	
				$.ajax({
					type:'POST',
					url:'getCurrentTime.php',
					success:function(data){
						if (parseInt(data) > 19 && $('#late').val() != '1') { 
							// it's now 8pm or after
							$('#nextdaywarning').show();
						}
					}			   
				});
			}
		}
	});
	
	$('#firstday').datepicker({
		minDate: minDatePick,
		maxDate:maxDatePick,
		showOn: 'both',
		buttonImage: 'images/date.jpg',
		buttonImageOnly: true,
		dateFormat:'dd/mm/yy'
	});
	
	$('img.ui-datepicker-trigger').css({'margin':'0 0 -3px 3px'});
		
	$('#arrivetime').change(function(){
		var time = $(this).val();
		if ((time > 0) && (time < 3)) { 
			// it's the morning:
			$('#firstday').val($('#arrivedate').val());
			$('#firstday').datepicker('option','minDate',$('#arrivedate').val());
		} else if (time > 0) {
			// it's the afternoon, so add a day to the arrive date for the first day:
			var arriveday = $('#arrivedate').datepicker('getDate');
			arriveday.setDate(arriveday.getDate()+1);
			$('#firstday').datepicker('setDate',arriveday);
			$('#firstday').datepicker('option','minDate',arriveday);	
		}
	});
	
	////////////////////////////////////////						   
	// FUNCTIONS FOR BOOKING STEP 2:
	////////////////////////////////////////
	
	// Back button:
	
	function storeForm2Data() {
		var numPeople = $('#numpeople').val();
		var peopleData = new Array;
		$.ajax({
				type:'POST',
				url:'setForm2Session.php',
				data: {'data':$('#bookingForm2').serializeArray()}				   
			});
	}
	
	$('#backStep2').click(function(){
		storeForm2Data();
		window.location.replace('booking.php');
		return false;					   
    });
	
	$('#backStep3').click(function(){
		//storeForm2Data();
		//window.location.replace('bookingStep2.php');
		history.go(-1);
		return false;					   
    });
	
	$('#submitStep2').click(function(){
										 
	});
	
	// Fill form if form2vars session is set
	//alert(window.location.pathname);
	if (window.location.pathname == '/slidecandy/bookingStep2.php') {
		if ($('#form2vars')!='') {
			//alert("session!");	
			//var obj = $.parseJSON($('#form2vars').val());
			//alert(obj);
			//$.each(obj,function(){
				//alert(this.name+' '+this.value);			
			//});
			//$('#bookingForm2').populate(obj,{debug:true});
			//$.post('popForm.php','',function(data){$('#bookingForm2').populate(data,{debug:true})},'json');
		}
	}
	
	// Help functions:
	
	$('a.weightinfo').click(function(){
		helpStr = '<div style="width:300px;background:white;border:1px solid #333">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295">';
		helpStr += '<tr><td><strong>Kgs</strong></td><td><strong>Lbs</strong></td></tr>';
		helpStr += '<tr><td>10-13 kg </td><td>22-29 lbs </td></tr> ';
        helpStr += '<tr><td>14-17 kg </td><td>  30-38 lbs </td></tr>';
        helpStr += '<tr><td>18-21 kg </td><td>  39-47 lbs </td></tr> ';
        helpStr += '<tr><td>22-25 kg </td><td>   48-56 lbs </td></tr> ';
        helpStr += '<tr><td>26-30 kg </td><td>     57-66 lbs </td></tr> ';
        helpStr += '<tr><td>31-35 kg </td><td>   67-78 lbs </td></tr> ';
        helpStr += '<tr><td>36-41 kg </td><td>    79-91 lbs </td></tr> ';
        helpStr += '<tr><td>42-48 kg </td><td>   92-107 lbs </td></tr> ';
        helpStr += '<tr><td>49-57 kg </td><td>  108-125 lbs </td></tr> ';
        helpStr += '<tr><td>58-66 kg </td><td>      126-147 lbs </td></tr> ';
        helpStr += '<tr><td>67-78 kg </td><td>     148-174 lbs </td></tr> ';
        helpStr += '<tr><td>79-94 kg </td><td>   175-209 lbs </td></tr> ';
        helpStr += '<tr><td>95+ kg </td><td>    210+ lbs </td></tr> ';
		helpStr += '<tr><td colspan="2"><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);	
		return false;							 
	});
	
	$('a.levelinfo').click(function(){
		helpStr = '<div class="helpBoxLong" style="height:720px">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295">';
		helpStr += '<tr><td colspan="2">';
		helpStr += '<h2 style="margin-top:0">Level</h2>';
		helpStr += '<h3>Skis</h3>';
		helpStr += '<p><strong>Skier Type -1</strong></p><p>You\'re an adult beginner aged 25yrs or older.</p><p><strong>Skier Type 1</strong></p><p>You\'re a young beginner under 25yrs, you\'re an average level skier who isn\'t in as good shape as you might be or more advanced skiers with a smooth style, who isn\'t aggressive and skis cautiously and carefully.</p><p><strong>Skier Type 2</strong></p><p>You\'re a technically competent skier, but ski fairly gently and carefully with a smooth style but prefer more difficult slopes than your type 1 friends.</p><p><strong>Skier Type 3</strong></p><p>You\'re a good skier who skis faster and aggressively on all terrains.</p><p><strong>Skier Type 3+</strong></p><p>You\'re technically an expert and ski correctly and in control at all speeds.</p>';	
		helpStr += '<h3>Snowboards</h3>';
		helpStr += '<p><strong>Beginner</strong></p><p>First time on a snowboard or working on keeping your turns linked</p><p><strong>Intermediate</strong></p><p>Find linking turns easy, comfortable on blue runs and find red runs a little more challenging.</p><p><strong>Advanced </strong></p><p>Happy on blue, red and black runs.  Looking to progress to off piste or getting some air.</p>';
		helpStr += '</td></tr>';
		helpStr += '<tr><td colspan="2"><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);
		return false;
	});
	
	$('a.insuranceinfo').click(function(){
		helpStr = '<div class="helpBoxLong">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295">';
		helpStr += '<tr><td colspan="2">';
		helpStr += '<h2 style="margin-top:0">Equipment insurance</h2>';
		helpStr += '<p>Have your skis or snowboard ever mysteriously disappeared from a restaurant? Ever blown an edge on a hidden rock? Avoid the trivialities of insurance claims at home and take out Slidecandy equipment insurance. Only &euro;2 per day covers theft and damage with no excess.</p><p>Tick the box to add equipment insurance to your booking.</p><p style="font-size:10px">See our terms &amp; conditions for full details.</p>';	
		helpStr += '</td></tr>';
		helpStr += '<tr><td colspan="2"><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);
		return false;
	});
	
	$('a.helmethire').click(function(){
		helpStr = '<div class="helpBoxSmall">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295" height="100">';
		helpStr += '<tr><td>';
		helpStr += '<h2 style="margin-top:0">Helmet hire</h2>';
		helpStr += '<p>At only 3&euro; per day, it\'s a no brainer! Protect your noggin with a comfortable and lightweight lid.</p>';	
		helpStr += '</td></tr>';
		helpStr += '<tr><td><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);
		return false;
	});
	
	$('a.blueinfo').click(function(){
		helpStr = '<div class="helpBox">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295" height="200">';
		helpStr += '<tr><td>';
		helpStr += '<h2 style="margin-top:0">Equipment category: Blue</h2>';
		helpStr += 'Beginners, improvers or careful & relaxed cruisers, snowbladers, cross country or budget conscious.';	
		helpStr += '</td></tr>';
		helpStr += '<tr><td><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);
		return false;
	});
	
	$('a.blackinfo').click(function(){
		helpStr = '<div class="helpBox">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295" height="200">';
		helpStr += '<tr><td>';
		helpStr += '<h2 style="margin-top:0">Equipment category: Black</h2>';
		helpStr += 'Confident progressing intermediates, advanced all mountain, precision carving experts, speed demons and powder hounds.';	
		helpStr += '</td></tr>';
		helpStr += '<tr><td><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);
		return false;
	});
	
	$('a.redinfo').click(function(){
		helpStr = '<div class="helpBox">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295" height="200">';
		helpStr += '<tr><td>';
		helpStr += '<h2 style="margin-top:0">Equipment category: Red</h2>';
		helpStr += 'Intermediate to advanced, cautiously experienced, technique improvers, picking up the pace, all snowboard levels and twin tip skis.';	
		helpStr += '</td></tr>';
		helpStr += '<tr><td><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);
		return false;
	});
	
	$('a.kidsinfo').click(function(){
		helpStr = '<div class="helpBox">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295" height="200">';
		helpStr += '<tr><td>';
		helpStr += '<h2 style="margin-top:0">Equipment category: Kids</h2>';
		helpStr += 'First time puddings, squealing sliders, stylish cruisers, budding racers, badass boarders, and all other under 13&rsquo;s.';	
		helpStr += '</td></tr>';
		helpStr += '<tr><td><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);
		return false;
	});
	
	$('a.eqsizeinfo').click(function(){
		helpStr = '<div style="width:300px;height:350px;background:white;border:4px solid #0099CC;padding:5px">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295">';
		helpStr += '<tr><td colspan="2">';
		helpStr += '<p><h3>Equipment size guide</h3></p><p>In each case measure from floor:</p><p><strong>Skis</strong></p><p>Beginner - Chin to nose height</p><p>Intermediate - Nose height</p><p>Advanced - Eye level</p><p>Expert - Eye Level - forehead height</p><p><strong>Snowboards</strong><p>Beginner - Chin Height</p><p>All mountain - Nose height</p>';	
		helpStr += '</td></tr>';
		helpStr += '<tr><td colspan="2"><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);
		return false;
	});
	
	$('a.solelengthinfo').click(function(){
		helpStr = '<div class="helpBoxLong" style="height:340px">'
		helpStr += '<table cellspacing="5" cellpadding="0" border="0" width="295">';
		helpStr += '<tr><td colspan="2">';
		helpStr += '<p>If you are bringing your own boots please let us know the sole length of your boots.</p><p>Have a look here on your boots and choose from the drop down list.</p>';	
		helpStr += '<img src="images/heel_sole_length_guide.jpg" />';
		helpStr += '</td></tr>';
		helpStr += '<tr><td colspan="2"><a class="close sprited"  href="#">Close</a></td></tr>';
		helpStr += '</table>';
		helpStr += '</div>';
		doPopup(helpStr);
		return false;
	});
	
	// Fill default ski size:

	function fillSkiSize(person)
	{
		var cat = $("input[name='eqtype"+person+"']").filter(':checked').val();
		var str;
		str = '<option value="Please select for me">Please select for me</option>';
		if (cat == 'kids') {
			str += '<option value="70 - 80cm">70 - 80cm</option>';
			str += '<option value="80 - 90cm">80 - 90cm</option>';
			str += '<option value="90 - 100cm">90 - 100cm</option>';
			str += '<option value="100 - 110cm">100 - 110cm</option>';
			str += '<option value="110 - 120cm">110 - 120cm</option>';
			str += '<option value="120 - 130cm">120 - 130cm</option>';
			str += '<option value="130 -140cm">130 -140cm</option>';
			str += '<option value="140-150cm">140-150cm</option>';
		} else {
			if (cat != 'black') {
			str += '<option value="135 - 140cm">135 - 140cm</option>';
			str += '<option value="140 - 145cm">140 - 145cm</option>';
			}
			str += '<option value="145 - 150cm">145 - 150cm</option>';
			str += '<option value="150 - 155cm">150 - 155cm</option>';
			str += '<option value="155 - 160cm">155 - 160cm</option>';
			str += '<option value="160 - 165cm">160 - 165cm</option>';
			str += '<option value="165 - 170cm">165 - 170cm</option>';
			str += '<option value="170 - 175cm">170 - 175cm</option>';
			str += '<option value="175 - 180cm">175 - 180cm</option>';
			if (cat != 'blue' && cat != 'red') {
			str += '<option value="180 - 185cm">180 - 185cm</option>';
			}
		}	
		$('#eqSize'+person).html(str);
	}
	
	// When Snowboard radio button is clicked, hide all equipment types except red:
	$('input.type').click(function(){
		var person = $(this).filter(':checked').attr('name').replace('type','');							   
		var type = $(this).filter(':checked').val();
		if (type == 'Snowboarder') {
			$('#blueholder'+person).hide();
			$('#blackholder'+person).hide();
			// If Equipment dropdown is showing, change to show only snowboards:
			if ($('#eqDropdown'+person).is(':visible')) {
				var sex = $("input[name='sex"+person+"']").filter(':checked').val();
				$.ajax({
					type:'POST',
					url:'populateEquipmentDD.php',
					data: {'category':'red','sex':sex,'type':type},
					success:function(data){
					$('#eqDropdown'+person).html(data);
						}					   
				});		
			}			
			// Hide own boots dropdown too:
			$('#ownbootsHolder'+person).hide();
			// Refresh Level dropdown:
			var levelStr = '<option value="0" selected="selected">Select:</option>';
            levelStr += '<option value="0">-------------</option>';
            levelStr += '<option value="Beginner">Beginner</option>';
            levelStr += '<option value="Intermediate">Intermediate</option>';
            levelStr += '<option value="Advanced">Advanced</option>';
			$('#level'+person).html(levelStr);
		} else if (type == 'Skier') {
			$('#blueholder'+person).show();
			$('#blackholder'+person).show();
			// If Equipment dropdown is showing, change to show only skis:
			if ($('#eqDropdown'+person).is(':visible')) {
				var sex = $("input[name='sex"+person+"']").filter(':checked').val();
				$.ajax({
				type:'POST',
				url:'populateEquipmentDD.php',
				data: {'category':'red','sex':sex,'type':type},
				success:function(data){
				$('#eqDropdown'+person).html(data);
					}					   
				});		
			}	
			// Show correct boots dropdown:
			var equipment = $("input[name='equipment"+person+"']").filter(':checked').val();
			if (equipment == 'skis') { 
				//$('#ownbootsHolder'+person).show();
			} else {
				$('#ownbootsHolder'+person).hide();
				
			}
			// Refresh Level dropdown:
			var levelStr = '<option value="0" selected="selected">Select:</option>';
            levelStr += '<option value="0">-------------</option>';
            levelStr += '<option value="-1">-1</option>';
            levelStr += '<option value="1">1</option>';
            levelStr += '<option value="2">2</option>';
            levelStr += '<option value="3">3</option>';
            levelStr += '<option value="3+">3+</option>';
			$('#level'+person).html(levelStr);
		}
    });
	
	// When Title dropdown is changed, select appropriate Sex radio button
	
	$('select.title').change(function(){
		var person = $(this).attr('id').replace('title','');
		var title = $(this).val();
		var eqtype = $("input[name='eqtype"+person+"']").filter(':checked').val();
		var type = $("input[name='type"+person+"']").filter(':checked').val();
		if (title == 'Mr' || title == 'Dr') {	
			$('#sexmale'+person).attr('checked',true);
		} else if ((title == 'Mrs') || (title == 'Miss') || (title == 'Ms') || (title == 'DrF')) {
			$('#sexfemale'+person).attr('checked',true);
		} 
		
		// Change the equipment dropdown if necessary:
		var sex = $("input[name='sex"+person+"']").filter(':checked').val();
		if (eqtype == 'blue' || eqtype == 'red' || eqtype == 'black')
		{
			$('#eqDropdownHolder'+person).css({'display':'block'});		
			$.ajax({
				type:'POST',
				url:'populateEquipmentDD.php',
				data: {'category':eqtype,'sex':sex,'type':type},
				success:function(data){
					$('#eqDropdown'+person).html(data);
				}					   
			});
		}
	});
	
	// When Age dropdown is changed, show / hide appropriate equipment types and helmet/boots prices:
		
	$('select.age').change(function(){
		var age = $(this).val();
		var person = $(this).attr('id').replace('age','');
		var adult = 'true';
		var inresort = $('#inresort').val();
		if (age < 6 && age > 0) {
			// i'm a kid:
			// uncheck adults radio buttons:
			$('#eqtypeRed'+person).attr('checked',false);
			$('#eqtypeBlue'+person).attr('checked',false);
			$('#eqtypeBlack'+person).attr('checked',false);
			// show kids radio button:
			$('#kidsequip'+person).show();
			// hide adults radio buttons:
			$('#adultequip'+person).hide();
			// hide adults boots sizes:
			$('.adultbootsize'+person).hide();
			$('.kidsbootsize'+person).show();
			adult = 'false';
		} else if (age > 5) {
			// i'm an adult:
			// uncheck kids radio button:
			$('#eqtypeKids'+person).attr('checked',false); 
			// hide kids radio button:
			$('#kidsequip'+person).hide();
			// show adults radio buttons:
			$('#adultequip'+person).show();
			// show adults boots sizes:
			$('.adultbootsize'+person).show();
			$('.kidsbootsize'+person).hide();
			adult = 'true';
		}
		if ($('#helmet'+person).is(':checked')) { 
			var days = $('#numdays').val();
			$.ajax({
			type:'POST',
			url:'setHelmetPrice.php',
			data: {'days':days,'adult':adult,'inresort':inresort},
			success:function(data){
				$('#helmetprice'+person).html('&euro;'+data);
				$('#hiddenhelmetprice'+person).val(data);
				updatePersonTotal(person);
				}					   
			});
		}
		if ($('#hireSize'+person).val() != 0) {
			var days = $('#numdays').val();
			$.ajax({
			type:'POST',
			url:'setBootPrice.php',
			async:false,
			data: {'days':days,'adult':adult,'inresort':inresort},
			success:function(data){
				$('#bootsprice'+person).html('&euro;'+data);
				$('#hiddenbootsprice'+person).val(data);
				updatePersonTotal(person);	
				}					   
			});	
		}
	
    });
	
	// Invoked when Equipment (skis, skis+boots, boots only) radio button is changed:
	$("input.equipment").click(function(){		
		var person = $(this).filter(':checked').attr('name').replace('equipment','');
		var equipment = $(this).filter(':checked').val();
		var type = $('input.type').filter(':checked').val();
		//alert (person+' '+equipment);
		if (equipment == 'skis') {
			$('#eqtypeHolder'+person).css({'display':'block'});
			$('#insuranceholder'+person).show();
			if (type != 'Snowboarder') {
				//$('#ownbootsHolder'+person).show();
			} else {
				$('#ownbootsHolder'+person).hide();
			}
			// Hide the boot hire section:
			$('#hirebootsHolder'+person).css({'display':'none'});
			// Set the hire boot size to zero:
			$('#hireSize'+person).val(0);
			// Set boot price to zero:
			$('#bootsprice'+person).html('&euro;00.00');
			$('#hiddenbootsprice'+person).val(0);
			updatePersonTotal(person);
			
			// show dropdown:
			//$('#eqDropdownHolder'+person).css({'display':'block'});
		}
		if (equipment == 'skisboots') {
			$('#eqtypeHolder'+person).css({'display':'block'});
			$('#hirebootsHolder'+person).css({'display':'block'});
			$('#insuranceholder'+person).show();
			if (type != 'Snowboarder') {
				$('#ownSize'+person).val(0);
				$('#ownbootsHolder'+person).hide();
			} else {
				$('#ownSize'+person).val(0);
				$('#ownbootsHolder'+person).hide();
			}
			// show dropdown:
			//$('#eqDropdownHolder'+person).css({'display':'block'});
		}
		if (equipment == 'boots') {
			$('#eqtypeHolder'+person).hide();
			$("input[name='eqtype"+person+"']").attr('checked',false);
			$('#hirebootsHolder'+person).show();
			// hide 'own boots' section and set dropdown to 0
			$('#ownbootsHolder'+person).hide();
			$('#ownSize'+person).val(0);
			$('#eqDropdownHolder'+person).hide();
			$('#insuranceholder'+person).hide();
			// Set ski price to zero:
			$('#skiprice'+person).html('&euro;000.00');
			$('#hiddenskiprice'+person).val(0);
			updatePersonTotal(person);
		}
	});
	
	// Invoked when the sex radio button is clicked -- only does something if an equipment type is selected
	$("input.sex").click(function(){
		var person = $(this).filter(':checked').attr('name').replace('sex','');						  
		var sex = $(this).filter(':checked').val();
		var eqtype = $("input[name='eqtype"+person+"']").filter(':checked').val();
		var type = $("input[name='type"+person+"']").filter(':checked').val();
		//alert (type);
		//alert ('eqtype = '+eqtype);
		// If an equipment type is already selected, update equipment dropdown according to sex:
		if (eqtype == 'blue' || eqtype == 'red' || eqtype == 'black')
		{
			$('#eqDropdownHolder'+person).css({'display':'block'});		
			$.ajax({
				type:'POST',
				url:'populateEquipmentDD.php',
				data: {'category':eqtype,'sex':sex,'type':type},
				success:function(data){
					$('#eqDropdown'+person).html(data);
				}					   
			});
		}
	});
	
	// Invoked when Equipment Type (blue,red,black,kids) radio button is changed:
	$("input.eqtype").change(function(){
		var person = $(this).filter(':checked').attr('name').replace('eqtype','');
		var category = $(this).filter(':checked').val();
		var type = $("input[name='type"+person+"']").filter(':checked').val();
		var days = $('#numdays').val();
		var sex = $("input[name='sex"+person+"']").filter(':checked').val();
		var inresort = $('#inresort').val();
		// Show dropdown:
		$('#eqDropdownHolder'+person).show();
		// Set the price
		$.ajax({
			type:'POST',
			url:'setSkiPrice.php',
			data: {'type':category,'days':days,'inresort':inresort},
			success:function(data){
				$('#skiprice'+person).html('&euro;'+data);
				$('#hiddenskiprice'+person).val(data);
				updatePersonTotal(person);
			}					   
		});
		// Fill the size drop down with default values
		fillSkiSize(person);
		//$('#eqSize'+person).html('');
		// Populate the Equipment drop down
		$('#eqDropdownHolder'+person).css({'display':'block'});		
		$.ajax({
			type:'POST',
			url:'populateEquipmentDD.php',
			data: {'category':category,'sex':sex,'type':type},
			success:function(data){
				$('#eqDropdown'+person).html(data);
			}					   
		});
	});
	
	// Invoked when Equipment dropdown (containing skis/snowboards) is changed:
	$("select.eqDropdown").change(function(){
		var person = $(this).attr('id').replace('eqDropdown','');
		var equipID = $(':selected',this).val();
		$.ajax({
			type:'POST',
			url:'populateEquipmentSizeDD.php',
			data: {'equipID':equipID},
			success:function(data){
				$('#eqSize'+person).html(data);
				updatePersonTotal(person);	
			}					   
		});										   
    });
	
	// Invoked when Boot Hire dropdown is changed:
	$("select.hireSize").change(function(){
		var person = $(this).attr('id').replace('hireSize','');	
		var age = $('#age'+person).val();
		var adult;
		var inresort = $('#inresort').val();
		if ((age < 6) && (age > 0)) { adult = 'false'; } else { adult = 'true'; }
		// Set the price:
		var days = $('#numdays').val();
		$.ajax({
			type:'POST',
			url:'setBootPrice.php',
			async:false,
			data: {'days':days,'adult':adult,'inresort':inresort},
			success:function(data){
				$('#bootsprice'+person).html('&euro;'+data);
				$('#hiddenbootsprice'+person).val(data);
				updatePersonTotal(person);	
			}					   
		});
    });
	
	// Invoked when Helmet checkbox is changed:
	$("input.helmet").change(function(){
		var person = $(this).attr('id').replace('helmet','');	
		var age = $('#age'+person).val();
		var adult;
		var inresort = $('#inresort').val();
		if ((age < 6) && (age > 0)) { adult = 'false'; } else { adult = 'true'; }
		if ($(this).is(':checked')) { 
			var days = $('#numdays').val();
			$.ajax({
			type:'POST',
			url:'setHelmetPrice.php',
			data: {'days':days,'adult':adult,'inresort':inresort},
			success:function(data){
				$('#helmetprice'+person).html('&euro;'+data);
				$('#hiddenhelmetprice'+person).val(data);
				updatePersonTotal(person);
				}					   
			});
		} else {
			$('#helmetprice'+person).html('&euro;00.00');
			$('#hiddenhelmetprice'+person).val(0);
			updatePersonTotal(person);
		}
    });
	
	// Invoked when Insurance checkbox is changed:
	$("input.insurance").change(function(){
		var person = $(this).attr('id').replace('insurance','');	
		var inresort = $('#inresort').val();								  
		if ($(this).is(':checked')) { 
			var days = $('#numdays').val();
			$.ajax({
			type:'POST',
			url:'setInsurancePrice.php',
			async:false,
			data: {'days':days,'inresort':inresort},
			success:function(data){
				$('#insuranceprice'+person).html('&euro;'+data);
				$('#hiddeninsuranceprice'+person).val(data);
				updatePersonTotal(person);
			}					   
		});
		} else {
			$('#insuranceprice'+person).html('&euro;00.00');
			$('#hiddeninsuranceprice'+person).val(0);
			updatePersonTotal(person);
		}
    });
	
	function updatePersonTotal(person) {
		var ski = parseFloat($('#hiddenskiprice'+person).val()) ;
		var boots = parseFloat($('#hiddenbootsprice'+person).val());
		var helmet = parseFloat($('#hiddenhelmetprice'+person).val());
		var insurance = parseFloat($('#hiddeninsuranceprice'+person).val());
		var total = parseFloat(ski+boots+helmet+insurance).toFixed(2);
		$('#totalprice'+person).html('&euro;'+total);
		$('#hiddentotalprice'+person).val(total);
		
		// Also update order total:
		var numPeople = $('#numpeople').val();
		var ordertotal = 0;
		var thisPrice;
		for (var i = 1; i <= numPeople; i++) {
			if ($('#hiddentotalprice'+i).val() != '') {
				thisPrice = parseFloat($('#hiddentotalprice'+i).val());
			} else {
				thisPrice = 0;
			}
			ordertotal += thisPrice;
		}
		$('#ordertotal').html('&euro;'+ordertotal.toFixed(2));
	}
	
	// Validate booking step 2 form:
	
	$('#bookingForm2').submit(function(){
		var errorStr = '';
		var numPeople = $('#numpeople').val();
		//alert(numPeople);
		for (var i = 1; i <= numPeople; i++) {
			
			var subStr='';
			
			// check age:
			if ($('#age'+i).val() == 0) {
				subStr += 'Please enter age.\n';
			}
			// check weight:
			if ($('#weight'+i).val() == 0) {
				subStr += 'Please enter weight.\n';
			}
			// check height:
			if ($('#height'+i).val() == 0) {
				subStr += 'Please enter height.\n';
			}
			// check level:
			if ($('#level'+i).val() == 0) {
				subStr += 'Please enter level.\n';
			}
			// check equipment category selected:
			if ((!($('#equipmentSBOnly'+i).is(':checked'))) && (!($('#equipmentSBBoots'+i).is(':checked'))) && (!($('#equipmentBoots'+i).is(':checked')))) {
				subStr += 'Please select some equipment.\n';	
			}
			// check subcategory (blue/red/black/kids) selected if 'skis/boards' or 'skis/boards/boots' selected:
			if (($('#equipmentSBOnly'+i).is(':checked')) || ($('#equipmentSBBoots'+i).is(':checked'))) {
				if ( (!($('#eqtypeBlue'+i).is(':checked'))) && (!($('#eqtypeRed'+i).is(':checked'))) && (!($('#eqtypeBlack'+i).is(':checked'))) && (!($('#eqtypeKids'+i).is(':checked'))) ) {
					subStr += 'Please select an equipment category.\n';	
				}
			}
			// check that if Kids equipment type is checked, a kids age is selected
			if (($('#eqtypeKids'+i).is(':checked')) && ( $('#age'+i).val() > 5 )) {
				subStr += 'You have selected an adult age group and a kids equipment category. Please try again.';	
			}			
			// check equipment dropdown if red/black/blue/kids selected:
			if ( (($('#eqtypeBlue'+i).is(':checked'))) || (($('#eqtypeRed'+i).is(':checked'))) || (($('#eqtypeBlack'+i).is(':checked'))) || (($('#eqtypeKids'+i).is(':checked'))) ) {
				/*console.log($('#eqDropdown'+i).val());*/
				if ($('#eqDropdown'+i).val() == 0 || $('#eqDropdown'+i).val() == null) {
					subStr += 'Please select a ski/snowboard.\n';	
				}
			}
			// check equipment size dropdown if ski/snowboard is selected:
			if ($('#eqDropdown'+i).val() != 0) {
				if ($('#eqSize'+i).val() == 0) {
					subStr += 'Please select your ski/snowboard size.\n';	
				}
			}
			// check Own Boots dropdown if 'skis/board only' is selected and person category = skier:
			//if (($('#equipmentSBOnly'+i).is(':checked')) && ($('#typeSkier'+i).is(':checked'))) {
			//	if ($('#ownSize'+i).val() == 0 || $('#ownSize'+i).val() == null) {
			//		subStr += 'Please select your boot size.\n';
			//	}
			//}
			// check Boot Hire size dropdown if 'skis/board and boots' or 'boots only' are selected:
			if (($('#equipmentSBBoots'+i).is(':checked')) || ($('#equipmentBoots'+i).is(':checked'))) {
				if ($('#hireSize'+i).val() == 0) {
					subStr += 'Please select a boot hire size.\n';	
				}
			}
			// check that this person's total price is greater than zero:
			if ($('#hiddentotalprice'+i).val() == '0' || $('#hiddentotalprice'+i).val() == '0.00' || $('#hiddentotalprice'+i).val() == '00.00' || $('#hiddentotalprice'+i).val() == '') {
				subStr += 'The total price for this person is zero. Please check your order and try again.\n';	
			}
			
			// End of checking this person. If any errors, add to main string:
			if (subStr != '') {
				errorStr += 'Error(s) for person '+i+': \n';
				errorStr += subStr;
			}
		}
		if (errorStr != '') {
			alert(errorStr);
			return false;
		}
	});
	
	////////////////////////////////////////						   
	// FUNCTIONS FOR BOOKING STEP 3:
	////////////////////////////////////////
	
	$('#bookingForm3').validate({
		rules: {
			billingcountry: {
				selectNone: true
			},
			billinghomephone: {
				minlength: 11
			},
			billingmobilephone: {
				minlength: 11
			},
			billinghearabout: {
				selectNone: true
			}
		}
	});
	
	$('#bookingForm3').submit(function(event){
		if ($('#discountcode').val() != '') {
			var discountError = 0;
			//var firstday = $('#firstdayd').val();
			var firstday = $('#bookingdate').val();
			//alert(firstday);
			$.ajax({
				type:'POST',
				url:'checkDiscountCode.php',
				data: {'code':$('#discountcode').val(),'firstday':$('#bookingdate').val()},
				async:false,
				success:function(data){
					if (data != '1') 
					{
						$('#discounterror').show();
						discountError = 1;
					} else {
						$('#discounterror').hide();
						discountError = 0;
					}
					//alert(data);
				}					   
			});	
			//alert(discountError);
			if (discountError == 1) { 
				//alert('error'); 
				event.preventDefault(); 
			}
		}
		//return false;
    });
	
	// Invoked when chalet company / tour operator dropdown is changed:
	
	$('#tourop').change(function(){
		var id = $(':selected',this).val();
		//console.log(id);
		if (!isNaN(parseFloat(id)) && isFinite(id) && (id > 0) && (id != 19)) {
			// if it's a number (and it's not 19, i.e. Meribel Connections), show the chalet dropdown and populate it:
			$('#chaletdd').show();
			$.ajax({
				type:'POST',
				url:'populateChaletsDD.php',
				data: {'id':id},
				success:function(data){
					$('#chalet').html(data);	
				}					   
			});	
		} else {
			// otherwise hide the chalet dropdown:
			$('#chaletdd').hide();
		}
								 
	});	
	
	//////////////////////////////////////
	// FUNCTIONS FOR FAQS
	//////////////////////////////////////
	
	var questions = [];
    var answers = [];
	
	$(".question").each(function () {
            questions.push(this);
        });

        $(".answer").each(function () {
            answers.push(this);
        });
		
		for (var i = 0; i < questions.length; i++) {
            $(answers[i]).hide();
        };

        $(".question").click(function () {
            for (var i = 0; i < questions.length; i++) {
                if (questions[i] == this) {
                    if ($(answers[i]).is(":visible") == true) {
                        $(answers[i]).slideUp('fast');
                    } else {
                        $(answers[i]).slideDown('fast');
                    }
                }
            };
        });
	
	//////////////////////////////////////
	// FUNCTIONS FOR CONTACT US
	//////////////////////////////////////
	
	$('#contactform').validate({
		rules: {
			title: {
				selectNone: true
			}
		}
	});	
	
	
});
