function loadFlashMap(url) {
	var soDist = new SWFObject(url, "dealers", "400", "400", "8", "");
	soDist.addParam("scale", "noscale");
	soDist.addParam("wmode", "transparent");
	soDist.write("flashDistributori");
}

function dynamicDistributors(provincia, regione, area) {
	var url = '/return/dynamic-distributors?provincia=' + provincia + '&regione=' + regione + '&area=' + area;
	//console.debug(url);
	var html = $.ajax({
		url: url,
		async: false
	}).responseText;
	$('.listDistributori').empty();
	$('.listDistributori').append(html);
}

function motoModelli(marca) {
	var url = '/return/moto-modelli?marca=' + marca;
	var html = $.ajax({
		url: url,
		async: false
	}).responseText;
	$('.modelloSelect .listaModelli').empty();
	$('.modelloSelect .listaModelli').append(html);

	$('.modelloSelectTitle .modello').text(marca);
	var pos = $('.main').offset();
	var top = pos.top - 168;
	$('.modelloSelect').css({'z-index': '9999'
						   , 'top': top
						   , 'left': pos.left
							});
	//$('.modelloSelect').appendTo(".main");
	$('.modelloSelect').show();
	
}

function motoMarche() {
	var url = '/return/moto-marche';
	var html = $.ajax({
		url: url,
		async: false
	}).responseText;
	$('#marcamoto').empty();
	$('#marcamoto').append(html);	
}

function getPageSize() {
	
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) { // all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}


	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}

	var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}

function getPageScroll () {
	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;
	}

	var arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
}

(function($) {

	$.fn.validation = function(lang) {		
	
		var error = 0;
			//console.debug(lang);
		$('.mandatory', this).each(function() {
			var input = $(':input', this).attr("value");
			var check = $(':checkbox:checked', this).length;
			if (input == "" || ($(':checkbox:checked', this).length == 0 && input == "Y")) {
				$('p.errorMessage', this).remove();
				$(this).append('<p class="errorMessage"><span class="error"></span></p>');
				$('span.error', this).html('Please fill in this field.');
				$(':input', this).addClass("errorHighlight");
				error++;
			} else {
				$('p.errorMessage', this).remove();
				$(':input', this).removeClass("errorHighlight");
			}
		});
		
		if (error == 0) {
			return true;
		} else {
			var pos = $('.errorMessage:first').offset();
			var realPos = (pos.top ? pos.top - 40 : 0);
			$('html, body').animate({scrollTop: realPos}, 'slow');
			return false;
		}
	};

})(jQuery);


function overlay(url) {		
	var overlay = $("#overlay");
	var wrap    = $(".wrap");
	var leftPos = ($(document).width() - $(".wrap").width()) / 2;

	overlay.css('height', $(document).height());
	overlay.css('display', 'block');
	wrap.css('display', 'block');
	wrap.css('left', leftPos);
	wrap.load(url);
	overlay.click(function() {
		overlay.css('display', 'none');
		wrap.css('display', 'none');
		wrap.remove();
		overlay.remove();
	});
};


