function linkifyHomepage() {
  // make product images linkable
  if($('products')) {
    if($('products').getElementsByTagName('table')[0]) {
      cells = $('products').getElementsByTagName('table')[0].getElementsByTagName('td');
      for(i=0;i<cells.length;i++) {
        if(cells[i].getElementsByTagName('a')[0]) {
          productLink = cells[i].getElementsByTagName('a')[0];
          parentDiv = productLink.parentNode.parentNode;
          parentDiv.onmouseover = function() {
            this.style.cursor = "pointer";
          }
          parentDiv.onclick = function(productLink) {
            location.href = this.getElementsByTagName('a')[0].href;
          }
        }
      }
    }
  }
  // make feature images linkable
  if($('featuredContent')) {
    if($('featuredContent').getElementsByTagName('li')[0]) {
      featureListItems = $('featuredContent').getElementsByTagName('li');
      for(i=0;i<featureListItems.length;i++) {
        featureListItems[i].onmouseover = function() {
          this.style.cursor = "pointer";
        }
        featureListItems[i].onclick = function() {
          location.href = this.getElementsByTagName('a')[0].href;
        }      
      }
    }
  }
}

function clearZipCode() {
  if($('headerZipCode')) {
    $('headerZipCode').onfocus = function() {
      if(this.value == "zip code") {
        this.value = "";
      }
    }
  }
  if($('zipCode')) {
    $('zipCode').onfocus = function() {
      if(this.value == "zip code") {
        this.value = "";
      }
    }
  }
}

//function $(elementId){
//	if(document.getElementById){
//		return document.getElementById(elementId);
//	}else{
//		return false;
//	}
//}

String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

function findPosition(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function getWindowHeight(){
	var myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
		myHeight = window.innerHeight;
	}else if( document.documentElement && document.documentElement.clientHeight ) {
	//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	}else if( document.body && document.body.clientHeight ) {
	//IE 4 compatible
		myHeight = document.body.clientHeight;
	}
	  
	var scrollOffset = 0;
	if(typeof( window.pageYOffset ) == 'number' ) {
	//Netscape compliant
		scrollOffset = window.pageYOffset;
	}else if( document.body && document.body.scrollTop ) {
	//DOM compliant
		scrollOffset = document.body.scrollTop;
	}else if( document.documentElement && document.documentElement.scrollTop ) {
	//IE6 standards compliant mode
		scrollOffset = document.documentElement.scrollTop;
	}
	return [myHeight + scrollOffset, scrollOffset];
}

function removeBigImg(thisAnchor){
	var thisNode = "";
	for(var n=document.body.childNodes.length - 1;n>=0;n--){
		thisNode = document.body.childNodes[n];
		if(thisNode.className == 'bigImage_popup' || thisNode.className == 'bigImage_shim'){
			document.body.removeChild(thisNode);
		}
	}
}

function createBigImg(thisAnchor){
	var path = thisAnchor.href;
	var thumbImage = thisAnchor.getElementsByTagName("img")[0];
	var thisImage = new Image();
	
	thisAnchor.onclick = function(){return false;}; 
	thisImage.className = "bigImage_popup";
	thisImage.thumbNail = thumbImage;
	thisImage.style.margin = '0px 0px 0px 0px';
	thisImage.style.padding = '0px 0px 0px 0px';
	thisImage.style.position = 'absolute';
	thisImage.style.zIndex = "501";
	thisImage.style.border = '1px solid #000000';
	thisImage.style.display = 'none';
	thisImage.onload = function(){showBigImg(this)};
	thisImage.src=thisAnchor.href;
	document.body.appendChild(thisImage);
}

function showBigImg(thisImage){
	var pageSize = getWindowHeight();
	var pageHeight = pageSize[0];
	var pageOffset = pageSize[1];
	var thumbImage = thisImage.thumbNail;
	var thumbTop = findPosition(thumbImage)[1];
	var pixelsFromLeft = (findPosition(thumbImage)[0] - 20 - thisImage.width);
	//var pixelsFromLeft = findPosition(thumbImage)[0] + 20 + thumbImage.width;
	var pixelsFromtop = thumbTop;
	thisImage.style.left = pixelsFromLeft + "px";

	if((pageHeight - thumbTop) < thisImage.height){
		//theres not enough room under the thumbnail - put it on top
		pixelsFromtop = (thumbTop + thumbImage.height - thisImage.height);
		if((pageOffset + 15) > pixelsFromtop){
			//there is not enough room on top so move it down 15 px from the top
			pixelsFromtop = (pageOffset + 15);
		}
	}
	thisImage.style.top = pixelsFromtop + "px";
	
	//this adds an Iframe shim under the image so it goes over dropdown menus 
	if (document.all){
		var iframeShim = document.createElement("IFRAME");
		thumbImage.parentNode.focus();
		iframeShim.className = "bigImage_shim";
		iframeShim.style.position = 'absolute';
		iframeShim.style.left = pixelsFromLeft + "px";
		iframeShim.style.height = thisImage.height;
		iframeShim.style.width = thisImage.width;
		iframeShim.style.zIndex = "500";
		iframeShim.style.top = pixelsFromtop + "px";
		thisImage.parentNode.appendChild(iframeShim);
	}
	thisImage.style.display = '';
}

