function getEl(id){
	return document.getElementById(id);	
}

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';
	document.body.appendChild(thisImage);
	thisImage.onload = function(){showBigImg(this)};
	thisImage.src=thisAnchor.href;
}

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 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 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 validateZip(inputId ,message){
	var inputDiv = getEl('' + inputId);
	//alert(inputId + " = " + $(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 = getEl('' + 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 = getEl('' + 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 enter 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 a valid first name.";
	if(!validateLength('mail_fromname',message,1,50)){errorMessage += message + "\n";}
	message = "Please enter a valid email address.";
	if(!validateEmail('mail_fromemail',message,50)){errorMessage += message + "\n";}
	message = "Please write a message of no more than 500 characters.";
	if(!validateLength('mail_message',message,1,500)){errorMessage += message + "\n";}
	message = "Please enter the Captcha phrase displayed in the red box below.";
	if(!validateLength('recaptcha_response_field',message,1,150)){errorMessage += message + "\n";}
	
	if(errorMessage.length > 0){
		alert(errorMessage);
		return false;
	}else{
		return true;
	}
}

function validateContestForm(){
	var errorMessage = "";
	var message = "Please enter a valid first name.";
	if(!validateLength('contest_fromname',message,1,50)){errorMessage += message + "\n";}
	message = "Please enter a valid email address.";
	if(!validateEmail('contest_fromemail',message,50)){errorMessage += message + "\n";}
	
	if(errorMessage.length > 0){
		alert(errorMessage);
		return false;
	}else{
		return true;
	}
}

function validateNewsletterForm(e){
	var errorMessage = "";
	var message = "Please enter a valid email address.";
	if(!validateEmail('contactEmail',message,50)){errorMessage += message + "\n";}
	
	if(errorMessage.length > 0){
		alert(errorMessage);
		return false;
	}else{
				
		var inputs = $('#newsletterForm input.newsletter_type');
		
		var errMsg = getEl('err_message');
		errMsg.style.display = 'none';
		
		if(inputs.length > 0){
			var updateMsg = getEl('newsletter_message');
			var contactTextField = getEl('contactEmail').value;
			var spinner = getEl('newsletter_loading');
			var myForm = getEl('newsletterForm');
			
			spinner.style.visibility = 'visible';
				
			var brandSiteIds = ""; 
			inputs.each(function(){if(this.checked){brandSiteIds += this.value + ',';}});		

			jQuery.ajax({
				url:'newsletter_response.jsp',
				type:'post',
				//parameter 'email' sends value of 'contactTextField' as ajax request to newsletter_respose.jsp
				data: {
					bsId: brandSiteIds,
					email: contactTextField
					//fromName: from,
					//sub: subject
				},
				success:function(){
					myForm.style.display = 'none';
					updateMsg.innerHTML = 'Thanks again for joining and welcome!';
					updateMsg.style.display = 'block';
					spinner.style.visibility = 'hidden';
					getEl('contactEmail').value = '';
					getEl('moose').checked = false;
					getEl('mudnra').checked = false;
;
				},
				error:function(){
					errorMsg.innerHTML = 'Error, please try again.';
					errorMsg.style.display = 'block';
					spinner.style.visibility = 'hidden';
				}
			});
		
		
		}
		
		return false;
	}
}

function validateLocatorForm(){
	var errorMessage = "";
	var message = "Please enter a valid zip code.";
	var headSuffix = '';
	if(this.id == 'dealerSearchHeader'){
		headSuffix = 'Header';
	}
	if(!validateZip('dealerSearchZipCode' + headSuffix,message)){
		errorMessage += message + "\n";
	}
	
	if(errorMessage.length > 0){
		alert(errorMessage);
		return false;
	}else{
		return true;
	}
}


