// ************************************************************
// Copyright Bridgemania.com 2008
// ************************************************************

// this is launched onload in the body tag
// create map object and initialize starting markers
// ************************************************************
function loadMap(getMarkers) {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("mapCanvas"));
		if(getMarkers) map["mapLoad"] = GEvent.addListener(map,'load',getServerMarkers);
		map.id = mapData["id"];
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
		map.addControl(new GScaleControl());

		if(!viewOnly) map.addControl(new GHierarchicalMapTypeControl());
		map.addMapType(G_PHYSICAL_MAP);
		map.addControl(new GLargeMapControl3D()); 
       	if(!viewOnly) map.addControl(new GOverviewMapControl()); 
		if(!viewOnly) map.enableGoogleBar();
		
		map.setMapType(mapData["type"]);
		z = mapData["zoom"];
		
		if(document.location.href.indexOf("/maps/new/") == -1){
			var ads=new GAdsManager(map, "ca-pub-6982317741240150",{maxAdsOnMap: '100',channel:'5819632064'});
			ads.enable();
		}
		
		//map.setMapType(G_HYBRID_MAP);
		map.setCenter(
			new GLatLng(
				(preFetch["lat"] != "") ? eval(preFetch["lat"]) : mapData["lat"],
				(preFetch["lng"] != "") ? eval(preFetch["lng"]) : mapData["lng"]
			),
			(preFetch["z"] != "") ? eval(preFetch["z"]) : z
		);
		
		if(typeof mapData["panTo"] != "undefined" && preFetch["m"] == ""){
			goto = mapData["panTo"].split(",");
			map.setCenter(new GLatLng(goto[0],goto[1]),4);
		}
		
		initializeMarkers(mapData["markers"],1);
		if(mapData['flickrUse']) initializePhotoMarkers(mapData["flickrs"],"flickr");
		if(mapData['panoramioUse']) initializePhotoMarkers(mapData["panoramios"],"panoramio");
		if(mapData['youtubeUse']) initializePhotoMarkers(mapData["youtubes"],"youtube");
		
		if(preFetch["m"] != "") openMarkerDetails(preFetch["m"]);
		
		GEvent.addListener(map,"extinfowindowclose", function(){
			linkToMarker = 0;
		});
		
		if(mapData["markerTypes"] != null){
			map["mapDragend"] = GEvent.addListener(map,'dragend',getServerMarkers);
			map["mapZoomend"] = GEvent.addListener(map,'zoomend',getServerMarkers);
			map["mapMoveend"] = GEvent.addListener(map,'moveend',getServerMarkers);
			
			
			if(!viewOnly && (mapData["public"] == 1 || mapData["userId"] == userId)){
				map["dblclick"] = GEvent.addListener(map,'singlerightclick', function(point, src, overlay){
					//if(overlay.id == "mapCanvas"){
						addMarker(point);
					//}
				});
			}
			
			if(!viewOnly) drawMapBound();
		} else{
			addLayer(
				'<div class="att"><h2>' + lang[66] + '</h2>' + lang[28] + '<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[29] + '</a></div></div>',
				300,
				0
			);
		}
		
		var legendHTML = createLegend();
		if(isIframe && legendHTML){
			var legendOverlay;
			legendOverlay = document.createElement("div");
			legendOverlay.innerHTML = legendHTML
			legendOverlay.style.position = "absolute";
			legendOverlay.style.right = "15px";
			legendOverlay.style.bottom = "20px";
			legendOverlay.style.backgroundColor = "#FFFFFF";
			legendOverlay.style.padding = "15px";
			$("mapCanvas").appendChild(legendOverlay);
		}
		
		geocoder = new GClientGeocoder();
	}
	
	if(justLoggedIn){
		addLayer(
			'<div class="ok">' + lang[42] + '</div>',
			300,
			0
		);
		ot = setTimeout("removeOverlay();",2000);
	}
	if(justRegistered){
		addLayer(
			'<div class="ok">' + lang[43] + '</div>',
			300,
			0
		);
		ot = setTimeout("removeOverlay();",2000);
	}
	/*if(memberOnly){
		addLayer(
			'<div class="ok">' + lang[50] + '<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div></div>',
			300,
			0
		);
	}*/
	if(justUpdated){
		addLayer(
			'<div class="ok">' + lang[68] + '</div>',
			300,
			0
		);	
		ot = setTimeout("removeOverlay();",2000);
	}
	if(firstTime){
		addLayer(
			'<div class="att">' + lang[77] + '</div>',
			300,

			0
		);	
		ot = setTimeout("removeOverlay();",2000);
	}
	now = new Date().getTime();
	if((mapData["createdRaw"]+30000000) > now && userId == mapData["userId"]){
		addLayer(
				'<div class="ok"><h2>' + lang[80] + '</h2>' + lang[81] + '<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[82] + '</a></div></div>',
				300,
				0
			);
	}
	
	
};

function mapMove(){
	getServerMarkers();
	openMarkerDetails(currentMarker);
};

function drawMapBound(){
	mapBounds = new GPolygon([    
		new GLatLng(mapData["mapSWLat"],mapData["mapSWLng"]),
		new GLatLng(mapData["mapNELat"],mapData["mapSWLng"]),
		new GLatLng(mapData["mapNELat"],mapData["mapNELng"]),
		new GLatLng(mapData["mapSWLat"],mapData["mapNELng"]),
		new GLatLng(mapData["mapSWLat"],mapData["mapSWLng"]),
	], "#ff0000", 2, 1, "#ff0000", 0.0, {clickable: false});  
	map.addOverlay(mapBounds);
};

function drawSiblingMapBound(){
	for(i = 0; i < mapData["around"].length; i++){
		siblingMaps[i] = new GPolygon([    
			new GLatLng(mapData["around"][i]["mapSWLat"],mapData["around"][i]["mapSWLng"]),
			new GLatLng(mapData["around"][i]["mapNELat"],mapData["around"][i]["mapSWLng"]),
			new GLatLng(mapData["around"][i]["mapNELat"],mapData["around"][i]["mapNELng"]),
			new GLatLng(mapData["around"][i]["mapSWLat"],mapData["around"][i]["mapNELng"]),
			new GLatLng(mapData["around"][i]["mapSWLat"],mapData["around"][i]["mapSWLng"]),
		], "#1EC501", 2, .5, "#1EC501", .1, {clickable: true});  
		map.addOverlay(siblingMaps[i]);
		siblingMaps[i].id = i;
	
		siblingLabel[i] = document.createElement("div");
		siblingLabel[i].setAttribute('id',"label" + i);
		map.getPane(G_MAP_MARKER_PANE).appendChild(siblingLabel[i]);
		
		var pos = new GLatLng(mapData["around"][i]["mapNELat"],mapData["around"][i]["mapSWLng"]);
		
		var p = map.fromLatLngToDivPixel(pos);
		var z = GOverlay.getZIndex(pos.lat());
		siblingLabel[i].innerHTML = '<a href="/maps/' + mapData["around"][i]["identifier"] + '">' + mapData["around"][i]["name"] + '</a>';
		siblingLabel[i].style.cssText = "border:1px #FFFFFF solid; color: #1EC501; font-weight: bold; width:200px; position: absolute; z-index: " + (z + 1) + "; top: " + (p.y + 10) + "px; left: " + (p.x + 10) + "px";
		
	}
};

