/*****************************************************************************************************

	Javascript functions for the tri247 website pages.
	
	Copyright 2006 Tri247 Ltd. / Pretentious Ltd.

*****************************************************************************************************/


/*
	Control over the homepage.
*/

var tri247_user_special_current = 0;
var tri247_user_special_playing = true;


function tri247_user_home_init()
{
	tri247_user_special_next();
	
	var movie = new SWFObject("bigregions.swf", "movie_bigregions", "308", "361", "8", "#FFFFFF");
	movie.addParam("scale", "noscale");
	movie.addParam("wmode", "transparent");
	movie.write("articles_24_map")
}


function tri247_user_special_next()
{
	if (tri247_user_special_playing)
	{
		tri247_user_special_current++;
		
		if (tri247_user_special_current > 5)
			tri247_user_special_current = 1;
			
		tri247_user_special_show(tri247_user_special_current);
		
		setTimeout('tri247_user_special_next()', 5000);
	}
}


function tri247_user_special_stop(n)
{
	tri247_user_special_playing = false;
	tri247_user_special_show(n);
}


function tri247_user_special_show(n)
{
	var i = 1;

	// Get rid of all buttons.	
	for (i = 1; i <= 5; i++)
	{
		document.getElementById('articles_21_special_button_'+i+'_off').style.display = 'none';
		document.getElementById('articles_21_special_button_'+i+'_on').style.display = 'none';
	}

	// Get rid of all content.
	for (i = 1; i <= 5; i++)
	{
		document.getElementById('articles_21_special_content_'+i).style.display = 'none';
	}
	
	// Show the content.
	Effect.Appear('articles_21_special_content_'+n, { duration: 1 });
	
	// Show the buttons.	
	for (i = 1; i <= 5; i++)
	{
		if (i == n)
			document.getElementById('articles_21_special_button_'+i+'_on').style.display = 'block';
		else
			document.getElementById('articles_21_special_button_'+i+'_off').style.display = 'block';
	}
}


/*
	Asks the user if they are sure they want to proceed before a link is processed.
*/
function tri247_areyousure_link(message, link)
{
	if (confirm(message))
	{
		document.location = link;
	}
}


