$(function() {

	$.widget( "div#menu_navigation div#ma_recherche ul#criteresprincipaux input_destination.autocomplete", $.ui.autocomplete, {
		_renderMenu: function( ul, items ) {
					var that = this,
					currentCategory = "";
					$.each( items, function( index, item ) {
						if(item.arbo!="")
						item.label = "<b>"+item.affichage+"</b><font style='color:#c0c0c0'>, "+item.arbo+"</font>" ;
						
						/*if ( item.category != currentCategory ) {
						ul.append( "<li class='ui-autocomplete-category'>" + item.categoryname + "</li>" );
						currentCategory = item.category;
						}*/
						that._renderItemData( ul, item );
					});
				}
	});

	
	$('div#menu_navigation div#ma_recherche p.affcriteres').click(function(){
		
		if($('#menurecherche_ensemblecriteres').is(':visible'))
		{
			$('div#menu_navigation div#ma_recherche p.affcriteres').html(criteresplus) ;
			$('div#menu_navigation div#ma_recherche p.affcriteres').addClass("affcriteresplus").removeClass("affcriteresmoins") ;
			$('#menurecherche_ensemblecriteres').hide() ;
		}
		else
		{
			$('div#menu_navigation div#ma_recherche p.affcriteres').html(criteresmoins) ;
			$('div#menu_navigation div#ma_recherche p.affcriteres').removeClass("affcriteresplus").addClass("affcriteresmoins") ;
			$('#menurecherche_ensemblecriteres').show() ;
		}
		
    });

	$( "div#menu_navigation div#ma_recherche ul#criteresprincipaux .input_destination" ).autocomplete({
		source: ajax_destinations,
		messages: {
			noResults: '',
			results: function() {}
		},
		minLength:2,
		select: function( event, ui ) {
			$(this).val(ui.item.arbo) ;
			send_modif("dest",ui.item.type + ":" + ui.item.id,$("#"+$(this).attr("id")+"_mask").val()) ;
		}
	}).data( "autocomplete" )._renderItem = function( ul, item ) {
			return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>"+ item.label + "</a>" )
                .appendTo( ul );
        };

	
	$('.ui-autocomplete').wrap('<div class="recherchedestination"></div>');

	
	$('.ui-autocomplete').wrap('<div class="recherchedestination"></div>');
	
	
	$("div#menu_navigation div#ma_recherche ul#criteresprincipaux li").hover(
		function () {
			$(this).find("a.action").show();
			$(this).find("div.affchamp").addClass("affchamp_emphase") ;
		},
		function () {
			$(this).find("a.action").hide();
			$(this).find("div.affchamp").removeClass("affchamp_emphase") ;
		}
	).bind("click", function(e) { e.stopPropagation(); }) ;
	
	$(document).bind("click", function(e) {
		$("div#menu_navigation div#ma_recherche ul#criteresprincipaux div.affchamp").show() ;
		$("div#menu_navigation div#ma_recherche ul#criteresprincipaux div.modifchamp").hide() ;
	});	
	
	$("div#menu_navigation div#ma_recherche ul#criteresprincipaux > li:not(.bonus)").bind("click", function(e) {
		
		$("div#menu_navigation div#ma_recherche ul#criteresprincipaux li div.modifchamp").hide() ;
		$("div#menu_navigation div#ma_recherche ul#criteresprincipaux li div.affchamp").show() ;
		$(this).children(".affchamp").hide() ;
		$(this).children(".modifchamp").show() ;
		$(this).find(".modifchamp input").eq(0).focus() ;
	});
	
	$("div#menu_navigation div#ma_recherche ul#criteresprincipaux li div.modifchamp").bind("click", function(e) {
		e.stopPropagation();
	});
	
	$("div#menu_navigation div#ma_recherche ul#criteresprincipaux li a.delete").bind("click", function(e) {
		e.stopPropagation();
	});
	
	$("div#menu_navigation div#ma_recherche .checkbox_recherche").bind("click", function(e) {
		//console.log(e.target.id,Boolean($("#"+e.target.id).is(':checked')));
		send_modif(e.target.id,Boolean($("#"+e.target.id).is(':checked')));
    });
	
	$("div#menu_navigation div#ma_recherche .checkbox_recherche_type").bind("click", function(e) {
		$("div#menu_navigation div#ma_recherche #toustypes").prop("checked",( $("div#menu_navigation div#ma_recherche .checkbox_recherche_type:checked").length == $("div#menu_navigation div#ma_recherche .checkbox_recherche_type").length ));
    });
	
	$("div#menu_navigation div#ma_recherche #toustypes").bind("click", function(e) {
		$("div#menu_navigation div#ma_recherche .checkbox_recherche_type").prop("checked",$("div#menu_navigation div#ma_recherche #toustypes").prop("checked"));
    });
	
	$("div#menu_navigation div#ma_recherche #recherche_type_modif").bind("click", function(e) {
		
		if ($("div#menu_navigation div#ma_recherche #toustypes").prop("checked"))
		{
			send_modif("toustypes","") ;
		}
		else
		{
			tabtype = new Array() ;
			vals = $("div#menu_navigation div#ma_recherche .checkbox_recherche_type:checked") ;
			for(i=0;i<vals.length;i++)
			{
				tabtype.push(vals.eq(i).attr("id")) ; 
			}
			send_modif("typegen",tabtype.join(",")) ;
			
		}
    });
	
	$( "div#menu_navigation div#ma_recherche .inputdates" ).datepicker();
	$( "div#menu_navigation div#ma_recherche .inputdates" ).datepicker("option",options_datepicker);
	$( "div#menu_navigation div#ma_recherche .inputdates" ).datepicker( "option", "minDate", 0);
	
	
	var options_datepicker_first = {
		onSelect: function(date) {
			if ($( "div#menu_navigation div#ma_recherche #recherche_date2" ).val()=="")
			{
				actualDate = $.datepicker.parseDate(formatcalendrier, date);
				var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+7);
				$( "div#menu_navigation div#ma_recherche #recherche_date2" ).datepicker( "setDate", $.datepicker.formatDate(formatcalendrier, newDate) );
			}
        }
	};
		
	$( "div#menu_navigation div#ma_recherche #recherche_date1" ).datepicker("option",options_datepicker_first);
	
	
	$('#ui-datepicker-div').wrap('<div class="datepickerperso"></div>');
	
	$("#ui-datepicker-div").bind("click", function(e) {
		e.stopPropagation() ;
	}) ;	
	
	$("div#menu_navigation div#ma_recherche #recherche_date_modif").bind("click", function(e) {
		
		if($("div#menu_navigation div#ma_recherche #recherche_date1").val()=="" && $("div#menu_navigation div#ma_recherche #recherche_date2").val()=="")
		{
			alert(zp_datedebutnonvalide) ;
			$("div#menu_navigation div#ma_recherche #recherche_date1").focus() ;
			return false;
		}
		
		if($("div#menu_navigation div#ma_recherche #recherche_date1").val()=="" && $("div#menu_navigation div#ma_recherche #recherche_date2").val()!="")
		{
			alert(zp_datedebutnonvalide) ;
			$("div#menu_navigation div#ma_recherche #recherche_date1").focus() ;
			return false;
		}
		
		if (($("div#menu_navigation div#ma_recherche #recherche_date1").val()!="" && $("div#menu_navigation div#ma_recherche #recherche_date2").val()==""))
		{
			alert(zp_datefinnonvalide) ;
			$("div#menu_navigation div#ma_recherche #recherche_date2").focus() ;
			return false;
		}

		if ($("div#menu_navigation div#ma_recherche #recherche_date1").val()!="" && $("div#menu_navigation div#ma_recherche #recherche_date2").val()!="")
		{
			date1 = $("div#menu_navigation div#ma_recherche #recherche_date1").val() ;
			date1 = $.datepicker.parseDate(formatcalendrier, date1);

			date2 = $("div#menu_navigation div#ma_recherche #recherche_date2").val() ;
			date2 = $.datepicker.parseDate(formatcalendrier, date2);
			
			if (date1>=date2)
			{
				alert(messageerrdate) ;
				$("div#menu_navigation div#ma_recherche #recherche_date1").focus() ;
				return false;
			}
			else
			{
				send_modif("dates",date_formatSQL(date1)+":"+date_formatSQL(date2)) ;
			}
		}
		
		
    });
	
	
});

function date_formatSQL(date)
{
	annee_s = date.getFullYear() ;
	
	mois = date.getMonth();
	mois = mois+1 ;
	if (mois<10)
        mois_s = "0"+mois;
	else
        mois_s = mois;
	
	jour = date.getDate() ;
	if (jour<10)
        jour_s = "0"+jour;
	else
        jour_s = jour;
	
	return annee_s+"-"+mois_s+"-"+jour_s ;
}

// Recherche l'url à atteindre
// champ : référence du champ à changer
// value : nouvelle valeur de ce champ
// oldvalue : ancienne valeur de ce champ (uniquement si on veut la retirer)
function send_modif(champ,value,oldvalue)
{
	oldvalue = typeof oldvalue !== 'undefined' ? oldvalue : '';
	$.ajax({
        type: "POST",  
        url: ajax_urllisting,
        data: {
			origine : "modifparam",
			urllisting: unrewriteurl,
			champmodif : champ,
			modif : value,
			oldvalue : oldvalue
        }
    }).done(function(msg) {
        //console.log('Réponse JSON : '+msg);

		window.location = msg;

    }).fail(function(jqXHR, textStatus) {
        console.log('erreur ajax demande');
    });
}
