var themap = null;
var bounds;

var infowindow;
var opened = 0;
var redisplayed = false;

function addMarker (lat, lng, txt, i, estUsager) {
    var marker;
    if (estUsager) {
        var iconUsager = new google.maps.MarkerImage ('http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=glyphish_user|0000FF',
	    	    	  			   new google.maps.Size (21, 34),
					           new google.maps.Point (0, 0),
						   new google.maps.Point (11, 34));
        marker = new google.maps.Marker ({map: themap, position: new google.maps.LatLng(lat, lng), icon: iconUsager});
    } else {
        marker = new google.maps.Marker ({map: themap, position: new google.maps.LatLng(lat, lng)});
    }
    bounds.extend (new google.maps.LatLng(lat, lng));
    infowindow[i] = new google.maps.InfoWindow ({ content: txt });
    google.maps.event.addListener (marker, 'click', function () {
	    if (opened) {
		infowindow[opened].close (); 
	    } 
	    infowindow[i].open (themap, this);
	    opened = i;
	});
}

function region_change () {
    rgn_id = $(this).val();
    thisregion = $(this);
    if (rgn_id > 0) {
	$(this).next (".departement").html ('<option value="0">Tous départements</option>');
	thisrgndom = $(this);
	$.ajax ( {
	    type: 'GET',
	    url: '/ajax/liste_departements.php?id='+rgn_id,
	    dataType: 'xml',
	    success: function (reponse) {
		thisregion.next (".departement").hide ();
		$(reponse).find('departement').each (function () {
		    thisrgndom.next (".departement").append ('<option value="'+$(this).attr('id')+'">'+$(this).attr('id')+' - '+$(this).text()+'</option>');
		});
		thisregion.next (".departement").show ();
		thisregion.next (".departement").next (".ville").hide ();
		thisregion.next (".departement").next (".ville").val ('');
	    }
	});
    } else {
	$(this).next (".departement").hide ();
	$(this).next (".departement").val (0);
	$(this).next (".departement").next (".ville").hide ();	    
	$(this).next (".departement").next (".ville").val ('');
    }	
}

function departement_change () {
    dep_id = $(this).val ();
    thisdpt = $(this);
    if (dep_id > 0) {
	$(this).next (".ville").html ('<option value="">Toutes villes</option>');
	thisdepdom = $(this);
	$.ajax ( {
	    type: 'GET',
	    url: '/ajax/liste_villes.php?id='+dep_id,
	    dataType: 'xml',
	    success: function (reponse) {
		thisdpt.next (".ville").hide ();
		$(reponse).find('ville').each (function () {
		    thisdepdom.next(".ville").append ('<option value="'+$(this).text()+'">'+$(this).text()+'</option>');
		});
		thisdpt.next (".ville").show ();
	    }
	});
	
    } else {
	$(this).next (".ville").hide ();	    
	$(this).next (".ville").val (''); 
    }
}

function supprime_critere_geo () {
    $(this).parent().remove ();
}

