var current_feature = 0;
var feature_timer = null;


// Set up the extra html for the main menu
function init_main_menu() {

	$("#access .menu").append("<div id='yellow_arrow'></div>");

	html = $("#access .menu").html();
	$("#access .menu").html("<div class='holder'><div class='left'></div>" + html + "<div class='right'></div></div>");
	$("#access .menu li:last").addClass("last");
	$("#access .menu li:first").addClass("first");
	
	// Move the header widgets inside the branding div
	widget = $('#contact_widget').html();
	$('#contact_widget').remove();
	$("#branding").append("<div id='contact_widget'>" + widget + "</div>");

	search = $('#search_widget').html();
	$('#search_widget').remove();
	$("#branding").append("<div id='search_widget'>" + search + "</div>");
	
	sub_nav = $('#sub_nav_menu').html();
	$("#sub_nav_menu").remove();
	$("#access .menu .holder").append("<div id='sub_nav_menu'>" + sub_nav + "</div>");
	
	
	init_footer();
	
	// Set up the search bar 
	$("input[type=text]").focus(function() {
		
		if ($(this).val() == $(this).attr('data-originalText')) {
			$(this).val('');
		} 	
	});
	
	$("input[type=text]").blur(function() {

		if ($(this).val() == "") {
			$(this).val($(this).attr('data-originalText'));
		}
	});
	
	
	
	// Add a special class to the menu items that have child menus
	$('#access .menu ul li ul li').each(function() {
	
		if ($(this).children(".sub-menu").size() > 0) {
		
			$(this).addClass('has_kids');
		
		}
	
	});
	
	

	// Set up the menu drop downs
	
	$("#access .menu").mouseover(function(event) {
/* 		event.stopPropagation(); */
	});
	
	$("#access .menu ul").mouseover(function(event) {
		event.stopPropagation();
	});

	$("#access .menu ul li").mouseover(function(event) {
		event.stopPropagation();
	});
			
	$("#menu-main-menu li a").mouseover(function(event) {
		event.stopPropagation();
		
		this_pos = $(this).position();
		this_width = ($(this).outerWidth(false) / 2) - 6;
		
		
		if (!$(this).parent().parent(".sub-menu").size() > 0) {
			if (!$("#yellow_arrow").is("visible")) {
				$("#yellow_arrow").animate({"left": this_pos.left + this_width});
				$("#yellow_arrow").fadeIn("fast");		
			} else {
				$("#yellow_arrow").animate({"left": this_pos.left + this_width});
			}
		}
		
		
		if (!$(this).parent().parent().parent().hasClass("has_kids")) {
			$('.viewing').removeClass("viewing");
		}
		
		if ($(this).parent().hasClass("has_kids")) {
			$(this).addClass("viewing");
		}

		$(this).parent().siblings().children(".sub-menu").fadeOut("fast");

		$(this).parent().children(".sub-menu").fadeIn("fast");
	});
	
	
	$("#menu-nav-menu li a").mouseover(function(event) {
		event.stopPropagation();
		
		this_pos = $(this).position();
		$(this).parent().children(".sub-menu").css({"left": this_pos.left - 20});
		
		$(this).parent().siblings().children(".sub-menu").fadeOut("fast");

		$(this).parent().children(".sub-menu").fadeIn("fast");
	});
	
	
	
/*
	$("#access .menu ul li ul li a").not("#access .menu ul li a").mouseover(function(event) {
		event.stopPropagation();
		
/* 		$(".sub-menu").stop(); */
/* 		$(".sub-menu").fadeOut("fast"); */
		
/* 		$(this).parent().children(".sub-menu").stop(); */
		
	/*
	$(this).parent().children(".sub-menu").fadeIn("fast");
	});
*/

	
	
	
	$(".sub-menu").mouseover(function(event) {
		event.stopPropagation();
	});
	
	
	$("body").mouseover(function() {
/* 		$(".sub-menu").stop(); */
		$(".sub-menu").fadeOut("fast");
		$("#yellow_arrow").fadeOut();
	});

	

	$(".menu").fadeIn('fast');
	$("#sub_nav_menu").fadeIn('fast');
	$("#contact_widget").fadeIn("fast");
	$("#search_widget").fadeIn("fast");
	
}



function init_feature_rotator() {
	
	current_feature = '#' + $('.feature_item:first').attr('id');
	$(current_feature).fadeIn();
	
	setInterval('next_feature()', 13000);
	
	$(".text a").append("<div class='arrow'></div>");
	

}

