//////////////////////////////////////////////////////////////////////////////
//                                                                          //
// scripts.js                                                               //
//                                                                          //
// Shared scripts for Marcelo's Home Page.                                  //
//                                                                          //
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
// Website constants.

// var rootUrl = "http://www.lopezruiz.net/";
// var serverRoot = "http://www.lopezruiz.net/";
var rootUrl = "http://localhost/marce/";
var serverRoot = "http://localhost/";
var styleSheetCookieName = "ssc";

//////////////////////////////////////////////////////////////////////////////
// Document initialization support.

/**
 * Performs any required initializations when the document is loaded.
 */
function bodyLoaded()
{
  // refreshStyleSheet();
  // setupFetchSupport();
}

//////////////////////////////////////////////////////////////////////////////
// Cookie support.

/**
 * Retrieves the value of the cookie with the specified name.
 *
 * cookieName - name of cookie value to get
 */
function getNamedCookie(cookieName)
{
  var allCookies;
  var singleCrumb;

  allCookies = document.cookie.split("; ");
  for (var i=0; i < allCookies.length; i++)
  {
    singleCrumb = allCookies[i].split("=");
    if (singleCrumb[0] == cookieName) 
      return unescape(singleCrumb[1]);
  }

  return null;
}

/**
 * Sets the value of the cookie with the specified name.
 *
 * cookieName   - name of cookie to set
 * cookieValue  - value of cookie
 */
function setNamedCookie(cookieName, cookieValue)
{
  document.cookie = cookieName + "=" + escape(cookieValue);
}

//////////////////////////////////////////////////////////////////////////////
// Logging support.

var logTarget;  // Target div for logging messages.

/**
 * Logs the specified message unless running in production mode.
 *
 * text - text of message to log
 */
function logText(text)
{
  if (logTarget == null)
  {
    // Create a logging div element.
    logTarget = document.createElement("div");
    document.body.appendChild(logTarget);
  }
  logTarget.innerHTML = text;
}

//////////////////////////////////////////////////////////////////////////////
// Stylesheet support.

/**
 * Changes the stylesheet of the current document.
 *
 * rootFileName - name of file, relative to root of site.
 */
function changeStyleSheet(rootFileName)
{
  var cssElement;

  cssElement = document.getElementById("pageCss");
  if (cssElement)
  {
    cssElement.href = rootUrl + rootFileName;
    setNamedCookie(styleSheetCookieName, rootFileName);
  }
  else
  {
    window.status = "Cannot change style - pageCss missing.";
  }
}

/**
 * Changes the stylesheet of the current document to whichever
 * user preference is stored in the stylsheet cookie.
 */
function refreshStyleSheet()
{
  var cssElement;
  var rootFileName;

  cssElement = document.getElementById("pageCss");
  if (cssElement)
  {
    rootFileName = getNamedCookie(styleSheetCookieName);
    if (rootFileName)
    {
      cssElement.href = rootUrl + rootFileName;
    }
  }
  else
  {
    window.status = "Cannot change style - pageCss missing.";
  }
}

/**
 * Toggles the stylesheet between css.css and css-blue.css.
 */
function toggleStyleSheet()
{
  var rootFileName;
  var newFileName;
  
  rootFileName = getNamedCookie(styleSheetCookieName);
  if (rootFileName && rootFileName == "css-blue.css")
  {
    newFileName = "css.css";
  }
  else
  {
    newFileName = "css-blue.css";
  }
  changeStyleSheet(newFileName);
}

//////////////////////////////////////////////////////////////////////////////
// Fetch support.

var fetchCallId;  // The identifier for a Fetch call.
var contentUrl;   // Absolute URL to fetched content.

/**
 * Fixes links in the page HTML, coming from contentUrl and making them
 * relative to the current document.
 *
 * pageHtml - HTML for page
 */
function fixupFetchLinks(pageHtml)
{
  var pageDirectory;
  var sourceExpression;
  var hrefExpression;

  // For example, the tag <img src='image.gif' />
  // from                 http://foo/bar/my-page.htm
  // when referenced from http://foo/my-doc.htm -- or any other place
  // becomes              <img src='http://foo/bar/image.gif' />
  
  pageDirectory = urlGetDirectoryName(contentUrl);
  pageDirectory = urlGetWithTrailingDelimiter(pageDirectory);
  sourceExpression = /(src=")(?!http)(.*)(")/g;
  pageHtml = pageHtml.replace(sourceExpression, "$1" + pageDirectory + "$2$3");

  hrefExpression = /(href=")(?!http)(.*)(")/g;
  pageHtml = pageHtml.replace(hrefExpression, "$1" + pageDirectory + "$2$3");
  
  // alert(pageHtml);
  return pageHtml;
}

/**
 * Invoked when the user clicks anywhere in the document.
 */
