// Variables: Driving Directions
gFrom 		= ''; // Format "Suburb, State"
gTo 		= gName; // Product or Town Name
gToGeoCode 	= gLat + ',' + gLong;
gLocale		= 'en';

var loading 	= false;
//var bounds 		= new GLatLngBounds();
var bounds = null; 
document.getElementById('google-map').style.display = 'block';

var FlgGoogleMapLoaded = false ;
var gmarkers 	= [];
var isCatSet 	= [];
var myListener 	= [];
var myCats 		= [];
var customIcons = [];

var latlongval;

// Street View variables declared
var marker;
var overlayInstance = null;
var client;
var lastMarkerLocation;
var panorama;
var mapT;
var guyIcon;
var malcontent;

var gZones;
var zoomLevel;

//Tell the global general.js file to activate google maps
FlgLoadGoogleMaps = true;

//alert(flgMapType + " : " +zone_title_global)

if(flgMapType=="TOWN"){
	  //gZones = { 'Lord Howe Island': 13, 'Sydney': 13, 'South Coast': 11, 'Sydney Surrounds': 11, 'Short Breaks': 11, 'Snowy Mountains': 11, 'North Coast': 11, 'Heart of Country': 10, 'Outback': 9 }}
		gZones =  {'Lord Howe Island': 14, 'Sydney': 14, 'South Coast': 14, 'Sydney Surrounds': 14, 'Short Breaks': 14, 'Snowy Mountains': 14, 'North Coast': 14, 'Heart of Country': 14, 'Outback':14}}
else {
		gZones =  {'Lord Howe Island': 15, 'Sydney': 15, 'South Coast': 15, 'Sydney Surrounds': 15, 'Short Breaks': 15, 'Snowy Mountains': 15, 'North Coast': 15, 'Heart of Country': 15, 'Outback':15}}

zoomLevel = gZones[zone_title_global];


myListener.push('PRODUCT_ACCOMMODATION','PRODUCT_ATTRACTION','EVENT','HIRE','TOUR','HOTEL','BACKPACKER','BEDBREAKFA','RESORT','FARMSTAY','VANCAMP','SELFCONTAI','TOWN','VIC');
myCats.push('Accommodation','Attractions','Events','Hire','Tours','Hotel / Motel','Backpacker / Hostel','Bed &amp; Breakfast','Resort','Farm stay','Caravan / Camping','Self contained','Town','VIC');

// Category Set Up Variables
for (i=0; i < myListener.length; i++) {
	isCatSet[myListener[i]] = '0';
}


function GLoad_Action() {
	if (!FlgGoogleMapLoaded && document.getElementById('ProductGoogleMap').style.display=='block')
	{
		// uncheck Accom & Attr check boxes on every page load 
		document.getElementById('PRODUCT_ACCOMMODATION').checked=false;
		document.getElementById('PRODUCT_ATTRACTION').checked=false;
		GLoad();
		FlgGoogleMapLoaded=true;
	}
}




// A TextualZoomControl is a GControl that displays textual "Zoom In"
// and "Zoom Out" buttons (as opposed to the iconic buttons used in
// Google Maps).
function TextualZoomControl() {
}
TextualZoomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var zoomInDiv = document.createElement("div");
  this.setButtonStyle_(zoomInDiv);
  container.appendChild(zoomInDiv);
  zoomInDiv.appendChild(document.createTextNode("Street View"));
  GEvent.addDomListener(zoomInDiv, "click", function() {
	toggleOverlay();
  });

  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
}

// Sets the proper CSS for the given button element.
TextualZoomControl.prototype.setButtonStyle_ = function(button) {
  button.style.marginRight = "16em";
  button.style.textDecoration = "none";
  button.style.color = "#0000cc";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.borderRight = "2px ridge #B0B0B0";
  button.style.borderBottom = "2px ridge #B0B0B0";
  button.style.padding = "2px 2px 1px 2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "6em";
  button.style.cursor = "pointer";
  button.style.color = "black";
}



