var objects_array = new Array();
var building = new Array();

function after_build_func(){};
function do_nothing(){
	return;
}

function init_arrays(){
objects_array['user']= new Array();
objects_array['user']['items'] = new Array('name','loc','comment','gender');
objects_array['user']['loading_text'] = "Finding people...";
objects_array['user']['ajax_link'] = "/ajax/get_usermarkers.php";

objects_array['member']= new Array();
objects_array['member']['items'] = new Array('name','loc','shoutout','uid');
objects_array['member']['loading_text'] = "Finding people...";
objects_array['member']['ajax_link'] = "/ajax/get_membermarkers.php";


objects_array['photo']= new Array();
objects_array['photo']['items'] = new Array('uid','owner','name','description','loc');
objects_array['photo']['loading_text'] = "Finding albums...";
objects_array['photo']['ajax_link'] = "/ajax/get_photomarkers.php";


objects_array['place']= new Array();
objects_array['place']['items'] = new Array('name','loc','description');
objects_array['place']['loading_text'] = "Finding places...";
objects_array['place']['ajax_link'] = "/ajax/get_placesmarkers.php";

building['user']=false;
building['member']=false;
building['photo']=false;
building['place']=false;

}
init_arrays();
var map;
var winOnLoad = new Array();
var cnt=0;
var requesting;
var urlextra='';
var dontLoadNow;
var start_time;
var elapsed;
//function getMarkerHTML;

if(self.GIcon){
	var icon=new Array();
for(i=1;i<=11;i++) {
icon[i] = new GIcon();
icon[i].image = BASE_URL+"/images/icons/marker_"+i+".gif";
icon[i].iconAnchor = new GPoint(12, 5);
}
}


function statusMessage(str) {
	document.getElementById('statusBox').innerHTML = str;
}

function showAllMarkers(current) {
	for (var i=0; i<objects_array[current].length; i++) {
	  objects_array[current][i]["markerobj"].display(true);
	}
}

function writeDebug(string){
	if($('debug_text')){
		$('debug_text').value= $('debug_text').value + "\n" + string;
	}
}

function loadMarkers(current) {
	start_time = new Date();
 	 writeDebug("==============================\nStarted loading of markers: "+Date());

  if (dontLoadNow) {
		dontLoadNow = false;
		return ;
	}
	//alert('loading markers');
	// Delete any markers for objects_array[current] that are now outside the bounding box
	//var bounds = map.getBounds();
	var bounds = new GBounds();
		map.addControl(new GLargeMapControl());
		var boundsLatLng = map.getBounds();
		var aux = boundsLatLng.getSouthWest();
		bounds.minX = aux.lng();
		bounds.minY = aux.lat();

		var aux = boundsLatLng.getNorthEast();
		bounds.maxX = aux.lng();
		bounds.maxY = aux.lat();
	var remainingobjects_array = new Array();

	var count=0;
	//map.closeInfoWindow();

	for (var i=0; i<objects_array[current].length-3; i++) {
		if (objects_array[current][i]["lng"] < bounds.minX || objects_array[current][i]["lng"] > bounds.maxX || objects_array[current][i]["lat"] < bounds.minY ||  objects_array[current][i]["lat"] > bounds.maxY) {
			if (objects_array[current][i]["markerobj"]) {

				map.removeOverlay(objects_array[current][i]["markerobj"]);

				count++;
			}
		} else {
			index = remainingobjects_array.length;
			remainingobjects_array[index] = objects_array[current][i];
			//alert('ramain');
		}
	}

	remainingobjects_array['items'] = objects_array[current]['items'];
	remainingobjects_array['ajax_link'] = objects_array[current]['ajax_link'];
	remainingobjects_array['loading_text'] = objects_array[current]['loading_text'];
	objects_array[current] = remainingobjects_array;
	//window.status = 'removed '+count;


	if (requesting) {
		return false;
	}

	var addr = BASE_URL+objects_array[current]['ajax_link']+'?west='+bounds.minX+'&east='+bounds.maxX+'&south='+bounds.minY+'&north='+bounds.maxY;
	if(GROUP_ID){
		addr = addr+'&gid='+GROUP_ID;
	}

	addr += urlextra;
	//alert(addr);
	//document.write(addr);
	//document.debug.text.value=addr;
	var request = GXmlHttp.create();
	request.open("GET", addr, true);
	statusMessage(objects_array[current]['loading_text']);
	requesting = true;
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var elapsed = new Date() - start_time;
			writeDebug("XML received: "+Date()+" (elapsed: "+elapsed+"ms)");
			start_time = new Date();

			//var xmlDoc = request.responseXML;
			//if(xmlDoc && xmlDoc.documentElement){
			//var markers = xmlDoc.documentElement.getElementsByTagName("marker");
			//	for (var i=0; i<markers.length; i++) {
var htmlDoc = request.responseText;
				if(htmlDoc!='')
					var the_object = eval('(' + htmlDoc + ')');
			if(the_object && the_object.markers){
			var markers = the_object.markers;
			for (var i=0;i<markers.length-1;i++) {

					if (!inobjects_arrayList(markers[i].id,current)) {
					var nextitem = objects_array[current].length;
					objects_array[current][nextitem] = new Array();
					objects_array[current][nextitem]["id"] = markers[i].id;
					objects_array[current][nextitem]["icon"] = markers[i].icon;
					objects_array[current][nextitem]["lat"] = parseFloat(markers[i].lat);
					objects_array[current][nextitem]["lng"] = parseFloat(markers[i].lng);
					objects_array[current][nextitem]["image"] = markers[i].image;
					objects_array[current][nextitem]["type"] = current;
					for(j=0;j<objects_array[current]['items'].length;j++){
					objects_array[current][nextitem][objects_array[current]['items'][j]] = eval('(markers[i].'+objects_array[current]['items'][j]+')');

					}

					/*objects_array[current][nextitem]["name"] = markers[i].getAttribute("name");
					objects_array[current][nextitem]["online_state"] = decode(markers[i].getAttribute("online_state"));
					objects_array[current][nextitem]["loc"] = markers[i].getAttribute("loc");
					objects_array[current][nextitem]["comment"] = markers[i].getAttribute("comment");
					objects_array[current][nextitem]['arebuddies'] = markers[i].getAttribute("arebuddies");
					objects_array[current][nextitem]["gender"] = markers[i].getAttribute("gender");*/

					objects_array[current][nextitem]['built'] = false;
					}
				}
			}
			statusMessage('Drawing '+current+'(s) on the map...');
			buildMarkers(current);
		}
		requesting = false;
		delete request;
	}
	request.send(null);
	elapsed = new Date() - start_time;
			writeDebug("XML request sent: "+Date()+" (elapsed: "+elapsed+"ms)");
			start_time = new Date();

}

