// setup globals
var map, search, from, to, fromTo, infoWindowListener, searched, searchedLat, searchedLng, hasSearched = false, zoom = 5, flag = false, full = false, marker = new Array(), markers = new Array(), clubMarker = new Array();

function showFilterPanel(show) {
	if (show) {
		$('#advanced-tips').addClass('shown');
		$('#advanced-tips span').html('Hide');
		$('#advanced-tips img').attr("src","/static/images/core/bullet_triangle_green_up.gif");
		$('#club_search #search_panel .bot').slideDown('normal', function() {
			$('#club_search #search_panel .leg h4').show();	
		});	
	} else {
		$('#advanced-tips').removeClass('shown');
		$('#advanced-tips span').html('Show');
		$('#advanced-tips img').attr("src","/static/images/core/bullet_triangle_green_down.gif");
		$('#club_search #search_panel .bot').slideUp('normal', function() {
			$('#club_search #search_panel .leg h4').hide();	
		});	
	}
}

// set state and attach events
$(document).ready(function() {
					
	$('form input[type="text"]').each(function() {
		$(this).val($('label[for="'+$(this).attr('id')+'"]').html());
		$('label[for="'+$(this).attr('id')+'"]').hide();
	});
	$('form input[type="text"]').focus(function() {
		if($(this).val() == $('label[for="'+$(this).attr('id')+'"]').html()) {
			$(this).val('');
		}
	});
	$('form input[type="text"]').blur(function() {
		if($(this).val() == '') {
			$(this).val($('label[for="'+$(this).attr('id')+'"]').html());
		}
	});
	$('form').submit(function() {
		$('form input[type="text"]').each(function() {
			if($(this).val() == $('label[for="'+$(this).attr('id')+'"]').html() && $(this).attr('id') != 'postcode') {
				$(this).val('');
			}
		});
	});
	
	$('*').removeClass('nojs_hidden');
	
	$('#map_view_button').addClass('selected');
	$('#list_view_button').removeClass('selected');
	$('#reset_map').addClass('on');
	
	$('.click_show').show();
	$('#list_view').hide();
	
	$('#advanced-tips').click(function() {		
		if ($(this).hasClass('shown')) {
			showFilterPanel(false);
		} else {
			showFilterPanel(true);
		}
		return false;
	});
	
	$('.click_show').click(function() {
		$(this).hide();
		$('.click_hide').show();
		$('#filter_toggle').slideDown();
	});
	
	$('.click_hide').click(function() {
		$(this).hide();
		$('.click_show').show();
		$('#filter_toggle').slideUp();
	});
	
	$('#map_view_button').click(function() {
		$('#map_view').fadeIn();
		$('#list_view').fadeOut();
		$('#view_container').height($('#map_view').height());
		$(this).addClass('selected');
		$('#list_view_button').removeClass('selected');
		if($('#directions').html() != '&nbsp;') {
			$('#directions').show();
			$('#directions_control').show();
		}
		return false;
	});

	$('#list_view_button').click(function() {
		$('#map_view').fadeOut();
		$('#list_view').fadeIn();
		$('#view_container').height($('#list_view').height());
		$(this).addClass('selected');
		$('#map_view_button').removeClass('selected');
		$('#directions').hide();
		$('#directions_control').hide();
		return false;
	});
	
	$('#list_view').css({position:"absolute"});
	$('#view_container').height($('#map_view').height());

	$('#directions_control').click(function() {
		if($(this).hasClass('off')) {
			$('#directions').css({opacity:0}).animate({
				width:"700px",
				paddingLeft:"10px",
				paddingRight:"10px",
				marginLeft:"8px",
				marginRight:"10px",
				opacity:0.9
			},1000);
			$(this).removeClass('off');
			$(this).attr('src', '/static/images/clubsearch/directions-close.gif');
		} else {
			$('#directions').animate({
				width:"0",
				paddingLeft:"0",
				paddingRight:"0",
				marginLeft:"0",
				marginRight:"0",
				opacity:0
			},1000);
			$(this).addClass('off');
			$(this).attr('src', '/static/images/clubsearch/directions-open.gif');
		}
	});
	
	$('#reset_map').click(function() {
		$('#FilterFacList input[type="checkbox"]').each(function() {
			$(this).attr("checked", false); 
		});
		hasSearched = false;
		defaultMap();
		clearDirections();
		$('#search_results_message').html('&nbsp;');
		$('#search_results_control').slideUp();
		$('#club_regions_list').show();
		$('#club_search_list').html('&nbsp;');
		updateList(999);
		adjustRegions();
		adjustMarkers();
		$('.click_hide').hide();
		$('.click_show').show();
		//$('#filter_toggle').hide();
		showFilterPanel(false);
		$('#filters').slideDown();

		return false;
	});
	
	$('#reset_facs').click(function(){
		$('#FilterFacList input[type="checkbox"]').each(function() {
			$(this).attr("checked", false); 
		});
		return false;
	});

	$('#select_facs').click(function(){
		$('#FilterFacList input[type="checkbox"]').each(function() {
			$(this).attr("checked", true);
		});
		return false;
	});
	
	$('#search_results_control img').click(function() {
		$('#reset_map').trigger('click');
	});
	
	$('#region_control ul li a.region').click(function() {
		attachRegionMenuAnimation(this);
		return false;
	});

	$('#region_control ul.subRegion li a.subRegionLink').live("click",function() {
		attachSubRegionMenuAnimation(this);
		return false;
	});
	
	$('#all_regions').click(function() {
		$('#reset_map').trigger('click');
		return false;
	});
	
	$('select.selClub').change(function() {
		if($(this).val()) {
			if($(this).val()=='go_to_uk') {
				$('#uk_clubs a').trigger('click');
			} else if ($(this).val().indexOf('http')!=-1) {
				window.open($(this).val());
			} else {
				window.location = $(this).val();
			}
		}
	});
	
	$('#location_search').submit(function() {
		if($(this).parent().find('#postcode').val() && $(this).parent().find('#postcode').val() != 'Search by postcode') {
			clearDirections();
			locationSearch($(this).parent().find('#postcode').val());
			$('#filters').slideUp();
		}else if($(this).parent().find('#postcode').val() == '') {
			$(this).parent().find('#postcode').val('Search by postcode');
		}else if(pageMode()=='eu') {
			clearDirections();
			locationSearch('');
			//$('#filters').slideUp();
		}
		return false;
	});
	
	$('#filter_search').submit(function() {
		var region = getRegion();
		var data = $(this).serialize();
		defaultMap();
		if (region) data += '&region=' + region;
		adjustRegions(data);
		adjustMarkers(data);
		updateList(999, data);
		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: $('#map_view').offset().top}, 900);
		return false;
	});
	
	$('#uk_clubs a').click(function() {
		$(this).addClass('selected');
		$('#european_clubs a').removeClass('selected');
		$('#postcode').val('Search by postcode');
		$('#postcode').show();
		$('#spnEuroPrompt').hide();
		$('#inpSearchPcode').show();
		$('#divFilterSel').show();
		//$('div.bot2').show();
		
		//$("label[for='postcode']").html('Search by postcode'); 
		adjustRegions();
		defaultMap();
		resetClubList();
		$('#reset_map').trigger('click');
		//$('#divFilterSel').css('display', '');
		resetFacs();
		
		$('#region_control ul li a.region').click(function() {
			attachRegionMenuAnimation(this);
			return false;
		});

		$('#location_search').hide();
		$('a#advanced-tips').hide();
		$('.cont.leg h4').hide();
		
		$('#all_regions').click(function() {
			$('#reset_map').trigger('click');
			return false;
		})
	
		return false;
	});
	
	$('#european_clubs a').click(function() {
		$(this).addClass('selected');
		$('#uk_clubs a').removeClass('selected');
		$('#postcode').hide();
		$('#spnEuroPrompt').show();
		$('#inpSearchPcode').hide();
		$('#divFilterSel').hide();
		//$('div.bot2').hide();		
		//$("label[for='postcode']").html('Search by region'); 
		adjustRegions();
		defaultMap();
		resetClubList();
		$('#reset_map').trigger('click');
		resetFacs();			
		
		$('#region_control ul li a.region').click(function() {
			attachRegionMenuAnimation(this);
			return false;
		});

		$('#location_search').show();
		$('a#advanced-tips').show();
		$('.cont.leg h4').show();
		
		$('#all_regions').click(function() {
			$('#reset_map').trigger('click');
			return false;
		})
		
		return false;
	});	
	attachPageClicks();

	initialiseMap();
