
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//	(VALUE)
//	mapHandler.div 									=	mapcontainer
//	mapHandler.size								=	size of the map - small , medium , large
//	mapHandler.startPosition					=	startposition of the map
//	mapHandler.dialogString					=	String for launching dialog 
//	mapHandler.setupMode					=	tabControl - basic , normal , all
//	mapHandler.targets							= current set of  targets with data, stored by UserID
// mapHandler.activeTargets				= array for storing the active targets UserIDs 
//
//	FUNCTION
//	mapHandler.initialize							=	setup the maphandler and GMaps functions
//	mapHandler.addTestUsers 			= function for testing (removed)
//	mapHandler.fit 									=	adjust map placement and zoom to fit markers
//	mapHandler.resetBounds				=	reset the current bounds
//	mapHandler.makeDialogString		= make string for dialog
//	mapHandler.initializeDialog				=	configure the dialog before open
//	mapHandler.getAdress 					=	get the current address using reverse geocoding 
//																		(calls mapHandler.arrayAddressString and then mapHandler.ripAdress) 	
// 	mapHandler.arrayAddressString 	= array the json return
// 	mapHandler.ripAdress 						= rip the correct address ("RipReturnOkänd" value on fail)
//	mapHandler.checkUsers					=	check if target has already been added
//  mapHandler.addTarget 					= add a new target
//	mapHandler.addStoredMarker		= add fetched marker (calls mapHandler.addStoredMarkerCallBack)
//	mapHandler.addStoredMarkerCallBack	=	handle the fetched markers once geocoding is complete
//	mapHandler.addMarker 					= adds single marker and draws it on map
// 	mapHandler.addMarkerCallBack	=  callback for addmarker once geocoding is complete
//	mapHandler.drawSingleMarkerAndFrame = add a marker with frame and optional radiuscircle (if  set to true)
//	mapHandler.checkAndAddAndFit	=	check which markerfunctions to add and fit the map
//																		(called to add the clickfunctions for mapHandler.addStoredMarker)
//  mapHandler.addMarkerFunctions 	= add all the marker click events for a target
//	mapHandler.displayText 					=	hide / fade in function for marker (not used?)
//  mapHandler.drawAll 							= clears the map and draws ALL markers and optional circles (if  set to true)
//	mapHandler.customMarker 				= set custom marker out of a point
//	mapHandler.frameMarker					=	make frame for marker out of MARKER
//  mapHandler.drawCircle  					= returns a GPolygon
//	mapHandler.clearAll							=	clears targets and activeTargets


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

mapHandler = new Object();

//////////////////////////////////////////////////////////////////

mapHandler.initialize = function(setSize , setupMode, addTestUsers, startPosition )
{
if (GBrowserIsCompatible()) { 

	mapHandler.size= setSize.toLowerCase() || "medium";
	mapHandler.setupMode=  setupMode.toLowerCase()  || "normal" ;
	mapHandler.addTestUsers =  addTestUsers || false;
	mapHandler.start = startPosition || new GLatLng(59.3076, 18.0124);
	mapHandler.geocoder = new GClientGeocoder();
	mapHandler.bounds = new GLatLngBounds();

	// Not used anymore
	mapHandler.statusPictureSize = 50;
	
	mapHandler.GGeoStatusError = {
	"400": "BAD_REQUEST",
	"500": "SERVER_ERROR",
	"601": "MISSING_QUERY",
	"602": "UNKNOWN_ADDRESS",
	"603": "UNAVAILABLE_ADDRESS",
	"604": "UNKNOWN_DIRECTIONS",
	"610": "BAD_KEY",
	"620": "TOO_MANY_QUERIES"
	 };
	
	mapHandler.geocoder.setBaseCountryCode("SE");
	
	mapHandler.makeDialogString();
	mapHandler.initializeDialog();

	goto('tabFriends');
	dialog.open();
	$("#loading").hide();

	
	mapHandler.map = new GMap2(mapHandler.div);	
	 _mPreferMetric=true;
    mapHandler.map.setCenter(mapHandler.start , 10);
	mapHandler.map.setUIToDefault();

	// Contains all the targets and their markers
	mapHandler.targets = new Object();
	mapHandler.targets = [];
	// Contains the userIDs of all the targets.
	mapHandler.activeTargets = new Array();
		
		
	if(mapHandler.addTestUsers)
		mapHandler.setUpTestUsers();
	}
    else {
      alert("Not compatible with this browser");
			}						
	}
	
