// observe the load event
Event.observe(window, 'load', initialize);
Event.observe(window, 'load', loadVideo);


function preloadImage(loc, caption){

	var imgPreloader = new Image();
	var tmp = new Date().getTime();

	loadBigImage(loc, imgPreloader, caption, tmp)
	imgPreloader.src = loc+ "?" + tmp;
}

function loadBigImage(imagePath, imgPreloader, caption, time){
	
	var imageElement = $('bigPictureImg');
	
	imgPreloader.onload=function(){
		
		var leftAmount = (Element.getDimensions('rightColumn').width/2 - imgPreloader.width/2);
		var topAmount = (Element.getDimensions('rightColumn').height/2 - imgPreloader.height/2);
		var minWidth = imgPreloader.width < 300 ? 300 : imgPreloader.width;
		
		Element.setStyle('bigPicture', {left:leftAmount+'px', top:topAmount+'px'});
		Element.setStyle('hide_media', {width:minWidth+'px'});
		Element.setStyle('mediaGuts', {width:minWidth+'px'});
		Element.setStyle('mediaNav', {width:minWidth+'px'});
		
		imageElement.src = imagePath + "?" + time;
		
		Element.show('bigPicture');		
		imgPreloader.onload=function(){}; // clear onLoad, IE behaves irratically with animated gifs otherwise 
	}
	$('bigPictureCaption').update(caption)
}

function showMedia(e){ 
	Element.show('screen');
	
	preloadImage(Element.ancestors(Event.element(e)).first().href, Event.element(e).alt)
	Event.stop(e);
}

function hideMedia(e){
	Element.hide('screen');
	Element.hide('bigPicture');
	Event.stop(e);
}

function currentImageName(){
	var pathInfo = $('bigPictureImg').src.split('?');
	pathInfo.pop();
	var thumbName = pathInfo[0].split('/').pop();
	return(thumbName);
}
function eventImages(){	$('eventImages').getElementsByTagName('a'); }
function prevMedia(e){
	var images = $('eventImages').getElementsByTagName('a');
	var currentImage = currentImageName();
	var nextImg = -1;
	for(var i=0; i<images.length; i++){
		if(currentImage == images[i].href.split('/').pop()){
	 		(i-1 == -1 ) ?	nextImg = images.length-1: nextImg = i-1;
		}
	}
	
	preloadImage(images[nextImg].href, images[nextImg].getElementsByTagName('img')[0].alt)
	Event.stop(e);
}
function nextMedia(e){
	var images = $('eventImages').getElementsByTagName('a');
	var currentImage = currentImageName();
	var nextImg = -1;
	for(var i=0; i<images.length; i++){
		if(currentImage == images[i].href.split('/').pop()){
	 		(i+1 == images.length) ?	nextImg = 0 : nextImg = i+1;
		}
	}
	preloadImage(images[nextImg].href, images[nextImg].getElementsByTagName('img')[0].alt)
	Event.stop(e);
}



