
//PTZ
$(function() {
	
	$("a.fancyBox").fancybox({ 
		'zoomOpacity': true,
		'zoomSpeedIn': 500,
		'frameHeight':600,
		'frameWidth':600,
		'zoomSpeedOut': 300, 
		'overlayShow': true,
		'overlayOpacity' : 0.5,
		type : 'iframe'
		});
	
	inputAssist('#NW_mail1','Indiquez votre mail');
	
	//Button hovers 
	$('img.hover, input.hover').each(function(i) {
		$(this).mouseover(function() {
			src = $(this).attr('src');
			ext = src.substring(src.lastIndexOf('.',src.length),src.length);
			$(this).attr('src',src.replace(ext,'_on'+ext));
		});
		$(this).mouseout(function() {
			$(this).attr('src',$(this).attr('src').replace('_on',''));
		});
	});
	
	//Tooltip ++
	/*
	$("#bas_accueil [title]").mbTooltip({ // also $([domElement]).mbTooltip  >>  in this case only children element are involved
	      opacity : .97,       //opacity
	      wait:50,           //before show
	      cssClass:"default",  // default = default
	      timePerWord:70,      //time to show in milliseconds per word
	      hasArrow:false,			// if you whant a little arrow on the corner
	      hasShadow:false,
	      imgPath:"images/",
	      ancor:"mouse", //"parent"  you can ancor the tooltip to the mouse position or at the bottom of the element
	      shadowColor:"black", //the color of the shadow
	      mb_fade:200 //the time to fade-in
	    });*/
});


function getVilleByCP() {
	
	var cp = $('#cp').val();
	
	$('#ville option').remove();
	if(cp != '') {
		$.get('index.php?ajax=getVilleByCP&cp='+cp, function(data) {
			$('#ville').attr('disabled',false);
			$('#ville').append(data);
		}); 
	} else {
		$('#ville').attr('disabled',true);
	}
}

function displayResult(expr, title, width) {
	if($('#dialogPTZ').size() == 0 || $('#dialogPTZ #montant').html() == '') {
		if(width == 0) width = $(expr).width();
		//if(width == 0) width = '500px';
		$(expr).dialog({
			draggable: false,
			resizable: false,
			title: title,
			modal: true,
			width:500,
			close : function(){$(expr).dialog('destroy');}
		});
	} else {
		var montant = new String($('#dialogPTZ #montant').html());
		var reg =new RegExp("[^0-9]", "g");
		montant = montant.replace(reg, "");
		$('#inputPTZ').val(montant);
		tosp('#inputPTZ');
		$('#dialogPTZ').dialog('close');
		tosp('#dialogPTZ');
		
		$('#codePostal').val($('#cp').val());
		$('#commune').val(
			$('#ville > option:selected').html().substr(0,$('#ville > option:selected').html().indexOf('-')-1)
			);
		$('#revenu_fiscal').val($('#revenuFiscalPTZ').val());
		tosp('#revenu_fiscal');
		$('#nb_pers_foyer_fiscal').val($('#nbPersonnePTZ').val());
		
		calcMontantPret();
	}
}

function displayPTZ() {
	
	var expr = '#dialogPTZ';
	
	$('body').append('<div id="dialogPTZ"></div>');
	
	$(expr).load('index.php?ajax=getPTZFormAjax');
	
	width = 500;
	title = 'Calculez votre prêt à taux zero';
	$(expr).dialog({
		draggable: false,
		resizable: false,
		title: title,
		modal: true,
		width:width,
		close : function(){
			$(expr).dialog('destroy');
		}
	});
}

//Newsletter

function inscriptionNewsletter() {
	if(isValid("#formNewsLetter input[name='mail_receiver']", validMail, '')) {
		$.post('index.php?ajax=inscriptionNewsletterAjax',$('#formNewsLetter').serialize(), function(data) {
			dialogBox(data);
		});
	} else {
		dialogBox('Le mail indiqué est invalide');
	}
}

function desinscriptionNewsletter() {
	if(isValid("#formNewsLetter input[name='mail_receiver']", validMail, '')) {
		$.post('index.php?ajax=desinscriptionNewsletterAjax',$('#formNewsLetter').serialize(), function(data) {
			dialogBox(data,5000);
		});
	} else {
		dialogBox('Le mail indiqué est invalide');
	}
}