function cree_xml_recherche () {
    var xml='<recherche>';
    if ($("#sur_domaine:checked").length) {
	xml = '<recherche sur-domaine="1" uti-id="'+$("#uti_id").val()+'">';
    }
    xml += '<geos>';
    $("#criteres_geo .critere").each (function () {
	    xml += '<geo><region>'+$(this).children (".region").val()+'</region><departement>'+$(this).children (".departement").val()+'</departement><ville>'+$(this).children (".ville").val()+'</ville></geo>';
	});
    xml += '</geos>';
    
    if ($("#toutes_categories:checked").length) {
	xml += '<categories></categories>';
    } else {
	xml += '<categories>';
	$("#cat_tree input:checked").each (function () {
		xml += '<categorie>'+$(this).val ()+'</categorie>';
	    });
	xml += '</categories>';
    }
    
    if ($("#tous_statuts:checked").length) {
	xml += '<statuts></statuts>';
    } else {
	xml += '<statuts>';
	$("#sta_tree input:checked").each (function () {
		xml += '<statut>'+$(this).val ()+'</statut>';
	    });
	xml += '</statuts>';
    }
    
    if ($("#toutes_tarifications:checked").length) {
	xml += '<tarifs></tarifs>';
    } else {
	xml += '<tarifs>';
	$("#tar_tree input:checked").each (function () {
		xml += '<tarif>'+$(this).val ()+'</tarif>';
	    });
	xml += '</tarifs>';
    }
    xml += '<raison>'+$("#raison").val()+'</raison>';  
    xml += '<siren>'+$("#siren1").val()+$("#siren2").val()+'</siren>'; 
    xml += '<finess>'+$("#nofiness").val()+'</finess>';
    
    if ($("#toutes_disciplines:checked").length) {
	xml += '<disciplines></disciplines>';
    } else {
	xml += '<disciplines>';
	$("#dil_tree input:checked").each (function () {
		xml += '<discipline>'+$(this).val ()+'</discipline>';
	    });
	xml += '</disciplines>';
    }
    
    if ($("#tous_modes:checked").length) {
	xml += '<modes></modes>';
    } else {
	xml += '<modes>';
	$("#mod_tree input:checked").each (function () {
		xml += '<mode>'+$(this).val ()+'</mode>';
	    });
	xml += '</modes>';
    }
    
    if ($("#tous_clients:checked").length) {
	xml += '<clients></clients>';
    } else {
	xml += '<clients>';
	$("#cli_tree input:checked").each (function () {
		xml += '<client>'+$(this).val ()+'</client>';
	    });
	xml += '</clients>';
    }

    xml += '<age>'+$('#age').val()+'</age>';
    var sexe = $('input[name="sexe"]:checked').val();
    if (sexe == undefined)
	sexe = '';
    xml += '<sexe>'+sexe+'</sexe>';
    
    
    if (/*$("#geoloc:checked").length &&*/ $("#code_geoloc").val() == "200") {
	xml += '<geoloc><lat>'+$("#lat_geoloc").val()+'</lat><lng>'+$("#lng_geoloc").val()+'</lng></geoloc>';
    }
    
    xml += '</recherche>';
    
    return xml;
}

