//Constants
var FH_TYPE_USER = 0;
var FH_TYPE_EVENT = 1;
var FH_TYPE_LOCATION = 2;

//Holds positions
var friendMarkersArray = [];
var map;

//have one hover window
var infoWindow = new google.maps.InfoWindow({
	maxWidth: 500,
    size: new google.maps.Size(500,500)
	});


//Setup the map
 function setUpMap(mapDivId, mapInformation, mapLocation, userLocation, userPositionString, friends) {
    
	//Map options
    var myOptions = {
      zoom: 15,
      center: mapLocation,
      scrollwheel: false,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      //navigationControl:false,
      mapTypeControl: false   	         	      
    };

    //Create and add
    map = new google.maps.Map(document.getElementById(mapDivId), myOptions);
	createMarkers(mapInformation, map, mapLocation, userLocation, userPositionString, friends);
	
}

 //Shows the location of your friends on the map
function addFriends(userLocation, friends)
{
	//Create friends position markers
	createFriendsPositionMarkers(userLocation, friends, map, infoWindow);

}
function createMarkers(mapInformation, map, mapLocation,userLocation, userPositionString, friends)
{
	
	//Create "You are here" marker
	//createUserLocationMarker(map, mapLocation, userPositionString, infoWindow);
	 
	//Create hop, event and location markers
	for(var i = 0; i < mapInformation.length; i++)		
   		createMarker(mapInformation[i], map, infoWindow);
	
	//Create friends position markers
	createFriendsPositionMarkers(userLocation, friends, map, infoWindow);
}

function createUserLocationMarker(map, location, userPositionString, infoWindow)
{
	//Create the "You are here" marker (for the current user)
	var marker = new google.maps.Marker({
		position:location,
		map:map,
		title: "You are here!"
	});
	
	//Hover Over
	google.maps.event.addListener(marker,'mouseover',function(){
			infoWindow.setContent("<div class='user_marker'><span class='user_marker_title'>You are here! </span><br/> <span class='user_marker_text'>" + userPositionString + "</span></div>");
			infoWindow.open(map,marker);
		});
}


function createMarker(location, map, infoWindow)
{

	//Get location info object
	var locationInfo = location.locationInfo;

	//Build coordinate
	var lat = locationInfo.coordinate.latitude;
	var lng = locationInfo.coordinate.longitude;
	var coordinate = new google.maps.LatLng(lat, lng);

	//Hover Tooltip
	var locationName = locationInfo.name;
	
	//Info Window Text
	var text = getHoverWindowText(location); 
	
	//Create Marker (add)
	var marker = new google.maps.Marker({
		position: coordinate,
		map: map,
		title: locationName
		});

	//Hover Over
	google.maps.event.addListener(marker,'mouseover',function(){
			infoWindow.setContent(text);
			infoWindow.open(map,marker);
		});
}

//Clussters by location and creates a marker for current position
function createFriendsPositionMarkers(userLocation, friends, map, infoWindow)
{
	
	//Create an array of gps coordinate to array of friends
	var positions = [];
		
	if(friends != null )
	{
		//Cluster users
		for(var i=0; i < friends.length; i++)
		{	
			if(friends[i].latitude == null || friends[i].longitude == null) continue;
			
			var lat = friends[i].latitude.toString();
			var long = friends[i].longitude.toString();
			var gpsIndex = lat+long;
			
			//If we have not seen this position, create an array and add the user to it
			if(positions[gpsIndex] == undefined)
				positions[gpsIndex] = new Array(friends[i]);
			else
				positions[gpsIndex].push(friends[i]);
		}
	}
	
	//Add extra zeros -34.746000000000000 -34.74600
	if(userLocation != null)
	{
		var userGpsIndex = getCoordinateArrayIndex(userLocation.lat(), userLocation.lng());		
		
		//Create new marker
		//Use the global user
		if(positions[userGpsIndex] == undefined)
			createUserPositionMarker('You', new Array(currUser), map, infoWindow);
		else
			//Add to frineds
			positions[userGpsIndex].push(currUser);
	}
	//else
		//console.log("userLocation null!");
	
	for(var i in positions) {
        var title="";
        if(positions[i].length==1) title = positions[i][0].firstName+" "+positions[i][0].lastName[0];
        else title =  "" + positions[i].length + " Friends";
        createUserPositionMarker(title,positions[i],map,infoWindow);
	}
	
}

//Gets the value to index into the positions array
//make it have 16 points after the decimal (like the db entries)
function getCoordinateArrayIndex(lat, long)
{
	return addZeros(lat.toString()) + addZeros(long.toString());
}