//////////////////////////////////////////////////////////////////

mapHandler.addTestUsers = function(){
};

//////////////////////////////////////////////////////////////////

mapHandler.fit = function(){

	// changed to centre and zoom to show all markers and circle.
	mapHandler.map.setZoom((mapHandler.map.getBoundsZoomLevel(mapHandler.bounds)));
	mapHandler.map.panTo(mapHandler.bounds.getCenter()); 
};

//////////////////////////////////////////////////////////////////

mapHandler.resetBounds = function(){
mapHandler.bounds = new GLatLngBounds();
};

//////////////////////////////////////////////////////////////////
	
mapHandler.makeDialogString = function (){

var html = 	'<div id="map-holder"></div>' +
			'<div id="block-history">' +
			'    <h2>Sökningar</h2>' +
			'    <ul></ul>' +
			'</div>' +
			'<div id="block-current">' +
			'    <h2>Visar</h2>' +
			'    <div class="details"></div>' +
			'</div>' +
			'<div id="block-message">' +
			'    <h2>Skicka meddelande</h2>' +
			'    <form id="form-send-message" action="' + window.location + '" method="post">' +
			'        <input type="hidden" name="uid" value="" />' +
			'        <div class="field">' +
			'            <input id="type-pm" type="radio" name="type" value="pm" checked="checked" /><label for="type-pm">PM</label>' +
			'            <input id="type-sms" type="radio" name="type" value="sms" /><label for="type-sms">SMS (5 poäng/SMS)</label>' +
			'        </div>' +
			'        <div class="field">' +
			'            <textarea id="field-message" name="message" onkeyup="countchars(\'#field-message\', \'#char-count\')"></textarea>' +
			'        </div>' +
			'        <div class="buttons">' +
			'            <p id="char-count"></p>' +
			'            <a class="button" id="button-send-message" href="' + window.location + '" onclick="send_message(); return false;"><span>Skicka</span></a>' +
			'        </div>' +
			'    </form>' +
			'</div>';

// Build the string for launching the dialog.  Switch checks mapHandler.setupMode. Basic show only Friends tab , others shows
// all tabs

var mapstring = '<div id="map" style="position: relative; top: -30px; left: 5px;" </div>'
var navHomeString 	=  '<li class="left">&nbsp;<a href="#" title="Hem" onclick="goto(\'tabHome\'); return false"><img src="/img/icons/mainmenu_home.png" width="16"  height="13" alt="" /></a>&nbsp;&nbsp;<img src="/img/mainmenu_divider.png" width="5" height="8" alt="" /></li> ' 
var tabHomeString 		=		'<div id="tabHome" class="container"> '+ 
													'<div class="mainleft_box">'+ 
													'<h1>HEM</h1> '+
													'<div id="hem" class="mainleft_boxcontent">'+
													'</div> '+
													'<div class="mainleft_boxbottom"></div>'+ 
													'</div>'+
												 '</div>'
var navFriendsString	= '<li class="left">&nbsp;<a href="#"  title="VÄNNER" onclick="goto(\'tabFriends\'); return false">VÄNNER&nbsp;</a>&nbsp;&nbsp;<img src="/img/mainmenu_divider.png" width="5" height="8" alt="" />  </li> '
var tabFriendsString	=			'<div id="tabFriends" class="container"> '+						
														'<div class="mainleft_box">'+ 
														'<h1>VÄNNER</h1> '+
														'<div id="friends" class="mainleft_boxcontent">'+
														'<ul id="list"></ul>'+
														'</div> '+
														'<div class="mainleft_boxbottom"></div>'+ 
													'</div>' +
													
													'<div class="mainleft_box">'+ 
														'<h1>STATUS</h1> '+
														'<div id="status" class="mainleft_boxcontent">'+
														'<div id="messageBOX"></div>'+		
														'</div> '+
														'<div class="mainleft_boxbottom"></div>'+ 
														'</div>'+
													'</div>'
var navSearchString	= '<li class="left">&nbsp;<a href="#" title="SÖK" onclick="goto(\'tabSearch\'); return false">SÖK&nbsp;</a>&nbsp;&nbsp;<img src="/img/mainmenu_divider.png" width="5" height="8" alt="" /> </li> '
var tabSearchString	=			'<div id="tabSearch" class="container"> '+
														'<div class="mainleft_box">'+ 
														'<h1>SÖK</h1> '+
														'<div id="search" class="mainleft_boxcontent">'+
														
														'<form action="javascript:alert(\'No deal\');> '+
														'<input type="hidden" name="" value="" id="">'+
														'<fieldset>'+
														'<legend>Positionera Nummer</legend>'+
														'<div class="error" style="display:none;"></div>'+
														'<div class="input">'+
														'<label for="Mobilnummer">Mobilnummer</label>'+
														'<input type="text"  id="inMobilnummer" value="07">'+
														'</div>'+
														'<input type="button" value="Positionera" onclick="DemoPosition()" title="Positionera" />     '+
														'</fieldset>'+
														'</form>'+
														
														'<form action="javascript:alert((\'No deal\'));>'+
														'<input type="hidden" name="" value="" id="" >'+
														'<fieldset>'+
														'<legend>Sök efter Plats</legend>'+
														'<div class="error" style="display:none;"></div>'+
														'<div class="input">'+
														'<label for="plats">Plats</label>'+
														'<input type="text" name="plats" id="plats" value="">'+
														'</div>'+
														'<div class="input">'+
														'<label for="adress">Adress</label>'+
														'<input type="text" name="adress" id="adress" value="">'+
														'</div>'+
														'<button>SÖ–K</button>'+
														'</fieldset>'+
														'</form>'+
														
														'</div> '+
														'<div class="mainleft_boxbottom"></div>'+ 
														'</div>'+
														'<div class="mainleft_box">'+ 
														'<h1>STATUS</h1> '+
														'<div id="statusSearch" class="mainleft_boxcontent"></div> '+
														'<div class="mainleft_boxbottom"></div>'+ 
														'</div>'+
													'</div>'
var navHistoryString	= '<li class="left">&nbsp;<a href="#" title="HISTORIK" onclick="goto(\'tabHistory\'); return false">HISTORIK&nbsp;</a></li> ' 
var tabHistoryString	='<div id="tabHistory" class="container"> '+
												'<div class="mainleft_box">'+ 
												'<h1>HISTORIK</h1> '+
												'<div id="historik" class="mainleft_boxcontent">'+
												'</div> '+
												'<div class="mainleft_boxbottom"></div>'+ 
												'</div>'+			
											'</div>'
	
switch(mapHandler.setupMode)
		{
		// MODES ???
			case 'basic':
				navHomeString ='';	navSearchString ='';navHistoryString = '';
				tabHomeString = '';	tabSearchString = '';tabHistoryString = ''	;				
				break;
			case 'full':
			case 'normal':
			default : ;	
		}
				
/*mapHandler.dialogString = '<div id="navigation" style="position: relative; top: -40px;"> ' +
						' <div class="border-left"></div> ' +
						'	<ul class="main"> ' +
						 navHomeString +
						 navFriendsString +
						 navSearchString +
						 navHistoryString +
						'	<li class="left">&nbsp;</li> </ul> ' +
						'	<div class="border-right"></div> '+
						'</div>'+
						'<div id="mainleft" style="position: relative; top: -30px;"> '+ 
						tabHomeString +
						tabFriendsString +
						tabSearchString +
						tabHistoryString +							
						'</div>'		 +
						mapstring;*/
//mapHandler.dialogString = '<div id="map-info"></div><div id="map-holder" style="position: relative; top: -30px; left: 5px;"></div>';
mapHandler.dialogString = html;
};
	
