/****************************************************
** functions.js - Main javascript function library **
****************************************************/

/* Init actions */
function changeOnSubmit() { // disable enter key form submission (chrome, safari)
  //oldsubmit = document.forms[0].onsubmit;
  document.forms[0].action = "javascript:return false();";
  /*document.forms[0].onsubmit = function() {
    //oldsubmit();
    return false;
  }*/
}
getTopic( TOPIC_ONLOAD ).addListener( 'changeOnSubmit()' );




/* browser detection, used to get visitor's browser name and version */
var BrowserDetect = {
  init: function () {
    this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    this.version = this.searchVersion(navigator.userAgent)
      || this.searchVersion(navigator.appVersion)
      || "an unknown version";
    this.OS = this.searchString(this.dataOS) || "an unknown OS";
  },
  searchString: function (data) {
    for (var i=0;i<data.length;i++)  {
      var dataString = data[i].string;
      var dataProp = data[i].prop;
      this.versionSearchString = data[i].versionSearch || data[i].identity;
      if (dataString) {
        if (dataString.indexOf(data[i].subString) != -1)
          return data[i].identity;
      }
      else if (dataProp)
        return data[i].identity;
    }
  },
  searchVersion: function (dataString) {
    var index = dataString.indexOf(this.versionSearchString);
    if (index == -1) return;
    return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
  },
  dataBrowser: [
    {
      string: navigator.userAgent,
      subString: "Chrome",
      identity: "Chrome"
    },
    {   string: navigator.userAgent,
      subString: "OmniWeb",
      versionSearch: "OmniWeb/",
      identity: "OmniWeb"
    },
    {
      string: navigator.vendor,
      subString: "Apple",
      identity: "Safari",
      versionSearch: "Version"
    },
    {
      prop: window.opera,
      identity: "Opera"
    },
    {
      string: navigator.vendor,
      subString: "iCab",
      identity: "iCab"
    },
    {
      string: navigator.vendor,
      subString: "KDE",
      identity: "Konqueror"
    },
    {
      string: navigator.userAgent,
      subString: "Firefox",
      identity: "Firefox"
    },
    {
      string: navigator.vendor,
      subString: "Camino",
      identity: "Camino"
    },
    {    // for newer Netscapes (6+)
      string: navigator.userAgent,
      subString: "Netscape",
      identity: "Netscape"
    },
    {
      string: navigator.userAgent,
      subString: "MSIE",
      identity: "Explorer",
      versionSearch: "MSIE"
    },
    {
      string: navigator.userAgent,
      subString: "Gecko",
      identity: "Mozilla",
      versionSearch: "rv"
    },
    {     // for older Netscapes (4-)
      string: navigator.userAgent,
      subString: "Mozilla",
      identity: "Netscape",
      versionSearch: "Mozilla"
    }
  ],
  dataOS : [
    {
      string: navigator.platform,
      subString: "Win",
      identity: "Windows"
    },
    {
      string: navigator.platform,
      subString: "Mac",
      identity: "Mac"
    },
    {
      string: navigator.platform,
      subString: "Linux",
      identity: "Linux"
    }
  ]

};
BrowserDetect.init();

function includeCss(cssHref) // include a css file dynamically based on filename
{
  var headID = document.getElementsByTagName("head")[0];
  var cssNode = document.createElement('link');
  cssNode.type = 'text/css';
  cssNode.rel = 'stylesheet';
  cssNode.href = urlPrefix + templateHome + 'css/browsers/' + cssHref;
  //cssNode.media = 'screen';
  headID.appendChild(cssNode);
}




/* browser hack css includes */
var browserName = BrowserDetect.browser.toLowerCase();
switch(browserName) { // include individual css based on browser name and version
  case "safari": // safari
    includeCss('safari.css');
    break;
  case "firefox": // firefox
    if(BrowserDetect.version >= 3) { includeCss('ff3.css'); browserName += "3"; } // ff3+
    else if(BrowserDetect.version < 3) { includeCss('ff2.css'); browserName += "2"; } // ff2-
    break;
  case "chrome": // chrome
    includeCss('chrome.css');
    break;
  case "opera": // opera
    includeCss('opera.css');
    break;
  case "explorer": // ie
    if(BrowserDetect.version >= 8) { includeCss('ie8.css'); browserName += "8"; } // ie8+
    else if(BrowserDetect.version == 7) { includeCss('ie7.css'); browserName += "7"; } // ie7
    else if(BrowserDetect.version < 7) { includeCss('ie6.css'); browserName += "6"; } // ie6-
    break;
}


/* nav menu functions */
var activeNav = [];
var openNav = [];
var navTimer = [];
var selectStatus = [];
var defaultOfficeId = "SanAntonio";

