var calendarEvents = [];
var headerSection = '';
jQuery(document).ready( function(){
	$.noConflict();
	var stopNavAnimations = false;
	var noSubNav = false;
	if(jQuery('#subNav').css('visibility') == "hidden"){
		noSubNav = true;
	}

	jQuery.each(jQuery('.menu_box'), function() {
		equalHeight(jQuery(this).children('.menu_box_right').children('.container').children('.menu_box_item'));
	});

	/*	This is a hack for IE7 that fixes the mega menu hover issue and z-index..
		But is applied to all elements TODO look into making more efficient and only
		target those elements that need it.. */
	if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) == 7) {
		var zIndexNumber = 1000;
		jQuery('div').each(function() {
			jQuery(this).css('zIndex', zIndexNumber);
			zIndexNumber -= 10;
		});
	}



	jQuery('.commentEntryContainer textarea').focus(function() {
		jQuery(this).prev('label').hide();
		jQuery(this).css('color', '#313335');
	});
	jQuery('.commentEntryContainer textarea').blur(function() {
		if (jQuery(this).val() == '') {
			jQuery(this).prev('label').show();
			jQuery(this).css('color', '#313335');
		}
	});
	jQuery('.commentEntryContainer .commentFormInput').focus(function() {
		jQuery(this).css('color', '#313335');
	});
	jQuery('.commentEntryContainer .commentFormInput').blur(function() {
		var value = jQuery(this).attr('value');
		if (value == 'Name' || value == 'Email'  || value == 'Location') {
			jQuery(this).css('color', '#C51527');
		}
	});
	jQuery('.commentEntryContainer .commentFormInput').each(function() {
		var value = jQuery(this).attr('value');
		if (value != 'Name' && value != 'Email'  && value != 'Location') {
			jQuery(this).css('color', '#313335');
		}
	});

	jQuery('.commentReply').live('click', function(event) {
		event.preventDefault();

		var replyContainer = jQuery(this).parents('.parentComment').find('.replyContainer');

		//If logged in
		if (jQuery('#commentEntryTop').size() > 0)
		{
			if (jQuery(replyContainer).children('.commentEntryContainer').size() == 0)
			{
				var replyClone = jQuery('#commentEntryTop').clone().appendTo(replyContainer);
				jQuery(replyClone).find('h2').html('POST YOUR REPLY');
				jQuery(replyClone).children('.commentEntryContainer').removeAttr('id');

				var commentContainerId = jQuery(this).parents('.parentComment').attr('id');
				var commentId = commentContainerId.replace("comment-", "");
				var hiddenField = '<input type="hidden" name="comment_related" value="'+commentId+'" />';
				var commentForm = jQuery(replyClone).find('form');
				jQuery(hiddenField).appendTo(commentForm);

			}
		}
		else
		{
			window.location = '/login';

			//jQuery(replyContainer).html('<div class="commentReplyNoLogin"><p>To reply this comment, please <a href="/login" class="loginComments" title="Login">login</a><p></div>');
		}


	});


	jQuery('.dislikeComment, .likeComment').live('click', function(event) {
		event.preventDefault();

		if (jQuery('#commentEntryTop').size() > 0)
		{
			var commentContainerId = jQuery(this).parents('.commentContainer').attr('id');
			var commentId = commentContainerId.replace("comment-", "");
			var section = jQuery('#commentEntryTop').find('input[name$="section"]').val();
			var action  = jQuery(this).attr('rel');

			var button = jQuery(this);

			jQuery.ajax({
				type: "POST",
				url: '/comments/likeDislike',
				data: ({'commentId':commentId,'section':section,'action':action}),
				dataType:'json',
				success: function(returnData)
				{
					var total = parseInt(jQuery(button).find('span').html());
					var newTotal = total + 1;
					jQuery(button).find('span').html(newTotal);
				}
			});
		}
		else
		{
			window.location = '/login';
		}
	});

	jQuery('.commentReport').live('click', function(event) {
		event.preventDefault();
		if (jQuery('#commentEntryTop').size() > 0)
		{
			var commentContainerId = jQuery(this).parents('.commentContainer').attr('id');
			var commentId = commentContainerId.replace("comment-", "");
			var section = jQuery('#commentEntryTop').find('input[name$="section"]').val();
			var button = jQuery(this);

			jQuery.ajax({
				type: "POST",
				url: '/comments/report',
				data: ({'commentId':commentId,'section':section}),
				dataType:'json',
				success: function(returnData)
				{
					alert('Thank you for reporting this comment and a site administrator will review the comment')
				}
			});
		}
		else
		{
			window.location = '/login';
		}
	});


	jQuery('#articleHideFake').hide();

	// hacky method to get the footer lists to all have the same height border
	var footerMenuHeight = 0;
	// loop through each footer list
	jQuery('#footerMenu li ul').each(function(i, element) {
		// if this list is taller than the previous biggest list...
		if(jQuery(element).height() > footerMenuHeight)
		{
			// ... update the variable with the height of this list, as it's the tallest so far
			footerMenuHeight = jQuery(element).height();
		}
	});

	// gone through all of them, got the tallest list, now set them all to this height so the borders are the same on all of them
	jQuery('#footerMenu li ul').css('height', footerMenuHeight);
	// probably possible with CSS but I couldn't figure out how, and this works, so hey
	// now we have to make sure the menu is made a bit shorter if the title goes onto more than 1 line
	jQuery('#footerMenu li').each(function(i, element) {
		title = jQuery(this).find('.title');
		if(jQuery(title).height() > 18)
		{
			//difference = jQuery(title).height() - 18;
			//jQuery(this).find('ul').height((jQuery(this).find('ul').height() - difference));
			jQuery(this).find('ul').css({paddingTop:0});
		}
	});


	jQuery('#travel_destinations_widget').change(function() {
		window.location  = '/travel/destinations-a-z/'+jQuery(this).val()
	});


	jQuery('.default-value').each(function() {
	    var default_value = this.value;
	    jQuery(this).css('color', '#666'); // this could be in the style sheet instead
	    //jQuery(this).css('font-size', '20px'); // this could be in the style sheet instead
	    jQuery(this).focus(function() {
	        if(this.value == default_value) {
	            this.value = '';
	            jQuery(this).css('color', '#333');
	            //jQuery(this).css('font-size', '12px'); // this could be in the style sheet instead
	        }
	    });
	    jQuery(this).blur(function() {
	        if(this.value == '') {
	            jQuery(this).css('color', '#666');
	            this.value = default_value;
	        }
	    });
	});

	jQuery('#nav a').click(function() {
		stopNavAnimations = true;
	});

	jQuery('.locationNear').click(function(e){
		e.preventDefault();
		window.location = '/entertainment/page/1?event_location='+jQuery(this).attr('href');
	});

	//jQuery('#subNav').css('visibility','hidden');
	//jQuery('#subNav ul:not(#'+headerSection+'_sub)').css('display','none');
	jQuery('#subNav ul#sub_'+headerSection).css('display','block');

	jQuery('#mainNav>li>a').hover(function(){
		if(stopNavAnimations)
		{
			return;
		}
		jQuery('.next').removeClass('next');
		jQuery('#mainNav li a.active').removeClass('active');
		if (!jQuery(this).parents('#subNav').length) {
			jQuery('.menu_box').removeClass('display');
		}
		jQuery(this).parent('li').children('div.menu_box').addClass('display');

		jQuery('#subNav').css('visibility','visible');
		jQuery('#subNav ul').css('display','none');
		jQuery(this).parent('li').next('li').children('a').addClass('next');

		if (jQuery('#subNav ul#sub_'+jQuery(this).attr('rel')).length) {
			jQuery('#subNav ul#sub_'+jQuery(this).attr('rel')).css('display','block');

			/*if (jQuery('#subNav').css('visibility')=='hidden') {
				jQuery('#subNav').css('visibility','visible');
			}*/

			jQuery(this).addClass('active');
		} else {
			//jQuery('#subNav').css('visibility','hidden');
			jQuery('#subNav ul:not(#sub_'+headerSection+')').css('display','none');
		}

		setTimeout("showDefaultNavList();", 1);
	});

	var timeoutID;
	jQuery('#nav').hover(
		function() {
			window.clearTimeout(timeoutID);
			if(stopNavAnimations)
			{
				return;
			}
			setTimeout("showDefaultNavTab();", 1);
		},
		function() {
			//timeoutID = window.setTimeout(function(){
				//if(stopNavAnimations)
				//{
					//return;
				//}
				//jQuery('#mainNav li a.active').removeClass('active');
				//jQuery('.next').removeClass('next');
				//jQuery('#subNav').css('visibility','hidden');
				//if(noSubNav){
					//jQuery('#subNav').css('visibility','hidden');
				//}
				//jQuery('#subNav ul:not(#sub_'+headerSection+')').css('display','none');
				//jQuery('#subNav ul.active_menu').css('display','block');
				//jQuery('#mainNav li a.menu_active ').addClass('active');
				//jQuery('#mainNav li a.menu_active ').addClass('active').parent('li').next('li').children('a').addClass('next');;

				//setTimeout("showDefaultNavTab();", 1);
				//setTimeout("showDefaultNavList();", 1);
			//},1000);
		}
	);


	jQuery('#nav').mouseleave(function() {
		jQuery('div.menu_box').removeClass('display');
	});

	jQuery(function() {
		jQuery( ".tabs" ).tabs();
	});

	//week_filter_calendar_300 calendar

	jQuery( ".week_filter_calendar_300 .datepicker" ).datepicker(
		{
		dateFormat: 'yy-mm-dd',
		onSelect: function(date, obj) {
			window.location.hash=date;
			window.setTimeout(function() {
				jQuery('ui-datepicker-row-active').removeClass('ui-datepicker-row-active');
				var s = obj.dpDiv.find('.ui-datepicker-current-day a').parent().parent('tr').addClass('ui-datepicker-row-active');
			}, 0);
		}
	});