/* Constructor for an extended Marker class */
function LabeledMarker(latlng, options){
    this.latlng = latlng;
    this.labelText = options.labelText || "";
    this.labelClass = options.labelClass || "markerLabel";
    this.labelOffset = options.labelOffset || new GSize(0, 0);
    GMarker.apply(this, arguments);
};


/* It's a limitation of JavaScript inheritance that we can't conveniently
extend GMarker without having to run its constructor. In order for the
constructor to run, it requires some dummy GLatLng. */
LabeledMarker.prototype = new GMarker(new GLatLng(0, 0));

// Creates the text div that goes over the marker.
LabeledMarker.prototype.initialize = function(map) {
        // Do the GMarker constructor first.
        GMarker.prototype.initialize.call(this, map);

        markerLabel[this.id] = document.createElement("div");
		markerLabel[this.id].className = this.labelClass;
        markerLabel[this.id].innerHTML = this.labelText;
        markerLabel[this.id].style.position = "absolute";
		
		map.getPane(G_MAP_MARKER_PANE).appendChild(markerLabel[this.id]);
		
        this.map = map;
        this.div = markerLabel[this.id];
		
};

// Redraw the rectangle based on the current projection and zoom level
LabeledMarker.prototype.redraw = function(force) {
        GMarker.prototype.redraw.call(this, map);
        
        // We only need to do anything if the coordinate system has changed
        if (!force) return;
        
        // Calculate the DIV coordinates of two opposite corners of our bounds to
        // get the size and position of our rectangle
        var p = this.map.fromLatLngToDivPixel(this.latlng);
        var z = GOverlay.getZIndex(this.latlng.lat());
        
        // Now position our DIV based on the DIV coordinates of our bounds
        this.div.style.left = (p.x + this.labelOffset.width) + "px";
        this.div.style.top = (p.y + this.labelOffset.height) + "px";

        this.div.style.zIndex = z + 1; // in front of the marker

};

// Remove the main DIV from the map pane
LabeledMarker.prototype.remove = function() {
  this.div.parentNode.removeChild(this.div);
  this.div = null;
  GMarker.prototype.remove.call(this);
};

function undrawSiblingMapBound(){;
	for (i in siblingMaps){
		map.removeOverlay(siblingMaps[i]);
		map.getPane(G_MAP_MARKER_PANE).removeChild($("label" + i));
		delete siblingMaps[i];
	}
};

// verify that zoom factor is above allowed limit to add marker
// then create a new empty marker, and open the initial infoWindow
// also attach a few listeners
// ************************************************************
function addMarker(point){
	/*if(map.getZoom() < minimumMarkerZoomFactor){
		addLayer(
			'<div class="error">' + 
				lang[6] + 
				'<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
			'</div>',
			300,
			0
		);
	} else{*/
		
		var tinyIcon = new GIcon();
		tinyIcon.image = theIcons[1];
		tinyIcon.iconSize = new GSize(25, 31);
		tinyIcon.iconAnchor = new GPoint(12, 26);
		tinyIcon.infoWindowAnchor = new GPoint(12, 4);
		
		newMarker = (point) ? map.fromContainerPixelToLatLng(point) : map.getCenter();

		markers[markerCounter] = new GMarker(newMarker,{draggable:true,icon:tinyIcon});
		markers[markerCounter]["markerStatus"] = 1;
		markers[markerCounter]["markerId"] = markerCounter;
		markers[markerCounter]["markerUserId"] = userId;
		map.addOverlay(markers[markerCounter]);
		
		if(point){
			/*if(newMarker.lat() > mapData["mapNELat"] || newMarker.lat() < mapData["mapSWLat"] || newMarker.lng() < mapData["mapSWLng"] || newMarker.lng() > mapData["mapNELng"]){
				
					addLayer(
						lang[52] + '<br><a href="javascript:removeOverlay();">' + lang[7] + '</a>',
						300,
						0
					);
			} else{ */
					markers[markerCounter].markerStatus = 3;
					addMarkerForm(markerCounter);
					markers[markerCounter].disableDragging();
					geocoder.getLocations(newMarker, showAddress);
			//}
		} else{
		
			tab = '<div style="padding:10px; text-align:left"><div class="att">' + lang[1] + '<div id="markerWinAction">' + '<a href="javascript:removeMarker(' + markerCounter + ');">' + lang[3] + '</a></div></div></div>';
			markers[markerCounter].openExtInfoWindow(map, "custom_info_window_red", tab, {beakOffset: 0} ); 
			
			markers[markerCounter]["listenerDragstart"] = GEvent.addListener(markers[markerCounter],"dragstart", function(){
				this.markerStatus = 2;
				map.closeExtInfoWindow();
			});
			
			markers[markerCounter]["listenerDragend"] = GEvent.addListener(markers[markerCounter],"dragend", function(){
				if(this.getLatLng().lat() > mapData["mapNELat"] || this.getLatLng().lat() < mapData["mapSWLat"] || this.getLatLng().lng() < mapData["mapSWLng"] || this.getLatLng().lng() > mapData["mapNELng"]){
					addLayer(
						lang[52] + '<br><a href="javascript:removeOverlay();">' + lang[7] + '</a>',
						300,
						0
					);
				} else {
					this.markerStatus = 3;
					addMarkerForm(this.markerId);
					this.disableDragging();
				}
			});
		}

		disableMap(markerCounter);
		markerCounter = markerCounter + 1;
	//}
};


function addMarker2(){
	addLayer(
		'<div class="att">' +
		'<h2>' + lang[84] + '</h2>' +
			lang[83] +
		'<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div></div>',
		300,
		0
	);
};

function searchByAddress(w) {
	geocoder.getLocations(w,function(response){
		if (response.Status.code == "602"){
			alert("'" + w + "' not found.");
		} 
		else if(response.Placemark[0].Point.coordinates[1] > mapData["mapNELat"] || response.Placemark[0].Point.coordinates[1] < mapData["mapSWLat"] || response.Placemark[0].Point.coordinates[0] < mapData["mapSWLng"] || response.Placemark[0].Point.coordinates[0] > mapData["mapNELng"]){
			alert("The location found is outside of your defined map area, try searching with more details, city name, zip...");
		} else{
			place = response.Placemark[0];
			c = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
			map.setCenter(c,16);
			point = map.fromLatLngToContainerPixel(c);
			removeOverlay();
			addMarker(point);
		}
	} );
	return false;
}

function zoomByAddress(w) {
	geocoder.getLocations(w,function(response){
		if (response.Status.code == "602"){
			alert("'" + w + "' not found.");
		}
		else{
			place = response.Placemark[0];
			c = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
			map.setCenter(c,10);
			removeOverlay();
		}
	} );
}