//	testScript(0);
});

function testScript(run) {	
	if (run==0) {
		$('#european_clubs a').trigger('click');
		$('#advanced-tips').trigger('click');
//		setTimeout("testScript(1)", 1000);
	} else if (run==1) {
		$('#facility17').attr('checked', 'checked');
		$('#facility29').attr('checked', 'checked');
		$('#filter_search').trigger('submit');
//		$('#brand').attr('selectedIndex', 1);
	}
	
}

function resetFacs() {
	$.get('/static/ajax/clubsearch.php?mode='+pageMode()+'&action=resetAllFacilityList', function(data) {
		$('#divAllFac>ul').html(data);
	});
	$.get('/static/ajax/clubsearch.php?mode='+pageMode()+'&action=resetFacilityList', function(data) {
		$('#filter_search>fieldset#FilterFacList').html(data);
	});
	
}

function pageMode() {
	if ($('#uk_clubs a').hasClass('selected')) return 'ie';
	else return 'eu';
}

function resetClubList() {
	if (pageMode()=='ie') {
		$('#club_select').show();
		$('#club_select_eu').hide();
	} else {
		$('#club_select').hide();
		$('#club_select_eu').show();
	}
//	$('#club_select').find('option').remove();
//	$.get('/static/ajax/clubsearch.php?mode='+pageMode()+'&action=resetClubList', function(data) {
//		$('#club_select').html(data);
//	});
}

