var venue_search_options = new Array();
var venue_search_options_checked = new Array();
var venue_search_checkbox_ids = new Array();
var venue_search_fieldset_ids = new Array();

//these need to be initialised to accept the onload checked checkboxes.
var fieldsets = new Array();
var lockAnimation = 0;
var leftClicks = 0;
var gmarkers = new Array();

var countProcedures = 0;

/* SiFR fonts */

var vag_std = {
	 src: base_url + 'assets/flash/vag_std.swf'
	};	
	
/* before doc ready is ok */
initBookmarkedSearches();




$(window).load(function () {

	  initSafeImagery();
    
});


function initCommonFunctions(){
	/* EVERY PAGE NEEDS THESE */
	
	$("#search_name_cuisine").attr('autocomplete', 'off');
	
	jQuery.easing.def = "easeOutExpo";  
	initEqualHeight();
	initSiFR();
	initForwardFriend();
	initClosers();
	initInputHover();
	initNavigation();
	initQuickSearch();
   	initSelectBoxes('#search_location'); 
	initDrilldownMenu();
   	initForms();
   	initBookmarks();
   	initCalendar();
   	$('.bookmark_link').jFav();
}

function initCalendar(){
	
	var calendar_months = $("table.calendar");
	if(calendar_months.length == 0){
		$("#calendar_container").remove();
	}
	
}


function initForms(){
	
	var forms = $('form');
	var requireds = $("input.required, select.required");
	
	requireds.each(function(){
	
		$(this).focus(function(e){
		
			$(this).removeClass('prompt');
		
		});
	
	});
	
	forms.each(function(){
	
		$(this).submit(function(e){
			var required_inputs = $(this).find("input.required[value=''],select.required[value='']");
			var inputs = $(this).find("input.required[value!=''],select.required[value!='']").removeClass('prompt');
			
			if(required_inputs.length > 0){
				$(required_inputs).addClass('prompt');
				
				e.preventDefault();				
				//window.location.hash = required_inputs[0].id;
			}
			else {
				// Validate password fields if they exist inside this form
				var pw_fields = $(this).find("#wlpeUserProfilePassword, #wlpeUserProfilePasswordConfirm");
				if (pw_fields.length == 2) {
					if ($(pw_fields[0]).val() != $(pw_fields[1]).val()) {
						e.preventDefault();
						$(pw_fields).addClass('prompt');
						window.location.hash = pw_fields[0].id;
					}
				}
			}
		
		});
		
	
	});

}

function initSafeImagery(){

	$('#article').imagefit();
	$('#featured_restaurant_content').imagefit();

}


(function($) {
	$.fn.imagefit = function(options) {
	
		var fit = {
			all : function(imgs){
				imgs.each(function(){
					fit.one(this);
					})
				},
			one : function(img){
					if($(img).attr('containerwidth') < $(img).attr('startwidth')){
						$(img).width('100%').each(
							function(){
								$(this).height(Math.round(
									$(this).attr('startheight')*($(this).width()/$(this).attr('startwidth')))
								);
							});
					} else {
						//ignore it, leave it be.
					}
				}
		};
		
		this.each(function(){
				var container = this;
				
				// store list of contained images (excluding those in tables)
				var imgs = $('img', container).not($("table img"));
				
				// store initial dimensions on each image 
				imgs.each(function(){
					$(this).attr('startwidth', $(this).width())
						.attr('containerwidth', $(container).width())
						.attr('startheight', $(this).height())
						.css('max-width', $(this).attr('startwidth')+"px");
					fit.one(this);
				});
				// Re-adjust when window width is changed
				$(window).bind('resize', function(){
					fit.all(imgs);
				});
			});
		return this;
	};
})(jQuery);






function initGallery(){
	
	var gallery = $('#gallery').galleriffic('#gallery_thumbs', {
					delay:                5000,
					imageContainerSel:    '#slideshow',
					controlsContainerSel: '#controls',
					titleContainerSel:    '#image-title',
					descContainerSel:     '#image-desc',
					downloadLinkSel:      '#download-link',
					numThumbs:            5,
					preloadAhead:         40, 
					enableTopPager:       false,
					enableBottomPager:    true,
					renderSSControls:     true,
					renderNavControls:    true,
					playLinkText:         'Play',
					pauseLinkText:        'Pause',
					prevLinkText:         '<',
					nextLinkText:         '>',
					nextPageLinkText:     'Next &rsaquo;',
					prevPageLinkText:     '&lsaquo; Prev'
	});
				
	gallery.onFadeOut = function() {
		$('#details').fadeOut('fast');
		$("#gallery_actions").fadeOut('fast');
		$('#slideshow').fadeOut('fast');
	};
				
	gallery.onFadeIn = function() {
		$('#details').fadeIn('fast');
		$('#slideshow').fadeIn('fast');
		$("#gallery_actions").fadeIn('fast');
	};
	
	//gallery.toggleSlideshow();
	
}

function deleteImage(){
	//ask for confirmation. if we get it, post the form after updating the id in the value of the source_id input
	
	var id = $("li.selected a img:first").attr("id").replace("photo_", "");
	
	var source_id = $("#source_id").attr("value", id);
	if(confirm("Are you sure you want to delete this photo?")){
		$("#delete_image_form").submit();
	}
}

function initRatingsBars(){

	var buttons = $(".rating_up a img");
	buttons.each(function(){
	
		$(this).hover(
			function(e){
				$(this).attr("src", "assets/images/rating_bar_plus_solo_hover.png");
			},
			function(e){
				$(this).attr("src", "assets/images/rating_bar_plus_solo.png");
			}
		
		);
		
		$(this).mousedown(
			function(e){
				$(this).attr("src", "assets/images/rating_bar_plus_solo_active.png");
			}
		);
		
		$(this).mouseup(
			function(e){
				$(this).attr("src", "assets/images/rating_bar_plus_solo.png");
			}
		);
	
	});
	
	var buttons = $(".rating_down a img");
	buttons.each(function(){
	
		$(this).hover(
			function(e){
				$(this).attr("src", "assets/images/rating_bar_minus_solo_hover.png");
			},
			function(e){
				$(this).attr("src", "assets/images/rating_bar_minus_solo.png");
			}
		
		);
		
		$(this).mousedown(
			function(e){
				$(this).attr("src", "assets/images/rating_bar_minus_solo_active.png");
			}
		);
		
		$(this).mouseup(
			function(e){
				$(this).attr("src", "assets/images/rating_bar_minus_solo.png");
			}
		);
	
	});

	var ratingsBars = $('.ratingBar');
	
	ratingsBars.each(function(){
		countProcedures++;
		var bar = $(this).find('div.review_rating');
		var number = $(this).find('div.review_rating_indicator');
		var currentNumber = parseInt( $(number).html() );
		var progressBar = $(this).find('div.progressBar');
		
		var options = $(this).find('select option');
		var rating_up = $(this).find('.rating_up a');
		var rating_down = $(this).find('.rating_down a');
		var this_id = $(this).attr('id');
		
			rating_up.click(function(e){
				e.preventDefault();
				e.stopPropagation();
				var new_number = parseInt($(number).html()) + 1;
				
				if(this_id == "review_form_rating_price"){
				
					if(new_number > 5){
						return;
					}
					
				}
				
				if(new_number > 10){
					return;
				}
				
				number.html(new_number);
				$(progressBar).removeClass();
				$(progressBar).addClass('progressBar');
				var prefix = "";
				if(this_id == "review_form_rating_price"){
					prefix = "_price";
				}
				$(progressBar).addClass('progress' + prefix + new_number);
				$(options).attr("selected", false);
				options.each(function(i, val){
					
					if(i == new_number - 1){
						$(this).attr("selected", true);
					}
				
				});
				
			});
			
			rating_down.click(function(e){
				e.preventDefault();
				e.stopPropagation();
				var new_number = parseInt($(number).html()) - 1;
				
				if(new_number == 0){
					return;
				}
				
				number.html(new_number);
				$(progressBar).removeClass();
				$(progressBar).addClass('progressBar');
				if(this_id == "review_form_rating_price"){
					new_number = "_price" + new_number;
				}
				$(progressBar).addClass('progress' + new_number);
				
				$(options).attr("selected", false);
				options.each(function(i, val){
				
					if(i == new_number - 1){
						$(this).attr("selected", true);
					}
				
				});
				
			});
		
		
	});
	
	var clickable = $("#review_form .progressBar");
	clickable.each(function(){
		
		var parent = $(this).parents(".review_rating");
		var type = $(this).parents(".ratingBar");
		
		if($(type).hasClass('review_form_rating_price')){
		
			$(this).click(function(e){
				var width = $(this).width() - 42;
				var x = e.pageX - $(this).offset().left - 21;
				var percentage = 5 * x / width;
				
				var rating = Math.round(percentage) - 1;
				
				if(rating > 0 && rating < 5) {
					var indicator = $(parent).find(".review_rating_indicator").html(rating);
					$(parent).find('.rating_up a').trigger('click');
				}
				
				if(rating == 0){
					rating = 2;
					var indicator = $(parent).find(".review_rating_indicator").html(rating);
					$(parent).find('.rating_down a').trigger('click');
				} 
				
			});
		
		} else {
		
			$(this).click(function(e){
				var width = $(this).width() - 42;
				var x = e.pageX - $(this).offset().left - 21;
				var percentage = 10 * x / width;
				
				var rating = Math.round(percentage) - 1;
				
				
				if(rating > 0 && rating < 10) {
					var indicator = $(parent).find(".review_rating_indicator").html(rating);
					$(parent).find('.rating_up a').trigger('click');
				}
				
				if(rating == 0){
					rating = 2;
					var indicator = $(parent).find(".review_rating_indicator").html(rating);
					$(parent).find('.rating_down a').trigger('click');
				} 
				
			});
		
		}
		
	
	});

}

