$(function(){
	
	// Tools
	initTools();
	
	// Banner flash
	initFlash();
	
	// Init banner elements
	initElements();
	
	// Init banner animation
	initAnimation();
	
	if ($("#map").length > 0) {
		// Init map on load
		google.setOnLoadCallback(initMap);

		// Call method to move map on search submit.
		$("#map_search_form").submit(function () {
			moveToAddress();
			return false;
		});
	}
	
	// Init link images
	//initLinkImages();
	
	// Init myth boxes.
	initMythBoxes();
	
	// Validate forms.
	validateContactUsForm();
	//validateSendToFriendForm();
	validateAddMythsForm();
	
	//background color for alternate table rows
	$("tbody tr:odd").addClass("even");
});

/* BANNER ********************************************************************/

// Elements.
var speedElement;
var camerasElement;
var consequencesElement;
var camerasFlashElement;
var speedFlashElement;
var consequencesFlashElement;

function initElements() {
	speedElement = $("#speed");
	camerasElement = $("#cameras");
	consequencesElement = $("#consequences");
	camerasFlashElement = $("#cameras_flash_content");
	speedFlashElement = $("#speed .content");
	consequencesFlashElement = $("#consequences .content");
	
	speedIsAnimatingTo = 0;
	cameraIsAnimatingTo = camerasElement.css("left");
	consequencesIsAnimatingTo = consequencesElement.css("left");
}

function initAnimation() {
	speedElement.hoverIntent(hoverOnSpeed, nullFunction);
	$("#speed a").focus(hoverOnSpeed);
	camerasElement.hoverIntent(hoverOnCameras, nullFunction);
	$("#cameras a").focus(hoverOnCameras);
	consequencesElement.hoverIntent(hoverOnConsequences, nullFunction);
	$("#consequences a").focus(hoverOnConsequences);
}

// A function that does nothing that is needed as an argument for hoverIntent.
function nullFunction() {
}

function hoverOnSpeed() {
	if (cameraIsAnimatingTo != 590) {
		cameraIsAnimatingTo = 590;
		camerasElement.animate({left: 590+"px"}, { queue:false, duration:(500) });
		moveSpeedFlashRight();
	}
	
	if (consequencesIsAnimatingTo != 790) {
		consequencesIsAnimatingTo = 790;
		$("#consequences").animate({left: 790+"px"}, { queue:false, duration:(500) });
	}
	
	fadeInImage("speed");
	fadeOutImage("cameras");
	fadeOutImage("consequences");
	$("#cameras_flash_content").css({width: 0+"px"});
}

// Animation for hovering on #cameras.
function hoverOnCameras() {
	if (cameraIsAnimatingTo != 200) {
		cameraIsAnimatingTo = 200;
		camerasElement.animate({left: 200+"px"}, { queue:false, duration:(500) });
		moveSpeedFlashLeft();
	}
	
	if (consequencesIsAnimatingTo != 790) {
		consequencesIsAnimatingTo = 790;
		consequencesElement.animate({left: 790+"px"}, { queue:false, duration:(500) });
	}
	
	fadeOutImage("speed");
	fadeInImage("cameras");
	fadeOutImage("consequences");
	setTimeout("expandCamerasFlash()", 500); // $("#cameras_flash_content").css({width: 590+"px"});
}

// Animation for hovering on #consequences.
function hoverOnConsequences() {
	if (cameraIsAnimatingTo != 200) {
		cameraIsAnimatingTo = 200;
		camerasElement.animate({left: 200+"px"}, { queue:false, duration:(500) });
		moveSpeedFlashLeft();
	}
	
	if (consequencesIsAnimatingTo != 400) {
		consequencesIsAnimatingTo = 400;
		consequencesElement.animate({left: 400+"px"}, { queue:false, duration:(500) });
	}
	
	fadeOutImage("speed");
	fadeOutImage("cameras");
	fadeInImage("consequences");
	$("#cameras_flash_content").css({width: 0+"px"});
}

function expandCamerasFlash() {
	if (cameraIsAnimatingTo == 200 && consequencesIsAnimatingTo == 790) {
		$("#cameras_flash_content").css({width: 590+"px"});
	}
}

