// JavaScript Document
var map = null;
var geocoder = null
var propmarkerlist = Array();
var shopmarkerlist = Array();
var foodmarkerlist = Array();
var doseemarkerlist = Array();
//initialise maps on load
var geocoder;
var map;

//home page
function initialize() {
	geocoder = new google.maps.Geocoder();
	var myOptions = {
		zoom: 1,
		mapTypeId: google.maps.MapTypeId.HYBRID
	}
	map = new google.maps.Map(document.getElementById("mapcanvas"),myOptions);
	//set opening map to zoom on italy
	address = "italy";
	
	geocoder.geocode( { address: address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK && results.length) {
			// You should always check that a result was returned, as it is
			// possible to return an empty results object.
			if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
				map.setCenter(results[0].geometry.location);
				xmlDataAllProp();
			}
			
		}
	});
	//slap in all properties
	
}
//advance search map

function str_replace(str, oldstr, newstr){
    return str.split(oldstr).join(newstr);
}


function initializeAdv (address, zoom) {
	geocoder = new google.maps.Geocoder();
	var myOptions = {
		zoom: zoom,
		mapTypeId: google.maps.MapTypeId.HYBRID
	}
	map = new google.maps.Map(document.getElementById("mapcanvas"),myOptions);
	geocoder.geocode( { address: address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK && results.length) {
			// You should always check that a result was returned, as it is
			// possible to return an empty results object.
			if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
				map.setCenter(results[0].geometry.location);
			}
		}
	});
}

//function to add a marker to the map
function addMarker(point, titleText, address,pid, type, mainpic, ownerid, owneridnum, giveReturn) {
	customIcons = Array();
	customIcons["property"] = gPath+"images/icons/map_icon_properties.png";
    customIcons["food place"] = gPath+"images/icons/map_icon_fooddrink.png";
	customIcons["shop"] = gPath+"images/icons/map_icon_shops.png";
    customIcons["do and see"] = gPath+"images/icons/map_icon_thingstodo.png";
	/**/
	iconURL = customIcons[type]
	//setup the type of marker
	var image = new google.maps.MarkerImage(iconURL,
		// This marker is 20 pixels wide by 32 pixels tall.
		new google.maps.Size(14, 14),
		// The origin for this image is 0,0.
		new google.maps.Point(0,0),
		// The anchor for this image is the base of the flagpole at 0,32.
		new google.maps.Point(7, 7)
	);
	var shadow = new google.maps.MarkerImage(gPath+'images/icons/map_icon_shad_22x14.png',
		// The shadow image is larger in the horizontal dimension
		// while the position and offset are the same as for the main image.
		new google.maps.Size(22, 14),
		new google.maps.Point(0,0),
		new google.maps.Point(7, 7)
	);
	// Shapes define the clickable region of the icon.

	var shape = {
		coord: [0,0,0,14,14,14,14,0],
		type: 'poly'
	};

	//titleText = decodeURIComponent(titleText);
	//get rid of html chars
	titleText = str_replace(titleText, '&amp;','&');
	titleText = str_replace(titleText, '&lt;','<');
	titleText = str_replace(titleText, '&gt;','>');
	titleText = str_replace(titleText, '&quot;','"');
	titleText = str_replace(titleText, '&#39;',"'");
 
	
	var marker = new google.maps.Marker({
		position: point,
		title: titleText,
		map: map,
		shadow: shadow,
        icon: image,
        shape: shape/**/
	});
	
	//setup the link url and the photopath
	
	if (type == "property") {
		pathURL = gPath+"property.php?id="+pid
		picpath = gPath+"members/"+owneridnum+"/"+pid+"/"
	} else {
		pathURL = gPath+"poi.php?id="+pid
		picpath = gPath+"members/"+owneridnum+"/poi/"+pid+"/"
	}
	if (mainpic == "") {
		picpath = gPath+"images/photo_filler_100x66.gif"
	}
	titleText = titleText.substr(0,20)
	 //'<div style="background:#ffcc00;width:200px;min-height:25px;overflow:hidden;">' +
		// '<div style="width:80px;height:100px;float:left;margin:2px 10px 0px 0px">' +
		contentString = 					'<img style="width:80px;height:53px;float:left;margin-right:3px;" src="'+picpath+mainpic+'" />' +
					//	'</div>' +
						'<div style="float:left;font-size:10px;width:95px;overflow:hidden;">' +
							'<b>'+titleText+'</b><br />'+address+'<br /><a href="'+pathURL+'">view details</a>' +
						'</div>' ;
					//	'<div style="clear:both"></div>' ;
					//'</div>'
	var infowindow = new google.maps.InfoWindow(
		{ //content: '<div style="width:80px;height:100px;float:left;margin:2px 10px 0px 0px"><img style="width:80px;height:53px;float:left;" src="'+picpath+mainpic+'" /></div><div style="float:left;font-size:10px;width:105px;overflow:visible;"><b>'+titleText+'</b><br />'+address+'<br /><a href="'+pathURL+'">view details</a></div><div style="clear:both"></div>',
		content: contentString,
		disableAutoPan:false
		}
	);
	google.maps.event.addListener(marker, 'click', function() {
    	infowindow.open(map,marker);
    	}
	);
	//add to list of markers
	if (type == "property") {
		propmarkerlist.push(marker);
	} else if (type == "shop") {
		shopmarkerlist.push(marker);
	} else if (type == "do and see") {
		doseemarkerlist.push(marker)
	} else if (type == "food place") {
		foodmarkerlist.push(marker)
	}
	
	if (giveReturn == 'return') {
		//put infowindow and marker in array and return
		markerWindow = Array()
		markerWindow.push(marker)
		markerWindow.push(infowindow)
		return markerWindow
	}
}

