// Add an entry to MyGuide from the entry's page.
function myguide_add(entry, url)
{
  myguide_handle(entry, url, 'add');
}

// Remove an entry to MyGuide from the entry's page.
function myguide_remove(entry, url)
{
  myguide_handle(entry, url, 'remove');
}

// Handle an add or remove from MyGuide.
function myguide_handle(entry, url, action)
{
  var link = $('#myguide_link');

  // Fade the add/remove link out.
  link.fadeTo(500, 0.01, function() {
    // Tell the server about the add/remove.
    link.load(url_with_query_string(entry, url + 'myguide/', action), function() {
      // Fade the link back in.
      link.fadeTo(500, 1.0, function() {
        // If we just removed, then we need to hide the remove warning.
        if (action == 'remove')
          $('#myguide_remove_warning').hide();
      });
    });
  });
}

// Remove an entry from MyGuide directly from the MyGuide favorites list, rather than from the entry page itself.
function myguide_remove_selected_from_list(url)
{
  var count;

  count = 0;
  $('.myguide_favorites .checkbox_cell input[type=checkbox]').each(function() {
    if (this.checked)
    {
      ++count;
      myguide_remove_from_list(/\[(\d+)\]/.exec(this.name)[1], url, false);
      this.checked = false;
    }
  });

  // Display a notification that the rows were removed.
  if (count > 0)
    myguide_display_notification('#remove_notification');
}

// Remove an entry from MyGuide directly from the MyGuide favorites list, rather than from the entry page itself.
function myguide_remove_from_list(entry, url, display_notification)
{
  // Remove the description row from the table.
  description = $(id_for('description', entry));
  description.fadeOut(500);

  myguide_remove_from_table(entry, url, display_notification, 'remove/from_list');
}

// Remove an entry from the comparison grid.
function myguide_remove_from_comparison_grid(entry, url, display_notification)
{
  myguide_remove_from_table(entry, url, display_notification, 'compare/remove');
}

// Perform the common actions for removing an entry from a MyGuide table.
function myguide_remove_from_table(entry, url, display_notification, url_suffix)
{
  // Remove the row from the table.
  row = $(id_for('row', entry));
  row.fadeOut(500);

  // Remove from the comparison grid.
  $.get(url_with_query_string(entry, url, url_suffix), function() {
    // Display a notification that the rows were removed.
    if (display_notification != false)
      myguide_display_notification('#remove_notification');
  });
}


