var noCoordMessage = 'No good coordinates found to show on map.';
var layerid = 1;
var featuredCounter = 0;
var maxNrOfLoops = 11;
var destinationZoomLevel = 4;
var poiZoomLevel = 15;
var timePan = 8000;
var hideMapPopup = false;
var hideMapTimeoutId = 0;
var globalMapwidth = 896;
var globalMapheight = 250;

var poiPins = new Array(new Array(), new Array(), new Array(), new Array(), new Array(), new Array());

function isSmallMap() {
	if (globalMapwidth < 200 && globalMapheight < 200) {
		return true;
	}
	return false;
}

function togglePoisOnMap(categoryType, all) {
	if (categoryType == null && all) {
		// show all pois
		var categorytypes = new Array;
		for (var i = 0; i < poiPins.length; i++ ){
			var img = document.getElementById('poisq'+parseInt(i+1));
			var spl = img.src.split('.');
			if(img.src.indexOf('on') > 1) {
				categorytypes.push(parseInt(i+1));
			}
		}
		buildPoisOnMap(categorytypes);
		return;
	}
	var img = document.getElementById('poisq'+categoryType);
	var spl = img.src.split('.');
	if(img.src.indexOf('on') > 1) {
		buildPoisOnMap([categoryType]);
	} else {
		removePoisFromMap(categoryType);		
	}	
}

function buildPoisOnMap(categoryTypes) {
try { 
	// go and get the pois and show them on the map
	var topleft = map.PixelToLatLong(0,0);
	var center = map.GetCenter();
	var bottomright = new VELatLong(center.Latitude + (center.Latitude - topleft.Latitude), center.Longitude + (center.Longitude - topleft.Longitude));
	var typesArg = '';
	for (var i = 0; i < categoryTypes.length; i++ ){
		typesArg += '&categoryTypeIds[]='+categoryTypes[i];
	}	
	if (typesArg != '') {
	//alert('/call/snippet/destinations.php?go=poisincat'+typesArg+'&top='+topleft.Latitude+'&left='+topleft.Longitude+'&bottom='+bottomright.Latitude+'&right='+bottomright.Longitude);
		//Connect.setArgument("poi");
		var cObj = Connect.asyncRequest('GET', '/call/snippet/destinations.php?go=poisincat'+typesArg+'&top='+topleft.Latitude+'&left='+topleft.Longitude+'&bottom='+bottomright.Latitude+'&right='+bottomright.Longitude, doNavigateMap, null);
	}
} catch (e) {
	//alert(e.message);
}
}

function removePoisFromMap(categoryType, all) {
try {
	if (categoryType == null && all) {
		// remove all pois
		var categorytypes = new Array;
		for (var i = 0; i < poiPins.length; i++ ){
			categoryType = i+1;
			while (poiPins[categoryType-1].length > 0) {
				map.DeletePushpin(poiPins[categoryType-1][0]);
				poiPins[categoryType-1].splice(0, 1);
			}
		}
		return true;
	}
	var l = poiPins[categoryType-1].length;
	while (poiPins[categoryType-1].length > 0) {
		map.DeletePushpin(poiPins[categoryType-1][0]);
		poiPins[categoryType-1].splice(0, 1);
	}
} catch (e) {
	//alert(e.message);
}
}

function DoPoisOnMap() {
	show("poidiv");
	hide("mapitemlist");
	//check all and show if necessary
//	for (var i = 0; i < poiPins.length; i++ ){
	togglePoisOnMap(null, true);
//	}
//	setTimeout(function() {document.getElementById("poidiv").style.display="none";} , 5000);
}


function navigateMap() {
	document.getElementById('mappopupdiv').style.display = "none";
	try { 
		var zoomlevel = map.GetZoomLevel();
		if (zoomlevel < 12) {
			// go and get the destinations and show them on the map
			KillPoisOnMap();
			var topleft = map.PixelToLatLong(0,0);
			var center = map.GetCenter();
			var bottomright = new VELatLong(center.Latitude + (center.Latitude - topleft.Latitude), center.Longitude + (center.Longitude - topleft.Longitude));
			Connect.setArgument("destination");
			var cObj = Connect.asyncRequest('GET', '/call/snippet/destinations.php?go=search&key=&ret=xml&top='+topleft.Latitude+'&left='+topleft.Longitude+'&bottom='+bottomright.Latitude+'&right='+bottomright.Longitude, doNavigateMap, null);
		} else {
			// show pois
			DoPoisOnMap();
		}
	} catch (e) {
		//alert(e.message);
	}
}

