/*
* This file adds the highlighting and filtering of the timeline.  A form is created and added to the including HTML file
* Author: Simon Woodman
* August 2010
* */
var filter_custom_table_id = "filter_custom_table";
var filter_highlight_table_id = "highlight_table";
var filter_types_table_id = "filter_types_table";

var timerID = null;
var filterMatcherGlobal = null;
var highlightMatcherGlobal = null;

var numOfFilters = 4;

function setupFilterHighlightControls(div, timeline, bandIndices, theme)
{
  /****************************************
   * Create table for event types filters
   ***************************************/

  var filter_types_table = document.createElement("table");
  filter_types_table.id = filter_types_table_id;

  // heading
  var tr = filter_types_table.insertRow(0);
  tr.style.textAlign = "center";
  var td = tr.insertCell(0);
  td.innerHTML = "Filter";

  // Create check boxes for the event types
  var eventTypes = new Array("New Friendship", "Updated", "Created", "Joined Groups", "Granted Permission", "Other");
  /* Create the text inputs for the filters and add eventListeners */
  for (var i = 0; i < eventTypes.length; i++)
  {
    //add a row
    tr = filter_types_table.insertRow(i + 1);
    tr.style.verticalAlign = "top";
    td = tr.insertCell(0);

    //add a label for each type
    var label = document.createElement("label");
    label.innerHTML = eventTypes[i];
    label.setAttribute('for', "filter_" + eventTypes[i]);

    //add a checkbox
    input = document.createElement("input");
    input.type = "checkbox";
    input.checked = "true";
    //name and id are the event types with spaces removed
    input.name = "filter_" + eventTypes[i].split(' ').join('');
    input.id = "filter_" + eventTypes[i].split(' ').join('');

    //add to the table
    label.appendChild(input);
    td.appendChild(label);
  }


  /****************************************
   * Create table for custom filters
   ***************************************/
  var filter_custom_table = document.createElement("table");
  filter_custom_table.id = filter_custom_table_id;

  //heading
  tr = filter_custom_table.insertRow(0);
  tr.style.textAlign = "center";
  td = tr.insertCell(0);
  td.innerHTML = "Custom Filter";

  // Text input boxes
  for (i = 0; i < numOfFilters; i++)
  {
    //start at row 1
    tr = filter_custom_table.insertRow(i + 1);
    tr.style.verticalAlign = "top";
    td = tr.insertCell(0);

    //create a text box for each filter
    var input = document.createElement("input");
    input.type = "text";
    input.id = "customFilter" + i;

    //add to the table
    td.appendChild(input);
  }


  /****************************************
   * Create table for custom filters
   ***************************************/
  var highlight_table = document.createElement("table");
  highlight_table.id = filter_highlight_table_id;

  //heading
  tr = highlight_table.insertRow(0);
  tr.style.textAlign = "center";
  td = tr.insertCell(0);
  td.innerHTML = "Highlight";

  // Create the text inputs for the highlights
  for (i = 0; i < theme.event.highlightColors.length; i++)
  {
    //add row
    tr = highlight_table.insertRow(i + 1);
    td = tr.insertCell(0);

    //add text input
    input = document.createElement("input");
    input.type = "text";
    input.id = "highlight" + i;

    //create a div to hold the colour
    var divColor = document.createElement("div");
    divColor.style.height = "0.5em";
    divColor.style.background = theme.event.highlightColors[i];

    //add to the table
    td.appendChild(input);
    td.appendChild(divColor);
  }

  /****************************************
   * Create the buttons
   ***************************************/
  var buttonsDiv = document.createElement("div");
  buttonsDiv.id = "buttonsDiv";

  //Filter Button
  var filterButton = document.createElement("button");
  filterButton.innerHTML = "Filter";
  filterButton.id = "filterButton";
  filterButton.className = "buttons";
  buttonsDiv.appendChild(filterButton);

  //Clear Button
  var clearFiltersButton = document.createElement("button");
  clearFiltersButton.innerHTML = "Clear All";
  clearFiltersButton.id = "clearAll";
  clearFiltersButton.className = "buttons";
  buttonsDiv.appendChild(clearFiltersButton);

  //Close Button
  var closeFiltersButton = document.createElement("button");
  closeFiltersButton.innerHTML = "Close";
  closeFiltersButton.id = "cancelFilter";
  closeFiltersButton.className = "buttons";
  buttonsDiv.appendChild(closeFiltersButton);

  // Append the buttons to the div and the div to the table
  div.appendChild(highlight_table);
  div.appendChild(filter_custom_table);
  div.appendChild(filter_types_table);
  div.appendChild(buttonsDiv);


  /****************************************
   * Add event handlers for the button clicks
   ***************************************/

  //hide the filtering controls
  $("#filter_container").hide();

  //make the buttons nice jQuery buttons
  $('#filter_container  button').button();

  //open the div when the user clicks the Show Filter Link
  $('#showFilter').click(function()
  {
    $("#filter_container").toggle('blind', {}, 500);
    return false;
  });

  //close the filter on cancel
  $('#cancelFilter').click(function()
  {
    $("#filter_container:visible").hide('blind', {}, 500);
    return false;
  });

  //do the filtering and close the div
  $('#filterButton').click(function()
  {
    //get the first timeline in the page - assumes only one timeline
    var t2 = Timeline.getTimelineFromID(0);
    performFiltering(t2, [0,1]);
    $("#filter_container:visible").hide('blind', {}, 500);
    return false;
  });

  //clear the filters
  $('#clearAll').click(function()
  {
    clearAll(timeline, bandIndices);
    $("#filter_container:visible").hide('blind', {}, 500);
    return false;
  });
}


