
// declare some global vars
var attrCurrentFile = "data/root.xml";
var attrPrevFile = attrCurrentFile;
var attrFileStack = new Array();
var attrZoom = 7;
var map;

var attrMapCenter = null;

attrFileStack.push( attrCurrentFile );

var tourTitle;
var desc;
var url;
var img;
var vrfile;

function onLoad() {
	
	var baseIcon = new GIcon();
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);

	if (GBrowserIsCompatible() == false ) return;
	
	map = new GMap2(document.getElementById("map") );

	//map.setMapType( G_HYBRID_TYPE );

	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());

	// Add event listeners
	GEvent.addListener(map, "moveend", function() {
		var center = map.getCenter();
		//alert("map lat=" + center.lat() + " " + center.lng() );
		
		//var latLngStr = "lat=" + center.lat() + " lng=" + center.lng();
		//document.getElementById("message").innerHTML = latLngStr;
	});

	// load XML data to configure the current map
	loadXMLData( map, attrFileStack[0]);
	
	// create event triggers for info window open and close
	GEvent.addListener( map, "infowindowopen", function() {
		attrMapCenter = map.getCenter();
	});

	GEvent.addListener( map, "infowindowclose", function() {
		if ( attrMapCenter != null )
			map.setCenter( attrMapCenter );
	});	
}

function transformXML( node, xmlDoc ) {
	// Load XML 
	var xml = new ActiveXObject("Microsoft.XMLDOM");
	xml.async = false;
	xml.load( xmlDoc );
	
	// Transform
	var html = xml.transformNode(node);
	alert("html=" + html );
	return html;
}

// Creates a marker whose info window displays the letter corresponding to
// the given index
function createMarker(map, point, info, tooltip ) {
	
	var marker = new GMarker( point, { title: tooltip } );
	
	//var html = info + "</b>";
	GEvent.addListener( marker, "click", function() {
		// we have to do our own XSL transformation because there are problems with
		// the Google implementation.
		
		tourTitle = info.getElementsByTagName("title")[0].firstChild.data;
		desc = info.getElementsByTagName("desc")[0].firstChild.data;
		url = info.getElementsByTagName("url")[0].firstChild.data;
		img = info.getElementsByTagName("img")[0].firstChild.data;
		vrfile = info.getElementsByTagName("vrfile")[0].firstChild.data;
		

		
		// create the window
		marker.openInfoWindowHtml( 
			"<div id='infoWindow'>"
				+ "<div style='margin-bottom:10px;text-align:center;'>" + tourTitle + "</div>" 
					+ "<div align='center'>"
						+ "<a href='#' onClick=\"loadTour( vrfile, tourTitle, desc);\">"
						+ "<img style='border-style:none' width='145px' height='95px' src='" + img 
						+ "'></img><br />view tour</a></div>"					
			+ "</div>");
	});
	
	map.addOverlay( marker );
					
}

function addToolTip( map, marker, tooltip ) {
	// add tool tip
	
	// Disable tool tip for now
	//if ( tooltip != null && tooltip != "" ) {
	//	var topElement = marker.iconImage;
	//	if (marker.transparentIcon) {topElement = marker.transparentIcon;}
	//	if (marker.imageMap) {topElement = marker.imageMap;}

	//	topElement.setAttribute( "title" , tooltip );
	//}
}

function createZoomMarker( point, map, file, tooltip ) {
	var marker = new GMarker(point);
	
	GEvent.addListener( marker, "click", function() {
		loadXMLData( map, file );
	});

	map.addOverlay( marker );
	
	//addToolTip( map, marker, tooltip );
	
	// set the marker tool tip
	marker.title = tooltip;
}

/**
Initialize the map by setting the following:
	map centre
	map zoom level
*/
function initMap( xmlDoc, map ) {
   
	var config = xmlDoc.documentElement.getElementsByTagName("config");
	
	// initialize the vars and set them to default values
	var attrZoom = 7;
	var centerPoint = new GLatLng( 43.6634012509597, -79.376220703125 );
	
	if ( config.length > 0 ) {
		// find the zoom value
		attrZoom = parseInt(config[0].getAttribute("zoom") );
	}

	// find the center of the map
	var mapCenter = xmlDoc.documentElement.getElementsByTagName("center");
	if ( mapCenter.length > 0 ) {
		//centerPoint = new GPoint(parseFloat(mapCenter[0].getAttribute("lng")),
		//				 parseFloat(mapCenter[0].getAttribute("lat")));
		centerPoint = new GLatLng(
						 parseFloat(mapCenter[0].getAttribute("lat")),
                   parseFloat(mapCenter[0].getAttribute("lng")));
	}
	
	//alert( "init: setting " + centerPoint.lat() + " " + centerPoint.lng() + " " + attrZoom );
	map.setCenter( new GLatLng( centerPoint.lat(), centerPoint.lng() ), 17 - attrZoom );
	
	// enable continuous zoom
	map.enableContinuousZoom();
	map.enableDoubleClickZoom();
}



