
 var ajaxRequest = null;
 
 function resetCommentForm() {
    Element.hide('newCommentContainer');
    $("btnAddComment").disabled = false;
    $("btnAddComment").value = "add";
    $("txtCommentSubject").value = "";
    $("txtComment").value = "";
 }
 
 /*
 * Adding Tags using AJAX
 */                
 function addComment() {
    if($("txtComment").value == "") {
       alert("You must enter a comment to add it to this trip");
       return;
    } else if ($("txtComment").value.length > 2000) {
       alert("Please shorten your comment.");
       return;
    } else if ($("txtCommentSubject").value == "") {
       alert("You must enter a title to add it to this trip");
       return;
    }
    $("btnAddComment").disabled = true;
    $("btnAddComment").value = "adding...";
    
    var secretLinkKey = GetUrlParameter("secretLinkKey");
    
    // Make sure we support things like “ and Vértice geodésico.
    var postData = "ajaxMethodName=addTripComment&subject=" + encodeURIComponent($("txtCommentSubject").value) + "&comment=" + encodeURIComponent($("txtComment").value) + "&tripId=" + shareTripId + "&secretLinkKey=" + secretLinkKey;
    ajaxRequest = new Ajax.Request("/dyn/AjaxHandlers/TripComments.ashx", { method: "post", postBody: postData, onSuccess: addCommentSuccess, onFailure: addCommentFailure, onException: addCommentException } );
 }
 
 function addCommentSuccess(request) {
    // Data should come back as: status=Success&id={0}&subject={1}&comment={2}&userid={3}&displayname={4}&date={5:MM/dd/yyyy}
    var params  = request.responseText.split('&');
    var id      = params[1].split('=')[1];
    var subject = decodeURIComponent(params[2].split('=')[1]);
    var comment = decodeURIComponent(params[3].split('=')[1]);
    var userId  = params[4].split('=')[1];
    var displayname = decodeURIComponent(params[5].split('=')[1]);
    var date    = params[6].split('=')[1];
    
    addCommentToList(id, userId, displayname, date, subject, comment, "true");
    
    //update the list
    resetCommentForm();
 }
 
 function addCommentFailure(request) {
    $("btnAddComment").disabled = false;
    $("btnAddComment").value = "add";
    
    alert(request.responseText);
 }
 
 function addCommentException(xhr, ex) {
    alert('Error: ' + ex.message);
 }
 
 function deleteComment(id) {
    if (confirm("Are you sure you want to delete this comment?")) {
       var postData = "ajaxMethodName=deleteTripComment&commentId=" + id;
       ajaxRequest = new Ajax.Request("/dyn/AjaxHandlers/TripComments.ashx", { method: "post", postBody: postData, onSuccess: deleteCommentSuccess, onFailure: deleteCommentFailure } );
    }
 }
 
 function deleteCommentSuccess(request) { 
    var id;
    var params = request.responseText.toQueryParams();
    id = params["id"];
    deleteCommentFromList(id);
 }
 
 function deleteCommentFailure(request) {
    alert(request.responseText);
 }
 
 var lastAddedItem = null;
 var commentTable = new Array();
 /*
 * Helpers for adding/removing from the list
 */
 function addCommentToList(id, userId, displayname, date, subject, comment, showDelete) {
    var container = document.createElement("div");
    container.className="commentContainer";
    
    var item;
    
    item = document.createElement("div");
    item.className = "date";
    item.innerHTML = date;
    container.appendChild(item);
    
    item = document.createElement("div");
    item.className = "subject";
    item.innerHTML = subject;
    container.appendChild(item);
    
    if (showDelete == "true") {
       item = document.createElement("div");
       item.className = "delete";
       item.innerHTML = "<a onclick='deleteComment(" + id + ");' style='cursor: pointer;'>[delete]</a>";
       container.appendChild(item);
    }
    
    item = document.createElement("div");
    item.className = "comment";
    item.innerHTML = comment;
    container.appendChild(item);
    
    // First Html encode the display name.
    item = document.createElement("div");
    item.appendChild(document.createTextNode(displayname));
    displayname = item.innerHTML;
    
    item = document.createElement("div");
    item.className = "user";
    item.innerHTML = "Added by <a href='/UserProfile.aspx?userId=" + userId + "'>" + displayname + "</a>";
    container.appendChild(item);
    
    // Append the comments in descending order.  So if there aren't any comments, we will append the first child,
    // otherwise, we will insert it before the first child.
    if(lastAddedItem == null) {
       // Clear the '0 Trip Comments' text and add the first item.
       $("commentList").innerHTML = "";
       lastAddedItem = $("commentList").appendChild(container);
    } else {
       lastAddedItem = $("commentList").insertBefore(container, $("commentList").childNodes[0]);
    }
    commentTable[id] = lastAddedItem;
 }
 
 function deleteCommentFromList(id) {
    var itemToDelete = commentTable[id];
    $("commentList").removeChild(itemToDelete);
    commentTable.splice(id, 1);
    
    // Since commentTable is a sparse array, we need to count the items ourselves.
    // http://hexmen.com/blog/2006/12/iterating-over-sparse-arrays/
    var commentCount = 0;
    for (var property in commentTable) {
       if (String(property >>> 0) == property && property >>> 0 != 0xffffffff) {
          commentCount++;
       }
    }
    
    if (commentCount == 0) {
      // They deleted the last comment.  Add some placeholder text back in there and remember to null out the lastAddedItem variable.
      $("commentList").innerHTML = "<i>0 Trip Comments</i>";
      lastAddedItem = null;
    }
 }

// Parameter arrays are not supported.
var params = null;
function GetUrlParameter(name)
{
   if (params == null)
   {
      params = [];
      
      var q = window.location.search.substring(1).split("&");
      
      for (var i = 0; i < q.length; i++)
      {
         var param = q[i].split("=");
         params[decodeURIComponent(param[0]).toLowerCase()] = decodeURIComponent(param[1]);
      }
   }   
   
   return params[name.toLowerCase()];
}
