var cookie_name = 'mylc_spotlight';
var spotlight_element = '#spotlight';
var spotlight_target_elements = '#mylc_speech_bubble, #mylc_start_now';

var predefined_areas = new Array(
	"acton",
	"aldwych",
	"archway",
	"balham",
	"bankside",
	"barbican",
	"barnes",
	"barons court",
	"battersea",
	"bayswater",
	"belgravia",
	"belsize park",
	"bermondsey",
	"bethnal green",
	"blackheath",
	"bloomsbury",
	"borough",
	"bow",
	"brent cross",
	"brick lane",
	"brixton",
	"camberwell",
	"camden",
	"catford",
	"chalk farm",
	"chancery lane",
	"chelsea",
	"chinatown",
	"chingford",
	"chiswick",
	"city",
	"clapham",
	"clapton",
	"clerkenwell",
	"colindale",
	"colliers wood",
	"covent garden",
	"cricklewood",
	"crouch end",
	"crystal palace",
	"dalston",
	"deptford",
	"docklands",
	"dulwich",
	"ealing",
	"earl's court",
	"earlsfield",
	"east dulwich",
	"east finchley",
	"east sheen",
	"edgware road",
	"elephant & castle",
	"euston",
	"farringdon",
	"finchley",
	"finsbury park",
	"fitzrovia",
	"forest hill",
	"fulham",
	"gipsy hill",
	"gloucester road",
	"golders green",
	"greenwich",
	"hackney",
	"hackney wick",
	"hammersmith",
	"hampstead",
	"harringay",
	"hendon",
	"herne hill",
	"highbury",
	"highgate",
	"holborn",
	"holland park",
	"holloway",
	"hornsey",
	"islington",
	"kennington",
	"kensal",
	"kensal green",
	"kensington",
	"kentish town",
	"kilburn",
	"king's cross",
	"knightsbridge",
	"ladbroke grove",
	"leicester square",
	"lewisham",
	"leyton",
	"leytonstone",
	"limehouse",
	"london bridge",
	"maida vale",
	"marble arch",
	"marylebone",
	"mayfair",
	"mile end",
	"mill hill",
	"muswell hill",
	"new cross",
	"newington green",
	"notting hill",
	"olympia",
	"oxford street",
	"paddington",
	"palmers green",
	"parsons green",
	"peckham",
	"piccadilly",
	"pimlico",
	"primrose hill",
	"putney",
	"queen's park",
	"raynes park",
	"rotherhithe",
	"shepherd's bush",
	"shoreditch",
	"soho",
	"south kensington",
	"south norwood",
	"south woodford",
	"southgate",
	"southwark",
	"spitalfields",
	"st james's",
	"st john's wood",
	"stockwell",
	"stoke newington",
	"strand",
	"stratford",
	"streatham",
	"stroud green",
	"surrey quays",
	"swiss cottage",
	"sydenham",
	"tooting",
	"tottenham hale",
	"tower bridge",
	"trafalgar square",
	"tufnell park",
	"upton park",
	"vauxhall",
	"victoria",
	"victoria park",
	"walthamstow",
	"wandsworth",
	"wanstead",
	"wapping",
	"waterloo",
	"west hampstead",
	"west kensington",
	"westbourne grove",
	"westbourne park",
	"westminster",
	"whetstone",
	"whitechapel",
	"willesden",
	"wimbledon",
	"winchmore hill",
	"wood green"
);

