// Feed-related 

var FEED_ADDRESS="feed/genhappfeed.php";
var FEED_UPDATE_INTERVAL = 600000;
var FEED_FETCH_OFFSET = 30000;

// Activity Box-related 

var ACTIVITY_LIST_ID = "activities";
var MAX_ACTIVITIES = 3;

// Map-related

var MAP_ID = "locMap";
var DEFAULT_ZOOM = 15;
var MAP_LONG_SHIFT = 0;

// String manipulation
var LINE_MAX_CHARS = 45;

var map;
var currMarker;

// Holds the timestamp of the last activity displayed

var latestTimestamp = 0;

// Date object with the current date.  Passed in feed query string to avoid
// caching issues

var currDate = new Date();



// Grab the feed  

var request = GXmlHttp.create();
request.open( "GET", FEED_ADDRESS, false );
request.send( null );

// Object to hold the parsed feed

var activities;


function renderMap() {

  // If the user's browser is supported by the Google Maps API...
  
  if ( GBrowserIsCompatible() ) {

    // Create the map
    // Also, we're going to disable dragging and double-click zooming on it
    
    map = new GMap2(document.getElementById(MAP_ID));
    map.disableDragging();
    map.disableDoubleClickZoom();
    
    // setCenter needs to always be set, stupid.
    
    map.setCenter( new GLatLng( 0, 0 ), DEFAULT_ZOOM );
    
    // Set up the marker to show where activities are going on
    
    // For some reason, you have to specifically tell the icon to
    // use the default image before it'll let you change it.  Why?  
    // Heck if I know
      
    var markerIcon = new GIcon( G_DEFAULT_ICON );
    markerIcon.image =  "images/happenings_b.png";
    markerIcon.shadow = null;
    markerIcon.iconSize =new GSize(30, 30);
    markerIcon.iconAnchor = new GPoint(15, 15);

    // Put the marker in the center to start and place it
    
    currMarker = new GMarker( map.getCenter(), { icon: markerIcon } );
    
    map.addOverlay( currMarker );
    
    // Run render the first batch of activities...

    if ( request.readyState == 4 ) {
      renderActivityBatch();
    }
    
    // Then run renderActivityBatch() every INFO_WINDOW_DELAY_INTERVAL * 
    // activities.length milliseconds
    
    setInterval( "if ( request.readyState == 4 ) { renderActivityBatch(); }", FEED_UPDATE_INTERVAL );  
  }
  
}

function renderActivityBatch() {
  activities = new Array();
  
  // Holds when to display the activity
  
  var displayTime = 0;
  
  // Parse the feed
  
  var allActivities = GXml.parse( request.responseText ).getElementsByTagName( "event" );
  
  // Go through the activities and remove the ones that happened before
  // the timestamp of the latest activity of the previous batch
 
  var w = 0;
  
  while ( w < allActivities.length ) {
    if ( parseInt( allActivities[ w ].getAttribute( "timestamp" ) ) > latestTimestamp ) {
      activities.push( allActivities[ w ] );
    }
    
    w++;
  }
  
  // For each activity...
  
  for ( var x = 0; x < activities.length; x++ ) {      
    var event = activities[ x ];

    // Put what we're going to do with it in a string.  First, we'll display it
    // on the map...
    
    var showActivity = "placeAndPanToMarker( " + event.getAttribute( "latt" ) + ", " + event.getAttribute( "longg" ) + " ); ";

    // Then we'll tell everyone what the activity was
    
	var content = event.firstChild.data;
	
	showActivity += "addToActivityFeed( prepActivity( " + parseInt( event.getAttribute( "timestamp" ) ) + ", '" + content + "' ) );";
    // Then wait displayTime milliseconds and exec that code
    
    setTimeout( showActivity, displayTime );
    
    // Increase displayTime
    
    displayTime += FEED_UPDATE_INTERVAL / activities.length;
    
    // Record the timestamp of the activity we just looked at
    
    latestTimestamp = parseInt( event.getAttribute( "timestamp" ) );
  }
  
  // After we're done displaying all the activity (minus an offset), grab the
  // next activity batch
  
  setTimeout( 'currDate = new Date(); if ( request.readyState != 2 && request.readyState != 3 ) { request.open( "GET", "' + FEED_ADDRESS + '", false ); request.send( null ); }', FEED_UPDATE_INTERVAL - FEED_FETCH_OFFSET );
}