// Fade in an image.
function fadeInImage(section) {
	$("#" + section + " .content img").css({display: "inline"});
	$("#" + section + " .content img").animate({opacity: 1.0}, { queue:false, duration:(500) });
}

// Fade out an image.
function fadeOutImage(section) {
	$("#" + section + " .content img").animate({opacity: 0}, { queue:false, duration:(500) });
}

// Move #speed-flash to the left.
function moveSpeedFlashLeft() {
	$("#speed .content").animate({left: "-390px"}, { queue:false, duration:(500) });
}

// Move #speed-flash to the right.
function moveSpeedFlashRight() {
	$("#speed .content").animate({left: "0"}, { queue:false, duration:(500) });
}

/* FLASH *********************************************************************/

function initFlash() {
	if ($("#cameras_flash_content").length > 0) {
		swfobject.embedSWF("", "t", "590", "310", "8.0.0", false, { xmlpath:"", allowScriptAccess:"always" }, false, false);
	}
}



/* MAP ***********************************************************************/

// Global vars shared by Google maps and Jquery autocomplete
var map;
var addresses = [];
var infowindow;

//Init Map
function initMap() {
	// Map settings
	var mapOptions = {
 		// Zoom level
		zoom: 9,

		// Center on Melbourne
		center: new google.maps.LatLng(-37.812, 144.963),

		// Controls
		navigationControl: true,
		mapTypeControl: false,
		scaleControl: true,

		// Only show roads - no satellite
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	// Create map
	map = new google.maps.Map(document.getElementById("map"), mapOptions);

	// Create infoWindow holder 
	infowindow = new google.maps.InfoWindow({	
		content: ''	
	});	
		
	// Get and parse XML with JQuery, and create markers
	jQuery.get("http://www.justice.vic.gov.au/wps/wcm/connect/c1eec90040d6ea1ebab7bf55d2030319/CCC_camera_locations_20101006.xml?MOD=AJPERES&CACHEID=c1eec90040d6ea1ebab7bf55d2030319", {}, function(data) {
		jQuery(data).find("camera").each(function() {
			// Get data for each camera
			var camera = jQuery(this);
			var cameraActive = camera.attr("active");
			
			// Skip inactive cameras
			if (cameraActive != "Yes") {
				return;
			}
			
			var cameraId = camera.attr("id");
			var cameraLocation = camera.find("location").text();
			var cameraIntersection = camera.find("intersection").text();
			var cameraSuburb = camera.find("suburb").text();
			var cameraAddress = camera.find("address").text();
			var cameraCertificate = camera.find("calibrationCert").text();
			var cameraType = camera.find("cameraType").text();

			if (cameraType == "Point to point") {
				var iconImage = new google.maps.MarkerImage("images/point_to_point_icon.gif", new google.maps.Size(13,13)); 
			} else {
				var iconImage = new google.maps.MarkerImage("images/fixed_icon.gif", new google.maps.Size(13,13));
			}
			
			// Create position from coordinates
			var latlng = new google.maps.LatLng(parseFloat(camera.attr("lat")), parseFloat(camera.attr("lng")));
	 	
			// Create marker on the map
			var marker = new google.maps.Marker({position: latlng, map: map, title: cameraLocation, icon: iconImage});

			// Create list of addresses from XML for autocomplete
		 	addresses[addresses.length] = {cameraLocation: cameraLocation, cameraAddress: cameraAddress, cameraSuburb: cameraSuburb, lat: camera.attr("lat"), lng: camera.attr("lng"), cameraCertificate: cameraCertificate, marker: marker};

		 	// Add event to open infoWindow when marker is clicked
			google.maps.event.addListener(marker, 'click', function() {showCameraDetails(infowindow, marker, cameraSuburb, cameraAddress, cameraCertificate)});

			// Add event to zoom when marker is double clicked
			google.maps.event.addListener(marker, 'dblclick', function() {
				
				// Zoom
				map.setZoom(15);
	
				// Move map to location
				map.panTo(marker.getPosition());
				
				// Open infowindow
				showCameraDetails(infowindow, marker, cameraSuburb, cameraAddress, cameraCertificate);
		 	});
		});

		// Init autocomplete
		initAutocomplete();
	});
}

// Move the map to the search address
function moveToAddress() {
	// Search address
	var address = $("#map_search_text").val();

	// Bound results to a rectangle including victoria
	var bounds = new google.maps.LatLngBounds(new google.maps.LatLng(-35.122155,141.010895), new google.maps.LatLng(-39.385264,151.391602));
	
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode({address: address + ", VIC, Australia", bounds: bounds, region:"AU"}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
		 	// Zoom
			map.setZoom(15);

			// Move map to location
			map.panTo(results[0].geometry.location);
		 
		} else {
			alert('We were unable to find this address, please correct the spelling and try again.');
		}
	});
}