function doNavigateMap(o, succes) {
	// never draw a square around here
//	map.DetachEvent("onchangeview", DrawSquare);
	try { 
		var type = o.argument;
		var conts = o.responseXML.getElementsByTagName("continent");
		locs = new Array;
		titles = new Array;
		descs = new Array;
		stars = new Array;
		var webnames = new Array;
		var types = new Array;
		for (var i=0;i<conts.length;i++) {
			for (var j=0;j<conts[i].childNodes.length;j++) {
				if (conts[i].childNodes[j].tagName == "country") {
					for (var k=0;k<conts[i].childNodes[j].childNodes.length;k++) {
						if (conts[i].childNodes[j].childNodes[k].tagName == "destination") {
							if (type == 'destination') {
								var title = conts[i].childNodes[j].childNodes[k].getAttribute("name");
								var desc = getNodeValue(conts[i].childNodes[j].childNodes[k],'description');
					           	locs.push(createCenterLatLong(conts[i].childNodes[j].childNodes[k].getAttribute('lat1'), conts[i].childNodes[j].childNodes[k].getAttribute('long1'), conts[i].childNodes[j].childNodes[k].getAttribute('lat2'), conts[i].childNodes[j].childNodes[k].getAttribute('long2')));
								titles.push(title);
								descs.push(desc);
								webnames.push(conts[i].childNodes[j].childNodes[k].getAttribute("webname"));
							} 
							for (var l=0;l<conts[i].childNodes[j].childNodes[k].childNodes.length;l++) {							
								if (conts[i].childNodes[j].childNodes[k].childNodes[l].tagName == "poi") {								
									type = 'poi';
									if (type == 'poi') {										
										var title = getNodeValue(conts[i].childNodes[j].childNodes[k].childNodes[l],'name')
										var desc = getNodeValue(conts[i].childNodes[j].childNodes[k].childNodes[l],'description');
										stars.push(conts[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('avgRating'));
							           	locs.push(new VELatLong(conts[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('lat'),conts[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('long')));
										titles.push(title);
										webnames.push(conts[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('webname'));
										var typer = conts[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('categoryTypeId');
										types.push(typer);
										descs.push(desc);
							        }
								}								
							}						
						}
					}
				}
			}
		}
		if (type == 'destination') {
			map.DeleteAllPushpins();	
		}
		for (var i = 0; i < locs.length; i++) {
			if (titles.length > i && descs.length > i) {
				if (type == 'poi') {
					//alert(types[i] + poiPins[types[i]-1]);
					if (!poiPins[types[i]-1].inArray(types[i]+'-'+i)) {
						AddPoiPin(types[i]+'-'+i, locs[i], titles[i], descs[i], types[i], webnames[i], stars[i]);
						//alert(types[i] + poiPins[types[i]-1]);
						poiPins[types[i]-1].push(types[i]+'-'+i);
					}
				} else {					
					AddPin(i, locs[i], titles[i], descs[i], webnames[i]); 
				}
			}
		}
	} catch (e) {
		if (showCatchAlert) alert('(A)' + e.message);
	}
}

function timeoutDoShowFeaturedDestinations() {
	//setTimeout("doShowFeaturedDestinations();", 400);
}

function doShowFeaturedDestinations() {
	document.getElementById('mapitems').innerHTML = 'Loading data...';
	Connect.setArgument("destination");
	var cObj = Connect.asyncRequest('GET', '/call/snippet/destinations.php?go=frontdestination&ret=xml&cache=1&size=gallerythumb', responseFeaturedDestinations, null);
}

var featuredLocs;
var featuredTitles;
var featuredDescs;
var featuredWebnames;
var featuredTypes;

function responseFeaturedDestinations(o, success){
//alert(o.responseText);
map.DetachEvent("onchangeview", navigateMap);
try { 
	var type = o.argument;
	var conts = o.responseXML.getElementsByTagName("destination");
	featuredLocs = new Array;
	featuredTitles = new Array;
	featuredDescs = new Array;
	featuredWebnames = new Array;
	featuredTypes = new Array;
	for (var i=0;i<conts.length;i++) {
//		for (var j=0;j<conts[i].childNodes.length;j++) {
//			if (conts[i].childNodes[j].tagName == "country") {
//				for (var k=0;k<conts[i].childNodes[j].childNodes.length;k++) {
//					if (conts[i].childNodes[j].childNodes[k].tagName == "destination") {
//						if (type == 'destination') {
							var title = conts[i].getAttribute("name");
							var desc = "<img align='right' src=\""+conts[i].getAttribute("photo")+"\" width='100'>";
							desc = desc + getNodeValue(conts[i],'description');
				           	featuredLocs.push(createCenterLatLong(conts[i].getAttribute('lat1'), conts[i].getAttribute('long1'), conts[i].getAttribute('lat2'), conts[i].getAttribute('long2')));
							featuredTitles.push(title);
							featuredDescs.push(desc);
							featuredWebnames.push(conts[i].getAttribute("webname"));
//						} 
//					}
//				}
//			}
//		}
	}
	map.DeleteAllPushpins();	
	for (var i = 0; i < featuredLocs.length; i++) {
		AddPin(i, featuredLocs[i], featuredTitles[i], featuredDescs[i], featuredWebnames[i]);		
	}	
// build mapitemlist for front
	var mil = document.getElementById('mapitems');
	var mapitemswidth = 0;
	if (mil) {	
		var inner = '<ul>';
		for (var i = 0; i < featuredLocs.length; i++) {
				mapitemswidth += (featuredTitles[i].length * 12);
				inner = inner + '<li><a id="map_'+i+'_'+featuredWebnames[i]+'" href="#" onclick="selectMapItem(\'map_'+i+'_'+featuredWebnames[i]+'\', this); return false;" onfocus="blur()">' + featuredTitles[i] + '</a></li>';
				if (i != (featuredLocs.length - 1)) {
					inner = inner + '<li class="sep">&nbsp;</li>';
				}
		}	
		inner += '</ul>';
	}		
	if (mapitemswidth > document.getElementById('mapitemlist').style.width) {
		document.getElementById('scrolllist').onmouseover = startScrolling;
	}
	mil.innerHTML = inner;	
	mil.style.width = mapitemswidth + "px";
	if (featuredLocs.length > 0) {
		playOrPause();
		map.SetZoomLevel(destinationZoomLevel);
		map.PanToLatLong(featuredLocs[0]);
		//manShowPushPin();
		setTimeout("panFront()", 100);
	}
	map.AttachEvent("onclick", goOnClick);
} catch (e) {
	//alert('(B) ' + e.message);
}
}

function goOnClick() {
	nrOfLoops = maxNrOfLoops;
	map.DetachEvent("onchangeview", manShowPushpin);
	map.AttachEvent("onchangeview", navigateMap);
}

var nrOfLoops = 0;
var featuredCounter = 0;
var stopPan = false;
var panFrontTimeoutIder = 0;
function manShowPushpin() {
try {
	if (nrOfLoops < maxNrOfLoops) {
		var looper2 = featuredCounter;
		var center = map.GetCenter();
		var geo2 = Microsoft.Web.Geometry;
		var ppobj = geo2.Functions.getElementPosition(document.getElementById(looper2 + '_' + map.GUID));
		var left = map.GetLeft();
		var top = map.GetTop();
		var right = left + 896;
		var bottom = top + 250;
		if (ppobj.x > right || ppobj.x < left || ppobj.y > bottom || ppobj.y < top) {
			setTimeout("manShowPushpin()", 100);
			return;
		}
		selectMapItem('map_'+looper2+'_'+featuredWebnames[looper2]);
		manShowDestPushpinDetail(looper2, featuredTitles[looper2], featuredDescs[looper2], featuredWebnames[looper2], featuredLocs[looper2], true);
//		VEPushpin.Show(map.GUID+'', looper2 + '', 1, 1, escape(featuredTitles[looper2]), escape(featuredDescs[looper2]), 'pinTitleStyle','pinDetailStyle');
//		VEPushpin.Show(map.GUID+"", featuredCounter + "",  featuredLocs[featuredCounter].Latitude, featuredLocs[featuredCounter].Longitude, escape(featuredTitles[featuredCounter]), escape(featuredDescs[featuredCounter]), 'pinTitleStyle','pinDetailStyle');
//		VEPushpin.Show(map.GUID+"", featuredCounter + "",  ''+10, ''+10, escape(featuredTitles[featuredCounter]), escape(featuredDescs[featuredCounter]), 'pinTitleStyle','pinDetailStyle');
		map.DetachEvent("onchangeview", manShowPushpin);
		if (!stopPan) {
			if (featuredCounter < (featuredLocs.length - 1)) {
				featuredCounter = parseInt(featuredCounter) + 1;
				panFrontTimeoutIder = setTimeout("panFront()",timePan);
//				alert('1');
			} else {
				nrOfLoops = nrOfLoops + 1;
				featuredCounter = 0;
				panFrontTimeoutIder = setTimeout("panFront()",timePan);
//				alert('2');
			}
		}
	} else {
		//map.AttachEvent("onchangeview", navigateMap);
	}
} catch (e) {
	//alert(e.message);
}	
}

function panFront() {
try {
//alert(nrOfLoops + ' --- ' + maxNrOfLoops + ' --- ' + featuredCounter + ' --- ' + featuredLocs.length);
	if (nrOfLoops < maxNrOfLoops && (featuredCounter < featuredLocs.length)) {
		map.AttachEvent("onchangeview", manShowPushpin);
		VEPushpin.Hide(true);
		map.PanToLatLong(featuredLocs[featuredCounter]);
	} else {
		//map.AttachEvent("onchangeview", navigateMap);
	}
} catch (e) {
	alert(featuredCounter + ' ' +e.message);
}
}


function DrawSquare(points, width, color, zoom) {
	try {
		if (points.length < 3) {
			// Make a square if you only have 2 points
			var newpoints = new Array();
			newpoints.push(points[0]);
			newpoints.push(new VELatLong(points[0].Latitude, points[1].Longitude));
			newpoints.push(points[1]);
			newpoints.push(new VELatLong(points[1].Latitude, points[0].Longitude));
			newpoints.push(points[0]);
		} else {
			newpoints = points;
		}
		poly = new VEPolyline('1', newpoints);
		poly.SetWidth(width);            
		poly.SetColor(color);            
		map.AddPolyline(poly);         
		
		if (zoom) {
			map.SetZoomLevel(15);
			map.SetMapView(newpoints);
		}
	} catch (e) {
		//alert(e.message);
	}
}


function createNewLatLong(obj,key) {
	// there are problems with virtual earth and 0 / 90 / -90 / 180 / -180 points, this is a hardcoded fix to not have JS exceptions
	var lat = fixCoord(obj.getAttribute('lat'+key));
	var long = fixCoord(obj.getAttribute('long'+key));
    return new VELatLong(lat,long);
}

function fixCoord(coord) {
	if (coord == 0) coord = 0.1;
	if (coord == -90) coord = 0.1;
	if (coord == 90) coord = 0.1;
	if (coord == -180) coord = 0.1;
	if (coord == 180) coord = 0.1;
	return coord;
}

function createCenterLatLong(lat1, long1, lat2, long2) {
    return new VELatLong( fixCoord((parseFloat(lat1)+parseFloat(lat2))/2) , fixCoord((parseFloat(long1)+parseFloat(long2))/2) );
}

var gradesPerPixel = new Array(0,0.703125145,0.351562572,0.175781286,0.087890643,0.043945322,0.021972616,0.010986308,0.005493199,0.002746599,0.001373255,0.000686672,0.000343336,0.000171668,0.0000857891,0.0000429395,0.0000214697,0.00001069,0.00000538989,0.00000269495);
      
function retrieveZoomlevel(leftupper, rightlower, mapwidth, mapheight) {
	if (mapwidth == undefined || mapwidth == null) {
		mapwidth = globalMapwidth;
	} 
	if (mapheight == undefined || mapheight == null) {
		mapheight = globalMapheight;
	} 
    //calculate the differences in world coordinates
    var latDiff = rightlower.Latitude - leftupper.Latitude;
    var longDiff = rightlower.Longitude - leftupper.Longitude;
    //compare them with the actual height and width of the map
    var latFactor = latDiff / mapheight / Math.abs(Math.cos((parseFloat(leftupper.Latitude)+parseFloat(latDiff)/2)*Math.PI/180));    
    var longFactor = longDiff / mapwidth;
    //find the biggest factor
    var factor = 0;
    if (latFactor > longFactor){
        factor = latFactor;
    } else {
        factor = longFactor;
    }
    //zoom until biggest factor fits
    var zoomresult = 1;
    while (gradesPerPixel[zoomresult+1]>factor && zoomresult < 13){
        zoomresult++;
    }
//    alert(zoomresult);
    return zoomresult;
}

function DoAlert(text) {
	var d = document.getElementById("alertdiv")
	if (d) {
		d.style.display="inline";
		d.innerHTML = text;
	//	d.style.margin = (center.x - map.GetLeft()) + "px 0px 0px " + (center.y - map.GetTop()) + "px";
		setTimeout(function() {document.getElementById("alertdiv").style.display="none";} , 5000);
	}
}

function AddPoiPin(pinID, loc, name, desc, type, webname, stars) {
try {
	var inner = buildBeautifulPopup(name, desc, webname, 'poi', stars);
	setVEPushpin();
	var img = '';
	switch(type){
		case '1': img = 'lightblue.gif';
		        break;
		case '2': img = 'darkblue.gif';
		        break;
		case '3': img = 'green.gif';
		        break;
		case '4': img = 'purple.gif';
		       break;
		case '5': img = 'red.gif';
		        break;
		case '6': img = 'yellow.gif';
		        break;
		default: img = 'yellow.gif';
		         break;
	}
	var pin = new VEPushpin(pinID, loc, '/img/map/flags/'+img, '', inner, 'iconStyle', 'pinTitleStyle','pinDetailStyle');	
	map.AddPushpin(pin);	

} catch (e) {
	if (showCatchAlert) alert(e.message);
}
}   

function AddPin(pinID, loc, name, desc, webname) {
	try {
		var inner = buildBeautifulPopup(name, desc, webname, 'destination');
		setVEPushpin();
		var pin = new VEPushpin( pinID, loc, '/img/map/pushpin1.gif', name, inner, 'iconStyle', 'pinTitleStyle','pinDetailStyle');
		map.AddPushpin(pin);	
	} catch (e) {
		alert('(D1) ' + e.message);
	}
}   


function AddQuickPin(pinID, loc, name, desc, webname, id) {
	try {
		var inner = buildQuickPopup(name, desc, webname, id);	
		setVEPushpin();
		var pin = new VEPushpin( pinID, loc, '/img/map/pushpin1.gif', name, inner, 'iconStyle', 'pinTitleStyle','pinDetailStyle');		
		map.AddPushpin(pin);	

	} catch (e) {
		//alert('(D2) ' + e.message);
	}
}   

function AddIframePin(pinID, loc, name, desc, webname) {
	try {
		var inner = buildIframePopup(name, desc, webname);
		setVEPushpin();
		var pin = new VEPushpin( pinID, loc, '/img/map/pushpin1.gif', '', inner, 'iconStyle', 'pinTitleStyle','pinDetailStyle');
		map.AddPushpin(pin);
	} catch (e) {
		//alert('(C) ' + e.message);
	}
}   

function setVEPushpin() {
	VEPushpin.ShowDetailOnMouseOver = false;
    VEPushpin.OnMouseOverCallback = function(x, y, title, details) {
        clearTimeout(hideMapTimeoutId);
        showBeautifulLesliePopup(x,y,'',unescape(details), false);
    }		
    VEPushpin.Hide=function(Cu) {
		hideMapTimeoutId = setTimeout("hideMapPopupFunction()" , 3000);
    }
    var d = document.getElementById('mappopupdiv');
	if (d) {
		d.onmouseover = function() { hideMapPopup = false; }
	    d.onmouseout = function() { hideMapPopup = true; }		
	}
}

function buildQuickPopup2(name, desc, webname, id) {
	var inner = '';
	inner += '<div class="content"><h2>'+ name + '</h2><p>';
	if (id != null) {
		inner += '<a href="#" onClick="add(\''+id+'\', \''+name+'\', true, 1); return false;"><img src="/img/map/infobox/beenhere.gif" height="17" width="66" border="0" alt="been here" title="add this to your quicktrayle" /></a><br />';
		inner += '<a href="#" onClick="add(\''+id+'\', \''+name+'\', true, 3); return false;"><img src="/img/map/infobox/wanttogohere.gif" height="17" width="92" border="0" alt="want to go" title="want to go" /></a></p></div>';
	}	
	return inner;
}


function buildIframePopup(name, desc, webname, id) {
	var inner = '';
	inner += '<div class="content" style="width: 100px;"><h2>'+ name + '</h2><p>';
	if (webname != '') {
		inner += '<a href="http://www.trayle.com/destinations/destination/'+webname+'" target="_blank"><img src="/img/map/infobox/moreinfo.gif" height="17" width="65" border="0" alt="more info" title="click to find more info" /></a>';
	}	
	return inner;
}


function buildBeautifulPopup(name, desc, webname, type, stars, reload) {
	var desc2 = desc.replace(/<img[^>]*>/i, '');
	var matches = desc.match(/src="([^"]*)"/i);
	if (matches != null && matches.length > 1) {
		var photo = matches[1].replace(/\.\.\//, '');
		photo = photo.replace(/\/400\//, '/210/');
		photo = photo.replace(/\/800\//, '/210/');
	} else {
		var photo = "";
	}
	var link = false;
	if (reload != null) {
		link = reload;
	}
	var addDots = false;
	if (desc2.trim().length > 250) addDots = true;
	desc2 = desc2.trim().substring(0,250);
	if (addDots) desc2 = desc2 + '...';		
	desc2 = unescape(desc2);
	var inner = '';
	inner += '<div class="content"><h2>'+ name + '</h2><p>' + desc2 + '</p>';
	if (stars != null && parseInt(stars) > 0) {
		inner += '<p>' + buildStarsReturn((parseInt(stars)*2)) + '</p>';
	} 
	inner += '</div>';
	if (photo != '') {
		inner += '<div class="photo">';
		inner += '<div class="image" style="background-image: url('+photo+'); background-repeat: no-repeat; background-position: center center;"><img src="/img/map/infobox/imgoverlay.gif" width="176" height="132px" border="0" alt="" /></div>';
		inner += '</div>';
	} 
	inner += '<div class="infoactions">';
	if (webname != '') {
		if (type == 'poi') {			
			inner += '<a href="';
			if (iframemap) inner += 'http://www.trayle.com/destinations/poi/'+webname+'" target="_blank">';
			else if (link) inner += '/destinations/poi/'+webname+'">';
			else inner += '#" onClick="buildPoi([\'' + webname + '\'], null);return false;">';
			inner += '<img src="/img/map/infobox/moreinfo.gif" height="17" width="65" border="0" alt="more info" title="click to get more info" /></a>&nbsp;';

		} else {			
			inner += '<a href="';
			if (iframemap) inner += 'http://www.trayle.com/destinations/destination/'+webname+'" target="_blank">';
			else if (link) inner += '/destinations/destination/'+webname+'">';
			else inner += '#" onClick="buildDestination([\'' + webname + '\'], null);return false;">';
			inner += '<img src="/img/map/infobox/moreinfo.gif" height="17" width="65" border="0" alt="more info" title="click to get more info" /></a>&nbsp;';		
			if (iframemap) {
				inner += '<a href="http://www.trayle.com/quickmap" target="_blank"><img src="/img/map/infobox/beenhere.gif" height="17" width="66" border="0" alt="been here" title="add this to your quicktrayle" /></a>&nbsp;';
				inner += '<a href="http://www.trayle.com/quickmap" target="_blank"><img src="/img/map/infobox/wanttogohere.gif" height="17" width="92" border="0" alt="want to go" title="want to go" /></a>&nbsp;';
			} else {			
				inner += '<a href="" onClick="addToQuickTrayle(\'' + webname + '\', 1);return false;"><img src="/img/map/infobox/beenhere.gif" height="17" width="66" border="0" alt="been here" title="add this to your quicktrayle" /></a>&nbsp;';
				inner += '<a href="" onClick="addToQuickTrayle(\'' + webname + '\', 3);return false;"><img src="/img/map/infobox/wanttogohere.gif" height="17" width="92" border="0" alt="want to go" title="want to go" /></a>&nbsp;';
			}
		}
	}
	inner += '</div>';
	//alert(iframemap + inner);
	return inner;
}

//manual is if the show is manual, the offset is different
var beautyTimeout = null;
function showBeautifulLesliePopup(x,y, title, text, manual) {
	if (isSmallMap()){
		return;
	}
	var d = document.getElementById("mappopupdiv");
	if (d) {		
		d.style.display="inline";
		d.innerHTML = text;
		if (manual) {
			x = x + map.GetLeft() + 20;
			y = y + 20;
		} else if (iframemap) {
			x = x + map.GetLeft() + 20;
			y = y - 20;			
		} else {
			x = x + 20;
			y = y - map.GetTop() + 20;
		}
		// check the width of the browser to decide where to put the element
		var dims = getClientDimensions();
		var elwidth = parseInt(d.currentStyle.width);
		var elheight = parseInt(d.currentStyle.height);
		if (dims != null && (x + elwidth) >= dims.width) {
			// to wide!
			x = x - 50 - (elwidth);
		}		
		if (elheight < 70) {
			y = y + 30;
		}
		d.style.margin = y  + "px 0px 0px " + x + "px";
		if (!manual) {
//			if (beautyTimeout != null) clearTimeout(beautyTimeout);
//			beautyTimeout = setTimeout("document.getElementById('mappopupdiv').style.display=\"none\";" , 4500);
		}
	}
}

function manShowDestPushpinDetail(pinID, title, desc, webname, loc, onclicklink) {
	var inner = buildBeautifulPopup(title, desc, webname, null, 0, true);
	var pixel = map.LatLongToPixel(loc);
	showBeautifulLesliePopup(pixel.x,pixel.y,'',unescape(inner), true);
	return;
}

function manShowPoiPushpinDetail(pinID, title, desc, webname, loc, onclicklink, stars) {
	var inner = buildBeautifulPopup(title, desc, webname, 'poi', stars, true);
	var pixel = map.LatLongToPixel(loc);
	showBeautifulLesliePopup(pixel.x,pixel.y,'',unescape(inner), true);
	return;
}

function DrawPoly(id,points,width,color)
         {
            poly = new VEPolyline(id,points);
            poly.SetWidth(width);
            poly.SetColor(color);
            map.AddPolyline(poly);
         }

// latlong - if given, panned to this latlong
// locs - if latlong not given, calc center of locs and pan
var newzoomlevelbypan = 0;
var globalSetCenter = null;
function PanMap(x,y,latlong, locs, mapwidth, mapheight) {
        if (x!=null & y!=null) {
           map.Pan(x,y);
        } else if (latlong!=null) {
           map.PanToLatLong(latlong);
        }  else if (locs!=null)  {
		try { 
			var min_lat = 91;
			var min_long = 181;
			var max_lat = -91;
			var max_long = -181;
			var temp_lat;
			var temp_long;
			for (var i = 0; i< locs.length; i++) {
				temp_lat = fixCoord(locs[i].Latitude);
				temp_long = fixCoord(locs[i].Longitude);
				if (temp_lat != 0.1 && temp_long != 0.1) {
					if (min_lat > temp_lat) min_lat = temp_lat;
					if (min_long > temp_long) min_long = temp_long;
					if (max_lat < temp_lat) max_lat = temp_lat;
					if (max_long < temp_long) max_long = temp_long;
				}
			}
			if (min_lat != 91 && min_long != 181 && max_lat != -91 && max_long != -181) {			
				var newlatlong = new VELatLong(parseFloat((parseFloat(min_lat)+parseFloat(max_lat))/2), parseFloat((parseFloat(min_long)+parseFloat(max_long))/2));
				var oldzoomlevel = map.GetZoomLevel();
				var newzoomlevel = retrieveZoomlevel(new VELatLong(min_lat, min_long), new VELatLong(max_lat, max_long), mapwidth, mapheight);
//				alert(mapwidth + '  ' + mapheight + '  ' + min_lat + '  ' + min_long + '  ' + max_lat + '  ' + max_long + '  ' + oldzoomlevel +  '  ' + newzoomlevel);
				globalSetCenter = null;
				if (min_lat == max_lat && min_long == max_long) {
					// only one point actually found
					globalSetCenter = new VELatLong(min_lat, min_long);
				}
				if (oldzoomlevel != newzoomlevel) {
					map.AttachEvent("onendcontinuouspan", onEndPanZoomLevel);					
					newzoomlevelbypan = newzoomlevel;
					map.PanToLatLong(newlatlong);
					//.SetCenterAndZoom(newlatlong, newzoomlevel);
				} else {
					map.PanToLatLong(newlatlong);
				}
			} else {
				//DoAlert(noCoordMessage);
				//map.ShowMessage(noCoordMessage);
			}
		}catch(e) {
			//alert("Error(9)" + e.message);
        }     
     }
}

function onEndPanZoomLevel() {
	if (globalSetCenter != null) {
		map.SetCenterAndZoom(globalSetCenter, newzoomlevelbypan);
	} else {	
		map.SetZoomLevel(newzoomlevelbypan);
	}
	map.DetachEvent("onendcontinuouspan", onEndPanZoomLevel);	
}

var _defaultLocation = "go:home";
var _homeData = "";
var squarelocs = new Array;

function displayLocation(go, args, data) {
	alert('displayloc');
	if(go == "home") {
		buildHome(args, data);
	}else if(go == "continent") {
		buildContinent(args, data);	
	}else if(go == "country") {
		buildCountry(args, data);
	}else if(go == "destination") {
		buildDestination(args, data);
	}	
}

function destinationSearch(searchKey, searchSpot, searchActivity, searchCountry) {
	map.DetachEvent("onchangeview", navigateMap);
	hide("browsedestinations");
	showLoadingContent('main');	
	var cArg = "main:search:"+searchKey+":"+searchSpot+":"+searchActivity+":"+searchCountry; 
	Connect.setArgument(cArg);
	var call = '/call/snippet/destinations.php?go=search&name='+searchKey+'&spot='+searchSpot+'&act='+searchActivity+'&country='+searchCountry;
//	alert(call);
	var cObj = Connect.asyncRequest('GET', call, showContent, null);
	buildMap(cArg);	
}

function buildHome(args, data) {
	hide("browsedestinations");
	if(_homeData == "") {
		_homeData = document.getElementById("dynamiccontent").innerHTML;
	}
	setDynamicContent(_homeData);
}

function buildContinent(args, data) {
	hide("browsedestinations");
	showLoadingContent('main');
	if(args.length > 1) {
		//document.title = document.title + " " + args[1];
	}
	if(data == null) {
		var cArg = "main:continent:"+args[0]
		Connect.setArgument(cArg);
		var cObj = Connect.asyncRequest('GET', '/call/snippet/destinations.php?go=continent&name='+args[0], showContent, null);
		buildMap(cArg);
	}else{
		setDynamicContent(data);
	}
}

function buildCountry(args, data) {
	hide("browsedestinations");
	showLoadingContent('main');
	if(data == null) {
		var cArg = "main:country:"+args[0];
		Connect.setArgument(cArg);
		var cObj = Connect.asyncRequest('GET', '/call/snippet/destinations.php?go=country&name='+args[0], showContent, null);
		buildMap(cArg);
	}else{
		setDynamicContent(data);
	}
}

function buildDestination(args, data) {
	map.AttachEvent("onchangeview", navigateMap);
	hide("browsedestinations");
	showLoadingContent('main');
	//return false;
	if(args.length > 3) {
		//document.title = document.title + " " + args[3] + " &gt; " + args[2] + " &gt; " + args[1];
	}
	if(data == null) {
		var cArg = "main:destination:"+args[0];
		Connect.setArgument(cArg);
		var cObj = Connect.asyncRequest('GET', '/call/snippet/destinations.php?go=destination&name='+args[0], showContent, null);
		buildMap(cArg);
	}else{
		setDynamicContent(data);
	}
}

function buildDestinationCat(args, data) {
//	map.AttachEvent("onchangeview", navigateMap);
	hide("browsedestinations");
	showLoadingContent('poicategories');
	if(data == null) {
		var cArg = "main:destination:"+args[0];
		Connect.setArgument(cArg);
		var cObj = Connect.asyncRequest('GET', '/call/snippet/destinations.php?go=destination&name='+args[0]+'&categoryType='+args[1]+'&poiCategoryId='+args[2], showContent, null);
		buildMap(cArg);
	}else{
		setDynamicContent(data);
	}
}

function buildPoi(args, data) {
//	map.AttachEvent("onchangeview", navigateMap);
	hide("browsedestinations");
	showLoadingContent('mid');
	if(data == null) {
		var cArg = "main:poi:"+args[0];
		Connect.setArgument(cArg);
		var cObj = Connect.asyncRequest('GET', '/call/snippet/destinations.php?go=poi&name='+args[0], showContent, null);
		buildMap(cArg);
	}else{
		setDynamicContent(data);
	}
}


function showContent(o, success) {
try {
	if(success) {
		var d = document.getElementById(o.getArgument(0)+'content');		
		if (d) {			
			d.innerHTML = o.responseText;
			dhtmlHistory.add(o.argument, document.getElementById(o.getArgument(0)+'content').innerHTML);
			var pt = document.getElementById('pageTitle');
			if (pt) setPageTitle(pt.innerHTML);
		}
	}
} catch (e) {
	if (showCatchAlert) alert(e.message);
}
}

function buildGoogle(o, success) {
	if (success) {
		alert(document.getElementById('ads').innerHTML);	
		var t = window.eval(o.responseText);
	}
}

function buildMap(args) {
	var splitted = args.split(':');
	Connect.setArgument(args);
	if (splitted.length > 1) {
		removePoisFromMap(null, true);
		var extra = '';
		if (splitted.length > 4) {
			extra = '&spot='+splitted[2]+'&act='+splitted[4]+'&country='+splitted[5];
		}
		//alert(splitted.length + ' ' + extra);
		var cObjMap = Connect.asyncRequest('GET', '/call/snippet/destinations.php?ret=xml&go='+splitted[1]+'&name='+splitted[2] + extra, showDynamicDestinationXMLContent, null);
	}	
}

function startMapSearch(searchKey) {
	map.DetachEvent("onchangeview", navigateMap);
	var cArg = 'main:search:'+searchKey;
	Connect.setArgument(cArg);
	var cObj = Connect.asyncRequest('GET', '/call/snippet/destinations.php?go=search&ret=xml&name='+searchKey, showDynamicDestinationXMLContent, null);
	buildMap(cArg);
}

function showDynamicContent(o, success) {
	if(success) {
		setDynamicContent(o.responseText);
	}
}

function showDynamicDestinationXMLContent(o, success) {	
	if(success) {				
		var typer = '';		
		typer = o.getArgument(1);		
		setDynamicDestinationXMLContent(o, typer);
		//dhtmlHistory.add(type, document.getElementById('dynamiccontent').innerHTML);
	}
}

var locs = new Array;
var titles = new Array;
var descs = new Array;
var webnames = new Array;
var stars = new Array;

function setDynamicDestinationXMLContent(o, type) {
	if (o.responseXML != null) {
		var conts = o.responseXML.getElementsByTagName("continent");
		var zoomlevel = 1;
		locs = new Array;
		titles = new Array;
		types = new Array;
		descs = new Array;
		stars = new Array;
		webnames = new Array;
		squarelocs = new Array;
		var showLocs = new Array; // show the following locs, element nr of locs array
		var toCallback = null;
		for (var i=0;i<conts.length;i++) {
			if (type == 'continent') {
	           	locs.push(createNewLatLong(conts[i],'1'));
	           	locs.push(createNewLatLong(conts[i],'2'));
				//map.AttachEvent("onchangeview", drawSquareEvent);
			}
			for (var j=0;j<conts[i].childNodes.length;j++) {
				if (conts[i].childNodes[j].tagName == "country") {
					if (type == 'country') {
			           	locs.push(createNewLatLong(conts[i].childNodes[j],'1'));
			           	locs.push(createNewLatLong(conts[i].childNodes[j],'2'));
						//map.AttachEvent("onchangeview", drawSquareEvent);
					}
					for (var k=0;k<conts[i].childNodes[j].childNodes.length;k++) {
						if (conts[i].childNodes[j].childNodes[k].tagName == "destination") {
							if (type == 'destination') {
					           	locs.push(createNewLatLong(conts[i].childNodes[j].childNodes[k],'1'));							
					           	locs.push(createNewLatLong(conts[i].childNodes[j].childNodes[k],'2'));
								titles.push(conts[i].childNodes[j].childNodes[k].getAttribute("name"));
								descs.push(getNodeValue(conts[i].childNodes[j].childNodes[k],'description'));
								//map.AttachEvent("onchangeview", drawSquareEvent);
					        }		
					        if (type == 'search') {
								try {
									var centerlatlong = createCenterLatLong(conts[i].childNodes[j].childNodes[k].getAttribute('lat1'), conts[i].childNodes[j].childNodes[k].getAttribute('long1'), conts[i].childNodes[j].childNodes[k].getAttribute('lat2'), conts[i].childNodes[j].childNodes[k].getAttribute('long2'))
						           	if (centerlatlong.Latitude != 0.1 && centerlatlong.Longitude != 0.1) {
							           	locs.push(centerlatlong);
										titles.push(conts[i].childNodes[j].childNodes[k].getAttribute("name"));
										webnames.push(conts[i].childNodes[j].childNodes[k].getAttribute("webname"));
										descs.push(getNodeValue(conts[i].childNodes[j].childNodes[k],'description'));
										map.AttachEvent("onchangeview", addPinsEvent);
									}				        
								}catch (e) {
									//alert(e.message);
								}
					        }				
							for (var l=0;l<conts[i].childNodes[j].childNodes[k].childNodes.length;l++) {							
								if (conts[i].childNodes[j].childNodes[k].childNodes[l].tagName == "poi") {								
									if (type == 'poi') {
										var latlonger = createNewLatLong(conts[i].childNodes[j].childNodes[k].childNodes[l],'');
										if (latlonger.Latitude == 0.1 && latlonger.Longitude == 0.1) {
											// coordinates are nog any good, so push destination coordinates instead of poi coords
								           	locs.push(createNewLatLong(conts[i].childNodes[j].childNodes[k],'1'));							
								           	locs.push(createNewLatLong(conts[i].childNodes[j].childNodes[k],'2'));
											titles.push(conts[i].childNodes[j].childNodes[k].getAttribute("name"));
											webnames.push(conts[i].childNodes[j].childNodes[k].getAttribute("webname"));
											descs.push(getNodeValue(conts[i].childNodes[j].childNodes[k],'description'));
								           	//map.AttachEvent("onchangeview", drawSquareEvent);
										} else {
										   	titles.push(getNodeValue(conts[i].childNodes[j].childNodes[k].childNodes[l],'name'));
										   	webnames.push(conts[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('webname'));
										   	types.push(conts[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('categoryTypeId'));
											stars.push(conts[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('avgRating'));
											descs.push(getNodeValue(conts[i].childNodes[j].childNodes[k].childNodes[l],'description'));
										   	locs.push(latlonger);
										   	map.AttachEvent("onchangeview", addPoiPinsEvent);
								        }
										
							        }
								}								
							}
						}				
					}
				}
			}
		}
		map.DeleteAllPolylines();
		map.DeleteAllPushpins();
	    if (locs.length>0){	
			PanMap(null,null,null, locs, 876, 230);
		}
	} else {
		// responseXML not OK, do nothing
	}
}

function drawSquareEvent() {
	try { 
		map.DetachEvent("onchangeview", drawSquareEvent);
		DrawSquare(locs, 2, new VEColor(255,0,0,1), false)
	} catch (e) {
		//alert('(D) ' + e.message);
	}
}

function addPinsEvent() {
	try { 
		map.DetachEvent("onchangeview", addPinsEvent);
		for (var i = 0; i < locs.length; i++) {			
			if (titles.length > i && descs.length > i, webnames.length > i) {
				AddPin(i, locs[i], titles[i], descs[i], webnames[i]); 
			}
		}
	} catch (e) {
		//alert('(E) ' + e.message);
	}
}

function addPoiPinsEvent() {
	try { 
		map.DetachEvent("onchangeview", addPoiPinsEvent);
		for (var i = 0; i < locs.length; i++) {			
			if (titles.length > i && descs.length > i && types.length > i && webnames.length > i) {
				AddPoiPin(i, locs[i], titles[i], descs[i], types[i], webnames[i], stars[i]); 
			}
		}
	} catch (e) {
		//alert('(F) ' + e.message);
	}
}

function getNodeValue(obj,tag) {
	try {
		var o = obj.getElementsByTagName(tag)[0];
		if (o.hasChildNodes()) {
			return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
		} 
		return obj.getElementsByTagName(tag)[0].nodeValue;
	} catch (e) {
		//alert('(G) ' + e.message);
	}
}

function setDynamicContent(html) {
	document.getElementById("dynamiccontent").innerHTML = html;
}

function addToQuickTrayle(webname, type) {
	var call = '/call/quicktrayle/quicktrayle.php?go=add&destName='+webname+'&type='+type;
//	alert(call);
	var cObj = Connect.asyncRequest('GET', call, quickTrayleDone, null);
}

function quickTrayleDone(o, success) {
	if (success) {
		if (o.responseText == 'add') {
			showBox('infobox', 100, 100);
			var res = "<h1>Added</h1><p>Destination added to quicktrayle.</p>";
			document.getElementById('infoboxcontent').innerHTML = res; 
			setTimeout("hide('infobox');", 5000);
		} else if (o.responseText == 'new') {
			showBox('infobox', 100, 100);
			var res = "<h1>Congratulations</h1><p>You have just made a Trayle of the places you have been / places you dream about. You probably have visited a few other cities / dream about a few other cities. Surf around in our travel guide and anytime you see the \"been there\" / \"dream about it\" button, click on it! That's all.</p>";
			res += '<div class="myactions"><a href="/quickmap">manage quicktrayle</a> <a href="#" onclick="hide(\'infobox\'); return false;">continue browsing</div>';
			document.getElementById('infoboxcontent').innerHTML = res; 
		} else if (o.responseText == 'addToSession') {
			showBox('infobox', 100, 100);
			var res = "<h1>Added</h1><p>Destination added to session quicktrayle, go to quicktrayle to save.</p>";
			res += '<div class="myactions"><a href="/quickmap">manage quicktrayle</a> <a href="#" onclick="hide(\'infobox\'); return false;">continue browsing</div>';
			document.getElementById('infoboxcontent').innerHTML = res; 
			setTimeout("hide('infobox');", 5000);
		}
	} else {
		alert('Destination not added, please try again');
	}
}