function next_feature() {
	
	$(current_feature).fadeOut("slow", function(){
	
		if ($(current_feature).next().size() > 0) {
			current_feature = '#' + $(current_feature).next().attr('id');
		} else {
			current_feature = '#' + $('.feature_item:first').attr('id');
		}
	
	
		
		$(current_feature).fadeIn("slow");
	
	
	});
	

}



// Init the subscribe footer

function init_footer () {

	// Find the labels and change the val of the accompanying input to the html of that label
	$(".mc_input").each(function() {

		$(".mc_required").remove();
		newval = $("label[for='" + $(this).attr('name') + "']").html().trim();
   		$(this).val(newval); 
   		$(this).attr("rel", newval);
	
	});
	
	$(".mc_input").focus(function() {
		
		if ($(this).val().trim() == $(this).attr("rel")) {
			$(this).val("");
		}
		
	});
	
	$(".mc_input").blur(function() {
	
		if ($(this).val().trim() == "" || $(this).val().trim() == " ") {
			$(this).val($(this).attr("rel"));
		}
	
	});
	
	$(".mc_merge_var label").remove();
	$(".mc_merge_var br").remove();		
	$("#mc-indicates-required").remove();

}






function init_page_layout() {

	// Make sure the sidebar is the same height as the content
	
	if ($("#sidebar_right").height() < $("#content").height()) {
	
		$("#sidebar_right").height($("#content").height() + 70);
	
	}

}



function init_contact_tabs() {

	$(".tab_content:first").fadeIn();

	$("a.tab").click(function() {
	
		curClick = $(this).attr('id');
	
		$("a.tab").removeClass("current");
		$(this).addClass("current");
		
		$(".tab_content:visible").fadeOut("fast", function() {
		
			$("#" + curClick + "_holder").fadeIn();
		
		});

	
	});

}




// Add the onclick events to the subnav tabs
function init_location_tabs(locations_url) {

	$(".location_nav").click(function() {
	
		$("#" + $(this).attr('rel')).click();
	
	});


$("a.location_tab").click(function() {

	var sideBarHtml = "";

	var linkCount = 0;
	
	curClick = $(this).attr('id');
	map_holder = $(this).attr("id") + "_map";
	
	$("." + curClick + "_dyn_locations").html("");
	
	$("a.location_tab").removeClass("current");
	$(this).addClass("current");
	
	$(".tab_content:visible").fadeOut("fast", function() {
		
		$("#" + curClick + "_holder").fadeIn();
	
	});
	
	
				// Use ajax and Jquery to read the googleEye.xml file
				$.ajax({
			        type: "GET",
					url: locations_url,
/* 					dataType: "xml", */
					error: function(data) {alert(data.responseText);},
					success: function(xml) {  // On success of reading that file we can now perform the other actions.
				 
				 	// Read the xml file and build the maps

				 	$(xml).find('state[name="' + curClick + '"]').each(function(){		
				 		
				 			xml = $(this);
				 		
				 			// These variables are pretty straight forward					 		
					 		var name = $(this).find('state_name').text();
					 		var campus_location_lattitude = parseFloat($(this).find('state_lattitude').text());
							var campus_location_longitude = parseFloat($(this).find('state_longitude').text());
							var zoom = parseFloat($(this).find('map_zoom').text());    
																			 		
							$(xml).find('markers').each(function(){												
								var place_group_id = $(this).attr('id');												
								
									// Create a map in the div that corresponds to the clicked tab.
									map = new GMap2(document.getElementById(map_holder));
									// Add controls to zoom and move around on the map.
									map.addControl(new GSmallMapControl());
									// Add the map, satelite and hybrid buttons to the map.
									map.addControl(new GMapTypeControl());
									// Set the lat and long of where we want to view in the world														  
									map.setCenter(new google.maps.LatLng(campus_location_lattitude, campus_location_longitude), zoom);
									
									var bounds = new GLatLngBounds();
									
									// Now generate all the markers for this maps
									$(xml).find('marker').each(function(){
									
										// Again, pretty straightforward variable names
										var marker_name = $(this).find('marker_name').text();
										var marker_lat  = parseFloat($(this).find('marker_lattitude').text());
										var marker_long = parseFloat($(this).find('marker_longitude').text());
										var marker_desc = $(this).find('marker_description').text().replace(/\n/g,'<br/>');
										
										var marker_address = $(this).find('marker_address').text();
										var marker_url = $(this).find('marker_url').text();
										var point = new GLatLng(marker_lat,marker_long);
												
										bounds.extend(point);		
																	
										// We could have put this in another function but there isn't much need or point at this stage
			                			var markerhtml = ""; 										                		
										if (marker_name != "") markerhtml += "<strong>" + marker_name + "</strong><br>";
										if (marker_desc != "") markerhtml += marker_desc + "<br>";
										if (marker_address != "") markerhtml += marker_address + "<br>";	
										if (marker_url != "") markerhtml += "<a href=\"" + marker_url + "\">" + marker_url + "</a>";
									 
										// Create the map marker using the supplied lat and long from the xml
										var marker = new GMarker(point);
										
										
										
										// Add a click event to each marker which will open the HTML window
										GEvent.addListener(marker, "click", function() {
											marker.openInfoWindowHtml("<span class='info'>" + markerhtml + "</span>");  // This will let you click on a marker to see its info bubble
										});
										
										marker_name_fixed = marker_name.replace("MAX Employment ", "")
										marker_name_fixed = marker_name_fixed.replace("Max Employment ", "")

									    // save the info we need to use later for the side_bar
										$("." + curClick + "_dyn_locations").prepend('<a id="' + curClick + '_marker_' + linkCount + '" class="location_nav" >' + marker_name_fixed + '</a>');
										
/* 										alert($("#marker_" + linkCount).size()); */
										
										$("#" + curClick + "_marker_" + linkCount).click(function() {
										
											map.setCenter(marker.position);
/* 		  								    marker.setMap(map); */
		 								    marker.openInfoWindowHtml("<span class='info'>" + markerhtml + "</span>");
											
										});
										
										
										
										
						                map.addOverlay(marker); // Add the marker to the current map, and then repeat if there are other markers		
						                
						                linkCount++;
						                
						                
										map.setZoom(map.getBoundsZoomLevel(bounds));
										
										if (map.getZoom() > 13) {map.setZoom(13);}
										
										map.setCenter(bounds.getCenter());	
						                
					                });				
				               
							});
							 
							
								            
					});
					
					}
					
				});			
			
});


$("a.location_tab:first").click();

}