// Open the infowindow with camera details
function showCameraDetails(infowindow, marker, cameraSuburb, cameraAddress, cameraCertificate) {
	// Set HTML in the infoWindow
	var htmlContent = '<div class="suburb">' + cameraSuburb + '</div><div class="address">' + cameraAddress + '</div><div class="address"><img src="images/pdf_icon.gif" ALT="PDF" WIDTH="17" HEIGHT="17" class="downloadpdf"/> <a href="' + cameraCertificate + '" >Download compliance certificate</a></div>';
	infowindow.setContent(htmlContent);
	// Show infoWindow	
	infowindow.open(map, marker); 
}

// Init autocomplete after addresses have been loaded
function initAutocomplete() {
	
	$("#map_search_text").autocomplete(addresses, {
		minChars: 0,
		width: 310,
		matchContains: true,
		highlightItem: false,
		formatItem: function(row, i, max, term) {
			return row.cameraLocation.replace(new RegExp("(" + term + ")", "gi"), "<strong>$1</strong>") + "<br><span style='font-size: 80%;'>" + row.cameraAddress + "</span>";
		},
		formatResult: function(row) {
			return row.cameraAddress;
		}
	}).result(function(event, data, formatted) {
		// On selection of a result, move the map to the selected camera
		// Zoom
		map.setZoom(14);

		// Move map to location
		map.panTo(new google.maps.LatLng(parseFloat(data.lat), parseFloat(data.lng)));
		
		// Open infowindow
		showCameraDetails(infowindow, data.marker, data.cameraSuburb, data.cameraAddress, data.cameraCertificate);
		
	});
}

/* TOOLS *********************************************************************/

// Add myth.
function addMyth() {
	var html = '<h2>Ask an Expert</h2><p style="text-align: right">* Mandatory Fields</p><form id="add_myth_form" action="#" method="post"><div id="add_myth"><table cellpadding="0"><tr><td class="label"><label for="your_name">* Your name</label></td><td><input type="text" id="your_name" name="your_name"></td></tr><tr><td class="label"><label for="your_email">* Your email</label></td><td><input type="text" id="your_email" name="your_email"></td></tr></td></tr><tr><td class="label"><label for="question">* Your Question</label></td><td><textarea id="question" name="question"></textarea></td></tr><tr><td class="label"></td><td style="text-align: left; vertical-align: top;"><input type="image" id="send_button" src="images/send_button.gif" alt="Send" style="width: 81px;"> <a href="javascript:return null;"  class="simplemodal-close">Cancel</a></td></tr></table></div></form>';
	
	$.modal(html, {maxHeight: 320});
	
	validateAddMythsForm();
}

// Clear form.
function clearForm() {
	$("#contact_name").val("");
	$("#contact_email").val("");
	$("#contact_subject").val("");
	$("#contact_message").val("");
}

// Validate contact us form.
function validateContactUsForm() {
	$("#contact_us_form").validate({
		rules: {
			contact_name: "required",
			contact_email: {
				required: true,
				email: true
			},
			contact_message: "required"
		},
		messages: {
			contact_name: "Please enter your name",
			contact_email: {
				required: "Please enter your email",
				email: "Please enter a valid email"
			},
			contact_message: "Please enter a message"
		}
	});
}