//16 decmial places
//-137.0346 to -137.0346000000000000
function addZeros(value)
{
	var DECIMAL_DIGITS = 16;
	
	var currNumDigits = value.length - value.indexOf(".") - 1;
	var zerosToAdd = DECIMAL_DIGITS - currNumDigits;
	
	for(var i =0; i < zerosToAdd; i++)
		value += "0";
	
	return value;
}
function createUserPositionMarker(title,position, map, infoWindow)
{	
	
	//Check if we have a valid location
	
	
	//Grab the position of the first user (since (clustered by position) they are all the same)
	var lat = position[0].latitude;
	var lng = position[0].longitude;
	var coordinate = new google.maps.LatLng(lat,lng);
	
	//Hover tooltip
	var userName = displayUsersNames(position);
	
	//InfoWindow text
	var text = displayUsers(position);

	
	//Create marker (add)
	var marker = new google.maps.Marker({
		position: coordinate,
		map: map,
		title:userName,
		flat:true,
		icon:'img/mapmarker_clear.png',
		zIndex:0
	});
	
	//Hover Over
	google.maps.event.addListener(marker,'mouseover',function(){
		infoWindow.setContent(text);
		infoWindow.open(map,marker);
	});
	
	if(position.length==1){
		google.maps.event.addListener(marker,'click',function(e){
			console.log(position[0]);
			click(e,FH_TYPE_USER,position[0].id.id);
		});
	}
	
	//Add visual overlay (what we see / think is the marker ) 
	var userOverlay = new UserNameOverlay(title, map,coordinate);
	
	//Add to array
	friendMarkersArray.push(marker);
	friendMarkersArray.push(userOverlay);
}
function UserNameOverlay(name, map, coord) {
  // Now initialize all properties.
  this.name_=name;
  // leave it null for now.
  this.div_ = null;
  
  this.coord_ = coord;

  // Explicitly call setMap() on this overlay
  this.setMap(map);
}

UserNameOverlay.prototype = new google.maps.OverlayView();

UserNameOverlay.prototype.onAdd = function() {
  // Note: an overlay's receipt of onAdd() indicates that
  // the map's panes are now available for attaching
  // the overlay to the map via the DOM.

  // Create the DIV and set some basic attributes.
  var div = document.createElement('DIV');
  div.style.border = "none";
  div.style.borderWidth = "0px";
  div.style.position = "absolute";
  div.style.backgroundRepeat="no-repeat";
  div.style.backgroundImage="url(img/mapmarker.png)";
  div.style.paddingLeft="6px";
  div.style.paddingTop="1px";
  div.style.fontSize="13px";
  div.style.fontWeight="bold";
  div.style.color="white";
  div.style.minWidth = '80px';
  div.style.position="absolute";
  div.style.minHeight = '30px';
  div.style.width = '80 px';
  div.style.height = '30 px';
  div.innerHTML=this.name_;
  
  // Set the overlay's div_ property to this DIV
  this.div_ = div;

  // We add an overlay to a map via one of the map's panes.
  // We'll add this overlay to the overlayImage pane.
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
  
};

UserNameOverlay.prototype.draw = function() {

  // Size and position the overlay. We use a southwest and northeast
  // position of the overlay to peg it to the correct position and size.
  // We need to retrieve the projection from this overlay to do this.
  var overlayProjection = this.getProjection();

  // Retrieve the southwest and northeast coordinates of this overlay
  // in latlngs and convert them to pixels coordinates.
  // We'll use these coordinates to resize the DIV.
  var pt = overlayProjection.fromLatLngToDivPixel(this.coord_);

  // Resize the image's DIV to fit the indicated dimensions.
  var div = this.div_;
  div.style.position="absolute";
  div.style.left = pt.x-55 + 'px';
  div.style.top = pt.y-30 + 'px';
  div.style.width = '80px';
  div.style.height = '30px';
  div.style.minWidth = '80px';
  div.style.minHeight = '30px';
  //div.style="left:"+(pt.x-55)+"px;top:"+(pt.y-30)+"px;width:75px;height:55px";
}


UserNameOverlay.prototype.onRemove = function() {
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
}



//Display names in header
function displayUsersNames(position)
{
	var text = position.length + ' Friends \n ';
	for(var i=0; i < position.length; i++) 
		text += formatUserName(position[i]) + '\n';
	
	return text;		
}

//Display users
function displayUsers(position)
{
	var text = position.length + ' Friends <br/>';
	for(var i =0; i < position.length; i++) 
		text += displayUser(position[i]) + '</br>';
	
	return '<span class="users">' + text + '</span>';
}

