//<![CDATA[



var layersUrl = "/includes/GeoSmartLayersProxy.aspx?sort=distance&radius=100000&start=1&maxResults=25";

var mousedOver = false;
var map;
var property;
var address;
var feature;
var indicatorTimeout = null;
var zoomLevel;
var iWin = null;
var bubbleTimeout = null, infoTimeout = null;
var propertiesAgregated = false;

// get an element value
function getPoiValue(poi, name){
	if(poi.getElementsByTagName(name)[0] && poi.getElementsByTagName(name)[0].childNodes[0])
		return poi.getElementsByTagName(name)[0].childNodes[0].nodeValue;
}
// put the pois on the map
function getPois(xmlDoc){
	var nodes = xmlDoc.getElementsByTagName('pois');
    // test what we've got
	if(nodes.length==0)
		return;
	
	var pois = nodes[0];
	var layerName = pois.getAttribute('category');
    var layer = map.getLayer(layerName);

    if(!layer)
		return;
	var poi = pois.getElementsByTagName("poi");
	var features = new Array();
	for(var i=0; i<poi.length; i++){
		// create the feature and add it to the map
		var gsp = new GSPoint(getPoiValue(poi[i],"x"), getPoiValue(poi[i],"y"));
		var street = getInfoValue(poi[i], 'street');
		var town = getInfoValue(poi[i], 'town');
		var suburb = getInfoValue(poi[i], 'suburb');
		var feature = new GSPointFeature({
			id: getPoiValue(poi[i],"id"),
			coordinate: gsp,
			icon: new GSIcon(eval('icon_'+layerName)),
			name: getPoiValue(poi[i],"name"),
			infoHtml: "<div id='mapPropDetails' class='mapBubble'><p class='heading'>" + getPoiValue(poi[i],"name") + "</p>" + street + town + suburb +"</div>"
		});
		feature.addEventHandler("click", function(e) {
			this.showInfoWindow();
			// prevents click event propagating to map
			GSUtil.cancelEvent(e);
			}
		);
		feature.addEventHandler("mouseover", function(e) {
				this.showInfoWindow();
				mousedOver = true;
				if(bubbleTimeout != null)
				{
					window.clearTimeout(bubbleTimeout);
					bubbleTimeout = null;
				}
				if(infoTimeout != null)
				{
					window.clearTimeout(infoTimeout);
					infoTimeout = null;
				}
				// prevents mouseover event propagating to map
				GSUtil.cancelEvent(e);
			}
		);
		feature.addEventHandler("mouseout", function(e) { 
			if(mousedOver)
			{
				bubbleTimeout = window.setTimeout('byeBubble();', 400);
			}
			}
		);
		features[i] = feature;
	}
	layer.addFeatures(features);
}
// Get a poi value for the info window
function getInfoValue(node, idx)
{
	var txt = getPoiValue(node,idx);
	if(txt == undefined)
		return '';
	else
		return '<p>' + txt + '</p>';
}
// close the info window if open
function byeBubble()
{
	map.closeInfoWindow();
	infoTimeout = window.setTimeout('helloInfo();', 2000);
}
function helloInfo()
{
	if(iWin != null)
			map.openInfoWindow(iWin.coordinate, iWin.htmlText);
}



// toggle layer display
// drawing all the little icons as necessary
function toggleLayer(layerName) {
    var layer = map.getLayer(layerName);

    if (! layer) {
        layer = map.createLayer(layerName);
		refreshLayer(layerName);
    }
    else {
		if(layer.visible)
			layer.setVisible(false);
		else
			layer.setVisible(true);
    }
}

function refreshLayer(layerName){
	var currLayer = map.getLayer(layerName);
	
	if(!currLayer) return;
	
	if(mode!='popup'){ 
		currLayer.clear();
	}
	
	if(!document.getElementById(layerName) || !document.getElementById(layerName).checked) return; 

	var url = layersUrl + "&category[]=" + layerName;
	// some sort of ie bug was not giving property co-ords
	if(property.x == undefined || property.y == undefined)
		url = url + "&x=" + map.centerX + "&y=" + map.centerY;
	else
		url = url + "&x=" + property.x + "&y=" + property.y;

    // load remote data
	var xmlhttp = getXMLHTTP();
	if(xmlhttp)
	{
		toggleMapInidcator(true);
		// just a little catch-all in case the boxes are clicked too fast
		indicatorTimeout = window.setTimeout('toggleMapInidcator(false);', 8000);
		xmlhttp.open("GET", url,true);
		//xmlhttp.layerName = layerName;
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				if (xmlhttp.status == 200) {
					xmlDoc = xmlhttp.responseXML;
					if(!xmlDoc || xmlDoc.xml=='')
					{
						xmlDoc = getXMLDoc(xmlhttp.responseText);
					}
					if(xmlDoc)
					{
						window.setTimeout('toggleMapInidcator(false);',200);
						getPois(xmlDoc);
					}
				}
			}
		}
		xmlhttp.send(null);
	}
}

