/*
function checkPieces(i){
	for(j=1;j<6;j++){
		if(i != j){
			$('input[name="rooms"][value="'+j+'"]').removeAttr("checked");
		}
	}
}

function checkChambre(i){
	for(j=1;j<6;j++){
		if(i != j){
			$('input[name="bedrooms"][value="'+j+'"]').removeAttr("checked");
		}
	}
}
*/

var timeInfo;
var posx = 0;
var posy = 0;
var saisieLibre = false;
var lastCompletionChoice = '';

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function checkFormulaire(i) {
	if ($('#'+i).attr('checked')) {
		$('input[name="parking"]').attr( 'disabled', 'disabled' ); 
		$('input[name="handicap"]').attr( 'disabled', 'disabled' );
		$('input[name="piscine"]').attr( 'disabled', 'disabled' );
		$('input[name="jardin"]').attr( 'disabled', 'disabled' );
		$('input[name="cave"]').attr( 'disabled', 'disabled' );
		$('input[name="balcon"]').attr( 'disabled', 'disabled' );
		$('input[name="ascenseur"]').attr( 'disabled', 'disabled' );
		
		$('input[name="parking"]').removeAttr("checked");
		$('input[name="handicap"]').removeAttr("checked");
		$('input[name="piscine"]').removeAttr("checked");
		$('input[name="jardin"]').removeAttr("checked");
		$('input[name="cave"]').removeAttr("checked");
		$('input[name="balcon"]').removeAttr("checked");
		$('input[name="ascenseur"]').removeAttr("checked");
	}
	else {
		$('input[name="parking"]').removeAttr("disabled");
		$('input[name="handicap"]').removeAttr("disabled");
		$('input[name="piscine"]').removeAttr("disabled");
		$('input[name="jardin"]').removeAttr("disabled");
		$('input[name="cave"]').removeAttr("disabled");
		$('input[name="balcon"]').removeAttr("disabled");
		$('input[name="ascenseur"]').removeAttr("disabled");
	}
}

function checkFormulaireRecherche(){
	
	if ($('input[name="id"]').val() !=''){
		window.document.location.href='/immobilier/annonces-immobilieres/produits.php?id='+$('input[name="id"]').val();
		return false;
	}
	
	if ($('input[name="libre"]').val() == ''){
		alert('Veuillez choisir une localisation pour votre recherche');
		return false;
	} else if(!($('#appartement').attr('checked')) 
			&& !($('#immeuble').attr('checked')) 
			&& !($('#maison').attr('checked')) 
			&& !($('#local').attr('checked')) 
			&& !($('#terrain').attr('checked')) 
			&& !($('#commerce').attr('checked')) 
			&& !($('#parkinggaragebox').attr('checked')) 
			&& !($('#bureau').attr('checked')) ){
		
		alert('Veuillez choisir un type de bien pour votre recherche');
		return false;
	}
}


function submitRecherche(i){
	if ($('input[name="libre"]').val() == '' || $('input[name="libre"]').val() =='Ville, CP, Département'){
		alert('Veuillez choisir une localisation pour votre recherche');
		
	}
	else if (i!=1 && !($('#appartement').attr('checked')) && !($('#maison').attr('checked')) ){
		alert('Veuillez choisir un type de bien pour votre recherche');
	}
	else {
		document.forms["FormMaRecherche"].submit();
	}
}

function checkFormulaireSimple(i){
	
	if ($('input[name="libre"]').val() == '' || $('input[name="libre"]').val() =='Ville, CP, Département') {
		alert('Veuillez choisir une localisation pour votre recherche');
		return false;
	}
	else if (saisieLibre == true && !isNumber($('input[name="libre"]').val())){
		var url = "/includes/modules/rechercheBiens/getVillesSearch.php?localisation="+escape($('input[name="libre"]').val());				
		var submit = false;
		$.ajax({
				url: url,
				dataType: 'json',
				async: false ,
				success: function (data){		
						il = data.length;
						for (var i = 0; i < il; i++) {
							  if($('input[name="libre"]').val().toLowerCase()==data[i].id.toLowerCase()){
								  submit = true;
							  }
						}
					}
				}
			   );	
		if(!submit){
			//alert('Vous devez choisir une localisation dans la liste proposée.\nSi la ville n\'apparait pas dans les suggestions, c\'est qu\'aucun bien ne correspond à votre recherche.\n N\'hésitez pas à contacter l\'agence Laforêt la plus proche.');						
			alert('Veuillez choisir une localisation valide pour votre recherche');
			return false;
		}else{
			return true;
		}
	}
	else if (i!=1 && !($('#appartement').attr('checked')) && !($('#maison').attr('checked'))) {
		alert('Veuillez choisir un type de bien pour votre recherche');
		return false;
	}
	else {
		return true;
	}

}

