//const values
var HIDE_CLASS = "hide";
//function obj
var Piaggio = {
	init : function() {
		jQuery(function($) {
			Piaggio.fixStyles();
			Piaggio.slideshow();
			Piaggio.printPage();
			Piaggio.navigator();
			Piaggio.moreDetail();
			Piaggio.configuratore();
			Piaggio.paginator();
			Piaggio.faq();
			Piaggio.formExtended();
			Piaggio.checkEmptyFields();
			Piaggio.overlayManager();
			Piaggio.dropdown();

			var pageId = $("html").attr("data-page");

			switch (pageId) {
			case "page-modello-dettagli" :
			case "page-versione":
				Piaggio.configDropdown();
				break;
			case "page-accessori":
				Piaggio.accessori();
				break;
			case "page-allestimenti":
			    Piaggio.allestimenti();
			break;
			case "page-registrati":
				Piaggio.registrati();
				break;
			case "page-newpassword":
				Piaggio.newPassword();
				break;
			case "page-resetpassword":
				Piaggio.resetPassword();
				break;
			case "page-mypage":
				Piaggio.mypage();
				break;
			case "page-assistenza-centri":
				Piaggio.services();
				break;
			}
		});
	},

	fn : {
		selectFn : function($this) {

			var me = $this, ul = $('<ul />'), li = $('<li />');

			if (me.data('class'))
				ul.addClass(me.data('class'));

			var cl = function(e) {
				e.preventDefault();

				var li = $(this), new_li = li.clone();

				ul.find('li:first').replaceWith(new_li);
				me.val(li.data('value'));
			};

			me.find('option').each(
					function() {
						var opt = $(this);
						ul.append(li.clone().click(cl).text(opt.text()).data(
								'value', opt.val()));
					});

			me.hide().after(ul);
		},
		ajaxRequestFn : function(url, data, successFn, failureFn) {
			$.ajax({
				type : "POST",
				url : url,
				data : data,
				dataType : "text",
				success : function(data) {
					successFn(data);
				},
				failure : function(data) {
					failureFn(data);
				}
			});
		},
		datePicker : function($target) {
			
			$target.datepicker({
				changeMonth : true,
				changeYear : true,
				dateFormat : 'dd/mm/yy',
				yearRange : '1910:2012',
				nextText : '',
				prevText : '',
				firstDay : 1
			});
		},
	    wrapSelect : function () {
		    //select wrapper
		    if (!$.browser.opera) {
		        $('select.no-style').each(function(){
		            var title = $(this).attr('title');
		            
		            if( $('option:selected', this).text() != ''  ) {
		            	title = $('option:selected',this).text();
		            }
		            $(this)
		                .css({'z-index':10,'opacity':0,'-khtml-appearance':'none'})
		                .after('<span class="select-wrap">' + title + '</span>')
		                .change(function(){
		                    val = $('option:selected',this).text();
		                    $(this).next().text(val);
		                    })
		        });
		    };
		}
	},
	makeActive : function(a) {
		var p = a.parent().get(0);
		if (p && p.tagName.toLowerCase() == 'li') {
			a.closest('ul').find('.active').removeClass('active');
			a = a.parent();
		} else
			a.parent().find('.active').removeClass('active');

		a.addClass('active');
	},

	toInt : function(str) {
		var f = parseFloat(str);
		if (isNaN(f))
			return 0;

		return f;
	},

	fullHeight : function(el) {
		var h = Piaggio.toInt(el.css('height'))
				+ Piaggio.toInt(el.css('paddingTop'))
				+ Piaggio.toInt(el.css('paddingBottom'))
				+ Piaggio.toInt(el.css('marginTop'))
				+ Piaggio.toInt(el.css('marginBottom'))
				+ Piaggio.toInt(el.css('borderTopWidth'))
				+ Piaggio.toInt(el.css('borderBottomWidth'));

		return h + 'px';
	},

	fixStyles : function() {

		var IE = $.browser.msie && parseFloat($.browser.version) <= 7;
		
		this.IE = IE;
		
		if ($.browser.msie)
			$('html').addClass('ie-' + parseInt($.browser.version));

		if (!IE){
			// main nav bottom left corner
			$('body > nav ul ul').each(function() {
				$(this).parent().addClass('parent');
			});
		}
		
		// active link in slideshow
		$('.slideshow nav, .navigator nav').each(function() {
			Piaggio.makeActive($(this).find('a[href]:first'));
		});

		// center thumbs in slideshow
		$('.top-navigation-versione .detail nav div').each(
				function() {
					var self = $(this), w = 0;

					self.find('a').each(
							function() {
								var e = $(this);

								w += Piaggio.toInt(e.css('width'))
										+ Piaggio.toInt(e.css('paddingLeft'))
										+ Piaggio.toInt(e.css('paddingRight'))
										+ Piaggio.toInt(e.css('marginLeft'))
										+ Piaggio.toInt(e.css('marginRight'));
							});

					self.css('width', w);
				});

		// navigation ul slidedown
		
		if (IE) {
			// leave menu open
			$('body > nav ul li:not(.open) ul').each(function() {
				var self = $(this);
				
// animation doesn't work properly in IE7
				
//				self.prev('a').hover(function() {
//					self.slideDown('slow');
//				});
//				self.mouseleave(function() {
//					self.slideUp('slow');
//				});
			});
		} else {
			$('body > nav ul li:not(.open) ul').each(function() {
				
				var self = $(this), 
				a = self.prev('a'), 
				isHover = false;

				a.hover(function() {
					
					if (isHover)
						return;
					self.slideDown(500);
				}, function() {
					setTimeout(function() {
						if (isHover)
							return;

						self.slideUp();
						isHover = false;
					}, 500);
				});

				self.hover(function() {
					isHover = true;
				}, function() {
					self.slideUp(function() {
						setTimeout(function() {
							isHover = false;
						}, 300);
					});
				});
			});
		}

		var nav = $('body > nav'), win = $(window), opt = nav.height(), slide = true, fit = function() {
			var h = win.height();
			slide = true;

			if (opt < h)
				return;

			nav.css('position', 'absolute');
			return slide = false;
		};

		// navigation semi fixed
		var originalTop = nav.offset().top; // store original top position

		win.scroll(function(e) {
			if (IE || !slide)
				return;

			if ($(this).scrollTop() > originalTop - 20) {
				nav.css({
					'position' : 'fixed',
					'top' : '20px'
				});
			} else {
				nav.css({
					'position' : 'absolute',
					'top' : originalTop
				});
			}
		});

		win.resize(fit);
		fit();

		//fix drop-down select for magnolia form	
		$(".flotte-contatti-container form").addClass("extended")
		.find("select").attr("data-class","drop-down");
		
		$(".form-wrapper fieldset > div:nth-child(2n+1)").addClass("child-odd");		
		$(".form-wrapper fieldset > div:nth-child(2n)").addClass("child-even").after("<div class='clear-both'/>");

	},
	
	printPage: function(){
	    
	    $(".print-page").click(function(e){
	    	e.preventDefault();
	    	window.print();
	    });
	
	},

	slideshow: function()
	{	    
		var slideTo = function(o)
		{
			return function(el)
			{
				if (o.type == 'horizontal')
				{
					el.nextUntil().add(el).animate({
						'margin-left': '0px'
					});

					el.prevUntil().animate({
						'margin-left': '-' +  o.w + 'px'
					}, { duration: o.duration });
				}


				if (o.type == 'fade')
				{
					if (el.index() == 0)
						el.parent().children().last().fadeOut();

					el.prevAll().fadeOut().end().fadeIn();
				}



				el.parent().find('.current').removeClass('current');
				el.addClass('current');

				Piaggio.makeActive(o.nav.find("a[href = '#" + el.attr('id') + "']"));
			};
		};



		$('.slideshow').each(function(){

			var self = $(this),
				ul   = self.find('>ul'),
				nav  = self.find('>nav'),
				type = self.data('slide-type'),
				duration = parseInt(self.data('duration')) || 1000,
				speed = (parseInt(self.data('speed')) || 4000) + duration,
				shouldSlide = true, paused = false, interval = null;

			if (!ul.length) ul = self.find('>div >ul');
			
			if (type == 'horizontal')
				ul.css('width', '9999px');

			if (type == 'fade')
				ul.find('> li:gt(0)').hide();

			var createInterval = function(){
				if (interval) clearInterval(interval);
				interval = setInterval(doSlideshow, speed);
			};


			ul.hover(
				function(){ shouldSlide = false; clearInterval(interval); },
				function(){ shouldSlide = true;  createInterval(); }
			);

			if (self.data('pauseOnNavHover'))
				nav.hover(
					function(){ shouldSlide = false; clearInterval(interval); },
					function(){ shouldSlide = true;  createInterval(); }
				);

			
			var doSlideshow = function()
			{
				if (!shouldSlide || paused) return;

				var el = ul.find('.current');
				if (!el.length) el = ul.find('li:first');

				var next = el.next();
				if (!next.length) next = ul.find('li:first');

				slide(next);
				//setTimeout(doSlideshow, speed);
			};
			
			createInterval();



			var b = $('body'),
				li = ul.find('li:first').clone().css({ visibility: 'hidden', display: 'block', position: 'absolute' });
				
			b.append(li);


			var w = Piaggio.toInt(li.css('width')) +
					Piaggio.toInt(li.css('marginRight')) +
					Piaggio.toInt(li.css('paddingLeft')) +
					Piaggio.toInt(li.css('paddingRight')),
				slide = slideTo({
					w: w, nav: nav, type: type, duration: duration
				});
				
			li.remove();

			nav.find('a:not(.pause):not([data-value])').click(function(e){
				e.preventDefault();

				var id = $(this).attr('href'),
					el = ul.find('li' + id);

				slide(el);
				pause();
			});

			nav.find("a[data-value]").click(function(e){
				e.preventDefault();

				var v  = $(this).data('value'),
					el = ul.find('.current'),
					next;

				if (v == 'next')
				{
					next = el.next();

					if (!next.length)
						next = ul.find('li:first');
				}

				if (v == 'prev')
				{
					next = el.prev();

					if (!next.length)
						next = ul.find('li:last');
				}

				if (next) slide(next);
			});



			var pause = function(e)
			{
				if (e) {
					e.preventDefault();
				}
				else {
					paused = false;
				}

				paused = !paused;

				if (paused)
					pauseBtn.addClass('play');
				else
					pauseBtn.removeClass('play');
				
				if (paused) return;

				createInterval();
			};

			var pauseBtn = nav.find('a.pause');
			pauseBtn.click(pause);
			
			$(window).blur(function(e){
				if (!pauseBtn.hasClass('play')) {
					pause(e);
				}
			}).focus(function(e){
				if (pauseBtn.hasClass('play')) {
					pause(e);
				}
			});
		});
	},
	navigator : function() {
		$('.navigator').each(
				function() {
					var self = $(this), nav = self.find('>nav');

					if (!nav.length)
						nav = self.find('.navigation');

					var links = nav.find('a:not([data-value])'), 
					    arrows = nav.find('a[data-value]'), 
					    adjust = self.data('adjustHeight'), 
					    slides = self.find('.slides > *');

					if (adjust !== false)
						adjust = true;

					links.click(function(e) {
						e.preventDefault();

						var id = $(this).attr('href'), el = self.find(id);

						if (!slides)
							slides = el.parent().children();

						var target = slides.filter(function() {
							return $(this).is(':visible');
						});

						if (target.attr('id') == el.attr('id'))
							return;

						if (adjust)
							target.parent().animate({
								height : Piaggio.fullHeight(el)
							}, function() {
								target.parent().css('height', 'auto');
							});

						target.fadeOut(function() {
							target.removeClass('current');
							el.addClass('current').fadeIn();
						});

						Piaggio.makeActive($(this));
						arrowStyling(el);
					});

					arrows.click(function(e) {
						e.preventDefault();

						var v = $(this).data('value'), el = self
								.find('.current'), next;

						if (!el.length)
							el = slides.first();

						if (v == 'next') {
							next = el.next();

							if (!next.length)
								return;
						}

						if (v == 'prev') {
							next = el.prev();

							if (!next.length)
								return;
						}

						el.fadeOut(function() {
							el.removeClass('current');
							next.addClass('current').fadeIn();
							arrowStyling(next);
						});

						Piaggio.makeActive(self.find('>nav a[href = "#'
								+ next.attr('id') + '"]'));
					});

					var arrowStyling = function(el) {
						var op = 1;
						var cur = 'auto'

						if (!el || !el.length) {
							el = slides.first();
						}
						
						if (!el.next().length) {
							op = 0.1;
							cur = 'default'
						}
						
						arrows.last().animate({
							'opacity' : op,
							'cursor' : cur
							
						});
						
						op = 1;
						cur = 'auto'

						if (!el.prev().length){
							op = 0.1;
							cur = 'default'
						}

						arrows.first().animate({
							'opacity' : op,
							'cursor' : cur
						});
					};
				});
	},
	moreDetail : function() {
		$('.more-detail')
				.each(
						function() {
							var self = $(this), nav = self.closest('div').find(
									'nav'), info = self.find('.info'), detail = self
									.find('.detail'), close = self.find(
									"a[data-value = 'close']").hide(), detail_button = self
									.find("a[data-value = 'detail']");

							if (!nav.length)
								nav = self.closest('.slideshow').find('nav');
							if (!nav.length)
								nav = self.closest('.navigator').find('nav');

							detail_button.click(function(e) {
								e.preventDefault();
								self.closest('div').animate({
									height : Piaggio.fullHeight(detail)
								});

								nav.fadeOut();
								info.fadeOut(function() {
									detail.fadeIn();
									close.fadeIn();
								});
							});

							close.click(function(e) {
								e.preventDefault();
								var h = info.css('height');
								self.closest('div').animate({
									height : h
								});

								close.fadeOut();
								detail.fadeOut(function() {
									info.fadeIn();
									nav.fadeIn();
								});
							});
						});
	},
	configuratore : function() {

		var me = $('.configuratore'), appCtx = me.eq("0").attr("data-app-ctx"), 
		         price = me.find('#price'), 
		         aside = me.find('aside'),
		         $selectionImage = aside.find("dt[data-bound = 'modello']").next().find("img");

		if (!me.length)
			return;

		aside.find('dt:first, dt:last').addClass('selected');

		var colorFn = function($kids) {
			$kids.each(function() {
				var $this = $(this), $span = $('<span />'), 
				            $inner = $span.clone(), 
				            color = $this.data('hex'), 
				            b = $('<u />'), 
				            t = $this.text();

				$inner.css('background', color);
				$span.append($inner);
				$this.text('').append($span).append(b.text(t));

				$this.click(function() {
					$kids.removeClass('selected');
					$this.addClass('selected');
					var previewUrl = $(this).attr("data-image");
					$(".preview img").removeClass(HIDE_CLASS).attr("src", previewUrl);
					$selectionImage.attr("src", previewUrl);
					selectionFn($(this));
				});
			});
		}

		var selectionFn = function($this) {

			var self = $this, id = self.closest('div[id]').attr('id');

			var actualElement = aside.find("dt[data-bound = '" + id + "']"), nextDd = actualElement
					.nextAll("dd"), nextDt = actualElement.nextAll("dt"), nextElement = nextDd
					.eq(0);

			if (actualElement.not(":visible")) {
				actualElement.fadeIn('slow');
			}
			if (nextElement.not(":visible")) {
				nextElement.fadeIn('slow');
			}

			if (id !== "colore") {
				nextDt.attr("data-value", "");
				nextDd.empty();
			}

			self.closest('ul').find('.selected').removeClass('selected')
			self.addClass('selected');

			var t = self.siblings('b').text() || '';
			if (t)
				t = t.toUpperCase() + '<br />';

			actualElement.addClass('selected').attr(
					"data-value",
					self.parent().attr("data-value") + "|"
							+ self.attr("data-value"));
			nextElement.html(t + self.text());

			if (id === "versione") {
				actualElement.attr("data-version-uuid", self.parent().attr(
						"data-version-uuid"));
				$selectionImage.attr("src",self.siblings("img").attr("src"));
			}

			if (id === "colore") {
				nextElement.data("hex", self.data("hex"));
				colorFn(nextElement);
			}

			if (id === "configurazione") {
				actualElement.hasClass(HIDE_CLASS) ? actualElement
						.removeClass(HIDE_CLASS) : true;
				nextElement.hasClass(HIDE_CLASS) ? nextElement.removeClass(HIDE_CLASS)
						: true;

				// calcolo prezzo
				var modelUuid = "modelUuid="
						+ $("aside dt[data-bound='modello']").attr(
								"data-model-uuid");

				var version = "&version="
						+ $("aside dt[data-bound='versione']").attr(
								"data-value").split('|')[0];

				var set = "&set="
						+ $("aside dt[data-bound='versione']").attr(
								"data-value").split('|')[1];

				var engine = "&engine="
						+ $("aside dt[data-bound='motorizzazione']").attr(
								"data-value").split('|')[0];

				var capacity = "&capacity="
						+ $("aside dt[data-bound='motorizzazione']").attr(
								"data-value").split('|')[1];

				var config = "&config="
						+ $("aside dt[data-bound='configurazione']").attr(
								"data-value").split('|')[1];

				var dataStr = encodeURI(modelUuid + version + set + engine + capacity
						+ config);

				$.ajax({
					type : "GET",
					url : appCtx + "/actions/conf/prices",
					data : dataStr,
					success : function(data) {
						var ivaEscl = $(data).find("IvaEscl").text(), 
						              ivaIncl = $(data).find("IvaIncl").text(),

						$priceBox = $("aside dt[data-bound='prezzo']")
									.attr("data-value", ivaIncl + "|" + ivaEscl)
										.fadeIn();
						$priceBox.next().html(ivaIncl + " " + $priceBox.attr("data-currency")).fadeIn();
					},
					failure : function(data) {
						$("#price").text("errore");
					}
				});
			}

			var data = {};

			me.find('label.selected').each(function() {
				var l = $(this), p = l.closest('div[id]').attr('id');

				data[p] = l.data('value');
			});
		}

		var loginBox = function($target, successFn) {

			var $form = $target.find("form");
			$form.submit(function(e) {
				e.preventDefault();
				$.ajax({
					type : "POST",
					url : $form.attr("action"),
					data : $form.serialize(),
					success : function(data) {
						successFn();
					},
					failure : function(data) {
						alert("error");
					}
					
				});
			});
		}

		// salva
		var salva = function() {
			var self = me.find('#salva'), 
			    save = self.find('a[data-value]'), 
			    old = self.find('.replace'), 
			    clone = old.clone().hide();

			loginBox($("#login-box"), function() {
				save.click();
				$.colorbox.close();
			});
			
			$(document).bind('cbox_closed', function(){
				$('.loading').addClass(HIDE_CLASS);
				$('.replace').removeClass(HIDE_CLASS);
			});

			save.click(function(e) {
				var modello = "model="
								+ $("aside dt[data-bound='modello']").attr(
										"data-value"),
						// allestimento e allestimento
						versione = "&version="
								+ $("aside dt[data-bound='versione']").attr(
										"data-value")
								// motorizzazione e portata
								+ "|"
								+ $("aside dt[data-bound='motorizzazione']")
										.attr("data-value")
								// configurazione
								+ "|"
								+ $("aside dt[data-bound='configurazione']")
										.attr("data-value").split('|')[1], color = "&color="
								+ $("aside dt[data-bound='colore']").attr(
										"data-value"), immagine = "&imagePath="
								+ $("aside dt[data-bound='modello']").attr(
										"data-image"), smil = "&smil= versione-xxx", 
						priceValue = $("aside dt[data-bound='prezzo']").attr(
								"data-value").split('|')[0],
						currency = "&currency="
								+ $("aside dt[data-bound='prezzo']").attr(
										"data-currency");
						
						priceValue = priceValue.replace(".", "");
								
						if (!priceValue) {
							price = "";
						} 
						else 
						{
							price = "&price=" + priceValue;
						}

						var params = modello + versione + smil + color
								+ immagine + price + currency;

						e.preventDefault();

						$('.replace').addClass(HIDE_CLASS);
						$('.loading').removeClass(HIDE_CLASS);

						$.ajax({
									type : "POST",
									url : self.data('callback'),
									data : params,
									dataType : "xml",
									success : function(data) {		
										var result = $(data).find("succesful").text();
										if (result === "true") {
											$('#success').removeClass(HIDE_CLASS);
											$('.loading').addClass(HIDE_CLASS);
											
											setTimeout(function(){												
												$('#success').addClass(HIDE_CLASS);
												$('.replace').removeClass(HIDE_CLASS);
												$(".navigator li a").eq(0).click();
											},3000);
											

										} else {
											$('.replace').removeClass(HIDE_CLASS);
											if ($(data).filter("notlogged")
													.text() === 'true') {
												$.colorbox({
													width : "600px",
													inline : true,
													open : true,
													href : "#login-box"
												});
											} else {
												$('#errors').removeClass(HIDE_CLASS);
											}
											$('.loading').addClass(HIDE_CLASS);
										}

									},
									statusCode : {
										401 : function() {
											$.colorbox({
												width : "600px",
												inline : true,
												open : true,
												href : "#login-box"
											});
										}
									},
									failure : function(data) {
										$('#errors').removeClass(HIDE_CLASS);
										$('.replace').addClass(HIDE_CLASS);
									}
								});
					});
		}

		var customizerPath = me.eq("0").attr("data-customizer-path");

		$("#versione label").click(
				function() {

					selectionFn($(this));

					var versionPath = $(this).parent("li").attr(
							"data-version-path");

					var modelUuid = $("aside dt[data-bound='modello']").attr(
							"data-model-uuid");

					var versionUuid = $("aside dt[data-bound='versione']")
							.attr("data-version-uuid");

					var versionParam = $("aside dt[data-bound='versione']")
							.attr("data-value")
							+ "|"
							+ $("aside dt[data-bound='motorizzazione']").attr(
									"data-value");
					
					// engines options loading
					$.ajax({
						type : "POST",
						url : customizerPath + ".engines",
						data : "modelUuid=" + modelUuid
								+ "&versionUuid=" + versionUuid
								+ "&versionParam=" + versionParam,
						dataType : "text",
						success : function(data) {
							$("#motorizzazione").empty().append(data);
							me.find('#motorizzazione label').click(
							    function() {
							        selectionFn($(this));
								});
							}
						});
				});

		$("#versione label.selected").click();

		$("#motorizzazione label").live(
				"click",
				function() {
					selectionFn($(this));

					var modelUuid = $("aside dt[data-bound='modello']").attr(
							"data-model-uuid");

					var versionUuid = $("aside dt[data-bound='versione']")
							.attr("data-version-uuid");

					var versionParam = $("aside dt[data-bound='versione']")
							.attr("data-value")
							+ "|"
							+ $("aside dt[data-bound='motorizzazione']").attr(
									"data-value");

					var engineUuid = $(this).parent("li").attr(
							"data-engine-uuid");

					// configs options loading
					$.ajax({
						type : "POST",
						url : customizerPath + ".configs",
						data : "modelUuid=" + modelUuid
								+ "&versionUuid=" + versionUuid
								+ "&versionParam=" + versionParam,
						dataType : "text",
						success : function(data) {
							$("#configurazione").empty().append(data);
							me.find('#configurazione label').click(
									function() {
										selectionFn($(this));
									});
						}
					});
					
					// colors options loading
					$.ajax({
						type : "POST",
						url : customizerPath + ".colors",
						data : "engineUuid=" + engineUuid,
						dataType : "text",
						success : function(data) {
							$("#colore").empty().append(data);
							colorFn(me.find('#colore li'));
						}
					});

				});

		salva();
		// end salva

	},
	dropdown : function() {
		
		$(".drop-down").mouseover(function(){$(this).find("li").removeClass(HIDE_CLASS)});
		
		$(".drop-down a").live(
				"click",
				function(e) {
					e.preventDefault();

					var $this = $(this),
					    $dropDown = $this.parents(".drop-down");
					
					$dropDown.find(".front-value").text($this.text());
					$dropDown.find("a").removeClass("selected");
					$this.addClass("selected");
					$dropDown.find("li").not(".front-value").addClass(HIDE_CLASS);
					
				});		
	},
	configDropdown : function() {

		var appCtx = $(".configurazione").attr("data-app-ctx"),
		    $configurazione = $(".configurazione"),
		    $versionsSelect = $("#select-versioni"),
		    $settingsSelect = $("#select-allestimenti");
		    
		if ( $versionsSelect.length) {
			$versionsSelect.find("a").click(function() {
				
				var versionValue = $(this).attr("data-value");
				
				$configurazione.attr("data-version", versionValue);
				
				$.ajax({
			        type : "GET",
					url : appCtx + "/actions/conf/allestimenti",
					data : "modelUuid="
							+ $configurazione.attr("data-model-uuid")
							+ "&version=" + versionValue,
					dataType : "text",
					success : function(data) {
								
						$settingsSelect.find("li:not(.front-value)").remove();
						$settingsSelect.append(data);
						
						var liCount = $(data).filter("li").length,
						    firstLiValue = $(data).find("a").eq(0).attr("data-value");
						    
						if ( liCount === 1 && firstLiValue === "-"){
							$settingsSelect.addClass(HIDE_CLASS);
							$settingsSelect.find("a[data-value='" + firstLiValue + "']").addClass("selected");
						}
						else
						{
							$settingsSelect.removeClass(HIDE_CLASS);
						}
					}
				});
			});
		}
		else
		{
			$.ajax({
			    type : "GET",
				url : appCtx + "/actions/conf/allestimenti",
				data : "modelUuid="
						+ $configurazione.attr("data-model-uuid")
						+ "&version=" + $configurazione.attr("data-version"),
				dataType : "text",
				success : function(data) {
					$settingsSelect.removeClass(HIDE_CLASS);
					$settingsSelect.find("li:not(.front-value)").remove();
					$settingsSelect.append(data);
				}
			});
		}

		$(".configura").click(
			function(e) {
				var $this = $(this);
				    urlModified = $this.attr("href")
					+ "&versione=" + $configurazione.attr("data-version")
					+ "&allestimento=" + $("#select-allestimenti a.selected").attr("data-value");
					$this.attr("href", urlModified);
				});
	},
	accessori : function() {

		var accessoriPath = $(".header-accessori").eq("0").attr(
				"data-accessori-path");
		var culture = $(".header-accessori").eq("0").attr("data-culture");
		var company = $(".header-accessori").eq("0").attr("data-company");

		var failureFn = function() {
			$(".loading").addClass(HIDE_CLASS);
			$("#resultfail").removeClass(HIDE_CLASS);
		}

		$("#model-drop-down a").click(
				function(e) {

					e.preventDefault();

					var containerHeight = $(".navigator").height();
					$(".loading").removeClass(HIDE_CLASS);
					var model = $(this).attr("data-model");

					var typeUrl = accessoriPath + ".types", typeData = "model="
							+ model + "&culture=" + culture + "&company="
							+ company, typeSuccessFn = function(data) {
						$(".navigation").empty().removeClass(HIDE_CLASS).append(
								data);
						$("#resultfail").addClass(HIDE_CLASS);
					};

					// load types
					Piaggio.fn.ajaxRequestFn(typeUrl, typeData, typeSuccessFn,
							failureFn);

					var accUrl = accessoriPath + ".ajax", accData = "model="
							+ model + "&culture=" + culture + "&company="
							+ company, accSuccessFn = function(data) {
						$(".slides").removeClass(HIDE_CLASS).empty().append(data);
						$("#resultfail").addClass(HIDE_CLASS);
						$(".loading").addClass(HIDE_CLASS);
						$(".plus").colorbox({
							inline : true,
							href : $(this).attr("href")
						});
						Piaggio.navigator();
						Piaggio.paginator();
					};

					// load first page
					Piaggio.fn.ajaxRequestFn(accUrl, accData, accSuccessFn,
							failureFn);
				});

		// load accessories page
		$(".page-accessori .paginator a").live(
				"click",
				function(e) {
					e.preventDefault();

					var containerHeight = $(".navigator").height();
					$(".loading").removeClass(HIDE_CLASS).find(".loading-box").css(
							"top", Math.round(containerHeight / 2) - 50);

					var $currentPage = $(".slides li.current");
					var url = $(this).attr("href").replace("?", "");
					var acType = $(".slides li.current").attr("id").replace(
							"cat-", "");

					$.ajax({
						type : "POST",
						url : accessoriPath + ".page",
						data : url + "&type=" + acType,
						dataType : "text",
						success : function(data) {
							$currentPage.replaceWith(data);
							$(".loading").addClass(HIDE_CLASS);
							$("#resultfail").addClass(HIDE_CLASS);
							$(".plus").colorbox({
								inline : true,
								href : $(this).attr("href")
							});
							Piaggio.navigator();
							Piaggio.paginator();
						},
						failure : function(data) {
							failureFn(data);
						}
					});

				});
	},
	allestimenti : function() {
	    $(".plus").colorbox({
			inline : true,
			href : $(this).attr("href")
		});
	},
	paginator : function() {
		
		$('.paginator').each(
			function() {
				
				
				var self = $(this), 
				    target = self.data('target'), 
				    count = self.find('li').length, 
				    first = self.find('li:first'),
				    last = self.find('li:last');

				// center
				var w = 0;
				self.find('li').each(function() {
					w += $(this).width() + 1;
				});
				self.find('ul').css('width', w + 'px');

				self.find('a').click(function(e) {
					
					if($(this).parent().hasClass("page-active-false")){
					e.preventDefault();
					}
					
											});
						});
	},

	faq : function() {
		$('.faq').each(
				function() {
					var me = $(this);
					me.find('li >a').each(function() {
					    var self = $(this);
						self.append($('<span />'));
						self.click(function(e) {
							e.preventDefault();
							self.parent().toggleClass('open').end()
								.next('div').slideToggle();
						});
					});
				});
	},
	formExtended : function() {
		$('form.extended').each(
			function() {
				var form = $(this);
				form.find("input[type = 'radio']").each(function() {
					var me = $(this), 
					    klass = 'check', 
					    checked = form.find('input[name="' + me.attr('name') + '"]:checked');

					if (checked.val() == me.val())
						klass += ' selected';
					me.hide().parent().addClass(klass).click(function(e) {
					    e.preventDefault();
					    form.find("input[name = '" + me.attr('name') + "']")
					    .attr('checked',false).parent().removeClass('selected');
							
					    me.attr('checked',true);
						$(this).addClass('selected');
						});
					});
				
				    Piaggio.fn.wrapSelect();

					form.find('select:not(.no-style)').each(function() {
						
						if (Piaggio.IE)
						    return;

						var me = $(this), 
						         ul = $('<ul />'), 
						         li = $('<li />');

						if (me.data('class'))
							ul.addClass(me.data('class'));

						var cl = function(e) {
							e.preventDefault();
							var li = $(this), 
							    new_li = li.clone().addClass('selected');

								ul.find('li:first').replaceWith(new_li);
								me.val(li.data('value'));
							};

							me.find('option').each(function() {
								var opt = $(this);
								ul.append(li.clone().click(cl).text(opt.text()).data('value',opt.val()));
							});

							me.hide().after(ul);
						});

						form.find("input[type = 'checkbox']").each(function() {
							var me = $(this);
							if (me.is(":checked")){
							    me.parent().addClass("selected")
							}
							me.hide().parent().addClass('tick').click(function(e) {
								e.preventDefault();
								var self = $(this);
								self.toggleClass('selected');
								me.attr('checked',self.hasClass('selected'));
							});
						});
			});
	},
	checkEmptyFields : function() {
		$('form .required').each(
				function() {
					var form = $(this).closest('form'),
					    blurHandler = function($this) {
							var self = $this, 
							    p = self.closest('.required');
							if (self.val()) {
								return p.removeClass('error');
							}
							p.addClass('error');
						}
					
					if (form.data('check-bound'))
						return;

					form.data('check-bound', true);

					form.submit(function(e) {
						
						
						var campi = form.find('.required').removeClass('error')
								.find('input, select, textarea')
								.not('.hasDatepicker')
								.unbind('focus')
								.unbind('blur');

						var empty = campi.filter(function() {
							return !$(this).val();
						});
						
						if (empty.length) {
							e.preventDefault();
						}
						empty.focus(function() {
							$(this).closest('.required').removeClass('error');
						})
						.blur(function() {
							blurHandler($(this));
						}).closest('.required').addClass('error');
					});
				});
	},
	overlayManager : function() {
		var objects = $(".use-overlay a, a[rel = 'iframe']");
		if (objects.length) {
			objects.colorbox({
				iframe : true,
				innerWidth : '800px',
				innerHeight : '400px',
				onComplete : function() {
					return;
					setTimeout(function() {
						var i = $('iframe');
						if (!i.length)
							return; // should not happen

						$.colorbox.resize({
							innerWidth : i.contents().find('body').width(),
							innerHeight : i.contents().find('body').height()
						});
					}, 500);
				}

			});
		}

		objects = $("a[rel = 'slideshow']");
		if (!objects.length)
			return;

		objects.colorbox({
			current : '{current} di {total}'
		});
	},

	newPassword : function() {

		var $form = $("form"), $loading = $("#loading"), $resultfail = $('#resultfail');
		$resultok = $('#resultok'), $regformDiv = $('#regformDiv');

		$loading.ajaxStart(function() {
			$(this).removeClass(HIDE_CLASS);
		}).ajaxStop(function() {
			$(this).addClass(HIDE_CLASS);
		}).ajaxSuccess(function() {
			$(this).addClass(HIDE_CLASS);
		});

		$form.submit(function(e) {

			e.preventDefault();

			$regformDiv.addClass(HIDE_CLASS);
			$resultfail.addClass(HIDE_CLASS);
			$resultok.addClass(HIDE_CLASS);

			$.ajax({
				type : "POST",
				url : $form.attr("action"),
				data : $form.serialize(),
				success : function(data) {
					var result = $(data).find("result").text();
					if (result == 'OK') {
						$resultok.removeClass(HIDE_CLASS);
						$regformDiv.addClass(HIDE_CLASS);
					} else {
						$resultfail.removeClass(HIDE_CLASS);
						$regformDiv.removeClass(HIDE_CLASS);
					}
				},
				failure : function(data) {
					$resultfail.removeClass(HIDE_CLASS);
					$regformDiv.removeClass(HIDE_CLASS);
				}
			});
		});

	},
	resetPassword : function() {

		var $form = $("form"), $loading = $("#loading"), $resultfail = $('#resultfail');
		$resultok = $('#resultok'), $validation = $('#validation');
		$errors = $("#errors");

		$loading.ajaxStart(function() {
			$(this).removeClass(HIDE_CLASS);
		}).ajaxStop(function() {
			$(this).addClass(HIDE_CLASS);
		}).ajaxSuccess(function() {
			$(this).addClass(HIDE_CLASS);
		});

		$form.submit(function(e) {
			e.preventDefault();

			var errors = false;
			if ($form.find('.error').length !== 0) {
				errors = true;
			};

			$errors.addClass(HIDE_CLASS);
			$form.addClass(HIDE_CLASS);
			$resultfail.addClass(HIDE_CLASS);
			$resultok.addClass(HIDE_CLASS);

			if (!errors) {
				$.ajax({
					type : "POST",
					url : $form.attr("action"),
					data : $form.serialize(),
					success : function(data) {
						var result = $(data).find("result").text();
						if (result == 'OK') {
							$resultok.removeClass(HIDE_CLASS);
							$form.addClass(HIDE_CLASS);
						} else {
							$(data).find("error").each(
								function(i) {
									$('#validation p[data-key="'+ $(this).attr('code')+ '"]')
									.removeClass(HIDE_CLASS);
								});
							$validation.removeClass(HIDE_CLASS);
							$resultfail.removeClass(HIDE_CLASS);
							$form.removeClass(HIDE_CLASS);
						}
					},
					failure : function(data) {
						$resultfail.removeClass(HIDE_CLASS);
						$form.removeClass(HIDE_CLASS);
					}
				});
			} else {
				$form.removeClass(HIDE_CLASS);
				$errors.removeClass(HIDE_CLASS);
			}
		});

	},
	registrati : function() {

		var $form = $("form"), 
		    $errors = $('#errors'), 
		    $loading = $("#loading"), 
		    $validation = $('#validation'), 
		    $regform = $('#regform'), 
		    $regformDiv = $('#regformDiv'), 
		    $resultfail = $('#resultfail');
		
		    $resultok = $('#resultok');

		$("#privacy").colorbox({
			width : "600px",
			inline : true,
			href : "#privacyContent"
		});

		Piaggio.fn.datePicker($("#datepicker"));

		$loading.ajaxStart(function() {
			$(this).removeClass(HIDE_CLASS);
		}).ajaxStop(function() {
			$(this).addClass(HIDE_CLASS);
		}).ajaxSuccess(function() {
			$(this).addClass(HIDE_CLASS);
		});
		
		$('#result').hide();

		$form.submit(function(e) {
			
			e.preventDefault();

			setTimeout(function() {
				var errors = false;

				if ($form.find(".error").length !== 0) {
					errors = true;
				}
				;

				$("#privacyOk").parent().removeClass("error");
				if (!$("#privacyOk").is(":checked")) {
					errors = true;
					$("#privacyOk").parent().addClass("error");
				}

				if (!errors) {

					$errors.addClass(HIDE_CLASS);
					$validation.addClass(HIDE_CLASS);
					$regformDiv.addClass(HIDE_CLASS);
					$resultfail.addClass(HIDE_CLASS);
					$resultok.addClass(HIDE_CLASS);
					$("#validation p").addClass(HIDE_CLASS);

					$.ajax({
						type : "POST",
						url : $form.attr("action"),
						data : $('form').serialize(),
						success : function(data) {
							var result = $(data).find("result").text();
							if (result == 'OK') {
								$resultok.removeClass(HIDE_CLASS);
								$regformDiv.addClass(HIDE_CLASS);
							} else {
								$(data).find("error").each(
								    function(i) {
										$('#validation p[data-key="'+ $(this).text() + '"]')
										.removeClass(HIDE_CLASS);
									});
								$validation.removeClass(HIDE_CLASS);
								$regformDiv.removeClass(HIDE_CLASS);
							}
						},
						failure : function(data) {
							$resultfail.removeClass(HIDE_CLASS);
							$errors.removeClass(HIDE_CLASS);
						}
					});
				} else {
					$regformDiv.removeClass(HIDE_CLASS);
					$errors.removeClass(HIDE_CLASS);
				}
			}, 500);
		});

//		$('#country select').change(
//				function() {
//					$loading.addClass(HIDE_CLASS);
//					$('#result').hide();
//
//					$.ajax({
//						type : "POST",
//						url : $("form").attr("data-reg-path") + ".ajax",
//						data : "countryId=" + $('.countryId').val(),
//						success : function(data) {
//						
//							$("#regionsResult").html(data).slideDown("slow")
//									.fadeIn('fast').find('select').each(
//											function() {
//												Piaggio.fn.selectFn($(this))
//											});
//							Piaggio.fn.wrapSelect();
//							
//						}
//					});
//				});
		
		$('#country select').change(
				function() {
					$loading.addClass(HIDE_CLASS);
					$('#result').hide();
					$.ajax({
						type : "POST",
						url : $("form").attr("data-reg-path") + ".ajax",
						data : "countryId=" + $(this).val(),
						success : function(data) {
						   
							$("#referral").remove();
							$("#region").remove();
							$("#country").after(data);
							 Piaggio.fn.wrapSelect();
						}
					});
				});
	},
	mypage : function() {
		$(".mypage .remove").click(function(e) {
			e.preventDefault();
			$(".loading").removeClass(HIDE_CLASS);
			$.ajax({
				type : "GET",
				url : $(this).attr("href"),
				success : function(data) {
					location.reload();
				},
				failure : function(data) {
					$(".loading").addClass(HIDE_CLASS);
					alert("errore durante l'eliminazione");
				}
			});
		});
	},
	services : function() {

		var pagePath = $(".assistenza-clienti").eq("0").attr("data-page-path");
		var failureFn = function() {
			$(".loading").addClass(HIDE_CLASS);
			$("#resultfail").removeClass(HIDE_CLASS);
		}
		
		Piaggio.fn.wrapSelect();

		$("#models-drop-down").change(
				function(e) {
					var url = pagePath + ".provinces", 
					    data = $(this).val(), 
					    successFn = function(data) {
						    $("#provincesList").empty().append(data);
						    $(".container-contatti").empty();
						    $(".loading").addClass(HIDE_CLASS);
						    $("#resultfail").addClass(HIDE_CLASS);
						    Piaggio.fn.wrapSelect();
					    };
					e.preventDefault();
					$(".loading").removeClass(HIDE_CLASS);
					// load list of provinces
					Piaggio.fn.ajaxRequestFn(url, data, successFn, failureFn);
				});

		$("#provinces-drop-down").live(
				"change",
				function(e) {
					var url = pagePath + ".page", 
					    data = $(this).val() + "&page=1", 
						successFn = function(data) {
						$(".container-contatti").empty().append(data);
						$(".loading").addClass(HIDE_CLASS);
						$("#resultfail").addClass(HIDE_CLASS);
					};
					e.preventDefault();
					$(".loading").removeClass(HIDE_CLASS);
					// load list of services
					Piaggio.fn.ajaxRequestFn(url, data, successFn, failureFn);
				});

		$(".page-assistenza-centri .paginator a").live(
				"click",
				function(e) {
					var url = pagePath + ".page", data = $(this).attr("href")
							.replace("?", "")
					successFn = function(data) {
						$(".container-contatti").empty().append(data);
						$(".loading").addClass(HIDE_CLASS);
						$("#resultfail").addClass(HIDE_CLASS);
					};
					e.preventDefault();
					$(".loading").removeClass(HIDE_CLASS);
					// load services page
					Piaggio.fn.ajaxRequestFn(url, data, successFn, failureFn);
				});
	}
};

(function() {

	var path = docRoot + '/js/';

	yepnope([
			{
				load : [
						'http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
						path + 'jquery-ui-1.8.16.custom.min.js',
						path + 'jquery.validMe.js', path + 'colorbox.js',
						path + 'jquery.getUrlParam.js' ],
				complete : function() {
					if (!window.jQuery)
						return yepnope({
							load : path + 'jquery.js',
							complete : Piaggio.init
						});
					Piaggio.init();
				}
			}, {
				load : 'ielt9!' + path + 'selectivizr-min.js'
			} ]);
})();

