var blueIcon = new GIcon();
blueIcon.image = "/images/kleinicon.png";
blueIcon.iconSize = new GSize(25, 30);
blueIcon.shadowSize = new GSize(37, 34);
blueIcon.iconAnchor = new GPoint(9, 34);
blueIcon.infoWindowAnchor = new GPoint(9, 2);
blueIcon.infoShadowAnchor = new GPoint(18, 25);

var greenIcon = new GIcon();
greenIcon.image = "/images/icons/iconinfo2.png";
greenIcon.iconSize = new GSize(25, 30);
greenIcon.shadowSize = new GSize(37, 34);
greenIcon.iconAnchor = new GPoint(9, 34);
greenIcon.infoWindowAnchor = new GPoint(9, 2);
greenIcon.infoShadowAnchor = new GPoint(18, 25);

function MyIcon(pos, number, size, _listings, map) {
	this.pos_ = pos;
	this.number_ = number;
	this.size_ = size;
	this.listings = _listings;
	this.map_obj = map;
	
	this.timer = null;
};
MyIcon.prototype = new GOverlay();
MyIcon.prototype.initialize = function(map) {
	var div = document.createElement("div");
	var img = document.createElement("img");
	var size = parseInt(84 - (50 / Math.max(map.getZoom(), 1)));
	img.src="/images/icons/icongroup.png";
	img.style.width = "45px";
	img.style.height = "30px";
	div.style.position = "absolute";
	div.appendChild(img);
	var txt = document.createElement("div");
	txt.innerHTML = this.number_;
	txt.style.cssText = "text-align:center; margin-top:-25px; color:#000; margin-left:9px; line-height:12px;";
	div.appendChild(txt);
	div.style.cursor = 'pointer';
	div.pos_ = this.pos_;
	div.onclick = function(){
		map.setZoom( 3 + map.getZoom() );
		map.setCenter(this.pos_);
	};
	map.getPane(G_MAP_MAP_PANE).appendChild(div);
	this.map_ = map;
	this.div_ = div;
	this.img_ = img;
	var me = this;
	this.img_.onmouseover = function(){ me.mouseover.call(me); };
	
};
MyIcon.prototype.remove = function() {
	this.div_.parentNode.removeChild(this.div_);
	while(document.getElementById('group_info_window')){
		var el = document.getElementById('group_info_window');
		el.parentNode.removeChild(el);
	}
};
MyIcon.prototype.copy = function() {
	return new MyIcon(this.pos_, this.number_, this.size_);
};
MyIcon.prototype.redraw = function(force) {
	if (!force) return;
	var c1 = this.map_.fromLatLngToDivPixel(this.pos_);
	this.div_.style.left = (Math.min(c1.x) - 10) + "px";
	this.div_.style.top = (Math.min(c1.y) - 25) + "px";
};
MyIcon.prototype.mouseover = function(){
	var getPos = function(owner){
			if(owner == undefined){
				return {top : 0, left:0 , width : 0, height : 0};
			};
			var e = owner;
			var oTop = e.offsetTop;
			var oLeft = e.offsetLeft;
			var oWidth = e.offsetWidth;
			var oHeight = e.offsetHeight;
			while(e = e.offsetParent){
				oTop += e.offsetTop;
				oLeft += e.offsetLeft;
			};
			return {
				top : oTop,
				left : oLeft,
				width : oWidth,
				height : oHeight
			};
		};
		
		
	var l = this.listings.length;
	var bits = [];
	for(var i=0; i<l; i++){
		var _item = this.listings[i];
		
		bits.push("<table>\
			<tr>\
				<td>\
				<a href='/properties_details/"+_item.id+"/?from_map=true'><img src='"+ _item.imgsrc +"' style='margin-right:5px; width:100px; border:none;' /></a>\
				</td>\
				<td><b>" + _item.name + "</b> <br/>" + _item.address+"<br/><a href='/properties_details/"+_item.id+"/?from_map=true'>Details</a></td>\
			</tr>\
		</table>");
	
	};
	
	while(document.getElementById('group_info_window')){
		document.getElementById('group_info_window').parentNode.removeChild(document.getElementById('group_info_window'));
	}
	
	var where = this.map_obj.map.fromLatLngToContainerPixel(this.pos_);
	if(!where){
		var where = { x : 0, y : 0 };
	};
	var map_div = document.getElementById('map');
	var pos = getPos(map_div);
	
	where.y -= pos.top;
	
	var div = document.createElement('div');
	div.setAttribute('id', 'group_info_window');
	div.setAttribute('class', 'info_window');
	div.setAttribute('style', 'width:300px;');
	var html = '<table cellpadding="0" cellspacing="0">\
						<tr>\
							<td><img src="/images/spacer.png" class="corner_tl" /></td>\
							<td class="top_bg"></td>\
							<td><img src="/images/spacer.png" class="corner_tr" /></td>\
						</tr>\
						<tr>\
							<td class="left_bg"></td>\
							<td style="background-color:#fff;"><div style="width:auto; margin:-8px; position:relative; z-index:100; font-size:80%; height:200px; overflow:auto;">' + bits.join("<hr />") + '</div></td>\
							<td class="right_bg"></td>\
						</tr>\
						<tr>\
							<td><img src="/images/spacer.png" class="corner_bl" /></td>\
							<td class="bottom_bg"></td>\
							<td><img src="/images/spacer.png" class="corner_br" /></td>\
						</tr>\
					</table>\
					<img src="/images/spacer.png" class="garrow" style="height:48px;" />';
					
	div.innerHTML = html;
	this.popup = div;
	
	document.body.appendChild(div);
	
	var pos = getPos(this.div_);
	
	where.x = pos.left;
	where.y += document.getElementById('group_info_window').clientHeight - 20;
	
	div.style.left = where.x+'px';
	div.style.top = (where.y-75)+'px';
	
	var me = this;
	div.onmouseover = function(){
		me.stop_hide();
	};
	div.onmouseout = function(){
		me.hide();
	};
	
	GEvent.addListener(this, 'remove', this.onremove);
};
MyIcon.prototype.hide = function(){
	var me = this;
	this.timer = setTimeout(function(){
		try{
			document.body.removeChild(me.popup);
		}catch(e){
			while(document.getElementById('group_info_window')){
				var el = document.getElementById('group_info_window');
				el.parentNode.removeChild(el);
			}
		}
	}, 100);
};
MyIcon.prototype.stop_hide = function(){
	clearTimeout(this.timer);
};
MyIcon.prototype.onremove = function(){
	if(this.popup){
		document.body.removeChild(this.popup);	
	};
};