// shows / hides the map loading indicator
// and disables dragging while loading
var loading=false;
function toggleMapInidcator(bShow)
{
	var loadStatus = $('mapLoadStatus');
	if(loadStatus)
	{
		if(bShow)
		{
			map.dragToPan=false;
			loadStatus.style.display = 'block';
			loading=true;
		}
		else
		{
			map.dragToPan=true;
			map.panTo(map.getMapCenter()); //Fixes FF bug that doesn't allow dragging if user tries to drag while still loading
			window.setTimeout("hideLoadStatus();",300);
			if(indicatorTimeout)
			{
				window.clearTimeout(indicatorTimeout);
				indicatorTimeout = null;
			}
		}
	}
}

function hideLoadStatus(){
	var loadStatus = $('mapLoadStatus');
	if(loadStatus){ 
		loadStatus.style.display = 'none';
	}
	loading=false;
}




// return an XML document
// which is populated with txt
// or false if failed
function getXMLDoc(txt)
{
	
	var xmlDoc = false;
	if (document.implementation && document.implementation.createDocument)
	{
		var parser = new DOMParser();
		xmlDoc = parser.parseFromString(txt, "text/xml");
	}
	else if (window.ActiveXObject)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML(txt);
	}
	else
	{
		return false;
	}
	return xmlDoc;
}

// return an xmlHTTP object
// or false if failed
function getXMLHTTP()
{
	var xmlhttp=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	try {
	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (E) {
	xmlhttp = false;
	}
	}
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	if (!xmlhttp && window.createRequest) {
		try {
			xmlhttp = window.createRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	return xmlhttp;
}

//variables to determine whether it is necessary to update features
var resultsRadius=0;
var resultsCenterX=0;
var resultsCenterY=0;
var update = true;
// event fires when the zoom level changes
mapZoomed = function(map, oldZoomLevel, newZoomLevel){
	zoomLevel = newZoomLevel;
	if(propertiesAgregated)
	{
		if(groupingScheme && zoomLevel>-1 && oldZoomLevel>-1 && groupingScheme[zoomLevel]!=groupingScheme[oldZoomLevel]){
			update = true;
			updateFeatures(map, false);
		}
	}
};
mapBoundsChanged = function(map,oldBounds,newBounds){
	//map.getLayer("properties").setVisible(false);
		//if circle of results fall within the map bounds, update. 
	if(parseInt(resultsCenterX)-resultsRadius<map.getBounds().minX
	&& parseInt(resultsCenterX)+resultsRadius>map.getBounds().maxX
	&& parseInt(resultsCenterY)-resultsRadius<map.getBounds().minY
	&& parseInt(resultsCenterY)+resultsRadius>map.getBounds().maxY){
		return;
	}
	//document.getElementById("debug").innerHTML+="radius"+(parseInt(resultsCenterX)-resultsRadius)+"&lt;"+map.getBounds().minX+","+(parseInt(resultsCenterX)-resultsRadius<map.getBounds().minX);
	
	updateFeatures(map,false);
	
};


function updateFeatures(map,center){
	if(!update) return;

	var url = "http://"+location.host+"/includes/MapFeatures.aspx?"
	url+="centerX="+map.centerX;
	url+="&centerY="+map.centerY;
	url+="&minX="+map.getBounds().minX;
	url+="&minY="+map.getBounds().minY;
	url+="&maxX="+map.getBounds().maxX;
	url+="&maxY="+map.getBounds().maxY;
	url+="&zoomLevel="+zoomLevel;
	url+="&"+window.location.search.substring(1);
	//document.getElementById("debug").innerHTML = url;
	map.closeInfoWindow();
	iWin = null;

	//return;
	var xmlhttp = getXMLHTTP();
	
		if(xmlhttp)
		{
			xmlhttp.open("GET", url,true);
			//xmlhttp.layerName = layerName;
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4) {

					if (xmlhttp.status == 200) {

						xmlDoc = xmlhttp.responseXML;

						if(!xmlDoc || xmlDoc.xml=='')
						{
							xmlDoc = getXMLDoc(xmlhttp.responseText);
						}
						if(xmlDoc)
						{
							window.setTimeout('toggleMapInidcator(false);',200);
							getPropertyPois(xmlDoc);
							
							if(center){ 
								map.centerOnLayer("properties", function() {
									gsp = map.getMapCenter();
									// seems to be a bug in the api
									if(gsp.x < 1975000 || gsp.x > 3000000 || gsp.y > 6770000 || gsp.y < 5300000)
										map.centerOnNewZealand();

								} );
							}
						}
					}
				}
			}
			
			xmlhttp.send(null);
			toggleMapInidcator(true);
			indicatorTimeout = window.setTimeout('toggleMapInidcator(false);', 8000);
		}
	
}