//menu object added events to hide and show the dropdown menus for the navigation
Menu = {
	init: function(){
		var links = $('#topNav .navLabel');
		links.bind('mouseover',this.show).bind('click',this.click);
		links.find('.topNavMenu').bind('mouseout',Menu.out).bind('mouseover',Menu.over);
		this.timeOut = '';
		this.currentEl = '';
	},
	click:function(){
		var aTag = $(this).children('.navLink');
		if(aTag.length > 0){
			if(aTag.attr('target')){
				window.open(aTag.attr('href'));				
			}else{
				window.location.href = aTag.attr('href');
			}
		}
	},
	show:function(){
		var thisEl = $(this).find('.topNavMenu');
		if(Menu.currentEl != thisEl){
  			window.clearTimeout(Menu.timeOut);
			if(Menu.currentEl)Menu.hide();
			Menu.currentEl = thisEl;
			thisEl.show();
		}
	},
	over:function(){
		window.clearTimeout(Menu.timeOut);
		$(document).unbind('click',Menu.hide);
	},
	out:function(){
		Menu.timeOut = window.setTimeout("Menu.hide()",500);
		$(document).bind('click',Menu.hide);
	},
	hide:function(){
		Menu.currentEl.hide();
	}
};


//twitter object to get and read the twitter json data
Twitter = {
	init: function(){
		this.news = $('#news');
		this.contentDiv = $('#twitterFeed');
		this.getFeed();
	},
		
	getFeed: function(){
		//http://dev.twitter.com/doc/get/statuses/home_timeline.json?count=10
		//$.getJSON("/static/data/twitter.json", function(data){
		var _twitter = this;
		//$.getJSON("http://api.twitter.com/1/statuses/user_timeline/mudTest.json?count=10&callback=?", function(data){
		$.getJSON("twitter.jsp", function(data){
			$.each(data, function(arrIndex){
				var thisText = this.text;
				var thisDt = this.created_at.replace('+0000','');
				thisDT = new Date(thisDt);
				thisDT = thisDT.toLocaleDateString();
				
				//hyperlink urls
				thisText = thisText.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url){
						return '<a href="' + url +'" target="blank">' + url + '</a>';
					});
				
				//hyperlink usernames
				thisText = thisText.replace(/[@]+[A-Za-z0-9-_]+/, function(u){
						var username = u.replace("@","");
						return '<a href="http://twitter.com/' + username +'" target="blank">' + u + '</a>';
					});
				
				//hyperlink hashtags
				thisText = thisText.replace(/[#]+[A-Za-z0-9-_]+/, function(t) {
						var tag = t.replace("#","%23")
						return '<a href="http://search.twitter.com/search?q=' + tag +'" target="blank">' + t + '</a>';
					});
				var newDiv = '<div class="pt10"></div>';
				if(arrIndex == 0){newDiv='<div></div>';}  
				$(newDiv)
					.append('<span>' + thisText + '</span>')
					.append('<div class="dt">' + thisDT + '</div>')
					.appendTo(_twitter.contentDiv);
	            //_twitter.news.scrollTop(_twitter.news.height());
	        });
	    });	
	}		
};


