var map;
var mapDiv;
var minimap;
var mgr;
var markers;
var proptypes;
var proptype;
var propArray = [];
var regionArray = [];
var currentId = 0;

var currentMarker = null;
var iwc = "";

function loadMap(longitude, latitude, zoomLevel, pt, hid) {
	var point = new GLatLng(latitude, longitude);
	proptypes = pt;
	currentId = hid;
	
	if (GBrowserIsCompatible()) {
	    map = new GMap2(mapDiv = document.getElementById("map"));
	    map.setCenter(point, zoomLevel);
	    map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		
		GEvent.addListener(map, "moveend", mapMoved);
		GEvent.addListener(map, "zoomend", zoomLevelChanged);
		
		GEvent.addListener(map, "dragstart", function () {
			var iw = this.getInfoWindow();
			iw.hide();
			currentMarker = null;
		});
		
		
		for(i=0; i < proptypes.length; i++) {
			GDownloadUrl("/getMapXML.php?proptype=" + proptypes[i], getProperties);	
		}
	}
}

function zoomLevelChanged(oldLevel, newLevel) {
	setMarkers(proptype);
}

function mapMoved() {
	setMarkers(proptype);
}


function loadOrientationMap(longitude, latitude, zoomLevel, proptype) {
	var point = new GLatLng(latitude, longitude);
  
	if (GBrowserIsCompatible()) {
		var mapdiv = document.getElementById("minimapdiv");
		//GetValues(mapdiv);
	   minimap = new GMap2(mapdiv);
	   minimap.setCenter(point, zoomLevel);
		minimap.disableDragging();
		baseIcon = getIcon(proptype);
		
		var opts = new Object();
    	opts.icon = baseIcon;
		opts.clickable = false;
		var marker = new GMarker(point, opts);
    	minimap.addOverlay(marker);	
    	
    	window.setTimeout("setCopyrightInfo()", 500);    	

	}
}

function setCopyrightInfo() {
	var CopyrightDiv = document.getElementById("minimapdiv").firstChild.nextSibling.nextSibling.firstChild.nextSibling;
	document.getElementById('c_mapdata').appendChild(CopyrightDiv.firstChild);	
}

function getIcon(proptype) {
	if(proptype == "pousada") {
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.image = "resources/images/PousadaMarker.png";
		baseIcon.shadow = "";
		baseIcon.iconSize = new GSize(20, 26);
		baseIcon.shadowSize = new GSize(37, 29);
		baseIcon.iconAnchor = new GPoint(10,10);
	}
	else if(proptype == "chateaux") {
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.image = "resources/images/ChateauxMarker.png";
		baseIcon.shadow = "";
		baseIcon.iconSize = new GSize(20, 21);
		baseIcon.shadowSize = new GSize(26, 23);
		baseIcon.iconAnchor = new GPoint(10,10);
	}
	else if(proptype == "parador") {
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.image = "resources/images/ParadorMarker.png";
		baseIcon.shadow = "";
		baseIcon.iconSize = new GSize(14, 20);
		baseIcon.shadowSize = new GSize(28, 13);
		baseIcon.iconAnchor = new GPoint(10,10);
	}	
	else {
		baseIcon = new GIcon(G_DEFAULT_ICON);
	}
	return baseIcon;
}

function getSelectedIcon(proptype) {
	if(proptype == "pousada") {
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.image = "resources/images/PousadaMarkerSelected.png";
		baseIcon.shadow = "";
		baseIcon.iconSize = new GSize(28, 34);
		baseIcon.shadowSize = new GSize(37, 29);
		baseIcon.iconAnchor = new GPoint(10,10);
	}
	else if(proptype == "chateaux") {
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.image = "resources/images/ChateauxMarkerSelected.png";
		baseIcon.shadow = "";
		baseIcon.iconSize = new GSize(28, 29);
		baseIcon.shadowSize = new GSize(26, 23);
		baseIcon.iconAnchor = new GPoint(10,10);
	}
	else if(proptype == "parador") {
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.image = "resources/images/ParadorMarkerSelected.png";
		baseIcon.shadow = "";
		baseIcon.iconSize = new GSize(22, 28);
		baseIcon.shadowSize = new GSize(28, 13);
		baseIcon.iconAnchor = new GPoint(10,10);
	}	
	else {
		baseIcon = new GIcon(G_DEFAULT_ICON);
	}
	return baseIcon;
}