function getPropertyPois(xmlDoc){

	var nodes = xmlDoc.getElementsByTagName('pois');
   
    // test what we've got
	if(nodes.length==0)
		return;
	
	var pois = nodes[0];
	var poi = pois.getElementsByTagName("poi");

	if(poi.length==0)
	{
		var d = document.getElementById("map");
		var mo = document.getElementById("mapOptions");
		var mn = document.getElementById("mapNone");
		if(d && mo && mn)
		{
			d.style.display = 'none';
			mo.style.display = 'none';
			mn.style.display = 'block';
		}
		return;
	}

	var layerName = "properties";
	resultsRadius = pois.getAttribute('radius');
	resultsCenterX = pois.getAttribute('centerX');
	resultsCenterY = pois.getAttribute('centerY');
	var totalNumberOfResults = parseInt(pois.getAttribute('totalNumberOfResults'));
	update = (totalNumberOfResults>parseInt(pois.getAttribute('numberOfResults')));
	var searchResultsCount = document.getElementById("searchResultsCount");
	if(searchResultsCount) searchResultsCount.innerHTML=totalNumberOfResults+" Search Results.&nbsp;&nbsp;&nbsp;&nbsp;Only properties that could be mapped will be displayed below."
	
	var layer = map.getLayer(layerName);

    if(!layer)
		return;
		
	layer.clear();
	for(var i=0; i<poi.length; i++){

		// create the feature and add it to the map
		gsp = new GSPoint(getPoiValue(poi[i],"x"), getPoiValue(poi[i],"y"));
		feature = new GSPointFeature({
			id: getPoiValue(poi[i],"id"),
			coordinate: gsp,
			icon: new GSIcon(eval(getPoiValue(poi[i],"iconName"))),
			name: getPoiValue(poi[i],"name"),
			infoHtml: getPoiValue(poi[i],"infoHtml")
		});
		feature.onclick = getPoiValue(poi[i],"onclick");
		feature.onmouseover = getPoiValue(poi[i],"onmouseover");
		feature.ondblclick = getPoiValue(poi[i],"ondblclick");
		layer.addFeature(feature);
		
		feature.addEventHandler("dblclick", function(e) {
				eval(this.ondblclick);
				
				// prevents click event propagating to map
				GSUtil.cancelEvent(e);
			}
		);
		
		feature.addEventHandler("click", function(e) {
				if(loading) return;
				eval(this.onclick);
				mousedOver = false;
				// prevents click event propagating to map
				GSUtil.cancelEvent(e);
				iWin = new iWindow(this.coordinate, this.infoHtml);
			}
		);

		feature.addEventHandler("mouseover", function(e) {
				eval(this.onmouseover);
				mousedOver = true;
				iWin = null;
				if(bubbleTimeout != null)
				{
					window.clearTimeout(bubbleTimeout);
					bubbleTimeout = null;
				}
				// prevents mouseover event propagating to map
				GSUtil.cancelEvent(e);
			}
		);
		feature.addEventHandler("mouseout", function(e) { 
			if(mousedOver)
			{
				bubbleTimeout = window.setTimeout('map.closeInfoWindow();', 1000);
			}
			}
		);
	}
	propertiesAgregated = true;	
}
// mouseout function of the info window
function infoOut()
{ 
	if(mousedOver)
	{
		bubbleTimeout = window.setTimeout('map.closeInfoWindow();', 1000);
	}
}
// mouseover function of the info window
function infoOver()
{
	mousedOver = true;
	iWin = null;
	if(bubbleTimeout != null)
	{
		window.clearTimeout(bubbleTimeout);
		bubbleTimeout = null;
	}
}
function getActiveLayers(){
	var activeLayers='';
	var layerCont = document.getElementById('mapOptions');
	if(!layerCont) return;
	var inputElements = layerCont.getElementsByTagName('INPUT');
	for(var i=0; i<inputElements.length; i++){
		if(inputElements[i].type=="checkbox" && inputElements[i].checked){
			activeLayers+=inputElements[i].id+",";
		}
	}
	if(activeLayers.lastIndexOf(',')==activeLayers.length-1) activeLayers = activeLayers.substring(0,activeLayers.length-1);
	return activeLayers;
}


//]]>