///////////////////////////////////////////////////////////////////
	
mapHandler.initializeDialog = function()
{
//			set the size of the dialog compared to all available space. Also set the statusbox. 

			var statusSize = 200;
			var setupDividerWidth =  3;
			var setupDividerHeight= 4;
			
		switch(mapHandler.size)
		{
			case 'small':
			var statusSize = 150;
			var setupDividerWidth =  2;
			var setupDividerHeight= 3;
				break;	
			case 'large':
			var setupDividerWidth =  4;
			var setupDividerHeight= 5;
			break;
			case 'medium':
			default : 		
		}

	dialog.init(mapHandler.dialogString, '', '', 998, 645);
	
	// Cannot be selected in jquery and then manipulate...
	mapHandler.div = document.getElementById("map-holder");
						
	$(mapHandler.div).width(744); 
	$(mapHandler.div).height(612);

	//$("#status").height((statusSize));
	//$("#friends").height(  ($(window).height()  - ($(window).height() /setupDividerHeight) - (140 + statusSize )));
	
	switch(mapHandler.setupMode)
		{
		// MODES ???
			case 'basic':		
				break;
			case 'full':
			case 'normal':
			default : 
			$("#hem").height(  ($(window).height()  - ($(window).height() /setupDividerHeight) - (85) 	));
			$("#search").height(  ($(window).height()  - ($(window).height() /setupDividerHeight) - (140 + statusSize )));
			$("#statusSearch").height((statusSize));
			$("#historik").height(  ($(window).height()  - ($(window).height() /setupDividerHeight) - (85)));
		}															
};

