//global variables
town_xml = "";
sites_p_xml = "";
sites_i_xml = "";
sites_l_xml = "";
avail_html = "";
str_town = getURLVar("str_town");
townsearchlat=54.0009;
townsearchlon=-1.5377;

t_xml_processed = false;
p_xml_processed = false;
i_xml_processed = false;
l_xml_processed = false;
a_xml_processed = false;

xml_tries = 0;

//if dom element defined by objectID has loaded, execute the function
function schedule(objectID, functionCall) {
	if (document.getElementById(objectID)) {
		eval(functionCall);
	} else {
		setTimeout("schedule('" + objectID + "', '" + functionCall + "')", 1);
	}
	return true;
}

//$_GET['var'] :)
function getURLVar(urlVarName) {
	var urlHalves = String(document.location).split('?');
	var urlVarValue = '';
	if(urlHalves[1]){
		var urlVars = urlHalves[1].split('&');
		for(i=0; i<=(urlVars.length); i++){
			if(urlVars[i]){	
				var urlVarPair = urlVars[i].split('=');
				if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	return urlVarValue;   
}

function trim (str) {
	str = this != window? this : str;
	return str.replace(/^\s+/, '').replace(/\s+$/,'');
}

//activities and venues
function PaintballSearch() {
	p_xml_processed = false;

	////alert(town_xml);

	townsearchlat = $("data towndata:first",town_xml).attr("lat");
	townsearchlon = $("data towndata:first",town_xml).attr("lon");

	$.ajax({
		//async: false,
		type: 'GET',
		url: "/mysql/site-list-by-activity-mini.asp",
		dataType: 'xml',
		data: "categoryID=0&activityID=1&lat="+townsearchlat+"&lon="+townsearchlon+"&websiteid="+websiteID,
		complete: function(a, b){
			//alert(b);
			//alert(a.readyState);
			//alert(a.responseText);
			//alert(a.responseXML);
			//alert(a.responseBody);
			//alert(a.status);
			//alert(a.statusText);
			if( b == 'success' ) {
				var xmlDoc = a.responseXML;
				sites_p_xml = xmlDoc;
				TopInfoBox();
				//alert("line 96: "+$('mark:first', sites_p_xml).attr('ttl'));

			if(getURLVar("gamedate") != "") {
				var gamedate = getURLVar("gamedate");
			} else {
				var d = new Date();
				var day = d.getUTCDay();

				d.setDate(d.getDate()+(6-day));

				var year = 1900+d.getYear();
				var month = d.getMonth() + 1;
				var day = d.getDate();

				if(month < 10) {
					month = "0"+month;
				}

				if(day < 10) {
					day = "0"+day;
				}

				var gamedate = year+"-"+month+"-"+day;
			}
			
			$.ajax({
				//async: false,
				type: 'GET',
				url: "/mysql/availability-ajax.asp",
				dataType: 'html',
				data: "booking_ref="+$("mark:first",sites_p_xml).attr('bookref')+"&gamedate="+gamedate,
				complete: function(a, b){
					if( b == 'success' ) {
						var html = a.responseText;
						//avail_html = html;
						$("div#this-week").empty().append(html);
						p_xml_processed = true;
					}
				}
			});


			}
		}
	});
	
}

function IndoorPaintballSearch() {

	i_xml_processed = false;

	townsearchlat = $("data towndata:first",town_xml).attr("lat");
	townsearchlon = $("data towndata:first",town_xml).attr("lon");

	$.ajax({
		//async: false,
		type: 'GET',
		url: "/mysql/site-list-by-activity-mini.asp",
		dataType: 'xml',
		data: "categoryID=0&activityID=60&lat="+townsearchlat+"&lon="+townsearchlon+"&websiteid="+websiteID,
		complete: function(a, b){
			//alert(b);
			//alert(a.readyState);
			//alert(a.responseText);
			//alert(a.responseXML);
			//alert(a.responseBody);
			//alert(a.status);
			//alert(a.statusText);
			if( b == 'success' ) {
				var xmlDoc = a.responseXML;
				sites_i_xml = xmlDoc;
				//alert("Indoor: "+$("mark:first",sites_i_xml).attr('ttl'));
				i_xml_processed = true;
			} else {
				//alert("Indoor painball failed");
			}
		}
	});
}

function LaserSearch() {

	l_xml_processed = false;

	townsearchlat = $("data towndata:first",town_xml).attr("lat");
	townsearchlon = $("data towndata:first",town_xml).attr("lon");
	
	////alert("Lat = "+townsearchlat+"\nLon = "+townsearchlon);

	$.ajax({
		//async: false,
		type: 'GET',
		url: "/mysql/site-list-by-activity-mini.asp",
		dataType: 'xml',
		data: "categoryID=0&activityID=7&lat="+townsearchlat+"&lon="+townsearchlon+"&websiteid="+websiteID,
		complete: function(a, b){
			//alert(b);
			//alert(a.readyState);
			//alert(a.responseText);
			//alert(a.responseXML);
			//alert(a.responseBody);
			//alert(a.status);
			//alert(a.statusText);
			if( b == 'success' ) {
				var xmlDoc = a.responseXML;
				sites_l_xml = xmlDoc;
				//alert("Laser: "+$("mark:first",sites_l_xml).attr('ttl'));
				l_xml_processed = true;
			} else {
				//alert("laser failed");
			}
		}
	});
}

//Top Info Box
function TopInfoBox() {
	
	if(t_xml_processed == true && p_xml_processed == true && i_xml_processed == true && l_xml_processed == true) {
	
		//alert("line 197: "+$('mark:first', sites_p_xml).attr('ttl'))
		
		if(document.searcher.str_town.value == "Town Search ...") {
			str_search = getURLVar("str_town").replace(/\+/," ");
		} else {
			str_search = document.searcher.str_town.value.replace(/\+/," ");
		}

		parts = str_search.split(" ");
		disp_search = str_search;

		if (parts.length == 2) {
			if (parts[0].length <=4 && parts[1].length <=3) {
				//probably a postcode
				$("#nearest-venue h3").empty().append("Paintball "+$('mark:first', sites_p_xml).attr('ttl'));
				$("#nearest-venue dl dd.description").empty().append("Paintball "+$('mark:first', sites_p_xml).attr('ttl')+" is the nearest <span id='topBoxAct'>paintball</span> venue to "+disp_search+".");
			}
		} else {
			$("#nearest-venue h3").empty().append("Paintball "+disp_search);
			$("#nearest-venue dl dd.description").empty().append("<b>Paintball "+$('mark:first', sites_p_xml).attr('ttl')+"</b> is the nearest <span id='topBoxAct'>paintball</span> venue to "+disp_search+".");
		}

		//$("#nearest-venue h3").empty().append("Paintball "+getURLVar("str_town"));
		//$("#nearest-venue dl dd.description").empty().append("<b>Paintball "+$('mark:first', sites_p_xml).attr('ttl')+"</b> is the nearest <span id='topBoxAct'>paintball</span> venue to "+getURLVar("str_town")+".");
		$("#nearest-venue dl dd.distance").empty().append($('mark:first', sites_p_xml).attr('dst')+" miles - Approx");
		$("#nearest-venue dl dd a").attr("href","javascript:tb_show('','http://console.theactivitypeople.co.uk/venue.php?activityID="+$('activ:first',sites_p_xml).attr('act')+"&locationID="+$('activ:first',sites_p_xml).attr('loc')+"&websiteID="+websiteID+"&KeepThis=true&TB_iframe=true&height=415&width=596','')");

		$("div.column1 p").remove();

		//how to get website url?

		var url_self = (document.location)+"";
		var url_parts = url_self.split("paintballing-site.co.uk");

		if(url_parts.length > 1) {
			priceAdjust = -6;
		} else {
			priceAdjust = 0;
		}

		/*
		switch(websiteID) {
			case 23:
				priceAdjust = -6;
				break;
			default:
				priceAdjust = 0;
		}
		*/

		$("feature",sites_p_xml).each(function() {
			switch($(this).attr("name")) {
				case "Half Day" :
					$("#nearest-venue-links").before("<p><strong><a href=\"javascript:tb_show('','http://console.theactivitypeople.co.uk/venue.php?activityID="+$('activ:first',sites_p_xml).attr('act')+"&locationID="+$('activ:first',sites_p_xml).attr('loc')+"&websiteID="+websiteID+"&KeepThis=true&TB_iframe=true&height=415&width=596','')\" title='Pay As You Play Paintball' class='thickbox'>"+$(this).attr("name")+"</a></strong> &pound;"+(parseFloat($(this).attr("value"))+priceAdjust)+"</p>");
					break;
				case "Full Day" :
					$("#nearest-venue-links").before("<p><strong><a href=\"javascript:tb_show('','http://console.theactivitypeople.co.uk/venue.php?activityID="+$('activ:first',sites_p_xml).attr('act')+"&locationID="+$('activ:first',sites_p_xml).attr('loc')+"&websiteID="+websiteID+"&KeepThis=true&TB_iframe=true&height=415&width=596','')\" title='Pay As You Play Paintball' class='thickbox'>"+$(this).attr("name")+"</a></strong> &pound;"+(parseFloat($(this).attr("value"))+priceAdjust)+"</p>");
					break;
				default:
					$("#nearest-venue-links").before("<p><strong>"+$(this).attr("name")+"</strong> &pound;"+$(this).attr("value")+"</p>");
			}
		});

		var html = "<b>Nearest Venues to "+document.searcher.str_town.value+"</b><table width='543' border='0' cellpadding='2' cellspacing='2'><tr><td width='100' height='25' valign='medium'>Paintball</td>"

		xx=0;

		$('mark', sites_p_xml).each(function() {
			if(xx == 0) {
				$("#nearest-venue-links a").attr("href","javascript:tb_show('','http://console.theactivitypeople.co.uk/venue.php?activityID="+$('activ',this).attr('act')+"&locationID="+$('activ', this).attr('loc')+"&websiteID="+websiteID+"&KeepThis=true&TB_iframe=true&height=415&width=596','')");
				$("#nearest_img").attr("src","http://console.theactivitypeople.co.uk/img/photos/1/"+$('activ', this).attr('loc')+"/1.jpg");
				$("input[@name='siteid']").attr("value",$('activ', this).attr('loc'));
				$("#nearest-venue-links").show();						
			} else {
				if(xx > 3) {
					return false;
				} else {
					html = html + "<td align='center' valign='medium' width='147'><a href=\"javascript:tb_show('','http://console.theactivitypeople.co.uk/venue.php?activityID="+$('activ',this).attr('act')+"&locationID="+$('activ', this).attr('loc')+"&websiteID="+websiteID+"&KeepThis=true&TB_iframe=true&height=415&width=596','')\"><span>"+$(this).attr('ttl')+"</span> "+$(this).attr('dst')+" miles</a></td>";
				}
			}
			xx++;	
		});

		html = html + "</tr><tr><td height='25' valign='medium'>Indoor Paintball </td>"


		xx=0;

		$('mark', sites_i_xml).each(function() {
			if(xx > 2) {
				return false;
			} else {
				html = html + "<td align='center' valign='medium'><a href=\"javascript:tb_show('','http://console.theactivitypeople.co.uk/venue.php?activityID="+$('activ',this).attr('act')+"&locationID="+$('activ', this).attr('loc')+"&websiteID="+websiteID+"&KeepThis=true&TB_iframe=true&height=415&width=596','')\"><span>"+$(this).attr('ttl')+"</span> "+$(this).attr('dst')+" miles</a></td>";
			}
			xx++;	
		});

		html = html +  "</tr><tr><td height='25' valign='medium'>Laser Combat </td>"

		xx=0;

		$('mark', sites_l_xml).each(function() {
			if(xx > 2) {
				return false;
			} else {
				html = html + "<td align='center' valign='medium'><a href=\"javascript:tb_show('','http://console.theactivitypeople.co.uk/venue.php?activityID="+$('activ',this).attr('act')+"&locationID="+$('activ', this).attr('loc')+"&websiteID="+websiteID+"&KeepThis=true&TB_iframe=true&height=415&width=596','')\"><span>"+$(this).attr('ttl')+"</span> "+$(this).attr('dst')+" miles</a></td>";
			}
			xx++;	
		});

		html = html +  "</tr></table>";

		$("#nearest_activities").empty().append(html);
		return true;
	} else {
		xml_tries++;
		if(xml_tries < 10) {
			setTimeout("TopInfoBox()",100);
		} else {
			//alert("I tried 10 times to get the XML and each time it failed - go change your browser to fireox and try again\ntowns = "+t_xml_processed+"\nPaintball = "+p_xml_processed+"\nIndoor = "+i_xml_processed+"\nLaser ="+l_xml_processed);
			return false;
		}
	}

}

//<td align='center' valign='medium' bgcolor='#333333'></td>

//initialise
function Initialise(str_town) {
	
	if(str_town != '') {
	
		var itm = str_town;

		var display_itm = itm;
		display_itm = decodeURI(display_itm);
		var itm_frags = display_itm.split('#');
		display_itm = itm_frags[0];
		$('input#str_town').attr('value',display_itm);

		t_xml_processed = false;

		$("div#this-week").empty().append('Loading...');
		$("#nearest-venue dl dd.description").empty().append('Loading...');

		////alert("/mysql/townsearch.asp?"+"townsearch="+town);

		$.ajax({
			//async: false,
			type: 'GET',
			url: "/mysql/townsearch.asp",
			dataType: 'xml',
			data: "townsearch="+itm,
			complete: function(a, b){
				if( b == 'success' ) {
					var xmlDoc = a.responseXML;
					town_xml = xmlDoc;
					changetown(itm);

					var activityID = getURLVar("activityID");
					var categoryID = getURLVar("categoryID");

					var activity = getURLVar("activity");

					if(activity != '') {
						changeactivity(activity);
					}

					if(activityID == '') {
						activityID = 0;
					}

					if(categoryID == '') {
						categoryID = 0;
					}

					$("#nearest_activities").empty();

					//activitySearch(categoryID,activityID);
					//alert("about to call painball search");
					PaintballSearch();
					//alert("after PB search");
					//alert("about to call indoor painball search");
					IndoorPaintballSearch();
					//alert("after IPB search");
					//alert("about to call laser search");
					LaserSearch();
					//alert("after laser search");


					//alert(xml_tries);

					t_xml_processed = true;
				}
			}
		});


	}

}

function changetown(a) {
	var a = decodeURI(a);
	$("span#act_town").empty().append(a);
}

function changeactivity(a) {
	var a = decodeURI(a);
	$("span#act_type").empty();
	$("span#act_type").append(a);
}

$(function() {
	
	if(str_town == "") {
		var txt = $("div.sitemap h1").text();
		txt = txt+"";
		
		//return str.replace(/^\s+/, '').replace(/\s+$/,'');
		
		txt = txt.replace(/Paintballing/,"");
		txt = trim(txt);
		if(txt != '') {
			str_town = txt;
			document.searcher.str_town.value = str_town;
			Initialise(str_town);
		}
		
	}

	$("form[@name='searcher']").submit(function() {
		str_town = $("input[@name='str_town']").val();
		Initialise(str_town);
		return false;
	});
});

$.delegate("div.jcalendar table td a.td","click",function(){
	var url = $(this).attr('href')+"&str_town="+str_town;
	document.location = url;

	return false;
});


$("div.jcalendar").livequery(function() {
	updateCalendarTitle();
});

$("div.jcalendar-links a").livequery('click',function() {
	updateCalendarTitle();
});


function updateCalendarTitle() {
	
	$("div#calendarTitle").remove();
	
	var month_num = $("select[@name='month']").val();
	var year = $("select[@name='year']").val();
	var month = "";
	switch(parseInt(month_num)) {
		case 1:
			month = "January";
			break;
		case 2:
			month = "February";
			break;
		case 3:
			month = "March";
			break;
		case 4:
			month = "April";
			break;
		case 5:
			month = "May";
			break;
		case 6:
			month = "June";
			break;
		case 7:
			month = "July";
			break;
		case 8:
			month = "August";
			break;
		case 9:
			month = "Septamber";
			break;
		case 10:
			month = "October";
			break;
		case 11:
			month = "November";
			break;
		case 12:
			month = "December";
			break;
	}
	
	$("div.jcalendar").prepend("<div id='calendarTitle' style='text-align: center;'>"+month+" "+year+"</div>");
}

//when the location list div is in the dom, Initialise
schedule("help","Initialise(str_town)");