var markers = new Array();	// Store currently displayed markers
var popup;

//  variables below are set in index.html
var uId; 					
var statementLat; 
var statementLng; 
var shouldOpenStatement; 	
var shouldOpenRandom;

function firePositionChangeEvents(){	
	var wizard = document.getElementById('wizard');
	if(wizard==undefined || wizard.style.display == 'none'){
		getOverlay();		
	}
}

function getOverlay(){
	var bounds = map.getBounds();
	var lat0 = bounds.getSouthWest().lat() + (0.1 * (bounds.getNorthEast().lat() - bounds.getSouthWest().lat()) );
	
	var lat1 = bounds.getNorthEast().lat() - (0.1 * (bounds.getNorthEast().lat() - bounds.getSouthWest().lat()) );
	var lng0 = bounds.getSouthWest().lng() + (0.1 * (bounds.getNorthEast().lng() - bounds.getSouthWest().lng()) );
	
	var lng1 = bounds.getNorthEast().lng() - (0.1 * (bounds.getNorthEast().lng() - bounds.getSouthWest().lng()) );	
	var zoom = map.getZoom();
	
	var url = "/xml/markers/?lat0=" + lat0 + "&lat1=" + lat1 + "&long0=" + lng0 + "&long1=" + lng1 + "&zoom=" + zoom
	if (uId){ url += '&id=' + uId;}
	var request = YAHOO.util.Connect.asyncRequest('GET', url, {success:placeOverlay, failure:null});	
}

function placeOverlay(o){

	var resXML = o.responseXML;
	var rootNode = resXML.getElementsByTagName('overlay')[0];
	if (!rootNode) 
		return;
	
	// Clear current markers 
	for (var i=0; i<markers.length; i++){
		if(markers[i] != undefined){
			map.removeOverlay(markers[i]);
		}
	}
	markers = new Array();
	
	// Loop through placemarks
	for (var i=0; i < rootNode.childNodes.length; i++){
		
		if(rootNode.childNodes[i].nodeName == 'placemark'){
			var placemark = rootNode.childNodes[i];
			
			// Add properties needed for popup to the marker object
			popup 			= new Array();
			popup['id']		= placemark.getAttribute('id');
			popup['title'] 	= placemark.getElementsByTagName('title')[0].firstChild.nodeValue;
			popup['date']  	= placemark.getElementsByTagName('date')[0].firstChild.nodeValue;
			popup['descr'] 	= placemark.getElementsByTagName('description')[0].firstChild.nodeValue;

			popup['avatar']	= placemark.getElementsByTagName('avatar')[0].firstChild.nodeValue;
			/*
			popup['friends'] = new Array();
			var friendsContainer = placemark.getElementsByTagName('friends')[0];
			var friends = friendsContainer.getElementsByTagName('friend');

			for( var l = 0; l<friends.length ; l++){
				var id = friends[l].getAttribute('id');
				var friendName 	= friends[l].firstChild.nodeValue; 
				popup['friends'] .push(id + '|' + friendName);
			}
*/
			// Create Marker 
			var iconType= placemark.getAttribute('icontype');
			var lat 	= parseFloat(placemark.getAttribute('lat'));
			var lng 	= parseFloat(placemark.getAttribute('long'));
			var cIcon	= new CustomIcon(iconType);
			var point	= new GLatLng(lat,lng);
			var marker 	= new GMarker(point, {icon:cIcon, title:popup.title});
			
			// We store all marker properties so they can be accessed later (when opening our custom popup)
			marker.popup = popup;	
			// Add clickEvent to marker, add it to the map (and to markers array to be able to access it later)
			GEvent.addListener(marker,  "click", gotoPopup);
			map.addOverlay(marker);
			markers.push(marker);
		}
	}	

	if(shouldOpenStatement ){
		// We run this after placement of the overlay to make sure all markers are loaded
		findAndOpenPopup( uId );
		shouldOpenStatement = false;
	}
	if(shouldOpenRandom){
		openRandomPopup();	
		shouldOpenRandom = false;
	}
	
}

function gotoPopup(){
	var clickedMarker = this;
	
	if(this.getLatLng() != map.getCenter()){
		// Set center of map to icon position, then show the popup
		var handler = GEvent.addListener(map, "moveend", function(){
			showPopup(clickedMarker, handler);
			
		});
		map.panTo(this.getLatLng());
	}
	showPopup(clickedMarker, null );
}

// If statement is assigned we should open that popup
function findAndOpenPopup(id, noZoom){
	if(!id){
		return false;
	}
	
	for(var i=0; i<markers.length; i++ ){
		if(markers[i].popup.id == id){
			
			var point = markers[i].getLatLng();

			if(!noZoom){
				map.setCenter(point);
				map.setZoom(18);
			}
			GEvent.trigger(markers[i],  'click');
			break;
		}
	}
	
}

function showPopup(marker,handler){
	// Prevent popup to show in wrong position
	var mapCenter = map.fromLatLngToDivPixel(map.getCenter());
	var currentMarkerPos = map.fromLatLngToDivPixel(marker.getLatLng());
	if(mapCenter.equals(currentMarkerPos) == true ){
		map.msgPopup.show(marker);	
		if(handler)
			GEvent.removeListener(handler);
	}
}

function openRandomPopup(){
	var randomItem = Math.floor( Math.random()*maxPointers );
	if(markers[randomItem])
		findAndOpenPopup(markers[randomItem].popup.id, true);
	
}

