/*
  common.js - Various JavaScript functions for TCSVM website.
*/

/*
  getRelativePath - Returns the URL of the current page minus the base.
*/
function getRelativePath() {
  return location.toString().
                  gsub($$("base")[0].readAttribute("href"), "").
                  gsub(/index\.html/, "").
                  gsub(/#.*/, "");
}

/*
  insertContentBefore - Inserts content before selected elements.

  selector - the CSS selector
  content - the content to be inserted
*/
function insertContentBefore(selector, content) {
  $$(selector).each( function(e) {
    e.insert({ before: content });
  });
}

/*
  insertQuotes - Inserts quotation marks where they are not supported 
  with CSS.
*/
function insertQuotes() {
  $$("q").each( function(e) {
    e.insert({ before: "“" });
    e.insert({ after: "”" });
  });
}

/*
  parseMailtoLinks - Parses anchors with a href beginning with 
  "mailto:" and replacing strings that web crawlers can't use.
*/
function parseMailtoLinks() {
  $$("a[href^=\"mailto:\"]").each( function(e) {
    e.writeAttribute("href", e.readAttribute("href").gsub(/ *\[at\] */, "@").gsub(/ *\[dot\] */, "."));
    e.innerHTML = e.innerHTML.gsub(/ *\[at\] */, "@").gsub(/ *\[dot\] */, ".");
  });
}

/*
  removeCurrentPageLink - Removes links to the current page as well as 
  the hidden class from appropriate sidebar elements.
  
  selector - the CSS selector
*/
function removeCurrentPageLink(selector) {
  selector.scan(/[^,]+/, function(m) {
    selector = selector.gsub(m, m + " a[href=\"" + 
                                    getRelativePath() + 
                                    "\"]");
  });

  $$(selector).each( function(e) {
    e.addClassName("current").writeAttribute("href", value = null);
  });
}

/*
  search - Called onclick. Supports various search methods.
*/
function search() {
  searchForm = $("search_form");
  searchForm.action = "http://googlesearch.tufts.edu/search";

  searchLocation = searchForm.getInputs("radio", "search_location");

  if (searchLocation[0].checked) {
    // search this site
    searchForm.as_sitesearch.value = "www.tufts.edu/vet";
    searchForm.proxystylesheet.value = "vet_template";
  } else if (searchLocation[1].checked) {
    // search tufts.edu
    searchForm.as_sitesearch.value = "";
    searchForm.proxystylesheet.value = "tufts_staging";
  } else if (searchLocation[2].checked) {
    // search for people
    searchForm.action = "http://whitepages.tufts.edu/searchresults.cgi";
    searchForm.search.value = $("search_text").value;
  }

  searchForm.submit();

  searchLocation = null;
  searchForm = null;
}