function performFiltering(timeline, bandIndices)
{
  //create an array of the text values for filtering
  var filterMatcher = null;
  var filterRegExes = new Array();

  $('#' + filter_custom_table_id + ' input:text').each(function()
  {
    if ($(this).val() !== "")
    {
      var cleanedString = cleanString($(this).val()) ;
      if (cleanedString !== "")
      {
        filterRegExes.push(new RegExp(cleanedString, "i"));
      }
    }
  });

  var eventTypes = new Array();
  $('#' + filter_types_table_id + ' input[type=checkbox]:checked').each(function()
  {
    //remove the 'filter_' from the id name
    eventTypes.push($(this).attr("id").substring(7));
  });


  filterMatcher = function(evt)
  {
    /* iterate through the regex's and check them against the evtText
     if match return true, if not found return false */
    var eventType = evt.getProperty('eventType').split(' ').join('');
    if ($.inArray(eventType, eventTypes) > -1) //if the event type is in the array of event types
    {
      if (filterRegExes.length != 0)
      {
        for (var j = 0; j < filterRegExes.length; j++)
        {
          if (filterRegExes[j].test(evt.getText()) === true)
          {
            return true;
          }
        }
        return false; //none of the regexes match
      }
      else //no regexes to match so return true
      {
        return true;
      }
    }
    else //event type is not in the array of event types so don't bother checking the custom filters
    {
      return false;
    }
  };

  var regexes = [];
  var hasHighlights = false;

  //add each of the highlight controls to a regex array
  $('#' + filter_highlight_table_id + ' input:text').each(function()
  {
    if ($(this).val() !== "")
    {
      hasHighlights = true;
      regexes.push(new RegExp(cleanString($(this).val()), "i"));
    }
    else
    {
      regexes.push(null);
    }
  });

  //return the index of the highlight if a highlight exists
  var highlightMatcher = hasHighlights ? function(evt)
  {
    var text = evt.getText();
    var description = evt.getDescription();
    for (var x = 0; x < regexes.length; x++)
    {
      var regex = regexes[x];
      if (regex != null && (regex.test(text) || regex.test(description)))
      {
        return x;
      }
    }
    return -1;
  } : null;


  // Set the matchers and repaint the timeline
  filterMatcherGlobal = filterMatcher;
  highlightMatcherGlobal = highlightMatcher;
  for (var i = 0; i < bandIndices.length; i++)
  {
    var bandIndex = bandIndices[i];
    timeline.getBand(bandIndex).getEventPainter().setFilterMatcher(filterMatcher);
    timeline.getBand(bandIndex).getEventPainter().setHighlightMatcher(highlightMatcher);
  }
  timeline.paint();
}

function cleanString(s)
{
  return s.replace(/^\s+/, '').replace(/\s+$/, '');
}


function clearAll(timeline, bandIndices)
{
  $('#filter_container input:text').val("");
  $('#filter_types_table input[type=checkbox]').attr('checked', true);

  // Then re-init the filters and repaint the timeline
  for (var i = 0; i < bandIndices.length; i++)
  {
    var bandIndex = bandIndices[i];
    timeline.getBand(bandIndex).getEventPainter().setFilterMatcher(null);
    timeline.getBand(bandIndex).getEventPainter().setHighlightMatcher(null);
  }
  timeline.paint();
}
