/* PAGE INITIALIZATION FUNCTIONS */
var addEvent = function(obj, type, fn) { //http://www.ilfilosofo.com/blog/2008/04/14/addevent-preserving-this/
  if (obj.addEventListener) {
    obj.addEventListener(type, fn, false);
  } else if (obj.attachEvent) {
    obj.attachEvent('on' + type, function() { return fn.apply(obj, new Array(window.event));});
  }
}
addEvent(window, 'load', preProcessPage);

function preProcessPage() {
	if (!document.getElementsByTagName || (!document.getElementById || (!document.createElement || !document.createTextNode))) return false;
	processPage();
}

function processPage() {
  processLinks();
  processForms();
  clearSearch();
  fixColumns();
  forceDownload();
  //processDivs();
}

/* INDIVIDUAL ELEMENT INITIALIZATIONS */
function clearSearch() {
  if (document.getElementById('edit-keys')) {
    var theElement = document.getElementById('edit-keys');
    theElement.value = theElement.value.replace(/( AND [a-zA-Z]*:[a-zA-Z0-9_-]*).*/, '');
    theElement.value = theElement.value.replace(/([a-zA-Z]*:[a-zA-Z0-9_-]*).*/, '');
    //theElement.value = theElement.value.replace('the is ','');
  }
}

function forceDownload() {
  var bodyNode = document.getElementsByTagName('body')[0];
  if (bodyNode.className && (/page-news/.test(bodyNode.className))) {
    var allDivs = bodyNode.getElementsByTagName('div');
    var targetDiv = false;
    var findTarget = function(theElement) {
      if (theElement.className && (/filefield-file/.test(theElement.className))) {
        if (targetDiv == false) {
          targetDiv = theElement;
        }
      }
    }
    forEach(allDivs,findTarget);
    if (targetDiv) {
      var targetLink = false;
      var allLinks = targetDiv.getElementsByTagName("a");
      if (allLinks.length > 0) {
        targetLink = allLinks[0];
      }
      if (targetLink) {
        var fileWindow = window.open(targetLink.getAttribute('href'));
      }
    }
  }
}

function fixColumns() {
  var maxHeight = 0;
  var rawColumns = ['navigation','content'];
  var allColumns = [];
  var getHeight = function(theColumn) {
    if (document.getElementById(theColumn)) {
      var thisCol = document.getElementById(theColumn);
      allColumns.push(thisCol);
      var thisHeight = thisCol.offsetHeight;
      if (thisHeight > maxHeight) {
        maxHeight = thisHeight;
      }
    }
  }
  forEach(rawColumns, getHeight);
  var setHeight = function(theColumn) {
    //theColumn.style.height = maxHeight + 'px';
    theColumn.style.minHeight = maxHeight + 'px';
  }
  forEach(allColumns, setHeight);
}


function processDivs() {
  var allDivs = document.getElementsByTagName("div");
  var viewDivs = new Array();
  var fixDiv = function(theElement) {
    if (hasClassHook(theElement)) {
    } else if (theElement.className) {
      if (/view-content/.test(theElement.className)) {
        viewDivs.push(theElement);
      }
    }
  }
  forEach(allDivs,fixDiv);
  var fixView = function(theElement) {
    setViewDiv(theElement);
  }
  forEach(viewDivs,fixView);
}

function setViewDiv(theElement) {
  var smallHeaders = theElement.getElementsByTagName("h3");
  while (smallHeaders.length > 0) {
    var oldHeader = smallHeaders[0];
    var newHeader = document.createElement("h2");
    newHeader.innerHTML = oldHeader.innerHTML;
    oldHeader.parentNode.replaceChild(newHeader,oldHeader);
  }
}

function processLinks() {
  var allLinks = document.getElementsByTagName("a");
  var fixLink = function(theElement) {
    if (theElement.href && (theElement.href.indexOf("#") != -1)) {
      removeClass(theElement,'active');
    }
    if (theElement.href && (theElement.href.toLowerCase().indexOf("mailto") == 0)) {
      theElement.onclick = function() {
        return (confirm('NOTICE:  Submission of a consultation request does not establish an attorney-client relationship, nor does it legally bind Blakely, Sokoloff, Taylor, & Zafman to provide a consultation.  If you send us confidential or sensitive information prior to establishment of an attorney-client relationship, your communication will not be treated as privileged or confidential.'));
      }
    }
    if (hasClassHook(theElement)) {
      if (/js_tabTrigger/.test(theElement.className)) {
        theElement.onclick = function() {
          switchTab(this);
          return false;
        }
      } if (/js_doPopup/.test(theElement.className)) {
        theElement.onclick = function() {
          var newWindow = window.open(this.href);
          return false;
        }
      }
    }
  }
  forEach(allLinks,fixLink);
}