// generic function to open the detailed infoWindow of a marker
// adding a few links for administrator and marker owners.
// priviledges model:
// Map administrator: add marker, edit and move own and anynymous markers, delete any markers
// Authenticated user: Add marker, edit and move own markers
// Anonymous users: Add marker
function openMarkerDetails(markerId){
	tab = "<div id='markerWinIcon'><img align='left' src='" + ((markers[markerId].markerType) ? theIcons[markers[markerId].markerType] : theIcons[1]) + "'>" + "</div>" +
		  "<div id='markerWinTitle'>" + markers[markerId].markerTitle + "</div>" +
		  "<div id='markerWinBy'>" + lang[54] + " " + markers[markerId].markerCreated + " " + lang[55] + " " +
				(
					// yourself
					(userId == markers[markerId].markerUserId) ? lang[73] : 
					// map owner
					(mapData["userId"] == markers[markerId].markerUserId) ? lang[56] : 
					// a logged user
					(markers[markerId].markerUserId > 0) ? lang[58] : 
					// anonymous
					lang[57]
				) +
				//((mapData["markerTypes"].length) ? " - " + lang[10] + ": " + getMarkerTypeName(markers[markerId].markerType) + "</i>" : "") +
			"</div>" +
			"<div id='markerWinDesc'>" +  url2Links(markers[markerId].markerDescription) + "</div>" + 
			((map.getZoom() != markers[markerId].markerZoom) ? '<a href="javascript:zoomIn(' + markers[markerId].markerLat + ',' + markers[markerId].markerLng + ',' + markerId + ',\'20\')"><img border="0" width="298" height="150" style="margin-bottom:10px;" src="http://maps.google.com/staticmap?center=' + markers[markerId].markerLat + ',' +  markers[markerId].markerLng + '&zoom=' + ((parseInt(markers[markerId].markerZoom) > 17) ? 17 : markers[markerId].markerZoom) + '&size=298x150&maptype=hybrid&markers=' + markers[markerId].markerLat + ',' +  markers[markerId].markerLng + ',midblue&key=ABQIAAAAx5UG4dCt9MCL7iSugYYA7hQeHKBGktg2ZLT-mXQs3igih6__ghRpSQUC4r6MwqDB62cV2HJL9ZM90A"></a>' : '') +
			'<div id="markerWinTool"><div style="float:left;">' +
			((userId == markers[markerId].markerUserId || (userId == mapData["userId"])) ? '<a href="javascript:editMarkerForm(' + markerId + ')">' + lang[15] + '</a> | ' : '') +
			((userId ==  mapData["userId"]) ? '<a href="javascript:deleteMarker(' + markerId + ',0)">' + lang[25] + '</a> | ' : '') +
			'<a href=\"javascript:zoomIn(' + markers[markerId].markerLat + ',' + markers[markerId].markerLng + ',' + markerId + ');\">' + lang[53] + '</a> | ' + 
			'<a href="javascript:copyURL(\'marker\',71);">' + lang[72] + '</a></div><div style="float:right;">' +
			
			'<a href="javascript:fb2();"><img src="http://www.mapmotive.com/images/facebook_16x16.jpg" alt="Share on Facebook" width="16" height="16" border=0 align="absmiddle"></a>&nbsp;&nbsp;' +
			'<a href="http://digg.com/submit?url=' + escape(getURL('marker')) + '"><img border=0 width="16" height="16" src="http://digg.com/img/digg-guy-icon.gif" alt="Submit to Digg"></a>&nbsp;&nbsp;' +
			'<a href="http://www.stumbleupon.com/submit?url=' + escape(getURL('marker')) + '"><img border=0 src="http://cdn.stumble-upon.com/images/16x16_su_3d.gif" alt="Submit to Stumble Upon"></a>&nbsp;&nbsp;' +
			'<a href="http://www.reddit.com/submit?url=' + escape(getURL('marker')) + '"><img src="http://www.reddit.com/static/spreddit1.gif" alt="Submit to Reddit" border="0" /></a></div></div>';

	markers[markerId].openExtInfoWindow(map, "custom_info_window_red", tab, {beakOffset: 0} ); 
	linkToMarker = markerId;
};

// for a specific marker, open the infoWindow with the 
// form to add a new marker on the map
// ************************************************************
function addMarkerForm(markerId){
	tab = '<form id="markerForm" onSubmit="saveMarker(' + markerId + ');  return false;"><input type="hidden" name="a" value="markerAdd" id="a"><div id="markerWinDesc">' + htmlText["addMarkerForm1"] + "<br><br>" + 
		markerTypeDropDown(0) +
		htmlText["addMarkerForm2"]  + 
		'</div><div id="markerWinAction"><a href="javascript:removeMarker(' + markerId + ');">' + lang[3] + '</a> | ' +
		'<a href="javascript:saveMarker(' + markerId + ')">' + lang[4] + '</a></div></form>';
	
	markers[markerId].openExtInfoWindow(map, "custom_info_window_red", tab, {beakOffset: 0} ); 
	
	markers[markerId]["listenersInfowindowclose"] = GEvent.addListener(map,"extinfowindowclose", function(){
			enableMap();
			map.removeOverlay(markers[markerId]);
			GEvent.removeListener(markers[markerId]["listenersInfowindowclose"]);
	});
	
	geocoder.getLocations(markers[markerId].getLatLng(), showAddress);
	
};

function showAddress(response) {  
	if (!response || response.Status.code != 200) {    
		//do nothing  
	} else {
		//$("markerDescription").value = response.Placemark[0].address + ", " +$("markerDescription").value;    
		if($("markerDescription")) $("markerDescription").value = response.Placemark[0].address; 
	}
};


// for a specific marker, open the infoWindow with the 
// form to add a new marker on the map, with marker info prefilled
// ************************************************************
function editMarkerForm(markerId){
	newDiv = ($("iw")) ? $("iw") : document.createElement('div');
	newDiv.setAttribute("id","iw");
	newDiv.innerHTML = '<form id="markerForm" onSubmit="updateMarker(' + markerId + '); return false;"><input type="hidden" name="a" value="markerUpdate" id="a"><div id="markerWinDesc">' + htmlText["addMarkerForm1"] + "<br><br>" + 
		markerTypeDropDown(markers[markerId].markerType) +
		htmlText["addMarkerForm2"] +
		'</div><div style="text-align: right"><a href="javascript:removeMarker(' + markerId + ');">' + lang[3] + '</a> | ' +
		'<a href="javascript:updateMarker(' + markerId + ')">' + lang[4] + '</a></div></form>';
	document.body.appendChild(newDiv);

	markers[markerId].openExtInfoWindow(map,"custom_info_window_red",$("iw").innerHTML);

	$("markerTitle").value = markers[markerId].markerTitle.unescapeHTML();
	if($("markerType")) $("markerType").value = markers[markerId].markerType;

	$("markerDescription").value = markers[markerId].markerDescription.replace(/<br \/>/g,"\n").unescapeHTML();	
	$("markerTags").value = markers[markerId].markerTags.unescapeHTML();	
	
	//geocoder.getLocations(markers[markerId].getLatLng(), showAddress);
};

// if the marker is not currently being dragged (status = 2)
// then close the InfoWindow and delete the marker from the map
// this should probably remove the marker from the markers array...
// ************************************************************
function removeMarker(markerId){
	if(markers[markerId].markerStatus != 2 && markers[markerId].markerStatus != 4){
		map.removeOverlay(markers[markerId]);
		map.closeExtInfoWindow();
		if(typeof markers[markerId] == "undefined") delete markers[markerId];
	} else{
		map.closeExtInfoWindow();
	}
};

/*function removeMarkers(){
	SWLat = map.getBounds().getSouthWest().lat();
	NELat = map.getBounds().getNorthEast().lat();
	SWLng = map.getBounds().getSouthWest().lng();
	NELng = map.getBounds().getNorthEast().lng();
	c = 0;
	for(i in markers){
		if(markers[i].getLatLng().lat() > NELat || markers[i].getLatLng().lat() < SWLat || markers[i].getLatLng().lng() < NELng || markers[i].getLatLng().lng() > SWLng){
			map.removeOverlay(markers[i]);
			delete markers[i];
			c = c + 1;
		}	
	}
};*/