function stoppedBuilding(current){
	building[current]=false;
	statusMessage(''+objects_array[current].length+' '+current+'(s) on the map.');
	//alert('stopped '+current);
}

function buildMarkers(current) {
	var elapsed = new Date() - start_time;
	writeDebug("Started building of markers: "+Date()+" (elapsed: "+elapsed+"ms - XML process)");
	start_time = new Date();

	var count=0;
	building[current]=true;
	for (var i=0; i<objects_array[current].length; i++) {
		if (!objects_array[current][i]['built']) {
			count++;
			setTimeout("buildMarker_"+current+"(objects_array['"+current+"']["+i+"]);",i*100);
			//buildMarker(objects_array[current][i]);
		}
	}
	setTimeout("stoppedBuilding('"+current+"')",(count+1)*500);

	//statusMessage('Builded '+count+' buddie(s).');
	after_build_func();
	after_build_func=do_nothing;
	var elapsed = new Date() - start_time;
	writeDebug("Finished building of markers: "+Date()+" (elapsed: "+elapsed+"ms)");
	start_time=null;
}

function removeAllMarkers() {
	/*for (var i=0; i<objects_array[current].length; i++) {
			if (objects_array[current][i]["markerobj"]) {
				map.closeInfoWindow();
				map.removeOverlay(objects_array[current][i]["markerobj"]);
			}
	}*/
	start_time = new Date();
	writeDebug("----------------\nStarted clearing of markers: "+Date());


	map.closeInfoWindow();

	map.clearOverlays();
	init_arrays();
	var elapsed = new Date() - start_time;
	writeDebug("Finished removing of markers: "+Date()+" (elapsed: "+elapsed+"ms)");
	start_time=null;

}

function buildMarker_user(objectInfo) {
	if(!objectInfo || !inobjects_arrayList(objectInfo["id"],'user')) return;
	var point = new GLatLng(objectInfo['lat'], objectInfo['lng']);


if (objectInfo['gender'] == 'female') {
		var marker = new GMarker(point, icon[1]);
	} else {
		var marker = new GMarker(point, icon[2]);

	}

	var html = getMarkerHTML_user(objectInfo);
	objectInfo['built'] = true;
	GEvent.addListener(marker, "click", function() {
		map.openInfoWindowHtml(point, html);
		GEvent.addListener(map.getInfoWindow(), "closeclick", resumeBaloon);
		 show_msg_popups = false;
	});
	objectInfo['markerobj'] = marker;
	map.addOverlay(marker);
	//marker.display(true);
}