$(document).ready(function() {
	if ( ! $.cookie('homepage_switch')) {
		$('#homepage_about_us').css('display', 'block');

		$.cookie('homepage_switch', 1, {
			expires: 365,
			path: '/'
		});
	}
	else
	{
		$('#homepage_editors_choice').css('display', 'block');
	}

	$('#print_itinerary').click(function() {
		$('#itinerary_container img').css('display', 'none');
		$('#itinerary_container li.placeholder_slot').css('display', 'none');
		$('#itinerary_container li.time_slot').css('font-weight', 'bold');
		$('.favourite_entry').css('margin-left', '20px');

		$('#itinerary_container').printElement();

		$('#itinerary_container img').css('display', 'inline');
		$('#itinerary_container li.placeholder_slot').css('display', 'block');
		$('#itinerary_container li.time_slot').css('font-weight', 'none');
		$('.favourite_entry').css('margin-left', '0');

		return false;
	});

	$('#register_interest_web_app').click(function() {
		$('#form_newsletter').spotlight({
			opacity: .6,
			color: '#000000',
			exitEvent: 'click',
			onShow: function() {
				setTimeout(function() {
					$(spotlight_element).animate({
						opacity: 0
					}, 400, '', function() {
						$('#form_newsletter').css('z-index', '5000');

						$(spotlight_element).remove();
					});
				}, 2000);
			}
		});
	});

	$('.slideshow').before('<div id="slideshow_buttons">');

	$('.slideshow').cycle({
		speed: 5000,
		pager: '#slideshow_buttons'
	});

	$('#navigation ul li').hover(
		function() {
			$('ul', this).slideDown(100);
		},
		function() {
			$('ul', this).slideUp(0);
		}
	);

	var default_values = new Array();

	$('input.default_value').focus(function() {
		if ( ! default_values[this.id]) {
			default_values[this.id] = this.value;
		}

		if (this.value == default_values[this.id]) {
			this.value = '';
		}

		$(this).blur(function() {
			if (this.value == '') {
				this.value = default_values[this.id];
			}
		});
	});

	if ($.cookie(cookie_name)) {
		$('#addthis').css('display', 'block');
	}
	else {
		$('#mylc_speech_bubble').css('display', 'block');
	}

	$('#search_keywords').keypress(function(e) {
		if (e.which == 13) {
			$('#button_search').click();
		}
	});

	$('#button_search').click(function() {
		var keywords = $('#search_keywords').val().toLowerCase();

		if ($.inArray(keywords, predefined_areas) > -1 || keywords.match(/(GIR 0AA)|(((A[BL]|B[ABDHLNRSTX]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]?|F[KY]|G[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?|M[EKL]?|N[EGNPRW]?|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKLMNOPRSTY]?|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)[1-9]?[0-9]|((E|N|NW|SE|SW|W)1|EC[1-4]|WC[12])[A-HJKMNPR-Y]|(SW|W)([2-9]|[1-9][0-9])|EC[1-9][0-9]) ?[0-9][ABD-HJLNP-UW-Z]{2})/i)) {
			// Location search

			if ($.inArray(keywords, predefined_areas) > -1) {
				keywords = 'london ' + keywords;
			}

			$('.location_search_keywords').val(keywords);
			$('#mx_locator').submit();
		}
		else {
			// Regular search
			$('.regular_search_keywords').val(keywords);
			$('#form_search_regular').submit();
		}

		return false;
	});

	$('#change_radius').change(function() {
		$(this).closest("form").submit();
	});


	if ($('#notification_special_offers').html() != '0')
		$('#notification_special_offers').css('display', 'block');

	if ($('#notification_features').html() != '0')
		$('#notification_features').css('display', 'block');

	/*$('a:not([href*="' + document.domain + '"])').attr('target', '_blank');

	$('a:not([href*="' + document.domain + '"])').click(function() {
		pageTracker._trackPageview('/outbound/' + $(this).attr('href'));
	});*/

	$('.hover').hover(function() {
		$(this).attr('src', $(this).attr('src').split('.').join('_hover.'));
	}, function() {
		$(this).attr('src', $(this).attr('src').split('_hover.').join('.'));
	});

	$(document).bind('cbox_open', function() {
		$('.flash_content').css({'visibility':'hidden'});
	}).bind('cbox_cleanup', function(){
		$('.flash_content').css({'visibility':'visible'});
	});

	$("a[rel='venue_gallery']").colorbox();

	$("#venue_image_gallery, .venue_image_gallery").click(function(e) {
		e.preventDefault();

		$("a[rel='venue_gallery']:first").click();
	});

	$("a[rel='venue_video_gallery']").colorbox({
		iframe : true,
		innerWidth: '640px',
		innerHeight: '480px',
		current: false
	});

	$(".open_colorbox_map").live('click', function() {
		$.colorbox({
			href: $(this).attr('href'),
			innerWidth: '500px',
			innerHeight: '500px',
			iframe: true,
			title: false
		});

		return false;
	});

	$(".open_colorbox_contact").live('click', function() {
		$.colorbox({
			href: $(this).attr('href'),
			innerWidth: '250px',
			innerHeight: '250px',
			iframe: true,
			title: false
		});

		return false;
	});

	$("#launch_video_gallery").click(function(e) {
		e.preventDefault();

		$("a[rel='venue_video_gallery']:first").click();
	});

	$("#prompt_register").click(function() {
		return confirm("Oops! It appears as though you do not have an account with us. Please Register/Login to continue.");
	});

	$(".navigate_away").live('click', function() {
		return confirm("You are about to leave this page which means you will lose any unsaved data. Do you want to continue?");
	});

	//$.localScroll();

	$('.favourites').click(function() {
		var href = $(this).attr('href');
		var id = $(this).attr('id');

		$(this).css('display', 'none');
		$('#mylc_ajax_loader').css('display', 'inline');

		$.get(href, function() {
			$('#mylc_ajax_loader').css('display', 'none');

			if (id == 'favourites_create') {
				$('#favourites_create').css('display', 'none');
				$('#favourites_delete').css('display', 'inline');
			}
			else {
				$('#favourites_delete').css('display', 'none');
				$('#favourites_create').css('display', 'inline');
			}
		});

		return false;
	});

	$('.delete_favourite').click(function() {
		var href = $(this).attr('href');
		var li = $(this).parent();

		$.get(href, function() {
			li.css('display', 'none');
			
			$('#favourites_count').html(parseInt($('#favourites_count').html() - 1));
		});

		return false;
	});

	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
		document.title = 'LC';
		
		$('#minimise_form_newsletter').css('display', 'none');
		$('#form_newsletter').css('position', 'absolute');
	}

	$('#minimise_form_newsletter').click(function() {
		if ( ! $.cookie('minimise_form_newsletter')) {
			$.cookie('minimise_form_newsletter', 1, {
				expires: 7,
				path: '/'
			});
		}

		$(this).css('display', 'none');
		$('#form_newsletter').css('position', 'absolute');

		return false;
	});

	if ($.cookie('minimise_form_newsletter')) {
		$('#minimise_form_newsletter').css('display', 'none');
		$('#form_newsletter').css('position', 'absolute');
	}

	$('.favourites_ > li').draggable({
		connectToSortable: '.itinerary',
		helper: 'clone'
	});

	$('#save_trip').click(function() {
		if ($('#trip_name').val() != '') {
			var itinerary = new Array();

			$('.itinerary li').each(function(i) {
				var data = $(this).metadata();

				if (data.date && data.time_slot) {
					itinerary[i] = data.date + '||' + data.time_slot;
				}
				else {
					itinerary[i] = data.favourite;
				}
			});

			$.post('/assets/php/trips.php', {
				trip_name: $('#trip_name').val(),
				from: $('#from').val(),
				to: $('#to').val(),
				itinerary: itinerary
			}, function() {
				alert("Your trip has been saved!");
			});
		}
		else {
			alert("Please enter the name of your trip!");
		}
	});

	$('#overwrite_trip').click(function() {
			var itinerary = new Array();

			$('.itinerary li').each(function(i) {
				var data = $(this).metadata();

				if (data.date && data.time_slot) {
					itinerary[i] = data.date + '||' + data.time_slot;
				}
				else {
					itinerary[i] = data.favourite;
				}
			});

			$.post('/assets/php/overwrite_trip.php', {
				key: $('#saved_trip_key').val(),
				itinerary: itinerary
			}, function() {
				alert("Your trip has been updated!");
			});
	});

	$('#view_itinerary').click(function() {
		$('#saved_trip_key').val($('#choose_save_trip').val());

		$.post('/assets/php/update_trip.php', {
			trip_key: $('#choose_save_trip').val()
		}, function(data) {
			$('#itinerary_planner').css('display', 'block');

			$('#itinerary_container').html(data);

				$('.sortable').sortable({
					cancel: '.cancel_slot',
					connectWith: 'ul.sortable',
					cursor: 'move',
					dropOnEmpty: true,
					items: 'li:not(.morning)',
					update: function(event, ui) {
						var data = ui.item.metadata();
						var fav = data.favourite;

						var bits = fav.split("||");
						var new_class = bits[0] + '_' + bits[1];

						if (this.id == 'trash') {
							if ($('.itinerary .' + new_class).length < 1) {
								$('.' + new_class).css('background', "url('/assets/images/backgrounds/attraction_background.png') no-repeat 0 0");
							}

							$('#' + ui.item.attr('id')).remove();
						}
						else {
							$('.' + new_class).css('background', "url('/assets/images/backgrounds/attraction_background_green.png') no-repeat 0 0");
						}
					}
				}).disableSelection();

				$('.itinerary li').each(function(i) {
					var data = $(this).metadata();

					if (data.favourite) {
						var fav = data.favourite;

						var bits = fav.split("||");
						var new_class = bits[0] + '_' + bits[1];

						$('.' + new_class).css('background', "url('/assets/images/backgrounds/attraction_background_green.png') no-repeat 0 0");
					}
				});
		}, 'html');
	});

	$('#create_trip').click(function() {
		if ($('#from').val() != '' && $('#to').val() != '') {
			$.post('/assets/php/dates.php', {
				from: $('#from').val(),
				to: $('#to').val()
			}, function(data) {
				var html = '';

				$.each(data, function(i, item) {
					html = html + '<h3 class="black">' + item + '</h3>';
					html = html + '<ul class="itinerary sortable">';
					html = html + '<li class="morning time_slot {date: \'' + item + '\', time_slot: \'morning\'}">Morning</li>';
					html = html + '<li class="cancel_slot placeholder_slot">&nbsp;</li>';
					html = html + '<li class="cancel_slot afternoon_evening time_slot {date: \'' + item + '\', time_slot: \'afternoon\'}">Afternoon</li>';
					html = html + '<li class="cancel_slot placeholder_slot">&nbsp;</li>';
					html = html + '<li class="cancel_slot afternoon_evening time_slot {date: \'' + item + '\', time_slot: \'evening\'}">Evening</li>';
					html = html + '<li class="cancel_slot placeholder_slot">&nbsp;</li>';
					html = html + '</ul>';
				});

				$('#itinerary_container').html(html);

				$('.sortable').sortable({
					cancel: '.cancel_slot',
					connectWith: 'ul.sortable',
					cursor: 'move',
					dropOnEmpty: true,
					items: 'li:not(.morning)',
					update: function(event, ui) {
						var data = ui.item.metadata();
						var fav = data.favourite;

						var bits = fav.split("||");
						var new_class = bits[0] + '_' + bits[1];

						if (this.id == 'trash') {
							if ($('.itinerary .' + new_class).length < 1) {
								$('.' + new_class).css('background', "url('/assets/images/backgrounds/attraction_background.png') no-repeat 0 0");
							}

							$('#' + ui.item.attr('id')).remove();
						}
						else {
							$('.' + new_class).css('background', "url('/assets/images/backgrounds/attraction_background_green.png') no-repeat 0 0");
						}
					}
				}).disableSelection();
			}, 'json');

			if (parseInt($('#favourites_count').html()) > 0) {
				$('#itinerary_planner').css('display', 'block');
			}
			else {
				alert("Please come back when you have added some venues to your favourites!");
			}
		}
		else {
			alert('Please choose a "From" and "To" date.');
		}
	});

	$('#custom_date_range').click(function() {
		$('#select_custom_date_range').toggle('slow');

		return false;
	});

	$('#button_subscribe').click(function() {
		$('#mailchimp_form').submit();

		return false;
	});

	$('#show_events').click(function() {
		var current_act = $('#show_events_form').attr('action');

		if ($('#custom_from').val() != '')
		{
			current_act += '/custom/' + $('#custom_from').val();

			if ($('#custom_to').val() != '')
			{
				current_act += '/' + $('#custom_to').val();
			}
		}

		$('#show_events_form').attr('action', current_act);

		$('#show_events_form').submit();
	});
});

