var baseIcon;
var icon;
var map;
var places = [];
var maxmarkers = 100;
var allowedBounds = new GBounds(-10,49.5,2.6,59);
var updateListResult = true;
var allowSearch = true;
var timeout = true;

function createPlace( id, lat, lng, address, address2, town, county, postcode, rooms, rent, type, image ) {
	var place=new Object();
	var image; 
	place.id = id;
	place.lat = lat;
	place.lng = lng;
	place.address = address;
	place.address2 = address2;
	place.town = town;
	place.county = county;
	place.rooms = rooms;
	place.rent = rent;
	place.type = type;
	place.houseimage = image;
	
	switch (type) {
		case 100 :
			place.html = "<h4 class='markeruni'>" + place.address + "<\/h4>";
			place.image = 'furniture/images/markers/uni.png';
			break;
		
		default :
			
			switch (type) {
				case 0 :
					place.image = 'furniture/images/markers/reserved.gif';
					place.typestring = 'Reserved'
					break;			
				case 1 :
					place.image = 'furniture/images/markers/reservedsubject.gif';
					place.typestring = 'Reserved subject to contract'
					break;
				case 2 :
					place.image = 'furniture/images/markers/house.png';
					place.typestring = 'Available'
					break;
			}
						
			place.html = "<div class=\"infowindow\">" +
						"<span class=\"infoimage\"><a href=\"view.aspx?id=" + place.id + "\"><img class=\"infoimage\" src=\"" + place.houseimage + "\" width=\"100\" height=\"75\" border=\"0\" \/><\/a><\/span>" +
						"<span class=\"infoleft\"><h6 class='markerhouse'>" + place.address + ", " + place.town + "<\/h6>" +
						"Rent: &pound;" + place.rent + " <br \/> " +
						"Rooms: " + place.rooms + "<br />" +
						"<a href=\"view.aspx?id=" + place.id + "\">View Property Details<\/a><br /><\/span>" +
						"\</div>";

			break;
		
	}
	places.push(place);
}
     
function createMap() {
		
	if (GBrowserIsCompatible()) {
		/* -- Setup base instance of our icon */
		baseIcon = new GIcon();
	    baseIcon.shadow = "/furniture/images/markers/shadow.png";
		baseIcon.iconSize = new GSize(16,16);
		baseIcon.shadowSize = new GSize(0, 0);
		baseIcon.iconAnchor = new GPoint(5, 5);
		baseIcon.infoWindowAnchor = new GPoint(10, 10);
		baseIcon.infoShadowAnchor = new GPoint(10, 10);
		
		icon  = new GIcon(baseIcon);
		icon.image = "/furniture/images/markers/house.png";
		
		icon  = new GIcon(baseIcon);
		icon.image = "/furniture/images/markers/house.png";
		
		/* -- Setup new G-Unit Map */
		map = new GMap2(document.getElementById("map"));
				
   	    /* -- Centre the map on something interesting */
	    setupMapSpecifics();

	    previousBounds = map.getBounds();
        previousZoom = map.getZoom();

		/* -- Add a couple of event listeners for when we drag the map about etc */
		GEvent.addListener(map, "moveend", function () {moveUpdate()});
		GEvent.addListener(map, "zoom", function () {zoomUpdate()});
		GEvent.addListener(map, "click", function(overlay, point) {
			if (overlay.openInfoWindowHtml) {
        		timeout = false;
                setTimeout("resetTimeout()",1000);			
				overlay.openInfoWindowHtml(overlay.html);
			}
		}); 
		
		/* -- Grab the markers for the initial page load */
		updateStatus('');

		if (update() == true ){
			document.getElementById("map").style.display = 'block';
		} else {
			document.getElementById("map").style.display = 'none';
			updateStatus('Sorry, the map is unable to load.');
		}
	}
}

function resetTimeout(){
    timeout = true;
}

function zoomUpdate() {

	var _bound = map.getBounds();
    var _zoom = map.getZoom();
    if (previousZoom) {
        if (previousZoom = _zoom) {
            return false;
        } else {
            previousZoom = _zoom;
            update();
            return true;
        }
    }
}