function euroTabSifr() {
	sIFR.replaceElement("#europe h2", named({sFlashSrc: "/static/fonts/din-bold.swf", sColor: "#ffffff", sBgColor: "#272727", sCase: "upper", sWmode: "transparent"}));
	sIFR.replaceElement("#europe h3", named({sFlashSrc: "/static/fonts/din-bold.swf", sColor: "#ffffff", sBgColor: "#272727", sCase: "upper", sWmode: "transparent"}));
}


function getRegion() {
	var region = $('#club_regions_list a.selected');
	
	if(!region || $(region).attr('id') == 'all_regions') region = 999
	else if(region.length>0) region = $(region).attr('href').split('?')[1].split('&')[0].split('=')[1];
	else region='';
	
	return region;
}

function attachPageClicks() {
	$('.paging a').click(function() {
		var page = $(this).html();
		if(page == 'Prev' || page == 'Next') {
			page = $(this).attr('rel');
		}
		if(hasSearched) {
			data = [];
			data.lat = searchedLat;
			data.lng = searchedLng;
			data.searched = searched;
			data.page = page;
			updateList(0, data);
		} else {
			var data = $('#filter_search').serialize();
			data += '&page=' + page;
			var region = getRegion();
			updateList(region, data);
		}
		return false;
	});
}

function attachRegionMenuAnimation(obj) {
	closeRegions();
	$(obj).addClass('selected');
	$(obj).parent().find('ul:not(.regionClubs)').slideDown(function(){
		clearOverlay();
		updateMap($(obj).parent().attr('id'));
	});
}

function attachSubRegionMenuAnimation(obj){
	$('#region_control ul ul ul.regionClubs').slideUp();
	var subRegion = $(obj).parent().attr('id').substr(9);
	var region = $(obj).parents('.countryRegion').attr('id').substr(6);
	$(obj).nextAll('ul').slideDown(function(){
		updateList(region, '', subRegion);

		subdata = $(obj).parent().attr('rel').split(':');
		data2 = new Object();
		data2.minY = subdata[0];
		data2.minX = subdata[1];
		data2.maxY = subdata[2];
		data2.maxX = subdata[3];

		focusMarkers(data2);
	});
}

function adjustRegions(data) {
	if ($('#uk_clubs a').hasClass('selected')) {
		action = 'regions';
	} else {
		action = 'countries';
	}
	
	$.get('/static/ajax/clubsearch.php?mode='+pageMode()+'&action='+action+'&'+data, function(data) {
		$('#club_regions_list').html(data);
		$('#region_control ul li a.region').click(function() {
			attachRegionMenuAnimation(this);
			return false;
		});
		$('#all_regions').click(function() {
			$('#reset_map').trigger('click');
			return false;
		});
	});
}