// Given a latitude and longitude, move the marker object there and pan the map
// so we can see it

function placeAndPanToMarker( latt, longg ) {
  currMarker.setLatLng( new GLatLng( latt, longg ) );
  map.panTo( new GLatLng( latt, longg + MAP_LONG_SHIFT ) );
}


// Take an event object and prep it to be dropped into the activity feed
// Given: Time of event in milliseconds, the event object 

function prepActivity( timestamp, event ) {
  
  // Figure out what the date of the activity is given the timestamp
  
  var dateOfEvent = new Date( timestamp );
  var dateHours = dateOfEvent.getHours();
  var dayOrNight = "AM";
  
  // Determine if this happened in the morning or the evening and store that
  
  if ( dateHours == 0 ) {
    dateHours = 12;
  }
  else if ( dateHours >= 12 ) {
    if ( dateHours > 12 ) {
      dateHours -= 12;
    }
    dayOrNight = "PM";
  }

  // Since we're figuring out if the time was AM or PM, make the hour the
  // correct 12-hour number
  
  var formattedTime = dateHours + ":" + 
   ( dateOfEvent.getMinutes() < 10 ? "0" : '' ) + dateOfEvent.getMinutes() + " " + dayOrNight + "";
  
  // Set up the HTML object to return with all the correct tags, classes, etc.
  
  var activityText = "  - " + event;
  
  var activityDiv = document.createElement( "div" );
  activityDiv.className = "event";
  
  var activityDiv = document.createElement( "div" );
  activityDiv.className = "event";
  
  var timeSpan = document.createElement( "span" );
  timeSpan.className = "time";
  var timeText = document.createTextNode( formattedTime );
  timeSpan.appendChild( timeText );
  activityDiv.appendChild( timeSpan );
  
  var activityTextNode = document.createTextNode( activityText );
  activityDiv.appendChild( activityTextNode );
  
  //fix for double lines
  var cr = document.createElement("br");
  var dr = document.createElement("br");
  if(event.length < LINE_MAX_CHARS){
  		activityDiv.appendChild(cr);
		activityDiv.appendChild(dr);
  }
  
  var ln = document.createElement("hr");
  activityDiv.appendChild(ln);
  
  // Return the HTML object  
  return activityDiv;
}


// Drop an HTML DOM object into the activity list
function addToActivityFeed( preppedActivity ) {
  var activityBox = document.getElementById("activities") ;
  if ( activityBox.childNodes.length >= MAX_ACTIVITIES ) {
    activityBox.removeChild( activityBox.lastChild );
  }
  
  activityBox.insertBefore( preppedActivity, activityBox.firstChild );
  
  if ( activityBox.childNodes.length >= MAX_ACTIVITIES - 1 ) {
    $( activityBox.childNodes[ MAX_ACTIVITIES - 2 ] ).addClass( "event2ndLast" );
    $( activityBox.childNodes[ MAX_ACTIVITIES - 2 ].firstChild ).addClass( "time2ndLast" );
    
    if ( activityBox.childNodes.length == MAX_ACTIVITIES ) {
      $( activityBox.lastChild.firstChild ).removeClass( "time2ndLast" );
      $( activityBox.lastChild ).removeClass( "event2ndLast" );
      
      $( activityBox.lastChild ).addClass( "eventLast" );
      $( activityBox.lastChild.firstChild ).addClass( "timeLast" );
    }
  }
}