 $(document).ready(function()
 {
	// Create accordions for accordion elements
	$(".accordion").accordion({ autoHeight: false });
	
	
	/** NEWSLETTER SUBMISION **/
	$('#newsletter-form .submit, #news-newsletters .submit').click( function (){ 
	  	//
		$(this).fadeOut(300);
		
		$parent = $(this).parent();
		
		$parent.children('.loader').delay(300).fadeIn(500);
		$parent.find('.msg').fadeOut(100).remove();
		
		$.ajax(
		{
			type: "POST",
			url: "/ajax.php?q=newsletter",
			data: {email: $parent.find('.newsletter-email').val()},
			async: false,
			success: function($data)
			{
				$data = $data.replace(/"/g, '');
				
				if ($data)
				{
					$('.loader').delay(200).fadeOut(500, function (){;
						
						$parent.append('<p class="msg">' + $data + '</p>');
						$parent.find('.submit').fadeIn(300);
						$parent.find('.msg').fadeIn(300);
					});
				}
			}
		});

	  });
	
	// Form Submission
	$('#contact-form .read-more').click( function (){ 
				
				$(this).fadeOut(300);
				setTimeout("$('#contact-form').submit()", 300 );
				
	 });
	
	
	$(function() {

	// if the function argument is given to overlay,
	// it is assumed to be the onBeforeLoad event listener
	$("#courses a[rel]").overlay({

		mask: '#E2E2E2',

		onBeforeLoad: function() {

			// grab wrapper element inside content
			var wrap = this.getOverlay().find("div");

			// load the page specified in the trigger
			wrap.load(this.getTrigger().attr("href"));
		}

		});
	});
	
	// Make side by side divs matching height
	//$(".block").matchHeights();
	
	$('.newsletter-email').bind('focus blur', function(){
		if ( $(this).val() == 'SIGN UP FOR OUR NEWSLETTER')
		{
			$(this).val('');
		}
		else if($(this).val() == '')
		{
			$(this).val('SIGN UP FOR OUR NEWSLETTER');
		}
	});
	
	$('#courses li .read-more').click( function(){
		$(this).parent().toggleClass('selected');
		
		if ( $(this).parent().hasClass('selected') )
		{
			$ajax_call = 'add_to_basket';
			$(this).html('Remove');
		}
		else
		{	
			$ajax_call = 'remove_product';
			$(this).html('Add to basket');
		}

		$.ajax(
		{
			type: "POST",
			url: "/ajax.php?q=" + $ajax_call,
			data: { product_id: $(this).parent().children('.prod_id').html() },
			async: false,
			success: function($data){ 
			$success = true; 
			}
		});
	});
	
	$('.add-delegate').click( function(){
		
		$new_count = parseInt($('#delegate_total').val())+1;
		
		$(this).fadeOut(500, function(){
			$('#form-details-' + $new_count).fadeIn(700);
		});
		
		
		$('#delegate_total').val($new_count);
	});
	
	$('#copy_billing_details').click( function(){
		
		if ($(this).attr('checked'))
		{
			$title = $('#billing_title').val();
			$first_name = $('#billing_first_name').val();
			$last_name = $('#billing_last_name').val();
			$company_name = $('#billing_company_name').val();
			$job_title = $('#billing_job_title').val();
			$email = $('#billing_email').val();
			$phone = $('#billing_phone').val();
			$address_1 = $('#billing_address_1').val();
			$address_2 = $('#billing_address_2').val();
			$address_3 = $('#billing_address_3').val();
			$town = $('#billing_town').val();
			$county = $('#billing_county').val();
			$postcode = $('#billing_postcode').val();
		}
		else
		{
			$title = '';
			$first_name = '';
			$last_name = '';
			$company_name = '';
			$job_title = '';
			$email = '';
			$phone = '';
			$address_1 = '';
			$address_2 = '';
			$address_3 = '';
			$town = '';
			$county = '';
			$postcode = '';
		}
			$('#delegate_title_1').val( $title );
			$('#delegate_first_name_1').val( $first_name );
			$('#delegate_last_name_1').val( $last_name );
			$('#delegate_company_name_1').val( $company_name );
			$('#delegate_job_title_1').val( $job_title );
			$('#delegate_email_1').val( $email );
			$('#delegate_phone_1').val( $phone );
			$('#delegate_address_1_1').val( $address_1 );
			$('#delegate_address_2_1').val( $address_2 );
			$('#delegate_address_3_1').val( $address_3 );
			$('#delegate_town_1').val( $town );
			$('#delegate_county_1').val( $county );
			$('#delegate_postcode_1').val( $postcode );
			
	});
	
	$('.copy_address_details').click( function(){
		
		if ($(this).attr('checked'))
		{
			$first_name = $('#billing_first_name').val();
			$last_name = $('#billing_last_name').val();
			$company_name = $('#billing_company_name').val();
			$address_1 = $('#billing_address_1').val();
			$address_2 = $('#billing_address_2').val();
			$address_3 = $('#billing_address_3').val();
			$town = $('#billing_town').val();
			$county = $('#billing_county').val();
			$postcode = $('#billing_postcode').val();
		}
		else
		{
			$company_name = '';
			$address_1 = '';
			$address_2 = '';
			$address_3 = '';
			$town = '';
			$county = '';
			$postcode = '';
		}
		
		$count = $(this).val();
		
			$('#delegate_company_name_' + $count).val( $company_name );
			$('#delegate_address_1_' + $count).val( $address_1 );
			$('#delegate_address_2_' + $count).val( $address_2 );
			$('#delegate_address_3_' + $count).val( $address_3 );
			$('#delegate_town_' + $count).val( $town );
			$('#delegate_county_' + $count).val( $county );
			$('#delegate_postcode_' + $count).val( $postcode );
			
	});
	
	
	$('#basket li form select[name=courses_details_id]').change( function(){
	
		$product_id = $(this).parents('form').find("input[name$=product_id]").val();
		$places_text = $(this).parents('form').find(".places");
		$quantity = $(this).parents('form').find("input[name$=quantity]").val();
		$courses_details_id = $(this).val();
		
		$price_area = $(this).parents('form').find('.price');
		
		
		$.ajax(
		{
			type: "POST",
			url: "/ajax.php?q=check_places_available",
			data: { product_id: $product_id, courses_details_id: $courses_details_id},
			success: function($data)
			{ 
				$data = eval('(' + $data + ')');
				
				if (( $data['places_left'] < 1) || ($quantity>$data['places_left']) )
				{
					alert('There are not enough places left for this course.');
					return false;
				}	
			}
		 });
		
		
		$.ajax(
			{
				type: "POST",
				url: "/ajax.php?q=update_course_price", 
				data: { product_id: $product_id, courses_details_id: $courses_details_id},
				async: false,
				success: function($data){
					update_subtotal(); 
					check_places_available(); 
					if ($data != 'null')
					{
						$price_area.html('&pound;' + $data.replace(/"/g, ''));
					}
					else
					{
						$price_area.html('&pound;0.00 <span class="small">Please select a date/venue</span>') ;
					}
				}
			});
			
			$.ajax(
			{
				type: "POST",
				url: "/ajax.php?q=check_places_available",
				data: { product_id: $product_id, courses_details_id: $courses_details_id},
				success: function($data){
					
					$data = eval('(' + $data + ')');
					
					if ($data) $places_text.html($data['places_left'] + ' out of ' + $data['total_places'] + ' places available');

				}
			});
		
	});
	
	/** Quantity change **/
	$('#basket li form input[name=quantity]').keyup( function(){
					
		$product_id = $(this).parent().children("input[name$=product_id]").val();
		$courses_details_id = $(this).parents('form').find("select[name$=courses_details_id]").val();
		$quantity = $(this).val();
		
		if ($quantity < 1){ $(this).parents('li').find('.remove').trigger('click'); return; }			
		
		
		$.ajax(
		{
			type: "POST",
			url: "/ajax.php?q=check_places_available",
			data: { product_id: $product_id, courses_details_id: $courses_details_id},
			success: function($data)
			{ 
				$data = eval('(' + $data + ')');
				
				if (( $data['places_left'] < 1) || ($quantity>$data['places_left']) )
				{
					alert('There are not enough places left for this course.');
					return false;
				}	
			}
		 });
										 
			$.ajax(
			{
				type: "POST",
				url: "/ajax.php?q=update_course_places",
				data: { product_id: $product_id, quantity: $quantity},
				async: false,
				success: function($data){ update_subtotal(); }
			});

	 });
	
	$('#basket .remove').click( function(){
	
	if (confirm('Are you sure you want to remove this item?'))
		{
			$.ajax(
			{
				type: "POST",
				url: "/ajax.php?q=remove_product",
				data: { product_id: $(this).parent().children("input[name$=product_id]").val() },
				async: false,
				success: function($data){ $success = true; update_subtotal();}
			});
			
			if ($success) $(this).parent().parent().parent().animate({ opacity:0 }, 500).slideUp(400, function ()
			 { 
				 
				 $(this).remove();
				 
				 $('#basket-btn strong').html('Basket (' + $('#basket').children('li').length + ')');
				 
				 if ( !$('#basket').children('li').length )
				 {
					 $('#basket').html('<li class="none">You have no items in your basket</li>');
					 $('#basket .none').slideDown(700);
					 $('#basket-container .read-more').remove();
				 }
  
				 
			 });

		}
		
	});

	
	
	// Force ain navigation far right dropdown menu's to point the other way
	//$('#nav>li>ul').last().addClass('left');
	// Not needed anymore

	// setup ul.tabs to work as tabs for each div directly under div.panes
	$(".tabs").tabs("div.panes > div");
	
	$("#clients ul").simplyScroll({autoMode: 'loop', frameRate: 24, speed: 1});
	
	// Add nice numbering to ordered lists
	$('#main-content ol').each( function(){ $count=1; $(this).children('li').each( function(){ $(this).addClass(toWords($count));$count++});  });
	
	$('#splash ul').anythingSlider({
		  // Appearance
		  width               : null,      // Override the default CSS width
		  height              : null,      // Override the default CSS height
		  resizeContents      : false,      // If true, solitary images/objects in the panel will expand to fit the viewport
		
		  // Navigation
		  startPanel          : 1,         // This sets the initial panel
		  hashTags            : false,      // Should links change the hashtag in the URL?
		  buildArrows         : false,      // If true, builds the forwards and backwards buttons
		  buildNavigation     : true,      // If true, buildsa list of anchor links to link to each panel
		  navigationFormatter : null,      // Details at the top of the file on this use (advanced use)
		  forwardText         : "&raquo;", // Link text used to move the slider forward (hidden by CSS, replaced with arrow image)
		  backText            : "&laquo;", // Link text used to move the slider back (hidden by CSS, replace with arrow image)
		 
		
		  // Slideshow options
		  autoPlay            : true,      // This turns off the entire slideshow FUNCTIONALY, not just if it starts running or not
		  startStopped        : false,     // If autoPlay is on, this can force it to start stopped
		  pauseOnHover        : false,      // If true & the slideshow is active, the slideshow will pause on hover
		  resumeOnVideoEnd    : true,      // If true & the slideshow is active & a youtube video is playing, it will pause the autoplay until the video has completed
		
		  stopAtEnd           : false,     // If true & the slideshow is active, the slideshow will stop on the last page
		  playRtl             : false,     // If true, the slideshow will move right-to-left
		  startText           : "",   // Start button text
		  stopText            : "",    // Stop button text
		  delay               : 5000,      // How long between slideshow transitions in AutoPlay mode (in milliseconds)
		  animationTime       : 2000,       // How long the slideshow transition takes (in milliseconds)
		  easing              : "easeInOutExpo",   // Anything other than "linear" or "swing" requires the easing plugin,Quint, Qaurt, Elastic, Quad, Expo
		  onSlideBegin        : function(e, slider){ $('#splash ul p, .title-corner').fadeOut(400) },
		  onSlideComplete: function(slider) {

				if ($('p.first').length) $('p.first').fadeIn(400); 
				if ($('p.second').length) $('p.second').delay(300).fadeIn(400); 
				//if ($('p.third').length) $('p.third').delay(600).fadeIn(400); 
				//if ($('p.fourth').length) $('p.fourth').delay(900).fadeIn(400); 
				if ($('.title-corner').length) $('.title-corner').delay(300).fadeIn(400); 

		  }
		  
		});
		
	
		
		// Form Submission
		$('#contact-form .read-more, #taster-form .read-more').click( function (){ 
					
					$(this).parent().append('<img src="/assets/images/ajax-loader.gif" alt="Loading" class="loader" style="margin:5px 0 0" />');
					$(this).parent().children('.loader').css('display', 'block');
					$(this).fadeOut(1000);
					setTimeout($(this).parents('form').submit(), 1000 );
		 });
		
		if ($('.success').length) $('.success').delay(500).slideDown('slow');
		if ($('.error').length) $('.error').delay(500).slideDown('slow');
			
		
		// Google maps
		if ($('#gMap').length) initialize_contact();
		
		
		// Video overlays
		$(function() {$("#videos li img[rel]").overlay({mask: '#F7F2EE', effect: 'apple'}); });
		
		
		// instantiate the overlay on the trigger element or elements
		$("#locations .video").each( function() {
			
			$class = '#' + $(this).attr('class').replace('video video-', 'overlay-');
		//	alert($id);
			//$id = '#overlay-hongkong';
			
			$( $class ).overlay({
				mask: {
					color: '#F7F2EE',
					opacity: 0.5
				},
				effect: 'apple',
				closeOnClick: true
			});
		});

		// bind the triggers with jQuery so they call the function
		$("#locations .video, .loclist li").bind('click', function(){ show_location_video( $(this).attr('class').replace('video video-', 'overlay-')); });
		
		
});

/** SCRIPTS **/

/** Location videos **/
function show_location_video($class) { $('#' + $class).data('overlay').load(); }


//*************
function update_subtotal()
{
	$.ajax(
	{
		type: "POST",
		url: "/ajax.php?q=update_subtotal",
		data: {},
		success: function($data){ if ($data){ $data = $data.replace(/"/g, ''); $('#total-price strong').html('&pound;' + $data); } }
	});
}


// Google maps
function initialize_contact()
{
	var myOptions = {
	  zoom: 10,
	  center: new google.maps.LatLng(51.467854, -0.382466),
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	var map = new google.maps.Map(document.getElementById("gMap"),
								  myOptions);
	
	var image = '/assets/images/gMap.png';
	var myLatLng = new google.maps.LatLng(51.467854, -0.382466);
	var beachMarker = new google.maps.Marker({
		position: myLatLng,
		map: map,
		icon: image
	});
}