function removeMarkers(){
	SWLat = map.getBounds().getSouthWest().lat();
	NELat = map.getBounds().getNorthEast().lat();
	SWLng = map.getBounds().getSouthWest().lng();
	NELng = map.getBounds().getNorthEast().lng();
	c = 0;
	for(i in markers){
		if(markers[i]["markerLat"] > NELat || markers[i]["markerLat"] < SWLat || markers[i]["markerLng"] > NELng || markers[i]["markerLng"] < SWLng){
			map.removeOverlay(markers[i]);
			delete markers[i];
			c = c + 1;
		}	
	}
};

function disableMap(except){
	//map.disableDragging();
	for(i in markers){
		if(i != except){
			markers[i].hide();
			if(typeof markerLabel[i] != "undefined") markerLabel[i].style.display = "none";
		}
	}
	mapDisabled = true;
	//GEvent.removeListener(map["mapMoveend"]);
};

function enableMap(){
	//map.enableDragging();
	for(i in markers){
		markers[i].show();
	}
	applyLegend(0);
	mapDisabled = false;
	map["mapMoveend"] = GEvent.addListener(map,'moveend',getServerMarkers);
};

function applyLegend(fadeIt){
	legendApply.clear();
	hasLegend = false;

	for(y = 0; y <= 7; y++){
		if($("legend"+y)) hasLegend = true;
		if($("legend"+y) && $("legend"+y).checked == true){
			legendApply.push(parseFloat($("legend"+y).value));
		}
	}


	if(hasLegend){
		for(i in markers){
			if(legendApply.indexOf(eval(markers[i].markerType)) != -1){
					markers[i].show();
					if(labelApply){
						//markerLabel[i].style.display = "";
					} else{ 
						//markerLabel[i].style.display = "none";
					}
			} else{
				
					markers[i].hide();
					//if(labelApply){
						//markerLabel[i].style.display = "";
					//} else{ 
						if(typeof markerLabel[i] != "undefined") markerLabel[i].style.display = "none";
					//}

			}
		} 
	} else{ 
		for(i in markers){
			if(labelApply && markerLabel[i]){
				//markerLabel[i].style.display = "";
			} else if(markerLabel[i]){ 
				//markerLabel[i].style.display = "none";
			}
		}
	}
		
};

function legendAll(fadeIt){
	for(y = 1; y <= 7; y++){
		if($("legend"+y)) $("legend"+y).checked = $("legendAll").checked;
	}
	applyLegend(fadeIt);
};

function applyLabel(){
	for(i in markers){
		if(labelApply){
			//markerLabel[i].style.display = "none";
		} else if(!markers[i].isHidden()){
			//markerLabel[i].style.display = "";
		}
	}
	labelApply = (labelApply) ? false : true;
};


// this takes an object, and place and configure all of them
// on the map, the marker object format is
// checks first to see if marker already exists.
// ************************************************************
function initializeMarkers(markerObj,init){
	var added = 0;
	var rejected = 0;
	
	c = 0;
	for(i in markerObj) c = c + 1;

	//if(init && c < 200){
		if($("labelsApply")) $("labelsApply").checked = 1;
		labelApply = true;
	//}
	
	if(!mapDisabled){
		for(i in markerObj){
			
			if(typeof markers[i] == "undefined"){
				
				
				
				added = added +1;
				theIcon = new GIcon();
				theIcon.image = theIcons[markerObj[i]["icon"]];
				theIcon.iconSize = new GSize(12,20);
				
				var tinyIcon = new GIcon();
				tinyIcon.image = theIcons[((!markerObj[i]["markerType"]) ? markerObj[i]["markerType"]+1 : markerObj[i]["markerType"])];
				
				//tinyIcon.shadow = theIcons[11];
				tinyIcon.iconSize = new GSize(25, 31);
				//tinyIcon.shadowSize = new GSize(22, 20);
				tinyIcon.iconAnchor = new GPoint(12, 26);
				tinyIcon.infoWindowAnchor = new GPoint(12, 4);

				
				

				opts = {
						id: i,
						"icon": tinyIcon,
						"labelClass": "markerLabel",
						"clickable": true,
						"draggable": true,
						"labelText": markerObj[i]["markerTitle"],
						"labelOffset": new GSize(13, -20)
				};
				
				/*latlng = new GLatLng(markerObj[i]["markerLat"],markerObj[i]["markerLng"]);
				markers[i] = new LabeledMarker(latlng, opts);*/
				
				markers[i] = new GMarker(
					new GLatLng(markerObj[i]["markerLat"],markerObj[i]["markerLng"]),opts
				);
				
				for(y in markerObj[i]){
					markers[i][y] = markerObj[i][y];
				}
				
				//markers[i].markerType = "marker";
				
				//attach drag behavior or disables it
				if((userId == markers[i].markerUserId) || (userId == mapData["userId"])){
					markers[i]["listenerDragstart"] = GEvent.addListener(markers[i],"dragstart", function(){
						this.closeInfoWindow();
						this.currentCoord = this.getLatLng();
					});
					markers[i]["listenerDragend"] = GEvent.addListener(markers[i],"dragend", function(){
						if(map.getZoom() < minimumZoomFactor){
							markers[this.id].setLatLng(this.currentCoord);
							addLayer(
								'<div class="error">' +
									lang[74] + '<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +

								'</div>',
								300,
								0
							);
						} else{
							updateMarkerCoord(this.id);
						}
					});
				} else{
					markers[i].disableDragging();
				}
				
				map.addOverlay(markers[i]);
				
				markers[i]["onmouseOver"] = GEvent.addListener(markers[i],"mouseover", function(){
					quickView(this);
				});
				
				markers[i]["onmouseOut"] = GEvent.addListener(markers[i],"mouseout", function(){
					$("mapCanvas").removeChild($("quickView"+this.id));
				});

				markers[i]["onclick"] = GEvent.addListener(markers[i],"click", function(){
					openMarkerDetails(this.id);
				});
		
				if(currentMarker){
					openMarkerDetails(currentMarker);
					currentMarker = 0;
				}

			} else{
				rejected = rejected + 1;
				
			}
		}
		
		removeMarkers(markerObj);
		applyLegend(0);
		
	}
};

// this generates the <option>s needed for the marker type
// as defined in the map property "markerTypes"
// ************************************************************
function markerTypeDropDown(selItem){
	markerTypeObj = mapData["markerTypes"];
	selItem = (selItem) ? selItem : 1;
	if(markerTypeObj.length){
		selects = '<b>' + lang[10] + '</b><br />' +
		'<img align="absmiddle" id="markerImg" src="' + theIcons[selItem] + '"> <select name="markerType" id="markerType" onchange="changeIconImg(this.value)" style="width:88%;">';
		for(i = 0; i < markerTypeObj.length; i++){
			selects = selects + '<option value="' + markerTypeObj[i]["id"] + '"' + ((selItem == markerTypeObj[i]["id"]) ? " selected" : "") +'>' + markerTypeObj[i]["name"] + '</option>\n';
		}
		selects = selects + '</select><br /><br />';
		return selects;
	} else{
		return "";
	}
};

function changeIconImg(imgId){
	$("markerImg").src = theIcons[imgId];
};

function getMarkerTypeName(typeId){
	markerTypeObj = mapData["markerTypes"];
	for(i = 0; i < markerTypeObj.length; i++){
		if(markerTypeObj[i]["id"] == typeId){
			return markerTypeObj[i]["name"];
		}
	}
	return lang[51];
};

