/* CMS functions */
function strip(string) {
  return string.replace(/^\s+/, '').replace(/\s+$/, '');
}

function downcase(string) {
  return string.toLowerCase();
}

function slugify(string) {
  return downcase(strip(string)).replace(/[^-a-z0-9~\s\.:;+=_]/g, '').replace(/[\s\.:;=+]+/g, '-');
}

function render_recaptcha(element){
  Recaptcha.create("6LfiPAUAAAAAAPzjBYJg5xcbT8vSIAmWBWYhN7uB", element, {
         theme: "white",
         callback: Recaptcha.focus_response_field
   });  
}

/* Site-specific */
function selectAndGo(fieldName) {
  value = $('#' + fieldName)[0].value;

  if(value != '') {
    window.location = value;
  }
}

function setupProjectSearchForm() {
  $("#project-search-form").ajaxForm({
    dataType: 'json',
    success: processProjectSearchJSON
  });
}

function processProjectSearchJSON(data) {
  $("div.projects-list ul li").removeClass('highlight').removeClass('solid-highlight');
  projects = eval(data);
  for(i = 0; i < projects.length; i++) {
    $('#' + projects[i]).addClass('highlight');
  }
}

function setupCategoryHighlightsForProjects() {
  $("div.tags ul li a").hover(
    function(){
      var tagName = $(this).attr('rel');
      $("div.projects-list ul li").removeClass('highlight');
      $("div.projects-list ul li." + tagName).addClass('highlight');
    },
    function(){
      var tagName = $(this).attr('rel');
      $("div.projects-list ul li").removeClass('highlight');
    }
  ).click(function(){
    var tagName = $(this).attr('rel');
    $("div.projects-list ul li").removeClass('solid-highlight');
    $("div.projects-list ul li." + tagName).addClass('solid-highlight');
  });
}

function setupNewsItemSearchForm() {
  $("#news-item-search-form").ajaxForm({
    success: processNewsItemSearchXML
  });
}

function processNewsItemSearchXML(data) {
  $("div#main-news").html("<h2>Search Results</h2>" + data);
  $("div#main-news").highlight();
}

function filterNewsItemsByTag(tagName) {
  $.ajax({
    type: "POST",
    url: "/news/category/search",
    data: "tag=" + tagName + "&authenticity_token=" + $("input[name=authenticity_token]")[0].value,
    success: function(data) {
      $("div#main-news").html("<h2>" + tagName + " news</h2>" + data);
      $("div#main-news").highlight();
    }
  });
}

function setupCategoryHighlightsForNewsItems() {
  $("div.tags u li a").click(
    function() {
      var tagName = $(this).attr('rel');
      
    }
  );
}

function buildPeopleLinks(data) {
  // format: 0=ID, 1=Full Name, 2=Path, 3=Photo URL, 4=Department Roles (BELOW)
  // Department Roles = [['department' => ..., 'working_title' => ...]]
  result = "";
  if($("input#hide_department").length > 0) {
    var hideDepartment = true;
  } else {
    var hideDepartment = false;
  }
  for(i = 0; i < data.length; i++) {
    // The following opens a shim div to ensure proper clearing of rows for those that contain people with more than one department.
    if (i % 2 == 0) {
      result += "<div class='block'>";
    }
    person = data[i];
    if(person[0] != 'EMPTY') {
      link = "<li>";
      link += "  <div class='photo'>" + "<img src=\"" + person[3] + "\" />" + "</div>";
      link += "  <div class='info'>";
      link += "    <span class='name'>" + "<a href=\"" + person[2] + "\">" + person[1] + "</a>" + "</span>";
      for(j = 0; j < person[4].length; j++) {
        dept = person[4][j];
        link += "    <div class='role'>";
        link += "      <span class='role'><strong>" + dept['working_title'] + "</strong></span>";
        if(hideDepartment == false) {
          link += "      <div class='department'>" + dept['department'] + "</div>";
        }
        link += "    </div>";
      }
      link += "  </div>";
      link += "</li>";
      result += link;
    } else {
      link = "<li class='blank'><a href='#'>#</a></li>";
      result += link;
    }
    // The following closes a shim div to ensure proper clearing of rows for those that contain people with more than one department.
    if(i % 2 == 1) {
      result += "</div>";
    }
  }
  return result;
}