function switchTab(theLink) {
  var theContainerId = getExtensionFromClass(theLink,"js_tabTrigger_");
  if (theContainerId && document.getElementById(theContainerId)) {
    var theContainer = document.getElementById(theContainerId);
    var theTriggers = new Array();
    var theTargets = new Array();
    var tabNumber = 0;
    var containerLinks = theContainer.getElementsByTagName("a");
    var grabTrigger = function(theElement) {
      if (theElement.className && /js_tabTrigger/.test(theElement.className)) {
        theTriggers.push(theElement);
      }
    }
    forEach(containerLinks,grabTrigger);
    var containerDivs = theContainer.getElementsByTagName("div");
    var grabTarget = function(theElement) {
      if (theElement.className && /js_tabTarget/.test(theElement.className)) {
        theTargets.push(theElement);
      } 
    }
    forEach(containerDivs,grabTarget);
    for (var i=0; i<theTriggers.length; i++) {
      var theElement = theTriggers[i];
      if (theElement == theLink) {
        addClass(theElement,"active");
        tabNumber = i;
      } else {
        removeClass(theElement,"active");
      }
    }
    for (var i=0; i<theTargets.length; i++) {
      var theElement = theTargets[i];
      if (i == tabNumber) {
        removeClass(theElement,"noshow");
      } else {
        addClass(theElement,"noshow");
      }
    }
  }
}

function processForms() {
  var allForms = document.getElementsByTagName('form');
  var fixForm = function(theForm) {
    if (hasClassHook(theForm) || (theForm.id == "search-block-form")) {
      if (theForm.id == "search-block-form") {
        initCategories(theForm);
      }
    }
  }
  forEach(allForms,fixForm);
}

function initCategories(theForm) {
  var formInputs = theForm.getElementsByTagName('input');
  for (var j=0; j<formInputs.length; j++) {
    var thisInput = formInputs[j];
    if (thisInput.type == "submit") {
      thisInput.onclick = function() {
        return popCategories(this);
      }
    }
  }
}

function popCategories(theSubmit) {
  var theForm = getParentElement(theSubmit,'form');
  var theInputs = theForm.getElementsByTagName('input');
  var theSelects = theForm.getElementsByTagName('select');
  var theTarget = false;
  var theVisible = false;
  var theTriggers = new Array();
  var checkTarget = function(theElement) {
    if (theElement.className && /js_popTarget/.test(theElement.className)) {
      theTarget = theElement;
      theTarget.value = '';
    } else if (theElement.className && /js_popVisible/.test(theElement.className)) {
      theVisible = theElement;
    }
  }
  forEach(theInputs,checkTarget);
  var popTrigger = function(theElement) {
    if ((theElement.className && /js_popTrigger/.test(theElement.className)) && (theElement.value != '')) {
      theTriggers.push(theElement.value);
    }
  }
  forEach(theSelects,popTrigger);
  if (theVisible && theTarget && (theVisible.value != '')) {
    //theTarget.value = '"'+theVisible.value+'"';
    var visibleValue = theVisible.value.split(" ");
    theTarget.value = visibleValue.join(' AND ');
  }
  if ((theTriggers.length > 0) && (theTarget)) {
  	if (theTarget.value != '') {
  		theTarget.value += " AND ";
  	}
    if (theTriggers.length > 1) {
      theTarget.value += "category:(" +theTriggers.join(' AND ')+ ")";
    } else {
      theTarget.value += "category:" +theTriggers[0];
    }
  }
  return true;
}

/* UTILITY FUNCTIONS */
function forEach(array, action) {
  for (var i=0; i < array.length; i++) {
    action(array[i]);
  }
}

function removeChildNodes(theElement) {
  while (theElement.hasChildNodes()) {
    theElement.removeChild(theElement.firstChild);
  }
}

function getParentElement(theElement, targetNodeName) {
  var bodyNode = document.getElementsByTagName("body")[0];
  var currentParent = theElement;
  var targetNodeName = targetNodeName.toLowerCase();
  while ((currentParent.nodeName.toLowerCase() != targetNodeName) && (currentParent != bodyNode)) {
    currentParent = currentParent.parentNode;
  }
  return currentParent;
}

function stripWhitespace(theString) {
	return theString.replace(/^\s*|\s*$/g,'');
}

function addClass(theElement,theClass) {
	if (!theElement.className) {
		theElement.className = theClass;
	} else if (theElement.className.indexOf(theClass) == -1) {
		theElement.className += (" " + theClass);
	}
}

function removeClass(theElement,theClass) {
  if (theElement.className && theElement.className.indexOf(theClass) != -1) {
    theElement.className = stripWhitespace(theElement.className.replace(theClass,""))
  }
}

function hasClassHook(theElement) {
  return (theElement.className && /js_/.test(theElement.className));
}

function getExtensionFromClass(theElement,theKey) {
	var theExtension = false;
	if (theElement.className) {
    var findExtension = function(thisClass) {
      if (thisClass.indexOf(theKey) == 0) {
        var tempName = thisClass.substring(theKey.length);
        if (tempName.length > 0) {
          theExtension = tempName;
        }
      }
    }
    forEach(theElement.className.split(' '),findExtension);
  }
	return theExtension;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
  }
  return [curleft,curtop];
}
