/* Copyright 2009 FitnessKeeper, Inc.  All Rights Reserved. */

var origMapContainerPosition;
var origMapContainerWidth;
var origMapContainerHeight;
var editActivitiesEnabled = false;

$(document).ready(function()
{
   initTripChart();
   
   // Initialize the map if needed
   if (rkMap == null)
   {
      rkMap = initMap("mapPanel", userDistanceUnits);
      rkMap.gmap.addControl(new GMenuMapTypeControl());
      rkMap.gmap.addMapType(G_PHYSICAL_MAP);
      rkMap.gmap.addControl(new GSmallZoomControl());
      rkMap.gmap.addControl(new GScaleControl());
   }
   
   $(".ActivityTable tr").click(
      function()
      {
         // Only invoke the activityClicked function if this is a different activity being clicked.
         var clickedTripId = $(this).attr("id").substring(5);
         
         if (clickedTripId != tripId)
         {
            activityClicked($(this));
         }
      });
   
   origMapContainerPosition = $("#mapContainer").css("position");
   origMapContainerWidth    = $("#mapContainer").css("width");
   origMapContainerHeight   = $("#mapContainer").css("height");
   
   $("#fullscreenMapButton").click(
      function(e)
      {
         e.preventDefault();
         expandFullscreenMap();
      });
   
   $("#closeFullscreenMapButton").click(
      function(e)
      {
         e.preventDefault();
         collapseFullscreenMap();
      });
   
   $(".monthHeader").click(
      function()
      {
         if ($(this).next().is(":hidden"))
         {
            $(this).children("img.navStatusArrow").attr("src", contextPath + "/images/arrow-down.png");
            $(this).next().slideDown("fast");
         }
         else
         {
            $(this).children("img.navStatusArrow").attr("src", contextPath + "/images/arrow-left.png");
            $(this).next().slideUp("fast");
         }
      });
   
   if ((tripId != null) && (tripId != "null"))
   {
      activityClicked($("#trip_" + tripId), true, false);
      $("#trip_" + tripId).parents(".ActivityTable").parent().prev().children("img.navStatusArrow").attr("src", contextPath + "/images/arrow-down.png");
      $("#trip_" + tripId).parents(".ActivityTable").parent().show();
   }
});

function activityClicked(clickedRow, fitTrack, updateTripChart)
{
   // Get the trip ID of the clicked row.
   tripId = clickedRow.attr("id").substring(5);
   
   if (fitTrack == undefined) fitTrack = true;
   if (updateTripChart == undefined) updateTripChart = true;
   
   // Style the selected trip
   $(".ActivityTable tr.selected").removeClass("selected");
   clickedRow.addClass("selected");
   
   if (editActivitiesEnabled)
   {
      activityClicked_NotifyEditable();
   }

   refreshPointData(true, fitTrack, updateTripChart, true);
   $("#fullscreenMapButton").show();
   
   // in case it was populated on the last activity reset the hrm box
   resetHRMDataBox();
   
   // create the Heart Rate chart if it exist for this activity
   getHRMData();
   
   //get any comments for the activity
   setTimeout("loadComments()", 450);
}

function loadActivityHeader()
{
   $("#activityHeader").load(contextPath + "/ui/activityHeader/" + tripId, {ajax: true},
         function()
         {
            if (editActivitiesEnabled)
            {
               loadActivityHeader_NotifyEditable();
            }
         });
}

function loadActivityDetails()
{
   $("#activityDetails").load(contextPath + "/ui/activityDetails/" + tripId, {ajax: true},
         function()
         {
            // Sync up the activity history table
            $("#trip_" + tripId + " td.Distance .DistanceVal").text($("#distanceVal").text());
         });
}

function loadActivitySplits(updateTripChart)
{
   $("#activitySplits").load(contextPath + "/ui/activitySplits/" + tripId, {ajax: true},
         function()
         {
            if (updateTripChart)
            {
               updateTripChartData();
            }

            if (editActivitiesEnabled)
            {
               loadActivitySplits_NotifyEditable();
            }
         });
}

function loadComments()
{
   $("#commentThead").load(contextPath + "/ui/getCommentThread/" + tripId, {ajax: true}, FB.XFBML.Host.parseDomTree);
}

function postComment()
{
   if ($.trim($("#commentTextArea").val()).length > 0)
   {
      $.ajaxSetup({scriptCharset: "utf-8" , contentType: "application/x-www-form-urlencoded; charset=UTF-8"});
      $.post(contextPath + "/my/createComment",
         {ajax: true,
          tripId: tripId,
          commentTextArea: $("#commentTextArea").val()}, loadComments, "text");
   }
}

function deleteComment(commentId)
{
   $.post(contextPath + "/my/deleteComment",
      {ajax: true,
       commentId: commentId}, loadComments, "text");
}