function initialize(){
	$('newsletter_form').onsubmit = validateNewsletterSignup;
	$('signup').onclick = clearNewsletterSignup;
	
	if($('secondaryInfo')){
		Event.observe('country', 'change', setDealerInfo)
		//$('country').onchange = setDealerInfo();
	}
	
	
	if($('eventImages')){
		$('screen').setStyle({width: Element.getDimensions('rightColumn').width+'px', height:  Element.getDimensions('rightColumn').height+'px'});
		var images =$('eventImages').getElementsByTagName('a');
		for (var i=0; i<images.length; i++){Event.observe(images[i],'click',showMedia);}

		Event.observe('previous_media','click',prevMedia);
		Event.observe('next_media','click',nextMedia);
		Event.observe('hide_media','click',hideMedia);
	}
	
	if($('flashDiv')){
		var videoLinks = $("moviesContent").getElementsByTagName("a");
		selectedLink = videoLinks[0]; // -this is a global variable used in the playVideo function below
		for (var i=0; i<videoLinks.length; i++){
			videoLinks[i].onclick = function(){
				if(selectedLink != this){ selectedLink.className = "";}
				selectedLink = this;
				clearSelectedVideoLinks();
				this.className = 'activeVideo';
				//thisHref = this.href.substr(this.href.indexOf('#')+1,this.href.length);
				thisHref = this.href.substr(this.href.indexOf('?video=')+7, this.href.length);
				mySWFObj.addVariable('videoPath','video/' + thisHref + '.flv'); 
				mySWFObj.addVariable('autoPlay','true'); 
				mySWFObj.write('flashDiv');
				return false
			}
		}
	}
	
	/* Dynamically calculate the width of the scrolling divs.  hardcoding is for rookies... */
	if($('desktopsDivContent')){
		var thumbs = $("desktopsDivContent").getElementsByTagName("img");
		for (i=0; i<thumbs.length; i++){
			if (thumbs[i].width > 0){
				desktopContainerWidth += thumbs[i].width + 10;
			} else {
				thumbs[i].onload = function(){
					desktopContainerWidth += this.width + 10;
					$('desktopsDivContent').style.width = desktopContainerWidth + "px";
				}
			}
		}
		$('desktopsDivContent').style.width = desktopContainerWidth + "px";
	}
	
	if($('wallpaperDivContent')){
		var thumbs = $("wallpaperDivContent").getElementsByTagName("img");
		for (i=0; i<thumbs.length; i++){
			if (thumbs[i].width > 0){
				wallpaperContainerWidth += thumbs[i].width + 10;
			} else {
				thumbs[i].onload = function(){
					wallpaperContainerWidth += this.width + 10;
					$('wallpaperDivContent').style.width = wallpaperContainerWidth + "px";
				}
			}
		}
		$('wallpaperDivContent').style.width = wallpaperContainerWidth + "px";
	}

	if($('catalogRequestForm')){$('catalogRequestForm').onsubmit = validateCatalogForm;}
	if($('contactForm')){$('contactForm').onsubmit = validateContactForm;}
	if($('locatorForm')){$('locatorForm').onsubmit = validateLocatorForm;}
	if($('searchForm')){$('searchForm').onsubmit = validateSearchForm;}
	if($('searchValue')){$('searchValue').onfocus = function(){if(this.value == 'SEARCH'){this.value = ''};};}
	if($('zipCode')){$('zipCode').onfocus = function(){if(this.value == 'Zip Code'){this.value = ''};};}
	
	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)};
			}
		}
	}
	
	if($('international_dealer_search')){
		$('submitInternationalSearch').hide();
		$('international_dealers').onchange = function(){$('select_international_dealer_form').submit();}
		if($('canadian_provinces')){
			$('submitProvinceSearch').hide();
			$('canadian_provinces').onchange = function(){$('select_canadian_province').submit();}
		}
	}
}

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 clearZipCode() {
  if($('dealerLocatorZip')) {
    $('dealerLocatorZip').onfocus = function() {
      if(this.value == "ZIP code") {
        this.value = "";
      }
    }
  }
}

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, inputObject){
	var inputName = inputObject.name;
	var inputLabel = $(inputName + '_label');
	if(inputLabel){
		inputLabel.className += " validationError";
	}else{
		var parentObject = inputObject.parentNode; 
		var labels = parentObject.getElementsByTagName("label");
		for (var n = 0; n < labels.length; n++ ){
			if(labels[n].htmlFor == inputObject.id){
				labels[n].className += " validationError";
			}
		}
	}	
}

function resetError(inputObject){
	var inputName = inputObject.name;
	var inputLabel = $(inputName + '_label');
	if(inputLabel){
		inputLabel.className = inputLabel.className.replace("validationError", "");
	}else{
		var parentObject = inputObject.parentNode; 
		var labels = parentObject.getElementsByTagName("label");
		for (var n = 0; n < labels.length; n++ ){
			if(labels[n].htmlFor == inputObject.id){
				labels[n].className = labels[n].className.replace("validationError", "");
			}
		}
	}
}

function validateNewsletterSignup(){
	if(!validateEmail('signup','',50)){
		$('newsletter_error').show();
		return false;
	}else{
		$('newsletter_error').hide();
	}
}

function clearNewsletterSignup(){
	if ($F('signup')=='E-Mail'){
		$('signup').value='';
	}
}

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 your first name.";
	if(!validateLength('firstname',message,1,50)){errorMessage += message + "\n";}
	message = "Please enter your last name.";
	if(!validateLength('lastname',message,1,50)){errorMessage += message + "\n";}
	message = "Please enter your address.";
	if(!validateLength('address',message,1,150)){errorMessage += message + "\n";}
	message = "Please enter your city.";
	if(!validateLength('city',message,1,50)){errorMessage += message + "\n";}
	message = "Please select your state.";
	if(!validateLength('state',message,2,2)){errorMessage += message + "\n";}
	message = "Please enter a valid zip code.";
	if(!validateZip('zip',message)){errorMessage += message + "\n";}
	message = "Please enter a valid email address.";
	if(!validateEmail('email',message,50)){errorMessage += message + "\n";}
	//validate that the survey is complete
	errorMessage += (validateSurvey()) ? '' : 'Please complete the survey.';
	
	return (errorMessage.length>0) ? false : true;
}