function getWindowHeight(){
	var myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
		myHeight = window.innerHeight;
	}else if( document.documentElement && document.documentElement.clientHeight ) {
	//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	}else if( document.body && document.body.clientHeight ) {
	//IE 4 compatible
		myHeight = document.body.clientHeight;
	}
	  
	var scrollOffset = 0;
	if(typeof( window.pageYOffset ) == 'number' ) {
	//Netscape compliant
		scrollOffset = window.pageYOffset;
	}else if( document.body && document.body.scrollTop ) {
	//DOM compliant
		scrollOffset = document.body.scrollTop;
	}else if( document.documentElement && document.documentElement.scrollTop ) {
	//IE6 standards compliant mode
		scrollOffset = document.documentElement.scrollTop;
	}
	return [myHeight + scrollOffset, scrollOffset];
}

function showError(message, errorDiv){
	errorDiv.className += " validationError";
	var siblings = errorDiv.parentNode.childNodes
	for(var n=siblings.length-1; n >= 0; n--){
		if(siblings[n].className == 'error_line'){
			siblings[n].appendChild(document.createTextNode(message));
			siblings[n].style.display = "block";
		}
	}
}

function resetError(errorDiv){
	errorDiv.className = errorDiv.className.replace("validationError", "");
	var siblings = errorDiv.parentNode.childNodes
	for(var n=siblings.length-1; n >= 0; n--){
		if(siblings[n].className == 'error_line'){
			while(siblings[n].hasChildNodes()){
				siblings[n].removeChild(siblings[n].firstChild);
			}
			siblings[n].style.display = "none";
		}
	}
	return true;
}

function numbersOnly(myfield, e, dec){
	var key;
	var keychar;
	if (window.event) {
		key = window.event.keyCode;
	} else if (e) {
		key = e.which;
	} else {
		return true;
	}
	keychar = String.fromCharCode(key);
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) {
		return true;
	} else if ((("0123456789").indexOf(keychar) > -1)) {
		return true;
	} else if (dec && (keychar == ".")) {
		myfield.form.elements[dec].focus();
		return false;
	} else {
		return false;
	}
}

function validateZip(inputId, message){
	var inputDiv = $(inputId);
	var inputValue = inputDiv.value.trim();
	resetError(inputDiv);
	inputDiv.errorMessage = message;
	inputDiv.onchange = function(){validateZip(this.id,this.errorMessage)};
	if(isNaN(inputValue) || inputValue.length != 5){
		showError(message,inputDiv);
		return false;
	}
	return true
}

function validateEmail(inputId, message, max){
	var inputDiv = $(inputId);
	var inputValue = inputDiv.value.trim();
	var re = /[a-z_]*[a-z0-9._%-]?[a-z0-9]+@[a-z0-9][a-z0-9._-]+\.[a-z0-9]+/i;
	resetError(inputDiv);
	inputDiv.errorMessage = message;;
	inputDiv.onchange = function(){validateEmail(this.id,this.errorMessage)};
	if (inputValue.search(re) == -1){
		showError(message,inputDiv);
		return false;
	}
	if(inputValue.length > max){
		showError(message,inputDiv);
		return false;
	}
	return true;
}

function validateLength(inputId, message, min, max){
	var inputDiv = $(inputId);
	var inputValue = inputDiv.value.trim();
	resetError(inputDiv);
	inputDiv.errorMessage = message;
	inputDiv.min = min;
	inputDiv.max = max;
	inputDiv.onchange = function(){validateLength(this.id,this.errorMessage,this.min, this.max)};
	if(inputValue.length < min){
		showError(message,inputDiv);
		return false;
	}
	if(inputValue.length > max){
		showError(message,inputDiv);
		return false;
	}
	return true;
}

