﻿///Start of LabeledMarker ////////////////////////////////////
function LabeledMarker(latlng, options){
    this.latlng = latlng;
    this.labelText = options.labelText || "";
    this.labelClass = options.labelClass || "markerLabel";
    this.labelOffset = options.labelOffset || new GSize(0, 0);
    this.clickable = options.clickable || true;
    if (options.draggable) {
    	options.draggable = false;
    }
    GMarker.apply(this, arguments);
}
LabeledMarker.prototype = new GMarker(new GLatLng(0, 0));
LabeledMarker.prototype.initialize = function(map) {
	GMarker.prototype.initialize.apply(this, arguments);
	var div = document.createElement("div");
	div.className = this.labelClass;
	div.innerHTML = this.labelText;
	div.style.position = "absolute";
	map.getPane(G_MAP_MARKER_PANE).appendChild(div);
	if (this.clickable) {
		var eventPassthrus = ['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseout'];
		for(var i = 0; i < eventPassthrus.length; i++) {
			var name = eventPassthrus[i];
			GEvent.addDomListener(div, name, newEventPassthru(this, name));
		}
		div.style.cursor = "pointer";
	}
	this.map = map;
	this.div = div;
}
function newEventPassthru(obj, event) {
	return function() { 
		GEvent.trigger(obj, event);
	};
}
LabeledMarker.prototype.redraw = function(force) {
	GMarker.prototype.redraw.apply(this, arguments);
	if (!force) return;
	var p = this.map.fromLatLngToDivPixel(this.latlng);
	var z = GOverlay.getZIndex(this.latlng.lat());
	this.div.style.left = (p.x + this.labelOffset.width) + "px";
	this.div.style.top = (p.y + this.labelOffset.height) + "px";
        this.div.style.color = "#000000";
	this.div.style.zIndex = z + 1; // in front of the marker
}
LabeledMarker.prototype.remove = function() {
	GEvent.clearInstanceListeners(this.div);
	this.div.parentNode.removeChild(this.div);
	this.div = null;
	GMarker.prototype.remove.apply(this, arguments);
}
///End of LabeledMarker ////////////////////////////////////
///Start MLoadingControl ///////////////////////////////////
function MLoadingControl(MOptions) {
	MOptions = MOptions ? MOptions : {};
	this.parent = MOptions.container ? MOptions.container : null;
	this.background = MOptions.background ? MOptions.background : '#EEEEEE';
	this.foreground = MOptions.foreground ? MOptions.foreground : '#000000';
	this.position = MOptions.position ? MOptions.position : new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(8, 30));
	this.visible = MOptions.visible ? MOptions.visible : false;
}
MLoadingControl.prototype = new GControl();
MLoadingControl.prototype.initialize = function(map) {
	this.map = map;
	this.loading = 0;
	this.container = document.createElement('div');
	var oTable = document.createElement('table');
	oTable.setAttribute('cellSpacing','0');
	oTable.style.border = '1px solid #c1c1c1';
	oTable.style.backgroundColor = '#e1e1e1';
	oTable.style.width = '200px';
	this.container.appendChild(oTable);
	var oRow = document.createElement('tr');
	oTable.appendChild(oRow);
	var oCell = document.createElement('td');
	oCell.innerHTML = '<img src="/images/icons/loading.gif">';
	this.setStyle2(oCell);
	oRow.appendChild(oCell);
	var oCell = document.createElement('td');
	oCell.innerHTML = 'loading ...';
	this.setStyle2(oCell);
	oRow.appendChild(oCell);
	if (this.parent) {
		this.parent.appendChild(container);
	}
	else {
		this.map.getContainer().appendChild(this.container);
	}
	if (!this.visible) {
		this.container.style.display = 'none';
	}
	this.container.innerHTML+="&nbsp;";  // This line for IE. Without it, it will not render the control
	return this.container;
}
MLoadingControl.prototype.getDefaultPosition = function() {
	return this.position;
}
MLoadingControl.prototype.show = function() {
	this.loading++;
	this.container.style.display = '';
}
MLoadingControl.prototype.hide = function() {
	this.loading--;
	if (this.loading <= 0) {
		this.container.style.display = 'none';
		this.loading = 0;
	}
}
MLoadingControl.prototype.isVisible = function() {
	return this.mapClick;
}
MLoadingControl.prototype.setStyle2 = function(obj) {
	obj.style.padding = '2px';
	obj.style.textAlign = 'center';
	obj.style.color = this.foreground;
	obj.style.backgroundColor = this.background;
	obj.style.font = 'normal 16px Arial';
}
/// END MLoadingControl ////////////////////////////////
/// Start of ServerMarkerControl ///////////////////////
var map;
var container;
var zoom = 4;
var centerPoint = new GLatLng(51.50076862304525, -0.1262856931152312);
var loadingControl = new MLoadingControl();
var requestSent = false;
var icons = map_createIcons();
var polygons = Array();
var properties = Array();
var clusters = Array();
var iwTemplates = Array();
var pixelThreshold = 256;
var infoWindow;
var centerBeforeMove;
var timeout;
var appRoot = "";