/*slideshow object will read an array of images and rotate through them - fading from one to another
* the init method should be called after the element is created with the following 3 params
* param1 slideShowEl - DOM element(block) required = the div where the slideshow will be displayed 
* param2 imagePaths - array required = array of file names
* param3 basePath - String optional = can be blank, relative, or absolute
*
*other values that can be changed:
* selectedImg - int = the first image to display;
* timeOutValue - int = the time before the next image starts to load
* fadeInTime - int = the time to fade from one img to the other after a normal timout 
* fadeInTimebyNumber - it = the time to fade when a specific img number is passed 
*/
var SlideShow = {
	slideShowEl: '',
	imagePaths:[],
	basePath: '',
	selectedImg:0,
	timeOutValue:5000,
	fadeInTime: 500,
	fadeInTimeByNumber: 200,
	preLoadImg: document.createElement('img'),
	
	init: function(ssElement, ssImages, ssBasePath){	
		var slideShowObj = this;
		this.slideShowEl = ssElement;
		this.imagePaths = ssImages;
		this.basePath = ssBasePath;
		if(!this.imagePaths){
			alert('imagePaths not defined!');
			return;
		}
		//create a new div to fade from -each time we switch imags this div is shown in front and the new image fades in
		//after the image is 100% opac the src for ssElement background is changed and this div is hidden. 
		this.slideShowBg = ssElement;
		this.slideShowEl = $('<div></div>').attr('id', 'slideShowTmpDiv');
		this.slideShowEl.css('height',this.slideShowBg.height());
		this.slideShowEl.css('width',this.slideShowBg.width());
		this.slideShowEl.css('position','absolute');
		this.slideShowEl.height(this.slideShowEl.parent().height());
		this.slideShowEl.width(this.slideShowEl.parent().width());
		this.slideShowEl.click(function(){
						var selImg = slideShowObj.imagePaths[slideShowObj.selectedImg];
						if(selImg.href){
							if(selImg.newWin){
								window.open(selImg.href);
							}else{
								window.location.href=selImg.href;
							}
						}
					});
		this.slideShowBg.prepend(this.slideShowEl);
		
		$(this.preLoadImg).bind('load',
				function() {
					var ssCursor = "default";
					if(slideShowObj.imagePaths[slideShowObj.selectedImg].href){
						ssCursor = "pointer";
					}
					slideShowObj.slideShowEl.hide()
						.css('background-image','url(' + this.src + ')')
						.css('cursor',ssCursor)
						.fadeIn(this.timeToFadeIn);

					slideShowObj.onChange();
				});
		
		this.show(this.selectedImg);
	},
	play:function(toggleValue){
		if(toggleValue){
			if(!this.slideShowIsStopped){
				this.stop();
				this.slideShowEl.show(this.selectedImg);
			}else{
				this.slideShowIsStopped = false;
				this.show();
			}
		}else{
			this.show();
		}
	},
	next:function(){
		this.show();
	},
	prev:function(){
		this.selectedImg--;
		if (this.selectedImg  < 0) {
			this.selectedImg  = this.imagePaths.length - 1;
		}
		this.show(this.selectedImg);
	},
	stop:function(){
		window.clearTimeout(this.slideShowTimer);
		this.slideShowIsStopped = true;
	},
	show: function(slideNum) {
		var slideShowObj = this;
		window.clearTimeout(this.slideShowTimer);
		this.preLoadImg.timeToFadeIn = this.fadeInTime;

		if(slideNum != undefined && !isNaN(slideNum)){
			if(slideNum>=0 && slideNum<this.imagePaths.length){
				this.selectedImg = slideNum;
				this.preLoadImg.timeToFadeIn = this.fadeInTimeByNumber;
			}else{
				alert('The requested image number for the slideshow is out of range.');
			}
		}else{
			this.selectedImg++;
			if (this.selectedImg >= this.imagePaths.length) {
				this.selectedImg  = 0;
			}
		}

		this.slideShowEl.parent().css('background-image', this.slideShowEl.css('background-image'));
		var path = this.basePath + this.imagePaths[this.selectedImg].img;
		this.preLoadImg.src = path;

		if (!this.slideShowIsStopped) {
			this.slideShowTimer = window.setTimeout(function(){slideShowObj.show();}, slideShowObj.timeOutValue);
		}
	},
	onChange: function(){}
};


