var clubMap, countryName = 'Ireland', selectedClubTab, selectedPropertyTab, selectedPartnerTab, selectedWorkFitTab, selectedSearchTab, largeMap, firstClick = false, localSearch, mapDirections;

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

window.onload = function() {
	if(window.XMLHttpRequest) {
		xmlHTTP = new XMLHttpRequest();
	} else {
		xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if(headerSearch = document.getElementById('frmHeaderSearch')) {
		headerSearch.txtSearch.onfocus = function() {
			if(this.value == 'search site') {
				this.value = '';
			}
			this.className = 'textbox swatch_grey swatch_grey_border swatch_white_bg';
			
		}
		headerSearch.txtSearch.onblur = function() {
			if(this.value == '') {
				this.value = 'search site';
			}
			this.className = 'textbox swatch_grey swatch_grey_border swatch_black_bg';
		}
		
	}
	if(healthadviceSearch = document.getElementById('frmSearchHealthAdvice')) {
		healthadviceSearch.txtSearch.onfocus = function() {
			if(this.value == 'search criteria') {
				this.value = '';
			}
			this.className = 'textbox swatch_grey swatch_grey_border swatch_white_bg';
		}
		healthadviceSearch.txtSearch.onblur = function() {
			if(this.value == '') {
				this.value = 'search criteria';
			}
			this.className = 'textbox swatch_grey swatch_grey_border swatch_black_bg';
		}
	}
	if(headerClubList = document.getElementById('header_club_list')) {
		if(headerClubSearch = document.getElementById('frmHeaderClubSearch')) {
			headerClubSearch.onsubmit = function() {
				var searchPostcode = document.getElementById('txtHeaderClubSearch_Postcode').value;
				if(searchPostcode != '' && searchPostcode != 'Enter your postcode') {
					headerClubList.style.display = 'block';
					xmlHTTP.open('POST', '/_action/search_clubs', true);
					xmlHTTP.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					xmlHTTP.onreadystatechange = function() {
						if(xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
							var clubListContent = document.getElementById('club_list_content');
							clubListContent.innerHTML = xmlHTTP.responseText;
						}
					}
					xmlHTTP.send('searchPostcode='+ searchPostcode);
				}
				return false;
			}
		}
	}
	if(clubList = document.getElementById('clubsearch_list')) {
		if(clubSearch = document.getElementById('frmClubSearch')) {
			clubSearch.onsubmit = function() {
				var searchPostcode = document.getElementById('txtClubSearch_Postcode').value;
				if(searchPostcode != '' && searchPostcode != 'Enter your postcode') {
					xmlHTTP.open('POST', '/_action/search_clubs', true);
					xmlHTTP.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					xmlHTTP.onreadystatechange = function() {
						if(xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
							document.getElementById('clubsearch_list').innerHTML = xmlHTTP.responseText;
						}
					}
					xmlHTTP.send('searchPostcode='+ searchPostcode);
				}
				return false;
			}
		}
	}
	if(countryContainer = document.getElementById('country_container')) {
		var countryAreas = countryContainer.getElementsByTagName('div');
		for(areaCount = 0; areaCount < countryAreas.length; areaCount++) {
			if(countryAreas[areaCount].getAttribute('id') != 'ireland') {
				countryAreas[areaCount].onclick = function() {
					var selectedArea = this.parentNode.getAttribute('selectedArea');
					if(selectedArea != '' && selectedArea != null) {
						document.getElementById(selectedArea).style.backgroundImage = 'url(/static/images/clubs/search/'+ selectedArea +'.gif)';
						document.getElementById('region_'+ selectedArea).style.display = 'none';
					}
					this.style.backgroundImage = 'url(/static/images/clubs/search/'+ this.id +'_selected.gif)';
					document.getElementById('region_'+ this.id).style.display = 'block';
					this.parentNode.setAttribute('selectedArea', this.id);
					switch(this.id) {
						case 'london':
						case 'midlands':
							document.getElementById('club_notice').style.display = 'block';
						break;
						default:
							document.getElementById('club_notice').style.display = 'none';
					}
				}
				countryAreas[areaCount].style.zIndex = (areaCount + 1);
				document.getElementById('region_'+ countryAreas[areaCount].id).style.display = 'none';
				if(countryAreas[areaCount].id == 'london') {
					var selectedRegion = countryAreas[areaCount];
				}
			}
		}
		selectedRegion.style.backgroundImage = 'url(/static/images/clubs/search/'+ selectedRegion.id +'_selected.gif)';
		document.getElementById('region_'+ selectedRegion.id).style.display = 'block';
		selectedRegion.parentNode.setAttribute('selectedArea', selectedRegion.id);
	}
	pageElements = document.getElementsByTagName('*');
	for(elementCount = 0; elementCount < pageElements.length; elementCount++) {
		if(pageElements[elementCount].getAttribute('coreElement') != '' && pageElements[elementCount].getAttribute('coreElement') != null) {
			switch(pageElements[elementCount].getAttribute('coreElement')) {
				case 'clubSearch':
					pageElements[elementCount].onchange = function() {
						if(this.value != '') {
							if(this.value.substr(0, 7) == 'http://') {
								window.open(this.value);
							}
							else {
								top.location.href = '/home/clubs/'+ this.value;
							}
						}
					}
				break;
			}
		}
	}
	if(activityEnquiry = document.getElementById('frmActivityEnquiry')) {
		for(valueCount = 0; valueCount < activityEnquiry.rdbMember.length; valueCount++) {
			activityEnquiry.rdbMember[valueCount].onclick = function() {
				if(membershipNumber = document.getElementById('membership_number')) {
					if(this.value == 'Yes') {
						membershipNumber.style.display = 'block';
					}
					else {
						membershipNumber.style.display = 'none';
					}
				}
			}
		}
	}
	
	
	if(activityEnquiry = document.getElementById('frmContactGeneralEnquiry')) {
		for(valueCount = 0; valueCount < activityEnquiry.rdbMember.length; valueCount++) {
			activityEnquiry.rdbMember[valueCount].onclick = function() {
				if(membershipNumber = document.getElementById('membership_number')) {
					if(this.value == 'Yes') {
						membershipNumber.style.display = 'block';
					}
					else {
						membershipNumber.style.display = 'none';
					}
				}
			}
		}
	}
	

	if(kidsParty = document.getElementById('frmKidsParty')) {
		for(valueCount = 0; valueCount < kidsParty.rdbMember.length; valueCount++) {
			kidsParty.rdbMember[valueCount].onclick = function() {
				if(membershipNumber = document.getElementById('membership_number')) {
					if(this.value == 'Yes') {
						membershipNumber.style.display = 'block';
					}
					else {
						membershipNumber.style.display = 'none';
					}
				}
			}
		}
		for(valueCount = 0; valueCount < kidsParty.rdbDietaryNeeds.length; valueCount++) {
			kidsParty.rdbDietaryNeeds[valueCount].onclick = function() {
				if(dietaryDescription = document.getElementById('dietary_description')) {
					if(this.value == 'Yes') {
						dietaryDescription.style.display = 'block';
					}
					else {
						dietaryDescription.style.display = 'none';
					}
				}
			}
		}
	}
	setTimeout(function(){
//		changeClubTab('uk');
		var str = "" + window.location;
		var strparts = str.split("#");
		
		if (strparts[1]) {
			changeClubTab(strparts[1]);
		}
		else {
			changeClubTab(countryName);
		}
		if(self.document.location.hash.substring(1) == 'contactform') {
			changePropertyTab('contactform');
		}
		else {
			changePropertyTab('overview');
		}
		if(self.document.location.hash.substring(1) == 'enquiryform') {
			changeWorkFitTab('enquiryform');
		}
		else {
			changeWorkFitTab('overview');
		}
		var locationPath = location.pathname.split('/');
		switch(locationPath[3]) {
			case 'activities':
			case 'healthadvice':
				changeSearchTab(locationPath[3]);
			break;
			default:
				changeSearchTab('thesite');
		}
	}, 10);
	
	var currentDate = new Date();
	if(document.getElementById('min_year')) {
		if(document.getElementById('min_month')) {
			var currentDate = new Date(document.getElementById('min_year').value, document.getElementById('min_month').value - 1);
		}
	}
	if(document.getElementById('calendar')) {
		var str = "" + window.location;
		var strparts = str.split("/");
		var club;
		if (strparts[5]) {
			club = strparts[5].split("?");
			club = club[0].split("#");
		}
		loadCalendar(currentDate.getFullYear(), currentDate.getMonth(), club);
	}
}

window.onunload = function() {
	GUnload();
}

/*
	Show container via javascript
	-----------------------------
	- This allows us to toggle an element that contains elements that are hidden on dom load
	- Removing the flickering on js/non-js loaded elements.
*/

function showContainerWhenReady(ref) {
	document.write('<style type="text/css">' + ref + '{visibility: hidden;}</style>');
	$(function() {
		$(ref).css('visibility', 'visible');
	});
}

/* START - Calendar */

var monthNames = new Array(12), setYear, setMonth, eventTimeout;

function loadCalendar(startYear, startMonth, club) {
	if(document.getElementById('calendar')) {
		monthNames[0] = 'January';
		monthNames[1] = 'February';
		monthNames[2] = 'March';
		monthNames[3] = 'April';
		monthNames[4] = 'May';
		monthNames[5] = 'June';
		monthNames[6] = 'July';
		monthNames[7] = 'August';
		monthNames[8] = 'September';
		monthNames[9] = 'October';
		monthNames[10] = 'November';
		monthNames[11] = 'December';
		displayCurrentMonth(startYear, startMonth);
		displayMonthDays(startYear, startMonth, club);
	}
}

function getMonthDays(year, month) {
	switch(month) {
		case 1:
			var days = Math.floor(year / 4) == year / 4 ? 29 : 28;
		break;
		case 3:
		case 5:
		case 8:
		case 10:
			var days = 30;
		break;
		default:
			var days = 31;
	}
	return(days);
}

function displayCurrentMonth(year, month) {
	var monthName = document.getElementById('month_name');
	var monthLink = document.getElementById('month_link');
	var currentMonth = new Date(year, month, 1);
	monthName.innerHTML = monthNames[currentMonth.getMonth()] +' '+ currentMonth.getFullYear();
	monthLink.href = '/home/events/'+ document.getElementById('event_club').value +'/'+ currentMonth.getFullYear() +'-'+ (currentMonth.getMonth() + 1) +'/1';
	monthLink.title = 'see all events in '+ monthNames[currentMonth.getMonth()];
}

function displayMonthDays(year, month, club) {
	document.getElementById('event_total').style.backgroundImage = 'url(/static/images/events/content/calendar/loader.gif)';
	
	var currentDate = new Date();
	
	var dayList = new Array();
	var monthDays = document.getElementById('month_days');
	while(monthDays.hasChildNodes()) {
		monthDays.removeChild(monthDays.firstChild);
	}
	
	var currentMonth = new Date(year, month, 1);
	var currentDays = getMonthDays(currentMonth.getFullYear(), currentMonth.getMonth());
	
	var prevMonth = new Date(year, month - 1, 1);
	var prevDays = getMonthDays(prevMonth.getFullYear(), prevMonth.getMonth());
	
	var weekDay = currentMonth.getDay() - 1;
	if(weekDay == -1) {
		weekDay = 6;
	}
	var dayCount = 0;
	for(prevCount = weekDay - 1; 0 <= prevCount; prevCount--) {
		dayCount++;
		var prevDay = new Date(prevMonth.getFullYear(), prevMonth.getMonth(), (prevDays - prevCount));
		var calendarDay = document.createElement('span');
		if(prevDay.getDay() == 0 || prevDay.getDay() == 6) {
			calendarDay.className = 'day non_month weekend';
		}
		else {
			calendarDay.className = 'day non_month';
		}
		calendarDay.innerHTML = prevDays - prevCount;
		monthDays.appendChild(calendarDay);
	}
	for(currentCount = 1; currentCount <= currentDays; currentCount++) {
		dayCount++;
		var currentDay = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), currentCount);
		var calendarDay = document.createElement('span');
		calendarDay.id = 'month_day'+ currentCount;
		if(currentDate.getFullYear() == currentDay.getFullYear() && currentDate.getMonth() == currentDay.getMonth() && currentDate.getDate() == currentDay.getDate()) {
			calendarDay.className = 'day current';
		}
		else {
			if(currentDay.getDay() == 0 || currentDay.getDay() == 6) {
				calendarDay.className = 'day weekend';
			}
			else {
				calendarDay.className = 'day';
			}
		}
		calendarDay.innerHTML = currentCount;
		monthDays.appendChild(calendarDay);
	}
	var nextCount = 0;
	while(Math.floor(dayCount / 7) != dayCount / 7) {
		dayCount++;
		nextCount++;
		var nextDay = new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, nextCount);
		var calendarDay = document.createElement('span');
		if(nextDay.getDay() == 0 || nextDay.getDay() == 6) {
			calendarDay.className = 'day non_month weekend';
		}
		else {
			calendarDay.className = 'day non_month';
		}
		calendarDay.innerHTML = nextCount;
		monthDays.appendChild(calendarDay);
	}
	setYear = year;
	setMonth = month;
	eventTimeout = setTimeout(function(){loadEvents(setYear, setMonth, club);}, 500);
}