function adjustMarkers(data) {
	$.getJSON('/static/ajax/clubsearch.php?mode='+pageMode()+'&action=lettermarkers&'+data, function(data) {
		letterMarkers = data;
		if(map.getZoom() > 8) {
			plotMarkers(letterMarkers, 2); // when we zoom in a bit show the letters
		}
		zoom = map.getZoom();
	});
	$.getJSON('/static/ajax/clubsearch.php?mode='+pageMode()+'&action=regionmarkers&'+data, function(data) {
		regionMarkers = data;
		if(map.getZoom() < 9) {
			plotMarkers(regionMarkers, 1); // when we zoom out a bit show the regions
		}
		zoom = map.getZoom();
	});
}


function clearDirections() {
	if(!$('#directions_control').hasClass('off')) {
		$('#directions_control').trigger('click');
	}
	$('#directions_control').hide();
	$('#directions').html('&nbsp;');
}


// find the region we clicked
function updateMap(id) {
	region = id.substr(6);
	data = $('#filter_search').serialize();
	updateList(region, data);
	
	$.each(regionMarkers.markers, function(i, data2) {
		if(data2.region == region) {
			focusMarkers(data2);
			return false;
		}
	});
}


// updates list view
function updateList(region, data, subRegion) {
	if(!region) region = 999;
	if(subRegion){
		region = region +'&subRegion='+subRegion;
	}
	var extra = '';
	if(data && data.lat) {
		if(data.page) {
			page = data.page;
		} else {
			page = 1;
		}
		extra = '&lat=' + data.lat + '&lng=' + data.lng + '&searched=' + data.searched + '&page=' + page;
	} else if(data) {
		extra = '&' + data;
	}
	var url = '/static/ajax/clubsearch.php?mode='+pageMode()+'&action=list&region='+region+extra+'&rand='+Number(new Date());
	//alert(url);
	$.get(url, function(data) {
		$('#list_view_content').html(data);
		attachPageClicks();
		if($('#list_view_button').hasClass('selected')) {
			$('#view_container').height($('#list_view').height());
		}
	});
}


// close clubs by regions panels
function closeRegions() {
		$('#region_control ul ul').slideUp();
		$('#region_control ul li a').removeClass('selected');
}


// define markers
function initialiseMap() {
	if (GBrowserIsCompatible() && typeof GIcon !== 'undefined') {
		searchMarker = new GIcon(G_DEFAULT_ICON);
		searchMarker.image = '/static/images/clubsearch/search-marker.png';
		searchMarker.shadow = '/static/images/clubsearch/search-marker-shadow.png';
		searchMarker.iconSize = new GSize(25, 36);
		searchMarker.shadowSize = new GSize(38, 34);
		searchMarker.iconAnchor = new GPoint(13, 36);
		if(typeof GMap2 == 'undefined'){
			$('#map_view').hide();
			$('#map_view_button').removeClass('selected');
			$('#list_view_button').addClass('selected');
			$('#list_view').show();
			$('#view_container').height($('#list_view').height());
			$('#map_view').html('<b style="display: block; padding: 12px; color:#8CC63F;">We apologise, Google maps is temporarily unavailable, please use the list view.</b>');
		}else{
			map = new GMap2(document.getElementById("map_canvas"));
			map.setUIToDefault();
			GEvent.addListener(map, "zoomend", function() {
				updateZoom();
			});
			//map.zoomend
			defaultMap();
			search = new GlocalSearch();
		}
	}
}


// control which markers are viewable and prevent scrolling out too far
function updateZoom() {		
	if (pageMode()=='ie') {
		var lng = 53.5;
		var lat = -4.6 ;
		var zm = 6;
		var letterBound = 6;
	} else {
		var lng = 49.5;
		var lat = 2.0 ;
		var zm = 5;
		var letterBound = 5;
	}
	
	if(!hasSearched) {
		if(map.getZoom() < zm) {
			map.setCenter(new GLatLng(lng, lat), zm); // prevent zoom out past set level
		}
		
		if(map.getZoom() > letterBound) {
			plotMarkers(letterMarkers, 2); // when we zoom in a bit show the letters
		}else if(map.getZoom() <= letterBound) {
			$('#cs_info_window').remove();
			plotMarkers(regionMarkers, 1); // when we zoom out a bit show the regions
		}
		zoom = map.getZoom();
	}
}