// Validate send to friend form.
function validateSendToFriendForm() {
	$("#send_to_a_friend_form").validate({
		rules: {
			your_name: "required",
			your_email: {
				required: true,
				email: true
			},
			friends_name: "required",
			friends_email: {
				required: true,
				email: true
			}
		},
		messages: {
			contact_name: "Please enter your name",
			contact_email: {
				required: "Please enter your email",
				email: "Please enter a valid email"
			},
			friends_name: "Please enter name",
			friends_email: {
				required: "Please enter email",
				email: "Please enter a valid email"
			}
		}
	});
	
	var resp = null;
	($("#send_to_a_friend_form").valid() == true) ? resp = true : resp = false; return resp;
}

// Validate add myths form.
function validateAddMythsForm() {
	$("#add_myth_form").validate({
		rules: {
			your_name: "required",
			your_email: {
				required: true,
				email: true
			},
			question: "required"
		},
		messages: {
			your_name: "Please enter your name",
			your_email: {
				required: "Please enter your email",
				email: "Please enter a valid email"
			},
			question: "Please enter a message"
		}
	});
}

//Send request to ACD for processing
function callACD(url){
	var dh = document.getElementsByTagName('head')[0];
	var script = null;
	script = document.createElement('script');	
	script.setAttribute('src', url);
	script.setAttribute('type', 'text/javascript');

	if($.browser.msie) {
		script.onreadystatechange = function () { if (this.readyState == 'complete' || this.readyState == 'loaded') { displaySendToFriendFormMessage(); }};
	}
	else {
		script.onload = function () { displaySendToFriendFormMessage(); };
	}

	dh.appendChild(script);
}

function displaySendToFriendFormMessage(){
	var dh2 = document.getElementsByTagName('head')[0];
	var script2 = null;
	script2 = document.createElement('script');
	script2.setAttribute('type', 'text/javascript');
	script2.text = "$('#response').css({'display': 'block', 'background': '#ddd', 'padding': '15px', 'border': '1px solid #333'}); $('#response').animate({height: '20px'}); if(ACD.responseText.match('true')) {$('#send_to_a_friend_form').hide(); $('#simplemodal-container').animate({height: '125px'}); $('#response').html('message successfully sent'); } else { $('#simplemodal-container').animate({height: '415px'}); $('#response').html('error in sending the message, please try again')}";
	//script2.text = "alert(ACD.responseText);";
	dh2.appendChild(script2);
}

// Send to friend.
function sendToFriend() {
	var html = '<h2>Send to a Friend</h2><div id="response"></div><form id="send_to_a_friend_form" action="#" onsubmit="return false" method="post"><input type="hidden" id="theURL" name="theURL" value="' + window.location + '"><div id="send_to_a_friend"><p style="text-align: right">* Mandatory Fields</p><table cellpadding="0"><tr><td class="label"><label for="your_name">* Your name</label></td><td><input type="text" id="your_name" name="your_name"></td></tr><tr><td class="label"><label for="your_email">* Your email</label></td><td><input type="text" id="your_email" name="your_email"></td></tr><tr><td class="label"><label for="friends_name">* Friend\'s name</label></td><td><input type="text" id="friends_name" name="friends_name"></td></tr><tr><td class="label"><label for="friends_email">* Friend\'s email</label></td><td><input type="text" id="friends_email" name="friends_email"></td></tr><tr><td class="label"><label for="message">Message</label></td><td><textarea id="message" name="message"></textarea></td></tr><tr><td class="label"></td><td style="text-align: left; vertical-align: top;"><input type="image" id="send_button" src="images/send_button.gif" alt="Send" style="width: 81px;"> <a href="javascript:return null;"  class="simplemodal-close">Cancel</a></td></tr></table></div></form>';
	
	$.modal(html, {});

	//AJAX Send Mail function
	$("#send_button").click(function(){
		if(validateSendToFriendForm() == true) {
			var sender_name = escape($("#your_name").val());
			var sender_email = $("#your_email").val();
			var rec_name = escape($("#friends_name").val());
			var rec_email = $("#friends_email").val();
			var message = escape($("#message").val());
			var theURL = $.URLEncode($("#theURL").val());
			
			callACD('http://multimedia.justice.vic.gov.au/cgi-bin/ACD/ACD.js?uri=(http://multimedia.justice.vic.gov.au/SendMail/mail.php)&method=post&postdata=(sender_name=' + sender_name + '&sender_email=' + sender_email + '&rec_name=' + rec_name + '&rec_email=' + rec_email + '&message=' + message + '&theURL=' + theURL + ')');	
		}
	});
}