function initBlockUI(){
	
}

function cleanBookmarks(target){

	var bookmarks = $(target).find(".bookmark_link");
	
	if(bookmarks.length == 0){
		$('.bookmarks_list_bookmark').hide();
		$('.bookmarks_list_nobookmark').show();
	}

}

/*
function initGmaps(){

	if(gmarkers.length > 0){
		gmarkers[0].openInfoWindowHtml(htmls[0]);
	}
		
}
*/

function createMarker(point,html,showOrHide) {
        var marker = new GMarker(point);
        
        // ========== Open the ew instead of a Google Info Window ==========
        GEvent.addListener(marker, "click", function() {
          ew.openOnMarker(marker,html);
        });
        
        if(showOrHide == "show"){
          ew.openOnMarker(marker,html);
        }
        
        return marker;
      }


function window_popup(title, url, img, food, service, ambiance, price, district, cuisine) {

		if(food != "0"){

		return '<div class="map_popup">' +
        		'<img width="65px" src="' + img + '" />' +
				'<h3>' + title + '</h3>' +
				'<p>Cuisine: <span class="map_popup_p_bold">' + cuisine + '</span></p>' +
				'<p>Location: <span class="map_popup_p_bold">' + district + '</span></p>' +
				'<a class="closer" href="javascript:ew.hide()">Close</a>' +
				'<ul class="rating_gmaps_list_1">' +
				'<li class="rating_gmaps"><span class="rating_gmaps_description_food">Food:</span><span class="rating_mini_' + food + ' rating_score">' + food + '</span></li>' +
				'<li class="rating_gmaps"><span class="rating_gmaps_description_service">Service:</span><span class="rating_mini_' + service + ' rating_score">' + service + '</span></li>' +
				'</ul>' +
				'<ul class="rating_gmaps_list_2">' +
				'<li class="rating_gmaps"><span class="rating_gmaps_description_atmo">Ambiance:</span><span class="rating_mini_' + ambiance + ' rating_score">' + ambiance + '</span></li>' +
				'<li class="rating_gmaps"><span class="rating_gmaps_description_price">Price:</span><span class="rating_price_mini_' + price + ' rating_score">' + price + '</span></li>' +
				'</ul>' +
				'</div>';
		} else {
		
		return '<div class="map_popup">' +
        		'<img width="65px" src="' + img + '" />' +
				'<h3>' + title + '</h3>' +
				'<p>Cuisine: <span class="map_popup_p_bold">' + cuisine + '</span></p>' +
				'<p>Location: <span class="map_popup_p_bold">' + district + '</span></p>' +
				'<a class="closer" href="javascript:ew.hide()">Close</a>' +
				'</div>';
		
		}

}
//'<a href="' + url + '">view details</a>' +

//


function cleanAddress(address){
	//this will make sure that 'hong kong' exists in the address
	var regEx = /Hong Kong/;
	if(address.search(regEx) < 0){
		address = address + " Hong Kong";
	}
	
	return address;
}

function showCoords(coords, info, ratings, showOrHide) {
	
	map.addOverlay(ew);
	coords = coords.split(",");
	
	var point = new GLatLng(parseFloat(coords[0]), parseFloat(coords[1]));
	
	
	
		if (!point) {
        		        		
        		$("#map").hide();
        		var thumbs = $(".venue_image_carousel_thumb_image");
        		if(thumbs.length == 0){
        			$("#venue_image_carousel").hide();
        		}
        		
      		} else {
      			
       			map.setCenter(new GLatLng(parseFloat(point.lat()) + 0.001, parseFloat(point.lng()) + 0.00015 ), 17);
        		
        		
        		//var point_marked = new GLatLng(point);
      			var html = window_popup(info[0], info[1], info[2], ratings[0], ratings[1], ratings[2], ratings[3], info[3], info[4]); 
      			
      			
      			var marker = createMarker(point,html,showOrHide);
     			map.addOverlay(marker);
				
        		//marker.openInfoWindowHtml(address);
        		
    	}
      	
}

function showAddress(address, info, ratings, showOrHide) {
	
	address = cleanAddress(address);
	
	var geocoder = new GClientGeocoder();
	
	map.addOverlay(ew);
	
	geocoder.getLatLng(
		address,
		
		function(point) {
			if (!point) {
        		//show hong kong at bare min
        		//fire off an ajax request to log the error
        		
        		$("#map").hide();
        		var thumbs = $(".venue_image_carousel_thumb_image");
        		if(thumbs.length == 0){
        			$("#venue_image_carousel").hide();
        		}
        		
      		} else {
      			
       			map.setCenter(new GLatLng(point.lat() + 0.001, point.lng() + 0.00015 ), 17);
        		
        		//var point_marked = new GLatLng(point);
      			var html = window_popup(info[0], info[1], info[2], ratings[0], ratings[1], ratings[2], ratings[3], info[3], info[4]); 
      			var marker = createMarker(point,html, showOrHide);
     			map.addOverlay(marker);
				
        		//marker.openInfoWindowHtml(address);
      		}
		}
	);
}



