function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
	vars[key] = value;
    });
    return vars;
}

$(document).ready(function(){
    mprot = '040;';
    mprot2= 'lt';
    $('span.a').replaceWith('&#x0'+mprot);
    $('a.joindre').attr("href",function(){
	return "mai"+mprot2+"o:"+$(this).text();
    });
    $('.toggle_fichemail').click(function(){ $('div#fichemail').toggle(); });
    var Couleurs = {
	'colloque':'jaunec',
	'workshop':'bleuc',
	'publications':'vertf',
	'partenaires':'jaunef',
	'prive':'bleui',
	'biblio':'rouge',
	'annuaire':'bleuf',
	'agenda':'noir',
	'richie':'vertc'
    };
    var data = $.parseJSON($.ajax({
	type: "POST",
	url: "/getlang.php",
	data: "page=menu&pref=desc",
	dataType: "json",
	async: false,
	success: function(){ return true }
    }).responseText);
    var Descriptions = new Array();
    for (i=0;i<data.length;i++) {
	Descriptions[data[i].nom] = data[i].texte;
    }
    function centre(event) { document.location.href=$('#'+event.data.couleur+' p a').attr('href'); };
    function entree(event) {
	$('#'+event.data.couleur+' p a').toggleClass("selected");
	$('#centre').click({couleur: event.data.couleur},centre);
    }
    function sortie(event) { $('#'+event.data.couleur+' p a').toggleClass("selected"); }
    function over(event) { $('#centre p').text(event.data.contenu); }

    for(i in Couleurs) {
	$('[id^="'+Couleurs[i]+'"]').mouseenter({couleur: Couleurs[i]},entree).mouseleave({couleur: Couleurs[i]},sortie).attr('href',$('#'+Couleurs[i]+' p a').attr('href'));
	$('[id^="'+Couleurs[i]+'"]').mouseover({contenu: Descriptions[i]},over);
    }
	
//    $('#newsletter').attr('action', '#');

    $("#newsletter input[type='submit'],#newsletter_colloque input[type='submit'],#newsletter_workshop input[type='submit']").click(function(){
	var post = $(this).attr("name") + "=vide&ajax=oui";
	var form_data = $(this).closest('form').serialize() + "&" + post;
	$.ajax({
	    type: "POST",
	    url: $(this).closest('form').attr('action'),
	    data: form_data,
	    dataType: "json",
	    success: function(data) {
		alert(data.description);
	    }
	});
	return false;
    });

    $("#newsletter").submit(function() { $("#newsletter input[name='inscrire']").click(); });
    $("#newsletter_workshop").submit(function() { $("#newsletter_workshop input[name='inscrire']").click(); });
    $("#newsletter_colloque").submit(function() { $("#newsletter_colloque input[name='inscrire']").click(); });


    $("#annuaire input[name='ajout_domaine']").click(function(){
	$("#domaines").append('<li style="list-style:none"><input type="text" name="domaines[]" class="large" value="" /></li>');
	return false;
    });
    $("#annuaire input[name='ajout_cv']").click(function(){
	$("#cv").append('<li style="list-style:none"><input type="text" name="cv[]" class="large" value="" /></li>');
	return false;
    });
		
    $("#biblio input[name='type']").change(function() {
	var form_data = "type="+$("#biblio input[name='type']:checked").val();
        var get = getUrlVars();
	if(get['add']) {
	    form_data = form_data+"&add=1";
	}
	$.ajax({
	    type: "POST",
	    url: "/inc/bibliographie_champs.php",
	    data: form_data,
	    dataType: "html",
	    success: function(data) {
		$("#biblio div#champs").html(data);
		$('textarea[class!="nomark"]').markItUp(mySettings);
	    }
	});
    });
    $("#biblio input[name='ajout']").live('click',function(){
	clone = $(this).parent().next('div.group').clone();
	clone.children('p').children('label').children('input').attr('value','');
	$(this).parent().append(clone);
	return false;
    });
    $("#biblio span[class='local']").live('click',function(){
	$(this).next('ul').toggle();
	return false;
    });

    $("#annonce select[name='categorie']").change(function() {
	categorie = $("#annonce select[name='categorie'] option:selected").val();
	if(categorie == 'seminaire') {
	    $("#annonce input[name='date']").attr('name','dates[]').parent().after('<input type="button" class="seminaire" value="+" name="ajout_date" />');
	}
	else {
	    $('#annonce .seminaire').remove();
	    $("#annonce input[name='dates[]']").attr('name','date');
	}
    });

    $("#annonce input[name='ajout_date']").live('click',function() {
	obj_date = $(this).parent().clone();
	obj_date.addClass('seminaire');
	$($(obj_date.children('label')[0]).children('input')[1]).remove();
	$($(obj_date.children('label')[0]).children('input')[0]).css('display','inline').attr('value','').attr('name','dates[]');
	$(this).parent().after(obj_date);
	will($($($(this).parent().next('p').children('label')).children('input')[0]));
	$(this).remove();
    });

    $('textarea').map(function() {
	if(!$(this).hasClass('nomark')) {
	    $(this).markItUp(mySettings);
	}
    });
	
    var dow = $.parseJSON($.ajax({
	type: "POST",
	url: "/getlang.php",
	data: "page=dow",
	dataType: "json",
	async: false,
	success: function(){ return true }
    }).responseText);
    var moy = $.parseJSON($.ajax({
	type: "POST",
	url: "/getlang.php",
	data: "page=moy",
	dataType: "json",
	async: false,
	success: function(){ return true }
    }).responseText);
    var date_min = new Date();
    var date_change = function(e) {
	if(this.id == 'date') {
	    date_min = e;
	}
	if(this.id == 'dates[]' && date_min < e) {
	    date_min = e;
	}
	if(this.id == 'fin' || this.id == 'dates[]') {
	    this.minDate = date_min.getTime();
	}
    }
    var will = function(obj) {
	obj.will_pickdate({
	    pickerClass: 'wpd',
	    days: dow,
	    id: obj.attr('name'),
	    months: moy,
	    dayShort: 2,
	    monthShort: 3,
	    startDay: 1,
	    timePicker: true,
	    timePickerOnly: false,
	    yearPicker: false,
	    militaryTime: true,
	    yearsPerPage: 20,
	    format: 'Y-m-d H:i',
	    allowEmpty: true,
	    inputOutputFormat: 'Y-m-d H:i', // default to unix timestamp
	    startView: 'month', // allowed values: {time, month, year, decades}
	    positionOffset: { x: 0, y: 0 },
	    debug: false,
	    toggleElements: null,
	    onSelect: date_change,
	    beforeShow: date_change
	});
    }
    $('input.date').each(function() { will($(this)); });
    

    $('ul#groupes a').parent().append('<ul style="display:none"></ul>');
    $('ul#groupes a').click(function() {
	box = $(this);
	if(box.data('ex') == 1) {
	    box.next('ul').toggle('slow',function(){ $(this).html('') });
	    box.data('ex',0);
	}
	else {
	    if($('ul#groupes').data('lien') == 1) {
		var lien='&lien=1';
	    }
	    else {
		var lien='';
	    }
	    $.ajax({
		type: "POST",
		url: "/inc/motscles.php",
		data: 'id='+box.attr('id')+lien,
		dataType: "html",
		success: function(data) {
		    box.next('ul').html(data);
		    box.next('ul').toggle('slow');
		    box.data('ex',1);
		}
	    });
	}
    });
    $('ul#groupes ul li').live('click',function() {
	motcle = $(this).clone();
	$('ul#choix').append(motcle.children('input').attr('name','motscles[]').parent().css('list-style','url("/croix.gif")'));
    });
    $('ul#choix li').live('click',function() { $(this).remove(); });
    


    $("#show_motscles").attr('href','#').click(function(){
	$(".motscles").data('lien',1);
	$(".motscles").toggle('slow');
    });




    $('#biblio ul[id$="_liste"] li').live('click',function() {
	id = $(this).parent().attr('id').split('_')[0];
	personne = $(this).clone();
	$('#biblio ul#'+id+'_choix').append(personne.children('input').attr('name',id+'_loc[]').parent().css('list-style','url("/croix.gif")'));
    });

    $('#biblio ul[id$="_choix"] li').live('click',function() { $(this).remove(); });


    $("#motscles input[name='motscle']").attr("autocomplete","off");
    $("#motscles input[name='valider']").click(function() {
	var form_data = "action=motcle&mot="+$("#motscles input[name='motscle']").attr("value");
	var ajout = function(data) {
	    $('ul#choix').append($("<li><input type='hidden' name='motscles[]' value=\""+data.id.replace('/"/','&quot;')+"\" />"+data.mot+"</li>").css('list-style','url("/croix.gif")'));
	}
	$.ajax({
	    type: "POST",
	    url: "/suggestion_motcle.php",
	    data: form_data,
	    dataType: "json",
	    success: ajout
	});
	$("#motscles input[name='motscle']").attr("value",'');
	return false;
    });
    $("#motscles input[name='motscle']").keypress(function(e) {
	if(e.keyCode == 13) {
	    var form_data = "action=motcle&mot="+$("#motscles input[name='motscle']").attr("value");
	    var ajout = function(data) {
		$('ul#choix').append($("<li><input type='hidden' name='motscles[]' value=\""+data.id.replace('/"/','&quot;')+"\" />"+data.mot+"</li>").css('list-style','url("/croix.gif")'));
	    }
	    $.ajax({
		type: "POST",
		url: "/suggestion_motcle.php",
		data: form_data,
		dataType: "json",
		success: ajout
	    });
	    $("#motscles input[name='motscle']").attr("value",'');
	    return false;
	}
    });

    $('#requete input[type="checkbox"][name^="pays"]:checked').next('img').addClass('checked');
    $('#requete input[type="checkbox"]').click(function() {
	var nom = $(this).attr('name').split('[');
	var val = ($(this).prop('checked'));
	type=nom[0];
	valeur=nom[1];
	if(type == 'pays' && valeur != 'tous]' && val) {
	    $(this).next('img').addClass('checked');
	}
	if(type == 'pays' && valeur != 'tous]' && !val) {
	    $(this).next('img').removeClass('checked');
	}
	if(valeur == 'tous]') {
	    $('#requete input[name^="'+type+'"][type="checkbox"]').prop("checked",val);
	    if(val && type=="pays") {
		$('#requete input[name^="pays"][type="checkbox"]').next('img').addClass('checked');
	    }
	    else if(!val && type=="pays") {
		$('#requete input[name^="pays"][type="checkbox"]').next('img').removeClass('checked');
	    }
	}
	if(valeur == 'avenir]' && val) {
	    $('#requete input[name^="'+type+'[2"][type="checkbox"]').prop("checked",false);
	}
	if($('#requete input[name^="'+type+'"][type="checkbox"]:not(:checked)').length > 0) {
	    $('#requete input[name="'+type+'[tous]"][type="checkbox"]').prop("checked",false);
	}
	if($('#requete input[name^="'+type+'"][type="checkbox"]:not(:checked):not([name="'+type+'[tous]"])').length == 0) {
	    $('#requete input[name="'+type+'[tous]"][type="checkbox"]').prop("checked",true);
	}
    });


    $("#annonce input, #annonce textarea").change(function() {
	if($(this).hasClass('a_remplir') && $(this).attr("value") != "") {
	    $(this).addClass('rempli');
	    $(this).removeClass('a_remplir');
	}
	if($(this).hasClass('rempli') && $(this).attr("value") == "") {
	    $(this).removeClass('rempli');
	    $(this).addClass('a_remplir');
	}
    });

    $("#annuaire .decache").click(function() { $(this).parent().next(".cache").toggle(); });

    $("#requete .ligne_recherche input[name='ajout']").live('click',function(){
	clone = $(this).parent().clone();
	$(clone).children("input[name^='champ']").attr("value","");
	$(this).parent().after(clone);
	$(this).css('visibility','hidden');
	return false;
    });
});