function showNavMenu(navId, navNum) // unhide nav menu content to display
{
  if(document.getElementById(navId + navNum)) { // just in case page hasn't finished loading yet
    openNav[navId] = true;
    if(navNum != activeNav[navId]) { // if not dealing with currently opened menu
      if(activeNav[navId]) { // if any open
        document.getElementById(navId + activeNav[navId]).style.display = "none";
        if(navId == "navMenu") { // also change top nav button class
          document.getElementById("navLink" + activeNav[navId]).className = "";
        }
        else if(navId == "navOfficeInfo") { // change office image too
          document.getElementById("navOfficeImage" + activeNav[navId]).style.display = "none";
        }
      }
      if(navId == "navOfficeInfo" && navNum != defaultOfficeId) { // hide office image too
        document.getElementById("navOfficeInfo" + defaultOfficeId).style.display = "none";
        document.getElementById("navOfficeImage" + defaultOfficeId).style.display = "none";
      }

      document.getElementById(navId + navNum).style.display = "block";
      if(navId == "navMenu") { // also change top nav button class
        document.getElementById("navLink" + navNum).className = "active";
      }
      else if(navId == "navOfficeInfo") { // change office image too
        document.getElementById("navOfficeImage" + navNum).style.display = "block";
      }
      activeNav[navId] = navNum;

      selectStatus[navId] = false;
    }
    if(navTimer[navId]) {
      clearTimeout(navTimer[navId]); // cancel any pending menu hiding
    }
  }
}


function hideNavMenu(navId) // initialize a menu hide with a delay
{
  openNav[navId] = false;
  if(selectStatus[navId] == undefined || selectStatus[navId] == false) { // hide
    navTimer[navId] = setTimeout("hideHelper('" + navId + "')", 250); // queue up menu hiding
  }
/*  else if(browserName.indexOf("explorer") == -1) { // ie handles select hovers weirdly, so do nothing until they have unselected the box
    navTimer[navId] = setTimeout("hideHelper('" + navId + "')", 1000); // queue up menu hiding
  }*/
}

function hideHelper(navId) // hide menu
{
  if(openNav[navId] == undefined || openNav[navId] == false) { // hide
    if(activeNav[navId]) { // if any open
      var doHide = true;
      if(navId == "navMenu") { // also change top nav button class
        document.getElementById("navLink" + activeNav[navId]).className = "";
      }
      else if(navId == "navOfficeInfo") { // change office image too
        if(activeNav[navId] == defaultOfficeId) { // moving off default office, do nothing
          doHide = false;
        }
        else {
          document.getElementById("navOfficeImage" + activeNav[navId]).style.display = "none";
          // turn on default (San Antonio)
          document.getElementById("navOfficeInfo" + defaultOfficeId).style.display = "block";
          document.getElementById("navOfficeImage" + defaultOfficeId).style.display = "block";
        }
      }

      if(doHide) {
        document.getElementById(navId + activeNav[navId]).style.display = "none";
      }
      activeNav[navId] = null;
    }
  }
}

function selectOpen(navId) // don't hide menu when select is open
{
  clearTimeout(navTimer[navId]); // cancel any pending menu hiding
  selectStatus[navId] = true;
}
function selectClose(navId) // select is closed, no longer under anti-close protection
{
  selectStatus[navId] = false;
  clearTimeout(navTimer[navId]); // cancel any pending menu hiding
  navTimer[navId] = setTimeout("hideHelper('" + navId + "')", 1000); // queue up menu hiding
}


/* Utility Functions */
function imgro(item) // rollover image replacement
{
  var imgpath = item.src;
  if(imgpath.match("_ro") == null) {
    var last_dot = imgpath.lastIndexOf(".");
    var x = imgpath.substring(0, last_dot) + "_ro" + imgpath.substring(last_dot);
    item.src = x;
  }
}
function imgundo(item) // unrollover image restoration
{
  var imgpath = item.src;
  if(imgpath.match("_ro") != null) {
    var x = imgpath.replace('_ro.','.');
    item.src = x;
  }
}

function checkEnter(e, funcToCall) // uses enter key to submit form
{
  if(!e) {
    e = window.event;
  }
  var characterCode = (e && e.which ? e.which : (e.keyCode ? e.keyCode : event.keyCode));
  //var characterCode = (((!e || e.keycode) && !e.which) ? (!e ? event.keyCode : e.keycode) : e.which);

  if(characterCode == 13) { // enter key
    (e ? e : event).returnValue = false;
    (e ? e : event).cancelBubble = true;
    funcToCall(); // submit the form
    return false;
  }
  else {
    return true;
  }
}