function validateSurvey(){
	$('surveyError').innerHTML = ''
	var surveyResults = "";
	surveyResults += getCheckedValue(document.catalogRequestForm.qa_1);
	surveyResults += getCheckedValue(document.catalogRequestForm.qa_2);
	surveyResults += getCheckboxValues(document.catalogRequestForm.qa_3);
	surveyResults += getCheckboxValues(document.catalogRequestForm.qa_4);
	surveyResults += getCheckboxValues(document.catalogRequestForm.qa_5);
	surveyResults += getCheckboxValues(document.catalogRequestForm.qa_6);
	if(surveyResults.match('undefined')){
		$('surveyError').innerHTML = 'Please complete the survey.';
		return false;
	}else{
		return true;
	}
}


function validateContactForm(){
	var errorMessage = "";
	var message = "Please enter your name.";
	if(!validateLength('name',message,1,50)){errorMessage += message + "\n";}
	message = "Please enter a valid email address.";
	if(!validateEmail('email',message,50)){errorMessage += message + "\n";}
	message = "Please enter a message.";
	if(!validateLength('message',message,1,500)){errorMessage += message + "\n";}

	return (errorMessage.length > 0) ? false : true;
}

function validateLocatorForm(){
	var errorMessage = "";
	var message = "Please enter a valid zip.";
	if(!validateZip('zipCode',message)){errorMessage += message + "\n";}

	return (errorMessage.length > 0) ? false : true;
}

function validateSearchForm(){
	var errorMessage = "";
	var message = "Please enter your search criteria.";
	if(!validateLength('searchValue',message,1,250)){errorMessage += message + "\n";}
	
	return (errorMessage.length > 0) ? false : true;
}

function getCheckedValue(radioObj){
		for(var i = 0; i < radioObj.length; i++) {
			if(radioObj[i].checked){return radioObj[i].value;}
		}
	}
	
function getCheckboxValues(checkboxGroup){
	var results = 0;
	for(var i=0; i<checkboxGroup.length; i++){
		results += (checkboxGroup[i].checked==false) ? 1 : 0;
	}
	return (results < checkboxGroup.length) ? '' : 'undefined';
}

function getScrollPosition(){
 	//var yScroll = document.getElementById("ridersList").scrollTop;
 	alert('scrolling');
}

	
function setDealerInfo(){
	var selected = $F('country');
	var url = 'inc/secondaryDealerForms.jsp'; 
	new Ajax.Request(url, {parameters: 'country='+selected,onSuccess: function(request){			
			$('secondaryInfo').update(request.responseText);
		}
	});
}

function setVideoClass(vid){
	// Set class 'activeVideo' on initial video
	if($('flashDiv')){
		var videoLinks = $("moviesContent").getElementsByTagName("a");
		for (var i=0; i<videoLinks.length; i++){
			theURL = '?video=' + vid;
			theHREF = videoLinks[i].href.gsub(/(.*)(\?video=.*)/, function(match){return match[2]});
			if(theURL == theHREF){
				videoLinks[i].className = 'activeVideo';
			}
		}
	}
}

function clearSelectedVideoLinks(){
	if($('flashDiv')){
		var videoLinks = $("moviesContent").getElementsByTagName("a");
			for (var i=0; i<videoLinks.length; i++){
				videoLinks[i].className = '';
			}
	}
}

function testVideoPath(vid){
	if($('flashDiv')){
		vidLinks = $("moviesContent").getElementsByTagName("a");
		for (var i=0; i<vidLinks.length; i++){
			path = vidLinks[i].href.gsub(/(.*)(\?video=.*)/, function(match){return match[2]});
			path = path.gsub(/(\?video=)(.*)/, function(match){return match[2]});
			if(vid == path) {
				return true;
			}
		}
	}
}

function getLatestVideo(){
	if($('flashDiv')){
		vidLinks = $("videos").getElementsByTagName("a");
		path = vidLinks[0].href.gsub(/(.*)(\?video=.*)/, function(match){return match[2]});
		path = path.gsub(/(\?video=)(.*)/, function(match){return match[2]});
		return path;
	}
}

function loadVideo() {
	if($('flashDiv')){
		vid = window.location.href.gsub(/(.*)(\?video=.*)/, function(match){return match[2]});
		vid = vid.gsub(/(\?video=)(.*)/, function(match){return match[2]});
		videoPath = testVideoPath(vid);
		clearSelectedVideoLinks();
		if(videoPath !== true) {
			vid = getLatestVideo();
		}
		mySWFObj = new SWFObject("flash/videoPlayer.swf", "index", "350", "235", "7", "#9D9FA2");
		mySWFObj.addVariable("videoPath", "video/" + vid + ".flv");
		//getQueryParamValue("id")
		mySWFObj.addVariable('autoPlay','false'); 
		mySWFObj.write('flashDiv');
		setVideoClass(vid);
	}
}