Object.prototype.toString = function(){
	var bits = [];
	for(var i in this){
		bits.push('	' +i + ' : ' + this[i]);
	};
	return '{\n' + bits.join("\n") + '\n}';
};

var Ext = {
	
};
var $Ext = function(el){
	for(var i in Ext){
		el[i] = Ext[i];	
	};
	return el;
};
var $$Ext = function(o1, o2){
	for(var i in o2){
		o1[i] = o2[i];
	};
	return o1;
};
function KleinMap(_url, _map){
	this.url = _url;
	this.map = _map;
	this.overlays = [];
	this.infoWindowIsOpen = false;
	this.infoTimer = 0;
	this.infoCloseTimer = 0;
	this.infoNoCloseTimer = 0;
	this.infoID = 0;
	this.infoClose = true;
	this.private = 0;
	this.resized = false;
	
	this.queryTimer = null;
};

window.mouseclicked = false;
window.mouseoverid = null;

$$Ext(KleinMap.prototype, {

	restart: function () {
		var els = document.getElementsByTagName('input');
		for (var i = 0; i < els.length; i++) {
			if (els[i].type == "checkbox") {
				els[i].checked = false;
			} else if (els[i].type == "text") {
				els[i].value = '';

				if (els[i].className == "multiple_select") {
					els[i].value = "Please Select";
				}
			}
		}
		this.map.setCenter(new GLatLng(__center_lat, __center_lng), 2);
		this.resized = false;
		document.cookie = '';
		//this.init();
	},

	queryTime: function () {
		var that = this;
		clearTimeout(this.queryTimer);
		this.queryTimer = setTimeout(function () { that.query(); }, 1);
		this.map.setCenter(new GLatLng(__center_lat, __center_lng), 2);
		document.cookie = '';
	},

	query: function () {

		var b = this.map.getBounds();
		var west = b.getSouthWest().lng();
		var north = b.getNorthEast().lat();
		var south = b.getSouthWest().lat();
		var east = b.getNorthEast().lng();
		var data = {
			x: '[' + b.getSouthWest().lng() + ',' + b.getNorthEast().lng() + ']',
			y: '[' + b.getSouthWest().lat() + ',' + b.getNorthEast().lat() + ']',
			action: 'pub-search'
		};

		var trans = document.getElementById('trans_assets_thing');
		var ob = trans;
		var list = trans.childNodes;
		var str = [];
		var reselect = [];
		while (ob.selectedIndex != -1) {
			if (ob.selectedIndex >= 0)
				str.push(parseInt(ob.options[ob.selectedIndex].value)+1);

			reselect.push(ob.selectedIndex);
			ob.options[ob.selectedIndex].selected = false;
		}
		for (1; reselect.length > 0; ) {
			ob.options[reselect.pop()].selected = true;
		}

		if (trans) { data['intTransactionType'] = str.join(';'); };

		var ob = document.getElementById('id_cat_thing');
		var str = [];
		var reselect = [];
		while (ob.selectedIndex != -1) {
			str.push(ob.options[ob.selectedIndex].value);

			reselect.push(ob.selectedIndex);
			ob.options[ob.selectedIndex].selected = false;
		}
		for (1; reselect.length > 0; ) {
			ob.options[reselect.pop()].selected = true;
		}

		if (str.length != 0) { data['id_cat'] = str.join(';'); };

		var keywords = document.getElementById('keywords').value;
		if (keywords != '') { data['keywords'] = keywords; };		
		this.request(this.url, data);
	},

	initResize: function () {
		var top = -90, left = 180, right = -180, bottom = 90;
		var l = this.list.length;
		var floatMax = function (str) {
			str = str.toString();
			return str.substr(0, str.indexOf('.')) + str.substr(str.indexOf('.') || str.length, 15);
		};
		for (var i = 0; i < l; i++) {
			if (parseFloat(this.list[i]['latLng'].lat()) > 0) {
				top = Math.max(top, floatMax(this.list[i]['latLng'].lat()));
				bottom = Math.min(bottom, floatMax(this.list[i]['latLng'].lat()));
				left = Math.min(left, floatMax(this.list[i]['latLng'].lng()));
				right = Math.max(right, floatMax(this.list[i]['latLng'].lng()));
			};
		};
		var vdist = Math.abs(top) - Math.abs(bottom);
		var hdist = Math.abs(left) - Math.abs(right);
		var centery = top - (vdist / 2);
		var centerx = right - (hdist / 2);
		if (centery == -90) centery = 49.291826;
		if (centerx == -180) centerx = -123.109531;

		var z = 12;
		if (vdist >= 0.04013 || hdist >= 0.0653) {
			z = 12;
		};
		if (vdist >= 0.07618 || hdist >= 0.1191) {
			z = 11;
		};
		if (vdist >= 0.15263 || hdist >= 0.2389) {
			z = 10;
		};
		if (vdist >= 0.30133 || hdist >= 0.4779) {
			z = 9;
		};
		if (vdist >= 0.60802 || hdist >= 0.9571) {
			z = 8;
		};
		if (vdist >= 1.20539 || hdist >= 1.9116) {
			z = 7;
		};
		if (vdist >= 2.43287 || hdist >= 3.8232) {
			z = 6;
		};
		if (vdist >= 4.86412 || hdist >= 7.6574) {
			z = 5;
		};
		if (vdist >= 9.63382 || hdist >= 15.205) {
			z = 4;
		};
		if (vdist >= 19.3774 || hdist >= 30.629) {
			z = 3;
		};
		if (vdist >= 36.7212 || hdist >= 60.996) {
			z = 2;
		};
		if (vdist >= 40 || hdist >= 90) {
			z = 1;
		};
		if (vdist >= 50 || hdist >= 100) {
			z = 1;
		};
		this.resized = true;
		//this.map.setZoom(z);
		this.map.setCenter(new GLatLng(centery, centerx), z);
	},

	init: function (search) {
		window.that = this;
		this.list = [];
		this.nextRequest = false;
		this.markers = [];
		this.query();

		var that = this;
		if (!window.maplistener) {
			window.mapListener2 = GEvent.addListener(this.map, "movestart", function () {
				while (document.getElementById('group_info_window')) {
					var el = document.getElementById('group_info_window');
					el.parentNode.removeChild(el);
				}
			});
			window.maplistener = GEvent.addListener(this.map, "moveend", function () {
				if (that.map.getZoom() == 0) {
					that.map.setZoom(1);
				};
				if (that.resized) {
					document.cookie = 'loc,' + that.map.getCenter().lat() + ',' + that.map.getCenter().lng() + ',' + that.map.getZoom() + ';';
				};
				that.query();
				return;
			});
		};
		G_PHYSICAL_MAP.getMinimumResolution = function () { return 1 };
		G_NORMAL_MAP.getMinimumResolution = function () { return 1 };
		G_SATELLITE_MAP.getMinimumResolution = function () { return 1 };
		G_HYBRID_MAP.getMinimumResolution = function () { return 1 };

		if (!window.maplistener2) {
			window.maplistener2 = GEvent.addListener(this.map, "movestart", function () {
				that.closeInfoWindow();
				return;
			});
		};
		this.infoCloseTimer = setInterval(function () {
			that.infoCloseCheck();
		}, 400);
	},

	objectToQueryString: function (obj) {
		var bits = [];
		for (var i in obj) {
			bits.push(i + '=' + obj[i]);
		};
		return bits.join('&');
	},

	/**
	* bounds : GLatLngBounds object 
	* Url: http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds
	*/
	getInArea: function (bounds, type) {
		if (type != 'list') {
			type = 'count';
		};
		var l = this.list.length;
		var count = 0;
		var inArea = [];
		for (var i = 0; i < l; i++) {
			if (bounds.containsLatLng(this.list[i].latLng) && this.list[i].private != 1) {
				count++;
				inArea.push(this.list[i]);
			};
		};
		if (type == 'count') {
			return count;
		} else if (type == 'both') {
			return { 'count': count, 'list': inArea };
		} else {
			return inArea;
		};
	},

	request: function (url, request) {
		if (!request) {
			return;
		};

		var xmlHttp;
		try {
			xmlHttp = new XMLHttpRequest();
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					return false;
				};
			};
		};
		var that = this;
		xmlHttp.onreadystatechange = function () {
			if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
				that.xmlComplete();
			};
		};

		this.xml = xmlHttp;

		document.getElementById('loading_overlay').style.display = '';
		document.getElementById('loading_overlay').style.left = ((document.documentElement.clientWidth / 2) - (document.getElementById('loading_overlay').clientWidth / 2)) + (144 + 9) + 'px';
		request.r = Math.random();
		if ((this.xml.readyState == 4 && this.xml.status == 200) || this.xml.readyState == 0) {
			this.xml.open('GET', url + '?' + this.objectToQueryString(request), true);
			this.xml.send(null);
		} else {
			this.nextRequest = request;
		};
	},

	xmlComplete: function () {
		document.getElementById('loading_overlay').style.display = 'none';

		var subString = function (string, length, end) {
			if (string.length > length) {
				return string.substring(0, string.indexOf(' ', length)) + end;
			} else {
				return string;
			};
		};

		if (this.nextRequest) {
			this.request(this.nextRequest);
			this.nextRequest = null;
		};
		this.list = [];
		if (typeof (this.xml.responseText) == "unknown") {
			return;
		};
		var xml = GXml.parse(this.xml.responseText);
		var markers = xml.documentElement.getElementsByTagName("marker");

		this.private = xml.getElementsByTagName('markers')[0] ? xml.getElementsByTagName('markers')[0].getAttribute('private') : 0;
		this.total = xml.getElementsByTagName('markers')[0] ? xml.getElementsByTagName('markers')[0].getAttribute('total') : 0;
		this.public = markers.length;

		$('mapstats_results').innerHTML = "Results Found: " + ((+this.total)); // + (+this.private));
		$('mapstats_mapped').innerHTML = "Shown: " + Math.max((+this.public - (+this.private)), 0);
		if (this.private > 0) {
			$('mapstats_unmapped').innerHTML = "<a href=\"javascript://\" onclick=\"window.tool.displayPrivate()\" style=\"line-height:29px; height:29px;\">(" + this.private + " Hidden Listings)</a>";

			if (this.first_init !== true) {
				$('private_listings_display2').innerHTML = '';
				var tmp = "Note: There are " + this.private + " confidential listing(s) shown below, but their locations are not shown here on the map. Click the  at the bottom of the map frame to filter these opportunities at any time.";

				$('private_listings_display2').innerHTML = tmp;
				$('private_box2').style.display = 'block';
				this.timer = setTimeout(function () {
					$('private_box2').style.display = 'none';
				}, 6000);
			}

			this.first_init = true;

		} else {
			$('mapstats_unmapped').innerHTML = "Unmapped: 0";
		};




		var l = markers.length;
		for (var i = 0; i < l; i++) {
			var obj = {
				'latLng': new GLatLng(markers[i].getAttribute("lat"), markers[i].getAttribute("lng")),
				'id': markers[i].getAttribute("id"),
				'private': markers[i].getAttribute("private"),
				'address': markers[i].getAttribute("address") || "",
				'province': markers[i].getAttribute("province") || "",
				'country': markers[i].getAttribute("country") || "",
				'name': markers[i].getAttribute("name"),
				'city': markers[i].getAttribute("city") || "",
				'description': subString(markers[i].getAttribute("description").toString(), 240, '...'),
				'bedrooms': markers[i].getAttribute("bedrooms"),
				'bathrooms': markers[i].getAttribute("bathrooms"),
				'saleprice': markers[i].getAttribute("price"),
				'parking': markers[i].getAttribute("parking"),
				'count': markers[i].getAttribute("count"),
				'imgsrc': (markers[i].getAttribute("img").length > 1 ? markers[i].getAttribute("img") : '/images/no-image-small.jpg'),
				'overlay': markers[i].getAttribute("overlay"),
				'listings': markers[i].getAttribute("listings"),
				'numberofunits': markers[i].getAttribute('numberOfUnits'),
				'businessTypeMajorType': markers[i].getAttribute('businessTypeMajorType'),
				'businessTypeMinorType': markers[i].getAttribute('businessTypeMinorType'),
				'additionalRent': markers[i].getAttribute('additionalRent'),
				'leaseRate': markers[i].getAttribute('leaseRate'),
				'buildingType': markers[i].getAttribute('buildingType')
			};
			this.list[i] = obj;
		};

		if (this.resized == false) {
			if (document.cookie.substr(0, 3) == "loc") {
				var data = document.cookie.substr(0, document.cookie.indexOf(';'));
				var data = data.split(',');
				this.map.setCenter(new GLatLng(parseFloat(data[1]), parseFloat(data[2])), +data[3]);
				this.resized = true;
			} else {
				this.initResize();
			};
		}
		else {
			this.process(l);
		}
	},

	process: function (num) {

		document.offset = 0;
		document.page = 0;
		document.perpage = 8;
		//var count = this.getInArea(this.map.getBounds(), 'count');
		this.clearOverlays();

		this.listPaging();

		if (num > 49 || this.map.getZoom() < 8) {
			// Grouping
			this.groupListings(num);
		} else {
			// List	
			this.showListings(num);
		};

		//if(this.private > 0){
		//	$('private_listings').style.display = '';
		//	$('privateListingCount').innerHTML = this.private;
		//}

	},

	showListings: function (total) {
		var that = this;
		for (var i = 0; i < total; i++) {
			if (this.list[i].private == '1') {
				continue;
			};
			var marker = new GMarker(this.list[i].latLng, blueIcon);
			marker.list_id = this.list[i].id;
			this.markers[i] = marker;
			var j = i;
			window.that = this;
			GEvent.addListener(
				marker,
				'click',
				new Function("window.tool.map.setCenter(new GLatLng(" + this.list[i].latLng.lat() + ", " + this.list[i].latLng.lng() + "), " + (this.map.getZoom() + 1) + ")")
			);
			//GEvent.addListener(marker, 'click', new Function('window.mouseoverid = '+marker.list_id+'; window.mouseclicked = true; window.that.listingShow('+marker.list_id+');'));
			GEvent.addListener(
				marker,
				'mouseover',
				new Function('window.mouseoverid = ' + marker.list_id + ';')
			);
			GEvent.addListener(
				marker,
				'mouseout',
				new Function('window.mouseoverid = null;')
			);
			this.addOverlay(marker);

		}
	},

	getListByID: function (id) {
		var l = this.list.length;
		for (var i = 0; i < l; i++) {
			if (this.list[i]['id'] == id) {
				return this.list[i];
			};
		};
		return null;
	},

	groupListings: function (total) {
		var size = {
			'0': { w: 10, h: 10 },
			'1': { w: 25, h: 18 },
			'2': { w: 18, h: 12 },
			'3': { w: 8, h: 8 },
			'4': { w: 4, h: 3.5 },
			'5': { w: 1.9, h: 1.9 },
			'6': { w: 0.95, h: 0.95 },
			'7': { w: 0.45, h: 0.45 },
			'8': { w: 0.1374, h: 0.1374 },
			'9': { w: 0.1374, h: 0.1374 },
			'10': { w: 0.1374, h: 0.1374 },
			'11': { w: .03433, h: .03433 },
			'12': { w: .03433, h: .03433 },
			'13': { w: .03433, h: .03433 },
			'14': { w: .03433, h: .03433 },
			'15': { w: .03433, h: .03433 }
		}[this.map.getZoom()];

		var bounds = this.map.getBounds();
		var right = bounds.getNorthEast().lng();
		var top = bounds.getNorthEast().lat();
		var left = bounds.getSouthWest().lng();
		var width = size.w;
		var height = size.h;
		var minY = bounds.getSouthWest().lat();
		var minX = bounds.getNorthEast().lng();
		var records = [];
		var max = {
			count: 0
		};

		// For fixin' the IDL (International Date Line)
		var left_reset = false;
		if (left > right) {
			left_reset = true;
		}

		top = Math.round(top / height) * height;
		left = Math.round(bounds.getSouthWest().lng() / width) * width;
		var left_original = left;
		// For fixin' the IDL (International Date Line)
		if (left_reset) {
			left_original = left = -179
		}

		// Move test bound all around the map to determine the highest density area.
		window.listings_lists = [];
		while (top > (minY)) {
			while (left < (minX)) {
				var testBounds = new GLatLngBounds(
					new GLatLng(top - height, left),
					new GLatLng(top, left + width)
				);

				var count = this.getInArea(testBounds, 'count');

				if (count > 0) {
					records.push({
						'center': testBounds.getCenter(),
						'count': count
					});
					window.listings_lists.push(this.getInArea(testBounds, 'list'));
				};

				left += width;
			};


			top -= height;
			left = left_original;
		};

		var l = records.length;
		for (var i = 0; i < l; i++) {
			var ico = new MyIcon(
				records[i]['center'],
				records[i].count, //number
				.25, //records[i].count / total
				window.listings_lists[i],
				this
			);
			this.addOverlay(ico);
			//ico.onmouseover = ico.mouseover;
		};
	},

	addOverlay: function (overlay) {
		this.overlays.push(overlay);
		this.map.addOverlay(overlay);
	},

	clearOverlays: function () {
		for (var i = 0; i < this.overlays.length; i++) {
			this.map.removeOverlay(this.overlays[i]);
		};
		this.overlays = [];
	},

	infoCloseCheck: function () {
		if (window.mouseoverid == null && this.infoWindowIsOpen) {
			window.listing_showing = -1;
			this.closeInfoWindow();
		} else {
			this.listingShow(window.mouseoverid);
			window.listing_showing = window.mouseoverid;
		};
	},

	closeInfoWindow: function () {
		var el = document.getElementById('info_window');
		if (!el) {
			el = this.createInfoWindow();
		};
		el.innerHTML = '';
		this.infoWindowIsOpen = false;
		this.infoID = -1;
	},

	listingShow: function (index) {
		if (index == window.listing_showing) {
			return;
		};
		var _item = this.getListByID(index);
		if (_item == null) {
			return;
		};
		this.infoWindow(
			 "<table>\
				<tr>\
					<td>\
					<a href='/properties_details/" + _item.id + "/?from_map=true'><img src='" + _item.imgsrc + "' style='margin-right:5px; width:100px; border:none;' /></a>\
					</td>\
					<td><b>" + _item.name + "</b> <br/>" + _item.address + "<br/><a href='/properties_details/" + _item.id + "/?from_map=true'>Details</a></td>\
				</tr>\
			</table>",
			_item.latLng
		);
		var el = document.getElementById('info_window');
		el.onmouseover = function () {
			window.mouseoverid = index;
		};
	},

	createInfoWindow: function () {
		var el;
		el = document.createElement('div');
		el.id = "info_window";
		el.className = "info_window";
		document.body.appendChild(el);
		var that = this;
		el.onmouseout = function () {
			window.mouseoverid = null;
		};
		return el;
	},

	infoWindow: function (content, latlng) {

		if (this.infoWindowIsOpen) {
			this.closeInfoWindow();
		};
		this.infoWindowIsOpen = true;

		/*'<div class="info_window" id="info_window">'*/
		var html = '<table cellpadding="0" cellspacing="0">\
						<tr>\
							<td><img src="/images/spacer.png" class="corner_tl" /></td>\
							<td class="top_bg"></td>\
							<td><img src="/images/spacer.png" class="corner_tr" /></td>\
						</tr>\
						<tr>\
							<td class="left_bg"></td>\
							<td style="background-color:#fff;"><div style="width:auto; margin:-8px; position:relative; z-index:100; font-size:80%;">' + content + '</div></td>\
							<td class="right_bg"></td>\
						</tr>\
						<tr>\
							<td><img src="/images/spacer.png" class="corner_bl" /></td>\
							<td class="bottom_bg"></td>\
							<td><img src="/images/spacer.png" class="corner_br" /></td>\
						</tr>\
					</table>\
					<img src="/images/spacer.png" class="garrow" />';
		//+'</div>';


		var el = document.getElementById('info_window');
		if (!el) {
			el = this.createInfoWindow();
		};
		el.innerHTML = html;
		var getPos = function (owner) {
			if (owner == undefined) {
				return { top: 0, left: 0, width: 0, height: 0 };
			};
			var e = owner;
			var oTop = e.offsetTop;
			var oLeft = e.offsetLeft;
			var oWidth = e.offsetWidth;
			var oHeight = e.offsetHeight;
			while (e = e.offsetParent) {
				oTop += e.offsetTop;
				oLeft += e.offsetLeft;
			};
			return {
				top: oTop,
				left: oLeft,
				width: oWidth,
				height: oHeight
			};
		};
		var where = this.map.fromLatLngToContainerPixel(latlng);
		if (!where) {
			var where = { x: 0, y: 0 };
		};

		var map_div = document.getElementById('map');
		var pos = getPos(map_div);
		var divsize = { x: document.getElementById('info_window').clientWidth, y: document.getElementById('info_window').clientHeight };
		
		el.style.left = (pos.left + where.x - 24) + 'px';
		el.style.top = (pos.top + where.y - divsize.y - 43) + 'px';
	},
	listPaging: function (page) {
		if (!page) page = 1;
		document.page = page;
		document.offset = (document.page - 1) * document.perpage;
		document.pages = null;
		var html = [];

		for (var i = document.offset; i < Math.min(document.offset + document.perpage, this.list.length); i++) {
			this.list[i]['class_'] = (i % 2 ? '1' : '2');
			html.push(listingHTML(this.list[i]));
		};

		/*
		var pagesDiv = document.getElementById('property_list_pages');
		pagesDiv.innerHTML = '';
		var textnode = function(a){ return document.createTextNode(a); }
		var node = function(a){ return document.createElement(a); };
		var that = this;
		var sel = node('select');
		for(var i=0; i<Math.ceil(this.list.length/document.perpage); i++){
		var opt = node('option');
		if(i==document.page){
		opt.setAttribute('selected', 'selected');	
		};
		var txt = textnode('Page: ' + (i+1) + ' ');
		opt.appendChild( txt );
		opt.page = i;
		opt.onclick=function(){
		document.page = this.page;
		that.listPaging();
		};
		sel.appendChild( opt );
		};
		
		document.getElementById('property_list_pages').appendChild( sel );
		document.getElementById('property_list').innerHTML = html.join('');
		*/
		this.pagebar();
		document.getElementById('property_list').innerHTML = html.join('');
	},


	pagebar: function () {

		var that = this;
		var pagesDiv = document.getElementById('property_list_pages');
		pagesDiv.innerHTML = '';

		var end, p, pre_page, next_page, pre_group, next_group;
		var pagesize = 5;
		// this.list.length 10
		// document.perpage 5
		var total_pages = Math.ceil(this.list.length / document.perpage);
		var start = document.page - (document.page - 1) % pagesize;

		if ((end = start + pagesize - 1) > total_pages) end = total_pages;
		if (end == 0) end = 1;

		if (start > pagesize) pre_group = start - 1;
		if (total_pages > end) next_group = end + 1;
		if (document.page > 1) pre_page = document.page - 1;
		if (document.page < total_pages) next_page = document.page + 1;

		if (pre_group) pagesDiv.innerHTML += '<a href="javascript:" onclick="paging(' + pre_group + ');" style="font-size:10pt;">&laquo;</a>';
		else pagesDiv.innerHTML += '<a style="font-size:10pt;" class="nounder">&laquo;</a>';
		pagesDiv.innerHTML += '&nbsp;';

		if (pre_page) pagesDiv.innerHTML += '<a href="javascript:" onclick="paging(' + pre_page + ');" style="font-size:10pt;">&lsaquo;</a>';
		else pagesDiv.innerHTML += '<a style="font-size:10pt;" class="nounder">&lsaquo;</a>';
		pagesDiv.innerHTML += '&nbsp;';
		pagesDiv.innerHTML += '&nbsp;';
		if (start > 1) {
			pagesDiv.innerHTML += '<a href="javascript:" onclick="paging(1);>1</a>';
			pagesDiv.innerHTML += '....';
			pagesDiv.innerHTML += '&nbsp;';
		}

		for (var i = start; i <= end; i++) {
			if (i == document.page) {
				pagesDiv.innerHTML += '<a class="nounder" style="font-size:11pt;">' + i + '</a>';
			}
			else {
				pagesDiv.innerHTML += '<a href="javascript:" onclick="paging(' + i + ');>' + i + '</a>';
			}
			pagesDiv.innerHTML += '&nbsp;';
		}

		if (total_pages > end) {
			pagesDiv.innerHTML += '....';
			pagesDiv.innerHTML += '<a href="javascript:" onclick="paging(' + total_pages + ');>' + total_pages + '</a>';
			pagesDiv.innerHTML += '&nbsp;';

		}

		pagesDiv.innerHTML += '&nbsp;';
		if (next_page) pagesDiv.innerHTML += '<a href="javascript:" onclick="paging(' + next_page + ');" style="font-size:10pt;">&rsaquo;</a>';
		else pagesDiv.innerHTML += '<a style="font-size:10pt;" class="nounder">&rsaquo;</a>';
		pagesDiv.innerHTML += '&nbsp;';
		if (next_group) pagesDiv.innerHTML += '<a href="javascript:" onclick="paging(' + next_group + ');" style="font-size:10pt;">&raquo;</a>';
		else pagesDiv.innerHTML += '<a style="font-size:10pt;" class="nounder">&raquo;</a>';
	},

	displayPrivate: function () {
		$('private_listings_display').innerHTML = '';
		var tmp = [];
		for (var i = 0; i < this.list.length; i++) {
			if (this.list[i].private == "1") {
				tmp.push(privateListingHTML(this.list[i]));
			};
		};
		$('private_listings_display').innerHTML = tmp.join("<br style='clear:both;' /><hr style=' margin:8px 0;' />");
		$('private_box').style.display = 'block';
		var out = function () {
			$('private_box').style.display = 'none';
		};
		$('private_box').out = function () {
			$('private_box').style.display = 'none';
		};
		$('private_box').onmouseout = function () {
			this.timer = setTimeout(this.out, 200);
		};
		$('private_box').onmouseover = function () {
			clearTimeout(this.timer);
		};
	},

	testDisplayPrivate: function () {
		var p = 0;
		for (var i = 0; i < this.list.length; i++) {
			if (this.list[i].private == "1") {
				p++;
			};
		};
		return p;
	},

	tempShow: function (id) {
		clearInterval(window.tempInt);
		clearTimeout(window.tempTime);
		window.tempInt = setInterval(
			new Function('window.mouseoverid = ' + id + ';'),
			100
		);
		window.tempTime = setTimeout(
			new Function('window.mouseoverid = null; clearInterval(window.tempInt);'),
			4500
		);

	},

	groupTimers: function (index) {
		clearInterval(window.groupInt);
		clearTimeout(window.groupTime);
		window.groupInt = setInterval(
			new Function('window.group_index = ' + index + ';'),
			100
		);
		window.groupTime = setTimeout(
			new Function('window.group_index = null; clearInterval(window.groupInt);'),
			4500
		);
	}


});