/*
	Used to add bookmarks.
*/
function tri247_user_bookmark(page_title, page_url)
{
	if (window.sidebar)
	{
		// Firefox
		window.sidebar.addPanel(page_title, page_url, "");
	}
	else if (window.opera && window.print)
	{
		// Opera
		var elem = document.createElement('a');
		elem.setAttribute('href',page_url);
		elem.setAttribute('title',page_title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if (document.all)
	{
		// IE
		window.external.AddFavorite(page_url, page_title);
	}
	else
	{
		// Otherwise!
		alert("Sorry, we cannot automatically add bookmarks to your browser");
	}
}


/*
	Opens up a new window to print an article.
*/
function tri247_user_printpage(article_id)
{
	window.open('print_'+article_id+'.html','','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=600,height=400');
}


function tri247_user_regions_reveal()
{
	Effect.SlideUp('area_region_off', { afterFinish : function() 
		{
			Effect.SlideDown('area_region_on', { afterFinish : function()
				{
					Effect.Appear('area_region_select', { afterFinish : function()
						{
							var movie = new SWFObject("regions.swf", "movie_regions", "160", "201", "8", "#FFFFFF");
							movie.addParam("scale", "noscale");
							movie.addParam("wmode", "transparent");
							movie.write("area_region_map")
						}
					});
				}
			});
		}
	});
}


/*
	Used to dynamically explain what the Alias is.
*/
function tri247_user_help_screenname(show)
{
	if (show)
	{
		var new_area = document.createElement('div');
		new_area.id = 'help_screenname';
		new_area.style.position = 'absolute';
		new_area.style.left = '380px';
		new_area.style.top = '450px';
		document.getElementById('document_body').appendChild(new_area);
		
		Effect.Fade('help_screenname', { duration : 0.1, afterFinish : function() 
			{ 
				new_area.style.width = '200px';
				new_area.style.height = '50px';
				new_area.style.padding = '5px';
				new_area.style.border = 'solid 1px #B20000';
				new_area.style.backgroundColor = '#FFFFFF';
				new_area.style.textAlign = 'left';
				
				new_area.innerHTML = "";
				new_area.innerHTML += "This will be used as the name shown on any comments you post.";
				new_area.innerHTML += "<br /><br />";
				new_area.innerHTML += "<div style=\"width : 100%; text-align : right;\"><a href=\"javascript:tri247_user_help_screenname(false);\">[close]</a></div>";
				
				Effect.Appear('help_screenname', { duration : 0.8 } );
			}
		});
	}
	else
	{
		Effect.Fade('help_screenname', { duration : 0.8, afterFinish : function() 
			{ 
				document.getElementById('document_body').removeChild(document.getElementById('help_screenname'));
			}
		});
	}
}


/*
	Used to dynamically change the background on the site
*/
function tri247_user_changebackground(obj, color)
{
	obj.style.backgroundColor = color;
}


/*
	Used to dynamically change images on the site.
*/
function tri247_user_changeimage(image, url)
{
	image.src = url;
}


/*
	Used to dynamically change images on the site.
*/
function tri247_user_changeimageid(image_id, url)
{
	document.getElementById(image_id).src = url;
}


/*
	Used to disable and enable image for news article
*/
function tri247_user_admin_news_change_image(form)
{
	for (i = 0; i < form.image_options.options.length; i++)
	{
		if (form.image_options.options[i].selected)
			value = form.image_options.options[i].value;
	}
	
	if (value == "new")
	{
		form.desc_image.disabled = false;
	}
	else
	{
		form.desc_image.value = '';
		form.desc_image.disabled = true;
	}
}

		
/*
	Used to dynamically show/hide the Pretentious info.
*/
function tri247_user_pretentious()
{
	var ref = document.getElementById('bottom_pretentious_text');
	
	if (ref.innerHTML == '')
		ref.innerHTML='Site by Pretentious';
	else
		ref.innerHTML='';
}


/*
	Used to pop up the terms and conditions for the site.
*/
function tri247_user_showterms(id)
{
	window.open('terms.html','','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=300,height=400');
}


/*
	Submits the form if everything is OK.
	
	Parameters:
	
		do_continue			true for "yes", otherwise false.
		do_step_1_checks		Either true or false.
*/
function tri247_user_signup_submit(do_continue, do_step_1_checks)
{
	form_elem = document.getElementById('signup_form');
	
	var warning_message = "";
	
	if (do_step_1_checks)
	{
		if (form_elem.email.value == "")
			warning_message = "Please enter an email address";
	
		if(form_elem.password.value == "")
			warning_message = "Please enter a password";
	
		if(form_elem.password.value != form_elem.password2.value)
			warning_message = "Please enter matching passwords";
		
		if(form_elem.email.value != form_elem.email2.value)
			warning_message = "Please enter matching e-mail addresses";
		
		if(form_elem.alias.value == "")
			warning_message = "Please enter an alias";
	}
	
	if (warning_message != "")
	{
		alert(warning_message);
	}
	else
	{
		if (do_continue)
			form_elem.do_continue.value = "yes";
		else
			form_elem.do_continue.value = "no";
			
		form_elem.submit();
	}
}


/*
	Votes in a poll.
*/
function tri247_user_poll_vote(answer_id)
{
	// Set up request processor, XML processor and URL.
	var request;
	var xmlDoc;
	
	var url = 'user_poll.ajax?answer_id='+String(answer_id);
	
	// Execute the query.
	if (window.XMLHttpRequest) 
	{
		request = new XMLHttpRequest();
		request.open("GET", url, false);
		request.send(null);
	}
	else if (window.ActiveXObject) 
	{
		request = new ActiveXObject("Microsoft.XMLHTTP");
		if (request) 
		{
			request.open("GET", url, false);
			request.send();
		}
	}

	// Put the response in place.
	if (request.status == 200)
	{
		if (request.responseText != '' && request.responseText != 'null' && request.responseText != null)
			alert(request.responseText);
	}
}


// These are the GMap objects.
var gmaps_map = null;
var gmaps_zoom_level = null;
var gmaps_markers = new Object();
var gmaps_info_values = new Object();
var gmaps_info_num = new Object();
var gmaps_marker_default_type = null;
var gmaps_marker_default_id = null;
var gmaps_click_listener = null;


// Create the icon class.
try
{
	var gmaps_icon = new GIcon();
	gmaps_icon.shadow = "media/user/images/pins/shadow.png";
	gmaps_icon.iconSize = new GSize(31, 46);
	gmaps_icon.shadowSize = new GSize(51, 47);
	gmaps_icon.iconAnchor = new GPoint(31, 46);
	gmaps_icon.infoWindowAnchor = new GPoint(31, 1);
}
catch (e) { }

/*
	Google Maps Initialise
*/
function tri247_user_gmaps_init(start_lat, start_lng, start_zoom, resource_type, resource_id, resource_lat, resource_lng)
{
	if (GBrowserIsCompatible()) 
	{
		gmaps_map = new GMap2(document.getElementById("area_google_map"));

		GEvent.addListener(gmaps_map, "moveend", function() 
			{
				tri247_user_gmaps_update();
			});
		
		if (start_lat != null)
		{
			gmaps_map.setCenter(new GLatLng(start_lat, start_lng), start_zoom);
			gmaps_map.addControl(new GLargeMapControl());
		}
		else if (resource_type == null)
		{
			gmaps_map.setCenter(new GLatLng(54.622, -3.515), 5);
			gmaps_map.addControl(new GLargeMapControl());
		}
		else
		{
			gmaps_marker_default_type = resource_type;
			gmaps_marker_default_id = resource_id;
			gmaps_map.setCenter(new GLatLng(resource_lat, resource_lng), 11);
			gmaps_map.addControl(new GLargeMapControl());
		}
	}
}


/*
	Updates our preloader.
*/
function tri247_user_gmaps_loader_width(percent_complete)
{
	 return String(Math.max(1, Math.round(percent_complete / 100 * 178)))+'px';
}


/*
	Google Maps Initialise
*/
function tri247_user_gmaps_update()
{
	// Starting.
	document.getElementById('area_google_loader').style.width = tri247_user_gmaps_loader_width(0);
	
	// Get information about the current map view.
	var zoom_level = gmaps_map.getZoom();
	var bounds = gmaps_map.getBounds();
	var lat_north = bounds.getNorthEast().lat();
	var lat_south = bounds.getSouthWest().lat();
	var lng_east = bounds.getNorthEast().lng();
	var lng_west = bounds.getSouthWest().lng();
	
	// Clear all current addresses.
	if (zoom_level != gmaps_zoom_level)
	{
		gmaps_zoom_level = zoom_level;
		gmaps_map.clearOverlays();
		for (key in gmaps_markers)
		{
			delete gmaps_markers[key];
		}
		
		if  (gmaps_click_listener != null)
			GEvent.removeListener(gmaps_click_listener);

		if (gmaps_zoom_level < 9)
		{
			gmaps_click_listener = GEvent.addDomListener(gmaps_map, "click", function(overlay, point) 
				{ 
					this.setCenter(point, this.getZoom() + 1);
					tri247_user_gmaps_update();
				});
		}
	}

	// Put together the list of resource types that we are looking for.
	var resource_string = '';
	var resource_types = Array('event', 'club','coach','course','facility','service','shop');
	for (var i = 0; i < resource_types.length; i++)
	{
		if (document.getElementById('input_gmaps_show_'+resource_types[i]).checked)
		{
			if (resource_string != '')
				resource_string += ',';
			resource_string += resource_types[i];
		}
	}
		
	// Request information from the server.
	document.getElementById('area_google_loader').style.width = tri247_user_gmaps_loader_width(50);
	//document.getElementById('area_google_message').innerHTML = 'zoom_level='+zoom_level+'&lat_north='+lat_north+'&lat_south='+lat_south+'&lng_east='+lng_east+'&lng_west='+lng_west+'&resource_types='+resource_string;
	var response = tri247_user_request('user_gmaps.ajax', 'zoom_level='+zoom_level+'&lat_north='+lat_north+'&lat_south='+lat_south+'&lng_east='+lng_east+'&lng_west='+lng_west+'&resource_types='+resource_string);
	//alert ((new XMLSerializer()).serializeToString(response));

	// Add resources.
	var resources = response.getElementsByTagName('resource');
	for (var i = 0; i < resources.length; i ++)
	{
		try
		{
			var resource_type = resources[i].attributes[0].value;
			var resource_id = resources[i].attributes[1].value;
			var resource_lat = resources[i].attributes[2].value;
			var resource_lng = resources[i].attributes[3].value;
			var resource_name = resources[i].attributes[4].value;
			var resource_url = resources[i].attributes[5].value;
			var resource_description = resources[i].attributes[6].value;
			
			if (gmaps_markers[resource_type+'_'+resource_id] == null)
				if (document.getElementById('input_gmaps_show_'+resource_type).checked)
					gmaps_markers[resource_type+'_'+resource_id] = tri247_user_gmaps_showaddress('resource', resource_type, resource_id, resource_lat, resource_lng, "<a href=\""+resource_url+"\"><b>"+resource_name+"</b></a><br />"+resource_description);
		}
		catch (e) { alert(e); }
	}

	// Remove necessary resources and ALL regions.
	for (key in gmaps_markers)
	{
		var resource_type = key.split('_');

		try
		{
			if (resource_type[0] == 'region')
			{
				gmaps_map.removeOverlay(gmaps_markers[key]);
				delete gmaps_markers[key];
			}
			else if (!document.getElementById('input_gmaps_show_'+resource_type[0]).checked)
			{
				gmaps_map.removeOverlay(gmaps_markers[key]);
				delete gmaps_markers[key];
			}
		}
		catch (e) { } ;
	}

	// Add new regions.
	var regions = response.getElementsByTagName('region');
	for (var i = 0; i < regions.length; i ++)
	{
		try
		{
			var region_id = regions[i].attributes[0].value;
			var region_lat = regions[i].attributes[1].value;
			var region_lng = regions[i].attributes[2].value;
			var region_name = regions[i].attributes[3].value;
			var region_count = regions[i].attributes[4].value;
			if (gmaps_markers['region_'+region_id] == null)
			{
				gmaps_markers['region_'+region_id] = tri247_user_gmaps_showaddress('region', null, null, region_lat, region_lng, region_name+'<br />'+region_count+' Listings');
			}
		}
		catch (e) { alert(e); }
	}
	
	// Finished.
	document.getElementById('area_google_loader').style.width = tri247_user_gmaps_loader_width(100);
}


/*
	Adds a new resource to the map, taking care of any collisions.
*/
function tri247_user_gmaps_get_marker(new_resource_type, new_info_html, new_address_lat, new_address_lng)
{
	var current_ok = true;
	var new_marker = null;
	var old_marker_key = null;
	
	for (key in gmaps_markers)
	{
		var resource_type = key.split('_');

		try
		{
			if (resource_type[0] != 'region')
			{
				if (gmaps_markers[key].getPoint().lat() == new_address_lat && gmaps_markers[key].getPoint().lng() == new_address_lng)
				{
					old_marker = gmaps_markers[key];
					current_ok = false;
				}
			}
		}
		catch (e) { } ;
	}

	/*
		Three possibilities:
		
			New marker!
			Old marker, one of first three!
			Old marker, more than three already in place!
	*/
	if (current_ok)
	{
		// Add new marker in this position.
		var icon = new GIcon(gmaps_icon);
		icon.image = "media/user/images/pins/pin_"+new_resource_type+".png";
		new_marker = new GMarker(new GLatLng(new_address_lat, new_address_lng), icon);
		
		// Store info on this marker.
		gmaps_info_values[new_address_lat+'_'+new_address_lng] = new_info_html;
		
		// Record the fact that this is the first.
		gmaps_info_num[new_address_lat+'_'+new_address_lng] = 0;
		
		// Create the info window.
		GEvent.addListener(new_marker, "click", function() 
			{
				new_marker.openInfoWindowHtml(gmaps_info_values[new_address_lat+'_'+new_address_lng]);
			});
	}
	else
	{
		// Remove the old icon from the map.
		gmaps_map.removeOverlay(old_marker);
		
		// Adjust the marker in this position and return it.
		old_marker.getIcon().image = "media/user/images/pins/pin_multi.png";
		new_marker = old_marker;
		
		// Store info on this marker.
		if (gmaps_info_num[new_address_lat+'_'+new_address_lng] < 2)
			gmaps_info_values[new_address_lat+'_'+new_address_lng] += '<br /><br />'+new_info_html;
		else if (gmaps_info_num[new_address_lat+'_'+new_address_lng] == 2)
			gmaps_info_values[new_address_lat+'_'+new_address_lng] += '<br /><br /><a href="lnglat_'+new_address_lat+'_'+new_address_lng+'.html"><b>Click for more ...</b></a>';
		
		// Increment the counter.
		gmaps_info_num[new_address_lat+'_'+new_address_lng]++;
	}

	return new_marker;
}


/*
	Adds an address to the map as a point.
*/
function tri247_user_gmaps_showaddress(address_type, resource_type, resource_id, address_lat, address_lng, info_html)
{
	var address = null;

	if (address_type == 'resource')
	{
		address = tri247_user_gmaps_get_marker(resource_type, info_html, address_lat, address_lng);
	}
	else // address_type == 'region'
	{
		// This class is an override for GOverlay that allows us to have our regions as nice boxes.
		// For some reason, I have to declare it inline!
		function Region(address_lat, address_lng, info_html) 
		{
			this.lat_ = address_lat;
			this.lng_ = address_lng;
			this.info_html_ = info_html;
		}
		Region.prototype = new GOverlay();
		Region.prototype.initialize = function(map) 
		{
			var container = document.createElement("div");
			var zoomInDiv = document.createElement("div");
			this.setButtonStyle_(zoomInDiv);
			container.appendChild(zoomInDiv);
			zoomInDiv.innerHTML = this.info_html_;
			//GEvent.addDomListener(zoomInDiv, "click", function() { map.zoomIn(); });
			map.getPane(G_MAP_MARKER_PANE).appendChild(container);
			this.map_ = map;
			this.div_ = container;
		}
		Region.prototype.remove = function() { this.div_.parentNode.removeChild(this.div_); }
		Region.prototype.copy = function() 
		{
			return new Region(this.backgroundColor_, this.opacity_);
		}
		Region.prototype.redraw = function(force) 
		{
			if (!force) return;
			var gpoint2 = this.map_.fromLatLngToDivPixel(new GLatLng(this.lat_, this.lng_));
			this.div_.style.position = 'absolute';
			this.div_.style.left = gpoint2.x + "px";
			this.div_.style.top = gpoint2.y + "px";
		}
		Region.prototype.setButtonStyle_ = function(button) 
		{
			button.style.font = "10px Verdana,Arial,sans-serif";
			button.style.textDecoration = "none";
			button.style.color = "#000000";
			button.style.backgroundColor = "#FFFFFF";
			button.style.border = "1px solid #000000";
			button.style.padding = "2px";
			button.style.marginBottom = "3px";
			button.style.textAlign = "center";
			button.style.cursor = "pointer";
		}
		
		// Now use the class defined above.
		address = new Region(address_lat, address_lng, info_html);
	}
		
	gmaps_map.addOverlay(address);	
	
	if (address_type == 'resource' && resource_type == gmaps_marker_default_type && resource_id == gmaps_marker_default_id)
	{
		address.openInfoWindowHtml(info_html);
	}
	
	return address;
}


/*
	Sends an HTTP request and returns the resulting XML object.
*/
function tri247_user_request(url, parameters)
{
	// Send the HTTP request.
	if (window.XMLHttpRequest) 
	{
		request = new XMLHttpRequest();
		request.open("POST", url, false);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		request.send(parameters);
	}
	else if (window.ActiveXObject) 
	{
		request = new ActiveXObject("Microsoft.XMLHTTP");
		request.open("POST", url, false);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		request.send(parameters);
	}

	// Process response on a successful return.
	if (request.status == 200)
	{
		var xml_response = '';
		if (window.ActiveXObject) 
		{
			xml_response = new ActiveXObject("Microsoft.XMLDOM");
			xml_response.loadXML(request.responseText);
		}
		else
		{
			xml_response = (new DOMParser()).parseFromString(request.responseText, "text/xml");
		}
		
		return xml_response;
	}
}


/*
	Mazda Performance Predictor
*/
var performance_ratio_yards_to_metres = 0.9144;
var performance_ratio_km_to_metres = 1000;
var performance_ratio_miles_to_metres = 1609;
function performance_calculate_get_metres(distance_n, distance_units)
{
	if (distance_units == "metres")
	{
		return distance_n;
	}
	else if (distance_units == "yards")
	{
		return distance_n * performance_ratio_yards_to_metres;
	}
	else if (distance_units == "km")
	{
		return distance_n * performance_ratio_km_to_metres;
	}
	else if (distance_units == "miles")
	{
		return distance_n * performance_ratio_miles_to_metres;
	}
	else
	{
		alert('Performance Conversion Error');
		return 0;
	}
}
function performance_calculate_get_seconds(time_hours, time_minutes, time_seconds)
{
	var seconds = 0;
	seconds += Math.round(time_seconds);
	seconds += Math.round(time_minutes * 60);
	seconds += Math.round(time_hours * 60 * 60);
	return seconds;
}
function performance_calculate_get_time(time_seconds)
{
	var hours = Math.floor(time_seconds / 3600);
	time_seconds = time_seconds - (hours * 3600);
	var minutes = Math.floor(time_seconds / 60);
	time_seconds = time_seconds - (minutes * 60);
	var seconds = time_seconds;
	if (String(hours).length == 1)
		hours = '0'+hours;
	if (String(minutes).length == 1)
		minutes = '0'+minutes;
	if (String(seconds).length == 1)
		seconds = '0'+seconds;
	return hours+":"+minutes+":"+seconds;
}
function performance_calculate()
{
	var distance_swim_array = document.getElementById('area_performance_swim_distance').value.split('_');
	var distance_swim_n = distance_swim_array[0];
	var distance_swim_units = distance_swim_array[1];
	var distance_swim = performance_calculate_get_metres(distance_swim_n, distance_swim_units);
	var seconds_swim = performance_calculate_get_seconds(document.getElementById('area_performance_swim_hours').value, document.getElementById('area_performance_swim_minutes').value, document.getElementById('area_performance_swim_seconds').value)
	
	var distance_bike_array = document.getElementById('area_performance_bike_distance').value.split('_');
	var distance_bike_n = distance_bike_array[0];
	var distance_bike_units = distance_bike_array[1];
	var distance_bike = performance_calculate_get_metres(distance_bike_n, distance_bike_units);
	var seconds_bike = performance_calculate_get_seconds(document.getElementById('area_performance_bike_hours').value, document.getElementById('area_performance_bike_minutes').value, document.getElementById('area_performance_bike_seconds').value)
	
	var distance_run_array = document.getElementById('area_performance_run_distance').value.split('_');
	var distance_run_n = distance_run_array[0];
	var distance_run_units = distance_run_array[1];
	var distance_run = performance_calculate_get_metres(distance_run_n, distance_run_units);
	var seconds_run = performance_calculate_get_seconds(document.getElementById('area_performance_run_hours').value, document.getElementById('area_performance_run_minutes').value, document.getElementById('area_performance_run_seconds').value)
	
	var race_format = document.getElementById('area_performance_race_format').value;

	if (seconds_swim == 0 || seconds_bike == 0 || seconds_run == 0)
	{
		alert('Please enter a time for all three stages');
	}
	else
	{
		var xml_response = tri247_user_request('user_predictor.ajax', 'distance_swim='+distance_swim+'&seconds_swim='+seconds_swim+'&distance_bike='+distance_bike+'&seconds_bike='+seconds_bike+'&distance_run='+distance_run+'&seconds_run='+seconds_run+'&race_format='+race_format);
		var predictions = xml_response.getElementsByTagName('prediction');
		for (var i = 0; i < predictions.length && i == 0; i ++)
		{
			var time_total = predictions[i].attributes[0].value;
			var movie = new SWFObject("predictor.swf?time_total="+performance_calculate_get_time(time_total), "movie_predictor", "262", "83", "9", "#8ED4F7");
			movie.addParam("scale", "noscale");
			movie.addParam("wmode", "transparent");
			movie.write("area_predictor")
		}
	}
	
	return null;
}