function validateCatalogForm(){
	var errorMessage = "";
	var message = "Please enter a valid first name.";
	if(!validateLength('catalogFirstName',message,1,50)){errorMessage += message + "\n";}
	message = "Please enter a valid last name.";
	if(!validateLength('catalogLastName',message,1,50)){errorMessage += message + "\n";}
	message = "Please enter a valid address.";
	if(!validateLength('catalogAddress1',message,1,150)){errorMessage += message + "\n";}
	message = "Please enter a valid city.";
	if(!validateLength('catalogCity',message,1,50)){errorMessage += message + "\n";}
	message = "Please select a valid state.";
	if(!validateLength('catalogState',message,2,2)){errorMessage += message + "\n";}
	message = "Please enter a valid zip.";
	if(!validateZip('catalogZip',message)){errorMessage += message + "\n";}
	message = "Please enter a valid email address.";
	if(!validateEmail('catalogEmail',message,50)){errorMessage += message + "\n";}
	
	if(errorMessage.length > 0){
		alert(errorMessage);
		return false;
	}else{
		return true;
	}
}

function validateContactForm(){
	var errorMessage = "";
	var message = "Please enter valid name.";
	if(!validateLength('mail_name',message,1,50)){errorMessage += message + "\n";}
	message = "Please enter a valid email address.";
	if(!validateEmail('mail_email',message,50)){errorMessage += message + "\n";}
	message = "Please enter a message.";
	if(!validateLength('mail_message',message,1,500)){errorMessage += message + "\n";}

	if(errorMessage.length > 0){
		alert(errorMessage);
		return false;
	}else{
		return true;
	}
}

function validateLocatorForm(){
	var errorMessage = "";
	var message = "Please enter valid zip code.";
	if(!validateZip('zipCode',message)){errorMessage += message + "\n";}

	if(errorMessage.length > 0){
		alert(errorMessage);
		return false;
	}else{
		return true;
	}
}

function validateHeaderLocatorForm(){
	var errorMessage = "";
	var message = "Please enter valid zip code.";
	if(!validateZip('headerZipCode',message)){errorMessage += message + "\n";}

	if(errorMessage.length > 0){
		alert(errorMessage);
		return false;
	}else{
		return true;
	}
}

function closePicture(evt){
	Event.stop(evt);
	Element.hide('bigPicture');
	Element.hide('screen_capture');
	$('bigPictureImg').src = "img/imageLoading.gif";
	//$('bigPicture').setStyle({left:'400px'})
}

function showPicture(evt, loc, name){
	var scrollDist = getWindowHeight()[1];
	if(scrollDist < 300 ){
		scrollDist = 270;
	}else{
		scrollDist += 20;
	}
	
	var imgPreloader = new Image();
	imgEl = $('bigPictureImg');
	var tmp = new Date();
  // once image is preloaded, resize image container
	imgPreloader.onload=function(){
		imgEl.src = loc + "?" + tmp.getTime();
		
		var leftAmount = (760/2 - imgPreloader.width/2);
		
		Element.setStyle('bigPicture', {left:leftAmount+'px', top:scrollDist+'px'});
		logger("left, width = " + leftAmount+', '+ imgPreloader.width);
		logger("style.left = " + $('bigPicture').style.left);
		Element.update('bigPicName', name);
		Element.show('bigPicture');
		imgPreloader.onload=function(){}; // clear onLoad, IE behaves irratically with animated gifs otherwise 
	}
	Element.show('screen_capture');
	imgPreloader.src = loc;
	Event.stop(evt);
}

function logger(message){
	//$("logger").innerHTML = $("logger").innerHTML + "<br />" + message;
}
function initialize(){
	linkifyHomepage();
	clearZipCode();
	if($('bigPicture')){
		$('screen_capture').setStyle({height: Element.getDimensions('products').height+'px'});
		
	}
	if($('contactForm')){
		$('contactForm').onsubmit = validateContactForm;
	}
	
	if($('requestCatalog')){
		$('requestCatalog').onsubmit = validateCatalogForm;
	}
	
	if($('locatorForm')){
		$('locatorForm').onsubmit = validateLocatorForm;
	}
	
	if($('headerLocatorForm')){
		$('headerLocatorForm').onsubmit = validateHeaderLocatorForm;
	}
	
	if($('dealerLocatorResults')){
		var anchors = $('dealerLocatorResults').getElementsByTagName('a');
		for(var i = 0; i<anchors.length; i++ ){
			if(anchors[i].className == 'dealerImg'){
				anchors[i].onmouseover = function(){createBigImg(this)};
				anchors[i].onmouseout = function(){removeBigImg(this)};
			}
		}
	}
}



Event.observe(window, "load", initialize, false);