/**
 * This is where all the javascript functionality resides for the Slippery site.
 */
 
 function removeBigImg(thisAnchor) {
	$('.bigImage_popup').remove();
	$('.bigImage_shim').remove();
}

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 = '-20px';
	thisImage.style.padding = '10px';
	thisImage.style.position = 'absolute';
	thisImage.style.zIndex = "12001";
	thisImage.style.backgroundColor = "#ffffff"
	thisImage.style.border = '1px solid #cccccc';
	thisImage.style.display = 'none';
	thisImage.onload = function() {
		showBigImg(this);
	};
	thisImage.src=thisAnchor.href;
	document.body.appendChild(thisImage);
}

function showBigImg(thisImage) {
	var pageHeight = $(window).height();
	var pageOffset = $(document).scrollTop();
	var thumbImage = thisImage.thumbNail;
	var thumbOffset = $(thumbImage).offset();
	var thumbTop = thumbOffset.top;
	var pixelsFromLeft = (thumbOffset.left - 40 - thisImage.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";
	thisImage.style.display = '';
}
 

function ImgObj(imgEl, conf){
	//set the object configuration variables
	var that = this;
	this.hasZoom = 1;
	this.hasBack = 1;
	this.hasZoomBack = 1;
	this.isModal = 0;

	if(conf){
		for(var n in conf){
			this[n] = conf[n];
		}
	}
	
	//clone the image and put the copy in a new div that will wrap around the image then remove the original image
	this.imgEl = imgEl.clone();
	this.parentDiv = $('<div></div>')
						.attr('id', imgEl.id + '_parent')
						.addClass('imgParentDiv')
						.width(imgEl.width())
						.height(imgEl.height());
	
	imgEl.before(this.parentDiv);
	this.parentDiv.append(this.imgEl);
	$(imgEl).remove();
	
	//create an absolutely positioned div to hold the back and zoom buttons
	this.imgBtns = $('<div></div>').addClass('_imgBtns');
	this.parentDiv.append(this.imgBtns);
	
	
	var resize = function(){
		that.parentDiv
			.width(that.imgEl.width())
			.height(that.imgEl.height());
	};
	this.imgEl.bind('load',resize);

	if(this.hasBack && this.hasBack != 0){
		var frontBtn = $('<div></div>').addClass('_frontBtn')
			.bind('mouseover',function(){$(this).addClass('mo');})
			.bind('mouseout',function(){$(this).removeClass('mo');})
			.click(function(){
				that.imgEl[0].src = that.imgEl[0].src.replace('rank=2','rank=1').replace('rank=4','rank=3');
			});
		this.imgBtns.append(frontBtn); 
		
		var backBtn = $('<div></div>').addClass('_backBtn')
			.bind('mouseover',function(){$(this).addClass('mo');})
			.bind('mouseout',function(){$(this).removeClass('mo');})
			.click(function(){
				that.imgEl[0].src = that.imgEl[0].src.replace('rank=1','rank=2').replace('rank=3','rank=4');
			});
		this.imgBtns.append(backBtn);
	}

	if(this.isModal){
		var closeBtn = $('<div></div>').addClass('_closeModalBtn')
		.bind('mouseover',function(){$(this).addClass('mo');})
		.bind('mouseout',function(){$(this).removeClass('mo');})
		.click(function(){that.parentDiv.dialog( "close" );});
		this.parentDiv.append(closeBtn);

	}else if(this.hasZoom){
		var zoomBtn = $('<div></div>').addClass('_zoomBtn')
			.bind('mouseover',function(){$(this).addClass('mo');})
			.bind('mouseout',function(){$(this).removeClass('mo');})
			.click(function(){
				var oldPath = that.imgEl[0].src;
				var newPath = oldPath.replace('rank=1','rank=3').replace('rank=2','rank=4');
				if(!that.hasZoomBack || that.hasZoomBack == 0){
					newPath = newPath.replace('rank=4','rank=3');
				}
				var newImgEl = document.createElement('img');
				newImgEl.onload = function(){
					if(this.height > $(window).height()){
						var newHeight = $(window).height();
						var minZoom = that.imgEl.height() * 1.5;
						var scale = newHeight / this.height;
						newHeight = newHeight - 50; //make room for the modal
						if(newHeight < minZoom && minZoom < this.height){
							newHeight = minZoom;
							var scale = newHeight / this.height;
						}
						this.height = newHeight;
						this.width = this.width * scale;
					}
					if(this.width > $(window).width()){
						var scale =  $(window).width() / this.width;
						this.width = $(window).width() - 50;
						this.height = this.height * scale;
					}
					var modalConf = {
							hasBack: that.hasZoomBack,
							isModal: 1
						};
					var Content = new ImgObj($(this), modalConf);
					Content.parentDiv.dialog({
						autoOpen: false,
						height: 'auto',
						width: 'auto',
						modal: false,
						title: ''
					});
					Content.parentDiv.dialog( "open" );
				};
				newImgEl.src = newPath;
				
			});
		this.imgBtns.append(zoomBtn);
		
	}
};


function updateImgSrc(event) {
	var img = $(this).find('img');
	var imgSrc = img.attr('src');
	imgSrc = imgSrc.replace('thumbnail','fullsize');
	$('#bigImage').attr('src',imgSrc);
	$(this).parent().parent().parent().find('.mo').removeClass('mo');
	$(this).parent().addClass('mo');
	$('#thumbDesc').html(img.attr('title'));
	event.stopPropagation();
	return false;
}



// Toggle Side Nav for gear.jsp
function toggleChild(event){
	//this = a tag nested in a li tag
	var myParent = $(this).parent();
	myParent.parent().find('li.selected').removeClass('selected');
	var findChild = myParent.addClass('selected').find('ul');
	//if there is a subcategory or if this is the product page we are on, stop here
	if(findChild.length || myParent.hasClass('selectedProduct')){
		event.stopPropagation();
		return false;
	}else{ //follow href link
		return true;
	}
}

function numbersOnly(e) {
	var key = e.keyCode;
	if (key>=48 && key<=57 || key>=96 && key<=105 || key==null || key==0 || key==8 || key==9 || key==13 || key==27 || key==37 || key==39) {
		return true;
	} else {
		event.stopPropagation();
		return false;
	}
}

function  getEl(id){
	return document. getElementById(id);
}

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 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 false;
		return true;
	}
}