//Display the info for the user for their position
function displayUser(user)
{
	return '<span class="user">' + displayProfilePic(user) + displayUserName(user) + ' ' + displayHopTime(user.updateTime) + "</span>";
}

//Display the location info
function getHoverWindowText(location)
{
	var text;
		
  	 //Display the location name
  	 text = displayLocationHeader(location);
    	 
  	 //Display the Events
  	 text += displayEvents(location.events);

  	return '<div class="location">' + text + '</div>';
}

function displayLocationHeader(location)
{
	//Title
	var text = '<span class="location_name">' + location.locationInfo.name + " </span> <br/>"; 
	
	//Display a separating line 
 	text += '<div class="horizontal_line"></div>';
 	
	//Add link
	text = createLink(text, FH_TYPE_LOCATION, location.locationInfo.id.id);
	
	//Display The location hops
 	text += displayHops(location.hops);	
 	
	return text;
}
function displayHops(hops)
{
	var hopText = '<span class="hops">';
	if(hops.length > 0) hopText += '<span class="hop_title">Who\'s here </span><br/>';
    for(var i=0; i< hops.length; i++)
    {
        hopText += displayHop(hops[i]);
        hopText += '<br/>';
    }
	hopText += '</span>';

    return hopText; 
}

function displayHop(hop)
{
	return '<span class="hop">' + displayProfilePic(hop.user) + displayUserName(hop.user) + ' ' + displayHopTime(hop.time) + "</span>";
}

function displayProfilePic(user)
{
	var text = '<img src="http://graph.facebook.com/' + user.facebookId +'/picture" class="profile_pic_img"></img>';
	text = createLink(text,FH_TYPE_USER,user.id.id);
	return '<span class="hop_profile_pic">' + text + '</span>'; 
}


function displayUserName(user)
{
	var text = formatUserName(user);
	text = createLink(text,FH_TYPE_USER,user.id.id);
	return '<span class="hop_user_name">' + text + '</span> ';
}

//format name
function formatUserName(user)
{
	return user.firstName + ' ' + user.lastName;
}

function displayHopTime(time)
{
	return "<span class='hop_time'>" + formatTimeAsTimeAgo(time) + "</span>";
}

function displayEvents(events)
{
	var eventText = '<span class="events">';
	for(var i=0; i < events.length; i++)
	{
		if(i%2 == 0) eventText += '<br/> <div class="event_even">' + displayEvent(events[i]) + '</div>';
		else eventText += '<br/> <div class="event_odd">' + displayEvent(events[i]) + '</div>';
	}
	
	eventText += '</span>';

	return eventText; 
}

function displayEvent(event)
{
	var text = '<span class="event">';
	
	//Display Event Info
	text += '<span class="event_title">' + event.eventInfo.title + '</span>';  
	
	//Add link
	text = createLink(text, FH_TYPE_EVENT, event.eventInfo.id.id);
	
	//Display the hops at the event
	text += displayHops(event.hops);
	text+='<br/>' + formatEventTime(event.eventInfo.startTime, event.eventInfo.endTime) + '<br/>';
	text += '</span>';

	
	
	return text;
}

function formatEventTime(startTime,endTime)
{
	return "<span class='event_time'>"+formatTime(startTime) + " - " + formatTime(endTime) + "</span>";
}
function createLink(text,type,id)
{
	var onClick = createOnClick(type, id);
	return '<a href="" ' + onClick + '>' + text + '</a>';	
}
function createOnClick(type,id)
{
	return ' onClick= "return click(event, ' + type + ' , ' + id + ');" '; 
}

/*Override the behavior of the links and change the page of the side iframe div to reflect that click and go to stream */

function click(event, type, id)
{
	//for chrome
	if(event.stopPropagation) event.stopPropagation();
	
	//Get the desired url
	var url;
	if(type == FH_TYPE_USER) url = 'user.php';
	else if(type == FH_TYPE_EVENT) url = 'event.php';
	else if(type == FH_TYPE_LOCATION) url = 'location.php';
	else alert('Error Unknown link type!');
	url += "?id=" + id;
	
	//Redirect the div frame
	$('iframe').attr('src',url);
	
	//Stop link
	return false;
}

function hideFriendMarkers()
{
	if(friendMarkersArray){
		for( i in friendMarkersArray){
			friendMarkersArray[i].setMap(null);
		}
	}
}

function showFriendMarkers(map)
{
	if(friendMarkersArray){
		for(i in friendMarkersArray){
			friendMarkersArray[i].setMap(map);
		}
	}
}
