/*
################################################################################
#
# File:     shared/js/shared.js
#
# Contents: Javascript used by multiple sites.
#
# Modifications:
#   - 2004-05-15  txe  Initial creation.
#   - 2004-07-14  txe  Added css functions().
#   - 2004-07-28  txe  Added handleLoad(), handleDirectoryLinks().
#   - 2004-07-29  txe  Updated changeCSS, added getElementsWithName().
#   - 2004-08-08  txe  Added hostIsOffline().
#   - 2004-08-11  txe  Fixed deletion of bookmarks (#...).
#   - 2004-08-19  txe  Added verifyContactForm().
#   - 2004-08-20  txe  Added style support to switchCSS(), added isTargetXml to link handling.
#   - 2004-10-03  txe  Added getCurrentHost(), updateGoogleSearch.
#   - 2004-10-05  txe  Added populateForm().
#   - 2004-10-14  txe  Changed openWindow to allow null features (full chrome).
#   - 2004-10-27  txe  Debugged populateForm().
#   - 2005-09-22  txe  Added redirectToUrl(), moveToUrl().
#   - 2007-05-01  txe  Added getDocumentLinks() for Firefox XSLT.
#   - 2008-03-13  txe  Added buyAmazon().
#   - 2008-03-21  txe  Added support for "buy-amazon" in body class.
#   - 2008-04-28  txe  Added robustness to handleBuyAmazonLinks().
#   - 2008-05-21  txe  Added more robustness to handleBuyAmazonLinks().
#   - 2008-05-29  txe  Added more popup functions.
#   - 2008-05-30  txe  Tweaked popup functions.
#   - 2009-06-15  txe  Updated openWindow().
#   - 2010-02-26  txe  Added refreshOpener().
#   - 2010-07-27  txe  Tweaked popup logic, added popupTiny().
#   - 2010-08-09  txe  Added cookie functions.
#   - 2010-08-17  txe  Added popupFull().
#   - 2010-09-09  txe  Added hide*, show*.
#   - 2011-06-02  txe  Added addCssToggle().
#   - 2011-06-13  txe  Updated local logic.
#   - 2011-07-07  txe  Added google +1 logic.
#   - 2011-07-18  txe  Started  updating local logic.
#   - 2011-07-20  txe  Finished updating local logic.
#   - 2011-07-25  txe  Updated isNormalizedSiteCode().
#   - 2011-07-26  txe  Updated isNormalizedSiteCode().
#   - 2011-07-27  txe  Updated isNormalizedSiteCode(), support for nested dirs.
#   - 2011-07-28  txe  Updated isNormalizedSiteCode().
#   - 2011-07-29  txe  Updated isNormalizedSiteCode().
#   - 2011-07-30  txe  Updated isNormalizedSiteCode(), added isOldHtmlPath().
#   - 2011-08-01  txe  Updated isNormalizedSiteCode().
#   - 2011-08-08  txe  Fixed static host link.
#   - 2011-08-18  txe  Added trackEvent().
#   - 2011-12-11  txe  Added robustness to getSiteCodeFromPath().
#
################################################################################
*/

function isNormalizablePath(path) { return !isOldHtmlPath(path) && isNormalizedSiteCode(getSiteCodeFromPath(path)); }

////////////////////////////////////////////////////////////////////////////////

function isOldHtmlPath(path)
{
  return (path.indexOf("/travis/school/uva") !== -1);
}

////////////////////////////////////////////////////////////////////////////////

function isNormalizedSiteCode(siteCode)
{ 
  return (siteCode == "") 
      || (siteCode == "comsat")
      || (siteCode == "contact")
      || (siteCode == "cope")
      || (siteCode == "dave")
      || (siteCode == "digital-sex")
      || (siteCode == "for-against")
      || (siteCode == "games")
      || (siteCode == "giovanna")
      || (siteCode == "karen")
      || (siteCode == "ipr")
      || (siteCode == "issues")
      || (siteCode == "jess")
      || (siteCode == "pets")
      || (siteCode == "roguelike")
      || (siteCode == "search")
      || (siteCode == "springhouse")
      || (siteCode == "travel")
      || (siteCode == "travis")
      || (siteCode == "unme");
}