function initBookmarks(){

	var deleteButtons  = $('.deleteBookmark');
	
	deleteButtons.each(function(){
		countProcedures++;
		$(this).click(function(e){
		
			e.preventDefault();
			var delete_id = $(this).attr("id").replace("delete_", "");
			var url = base_url + "profile/ajax-update/remove-bookmark?&content_id=" + delete_id;
			
			$(this).parents('.bookmark_link').fadeTo('slow', 0);
			var parent = $(this).parents('.bookmarks');
			$(this).parents('.bookmark_link').remove();
			
			$.get(url, function(data){
				
			});
			
			cleanBookmarks(parent);
		});
	
	});

}

function initRestaurantGallery(){

	var thumbs = $(".venue_image_carousel_thumb_image");
	var target = $("#venue_image_carousel_image_active");
	
	thumbs.each(function(){
		countProcedures++;
		$(this).click(function(e){
			
			e.preventDefault();
			
			$(target).empty();
			$(target).append($(this).html());
			$(thumbs).removeClass('venue_image_carousel_thumb_active');
			$(this).addClass('venue_image_carousel_thumb_active');
			$(this).fadeTo("slow", 1);
			fadeThumbs();
		});
	
	});
	
	fadeThumbs();
	
}

function fadeThumbs(){

	var thumbs = $(".venue_image_carousel_thumb_image");
	thumbs.each(function(){
		countProcedures++;
		if(!$(this).hasClass('venue_image_carousel_thumb_active')){
			$(this).fadeTo("slow", 0.33);
		}
	
	});

}



function moveContentToPane(target){

	var child_id = $(target).attr('id').replace("accordion_item_", "accordion_item_child_");
	var targetDiv = $(target).parent().parent().parent().contents().find('div.pane_level_2_content').empty();
	$(targetDiv).append($("#" + child_id).html());

}

function initGalleryOverviewItems(){

	var pane_items = $(".gallery_overview_item");
	var pane_rollovers = $(".gallery_overview_item p").hide();
	
	pane_items.hover(
			function(){
				$(this).addClass('gallery_overview_item_hover');
			},
			function(){
				$(this).removeClass('gallery_overview_item_hover');
			}
	);

}

function initWomChoiceDeeplinks(){

	if(window.location.hash != ""){
	
		
		var showMe = window.location.hash.replace("/", "");
		
		openAccordionAt(showMe);
		
	}

}

function openAccordionAt(selector){


		var parent_blade = $(selector).parents('.pane_level_1').attr('id');
		var blades = $('.pane_level_1');
		blades.each(function(i){
		
			if($(this).attr('id') == parent_blade){
				
				$("#accordion").accordion("activate", i)
			}
		
		});
		
		//.children('.ui-accordion-link').css('border', '1px solid red').trigger('click');
		var target = $(selector);//.trigger('click');
		
		moveContentToPane(target);
				
		var slider = $(target).parents("div.pane_slider");
		
		slideInnerPane(slider, -1, false);

}

function initWomChoiceAccordion(){

	$("#accordion").accordion(
		{
			header: 'a.ui-accordion-link',
  			fillSpace: true
		}
	);
	
	$('.accordion_item_child').hide();
	

	var pane_items = $("div.accordion_item_parent");
	var pane_rollovers = $("div.accordion_item_parent p").hide();
	
	pane_items.each(function(i, element){
	
		
	
		$(element).mouseover(
			function(){
				//$(element).addClass('accordion_item_parent_hover');
				$(element).find('h1').hide();
				$(element).find('p').show();
			}
		);
		
		$(element).mouseout(
			function(){
				//$(element).removeClass('accordion_item_parent_hover');
				$(element).find('h1').show();
				$(element).find('p').hide();
			}
		);
	
		
	
	});
	
	
	
	pane_items.click(function(e){
		window.location.hash = "/" + $(this).attr('id');
		e.preventDefault();
		moveContentToPane(this);
				
		var slider = $(this).parents("div.pane_slider");
		
		slideInnerPane(slider, -1, true);
	
	});
	
	initWomChoiceDeeplinks();
	
}



function slideInnerPane(pane, direction, animate){

	var amount = 489 * direction;

	if(animate){

	if(lockAnimation == 0){
		
		lockAnimation = 1;
		var height = $('table', this).height();
		$(pane).animate(
			{
				left: amount + 'px',
				height: height
			},
			1000,
				function(){
					lockAnimation = 0;
			}
		);
	}
	
	}else{
	
	 $(pane).css('left', amount + "px");
	
	}

	//we're appending html during some slides (best to rebind the events)

}

function initForwardFriend(){

	$('#forward_friend').click(function(e){
		e.preventDefault();
		$(this).parent().append($('#send_to_friend_form'));
		toggleInlinePopup('#send_to_friend_form');
	});
	
	$("#form_send_friend").submit(function(e){
		e.preventDefault();
		var inputs = $("#form_send_friend input.required[value='']");
		
		if(inputs.length > 0){
			
			$(inputs).addClass('prompt');
			
		} else {
			//send_to_friend_form
			$('#send_to_friend_form').block({ 
				message: 'Sending' 
			});
			//post the form
			$.post(send_friend_url, {
				id: $("#doc_id").val(),
				email: $("#send_friendsEmail").val(),
				sendersName: $("#send_sendersName").val(),
				name: $("#send_friendsName").val(),
				post_friend: "post_friend"
			},
				function(data){
				
					$("#form_send_friend").empty().prepend(data);
					$('#send_to_friend_form').unblock();
				}
			
			);
		
		}
		
		var inputs = $("#form_send_friend input.required[value!='']").removeClass('prompt');
		
		
		
		
	});
	
	$('#print_page').click(function(e){
		e.preventDefault();
		window.print();
	});
	
}

function initSiFR(){
	
	/*
sIFR.activate();

	sIFR.replace(vag_std, {
		selector: 'h1.sifr',
		wmmode: 'transparent',
		transparent: true,
		css: {
			'.sIFR-root': { 
				'text-align': 'left','letter-spacing': '0.6','color': '#ca9810','text-transform': 'uppercase','font-family': "VAG Rounded Std Black"
				},
			'.remainingWords': { 
				'color': '#6a6138','font-family': "VAG Rounded Std Light" 
			}
		}
	});

	sIFR.replace(vag_std, {
		selector: 'h2.sifr',
		wmmode: 'transparent',
		transparent: true,
		css: {
			'.sIFR-root': { 
				'text-align': 'left','letter-spacing': '0.6','color': '#6a6138','text-transform': 'uppercase','font-family': "VAG Rounded Std Light" 
			}
		}
	});

	sIFR.replace(vag_std, {
		selector: 'p.homepage_events_date_sifr, p.events_details_month_sifr, p.events_details_day_sifr, p.homepage_events_details_day_sifr, p.homepage_events_details_month_sifr',
		wmmode: 'transparent',
		transparent: true,
		css: {
			'.sIFR-root': { 
				'text-align': 'center','color': '#46100c','font-family': "VAG Rounded Std Black" 
				}
		}
	});
	
	sIFR.replace(vag_std, {
		selector: 'p.homepage_events_details_day_sifr, p.homepage_events_details_month_sifr',
		wmmode: 'transparent',
		transparent: true,
		css: {
			'.sIFR-root': { 
				'text-align': 'center','color': '#8c231c','font-family': "VAG Rounded Std Black" 
				}
		}
	});
	
	sIFR.replace(vag_std, {
		selector: 'p.homepage_events_to_details_day_sifr, p.homepage_events_to_details_month_sifr',
		wmmode: 'transparent',
		transparent: true,
		css: {
			'.sIFR-root': { 
				'text-align': 'center','color': '#3a444b','font-family': "VAG Rounded Std Black" 
				}
		}
	});
	
	sIFR.replace(vag_std, {
		selector: 'h3.sifr',
		wmmode: 'transparent',
		transparent: true,
		// preventWrap: true,
		css: {
			'.sIFR-root': { 
				'text-align': 'left','color': '#3e331a','letter-spacing': '0.6','text-transform': 'uppercase','font-family': "VAG Rounded Std Black" 
			},
			'.remainingWords': { 
				'color': '#3e331a','font-family': "VAG Rounded Std Light" 
			}
		}
	});
*/

}