// Make text bigger.
function makeTextBigger() {
	var fontSize = parseFloat($("#content").css("font-size")) + 2;
	$("#content").css("font-size", fontSize + "px");
}

// Make text smaller.
function makeTextSmaller() {
	var fontSize = parseFloat($("#content").css	("font-size")) - 2;
	$("#content").css("font-size", fontSize + "px");
}

// Init text, send to friend and print tools.
function initTools() {
	if (navigator.userAgent.match("Firefox/3.0") == null) {
		if ($("#content.tools").length > 0) {
			$("#title").append('<div id="tools"><a href="#"  onclick="javascript:makeTextBigger();return false"><img src="images/tools_bigger.gif" ALT="Make text bigger" WIDTH="19" HEIGHT="14"/></a><a href="#"  onclick="javascript:makeTextSmaller();return false"><img src="images/tools_smaller.gif" ALT="Make text smaller" WIDTH="11" HEIGHT="14"/></a><a href="#"  onclick="javascript:sendToFriend();return false"><img src="images/tools_send.gif" ALT="Send to a friend" WIDTH="17" HEIGHT="14"/></a> <a href="#"  onclick="javascript:sendToFriend();return false">Send this page</a><a href="#"  onclick="javascript:window.print();return false"><img src="images/tools_print.gif" ALT="Print" WIDTH="17" HEIGHT="14"/></a> <a href="#"  onclick="javascript:window.print();return false">Print</a></div>');
		}
	} else {
		if ($("#content.tools").length > 0) {
			$("#title").append('<div id="tools" style="position: absolute; top: 0; right: 0;"><a href="#"  onclick="javascript:makeTextBigger();return false"><img src="images/tools_bigger.gif" ALT="Make text bigger" WIDTH="19" HEIGHT="14"/></a><a href="#"  onclick="javascript:makeTextSmaller();return false"><img src="images/tools_smaller.gif" ALT="Make text smaller" WIDTH="11" HEIGHT="14"/></a><a href="#"  onclick="javascript:sendToFriend();return false"><img src="images/tools_send.gif" ALT="Send to a friend" WIDTH="17" HEIGHT="14"/></a> <a href="#"  onclick="javascript:sendToFriend();return false">Send this page</a><a href="#"  onclick="javascript:window.print();return false"><img src="images/tools_print.gif" ALT="Print" WIDTH="17" HEIGHT="14"/></a> <a href="#"  onclick="javascript:window.print();return false">Print</a></div>');
		}
	}
}

// Init link images.
/*
function initLinkImages() {
	// Add PDF icon to links pointing to *.pdf.
	$("a[href$='.pdf']").before('<img src="images/pdf_icon.gif" ALT="PDF Document" class="link-image"/> ');

	// Add external website icon to links pointing to http://*.
	$("a[href^='http://']").before('<img src="images/external_icon.gif" ALT="External Website" class="link-image"/> ');

	// Don't display link images for .no-link-image classes.
	$(".link-image + .no-link-image").prev().css({display: "none"});
}
*/

// Init myth boxes.
function initMythBoxes() {
	$("#ask-myth").click(function () { addMyth(); return false; });
	
	var mythCounter = 1;
	
	$("#middle.span_440 .myth_box").each (
		function() {
			// change colour
			
			switch (mythCounter) {
				case 1: break; // yellow
				case 2: $(this).addClass("purple"); break; // purple
				case 3: $(this).addClass("blue"); break; // blue
				case 4: $(this).addClass("orange"); break; // orange
				case 5: $(this).addClass("green"); mythCounter = 0; break; // green
			}
			
			mythCounter++;
		}
	);
	
	var showText='Show the Fact';
	var hideText='Hide the Fact';

	$('.fact').prev().append('<a href="#"  class="toggleLink">'+showText+'</a>');
	$('.fact').hide();

	$('a.toggleLink').click(function() {
		$(this).html( (!$(this).parent().next('.fact').is(":hidden")) ? showText : hideText);
		$(this).parent().next('.fact').toggle('fast');
		return false;
	});
}