/*
optimized
*/

mapHandler.initializeDialogue = function() {
	
};

//////////////////////////////////////////////////////////////////

mapHandler.getAdress = function(data){
	// data.Status.code 200 is success. 
	if (!data || data.Status.code != 200) 
		return ('Error: ' +  mapHandler.GGeoStatusError [data.Status.code]);
	else
		{
		// closest match is first placemark returned.
		place = data.Placemark[0];
		// array the json and then rip the adress.
		return (mapHandler.ripAdress(mapHandler.arrayAddressString(place.AddressDetails)));
		}
};

////////////////////////////////////////////////////////////////

mapHandler.arrayAddressString = function(feature) {
  var theArray = new Array();
  for (var key in feature) {
    if (feature[key] instanceof Array) {
      theArray.push(key);  theArray.push(feature[key][0]);
    } else if (feature[key] instanceof Object) {
      theArray = theArray.concat(mapHandler.arrayAddressString(feature[key]));
    } else {
      theArray.push(key);  theArray.push(feature[key]);
	}
  }
  return theArray;
};
  
////////////////////////////////////////////////////////////////
  
mapHandler.ripAdress = function(theArray){
/*check the arrayed json return for match according to searchprio. Returns if match.

Geocoder for the address of Google's headquarters example contains:
  "name": "1600 Amphitheatre Parkway, Mountain View, CA, USA",
  "Status": 
    "code": 200,
    "request": "geocode"
 
  "Placemark": [
    {
      "address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
      "AddressDetails": {
        "Country": {
          "CountryNameCode": "US",
          "AdministrativeArea": {
            "AdministrativeAreaName": "CA",
            "SubAdministrativeArea": {
              "SubAdministrativeAreaName": "Santa Clara",
              "Locality": {
                "LocalityName": "Mountain View",
                "Thoroughfare": {
                  "ThoroughfareName": "1600 Amphitheatre Pkwy"
                },
                "PostalCode": {
                  "PostalCodeNumber": "94043"
        
*/
searchPrio=new Array ("ThoroughfareName","LocalityName","SubAdministrativeArea","PostalCodeNumber");
  		for(var a=0 ; a< searchPrio.length ; a++ ){
				for(b=0 ; b < (theArray.length) ; b++ ){
				// ThoroughfareName sometimes returns a number. Checks if that is the case. If it is throughfare is ignored.
					if(    (searchPrio[a] == theArray[b])	&&    !((searchPrio[a] == 'ThoroughfareName') && !(isNaN(theArray[b + 1]) ))	) {
						// If match is PostalCode then that text is added to response
						if(searchPrio[a] == "PostalCodeNumber")
							return('Postkod: ' + theArray[b + 1]);
						return(theArray[b + 1]);
						}
					}
				}
// if no match is made in searchprio.
return ('RipReturnOkänd');			
};
  
///////////////////////////////////////////////////////////////////

mapHandler.checkUsers = function(target_id){
for(var tango in mapHandler.activeTargets)
{
	if(mapHandler.activeTargets[tango] == target_id)
		return true;
}
return false;
};

mapHandler.userExists = function(target_id) {
	for(var i in mapHandler.activeTargets) {
		if(mapHandler.activeTargets[i] == target_id) {
			return true;
		}
	}
	return false;
}

///////////////////////////////////////////////////////////////////

mapHandler.addTarget = function(target_id) {
if(target_id)
	{

	mapHandler.targets[target_id] = new Object();	
	//Use for image?
	//mapHandler.targets[target_id].image = new Object();
	mapHandler.targets[target_id].markers = [];
	mapHandler.targets[target_id].GetLocationResult = [];
	mapHandler.targets[target_id].circles = [];

	mapHandler.activeTargets.push(target_id);
	}
else
	alert("Cannot add user - Missing target_id!");
};

///////////////////////////////////////////////////////////////////