////////////////////////////////////////////////////////////////////////////////
// ONLOAD
////////////////////////////////////////////////////////////////////////////////

function handleLoad()
{
  handleLocalLinks();
  handleBuyAmazonLinks();
  addCssToggle();
}


////////////////////////////////////////////////////////////////////////////////
// URL
////////////////////////////////////////////////////////////////////////////////

function getCurrentHost()   { return document.location.hostname; }
function redirectToUrl(url) { window.location.href = url; }

////////////////////////////////////////////////////////////////////////////////

function moveToUrl(url)
{
  var command = "redirectToUrl('" + url + "');";
  var delay   = 3 * 1000;
  setTimeout(command, delay);
}

////////////////////////////////////////////////////////////////////////////////

function refreshOpener()
{
  if (opener && opener.document && opener.document.location)
  {
    opener.document.location = opener.document.location + "";
  }
}


////////////////////////////////////////////////////////////////////////////////
// SEARCH
////////////////////////////////////////////////////////////////////////////////

function updateGoogleSearch()
{
  var currentHost = getCurrentHost();
  var googleForm  = (document.forms ? document.forms["google"] : null);
  if (googleForm)
  {
    googleForm.domains.value    = currentHost;
    googleForm.sitesearch.value = currentHost;
  }
}


////////////////////////////////////////////////////////////////////////////////
// WINDOWS
////////////////////////////////////////////////////////////////////////////////

function popupUrlNameWHXYExtra(url,name,w,h,x,y,extra) { return popup(url, name, "width=" + w + ",height=" + h + ",left=" + x + ",top=" + y + ",scrollbars=yes,resizable=yes" + (extra ? "," + extra : "")); }
function popupUrlNameWHExtra(url,name,w,h,extra)       { return popupUrlNameWHXYExtra(url, name, w, h, (screen.width-w)/2, (screen.height-h)/2, extra); }
function popupTiny(element,   name) { return popupUrlNameWHExtra(element.href,name,300,300); }
function popupSmall(element,  name) { return popupUrlNameWHExtra(element.href,name,500,500); }
function popupMedium(element, name) { return popupUrlNameWHExtra(element.href,name,600,500); }
function popupLarge(element,  name) { return popupUrlNameWHExtra(element.href,name,800,600); }
function popupHuge(element,   name) { return popupUrlNameWHExtra(element.href,name,1000,700); }
function popupFull(element,   name) { return popupUrlNameWHExtra(element.href,name,1000,700,"directories=1,location=1,menubar=1,resizable=1,scrollbars=1,status=1,toolbar=1"); }
// special popups //
function popupRating(element, name) { var w=480; var h=650; return popupUrlNameWHXYExtra(element.href,name,w,h,screen.width-w-40,(screen.height-h)/2); }

////////////////////////////////////////////////////////////////////////////////

function popup(elementOrUrl, name, features)
{
  var isNeedingReplace = true;
  if (!elementOrUrl)
  {
    alert("popup(null,*) called");
  }
  else
  {
    var url = (elementOrUrl.href ? elementOrUrl.href : elementOrUrl);
    url    += (url.indexOf("?") > 0 ? "&" : "?") + "popup=1";
    name    = (name ? name : "_blank");
    var win = window.open(url, name, features);
    win.focus();
    isNeedingReplace = false;  // don't change current window contents //
  }
  return isNeedingReplace;
}

////////////////////////////////////////////////////////////////////////////////