/* Email and Print Functions */
var MAILTO_CONFIRMATION = "The purpose of our website is to inform our clients and friends about the firm and of recent legal developments in different areas of law. It is not intended nor should it be used as a substitute for specific legal advice or opinions since legal counsel may be given only in response to inquiries regarding particular situations.  While we would like to hear from you, an attorney/client relationship cannot be established until we know that doing so will not create a conflict of interest and until we reach an agreement on terms of representation. Therefore do not send us confidential information about any matter that may involve you at this time.";
var VCARD_CONFIRMATION = "";

function mailTo(email)
{
  //if(confirm(MAILTO_CONFIRMATION)) {
    window.parent.location = "mailto:" + email;
  //}
}

function vCard(path)
{
  //if(confirm(VCARD_CONFIRMATION)) {
    window.parent.location = path;
  //}
}

function printPage()
{
  var url = window.location.href;
  url += (url.indexOf("?") == -1 ? "?" : "&") + "printver=true";
  window.open(url, 'Print', 'width=725,height=475,directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,top=20,left=20');
}

function emailPage()
{
  var url = window.location.href;
  //if(confirm(MAILTO_CONFIRMATION)) {
    window.location = "mailto:?body=" + escape(url);
  //}
}


function printPDF( pagePath, templateName, designName )
{
  var url = window.location.href;
  url += (url.indexOf("?") == -1 ? "?" : "&") + "printTo=pdfw";

  if(pagePath) {
    url += "&pagePath=" + pagePath;
  }

  if(templateName) {
    url += "&templateName=" + templateName;
  }

  if(designName) {
    url += "&designName=" + designName;
  }

  window.location = url;
}


/*
  Developed by Robert Nyman, http://www.robertnyman.com
  Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function(className, tag, elm) {
  if(document.getElementsByClassName) {
    getElementsByClassName = function(className, tag, elm) {
      elm = elm || document;
      var elements = elm.getElementsByClassName(className),
        nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
        returnElements = [],
        current;
      for(var i=0, il=elements.length; i<il; i+=1){
        current = elements[i];
        if(!nodeName || nodeName.test(current.nodeName)) {
          returnElements.push(current);
        }
      }
      return returnElements;
    };
  }
  else if(document.evaluate) {
    getElementsByClassName = function(className, tag, elm) {
      tag = tag || "*";
      elm = elm || document;
      var classes = className.split(" "),
        classesToCheck = "",
        xhtmlNamespace = "http://www.w3.org/1999/xhtml",
        namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
        returnElements = [],
        elements,
        node;
      for(var j=0, jl=classes.length; j<jl; j+=1){
        classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
      }
      try  {
        elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
      }
      catch (e) {
        elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
      }
      while ((node = elements.iterateNext())) {
        returnElements.push(node);
      }
      return returnElements;
    };
  }
  else {
    getElementsByClassName = function(className, tag, elm) {
      tag = tag || "*";
      elm = elm || document;
      var classes = className.split(" "),
        classesToCheck = [],
        elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
        current,
        returnElements = [],
        match;
      for(var k=0, kl=classes.length; k<kl; k+=1){
        classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
      }
      for(var l=0, ll=elements.length; l<ll; l+=1){
        current = elements[l];
        match = false;
        for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
          match = classesToCheck[m].test(current.className);
          if(!match) {
            break;
          }
        }
        if(match) {
          returnElements.push(current);
        }
      }
      return returnElements;
    };
  }
  return getElementsByClassName(className, tag, elm);
};


// check all divs in narrow page column (if exists) to see if anything is drawn to the page, if not then hide it (allowing the wide column to be 100% width)
function hideNarrowColIfEmpty() {
  var narrowCol = getElementsByClassName("narrow-col", "td", document.getElementById("contentBody"));

  if(narrowCol.length > 0) { // if narrow col exists
    var narrowColDivs = narrowCol[0].getElementsByTagName("DIV");
    var totalHeight = 0;
    var temp;
    var pb;

    for(var i=0; i<narrowColDivs.length; i++) { // loop through all narrow col divs
      if((temp = narrowColDivs[i].id) && temp.indexOf("portlet") >= 0) { // one of the main portlets
        temp = narrowColDivs[i].offsetHeight;
        if(temp > 0) {
          pb = parseInt(getStyle(narrowColDivs[i], "paddingBottom"));
          temp = (temp >= pb ? (temp - pb) : temp);
          totalHeight += temp;
        }
      }
    }

    if(totalHeight <= 0) {
      narrowCol[0].style.display = "none";
      var wideCol = getElementsByClassName("wide-col", "td", document.getElementById("contentBody"));

      if(wideCol.length > 0) { // if wide col exists
        wideCol[0].className = wideCol[0].className.replace("wide-col", "");
      }
    }
  }
}