function getRegionIcon(regionId) {
	// Hack ****************************
	// IE for some reason suddenly needs an image width
	var regionWidth = new Array(null, 100, 59, 149, 170, 170, 149, 51, 69, 170, null, 117, 74, 170, 67, 110, 136, null, 154, 77, 71, 143);
	
	baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.image = "resources/images/RegionName" + regionId + ".png";
	baseIcon.iconSize = new GSize(regionWidth[regionId], 14);
//	baseIcon.iconSize = "";
	baseIcon.shadow = "";
	baseIcon.iconAnchor = new GPoint(10,10);
	return baseIcon;
}

function getProperties(datastring, responseCode) {
	if(!propArray.length) {
		var xml = GXml.parse(datastring);
		proptype = xml.documentElement.nodeName;
		var a = xml.documentElement.getElementsByTagName("property");
		for(i=0; i < a.length; i++) {
			var e = a[i];
			var o = new Object();
			for(j=0; j < e.childNodes.length; j++) {
				if(e.childNodes[j].firstChild && e.childNodes[j].tagName)
					eval("o." + e.childNodes[j].tagName + " = e.childNodes[j].firstChild.nodeValue;");
			}
			propArray[i] = o;
		}
	}

	setMarkers(proptype);
}

function getRegions(datastring, responseCode) {
	if(!regionArray.length) {
		var xml = GXml.parse(datastring);
		regionArray = xml.documentElement.getElementsByTagName("property");
	}

	setMarkers("regions");
}

function setMarkers(proptype) {
	var num = propArray.length;

	if(proptype != "regions" && num > 100 && map.getZoom() < 7) {
		GDownloadUrl("regions.xml", getRegions);
	}
	else if(proptype == "regions") {
		
		var batch = [];
		
		
		map.clearOverlays();
				
		for(var i = 0; i < regionArray.length; i++) {
			
			var point = new GLatLng(regionArray[i].getElementsByTagName("latitude")[0].firstChild.nodeValue,regionArray[i].getElementsByTagName("longitude")[0].firstChild.nodeValue);
			
			var opts = new Object();
		  	opts.proptype = "regions";
		  	opts.title = regionArray[i].getElementsByTagName("name")[0].firstChild.nodeValue;
	    	opts.id = regionArray[i].getElementsByTagName("id")[0].firstChild.nodeValue;
		  	
		  	baseIcon = getRegionIcon(opts.id);
		  	opts.icon = baseIcon;
		  	
		  	var marker = createMarker(point, opts);
	    	map.addOverlay(marker);
		}
	}
	else {
		
		var bounds = map.getBounds();
		map.clearOverlays();
		var batch = [];
		var baseIcon = getIcon(proptype);
		
		for(var i = 0; i < num; i++) {
			
			if(propArray[i].latitude <= 180 && propArray[i].latitude >= -180
				&& propArray[i].longitude < 180 && propArray[i].longitude >= -180) {
				var point = new GLatLng(propArray[i].latitude, propArray[i].longitude);
			
				if(bounds.contains(point)) {
			    	var opts = new Object();
			    	if(propArray[i].id == currentId) opts.icon = getSelectedIcon(proptype);
			    	else opts.icon = baseIcon;

			    	opts.id = propArray[i].id;
			    	if(propArray[i].mapdistance) opts.distance = propArray[i].mapdistance;
			    	if(propArray[i].stars) opts.stars = propArray[i].stars;
			    	if(propArray[i].style) opts.style = propArray[i].style;
			    	if(propArray[i].thumb) opts.thumb = propArray[i].thumb;
			    	
			    	if(propArray[i].location)
			    		opts.location = propArray[i].location;
			    	else opts.location = "";
					opts.proptype = proptype;
			    	if(opts.proptype == 'pousada') opts.title = propArray[i].location;
			    	else opts.title = propArray[i].name;					
			    		
			    	var marker = createMarker(point, opts);
		
			    	map.addOverlay(marker);
			    }
			    
			}
		}
		
		if(currentMarker) currentMarker.openInfoWindowTabsHtml(iwc);

	}
}	
	
