/*
	Always called to initialise the site.
*/
function run247_init()
{
	if (document.getElementById('block_21'))
	{
		run247_features_next();
	}
	
 	if (document.getElementById('block_24'))
	{
		var regions = new SWFObject('regions.swf', 'movie_regions', '305', '300', '9');
		regions.addParam('scale', 'noscale');
		regions.write('block_24');
	}

	var movie = new SWFObject('logo02.swf', 'movie_logo', '270', '97', '9');
        movie.addParam('scale', 'noscale');
        movie.addParam('wmode', 'transparent');
        movie.write('area_left_menu_logo');
}


/*
	Used to dynamically change images on the site.
*/
function run247_changeimage(image, url)
{
	image.src = url;
}


/*
	Creates an "are you sure?" dialogue.
*/
function run247_areyousure_link(message, link)
{
	if (confirm(message))
	{
		document.location = link;
	}
	
	return false;
}


/*
	Updates the page location.
*/
function run247_location(new_location)
{
	document.location = new_location;
	
	return false;
}


/*
	Used to clear an input.
*/
function run247_clearinput(input)
{
	input.value = '';

	return false;
}


/*
	Used to clear a textarea.
*/
function run247_cleartextarea(input)
{
	if (input.value == 'Message')
		input.value = '';

	return false;
}


/*
	Prints the viewable area of the page.
*/
function run247_print()
{
	var area_content = null;
	try { area_content = document.getElementById('area_left_content'); } catch (e) { }
	if (area_content === null)
		area_content = document.getElementById('area_left_both');
	
	var print_window = window.open('','run247_print_window','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=550');
	print_window.document.open();
	print_window.document.title = 'www.run247.com';
	print_window.document.write("<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"run247_001.css\" /></head><body>"+area_content.innerHTML+"</body></html>");
	print_window.document.getElementsByTagName('body')[0].style.background = "none";
	print_window.document.close();

	print_window.focus();
	print_window.print();
	//print_window.close();

	return false;
}