document.offset = 0;
document.page = 0;
document.perpage = 2;

function replaceAll(haystack, needle, text){
	while(haystack.indexOf(needle) > 0){
		haystack = haystack.replace(needle, text || '');
	};
	return haystack;
};
function privateListingHTML(data){
	var html = '<div>\
	<div style="width: 150px; height: 105px; float: left;">\
	<a href="/properties_details/{id}#{name}">\
	<img style="border: medium none ; float: left; width: 150px; height: 104px;" src="{imgsrc}"/>\
	<img style="border: medium none ; float: left; margin-top: -104px; width: 150px; height: 104px;" src="/images/overlays/{overlay}.png"/></a>\
	</div>\
	\
	<div style="float:right; padding:0 0 0 5px; width:160px;">	\
		<div class="map_list_title">{name}</div>\
		<span style="font-size:9px;"><em>{address}</em> {count}</span>\
		{description}\
		<br />\
		<a href="/properties_details/{id}#{name}" style="">Details</a>\
		<a onclick="contactBroker({id})" style="" href="javascript://">Contact Broker</a>\
	</div>\
</div>\
';
	
	
	var in_array = function(arry, t){
		for(var i in arry){
			if(arry[i] == t){
				return true;	
			};
		};
		return false;
	};
	var number_format = function(number, decimal, thou){
		
		var total = number.toString();
		
		if(total.indexOf(decimal) == -1){
			total = total + decimal + "00";	
		};
		if(total.substr(total.indexOf(decimal)).length < 3){
			total = total + "0";	
		};
		
		var decimal = total.substr(total.indexOf(decimal)).toString();
		while(parseInt(total.charAt(0)) <= 0){
			total = total.substr(1);
		};
		total = total.toString();
		var int = total.substr(0, total.indexOf(decimal));
		var tmp = int.split('');
		tmp = tmp.reverse();
		for(var i=0; i<Math.floor(tmp.length/3); i++){
			tmp.splice((i*4)+3, 0, thou);
		};
		tmp = tmp.reverse();
		tmp = tmp.join('');
		if(tmp.charAt(0) == thou){
			tmp = tmp.substr(1);
		};
		if(tmp.charAt(0) == thou){
			tmp = tmp.substr(1);
		};
		if(tmp.charAt(0) == thou){
			tmp = tmp.substr(1);
		};
		if(tmp.charAt(tmp.length-1) == thou){
			tmp = tmp.substr(0,tmp.length-1);
		};
		if(tmp.length==0){
			tmp = "0";	
		};
		
		return tmp;
	};
	
	var rep = {
		'events' :' onmouseover="window.mouseoverid = {id};" onmouseout="window.mouseoverid = null;"',
		'map_link' : '<a href="#map" onclick="window.tool.tempShow({id});" style="font-size:9px;">Show on map</a>',
		
		'1or2'        : data.class_,
		'id'          : data.id,
		'description' : data.description.substr(0, 200) + '&hellip;',
		
		'name'     : data.name,
		'count'    : data.count,
		'imgsrc'   : data.imgsrc,
		'address'  : data.address,
		'province'  : data.province,
		'country'  : data.country,
		'overlay'  : data.overlay,
		
		
		'transactionType' : data.transactiontype ? '<b>Type:</b> ' + data.transactiontype + "<br>" : '',
		'salePrice'       : data.saleprice       ? '<b>Price:</b> ' + data.saleprice + "<br>" : '',
		'leaseRate'       : data.leaserate       ? '<b>Lease:</b> ' + data.leaserate + "<br>" : '',
		'additionalRent'  : data.additionalrent  ? '<b>Rent:</b> ' + data.additionalrent + "<br>" : '',
		'subjectSize'     : data.subjectsize     ? '<b>Size:</b> ' + data.subjectsize + "<br>" : '',
		'buildingType'    : data.buildingtype    ? '<b>Building:</b> ' + data.buildingtype + "<br>" : '',
		'numberOfUnits'   : data.numberofunits   ? '<b>Units:</b> ' + data.numberofunits + "<br>" : ''
		
	};
	if(data.private == '1'){
		rep['events'] = '';
		rep['1or2'] = "3";	
		rep['map_link'] = '';
	};
	
	for(var i in rep){
		html = replaceAll(html, '{'+i+'}', rep[i]);	
	};
	
	return html;
};
function listingHTML(data){        
	var html = '<div class="map_listing{1or2}" id="listing_id_{id}"{events}>\
				<div style=\"width:902px;\">\
				<div style="width:150px;height:105px; float:left;">\
					<a href="/properties_details/{id}#{name}"><img src="{imgsrc}" style="float:left; width:150px; height:104px; border:none;" />\
					<img src="/images/overlays/{overlay}.png" style="float:left; margin-top:-104px; width:150px; height:104px; border:none;" /></a>\
				</div>\
				<div class="" style="float:left;">\
					<table cellpadding="0" cellspacing="0" style="margin-left:3px;">\
						<tr>\
							<td class="map_list_title" >\
								<div>{name}</div>\
								<span style="font-size:9px;"><em>{address} {province} {country}</em>\
								{count}</span>\
							</td>\
							<td rowspan="2">\
								<div style="float:right; padding:10px 0px 14px 10px; width:226px;font-size:9px;">\
									<div style="display:table-cell; font-weight:normal;  padding-right:10px; ">\
										{transactionType}\
										{salePrice}\
										{leaseRate}\
										{additionalRent}\
										{subjectSize}\
										{buildingType}\
										{numberOfUnits}\
									</div>\
								</div>\
							</td>\
							<td rowspan="2">\
								<a href="/properties_details/{id}#{name}" style="display:block;">\
									<img src="/images/button_view_details.png" style="margin-top:20px;" onMouseOver="this.src=\'/images/button_view_details_on.png\'" onMouseOut="this.src=\'/images/button_view_details.png\'" />\
								</a>\
								<a href="javascript://contact_broker:{id}"\
									style="display:block;"\
									onclick="window.open(\'/inquire.php?pid={id}\', \'\', \'scrollbars=1,statusbar=0,locationbar=0,0,0,0,width=960,height=600\');//contactBroker({id})">\
									<img src="/images/button_contact_broker.png" onMouseOver="this.src=\'/images/button_contact_broker_on.png\'" onMouseOut="this.src=\'/images/button_contact_broker.png\'" style="margin-top:10px;" />\
								</a>\
							</td>\
						</tr>\
						<tr>\
							<td style="width:385px;">\
								<div style="padding:4px 6px 2px 6px; font-size:9px;">\
									{description}\
									<br />\
									{map_link}\
								</div>\
							</td>\
						</tr>\
					</table>\
				</div>\
				<b style="clear:both;"></b>\
				</div>\
				<br style="clear:both;" />\
			</div>';
	var in_array = function(arry, t){
		for(var i in arry){
			if(arry[i] == t){
				return true;	
			};
		};
		return false;
	};
	var number_format = function(number, decimal, thou){
		
		var total = number.toString();
		
		if(total.indexOf(decimal) == -1){
			total = total + decimal + "00";	
		};
		if(total.substr(total.indexOf(decimal)).length < 3){
			total = total + "0";	
		};
		
		var decimal = total.substr(total.indexOf(decimal)).toString();
		while(parseInt(total.charAt(0)) <= 0){
			total = total.substr(1);
		};
		total = total.toString();
		var int = total.substr(0, total.indexOf(decimal));
		var tmp = int.split('');
		tmp = tmp.reverse();
		for(var i=0; i<Math.floor(tmp.length/3); i++){
			tmp.splice((i*4)+3, 0, thou);
		};
		tmp = tmp.reverse();
		tmp = tmp.join('');
		if(tmp.charAt(0) == thou){
			tmp = tmp.substr(1);
		};
		if(tmp.charAt(0) == thou){
			tmp = tmp.substr(1);
		};
		if(tmp.charAt(0) == thou){
			tmp = tmp.substr(1);
		};
		if(tmp.charAt(tmp.length-1) == thou){
			tmp = tmp.substr(0,tmp.length-1);
		};
		if(tmp.length==0){
			tmp = "0";	
		};
		
		return tmp;
	};
	
	var rep = {
		'events' :' onmouseover="window.mouseoverid = {id};" onmouseout="window.mouseoverid = null;"',
		'map_link' : '<a href="#map" onclick="window.tool.tempShow({id});" style="font-size:9px;">Show on map</a>',
		
		'1or2'        : data.class_,
		'id'          : data.id,
		'description' : data.description,
		
		'name'     : data.name,
		'count'    : data.count,
		'imgsrc'   : data.imgsrc,
		'address'  : data.address,
		'province'  : data.province,
		'country'  : data.country,
		'overlay'  : data.overlay,
		
		
		'transactionType' : data.transactiontype ? '<b>Type:</b> ' + data.transactiontype + "<br>" : '',
		'salePrice'       : data.saleprice       ? '<b>Price:</b> ' + data.saleprice + "<br>" : '',
		'leaseRate'       : data.leaserate       ? '<b>Lease:</b> ' + data.leaserate + "<br>" : '',
		'additionalRent'  : data.additionalrent  ? '<b>Rent:</b> ' + data.additionalrent + "<br>" : '',
		'subjectSize'     : data.subjectsize     ? '<b>Size:</b> ' + data.subjectsize + "<br>" : '',
		'buildingType'    : data.buildingtype    ? '<b>Building:</b> ' + data.buildingtype + "<br>" : '',
		'numberOfUnits'   : data.numberofunits   ? '<b>Units:</b> ' + data.numberofunits + "<br>" : ''
		
	};
	if(data.private == '1'){
		rep['events'] = '';
		rep['1or2'] = "3";	
		rep['map_link'] = '';
	};
	
	for(var i in rep){
		html = replaceAll(html, '{'+i+'}', rep[i]);	
	};
	return html;
};