function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];
 
  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}





function init_postcode_search(locations_url) {

	$("#postcode_search").click(function() {
		
		pc = $("#postcode").val();
	
		if(isNaN(pc)){
			alert("The postcode must only contain numbers");
			return false;
		} 

		if (pc.length != 4) {
			alert("The postcode must be four numbers long");
			return false;
		}
			
		// Get the lat and lon for the postcode from google
		
		$("#closest_office").fadeIn();
		$("#closest_office").html("Calculating...");
		
		var address = pc + " Australia";
		
	    var map = null;
	    var geocoder = null;
	    geocoder = new GClientGeocoder();
	      
	        geocoder.getLatLng(
	          address,
	          function(point) {
	            if (!point) {
	              alert(address + " not found");
	              return false;
	            } else {

	              var marker = new GMarker(point);
	              
	              lat = marker.getPoint().lat();
	              lng = marker.getPoint().lng();
	              
	              var locations = new Array();
	              
	              
				$.ajax({
			        type: "GET",
					url: locations_url,
/* 					dataType: "xml", */
					error: function(data) {alert(data.responseText);},
					success: function(xml) {  // On success of reading that file we can now perform the other actions.
				 
				 	// Read the xml file and build the maps

				 	$(xml).find('state').each(function(){		
				 		
				 			xml = $(this);
				 		
				 			// These variables are pretty straight forward					 		
					 		var name = $(this).find('state_name').text();
					 		var campus_location_lattitude = parseFloat($(this).find('state_lattitude').text());
							var campus_location_longitude = parseFloat($(this).find('state_longitude').text());
							var zoom = parseFloat($(this).find('map_zoom').text()); 
							  
																			 		
							$(xml).find('markers').each(function(){												
								var place_group_id = $(this).attr('id');												
								

									
									// Now generate all the markers for this map
									$(xml).find('marker').each(function(){
									
										// Again, pretty straightforward variable names
										var marker_name = $(this).find('marker_name').text();
										var marker_lat  = parseFloat($(this).find('marker_lattitude').text());
										var marker_long = parseFloat($(this).find('marker_longitude').text());
										var marker_desc = $(this).find('marker_description').text().replace(/\n/g,'<br/>');
										
										var marker_address = $(this).find('marker_address').text();
										var marker_url = $(this).find('marker_url').text();
										
										
								        var lat1 = Geo.parseDMS(lat);
								        var lon1 = Geo.parseDMS(lng);
								        var lat2 = Geo.parseDMS(marker_lat);
								        var lon2 = Geo.parseDMS(marker_long);
								        var p1 = new LatLon(lat1, lon1);
								        var p2 = new LatLon(lat2, lon2);
										
										var marker_distance = p1.distanceTo(p2);
										
/* 										var point = new GLatLng(marker_lat,marker_long); */
																																		
										var location = new Array();			
										
										location['marker_name'] = marker_name;
										location['marker_distance'] = marker_distance;
										location['marker_desc'] = marker_desc;
										location['marker_address'] = marker_address;
										location['marker_lat'] = marker_lat;
										location['marker_long'] = marker_long;
																				
										locations[locations.length + 1] = location;
										
					                });				
				               
							});
								 
								            
					});
					
					var currentDistance = 100000;
					var closest = new Array();
					
/* 					alert(locations.length); */
					
					for (x in locations)
					{
						
						if (parseInt(locations[x]['marker_distance']) < parseInt(currentDistance)) {
						
							closest = locations[x];
							currentDistance = locations[x]['marker_distance'];
							
						}
					
					}
					
					$("#closest_office").hide();

					


					if (closest['marker_distance']) {


					$("#closest_office").html("");
/* 					$("#closest_office").append("Your closest MAX Employment office:<br/><br/>"); */
					$("#closest_office").append("<h3>" + closest['marker_name'] + "</h3>");
					$("#closest_office").append(closest['marker_name'] + " is <strong style='color: #ff0000;'>" + closest['marker_distance'] + " kilometres</strong> away from " + pc +   "<br/>");
					$("#closest_office").append("<div id='closest_map' class='map' style='margin-top: 10px; width: 898px; height: 380px; padding: 10px; background-color: #fff; border: 1px solid #333;'></div>");
					
					} else {
					
						alert("Postcode not found");
						return false;
						
					}
					
					$("#closest_office").fadeIn(function() {
					
					
									// Create a map in the div that corresponds to the clicked tab.
									map = new GMap2(document.getElementById("closest_map"));
									
									// Add controls to zoom and move around on the map.
									map.addControl(new GSmallMapControl());
									
									// Add the map, satelite and hybrid buttons to the map.
									map.addControl(new GMapTypeControl());
									
									// Set the lat and long of where we want to view in the world														  
									map.setCenter(new google.maps.LatLng(closest['marker_lat'], closest['marker_long']), 10);					
					
									var point = new GLatLng(closest['marker_lat'],closest['marker_long']);
					
										var marker_name = closest['marker_name'];
										var marker_lat  = closest['marker_lat'];
										var marker_long = closest['marker_long'];
										var marker_desc = closest['marker_desc'].replace(/\n/g,'<br/>');
										
/* 										var marker_address = closest['marker_address']; */
															
					
			                			var markerhtml = ""; 										                		
										if (marker_name != "") markerhtml += "<strong>" + marker_name + "</strong><br>";
										if (marker_desc != "") markerhtml += marker_desc + "<br>";
/* 										if (marker_address != "") markerhtml += marker_address + "<br>";	 */
/* 										if (marker_url != "") markerhtml += "<a href=\"" + marker_url + "\">" + marker_url + "</a>";					 */
					
										// Create the map marker using the supplied lat and long from the xml
										var marker = new GMarker(point);
										
										// Add a click event to each marker which will open the HTML window
										GEvent.addListener(marker, "click", function() {
											marker.openInfoWindowHtml("<span class='info'>" + markerhtml + "</span>");  // This will let you click on a marker to see its info bubble
										});
										
										marker_name_fixed = marker_name.replace("MAX Employment ", "")
										marker_name_fixed = marker_name_fixed.replace("Max Employment ", "")

									    // save the info we need to use later for the side_bar

										
/* 										$("#marker_closest").click(function() { */
										
/* 										}); */
										
										map.addOverlay(marker); // Add the marker to the current map, and then repeat if there are other markers		
						                		
											map.setCenter(marker.position);
/* 		  								    marker.setMap(map); */
		 								    marker.openInfoWindowHtml("<span class='info'>" + markerhtml + "</span>");
																	                		
	                					});
					
					
					}
					
				});			              
	              
	              
	              
	              
	              
	              
	              
	              
	            }
	          }
	        );
	      
	});	   	
}