function createLegend(){
	markerTypeObj = mapData["markerTypes"];
	var legend = "";
	if(markerTypeObj.length > 1){
		legend = '<b>' + lang[85] + '</b><br />';
		for(i = 0; i < markerTypeObj.length; i++){
			legend = legend + '<img align="absmiddle" id="markerImg" src="' + theIcons[markerTypeObj[i]["id"]] + '">' + markerTypeObj[i]["name"] + '<br />\n';
		}
		return legend;
	} else{
		return false;
	}
};

// validate that the new marker form has all 
// required fields
// ************************************************************
function validateMarkerForm(){
	t = $("markerTitle").value;
	ty = $("markerType").value;
	d = $("markerDescription").value;
	
	if(t == "" || ty == "" || d == ""){
		return false;
	} else{
		return true;
	}
};

// validate that the new marker form has all 
// required fields
// ************************************************************
function validateMarkerForm(){
	t = $("markerTitle").value;
	ty = ($("markerType")) ? $("markerType").value : "ok";
	d = $("markerDescription").value;
	
	if(t == "" || ty == "" || d == ""){
		return false;
	} else{
		return true;
	}
};

// this grabs all the values form the "add marker" form (it should use prototype "serialize", to be added)
// validates the fields, and issue an AJAX post to the map gateway with everything it needs to
// add a marker in the DB, the gateway answer is a success/error code
// marker ID = success
// 0 = error
// ************************************************************
function saveMarker(markerId){
	if(validateMarkerForm()){

		addLayer(
			'<div class="wait">' + lang[11] + '</div>',


			300,
			0
		);
	
		t = $("markerTitle").value;
		ty = ($("markerType")) ? $("markerType").value : 0;
		d = $("markerDescription").value;
		la = markers[markerId].getLatLng().lat();
		ln = markers[markerId].getLatLng().lng();
		ta = $("markerTags").value;
		
		function completeAjax(request){
			if(request.responseText > 0){
				addLayer(
					'<div class="ok">' +
						lang[14] + '<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
					'</div>',
					300,
					1
				);
				ot = setTimeout("removeOverlay();",1000);
				
				// removes temporary marker and create definitive one
				markers[markerId].markerStatus = 5;
				
				removeMarker(markerId);
				props = {};
				u = (userId) ? userId : 0;
				
				d = d.replace("\r\n","<br />","g");	
	
				props[request.responseText] = { 
					"markerUserId": u,
					"markerType": ty,
					"markerStatus": 4,
					"markerLat": la,
					"markerLng": ln,
					"markerTitle": t,
					"markerDescription": d,
					"markerCreated": lang[59],
					"markerTags": ta
				};
				
				initializeMarkers(props);
				openMarkerDetails(request.responseText);
			} else{
				addLayer(
					'<div class="error">' + lang[13] +
						'<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
					'</div>',
					300,
					0
				);	
			}
		}
		
		var req = new Ajax.Request(gatewayURL, {   
			method: 'post',   
			parameters: $('markerForm').serialize() + "&i=" + markerId + "&m=" + map.id + "&lat=" + la + "&lng=" + ln,
			onComplete: completeAjax
		});	
	} else{
		addLayer(
			'<div class="error">' + lang[12] +
				'<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
			'</div>',
			300,
			0
		);	
	}
};

// this grabs all the values form the "add marker" form (it should use prototype "serialize", to be added)
// validates the fields, and issue an AJAX post to the map gateway with everything it needs to
// update a marker in the DB, the gateway answer is a success/error code
// 1 = success
// 2 = error
// ************************************************************
function updateMarker(markerId){
	if(validateMarkerForm()){
		addLayer(
			'<div class="wait">' + lang[11] + '</div>',
			300,
			0
		);
		
		function completeAjax(request){
			if(request.responseText == 1){
				addLayer(
					'<div class="ok">' +
						lang[16] + '<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
					'</div>',
					300,
					1
				);
				ot = setTimeout("removeOverlay();",1000);
				
				t = $("markerTitle").value;
				ty = ($("markerType")) ? $("markerType").value : 0;
				d = $("markerDescription").value;
				ta = $("markerTags").value;
				
				d = d.replace("\r\n","<br />","g");	
				
				// removes temporary marker and create definitive one
				markers[markerId].markerStatus = 5; // temp state until deletion
				i = "\"" + markerId + "\"";
				props = {};
				props[markerId] = { 
					"markerUserId": markers[markerId].markerUserId, 
					"markerType": ty, 
					"markerStatus": 4,
					"markerLat": markers[markerId].markerLat, 
					"markerLng": markers[markerId].markerLng,
					"markerTitle": t, 
					"markerDescription": d,
					"markerCreated": markers[markerId].markerCreated,
					"markerTags": ta

				};
			
				removeMarker(markerId);
				//markers[markerId] = null;
				delete markers[markerId];
				initializeMarkers(props);
				openMarkerDetails(markerId);
			} else{
				addLayer(
					'<div class="error">' + lang[13] +
						'<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
					'</div>',
					300,
					0
				);	
			}
		}	
		var req = new Ajax.Request(gatewayURL, {   
			encoding:'iso-8859-1',
			method: 'post',   
			parameters: $('markerForm').serialize() + "&i=" + markerId + "&m=" + map.id,
			onComplete: completeAjax
		});	
	} else{
		addLayer(
			'<div class="error">' + lang[12] +
				'<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
			'</div>',
			300,
			0
		);	
	}
};


function deleteMarker(markerId,commit){
	if(!commit){
		addLayer(
			'<div class="att">' + lang[22] + '<div id="markerWinAction">' + 
			'<a href="javascript:deleteMarker(' + markerId + ',1)">' + lang[23] + '</a> | ' + 
			'<a href="javascript:removeOverlay();">' + lang[24] + '</a></div></div>',
			300,
			0
		);


	} else{
		a = "markerDelete";

		function completeAjax(request){
			if(request.responseText == 1){
				addLayer(
					'<div class="ok">' +
						lang[26] + '<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
					'</div>',
					300,
					1
				);
				ot = setTimeout("removeOverlay();",2000);
				markers[markerId].markerStatus = 1;
				removeMarker(markerId);
			} else{
				addLayer(
					'<div class="error">' + lang[27] +
						'<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
					'</div>',
					300,
					0
				);	
			}
		}
			
		var req = new Ajax.Request(gatewayURL, {   
			method: 'post',   
			parameters: 'a='+ a + '&i=' + markerId + '&m=' + map.id,
			onComplete: completeAjax
		});	
	}
};



// this is a function to update a marker coordinates, it is triggered
// when a user drags a saved marker and drops it
function updateMarkerCoord(markerId){
	a = "markerCoordUpdate";
	la = markers[markerId].getLatLng().lat();
	ln = markers[markerId].getLatLng().lng();
	
	if(la < mapData["mapNELat"] && la > mapData["mapSWLat"] && ln > mapData["mapSWLng"] && ln < mapData["mapNELng"]){
		addLayer(
			'<div class="wait">' + lang[11] + '</div>',
			300,
			0
		);
		ot = setTimeout("removeOverlay();",2000);
		function completeAjax(request){
			if(request.responseText == 1){
				/*addLayer(
					'<div class="ok">' +
						lang[20] + '<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
					'</div>',
					300,
					1
				);
				ot = setTimeout("removeOverlay();",2000);*/
				markers[markerId].markerLat = la;
				markers[markerId].markerLng = ln;
				openMarkerDetails(markerId);
			} else{
				markers[markerId].setLatLng(markers[markerId].currentCoord);
				//markers[markerId].disableDragging();
				addLayer(
					'<div class="error">' + lang[21] +
						'<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
					'</div>',
					300,
					0
				);	
			}
		}
			
		var req = new Ajax.Request(gatewayURL, {   
			method: 'post',   
			parameters: 'a='+ a + '&i=' + markerId + '&lan=' + la + '&lng=' + ln + '&m=' + map.id,
			onComplete: completeAjax
		});	
	} else{
		var point = new GLatLng(eval(markers[markerId].markerLat),eval(markers[markerId].markerLng)); 
		markers[markerId].setLatLng(point);
		addLayer(
			lang[52] + '<br><a href="javascript:removeOverlay();">' + lang[7] + '</a>',
			300,
			0
		);
	}
};