//events / functions called on page load
function pageInitialize(){
	Menu.init();
	
	if(getEl('contactForm')){
		getEl('contactForm').onsubmit = validateContactForm;
	}

	if(getEl('CatalogRequestForm')){
		 getEl('CatalogRequestForm').onsubmit = validateCatalogForm;
	}
	
	if(getEl('dealerSearch')){
		getEl('dealerSearch').onsubmit = validateLocatorForm;
	}

	if(getEl('dealerSearchHeader')){
		getEl('dealerSearchHeader').onsubmit = validateLocatorForm;
	}
	
	if(getEl('newsletterForm')){
		//Event.observe('newsletterForm','submit', validateNewsletterForm);
		$('#newsletterForm').bind('submit', validateNewsletterForm)
	}
	
	if(getEl('newsSignup')) {
		getEl('contactEmail').onfocus = function() {
			getEl('contactEmail').value = '';
		}
	}

	if(getEl('contestForm')) {
		getEl('contest_message').onkeyup = function() {
			if (getEl('contest_message').value.length >= 3000) {
				getEl('contest_message').value = getEl('contest_message').value.substring(0,3000);
			}
			getEl('charCount').innerHTML = 3000 - parseInt(getEl('contest_message').value.length); 

		};
		getEl('contestForm').onsubmit = validateContestForm;
	}
	
	// enable the thumbnail links (if js is enabled, simply swap out the images as opposed to refreshing the entire page
	//this is used on the product page
	if (getEl("thumbnails") && getEl("bigImage")){
		var bigImage = getEl("bigImage").getElementsByTagName("img")[0];
		var bigImageSrc = bigImage.src.substr(0,bigImage.src.indexOf('&rank='))
		if(bigImage.src.indexOf('&',bigImageSrc.length+1) > 0){
			bigImageSrc = bigImage.src.substr(bigImage.src.indexOf('&',bigImageSrc.length+1),bigImage.src.length);
		}
	
		var thumbnails = getEl("thumbnails").getElementsByTagName("li");
		for (var i=0; i<thumbnails.length; i++){
			thisLink = thumbnails[i].getElementsByTagName("a")[0];
			thisImage = thumbnails[i].getElementsByTagName("img")[0];
			thisLink.onclick = function(){
				bigImage.src = bigImageSrc + '&rank='+ this.id;
				return false;
			}
		}
	}
	
	if(getEl('dealerSearchZipCodeHeader')){
		getEl('dealerSearchZipCodeHeader').onclick = function(){ if(this.value=='Zip Code') this.value = ''};
	}
	
	if(getEl('dealerSearchZipCode')){
		getEl('dealerSearchZipCode').onclick = function(){ if(this.value=='Zip Code') this.value = ''};
	}
	
	if(getEl('dealerList')){
		var anchors = getEl('dealerList').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)};
			}
		}
	}
	
	//initialize the slideshow and set-up the navigation of the slideshow
	var ssElem = $('#slideShow');
	var ssImgs = [
			{img:'footer_feature_nra.jpg',href:'/products.jsp?level1=3657&category_id=3657', newWin:false},
			{img:'features_3700_winch.jpg',href:'/products.jsp?level1=3526&product_group_id=11402', newWin:false},
			{img:'features_beacon_light.jpg',href:'/products.jsp?level1=3533&product_group_id=13503', newWin:false},	
			{img:'mud_tube.jpg',href:'http://www.youtube.com/mooseutilities', newWin:true}	
			];
		/*{img:'slideShow2.jpg'},{img:'slideShow3.jpg'},{img:'slideShow4.jpg'}*/
	var ssBasePath = 'http://assets-static.lemansnet.com/sites/mooseutilities/images/slideShow/';
	SlideShow.init(ssElem, ssImgs, ssBasePath);
	var mediaControl = $('#mediaControl');
	var mediaBox = [];
	for(var b=0;b<ssImgs.length;b++){
		mediaBox[b] = $('<div></div>').attr('ssNum', b); //.addClass('ssBox')
		if(b==0){mediaBox[b].addClass('selectedImg');}
		mediaBox[b].click(function(){SlideShow.show($(this).attr('ssNum'));});
		mediaControl.append(mediaBox[b]);
	}
	SlideShow.onChange = function(){
		for(var e in mediaBox){
			if(this.selectedImg == mediaBox[e].attr('ssNum')){
				mediaBox[e].addClass('selectedImg');		
			}else if(mediaBox[e].className != ''){
				mediaBox[e].removeClass('selectedImg');
			}
		}
	};
	
	Twitter.init();
}

$(document).ready(pageInitialize);