function map_moveEnd() {
	if (loadingControl.isVisible() || !infoWindow.isHidden()) {
		return;
	}
	var proj = map.getCurrentMapType().getProjection();
	var zoom = map.getZoom();
	var centerAfterMove = map.getCenter();
	var beforePx = proj.fromLatLngToPixel(centerBeforeMove, zoom);
	var afterPx = proj.fromLatLngToPixel(centerAfterMove, zoom);
	var d = Math.sqrt(Math.pow((beforePx.x - afterPx.x),2) + Math.pow((beforePx.y - afterPx.y),2));
	if (d < pixelThreshold) {
		return;
	}	
	centerBeforeMove = centerAfterMove;
	map_doSearch();
};

function map_zoomEnd(oldZ,zoom) {
	if (loadingControl.isVisible() || !infoWindow.isHidden()) {
		return;
	}
	var centerBeforeMove = map.getCenter();
	if (timeout) {
		window.clearTimeout(timeout);
	}
	timeout = window.setTimeout(function(){
		map_doSearch();
	},200);
};

function map_doSearch() {
	if (requestSent) {
		return;
	}
	 var query_str="a=";
     var __ttype0 = document.getElementById('ttype0')
     if (__ttype0 ) {
        if (__ttype0.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     }
     var __ttype1 = document.getElementById('ttype1')
     if (__ttype1 ) {
        if (__ttype1.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     }
     query_str += "&b=";
     var __typeab0= document.getElementById('typeab0')
     if (__typeab0) {
        if (__typeab0.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     }
     var __typeab1= document.getElementById('typeab1')
     if (__typeab1) {
        if (__typeab1.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     }
     var __typeab2= document.getElementById('typeab2')
     if (__typeab2) {
        if (__typeab2.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     }
     var __typeab3= document.getElementById('typeab3')
     if (__typeab3) {
        if (__typeab3.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     }
     var __typeab4= document.getElementById('typeab4')
     if (__typeab4) {
        if (__typeab4.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     }
     query_str += "&c=";
     var __room0 = document.getElementById('rooms0')
     if (__room0 ) {
        if (__room0.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     } 
     var __room1 = document.getElementById('rooms1')
     if (__room1 ) {
        if (__room1.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     } 
     var __room2 = document.getElementById('rooms2')
     if (__room2 ) {
        if (__room2.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     } 
     var __room3 = document.getElementById('rooms3')
     if (__room3 ) {
        if (__room3.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     } 
     var __room4 = document.getElementById('rooms4')
     if (__room4 ) {
        if (__room4.checked == true) { query_str += "1"; } else {  query_str += "0"; }
     } else {
        query_str += "0";
     } 
	var oClamp = document.getElementById('cbClamp');
	var oCenter = document.getElementById('cbCenter');
	var oMarkers = document.getElementById('markerLimit');
	var oGridDiv = document.getElementById('gridDiv');
	var oDeclust = document.getElementById('decluster');


	var zoom = map.getZoom();
	var proj = map.getCurrentMapType().getProjection();
	var NEPx = proj.fromLatLngToPixel(map.getBounds().getNorthEast(), zoom);
	var tileNEPx = new GPoint(NEPx.x - (NEPx.x % 256) + 256,NEPx.y - (NEPx.y % 256));
	var searchNE = proj.fromPixelToLatLng(tileNEPx,zoom);

	var SWPx = proj.fromLatLngToPixel(map.getBounds().getSouthWest(), zoom);
	var tileSWPx = new GPoint(SWPx.x - (SWPx.x % 256),SWPx.y - (SWPx.y % 256) + 256);
	var searchSW = proj.fromPixelToLatLng(tileSWPx,zoom);

	var lat1 = searchSW.lat().toFixed(6);
	var lon1 = searchSW.lng().toFixed(6);
	var lat2 = searchNE.lat().toFixed(6);
	var lon2 = searchNE.lng().toFixed(6);

	var deltaLat = Math.abs(lat1-lat2);
	var deltaLon = Math.abs(lon1-lon2);

	var url = appRoot + '/data/property_grid.aspx?lat1=' + lat1 + '&lon1=' + lon1 + '&lat2=' + lat2 + '&lon2=' + lon2 + '&zoom=' + zoom + "&" + query_str;

	requestSent = true;
	loadingControl.show();
	ajaxLoad(url,map_readMarkers);
};

function map_clearMarkers(){
	var marker = properties.shift();
	while (marker) {
		map.removeOverlay(marker);
		marker = properties.shift();
	}
	var marker = clusters.shift();
	while (marker) {
		map.removeOverlay(marker);
		marker = clusters.shift();
	}
}

function map_readMarkers(http_request) {
	var xml = http_request.responseXML;
	loadingControl.hide();
	requestSent = false;
	map_clearMarkers();
	var propCount = 0;
	var elements = xml.documentElement.getElementsByTagName('e');
	var resInfo = xml.documentElement.getElementsByTagName('results');
	var found = resInfo[0].getAttribute('found');
	var qTime = resInfo[0].getAttribute('queryTime');
	var qTime2 = resInfo[0].getAttribute('queryTime2');
	var declusterLimit = 5;//resInfo[0].getAttribute('declusterLimit');

	for (var i = 0; i < elements.length; i++) {
		var element = map_parseElement(elements[i])
		if (typeof element.gridX != 'undefined') {
			if (parseInt(element.cnt) > declusterLimit) {
				var marker = map_parseCluster(element);
				clusters.push(marker)
				map.addOverlay(marker);
				propCount += parseInt(element.cnt);
			}
			else {
				var sMarkers = elements[i].getElementsByTagName('m');
				for (var s = 0; s < sMarkers.length; s++) {
					var element = map_parseElement(sMarkers[s]);
					var marker = map_parseMarker(element);
					properties.push(marker)
					map.addOverlay(marker);
				}
			}
		}
		else if (typeof element.lat != 'undefined') {
			var marker = map_parseMarker(element);
			properties.push(marker)
			map.addOverlay(marker);
		}
	}
}

function map_parseElement(elem) {
	var str = '';
	str += '{';
	var attrs = elem.attributes;
	for ( var n = 0; n < attrs.length ; n++) {
		str += attrs[n].name + ': "' + attrs[n].value + '",';
	}
	str = str.replace(/,$/,"");
	str += '}';
	return element = eval("(" + str + ")");
}

function map_parseCluster(element) {	
	if (element.avLat && element.avLon) {
		var point = new GLatLng(parseFloat(element.avLat),parseFloat(element.avLon));
		var markerName = element.cnt + ' properties';
		var mIcon = new GIcon();
		var bounds = new GLatLngBounds();
		bounds.extend(new GLatLng(parseFloat(element.gridSWLat),parseFloat(element.gridSWLon)));
		bounds.extend(new GLatLng(parseFloat(element.gridNELat),parseFloat(element.gridNELon)));
		
		var marker = map_createMarker(element.cnt, element.gridX+'_'+element.gridY,point,markerName,'',mIcon,bounds);
		return marker;
	}
}

function map_parseMarker(element) {
	var point = new GLatLng(parseFloat(element.lat),parseFloat(element.lon));
	function templateComplete(str, p1) {
	  return eval(p1);
	}
	var infoTabs = Array();
	for (var c = 0 ; c < iwTemplates.length ; c++ ) {
		var html = iwTemplates[c].innerHTML;
		html = html.replace(/%%([^%]+)%%/g,templateComplete);
		var tabTitle = iwTemplates[c].title ? iwTemplates[c].title : "Tab " + c;
		var newTab = new GInfoWindowTab(tabTitle, html);
		infoTabs.push(newTab);
	}
	var markerName = element.title;
	var mIcon = new GIcon();
	var marker = map_createMarker(1, properties.length,point,markerName,infoTabs,mIcon,null);
	marker.type = element.type;				
	return marker;
}

function map_createMarker(no_prop, i,point,markerName,infoTabs,mIcon,bounds) {
	var marker = new GMarker(point,{title:markerName});
	marker.ix = i;
	marker.markerName = markerName;
	if (infoTabs) {
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowTabsHtml(infoTabs);
		});
	}
	if (bounds) {
	  mIcon.iconSize = new GSize(32, 32);
	  mIcon.iconAnchor = new GPoint(16, 16);
	  var _lOffset = new GSize(-6, -10);
	  var _mIconC = new GIcon();
	  if (no_prop == 1) {
	    _mIconC.image = appRoot + "/images/maps/m1.png";
	    _mIconC.iconSize = new GSize(52,52);
	    _mIconC.iconAnchor = new GPoint(26,26);
	    _lOffset = new GSize(-5, -5);
	  } else if ((no_prop>1)&&(no_prop<10)) {
	    _mIconC.image = appRoot + "/images/maps/m1.png";
	    _mIconC.iconSize = new GSize(52,52);
	    _mIconC.iconAnchor = new GPoint(26,26);
	    _lOffset = new GSize(-5, -5);
	  } else if ((no_prop>9)&&(no_prop<100)) {
	    _mIconC.image = appRoot + "/images/maps/m2.png";
	    _mIconC.iconSize = new GSize(52,52);
	    _mIconC.iconAnchor = new GPoint(26,26);
	    _lOffset = new GSize(-8, -5);
	  } else if ((no_prop>99)&&(no_prop<1000)) {
	    _mIconC.image = appRoot + "/images/maps/m3.png";
	    _mIconC.iconSize = new GSize(66,66);
	    _mIconC.iconAnchor = new GPoint(33,33);
	    _lOffset = new GSize(-12, -5);
	  } else if ((no_prop>999)&&(no_prop<10000)) {
	    _mIconC.image = appRoot + "/images/maps/m4.png";
	    _mIconC.iconSize = new GSize(66,66);
	    _mIconC.iconAnchor = new GPoint(33,33);
	    _lOffset = new GSize(-15, -5);
	  } else {
	    _mIconC.image = appRoot + "/images/maps/m5.png";
	    _mIconC.iconSize = new GSize(66,66);
	    _mIconC.iconAnchor = new GPoint(33,33);
	    _lOffset = new GSize(-15, -5);
	  }
	  
	    opts = {
                "icon": _mIconC,
                "clickable": false,
                "draggable": false,
                "labelText": no_prop,
                "labelOffset": _lOffset
                };
            marker = new LabeledMarker(point, opts);
        
	    marker.bounds = bounds;
		GEvent.addListener(marker, "click", function() {
			map.setCenter(marker.bounds.getCenter(), map.getBoundsZoomLevel(marker.bounds)); 
		});
	}
	return marker;
};

function map_createIcons() {
    var icons = Array();
	return icons;
}


/// End of ServerMarkerControl /////////////////////////
/// Start Ajax /////////////////////////////////////////
function ajaxLoad(url,callback,plain) {
	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType && plain) {
			http_request.overrideMimeType('text/plain');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	http_request.onreadystatechange =  function() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				eval(callback(http_request));
			}
			else {
				alert('Request Failed: ' + http_request.status);
			}
		}
	};
	http_request.open('GET', url, true);
	http_request.send(null);
}
/// End Ajax ///////////////////////////////////////////