// after a user have panned or zoom on the map, using Ajax, 
// get a string from the gateway representing all revealed markers
// parse this string into a JS array, then add markers to the map
// need to add the cordinates to the request.
function getServerMarkers(){
	if(mapData["flickrUse"]) getServerPhotos("getFlickr");
	if(mapData["panoramioUse"]) getServerPhotos("getPanoramio");
	if(mapData["youtubeUse"]) getServerPhotos("getYoutube");
	if(freedUp == 1){
		freedUp = 0;
		a = "markersGet";
		
		SWLat = map.getBounds().getSouthWest().lat();
		NELat = map.getBounds().getNorthEast().lat();
		SWLng = map.getBounds().getSouthWest().lng();
		NELng = map.getBounds().getNorthEast().lng();
		
		function completeAjax(request){
			
			eval(request.responseText);
			//removeMarkers();
			initializeMarkers(ajaxMarkers);
			freedUp = 1;
		}
		var req = new Ajax.Request(gatewayURL, {   
			method: 'post',   
			parameters: 'a=' + a + '&m=' + map.id + "&swlat=" + SWLat + "&swlng=" + SWLng + "&nelat=" + NELat +"&nelng=" + NELng,
			onComplete: completeAjax
		});	
	}
};

// after a user click search
// get a string from the gateway representing all revealed markers
// parse this string into a JS array, then add markers to the map
// need to add the cordinates to the request.
function searchMap(){
	addLayer(
		'<div class="wait">' + lang[60] + '</div>',
		300,
		0
	);
	
	a = "searchMap";
	
	SWLat = map.getBounds().getSouthWest().lat();
	NELat = map.getBounds().getNorthEast().lat();
	SWLng = map.getBounds().getSouthWest().lng();
	NELng = map.getBounds().getNorthEast().lng();
	s = $("mapKeywords").value;
	
	function completeAjax(request){
		eval(request.responseText);
		if(Object.keys(ajaxMarkers).length == 0){
				addLayer(

					'<div class="att">' + lang[61] + '<div id="markerWinAction">' + 
					'<a href="javascript:removeOverlay();">' + lang[7] + '</a></div></div>',
					300,
					1
				);
		} else{
			sr = "found " + Object.keys(ajaxMarkers).length + " results.<br><br>";
			c = 0;
			for (i in ajaxMarkers){
				sr = sr + (c + 1) + '. <a href="javascript:removeOverlay(); zoomIn(' + ajaxMarkers[i]["markerLat"] + ',' + ajaxMarkers[i]["markerLng"] + ',' + i + ')">' + ajaxMarkers[i]["markerTitle"] + '</a><br>';
				c = c + 1;
				if(c == 9) break;
			}
			if(Object.keys(ajaxMarkers).length > 10){
				sr = sr + "<br /><br />More result, see map";
			}
			
			addLayer(
				'<div class="ok">' +
					sr + '<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
				'</div>',
				300,
				1
			);
			
			removeMarkers();
			initializeMarkers(ajaxMarkers);
		}
	}
	var req = new Ajax.Request(gatewayURL, {   
		method: 'post',   
		parameters: 'a=' + a + '&m=' + map.id + "&swlat=" + SWLat + "&swlng=" + SWLng + "&nelat=" + NELat +"&nelng=" + NELng + "&s=" + s,
		onComplete: completeAjax
	});	
};


// function that gathers the form fields values, validates them
// then get a few map current state values and send to gateway for processing
function saveMap(){
	if(validateMap()){
		$("mapLat").value = map.getCenter().lat();
		$("mapLng").value = map.getCenter().lng();
		$("mapZoom").value = map.getZoom();
		$("mapType").value = map.getCurrentMapType().getName();
		$("mapSWLat").value = map.getBounds().getSouthWest().lat();

		$("mapNELat").value = map.getBounds().getNorthEast().lat();
		$("mapSWLng").value = map.getBounds().getSouthWest().lng();
		$("mapNELng").value = map.getBounds().getNorthEast().lng();
		return true;
	} else{
		return false;
	}
};

// function to validate a few form fields, basically just check for empty state.
// it also checks for the minium zoom factor
function validateMap(){
	n = $("mapName").value;
	d = $("mapDescription").value;
	z = map.getZoom();

	/*if(z < minimumZoomFactor){
		addLayer(
			lang[31] + '<br><a href="javascript:removeOverlay();">' + lang[7] + '</a>',
			300,
			0
		);
		return false;
	} else */ if(n == "" || d == ""){
		addLayer(
				'<div class="error">' + lang[12] +
					'<div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div>' +
				'</div>',
				300,
				0
			);	
		return false;
	} else{
		return true;
	}	
};

function zoomIn(lat,lng,markerId,mzoom){
	//map.closeExtInfoWindow();
	//currentMarker = markerId;
	
	/*if(lat == map.getCenter().lat() && lng == map.getCenter().lng()){
		map.setZoom(16);
	} else{	
		temp = GEvent.addListener(map,'moveend',function(){
			GEvent.removeListener(temp);
			map.setZoom(16);
		});
		map.panTo(new GLatLng(lat,lng));
	}*/
	
	map.closeExtInfoWindow();
	currentMarker = markerId;
	
	nZoom = (mzoom) ? mzoom : map.getZoom() + 2;
	if(mzoom) map.setMapType(G_HYBRID_MAP);
	map.setCenter(new GLatLng(lat,lng),parseFloat(nZoom));
	if(typeof markers[markerId] != "undefined") openMarkerDetails(markerId); 

};

function showMe(lat,lng,markerId){
	map.closeExtInfoWindow();
	currentMarker = markerId;
	temp = GEvent.addListener(map,'moveend',function(){
				GEvent.removeListener(temp);
				getServerMarkers();
				map.setCenter(new GLatLng(lat,lng));
			});
	map.panTo(new GLatLng(lat,lng));
};

function highliteMarker(markerId){
	markers[markerId].setImage('/images/markers/hover.png');
};

function dehighliteMarker(markerId){
	markers[markerId].setImage(theIcons[((!markers[markerId].markerType) ? markers[markerId].markerType+1 : markers[markerId].markerType)]);
};


// ######################

function quickView(objId){
	var messageOverlay;
	var theCss;
	messageOverlay = document.createElement("div");
	messageOverlay.id = "quickView"+markers[objId].id;
	messageOverlay.innerHTML = ((markers[objId].markerType != "marker") ? "<img src='" + markers[objId].thumb + "' width='60' height'60' style='padding:2px;' align='top' />" : ""); // + constrain(markers[objId].markerTitle,30);
	theCss = "position:absolute; background-color:#FFFFFF; font-size:11px; font-weight:bold; padding:2px; border:1px solid #999999; filter: alpha(opacity=90); -moz-opacity: .90; left:" + (parseInt(map.fromLatLngToContainerPixel(markers[objId].getLatLng()).x)+12) + "px; top:" + (parseInt(map.fromLatLngToContainerPixel(markers[objId].getLatLng()).y)-12) + "px";
	messageOverlay.style.cssText = theCss;
	$("mapCanvas").appendChild(messageOverlay);
}