function prevMonth(club) {
	clearTimeout(eventTimeout);
	
	var prevMonth = new Date(setYear, setMonth - 1, 1);
	displayCurrentMonth(prevMonth.getFullYear(), prevMonth.getMonth());
	displayMonthDays(prevMonth.getFullYear(), prevMonth.getMonth(), club);
}

function nextMonth(club) {
	clearTimeout(eventTimeout);
	
	var nextMonth = new Date(setYear, setMonth + 1, 1);
	displayCurrentMonth(nextMonth.getFullYear(), nextMonth.getMonth());
	displayMonthDays(nextMonth.getFullYear(), nextMonth.getMonth(), club);
}

function loadEvents(year, month, club) {
	if(window.XMLHttpRequest) {
		xmlHTTP = new XMLHttpRequest();
	}
	else {
		xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (club == undefined) {club = '';}
	xmlHTTP.open('POST', '/_action/get_events?club=' + club, true);
	xmlHTTP.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHTTP.onreadystatechange = function() {
		if(xmlHTTP.status == 200) {
			document.getElementById('event_total').style.backgroundImage = 'none';
			if(xmlHTTP.readyState == 4) {
				if(xmlHTTP.responseText != null && xmlHTTP.responseText != '') {
					if(year == setYear && month == setMonth) {
						var eventCount = 0;
						var foundEvents = xmlHTTP.responseText.substr(0, xmlHTTP.responseText.length-1);
						if(foundEvents != '') {
							foundEvents = foundEvents.split(',');
							if(foundEvents.length > 1) {
								var totalEvents = foundEvents.length+' events';
							} else {
								var totalEvents = '1 event';
							}
						} else {
							var totalEvents = 'No events';
						}
						document.getElementById('event_count').innerHTML = totalEvents;
						for(eventCount = 0; eventCount < foundEvents.length; eventCount++) {
							var day = foundEvents[eventCount].trim();
							var dayElement = document.getElementById('month_day'+ day);
							dayElement.year = year;
							dayElement.month = month;
							dayElement.day = day;
							dayElement.className = 'day event';
							dayElement.style.cursor = 'pointer';
							dayElement.onclick = function() {
								window.location = '/home/events/'+ document.getElementById('event_club').value +'/'+ this.year +'-'+ (this.month + 1) +'-'+ this.day +'/1';
							}
						}
					}
				}
			}
		}
	}
	xmlHTTP.send('year='+ year +'&month='+ (month + 1));
}

/* END - Calendar */

function closeClubList() {
	if((clubList = document.getElementById('header_club_list')) && (clubListContent = document.getElementById('club_list_content'))) {
		clubList.style.display = 'none';
		clubListContent.innerHTML = '<div id="club_list_loader"><!-- --></div>';
	}
}

function kenshoo_conv(id,type,value,orderId,promoCode,valueCurrency) {
	var url = "http://www.xg4ken.com/media/redir.php?track=1&id=" + id + "&type=" + type + "&val=" + value + "&orderId=" + orderId + "&valueCurrency=" + valueCurrency + "&promoCode=" + promoCode + "&ref=" + document.referrer;
	var a = new Image(1,1);
	a.src = url;
	a.onload = function() { _uVoid(); }
}

function changeClubTab(newClubTab) {
	if(document.getElementById('clubsEurope') && document.getElementById('clubsUK') && document.getElementById('clubsSearch') && document.getElementById('tab_europe') && document.getElementById('tab_uk')) {
	// if(document.getElementById('clubsEurope') && document.getElementById('clubsUK') && document.getElementById('clubsSearch') && document.getElementById('tab_europe') && document.getElementById('tab_uk') && document.getElementById('tab_search')) {
		if(newClubTab != selectedClubTab) {
			switch(newClubTab) {
				case 'europe':
					document.getElementById('clubsEurope').style.display = 'block';
					document.getElementById('clubsUK').style.display = 'none';
					document.getElementById('clubsSearch').style.display = 'none';
					document.getElementById('tab_europe').style.backgroundImage = 'url(/static/images/clubs/search/tab_europe_selected.gif)';
					document.getElementById('tab_uk').style.backgroundImage = 'url(/static/images/clubs/search/tab_uk.gif)';
					document.getElementById('tab_search').style.backgroundImage = 'url(/static/images/clubs/search/tab_search.gif)';
				break;
				case 'uk':
					document.getElementById('clubsEurope').style.display = 'none';
					document.getElementById('clubsUK').style.display = 'block';
					document.getElementById('clubsSearch').style.display = 'none';
					document.getElementById('tab_europe').style.backgroundImage = 'url(/static/images/clubs/search/tab_europe.gif)';
					document.getElementById('tab_uk').style.backgroundImage = 'url(/static/images/clubs/search/tab_uk_selected.gif)';
					document.getElementById('tab_search').style.backgroundImage = 'url(/static/images/clubs/search/tab_search.gif)';
				break;
				case 'search':
					document.getElementById('clubsEurope').style.display = 'none';
					document.getElementById('clubsUK').style.display = 'none';
					document.getElementById('clubsSearch').style.display = 'block';
					document.getElementById('tab_europe').style.backgroundImage = 'url(/static/images/clubs/search/tab_europe.gif)';
					document.getElementById('tab_uk').style.backgroundImage = 'url(/static/images/clubs/search/tab_uk.gif)';
					document.getElementById('tab_search').style.backgroundImage = 'url(/static/images/clubs/search/tab_search_selected.gif)';
				break;

			}
			selectedClubTab = newClubTab;
		}
	}
}

function changePartnerTab(newPartnerTab) {
	switch(newPartnerTab) {
		case 'charity':
			document.getElementById('tab_charity').style.backgroundImage = 'url(/static/images/about/partnerslinks/tab_charity_selected.png)';
			document.getElementById('tab_strategic').style.backgroundImage = 'url(/static/images/about/partnerslinks/tab_strategic.png)';
			document.getElementById('tab_suppliers').style.backgroundImage = 'url(/static/images/about/partnerslinks/tab_suppliers.png)';
		break;
		case 'strategic':
			document.getElementById('tab_charity').style.backgroundImage = 'url(/static/images/about/partnerslinks/tab_charity.png)';
			document.getElementById('tab_strategic').style.backgroundImage = 'url(/static/images/about/partnerslinks/tab_strategic_selected.png)';
			document.getElementById('tab_suppliers').style.backgroundImage = 'url(/static/images/about/partnerslinks/tab_suppliers.png)';
		break;
		case 'suppliers':
			document.getElementById('tab_charity').style.backgroundImage = 'url(/static/images/about/partnerslinks/tab_charity.png)';
			document.getElementById('tab_strategic').style.backgroundImage = 'url(/static/images/about/partnerslinks/tab_strategic.png)';
			document.getElementById('tab_suppliers').style.backgroundImage = 'url(/static/images/about/partnerslinks/tab_suppliers_selected.png)';
		break;
	}
}


/*
	Club page map functions
	------------------------
		- This should ideally be in it's own JS file
*/

function initClubMap(club_latitude, club_longitude, club_defaultZoom) {
	mapContainer = document.getElementById('locationmap');
	clubMap = new GMap2(mapContainer);
	if (clubMap) {
		clubMap.setCenter(new GLatLng(club_latitude, club_longitude), club_defaultZoom);
		clubMap.addOverlay(new GMarker(new GLatLng(club_latitude, club_longitude)));
		clubMap.addControl(new GLargeMapControl());
		clubMap.addControl(new GMapTypeControl());
		if (mapContainer) {
			window.localSearch = new GlocalSearch();
			if (!firstClick) {
				document.getElementById('frmSearchDirections').onsubmit = function() {
					clubMap.clearOverlays(); // clear previous direction overlay
					$("html:not(:animated),body:not(:animated)").animate({
						scrollTop: ($('#locationmap').offset().top - 10)
					}, 900);
					var resultsContainer = document.getElementById('mapdirections_resultscontainer'); // clear container
					resultsContainer.innerHTML = '';
					mapDirections = new GDirections(clubMap, resultsContainer); // create a new direction search object
					usePointFromTownname(document.getElementById('txtSearchDirections').value, mapTabCallback);
					return false;
				}
				firstClick = true;
			}
		}
	}
}

function usePointFromTownname(townname, callbackFunction) {
	localSearch.setSearchCompleteCallback(null, function() {
		if (localSearch.results[0]) {
			callbackFunction(localSearch.results[0]);
		}
	});
	localSearch.execute(townname + ', Ireland');
}

function setDirectionsOverlay(start, end) {
	$("html:not(:animated),body:not(:animated)").animate({
		scrollTop: ($('#locationmap').offset().top - 10)
	}, 900);
	$('#txtSearchDirections').val(start);
	var resultsContainer = document.getElementById('mapdirections_resultscontainer');
	resultsContainer.innerHTML = '';
	//mapDirections = new GDirections(clubMap, resultsContainer);
	usePointFromTownname(document.getElementById('txtSearchDirections').value, mapTabCallback);
}

function mapTabCallback(coords) {
	mapDirections.load('from: '+ coords.lat +', '+ coords.lng + ' to: '+ document.getElementById('hdnClubLatitude').value + ', ' + document.getElementById('hdnClubLongitude').value);
}

function setLatAndLong(lat, long) {
	$("#hdnClubLatitude").val(lat);
	$("#hdnClubLongitude").val(long);
	$("#mapdirections_results").html("");
}

function initMapTab(zoom,largeMap) {
	if(mapContainer = document.getElementById('locationmap')) {
		window.localSearch = new GlocalSearch();
            if (!firstClick) {
//				largeMap = new GMap2(document.getElementById('largemap'));
//				largeMap.setCenter(new GLatLng(document.getElementById('hdnClubLatitude').value, document.getElementById('hdnClubLongitude').value), zoom);
//				largeMap.addOverlay(new GMarker(new GLatLng(document.getElementById('hdnClubLatitude').value, document.getElementById('hdnClubLongitude').value)));
//				largeMap.addControl(new GLargeMapControl());
//				largeMap.addControl(new GMapTypeControl());
				document.getElementById('frmSearchDirections').onsubmit = function() {
					var resultsContainer = document.getElementById('mapdirections_resultscontainer');
					resultsContainer.innerHTML = '';
					mapDirections = new GDirections(largeMap, resultsContainer);
					var coords = usePointFromPostcode(document.getElementById('txtSearchDirections').value, mapTabCallback);
					return false;
				}
			firstClick = true;
		}
	}
}

function openMapTab(tabName, zoom) {
	if(mapContainer = document.getElementById('map_container')) {
		localSearch = new GlocalSearch();
		mapContainer.style.display = 'block';
		var getDirections = document.getElementById('mapcontent_getdirections');
		var getDirectionsTab = document.getElementById('maptab_getdirections');
		var largerVersion = document.getElementById('mapcontent_largerversion');
		var largerVersionTab = document.getElementById('maptab_largerversion');
		if(!firstClick) {
			largeMap = new GMap2(document.getElementById('largemap'));
			largeMap.setCenter(new GLatLng(document.getElementById('hdnClubLatitude').value, document.getElementById('hdnClubLongitude').value), zoom);
			largeMap.addOverlay(new GMarker(new GLatLng(document.getElementById('hdnClubLatitude').value, document.getElementById('hdnClubLongitude').value)));
			largeMap.addControl(new GLargeMapControl());
			largeMap.addControl(new GMapTypeControl());
			document.getElementById('frmSearchDirections').onsubmit = function() {
				var resultsContainer = document.getElementById('mapdirections_resultscontainer');
				var directionResults = document.getElementById('mapdirections_results');
				mapDirections = new GDirections(largeMap, resultsContainer);
				GEvent.addListener(mapDirections, 'addoverlay', function() {
					directionResults.innerHTML = resultsContainer.innerHTML;
					document.getElementById('mapsearch_links').style.display = 'block';
				});
				var coords = usePointFromPostcode(document.getElementById('txtSearchDirections').value, mapTabCallback);
				//mapDirections.load('from: '+ document.getElementById('txtSearchDirections').value +', UK to: '+ document.getElementById('hdnClubLatitude').value +', '+ document.getElementById('hdnClubLongitude').value);
				return false;
			}
			firstClick = true;
		}
		switch(tabName) {
			case 'get_directions':
				largerVersion.style.display = 'none';
				getDirections.style.display = 'block';
				largerVersionTab.style.backgroundImage = 'url(/static/images/clubs/content/maptab_largerversion_off.gif)';
				getDirectionsTab.style.backgroundImage = 'url(/static/images/clubs/content/maptab_getdirections_on.gif)';
			break;
			case 'larger_version':
				getDirections.style.display = 'none';
				largerVersion.style.display = 'block';
				getDirectionsTab.style.backgroundImage = 'url(/static/images/clubs/content/maptab_getdirections_off.gif)';
				largerVersionTab.style.backgroundImage = 'url(/static/images/clubs/content/maptab_largerversion_on.gif)';
			break;
		}
	}
}

function openMulitpleMapTab(tabName, newMap, postcode) {
	if(mapContainer = document.getElementById('map_container')) {
		localSearch = new GlocalSearch();
		mapContainer.style.display = 'block';
		var getDirections = document.getElementById('mapcontent_getdirections');
		var getDirectionsTab = document.getElementById('maptab_getdirections');
		var largerVersion = document.getElementById('mapcontent_largerversion');
		var largerVersionTab = document.getElementById('maptab_largerversion');
		if(newMap == true) {
			largeMap = new GMap2(document.getElementById('largemap'));
			largeMap.setCenter(new GLatLng(document.getElementById('hdnClubLatitude').value, document.getElementById('hdnClubLongitude').value), 15);
			largeMap.addOverlay(new GMarker(new GLatLng(document.getElementById('hdnClubLatitude').value, document.getElementById('hdnClubLongitude').value)));
			largeMap.addControl(new GLargeMapControl());
			largeMap.addControl(new GMapTypeControl());

				var resultsContainer = document.getElementById('mapdirections_resultscontainer');
				var directionResults = document.getElementById('mapdirections_results');
				mapDirections = new GDirections(largeMap, resultsContainer);
				GEvent.addListener(mapDirections, 'addoverlay', function() {
					directionResults.innerHTML = resultsContainer.innerHTML;
					document.getElementById('mapsearch_links').style.display = 'block';
				});
				var coords = usePointFromPostcode(postcode, mapTabCallback);
				document.getElementById('txtSearchDirections').value = postcode;

			document.getElementById('frmSearchDirections').onsubmit = function() {
				var resultsContainer = document.getElementById('mapdirections_resultscontainer');
				var directionResults = document.getElementById('mapdirections_results');
				mapDirections = new GDirections(largeMap, resultsContainer);
				GEvent.addListener(mapDirections, 'addoverlay', function() {
					directionResults.innerHTML = resultsContainer.innerHTML;
					document.getElementById('mapsearch_links').style.display = 'block';
				});
				var coords = usePointFromPostcode(document.getElementById('txtSearchDirections').value, mapTabCallback);
				//mapDirections.load('from: '+ document.getElementById('txtSearchDirections').value +', UK to: '+ document.getElementById('hdnClubLatitude').value +', '+ document.getElementById('hdnClubLongitude').value);
				return false;
			}
		}
		switch(tabName) {
			case 'get_directions':
				largerVersion.style.display = 'none';
				getDirections.style.display = 'block';
				largerVersionTab.style.backgroundImage = 'url(/static/images/clubs/content/maptab_largerversion_off.gif)';
				getDirectionsTab.style.backgroundImage = 'url(/static/images/clubs/content/maptab_getdirections_on.gif)';
			break;
			case 'larger_version':
				getDirections.style.display = 'none';
				largerVersion.style.display = 'block';
				getDirectionsTab.style.backgroundImage = 'url(/static/images/clubs/content/maptab_getdirections_off.gif)';
				largerVersionTab.style.backgroundImage = 'url(/static/images/clubs/content/maptab_largerversion_on.gif)';
			break;
		}
	}
}

function printDirections() {
	var printFrame = document.getElementById('mapdirections_printframe');
	var frameDoc = printFrame.contentDocument;
	if(frameDoc == undefined || frameDoc == null) {
		frameDoc = printFrame.contentWindow.document;
	}
	frameDoc.open();
	frameDoc.write(document.getElementById('mapdirections_results').innerHTML);
	frameDoc.close();
	this.frames['mapdirections_printframe'].focus();
	this.frames['mapdirections_printframe'].print();
}

function closeMap() {
	if(mapContainer = document.getElementById('map_container')) {
		mapContainer.style.display = 'none';
	}
}

function changePropertyTab(newPropertyTab) {
	if(document.getElementById('propertyOverview') && document.getElementById('propertyTargetList') && document.getElementById('propertyContactForm') && document.getElementById('tab_overview') && document.getElementById('tab_targetlist') && document.getElementById('tab_contactform')) {
		if(newPropertyTab != selectedPropertyTab) {
			switch(newPropertyTab) {
				case 'overview':
					document.getElementById('propertyOverview').style.display = 'block';
					document.getElementById('propertyTargetList').style.display = 'none';
					document.getElementById('propertyContactForm').style.display = 'none';
					document.getElementById('tab_overview').style.backgroundImage = 'url(/static/images/property/content/tab_overview_selected.gif)';
					document.getElementById('tab_targetlist').style.backgroundImage = 'url(/static/images/property/content/tab_targetlist.gif)';
					document.getElementById('tab_contactform').style.backgroundImage = 'url(/static/images/property/content/tab_contactform.gif)';
				break;
				case 'targetlist':
					document.getElementById('propertyOverview').style.display = 'none';
					document.getElementById('propertyTargetList').style.display = 'block';
					document.getElementById('propertyContactForm').style.display = 'none';
					document.getElementById('tab_overview').style.backgroundImage = 'url(/static/images/property/content/tab_overview.gif)';
					document.getElementById('tab_targetlist').style.backgroundImage = 'url(/static/images/property/content/tab_targetlist_selected.gif)';
					document.getElementById('tab_contactform').style.backgroundImage = 'url(/static/images/property/content/tab_contactform.gif)';
				break;
				case 'contactform':
					document.getElementById('propertyOverview').style.display = 'none';
					document.getElementById('propertyTargetList').style.display = 'none';
					document.getElementById('propertyContactForm').style.display = 'block';
					document.getElementById('tab_overview').style.backgroundImage = 'url(/static/images/property/content/tab_overview.gif)';
					document.getElementById('tab_targetlist').style.backgroundImage = 'url(/static/images/property/content/tab_targetlist.gif)';
					document.getElementById('tab_contactform').style.backgroundImage = 'url(/static/images/property/content/tab_contactform_selected.gif)';
				break;				
			}
			selectedPropertyTab = newPropertyTab;
		}
	}
}

function changeWorkFitTab(newWorkFitTab) {
	if(document.getElementById('workfitOverview') && document.getElementById('workfitMembershipOptions') && document.getElementById('workfitEnquiryForm') && document.getElementById('tab_overview') && document.getElementById('tab_membershipoptions') && document.getElementById('tab_enquiryform')) {
		if(newWorkFitTab != selectedWorkFitTab) {
			switch(newWorkFitTab) {
				case 'overview':
					document.getElementById('workfitOverview').style.display = 'block';
					document.getElementById('workfitMembershipOptions').style.display = 'none';
					document.getElementById('workfitEnquiryForm').style.display = 'none';
					document.getElementById('tab_overview').style.backgroundImage = 'url(/static/images/workfit/content/tab_overview_selected.gif)';
					document.getElementById('tab_membershipoptions').style.backgroundImage = 'url(/static/images/workfit/content/tab_membershipoptions.gif)';
					document.getElementById('tab_enquiryform').style.backgroundImage = 'url(/static/images/workfit/content/tab_enquiryform.gif)';
					document.getElementById('overview_link').className = 'active_link';
					document.getElementById('membership_options').className = 'top_line swatch_greydrk_border';
					document.getElementById('enquiry_form').className = 'top_line swatch_greydrk_border';
				break;
				case 'membershipoptions':
					document.getElementById('workfitOverview').style.display = 'none';
					document.getElementById('workfitMembershipOptions').style.display = 'block';
					document.getElementById('workfitEnquiryForm').style.display = 'none';
					document.getElementById('tab_overview').style.backgroundImage = 'url(/static/images/workfit/content/tab_overview.gif)';
					document.getElementById('tab_membershipoptions').style.backgroundImage = 'url(/static/images/workfit/content/tab_membershipoptions_selected.gif)';
					document.getElementById('tab_enquiryform').style.backgroundImage = 'url(/static/images/workfit/content/tab_enquiryform.gif)';
					document.getElementById('overview_link').className = '';
					document.getElementById('membership_options').className = 'top_line swatch_greydrk_border active_link';
					document.getElementById('enquiry_form').className = 'top_line swatch_greydrk_border';
				break;
				case 'enquiryform':
					document.getElementById('workfitOverview').style.display = 'none';
					document.getElementById('workfitMembershipOptions').style.display = 'none';
					document.getElementById('workfitEnquiryForm').style.display = 'block';
					document.getElementById('tab_overview').style.backgroundImage = 'url(/static/images/workfit/content/tab_overview.gif)';
					document.getElementById('tab_membershipoptions').style.backgroundImage = 'url(/static/images/workfit/content/tab_membershipoptions.gif)';
					document.getElementById('tab_enquiryform').style.backgroundImage = 'url(/static/images/workfit/content/tab_enquiryform_selected.gif)';
					document.getElementById('overview_link').className = '';
					document.getElementById('membership_options').className = 'top_line swatch_greydrk_border';
					document.getElementById('enquiry_form').className = 'top_line swatch_greydrk_border active_link';
				break;				
			}
			selectedWorkFitTab = newWorkFitTab;
		}
	}
}

function changeSearchTab(newSearchTab) {
	if(document.getElementById('searchresultsTheSite') && document.getElementById('searchresultsActivities') && document.getElementById('searchresultsHealthAdvice') && document.getElementById('tab_thesite') && document.getElementById('tab_activities') && document.getElementById('tab_healthadvice')) {
		if(newSearchTab != selectedSearchTab) {
			switch(newSearchTab) {
				case 'thesite':
					document.getElementById('searchresultsTheSite').style.display = 'block';
					document.getElementById('searchresultsActivities').style.display = 'none';
					document.getElementById('searchresultsHealthAdvice').style.display = 'none';
					document.getElementById('tab_thesite').style.backgroundImage = 'url(/static/images/search/content/tab_thesite_selected.gif)';
					document.getElementById('tab_activities').style.backgroundImage = 'url(/static/images/search/content/tab_activities.gif)';
					document.getElementById('tab_healthadvice').style.backgroundImage = 'url(/static/images/search/content/tab_healthadvice.gif)';
				break;
				case 'activities':
					document.getElementById('searchresultsTheSite').style.display = 'none';
					document.getElementById('searchresultsActivities').style.display = 'block';
					document.getElementById('searchresultsHealthAdvice').style.display = 'none';
					document.getElementById('tab_thesite').style.backgroundImage = 'url(/static/images/search/content/tab_thesite.gif)';
					document.getElementById('tab_activities').style.backgroundImage = 'url(/static/images/search/content/tab_activities_selected.gif)';
					document.getElementById('tab_healthadvice').style.backgroundImage = 'url(/static/images/search/content/tab_healthadvice.gif)';
				break;
				case 'healthadvice':
					document.getElementById('searchresultsTheSite').style.display = 'none';
					document.getElementById('searchresultsActivities').style.display = 'none';
					document.getElementById('searchresultsHealthAdvice').style.display = 'block';
					document.getElementById('tab_thesite').style.backgroundImage = 'url(/static/images/search/content/tab_thesite.gif)';
					document.getElementById('tab_activities').style.backgroundImage = 'url(/static/images/search/content/tab_activities.gif)';
					document.getElementById('tab_healthadvice').style.backgroundImage = 'url(/static/images/search/content/tab_healthadvice_selected.gif)';
				break;				
			}
			selectedSearchTab = newSearchTab;
		}
	}
}

function clubs_list(){
	document.getElementById('sltClubSearch_Clubs').className = 'club_select_white';
}

function newsSignupDefaults(fieldId) {
	switch(fieldId) {
		case 'newsAlertFirstname':
			return 'First name';
		case 'newsAlertSurname':
			return 'Last name';
		case 'newsAlertCompany':
			return 'Company';
		case 'newsAlertEmail':
			return 'Email';
		case 'newsAlertConfirmEmail':
			return 'Confirm Email address';
		case 'newsAlertTelephone':
			return 'Telephone number';
	}
}

function toggleSignupContent() {
	if($(this).val() == newsSignupDefaults($(this).attr('id'))) {
		$(this).val('');
		//$(this).css("color", "white");
	}
}

function blurSignupContent() {
	if($(this).val() == '') {
		//$(this).css("color", "#808080");
		$(this).val(newsSignupDefaults($(this).attr('id')))
	}
}

$(document).ready(function() {
	$('.confirm_delete').click(function() {
		if(!confirm("Are you sure?")) {
			return false;
		}
	});
	
	// Toggle input background
	$(".toggle_bg").focus(function(){
			$(this).removeClass('swatch_black_bg');
			$(this).addClass('swatch_white_bg');
			return false;
	});
	$(".toggle_bg").blur(function(){
			if($(this).val() == this.defaultValue) {
				$(this).removeClass('swatch_white_bg');
				$(this).addClass('swatch_black_bg');
			}
			return false;
	});
	$("select.toggle_bg").change(function(){
			this.blur();
	});
	
	// -------------------
	// news alerts signups
	// -------------------
	
	$('.newsAlertFields').each(function() {
		if($(this).val() == '') {
			$(this).val(newsSignupDefaults($(this).attr('id')))
		}
		$(this).focus(toggleSignupContent);
		$(this).blur(blurSignupContent);
	});
	$('.newsAlertSignupLabels').hide();
	$('#signupSubmit').click(function() {
		$('#signupSubmitIsAjax').val('1');
		var signupErrors = new Array();
		$('#newsAlertFirstname,#newsAlertCompany,#newsAlertEmail,#newsAlertEmail,#newsAlertConfirmEmail').removeClass('highlight_error');
		if ($('#newsAlertFirstname').val() == '' || $('#newsAlertFirstname').val() == 'First Name') {
			signupErrors.push({'name' : 'newsAlertFirstname', 'error' : 'Please enter your first name'});
			$('#newsAlertFirstname').addClass('highlight_error');
		}
		if ($('#newsAlertCompany').val() == '' || $('#newsAlertCompany').val() == 'Company') {
			signupErrors.push({'name' : 'newsAlertCompany', 'error' : 'Please enter your company name'});
			$('#newsAlertCompany').addClass('highlight_error');
		}
		if ($('#newsAlertEmail').val() == '' || $('#newsAlertEmail').val() == 'Email') {
			signupErrors.push({'name' : 'newsAlertEmail', 'error' : 'Please enter a valid email'});
			$('#newsAlertEmail').addClass('highlight_error');
		} else if ($('#newsAlertEmail').val() != $('#newsAlertConfirmEmail').val()) {
			signupErrors.push({'name' : 'newsAlertEmail', 'error' : 'Your emails do not match'});
			$('#newsAlertEmail').addClass('highlight_error');
			$('#newsAlertConfirmEmail').addClass('highlight_error');
		}
		if (signupErrors.length == 0) {
			$.post($("#newsSignupFormData").attr('action'), $("#newsSignupFormData").serialize(), function(responseData) {
				$('#newsSignupForm').slideUp( 'normal', function() {
					$(this).html('<div class="newsSignupSuccess">Thanks for your interest.<br />You are signed up to our news alerts.</div>').slideDown('normal');
					$('.sidebarSubtxt').hide();
				});
			});
		} else {
			var errorDisplay = '';
			for (var error in signupErrors) {
				errorDisplay += '<div class="signupError">' + signupErrors[error].error + '</div>';
			}
			if ($('#newsSignupErrorsContainer').length == 0) {
				$('#newsSignupForm').prepend('<div class="newsSignupErrs" id="newsSignupErrorsContainer"></div>');
				$('#newsSignupErrorsContainer').hide().html(errorDisplay).slideDown('slow');
			} else {
				$('#newsSignupErrorsContainer').slideUp('fast', function() {
					$(this).html(errorDisplay).slideDown('slow');
				});
			}
		}
		return false;
	});

	$('.clubchat_readmore').click(function() {
		var class1 = $(this).attr('class');
		class1 = class1.split(' ');
		class1 = class1[2];
		$('div.clubchat_story').slideUp(500);
		$('.'+class1).slideDown(1000);
		$('.main_story').each(function() {
			$(this).fadeTo(500, 1);
		});		
		$('.clubchat_readmore').fadeIn();
		$(this).fadeOut();
		$('.main_story').each(function() {
			class2 = $(this).attr('class');
			class2 = class2.split(' ');
			class2 = class2[2];
			if(class2 != class1) {
				$(this).fadeTo(500, 0.3);
			}
		});
		return false;
	});
	
	 $('.clubchat_readless').click(function() {
		$(this).parent().slideUp(1000);
		$('.main_story').each(function() {
			$(this).fadeTo(500, 1);
		});
		$('.clubchat_readmore').fadeIn();
		return false;
	});	
	
});

function showBlogComments(type) {
	if (type == 'form') {
		$('#panel_comments_form').show();
		$('#panel_comments').hide();
		$('#comments_nav_comment').attr('class', 'active');
		$('#comments_nav_comments').removeAttr('class');
	}
	else {
		$('#panel_comments_form').hide();
		$('#panel_comments').show();
		$('#comments_nav_comments').attr('class', 'active');
		$('#comments_nav_comment').removeAttr('class');
	}
	return false;
}

function closeThickbox() {
	window.top.tb_remove();
}

function in_array(needle,haystack) {
        for(var i in haystack)
                if(haystack[i]==needle)
                        return true;
 
        return false;
}