function eventXMLReadyStateChange( request, map ) {
	if (request.readyState == 4) {
		var xmlDoc = request.responseXML;

		// need to initialize the map after marker creation
		initMap( xmlDoc, map );	// initialize the map

		var markers = xmlDoc.documentElement.getElementsByTagName("point");
		var info = xmlDoc.documentElement.getElementsByTagName("info");


		for (var i = 0; i < markers.length; i++) {
			var point = new GPoint(parseFloat(markers[i].getAttribute("lng")),
							 parseFloat(markers[i].getAttribute("lat")));

			// find out if the point is a branch to another node
			var file = markers[i].getAttribute("file");
			var tooltip = markers[i].getAttribute("tt");

			if ( file == null || file == "" ) {
				createMarker( map, point, info[i], tooltip )   
			} else {
				createZoomMarker( point, map, file, tooltip );
			}
		}
	}	
}

// load data from an XML file
function loadXMLData( map, fileName ) {
	map.clearOverlays();
	var request = GXmlHttp.create();

	// save the current file
	attrFileStack.push( attrCurrentFile );
	attrCurrentFile = fileName;

	request.open("GET", fileName, true);
	request.onreadystatechange = function () {
		eventXMLReadyStateChange( request, map );
	}
	request.send(null);
}

function navPrevFile() {
	if ( attrFileStack.length > 1 ) {
		loadXMLData( map, attrFileStack[ attrFileStack.length - 2 ] );
		attrFileStack.pop();
	}
}

/******************************************
* Popup Box- By Jim Silver @ jimsilver47@yahoo.com
* Visit http://www.dynamicdrive.com/ for full source code
* This notice must stay intact for use
******************************************/

var ns4=document.layers
var ie4=document.all
var ns6=document.getElementById&&!document.all

//drag drop function for NS 4////
/////////////////////////////////

var dragswitch=0
var nsx
var nsy
var nstemp

function drag_dropns(name){
	if (!ns4)
		return
	temp=eval(name)
	temp.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP)
	temp.onmousedown=gons
	temp.onmousemove=dragns
	temp.onmouseup=stopns
}

function gons(e){
	temp.captureEvents(Event.MOUSEMOVE)
	nsx=e.x
	nsy=e.y
}
function dragns(e){
	if (dragswitch==1){
		temp.moveBy(e.x-nsx,e.y-nsy)
		return false
	}
}

function stopns(){
	temp.releaseEvents(Event.MOUSEMOVE)
}

//drag drop function for ie4+ and NS6////
/////////////////////////////////


function drag_drop(e){
	if (ie4&&dragapproved){
		crossobj.style.left=tempx+event.clientX-offsetx
		crossobj.style.top=tempy+event.clientY-offsety
		return false
	}
	else if (ns6&&dragapproved){
		crossobj.style.left=tempx+e.clientX-offsetx+"px"
		crossobj.style.top=tempy+e.clientY-offsety+"px"
		return false
	}
}

function initializedrag(e){
	crossobj=ns6? document.getElementById("showimage") : document.all.showimage
	var firedobj=ns6? e.target : event.srcElement
	var topelement=ns6? "html" : document.compatMode && document.compatMode!="BackCompat"? "documentElement" : "body"
	while (firedobj.tagName!=topelement.toUpperCase() && firedobj.id!="dragbar"){
		firedobj=ns6? firedobj.parentNode : firedobj.parentElement
	}

	if (firedobj.id=="dragbar"){
		offsetx=ie4? event.clientX : e.clientX
		offsety=ie4? event.clientY : e.clientY

		tempx=parseInt(crossobj.style.left)
		tempy=parseInt(crossobj.style.top)

		dragapproved=true
		document.onmousemove=drag_drop
	}
}

document.onmouseup=new Function("dragapproved=false")

////drag drop functions end here//////

function hidebox(){
	crossobj=ns6? document.getElementById("showimage") : document.all.showimage
	if (ie4||ns6)
	crossobj.style.visibility="hidden"
	else if (ns4)
	document.showimage.visibility="hide"
}

// iState: 1 visible, 0 hidden
function toggleBox(szDivID, iState)  {
	if(document.layers) {	   //NN4+
	   document.layers[szDivID].visibility = iState ? "show" : "hide";
	} else if( document.getElementById )	{  //gecko(NN6) + IE 5+
		var obj = document.getElementById(szDivID);
		if ( obj != null )
			obj.style.visibility = iState ? "visible" : "hidden";
		else
			alert( szDivID + " div is not found!" );
	} else if(document.all)	{ // IE 4
		document.all[szDivID].style.visibility = iState ? "visible" : "hidden";
	}

}

// ajax code

var http_request = false;

function makeRequest(url, parameters) {

  	http_request = false;
	
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
	 	http_request = new XMLHttpRequest();
	 	if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
	 	}
	} else if (window.ActiveXObject) { // IE
	 	try {
			http_request = new ActiveXObject("Msxml4.XMLHTTP");
	 	} catch (e) {
			try {
		   		http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
	 	}
	}

	if (!http_request) {
	 	alert('Cannot create XMLHTTP instance');
	 	return false;
	}
	http_request.onreadystatechange = alertContents;
	http_request.open('GET', url + parameters, true);
	http_request.send(null);
}

function alertContents() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			result = http_request.responseText;

			document.getElementById('tour').innerHTML = result;

			toggleBox( "showimage", 1 );
			
			http_request = null;
		} else {
			alert('There was a problem with the request.');
		}
	}
}
