var isLoadedFlag = false;
var disableLoad = 5;

window.onload = function() { init(); }
window.onresize = function() { resizeWindowToElement(); }

function init() {
	loadHome(); goTo();
	if ( isSaf ) { safariSubmit(); }
	if ( isMacMoz ) { macMozClear(); }
}

function goTo() {  
	
  if (!myGetElementById('codification_text')) return false;
    myGetElementById('codification_text').onfocus = function() {
      if (this.value == "ex: 740-10-25") {
        this.value = "";
		this.style.color = "#000000";
      }
    }
    myGetElementById('codification_text').onblur = function() {
      if (this.value == "") {
	  	this.style.color = "#999999";
        this.value = "ex: 740-10-25";
      }
    }
}


function newHttpRequest() {
	var xmlreq = false;
	if (window.XMLHttpRequest) {
		// Create XMLHttpRequest object in non-Microsoft browsers
		xmlreq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// Create XMLHttpRequest via MS ActiveX
    try {
		// Try to create XMLHttpRequest in later versions
		// of Internet Explorer
		xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e1) {
		// Failed to create required ActiveXObject
			try {
				// Try version supported by older versions
				// of Internet Explorer
				xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				// Unable to create an XMLHttpRequest with ActiveX
			}
		}
	}
	return xmlreq;
}

function getReadyStateHandler(req, divID, responseHandler) {
  // Return an anonymous function that listens to the
  // XMLHttpRequest instance
  return function () {
    // If the request's status is "complete"
    if (req.readyState == 4) {
      // Check that a successful server response was received
      if (req.status == 200) {
	responseHandler(divID, req.responseText);
      } else {
	// An HTTP problem has occurred
      }
    }
  }
}

// OVITAS:  Changed load home function to resize every 2.5 seconds
function loadHome() {
	
	
	if (!isLoadedFlag) {
		//setInterval("loadHome2(false)",2500);
			
	}

	loadHome2(false);

	isLoadedFlag=true;
	
}

function resizeWindowToElement(contentId){
	loadHome2_helper(true, contentId);
}

function loadHome2(reset){
	loadHome2_helper(reset, 'section_wrapper');
}


function loadHome2_helper(reset, contentDivId) {
	if (reset) disableLoad = 5;
	if(disableLoad>0) {
		disableLoad--;	
		resizeLeftPanel(contentDivId);
	}	
}

function resizeLeftPanel(contentDivId){
	//default to section wrapper
	if (!contentDivId)
		contentDivId = 'section_wrapper';
	
	var content = myGetElementById(contentDivId);
	
	var ruler = 0;
	if (myGetElementById('banner'))
		ruler = myGetElementById('banner').clientHeight;
	
	var browseTag = document.getElementById('browse');
	var notBrowseTag = document.getElementById('not_browse');
	var browseMarkTag = document.getElementById('leftnav_mark');
	var notBrowseMarkTag = document.getElementById('content_mark');

	if (isIE) {
		if (notBrowseMarkTag == null){
			return;
		}
		var browse =  myGetElementById('leftnav_mark').offsetTop;
		var notBrowse = myGetElementById('content_mark').offsetTop;
		var notBrowse = myGetElementById('content_mark').offsetTop;
	} else if (isFireFox) {
		if (browseTag == null || notBrowseTag == null){
			return;
		}
		document.getElementById('browse').style.height="auto";
		document.getElementById('not_browse').style.height="auto";
		content.style.height = 'auto';

		var browse = myGetElementById('browse').offsetHeight;
		var notBrowse = myGetElementById('not_browse').offsetHeight;
	} else {
		var browse = myGetElementById('browse').clientHeight;
		var notBrowse = myGetElementById('not_browse').clientHeight;
	}

	if ( browse > notBrowse ) {  // if left nav is longer than content
		if (isFireFox) {
			if ( myGetElementsByClass('tabs',null,'div')[0] ) {
				content.style.height = browse - ( ruler * 1.6 ) + "px";
			} else {
				content.style.height = browse - ( ruler * 0.75 ) + "px";
			}
		} else {
			content.style.height = browse + "px";
		}
	} else {  // if content is longer than left nav
		
		//notBrowse = myGetElementById(contentDivId).offsetHeight;
		//alert('not browse height: ' + notBrowse);
		$('browse').style.height =  (notBrowse) + "px";

	} 
	
}