$(document).ready(function(){

	/* apre overlay */
	if ($('#overlay').length > 0) {
		overlay("youtube.html");
	}
	
	// Gestione menu
	$("ul.menuI").superfish();
	$("ul.menuServizio").superfish();

	if ($('#modelloSelect').length > 0) {
		$('#modelloSelect').hide();
	}
	
	if (!$('home') && $('#myLoading').length > 0) {
		$('#myLoading').draggable();
	}
	
	// Mouseover su immagini
	$('.imgBorder').each(function() {
		$(this).mouseover(function() {
			$(this).css('border-color', '#ee1c25');
		}).mouseout(function() {
			$(this).css('border-color', '#dcdbe0');
		});
	});

/*if ($("a[rel]").length > 0) {
	$("a[rel]").overlay();
}*/

	/*
	 * Gestione form community
	 */
	
	function displayFieldset(step1, step2privato, step2rivenditore, step3) {
		if ($('fieldset.step1 input:checked').length > 0) {
			var tipo = $('fieldset.step1 input:checked').attr('value');
			$('#tipoUtente').attr('value', tipo);
		} //else { $('#tipoUtente').attr('value', ''); }
		if (step1 == 'open') {
			$('fieldset.step1').css('display', 'block');
		} else if (step1 == 'erase')  {
			$('fieldset.step1').remove();
		} else  {
			$('fieldset.step1').css('display', 'none');
		}
		
		if (step2privato == 'open') {
			//$('fieldset.step2.privato').css('display', 'block');
			$('fieldset.step2.privato').slideToggle();
		} else if (step2privato == 'erase')  {
			$('fieldset.step2.privato').remove();
		} else  {
			$('fieldset.step2.privato').css('display', 'none');
		}
		
		if (step2rivenditore == 'open') {
			//$('fieldset.step2.rivenditore').css('display', 'block');
			$('fieldset.step2.rivenditore').slideToggle();
			motoMarche();
		} else if (step2rivenditore == 'erase')  {
			$('fieldset.step2.rivenditore').remove();
		} else  {
			$('fieldset.step2.rivenditore').css('display', 'none');
		}
		
		if (step3 == 'open') {
			//$('fieldset.step3').css('display', 'block');
			$('fieldset.step3').fadeIn();
		} else if (step3 == 'erase')  {
			$('fieldset.step3').remove();
		} else  {
			$('fieldset.step3').css('display', 'none');
		}
	}
	
	if ($('#magForm').length > 0) {
		displayFieldset('open', 'close', 'close', 'close');
		
		$('#magForm input:checked').removeAttr('checked');
		
		$('#tipoprivato').click(function() {
			displayFieldset('erase', 'open', 'erase', 'open');
		});
		$('#tiporivenditore').click(function() {
			displayFieldset('erase', 'erase', 'open', 'open');
		});
	}

	// gestione immagine ultime news
	//if ($('.newsLast').length > 0) {
		var firstHref  = $('.newsLast ul li:first a.imgLink').attr("href");
		var firstTitle = $('.newsLast ul li:first a.imgLink').attr("title");
		var firstSrc   = $('.newsLast ul li:first img').attr("src");
		var firstAlt   = $('.newsLast ul li:first img').attr("src");
		var firstCode  = '<a href="' + firstHref + '" title="' + firstTitle + '" class="img">'
					   + '<img src="' + firstSrc + '" width="96" height="66" alt="' + firstAlt + '" />'
					   + '</a>'
						 ;

		$('.imgMain').append(firstCode);	
		$('.newsLast ul li').each(function(){
			$(this).mouseover(function(){
				var newHref = $(this).children(".imgLink").attr("href");
				var newSrc  = $(this).children(".imgLink").children(".img").attr("src");
				$('.imgMain').hide();
				$('.imgMain .img').attr("href",newHref);
				$('.imgMain .img img').attr("src",newSrc);
				$('.imgMain').fadeIn();
			});
		});
	//}
	
	/*if ($('.newsList').length > 0) {
		if ($('.newsList li').length != 0) {
			$('.newsList li').each(function(){
				var img = $(this).children('a').children('.imgNewsList');
				$(this).mouseover(function(){
					img.css('border', '1px solid #666');
				});
				$(this).mouseout(function(){
					img.css('border', '1px solid #fff');
				});
			});
		}
	}*/
	
	// Gestione flash dealers
	//$("#myLoading").hide();
	var arrayPageSize   = getPageSize();
	var arrayPageScroll = getPageScroll();
	var loadingTop      = arrayPageScroll[1] + (arrayPageSize[3] / 10);
	var loadingLeft     = arrayPageScroll[0];
	//$('#myLoading').css({top: loadingTop+'px', left: loadingLeft+'px'});
	//$('#myLoading').css({top: 200+'px', left: 200+'px'});
	$("#myLoading").ajaxStart(function(){
		$("#myLoading p").text('Loading ...');
		$(this).fadeIn();
	});
	$("#myLoading").ajaxComplete(function(){
		$(this).fadeOut();
	});
	$("#myLoading").click(function() {
		$(this).hide();
	});

	if ($('#flashDistributori').length != 0) {
		var defLang = $('#flashDistributori').attr('class');
		if (defLang == 'it') {
			var url = '/skin/website/swf/it.swf';
		} else if (defLang == 'usa') {
			var url = '/skin/website/swf/usa.swf';
		} else if (defLang == 'de'
				|| defLang == 'es'
				|| defLang == 'fr'
				|| defLang == 'pt') {
			var url = '/skin/website/swf/eu.swf';
		} else {
			var url = '/skin/website/swf/world.swf';
		}
		loadFlashMap(url);
		$('.whereSelect').each(function(){
			$(this).click(function(){
				var where    = $(this).attr("title");
				var newFlash = '';
				$('.listDistributori').empty();
				$('#flashDistributori').empty();				
				loadFlashMap('/skin/website/swf/' + where + '.swf');
				return false;
			});
		});
	}
	
	if ($('.motoSelect').length > 0) {
		$('.back2list').hide();
		$('.motoSelect ul li a').each(function() {
			$(this).click(function() {
				var marca = $(this).attr('title');
				motoModelli(marca);
				return false;
			});
		});
		$('.modelloSelectClose').click(function() {
			$('.modelloSelect').hide();
		});
		
		$(".altriModelli").change(function() {
			var selected = $(".altriModelli option:selected");
			var marca = selected.attr('text');
			motoModelli(marca);
		});
	}
	
	if ($('.modelloSelect').length > 0) {
		$('.back2list').hide();
		$('a.cambiaModello').each(function() {
			$(this).click(function() {
				var marca = $(this).attr('title');
				motoModelli(marca);
				return false;
			});
		});
		$('.modelloSelectClose').click(function() {
			$('.modelloSelect').hide();
		});
		
		$(".altriModelli").change(function() {
			var selected = $(".altriModelli option:selected");
			var marca = selected.attr('text');
			motoModelli(marca);
		});
	}
	
	if ($('a.lightbox').length > 0) {
		$('a.lightbox').lightbox();
	}
	
	if ($('a.newWin').length > 0) {
		$('a.newWin').each(function() {
			var url   = '';
			$(this).click(function() {
				url   = $(this).attr('href');
				window.open(url,'Givi', 'width=800,height=600,directories=1,menubar=1,toolbar=1');
				return false;
			});
		});
	}
	
	/*
	if ($('.remDiv').length > 0) {
		$('.openPass').click(function() {
			$('.remDiv').slideToggle();
			$('.iscDiv').slideUp();
			return false;
		});
		$('.openIsc').click(function() {
			$('.remDiv').slideUp();
			$('.iscDiv').slideToggle();
			return false;
		});
	}
	*/
	
	$("#magForm").submit(function () {
		return $(this).validation();
	});
	$("#fPriceQuote").submit(function () {
		return $(this).validation();
	});
	$("#fContattaci").submit(function () {
		return $(this).validation();
	});
	$("#fCurriculum").submit(function () {
		return $(this).validation();
	});
	/*
	$("#remForm").submit(function () {
		return $(this).validation();
	});
	$("#iscForm").submit(function () {
		return $(this).validation();
	});
	*/
	
	if ($(".msgForm").length > 0) {
		$(".msgForm").animate({color: "#ed1b24"}, 1500 )
					 .animate({backgroundColor: "#ffffff"}, 1500 )
					 ;
	}
	
	// Gestione verianti colori per immagine principale prodotto
	if ($('ul.prodColoriList').length > 0) {
		var oldSrc  = $('img.mainImg').attr('src');
		var oldHref = $('a.mainImg').attr('href');
		$('ul.prodColoriList li a').each(function() {
			$(this).click(function() {
				var title = $(this).attr('title');
				if ($('ul.listVars li img[alt=' + title + ']')) {
					var newSrc  = $('ul.listVars li img[alt=' + title + ']').attr('src');
					var newHref = $('ul.listVars li img[alt=' + title + ']').attr('title');
					if (newSrc != undefined) {
						$("#myLoading").stop().hide();
						$('img.mainImg').attr('src', newSrc);
						$('a.mainImg').attr('href', newHref);
					} else {
						$("#myLoading").stop();
						$("#myLoading p").text('Preview not available');
						var css = {
							left: "730px",
							top: "530px"
						};
						$("#myLoading").css(css);
						$("#myLoading").stop()
							.fadeIn()
							.animate({opacity: 1.0}, 1000)
							.fadeOut()
							;
						$('img.mainImg').attr('src', oldSrc);
						$('a.mainImg').attr('href', oldHref);
					}
				}
				return false;
			});
		});
	}
	
	// Gestione lista categorie aggiuntive di prodotti
	if ($('.aggiuntiva1').length > 0 && $('.aggiuntiva2').length > 0) {
		var height1 = $('.aggiuntiva1').height();
		var height2 = $('.aggiuntiva2').height();
		if (height1 > height2) {
			$('.aggiuntiva2').height(height1);
		} else {
			$('.aggiuntiva1').height(height2);
		}
	}
	
	FLIR.init({ path: '/facelift/' });
	$(".flir").each(function() {
		FLIR.replace(this);
	});

});