function desinscriptionNewsletter2() {
	
	if(isValid("#formNewsLetter2 input[name='mail_receiver']", validMail, '')) {
		$.post('index.php?ajax=desinscriptionNewsletterAjax',$('#formNewsLetter2').serialize(), function(data) {
			dialogBox(data,5000);
		});
	} else {
		dialogBox('Le mail indiqué est invalide');
}
}

function boutonHover(expr, image) {
	var image2 = $(expr).attr('src');
	$(expr).mouseover(function() {$(expr).attr('src',image)});
	$(expr).mouseout(function() {$(expr).attr('src',image2)});
}



//Contact


function showToolTipUpToElement(expr, message) {
	exprErr = '#tooltip';
	if(message != "") {
		if($(exprErr).size() > 0) {
			$(exprErr).remove();
		}
		var toolTip = '<div id="tooltip" class="toolTip" '+ 
						'onClick="$(this).remove();">'+message+'</div>';
		$(expr).before(toolTip);
		var errOffsetTop = $(expr).offset().top - (-20);
		var errOffsetLeft = $(expr).offset().left - 50;
		
		$(exprErr).css('top',errOffsetTop);
		$(exprErr).css('left',errOffsetLeft);
		
	}
}

function dialogBox(message, time) {
	
	var dialog = '#dialogBox';
	
	$('body').append('<div id="dialogBox">'+message+'</div>');
	
	$(dialog).dialog({
		draggable: false,
		resizable: false,
		title: 'Information',
		modal: true,
		close:function(){$(dialog).remove();}
	});
	
	$(dialog).click(function() {$(dialog).dialog('close');});
	
	$('.ui-widget-overlay').click(function() {$(dialog).dialog('close');});
	if(time != 0)
		$(dialog).oneTime(time, function() {$(dialog).dialog('close');});
}

//Regex
var integer = "^[0-9]*$";
var mois = "^11|10|[0-9]$";
var validMail = "\\b[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}\\b";
var validDate = "^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\\d\\d$";
var validTel = "^\\+?\\d{10,11}$";
var validMdp = "\\S{6,15}";

//Valide le contenu d'un ï¿½lï¿½ment par son id et une regex 
//sinon affiche le message
function isValid(expr, regex, message) {
	//Construction de la regex
	tester = new RegExp(regex);
	//Si regex invalide
	if ($(expr).val()=="" || !tester.test($(expr).val())) {
		//afficher le message
		appendToToolTip(expr,message);
		return false;
	} else {
		removeFromToolTip(expr);
		return true;
	}
}

function isValidOnKeyUp(expr, regex) {
	//Construction de la regex
	tester = new RegExp(regex);
	//Si regex invalide
	if ($(expr).val()=="" || !tester.test($(expr).val())) {
		//afficher le message
		$(expr).css('border','#e31f1c 2px solid');
		
		return false;
	} else {
		$(expr).css('border','1px solid #8B8C90');
		return true;
	}
}

function isEqualValues(expr1, expr2, message) {
	if($(expr1).val() == $(expr2).val()) {
		removeFromToolTip(expr1);
		return true;
	} else {
		appendToToolTip(expr1,message);
		return false;
	}
}

function isEmptyValue(expr, message) {
	var empty = true;
	if($(expr).attr('type') == 'radio') {
		for (i=0; i<$(expr).size() ;i++){
			if ($(expr).get(i).checked ==true){
				empty=false;
				break;
			}
		}	
	} else {
		empty = $(expr).val() == "";
	}

	if (empty) {
		//afficher le message
		appendToToolTip(expr, message);
		return true;
	} else {
		removeFromToolTip(expr);
		return false;
	}
}

function appendToToolTip(expr, message) {
	$(expr).css('border','#e31f1c 2px solid');
	exprErr = '#tooltipErreur';
	if(message != "") {
		if(!$(exprErr).html() == '') {
			$(exprErr).append('<br/>');
		}
		$(exprErr).append(message);
	}
}

function removeFromToolTip(expr) {
	$(expr).css('border','1px solid #8B8C90');
}


function inputAssist(expr, assist) {
	if($(expr).val() == "")
		$(expr).val(assist);
	$(expr).focus(function() {
		if($(expr).val() == assist)$(expr).val("");
	});
	$(expr).blur(function() {
		if($(expr).val() == "") $(expr).val(assist);
	});
}