function initSelectBoxes(target){
	$(target).selectbox({debug: true});
}

function initTabbedDisplays(){

	var tabs = $('a.tabbedDisplayAnchor');
	var targets = $('.tabbedDisplay').hide();
	tabs.each(function(i){
	
	var target_div = $("#" + $(this).attr('id').replace("toggle_", "venue_"));
		//onload, we hide the divs where the tab is inactive
		if($(this).hasClass('active')){
			$(target_div).show();
		}
	
		$(this).click(function(e){
			e.preventDefault();
			//kill all targets!
			$(targets).hide();
			tabs.removeClass('active');
			$(this).addClass('active');
			window.location.hash = "tab=" + $(this).attr('id').replace("toggle_", "");
			//re-init the sifr
						
			$(target_div).show();
			initSiFR();
			
		});
	
	});

}

function initShowHide(){

	var showHides = $('a.showHide');
	var onHides = $('a.showHide span.onHide').hide();
	showHides.each(function(){
		
		$(this).click(function(e){
			e.preventDefault();
			
			var target_div = $("#" + $(this).attr('id').replace("toggle_", "venue_"));
			
			$(this).children('span.onShow').toggle();
			$(this).children('span.onHide').toggle();
			$(target_div).toggle();
			
			
		});
		
	});

}

function initScrollPanes(){

	//$('.scroll-pane').jScrollPane({showArrows:false});

}

function initCarousels(){

	var slider = $('.slider');
	var slideLeft = $('#slideLeft').hide();
	var slideRight = $('#slideRight');
	var highlights = $('.slidingElement');
	var storage = $("#highlightsStorage");
	var initialPadding = 0;
	
	highlights.each(function(i){
		countProcedures++;
		if($(this).hasClass("active")){
			if(i >= 3){
				leftClicks = i - 2;
				initialPadding = (i-2) * 169;
			}
		}
	
	});
	
	highlights.each(function(i){
			countProcedures++;
			var left = (169 * i) - initialPadding;//here
			$(this).css('left', left + "px");
			
	});
	
	if(highlights.length <= 3 || highlights.length == 3 + leftClicks){
		slideRight.hide();
	}
	
	if(leftClicks > 0){
		slideLeft.show();
	}
	
	
	
	initialiseSlider();
}

function initialiseSlider(){

	var slider = $('.slider');
	var slideLeft = $('#slideLeft');
	var slideRight = $('#slideRight');
	var highlights = $('.slidingElement');
	var storage = $("#highlightsStorage");
	countProcedures++;
	$(slideRight).click(function(e){
		
		e.preventDefault();
		
		if(lockAnimation == 0){
			
			if(leftClicks + 3 < highlights.length){
			
			leftClicks++;
			//alert(leftClicks);
				if(leftClicks == highlights.length - 3){
					//disable/hide it.
					slideRight.hide();
				}
				
				if(leftClicks > 0){
					slideLeft.show();
				}
			
			lockAnimation = 1;
			
			highlights.each(function(i){
				
				var amount = parseInt($(this).css('left').replace("px", "")) - 169;
				
					$(this).animate(
						{
							left: amount + 'px'
						},
						1000,
						function(){
							if(i == 0){
								initialiseSlider();
							}
							lockAnimation = 0;
						}
					);	
			});
			
			}
		}
		
	});
	$(slideLeft).click(function(e){
		
		e.preventDefault();
		
		if(lockAnimation == 0){
			
			if(leftClicks > 0){
			
			leftClicks--;
			
				if(leftClicks == 0){
					//disable/hide it.
					slideLeft.hide();
				}	
				
				if(leftClicks > 0){
					slideRight.show();
				}
			
			lockAnimation = 1;
			
			highlights.each(function(i){
				
				var amount = parseInt($(this).css('left').replace("px", "")) + 169;
				
					$(this).animate(
						{
							left: amount + 'px'
						},
						1000,
					function(){
							if(i == 0){
								initialiseSlider();
							}
							lockAnimation = 0;
						}
					);
				
					
			});
				//$(slideLeft).unbind('click');
			}
		}
		
		
	});
	

}

function initEqualHeight(){

	equalHeight('.tabbedDisplay');
	
}

function equalHeight(selector){

	var parents = $(selector);
	
	var TallestHeight = 0;
	
	parents.each(function(){
	
		if($(this).height() > TallestHeight){
			TallestHeight = $(this).height();
		}
	
	});
		
	parents.css('height', TallestHeight + "px");

}

function alphaOnly(evt) 
{ 
	
    var charCode = (evt.which) ? evt.which : window.event.keyCode; 

		
    if ((charCode <= 13) || (charCode == 222) || (charCode == 46) || (charCode == 224)) 
    { 
        return true; 
    }
    else 
    { 
        var keyChar = String.fromCharCode(charCode); 
        var re = /[a-zA-Z]/ 
        return re.test(keyChar); 
    } 
}

var hasFocus = 0;
var doLiveSearchInterval;

function arrowKeyHandler(direction){
	
	/*
var results = $("#live_search .venue_item");
	var currentlySelected = -1;
	
	$(results).each(function(i){
	
		if($(this).hasClass('selected')){
			//$(this).removeClass('selected');
			currentlySelected = i;
		}
	
	});
	
	switch(direction){
	
		case 1:
			$(results).removeClass('selected');
			if(currentlySelected == -1 || currentlySelected == results.length - 1){
				$("#live_search .venue_item:eq(0)").addClass('selected');
			} else {
				var newlySelected = 1 + currentlySelected;
				$("#live_search .venue_item:eq(" + newlySelected + ")").addClass('selected');
			}
			
		break;
		
		case -1:
			$(results).removeClass('selected');
			if(currentlySelected == -1 || currentlySelected == 0){
				var newlySelected = results.length - 1;
				$("#live_search .venue_item:eq(" + newlySelected + ")").addClass('selected');
			} else {
				var newlySelected = -1 + currentlySelected;
				$("#live_search .venue_item:eq(" + newlySelected + ")").addClass('selected');
			}
			
		break;
	
	}
*/
	
	
	
}

function initQuickSearch(){

	var firstOption = $('#search_location option:first');
	$(firstOption).attr('value', "");
	//kill the value of the first input option JUST IN CASE
	
	var dontsubmit = 0;
	
	$('#search_name_cuisine').keyup(function(e){
		
		
			
		
		switch(e.keyCode){

			case 40:
				arrowKeyHandler(1);
				dontsubmit = 1;
				break;
				//that's down
			case 38:
				arrowKeyHandler(-1);
				dontsubmit = 1;
				break;
				//that's down
			case 13:
				dontsubmit = 1;
			
			default:
				//nothing for now.
				dontsubmit = 0;
				break;

		}
		
		if(e.which == 13){
			//submit it
			submitQuickSearch();
			dontsubmit = 1;
		}
		
		if(alphaOnly(e) && dontsubmit == 0){
		
			//delay this, we dont want to immediately search
			clearInterval(doLiveSearchInterval);
			doLiveSearchInterval = setTimeout("doLiveSearch()", 250);
			show_dropdown();
		}

		
	});
	
	$('#search_name_cuisine').focus(
		function(){
			hasFocus = 1;
			show_dropdown();
		}
	);
	
	$('#search_name_cuisine').blur(

		function(){
			hasFocus = 0;
			//hide_dropdown();	
		}
	
	)
	
	$('#quick_search_toolbar').hover(
		function(){
		
		},
		function(){
				
			if(hasFocus == 0){
			
				hide_dropdown();
				
			}
		}
	);
	
}