function refreshPointData(updateTripMap, fitTrack, updateTripChart, updateSplits)
{
   // Request the set of points from the server for the clicked trip.
   // The callback function will process the JSON response and will update the map.
   $.getJSON(contextPath + "/ui/trippoints/json/" + tripId, {ajax: true},
      function(points)
      {
         if (updateSplits)
         {
            loadActivitySplits();
         }
         
         loadActivityHeader();
         loadActivityDetails();
         refreshStatusUpdates();

         if ("manualEntry" in points)
         {
            if (editActivitiesEnabled)
            {
               refreshPointData_NotifyEditable(false);
            }
            
            $("#activityChartPanel").hide();
            $("#mapPanel").hide();
            $("#fullscreenMapButton").hide();
            $("#mapContainer").css("height", "300px");
            
            if ("gymEquip" in points)
            {
               $("#mapContainer").css("background-image", "url(" + contextPath + "/images/gym-bg.jpg)");
            }
            else
            {
               $("#mapContainer").css("background-image", "url(" + contextPath + "/images/manual-bg.jpg)");
            }
         }
         else // gps-tracking
         {
            $("#activityChartPanel").show();
            
            if (updateTripChart)
            {
               updateTripChartData();
            }
            
            if (!("mapPrivate" in points))
            {
               if (editActivitiesEnabled)
               {
                  refreshPointData_NotifyEditable(true);
               }

               $("#mapPanel").show();
               $("#fullscreenMapButton").show();
               $("#mapContainer").css("height", "300px");
               $("#mapContainer").css("background-image", "url(" + contextPath + "/images/mapPanel-bg.png)");
            
               if (updateTripMap)
               {
                  rkMap.points = points;
                  updateMap(rkMap);
                  
                  if (fitTrack)
                  {
                     fitPath(rkMap);
                  }
               }
            }
            else // map is private
            {
               $("#mapPanel").hide();
               $("#fullscreenMapButton").hide();
               $("#mapContainer").css("height", "300px");
               $("#mapContainer").css("background-image", "url(" + contextPath + "/images/private-bg.jpg)");
            }
         }
      }
   );
}

function refreshStatusUpdates()
{
   $.getJSON(contextPath + "/ui/statusupdates/json/" + tripId, {ajax: true},
      function(statusUpdates)
      {
         rkMap.statusUpdates = statusUpdates;
         overlayStatusUpdates(rkMap);
         refreshPhotoViewer(statusUpdates);
      }
   );
}

function expandFullscreenMap()
{
   $("#mapContainer").appendTo("body");
   
   $("#fullscreenMapButton").hide();
   $("#mapContainer").css("position", "absolute");
   $("#mapContainer").css("top",  "300px");
   $("#mapContainer").css("left", "40%");
   $("#mapContainer").css("width",  "300px");
   $("#mapContainer").css("height", "150px");
   
   $("#mapContainer").animate({top: "0px",
                               left: "3px",
                               width: "99%",
                               height: "99%"}, "slow", "linear", 
                               function()
                               {
                                  $("#container").hide();
                                  $("#closeFullscreenMapButton").show();
                                  rkMap.gmap.checkResize();
                               });
}

function collapseFullscreenMap()
{
   $("#closeFullscreenMapButton").hide();
   
   $("#activityChartPanel").hide();
   $("#activitySplits").hide();
   $("#container").show();
   $("#mapContainer").animate({top:    "300px",
                               left:   "40%",
                               width:  "300px",
                               height: "150px"}, "slow", "linear",
                               function()
                               {
                                  $("#mapContainer").insertAfter("#activityDetails");
                                  $("#activityChartPanel").show();
                                  $("#activitySplits").show();
                                  $("#mapContainer").css("position", origMapContainerPosition);
                                  $("#mapContainer").css("top",  "0px");
                                  $("#mapContainer").css("left", "0px");
                                  $("#mapContainer").css("width",  origMapContainerWidth);
                                  $("#mapContainer").css("height", origMapContainerHeight);
                                  $("#fullscreenMapButton").show();
                                  rkMap.gmap.checkResize();
                               });
}

function getHRMData()
{
   $.getJSON(contextPath + "/ui/getHRMChart/" + tripId, {ajax: true},
      function(data)
      {
         if (data.chartData.length > 0)
         {
            $('#showHeartRateUpload').hide();
            $("#deleteHRFileDiv").show();
            $("#HeartRateChartBox").show("");
            var chart = new Highcharts.Chart(data.chartData[0]);
         }
      });
}

function resetHRMDataBox()
{
   $("#HeartRateChartBox").hide();
   $("#deleteHRFileDiv").hide();
   $("#HeartRateChart").html("");
   $("#hrmfileToUpload").value = "";
   $('#HeartRateFileBox').hide();
   $('#showHeartRateUpload').show();
}