function moveUpdate() {
	var _bound = map.getBounds();
    if (previousBounds) { 
        var boundYDiff = Math.abs((previousBounds.minY-_bound.minY) / (_bound.maxY-_bound.minY)); 
        var boundXDiff = Math.abs((previousBounds.minX-_bound.minX) / (_bound.maxX-_bound.minX)); 

        if (boundYDiff < 0.025 && boundXDiff < 0.025) { 
            return false;
         } else {
            previousBounds = _bound;
            update();

            return true;
         }
     }
    
}


function update(panToMarkers) {
    if (timeout){
	updateStatus('Please wait - Loading...');
	var c1, c2, c3;
	c1 = panToMarkers;
    var _bound = map.getBounds();
	var university, town, rent, rooms;
        var southWest = _bound.getSouthWest();
        var northEast = _bound.getNorthEast();
          var minX, maxX, minY, maxY


	    minX = southWest.lng();
	    maxX = northEast.lng();
	    minY = southWest.lat();
	    maxY = northEast.lat();
	    
	    	
	if (allowSearch == true){
		university = document.getElementById("university").options[document.getElementById("university").selectedIndex].value;
		town = document.getElementById("town").options[document.getElementById("town").selectedIndex].value;
		rent = document.getElementById("rent").options[document.getElementById("rent").selectedIndex].value;
		rooms = document.getElementById("rooms").options[document.getElementById("rooms").selectedIndex].value;	
	} else {
		university = "";
		town = "";
		rent = "";
		rooms = "";
	}

	/* -- Client invoked .NET postback which calls function to get data and executes the javascript to update the map */
	RS.Execute("search.aspx", "GetProperties", university, town, rent, rooms, minX, maxX, minY, maxY, 0, popuplatePlaces, popuplateError, c1, c2, c3);
	return true;
	}
}

function searchMap() {
	update(true);
}

function popuplatePlaces(responseXML, c1, c2, c3) {
	/* c1 = panToMarkers */
	var xmlDoc = GXml.parse(responseXML)
	
	/* -- Read properties */
	var markers = xmlDoc.documentElement.getElementsByTagName("property");
	
	places = [];
	updateStatus( markers.length + ' Properties');
	
	for (var i = 0; i < markers.length; i++) {
		var id = markers[i].getAttribute("id");
		var lat = parseFloat(markers[i].getAttribute("lat"));
		var lng = parseFloat(markers[i].getAttribute("lon"));
		var address = markers[i].getAttribute("address");
		var address2 = markers[i].getAttribute("address2");
		var town = markers[i].getAttribute("town");
		var county = markers[i].getAttribute("county");
		var postcode = markers[i].getAttribute("postcode");
		var rooms = markers[i].getAttribute("rooms");
		var rent = markers[i].getAttribute("rent");
		var type = parseFloat(markers[i].getAttribute("type"));
		var image = markers[i].getAttribute("image");
		createPlace( id, lat, lng, address, address2, town, county, postcode, rooms, rent, type, image);
	}
	var universities = xmlDoc.documentElement.getElementsByTagName("university");
	
	for (var i = 0; i < universities.length; i++) {
		var lat = parseFloat(universities[i].getAttribute("lat"));
		var lng = parseFloat(universities[i].getAttribute("lon"));
		var name = universities[i].getAttribute("name");
		
		createPlace( 0, lat, lng, name, '', '', '', '', '', '', 100 );
	}
	updateMarkers();
	updateHTML();
}
   
function popuplateError(){
	updateStatus('Last update unsucessful.');
	alert('Yeah hi, \n sorry there has been a problem whilst updating the properties. Try again in a few moments.');
}

function updateMarkers() {
	var n=0;


    map.clearOverlays();
    for (var i=0; i<maxmarkers; i++) {
        if (i<places.length){
            var place = places[i];
            var point = new GLatLng(place.lat, place.lng);
            var icon = new GIcon(baseIcon);
            
            icon.image = place.image;
            switch (place.type) {
                case "property" :
                    icon.iconSize = new GSize(16, 16);
	                break;
                case "poi" :
                    icon.iconSize = new GSize(17, 22);
	                break;
            }

            var marker = new GMarker(point, icon);

            marker.html = place.html;


            map.addOverlay(marker);
		}
	}




}