//function to populate all the properties on the map on first load
function xmlDataAllProp() {
	PAGExmlHttp=GetXmlHttpObject()
	Args = "&onlyprop=yes";
	if (PAGExmlHttp==null)  {
		  alert ("Your browser does not support AJAX!");
		  return;
	} 
	PAGExmlHttp.onreadystatechange=function () { 
		if (PAGExmlHttp.readyState==4) {
			//alert (PAGExmlHttp.responseText);
			var xml = PAGExmlHttp.responseXML; 
			var markers = xml.documentElement.getElementsByTagName("marker");
			
			for (var i = 0; i < markers.length; i++) {				
				var address = HtmlEncode(markers[i].getAttribute("address")); 
				var type = HtmlEncode(markers[i].getAttribute("type"));
				var title = HtmlEncode(markers[i].getAttribute("title"));
				var Lprice = HtmlEncode(markers[i].getAttribute("lowprice"));
				var pid = markers[i].getAttribute("id");
				var ownerid = HtmlEncode(markers[i].getAttribute("ownerid"));
				var owneridnum = HtmlEncode(markers[i].getAttribute("owneridnum"));
				var mainpic = HtmlEncode(markers[i].getAttribute("mainpic"));
				var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("long")));
				addMarker(point, title, address,pid,type, mainpic, ownerid, owneridnum)
	 
			} 	
		}
	}

	url=gPath+"returnXMLdata.php"+"?sid="+Math.random()+Args
	//alert("URL: "+url)
	PAGExmlHttp.open("GET",url,true);
	PAGExmlHttp.send(null);
}

//function to deal with the select country drop down
//needs to zoom to country
//needs to build a searcgh results list header
//needs to populate the map with only properties form that country
//needs to build the results list

function selectCountry(ad, zoom) {
	
	PAGExmlHttp=GetXmlHttpObject()
	//these vars are for get data
	countryArg = "&country="+encodeURIComponent(ad)
	if (PAGExmlHttp==null)  {
		  alert ("Your browser does not support AJAX!");
		  return;
	} 
	//se the centre and zoom
	if (ad == "United States of America" ) { //zoom out for USA
		zoom = 3;
	}
	if (ad == "Mexico" ) { //zoom out for USA
		zoom = 4;
	}
	if (ad == "Canada" ) { //zoom out for USA
		zoom = 3;
	}
	if (ad == "Australia") { //zoom out for Australia
		zoom = 3;
	}
	if (ad == "Switzerland") { //zoom out for Australia
		zoom = 6;
	}
	if (ad == "Austria") { //zoom out for Australia
		zoom = 6;
	}
	if (ad == "United Kingdom") {
		centreAd = "isle of man, united kingdom";	
	} else {
		centreAd =ad
	}
	if (ad == "null") {
		clearResults(); //clears search and resets session results
		return
	}
	//re-inti map -------------
	
	geocoder = new google.maps.Geocoder();
	var myOptions = {
		zoom: zoom,
		mapTypeId: google.maps.MapTypeId.HYBRID
	}
	map = new google.maps.Map(document.getElementById("mapcanvas"),myOptions);

	geocoder.geocode( { address: centreAd}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK && results.length) {
			// You should always check that a result was returned, as it is
			// possible to return an empty results object.
			if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
				map.setCenter(results[0].geometry.location);
				//map.setZoom(zoom);
				getSearchProp(ad);
			}
			
		}
	});
	//-------------------------
}