function checkFormulaireAgence(i){
	
	if($('#localisation_agence').val() == '' || $('#localisation_agence').val() =='Ville, CP, Département'){
		alert('Veuillez choisir une localisation pour votre recherche');
		return false;
	}else{
		return true;
	}

}

// Autocompletion
function searchPreview(like, id, callback) {
	
	if (lastCompletionChoice == '' || lastCompletionChoice != $("#"+id).val()) {
		saisieLibre = true;
	}
	
	$("#"+id).autocomplete({
		source: "/includes/modules/rechercheBiens/getVillesSearch.php",
		minLength: 2,
		select: function(event, ui) {
			if (ui) {
				saisieLibre = false;
				lastCompletionChoice = ui.item.label;
                $("#"+id).val(ui.item.label);
				
				if (callback) {
					callback.call();
				}
                
                return false;
			}
		}
	});
}

//multiples localisation
function rempliMultipleLoacl(type)
{
	
	if($('#libre1').val() != ''){
		$(window.parent.document).find('#libre1').html($('#libre1').val());
		$(window.parent.document).find('#in_libre1').val($('#libre1').val());
		$(window.parent.document).find('#p_libre1').attr('style','display:block;');
	}else{
		$(window.parent.document).find('#libre1').html('');
		$(window.parent.document).find('#in_libre1').val('');
		$(window.parent.document).find('#p_libre1').attr('style','display:none;');
	}
	if($('#libre2').val() != ''){
		$(window.parent.document).find('#libre2').html($('#libre2').val());
		$(window.parent.document).find('#in_libre2').val($('#libre2').val());
		$(window.parent.document).find('#p_libre2').attr('style','display:block;');
	}else{
		$(window.parent.document).find('#libre2').html('');
		$(window.parent.document).find('#in_libre2').val('');
		$(window.parent.document).find('#p_libre2').attr('style','display:none;');
	}
	if($('#libre3').val() != ''){
		$(window.parent.document).find('#libre3').html($('#libre3').val());
		$(window.parent.document).find('#in_libre3').val($('#libre3').val());
		$(window.parent.document).find('#p_libre3').attr('style','display:block;');
	}else{
		$(window.parent.document).find('#libre3').html('');
		$(window.parent.document).find('#in_libre3').val('');
		$(window.parent.document).find('#p_libre3').attr('style','display:none;');
	}
	if($('#libre4').val() != ''){
		$(window.parent.document).find('#libre4').html($('#libre4').val());
		$(window.parent.document).find('#in_libre4').val($('#libre4').val());
		$(window.parent.document).find('#p_libre4').attr('style','display:block;');
	}else{
		$(window.parent.document).find('#libre4').html('');
		$(window.parent.document).find('#in_libre4').val('');
		$(window.parent.document).find('#p_libre4').attr('style','display:none;');
	}
	$(window.parent.document).find('#fancybox-overlay').css('display','none');		
	$(window.parent.document).find('#fancybox-wrap').css('display','none');	
	if($(window.parent.document).find('#libre1').html()!="" && $(window.parent.document).find('#libre2').html()!="" && $(window.parent.document).find('#libre3').html()!="" && $(window.parent.document).find('#libre4').html()!=""){
		$(window.parent.document).find("#libre").attr('disabled','disabled');
	}else{
		$(window.parent.document).find("#libre").removeAttr('disabled');
	}
}