mapHandler.addStoredMarker= function(data){

		// finds address first
			jQuery.getJSON('http://maps.google.com/maps/geo?q=' + data.latitude + ',' +  data.longitude + '&output=json&oe=utf8\&sensor=false&key=ABQIAAAAQYTs0Am4zpghLCHA4P_adhQXwBLGIGbcZioHZvIGUiaAN1KTzxSiqDIlU5JKhSSjdLR7yxpVrr8oYg&callback=?', 
			function(data2){ 
				// Call once complete
				mapHandler.addStoredMarkerCallBack(data, data2);
				}
			);
};


///////////////////////////////////////////////////////////////////

mapHandler.addStoredMarkerCallBack = function( data, data2){
 
var currentTime = new Date(data.timestamp*1000);
var year = currentTime.getFullYear();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var hours   = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();

if (month < 10)   month   = "0" + month;
if (day < 10)   day   = "0" + day;
if (hours < 10)   hours   = "0" + hours;
if (minutes < 10)   minutes   = "0" + minutes;
if (seconds < 10)   seconds   = "0" + seconds;

var arrayPosition = mapHandler.targets[data.target_id].GetLocationResult.length;
	

	mapHandler.targets[data.target_id].GetLocationResult[arrayPosition] = new Object();
	mapHandler.targets[data.target_id].GetLocationResult[arrayPosition].latitude = (+data.latitude);
	mapHandler.targets[data.target_id].GetLocationResult[arrayPosition].longitude = (+data.longitude);
	mapHandler.targets[data.target_id].GetLocationResult[arrayPosition].accuracy = (+data.accuracy);
	mapHandler.targets[data.target_id].GetLocationResult[arrayPosition].timestamp =  (year + "-" + month + "-" + day + " " +  hours + ":" + minutes + ":" + seconds);
	
	mapHandler.targets[data.target_id].GetLocationResult[arrayPosition].closeTo =  mapHandler.getAdress(data2);
	
	
var punkt = new GLatLng( data.latitude , data.longitude);
mapHandler.targets[data.target_id].markers[arrayPosition] = mapHandler.customMarker(punkt , data.target_id );
mapHandler.targets[data.target_id].circles[arrayPosition] = mapHandler.drawCircle(punkt , data.accuracy);

mapHandler.drawSingleMarkerAndFrame(data.target_id , arrayPosition , 1);
mapHandler.bounds.extend(punkt);
};

/////////////////////////////////////////////////////////////////////////////////////////

mapHandler.addMarker = function(target_id , data){

			// finds address first
			jQuery.getJSON('http://maps.google.com/maps/geo?q=' + data.getLocationReturn.latitude + ',' +  data.getLocationReturn.longitude + 			'&output=json&oe=utf8\&sensor=false&key=ABQIAAAAQYTs0Am4zpghLCHA4P_adhQXwBLGIGbcZioHZvIGUiaAN1KTzxSiqDIlU5JKhSSjdLR7yxpVrr8oYg&callback=?', 
			function(data2){ 
				// Call once complete
				mapHandler.addMarkerCallBack( target_id , data, data2);
				}
			);
};

///////////////////////////////////////////////////////////////////