function updateHTML() {
	if (updateListResult == true) {
	document.getElementById("listresult").innerHTML = '';
	var placeHTML = '';
	var placeCount = 0;
//	for (var i=0; i<places.length && placeCount <= 10 ; i++) {
	for (var i=0; i<places.length; i++) {
		var place = places[i];
		if (place.type < 10 ) {
			placeHTML += "<div class=\"indent\"><div class=\"resultleft\">" +
						"<span class=\"resulttown\">" + place.address + ", " + place.town + "<\/span>" +
						"<span class=\"resultrooms\">" + place.rooms + " Bedrooms <\/span>" +
						"<span class=\"resultrent\">Rent &pound;" + place.rent + " pp pw <\/span>" +
						"<span class=\"resultbutton\"><a class=\"button_viewdetails\" href=\"view.aspx?id=" + place.id + "\">View Details<\/a> " +
						"<a class=\"button_type" + place.type + "\" href=\"availablity.aspx\" target=\"_blank\">Availablity<\/a><\/span>" +
						"<\/div><div class=\"resultright\">" +
						"<span class=\"resultimage\"><a href=\"view.aspx?id=" + place.id + "\"><img class=\"resultimage\" src=\"" + place.houseimage + "\" width=\"100\" height=\"75\" border=\"0\" \/><\/a><\/span>" +
						"</div></div>" +
						"<div style=\"clear: both;\" class=\"spacerstyle1\">&nbsp;<\/div>";
			placeCount++;
		}
	}
	
	
	document.getElementById("listresult").innerHTML = placeHTML;
	if (placeCount != 0 ){
		document.getElementById("titleresult").innerHTML = "<h5 class=\"indent\">Your&nbsp;Search&nbsp;Returned&nbsp;" + placeCount + "&nbsp;Results<\/h5>";
	} else {
		document.getElementById("titleresult").innerHTML = "<h5 class=\"indent\">No&nbsp;Search&nbsp;Results<\/h5>";
	}
	}
}

function updateLocation(){
	var university = document.getElementById("university").options[document.getElementById("university").selectedIndex].value;
	var town = document.getElementById("town").options[document.getElementById("town").selectedIndex].value;
	if (university != "") {
		getCordsAndPan("university", university)
	} else if (town != "") {
		getCordsAndPan("town", town)
	}
}
function getCordsAndPan(type, id){
	var c1, c2, c3;
	RS.Execute("search.aspx", "GetCords", type, id, panToPlace, panToPlaceError, c1, c2, c3);
}

function panToPlace(responseXML, c1, c2, c3) {
	var xmlDoc = GXml.parse(responseXML);
	var place = xmlDoc.documentElement.getElementsByTagName("place");
	zoomToPoint(place.item(0).getAttribute("lon"),place.item(0).getAttribute("lat"), 7);
}

function panToPlaceError(){
	updateStatus('Unable to find location.');
	alert('Yeah hi, \n sorry there has been a problem whilst trying to find the location specified. Try again in a few moments.');
}

function updateStatus(toWhat){
	document.getElementById("status").innerHTML = toWhat;
}	

function zoomTo(markerid){
	var markerid = '1';
	var marker = map.overlays[places[markerid].markerid]

	map.centerAndZoom(new GPoint(marker.point.x, marker.point.y), 4);
	marker.openInfoWindowHtml(marker.html);
}

function zoomToPoint(x,y, zoom) {
	map.centerAndZoom(new GPoint(x, y), zoom); 
}

function checkZoom() {
	if (map.getZoomLevel() > 12) { map.zoomTo(12); }
}

function checkBounds() {
	var A = allowedBounds;
	var B = map.getBoundsLatLng();
	var C = map.getCenterLatLng();
	var X = C.x;
	var Y = C.y;
	if (B.minX < A.minX) {X += A.minX - B.minX;}
	if (B.maxX > A.maxX) {X += A.maxX - B.maxX;}
	if (B.minY < A.minY) {Y += A.minY - B.minY;}
	if (B.maxY > A.maxY) {Y += A.maxY - B.maxY;}
	if ((X != C.x) || (Y != C.y)) {
		map.recenterOrPanToLatLng(new GPoint(X,Y));
	}
}