function getSearchProp(country) {
	
	//insert loader gif for display res list
	loadspace = document.getElementById('searchresults');
	loadspace.innerHTML = "";
	loadspace.innerHTML = "<div class=\"loadergifwrapper\" ><img src=\""+gPath+"images/ajax-loader.gif\" alt=\"loading...\"/></div>";
	//eof loader gif
	PAGExmlHttp=GetXmlHttpObject()
	
	countryArg = "&country="+encodeURIComponent(country)
	Args = countryArg + "&onlyprop=yes"; //country is passed in argument format
	if (PAGExmlHttp==null)  {
		  alert ("Your browser does not support AJAX!");
		  return;
	} 
	PAGExmlHttp.onreadystatechange=function () { 
		if (PAGExmlHttp.readyState==4) {
			//alert (PAGExmlHttp.responseText);
			var xml = PAGExmlHttp.responseXML; 
			var markers = xml.documentElement.getElementsByTagName("marker");
			//alert(PAGExmlHttp.responseText)
			//build results header
			resultsHeader(markers.length)
			
			//build array for list ids - then to shuffle for random
			arrayKeys = Array();
			//fill with integers upto maerker total
			for (n=0;n<markers.length;n++) {
				arrayKeys.push(n)
			}
			
			//shuffle arrayKeys 
			arrayKeys.sort(function() {return 0.5 - Math.random()})
			
			for (var n = 0; n < arrayKeys.length; n++) {
				i = arrayKeys[n]
				var address = HtmlEncode(markers[i].getAttribute("address")); 
				var type = HtmlEncode(markers[i].getAttribute("type"));
				var title = HtmlEncode(markers[i].getAttribute("title"));
				var Lprice = HtmlEncode(markers[i].getAttribute("lowprice"));
				var cIcon = HtmlEncode(markers[i].getAttribute("curicon"));
				var cText = HtmlEncode(markers[i].getAttribute("curtext"));
				var pid = markers[i].getAttribute("id");
				var ownerid = HtmlEncode(markers[i].getAttribute("ownerid"));
				var owneridnum = HtmlEncode(markers[i].getAttribute("owneridnum"));
				var mainpic = HtmlEncode(markers[i].getAttribute("mainpic"));
				var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("long")));
				M=addMarker(point, title, address,pid,type, mainpic, ownerid,owneridnum, 'return')
				searchResList(title,address,mainpic,Lprice,cIcon,cText, owneridnum, pid, point, M)
			}
			resultsList = loadspace.innerHTML //get the results html
			//store country in sessio list so it can erload results and map when page loads;
			storeRes("\"selectCountry('"+country+"', 5)\"")
			
			//add a button at the endof the res
			addCLearResBtn() 
		}
	}
	url=gPath+"returnXMLdata.php"+"?sid="+Math.random()+Args
	//alert("URL: "+url)
	PAGExmlHttp.open("GET",url,true);
	PAGExmlHttp.send(null);
}

function addCLearResBtn() {
	//add a button at the endof the res
	SR = document.getElementById('searchresults')
	b = document.createElement('button');
	b.setAttribute("type", "button");
	b.setAttribute("id", "clearresbutton");
	bTxt = document.createTextNode("Clear");
	b.appendChild(bTxt);
	b.onclick = function() {
		clearResults();
		resetCountrySel();
	}
	cont= document.createElement("div");
	cont.setAttribute("id","clearbutton_wrapper");
	cont.appendChild(b);
	SR.appendChild(cont);
	
}

function resetCountrySel() {
	cSel = document.getElementById('country');
	cAdvSel = document.getElementById('country_adv');
	//alert(cSel.options[1].value);
	//for (n=0;n<cSel.length; n++) {
	cSel.options[0].selected = true
	cAdvSel.options[0].selected = true	
}