function linkClicked()
{
  var urlToRequest;
  var anchorElement;
  
  if (window.event.srcElement.tagName == "A")
  {
    anchorElement = window.event.srcElement;
  }
  else if (window.event.srcElement.tagName == "IMG" && window.event.srcElement.parentNode.tagName == "A")
  {
    anchorElement = window.event.srcElement.parentNode;
  }
  else
  {
    return;
  }
  
  urlToRequest = anchorElement.href;
  
  // Ignore links that point somewhere within this page.
  if (urlToRequest.indexOf("#") != -1)
  {
    return;
  }
  
  // Verify that this is something within our site.
  if (urlToRequest.substr(0, serverRoot.length) != serverRoot)
  {
    return;
  }
  urlToRequest = "/" + urlToRequest.substr(serverRoot.length);
  
  if (urlIsTargetImage(urlToRequest))
  {
    if (contentUrl == null)
    {
      contentUrl = "/";
    }
    divTarget.innerHTML = 
      "<A HREF='" + contentUrl + "'>Back</A><BR />" +
      "<IMG src='" + urlToRequest + "' />";
  }
  else
  {
    FetchServiceDiv.useService(rootUrl + "services/FetchPageService.asmx?WSDL", "FetchPage");
    fetchCallId = FetchServiceDiv.FetchPage.callService("FetchPage", urlToRequest);
  }
  contentUrl = urlCombine(serverRoot, urlToRequest);
  window.event.returnValue = false;
}

/**
 * Invoked when the WebService behavior is available.
 */
function onFetchAvailable()
{
  // logText("available");
}

/**
 * Invoked when a Fetch operation has finished.
 */
function onFetchResult()
{
  if ((event.result.error) && (fetchCallId==event.result.id))
  {
    var xfaultcode   = event.result.errorDetail.code;
    var xfaultstring = event.result.errorDetail.string;
    var xfaultsoap   = event.result.errorDetail.raw;

    logText(event.result.errorDetail.string);
  }
  else if((!event.result.error) && (fetchCallId == event.result.id))
  {
    divTarget.innerHTML = fixupFetchLinks(event.result.value);
  }
  else
  {
    logText("Something else fired the event!");
  }
}

/**
 * Sets up the document to support fetching.
 */
function setupFetchSupport()
{
  // Set up a handler to trap all clicks. This is used
  // to redirect anchor clicks to use the server fetch.
  document.body.onclick = linkClicked;
  
  // Create and initialize an element to hold the WebService behavior.
  var newDiv;
  newDiv = document.createElement("div");
  newDiv.id = "FetchServiceDiv";
  newDiv.style.behavior = "url(" + rootUrl + "services/webservice.htc)";
  newDiv.onresult = onFetchResult;
  newDiv.onserviceavailable = onFetchAvailable;
  document.body.appendChild(newDiv);
}

//////////////////////////////////////////////////////////////////////////////
// Path support.

/**
 * Combined the base url with a url fragment to append, and returns the
 * well-formed resulting url.
 *
 * baseUrl    - base url to start from
 * appendUrl  - url to append to baseUrl
 */
function urlCombine(baseUrl, appendUrl)
{
  if (baseUrl == null || baseUrl.length == 0)
  {
    return appendUrl;
  }
  if (appendUrl == null || appendUrl.length == 0)
  {
    return baseUrl;
  }
  
  if (baseUrl.substr(baseUrl.length - 1) == "/")
  {
    if (appendUrl.substr(0, 1) == "/")
    {
      return baseUrl + appendUrl.substr(1);
    }
    else
    {
      return baseUrl + appendUrl;
    }
  }
  else
  {
    return baseUrl + "/" + appendUrl;
  }
}

/**
 * Returns the directory information for the specified path url.
 *
 * url  - a url to a file
 */
function urlGetDirectoryName(url)
{
  var lastSeparator;

  if (url == null || url.length == 0)
  {
    return ".";
  }
  
  lastSeparator = url.lastIndexOf("/");
  return url.substr(0, lastSeparator);
}

/**
 * Returns the url with a trailing delimiter if it doesn't have one already.
 *
 * url  - a url to a file
 */
function urlGetWithTrailingDelimiter(url)
{
  var lastSeparator;

  if (url == null || url.length == 0)
  {
    return "/";
  }
  
  if (url.substr(url.length - 1) == "/")
  {
    return url;
  }
  else
  {
    return url + "/";
  }
}

/**
 * Checks whether the url refers to an image file.
 *
 * url  - a url to a file
 */
function urlIsTargetImage(url)
{
  var extension;
  
  extension = url.substr(url.length - 3, 3);
  if (extension == "png" || extension == "gif" || extension == "jpg" || extension == "bmp")
  {
    return true;
  }
  else
  {
    return false;
  }
}