function buildMarker_member(objectInfo) {
	if(!objectInfo || !inobjects_arrayList(objectInfo["id"],'member')) return;
	var point = new GLatLng(objectInfo['lat'], objectInfo['lng']);


		var marker = new GMarker(point, icon[objectInfo['icon']]);

	var html = getMarkerHTML_member(objectInfo);
	objectInfo['built'] = true;
	GEvent.addListener(marker, "click", function() {
		map.openInfoWindowHtml(point, html);
		GEvent.addListener(map.getInfoWindow(), "closeclick", resumeBaloon);
		 show_msg_popups = false;
	});
	objectInfo['markerobj'] = marker;
	map.addOverlay(marker);
	//marker.display(true);
}


function inobjects_arrayList(id,current) {
	for (var i=0; i<objects_array[current].length; i++) {
		if (objects_array[current][i]["id"] == id) {
			return true;
		}
	}
	return false;
}


function getMarkerHTML_user(objectInfo) {

	html ='';
	html = html + '';


html += '<table border="0" cellspacing="0" cellpadding="0" width="200"><tr>';

	if (objectInfo['image'] != "0") {
		html += '<td valign="top" width="80"><a href="user_profile.php?gid='+GROUP_ID+'&uid='+objectInfo['id']+'" title="Click for my profile"><img src="'+BASE_URL+'/images/userimages/'+objectInfo['id']+'/profile_80.jpg" border="0"></a></td>';
	}
	html += '<td style="padding-left:3px;font-size:9px;color:#444444;white-space: normal;" valign="top"><a href="mypage.php?id='+objectInfo['id']+'" title="Click for my page">'+objectInfo['name']+'</a> <br>	 <a href="mymessages.php?recipient='+objectInfo['id']+'" title="Send a message">Send a message</a><br><span>('+objectInfo['loc']+')</span><br><br><div style="width:120px">'+objectInfo['comment']+'</div></td></tr></table>';

	return html;
}


function getMarkerHTML_member(objectInfo) {

	html ='<div id="'+objectInfo['name']+'">';


	if(objectInfo['uid']){
	html = html + '<a href="user_profile.php?uid='+objectInfo['uid']+'" title="My page">'+objectInfo['name']+'</a><br><span style="color:dimgray" style="font-size:9px">('+objectInfo['loc']+')</span><br><br>';
	} else {
			html = html + ''+objectInfo['name']+'<br><span style="color:dimgray" style="font-size:9px">('+objectInfo['loc']+')</span><br><br>';
	}


	html += '<table border="0" cellspacing="0" cellpadding="0" width="200"><tr>';

	if (objectInfo['image'] == "1") {
		html += '<td valign="top" width="80"><img src="'+BASE_URL+'/images/groupimages/'+GROUP_ID+'/'+objectInfo['id']+'_80.jpg" border="0"></a></td>';
	} else if (objectInfo['image'] == "2") {
		html += '<td valign="top" width="80"><img src="'+BASE_URL+'/images/userimages/'+objectInfo['id']+'/profile_80.jpg" border="0"></a></td>';
	}
	html += '<td style="padding-left:3px;font-size:9px;color:#444444;white-space: normal;" valign="top"><div style="width:120px">'+objectInfo['shoutout']+'</div></td></tr></table></div>';

	return html;
}



function buildMarker_place(objectInfo) {
	if(!objectInfo || !inobjects_arrayList(objectInfo["id"],'place')) return;
	var point = new GLatLng(objectInfo['lat'], objectInfo['lng']);


		var marker = new GMarker(point, icon[objectInfo['icon']]);

	var html = getMarkerHTML_place(objectInfo);
	objectInfo['built'] = true;
	GEvent.addListener(marker, "click", function() {
		map.openInfoWindowHtml(point, html);
		GEvent.addListener(map.getInfoWindow(), "closeclick", resumeBaloon);
		 show_msg_popups = false;
	});
	objectInfo['markerobj'] = marker;
	map.addOverlay(marker);
	//marker.display(true);
}

function getMarkerHTML_place(objectInfo) {

	html ='<div id="'+objectInfo['name']+'">';


	html = html + ''+objectInfo['name']+'<br><span style="color:dimgray" style="font-size:9px">('+objectInfo['loc']+')</span><br><br>';


	html += '<table border="0" cellspacing="0" cellpadding="0" width="200"><tr>';

	if (objectInfo['image'] != "0") {
		html += '<td valign="top" width="80"><img src="'+BASE_URL+'/images/placeimages/'+objectInfo['id']+'_80.jpg" border="0"></a></td>';
	}
	html += '<td style="padding-left:3px;font-size:9px;color:#444444;white-space: normal;" valign="top"><div style="width:120px">'+objectInfo['description']+'</div></td></tr></table></div>';

	return html;
}