mapHandler.addMarkerCallBack = function( target_id , data, data2){

var arrayPosition = mapHandler.targets[target_id].GetLocationResult.length;

mapHandler.targets[target_id].GetLocationResult[arrayPosition] = new Object();
mapHandler.targets[target_id].GetLocationResult[arrayPosition].latitude = (+data.getLocationReturn.latitude);
mapHandler.targets[target_id].GetLocationResult[arrayPosition].longitude = (+data.getLocationReturn.longitude);
mapHandler.targets[target_id].GetLocationResult[arrayPosition].accuracy = (+data.getLocationReturn.accuracy);

// No longer using service timestamp since value was sometimes incorrect. Local time used instead.

var currentTime = new Date();
var year = currentTime.getFullYear();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var hours   = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();

if (month < 10)   month   = "0" + month;
if (day < 10)   day   = "0" + day;
if (hours < 10)   hours   = "0" + hours;
if (minutes < 10)   minutes   = "0" + minutes;
if (seconds < 10)   seconds   = "0" + seconds;

mapHandler.targets[target_id].GetLocationResult[arrayPosition].timestamp = (year + "-" + month + "-" + day + " " +  hours + ":" + minutes + ":" + seconds);
	
mapHandler.targets[target_id].GetLocationResult[arrayPosition].closeTo =  mapHandler.getAdress(data2);

var punkt = new GLatLng( data.getLocationReturn.latitude , data.getLocationReturn.longitude);
mapHandler.targets[target_id].markers[arrayPosition] = mapHandler.customMarker(punkt , target_id );
mapHandler.targets[target_id].circles[arrayPosition] = mapHandler.drawCircle(punkt , data.getLocationReturn.accuracy);

mapHandler.drawSingleMarkerAndFrame(target_id , arrayPosition , 1);
mapHandler.addMarkerFunctions(target_id);
mapHandler.bounds.extend(punkt);
mapHandler.fit();

$.ajax({
	url:"/ajax/get_username.php",
	type:"GET",
	dataType:"json",
	data:"id=" + target_id,
	success:function(data) {
		var username = data.username;
		var timestamp = humanize(mapHandler.targets[target_id].GetLocationResult[0].timestamp);
		$("#block-current .details").html(
			'    <a class="photo" href="/mypages/profile/' + target_id + '/"><img src="/upload-image/photo.php?UserID=' + target_id + '&width=56&square=1" width="56" height="56" alt="" /></a>' +
'        <p><a href="/mypages/profile/' + target_id + '/"><strong>' + username + '</strong></a><br />' + (timestamp == "just nu" ? "är" : "var") + ' nära<br />' + mapHandler.targets[target_id].GetLocationResult[0].closeTo + '<br />' + timestamp + '</p>' +
			'    </div>'
		);
		$("#form-send-message input[name=uid]").val(target_id);
		$("#block-current").show();
		$("#block-message").show();
	}
});
 };

///////////////////////////////////////////////////////////////////

mapHandler.drawSingleMarkerAndFrame = function(target_id , arrayPosition , drawCircle){

// add the frame first then the userimage ontop
mapHandler.map.addOverlay(mapHandler.frameMarker(mapHandler.targets[target_id].markers[arrayPosition]));
mapHandler.map.addOverlay(mapHandler.targets[target_id].markers[arrayPosition]);
// add the radius circle?
if(drawCircle)
	mapHandler.map.addOverlay(mapHandler.targets[target_id].circles[arrayPosition]);
};

///////////////////////////////////////////////////////////////////

mapHandler.checkAndAddAndFit = function(){
// add all of the active targets markers and then fit the map.
for(var sierra in mapHandler.activeTargets)
mapHandler.addMarkerFunctions(mapHandler.activeTargets[sierra]);
mapHandler.fit();
};

///////////////////////////////////////////////////////////////////

