/**
* Autocompletion
*/

// Lorsque la totalité de la page est chargée
	$(document).ready(function() {
		function formatItem(row) {
			return row[0] + " (<strong>id: " + row[1] + "</strong>)";
		}
		function formatResult(row) {
			return row[0].replace(/(<.+?>)/gi, '');
		}

		/**
		 * Autocomplétion lieu de travail
		 */

    if(typeof($('#codeEntreprise').val()) != 'undefined') { 

		idChampLieuValue = '#lieuPro';
		idChampLieuHiddenValue = '#listeSiteEntreprise';
		codeEntreprise = $('#codeEntreprise').val();

		$(idChampLieuValue).autocomplete("/ajax/entreprises.php?action=SearchLieu&codeEntreprise=" + codeEntreprise, {
			width: 260,
			minChars: 5,
			selectFirst: true,
			delay: 300,//200
			cacheLength: 0,//1
			max: 150
		});
		
		HiddenLoading('#loadingLieuEntreprise');

		$(idChampLieuValue).result(function(event, data, formatted) {
			if (data) {
				
				if ($('#codeEntreprise').val() != '') {
					DisplayLoading('#loadingLieuEntreprise');
				} else {
					HiddenLoading('#loadingLieuEntreprise');
				}
				
				//Valeur du champ input après sélection
				$(idChampLieuValue).val(data[2]);
				//Valeur de l'idVille après sélection
				$(idChampLieuHiddenValue).val(data[1]);
				
				if ($('#codeEntreprise').val() != '') {
					HiddenLoading('#loadingLieuEntreprise');
				}
			}
		});
		}

		/**
		 * Autocomplétion ville de résidence
		 */

		idChampValue = '#ville_autocomplete';
		idChampHiddenValue = '#geonameid';
		idChampPaysValue = '#pays';

		$(idChampValue).autocomplete("/ajax/geonames.php?action=SearchCityMemory&favori=false", {
			width: 260,
			minChars: 3,
			selectFirst: true,
			delay: 300,//200
			cacheLength: 0,//1
			max: 150
		});

		$(idChampValue).result(function(event, data, formatted) {
			if (data) {
				//Valeur du champ input après sélection
				$(idChampValue).val(data[2]);
				//Valeur de l'idVille après sélection
				$(idChampHiddenValue).val(data[1]);
				//Valeur de l'idPays après sélection
				$(idChampPaysValue).val(data[3]);
				
				if(typeof($('#idLieuDepart').val()) != 'undefined') {
				//On recherche les lieux publics à proximité de la ville de résidence
				majListeLieuProximite('#geonameid', 10, 50, '#idLieu_residence_select', '');
			}
			}
		});

		if(typeof($('#codeEntreprise').val()) != 'undefined') {
		verifCodeEntreprise();
    }
		if(typeof($('#idLieuDepart').val()) != 'undefined') {
		//On recherche les lieux publics à proximité de la ville de résidence
		majListeLieuProximite('#geonameid', 10, 50, '#idLieu_residence_select', '');
		}
	});

	/**
	 *
	 * @access public
	 * @return void
	 **/
	function verifSiteCodePostal(){
		if ($('#postal_code').val() != '') {
			parametres = 'action=SearchVille' + '&codePostal=' + $('#postal_code').val() + '&pays=' + $('#pays_id').val();

			$.ajax({
					type: 'GET',
					url: '/ajax/entreprises.php',
					data: parametres,
					//error: rapporteErreur,
					success: function(data) {
					  $('#champHiddenGeonameid').html(data);
					  listeSites();
					}
				});
		}
	}

	function listeSites() {
		if ($('#geonameid').val() != '') {
			parametres = 'action=SearchLieuEntreprise&geonameid=' + $('#geonameid').val();

			$.ajax({
						type: 'GET',
						url: '/ajax/entreprises.php',
						data: parametres,
						//error: rapporteErreur,
						success: function(data) {
						  $('#listeSites').html(data);
						}
					});
		} else {
			$('listeSites').innerHTML = '';
		}
	}

	function majListeLieu() {
		parametres = 'action=GetLieuMembre';

		$.ajax({
					type: 'GET',
					url: '/ajax/entreprises.php',
					data: parametres,
					//error: rapporteErreur,
					success: function(data) {
					  $('#listeSitesMembre').html(data);
					  $('#listeSites').html('');
					}
				});
	}

	/*function deleteLieu(idLieu) {
		parametres = 'action=DeleteLieu&local_id=' + idLieu;

		$.ajax({
					type: 'GET',
					url: '/ajax/entreprises.php',
					data: parametres,
					//error: rapporteErreur,
					success: function(data) {
					  //$('#listeSitesMembreTraitement').html(data);
					  majListeLieu();
					}
				});
	}*/

	function selectSite() {
		if ($('#local_id').val() != '') {
			url = '/ajax/entreprises.php';
			parametres = 'action=AddLieu&local_id=' + $('#local_id').val();

			$.ajax({
					type: 'GET',
					url: '/ajax/entreprises.php',
					data: parametres,
					//error: rapporteErreur,
					success: function(data) {
					  //$('#listeSitesMembreTraitement').html(data);
					  
					  $('#geonameid').val('');
					  $('#postal_code').val('');
					  $('#local_id').val('');
					  $('#local_id').attr("disabled", true);
					  $('#submit_entreprise_site').attr("disabled", true);
					  majListeLieu();
					  
					  alert('Votre site professionnel a été ajouté. Vous pouvez à présent effectuer des trajets au sein de votre entreprise/administration');
					  
					  document.location.href="/membres/Entreprise";
					}
				});

			/*myAjax = new Ajax.Updater(
					'listeSitesMembreTraitement',
					url,
					{
					method: 'get',
					parameters: parametres,
					evalScripts: true,
					onFailure: rapporteErreur,
					onComplete: majListeLieu
					}
				);*/
		} else {
			//$('listeSites').innerHTML = '';
		}
		//document.location.href="/membres/Entreprise";
	}

	function confirmDeleteMembreFavoris(idmf) {
		res = confirm('Voulez-vous vraiment supprimer le membre favoris ?');

		if (res == true) {
			window.location.href = '/membres.php?action=DeleteMembreFavoris&idmf=' + idmf;
		}
	}

	function verifCodeEntreprise() {
		if (typeof($('#codeEntreprise').val()) != 'undefined') {
			action = 'VerifCodeEntreprise';
			code = $('#codeEntreprise').val();
		  parametres_postal = '';

			if (code != '' && typeof(code) != 'undefined') {
				code = code.replace(/é/g, "e");

				if( typeof(C_EntrepriseDpt) != 'undefined') {
					if( (C_EntrepriseDpt == 'true') || (C_EntrepriseDpt == true) ) {
						postal = $('#codePostalEntreprise').val();
			            parametres_postal = '&postal=' + postal;

						if (postal == '') {
							code = '';
						}
					}
				}

				if ( typeof( $('#dptEntreprise').val() ) != 'undefined') {
					code = '';
				}

        if (code != '') {
					url = '/ajax/membres.php?';
					idLieu = '#listeSiteEntreprise';

					parametres = 'action=' + action + '&code=' + code + parametres_postal;

					/*$.ajax({
						type: 'GET',
						url: '/ajax/membres.php',
						data: parametres,
						success: function(data) {
						  $("#gc_form_inscription_ResultVerifCodeEntreprise").html(data);
						  $('#gc_form_inscription_ResultVerifCodeEntreprise').show();
						  $('#gc_form_inscription_verifCodeEntreprise').show();
						}
					});*/

					/*if( typeof(C_membreServiceEntreprise) != 'undefined') {
						if( (C_membreServiceEntreprise == true) || (C_membreServiceEntreprise == 'true') ) {
							ServiceFromEntreprise();
						}
					}*/
					
					//Lieu correspondant

	       var html = $.ajax({ url: url + parametres, async: false }).responseText;

	       reg = new RegExp("[;]+", "g");
	       tableau=html.split(reg);

	       tmp = new Array();

	       //Creation de l'objet des groups de lieux
	       data_lieu = new Object();

	       if(tableau.length > 1) {
		        delete data_lieu;
		        data_lieu = new Object();
	       }

	       for (var i=0; i<tableau.length; i++) {
 		       reg2 = new RegExp("[|]+", "g");
		       tmp=tableau[i].split(reg2);
		       index = tmp[0];
		        data_lieu[index] = tmp[1];
	       }

	       $(idLieu).children().remove();

	       if(tableau.length == 1) {
		        delete data_lieu;
		        data_lieu = new Object();
		        data_lieu['none'] = 'Aucun lieu correspondant';
	       }

	       $.each(data_lieu, function(val, text) {
		        reg3 = new RegExp("[_]+", "g");
		        tmp=val.split(reg3);

		        if(tmp[0] == 'local' && tableau.length == 2) {
			         $(idLieu).append(
        		    $('<option selected="selected"></option>').val(tmp[1]).html(text)
    		      );
				} else if(tmp[0] == 'local') {
			         $(idLieu).append(
        		    $('<option></option>').val(tmp[1]).html(text)
    		      );
		        } else if(tmp[0] == 'group') {
			         $(idLieu).append('<optgroup label="' + text + '"></optgroup>');
		        } else {
			         $(idLieu).append(
        		      $('<option></option>').val(val).html(text)
    		        );
    		        $(idLieu).attr("disabled", true);
		        }
	       });

	       if(tableau.length > 1) {
		        $(idLieu).attr("disabled", false);
	       }
				}
			}
		}
	}