function buildMarker_photo(objectInfo) {
	if(!objectInfo || !inobjects_arrayList(objectInfo["id"],'photo')) return;
	var point = new GLatLng(objectInfo['lat'], objectInfo['lng']);


		var marker = new GMarker(point, icon[11]);

	var html = getMarkerHTML_photo(objectInfo);
	objectInfo['built'] = true;
	GEvent.addListener(marker, "click", function() {
		map.openInfoWindowHtml(point, html);
		GEvent.addListener(map.getInfoWindow(), "closeclick", resumeBaloon);
		 show_msg_popups = false;
	});
	objectInfo['markerobj'] = marker;
	map.addOverlay(marker);
	//marker.display(true);
}

function getMarkerHTML_photo(objectInfo) {

	html ='';


	html = html + ''+objectInfo['name']+'<br>';


	html += '';

	if (objectInfo['image'] != "0") {
		html += '<img src="'+BASE_URL+'/images/userimages/'+objectInfo['uid']+"/photos/"+objectInfo['id']+'_150.jpg" border="0">';
	}
	html += '';

	return html;
}

function getMarkerHTML_album(objectInfo) {
	html ='<div id="'+objectInfo['name']+'"><a href="photo_album.php?id='+objectInfo['id']+'" title="Click for details">'+objectInfo['name']+'</a> (owner: <a href="user_profile.php?uid='+objectInfo['uid']+'" title="Owner profile">'+objectInfo['owner']+'</a>)<br>';


html += '<table border="0" cellspacing="0" cellpadding="0" width="200"><tr>';

	if (objectInfo['image'] != "0") {
		html += '<td valign="top" width="80"><a href="photo_album.php?id='+objectInfo['id']+'" title="Click for details"><img src="images/userimages/'+objectInfo['uid']+'/photo_albums/'+objectInfo['id']+'/'+objectInfo['image']+'_map.jpg" border="0"></a></td>';
	}
	html += '<td style="padding-left:3px;font-size:9px;color:#444444;white-space: normal;" valign="top"><div style="width:120px">'+objectInfo['description']+'</div></td></tr></table></div>';

	return html;
}


function getMarkerHTML_event(objectInfo) {
	html ='<div id="'+objectInfo['name']+'"><a href="event.php?eid='+objectInfo['id']+'" title="Click for details">'+objectInfo['name']+'</a> (owner: <a href="user_profile.php?uid='+objectInfo['uid']+'" title="Owner profile">'+objectInfo['owner']+'</a>)<br><span style="color:dimgray" style="font-size:9px">('+objectInfo['loc']+' on '+objectInfo['date']+')</span><br><br>';


html += '<table border="0" cellspacing="0" cellpadding="0" width="200"><tr>';

	if (objectInfo['image'] == "1") {
		html += '<td valign="top" width="80"><a href="event.php?eid='+objectInfo['id']+'" title="Click for details"><img src="images/userimages/'+objectInfo['uid']+'/events/'+objectInfo['id']+'/80.jpg" border="0"></a></td>';
	}
	html += '<td style="padding-left:3px;font-size:9px;color:#444444;white-space: normal;" valign="top"><div style="width:120px">'+objectInfo['comment']+'</div></td></tr></table></div>';


	if (objectInfo['isguest'] == 'yes') {
		html += '<br><br>You are invited.';
	} else {
		//html += '<br><a href="javascript:buddyRequest(\''+objectInfo['id']+'\')" style="font-size:10px">Wanna be my Buddy?</a>';
	}
	return html;
}


function resumeBaloon() {

	show_msg_popups = true;
	//alert('resumed!');


}

function displayMarkerById(id,current) {
	for (var i=0; i<objects_array[current].length; i++) {
		if (objects_array[current][i]["id"] == id) {
		var point = new GLatLng(objects_array[current][i]["lat"], objects_array[current][i]["lng"]);
		if(current=='user'){
			getMarkerHTML=getMarkerHTML_user;
		}

		var html = getMarkerHTML(objects_array[current][i]);
		dontLoadNow = true;
		map.openInfoWindowHtml(point, html);

		GEvent.addListener(map.getInfoWindow(), "closeclick", resumeBaloon);

		return true;
		}
	}

	return false;
}

function displayMarkerByIndex(index,current) {
	var point = new GLatLng(objects_array[current][index]["lat"], objects_array[current][index]["lng"]);
	if(current=='user'){
			getMarkerHTML=getMarkerHTML_user;
		}
var html = getMarkerHTML(objects_array[current][index]);
	dontLoadNow = true;


	map.openInfoWindowHtml(point, html);

		GEvent.addListener(map.getInfoWindow(), "closeclick", resumeBaloon);

	//document.location.hash='buddymap';
	//objects_array[current][index]['name'];
}