//supprimer une localisation
function supprimerLocal(i)
{
  var count = 0;
  for (var j = 1;j < 5; j++)
  {
    if ($(window.parent.document).find('#in_libre'+j).val ())
      ++count;
  }

  if (count > 1)
  {
    show_modal('Recherche en cours, veuillez patienter ...');

    $(window.parent.document).find('#libre'+i).html('');
    $(window.parent.document).find('#p_libre'+i).attr('style','display:none;');
    $(window.parent.document).find('#in_libre'+i).val('');
    $(window.parent.document).find('#libre').removeAttr('disabled');
  }
  else
    alert ('La localisation est obligatoire pour lancer une recherche');
}


//formulaire d'inscription

function getForm(nb)
{
  var err = '';
  var civ1 = document.FormSubscribtion.civilite[0].checked;
  var civ2 = document.FormSubscribtion.civilite[1].checked;
  var civ3 = document.FormSubscribtion.civilite[2].checked;
  var civ4 = document.FormSubscribtion.civilite[3].checked;
  var cprenom = document.FormSubscribtion.cprenom.value;
  var cnom = document.FormSubscribtion.cnom.value;
  var ccp = document.FormSubscribtion.cCP.value;
  var cemail = document.FormSubscribtion.cemail.value;
  var pswd1 = document.FormSubscribtion.pswd1.value;
  var pswd2 = document.FormSubscribtion.pswd2.value;
  var show = 1;
	
  document.getElementById('alertForm2').innerHTML = '';
  document.getElementById('alertFormV').innerHTML = '';

  if (cemail == '' || pswd1 == '' || pswd2 == '' ||
      (civ1 == '' && civ2 == '' && civ3 == '' && civ4 == '') ||
      cprenom == '' || cnom == '')
  {
    err = "Veuillez remplir les champs suivants&nbsp:<br />";
    if (cemail == '') 
      err += "- E-Mail<br />";
    if (pswd1 == '') 
      err += "- Mot de passe<br/>";
    if (pswd2 == '') 
      err += "- Confirmation du mot de passe<br/>";
    if (civ1 == '' && civ2 == '' && civ3 == '' && civ4 == '') 
      err += "- Civilité<br />";
    if (cprenom == '') 
      err += "- Prénom<br />";
    if (cnom == '') 
      err += "- Nom";


    document.getElementById('alertForm2').innerHTML = err;

    if (ccp == '')
      return;
  }

  if (nb == 1 && ccp == '')
  {
    show = 0;
    document.FormSubscribtion.submit ();
  }

  if ((cprenom != '' && cnom != '' && ccp != '') && 
      (texte = file("/immobilier/mon-espace-laforet/getForm.php?cnom=" + 
        escape (cnom) + '&cprenom=' + escape (cprenom) + '&ccp=' + 
	ccp + '&cemail=' + escape (cemail))))
  {
    if (texte != '')
    {
      if (texte == '0')
      {
        err = "Aucun bien en vente n'est lié aux nom, prénom et numéro saisis. Pour accéder à l'isuivi, vous devez les modifier et cliquer sur <i>Corriger</i>.<br>Si vous souhaitez simplement mémoriser une recherche, veuillez effacer les données saisies dans le cadre réservé aux vendeurs.";
	document.getElementById('alertFormV').innerHTML = err;
	show = 1;
        document.getElementById('vendorRetry').style.display = 'block';
      }
      else if (texte.indexOf('::') == -1)
      {
        tabForm = texte.split ('|');
			
        civ = tabForm[0];
        //cprenom = tabForm[1];
        ccp2 = tabForm[2];
        cnum2 = tabForm[3];
        adresse1 = tabForm[4];
        adresse2 = tabForm[5];
        cp = tabForm[6];
        country = tabForm[7];
        ville = tabForm[8];
        tel = tabForm[9];
				
        if (nb == 1)
        {
          if (civ == "m") 
	    document.FormSubscribtion.civilite[0].checked = true;
          else if (civ == "mme") 
	    document.FormSubscribtion.civilite[1].checked = true;
          else if (civ == "mlle") 
	    document.FormSubscribtion.civilite[2].checked = true;
					
          if(ccp == '' && ccp2 != '')
          {
            show = 0;
            openPopup (
	      '/immobilier/mon-espace-laforet/popup/' +
	      'profil-contrat-privilege.php', 'contrat', 541, 300);
          }
          else 
	    document.FormSubscribtion.cCP.value = ccp2;
					
          document.FormSubscribtion.cadrs.value = adresse1;
          document.FormSubscribtion.cadrs2.value = adresse2;
          document.FormSubscribtion.cp.value = cp;
          document.FormSubscribtion.ccountry.value = country;
          document.FormSubscribtion.cville.value = ville;
          document.FormSubscribtion.ctel.value = tel;
        }
				
        var arrDisabledFields = new Array ();
	arrDisabledFields['civilite'] = 1;
	arrDisabledFields['cprenom'] = 1;
	arrDisabledFields['cnom'] = 1;
	arrDisabledFields['cCP'] = 1;
	arrDisabledFields['cadrs'] = 1;
	arrDisabledFields['cadrs2'] = 1;
	arrDisabledFields['cp'] = 1;
	arrDisabledFields['ccountry'] = 1;
	arrDisabledFields['cville'] = 1;
	arrDisabledFields['ctel'] = 1;
				
        if (nb == 2)
        {
          var arrPericlesFields = new Array ();					
          periclesFields = document.FormSubscribtion.periclesFields.value;
          arrPericlesFields = periclesFields.split(',');
					
          arrDisabledFields['civilite'] = 0;
          arrDisabledFields['cprenom'] = 0;
          arrDisabledFields['cnom'] = 0;
          //arrDisabledFields['cCP'] = 0;
          arrDisabledFields['cadrs'] = 0;
          arrDisabledFields['cadrs2'] = 0;
          arrDisabledFields['cp'] = 0;
          arrDisabledFields['ccountry'] = 0;
          arrDisabledFields['cville'] = 0;
          arrDisabledFields['ctel'] = 0;
					
          for (i = 0; i < arrPericlesFields.length; i++)
          {
            if (arrPericlesFields[i] == "civilite") 
	      arrDisabledFields['civilite'] = 1;
            if (arrPericlesFields[i] == "cprenom")
	      arrDisabledFields['cprenom'] = 1;
            if (arrPericlesFields[i] == "cnom")
	      arrDisabledFields['cnom'] = 1;
            if (arrPericlesFields[i] == "cCP") 	
	      arrDisabledFields['cCP'] = 1;
            if (arrPericlesFields[i] == "cadrs")
	      arrDisabledFields['cadrs'] = 1;
            if (arrPericlesFields[i] == "cadrs2")
	      arrDisabledFields['cadrs2'] = 1;
            if (arrPericlesFields[i] == "cp")
	      arrDisabledFields['cp'] = 1;
            if (arrPericlesFields[i] == "ccountry")
	      arrDisabledFields['ccountry'] = 1;
            if (arrPericlesFields[i] == "cville")
	      arrDisabledFields['cville'] = 1;
            if (arrPericlesFields[i] == "ctel")
	      arrDisabledFields['ctel'] = 1;
          }
        }
				
        if ((document.FormSubscribtion.civilite[0].checked || 
	     document.FormSubscribtion.civilite[1].checked || 
	     document.FormSubscribtion.civilite[2].checked) && 
	     arrDisabledFields['civilite'] == 1)
        {
          document.FormSubscribtion.civilite[0].disabled = "disabled";
          document.FormSubscribtion.civilite[1].disabled = "disabled";
          document.FormSubscribtion.civilite[2].disabled = "disabled";
        }
	
        if (document.FormSubscribtion.cprenom.value != '' && 
	    arrDisabledFields['cprenom'] == 1) 
	  document.FormSubscribtion.cprenom.disabled = 'disabled';
	  
        if (document.FormSubscribtion.cnom.value != '' && 
	    arrDisabledFields['cnom'] == 1) 
	  document.FormSubscribtion.cnom.disabled = 'disabled';
	  
        if (document.FormSubscribtion.cCP.value != '' && 
	    arrDisabledFields['cCP'] == 1)
	  document.FormSubscribtion.cCP.disabled = 'disabled';

        if (document.FormSubscribtion.cadrs.value != '' && 
	    arrDisabledFields['cadrs'] == 1)
	  document.FormSubscribtion.cadrs.disabled = 'disabled';
	  
        if (document.FormSubscribtion.cadrs2.value != '' && 
	    arrDisabledFields['cadrs2'] == 1)
	  document.FormSubscribtion.cadrs2.disabled = 'disabled';
	  
        if (document.FormSubscribtion.cp.value != '' && 
	    arrDisabledFields['cp'] == 1)
	  document.FormSubscribtion.cp.disabled = 'disabled';
	  
        if (document.FormSubscribtion.ccountry.value != '' && 
	    arrDisabledFields['ccountry'] == 1)
	  document.FormSubscribtion.ccountry.disabled = 'disabled';

        if (document.FormSubscribtion.cville.value != '' && 
	    arrDisabledFields['cville'] == 1)
	  document.FormSubscribtion.cville.disabled = 'disabled';
	  
        if (document.FormSubscribtion.ctel.value != '' && 
	    arrDisabledFields['ctel'] == 1)
	  document.FormSubscribtion.ctel.disabled = 'disabled';
      }
      else
      {
        show = 0;
	err = 'yes';
        document.getElementById('alertFormV').innerHTML = 
          texte.replace ('::', '');
      }
    }
  }

  if (show == 1)
  {
    for (i = 0;i <= 10; i++)
    {
      document.getElementById('formLine' + i).style.display = '';
    }
    document.getElementById('btn2').style.visibility  = 'hidden';
    document.getElementById('vendorRetry').style.display = 'block';
    location.href = '#suite';
  }

  if (err == '' && document.getElementById('fmkError').value != '1')
    document.getElementById('alertForm2').innerHTML = '';
}