function filterPeopleByCenterAndAlpha(id, alpha) {
  if($("input#attribute_last_name").attr('checked')) {
    attr = 'last_name';
  } else {
    attr = 'first_name';
  }
  $.ajax({
    type: "GET",
    url: "/research/research-centers/people/search/alpha",
    data: "center=" + id + "&alpha=" + alpha + "&attribute=" + attr,
    dataType: 'json',
    success: function(data) {
      if(data.length > 0) {
        result = "<h2>Search Results</h2><ul>";
        result += buildPeopleLinks(data);
        result += "</ul>";
        result += "<!--[if IE]><div class='clearfix'>&nbsp;</div><![endif]-->";
        $("#search-results").html(result).highlight();
      } else {
        result = "<h2>Search Results</h2><p>Your search produced no results.</p>"
        $("#search-results").html(result).highlight();
      }
    }
  });
}

function setupResearchCenterSearchForm() {
  $("#research-center-search-form").ajaxForm({
    dataType: 'json',
    success: function(data) {
      if(data.length > 0) {
        result = "<h2>Search Results</h2><ul>";
        result += buildPeopleLinks(data);
        result += "</ul>";
        result += "<!--[if IE]><hr class=\"search-results-divider\" /><![endif]-->";
        $("#search-results").html(result).highlight();
      } else {
        result = "<h2>Search Results</h2><p>Your search produced no results.</p>"
        $("#search-results").html(result).highlight();
      }
    }
  });
}

function setupResearchCenterTypeSearch() {
  $("div.pulldown select").change(function(){
    value = this.value;
    $.ajax({
      type: "GET",
      url: "/research/research-centers/people/search/type",
      data: "center=" + activeResearchCenterID + "&type=" + value,
      dataType: 'json',
      success: function(data) {
        if(data.length > 0) {
          result = "<h2>Search Results</h2><ul>";
          result += buildPeopleLinks(data);
          result += "</ul>";
          $("#search-results").html(result).highlight();
        } else {
          result = "<h2>Search Results</h2><p>Your search produced no results.</p>"
          $("#search-results").html(result).highlight();
        }
      }
    });
  });
}

function setupNewsFilterByType(){
  $("#item-selector ul li input[type=radio]").click(function(){
    $.ajax({
      type: "GET",
      url: "/news/recent/filter" + "?type=" + this.value,
      dataType: "script"
    });
  });
}

function setupCollapsibleAreasInSidebar() {
  areas = ['.featured-story', '.recent-news', '.upcoming-events'];
  collapsedByDefault = ['.featured-story', '.recent-news', '.upcoming-events'];
  for(i = 0; i < areas.length; i++) {
    k = areas[i];
    setupCollapsibleArea(k);
  }
  if($.cookie('sidebar-default-states-applied') == 'true') {
    for(i = 0; i < areas.length; i ++) {
      k = areas[i];
      // Set initial states
      if($.cookie(k + "-collapsed") == "true") {
        $(k + " h4").click();
      }
    }
  } else {
    for(i = 0; i < collapsedByDefault.length; i++) {
      k = collapsedByDefault[i];
      $(k + " h4").click();
    }
    $.cookie('sidebar-default-states-applied', true);
  }
}

function setupCollapsibleArea(klass) {
  $(klass + " h4").click(function(){
    if($(this).hasClass('collapsed')) {
      $(klass + " .content").show();
      $(this).removeClass('collapsed');
      $.cookie(klass + "-collapsed", false);
    } else {
      $(klass + " .content").hide();
      $(this).addClass('collapsed');
      $.cookie(klass + "-collapsed", true);
    }
  });
}

function setupDepartmentPeopleSearch() {
  $("div.pulldown select").change(function(){
    value = this.value;
    $.ajax({
      type: "GET",
      url: "/people/search/department",
      data: "id=" + value,
      dataType: 'json',
      success: function(data) {
        if(data.length > 0) {
          result = "<h2>Search Results</h2><ul>";
          result += buildPeopleLinks(data);
          result += "</ul>";
          $("#search-results").html(result).highlight();
        } else {
          result = "<h2>Search Results</h2><p>Your search produced no results.</p>"
          $("#search-results").html(result).highlight();
        }
      }
    });
  });
}

function hideNav() {
  $("#navigation>ul").hide();
}

function showNav() {
  $("#navigation>ul").show();
}

// Make jQuery trigger RJS templates - Courtesy of http://ozmm.org/posts/jquery_and_respond_to.html
jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
})