function openWindow(url, name, settings)
{
//alert("openWindow('" + url + "','" + name + "','" + settings + "') called");

  name         = (name     ? name     : "_blank");
  settings     = (settings ? settings : "scrollbars=yes,resizable=yes");
  var w        = 800;
  var h        = 600;
  var x        = (screen.width  ? ((screen.width  - w) / 2) : 0);
  var y        = (screen.height ? ((screen.height - h) / 2) : 0);
  var features = "width=" + w + ",height=" + h + ",left=" + x + ",top=" + y + "," + settings;
  var win      = window.open(url, name, features);
  win.focus();

  return false;
}


////////////////////////////////////////////////////////////////////////////////
// ELEMENTS
////////////////////////////////////////////////////////////////////////////////

function hideElementID(elementID) { hideElement(document.getElementById(elementID)); }
function showElementID(elementID) { showElement(document.getElementById(elementID)); }
function hideElement(element)     { element.className = ((element.className ? element.className : "").replace("hidden","").replace("visible","") + " hidden").replace("  "," "); }
function showElement(element)     { element.className = ((element.className ? element.className : "").replace("hidden","").replace("visible","") + " visible").replace("  "," "); }

////////////////////////////////////////////////////////////////////////////////

function getElementsWithTagName(name)
{
  return (document.getElementsByTagName ? document.getElementsByTagName(name)
        : document.all                  ? document.all.tags(name)
        : null);
}


////////////////////////////////////////////////////////////////////////////////
// FORMS
////////////////////////////////////////////////////////////////////////////////

function validateContactForm(formName)
{
  var form     = getForm(formName);
  var warnings = "";
  if (!form.email.value)
  {
    warnings += "Please specify your email address.\n";
  }
  if (!form.name.value)
  {
    warnings += "Please specify your name.\n";
  }
  if (!form.subject.value)
  {
    warnings += "Please specify a subject.\n";
  }
  if (!form.body.value)
  {
    warnings += "Please enter a message.\n";
  }
  if (warnings != "")
  {
    alert(warnings);
  }
  return (warnings == "");
}

////////////////////////////////////////////////////////////////////////////////

function getForm(formName)
{
  var index = (formName ? formName : 0);
  return document.forms[index];
}

////////////////////////////////////////////////////////////////////////////////

function getFormFieldWithName(fieldName, formName)
{
  var form = getForm(formName);
  return eval("form." + fieldName);
}

////////////////////////////////////////////////////////////////////////////////

function setFieldValue(field, fieldValue) { field.value = fieldValue; }

////////////////////////////////////////////////////////////////////////////////

function populateForm(formName)
{
  var requestFields = getRequestFields();
  for (var fieldName in requestFields)
  {
    var fieldValue = requestFields[fieldName];
    var field      = getFormFieldWithName(fieldName, formName);
    setFieldValue(field, fieldValue);
  }
}


////////////////////////////////////////////////////////////////////////////////
// REQUEST
////////////////////////////////////////////////////////////////////////////////

function getRequestFields()
{
  var fields = new Array();
  var query  = window.location.search.substring(1);
  var pairs = query.split("&");
  for (var i = 0; i < pairs.length; i++)
  {
    var pair = pairs[i];
    if (pair.indexOf("=") > -1)
    {
      var parts  = pair.split("=");
      var name   = parts[0];
      var value  = parts[1];
      fields[name] = unescape(value);
    }
  }
  return fields;
}


////////////////////////////////////////////////////////////////////////////////
// COOKIES
////////////////////////////////////////////////////////////////////////////////

function cookie(name, defaultValue)
{
  defaultValue = (defaultValue == null ? "" : defaultValue);
  var temp = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
  return (temp ? unescape(temp[2]) : defaultValue);
}


////////////////////////////////////////////////////////////////////////////////
// AMAZON
////////////////////////////////////////////////////////////////////////////////

function buyAmazon(sku) { document.write(createBuyAmazonHtmlForSku(sku)); }

////////////////////////////////////////////////////////////////////////////////

function handleBuyAmazonLinks()
{
  if (document.body
   && document.body.className
   && (document.body.className.indexOf("buyAmazon")  >= 0
    || document.body.className.indexOf("buy-amazon") >= 0))
  {
    addBuyAmazonLinks();
  }
}

