$(function() {
	var newsHome = $('#newsHome'),
		inputS = $('input[name="myForm[q]"]:not(.searchToolRow > input)'),
		helpLink = $('.newsForm a'),
		pagePrint = $('#pagePrint'),
		gallery = $('#gallery'),
		littleBox = $('.littleBox'),
		searchVille = $('.searchVille'),
		moreDiags = $('#moreDiags'),
		forceDiag = $('.forceDiag'),
		devisForm = $('#devisForm'),
		devisForm2 = $('#devisForm2'),
		navTop = $('.front #navTop');
	
	$('.ajaxPrm').each(function() {
		var me = $(this);
		me.attr('href', me.attr('href')+'?ajax=1');
	});
	if (navTop.length) {
		function preloadImg(image) {
			var img = new Image();
			img.src = image;
		}
		navTop.find('a').each(function() {
			var me = $(this);
			me.data('img', me.find('img'));
			me.data('initSrc', me.data('img').attr('src'));
			me.data('onSrc', me.data('initSrc').substr(0, me.data('initSrc').indexOf('.'))+'_on.png');
			preloadImg(me.data('onSrc'));
		}).hover(function() {
			var me = $(this);
			me.data('img').attr('src', me.data('onSrc'));
		}, function() {
			var me = $(this);
			me.data('img').attr('src', me.data('initSrc'));
		});
	}
	if (devisForm2.length) {
		var prixDiv = devisForm2.find('#devisTarif #estimation'),
			temps = devisForm2.find('#devisTemps strong'),
			devisContact = devisForm2.find('#devisContact'),
			devisPrint = devisForm2.find('#devisPrint'),
			devisEmail = devisForm2.find('#devisEmail');
		devisForm2.find('#devisTitle h3').click(function(e) {
			devisForm2.find('input[name=forceStep1]').click();
		});
		if (devisContact.length) {
			devisContact.click(function(e) {
				e.preventDefault();
				var input = $('<input type="hidden" name="actionDevis" value="contact" />');
				devisForm2
					.append(input)
					.nyroModal()
					.submit()
					.unbind('.nyroModal');
				input.remove();
			});
		}
		if (devisEmail.length) {
			devisEmail.click(function(e) {
				e.preventDefault();
				var input = $('<input type="hidden" name="actionDevis" value="email" />');
				devisForm2
					.append(input)
					.nyroModal()
					.submit()
					.unbind('.nyroModal');
				input.remove();
			});
		}
		if (devisPrint.length) {
			devisPrint.click(function(e) {
				e.preventDefault();
				var input = $('<input type="hidden" name="actionDevis" value="print" />');
				devisForm2
					.attr('target', '_blank')
					.append(input)
					.find('input[type=submit]').attr('name', 'ytfyt').click();
				input.remove();
				devisForm2.removeAttr('target');
			});
		}
		if (prixDiv.length) {
			devisForm2.find('input[type=checkbox]').change(function() {
				$.ajax({
					url: devisForm2.attr('action'),
					type: devisForm2.attr('method'),
					dataType: 'json',
					data: devisForm2.serialize(),
					success: function(data) {
						prixDiv.html(data.prix);
						temps.html(data.temps);
					}
				});
			});
		}
		
	}
	if (devisForm.length) {
		devisForm.find('.help').click(function(e) {
			e.preventDefault();
			$.nmData('<p id="helpModal">'+$(this).attr('title')+'</p>');
		});
		devisForm.find('p:not(:first), .devisSubmitRow').hide();
		devisForm.find('.devisSubmitRow input').click(function(e) {
			var ok = true,
				cur;
			devisFormRow.filter(':visible:not(p, .devisSubmitRow)').each(function() {
				cur = $(this).removeClass('requiredRow').find('input:checked').length == 1;
				if (!cur)
					$(this).addClass('requiredRow');
				ok = ok && cur;
			});
			if (!ok) {
				e.preventDefault();
				alert('Merci de renseigner toutes les informations.');
			}
		});
		var showPieces = false,
			typeBien = null,
			isOuttime = (new Date()).getTime() / 1000 > 1341100800,
			inputs = devisForm.find('input[type=radio]'),
			dates = inputs.filter('input[name=date]'),
			pieces = inputs.filter('input[name=pieces]'),
			showSubmit = function() {
				var ok = true;
				if (dates.filter(':checked').length == 0) {
					devisFormRow.filter('.devisShow'+typeBien+':not(p, .devisSubmitRow)').each(function() {
						ok = ok && $(this).find('input:checked').length == 1;
					});
				}
				if (typeBien && ok)
					$('.devisSubmitRow').slideDown();
				else
					$('.devisSubmitRow').slideUp();
			},
			nb = 0,
			updateDate = function() {
				if (typeBien.indexOf('localcommercial') > -1) {
					if (!devisForm.find('input[name=chauffage]:checked').length)
						devisForm.find('#chauffage-1').attr('checked', 'checked').closest('.devisFormRow');
				} else {
					if (!isOuttime && !devisForm.find('input[name=elec]:checked').length) {
						if (inputs.filter('input[name=date]:checked').val() == 'apres1997') {
							devisForm.find('#elec-2').attr('checked', 'checked').closest('.devisFormRow');
						} else {
							devisForm.find('#elec-1').attr('checked', 'checked').closest('.devisFormRow');
						}
					}
					if (!devisForm.find('input[name=chauffage]:checked').length)
						devisForm.find('#chauffage-1').attr('checked', 'checked').closest('.devisFormRow');
					if (!devisForm.find('input[name=assain]:checked').length && devisForm.find('#type-1').is(':checked'))
						devisForm.find('#assain-1').attr('checked', 'checked').closest('.devisFormRow');
				}
				devisFormRow.filter('.directShowDate').show();
				//devisForm.find('input:checked').closest('.devisFormRow').trigger('devisShow');
			},
			updateEven = function() {
				devisFormRow.filter(':not(p, .devisSubmitRow)')
					.removeClass('devisFormRowEven')
					.filter(':visible:even').addClass('devisFormRowEven');
				showSubmit();
			},
			rows,
			devisFormRow = devisForm.find('.devisFormRow').not(':first').hide().end().bind('devisShow', function() {
				var me = $(this),
					ind = rows.index(me),
					next = rows.eq(ind+1);
					//next = me.next('.devisShow'+typeBien);
				
				if (next.is('.devisSubmitRow')) {
					showSubmit();
					return;
				}
				if (me.is('#devisDate'))
					updateDate();
				if (!next.is(':visible')) {
					next.slideDown(updateEven);
				} else
					updateEven();
				if (next.is('p') || next.find('input:checked').length) {
					//nb--;
					next.trigger('devisShow');
				}
				
				return;
				
				
				if (me.is('#devisType') && typeBien == 'terrainnu') {
					if (devisFormRow.not(':first').filter(':visible').length)
						devisFormRow.not(':first').slideUp(function() {
							updateEven();
							showSubmit();
						});
					else
						showSubmit();
					return;
				}
				nb = 0;
				if (next.is('#devisPieces')) {
					if (!showPieces) {
						nb--;
						next.slideUp(updateEven);
						next = next.next();
					} else {
						if (!dates.filter(':checked').length && !pieces.filter(':checked').length) {
							nb--;
							devisForm.find('#devisDate').slideUp(updateEven);
						}
					}
				}
				if (next.is('#devisAssain') && typeBien.indexOf('localcommercial') > -1) {
					next = next.next();
				}
				if (next.is('.devisSubmitRow')) {
					showSubmit();
				} else {
					if (!next.is(':visible'))
						next.slideDown(updateEven);
					else {
						updateEven();
						showSubmit();
					}
					if (next.is('p') && typeBien.indexOf('localcommercial') == -1) {
						next.next().slideDown(updateEven);
					} else
						updateEven();
				}
			});
		inputs.change(function() {
			var me = $(this);
			if (me.is(':checked')) {
				if (me.is('input[name=type]')) {
					showPieces = me.is('.showPieces');
					if (typeBien != me.val()) {
						var hide = devisFormRow.filter(':not(.devisShow'+me.val()+')');
						if (hide.length) {
							var ln  = hide.length;
							hide
								.find('input:checked').removeAttr('checked').end()
								.slideUp(function() {
									ln--;
									if (ln == 0) {
										//nb = 0;
										updateEven();
									}
								});
						}
					}
					typeBien = me.val();
					rows = devisFormRow.filter('.devisShow'+typeBien);
				}
				if (false && me.is('input[name=date]')) {
					updateDate();
				}
				me.closest('.devisFormRow').trigger('devisShow');
			}
		}).filter(':checked').change();
		updateEven();
	}
	
	if (moreDiags.length) {
		var moreDiagsCont = $('#moreDiagsCont').hide();
		moreDiags.click(function(e) {
			e.preventDefault();
			moreDiagsCont.slideToggle();
		});
	}
	
	if (forceDiag.length) {
		forceDiag.click(function(e) {
			e.preventDefault();
			var devisFormCol = $('#devisFormCol'),
				active = devisFormCol.find('.active');
			devisFormCol
				.append('<input type="hidden" name="diagId" value="'+$(this).attr('rel')+'" />')
				.append('<input type="hidden" name="submit" value="'+active.attr('value')+'" />');
			active.click();
		});
	}

	if (searchVille.length) {
		if (searchVille.is('.autoSubmit'))
			searchVille.find('.searchSubmitRow').hide();
		var cache = {},
			lastXhr,
			url = '/diag/searchVille',
			inputs = searchVille.find('input[type=text]');
		inputs
			.autocomplete({
				minLength: 0,
				source: function(request, response) {
					var term = request.term;
					if (term in cache) {
						response(cache[term]);
						return;
					}

					lastXhr = $.getJSON(url, {
						term: term,
						field: this.element.is('.numCP') ? 'numCP' : 'nomCommune'
					}, function(data, status, xhr) {
						cache[term] = data;
						if (xhr === lastXhr)
							response(data);
					});
				},
				focus: function(event, ui) {
					inputs.filter('.numCP').val(ui.item.numCP);
					inputs.filter('.nomCommune').val(ui.item.nomCommune);
					return false;
				},
				select: function(event, ui) {
					inputs.filter('.numCP').val(ui.item.numCP);
					inputs.filter('.nomCommune').val(ui.item.nomCommune);
					if (searchVille.is('.autoSubmit'))
						searchVille.submit();
					else if (searchVille.is('.autoSubmitActive')) {
						if (searchVille.is('.removeDiagId'))
							searchVille.find('input[name=diagId]').remove();
						searchVille.find('.active').click();
					}
					return false;
				}
			})
			.keypress(function (e) {
				if (e.keyCode == $.ui.keyCode.TAB || e.which == $.ui.keyCode.ENTER) {
					var me = $(this),
						menu = me.data('autocomplete').menu;
					menu.activate($.Event({type: 'mouseenter'}), menu.element.children().first());
					menu.select(e);
				}
			});
		if (searchVille.is('.sumbitOnlyFilled')) {
			searchVille.submit(function(e) {
				var filled = 0;
				inputs.each(function() {
					filled+= $(this).val().length > 0 ? 1 : 0;
				});
				if (filled < inputs.length) {
					e.preventDefault();
					alert('Veuillez d\'abord renseigner le code postal et la ville.');
				}
			});
		}
	}
	if (littleBox.length) {
		littleBox
			.not('.littleBoxOff').addClass('littleBoxOn').end()
			.find('h3, a.showAll').click(function(e) {
				e.preventDefault();
				$(this).closest('.littleBox').toggleClass('littleBoxOn littleBoxOff');
			});
	}
	if (gallery.length) {
		gallery.find('a').nm();
	}
	if (pagePrint.length) {
		pagePrint.click(function(e) {
			e.preventDefault();
			window.print();
		});
	}
	if (helpLink.length) {
		helpLink.click(function(e) {
			$(helpLink.attr('href')).slideToggle();
		});
		$(helpLink.attr('href')).hide();
	}
	if (inputS.length) {
		inputS.focus(function() {
			var me = $(this);
			if (me.val() == me.get(0).defaultValue)
				me.val('');
		}).blur(function() {
			var me = $(this);
			if (me.val().length == 0)
				me.val(me.get(0).defaultValue);
		})
	}
	if (newsHome.length) {
		$.ajax('/diag/newsHome', {
			success: function(data) {
				newsHome.prepend(data);
			}
		})
	}
});