// Call this function when the page has been loaded
function GLoad() {
		//alert('testA');
		if (GBrowserIsCompatible()) {

		// Show the Map and Change the Namespace
		addVML();
		document.getElementById('categories').style.display = 'block';
		document.getElementById('google-map').style.display = 'block';
		
		// Street View client
		client = new GStreetviewClient();

		map = new GMap2(document.getElementById("google-map"));
		map.setCenter(new GLatLng(-33.642063,150.472241), zoomLevel);
		
		map.addControl(new TextualZoomControl());
		map.addControl(new GScaleControl());
		map.addControl(new GSmallMapControl());
		
		map.addControl(new GMapTypeControl());
		if (zone_title_global == 'Lord Howe Island') {
			map.setMapType(G_SATELLITE_MAP);
		} else {
		map.setMapType(G_NORMAL_MAP);
		}
		map.enableScrollWheelZoom();

		var overviewmap = new GOverviewMapControl();
		map.addControl(overviewmap);
		overviewmap.hide();


		// Build Icons
		for (i=0; i < myListener.length; i++) {
			eval("icon"+myListener[i]+" = new GIcon();");
			eval("icon"+myListener[i]+".image = '/controls/Search/googleMaps/images/marker-" + myListener[i].toLowerCase() + ".png';");
			eval("icon"+myListener[i]+".shadow = '/controls/Search/googleMaps/images/marker-shadow.png';");
			eval("icon"+myListener[i]+".iconSize = new GSize(19, 30);");
			eval("icon"+myListener[i]+".shadowSize = new GSize(38, 30);");
			eval("icon"+myListener[i]+".iconAnchor = new GPoint(10, 34);"); // was 0, 18
			eval("icon"+myListener[i]+".infoWindowAnchor = new GPoint(8, 1);");
		}

		// Custom Icons Array
		for (i=0; i < myListener.length; i++) {
			customIcons[myListener[i]] = eval("icon"+myListener[i]);
		}

		// Load Product Marker from Query String
		if (gATDW!='') {
			map.setCenter(new GLatLng(gLat,gLong), zoomLevel);
			getMarkers(gATDW, '', '', '', '', '', '');
		}
		else // Non ATDW GMAPS - PCC (26Feb2010)
		{
		//alert('test');
			geocoder = new GClientGeocoder();
			if (geocoder) {
			//alert(addressNonATDW);
				geocoder.getLatLng(
				addressNonATDW,
				function(point) {
					if (!point) {
						alert(addressNonATDW + " not found");
					} else {
						map.setCenter(point, 13);
						var marker = new GMarker(point);
						var LatLng = String(point);
						latlongval = LatLng;
						map.addOverlay(marker);
						var mySplit = LatLng.split(",");
						
						gLat=mySplit[0].replace("(","");
						gLong=mySplit[1].replace(")","");
						gToGeoCode=String(point);
						
						document.getElementById('toGeoCode').value 	= gToGeoCode;
						document.getElementById('toName').value 	= gTo;
						document.getElementById('locale').value 	= gLocale;
						document.getElementById('fromState').value 	= 'NSW';
						document.getElementById('toSuburb').value 	= gTo;
						
						document.getElementById('categories').style.display = 'none';
					}
				}
				);
			}
		}

		// Driving Directions
		gdir = new GDirections(map, document.getElementById("driving-route"));
		GEvent.addListener(gdir, "error", handleErrors);

		// Load Directions from Previous Page
		if (gToGeoCode != '') {
			document.getElementById('toGeoCode').value 	= gToGeoCode;
			document.getElementById('toName').value 	= gTo;
			document.getElementById('locale').value 	= gLocale;
			document.getElementById('fromState').value 	= 'NSW';
			document.getElementById('toSuburb').value 	= gTo;
		}
		if (gFrom != '') {
			setDirections();
		}

		
		shrinkCopyright();
		autoZoom();
		// streetviewButton();

	} else {
		// Hide the Map!
		document.getElementById('google-map').style.display = 'none';
	}
}


/*///////////////////////////////////////////////////////////
Marker Management
///////////////////////////////////////////////////////////*/

// Marker Control for the Category Search

