	/*
	APT Map Functions
	23 July 2008
	Author: peter.kumaschow@aptouring.com.au
	http://www.aptouring.com.au
	*/ 

	// Some Globals
	// Info Bubble Tabbed Panel
	var oTabbedPanel;
	// Default Info Bubble Position is defined in CSS but lets set up the vars here as well
	var iInfoBubbleTop = 20;
	var iInfoBubbleLeft = 420;
	var aImages = new Array;
	// Map Images
	var aRollOverImages = new Array;
	// Rollover Map Images
	var sMapHTML = "";
	var debug = false;
	// var sLoading = '<img src="images/loadingMap.jpg" width="776" height="462">';
	if (document.images)
	{
		var aPreImages = new Array, nCurrCount = 0;
		var aLoaded = new Array, i, timerID;
	}

	// MM Functions required for swapping images
	function MM_findObj(n, d)
	{
		// v4.01
		var p, i, x;
		if (!d)
		{
			d = document;
		}
		if ((p = n.indexOf("?")) > 0 && parent.frames.length)
		{
			d = parent.frames[n.substring(p + 1)].document;
			n = n.substring(0, p);
		}
		if (!(x = d[n]) && d.all)
		{
			x = d.all[n];
		}
		for (i = 0; !x && i < d.forms.length; i++)
		{
			x = d.forms[i][n];
		}
		for (i = 0; !x && d.layers && i < d.layers.length; i++)
		{
			x = MM_findObj(n, d.layers[i].document);
		}
		if (!x && d.getElementById)
		{
			x = d.getElementById(n);
		}
		return x;
	}

	function MM_swapImage()
	{
		// v3.0
		var i, j = 0, x, a = MM_swapImage.arguments;
		document.MM_sr = new Array;
		for (i = 0; i < a.length - 2; i += 3)
		{
			if ((x = MM_findObj(a[i])) != null)
			{
				document.MM_sr[j++] = x;
				if (!x.oSrc)
				{
					x.oSrc = x.src;
				}
				x.src = a[i + 2];
			}
		}
	}

	function MM_swapImgRestore()
	{
		// v3.0
		var i, x, a = document.MM_sr;
		for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
		{
			x.src = x.oSrc;
		}
	}
	
	// Fetch the Map XML Data
	function fGetXML(url, cache_method, ui_id)
	{
		if (debug){fLog('fGetXML ' + url + ' ' + cache_method + ' ' + ui_id)};
		if (ui_id == "TourStyle")
		{
			Http.get({url: url, callback: fUpDateTourStyles, cache: cache_method}, [ui_id]);
		} else {
			Http.get({url: url, callback: fUpdate, cache: cache_method}, [ui_id]);	
		}
	}
	
	// Callback function for fGetXML
	function fUpdate(result, ui_id)
	{
		if (debug)fLog(Http._get.readyState);
		if (debug){fLog('fUpdate ' + ui_id)};
		var div = document.getElementById(ui_id);
		// If XML was retrieved extract and load the images
		if (result.status == Http.Status.OK)
		{
			switch (ui_id)
			{
				case "aptMap":
					// fRenderOutput("XML Loaded",'debug');
					sMapHTML = result.responseText;
					// Create a Tab Panel if we need one
					if (!fLoadImages(result.responseText))
					{
						if (debug){fLog('floadImages failed')};	
					}
					break;
				case "DestinationCity_ID":
					fRemoveOptions(document.getElementById('DestinationCity_ID'));
					fAddOptions(document.getElementById('DestinationCity_ID'),result.responseText);
					if (debug){fLog('floadTourStyles 1 ')};
					floadTourStyles('TourStyle');
					break;
				case "DestinationRegion_ID":
					fRemoveOptions(document.getElementById('DestinationRegion_ID'));
					fRemoveOptions(document.getElementById('DestinationCity_ID'));
					fAddOptions(document.getElementById('DestinationRegion_ID'),result.responseText);
					var tempEl = document.getElementById('DestinationCity_ID');
					fAddOptions(tempEl,'<list name="DestinationCity_Document_ID"><option value="0">Select City / Place</option><option value="0">Please select a Region / Country First...</option></list>\n');
					if (debug){fLog('floadTourStyles 2 ')};
					floadTourStyles('TourStyle');
					break;			
				default :
					if (debug){fLog('fUpdate ' + result.responseText)};
					div.innerHTML = result.responseText;
			}
		}
		else // Else show an error message
		{
			if (result.status.toString() != "0") // ignore if a blank code
			{
				div.innerHTML = "<img src=\"images/notfoundMap.jpg\" width=\"776\" height=\"462\" /><br/><center>An error occurred (" + result.status.toString() + ")</center>";
			}
		}
	}
	
	function fUpDateTourStyles(result1, ui_id)
	{
		if (debug){fLog('fUpDateTourStyles ')};
		tourStyleSelect = document.getElementById('TourStyle');
		fRemoveOptions(tourStyleSelect);
		fAddOptions(tourStyleSelect,result1.responseText);
	}
	
	//Add new items to a drop down list
	function fAddOptions(el,sXML)
	{
		if (debug)fLog("fAddOptions " + el.name);
		var oXMLTree = new (XML.ObjTree);	
		oXMLTree.force_array = ["list:option"];
		var oTree = oXMLTree.parseXML(sXML);
		//fLog(oTree.list);
		var sOutput = "";
		
		for (var option in oTree.list.option)
		{
			if (typeof(oTree.list.option[option]['-value']) != 'undefined') 
			{
				var newoption = document.createElement('option');
				newoption.text = oTree.list.option[option]['#text'];
				newoption.value = oTree.list.option[option]['-value'];
				if (debug){fLog(newoption.text)};
				try
				{
				  el.add(newoption,null);	
				} catch(e) {
				  el.add(newoption);	
				}
			}
		}			
	}
	
	//function remove ALL items from a drop down list
	function fRemoveOptions(el)
	{
		if (debug){fLog("fRemoveOptions " + el.options.length)};
		var optionlength = el.options.length;
		for (var i = 0; i < optionlength; i++)
		{
			//if (debug){fLog("fRemoveOptions " + i)};
			el.remove(el.options[i]);
		}
	}
	
	// Process the XML, extract and load the images required for a map
	function fLoadImages(sXML)
	{
		if (debug){fLog('fLoadImages')};
		try
		{	
			
		    //fLog('1');			    		        
		    //fLog('xml from webservice: ' + sXML.replace(/\s/g,' ').replace(/  ,/g,','));	
		        
			var oXMLTree = new (XML.ObjTree);						
			oXMLTree.force_array = ["apt:MapXML:table:tr"];						
			var oTree = oXMLTree.parseXML(sXML.replace(/\s/g,' ').replace(/  ,/g,','));						
			var sOutput = "";			
			//fLog('2');
			try
			{
				// console.debug(oTree.apt.div["-id"] + 'top: ' + oTree.apt.div["-top"]);
				// console.debug(oTree.apt.div["-id"] + 'left: ' + oTree.apt.div["-left"]);
				iInfoBubbleTop = oTree.apt.div['-top'];
				iInfoBubbleLeft = oTree.apt.div['-left'];
			}
			catch (e)
			{
				// Set Default Position
				iInfoBubbleTop = 20;
				iInfoBubbleLeft = 420;
			}
			//fLog('3');
			//fLog('Parsed Xml: ' + oXMLTree.writeXML(oTree));						
			var spaceloaded = false;
			for (var tr in oTree.apt.MapXML.table.tr)
			{			
				try
				{			
					for (var td in oTree.apt.MapXML.table.tr[tr].td)
					{
					    //if (debug){fLog('3c')};
						if (oTree.apt.MapXML.table.tr[tr].td[td].img['-src'] != 'images/spacer.gif')
						{
							sOutput += oTree.apt.MapXML.table.tr[tr].td[td].img['-src'] + "\n";
							aImages.push(oTree.apt.MapXML.table.tr[tr].td[td].img['-src']);
							spaceloaded = true;							
							//if (debug){fLog("mouse over table image " + oTree.apt.MapXML.table.tr[tr].td[td].img['-src'])};
						} 
					}
				}
				catch (e)
				{
					// no img 
					//fLog('no img error');
					//if (debug){fLog('fLoadImages error: ' + e)};
					//return false;
				}
			}
			//if (debug)fLog('4');
			for (var map in oTree.apt.MapXML.map)
			{
				try
				{
					if (oTree.apt.MapXML.map[map].area['-onmouseover'])
					{
						//fLog("mouse over " + oTree.apt.MapXML.map[map].area['-onmouseover']);
						var sTemp = new String(oTree.apt.MapXML.map[map].area['-onmouseover']);
						var aSplit = sTemp.split(",");
						for (var i in aSplit)
						{
							if (/images/.exec(String(aSplit[i])))
							{
								if (oTree.apt.MapXML.table.tr[tr].td[td].img['-src'] != "'images/spacer.gif'")
								{
								// using eval because the filename is wrapped in single quotes
								eval("aRollOverImages.push(" + aSplit[i] + ")");
								}
								//if (debug){fLog("mouse over map image " + i + " " + aSplit[i])};
							}
						}
					}
				}
				catch (e)
				{
					//fLog("no image");
					// no img
				}
			}
			// Remove Duplicate File Names 
			//fLog('5');
			var allImages = aImages.concat(aRollOverImages);
			for (i = 0; i < allImages.length; i++)
			{
				aPreImages[i] = new Image;
				aPreImages[i].src = allImages[i];
				aLoaded[i] = false;
			}
			/*for (i = 0; i < aPreImages.length; i++)
			{
				aLoaded[i] = false;
			}*/
			//fLog('6');
			fCheckLoad();
			//fLog('7');
		}
		catch (e)
		{
			fRenderOutput("XML Processing Error occurred", "aptMap");
			return false;
		}
		return true;
	}

	// Check to see if all required images are loaded
	function fCheckLoad()
	{
		if (debug){fLog('fCheckLoad ' + aPreImages.length)};
		try
		{
			if (nCurrCount == aPreImages.length)
			{
				fRenderOutput(sMapHTML, "aptMap");
				fHideLoading();
				return;
			}
			for (i = 0; i <= aPreImages.length; i++)
			{
				if (aLoaded[i] == false && aPreImages[i].complete)
				{
					//if (debug){fLog('fCheckLoad loaded image ' + i + ' ' + aPreImages[i].src)};
					aLoaded[i] = true;
					nCurrCount++;
				}
			}
			timerID = setTimeout("fCheckLoad()", 1000);
		}
		catch (e)
		{
			fRenderOutput("Map loading Error occurred", "aptMap");
			return;
		}
	}

	// Render html output to an element on the page
	function fRenderOutput(sOutput, ui_id)
	{
		if (debug){fLog('fRenderOutput')};
		// console.info('fRenderOutput ' + ui_id);

		try
		{
		var oDiv = document.getElementById(ui_id);
		oDiv.innerHTML = sOutput;
		oInfoBubble = document.getElementById("InfoBubble");
			oTabbedPanel = new (Spry.Widget.TabbedPanels)("InfoBubble");
			oInfoBubble.style.top = iInfoBubbleTop + "px";
			oInfoBubble.style.left = iInfoBubbleLeft + "px";
		}
		catch (e)
		{
			//fLog("Tabbed Panel Instantiation failed");
		}
	}
	
	// Clear Cache and Request the Map XML Data
	function fLoadMap(sURL)
	{
		if (debug){fLog('fLoadMap ' + sURL)};
		var re = /=\w+/;
		var s = new String(sURL);
		var sMapKey = new String(s.match(re));		
		
		// Clear the cache and images from previous map if required
		//Http.clear_cache();
		if (document.images)
		{
			aPreImages = new Array;
			nCurrCount = 0;
			aLoaded = new Array;
		}
		// show the Loading Message
		fShowLoading();
		// get the requested map xml data 
		fGetXML(sURL, Http.Cache.GetCache, "aptMap");
		pageTracker._trackPageview("mapKey-" + sMapKey.substring(1) ); //remove = from mapKey
	}
	
	function floadDestinationRegions(iDestinationID)
	{
		if (debug){fLog('floadDestinationRegions ' + iDestinationID)};
		var strURL = '/mapwebservice.asp?op=GetRegions&id=' + iDestinationID;
		//These vars aren't used yet - Feature 258
		var elDestRegionID = document.getElementById('DestinationRegion_ID'); 
		var elDestCityID = document.getElementById('DestinationCity_ID');	
		//fLog(elDestCityID.value);	
		fGetXML(strURL, Http.Cache.GetCache, "DestinationRegion_ID");
	}
	
	function floadDestinationRegionCities(iDestinationRegionID)
	{
		if (debug){fLog('floadDestinatonRegionCities ' + iDestinationRegionID)};
		var strURL = '/mapwebservice.asp?op=GetCities&id=' + iDestinationRegionID;
		//These vars aren't used yet - Feature 258
		var elDestID = document.getElementById('Destination_ID');
		var elDestRegionID = document.getElementById('DestinationRegion_ID');
		fGetXML('/mapwebservice.asp?op=GetCities&id=' + iDestinationRegionID, Http.Cache.GetCache, "DestinationCity_ID");
	}
	
	function floadTourStyles()
	{
		if (debug){fLog('floadTourStyles ')};
		var elDestID = document.getElementById('Destination_ID');
		var elDestRegionID = document.getElementById('DestinationRegion_ID');		
		var elDestCityID = document.getElementById('DestinationCity_ID');
		//Don't actually need an id value for this so passing a value of 0
		var strURL = '/mapwebservice.asp?op=GetTourStyles&id=0&did=' + elDestID.value + '&drid=' + elDestRegionID.value + '&dcid=' + elDestCityID.value;
		//if (debug){fLog(strURL)};
		//Http.clear_cache();
		fGetXML(strURL, Http.Cache.GetNoCache, "TourStyle");
	}	
	
	// Show the Loading Message
	function fShowLoading()
	{
		if (debug){fLog('fShowLoading')};
		try {
			oDiv = document.getElementById("loading");
			oDiv.style.visibility = "visible";
		} catch(e) {
			
		}
	}
	
	// Hide the Loading Message
	function fHideLoading()
	{
		if (debug){fLog('fHideLoading')};
		try {
			oDiv = document.getElementById("loading");
			oDiv.style.visibility = "hidden";
		} catch(e) {
			
		}
	}
	
	// Hide an Element on the page
	function fHide(ui_id)
	{
		if (debug){fLog('fHide')};
		try
		{
			el = document.getElementById(ui_id);
			el.style.visibility = "hidden";
		}
		catch (e)
		{
		}
	}
	
	function fLog(sMsg)
	{
		try {
			console.log(sMsg);
		} catch(e) {
			//nada
		}
	}