function safariSubmit() {
		var button = document.getElementById('tableless');
		var corners = button.getElementsByTagName('img');
		for ( var i=0; i<corners.length; i++ ) {
			corners[i].style.display = "none";
			}
		button.style.backgroundColor = "transparent";
}

function macMozClear() {
		var clears = myGetElementsByClass('clear');
		for ( var i=0; i<clears.length; i++ ) {
			clears[i].style.width = "1px";
			clears[i].style.height = "1px";
			clears[i].style.marginBottom = "-1px";
			}
}


/* First principles */

var agt     = navigator.userAgent.toLowerCase();
var isIE    = (document.getElementById && document.all)?true:false;
var isFireFox = (agt.indexOf("firefox")!=-1)?true:false;
var isNS4   = (document.layers)?true:false;
var isNS6   = (document.getElementById && !document.all)?true:false;
var isSaf   = ( (agt.indexOf("mac")!=-1) && (agt.indexOf("safari")!=-1) )?true:false;
var isMacMoz = ( (agt.indexOf("mac")!=-1) && (agt.indexOf('mozilla')!=-1) && (parseInt(navigator.appVersion)<2))?true:false;

function myGetElementsByClass(searchClass,node,tag) {
  var classElements = new Array();
  if (node == null)
    node = document;
  if (tag == null)
    tag = '*';
  var els = node.getElementsByTagName(tag);
  var elsLen = els.length;
  var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
  for (i = 0, j = 0; i < elsLen; i++) {
    if (pattern.test(els[i].className) ) {
      classElements[j] = els[i];
      j++;
    }
  }
  return classElements;
}

function myGetElementById (id)
{

if ( isFireFox ) {
isIE=false;
}
    if ( isIE )
    {
	var str = "document.all('" + id + "')";
	var o = eval(str);
	return o;
    }

    return document.getElementById(id);
}

function searchInput(text,input) {  
	
  if (!document.getElementById(input)) return false;
    document.getElementById(input).onfocus = function() {
      if (this.value == text) {
        this.value = "";
      }
    }
    document.getElementById(input).onblur = function() {
      if (this.value == "") {
        this.value = text;
      }
    }
}


function IE6orLess() {
	var appVer = navigator.appVersion.toLowerCase();
	var iePos = appVer.indexOf('msie');
	if (iePos !=-1) {
		var version = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)))
		return version < 7;
	}
	return false;
}

/** Setter and Getter for session cokies .*/
function getSessionCookie(Name) {
	var search = Name + "="
	var returnvalue = "";
	if (document.cookie.length > 0) {
		offset = document.cookie.indexOf(search)
		// if cookie exists
		if (offset != -1) {
			offset += search.length
			// set index of beginning of value
			end = document.cookie.indexOf(";", offset);
			// set index of end of cookie value
			if (end == -1) end = document.cookie.length;
				returnvalue = unescape(document.cookie.substring(offset, end))
		}
	}
	return returnvalue;
}

function setSessionCookie(name, value){
	document.cookie=name + "=" + value;
}


/** Bottom Navigation Widget */

var toolbarInterval = null;
var motionInterval = 15;
var elWidth = 191;

/** Functions for the floating bottom toolbar. */
function expandToolbar(){
	var collapsedDiv = document.getElementById('collapsedToolbar');
	var expandedDiv = document.getElementById('expandedToolbar');
	collapsedDiv.style.display = 'none';
	expandedDiv.style.display = 'block';
	if (IE6orLess()) {
//		expandedDiv.style.left = '-10px';
	} else {
		expandedDiv.style.left = '-'+elWidth+'px';
		toolbarLeft = -elWidth;
		killMouseEvents();
		toolbarInterval = setInterval('slideRight()', 1);
	}
	setSessionCookie('fixedToolbarState', 'expanded');
	return false;
}