// set map to start
function defaultMap() {
	if (pageMode()=='ie') {
		var lng = 53.5;
		var lat = -4.6 ;
		var zm = 6;
	} else {
		var lng = 49.5;
		var lat = 2.0 ;
		var zm = 5;
	}
	if(pageMode()=="ie"){
		$('#location_search').hide();
		$('a#advanced-tips').hide();
		$('.cont.leg h4').hide();
	}
	closeRegions();
	$('#all_regions').addClass('selected');
	map.setCenter(new GLatLng(lng, lat), zm);
	plotMarkers(regionMarkers, 1);

}


// calculate the appropriate zoom level for the clubs we're about to plot
function focusMarkers(data) {
	var bounds = new GLatLngBounds(new GLatLng(data.minY,data.minX), new GLatLng(data.maxY,data.maxX)); 
	
	var zoom = map.getBoundsZoomLevel(bounds);
	if(zoom > 15) zoom = 15;
	
	map.setCenter(bounds.getCenter(), zoom);	
	plotMarkers(letterMarkers, 2);
}

//map.clearOverlays(); is buggy so written own function which cleans garbage after
//requires overlays to be added to 'overlays' array
var overlays = new Array();
function clearOverlay() {
//	map.closeInfoWindow();
	map.closeExtInfoWindow();
	map.clearOverlays();	
//	for (var x=0;x<overlays.length;x++) {
//		map.removeOverlay(overlays[x]);
//	}
}

// draw markers onto the map and apply click callbacks
function plotMarkers(data, type) {	
	if (pageMode()=='ie') {
		var dir = 'region-markers';
	} else {
		var dir = 'country-markers';
	}
	
//	map.clearOverlays();
	clearOverlay();
		
	$.each(data.markers, function(i, data2) {		
		if(type != 1) {
			var point = new GLatLng(data2.lat, data2.lng);
			clubMarker = new GIcon(G_DEFAULT_ICON);
			clubMarker.image = '/static/images/clubsearch/club-markers/'+data2.type+'/'+String.fromCharCode(data2.letter)+'.png';
			clubMarker.shadow = '/static/images/clubsearch/club-markers/marker-shadow.png';
			clubMarker.iconSize = new GSize(24, 32);
			clubMarker.shadowSize = new GSize(37, 32);
			clubMarker.iconAnchor = new GPoint(12, 32);
			clubMarker.imageMap = [23,0,23,1,23,2,23,3,23,4,23,5,23,6,23,7,23,8,23,9,23,10,23,11,23,12,23,13,23,14,23,15,23,16,23,17,23,18,23,19,23,20,23,21,23,22,23,23,16,24,15,25,15,26,14,27,14,28,13,29,13,30,12,31,11,31,10,30,10,29,9,28,9,27,8,26,8,25,7,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,0,1,0,0];
			markers[i] = new GMarker(point, clubMarker);
			
			GEvent.addListener(markers[i], 'click', function() {	
				markers[i].openExtInfoWindow(map, "cs_info_window", '<div id="info_window_html">Loading...<\/div>', {ajaxUrl: "/static/ajax/clubsearch.php?mode="+pageMode()+"&action=info&id="+data2.id});
				if(infoWindowListener) GEvent.removeListener(infoWindowListener);
				infoWindowListener = GEvent.addListener(map, 'extinfowindowupdate', function() {
					$('#get_directions span').click(function() {
						$('#get_directions span').removeClass('selected');
						$(this).addClass('selected');
					});
					$('#get_directions').submit(function() {
//						$('#directions').html('&nbsp;');
//						if($('#get_directions #to_here').hasClass('selected')) {
//							from = $("#address").val() + ', '+$('#hdnCountry').val();
//							to = point;
//							fromTo = 'from';
//							getDirections(from);
//						} else {
//							from = $("#address").val() + ', '+$('#hdnCountry').val();
//							to = point;
//							fromTo = 'to';
//							getDirections(to);
//						}
//						return false;
					});
				});
			});
		} else {
			marker = new GIcon(G_DEFAULT_ICON);
			marker.image = '/static/images/clubsearch/'+dir+'/'+data2.name+'-'+data2.total+'.png';
			marker.shadow = '';
			marker.iconSize = new GSize(data2.width, data2.height);
			marker.iconAnchor = new GPoint(Math.floor(data2.width/2), Math.floor(data2.height/2));
			markers[i] = new GMarker(new GLatLng(data2.lat, data2.lng), marker);
			
			GEvent.addListener(markers[i],'click', function() {
				closeRegions();
				data = $('#filter_search').serialize();
				updateList(data2.region, data);
				$('#region'+data2.region+' a.region').addClass('selected').parent().find('ul').slideDown();
				focusMarkers(data2);
			});
		}
		map.addOverlay(markers[i]);
		overlays[overlays.length] = markers[i];
	});
}


