var availableCountries = ['FR', 'GF'];
var tab_countries = new Array();        
tab_countries['FR']='France';
tab_countries['RE']='Réunion';
var selectList = 'listCountries';  // le nom de l'objet HTML SELECT qui contient les zones
var radioList = 'range';  // le nom de l'objet HTML RADIO qui liste les distances de 'viewport' possibles

$( function() {
/*** MOTEUR DE RECHERCHE AGENCE ***/ 
	function submitSearch( event )
	{
		if ( $( 'input#local-region' ).val() == $( 'input#local-region' ).attr( 'title' ) )
		{
			$( 'input#local-region' ).val( '' );
		}
		else if ( ( (typeof( $( 'input#local-region' ).val() ) === 'number' || typeof( $( 'input#local-region' ).val() ) === 'string') && $( 'input#local-region' ).val() !== '' && !isNaN( $( 'input#local-region' ).val() ) ) && $( 'input#local-region' ).val().length < 5 )
		{
			alert( "Il ne s'agit pas d'un code postal valide." );
			event.preventDefault();
			return false;
		}
		if ( $( '#formationCategory' ).get(0).selectedIndex == 2  && $( '#formationDa' ).val() == '' )
		{
			alert( 'Veuillez sélectionner une formation.');
			$( '#formationList' ).focus();
			event.preventDefault();
			return false;
		}
		else if ( $( '#formationCategory' ).get(0).selectedIndex > 0  && $( '#formationList' ).val() == '' )
		{
			alert( 'Veuillez sélectionner une formation.');
			$( '#formationList' ).focus();
			event.preventDefault();
			return false;
		} 
		return true;
	}
	
	function changeFormationCategory() {
//			$('#local-region').val('');
		var formationCategory = $("#formationCategory option:selected").val();
		var searchClass = ( formationCategory == 2096 ) ? "include::domain" : "include::formation::"
		var target = ( formationCategory == 2096 ) ? $('#formationDa') : $('#formationList');
		var url = "ezjscore/call/ecfnode::subtree::"+formationCategory+"::50::0::"+searchClass+"?ContentType=json";
		$('#formationDa, #formationList').hide();
		$('#formationDa option[value!=""], #formationList option[value!=""]').remove();
		
		var test_array= new Array();
		if ( formationCategory !== '-1' )
		{
			$.getJSON( url, function(data) {
				var items = []
				//alert( data.content.list[0].node_id );
				$.each( data.content.list, function(key,val) {
					// je dois retourner l'object ID pour les formations
					if( formationCategory == 2096 )
					{			
							if (val.depth==5)  
							{
									//	items.push( '<option value="'+val.node_id+'">'+nom_precedent+" -- "+val.name+'</option>');
							}else
							{
									items.push( '<option value="'+val.node_id+'">'+val.name+'</option>');
									nom_precedent=	val.name
							}	
											
					} else {
						if($.inArray(parseInt(val.contentobject_id),test_array)==-1)
						{
							//console.log(parseInt(val.contentobject_id),test_array);
							items.push( '<option value="'+val.contentobject_id+'">'+val.name+'</option>');
							test_array.push(parseInt(val.contentobject_id))
						}
						
					}
				})
				target.append( items.join() );
				target.show();
				if( formationCategory == 2096 )
				{
					changeFormationDa()
				}
			});
		}
	}
	
	function changeFormationDa()
	{
		var test_array= new Array();
		if ( $("#formationDa option:selected").length > 0 && $("#formationCategory option:selected").val() !== '-1' )
		{
			var formationDomaine = $("#formationDa option:selected").val();
			
			var searchClass = "include::formation"
			var url = "ezjscore/call/ecfnode::subtree::"+formationDomaine+"::50::0::"+searchClass+"?ContentType=json";
			$('#formationList option[value!=""]').remove();
			$('#formationList' ).hide();
			if ( $( '#formationDa' ).val() != '' )
			{
				$.getJSON( url, function(data) {
					var items = []
					//alert( data.content.list[0].node_id );
					$.each( data.content.list, function(key,val) {
						if($.inArray(parseInt(val.contentobject_id),test_array)==-1)
						{
							items.push( '<option value="'+val.contentobject_id+'">'+val.name+'</option>');
							test_array.push(parseInt(val.contentobject_id))
						}
					})
					
					$('#formationList').append( items.join() );
					$('#formationList').show();
				});
			}
		}
	}
	
	function changeTrainingDa()
	{
		if ( $("#trainingDa option:selected").length > 0 && $("#formationCategory option:selected").val() !== '-1' )
		{
			var formationDomaine = $("#trainingDa option:selected").val();
			
			var searchClass = "include::domain"
			var url = "/index.php/ezjscore/call/ecfnode::subtree::"+formationDomaine+"::50::0::"+searchClass+"::2?ContentType=json";
			$('#trainingSDa option[value!=""]').remove();
			$.getJSON( url, function(data) {
				var items = []
				//alert( data.content.list[0].node_id );
				$.each( data.content.list, function(key,val) {
					items.push( '<option value="'+val.contentobject_id+'">'+val.name+'</option>');
				})
				$('#trainingSDa').append( items.join() );
				if( data.content.list.length > 0 )
				{
					$('#trainingSDa').show();
				}
			})
		}
	}
	
	$('#formationCategory').change( changeFormationCategory );
	
	$('#formationDa').change( changeFormationDa );

	$('#trainingDa').change( changeTrainingDa );
	
	$( '#formSearchAgence' ).submit( submitSearch );
	if ( $('#formationCategory').get( 0 ).selectedIndex == 0)
	{
		if ( document.referrer.indexOf( 'Formation-permis' ) != -1 )
		{
			$('#formationCategory').get( 0 ).selectedIndex = 1;
			$('#formationCategory').change();
			/*$('#formationCategory').after( '<span class="min">Veuillez sélectionner votre formation</span>' ); */
				$('#formSearchAgence').after( '<div class="error-message"><img src="/extension/isecf/design/ecf/images/ico-error.png" alt="" /> Veuillez sélectionner votre formation</div>' ); 
		}
		else if ( document.referrer.indexOf( 'Formation-pro' ) != -1 )
		{
			$('#formationCategory').get( 0 ).selectedIndex = 2;
			$('#formationCategory').change();
			/*$('#formationCategory').after( '<span class="min">Veuillez sélectionner votre formation</span>' );*/
				$('#formSearchAgence').after( '<div class="error-message"> <img src="/extension/isecf/design/ecf/images/ico-error.png" alt="" />Veuillez sélectionner votre formation</div>' ); 
		}
	}
	
	$( '#cities a').bind( 'click', function( event ) {
		event.preventDefault();
		$( '#local-region').val( $( event.currentTarget ).html() );
		$( '#formSearchAgence' ).submit();
	});
	
//	var autocomplete = new google.maps.places.Autocomplete( $( '#local-region' ).get( 0 ) , {region:'FR', types:['geocode']} );
	
	$( '#listCountries' ).bind( 'change', function( event ) {
		$( '#local-region' ).val( $( '#local-region' ).attr( 'title' ) );
	});
	$( '#local-region' ).autocomplete( {
		source: function( request, response ) {
	        $.ajax( {
	        	url: "ezjscore/call/ecfnode::autoCompleteCities::"+$( '#local-region' ).val()+"?ContentType=json",
	        	success: function( data ) {
	        		var result = $.map( data.content, function( item ) {
	        			return { label : item.name,
	        			value: item.name,
	        			favorite_range: item.favorite_range }
	        		} );
	        		response( result );
	        	}
	        });
	    },
	    select: function( event, ui ) {
	    	if ( ui.item.favorite_range != 0 )
    		{
	    		var elementToCheck = false;
	    		$( 'input[name="range"]' ).each( function( index, item ) {
	    			elementToCheck = item;
	    			if ( parseInt( $( elementToCheck ).val() ) >= parseInt( ui.item.favorite_range ) )
    				{
	    				return false;
    				}
	    		});
	    		elementToCheck.checked = true;
    		}
	    },
		minLength: 1
	});
});