function removePhotos(a){
	var removed = 0;
	for(i in markers){
		if(i.indexOf(a) != -1){
			map.removeOverlay(markers[i]);
			map.closeExtInfoWindow();
			if(typeof markers[i] != "undefined") delete markers[i];
			removed = removed + 1;
		}
	}
	return removed;
}

function showHideType(showHide){
	if(removePhotos(showHide) == 0){
		initializePhotoMarkers(mapData[showHide+"s"],showHide);
		$("legendBut_"+showHide).style.backgroundColor = "#EFEFEF";
	} else{
		$("legendBut_"+showHide).style.backgroundColor = "#CCCCCC";
	}
}

function initializePhotoMarkers(markerObj,markerType){
	if(!mapDisabled){
		j = 0;
		for(i in markerObj){
			if(i.indexOf(markerType) != -1){
				if(typeof markers[i] == "undefined"){
					j = j + 1;
					var tinyIcon = new GIcon();
					tinyIcon.shadow = theIcons[markerType];
					tinyIcon.iconSize = new GSize(25,25);
					tinyIcon.iconAnchor = new GPoint(12,12);
					tinyIcon.infoWindowAnchor = new GPoint(12,5);
					
					opts = {
						id: i,
						"icon": tinyIcon,
						"clickable": true,
						"draggable": false
					};
					
					latlng = new GLatLng(markerObj[i]["lat"],markerObj[i]["lng"]);
					markers[i] = new GMarker(latlng, opts);
		
					for(y in markerObj[i]){
						markers[i][y] = markerObj[i][y];
					}
					
					if(i.indexOf("flickr") != -1){
						markers[i]["markerType"] = "flickr";
						markers[i].regMark = "Photos provided by <a href='http://www.flickr.com/' target='_blank'>Flickr</a> are under the copyright of their owners.";
					} else if(i.indexOf("panoramio") != -1){
						markers[i]["markerType"] = "panoramio";
						markers[i].regMark = "Photos provided by <a href='http://www.panoramio.com/' target='_blank'>Panoramio</a> are under the copyright of their owners.";
					} else if(i.indexOf("youtube") != -1){
						markers[i].regMark = "Photos from <a href='http://www.youtube.com' target='_blank'>Youtube</a>.";
						markers[i]["markerType"] = "youtube";
					}
					
					map.addOverlay(markers[i]);
					$("mtgt_"+i).title = markerObj[i]["markerTitle"];
				
					
					markers[i]["onmouseover"] = GEvent.addListener(markers[i],"mouseover", function(){
						quickView(this.id);
					});
					
					markers[i]["onmouseout"] = GEvent.addListener(markers[i],"mouseout", function(){
						$("mapCanvas").removeChild($("quickView"+this.id));
					});
					
					if(markerType == "youtube"){
						markers[i]["onclick"] = GEvent.addListener(markers[i],"click", function(){
							openVideoMarkerDetails(this.id);
						});
					
					} else{
						markers[i]["onclick"] = GEvent.addListener(markers[i],"click", function(){
							//openPhotoMarkerDetails(this.id);
							if(!viewOnly){ openPhoto(this.id); }
							//else{ parent.openPhoto(this.id); }
						});
					}
				}
			}
		}	
	}
};


function openPhotoMarkerDetails(markerId){

	tab = "<div style='height:50px; padding-bottom:7px;'><div id='markerWinIcon' ><img align='left' src='" + markers[markerId].ownerThumb + "' width='50' height='50' style='padding-bottom:10px'>" + "</div>" +
		  "<div id='markerWinTitle'><h2><a href='javascript:openPhoto(\"" + markerId + "\")'>" + markers[markerId].markerTitle + "</a></h2></div>" +
		  "<div id='markerWinBy'>By <a href='" + markers[markerId].photoStream + "' target='_blank'>" + markers[markerId].ownerName + "</a></div></div>" +
		  "<div style='clear:both'></div>" +
		  "<div style='margin:5px; background-color:#EFEFEF; height:200px; background-image:url(" + markers[markerId].photo + "); background-repeat:no-repeat; background-position:center; text-align:right; color:#CCCCCC; font-size:10px;'><a href='javascript:openPhoto(\"" + markerId + "\")'><div style='height:200px; background-image:url(images/icon_" + markers[markerId].markerType + ".png); background-repeat:no-repeat; background-position: 5px 5px' onmouseover=\"this.style.cursor='pointer'\">Click to enlarge.</div></a></div>" +
		  "<div style='clear:both'></div>" +
		  "<div id='markerReg'>" + markers[markerId].regMark + "</div>";

	markers[markerId].openExtInfoWindow(map, "custom_info_window_red", tab, {beakOffset: 0} ); 	
	
	markers[markerId]["listenersInfowindowclose"] = GEvent.addListener(map,"extinfowindowclose", function(){
			GEvent.removeListener(markers[markerId]["listenersInfowindowclose"]);
	});
};

function openVideoMarkerDetails(markerId){
	tab = '<div style="text-align:left; padding-left:4px;"><div><b>' + markers[markerId].markerTitle + '</b></div>' +
			'<div>Uploaded by: ' + markers[markerId].ownerName + ' on ' + markers[markerId].recorded + '</div>' +
			'<div>Duration: ' + markers[markerId].duration + '</div>' +
			'<div>Video from <a href="http://www.youtube.com" target="_blank">Youtube</a>.</div>' +
			'</div>' +
		  	"<div style='margin:5px; background-color:#EFEFEF; height:120px; background-image:url(" + markers[markerId].thumb + "); background-repeat:no-repeat; background-position:center; overflow:hidden;'><div style='height:240px; background-image:url(images/icon_" + markers[markerId].markerType + ".png); background-repeat:no-repeat; background-position: 5px 5px'><a target='_blank' href=\"" + markers[markerId].url + "\"><img style='padding-top:15px;' src='/images/play.png' width='120' height'90' border='0' /></a></div></div>";

	markers[markerId].openExtInfoWindow(map, "custom_info_window_red", tab, {beakOffset: 0} ); 	
	
	markers[markerId]["listenersInfowindowclose"] = GEvent.addListener(map,"extinfowindowclose", function(){
			GEvent.removeListener(markers[markerId]["listenersInfowindowclose"]);
	});
};

function openPhoto(id,wMode){
	if(wMode == undefined) wMode = 0;
	addLayer(
		'<div id="markerWinAction" style="padding-bottom:10px;"><a href="javascript:browsePhotos(\'previous\',\'' + id + '\',\'' + markers[id].markerType + '\')">Previous</a> - <a href="javascript:browsePhotos(\'next\',\'' + id + '\',\'' + markers[id].markerType + '\')">Next</a> | <b><a href="javascript:removeOverlay();">Close</a></b></div>' +
		'<a href="' + markers[id].imageLink + '" target="_blank"><img src="' + markers[id].photoLarge + '" border="0" /></a>' +
		'<div style="padding-top:10px"><h1><a href="' + markers[id].imageLink + '" target="_blank">' + markers[id].markerTitle + '</a></h1></div>' +
		'<div style="padding-top:5px;"><b>By:</b> <a href="' + markers[id].photoStream + '" target="_blank">' + markers[id].ownerName + '</a></div>' +
		'<div><b>Tags:</b> ' + markers[id].tags + '</div>' +
		'<div style="padding-top:10px; font-size:10px;">' + markers[id].regMark + '</div>' +
		'<div id="markerWinAction"><a href="javascript:browsePhotos(\'previous\',\'' + id + '\',\'' + markers[id].markerType + '\')">Previous</a> - <a href="javascript:browsePhotos(\'next\',\'' + id + '\',\'' + markers[id].markerType + '\')">Next</a> | <b><a href="javascript:removeOverlay();">Close</a></b></div>',
		600,
		wMode
	);
}