function initSpellSuggestions(){
	var link = $(".spelling_suggestion a:first");
	link.click(function(e){
	
		e.preventDefault();
		$('#search_name_cuisine').val($(this).html());
		doLiveSearch();
	});
}

function show_dropdown(){
	$('#live_search').removeClass('hidden');

}

function hide_dropdown(){
	$('#live_search').addClass('hidden');
}

function doLiveSearch(){
	var search = encodeURIComponent($('#search_name_cuisine').attr("value"));
	var searchQuery = base_url + "search/ajax-live/?&search=" + search + "&venue_district=" + $("#search_location").attr("value");
	
	$('#live_search').block({ 
		message: 'Loading Search Results' 
	});
	
	$.get(searchQuery, function(data){
		$('#live_search').empty();
		$('#live_search').append(data);
		$('#live_search').unblock();
		show_dropdown();
		initSpellSuggestions();
	});

}

function submitQuickSearch(){
	
	var selected = $("#live_search .selected a");
	if(selected.length == 1){
	
		var goto = $(selected).attr('href');
		$(selected).parents('.venue_item').removeClass('selected')
		window.location.href = goto;
	} else {
	
		$("#quick_search").submit();
	
	}

}

function initInlinePopups() {

	var popups = $(".inlinePopup");
	popups.each(function(){
		countProcedures++;
	
	});
	
}

function toggleInlinePopup(target) {
	$(target).toggleClass('displayBlock');
	return false;
}

function initClosers() {

	var closers = $(".closeParent");
	closers.each(function(){
		countProcedures++;
		$(this).click(function(e){
			e.preventDefault();
			if($(this).hasClass('closeParent')){//in those cases where we've removed it!
			
				var parents = $(this).parents();
				parents.each(function(){
					
					if($(this).hasClass('inlinePopup')){
						$(this).removeClass('displayBlock');
						return;
					}
				});
			
			}
			
		});
			
	});
	
}

function unbindEvents(selector, event){
	$(selector).unbind('click');
}


function initTabs(){
   
	var carousels = $('.carousel_holder');
	
	carousels.each(function(){
		countProcedures++;
		 var panes = $("#" + $(this).attr('id') + ' .tab-pane .inactive_img a');
		 var contents = $("#" + $(this).attr('id') + ' .carousel_content');
		 var hidden_holder = $("#" + $(this).attr('id') + ' .carousel_hidden_holder');
		 var mask_one = $("#" + $(this).attr('id') + ' .carousel_mask_one');
		 var mask_two = $("#" + $(this).attr('id') + ' .carousel_mask_two');
		 
		 
		 //hide all after the first...
		 panes.each(function(i){
				countProcedures++;
				if(i > 0){
		 			//$(contents[i]).css('display', 'none');
		 			$(hidden_holder).append($(contents[i]));
		 		}else{
		 			$(mask_one).append($(contents[i]));
		 			$(this).parent().parent().addClass('active');
		 		}
		 		
		 		$(this).click(function(e){
		 		
		 			e.preventDefault();
		 		
		 			if(lockAnimation == 0){
		 				
		 				lockAnimation = 1;//LOCK IT!
		 				
		 				if($(this).hasClass('active')){
		 					//dont do anything
		 				}else{
		 					panes.parent().parent().removeClass('active');
		 					$(this).parent().parent().addClass('active');
		 					
		 					if($(mask_one).hasClass('onDisplay')){
		 						//we're sliding out mask one.
		 						$(mask_one).removeClass('onDisplay');
		 						$(mask_two).addClass('onDisplay');
		 						var slideOut = mask_one;
		 						var slideIn = mask_two;
		 					} else if($(mask_two).hasClass('onDisplay')){
		 						//we're sliding out mask two.
		 						$(mask_two).removeClass('onDisplay');
		 						$(mask_one).addClass('onDisplay');
		 						var slideOut = mask_two;
		 						var slideIn = mask_one;
		 					}
		 					
		 					//mask two should be empty...
		 					$(slideIn).append($(contents[i]));
		 					//slide the currently open mask to the left
		 					
		 					animateAfterClick(slideOut, slideIn, "-500px");
		 					
		 					
		 					//move the content element into the off page mask
		 					var children = $(slideOut).children('div.carousel_content');
		 					setTimeout(function(){ 
		 						children.each(function(){
		 							$(hidden_holder).append($(this));
		 						});
		 					}, 1000);
		 					
		 					
		 					//move the off screen mask to the right, and remove the html from it
		 				}
		 			
		 			}
		 			
		 			//contents.css('display', 'none');
		 			//$(contents[i]).css('display', 'block');
		 			
		 			
		 		});
		 		
		 		
		 });

	});
	
	//ie6 needs us to redraw
	$(".callout_left_column_end").css("height", "auto");
	$("#your_opinion_counts").css("height", "auto");
	
	
	
	  
}

function initInitialTabState(){

	//get the hash
	var hash = window.location.hash;
	if(hash != "#" && hash.length > 0){
		hash = hash.split("#");
		var key = hash[1];
		
		tokens = key.split("/");
		for(var x = 0; x < tokens.length; x++){
			
			if(tokens[x].indexOf("tab=") >= 0){
				target_div = tokens[x].replace("tab=", "");
				$("#toggle_" + target_div).trigger('click');
			}
			
			if(tokens[x].indexOf("click=") >= 0){
				target_div = tokens[x].replace("click=", "");
				$("#" + target_div).trigger('click');
			}
		
		}
	}
	

}