function createMarker(point, opts) {
	var marker = new GMarker(point, opts);
	if(opts.proptype == "regions") {
		GEvent.addListener(marker, "click", function() {
			
			var coords = new GLatLng(marker.getPoint().y, marker.getPoint().x);
			map.zoomIn();
			map.panTo(coords);
		});
	}		
	else  {
		GEvent.addListener(marker, "click", function() {

			var iw = '';
			if(opts.proptype == 'parador') {
				var tab1 = "Parador";
				iw += "<b>Parador de " + opts.title + "</b><br />";
			}
			else if(opts.proptype == 'pousada') {
				var tab1 = "Pousada";
				iw += "<b>Pousada de " + opts.location +"<br />";
			}
			else {
				var tab1 = "Châteaux";
				iw += "<b>" + opts.title + "</b><br />"+ opts.location +"<br />";
			}
			
			if(opts.proptype == 'parador')
				iw += "<img src='/resources/images/symbols/" + opts.stars + "starsSmall.gif' /><br />";
			else if(opts.proptype == 'chateaux') iw += "<img src='/resources/images/symbols/chateaux_collection_bubble_" + opts.style + ".gif' /><br />";
			else if(opts.proptype == 'pousada')
				iw += "<b>Style: " + opts.style + "</b><br />";
				
			if(opts.thumb) iw += "<img width='150' height='113' src='property_images/" + opts.proptype + "/thumb/" + opts.thumb + ".jpg' style='margin: 5px;' /><br />";
			
			
			var iw2 = "";
			if(opts.distance) iw2 += "<b>Distances:</b><br />"+ opts.distance.replace(/\n/g, "<br />") + "<br />";
			
			iw += viewDetails = "<div style='display:block;'><a href='index.php?module=custom_property-view&property_id=" + opts.id + "'>View details</a><br /></div>";
			
			iw2 += viewDetails;

			
			var infoTabs = [
  				new GInfoWindowTab(tab1, iw)
  				
			];

			if(opts.distance) infoTabs.push(new GInfoWindowTab("Distances", iw2));
			
			marker.openInfoWindowTabsHtml(infoTabs);
			iwc = infoTabs;
			
		});
		
		GEvent.addListener(marker, "infowindowopen", function() {
			currentMarker = marker;
		});
		
	}
	return marker;
}

function focusRegion(region) {
	var coords;
	if(region == "portugal") {
		coords = new GLatLng(39.482845,-6.410522);
		map.setZoom(6);
	}
	else if(region == "azores") {
		coords = new GLatLng(38.745515,-27.125244);
		map.setZoom(8);
	}
	else if(region == "france") {
		coords = new GLatLng(47.323931,2.834473);
		map.setZoom(5);
	}
	else if(region == "paris") {
		coords = new GLatLng(48.861553,2.340775);
		map.setZoom(12);
	}
	else if(region == "spain") {
		coords = new GLatLng(40.313043,-3.581543);
		map.setZoom(6);
	}
	else if(region == "canaries") {
		coords = new GLatLng(28.376902,-15.5896);
		map.setZoom(7);
	}

	map.panTo(coords);
}


function validate(formname) {
   var why = "";
   if (formname.name.value == "") why += "- Please insert your name\n";
   emailFilter=/^.+@.+\..{2,3}$/;
   if (!(emailFilter.test(formname.email.value)) && (formname.email.value != "")){
	   why += "- Please use a valid email address\n";
   }
   keytelFilter=/@keytel.co.uk/;
   if (keytelFilter.test(formname.email.value)) why += "- Please use your own email address\n";
   if (formname.address.value == "") why += "- Please insert your address\n";

   if (formname.howdidyouhear.value == '') why += "- Please select how you heard about us"; 

   if (why != "") {

	   alert("KEYTEL INFORMATION PACK CHECKER\n_________________________________________\n\nThere is a problem with your Information Pack request.\nPlease ensure that you have filled in the following:\n_________________________________________\n\n"+why);
	   return false;

	} else {

	//formname.submit();
		return true;
	}

}

function GetValues(obj)
{
var res = '';
res += 'Objekt: '+obj+'\n\n';
for(temp in obj)
{
res += temp +': '+obj[temp]+'\n';
}
alert(res);
}


// get position of this element
function getAbsX(elt) { return (elt.x) ? elt.x : getAbsPos(elt,"Left"); }
function getAbsY(elt) { return (elt.y) ? elt.y : getAbsPos(elt,"Top"); }
function getAbsPos(elt,which) {
	iPos = 0;
	while (elt != null) {
		iPos += elt["offset" + which];
		elt = elt.offsetParent;
	}
	return iPos;
}