function wikipedia(){
	if(wiki == 'no'){
		wiki = new GLayer("org.wikipedia.en");    
		map.addOverlay(wiki);
		$("legendBut_wikipedia").style.backgroundColor = "#EFEFEF";
	} else{
		map.removeOverlay(wiki);
		wiki = 'no';
		$("legendBut_wikipedia").style.backgroundColor = "#CCCCCC";
	}
}

function getPhotos(a){
	var markerType;
	if(a == "getFlickr"){
		//removePhotos("flickr");
	} else if(a == "getPanoramio"){
		//removePhotos("panoramio");
	} else if(a == "getYoutube"){
		//removePhotos("youtube");
	}
	if((a == "getYoutube" && $("youtubeUse").checked) || (a == "getFlickr" && $("flickrUse").checked) || (a == "getPanoramio" &&  $("panoramioUse").checked)){

		$("loadingPhotos").style.display = "";
		function completeAjax(request){
			if(a == "getFlickr"){
				//removePhotos("flickr");
				markerType = "flickr";
			} else if(a == "getPanoramio"){
				//removePhotos("panoramio");
				markerType = "panoramio";
			} else if(a == "getYoutube"){
				//removePhotos("youtube");
				markerType = "youtube";
			}
			eval(request.responseText);
			initializePhotoMarkers(ajaxMarkers,markerType);
			$("loadingPhotos").style.display = "none";
		}
		var mapRadius = Math.ceil(map.getBounds().getSouthWest().distanceFrom(map.getBounds().getNorthEast())/1000);
		var req = new Ajax.Request(gatewayURL, {   
			method: 'post',   
			parameters: 'a=' + a + '&minx=' + map.getBounds().getSouthWest().lng() + 
						'&miny=' + map.getBounds().getSouthWest().lat() + 
						'&maxx=' + map.getBounds().getNorthEast().lng() + 
						'&maxy=' + map.getBounds().getNorthEast().lat() + 
						'&youtubeTag=' + $("youtubeTags").value + 
						'&flickrTag=' + $("flickrTags").value + 
						'&panoramioTag=' + $("panoramioTags").value + 
						'&flickrUseAll=' + (($("flickrUseall").checked) ? "1" : "0") + 
						'&panoramioUseAll=' + (($("panoramioUseall").checked) ? "1" : "0") + 
						'&panoramioContextual=' + (($("panoramioContextual").checked) ? "1" : "0") + 
						'&flickrContextual=' + (($("flickrContextual").checked) ? "1" : "0") + 
						"&lat=" + map.getCenter().lat() + 
						"&lng=" + map.getCenter().lng() + 
						"&flickrId=" + $("flickrAccount").value + 
						"&panoramioId=" + $("panoramioAccount").value + 
						"&radius=" + mapRadius,
			onComplete: completeAjax
		});	

	} 
};

function getServerPhotos(a){
	var markerType;
	
	if((a == "getYoutube" && mapData["youtubeUse"]) || (a == "getFlickr" && mapData["flickrUse"]) || (a == "getPanoramio" &&  mapData["panoramioUse"])){

		$("loadingPhotos").style.display = "";
		function completeAjax(request){
			if(a == "getFlickr"){
				//removePhotos("flickr");
				markerType = "flickr";
			} else if(a == "getPanoramio"){
				//removePhotos("panoramio");
				markerType = "panoramio";
			} else if(a == "getYoutube"){
				//removePhotos("youtube");
				markerType = "youtube";
			}
			eval(request.responseText);
			initializePhotoMarkers(ajaxMarkers,markerType);
			$("loadingPhotos").style.display = "none";
		}
		var mapRadius = Math.ceil(map.getBounds().getSouthWest().distanceFrom(map.getBounds().getNorthEast())/1000);
		var req = new Ajax.Request(gatewayURL, {   
			method: 'post',   
			parameters: 'a=' + a + '&minx=' + map.getBounds().getSouthWest().lng() + 
						'&miny=' + map.getBounds().getSouthWest().lat() + 
						'&maxx=' + map.getBounds().getNorthEast().lng() + 
						'&maxy=' + map.getBounds().getNorthEast().lat() + 
						'&youtubeTag=' + mapData["youtubeTags"] + 
						'&flickrTag=' + mapData["flickrTags"] + 
						'&panoramioTag=' + mapData["panoramioTags"] + 
						'&flickrUseAll=' + ((mapData["flickrUseall"]) ? "1" : "0") + 
						'&panoramioUseAll=' + ((mapData["panoramioUseall"]) ? "1" : "0") + 
						'&panoramioContextual=' + ((mapData["panoramioContextual"]) ? "1" : "0") + 
						'&flickrContextual=' + ((mapData["flickrContextual"]) ? "1" : "0") + 
						"&lat=" + map.getCenter().lat() + 
						"&lng=" + map.getCenter().lng() + 
						"&flickrId=" + mapData["flickrAccount"] + 
						"&panoramioId=" + mapData["panoramioAccount"] + 
						"&radius=" + mapRadius,
			onComplete: completeAjax
		});	

	} 
};


/*function quickView(obj){
	var messageOverlay;
	var theCss;
	messageOverlay = document.createElement("div");
	messageOverlay.id = "quickView"+obj.id;
	messageOverlay.innerHTML = ((obj.markerType == "flickr" || obj.markerType == "panoramio" || obj.markerType == "youtube") ? "<img src='" + obj.thumb + "' width='60' height'60' style='padding:2px;' align='top' />" : "") + constrain(obj.markerTitle,30);
	theCss = "position:absolute; background-color:#FFFFFF; font-size:11px; font-weight:bold; padding:2px; border:1px solid #999999; filter: alpha(opacity=90); -moz-opacity: .90; left:" + (parseInt(map.fromLatLngToContainerPixel(obj.getLatLng()).x)+12) + "px; top:" + (parseInt(map.fromLatLngToContainerPixel(obj.getLatLng()).y)-12) + "px";
	messageOverlay.style.cssText = theCss;
	$("mapCanvas").appendChild(messageOverlay);
}*/

function browsePhotos(way,current,type){
	//find current
	var findIndex = 0;
	var allItems = new Array();
	var y = 0;
	var t = "";
		
	for(i in markers){
		if(i.indexOf(type) != -1){
			allItems[y] = {};
			allItems[y].id = i;
			allItems[y].date = markers[i].date; 
			y = y + 1;
	
		}
	}
	
	function sortDate(a,b){
		return (a.date - b.date);
	}
	allItems.sort(sortDate);

	for(i in allItems){
		if(current == allItems[i].id){ findIndex = parseInt(i); }
		t = t + " , " + allItems[i].id;
	}
	
	
	if(findIndex == 0) findIndex = 1;
	
	if(way == "previous"){
		findIndex = findIndex - 1;
	} else{
		findIndex = findIndex + 1;
	}
	
	if(typeof(allItems[findIndex]) != "undefined"){
		openPhoto(allItems[findIndex].id,1);
	} else{
		openPhoto(allItems[0].id,1);
	}
	
}