mapHandler.addMarkerFunctions = function(target_id){
	// Add the click functions for the markers on map and infowindows. Sets up the pan to on click and what is to be shown.
	if(target_id)
	{
		
				$('<div id="' + target_id + '"></div>').appendTo("#friends");
				$('<div><img src="/upload-image/photo.php?UserID='  + target_id +   '&width=50&square=1" /><br><br></div>').appendTo("#" + target_id);
				
				// go through all of the targets markers and set them up 
				
				$(mapHandler.targets[target_id].markers).each(function(i,marker){
					//add to #block-history
					$.ajax({
						url:"/ajax/get_username.php",
						type:"GET",
						dataType:"json",
						data:"id=" + target_id,
						success:function(data) {
							var username = data.username;
							var timestamp = humanize(mapHandler.targets[target_id].GetLocationResult[i].timestamp);
							var lid = 'marker-' + target_id;
							if($("#" + lid).length == 0) {
								$("#block-history ul").append('<li><a id="' + lid + '" href="' + window.location + '">' + username + '</a></li>');
								$("#" + lid).click(function() {
									mapHandler.map.panTo(marker.getLatLng());
									$("#block-current .details").html(
										'    <a class="photo" href="/mypages/profile/' + target_id + '/"><img src="/upload-image/photo.php?UserID=' + target_id + '&width=56&square=1" width="56" height="56" alt="" /></a>' +
							'        <p><a href="/mypages/profile/' + target_id + '/"><strong>' + username + '</strong></a><br />' + (timestamp == "just nu" ? "är" : "var") + ' nära<br />' + mapHandler.targets[target_id].GetLocationResult[0].closeTo + '<br />' + timestamp + '</p>' +
										'    </div>'
									);
									$("#form-send-message input[name=uid]").val(target_id);
									$("#block-current").show();
									$("#block-message").show();
									return false;
								});
							}
						}
					});

				var divString = (target_id + 'marker' + i); 
				//	Add a div for each marker named target_id + marker + counter(i) inside the target_id  div .
				$('<div id="' + divString + '" </div>') .appendTo("#" + target_id);	
				$("#"+divString).html('<a href="" onclick="return false;">' + (i+1) + '. ' + mapHandler.targets[target_id].GetLocationResult[i].closeTo +'</a>');
				
				// '<a href="#" title="' + + '" onclick="return false;"'
				//(i+1) + '. ' + mapHandler.targets[target_id].GetLocationResult[i].closeTo);
				
				$('#' + divString)		
				.click(function(){
						/*$("#block-current .content").html(
							'<p><a href="/mypages/profile/' + target_id + '/"><img src="/upload-image/photo.php?UserID='  + target_id +   '&width=70&square=1" width="70" height="70" alt="" /></a></p>' +
							'<p><span>LONGTITUDE</span>:' + mapHandler.targets[target_id].GetLocationResult[i].longitude.toFixed(5) + '</p>' +
							'<p><span>LATITUDE</span>:' + mapHandler.targets[target_id].GetLocationResult[i].latitude.toFixed(5) + '</p>' +
							'<p><span>PRECISION</span>:' + mapHandler.targets[target_id].GetLocationResult[i].accuracy.toFixed(0) + '</p>' +
							'<p><span>ADRESS:</span>' + mapHandler.targets[target_id].GetLocationResult[i].closeTo + '</p>'
						);
						$("#block-current .content").html('<img src="/upload-image/photo.php?UserID='  + target_id +   '&width=70&square=1" />'+ '<b></br>' +  target_id  +  ' </b><br/>' + 
						'<strong>LONGITUDE:	</strong><span class="alignright">'+ mapHandler.targets[target_id].GetLocationResult[i].longitude.toFixed(5)  +  '</span><br/>' +
						'<strong>LATITUDE:	</strong><span class="alignright">'			+mapHandler.targets[target_id].GetLocationResult[i].latitude.toFixed(5)  +  '</span><br/>' +
						'<strong>PRECISION :	</strong><span class="alignright">' + mapHandler.targets[target_id].GetLocationResult[i].accuracy.toFixed(0)  +' m</span><br/>'+
						'<strong>DATUM/TID:	</strong><span class="alignright">' 	+ mapHandler.targets[target_id].GetLocationResult[i].timestamp + '</span><br/>' +
						'<strong>NÄRA: </strong><span class="alignright">' +  mapHandler.targets[target_id].GetLocationResult[i].closeTo+ '</span><br/>');*/
						mapHandler.map.panTo(marker.getLatLng());
						})
						.appendTo("#" + target_id);
					GEvent.addListener(marker, "click", function()
						{
							$.ajax({
								url:"/ajax/get_username.php",
								type:"GET",
								dataType:"json",
								data:"id=" + target_id,
								success:function(data) {
									var username = data.username;
									var timestamp = humanize(mapHandler.targets[target_id].GetLocationResult[i].timestamp);
									$("#block-current .details").html(
										'    <a class="photo" href="/mypages/profile/' + target_id + '/"><img src="/upload-image/photo.php?UserID=' + target_id + '&width=56&square=1" width="56" height="56" alt="" /></a>' +
					'        <p><a href="/mypages/profile/' + target_id + '/"><strong>' + username + '</strong></a><br />' + (timestamp == "just nu" ? "är" : "var") + ' nära<br />' + mapHandler.targets[target_id].GetLocationResult[i].closeTo + '<br />' + timestamp + '</p>' +
										'    </div>'
									);
									$("#form-send-message input[name=uid]").val(target_id);
									$("#block-current").show();
									$("#block-message").show();
								}
							});

						/*$("#messageBOX").html('<img src="/upload-image/photo.php?UserID='  + target_id + '&width=70&square=1" />'+'<b></br>' +  target_id  +  ' </b><br/>'+ 
								'<strong>LONGITUDE:	</strong><span class="alignright">'+mapHandler.targets[target_id].GetLocationResult[i].longitude.toFixed(5) +  '</span><br/>' +
								'<strong>LATITUDE:	</strong><span class="alignright">'			+mapHandler.targets[target_id].GetLocationResult[i].latitude.toFixed(5) +  '</span><br/>' +
								'<strong>PRECISION :	</strong><span class="alignright">' + mapHandler.targets[target_id].GetLocationResult[i].accuracy.toFixed(0) +' m</span><br/>'+
								'<strong>DATUM/TID:	</strong><span class="alignright">' 	+ mapHandler.targets[target_id].GetLocationResult[i].timestamp + '</span><br/>' +
						'<strong>NÄRA: </strong><span class="alignright">' +  mapHandler.targets[target_id].GetLocationResult[i].closeTo+ '</span><br/>');*/
						mapHandler.map.panTo(marker.getLatLng());
						});
					});
			$('<br/>').appendTo("#friends");
	}
	else
	alert("Cannot add markers - missing target_id");
};
			