//	jQuery('.week_filter_calendar_300 div.container .ui-datepicker-calendar tr td a.ui-state-active').live('classActive', function(e) {
//		jQuery('tr.ui-datepicker-row-active').removeClass('ui-datepicker-row-active');
//		jQuery(this).parent('td').parent('tr').addClass('ui-datepicker-row-active');
//	});

	jQuery('.week_filter_calendar_300 div.container .ui-datepicker-calendar tr td a').live('mouseout', function() {
		jQuery(this).parent('td').parent('tr').removeClass('ui-datepicker-row-hover');
	});

	// article_tags_450 hide/show button
	jQuery('.hide_tags').live('click', function(e) {
		e.preventDefault();
		if (jQuery(this).next('div').css('display')=='none') {
			jQuery(this).next('div').css('display','block');
			jQuery(this).text('- Hide');
		} else {
			jQuery(this).next('div').css('display','none');
			jQuery(this).text('+ Show');
		}
	});

//---- JS --- OWEN


	// Social Bar Push
	var topYloc = 210;
	jQuery(window).scroll(function () {
	 var scrollTop = jQuery(document).scrollTop();
	 scrollTop = parseInt(scrollTop);

	 var offset = topYloc+scrollTop+"px";
	 jQuery("#network").animate({top:offset},{duration:500,queue:false});
	});


		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		// ~~~~~~~~~~~~~~~~~~~~~~  A-Z  Toggle/Hide Show ~~~~~~~~~~~~~~~~~~~~~~~~~
		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		var togCount;

		togCount =1;

		jQuery('.block_control a.a-z-show-hide').click(function(e) {
			e.preventDefault();
			jQuery(this).parent().parent().parent().find('div.block').slideToggle();
				if (togCount==1){
					togCount=0;
				}
				else
				{
					togCount=1;
				}
		});

		jQuery('.block_control h3 ').click(function(e) {
			e.preventDefault();
			jQuery(this).parent().parent().parent().find('div.block').slideToggle();
			if((jQuery(this).parent().parent().parent().find('.a-z-show-hide').html()) == "Show")
			{
				jQuery(this).parent().parent().parent().find('.a-z-show-hide').html('Hide');
				togCount = 0;
				var selectedLetter = jQuery(this).find('a').html();
				alphabetActiveLetter(selectedLetter);
			}
			else
			{
				jQuery(this).parent().parent().parent().find('.a-z-show-hide').html('Show');
				togCount = 1;



			}

		});

		jQuery('.block_control .a-z-show-all').click(function(){

			if(jQuery(this).html()=='Show all'){
				jQuery('.block').slideDown();
				jQuery('.block_control .a-z-show-hide').html('Hide');
				jQuery(this).html('Hide all');
				togCount = 0;

				var selectedLetter = '';
				alphabetActiveLetter(selectedLetter);
			}
			else
			{
				jQuery('.block').slideUp();
				jQuery('.block_control .a-z-show-hide').html('Show');
				jQuery(this).html('Show all');
				togCount = 1;
			}

		});

		jQuery('.block_control ul li a ').click(function(e) {
			//e.preventDefault();
			jQuery(this).parent().parent().parent().parent().find('div.block_'+jQuery(this).html()).slideToggle();
			if((jQuery('#'+jQuery(this).html()).find('.a-z-show-hide').html()) == "Show")
			{
				jQuery('#'+jQuery(this).html()).find('.a-z-show-hide').html('Hide');
				togCount = 0;

				var selectedLetter = jQuery(this).html();
				alphabetActiveLetter(selectedLetter);
			}
			else
			{
				jQuery('#'+jQuery(this).html()).find('.a-z-show-hide').html('Show');
				togCount = 1;
			}

		});


		/*
		jQuery('.block_control ul li a').live('click', function(e) {
			e.preventDefault();
			if (togCount==1) {
					alert('here1');jQuery('.a-z-show-hide').text('Hide'); // Default State
			}
			else
			{
				alert('here2');jQuery('.a-z-show-hide').text('Show'); // Default State
			}
		});
		*/

		//jQuery('.block_control a').click(function() {jQuery(this).fadeTo("fast", .5).replaceWith('<a>Hide</a>'); });

		// A-Z Hide/Show Button
		jQuery('.a-z-show-hide').live('click', function(e) {
			e.preventDefault();

			if (jQuery(this).html()=='Hide') {
				//console.log('set show');
				jQuery(this).html('Show'); // Default State
				var selectedLetter = jQuery(this).parent().parent().parent().attr('id');
				alphabetActiveLetter(selectedLetter);
			}
			else
			{
				jQuery(this).html('Hide'); // Default State
			}
		});

		// Slider
   		jQuery('#slider1').anythingSlider({ animationTime : 0 }); // add any non-default options here

		jQuery('#slider1').anythingSliderFx({
			'.panel' : [ 'fade', 1000, 'easeOutCirc' ] // target the entire panel and fade will take 1000ms
		});

     	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		// ~~~~~~~~~~~~~~~~~~~~~~ Events / What's on ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

		jQuery( "#to_date" ).datepicker({
			changeMonth: true,
			changeYear: true
		});
		jQuery( "#from_date" ).datepicker({
			changeMonth: true,
			changeYear: true

		});

		if (jQuery("#from_date").val() == '') {
			jQuery("#from_date").val('From Date');
			jQuery("#from_date").addClass('default-value');
		}


		// Init the clear fields so we don't show them
		checkSearchFormClears();

		jQuery('#from_date').change(function(e){
			checkSearchFormClears();
		});

		// Clear A tags are clicked so clear the relevant fields
		jQuery('.clear_date_input').click(function(e){
			e.preventDefault();
			//console.log(jQuery(this).prev('input'));
			jQuery(this).prev('input').val('');
			if (jQuery(this).prev('input').attr('id') == 'from_date') {
				jQuery(this).prev('input').val('From date');
			}
			checkSearchFormClears();
		});

		// If the form inputes have change then show/hide the clear A tags
		jQuery('.search_widget input').change(function(e){
			checkSearchFormClears();
		});

		// If the Main clear form A tag has been clicked
		jQuery('.clear_search').click(function(e){
			e.preventDefault();
			jQuery('#list_search').val('');
			jQuery('#from_date').val('');
			jQuery('#to_date').val('');
			jQuery('.event_type').each(function(index,item) {
				//console.log(item);
		  		if (item.checked) {
		  			jQuery(item).prop("checked",'');
		  		}
			}); // each .event_type.

			jQuery('.search_widget .checkboxes .checkbox').each(function(index,item) {
				//console.log(item);
		  		jQuery(item).css('background-position','');
			}); // each .event_type

			checkSearchFormClears();
		}); // click .clear_search

		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		// Submit the search form and call the custom
		// google search code
		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		jQuery('.search_widget #input_box').keypress(function(e) {
			var code = (e.keyCode ? e.keyCode : e.which);
		 	if(code == 13) { //Enter keycode
		   		//Do something
		   		executeQuery();
		 	}
		});

		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		// ~~~~~~~~~~~~~~~~~~~~~~ AutoComplete For Locations ~~~~~~~~~~~~~~~~~~~~~
		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		jQuery("#event_location").autocomplete({
	         source: function( request, response ) {
				jQuery.ajax({
					url: '/entertainment/jsonLocations',
					dataType: "json",
					data: {
						json: '1',
						search_query: request.term
					},
					type : "POST",
					success: function( data ) {
						response( jQuery.map( data, function( item ) {
							return {
								label: item.label ,
								value: item.value ,
								id: item.id
							}
						}));
					}
				});
			},
	        minLength: 2,
	        select: function( event, ui ) {
				//jQuery('#event_location_id').val(ui.item.id);
			}
     	});

	}); // Doc Ready?

	/**
	 * Checks the elements on the form to see if we should show or
	 * hide the clear buttons
	 * Author : Greg
	 * Date : 15/07/2011
	 * Versions Hisotyry
	 * Modified by <Your Name here> (DD/MM/YY)
	 *             [Comment about what's modified]
	 **/
	function checkSearchFormClears(){
		// Local Vars specified for checking
		var checkedCheckboxes = 0;
		var otherInputs = 0;

		// Check From Date has a value
		if (jQuery('#from_date').val()) {
			// Show the clear date A tag
			otherInputs++;
			jQuery('#from_date').next('a').addClass('visable');
			jQuery('#from_date').next('a').removeClass('hidden');
		}
		else
		{
			// Hide the clear date A tag
			jQuery('#from_date').next('a').addClass('hidden');
			jQuery('#from_date').next('a').removeClass('visable');
		}

		// Check To Date has a value
		if (jQuery('#to_date').val()) {
			// Show the clear date A tag
			otherInputs++;
			jQuery('#to_date').next('a').addClass('visable');
			jQuery('#to_date').next('a').removeClass('hidden');
		}
		else
		{
			// Hide the clear date A tag
			jQuery('#to_date').next('a').addClass('hidden');
			jQuery('#to_date').next('a').removeClass('visable');
		}

		if (jQuery('#list_search').val()) {
			otherInputs++;
		}

		// Check to see if any checkboxes are checked, if so then increase the coutner
		jQuery('.event_type').each(function(index,item) {
	  		if (item.checked) {
	  			checkedCheckboxes++;
	  		}
		}); // each .event_type

		if (checkedCheckboxes + otherInputs) {
			// Show the Clear Search A tag
			jQuery('.search_widget .clear_search').addClass('visable');
			jQuery('.search_widget .clear_search').removeClass('hidden');
	  	}
	  	else
	  	{
			// Hide the clear saerch A tag
			jQuery('.search_widget .clear_search').addClass('hidden');
			jQuery('.search_widget .clear_search').removeClass('visable');
	  	}

	} // end checkSearchFormClears function


	function revertField(location, value){
		if(jQuery(location).val() == "")
		{
			jQuery(location).val(value);
			return false;
		}
	}

	function refreshField(location, value){
		if(jQuery(location).val() == value)
		{
			jQuery(location).val('');
			return false;
		}
	}

	jQuery(function(){

				// Tabs
				jQuery('.trav-tabs').tabs();
				jQuery('.event-tabs').tabs();
				jQuery('.content-tabs').tabs();

				jQuery('.red-tab-promo ').tabs();
				jQuery('.searchAndCalendar300 ').tabs();

				// Corners
				jQuery('.event-tabs .ui-widget-content').corner("bottom 5px tr");
				jQuery('.event-tab-inner').corner("5px");
				jQuery('.event-tabs .ui-state-default.ui-state-active a').corner("top 5px");
				jQuery('.event-tabs .ui-state-default a').corner("top 5px");


				jQuery('.event-tab-inner').corner("5px");
				jQuery('.slide_btn').corner('3px');
				//jQuery('.red-tab-promo.ui-tabs .ui-tabs-nav li a').corner("3px");
				//jQuery('.red-tab-promo .ui-tabs .ui-tabs-nav l').corner("3px");

				//hover states on the static widgets
				jQuery('#dialog_link, ul#icons li').hover(
					function() { jQuery(this).addClass('ui-state-hover'); },
					function() { jQuery(this).removeClass('ui-state-hover'); }
				);

			});