function valideMdpOublie() {
	$.post("index.php?ajax=mdpOublieAjax", $("#mdpOublieForm").serialize(),
		function (data, textStatus) {
			if(data.indexOf('Erreur : ',0) > 0) {
				dialogBox(data, 5000);
			} else {
				dialogBox(data, 5000);
			}
		});
}
function validFormulaireNewMdp() {
	
	var form = '#changerMdpForm';
	
	$('#tooltipErreur').empty();
	
	var mdp = isValid('#newmdp', validMdp, 'Mot de passe invalide : 6 à 15 caracteres');
	mdp = isValid('#newmdp2', validMdp, 'Confirmation du mot de passe invalide : 6 à 15 caracteres') && mdp;
	if(mdp) {
		mdp = isEqualValues('#newmdp','#newmdp2','Le mot de passe et sa confirmation ne correspondent pas') && mdp;
	}	
	
	if($('#tooltipErreur').html() != "") {
		var errOffsetTop = $(form).offset().top - -10;
		var errOffsetLeft = $(form).offset().left - -250;
		
		$('#tooltipErreur').css('top',errOffsetTop);
		$('#tooltipErreur').css('left',errOffsetLeft);
		$('#tooltipErreur').show();
	} 
	
	if(mdp) {
		$.post("index.php?ajax=changerMdpAjax", $(form).serialize(),
			function (data, textStatus) {
				dialogBox(data, 5000);
				if(data.indexOf('Erreur : ',0) > 0) {
				}
			});
	}
}

function changerNewsletter() {
	var newsletter = $('#inscrireNewsletter').css('display') == 'none' ? 0 : 1 ; 
	$.get('index.php?ajax=changerNewsletterAjax&newsletter='+newsletter, function (data){
		dialogBox(data, 5000);
		if(data.indexOf('Erreur : ',0) < 0) {
			$('#inscrireNewsletter').toggle();
			$('#desinscrireNewsletter').toggle();
		}
	});
}

//Combien emprunter ********************************************************************

var factDuree = 2;
var initRevenuMensuel = 3000;
var initTaux = 5;
var initMensualite = 990;
var initDureeAnnees = 25;
var initDureeMois = 0;

var arrayValues = new Array({
	'revenuMensuel':initRevenuMensuel,
	'taux':initTaux,
	'montantMensualite':initMensualite,
	'dureeAnnees':initDureeAnnees,
	'dureeMois':initDureeMois	
});


function initCalcCbEmprunter(tx){
	initTaux = tx;
	
	//Défini le block comme resizable
	$('#rBlock').resizable({
		handles:'n,e,ne',
		maxHeight:200,
		maxWidth:240,
		resize:function(event,ui) {
			//top = offset.top+(210-height);
			//$('#rBlock').css('top',top);
			calc();
			
		}
	});
	/*
	//Ajoute les images pour tirer
	if($.browser.msie && $.browser.version < 8) {
		$('#rBlock').find('.ui-resizable-n').addClass('resizeIE');
		$('#rBlock').find('.ui-resizable-ne').addClass('resizeIE');
		$('#rBlock').find('.ui-resizable-e').addClass('resizeIE');
	} else {
		*/
		$('#rBlock').find('.ui-resizable-n').addClass('resize resize-n resize-bg');
		$('#rBlock').find('.ui-resizable-ne').addClass('resize resize-ne resize-bg');
		$('#rBlock').find('.ui-resizable-e').addClass('resize resize-e resize-bg');
	//}
	$("#revenuMensuel").val(initRevenuMensuel);
	setValue('revenuMensuel');
	$("#taux").val(initTaux);
	setValue('taux');
	$("#montantMensualite").val(initMensualite);
	setValue('montantMensualite');
	$("#dureeAnnees").val(initDureeAnnees);
	setValue('dureeAnnees');
	$("#dureeMois").val(initDureeMois);
	setValue('dureeMois');
	 
	
	height = parseInt(arrayValues['montantMensualite']/arrayValues['factRevenu']);
	
	offset = $('#rBlockContainer').offset();
	
	top = offset.top+(210-height);
	left =  offset.left+2;
	
	$('#rBlock').css('top',top);
	$('#rBlock').css('left',left);
	
}