function getMarkers(atdw, south, west, north, east, category, subcategory){
	locLength 	= '0';
	dataFile = '/googleGeoMaps.aspx?GST=SP&PLat='+gLat+'&PLong='+gLong+'&CatID='+ category+'&North=' + north + '&South=' + south + '&East=' + east + '&West=' + west;
	//alert(dataFile);
	//document.write(dataFile);
	if (atdw!='') {

		if (document.getElementById(gCategory)) {
			document.getElementById('gLabel' + gCategory).style.display = 'none';
			document.getElementById(gCategory).disabled = true;
			document.getElementById(gCategory).parentNode.className = 'disabled-option';
		}
		var point 			= new GLatLng(parseFloat(gLat), parseFloat(gLong));
		var marker 		= createMarker(point, gATDW, gName, 'Full details for this product are found below this map...', '', '', gCategory, '');
		map.addOverlay(marker);
		map.setCenter(point, zoomLevel);

	} else {
		GDownloadUrl(dataFile, function(data, responseCode) {
			var xml = GXml.parse(data);
			var locations = xml.documentElement.getElementsByTagName("location");

			markers = [];
			if (locations.length) {
				locLength = (locations.length<1) ? '0' : locations.length ;
				locLength = (locLength > maxResults) ? maxResults : locLength ;
				for (var i = 0; i < locLength; i++) { // Cycle through locations

					if ( (locations[i].getAttribute("lat") != '') && (locations[i].getAttribute("lng") != '') ) {
						if (locations[i].getAttribute("lng") > 100) {

							var id 					= locations[i].getAttribute("id");
							var category 			= locations[i].getAttribute("category");
							var subcategory 	= locations[i].getElementsByTagName("subcategory")[0].childNodes[0].nodeValue;
							var name 				= locations[i].getElementsByTagName("loc_name")[0].childNodes[0].nodeValue;
							var image 			= locations[i].getElementsByTagName("loc_img")[0].childNodes[0].nodeValue;
							var description 		= locations[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
							var address 			= locations[i].getElementsByTagName("physical_address")[0].childNodes[0].nodeValue;
							var link 				= locations[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
							var point 				= new GLatLng(parseFloat(locations[i].getAttribute("lat")), parseFloat(locations[i].getAttribute("lng")));

							var marker 		= createMarker(point, id, name, description, address, link, category, subcategory);
							map.addOverlay(marker);
						}
					}
				}
			}
		});

		// Removed Warning as this would come up all the time...

	}

}

// Generate Each Marker
function createMarker(point, id, name, description, address, link, category, subcategory) {
	var marker = new GMarker(point, {title:name, icon:customIcons[category]}); // draggable:true

	var redoSubCat = subcategory.split('Rating:&nbsp;');
	subcategory = (redoSubCat.length>1) ? redoSubCat[0] + ' <span class="star-rating" title="Star Rating">' + redoSubCat[1] + '</span>' : subcategory ;

	var html =
		'<div class="gdetails">' +
		'<span class="gname"><strong>' + name + '<\/strong><\/span>' +
		'<span>' + subcategory + '<\/span>' +
		'<span class="gaddress"><em>' + address + '<\/em><\/span>' +
		description + '<br \/>';
	if (link !='') { html += '<a href="' + link + '">View product details<a/>'; }
	html += '<\/div>';

	marker.category = category;
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});

	gmarkers.push(marker);
	return marker;
}

// Bound the Marker Generation to the Displayed Area
function getBoundMarkers(category, subcategory) {
bounds = new GLatLngBounds();
	bounds 	= map.getBounds();
	south 	= bounds.getSouthWest().lat();
	west 	= bounds.getSouthWest().lng();
	north 	= bounds.getNorthEast().lat();
	east 	= bounds.getNorthEast().lng();
	getMarkers('', south, west, north, east, category, subcategory);
}


/*///////////////////////////////////////////////////////////
Category Management
///////////////////////////////////////////////////////////*/

// Show/Build Marker Lists
function show(category, subcategory) {
	for (var i=0; i<gmarkers.length; i++) {
		if (gmarkers[i].category == category) {
			gmarkers[i].show();
		}
	}
}

// Hide Marker Sets
function hide(category, subcategory) {
	for (var i=0; i<gmarkers.length; i++) {
		if (gmarkers[i].category == category) {
			gmarkers[i].hide();
		}
	}
}

// Toggle Function for Marker Lists
function boxClick(box, category, subcategory) {
	if (box.checked) {
		var locLength = '0';
		show(category, subcategory);
		getBoundMarkers(category, subcategory);
		myListener[category] = GEvent.addListener(map, 'moveend', function() {
			getBoundMarkers(category, subcategory);
		});
		isCatSet[category] = '1';
	} else {
		hide(category, subcategory);
		isCatSet[category] = '0';
		GEvent.removeListener(myListener[category]);
	}
}

// Toggle Check/Uncheck All Lists
function checkAll(checkname, exby) {
	boxClick(exby,exby.name,'');
}


/*///////////////////////////////////////////////////////////
Driving Directions Functions
///////////////////////////////////////////////////////////*/