$(document).ready(function(){
	
	// Swap view on dealers page (search by zip vs. view online dealers
	function toggleDealersView(event) {
		$('#dSearch').toggle();
		$('#dOnline').toggle();
		event.stopPropagation();
		return false;
	}
	
	// Dealer Locator Results Images
	var anchors = $('#dealer_results .dealerImages a.dealerImg')
		.bind('mouseover', function(){createBigImg(this);})
		.bind('mouseout', function(){removeBigImg(this);});
	
	//Event handelers for gear
	var gear = $('#gear li a').click(toggleChild);
		
	
	// Numbers Only for ZIP code field
	var zipField = $('#zip_code').bind('keydown', numbersOnly);
	
	
	$('#btns a').click(function(){
		var thisDiv = this.id.split('_')[0];
		thisDiv = $('#'+ thisDiv);
		
		var closeBtn = $('<div></div>').addClass('_closeModalBtn')
			.bind('mouseover',function(){$(this).addClass('mo');})
			.bind('mouseout',function(){$(this).removeClass('mo');})
			.click(function(){thisDiv.dialog( "close" );});
		
		thisDiv
			.append(closeBtn)
			.css('padding', 15)
			.css('padding-top', 25);
		
		thisDiv.dialog({
			autoOpen: true,
			height: 'auto',
			width: 'auto',
			modal: false,
			title: ''
		});
		//$('#'+divId).dialog( "open" );
		//$('#'+divId).toggle();
		return false;
	})
	
	
	// Event handlers for Dealer Search
	var dealerSearch = $('#viewSearchForm').click(toggleDealersView);
	var dealerOnline = $('#viewOnline').click(toggleDealersView);
	
	//event handler for contact form submit
	var contactForm = $('#contactForm').bind('submit', validateContactForm);

	// Event Handlers for Thumbnails
	var thumbs = $('#thumbnails a')
		.bind('mouseover', updateImgSrc)
		.bind('click', updateImgSrc);
	
	var bigImg = $('#bigImage');
	if(bigImg.length && thumbs.length){
		var imgBtns = new ImgObj(bigImg, imgConf);
	}
	
	// NEWSLETTER AJAX REQUEST
	// Fire off an ajax request for a newsletter submission.
	submit_newsletter = function(e) {
		e.preventDefault();
		$.ajax({
			type: 'post',
			url: '/inc/common/submitNewsletter.jsp',
			data: { 'contactEmail': $('input#newsLetterTxt').val() },
			before: function(o){$('#newsLetter_Error').html("<img src='http://assets-static.lemansnet.com/sites/z1rhelmets/assets/img/graphics/icons/loading.gif' />");},
			success: function(o){$('#newsLetter_Error').html(o);},
			error: function(o){$('#newsLetter_Error').html('<span class="error">Communications error. Please refresh this page and try again.</span>');}
		});
	}; 

	$('input#newsLetterTxt').click(function(){this.value = "";});
	$('#newsLetterForm').bind('submit', submit_newsletter);
});