//var tabs;
$(document).ready (function () {    
	//    tabs = $("#tabs").tabs();

    $("#en-tete a").click (on_onglet_click);

    $(".departement").hide ();
    $(".departement").val (0);
    $(".ville").hide ();
    $(".ville").val ('');

    $("#export_tableur").hide ();
    $("#tab2").hide ();
    $("#tab3").hide ();

    $("#ajout_critere_geo").click (function () {
	$("#criteres_geo").append ('<div class="critere critcadre"><select class="region"><option value="0">Toutes régions</option></select><select class="departement"><option value="0">Tous départements</option></select><select class="ville"><option value="">Toutes villes</option></select><input type="button" class="supprime_critere_geo" value="Supprimer"></input></div>');
	$("#criteres_geo .critere:last .departement").hide ();
	$("#criteres_geo .critere:last .departement").val (0);
	$("#criteres_geo .critere:last .ville").hide ();
	$("#criteres_geo .critere:last .ville").val ('');
	rgndom = $("#criteres_geo .critere:last .region");
	$.ajax ( {
	    type: 'GET',
	    url: '/ajax/liste_regions.php',
	    dataType: 'xml',
	    success: function (reponse) {
		$("#criteres_geo .critere:last .region").hide ();
		$(reponse).find('region').each (function () {
		    rgndom.append ('<option value="'+$(this).attr('id')+'">'+$(this).text()+'</option>');
		});
		$("#criteres_geo .critere:last .region").show ();
	    }
	});

	$("#criteres_geo .critere:last .region").change (region_change);
	
	$("#criteres_geo .critere:last .departement").change (departement_change);

	$("#criteres_geo .critere:last .supprime_critere_geo").click (supprime_critere_geo);
    });

    $(".region").change (region_change);

    $(".departement").change (departement_change);

    $("#cat_tree").hide ();
    $("#toutes_categories").click (function () {
	if ($("#toutes_categories:checked").length) {
	    $("#cat_tree").hide ();
	} else {
	    $("#cat_tree").show ();	    
	}
    });
    $("#cat_tree").treeview ({
	url: '/ajax/cat_tree.php'
    });

    $("#sta_tree").hide ();
    $("#tous_statuts").click (function () {
	if ($("#tous_statuts:checked").length) {
	    $("#sta_tree").hide ();
	} else {
	    $("#sta_tree").show ();	    
	}
    });
    $("#sta_tree").treeview ({
	url: '/ajax/sta_tree.php'
    });

    $("#tar_tree").hide ();
    $("#toutes_tarifications").click (function () {
	if ($("#toutes_tarifications:checked").length) {
	    $("#tar_tree").hide ();
	} else {
	    $("#tar_tree").show ();	    
	}
    });
    $("#tar_tree").treeview ({
	url: '/ajax/tar_tree.php'
    });

    $("#psp_tree").hide ();
    $("#toutes_psph").click (function () {
	if ($("#toutes_psph:checked").length) {
	    $("#psp_tree").hide ();
	} else {
	    $("#psp_tree").show ();	    
	}
    });
    $("#psp_tree").treeview ({
	url: '/ajax/psp_tree.php'
    });

    $("#dil_tree").hide ();
    $("#toutes_disciplines").click (function () {
	if ($("#toutes_disciplines:checked").length) {
	    $("#dil_tree").hide ();
	} else {
	    $("#dil_tree").show ();	    
	}
    });
    $("#dil_tree").treeview ({
	url: '/ajax/dil_tree.php'
    });

    $("#mod_tree").hide ();
    $("#tous_modes").click (function () {
	if ($("#tous_modes:checked").length) {
	    $("#mod_tree").hide ();
	} else {
	    $("#mod_tree").show ();	    
	}
    });
    $("#mod_tree").treeview ({
	url: '/ajax/mod_tree.php'
    });

    $("#cli_tree").hide ();
    $("#tous_clients").click (function () {
	if ($("#tous_clients:checked").length) {
	    $("#cli_tree").hide ();
	} else {
	    $("#cli_tree").show ();	    
	}
    });
    $("#cli_tree").treeview ({
	url: '/ajax/cli_tree.php'
    });
    
    $("#table_resultat").tablesorter ();

    $("#rechercher").click (function () {
	    $("#lien_export").empty ();
	    //	    $("#tab2").show ();
	    //	    $("#tab3").show ();
	    //	    change_onglet ('rech3');

	$("#nombre_resultats").html ('');
	$("#nombre_resultats_carte").html ('');
	$("#table_resultat tbody").html ('<tr><td colspan="10" align="center"><strong>Recherche en cours ...</strong></td></tr>');

	xml = cree_xml_recherche ();

	$.ajax ( {
	    type: 'POST',
	    url: '/ajax/rechercher.php',
	    data: xml,
	    success: function (reponse) {		
		    if ($("#sur_domaine:checked").length) {
			$("#divexport").show ();
		    } else {
			$("#divexport").hide ();
		    }
		$("#table_resultat tbody").empty ();
		n = $(reponse).find ('etab').length;
		if (n == 100) {
		    $("#nombre_resultats").html ('Limité à '+n+' établissements');
		    $("#nombre_resultats_carte").html ('Limité à '+n+' établissements');
		    
		} else {
		    $("#nombre_resultats").html (n+' établissements');
		    $("#nombre_resultats_carte").html (n+' établissements');
		}
		i = 0;
		
		if (n > 0) {
		    $("#export_tableur").show ();
		}

		if ($("#map").length) {
		    redisplayed = false;
		    themap = new google.maps.Map(document.getElementById('map'),
						 { 
						     center: new google.maps.LatLng (0, 0), 
						     zoom: 8, 
						     mapTypeId: google.maps.MapTypeId.ROADMAP});
		    bounds = new google.maps.LatLngBounds ();
		    infowindow = Array ();
		}
		var compteur = 1;
		
		$(reponse).find ('etab').each (function () {
			if (i == 0) {
			    bgcol = '#eaeedb';
			} else {
			    bgcol = '#ffffff';
			}
			i = !i;
			finess = '';
			if ($(this).find ('finess').text().substring (0, 2) != 'NF') {
			    finess = $(this).find ('finess').text();
			}
			$("#table_resultat tbody").append ('<tr><td>'+finess+'</td><td><a target="_blank" href="http://profil.action-sociale.org/?p='+$(this).find('url').text()+'">'+$(this).find ('nom').text()+'</a></td><td>'+$(this).find ('cp').text()+'</td><td>'+$(this).find ('ville').text()+'</td><td>'+$(this).find ('cat').text()+'</td><td>'+$(this).find('distance').text()+'</td></tr>');
			
			if ($("#map").length) {
			    nom = $(this).find('nom').text();
			    descr = $(this).find('cat').text()+"<br/>"+$(this).find('cp').text()+" "+$(this).find('ville').text()+'<br/><img style="vertical-align: middle" src="/images/information.png"></img>';
                            descr += '<a target="_blank" href="http://profil.action-sociale.org/?p='+$(this).find('url').text()+'">Voir le profil</a>';
			    if ($("#code_geoloc").val() == '200') {
				descr += '<br/><img style="vertical-align: middle" src="/images/car.png"></img> <a href="#">Comment s\'y rendre</a>';
			    }
			    var txt = '<strong>'+nom+'</strong><br/><small>'+descr+'</small>';
			    lat = $(this).find('lat').text();
			    lng = $(this).find('lng').text();
			    if (lat != 0 || lng != 0) {
				addMarker (lat, lng, txt, compteur++, false);
			    }
			}
		    });

		if ($("#code_geoloc").val() == '200') {
		    addMarker ($("#lat_geoloc").val(), $("#lng_geoloc").val(), $("#adresse_geoloc").val(), compteur++, true);
		}		

		if ($("#map").length) {
		    themap.fitBounds (bounds);
		}
		$("#table_resultat").trigger("update"); 
		//		window.location = String(window.location).replace(/\#.*$/, "") + '#debut_resultats';
		
		change_onglet ('rech2');
		}
	    });
	});
    
    $("#export_tableur").click (function () {
	    xml = cree_xml_recherche ();
	    $.ajax ( {
		    type: 'POST',
			url: '/ajax/export_tableur.php',
			data: xml,
			success: function (reponse) {		
			$("#lien_export").html ('<a href="'+reponse+'">lien vers fichier</a>');
			window.location = reponse;
		    }
		});
	});
    //    $("#geolocdiv").hide ();
    $("#recherche_geoloc").click (function () {
	    $.ajax ( { 
		    type: 'GET',
			url: '/ajax/geo.php',
		data: { q: $("#adresse_geoloc").val()+' FRANCE' },
			dataType: 'xml',
			success: function (response) {
			  $("#code_geoloc").val ($(response).find('code').text());
			  if ($(response).find('code').text() == 200) {
			      $("#lat_geoloc").val ($(response).find('lat').text());
			      $("#lng_geoloc").val ($(response).find('lng').text());
			      $("#accur_geoloc").val ($(response).find('accur').text());
			      $("#trouve_geoloc").html ("Trouvé avec la précision : "+$(response).find('libaccur').text());
			  } else {
			      $("#lat_geoloc").val (0);
			      $("#lng_geoloc").val (0);
			      $("#accur_geoloc").val (0);
			      $("#trouve_geoloc").html ("Non trouvé");
			  }			  
		    }
		});
	    /*
	    $.ajax ( {
		    type: 'GET',
			url: '/ajax/geo.php?q='+$("#adresse_geoloc").val(), 
			dataType: 'xml',
			success: function (reponse) {
			alert (reponse);
		    }
		    });*/
	});
    /*
    $("#geoloc").click (function() {
	    if ($("#geoloc:checked").length) {
		$("#geolocdiv").show();
	    } else {
		$("#geolocdiv").hide();
	    }
	    });*/
    });