function setDirections() {
	
	ShowHideGoogleMap('block',true);
	fromGeoCode 	= document.getElementById('fromGeoCode').value;
	toGeoCode 		= document.getElementById('toGeoCode').value;
	locale 			= document.getElementById('locale').value;

	fromAddress 	= document.getElementById('fromAddress').value;
	fromSuburb 		= document.getElementById('fromSuburb').value;
	fromState 		= document.getElementById('fromState').value;

	viaAddress 		= document.getElementById('viaAddress').value;
	viaSuburb 		= document.getElementById('viaSuburb').value;
	viaState 		= document.getElementById('viaState').value;

	toAddress 		= document.getElementById('toAddress').value;
	toSuburb 		= document.getElementById('toSuburb').value;
	
	toState 		= document.getElementById('toState').value;

	if ( (fromSuburb=='') || (toSuburb=='') ) {
		alert('You will need at least a from and to suburb/town'+' from:'+fromSuburb+' to:'+toSuburb);
	} else {
		fromSubmit 		= (fromGeoCode!='') ? fromGeoCode : fromAddress +', '+ fromSuburb +', '+ fromState ;
		viaSubmit 		= (viaSuburb!='') ? ' to: '+ viaAddress +', '+ viaSuburb +', '+ viaState : '' ;
		toSubmit 		= ( (toGeoCode!='') && (toSuburb==gTo) ) ? toGeoCode : toAddress +', '+ toSuburb +', '+ toState ;

		gdir.load("from: " + fromSubmit + viaSubmit + " to: " + toSubmit, { "locale": locale });
		// window.location = window.location + "#google-map";

		document.getElementById('driving-route').style.display = 'block';
		// document.getElementById('driving-route').innerHTML = document.getElementById('driving-route').innerHTML + '';
	}
}

// Handling Errors
function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may have been incorrectly entered into the form field.\n\nAlternatively, you may simply need to supply more information. For example: 'Dundas' may not be recognised whereas 'Dundas, NSW' will.\n\nReport the Error Code to the site administrators: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n\nReport the Error Code to the site administrators: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n\nReport the Error Code to the site administrators: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
		alert("The given key is either invalid or does not match the domain for which it was given. \n\nReport the Error Code to the site administrators: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
		alert("A directions request could not be successfully parsed. Please check to see if you entered the correct details in all the fields.\n\nReport the Error Code to the site administrators: " + gdir.getStatus().code);
	} else {
		alert("An unknown error occurred.");
	}
}

// Clear Routes
function clearRoute() {
	gdir.clear();

	fromGeoCode 	= document.getElementById("fromGeoCode");
	fromAddress 		= document.getElementById("fromAddress");
	fromSuburb 		= document.getElementById("fromSuburb");
	fromState 			= document.getElementById("fromState");

	toGeoCode 		= document.getElementById("toGeoCode");
	toAddress 			= document.getElementById("toAddress");
	toSuburb 			= document.getElementById("toSuburb");
	toState 				= document.getElementById("toState");

	fromGeoCode.value 		= '';
	fromAddress.value 		= '';
	fromSuburb.value 			= '';
	fromState.value 			= '';
	fromAddress.className = '';

	toGeoCode.value 			= '';
	toAddress.value 			= '';
	toSuburb.value 				= '';
	toState.value 				= 'NSW';
	toAddress.className 	= '';
}

// Driving Directions from Marker
function getDirections(direction, address, suburb, state, point) {
	point = point.replace(/<br \/>/, '');

	clearRoute();

	document.getElementById('panels').tabber.tabShow(1);
	if (direction=='toHere') {
		fromAddress.className = 'focusedInput';
		fromAddress.focus();
		toGeoCode.value 		= point;
		toAddress.value 		= address;
		toSuburb.value 			= suburb;
		toState.value 			= state;
	} else {
		fromGeoCode.value 	= point;
		fromAddress.value 	= address;
		fromSuburb.value 		= suburb;
		fromState.value 		= state;
		toAddress.className = 'focusedInput';
		toAddress.focus();
	}
}



/*///////////////////////////////////////////////////////////
Street View Functions
///////////////////////////////////////////////////////////*/