function searchResList(title,address,mainpic,Lprice, cIcon, cText, owneridnum, pid, point, marker) {
	title = str_replace(title, '&amp;','&');
	title = str_replace(title, '&lt;','<');
	title = str_replace(title, '&gt;','>');
	title = str_replace(title, '&quot;','"');
	title = str_replace(title, '&#39;',"'");
	if (mainpic != "") {
		picPath = gPath+"members/"+owneridnum+"/"+pid+"/"+mainpic
	} else {
		picPath = gPath+"images/photo_filler_100x66.gif"
	}
	
	//now git the sr cont div
	SRC = document.getElementById("search_results_container")
	
	//create each list item ---------------------------------
	resWrap = document.createElement("div")
	resWrap.className = "result_wrapper"
	
	//add the wrapper
	RW = SRC.appendChild(resWrap)
	// create thumbnail in div wrapper
	thumbWrap = document.createElement("div")
	thumbWrap.className = "result_thumb"
	thumb = document.createElement("img")
	thumb.setAttribute("src", picPath);
	thumb.setAttribute("alt", "property thumbnail");
	thumbWrap.appendChild(thumb)
	//add to res wrapper RW
	RW.appendChild(thumbWrap)
	
	//create res info wrapper
	resInfoWrap = document.createElement("div")
	resInfoWrap.className = "result_info_wrapper"
	RIW = RW.appendChild(resInfoWrap)
	
	//make title
	resTitleWrap = document.createElement("div")
	resTitleWrap.className = "result_title"
	
	TW = RIW.appendChild(resTitleWrap);
	
	resLink = document.createElement("a")
	resLink.setAttribute("href", gPath+"property.php?id="+pid);
	tLen = title.length;
	if (tLen > 40) {
		sTitle = title.substring(0,40) + "..."
	} else {
		sTitle = title
	}
	linkText = document.createTextNode(sTitle);
	resLink.appendChild(linkText);
	//add link to RIW
	TW.appendChild(resLink);
	
	
	//now create price
	resInfo = document.createElement("div")
	resInfo.className = "result_info"
	
	lowprice = document.createTextNode("Min Price: "+cIcon+Lprice+" p/w ("+cText+")");
	resInfo.appendChild(lowprice);
	RIW.appendChild(resInfo);
	
	//now map link
	mapzw = document.createElement("div")
	mapzw.className = "map_zoom_wrapper"
	
	MZW = RIW.appendChild(mapzw)
	
	globe = document.createElement("img")
	globe.setAttribute("src", gPath+"images/icons/globe_18x18.png")
	globe.setAttribute("alt", "world icon")
	
	MZW.appendChild(globe)
	
	mapTextWrap = document.createElement("div")
	mapTextWrap.className = "map_text"
	mtext = document.createTextNode("Map");
	mapTextWrap.appendChild(mtext)
	MT = MZW.appendChild(mapTextWrap)
	

	
	MZW.onmouseover = function () {
		mapIconState(this, 'on')
	}
	MZW.onmouseout = function () {
		mapIconState(this, 'off')
	}
	MZW.onclick = function () {
		var icon = marker[0]
		var infowindow = marker[1];
		//infowindow.open(map,marker);
		map.setZoom(14)
		map.setCenter(point)
		infowindow.open(map,icon)
		//alert(map)
	}
}


function resultsHeader(numRes) {
	SR = document.getElementById('searchresults')
	SR.innerHTML = "";
	//create h2 and wrapper
	Title = document.createElement("h2")
	Title.setAttribute ("id","search_results_header");
	TitleText=document.createTextNode("Search Results ("+numRes+")")
	Title.appendChild(TitleText)
	SRcont = document.createElement("div")
	SRcont.setAttribute("id", "search_results_container");
	SR.appendChild(Title)
	SR.appendChild(SRcont);
	
	//set the height of the search container 
	cont = document.getElementById("search_results_container");
	
	if (numRes < 6 ) {
		cont.style.height = 62*numRes+"px"
	} 	
}



//clear reults 
function clearResults() {
	PAGExmlHttp=GetXmlHttpObject()

	if (PAGExmlHttp==null)  {
		  alert ("Your browser does not support AJAX!");
		  return;
	} 
	
	PAGExmlHttp.onreadystatechange=function () { 
		if (PAGExmlHttp.readyState==4) {
			document.getElementById('searchresults').innerHTML = "";
			initialize();
		}
	}

	url = "clear_results.php?sid="+Math.random()
	PAGExmlHttp.open("POST",url,true);
	PAGExmlHttp.send(null);	
	//PAGExmlHttp.send(post)
}


//store the search results
function storeRes(resString) {
		
	PAGExmlHttp=GetXmlHttpObject()

	if (PAGExmlHttp==null)  {
		  alert ("Your browser does not support AJAX!");
		  return;
	} 
	
	PAGExmlHttp.onreadystatechange=function () { 
		if (PAGExmlHttp.readyState==4) {
			//alert(PAGExmlHttp.responseText);
		}
	}
	
	post = "results="+resString

	url = "store_results.php"
	PAGExmlHttp.open("POST",url,true);
	//PAGExmlHttp.send(null);	
	PAGExmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
	PAGExmlHttp.send(post)
}