function setValue(name) {
	
	if(name=='revenuMensuel' || name=='taux') {
		if($("#"+name).val() != "")
			arrayValues[name] = parseFloat($("#"+name).val());
	}
	
	arrayValues['factRevenu'] = parseFloat(arrayValues['revenuMensuel']/400);
	
	if(name=='montantMensualite') {
		if($("#"+name).val() != '' && $("#"+name).val() <= Math.floor(arrayValues['revenuMensuel']/2)) {
			arrayValues[name] = parseFloat($("#"+name).val());
			var height = parseInt(arrayValues['montantMensualite']/arrayValues['factRevenu']);
			
			var offset = $('#rBlockContainer').offset();
			$('#rBlock').css('top',offset.top-(-(210-height)));
			$('#rBlock').height(height);
		}
	} 
	
	if(name=='dureeAnnees' || name=='dureeMois') {
		if(name=='dureeMois' && $("#dureeMois").val() >= 12) {
			arrayValues['dureeMois'] = $("#dureeMois").val() % 12;
			arrayValues['dureeAnnees'] += Math.floor($("#dureeMois").val() / 12);
			$("#dureeMois").val(arrayValues['dureeMois']);
		}
		
		if($("#"+name).val() != '' && $("#"+name).val() <= 40) {
			arrayValues[name] = parseInt($("#"+name).val());
			width = Math.floor(((arrayValues['dureeAnnees']*12)
					+arrayValues['dureeMois'])/factDuree);
			if(!isNaN(width)) {
				$('#rBlock').width(width);
			}
		}
	} 
	
	var ecart = parseInt(arrayValues['revenuMensuel'])/10;
	$('#echLeft ul li').each(function(i) {
		$(this).html(parseInt((parseInt(arrayValues['revenuMensuel'])/2) - (ecart*i))+' &euro;');
	});
	
	calc();
}

function valideContact() {
	
	var form = '#formContact';
	
	$('#tooltipErreur').empty();
	
	var empty = isEmptyValue(form+" input[name='nom']",'Veuillez indiquer votre nom');
	empty = isEmptyValue(form+" input[name='civilite']",'Veuillez indiquer votre statut') || empty;
	empty = isEmptyValue(form+" input[name='prenom']",'Veuillez indiquer votre prénom') || empty;
	
	var tel = isValid(form+" input[name='tel']", validTel, 'Téléphone invalide');
	
	var mail = isValid(form+" input[name='mail']", validMail, 'Mail invalide');
	mail = isValid(form+" input[name='conf_email']", validMail, 'Confirmation du mail invalide') && mail;
	if(mail) {
		mail = isEqualValues(form+" input[name='mail']",
							form+" input[name='conf_email']",
							'Le mail et sa confirmation ne correspondent pas') && mail;
	}
	
	if($('#tooltipErreur').html() != "") {
		var errOffsetTop = $(form).offset().top - -10;
		var errOffsetLeft = $(form).offset().left - -250;
		
		$('#tooltipErreur').css('top',errOffsetTop);
		$('#tooltipErreur').css('left',errOffsetLeft);
		$('#tooltipErreur').show();
	} 
	
	if(!empty && tel && mail) {
	
	$.post("index.php?ajax=contactAjax", $('#formContact').serialize(),
		function (data) {
			dialogBox(data, 5000);
			if(data.indexOf('Erreur : ',0) > 0) {
				showToolTipUpToElement('#validerContact',data);
			} else {
				$("#formContact *:not(#formContact input[type='hidden'])").val('');
			}
		});
	}	
}

function calc() {
	
	
	var fact = arrayValues['factRevenu'];
	var m = $('#rBlock').height()*fact;
	var d = $('#rBlock').width()*factDuree;
	var t = arrayValues['taux'];
	var end = parseInt(m/(arrayValues['revenuMensuel']/100));
	if(end > 33) {
		$('#endettement').css('color','red');
	} else {
		$('#endettement').css('color','#8d8b8c');
	}
	$('#endettement').val(end);
	$('#montantMensualite').val(m);
	$('#dureeAnnees').val(Math.floor(d/12));
	$('#dureeMois').val(d%12);
	
	emprunt = new String(parseInt(((m*12)*(1 - Math.pow((1+((t/100)/12)),-d)))/(t/100)));
	
	tmp = "";
	cpt = 0;
	for(i=emprunt.length;i>=0;i--) {
		tmp = emprunt.charAt(i)+tmp;
		if(cpt%3 == 0) {
			tmp = " "+tmp;
		}
		cpt++;
	}
	
	$('#montantEmprunt').val(tmp);
	
}

