/***** Popup *****/

function openPopup(url,name,w,h,o){
	window.open(url,name,'width='+w+',height='+h+',resizable=0,'+o);
}


/*** alerte Mail ***/

function alerteMail (recherche, val)
{
  if (val == 0 || val == 1)
	  var url = "/immobilier/mon-espace-laforet/getFonctions.php?fonction=alerteMail&recherche="+recherche+"&val="+val;				
  	  $.post(url,function (data){});
}

/*****  popup description annonce *********/
function showFiche(obj,propertyId,cpt,privi)
{
  if (document.all  && $('#flayerinfo'+privi) || !document.all ){
    //hideInfo ();
	 p = $('.numresultat'+cpt).position();
	 posx = p.left + 0;
	 posy = p.top + 0;
			
    if (propertyId != ""){
    	var texte = ""
    	var url = "/immobilier/annonces-immobilieres/getFicheSearch.php?search="+escape(propertyId)+"&cpt="+cpt;	
    	
	    	$.post(url,function (data){
	    			texte = data;
			    	if (texte != ""){
				        tabSearchFiche = texte.split("|");
				        transactionType = tabSearchFiche[0];
				        propertyType = tabSearchFiche[1];
				        city = tabSearchFiche[2];
				        contratPrivilege2 = tabSearchFiche[3];
				        sellingPrice = tabSearchFiche[4];
				        roomsQuantity = tabSearchFiche[5];
				        surface = tabSearchFiche[6];
				        surfaceUnit = tabSearchFiche[7];
				        departementId = tabSearchFiche[8];
				        desc = tabSearchFiche[9];
				        groundSurface = tabSearchFiche[10];
				        bedroomsQuantity = tabSearchFiche[11];
				        floorsQuantity = tabSearchFiche[12];
				        mainVisu = tabSearchFiche[13];
				        subVisus = tabSearchFiche[14];
				        fees =  tabSearchFiche[15];
				        deposit =  tabSearchFiche[16];
				        cession =  tabSearchFiche[17];
				        internetLocation = tabSearchFiche[18];
				        linkProduct = tabSearchFiche[19];
				        				
				        var infoLoc1 = '';
				        var infoLoc2 = '';
				        var infoLoc3 = '';
			
			        if (transactionType == '2'){
			          var localBureau = (propertyType == "Local commercial" ||  propertyType == "Bureau");
			          infoLoc1 = (localBureau) ?  " annuel HT HC" :  " mensuel CC";
			          if (fees != '0'){
			            infoLoc2 = 'Honoraires en sus : ' + fees +  '&nbsp;&euro;&nbsp;' + ((localBureau) ? 'HT' : 'TTC') + ' **';
			          }
			          if (deposit != '0'){
			            infoLoc3 += '<br />Dépôt de garantie : ' +  deposit + '&nbsp;&euro;&nbsp;' + 'TTC';
			          }
			          if (localBureau){
			            infoLoc3 += '<br />Cession de bail : ' + cession + '&nbsp;&euro;&nbsp;';
			          }
			        }
			
			        var infosfiche = "<h1><a href='" + linkProduct + "'><strong>"+sellingPrice+" &euro; " + infoLoc1 +  "</strong> * <strong> - "+ propertyType;
			        if (roomsQuantity != "" && roomsQuantity > 0){ 
			          infosfiche += " "+roomsQuantity+" pi&egrave;ce(s)";
			        }
			        if (surface != ""){ 
			          infosfiche +=  "<br />"+surface+" "+surfaceUnit + '&nbsp;' + 'environ';
			        }
			        infosfiche += "</strong></a></h1><h2>" + ((internetLocation == 1) ? "Aux alentours de " : "") + city + " (" + departementId + ")</h2>";
			        infosfiche += infoLoc2 + infoLoc3;
			        $("#infosFiche"+privi).html(infosfiche);
			        $("#descFiche"+privi).html(desc);
			        if (contratPrivilege2 == 1){ 
			          $("#contratPrivilege").css('display ',"block");
			        }else{ 
			          $("#contratPrivilege").css('display' , "none");
			        }
			         /* Visuels */
			        if (mainVisu != ""){ 
			          $("#visuFiche"+privi).html(mainVisu);
			        }
			        if (subVisus != ""){ 
			          $("#thumbFiche"+privi).html(subVisus + "\n<div class=\"clear\"></div>\n");
			        }
			        // Clear & appel
			        clearTimeout(timeInfo);
			        timeInfo = setTimeout("showInfo('"+privi+"');",500);
			      }
	        });
	    }
  }
  
}