// ==================================================================== trying to encode special chars entered into the mg comments
function encodeMyHtml(theUnencoded) {

    	

	encodedHtml = escape(theUnencoded);
	encodedHtml = encodedHtml.replace(/\//g,"%2F");
	// encodedHtml = encodedHtml.replace(/\?/g,"%3F"); doesnŐt work
	encodedHtml = encodedHtml.replace(/=/g,"%3D");
	encodedHtml = encodedHtml.replace(/&/g,"%26");
	encodedHtml = encodedHtml.replace(/@/g,"%40");
	return (encodedHtml);




/*
	// improved script shane found online for filtering special chars
 	var	encodedHtml = escape(theUnencoded);
 	encodedHtml = encodedHtml.replace(/\?/gm,"x3F");

 	var specialChars = [ '$', '^', '*', '(', ')', '+', '[', ']', '{', '}', '\\', '|', '.', '/' ];
 	var regex = new RegExp('(\\' + specialChars.join('|\\') + ')', 'g');
    return encodedHtml.replace(regex, '\\$1');
*/

} 


// Save a comment.
function myguide_save_comment(entry, url)
{
  row = $(id_for('comments_box', entry));
  
  theUnencoded = row.attr('value');
  
  theComment = encodeMyHtml(theUnencoded);
  

  // Save the comment.
  $.get(url_with_query_string(entry, url, 'favorites/save_comment') + '&comment=' + theComment, function() {
    // Display a notification that the comment was saved.
    myguide_display_notification(id_for('comment_notification', entry));
  });
}

// Popup a window showing the last email sent to a specific MyGuide entry.
function myguide_show_last_email(entry, url)
{
  window.open(url_with_query_string(entry, url, 'last_email'), 'last_email', 'width=400,height=300,location=no,toolbar=no');
}

// A global variable used by the dragging callbacks to indicate whether dragging is currently occurring.
// This is a hack that is necessary because of the way Safari sends events in Javascript.
dragging = false;

// Toggle the detail row for an entry in the MyGuide favorites list.
function myguide_toggle_details(entry)
{
  // If we're currently dragging then this wasn't a real click, just the spurious onClick that is sent when dragging
  // completes. In that case, don't toggle the entry row, but indicate that dragging is over.
  if (dragging == true)
    dragging = false;
  // Otherwise, toggle the description row for this entry.
  else {
    //$('tr.description').removeClass('temporarily_hidden');
    $(id_for('description', entry)).toggleClass('hidden');
  }
}

// Initialize a table as being sortable.
function myguide_make_sortable(group, url, url_component)
{
  var id = id_for('table', group);
  var timeout;

  $(document).ready(function() {
    $(id).tableDnD({serializeRegexp: /[^_]*$/, onDragClass: 'dragging', dragHandle: 'drag_handle', onDragStart: function(table, row) {
        // Temporarily hide all description rows, since they get in the way of drag and drop. There needs to be a timeout
        // since clicking the row (to hide and show the detail row) will initiate a drag event, and chaos ensues if the
        // detail rows disappear on a click instead of a drag.
        timeout = setTimeout(function() { $(id + ' tr.description').addClass('hidden'); }, 100);
        //timeout = setTimeout(function() { $(id + ' tr.description').addClass('temporarily_hidden'); }, 100);
      }, onDrop: function(table, row, real_drop) {
        // If we've already completed the drag, then the detail rows should not be hidden.
        clearTimeout(timeout);

        // If we started dragging but never actually moved this row anywhere, then don't do anything else.
        if (!real_drop)
          return;

        // Get the new row order.
        var rows = table.tBodies[0].rows;
        var entry_ids = [];

        for (var i = 0; i < rows.length; ++i)
        {
          // Figure out the ID of this row.
          var row_id = rows[i].id;
          var entry_id = row_entry_id(row_id);

          // If it's not a description row...
          if (row_type(row_id) == 'row')
          {
            // Save the ID.
            entry_ids.push(entry_id);

            // Move the corresponding description row to make sure it stays with its parent.
            var description_row = $('#description_' + entry_id);
            if (description_row.length)
              $('#' + row_id).after(description_row);
          }
        }

        // Re-stripe the table.
        $(id + ' tr').removeClass('even').removeClass('odd');
        $(id + ' tr.main:odd').addClass('odd');
        $(id + ' tr.main:even').addClass('even');
        $(id + ' tr.description:odd').addClass('odd');
        $(id + ' tr.description:even').addClass('even');

        // Show all description rows again.
        //$(id + ' tr.description').removeClass('temporarily_hidden');

        // Save the new row order.
        $.post(url + url_component + '/save_row_order', {'rows[]': entry_ids});

        // Unmark the final choice for this table if it's marked.
        final_choice_checkbox(group).each(function() {
          if (this.checked)
          {
            myguide_final_choice(group, url, false);
            this.checked = false;
          }
        });

        // Set a flag so that myguide_toggle_details() knows which clicks come from the dragging.
        dragging = true;
        timeout = setTimeout(function() { dragging = false }, 250);
    }});
  });
}

// Mark a group as being selected for final choice.
function myguide_final_choice(group, url, choice)
{
  var table = $(id_for('table', group));
  var entry = row_entry_id($('tr.main:first', table).attr('id'));

  // Tell the server.
  $.get(url_with_query_string(entry, url, 'favorites/final_choice') + '&value=' + Number(choice), null, function() {
    // Display a notification that the selection was saved.
    myguide_display_notification(id_for('final_choice_notification', group));
  });
}

// Show a particular tab pane in a MyGuide entry description row on the favorites list.
function myguide_show_tab(name, entry)
{
  // Hide the content of the other tabs.
  $(id_for('comments', entry)).hide();
  $(id_for('send_email', entry)).hide();
  if ($(id_for('email', entry)))
    $(id_for('email', entry)).hide();

  // Deactivate the other tabs.
  $(id_for('comments_tab', entry)).removeClass('current');
  $(id_for('send_email_tab', entry)).removeClass('current');
  if ($(id_for('email', entry)))
    $(id_for('email_tab', entry)).removeClass('current');

  // Activate the clicked tab and show its content.
  $(id_for(name + '_tab', entry)).addClass('current');
  $(id_for(name, entry)).show();
}

// Helpers.

// Fade a notification element in temporarily and then back out again.
function myguide_display_notification(id)
{
  var element = $(id);

  // Fade the notification in.
  element.fadeIn(250);

  // Set a timeout to fade it back out after 5 seconds.
  setTimeout(function() { element.fadeOut(500); }, 5000);
}

// An action URL for a particular entry.
function url_with_query_string(entry, url, action)
{
  return(url + action + '/?entry=' + entry);
}

// A CSS ID descriptor.
function id_for(name, entry)
{
  return('#' + name + '_' + entry);
}

// Whether a particular favorites list row is a main row or a description row.
function row_type(row_id)
{
  return(split_row_id(row_id)[0]);
}

// The entry ID for a particular favorites list row.
function row_entry_id(row_id)
{
  return(split_row_id(row_id)[1]);
}

// Split a favorites list row ID in half to determine its type and entry ID.
function split_row_id(row_id)
{
  return(row_id.split('_'));
}

// The CSS descriptor for a particular group's final choice checkbox.
function final_choice_checkbox(group)
{
  return($('#final_choice\\[' + group + '\\]'));
}