//------------------------------KAMIL IMPORTED
jQuery(document).ready(function() {



							var today = new Date();
							jQuery("input.datepicker_from").datepicker({
								showOn: "button",
								buttonImage: "/images/300_red_finder_widget/datepicker_icon.png",
								buttonImageOnly: true,
								defaultDate: new Date()
							});
							jQuery("input.datepicker_from").val((today.getMonth()+ 1)+'/'+today.getDate()+'/'+today.getFullYear());
							jQuery("input.datepicker_from").change(function(){
								var date = jQuery(this).val();
								var month = date.substr(0,2);
								var day = date.substr(3,2);
								var year = date.substr(6,4);
								jQuery("select[name='month_year_from']").val(year+'-'+month+'-01');
								var textvalue = jQuery("select[name='month_year_from'] option:selected").text();
								jQuery("select[name='month_year_from']").prev().text(textvalue);
								jQuery("select[name='day_from']").val(day);
								var textvalue = jQuery("select[name='day_from'] option:selected").text();
								jQuery("select[name='day_from']").prev().text(textvalue);
							});
							jQuery("select[name='day_from']").change(function(){
								var day = jQuery(this).val();
								var date = jQuery("select[name='month_year_from']").val();
								var month = date.substr(5,2);
								var year = date.substr(0,4);
								jQuery("input.datepicker_from").val(month+'/'+day+'/'+year);
							});
							jQuery("select[name='month_year_from']").change(function(){
								var date = jQuery(this).val();
								var year = date.substr(0, 4);
								var month = date.substr(5, 2);
								var day = jQuery("select[name='day_from']").val();
								jQuery("input.datepicker_from").val(month+'/'+day+'/'+year);
							});
							jQuery("input.datepicker_to").datepicker({
								showOn: "button",
								buttonImage: "/images/300_red_finder_widget/datepicker_icon.png",
								buttonImageOnly: true,
								defaultDate: new Date()
							});
							jQuery("input.datepicker_to").change(function(){
								var date = jQuery(this).val();
								var month = date.substr(0,2);
								var day = date.substr(3,2);
								var year = date.substr(6,4);
								jQuery("select[name='month_year_to']").val(year+'-'+month+'-01');
								var textvalue = jQuery("select[name='month_year_to'] option:selected").text();
								jQuery("select[name='month_year_to']").prev().text(textvalue);
								jQuery("select[name='day_to']").val(day);
								var textvalue = jQuery("select[name='day_to'] option:selected").text();
								jQuery("select[name='day_to']").prev().text(textvalue);
							});
							jQuery("select[name='day_to']").change(function(){
								var day = jQuery(this).val();
								var date = jQuery("select[name='month_year_to']").val();
								var month = date.substr(5,2);
								var year = date.substr(0,4);
								jQuery("input.datepicker_to").val(month+'/'+day+'/'+year);
							});
							jQuery("select[name='month_year_to']").change(function(){
								var date = jQuery(this).val();
								var year = date.substr(0, 4);
								var month = date.substr(5, 2);
								var day = jQuery("select[name='day_to']").val();
								jQuery("input.datepicker_to").val(month+'/'+day+'/'+year);
							});
						});
						jQuery(document).ready(function() {

							jQuery("div.calendar_date").datepicker();
							jQuery("table.ui-datepicker-calendar th:last").css('width', '25px');
							jQuery("table.ui-datepicker-calendar tr td:last").css('width', '25px');
						});


						//----------------------- Near me search functions. ----------------------
		jQuery(document).ready(function() {
			var map;
			var markersArray = [];
		    var latlng = new google.maps.LatLng(51.5001524,-0.12623619999999391);
			var ltlg = [];

			var infoWindowOptions = {
	                disableAutoPan: true
	                ,maxWidth: 0
	                ,maxHeight:200
	                ,pixelOffset: new google.maps.Size(0, -30)
	                ,zIndex: null
	                ,boxStyle: {
	                  background: "transparent url(/images/near_me_map_search/infoBoxArrow.png) no-repeat"
	                  ,width: "220px"
	                  ,border: "none"
	                  ,"border-radius": "5px"
	                  ,"-moz-border-radius": "5px"
	                 }
	                ,closeBoxMargin: "2px 2px 2px 2px"
	                ,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
	                ,infoBoxClearance: new google.maps.Size(1, 1)
	                ,isHidden: false
	                ,pane: "floatPane"
	                ,enableEventPropagation: false
	     	   };

	     	// Custom info window.
	     	var ib = new InfoBox(infoWindowOptions);


			// Custom icons for markers
			var icons = {"theatre":'/images/near_me_map_search/theatre_icon.png',
			"music":'/images/near_me_map_search/music_icon.png',
			"film" : '/images/near_me_map_search/film_icon.png'};

			// AJAXs
			function downloadUrl(url, callback) {
				var request = window.ActiveXObject ?
					new ActiveXObject('Microsoft.XMLHTTP') :
					new XMLHttpRequest;

				request.onreadystatechange = function() {
					if (request.readyState == 4) {
						request.onreadystatechange = doNothing;
						callback(request, request.status);
					}
				};
				request.open('GET', url, true);
				request.send(null);
			}
			function doNothing() {}

			// Get data from AJAX

			// Parse xml data
			function parseXML(markers){
				var mrData = [];
				//mrData[2387] = "hi";
				//selestiConsole(mrData);
				for (var i=0; i<markers.length; i++){
					var markerinfo = [];

					var locationId = markers[i].getAttribute('marker_location_id');
					if(!mrData[locationId]){
						mrData[locationId] = [];
						mrData[locationId]['events'] = [];
					}

//					markerinfo["marker_id"] = markers[i].getAttribute('marker_id');
//					markerinfo["marker_name"] = markers[i].getAttribute('marker_name');
					markerinfo["marker_description"] = markers[i].getAttribute('marker_description');
					markerinfo["marker_event_name"] = markers[i].getAttribute('marker_event_name');
					markerinfo["marker_event_date"] = markers[i].getAttribute('marker_event_date');
					markerinfo["marker_url"] = markers[i].getAttribute('marker_url');
//					markerinfo["marker_postcode"] = markers[i].getAttribute('marker_postcode');
//					markerinfo["marker_longitude"] = parseFloat(markers[i].getAttribute('marker_longitude'));
//					markerinfo["marker_latitude"] = parseFloat(markers[i].getAttribute('marker_latitude'));
//					markerinfo["marker_type"] = markers[i].getAttribute('marker_type');

					mrData[locationId]["marker_name"] = markers[i].getAttribute('marker_name');
					mrData[locationId]["marker_id"] = markers[i].getAttribute('marker_id');
					mrData[locationId]["marker_url"] = markers[i].getAttribute('marker_url');
					mrData[locationId]["marker_postcode"] = markers[i].getAttribute('marker_postcode');
					mrData[locationId]["marker_longitude"] = parseFloat(markers[i].getAttribute('marker_longitude'));
					mrData[locationId]["marker_latitude"] = parseFloat(markers[i].getAttribute('marker_latitude'));
					mrData[locationId]["marker_type"] = markers[i].getAttribute('marker_type');

					//mrData[locationId]['events'] = [];

					mrData[locationId]['events'].push(markerinfo);
				}
				return mrData;
			}
			// Calculate average positions of the set of markers
			function getCenter(mrData){
				var bounds = new google.maps.LatLngBounds();
				var latLong;

				for (i in mrData){
					var lat = parseFloat(mrData[i]["marker_latitude"]);
					var long = parseFloat(mrData[i]["marker_longitude"]);

					latLong = new google.maps.LatLng(lat,long);
					bounds.extend(latLong);
				}
				if(mrData.length == 0){
					return null;
				}else{
					return bounds;
				}
			}

			function getMarker(mrData, image, destMap) {
				position = new google.maps.LatLng(mrData['marker_latitude'],mrData['marker_longitude']);
				marker = new google.maps.Marker({
				    position: position,
				    map: destMap,
					icon: image,
					marker_id: mrData['marker_id'],
					marker_events: mrData['events'],
					marker_name: mrData['marker_name'],
//					marker_description: mrData['marker_description'],
//					marker_event_name: mrData['marker_event_name'],
//					marker_event_date: mrData['marker_event_date'],
//					marker_url: mrData['marker_url'],
					marker_postcode: mrData['marker_postcode'],
					marker_longitude: mrData['marker_longitude'],
					marker_latitude: mrData['marker_latitude']
				});
				return marker;
			}

			function clearOverlays(){
				if (markersArray.length > 0) {
					for (var i=0; i<markersArray.length; i++) {
						if(markersArray[i]){
							markersArray[i].setMap(null);
						}
					}
					markersArray = [];
				}
			}

			function refreshMap(url,formElement){
				downloadUrl(url,  function(data) {
					markerData = [];
					var xml = data.responseXML;
					var markers = xml.documentElement.getElementsByTagName('marker');
					markerData = parseXML(markers);
					var center;
					if(markerData.length == 0){
						//alert("No results");
						return false;
					}else{
						center = getCenter(markerData)
					}
					refreshGMap(markerData, center);
					formElement.parent().find('img.loadingMap').hide();
				});
			}
			function refreshGMap(mkrData, center, callback){
				// set zoom
				//map.setZoom(9);
				// set new centre
				if(center){
					//map.setCenter(center);
					map.fitBounds(center);
				}
				//remove old markers
				clearOverlays();
				markersArray = [];
				//set new markers
				var icon;



				for(i in mkrData){
					//var icon = icons[mkrData[i]['marker_type']];
					var icon = '';
			    	marker = getMarker(mkrData[i], icon, map);

					markersArray.push(marker);
			    }



				// add info window
				var infowindow = new google.maps.InfoWindow({
			            content: "loading..."
			    });

				// add listeners
				for (i in markersArray) {
					var eventHTML ='';


					for(j in markersArray[i]['marker_events']){
						if(j <= 3){
							event = markersArray[i]['marker_events'][j];
							eventHTML = eventHTML+'<a href="/'+event.marker_url+'" title="'+event.marker_event_name+'" >'+ event.marker_event_name +'</a><br />'+ event.marker_event_date +'<br />';
						}
					}

				//	markersArray[i].html = '<div class="popup"><div class="borderHider"></div><a href="'+markersArray[i].marker_url+'" title="'+markersArray[i].marker_event_name+'" >'+ markersArray[i].marker_event_name +'</a><br />'+ markersArray[i].marker_event_date +'<br />'+ markersArray[i].marker_name +'<br /><a href="'+markersArray[i].marker_url+'" class="more" title="'+markersArray[i].marker_event_name+'" >&gt; Full details</a></div>'
					markersArray[i].html = '<div class="popup"><div class="borderHider"></div>'+ markersArray[i].marker_name +'<br />'+eventHTML+'<a href="/entertainment/page" class="more" title="Event Listings" >&gt; Full details</a></div>'
					google.maps.event.addListener(markersArray[i], 'click', function() {

						ib.setContent(this.html);
						ib.open(map,this);

						/* Old info window
						infowindow.setContent(this.html);
						infowindow.open(map,this);
						*/

						map.setCenter(this.getPosition());
						map.panBy(110, 55)
					});
			    }
			}

			 // Finding out the long and lat of an address (Geocode address)
			  function codeAddress(address,formElement) {
			  	formElement.parent().find('img.loadingMap').show();
			    //initializeMap();
				geocoder = new google.maps.Geocoder();
				//var address = document.getElementById("address").value;
			    geocoder.geocode( { 'address': address + ''}, function(results, status) {
			      if (status == google.maps.GeocoderStatus.OK) {
			      	map.setCenter(results[0].geometry.location);
			      	ib.close();
			      	var longLat = results[0].geometry.location.lng()+','+results[0].geometry.location.lat();
			      //	refreshMap('images/near_me_map_search/init.xml'); //+'&town_city='+address
			      	refreshMap('/events/nearMeMapXML?longLat='+longLat,formElement); //+'&town_city='+address
			      	//document.getElementById("lonlat").value = results[0].geometry.location;

			      } else {

			      }
			    });

			  }
			/**
			 *
			 * @access public
			 * @return void
			 **/
			function nearMeMapSearch(formElement){
				var searchLocation = formElement.find('.location_input').val();

				codeAddress(searchLocation,formElement);
			}


		    var myOptions = {
		      zoom: 9,
		      center: latlng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP,
		      disableDefaultUI: false,
		      zoomControlOptions:true,
		      zoomControlOptions:{
		      	position:google.maps.ControlPosition.LEFT_BOTTOM
		      },
		      streetViewControl:false,
		      mapTypeControl:false
		    };

			if(jQuery('#small_map').length)
			{
			    var map = new google.maps.Map(document.getElementById("small_map"),myOptions);
			}

			jQuery('.near_me_map_search_form').submit(function(e) {
				e.preventDefault();
				nearMeMapSearch(jQuery(this));
			});


	jQuery('#searchWhatsOnForm').submit(function(e) {
		e.preventDefault();
		whatsOnSearch();
	});


	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// ~~~~~~~~~~~~~~~~~~~~~~ EVENT DETAIL Venues near me ~~~~~~~~~~~~~~~~~~~
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	// Only bother if the widget exists
	if(jQuery('.close_venues').length){
		//selestiConsole(center);
		if(jQuery('.small_nearby_venues_map').length)
		{
			//var close_venues_map = new google.maps.Map(document.getElementById("small_map"),myOptions);
			var close_venues_map = new google.maps.Map(jQuery(".small_nearby_venues_map")[0],myOptions);
		    var center = getCenter(close_venues);

		    refreshVenuesMap(close_venues,center,false,close_venues_map);
		}

	}

	function refreshVenuesMap(mkrData, center, callback, targetedMap){
		// set new centre
		if(center){
			//map.setCenter(center);
			targetedMap.fitBounds(center);
		}
		//remove old markers
		clearOverlays();
		markersArray = [];
		//set new markers
		var icon;

		for(i in mkrData){
			//var icon = icons[mkrData[i]['marker_type']];
			var icon = '';
	    	marker = getMarker(mkrData[i], icon, targetedMap);

			markersArray.push(marker);
	    }

		// add info window
		var infowindow = new google.maps.InfoWindow({
	            content: "loading..."
	    });

		// add listeners
		for (i in markersArray) {
			selestiConsole(markersArray[i]);
			//markersArray[i].html = '<div class="popup"><div class="borderHider"></div><a href="'+markersArray[i].marker_url+'" title="'+markersArray[i].marker_event_name+'" >'+ markersArray[i].marker_event_name +'</a><br />'+ markersArray[i].marker_event_date +'<br />'+ markersArray[i].marker_name +'<br /><a href="'+markersArray[i].marker_url+'" class="more" title="'+markersArray[i].marker_event_name+'" >&gt; Full details</a></div>'
			markersArray[i].html = '<div class="popup"><div class="borderHider"></div><a href="/entertainment/page/1?search='+encodeURIComponent(markersArray[i].marker_name)+'" class="more" title="Event Listings" >'+ markersArray[i].marker_name +'</a><br />'+markersArray[i].marker_postcode+'<br /><a href="/entertainment/page" class="more" title="Event Listings" >&gt; Full details</a></div>'
			google.maps.event.addListener(markersArray[i], 'click', function() {

				ib.setContent(this.html);
				ib.open(targetedMap,this);


				targetedMap.setCenter(this.getPosition());
				targetedMap.panBy(110, 55)
			});
	    }
	}

	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


   	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// ~~~~~~~~~~~~~~~~~~~~~~ Search Whats on Widget Form Submit ~~~~~~~~~~~~~
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


	function whatsOnSearch() {
		var search = jQuery('#searchWhatsOn_query');
		var searchWhatsOn_whatson = jQuery('#searchWhatsOn_whatson');
		var event_location = jQuery('#event_location');
		var searchWhatsOn_time = jQuery('#searchWhatsOn_time');

		var only_free 	= jQuery('#only_free');
		//console.log(only_free);
		if (only_free.is(':checked')) {
			only_free = 1;
		}
		else
		{
			only_free = 0;
		}

		var form = jQuery('#searchWhatsOnForm');

		// Added for the What's on page
		var from_date = jQuery('#from_date');
		var to_date = jQuery('#to_date');

		var event_types = "";

		jQuery('.event_type').each(function(index,item) {
			//console.log(item);
	  		if (item.checked) {
	  			event_types = event_types+jQuery(item).val()+',';
	  		}

		});
		//console.log('event_types'+event_types);
		window.location = form.attr('action')+'?search='+search.val()+'&from_date='+from_date.val()+'&only_free='+only_free+'&event_location='+event_location.val();
	}

   	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// ~~~~~~~~~~~~~~~~~~~~~~ Search Whats on Widget Form Submit ~~~~~~~~~~~~~
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	function listSearch() {
		var search = jQuery('#list_search');
		var sort_by = jQuery('#list_sort_by');
		var added = jQuery('#list_added');
		var form = jQuery('#list_search_form');

		// Added for the What's on page
		var from_date = jQuery('#from_date');
		var to_date = jQuery('#to_date');

		var event_location = jQuery('#event_location');
		var only_free 	= jQuery('#only_free');
		//console.log(only_free);
		if (only_free.is(':checked')) {
			only_free = 1;
		}
		else
		{
			only_free = 0;
		}

		var event_types = "";

		jQuery('.event_type').each(function(index,item) {

			//console.log(item);
	  		if (item.checked) {
	  			event_types = event_types+jQuery(item).val()+',';
	  		}

		});
		//console.log('event_types'+event_types);

		window.location = form.attr('action')+'?search='+search.val()+'&sort_by='+sort_by.val()+'&added='+added.val()+'&from_date='+from_date.val()+'&to_date='+to_date.val()+'&event_type='+event_types+'&event_location='+event_location.val()+'&only_free='+only_free;

	}

//	jQuery('#content_sort_by, #content_added').change(function(e) {
//		e.preventDefault();
//		listSearch('content');
//	});
//	jQuery('#content_search_form').submit(function(e) {
//		e.preventDefault();
//		listSearch('content');
//	});
	jQuery('#list_search_form').submit(function(e) {
		e.preventDefault();
		listSearch();
	});
	jQuery('#list_sort_by, #list_added').change(function(e) {
		e.preventDefault();
		listSearch();
	});
//	jQuery('#galleries_sort_by, #galleries_added').change(function(e) {
//		e.preventDefault();
//		listSearch('galleries');
//	});
//	jQuery('#galleries_search_form').submit(function(e) {
//		e.preventDefault();
//		listSearch('galleries');
//	});

	if(jQuery('#travel_destination_map').length)
	{
		if(lat != '' && lng != '')
		{
			var latlng = new google.maps.LatLng(lat, lng);
			var myOptions = {
				zoom: 4,
				center: new google.maps.LatLng(lat2, lng2),
				mapTypeId: google.maps.MapTypeId.TERRAIN
			};
			var map = new google.maps.Map(document.getElementById("travel_destination_map"), myOptions);

			var infoWindow = new google.maps.InfoWindow({
				content: '<p>'+destination_name+'</p>'
			});

			var marker = new google.maps.Marker({
				position: latlng,
				map: map,
				title: destination_name
			});

			google.maps.event.addListener(marker, 'click', function() {
		      infoWindow.open(map,marker);
		    });
	    	infoWindow.open(map,marker);
	    }
	    else
	    {
	    	jQuery('#travel_destination_map').hide();
	    }
	}

	if(jQuery('#travel_destination_a-z').length)
	{
		jQuery('#travel_destination_a-z').change(function() {
			letter = jQuery(this).find('option:selected').val();
			if(letter)
			{
				window.location = '/travel/destinations-a-z?show='+letter+'#'+letter;
			}
		});
	}
});


function showDefaultNavList() {
	if (jQuery('#subNav ul:visible').length == 0) {
		jQuery('#subNav ul#sub_'+headerSection).css('display','block');
	}
}
function showDefaultNavTab() {
	if (jQuery('#mainNav li a.active').length == 0) {
		jQuery('#mainNav li a.navTab_'+headerSection).addClass('active');
		jQuery('#mainNav li a.navTab_'+headerSection).parent('li').next('li').children('a').addClass('next');
	}
}

// Travel Designations make the selected letter with the 'active'  class, and remove all others.
function alphabetActiveLetter(letter){
	//console.log(letter);
	var currentLetter = '';
	jQuery('.block_control ul li a').each(function(i) {
		currentLetter =  jQuery(this).html()
		if (letter == currentLetter) {
			jQuery(this).addClass('active');
		}
		else
		{
			jQuery(this).removeClass('active');
		}
		//console.log();
	});
}

function selestiConsole(s) {
  try { console.log(s) } catch (e) { }
};

function equalHeight(group) {

   tallest = 0;

   group.each(function() {
      thisHeight = jQuery(this).height();

      if(thisHeight > tallest) {
         tallest = thisHeight;

      }
   });

   group.css('height', tallest);
}