//////////////////////////////////////////////////////////////////
			
mapHandler.displayText = function(marker){
// hide and fade in function. Fades in ones map has stopped moving.
	$('#messageBOX').hide();

  var moveEnd = GEvent.addListener(mapHandler.map, "moveend", function(){
        $("#messageBOX").fadeIn('slow'); 
        GEvent.removeListener(moveEnd);
    });
    mapHandler.map.panTo(marker.getLatLng());
	mapHandler.map.setZoom(16);
	// huh strange but other way doesnt work ...
	if( (marker.getPoint()) == (mapHandler.map.getCenter()))
	{
	$('#messageBOX').show();
	}
};
			
//////////////////////////////////////////////////////////////////

mapHandler.drawAll = function(drawCircle){
// clears the map and draws all the markers
mapHandler.map.clearOverlays();
for (alpha in mapHandler.activeTargets)
	{
		for(bravo in mapHandler.targets[mapHandler.activeTargets[alpha]].markers)
			{
			mapHandler.map.addOverlay(mapHandler.frameMarker(mapHandler.targets[mapHandler.activeTargets[alpha]].markers[bravo]));
			mapHandler.map.addOverlay(mapHandler.targets[mapHandler.activeTargets[alpha]].markers[bravo]);
			if(drawCircle)
				mapHandler.map.addOverlay(mapHandler.targets[mapHandler.activeTargets[alpha]].circles[bravo]);
			}
	}
};

//////////////////////////////////////////////////////////////////

mapHandler.customMarker = function(point , target_id){

		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = '';
		baseIcon.iconSize = new GSize(39, 39);
		baseIcon.iconAnchor = new GPoint(19,54);
		baseIcon.infoWindowAnchor = new GPoint(18, 2);
		
		var imageIcon = new GIcon(baseIcon);
		imageIcon.image = ('/upload-image/photo.php?UserID=' + target_id + '&width=39&square=1');
		markerOptions = { icon:imageIcon };
		var marker = new GMarker(point, markerOptions);

		return marker;
};

//////////////////////////////////////////////////////////////////

mapHandler.frameMarker = function(marker){
	var frameIcon = new GIcon(G_DEFAULT_ICON);
		frameIcon.shadow = ''
		frameIcon.iconSize = new GSize(51, 66);
		frameIcon.iconAnchor = new GPoint(25, 60);
		//frameIcon.image = ('/img/Boxar/Box1.gif');
		frameIcon.image = ('/img/box.gif');
		markerOptions = { icon:frameIcon , clickable:false};
		var marker = new GMarker(marker.getPoint(), markerOptions);
		return marker;
};

//////////////////////////////////////////////////////////////////

mapHandler.drawCircle = function (center, radius, nodes,liColor, liWidth, liOpa, fillColor, fillOpa)
{
	//calculating km/degree and resetting to km
	radius /=1000;
	var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;

	//Loop 
	var points = [];
	var step = parseInt(360/nodes)||10;
	for(var i=0; i<=360; i+=step)
	{
		var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + 
		(radius/lngConv * Math.sin(i * Math.PI/180)));
		points.push(pint);
	}
	points.push(points[0]);
	//So Circle will be visable on fit
	var pint = new GLatLng(center.lat() + radius/latConv, center.lng());
	mapHandler.bounds.extend(pint);
	var pint = new GLatLng(center.lat() - radius/latConv, center.lng());
	mapHandler.bounds.extend(pint);
	var pint = new GLatLng(center.lat(), center.lng() + (radius/lngConv));
	mapHandler.bounds.extend(pint);
	var pint = new GLatLng(center.lat(), center.lng() - (radius/lngConv));
	mapHandler.bounds.extend(pint);
	

	fillColor = fillColor||liColor||"#0055ff";
	liWidth = liWidth||2;
	return (new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa));
};

///////////////////////////////////////////////////////////////////
	
mapHandler.clearAll = function(){
	mapHandler.targets = new Object();
	mapHandler.targets = [];
	mapHandler.activeTargets = new Array();
};