/*
	Bookmarks the current page.
*/
function run247_bookmark(url, title)
{
	if (window.sidebar)
	{
		window.sidebar.addPanel(title, url, "");
	}
	else if (window.opera && window.print)
	{
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
	else if(document.all)
	{
		window.external.AddFavorite(url, title);
	}
	
	return false;
}


/*
	Called when a form is submitted for client side checking.
*/
function run247_form_submit(form_name, form_ref)
{
	var warning_message = '';
	
	if (form_name == 'comment')
	{
		if (form_ref.title.value == '' || form_ref.title.value == 'Subject')
			warning_message = 'Please enter a subject for your comment.';
		else if (form_ref.content.value == '' || form_ref.content.value == 'Message')
			warning_message = 'Please enter your comment.';
	}
	if (form_name == 'details')
	{
		if (form_ref.info_email.value == '')
			warning_message = 'Please enter your e-mail address.';
		else if (form_ref.pass_1.value != form_ref.pass_2.value)
			warning_message = 'Sorry, your passwords do not match.';
		else if (form_ref.info_alias.value == '')
			warning_message = 'Please enter your screen name.';
	}
	if (form_name == 'login')
	{
		if (form_ref.email.value == '')
			warning_message = 'Please enter your e-mail address.';
		else if (form_ref.password.value == '')
			warning_message = 'Please enter your password.';
	}
	if (form_name == 'reminder')
	{
		if (form_ref.email.value == '')
			warning_message = 'Please enter your e-mail address.';
	}
	if (form_name == 'signup')
	{
		if (form_ref.info_email.value == '')
			warning_message = 'Please enter your e-mail address.';
		else if (form_ref.pass_1.value == '')
			warning_message = 'Please enter a password.';
		else if (form_ref.pass_2.value == '')
			warning_message = 'Please confirm your password .';
		else if (form_ref.pass_1.value != form_ref.pass_2.value)
			warning_message = 'Sorry, your passwords do not match.';
		else if (form_ref.info_alias.value == '')
			warning_message = 'Please enter your screen name.';
	}
	if (form_name == 'submit_article')
	{
		if (form_ref.info_headline.value == '')
			warning_message = 'Please enter an article headline.';
		if (form_ref.info_content.value == '')
			warning_message = 'Please enter your article conent.';
	}
	if (form_name == 'submit_event')
	{
		if (form_ref.info_name.value == '')
			warning_message = 'Please enter the name of your event.';
		if (form_ref.location_name.value == '')
			warning_message = 'Please enter the location of your event.';
	}
	if (form_name == 'subscribe')
	{
		if (form_ref.email.value == '')
			warning_message = 'Please enter your e-mail address.';
	}
	if (form_name == 'unsubscribe')
	{
		if (form_ref.email.value == '')
			warning_message = 'Please enter your e-mail address.';
	}
	
	if (warning_message == '')
	{
		return true;
	}
	else
	{
		alert(warning_message);
		return false;
	}
}


/*
	Updates the advanced search form based on the selected search type.
*/
function run247_search_advanced(search_type)
{
	// Hide All Fields.
	document.getElementById('area_left_content_search_advanced_search_string').style.display = 'none';
	document.getElementById('area_left_content_search_advanced_region_id').style.display = 'none';
	document.getElementById('area_left_content_search_advanced_date_after').style.display = 'none';
	document.getElementById('area_left_content_search_advanced_date_before').style.display = 'none';
	document.getElementById('area_left_content_search_advanced_surface').style.display = 'none';
	document.getElementById('area_left_content_search_advanced_search_distance').style.display = 'none';
	document.getElementById('area_left_content_search_advanced_restrictions').style.display = 'none';
	document.getElementById('area_left_content_search_advanced_has_entry').style.display = 'none';
	document.getElementById('area_left_content_search_advanced_sort_postcode').style.display = 'none';
	document.getElementById('area_left_content_search_advanced_manufacturer_id').style.display = 'none';
	document.getElementById('area_left_content_search_advanced_resource_type').style.display = 'none';
	
	// Show Appropriate Fields.
	document.getElementById('area_left_content_search_advanced_search_string').style.display = 'block';
	if (search_type != 'product')
		document.getElementById('area_left_content_search_advanced_region_id').style.display = 'block';
	if (search_type == 'event' || search_type == 'result')
		document.getElementById('area_left_content_search_advanced_date_after').style.display = 'block';
	if (search_type == 'event' || search_type == 'result')
		document.getElementById('area_left_content_search_advanced_date_before').style.display = 'block';
	if (search_type == 'event' || search_type == 'result')
		document.getElementById('area_left_content_search_advanced_surface').style.display = 'block';
	if (search_type == 'event' || search_type == 'result')
		document.getElementById('area_left_content_search_advanced_search_distance').style.display = 'block';
	if (search_type == 'event' || search_type == 'result')
		document.getElementById('area_left_content_search_advanced_restrictions').style.display = 'block';
	if (search_type == 'event')
		document.getElementById('area_left_content_search_advanced_has_entry').style.display = 'block';
	if (search_type == 'event')
		document.getElementById('area_left_content_search_advanced_sort_postcode').style.display = 'block';
	if (search_type == 'product')
		document.getElementById('area_left_content_search_advanced_manufacturer_id').style.display = 'block';
	if (search_type == 'resource')
		document.getElementById('area_left_content_search_advanced_resource_type').style.display = 'block';
	
	// Set Restrict Types.
	document.getElementById('area_left_content_search_advanced_restrict_types').value='';
	if (search_type == 'article')
		document.getElementById('area_left_content_search_advanced_restrict_types').value='article';
	if (search_type == 'event')
		document.getElementById('area_left_content_search_advanced_restrict_types').value='event';
	if (search_type == 'product')
		document.getElementById('area_left_content_search_advanced_restrict_types').value='product';
	if (search_type == 'resource')
		document.getElementById('area_left_content_search_advanced_restrict_types').value='resource';
	if (search_type == 'result')
		document.getElementById('area_left_content_search_advanced_restrict_types').value='result';
	
	// Finished.
	return true;
}


/*
	LHS Events Switching.
*/
function run247_showevents(hide_index, show_index)
{
	document.getElementById('area_left_submenu_events_outer_'+hide_index).style.display = 'none';
	document.getElementById('area_left_submenu_events_outer_'+show_index).style.display = 'block';
	return false;
}


/*
	Block 29 Support.
*/
function run247_block29_show(n)
{
	for (var i = 0; i < 3; i++)
	{
		document.getElementById('block_29_image_'+i).style.display = 'none';
	}
	
	document.getElementById('block_29_image_'+n).style.display = 'block';
	
	return true;
}


/*
	Features Block Support.
*/
var run247_features_current = 0;
var run247_features_playing = true;
function run247_features_next()
{
	if (run247_features_playing)
	{
		run247_features_current++;
		
		if (run247_features_current > 5)
			run247_features_current = 1;
			
		run247_features_show(run247_features_current);
		
		setTimeout('run247_features_next()', 5000);
	}
}
function run247_features_stop(n)
{
	run247_features_playing = false;
	run247_features_show(n);
	return false;
}
function run247_features_show(n)
{
	var i = 1;

	// Get rid of all content.
	for (i = 1; i <= 5; i++)
	{
		document.getElementById('block_21_feature_'+i).style.display = 'none';
	}
	
	// Show the content.
	Effect.Appear('block_21_feature_'+n, { duration: 1 });
}





// 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.iconSize = new GSize(30, 30);
	gmaps_icon.iconAnchor = new GPoint(30, 30);
	gmaps_icon.infoWindowAnchor = new GPoint(30, 0);
}
catch (e) { }

/*
	Google Maps Initialise
*/
function run247_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() 
			{
				run247_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 run247_gmaps_loader_width(percent_complete)
{
	 return String(Math.max(1, Math.round(percent_complete / 100 * 178)))+'px';
}


/*
	Google Maps Initialise
*/
function run247_gmaps_update()
{
	// Starting.
	document.getElementById('area_google_loader').style.width = run247_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);
					run247_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 = run247_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 = run247_request(run247_url_root+'interface/gmaps.xml', '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] = run247_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] = run247_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 = run247_gmaps_loader_width(100);
}


/*
	Adds a new resource to the map, taking care of any collisions.
*/
function run247_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/run247/images/shared_pin_"+new_resource_type+".png";
		new_marker = new GMarker(new GLatLng(new_address_lat, new_address_lng), icon);
		//new_marker = new GMarker(new GLatLng(new_address_lat, new_address_lng));
		
		// 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 run247_gmaps_showaddress(address_type, resource_type, resource_id, address_lat, address_lng, info_html)
{
	var address = null;

	if (address_type == 'resource')
	{
		address = run247_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 run247_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;
	}
}