function hideInfo(){ 
	var layerInfo = $('#infoLayer');
	var layerInfo1 = $('#infoLayer1');
	layerInfo.css('top' , '-999px');
	layerInfo.css('left' , '-999px');
	layerInfo1.css('top' , '-999px');
	layerInfo1.css('left' , '-999px');
	if(document.all ){
		$('#flayerinfo').css('left' , '-999px');
		$('#flayerinfo').css('top' , '-999px');
		$('#flayerinfo1').css('left' ,'-999px');
		$('#flayerinfo1').css('top' , '-999px');
	}
}

function showInfo(privi){
		
	var resultat = '';
	var layerInfo = $('#infoLayer'+privi);
	layerInfo.css('left',posx+'px');
	if (document.all) {
		$('#flayerinfo'+privi).css('left' , (posx+50)+'px');
		$('#flayerinfo'+privi).css('height',$('#infoLayer'+privi).height());
	}
	layerInfo.css('top' , posy+'px');
    
    $('img').bind('contextmenu', function(){
       return false; 
    });
            
    $(document).bind('dragstart', function(){
       return false; 
    });
}

function changeImg(bigImage){
	$('#visuFiche1 > a > img').attr('src',bigImage);
	$('#visuFiche > a > img').attr('src',bigImage);
}

function number_format (number, decimals, dec_point, thousands_sep) {
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');    }
    return s.join(dec);
}

function updateTotalSelection()
{
	var url = '/immobilier/annonces-immobilieres/getTotalSelection.php';
	$.get(url,function (data){
		if ($('#totalSelection')) {
			$('#totalSelection').html(data);
		}
	});
}