function open_colorbox(id)
{
	$.colorbox({
		inline: true,
		href: id
	});
}

$(function() {
	var dates = $("#from, #to").datepicker({
		defaultDate: "+1w",
		dateFormat: 'd M yy',
		changeMonth: true,
		numberOfMonths: 1,
		minDate: 0,
		onSelect: function(selectedDate) {
			var option = this.id == "from" ? "minDate" : "maxDate",
			instance = $(this).data("datepicker"),
			date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings
			);
			dates.not(this).datepicker("option", option, date);
		}
	});
});

$(function() {
	var dates = $("#custom_from, #custom_to").datepicker({
		defaultDate: "+1w",
		dateFormat: 'yy-mm-dd',
		changeMonth: true,
		numberOfMonths: 1,
		minDate: 0,
		onSelect: function(selectedDate) {
			var option = this.id == "custom_from" ? "minDate" : "maxDate",
			instance = $(this).data("datepicker"),
			date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings
			);
			dates.not(this).datepicker("option", option, date);
		}
	});
});

$(window).load(function() {
	if ( ! $.cookie(cookie_name)) {
		setTimeout(function() {
			$(spotlight_target_elements).spotlight({
				opacity: .6,
				color: '#000000',
				exitEvent: 'click',
				onShow: function() {
					setTimeout(function() {
						$(spotlight_element).animate({
							opacity: 0
						}, 400, '', function() {
							$(spotlight_target_elements).css('z-index', '1');

							$(spotlight_element).remove();
						});
					}, 2000);
				}
			});

			$.cookie(cookie_name, 1, {
				expires: 7,
				path: '/'
			});
		}, 3000);
	}
});