function collapseToolbar(){
	var expandedDiv = document.getElementById('expandedToolbar');
	var collapsedDiv = document.getElementById('collapsedToolbar');
	expandedDiv.style.display = 'block';
	expandedDiv.style.left = '0';
	if (IE6orLess()) {
		expandedDiv.style.display = 'none';
		collapsedDiv.style.display = 'block';
		collapsedDiv.style.position = 'absolute';
		//collapsedDiv.style.bottom = '32px';
//		collapsedDiv.style.left = '-10px';

	} else {
		toolbarLeft = 0;
		killMouseEvents();
		toolbarInterval = setInterval('slideLeft()', 1);
	}
	setSessionCookie('fixedToolbarState', 'collapsed');
	return false;
}

var toolbarLeft;
function slideRight(){
	if (toolbarLeft >= 0){
		document.getElementById('collapsedToolbar').style.display = 'none';
		clearInterval(toolbarInterval);
		resumeMouseEvents();
	} else {
		if (toolbarLeft + motionInterval > 0){
			toolbarLeft = 0;
		} else {
			toolbarLeft += motionInterval;
		}
		var el = document.getElementById('expandedToolbar');
		el.style.left = toolbarLeft + 'px';
	}
}

function slideLeft(){
	var expandedDiv = document.getElementById('expandedToolbar');
	if (toolbarLeft <= -elWidth){
		var el = document.getElementById('collapsedToolbar');
		el.style.display = 'block';
		clearInterval(toolbarInterval);
		resumeMouseEvents();
	} else {
		toolbarLeft -= motionInterval;
		expandedDiv.style.left = toolbarLeft + 'px';
	}
}

var originalEvents = new Array();
/** This will supress click events from inner elements. */
function killMouseEvents(){
	originalEvents = new Array();
	var elementsWithEvents = ['whereamiButton'];
	for (var i=0; i<elementsWithEvents.length; i++){
		var id = elementsWithEvents[i];
		var el = document.getElementById(id);
		var currentEvents = new Object();
		currentEvents['elementID'] = id;
		currentEvents['onmouseover'] = el.onmouseover;
		currentEvents['onmouseout'] = el.onmouseout;
		el.onmouseover = 'return false;';
		el.onmouseout = 'return false;';
		originalEvents.push(currentEvents);
	}
	return;
}

function resumeMouseEvents(){
	for (var i=0; i<originalEvents.length; i++){
		var entry = originalEvents[i];
		var id = entry['elementID'];
		var el = document.getElementById(id);
		el.onmouseover = entry['onmouseover'];
		el.onmouseout = entry['onmouseout'];
	}
	originalEvents = new Array();
}


	/** 
	 * This will make the browser's back button work as expected even with Hashes.
	 * For example, if your url is http://test/page#somehash, normall the back button would take the user to http://test/page.
	 * Instead, this fix will take the user to the previous page.
	 */
/*
	function goBackFromHash(hash){
		if (hash == '')
			history.back();
	}

	var initialHash = document.location.hash;

	function initializeBackButtonFix() {
		window.setInterval(
			function () {
				var currentHash = document.location.hash;
				
				//alert(initialHash +','+currentHash +",   "+window.history.current) ;
				//window.location.replace();
				if (initialHash != currentHash) {
					goBackFromHash(currentHash);
					initialHash = currentHash;
				}
			}, 4000);
	}

	initializeBackButtonFix();
*/
	
var showFunctionsHelp = false;	
function showPageFunctionsHelp(show){
	var inner = document.getElementById('innerPageFunctionHelp');
	if (show){
		showFunctionsHelp = true;
		inner.style.display = 'block';
	} else  {
		showFunctionsHelp = false;
		setTimeout("if (!showFunctionsHelp) {document.getElementById('innerPageFunctionHelp').style.display = 'none';}", 1000);
	}
}	

function range(min, val, max){
	if (min > val) return min;
	if (max < val) return max;
	return val;
}

var scrollToId = null;
function ovitasScrollTo(id, moveBy){
	if (id){
		scrollToId = id;
	}
	if ($(scrollToId)){
		try{
			var offset = Position.cumulativeOffset($(scrollToId))[1];
		} catch (e){
			var offset = $(scrollToId).offsetTop;
		}
		if (offset != null)
			window.scrollTo(0, offset);
	}
}