function on_onglet_click () {
    var id = $(this).children ('<span>').attr('id');
    change_onglet (id);
}

function change_onglet (id) {
    $("#en-tete ul").empty ();
    if (id == 'rech1')
	$("#en-tete ul").append ('<li id="actif"><span id="rech1">Recherche</span></li>');
    else
	$("#en-tete ul").append ('<li><a href="#"><span id="rech1">Recherche</span></a></li>');

    if (id == 'rech2')
	$("#en-tete ul").append ('<li id="actif"><span id="rech2">Liste</span></li>');
    else
	$("#en-tete ul").append ('<li><a href="#"><span id="rech2">Liste</span></a></li>');

    if (id == 'rech3')
	$("#en-tete ul").append ('<li id="actif"><span id="rech3">Carte</span></li>');
    else
	$("#en-tete ul").append ('<li><a href="#"><span id="rech3">Carte</span></a></li>');

    if (id == 'rech1') {
	$("#tab1").show ();
	$("#tab2").hide ();
	$("#tab3").hide ();
    } else if (id == 'rech2') {
	$("#tab1").hide ();
	$("#tab2").hide ();
	$("#tab3").show ();
    } else {
	$("#tab1").hide ();
	$("#tab2").show ();
	$("#tab3").hide ();
	if (themap && !redisplayed) {
	    google.maps.event.trigger(themap, 'resize');
	    themap.setZoom( themap.getZoom() );
	    themap.fitBounds (bounds);
	    redisplayed = true;
	}
    }

    $("#en-tete a").click (on_onglet_click);
}

function onMapReady () {
    alert ('map ready');
}