function mapIconState(Id, onoff) {
	//alert(Id.firstChild.nextSibling.nextSibling.nextSibling.className)

	if (navigator.appName != "Microsoft Internet Explorer") {
		mapIcon = Id.firstChild
		mapLink = Id.firstChild.nextSibling

	} else {
		mapIcon = Id.firstChild
		mapLink = Id.firstChild.nextSibling
	}
	
	if (onoff == "on") {
		mapIcon.setAttribute("src", gPath+'images/icons/globe_18x18_on.png');
		mapLink.style.color = "#000000";
	} else {
		mapIcon.setAttribute("src", gPath+'images/icons/globe_18x18.png');
		mapLink.style.color = "#666666";
	}
		
}

//========================================================
//property and poi pages
//========================================================

function initialize2(lat,lng,country, page) { 
	geocoder = new google.maps.Geocoder();
	latlng = new google.maps.LatLng(lat, lng);
	var myOptions = {
		zoom: 12,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map(document.getElementById("poimapwrapper"),myOptions);
	//add markers from country
	getXMLdataPropPage(country)
	//setMapCentre(lat,lng)
	//fetchAttractions('poifeatures');
	/*if (page == "property") {
		google.maps.event.addListener(map, 'tilesloaded', function() {
			//fetchAttractions('poifeatures');
			}
		);
	}*/
	
	//alert('X:'+map.getBounds())
	//alert(country)
	
	
}
function getXMLdataPropPage(country) {
	PAGExmlHttp=GetXmlHttpObject()
	c = encodeURIComponent(country)
	Args = "&onlyprop=no&country="+c;
	if (PAGExmlHttp==null)  {
		  alert ("Your browser does not support AJAX!");
		  return;
	} 
	PAGExmlHttp.onreadystatechange=function () { 
		if (PAGExmlHttp.readyState==4) {
			//alert (PAGExmlHttp.responseText);
			var xml = PAGExmlHttp.responseXML; 
			
			var markers = xml.documentElement.getElementsByTagName("marker");
			
			for (var i = 0; i < markers.length; i++) {				
				var address = HtmlEncode(markers[i].getAttribute("address")); 
				var type = HtmlEncode(markers[i].getAttribute("type"));
				var title = HtmlEncode(markers[i].getAttribute("title"));
				var Lprice = HtmlEncode(markers[i].getAttribute("lowprice"));
				var pid = markers[i].getAttribute("id");
				var ownerid = HtmlEncode(markers[i].getAttribute("ownerid"));
				var owneridnum = HtmlEncode(markers[i].getAttribute("owneridnum"));
				var mainpic = HtmlEncode(markers[i].getAttribute("mainpic"));
				var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("long")));
				var m = addMarker(point, title, address,pid,type, mainpic, ownerid, owneridnum, 'return')
	 
			}
			
			//fetchAttractions('poifeatures');
			
		}
	}
	url=gPath+"returnXMLdata.php"+"?sid="+Math.random()+Args
	//alert("URL: "+url)
	PAGExmlHttp.open("GET",url,true);
	PAGExmlHttp.send(null);
}

function fetchAttractions(loadDiv) {
	
	loadspace = document.getElementById(loadDiv)
	if (loadspace.innerHTML != "") {
		return	
	}
	//url = "http://www.getawayearth.com/"
	url = gPath + "fetchattractions.php";
	
	Bounds = map.getBounds();
	north = Bounds.getNorthEast().lat();
	south = Bounds.getSouthWest().lat();
	east = Bounds.getNorthEast().lng();
	west = Bounds.getSouthWest().lng();
	
	var post = "&north="+north+"&south="+south+"&west="+west+"&east="+east;
	
	
	loadspace.innerHTML = "";
//	loadspace.innerHTML = "<div class=\"loadergifwrapper\" ><img src=\"images/ajax-loader.gif\" alt=\"loading...\"/></div>";
	loadspace.innerHTML = "<img src=\""+gPath+"images/ajax-loader.gif\" alt=\"Loading\"/> &nbsp;Searching for nearby attractions...</option>";
	PAGExmlHttp2=GetXmlHttpObject()
	
	if (PAGExmlHttp2==null)  {
		  alert ("Your browser does not support AJAX!");
		  return;
	} 
	PAGExmlHttp2.onreadystatechange=function () { 
		if (PAGExmlHttp2.readyState==4) {
				loadspace.innerHTML = PAGExmlHttp2.responseText;
				
		}
	}
	url=url+"?sid="+Math.random()+post;
	PAGExmlHttp2.open("GET",url,true);
	PAGExmlHttp2.send(null);/**/
}

//function to centre map
function setMapCentre(lat,lng) {
	//alert(lat+", "+lng)
	latlng = new google.maps.LatLng(lat, lng);
	map.setZoom(14);
	map.setZoom(13);
	map.setCenter(latlng);
}