function openPanoramaBubble() {
  var contentNode = document.createElement('div');
  contentNode.style.textAlign = 'center';
  contentNode.style.fontSize = '12px';
  contentNode.style.width = '435px';
  contentNode.style.height = '300px';
  contentNode.style.zIndex = '900';
  contentNode.innerHTML = 'Loading panorama';

  var smallNode = document.createElement('div');
  smallNode.style.width = '220px';
  smallNode.style.height = '220px';
  smallNode.id = 'pano';
  marker.openInfoWindow(smallNode, {maxContent: contentNode, maxTitle: "Full screen"});

  panorama = new GStreetviewPanorama(smallNode);
  panorama.setLocationAndPOV(marker.getLatLng(), null);
  // GEvent.addListener(panorama, "newpano", onNewLocation);
  // GEvent.addListener(panorama, "yawchanged", onYawChange); 

  var iw = map.getInfoWindow();
  GEvent.addListener(iw, "maximizeclick", function() {
	// GMapDivs[i].style.display = 'none';
  });
  GEvent.addListener(iw, "maximizeend", function() {
    panorama.setContainer(contentNode);  
    window.setTimeout("panorama.checkResize()", 5);
  });
}

function toggleOverlay() {
  if (!overlayInstance) {
    overlayInstance = new GStreetviewOverlay();
    map.addOverlay(overlayInstance);

	// Street View code
	var guyIcon = new GIcon(G_DEFAULT_ICON);
	guyIcon.image = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-0.png";
	guyIcon.transparent = "http://maps.google.com/intl/en_us/mapfiles/cb/man-pick.png";
	guyIcon.imageMap = [
	26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27, 16,26,
	16,20, 16,14, 19,13, 22,8
	];
	guyIcon.iconSize = new GSize(49, 52);
	guyIcon.iconAnchor = new GPoint(25, 35);  // near base of guy's feet
	guyIcon.infoWindowAnchor = new GPoint(25, 5);  // top of guy's head
	
	// latlng = new GLatLng(gLat,gLong);
	latlng = new GLatLng(map.getCenter().lat(),map.getCenter().lng());
	marker = new GMarker(latlng, {icon: guyIcon, draggable: true});
	map.addOverlay(marker);
	lastMarkerLocation = latlng;
	GEvent.addListener(marker, "dragend", onDragEnd);
	GEvent.addListener(marker, "click", openPanoramaBubble);

	malcontent = GEvent.addListener(map, "click", function(overlay,point) {
		if (point) { 
			map.setCenter(point);
			marker.setPoint(point);
			openPanoramaBubble();
		}
	});

	
  } else {
    map.removeOverlay(marker);
    GEvent.removeListener(malcontent);
    malcontent = null;

    map.removeOverlay(overlayInstance);
    overlayInstance = null;
  }
}


function onYawChange(newYaw) {
  var GUY_NUM_ICONS = 16;
  var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;
  if (newYaw < 0) {
    newYaw += 360;
  }
  guyImageNum = Math.round(newYaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS;
  guyImageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + guyImageNum + ".png";
  marker.setImage(guyImageUrl);
}

function onNewLocation(lat, lng) {
  var latlng = new GLatLng(lat, lng);
  marker.setLatLng(latlng);
  openPanoramaBubble();
}

function onDragEnd() {
  var latlng = marker.getLatLng();
  openPanoramaBubble();
  if (panorama) {
    client.getNearestPanorama(latlng, onResponse);
  }
}

function onResponse(response) {
  if (response.code != 200) {
    marker.setLatLng(lastMarkerLocation);
  } else {
    var latlng = new GLatLng(response.Location.lat, response.Location.lng);
    marker.setLatLng(latlng);
    lastMarkerLocation = latlng;
    openPanoramaBubble();
  }
}

function handleNoFlash(errorCode) {
  if (errorCode == 603) {
	alert("Error: Flash doesn't appear to be supported by your browser");
	return;
  }
}  

function resetMap() {
// Reset the centre of the map
map.setCenter(new GLatLng(gLat,gLong), zoomLevel);

// Kill surrounding Attractions
category = 'PRODUCT_ATTRACTION';
document.getElementById(category).checked = false;
hide(category, '');
isCatSet[category] = '0';
GEvent.removeListener(myListener[category]);

// Kill surrounding Accommodation
category = 'PRODUCT_ACCOMMODATION';
document.getElementById(category).checked = false;
hide(category, '');
isCatSet[category] = '0';
GEvent.removeListener(myListener[category]);
}

/*///////////////////////////////////////////////////////////
Event-Manager Script by Keith Gaughan
///////////////////////////////////////////////////////////*/
//EventManager.Add(window,'load', GLoad_Action);
//EventManager.Add(window,'load', GLoad);
//EventManager.Add(window,'unload', GUnload);