function randomToN(maxVal,floatVal)
{
   var randVal = Math.random()*maxVal;
   return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

function clickRandomList(){
	var list_number = randomToN(4);
	$("#listToggler ul li a:eq(" + list_number + ")").trigger('click');
}


function initListTogglers(){

	var togglers = $("#listToggler ul li a");
	var hidden_div = $("#listTogglerHider");
	var visible_area = $("#top10_visible_list .top10_list");
	var title = $("#left_column_headline_top10 p");
	
	togglers.each(function(){
		countProcedures++;
		var target_id = $(this).attr('id').replace('toggle_', "");
		
		$(this).click(function(e){
			e.preventDefault();
			if($(this).hasClass('active')){
				//do nothing 
			}else{
				togglers.removeClass('active');
				togglers.removeClass('closeParent');
				togglers.unbind('click');
				
				//move the current div inside the shown area to the hidden div
				var children = visible_area.children('div.feature_list_top10_list');
				children.each(function(){
		 			$(hidden_div).append($(this));
		 		});
		 		
		 		//alert(target_id);
		 		
		 		$(visible_area).append($("#" + target_id));
				//pull the target div into the show area
				
				$(this).addClass('active');
				$(this).addClass('active closeParent');
				
				var text = $(this).text().replace('Top 10 ', '');
				$(title).empty().html(text);
				
				initListTogglers();	
				initClosers();
				//assume the scroller needs reinitialising too...
			}
		
			initScrollPanes();
		
		});
		
	
	});

}


function initInputHover(){

	var hasBgInputs = $('.hasBgText');
	
	hasBgInputs.each(function(){
		countProcedures++;
		if(this.value != ""){
			$(this).addClass('noBackground');
		}
		
		$(this).focus(function(){
			$(this).addClass('noBackground');
		});
		
		$(this).blur(function(){
			if(this.value == ""){
				$(this).removeClass('noBackground');
			}
		});
	
	});

}

$.fn.hoverClass = function(c) {
    return this.each(function(){
        $(this).hover( 
            function() { $(this).addClass(c);  },
            function() { $(this).removeClass(c); }
        );
    });
}; 

function initNavigation(){
	
	$("#navigation > li").hoverIntent(
        function(){ 
        	//alert('hovered');
        	$(this).addClass('sfHover');
           	hide_dropdown();
        }, 
        function() { 
        	$(this).removeClass('sfHover');
        } 
    );
    
   $("input").hover(
        function(){
        	$("#navigation li").removeClass('sfHover');
        }, 
        function() { } 
    );
}

function resizeMenu(){

	//alert($("#mask_one").height());

	if( $("#mask_one").height() > $("#slider").height() ) {
	
		$("#slider").css('height', $("#mask_one").height() + 165 );
		
	}
	
	if( $("#mask_two").height() > $("#slider").height()) {
	
		$("#slider").css('height', $("#mask_two").height() + 165 );
		
	}
	
	if( $("#ajax_update").height() > $("#slider").height() ) {
	
		$("#slider").css('height', $("#ajax_update").height());
		
	}
}

function initBookmarkedSearches(){
	//it's gonna load up a 'bookmarked' search
	
	if(location.hash.substring(1, 9) == "bookmark"){  
		window.location.href = location.hash.substring(1).replace("bookmark_", "");
	}
	
}


function initDrilldownMenu(){

	var checkboxes = $('#venue_search label input');

	
	//this is for fucking shite ie
	if($.browser.msie){
		var checkbox_labels = $('#venue_search label .label');
			checkbox_labels.each(function(i, val){
				countProcedures++;
				$(this).click(function(e){
					$(checkboxes).eq(i).trigger('click');
				});
		});
	}
	
	resizeMenu();
	
	checkboxes.each(function(){
		countProcedures++;
		
		var label = $(this).parent();
		var fieldset = $(label).parent();
		
		if($(this).attr("checked") == true){
			
			if($(this).parent().hasClass('selected')){
				venue_search_options.push($(this).attr("name").replace("[]", ""));
				venue_search_options_checked.push( $(this).parent().find('.label').html() );
				venue_search_checkbox_ids.push($(this).attr("id"));
				venue_search_fieldset_ids.push($(fieldset).attr("id"));
			}else{
				//browser is being a pain
				$(this).attr("checked", false);// = false;
				//bugfix flag
			}
		}
	//why is this here?
	initSearchCrumbs();
		
		$(this).click(
			function(){
				countProcedures = 0;
				resetCheckboxes("#" + $(fieldset).attr("id"));
				removeDuplicateCrumbs($(this).attr("name"));
				
				label.addClass('selected');
				$(this).checked = true;
				venue_search_options.push($(this).attr("name").replace("[]", ""));
				venue_search_options_checked.push( $(this).parent().find('.label').html() );
				venue_search_checkbox_ids.push($(this).attr("id"));
				venue_search_fieldset_ids.push($(fieldset).attr("id"));
				
				initSearchCrumbs();
				doAjaxSearch();
				rebuildLegends();
				animateAfterClick("#mask_two", "#mask_one", "-180px");
				
				//move mask one to the right...
				//alert(countProcedures);
			}
		);
	
	});
	
	//onload
	showLegends();
	initReOrder();
	initLegends();
	initPaginationLinks();

	initSearchCrumbs();
	initBacktracks();
	
}

function initLegends(){

	var legends = $('#venue_search fieldset legend span');

	legends.each(function(){
		countProcedures++;
		$(this).click(
			function(){
				//slide out the legends somehow...
				animateAfterClick("#mask_two", "#mask_one", "-180px");
			}
		);
	});

}

/* initialise these properly */
var sortOrder = 'asc';
var defaultOrder = 'asc';
var sortBy = '_relevancy_';
var searchOrder = "&sortOrder=" + sortOrder + "&sortBy=" + sortBy;
var start = "start=0";

function initReOrder(){

	var orderingLinks = $("#sort_results li a");
	orderingLinks.each(function(){
		countProcedures++;
			$(this).click(function(e){
			
			e.preventDefault();
			
			orderingLinks.removeClass('asc');
			orderingLinks.removeClass('desc');
			
				var wasSortingBy = sortBy;
			
				sortBy = $(this).attr('id').replace("reorder_", "");

				if($(this).attr('id') == 'reorder_relevancy'){
					sortBy = '_relevance_';
					sortOrder = '';
				}

				searchOrder = "&sortOrder=" + sortOrder + "&sortBy=" + sortBy;
				
				$(this).addClass(sortOrder);
				
				if(sortOrder == "asc"){
					sortOrder = "desc";
				} else {
					sortOrder = "asc";
				}
				
				if(wasSortingBy == sortBy){
					//do nothing
				} else {
					//we just clicked a new order, so sortOrder should default back to the original.
					sortOrder = defaultOrder;
				}
				
				doAjaxSearch();
				
			});
	
	});

}

function doAjaxSearch(startQuery){
	
	
	
	if(typeof startQuery == "undefined"){
		startQuery = "start=0"
	}
	
	var searchWords = $("#search_words").val();
	//var searchWords = $("#query_words a.query_words_content").text();
	
	var searchQuery = base_url + "search/ajax/?" + searchOrder + "&do_search=1&search=" + searchWords + "&" + startQuery;
	
	if(character != ""){
		searchQuery += "&character=" + character;
	}
	
	jQuery.each(venue_search_options_checked, function(i, val){
		countProcedures++;
		if(val != ""){
			val = $("#" + venue_search_checkbox_ids[i]).attr('value');
			searchQuery += "&" + venue_search_options[i] + "=" + val;
		}
	});
	
	if($("#ajax_update").length == 0){
		//we're going to need to reload the page
		window.location.href = searchQuery.replace("ajax/", "");
	}
	
		$('#venue_breadcrumb').block({ 
			message: 'Loading Search Results' 
		});
	
		updateHash("bookmark_" + searchQuery);
	
		$.get(searchQuery, function(data){
			$('#ajax_update').empty();
			$('#ajax_update').append(data);
			$('#venue_breadcrumb').unblock();
			initSearchCrumbs();
			initBacktracks();
			initReOrder();
			resizeMenu();
			initPaginationLinks();
		});
	
}

function updateHash(hash_string){
	hash_string = hash_string.replace("ajax/", "");
	location.hash = hash_string;
}

function resetCheckboxes(target){
	
	var checkboxes = $(target+ " input");
	checkboxes.each(function(){
		$(this).checked = false;
		$(this).parent().removeClass('selected');
		countProcedures++;
	});
	
}

function removeDuplicateCrumbs(targetIndex){

	jQuery.each(venue_search_options, function(i, val){
	
		if(val == targetIndex){
			spliceIndex(i);
		}
		countProcedures++;
	});

}


function spliceIndex(i){
	venue_search_options.splice(i, 1);
	venue_search_options_checked.splice(i, 1);
	venue_search_checkbox_ids.splice(i, 1);
	venue_search_fieldset_ids.splice(i, 1);
	
}

function rebuildLegends(){
	
	$('#legends').empty();
	$('#legends').append($("#selector_tooltip"));
	var sorted = venue_search_fieldset_ids;
	
	
	var fieldsets = $("#venue_search fieldset");
	fieldsets.each(function(i){
		countProcedures++;
		var this_id = $(this).attr('id');
		if(jQuery.inArray(this_id, sorted) == -1){
			var list_item = "<label id='target_" + this_id + "'>" + $("#" + this_id + " > legend").html() + "</label>";
			$('#legends').append(list_item);
		}
		countProcedures++;
	});
	
	
	//now initialise the clicks on them.
	var legends = $("#legends label");
	var ids = new Array();
	var counter = 0;
	legends.each(function(){
		countProcedures++;
		
		ids[counter] = $(this).attr('id');
		counter++;
		$(this).click(
			function(){
				//remove the mask two shit - put into the holder
				$("#onload_holder").append($('#mask_two fieldset'));
				var target_fieldset = $(this).attr("id").replace("target_", "");
				
				//dump the target fieldset into mask two, 
				$("#mask_two").append($("#" + target_fieldset));
				//slide in mask two...
				animateAfterClick("#mask_one", "#mask_two", "-180px");
				//move mask one to the right...
			}
		);
	
	});
	
	ids = ids.sort();
	ids = ids.reverse();
	
	for(var x_index = 0; x_index < ids.length; x_index++){
	
		$('#legends').prepend($("#" + ids[x_index]));
	
	}
	
	//now sort the legends?
	
	
}

function initPaginationLinks(){

	
	
	var paginationLinks = $("#pagination_bar li a");
	var activeLink = $("#pagination_bar li a.active:last");
	
		paginationLinks.each(function(){
			countProcedures++;
			$(this).click(function(e){
				e.preventDefault();
				
				if($(this).hasClass('active')){
				//ignore please.
				} else {
				
					if($(this).parent().attr("id") == "next"){
						var number = parseInt($('#pagination_bar li a.active:last').html());
						var startQuery = number * 10;
						startQuery = "start=" + startQuery;
						//do ajax search. need to tell it which page to start from though!
						doAjaxSearch(startQuery);
						return;
					} else if($(this).parent().attr("id") == "last"){
						//alert($(activeLink).parent().attr('id'));
						var number = parseInt($('#pagination_bar li a.active:last').html());
						var startQuery = (number - 2) * 10;
						startQuery = "start=" + startQuery;
						//do ajax search. need to tell it which page to start from though!
						doAjaxSearch(startQuery);
						return;
					} else {
				
						var startQuery = (parseInt( $(this).parent().attr("id").replace("page_", "") ) - 1) * 10;
									
						//this is shit
				
						startQuery = "start=" + startQuery;
						//do ajax search. need to tell it which page to start from though!
						doAjaxSearch(startQuery);
						}
				
				
				}
			
			});
		
			
			
		});
		
		
		var bottomPagination = $("#pagination_bottom li a");
		
		bottomPagination.each(function(i, val){
			
			$(this).click(function(e){
				e.preventDefault();
				
				$("#pagination_bar li a:eq(" + i + ")").trigger('click');
				$.scrollTo(0, 800, {easing:'easeOutExpo'});
			});
		
		});
	
}

function animateAfterClick(slideOutTarget, slideInTarget, amount){
		
		resizeMenu();
		
		$(slideInTarget).animate(
				{
					left: '0px'
				},
				1000	
		);			
			
		$(slideOutTarget).animate(
				{
					left: amount
				},
				1000,
				function(){
					rehide(slideOutTarget, amount);
					lockAnimation = 0;
				}
		);
		
		
	
}

function rehide(target, amount){
	
	amount = parseInt(amount) * -1;

	$(target).css('left', amount + "px");
	lockAnimation = 0;
}

function showLegends(){
	
		rebuildLegends();
		
		$('#mask_one').append($("#legends"));
}


function initBacktracks(){

	var crumbs = $('#search_crumbs li');
		
	crumbs.each(function(i){
		countProcedures++;
		$(this).addClass('clickable');
		
		if(crumbs.length == i+1){
			//make this appear 'clickable'
			$(this).addClass('clickable');
		}
		
		$(this).click(
		
			function(){
				if($(this).hasClass('clickable')){
					var checkbox = $("#" + venue_search_checkbox_ids[i]);
					resetCheckboxes("#" + $(checkbox).parent().parent().attr("id") );
					//resetCheckboxes
					spliceIndex(i);
					rebuildLegends();
					initSearchCrumbs();
					doAjaxSearch();						
				}
			}
			
		);
	
	});
	
	var secondary_crumbs = $("#search_query ul li a.query_words_delete");
		
	if(secondary_crumbs.length == 0){
		$('#search_query_wrapper').hide();
	}
	
	secondary_crumbs.each(function(i, val){
		countProcedures++;
		$(this).click(function(e){
			e.preventDefault();
			//fire a click on the primary crumb
			var target_id = $(this).parent().attr("id").replace("query_", "");
			
			if(target_id == "words"){
				$('#search_words').val('');
				doAjaxSearch();
				
			}else{
				target_id = "#venue_" + target_id;
				$(target_id).trigger('click');
			}		
			
		});
	
	});
	
}

Array.prototype.sum = function() {
	var sum = 0;
	for(i = 0; i < this.length; i++){
	
		sum += parseInt(this[i]);
	
	}
   	return sum;
};


function initSearchCrumbs(){
	$('#search_crumbs').empty();
	
	var index = 0;
	jQuery.each(venue_search_options_checked, function(i, val){
		countProcedures++;
		if(val != ""){
			var itemLabel = $("#fieldset_" + venue_search_options[i].replace("venue_", "") + " legend span").html();
			var list_item = "<li class='crumb_" + i + "' id='" + venue_search_options[i] + "'><label>" + itemLabel + "</label><span>" + val + "</span></li>";
			$('#search_crumbs').append(list_item);
		}
	});
	
	
	
}

jQuery.fn.log = function (msg) {
  console.log("%s: %o", msg, this);
  return this;
};

function hideNotInArray(id_array, counter_array, fieldset_target){

	if(id_array.length == 1 && id_array[0] == ""){
		return;
	}

	var checkboxes = $(fieldset_target + " input");
	
	checkboxes.each(function(i){
		countProcedures++;
		if(jQuery.inArray($(this).attr('id'), id_array) == -1){
			//so it is not found by now
			$(this).parent().css('display', 'none');
		}else{
			//append the count to the label
			$(this).parent().css('display', 'block');
			//kill any current spans
			$(this).parent().children(".count").remove();
			$(this).parent().append("<span class='count'>" + counter_array[jQuery.inArray($(this).attr('id'), id_array)] + "</span>");
		} 
	
	});
	
	var ranges = Array("fieldset_rating_food", "fieldset_rating_service", "fieldset_rating_ambiance");
	
	for(var d = 0; d < ranges.length; d++){
		
		if("#" + ranges[d] == fieldset_target){
			
			//'grow' each number cumulatively in reverse
			var counts = $(fieldset_target + " span.count");
			counts.each(function(i, val){
			
				var aboveMe = $(fieldset_target + " span.count:gt(" + i + ")");//.log();
				var runningTotal = parseInt( $(this).text() ) + 0;
				
				//alert($(this).text());
				
				
				aboveMe.each(function(){
					
					runningTotal = runningTotal + parseInt($(this).text());
				
				});
				
				$(this).html(runningTotal);
				
				
			});
			
		}
		
	}
	
	var counts = $(fieldset_target + " span.count");
	counts.each(function(){
	
		$(this).html( "(" + $(this).text() + ")" );
	
	});

}

// VALIDATION RULES 

/* Venue Registration Form */

$(document).ready(function(){

	$("#venue_registration_form").validate({
		errorPlacement: function(error, element) {
			error.insertBefore( element );
 		},
	
		errorLabelContainer: "#required_venue_registration",
			rules: {
				first_name: { required: true, minlength: 2 },
				last_name: { required: true, minlength: 3 },
				gender: { required: true },
				age_group: { required: true },
				district: { required: true },
				restaurant_name: { required: true, minlength: 2 },
				cuisine: { required: true },
				restaurant_district: { required: true },
				restaurant_address: { required: true },
				restaurant_phone: { required: true },
				restaurant_email: { required: true, email: true }, 
				restaurant_openhours: { required: true },
				reservations_taken: { required: true },
				valet_parking: { required: true },
				nearby_car_park: { required: true, minlength: 2 },
				take_away: { required: true },
				delivery: { required: true },
				creditcard: { required: true },
				bring_wine: { required: true },
				//corkage_fee: { required: function(element) { return ($("#bring_wine").val() != "No" ); } }, 
				outdoor_dining: { required: true },
				photo1: { accept: "JPG|jpg" },
				photo2: { accept: "JPG|jpg" },
				photo3: { accept: "JPG|jpg" },
				photo4: { accept: "JPG|jpg" },
				vericode: { required: true },
				terms_and_conditions: { required: true }
					},
					
			messages: {
				first_name: "Please enter your first name",
				last_name: "Please enter your last name",
				gender: "Please enter your gender",
				age_group: "Please select your age group",
				district: "Please select your district",
				restaurant_name: { required: "Please enter the restaurants name", minlength: "Please enter the restaurants name" },
				cuisine: "Please select your cuisine",
				restaurant_district: "Please select the restaurants district",
				restaurant_address: "Please enter the restaurants address",
				restaurant_phone: "Please enter the restaurants telephone number",
				restaurant_email: { required: "Please enter the restaurants email address", email: "Please enter a valid email address" },
				restaurant_openhours: "Please enter the restaurants opening hours",
				reservations_taken: "Please select an option for reservations taken",
				valet_parking: "Please select an option for valet parking",
				nearby_car_park: "Please enter a nearby car park",
				take_away: "Please select an option for take away",
				delivery: "Please select an option for delivery",
				creditcard: "Please make a selection for credit card",
				bring_wine: "Please make a selection for BYOW",
				//corkage_fee: "Please enter a corkage fee",
				outdoor_dining: "Please select an option for outdoor dining",
				photo1: "Please make sure your image is of .jpg format",
				photo2: "Please make sure your image is of .jpg format",
				photo3: "Please make sure your image is of .jpg format",
				vericode: "Please enter the security code from the image above",
				terms_and_conditions: "You must agree to the terms &amp; conditions"
						}
	});
});


/* Tell Wom Validation */

$().ready(function() {
	
	$("#tell_wom_form").validate({
		errorPlacement: function(error, element) {
			error.insertBefore( element );
 		},

		rules: {
			your_email: { required: true, email: true },
			your_comments: { required: true, minlength: 5 },
			vericode: { required: true }
		},
				
		messages: {
			your_email: { required: "Please enter your email address", email: "Please enter a valid email address" },
			your_comments: { required: "Please enter your comments", minlength: "Please enter your comments" },
			vericode: "Please enter the code above"
		}
	});
});


/* Advertise on WOM */

$(document).ready(function() {
		$("#advertise_form").validate({
			errorPlacement: function(error, element) {
				error.insertBefore( element );
 			},

 			rules: {
				first_name: { required: true, minlength: 2 },
				last_name: { required: true, minlength: 3 },
				email: { required: true, email: true },
				vericode: { required: true }
			},

			messages: {
				first_name: { required: "Please enter your first name", minlength: "Please enter your first name" },
				last_name: { required: "Please enter your last name", minlength: "Please enter your last name" },
				email: { required: "Please enter your email address", email: "Please enter a valid email address" },
				vericode: "Please enter the code above"
			}
	});
});


/* Contact Us Form */

$().ready(function() {
	
	$("#contact_form").validate({
		errorPlacement: function(error, element) {
				error.insertBefore( element );
 		},

		errorLabelContainer: "#required_contact",

		rules: {
			first_name: { required: true, minlength: 2 },
			last_name: { required: true, minlength: 3 },
			email: { required: true, email: true },
			vericode: { required: true }
		},
				
		messages: {
			first_name: { required: "Please enter your first name", minlength: "Please enter your first name" },
			last_name: { required: "Please enter your last name", minlength: "Please enter your last name" },
			email: { required: "Please enter your email address", email: "Please enter a valid email address" },
			vericode: "Please enter the code above"
		}
	});
});


/* Ask A Chef Form */

$().ready(function() {
	
	$("#form_send_chef").validate({
		errorPlacement: function(error, element) {
				error.insertBefore( element );
 		},
		rules: {
			my_question: { required: true, minlength: 4 }
		},
				
		messages: {
			my_question: { required: "Please enter your question", minlength: "Please enter your question" }
		}
	});
});


/* Recommend a Restaurant Form */

$().ready(function() {
	
	$("#recommend_a_restaurant_form").validate({
		errorPlacement: function(error, element) {
				error.insertBefore( element );
 		},

		rules: {
			restaurant_name: { required: true, minlength: 2 },
			restaurant_address: { required: true, minlength: 2 },
			restaurant_cuisine: { required: true, minlength: 1 }
		},
				
		messages: {
			restaurant_name: { required: "Please enter the name of the restaurant", minlength: "Please enter the name of the restaurant" },
			restaurant_address: { required: "Please enter an address", minlength: "Please enter an address" },
			restaurant_cuisine: { required: "Please select the cuisine", email: "Please select the cuisine" }
		}
	});
});

/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Tested with jQuery 1.2.6. On FF 2/3, IE 6/7, Opera 9.2/5 and Safari 3. on Windows.
 *
 * @author Ariel Flesler
 * @version 1.4
 *
 */
 
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'y',
		duration:1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window).scrollable();
	};

	// Hack, hack, hack... stay away!
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn.scrollable = function(){
		return this.map(function(){
			// Just store it, we might need it
			var win = this.parentWindow || this.defaultView,
				// If it's a document, get its iframe or the window if it's THE document
				elem = this.nodeName == '#document' ? win.frameElement || win : this,
				// Get the corresponding document
				doc = elem.contentDocument || (elem.contentWindow || elem).document,
				isWin = elem.setInterval;

			return elem.nodeName == 'IFRAME' || isWin && $.browser.safari ? doc.body
				: isWin ? doc.documentElement
				: this;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this.scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(px)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					Dim = axis == 'x' ? 'Width' : 'Height',
					dim = Dim.toLowerCase();

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[dim]() * settings.over[pos];
				}else
					attr[key] = targ[pos];

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});			
			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};
			function max( Dim ){
				var attr ='scroll'+Dim,
					doc = elem.ownerDocument;
				
				return win
						? Math.max( doc.documentElement[attr], doc.body[attr]  )
						: elem[attr];
			};
		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );

/**

* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
*/
(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);

(function($){
		$.extend({
			jYoutube: function( url, size ){
				if(url === null){ return ""; }
	
				size = (size === null) ? "big" : size;
				var vid;
				var results;
	
				results = url.match("[\\?&]v=([^&#]*)");
	
				vid = ( results === null ) ? url : results[1];
	
				if(size == "small"){
					return "http://img.youtube.com/vi/"+vid+"/2.jpg";
				}else {
					return "http://img.youtube.com/vi/"+vid+"/0.jpg";
				}
			}
		})
	})(jQuery);