/*
 * fcheck per sondaggio
 */
function fCheck(field)
{
	processingFieldsetDependency(field.form)
}


function processingFieldsetDependency(formId)
{
	var aFieldsets = formId.getElementsByTagName('fieldset');
    for (i=0; i<aFieldsets.length; i++) {
		var f = aFieldsets[i];
		if (typeof(f.showOnlyIf)=='function') {
			if (typeof(f.memoDisplay) == 'undefined') {
				f.memoDisplay = (typeof(f.style.display)!='undefined' && f.style.display!='none' ? f.style.display : 'block')
			}
			if (f.showOnlyIf()) {
				f.style.display = f.memoDisplay
			} else {
				f.style.display = 'none'
			}
		}
	}
}


/*
 * Price quote
 */

function selectedItem(valore,id){	
		if (valore ==1) {
			$("#color1").load('/fill-coloriaccessori/',{type:'colori',id_content : id});
			$("#divaccessori1").load('/fill-coloriaccessori/',{type:'accessori',id_content : id, numero : 1});
		} else if (valore ==2) {
			$("#color2").load('/fill-coloriaccessori/',{type:'colori',id_content : id});
			$("#divaccessori2").load('/fill-coloriaccessori/',{type:'accessori',id_content : id, numero : 2});
		} else if (valore ==3){
			$("#color3").load('/fill-coloriaccessori/',{type:'colori',id_content : id});
			$("#divaccessori3").load('/fill-coloriaccessori/',{type:'accessori',id_content : id, numero : 3});		
		}
}

function selectedLuggage (selected){
	var stringa = String(selected);
	first = stringa.split(',',1);
	if (first == ''){
		first = stringa.split(',',2);
	}	
	if (first != ''){
		$("#colorSF").load('/fill-coloriaccessori/',{type:'colori',id_content : first});
	}
}

$(document).ready(function() {
	/*if ($('#fPriceQuote .accessori').length > 0) {
		$('#fPriceQuote .accessori').css('display','none');
	}*/

    $('#case1').change(function() { selectedItem(1,$('#case1').val() ); } )
    $('#case2').change(function() { selectedItem(2,$('#case2').val()); } )
    $('#case3').change(function() { selectedItem(3,$('#case3').val()); } )
	$('#softLuggage').change(function() { selectedLuggage($('#softLuggage').val()); } )
	
	//Al primo caricamento
	if ($('#case1 option:selected').val()) {
     	selectedItem(1,$('#case1').val() );
    };
	if ($('#case2 option:selected').val()) {
     	selectedItem(2,$('#case2').val() );
    };
	if ($('#case3 option:selected').val()) {
     	selectedItem(3,$('#case3').val() );
    };
	
});