////////////////////////////////////////////////////////////////////////////////

function addBuyAmazonLinks()
{
  var elements = document.getElementsByTagName("span");
  for (var i = 0; i < elements.length; i++)
  {
    var element = elements[i];
    if (element.className == "amazon")
    {
      var sku = element.id.replace(/^sku-/,"").replace(/-.*$/,"");
      if (sku)
      {
        element.innerHTML = createBuyAmazonHtmlForSku(sku);
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////

function createBuyAmazonHtmlForSku(sku)
{
  return '<a class="buy-amazon" href="http://www.amazon.com/gp/product/' + sku + '?'
    + 'ie=UTF8&tag=tripalot-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=' + sku + '">'
    + '<img src="http://tripalot.com/shared/images/buy-amazon.gif" alt="Buy from Amazon" />'
    + '<img src="http://www.assoc-amazon.com/e/ir?t=tripalot-20&l=as2&o=1&a=' + sku + '" width="1" height="1" alt="" /></a>';
}


////////////////////////////////////////////////////////////////////////////////
// CSS TOGGLE
////////////////////////////////////////////////////////////////////////////////

function disableCss() { changeCss(0); }
function enableCss()  { changeCss(1); }

////////////////////////////////////////////////////////////////////////////////

function changeCss(cssIndex)
{
  var links  = getElementsWithTagName("link");
  var styles = getElementsWithTagName("style");
//alert("This page contains = " + links.length + " links and " + styles.length + " styles");
  if (!links && !styles)
  {
    alert("This script does not work in your browser");
  }
  for (var i = 0; i < links.length; i++)
  {
    links[i].disabled = (i != cssIndex - 1);
  }
  for (var i = 0; i < styles.length; i++)
  {
    styles[i].disabled = (i != cssIndex - 1);
  }
}

////////////////////////////////////////////////////////////////////////////////
// 2011-06-02 txe start //

function addCssToggle()
{
  var element = document.getElementById("header");  
  element.innerHTML = createCssToggleHtml() + element.innerHTML;
}

////////////////////////////////////////////////////////////////////////////////

function createCssToggleHtml()
{
  return '<div id="cssSwitcher">'
       + '  <a id="enableCss"  href="javascript:enableCss()"  title="Enable CSS" class="hidden">enable css</a>'
       + '  <a id="disableCss" href="javascript:disableCss()" title="Disable CSS">disable css</a>'
       + '  <span class="hidden">'
       + '    You\'re viewing this page without CSS because either'
       + '    your browser doesn\'t support it,'
       + '    you disabled CSS in your browser or clicked the "disable css" link,'
       + '    or are viewing offline without the associated CSS file.'
       + '    The page should still be usable without CSS.</span>'
       + '  <hr class="hidden"></hr>'
       + '</div>';       
}

// 2011-06-02 txe end //


////////////////////////////////////////////////////////////////////////////////
// LOCAL (OFFLINE) VIEWING
////////////////////////////////////////////////////////////////////////////////

function getLocalRoot()            { return "d:\\www"; }  // for flexibility might want to detect from host link //


// 2011-08-16 txe start //        
function getMp3Root()              { return "d:"; } 
// 2011-08-16 txe end //        


function getCurrentPath()          { return normalizeSlashes(document.location.pathname); }
//function isLocalHost(host)         { return (host == "") || (host == "localhost"); } // Opera uses "localhost" //
function isLocalHost(host)         { return (host == ""); }
function isCurrentXml()            { return (getCurrentPath().indexOf(".xml") > getCurrentPath().indexOf("/")); }
function isOffline()               { return isLocalHost(document.location.hostname); }
function isLocalPath(path)         { return (path.indexOf("http://") != 0) && (path.indexOf("ftp://") != 0); }  // fix later //
function normalizeSlashes(oldPath) { return oldPath.replace(/\\/g, "/").replace(/\/\//g, "/"); }

////////////////////////////////////////////////////////////////////////////////

function getDocumentLinks()
{
  var links = (document.links ? document.links : new Array());
  if (links.length == 0)
  {
    var elements = document.getElementsByTagName("a");
    for (var i = 0; i < elements.length; i++)
    {
      if (elements[i].hasAttribute("href"))
      {
        links.push(elements[i]);
      }
    }
  }
  return links;
}

////////////////////////////////////////////////////////////////////////////////
// 2011-07-18 txe start //

function getSiteCodeFromPath(path)
{
  var siteCode = path;


// 2011-12-11 txe start //
//  siteCode     = siteCode.replace(/^(\/d\:\/www)?\//, "");
  siteCode     = siteCode.replace(/^(\/[a-z]\:\/www)?\//i, "");
// 2011-12-11 txe end //


  siteCode     = siteCode.replace(/\/.*$/,            "");
//alert("getSiteCodeFromPath('" + path + "') = '" + siteCode + "'");
  return siteCode;
}

////////////////////////////////////////////////////////////////////////////////

function getPageCodeFromPath(path)
{
  var pageCode = path;


// 2011-12-11 txe start //
//  pageCode     = pageCode.replace(/^(\/d\:\/www)?\//, "");
  pageCode     = pageCode.replace(/^(\/[a-z]\:\/www)?\//i, "");
// 2011-12-11 txe end //


  pageCode     = pageCode.replace(getSiteCodeFromPath(path) + "/", "");


// 2011-07-27 txe start //
//  pageCode     = pageCode.replace(/\/.*$/,            "");
  pageCode     = pageCode.replace(/\/$/, "");
// 2011-07-27 txe end //


  pageCode     = (pageCode == "" ? "home" : pageCode);
//alert("getPageCodeFromPath('" + path + "') = '" + pageCode + "'");
  return pageCode;
}

////////////////////////////////////////////////////////////////////////////////

function getLocalPathForPath(path)
{
  var siteCode  = getSiteCodeFromPath(path);
  var pageCode  = getPageCodeFromPath(path);
  var newPath   = "/" + siteCode + "/htm/" + pageCode + ".htm";
//  var localPath = normalizeSlashes(getLocalRoot()) + newPath;
//alert("getLocalPathForPath('" + path + "') = '" + localPath + "'");
//  return localPath;
  return newPath;
}


////////////////////////////////////////////////////////////////////////////////

function handleLocalCss()
{
//alert("handleLocalCss() called");
  var currentPath = getCurrentPath();
//alert("currentPath = '" + currentPath + "'");
//alert("isOffline() = '" + isOffline() + "'");
//alert("getSiteCodeFromPath('" + currentPath + "') = '" + getSiteCodeFromPath(currentPath) + "'");
//alert("isNormalizedSiteCode(getSiteCodeFromPath('" + currentPath + "')) = '" + isNormalizedSiteCode(getSiteCodeFromPath(currentPath)) + "'");

//alert("isNormalizablePath('" + currentPath + "') = '" + isNormalizablePath(currentPath) + "'");
  if (isOffline() && isNormalizablePath(currentPath))
  {
//alert("in if");
    var siteCode    = getSiteCodeFromPath(currentPath);
//alert("siteCode = '" + siteCode + "'");
    var localCssUrl = "file:///" + normalizeSlashes(getLocalRoot()) + "/" + siteCode + "/css/" + siteCode + ".css";
//alert("localCssUrl = '" + localCssUrl + "'");
//alert("localCssUrl = '" + localCssUrl + "'");
//    document.writeln("<link rel='stylesheet' type='text/css' href='" + localCssUrl + "' />");
    var html = "<link rel='stylesheet' type='text/css' href='" + localCssUrl + "' />";
//alert("html '" + html + "'");
    document.writeln(html);
//alert("wrote html to document");
  }
}

////////////////////////////////////////////////////////////////////////////////

function handleLocalImages()
{
  if (isOffline())
  {
    var images = getElementsWithTagName("img");
    for (var i = 0; i < images.length; i++)
    {
      var image   = images[i];
      var oldPath = image.src;
      if (isLocalPath(oldPath))
      {
        var newPath = oldPath.replace("file:///", "file:///" + normalizeSlashes(getLocalRoot()) + "/");
//alert("handleLocalImages(): '" + oldPath + "' --> '" + newPath + "'");        
        image.src = newPath;
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////

handleLocalCss(); // execute in head //



// 2011-07-18 txe end //
////////////////////////////////////////////////////////////////////////////////

// 2011-07-18 txe start //
//  function handleDirectoryLinks()
function handleLocalLinks()
// 2011-07-18 txe end //
{
  if (isOffline() || isCurrentXml())
  {
    var documentLinks = getDocumentLinks();
    for (var i = 0; i < documentLinks.length; i++)
    {
      var link        = documentLinks[i];
      var path        = normalizeSlashes(link.pathname);
      var oldPath     = link.pathname;
      var newPath     = oldPath;
      var isLocal     = isLocalHost(link.hostname);
      var isTargetXml = (path.indexOf("/xml/") > -1);


// 2011-08-16 txe start //        
      var isTargetMp3 = (path.indexOf("/mp3/") > -1);
// 2011-08-16 txe end //        


      var isDirectory = (path.lastIndexOf("/") > path.lastIndexOf("."));

      if ((isLocal || isTargetXml) && isDirectory)
      {


// 2011-08-08 txe start //        
//        if (isNormalizablePath(path))
        var isHost = (link.className == "host");        
        if (!isHost && isNormalizablePath(path))
// 2011-08-08 txe end //        

        
        {
          newPath         = getLocalPathForPath(path);
        }
        else
        {        
          var pathNoSlash = path.replace(/\/$/, "");
          pathNoSlash     = pathNoSlash.replace(/\/xml$/, "/xml/home");  // handle home page for xml //
//alert("isHost: " + link);
          var suffix      = (isTargetXml ? ".xml" : (isHost ? "/tripalot.html" : "/index.html"));
          newPath         = pathNoSlash + suffix;        
        }
      }

      if (isLocal)
      {
        var isLegitPath = (newPath.indexOf(":\/") > 0);


// 2011-08-16 txe start //        
//        newPath         = (isLegitPath ? "" : normalizeSlashes(getLocalRoot())) + newPath;
        if (isTargetMp3)
        {
          newPath = normalizeSlashes(getMp3Root()) + newPath;
        }
        else if (!isLegitPath)
        {
          newPath = normalizeSlashes(getLocalRoot()) + newPath;
        }
// 2011-08-16 txe end //        


      }
            
      if (newPath != oldPath)
      {                
        var oldHash     = link.hash;
        var newHash     = (oldHash.indexOf("#") == 0 ? oldHash.substring(1) : oldHash);
        var debugInfo   = " ( " + oldPath + oldHash + " --> " + newPath + (newHash ? "#" + newHash : "") + ")";
        link.href       = link.href.replace(oldPath, newPath);  // works for opera, mozilla //
        link.pathname   = newPath;                              // works for ie //
        link.title     += debugInfo;
        link.hash       = (newHash ? newHash : oldHash);  // we need this to preserve the bookmark //
      }
    }


// 2011-07-18 txe start //    
    handleLocalImages();
// 2011-07-18 txe start //    


  }
}


////////////////////////////////////////////////////////////////////////////////
// GOOGLE ANALYTICS
////////////////////////////////////////////////////////////////////////////////
// 2011-08-18 txe start //

function trackEvent(element,category, action, label)
{
//alert("trackDownload(element,'" + category + "', '" + action + "', '" + label + "') called");
  if (_gaq)
  {
    _gaq.push(["_trackEvent", category, action, label]);        
    setTimeout(function(){location.href=element.href;}, 200);
  }   
  return !_gaq;
}


// 2011-08-18 txe end //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
