////////////////////////////////////////////////////////////////////////////////
//
// File:     shared/js/shared.js
//
// Contents: Javascript that can be used by any of my personal 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 targetIsXml 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().
//
////////////////////////////////////////////////////////////////////////////////


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

function handleLoad()
{
  handleDirectoryLinks();
  handleBuyAmazonLinks();
}


////////////////////////////////////////////////////////////////////////////////
// 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;
  }
}


////////////////////////////////////////////////////////////////////////////////
// OFFLINE VIEWING
////////////////////////////////////////////////////////////////////////////////

function handleDirectoryLinks()
{
  var currentPath  = normalizeSlashes(document.location.pathname);
  var currentIsXml = (currentPath.indexOf(".xml") > currentPath.indexOf("/"));
  var isOffline    = isLocalHost(document.location.hostname);
  if (isOffline || currentIsXml)
  {
    var documentLinks = getDocumentLinks();
    for (var i = 0; i < documentLinks.length; i++)
    {
      var link        = documentLinks[i];
      var path        = normalizeSlashes(link.pathname);
      var targetIsXml = (path.indexOf("/xml/") > -1);
      var isLocal     = isLocalHost(link.hostname);
      var isDirectory = (path.lastIndexOf("/") > path.lastIndexOf("."));
      if ((isLocal || targetIsXml) && isDirectory)
      {
        var hash        = link.hash;
        var pathNoSlash = path.replace(/\/$/, "");
        pathNoSlash     = pathNoSlash.replace(/\/xml$/, "/xml/home");  // handle home page for xml //
        var oldPath     = link.pathname;
        var suffix      = (targetIsXml ? ".xml" : "/index.html");
        var newPath     = pathNoSlash + suffix;
        link.href       = link.href.replace(oldPath, newPath);  // works for opera, mozilla //
        link.pathname   = newPath;                              // works for ie //
        var newHash     = (hash.indexOf("#") == 0 ? hash.substring(1) : hash);
        if (newHash)
        {
          link.hash     = newHash;  // we need this to preserve the bookmark //
        }
      }
    }
  }
}

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

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;
}

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

function isLocalHost(host) { return (host == "") || (host == "localhost"); } // Opera uses "localhost" //

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

function normalizeSlashes(oldPath)
{
  var newPath = oldPath.replace(/\\/g,   "/");
  newPath = newPath.replace(/\/\//g, "/");
  return newPath;
}


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

function openWindow(url, name, settings)
{
  name    = (name     ? name     : "_blank");

// 2009-06-15 txe start //
//  var win = (features ? window.open(url, name, features) : window.open(url,name));
//  win.focus();

  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;
// 2009-06-15 txe end //
}

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

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

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

function popupUrlNameWHXYExtra(url,name,w,h,x,y,extra) { return popup(url, name, "height=" + h + ",width=" + w + ",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 popupSmall(element,  name) { return popupUrlNameWHExtra(element.href,name,500,500); }
function popupMedium(element, name) { return popupUrlNameWHExtra(element.href,name,600,600); }
function popupLarge(element,  name) { return popupUrlNameWHExtra(element.href,name,800,600); }
function popupHuge(element,   name) { return popupUrlNameWHExtra(element.href,name,1000,700); }

// 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); }

////////////////////////////////////////////////////////////////////////////////
// CSS
////////////////////////////////////////////////////////////////////////////////

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);
  }
}


////////////////////////////////////////////////////////////////////////////////
// WRAPPERS
////////////////////////////////////////////////////////////////////////////////

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;
}


////////////////////////////////////////////////////////////////////////////////
// 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>';
}

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