// directions search and display
function getDirections(data) {
	search.setSearchCompleteCallback(null, function() {
		if(search.results[0]) {
			var point = new GLatLng(search.results[0].lat, search.results[0].lng);
			if(fromTo == 'from') {
				from = point;
			} else {
				to = point;
			}
			var directions = new GDirections(map, document.getElementById("directions"));
			directions.load('from: ' + from + ' to: ' + to);
			GEvent.addListener(directions, "load", function() {
				clearOverlay();
//				map.clearOverlays();
				$('#directions_control').show().attr('src','/static/images/clubsearch/directions-open.gif').addClass('off');
				$('#directions_control').trigger('click');
			});
			GEvent.addListener(directions, "error", function() {
				alert("Directions for that address could not be found, please check you entered the correct address.");
			});
		} else {
			alert("Directions for that address could not be found, please check you entered the correct address.");
		}
	});
	search.execute(data);
}


// address search and display
function locationSearch(data) {
	search.setSearchCompleteCallback(null, function() {
		if(search.results[0]) {
			$.getJSON('/static/ajax/clubsearch.php?action=distance&lat=' + search.results[0].lat + '&lng=' + search.results[0].lng, function(data) {
				var point = new GLatLng(search.results[0].lat, search.results[0].lng);
				searched = $('#postcode').val();
				searched = searched.replace(/<.*?>/gi, '');
				if(data.total > 0) {
					var bounds = new GLatLngBounds(new GLatLng(data.minY,data.minX), new GLatLng(data.maxY,data.maxX));  
					map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));  
					if(data.total == 1) {
						var clubs = 'is <strong>1 club</strong>';
					} else {
						var clubs = 'are <strong>' + data.total + ' clubs</strong>';
					}
					$('#club_regions_list').hide();
					plotMarkers(data, 2);
					data.lat = search.results[0].lat;
					data.lng = search.results[0].lng;
					searchedLat = search.results[0].lat;
					searchedLng = search.results[0].lng;
					data.searched = searched;
					updateSearchList(data);
				} else {
					map.setCenter(point, 8);
					var clubs = 'are no clubs';
				}
				$('#search_results_message').html('There ' + clubs + ' within a 30 mile radius of \'<strong>' + searched + '</strong>\'');
				$('#search_results_control').slideDown();
				var overlay = map.addOverlay(new GMarker(point, searchMarker));
				overlays[overlays.length] = overlay;
				hasSearched = true;
			});
		} else {
			alert("We couldn't find that location, please check you entered the correct address.");
		}
	});	
	search.execute(data + ', Ireland');
}


function updateSearchList(data) {
	if(data.total == 1) {
		var text = '1 Club';
	} else { 
		var text = data.total + ' Clubs';
	}	
	var html = '<h3>YOUR NEAREST CLUBS</h3><ul><li><a href="#" class="region selected">' + text + ' near \'' + data.searched + '\'</a><ul style="display:block">';
	$.each(data.markers, function(i, data2) {
		html += '<li><strong>' + String.fromCharCode(data2.letter - 32) + '</strong> <a href="/home/clubs/' + data2.code + '">' + data2.name + '</a> <span class="distance">' + data2.distance + ' miles</span></li>';
	});
	html += '</ul></li></ul>';
	$('#club_search_list').html(html);
	
	$('#all_regions').click(function() {
		$('#reset_map').trigger('click');
		return false;
	});
	
	updateList(0, data);
}
