/*Ajout Fonctions*/
Array.prototype.in_array = function(p_val) {
    for(var i = 0, l = this.length; i < l; i++) {
        if(this[i] == p_val) {
            rowid = i;
            return rowid;
        }
    }
    return -1;
}

var PAGE_FORM_CONFIG = 107;
var PAGE_FORM_PICTURE = 124;
var PAGE_LIST_PICTURES = 125;
var PAGE_FORM_EVENT = 122;
var PAGE_LIST_EVENTS = 123;
var PAGE_FORM_ALBUM = 134;
var PAGE_LIST_ALBUMS = 135;
var PAGE_FORM_SONG = 144;
var PAGE_LIST_SONGS = 145;

var PAGE_FORM_RESERVATION = 157;
var PAGE_LIST_RESERVATION = 156;

var PAGE_DISPLAY_PICTURES = 96;
var PAGE_DISPLAY_EVENTS = 98;
var PAGE_DISPLAY_EVENT = 130;
var PAGE_DISPLAY_CALENDAR = 131;
var PAGE_DISPLAY_HOME = 3;

var FD_GRID_SEARCH = 0;
var FD_GRID_SORT = 1;
var FD_GRID_SIDE = 2;
var FD_GRID_PAGE = 3;
var FD_GRID_LIMIT = 4;

var HOME_LOOP_TIME = 8000;

var DOMAIN = 'http://dagobert.fdcanada.ca/';

var LOADING_PANEL = '<div class="blank_loading" style="width:100%;height:100%;background-color:black;text-align:center;"><img style="margin-top:100px;" src="gestion/images/loading.gif"></div>';

var COOKIE_LANG = 'lang';
var FR = 1;
var EN = 2;
var DEFAULT_LANG = FR;
var FILE_LANG_FR = 'gestion/js/lang/lang.fr.js';
var FILE_LANG_EN = 'gestion/js/lang/lang.en.js';

function getLang(){
	var lang = DEFAULT_LANG;
	if($.cookie(COOKIE_LANG) != ''){
		lang = $.cookie(COOKIE_LANG);
	}
	return lang;
}

function getLangFile(){
	var lang = DEFAULT_LANG;
	if($.cookie(COOKIE_LANG) != ''){
		lang = $.cookie(COOKIE_LANG);
	}
	switch(parseInt(lang)){
		case FR:
			return FILE_LANG_FR;
		case EN:
			return FILE_LANG_EN;
		default:
			return FILE_LANG_FR;
	}
}

function getLangName(){
	var lang = DEFAULT_LANG;
	if($.cookie(COOKIE_LANG) != ''){
		lang = $.cookie(COOKIE_LANG);
	}
	switch(parseInt(lang)){
		case FR:
			return 'FR';
		case EN:
			return 'EN';
		default:
			return 'FR';
	}
}

/*START HOME*/
function createDisplayEventsHome(){
	$.ajax({
		url: "gestion/ajax/home/displayEventsHome.php",
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplayEventsHome").empty();
			$("#contentDisplayEventsHome").html(data);
			
			$.preload('.preload', {
				onFinish:function(){
					$('.homeEventGallery').easySlider({
						controlsBefore: '<div id="controls">',
						controlsAfter: '</div>',
						auto: true, 
						continuous: true,
						prevText: '',
						nextText: '',
						speed: 1000,
						pause: 8000,
						vertical: false
					});
				}
			})
			
			$('.homeEventImage').click(function(){
				var id = $(this).attr('id');
				var uid = id.split('-');
				document.location.href = "index.php?id="+PAGE_DISPLAY_EVENT+"&uid="+uid[1]+"&returnType=1&L="+getLang();
			});
			
			$('.homeCalendarEvent a').click(function(){
				document.location.href = "index.php?id="+PAGE_DISPLAY_EVENTS+"&L="+getLang();
				return false;
			});	
		}
	});
}
/*Nouvelle maquette*/
function createDisplayEventsHome2(){
	$.ajax({
		url: "gestion/ajax/home/displayEventsHome2.php",
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplayUpcomingEventsHome").empty();
			$("#contentDisplayUpcomingEventsHome").html(data);
			
			
			$('.homeUpcomingEventImage').click(function(){
				var id = $(this).attr('id');
				var uid = id.split('-');
				document.location.href = "index.php?id="+PAGE_DISPLAY_EVENT+"&uid="+uid[1]+"&returnType=1&L="+getLang();
			});
			
			// $('.homeCalendarEvent a').click(function(){
				// document.location.href = "index.php?id="+PAGE_DISPLAY_EVENTS+"&L="+getLang();
				// return false;
			// });	
		}
	});
}
function createDisplayEventsHome3(){
	$.ajax({
		url: "gestion/ajax/home/displayEventsHome3.php",
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplayCalendarEventsHome").empty();
			$("#contentDisplayCalendarEventsHome").html(data);
			
			$.preload('.preload', {
				onFinish:function(){
					// $(document).everyTime(7000, function(){
						// changeImage();
					// });
				}
			});
			
			$('.homeCalEventImage').click(function(){
				var id = $(this).attr('id');
				var uid = id.split('-');
				document.location.href = "index.php?id="+PAGE_DISPLAY_EVENT+"&uid="+uid[1]+"&returnType=1&L="+getLang();
			});
			
			$('#cmdUp').click(function (){
				changeImageUp();
			});
			
			$('#cmdDown').click(function (){
				changeImageDown();
			});
			
			// $('.homeCalendarEvent a').click(function(){
				// document.location.href = "index.php?id="+PAGE_DISPLAY_EVENTS+"&L="+getLang();
				// return false;
			// });	
		}
	});
}
/*Fonction Manip pour events*/
var currentImg = 1;

function changeImage(){
	var nb = 0;
	$(".homeCalPanEvent").each(function(){										
		nb++;
	});
	
	var image = 0;
	image = parseInt(currentImg)+1;
	
	if(currentImg != image){
		if(currentImg >= nb){
			image = 1;
		}
		$("#bloc-"+currentImg).fadeOut(1000,function(){
			$("#bloc-"+currentImg).addClass("hidden");
			$("#bloc-"+image).fadeIn("slow");
			$("#bloc-"+image).removeClass("hidden");
		});
		currentImg++;
		if(currentImg > nb){
			currentImg = 1;
		}
	}
}
function changeImageUp(){
	var nb = 0;
	$(".homeCalPanEvent").each(function(){										
		nb++;
	});
	
	var image = 0;
	image = parseInt(currentImg)+1;
	
	if(currentImg != image){
		if(currentImg >= nb){
			image = 1;
		}
		$("#bloc-"+currentImg).fadeOut(1000,function(){
			$("#bloc-"+currentImg).addClass("hidden");
			$("#bloc-"+image).fadeIn("slow");
			$("#bloc-"+image).removeClass("hidden");
		});
		currentImg++;
		if(currentImg > nb){
			currentImg = 1;
		}
	}
}
function changeImageDown(){
	var nb = 0;
	$(".homeCalPanEvent").each(function(){										
		nb++;
	});
	
	var image = 0;
	image = parseInt(currentImg)-1;
	
	if(currentImg != image){
		if(currentImg <= 1){
			image = nb;
		}
		$("#bloc-"+currentImg).fadeOut(1000,function(){
			$("#bloc-"+currentImg).addClass("hidden");
			$("#bloc-"+image).fadeIn("slow");
			$("#bloc-"+image).removeClass("hidden");
		});
		currentImg--;
		if(currentImg < 1){
			currentImg = nb;
		}
	}
}
	/* formVipMap */
function createFormVIPMAP(){
	$.ajax({
		url: "gestion/ajax/home/displayFormVIPMAP.php",
		async: true,
		type: "POST",
		success: function(data){
			$("#contentFormVIPMAP").empty();
			$("#contentFormVIPMAP").html(data);
			setEventFormVIPMAP();
		}
	});
}
function setEventFormVIPMAP(){
	
	var date_now = $('#txt_date').attr('value');
	getDivSectionByDate(date_now);
	
	$('.send').click(function(){
		if(validateFormVIPMAP()){
			var date = $('#txt_date').attr('value');
			var email = $('#courriel').attr('value');
			var phone = $('#txt_telephone').attr('value');
			var name = $('#txt_client_name').attr('value');
			var lastName = $('#txt_client_lastname').attr('value');
			var sections = $('#txt_client_reservation').attr('value');
			
			// var responsable = $('#txt_responsable').attr('value');
			// var salle = $('#opt_salle').attr('value');
			// var nbPersonne = $('#txt_nbPers').attr('value');
			var bultin = ($('#chk_news').is(':checked'))?1:0;
			
			$.ajax({
				url: "gestion/ajax/home/saveFormVIPMAP.php",
				async: false,
				type: "POST",
				data: ({
					date:date,
					email:email,
					phone:phone,
					name:name,
					lastName:lastName,
					sections:sections,
					bultin:bultin
				}),
				success: function(data){
					switch(data){
						case "0":	
							$("#contentFormVIPMAP").empty();
							$("#contentFormVIPMAP").html("Merci ! Nous confirmerons la réservation dans les plus brefs délais.");
							break;
						case "1":
							alert("Champs vides");
							break;
						case "2":
							alert("Mail erreur");
							break;
						case "3":
							alert("Courriel invalid");
							break;
						default:
							alert("Erreur Inconnu");
							break;
					}
				}
			});
		}else{
			
		}
	});
		
	$("#txt_date").datepicker($.extend({}, 
		$.datepicker.regional[DATEPICKER_LANG], {
			dateFormat: "yy-mm-dd", 
			showOn: "both", 
			yearRange: '-0:+1',
			minDate: '0',
			buttonImage: "gestion/images/icons/calendar.gif", 
			buttonImageOnly: true,
			changeMonth: true,
			changeYear: true 
		}
	));
	
	$("#txt_date").change(function(){
		var date_now2 = $('#txt_date').attr('value');
		getDivSectionByDate(date_now2);
	});
	
}
function getDivSectionByDate(date_selected){
	$('#txt_client_reservation').attr('value','');
	$("#id_map_box").empty();
	$("#id_map_box").html(LOADING_PANEL);
	$.ajax({
		url: "gestion/ajax/reservation/loadDivSectionByDayClient.php",
		async: false,
		type: "POST",
		data: ({date:date_selected}),
		success: function(data){
			$('.blank_loading').fadeOut('slow',function(){
				$("#id_map_box").empty();
				$("#id_map_box").html(data);
				
				
				$('.section_box').click(function(){
					if($(this).hasClass("section_reserve")){
						alert("Impossible de réserver une section déjà réservée");
					}else{
						if($(this).hasClass("section_selected")){
							$(this).removeClass("section_selected");
							addOrRemoveSectionSelectionClient($(this));
							/*A COMPLETER*/
						}else{
							$(this).addClass("section_selected");
							addOrRemoveSectionSelectionClient($(this));
							/*A COMPLETER*/
						}
						updateAlcoolMustBuy();
					}
				});
				
				$('.section_box').simpletip({
					fixed: true, 
					position: [40, 17],
					onBeforeShow: function(){
						
						var uid = this.getParent().attr('id');
						var tabUid = uid.split("-");
						var txtToolTip = $('#box\\_info\\_client\\-'+tabUid[1]).html();
						this.update(txtToolTip); 
					} 
				});
				
				// $(".section_box").mouseover(function(){
					
					// var id = $(this).attr('id');
					// var tabId = id.split('-');
					// alert('Allo toi !' + tabId[1]);
				// }); 
			});
		}
	});
	
	// $.ajax({
		// url: "gestion/ajax/reservation/loadSectionByDate.php",
		// async: false,
		// type: "POST",
		// data: ({}),
		// success: function(data){
			// $("#contentFormReservation").empty();
			// $("#contentFormReservation").html(data);
			
			// loadDivSectionByDate(dateNow);
		// }
	// });
}

function updateAlcoolMustBuy(){
	var sections = $('#txt_client_reservation').attr('value');
	
	$.ajax({
		url: "gestion/ajax/reservation/displayConsumation.php",
		async: true,
		type: "POST",
		data: ({
			sections:sections
		}),
		success: function(data){
			if(data != "|"){
				var tabData = data.split("|");
				$('#txt_des_sections_reserves').html(tabData[0]);
				$('#txt_des_achats_minimum').html(tabData[1]);
				
			}else{
				$('#txt_des_sections_reserves').html('Aucune. Veuillez sélectionner les sections désirées <br/>sur la carte.');
				$('#txt_des_achats_minimum').html('Vos achats minimums sont calculés en fonctions <br/>du nombre de places réservées.');
			}
			// alert(data);
			// $("#contentFormVIP").empty();
			// $("#contentFormVIP").html(data);
			// setEventFormVIP();
		}
	});
}

function addOrRemoveSectionSelectionClient(element){
	var uid = element.attr("id");
	var tabUid = uid.split("-");
	var goodUid = tabUid[1];
	
	var txtUid = $('#txt_client_reservation').attr('value');
	
	var existTabUid = txtUid.split("-");
	
	if(existTabUid.in_array(goodUid) == -1){
		existTabUid.push(goodUid);	
	}else{
		var pos = existTabUid.in_array(goodUid);
		existTabUid[pos] = '';
	}
	var newArr = [];
	existTabUid.sort(function(a,b){return a - b});
	for(var o=0;o<existTabUid.length;o++){
		if(existTabUid[o]!=''){
			newArr.push(existTabUid[o]);
		}
	}
	
	var newTxtUid = newArr.join("-");
	
	$('#txt_client_reservation').attr('value',newTxtUid);
}

function validateFormVIPMAP(){
	var valid  = true;
	
	var date = $('#txt_date').attr('value');
	var prenom = $('#txt_client_name').attr('value');
	var nom = $('#txt_client_lastname').attr('value');
	var tel = $('#txt_telephone').attr('value');
	var email = $('#courriel').attr('value');
	var section = $('#txt_client_reservation').attr('value');
	
	$('#messages').html('<FONT COLOR="#CC0000"></FONT>');
	
	if(date ==''){
		valid = false;
		$('#messages').append('<div><FONT COLOR="#CC0000">Veuillez choisir une date</FONT></div>');
	}
	
	if(section == ''){
		valid = false;
		$('#messages').append('<div><FONT COLOR="#CC0000">Veuillez choisir une ou plusieurs section(s)</FONT></div>');
	}
	
	if(prenom == ''){
		valid = false;
		$('#messages').append('<div><FONT COLOR="#CC0000">Veuillez entrer le prénom du responsable</FONT></div>');
	}
	
	if(nom == ''){
		valid = false;
		$('#messages').append('<div><FONT COLOR="#CC0000">Veuillez entrer le nom du responsable</FONT></div>');
	}
	
	if(email==''){
		valid = false;
		
		// $('#courriel').removeClass();
		// $('#courriel').addClass('eno_textbox_error');
		$('#messages').append('<div><FONT COLOR="#CC0000">Veuillez entrer une adresse courriel.</FONT></div>');
	}
	else if(!isEmail(email)){
		valid = false;
		
		// $('#courriel').removeClass();
		// $('#courriel').addClass('eno_textbox_error');
		$('#messages').append('<div><FONT COLOR="#CC0000">Veuillez entrer une adresse courriel valide.</FONT></div>');
	}
	
	if(tel == ''){
		valid = false;
		$('#messages').append('<div><FONT COLOR="#CC0000">Veuillez entrer une numéro de téléphone.</FONT></div>');
		
	}else if(!isPhoneNumber(tel)){
		valid = false;
		$('#messages').append('<div><FONT COLOR="#CC0000">Veuillez entrer une numéro de téléphone valid.</FONT></div>');
		
	}
	
	if(valid){
		$('#messages').html('<FONT COLOR="#CC0000"></FONT>');
	}
	
	return valid;
}

	/* formVIP */
function createFormVIP(){
	$.ajax({
		url: "gestion/ajax/home/displayFormVIP.php",
		async: true,
		type: "POST",
		success: function(data){
			$("#contentFormVIP").empty();
			$("#contentFormVIP").html(data);
			setEventFormVIP();
		}
	});
}

function setEventFormVIP(){
	$('.send').click(function(){
		if(validateFormVIP()){
			var date = $('#txt_date').attr('value');
			var email = $('#courriel').attr('value');
			var phone = $('#txt_telephone').attr('value');
			var responsable = $('#txt_responsable').attr('value');
			var salle = $('#opt_salle').attr('value');
			var nbPersonne = $('#txt_nbPers').attr('value');
			var bultin = ($('#chk_news').is(':checked'))?1:0;
			
			$.ajax({
				url: "gestion/ajax/home/saveFormVIP.php",
				async: false,
				type: "POST",
				data: ({
					date:date,
					email:email,
					phone:phone,
					responsable:responsable,
					salle:salle,
					nbPersonne:nbPersonne,
					bultin:bultin
				}),
				success: function(data){
					switch(data){
						case "0":	
							$("#contentFormVIP").empty();
							$("#contentFormVIP").html("<h1 class='csc-firstHeader'>Réservation de sections VIP</h1>Merci ! Nous confirmerons la réservation dans les plus brefs délais.");
							break;
						case "1":
							alert("Champs vides");
							break;
						case "2":
							alert("Mail erreur");
							break;
						case "3":
							alert("Courriel invalid");
							break;
						default:
							alert("Erreur Inconnu");
							break;
					}
				}
			});
		}else{
			
		}
	});
	
	$("#txt_date").datepicker($.extend({}, 
		$.datepicker.regional[DATEPICKER_LANG], {
			dateFormat: "yy-mm-dd", 
			showOn: "both", 
			yearRange: '-0:+2',
			buttonImage: "gestion/images/icons/calendar.gif", 
			buttonImageOnly: true,
			changeMonth: true,
			changeYear: true 
		}
	));
	
	
}

function validateFormVIP(){
	var valid  = true;
	
	var phone = $('#txt_telephone').attr('value');
	var email = $('#courriel').attr('value');

	if(email==''){
		valid = false;
		
		$('#courriel').removeClass();
		$('#courriel').addClass('eno_textbox_error');
		$('#messages').html('<FONT COLOR="#CC0000">Veuillez entrer une adresse courriel.</FONT>');
	}
	else if(!isEmail(email)){
		valid = false;
		
		$('#courriel').removeClass();
		$('#courriel').addClass('eno_textbox_error');
		$('#messages').html('<FONT COLOR="#CC0000">Veuillez entrer une adresse courriel valide.</FONT>');
	}
	else{
		$('#courriel').removeClass();
		$('#messages').html('<FONT COLOR="#CC0000"></FONT>');
	}
	
	
	return valid;
	
}

	/* formLimo */
function createFormLimo(){
	$.ajax({
		url: "gestion/ajax/home/displayFormLimo.php",
		async: true,
		type: "POST",
		success: function(data){
			$("#contentFormLimo").empty();
			$("#contentFormLimo").html(data);
			setEventFormLimo();
		}
	});
}

function setEventFormLimo(){
	$('.send').click(function(){
		if(validateFormLimo()){
			var date = $('#txt_date').attr('value');
			var email = $('#courriel').attr('value');
			var phone = $('#txt_telephone').attr('value');
			var name = $('#txt_name').attr('value');
			var lastName = $('#txt_lastname').attr('value');
			var nbPersonne = $('#txt_nbPers').attr('value');
			var bultin = ($('#chk_news').is(':checked'))?1:0;
			
			$.ajax({
				url: "gestion/ajax/home/saveFormLimo.php",
				async: false,
				type: "POST",
				data: ({
					date:date,
					email:email,
					phone:phone,
					name:name,
					lastName:lastName,
					nbPersonne:nbPersonne,
					bultin:bultin
				}),
				success: function(data){
					switch(data){
						case "0":	
							$("#contentFormLimo").empty();
							$("#contentFormLimo").html("Merci ! Limo Québec confirmera la réservation dans les plus brefs délais.");
							break;
						case "1":
							alert("Champs vides");
							break;
						case "2":
							alert("Mail erreur");
							break;
						case "3":
							alert("Courriel invalid");
							break;
						default:
							alert("Erreur Inconnu");
							break;
					}
				}
			});
		}else{
			
		}
	});
	
	$("#txt_date").datepicker($.extend({}, 
		$.datepicker.regional[DATEPICKER_LANG], {
			dateFormat: "yy-mm-dd", 
			showOn: "both", 
			yearRange: '-0:+2',
			buttonImage: "gestion/images/icons/calendar.gif", 
			buttonImageOnly: true,
			changeMonth: true,
			changeYear: true 
		}
	));
}

function validateFormLimo(){
	var valid  = true;
	
	var tel = $('#txt_telephone').attr('value');
	var email = $('#courriel').attr('value');

	if(email==''){
		valid = false;
		
		$('#courriel').removeClass();
		$('#courriel').addClass('eno_textbox_error');
		$('#messages').html('<FONT COLOR="#CC0000">Veuillez entrer une adresse courriel.</FONT>');
	}
	else if(!isEmail(email)){
		valid = false;
		
		$('#courriel').removeClass();
		$('#courriel').addClass('eno_textbox_error');
		$('#messages').html('<FONT COLOR="#CC0000">Veuillez entrer une adresse courriel valide.</FONT>');
	}
	else{
		$('#courriel').removeClass();
		$('#messages').html('<FONT COLOR="#CC0000"></FONT>');
		
		if(tel==''){
			valid = false;
			
			$('#txt_telephone').removeClass();
			$('#txt_telephone').addClass('eno_textbox_error');
			$('#messages').html('<FONT COLOR="#CC0000">Veuillez entrer un numéro de téléphone.</FONT>');
		}
		else if(!isPhoneNumber(tel)){
			valid = false;
			
			$('#txt_telephone').removeClass();
			$('#txt_telephone').addClass('eno_textbox_error');
			$('#messages').html('<FONT COLOR="#CC0000">Veuillez entrer un numéro de téléphone valide.</FONT>');
		}else{
			$('#txt_telephone').removeClass();
			$('#messages').html('<FONT COLOR="#CC0000"></FONT>');
		}
	}
	
	return valid;
}

	/* formHotel */
function createFormHotel(){
	$.ajax({
		url: "gestion/ajax/home/displayFormHotel.php",
		async: true,
		type: "POST",
		success: function(data){
			$("#contentFormHotel").empty();
			$("#contentFormHotel").html(data);
			setEventFormHotel();
		}
	});
}

function setEventFormHotel(){
	$('.send').click(function(){
		if(validateFormLimo()){
			var date = $('#txt_date').attr('value');
			var days = $('#opt_nbJour').attr('value');
			var email = $('#courriel').attr('value');
			var phone = $('#txt_telephone').attr('value');
			var name = $('#txt_name').attr('value');
			var lastName = $('#txt_lastname').attr('value');
			var nbPersonne = $('#txt_nbPers').attr('value');
			var bultin = ($('#chk_news').is(':checked'))?1:0;
			
			$.ajax({
				url: "gestion/ajax/home/saveFormHotel.php",
				async: false,
				type: "POST",
				data: ({
					date:date,
					email:email,
					days:days,
					phone:phone,
					name:name,
					lastName:lastName,
					nbPersonne:nbPersonne,
					bultin:bultin
				}),
				success: function(data){
					switch(data){
						case "0":
							$("#contentFormHotel").empty();
							$("#contentFormHotel").html("<h1 class='csc-firstHeader'>Réservation de sections VIP</h1>Merci ! Nous confirmerons la réservation dans les plus brefs délais.");
							break;
						case "1":
							alert("Champs vides");
							break;
						case "2":
							alert("Mail erreur");
							break;
						case "3":
							alert("Courriel invalid");
							break;
						default:
							alert("Erreur Inconnu");
							break;
					}
				}
			});
		}else{
			
		}
	});
	
	$("#txt_date").datepicker($.extend({}, 
		$.datepicker.regional[DATEPICKER_LANG], {
			dateFormat: "yy-mm-dd", 
			showOn: "both", 
			yearRange: '-0:+2',
			buttonImage: "gestion/images/icons/calendar.gif", 
			buttonImageOnly: true,
			changeMonth: true,
			changeYear: true 
		}
	));
	
}

function validateFormHotel(){
	var valid  = true;
	
	var tel = $('#txt_telephone').attr('value');
	var email = $('#courriel').attr('value');

	if(email==''){
		valid = false;
		
		$('#courriel').removeClass();
		$('#courriel').addClass('eno_textbox_error');
		$('#messages').html('<FONT COLOR="#CC0000">Veuillez entrer une adresse courriel.</FONT>');
	}
	else if(!isEmail(email)){
		valid = false;
		
		$('#courriel').removeClass();
		$('#courriel').addClass('eno_textbox_error');
		$('#messages').html('<FONT COLOR="#CC0000">Veuillez entrer une adresse courriel valide.</FONT>');
	}
	else{
		$('#courriel').removeClass();
		$('#messages').html('<FONT COLOR="#CC0000"></FONT>');
	}
	
	return valid;
}

/*Fin maquette*/

/* Video */
function showVideoHome(){
	$.ajax({
		url: "gestion/ajax/home/displayVideo.php",
		async: true,
		type: "POST",
		success: function(data){
			$("#contentVideo").empty();
			$("#contentVideo").html(data);
			setEventShowVideo();
		}
	});
}
function setEventShowVideo(){
	
	$('#dialogShowVideo').dialog({
			resizable: false,
			draggable: false,
			autoOpen: true,
			height:580,
			width:700,
			modal: true,
			close: function(ev, ui) {
				$(this).dialog("destroy");
			},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				"Fermer la vidéo": function(){
					$(this).dialog('destroy');
				},
				"Acheter des billets": function() {
					window.open('http://www.billetech.com/html/artist.htmI?l=FR&artist=FEDDE+LE+GRAND+%28HOLLANDE%29');
					
				}
			}
		});
	
}
/* Fin Video */

function createDisplayPlayerHome(){
	$.ajax({
		url: "gestion/ajax/home/displayPlayerHome.php",
		async: true,
		type: "POST",
		success: function(data){
			$("#contentDisplayPlayerHome").empty();
			$("#contentDisplayPlayerHome").html(data);
			
			$.ajax({
				url: "gestion/ajax/home/loadListSongs.php",
				async: true,
				type: "POST",
				success: function(data){
					if(data != ''){
					
						var playItem = 0;
						var myPlayList = [];
					
						songs = data.split('|');
						for(i=0;i<songs.length;i++){
							infos = songs[i].split('#');
							myPlayList[i] = [];
							myPlayList[i].name = infos[0];
							myPlayList[i].mp3 = infos[1];
						}
						
						if($(".showIntro").length > 0){
							$(".showIntro").colorbox({transition:"fade"});
							$(".showIntro").trigger('click');
							
							$(".showIntro").bind("cbox_closed", function(){
								playListChange(playItem);
							});
						}
						
						$("#jquery_jplayer").jPlayer({
							swfPath: 'gestion/js/jquery/plugins/jquery-jplayer',
							ready: function() {
								displayPlayList();
								if($(".showIntro").length > 0){
									playListInit(false);
								}
								else{
									playListInit(true);
								}
							}
						})
						.jPlayerId("play", "player_play")
						.jPlayerId("pause", "player_pause")
						.jPlayerId("stop", "player_stop")
						.jPlayerId("loadBar", "player_progress_load_bar")
						.jPlayerId("playBar", "player_progress_play_bar")
						.jPlayerId("volumeMin", "player_volume_min")
						.jPlayerId("volumeMax", "player_volume_max")
						.jPlayerId("volumeBar", "player_volume_bar")
						.jPlayerId("volumeBarValue", "player_volume_bar_value")
						.onProgressChange( function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
							var myPlayedTime = new Date(playedTime);
							var ptMin = (myPlayedTime.getUTCMinutes() < 10) ? "0" + myPlayedTime.getUTCMinutes() : myPlayedTime.getUTCMinutes();
							var ptSec = (myPlayedTime.getUTCSeconds() < 10) ? "0" + myPlayedTime.getUTCSeconds() : myPlayedTime.getUTCSeconds();
							$("#play_time").text(ptMin+":"+ptSec);

							var myTotalTime = new Date(totalTime);
							var ttMin = (myTotalTime.getUTCMinutes() < 10) ? "0" + myTotalTime.getUTCMinutes() : myTotalTime.getUTCMinutes();
							var ttSec = (myTotalTime.getUTCSeconds() < 10) ? "0" + myTotalTime.getUTCSeconds() : myTotalTime.getUTCSeconds();
							$("#total_time").text(ttMin+":"+ttSec);
						})
						.onSoundComplete( function() {
							playListNext();
						});

						$("#ctrl_prev").click( function() {
							playListPrev();
							return false;
						});

						$("#ctrl_next").click( function() {
							playListNext();
							return false;
						});

						function displayPlayList() {
							for (i=0; i < myPlayList.length; i++) {
								$("#playlist_list ul").append("<li id='playlist_item_"+i+"'>"+ myPlayList[i].name +"</li>");
								$("#playlist_item_"+i).data( "index", i ).hover(
									function() {
										if (playItem != $(this).data("index")) {
											$(this).addClass("playlist_hover");
										}
									},
									function() {
										$(this).removeClass("playlist_hover");
									}
								).click( function() {
									var index = $(this).data("index");
									if (playItem != index) {
										playListChange( index );
									}
								});
							}
						}

						function playListInit(autoplay) {
							if(autoplay) {
								playListChange( playItem );
							} else {
								playListConfig( playItem );
							}
						}

						function playListConfig( index ) {
							$("#playlist_item_"+playItem).removeClass("playlist_current");
							$("#playlist_item_"+index).addClass("playlist_current");
							playItem = index;
							$("#jquery_jplayer").setFile(myPlayList[playItem].mp3);
							//$("#jquery_jplayer").setFile("gestion/files/songs/01-383qp22253h9y2s.mp3", myPlayList[playItem].ogg);
						}

						function playListChange( index ) {
							playListConfig( index );
							$("#jquery_jplayer").play();
						}

						function playListNext() {
							var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
							playListChange( index );
						}

						function playListPrev() {
							var index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1;
							playListChange( index );
						}
						
					}else{
						alert("vide");
					}
				}
			});
		}
	});
}
function createDisplayPlayerHome2(){
	$.ajax({
		url: "gestion/ajax/home/displayPlayerHome2.php",
		async: true,
		type: "POST",
		success: function(data){
			$("#contentDisplayPlayerHome").empty();
			$("#contentDisplayPlayerHome").html(data);
			
			$.ajax({
				url: "gestion/ajax/home/loadListSongs.php",
				async: true,
				type: "POST",
				success: function(data){
					if(data != ''){
						var myPlayList = [];
						var playItem = 0;
						
						songs = data.split('|');
						for(i=0;i<songs.length;i++){
							infos = songs[i].split('#');
							myPlayList[i] = [];
							myPlayList[i].name = infos[0];
							myPlayList[i].mp3 = infos[1];
						}
						
						$("#jquery_jplayer").jPlayer({
							swfPath: 'gestion/js/jquery/plugins/jq_jplayer_2',
							ready: function() {
								displayPlayList();
								if($(".showIntro").length > 0){
									playListInit(false);
								}
								else{
									playListInit(true);
								}
							}
						});
						
						function displayPlayList() {
							for (i=0; i < myPlayList.length; i++) {
								$("#jplayer_playlist ul").append("<li id=\'jplayer_playlist_item_"+i+"\'>"+ myPlayList[i].name +"</li>");
								$("#jplayer_playlist_item_"+i).data( "index", i ).click( function() {
									var index = $(this).data("index");
									if (playItem != index) {
										playListChange( index );
									} else {
										$("#jquery_jplayer").jPlayer("play");
									}
								});
							}
						}

						function playListInit(autoplay) {
							if(autoplay) {
								playListChange( playItem );
							} else {
								playListConfig( playItem );
							}
						}

						function playListConfig( index ) {
							$("#jplayer_playlist_item_"+playItem).removeClass("jplayer_playlist_current");
							$("#jplayer_playlist_item_"+index).addClass("jplayer_playlist_current");
							playItem = index;
							$("#jquery_jplayer").jPlayer("setFile", myPlayList[playItem].mp3, myPlayList[playItem].ogg);
						}

						function playListChange( index ) {
							playListConfig( index );
							$("#jquery_jplayer").jPlayer("play");
						}

						function playListNext() {
							var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
							playListChange( index );
						}

						function playListPrev() {
							var index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1;
							playListChange( index );
						}
						
						$("#jplayer_previous").click( function() {
							playListPrev();
							return false;
						});

						$("#jplayer_next").click( function() {
							playListNext();
							return false;
						});
					
					}else{
						alert("vide");
					}
					
				}
			});
		}
	});
}
function createDisplayPicturesHome(){
	$.ajax({
		url: "gestion/ajax/home/displayPicturesHome.php",
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplayPicturesHome").empty();
			$("#contentDisplayPicturesHome").html(data);
			
			$.preload('.preload', {
				onFinish:function(){
					$('.homePictureGallery').easySlider({
						controlsBefore: '<div id="controls">',
						controlsAfter: '</div>',
						prevId: 'prevBtn2',
						nextId: 'nextBtn2',
						auto: false, 
						continuous: true,
						prevText: '',
						nextText: '',
						speed: 500,
						pause: 6000,
						vertical: false
					});
				},
				threshold: 20
			});
			
			$('.homePictureImage').click(function(){
				var id = $(this).attr('id');
				var uid = id.split('-');
				document.location.href = "index.php?id="+PAGE_DISPLAY_PICTURES+"&uid="+uid[1]+"&L="+getLang();
			});
			
			$('.homeUploadPicture a').click(function(){
				$('#dialogUploadPicture').dialog({
					resizable: false,
					draggable: false,
					autoOpen: true,
					closeOnEscape: true,
					width: 445,
					modal: true,
					close: function() { $(this).dialog("destroy"); },
					open: function(){
						$('.message').hide();
					}
				});
				return false;
			});
			
			$('form#uploadImage').ajaxForm({
				beforeSubmit: function(){
					$('.message').hide();
					if(validateUploadPicture()){
						$('#loadingContainer').append($('#loading').html()).show();
						return true;
					}
					else{
						return false;
					}
				},
				success: function(e){
					$('#loadingContainer').empty();
					if(e != ''){
						var name = $('#txtName').attr('value');
						var date  = $('#txtDate').attr('value');
						var image  = e;
					
						$.ajax({
							url: "gestion/ajax/picture/uploadPicture.php",
							async: false,
							type: "POST",
							data: ({
								name:name,
								image:image,
								date:date
							}),
							success: function(data){
								if(parseInt(data) != 0){
									$('#message_error').hide();
									$('#message_success').show();
									
									$('#txtName').attr('value','');
									$('#txtDate').attr('value','');
									$('#txtImage').attr('value','');
								}
								else{
									$('#message_success').hide();
									$('#message_error').show();
								}
							}
						});
					}
					else{
						$('#message_success').hide();
						$('#message_error').show();
					}
				}
			});
			
			$("#txtDate").datepicker($.extend({}, 
				$.datepicker.regional[DATEPICKER_LANG], {
					dateFormat: "yy-mm-dd", 
					showOn: "both", 
					yearRange: '-10:+10',
					buttonImage: "gestion/images/icons/calendar.gif", 
					buttonImageOnly: true,
					changeMonth: true,
					changeYear: true 
				}
			));
		}
	});
}
function validateUploadPicture(){
	var name = $('#txtName').attr('value');
	var date = $('#txtDate').attr('value');
	var image = $('#txtImage').attr('value');
	
	var confirm = false;
	if($('#chkConfirm').is(':checked')){
		confirm = true;
	}
	
	var valid = true;
	
	if(name==''){
		valid = false;
		$('#errorName').show();
	}
	else{
		$('#errorName').hide();
	}
	if(date==''){
		valid = false;
		$('#errorDate').show();
	}
	else{
		$('#errorDate').hide();
	}
	if(image==''){
		valid = false;
		$('#errorImage').show();
	}
	else{
		$('#errorImage').hide();
	}
	if(!confirm){
		valid = false;
		$('#errorConfirm').show();
	}
	else{
		$('#errorConfirm').hide();
	}
	
	return valid;
}
function createDisplayHome(){
	$.ajax({
		url: "gestion/ajax/home/displayHome.php",
		async: false,
		type: "POST",
		success: function(data){
			$.preload('.preload', {
				onFinish:function(){
					$("#contentDisplayHome").empty();
					$("#contentDisplayHome").html(data);
			
					var src = $("#homeImage").css('backgroundImage');
					$('#header').css({'backgroundImage':src}); 
				}
			});
		}
	});
}
/*END HOME*/

/*START EVENTS*/
function createDisplayEvent(uid,returnType,returnUid){
	$.ajax({
		url: "gestion/ajax/event/displayEvent.php",
		data: ({uid:uid,returnType:returnType,returnUid:returnUid}),
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplayEvent").empty();
			$("#contentDisplayEvent").html(data);
		}
	});
	
	$('.returnLink').click(function(){
		switch(parseInt(returnType)){
			case 1:
				document.location.href = "index.php?id="+PAGE_DISPLAY_HOME+"&L="+getLang();
				break;
			case 2:
				var infos = $(this).attr('id').split('-');
				document.location.href = "index.php?id="+PAGE_DISPLAY_CALENDAR+"&uid="+infos[1]+"&L="+getLang();
				break;
			default:
				document.location.href = "index.php?id="+PAGE_DISPLAY_EVENTS+"&L="+getLang();
				break;
		}
		return false;
	});
}

function createDisplayCalendar(uid){
	$.ajax({
		url: "gestion/ajax/event/displayCalendar.php",
		data: ({uid:uid}),
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplayCalendar").empty();
			$("#contentDisplayCalendar").html(data);
		}
	});
	
	var options = {
		onMonthChanging: function(dateIn){
			var events = loadCalendarEvents(uid,parseInt(dateIn.getMonth())+1,parseInt(dateIn.getYear()));
			$.jMonthCalendar.ReplaceEventCollection(events);
			return true;
		},
		onYearChanging: function(dateIn){
			var events = loadCalendarEvents(uid,parseInt(dateIn.getMonth())+1,parseInt(dateIn.getYear()));
			$.jMonthCalendar.ReplaceEventCollection(events);
			return true;
		}
	};
	
	var date = new Date();
	var events = loadCalendarEvents(uid,parseInt(date.getMonth())+1,parseInt(date.getYear()));
	$.jMonthCalendar.Initialize(options, events);
	
	$('.showEvent').click(function(){
		var uid = $(this).attr('id').split('-');
		document.location.href = "index.php?id="+PAGE_DISPLAY_EVENT+"&uid="+uid[1]+"&returnType=2&returnUid="+uid+"&L="+getLang();
		return false;
	});
	
	$('.showCalendar').click(function(){
		var uid = $(this).attr('id').split('-');
		document.location.href = "index.php?id="+PAGE_DISPLAY_CALENDAR+"&uid="+uid[1]+"&L="+getLang();
		return false;
	});
}

function loadCalendarEvents(uid,month,year){
	var newEvents = [];
	$.ajax({
		url: "gestion/ajax/event/loadCalendarEvents.php",
		async: false,
		type: "POST",
		data: ({uid:uid,month:month,year:year}),
		success: function(data){
			if(data != ''){
				var events = data.split('|');
				for(i=0;i<events.length;i++){
					var eventInfos = events[i].split(';');
					var dateInfos = eventInfos[0].split('-');
					var date = new Date(parseInt(dateInfos[0]), 
										parseInt(dateInfos[1])-1, 
										parseInt(dateInfos[2]));
					newEvents[i] = {  
						"EventID": i+1,  
						"Date": date,  
						"Title": eventInfos[1],  
						"URL": eventInfos[2]
					};  
				}
			}
		}
	});
	return newEvents;
}

function createDisplayEvents(uid){
	$.ajax({
		url: "gestion/ajax/event/displayEvents.php",
		data: ({uid:uid}),
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplayEvents").empty();
			$("#contentDisplayEvents").html(data);
		}
	});
	
	$('.showCalendar').click(function(){
		var uid = $(this).attr('id').split('-');
		document.location.href = "index.php?id="+PAGE_DISPLAY_CALENDAR+"&uid="+uid[1]+"&L="+getLang();
		return false;
	});
	
	loadEvents();

	$('#calendar').daterangepicker({
		arrows: true,
		presetRanges: [],
		rangeStartTitle: START_DATE,
		rangeEndTitle: END_DATE,
		prevLinkText: PREVIOUS,
		nextLinkText: NEXT,
		doneButtonText: SELECT,
		presets: {
			specificDate: SPECIFIC_DATE, 
			allDatesBefore: DATES_BEFORE, 
			allDatesAfter: DATES_AFTER, 
			dateRange: DATE_RANGE
		},
		rangeSplitter: '-',
		dateFormat: 'yy-mm-dd',
		closeOnSelect: true,
		onChange: function(){
			loadEvents();
		},
		datepickerOptions: {
			changeMonth: true,
			changeYear: true 
		}
	}); 
}
function loadEvents(){
	var dates = [];
	if($('#calendar').attr('value') != ''){
		dates = $('#calendar').attr('value').split(' - ');
	}
	$.ajax({
		url: "gestion/ajax/event/loadEvents.php",
		data: ({'dates[]':dates}),
		async: false,
		type: "POST",
		success: function(data){
			$("#events").empty();
			$("#events").html(data);
		}
	});
	
	$(".displayEventsBoxEvent").each(function(){
		var uid = $(this).attr('id').split('-');
		$("a[rel='image-"+uid[1]+"']").colorbox({transition:"fade"});
	});
	
	$(".displayEventsBoxEvent").each(function(){ 
		var uid = $(this).attr('id').split('-');
		$("a[rel='flyer-"+uid[1]+"']").colorbox({transition:"fade"});
	});
	
	$(".displayEventsBoxEvent").each(function(){ 
		var uid = $(this).attr('id').split('-');
		$("a[rel='flash-"+uid[1]+"']").colorbox({transition:"fade"});
	});
	
	$('.showEvent').click(function(){
		var uid = $(this).attr('id').split('-');
		document.location.href = "index.php?id="+PAGE_DISPLAY_EVENT+"&uid="+uid[1]+"&returnType=0&L="+getLang();
		return false;
	});
}
/*END EVENTS*/

/*START PICTURES*/
function createDisplayPictures(uid){
	$.ajax({
		url: "gestion/ajax/picture/displayPictures.php",
		data: ({uid:uid}),
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplayPictures").empty();
			$("#contentDisplayPictures").html(data);
			
			loadPictures();
			loadAlbums();

			$('#calendar').daterangepicker({
				arrows: true,
				presetRanges: [],
				rangeStartTitle: START_DATE,
				rangeEndTitle: END_DATE,
				prevLinkText: PREVIOUS,
				nextLinkText: NEXT,
				doneButtonText: SELECT,
				presets: {
					specificDate: SPECIFIC_DATE, 
					allDatesBefore: DATES_BEFORE, 
					allDatesAfter: DATES_AFTER, 
					dateRange: DATE_RANGE
				},
				rangeSplitter: '-',
				dateFormat: 'yy-mm-dd',
				closeOnSelect: true,
				onChange: function(){
					loadPictures();
					loadAlbums();
				},
				datepickerOptions: {
					changeMonth: true,
					changeYear: true
				}
			});
		}
	});
}
function loadPictures(){
	var dates = [];
	// if($('#calendar').attr('value') != ''){
		// dates = $('#calendar').attr('value').split(' - ');
	// }
	$.ajax({
		url: "gestion/ajax/picture/loadPictures.php",
		data: ({'dates[]':dates}),
		async: false,
		type: "POST",
		success: function(data){
			$("#picturesLeft").empty();
			$("#picturesLeft").html(data);
			
			$(".displayPicturesMonthBox").each(function(){
				var id = $(this).attr('id');
				var uid = id.split('-');
				$("a[rel='gallery-"+uid[1]+"']").colorbox({transition:"fade",current:GALLERY_CURRENT});
			});
		}
	});
}
function loadAlbums(){
	var dates = [];
	// if($('#calendar').attr('value') != ''){
		// dates = $('#calendar').attr('value').split('  -  ');
	// }
	$.ajax({
		url: "gestion/ajax/album/loadAlbums.php",
		data: ({'dates[]':dates}),
		async: false,
		type: "POST",
		success: function(data){
			$("#picturesRight").empty();
			$("#picturesRight").html(data);
			
			$(".displayPicturesMonthBox").each(function(){
				var id = $(this).attr('id');
				var uid = id.split('-');
				$("a[rel='album-"+uid[1]+"']").colorbox({transition:"fade",current:GALLERY_CURRENT});
			});
		}
	});
}
/*END PICTURE*/

/*START PICTURE*/
var gridPictures = null;
function createFormPicture(uid){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/picture/formPicture.php",
			async: false,
			type: "POST",
			data: ({uid:uid}),
			success: function(data){
				$("#contentFormPicture").empty();
				$("#contentFormPicture").html(data);
			}
		});
		
		$('.btnSave').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			savePicture(uid[1],0);
		});
		
		$('.btnSaveClose').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			savePicture(uid[1],1);
		});
		
		$('.btnClose').click(function(){
			document.location.href = "index.php?id="+PAGE_LIST_PICTURES+"&L="+getLang();
		});
		
		$('.removeImageUpload').click(function(){
			$('#resultImageUpload').empty();
			$('#resultImageUpload').html('<input type="file" name="file" size="45" /><input type="submit" class="button" value="'+UPLOAD_BUTTON+'" />');
			$('#txtImage').attr('value','');
			return false;
		});
		
		$('form#uploadImage').ajaxForm({
			success: function(e) {
				if(e != '')
				{
					$('#resultImageUpload').empty();
					$('#resultImageUpload').html('<div><table cellpadding="0" cellspacing="0" border="0"><tr><td valign="middle"><a href="gestion/files/_temp/'+e+'" target="_blank">'+VIEW_LINK+'</a></td><td valign="middle" style="padding-left:5px;"><a href="" class="removeImageUpload"><img src="gestion/images//delete.png" alt="'+DELETE_LINK+'" title="'+DELETE_LINK+'" border="0" /></a></td></tr></table></div>');
					$('#txtImage').attr('value',e);
					
					$('.removeImageUpload').click(function(){
						$('#resultImageUpload').empty();
						$('#resultImageUpload').html('<input type="file" name="file" size="45" /><input type="submit" class="button" value="'+UPLOAD_BUTTON+'" />');
						$('#txtImage').attr('value','');
						return false;
					});
				}
			}
		});
		
		$("#txtDate").datepicker($.extend({}, 
			$.datepicker.regional[DATEPICKER_LANG], {
				dateFormat: "yy-mm-dd", 
				showOn: "both", 
				yearRange: '-10:+10',
				buttonImage: "gestion/images/icons/calendar.gif", 
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true 
			}
		));
	}
}
function savePicture(uid, returnType){
	if(checkLogin()){
		var name = $('#txtName').attr('value');
		var date  = $('#txtDate').attr('value');
		var image  = $('#txtImage').attr('value');
		var event  = $('#optEvent').attr('value');
		
		if(validateFormPicture()){
			$.ajax({
				url: "gestion/ajax/picture/savePicture.php",
				async: false,
				type: "POST",
				data: ({
					uid:uid,
					name:name,
					image:image,
					date:date,
					event:event
				}),
				success: function(data){
					if(returnType==1){
						document.location.href = "index.php?id="+PAGE_LIST_PICTURES+"&L="+getLang();
					}
					else if(returnType==0)
					{
						createFormPicture(uid);
					}
						
					if(parseInt(data) != 0){
						$('#message_error').hide();
						$('#message_success').show();
					}
					else{
						$('#message_success').hide();
						$('#message_error').show();
					}
				}
			});
		}
		else{
			$('#message_success').hide();
			$('#message_error').show();
		}
	}
}
function validateFormPicture(){
	var name = $('#txtName').attr('value');
	var date  = $('#txtDate').attr('value');
	var image  = $('#txtImage').attr('value');
	
	var valid = true;
	
	if(name==''){
		valid = false;
		$('#errorName').show();
	}
	else{
		$('#errorName').hide();
	}
	if(date==''){
		valid = false;
		$('#errorDate').show();
	}
	else{
		$('#errorDate').hide();
	}
	if(image==''){
		valid = false;
		$('#errorImage').show();
	}
	else{
		$('#errorImage').hide();
	}
	
	return valid;
}
function deletePicture(uid){
	if(checkLogin()){
		$('#dialogDeletePicture').dialog({
			resizable: false,
			draggable: false,
			autoOpen: true,
			height:100,
			width:350,
			modal: true,
			close: function(ev, ui) {
				$(this).dialog("destroy");
			},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				"Non": function(){
					$(this).dialog('destroy');
				},
				"Oui": function() {
					$(this).dialog('destroy');
					$.ajax({
						url: "gestion/ajax/picture/deletePicture.php",
						async: false,
						type: "POST",
						data: ({uid:uid}),
						success: function(data){
							gridPictures.update();
						}
					});
				}
			}
		});
	}
}
function changeStatusPicture(uid){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/picture/changeStatusPicture.php",
			async: false,
			type: "POST",
			data: ({uid:uid}),
			success: function(data){
				gridPictures.update();
			}
		});
	}
}
function loadListPictures(){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/loadGrid.php",
			async: false,
			type: "POST",
			data: ({name: 'gridPictures'}),
			success: function(data){
				var search = '';
				var sort = 1;
				var side = 'desc';
				var page = 1;
				var limit = 10;
				if(data != ''){
					var config = data.split('|');
					search = config[FD_GRID_SEARCH];
					sort = parseInt(config[FD_GRID_SORT]);
					side = config[FD_GRID_SIDE];
					page = parseInt(config[FD_GRID_PAGE]);
					limit = parseInt(config[FD_GRID_LIMIT]);
				}
				$('#contentListPictures').empty();
				$('#contentListPictures').fdGrid({
					lang: getLangName(),
					rows: limit,
					url: 'gestion/ajax/picture/listPictures.php',
					configUrl: 'gestion/ajax/saveGrid.php',
					name: 'gridPictures',
					page: page,
					sortCol: sort,
					sortOrder: side,
					filter: search,
					navBarAlign: 'left',
					navBarLocation: 'bottom',
					callback: function(g){
						gridPictures = g;
						setEventListPictures();
					}
				});
			}
		});
	}
}
function setEventListPictures(){	
	$(".changeStatusPicture").click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		changeStatusPicture(uid[1]);
		return false;
	});
		
	$(".createFormPicture").click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		if(uid[1]==0){
			document.location.href = "index.php?id="+PAGE_FORM_PICTURE+"&L="+getLang();
		}
		else{
			document.location.href = "index.php?id="+PAGE_FORM_PICTURE+"&uid="+uid[1]+"&L="+getLang();
		}
		return false;
	});
	
	$(".deletePicture").click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		deletePicture(uid[1]);
		return false;
	});
}
/*END PICTURE*/

/*START EVENT*/
var gridEvents = null;
function createFormEvent(uid){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/event/formEvent.php",
			async: false,
			type: "POST",
			data: ({uid:uid}),
			success: function(data){
				$("#contentFormEvent").empty();
				$("#contentFormEvent").html(data);
			}
		});
		
		$('#optType').change(function(){
			switch(parseInt($(this).attr('value'))){
				case 1:
					$('#frequency').hide();
					$('#date').show();
					$('#dateStart').hide();
					$('#dateEnd').hide();
					$('#nbWeek').hide();
					break;
					
				case 2:
					$('#frequency').hide();
					$('#date').show();
					$('#dateStart').hide();
					$('#dateEnd').hide();
					$('#nbWeek').show();
					break;
					
				case 3:
					$('#frequency').show();
					$('#date').hide();
					$('#dateStart').show();
					$('#dateEnd').show();
					$('#nbWeek').hide();
					break;
			}
		}).change();
		
		$('.btnSave').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			saveEvent(uid[1],0);
		});
		
		$('.btnSaveClose').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			saveEvent(uid[1],1);
		});
		
		$('.btnClose').click(function(){
			document.location.href = "index.php?id="+PAGE_LIST_EVENTS+"&L="+getLang();
		});
		
		$('.removeImageUpload').click(function(){
			$('#resultImageUpload').empty();
			$('#resultImageUpload').html('<input type="file" name="image" size="45" /><input type="submit" class="button" value="'+UPLOAD_BUTTON+'" />');
			$('#txtImage').attr('value','');
			return false;
		});
		
		$('form#uploadImage').ajaxForm({
			success: function(e) {
				if(e != '')
				{
					$('#resultImageUpload').empty();
					$('#resultImageUpload').html('<div><table cellpadding="0" cellspacing="0" border="0"><tr><td valign="middle"><a href="gestion/files/_temp/'+e+'" target="_blank">'+VIEW_LINK+'</a></td><td valign="middle" style="padding-left:5px;"><a href="" class="removeImageUpload"><img src="gestion/images/icons/delete.png" alt="'+DELETE_LINK+'" title="'+DELETE_LINK+'" border="0" /></a></td></tr></table></div>');
					$('#txtImage').attr('value',e);
					
					$('.removeImageUpload').click(function(){
						$('#resultImageUpload').empty();
						$('#resultImageUpload').html('<input type="file" name="image" size="45" /><input type="submit" class="button" value="'+UPLOAD_BUTTON+'" />');
						$('#txtImage').attr('value','');
						return false;
					});
				}
			}
		});
		
		$('.removeImageUpload2').click(function(){
			$('#resultImageUpload2').empty();
			$('#resultImageUpload2').html('<input type="file" name="image" size="45" /><input type="submit" class="button" value="'+UPLOAD_BUTTON+'" />');
			$('#txtFlyer').attr('value','');
			return false;
		});
		
		$('form#uploadImage2').ajaxForm({
			success: function(e) {
				if(e != '')
				{
					$('#resultImageUpload2').empty();
					$('#resultImageUpload2').html('<div><table cellpadding="0" cellspacing="0" border="0"><tr><td valign="middle"><a href="gestion/files/_temp/'+e+'" target="_blank">'+VIEW_LINK+'</a></td><td valign="middle" style="padding-left:5px;"><a href="" class="removeImageUpload2"><img src="gestion/images/icons/delete.png" alt="'+DELETE_LINK+'" title="'+DELETE_LINK+'" border="0" /></a></td></tr></table></div>');
					$('#txtFlyer').attr('value',e);
					
					$('.removeImageUpload2').click(function(){
						$('#resultImageUpload2').empty();
						$('#resultImageUpload2').html('<input type="file" name="image" size="45" /><input type="submit" class="button" value="'+UPLOAD_BUTTON+'" />');
						$('#txtFlyer').attr('value','');
						return false;
					});
				}
			}
		});
		
		$('.removeFlashUpload').click(function(){
			$('#resultFlashUpload').empty();
			$('#resultFlashUpload').html('<input type="file" name="flash" size="45" /><input type="submit" class="button" value="'+UPLOAD_BUTTON+'" />');
			$('#txtFlash').attr('value','');
			return false;
		});
		
		$('form#uploadFlash').ajaxForm({
			success: function(e) {
				if(e != '')
				{
					$('#resultFlashUpload').empty();
					$('#resultFlashUpload').html('<div><table cellpadding="0" cellspacing="0" border="0"><tr><td valign="middle"><a href="gestion/files/_temp/'+e+'" target="_blank">'+VIEW_LINK+'</a></td><td valign="middle" style="padding-left:5px;"><a href="" class="removeFlashUpload"><img src="gestion/images/icons/delete.png" alt="'+DELETE_LINK+'" title="'+DELETE_LINK+'" border="0" /></a></td></tr></table></div>');
					$('#txtFlash').attr('value',e);
					
					$('.removeFlashUpload').click(function(){
						$('#resultFlashUpload').empty();
						$('#resultFlashUpload').html('<input type="file" name="flash" size="45" /><input type="submit" class="button" value="'+UPLOAD_BUTTON+'" />');
						$('#txtFlash').attr('value','');
						return false;
					});
				}
			}
		});
		
		$("#txtDate").datepicker($.extend({}, 
			$.datepicker.regional[DATEPICKER_LANG], {
				dateFormat: "yy-mm-dd", 
				showOn: "both", 
				yearRange: '-10:+10',
				buttonImage: "gestion/images/icons/calendar.gif", 
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true 
			}
		));
		
		$("#txtDateStart").datepicker($.extend({}, 
			$.datepicker.regional[DATEPICKER_LANG], {
				dateFormat: "yy-mm-dd", 
				showOn: "both", 
				yearRange: '-10:+10',
				buttonImage: "gestion/images/icons/calendar.gif", 
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true 
			}
		));
		
		$("#txtDateEnd").datepicker($.extend({}, 
			$.datepicker.regional[DATEPICKER_LANG], {
				dateFormat: "yy-mm-dd", 
				showOn: "both", 
				yearRange: '-10:+10',
				buttonImage: "gestion/images/icons/calendar.gif", 
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true 
			}
		));
		
		//$('#txtDescriptionFr').wysiwyg();
		//$('#txtDescriptionEn').wysiwyg();
	}
}
function saveEvent(uid, returnType){
	if(checkLogin()){
		if(validateFormEvent()){
			if(uid != 0){
				$.ajax({
					url: "gestion/ajax/event/countSimilarEvents.php",
					async: false,
					type: "POST",
					data: ({uid:uid}),
					success: function(data){
						var similarEvents = parseInt(data);
						if(similarEvents > 0){
							$('#similarEventsContainer').html(similarEvents);
							$('#dialogDeleteSimilarEvents').dialog({
								resizable: false,
								draggable: false,
								autoOpen: true,
								height:100,
								width:350,
								modal: true,
								close: function(ev, ui) {
									$(this).dialog("destroy");
									saveEvent2(uid,0,returnType);
								},
								overlay: {
									backgroundColor: '#000',
									opacity: 0.5
								},
								buttons: {
									"Non": function(){
										$(this).dialog('destroy');
										saveEvent2(uid,0,returnType);
									},
									"Oui": function() {
										$(this).dialog('destroy');
										saveEvent2(uid,1,returnType);
									}
								}
							});
						}
						else{
							saveEvent2(uid,0,returnType);
						}
					}
				});
			}
			else{
				saveEvent2(uid,0,returnType);
			}
		}
		else{
			$('#message_success').hide();
			$('#message_error').show();
		}
	}
}
function saveEvent2(uid, similar, returnType){
	if(checkLogin()){
		var type = $('#optType').attr('value');
		var nameFr = $('#txtNameFr').attr('value');
		var nameEn = $('#txtNameEn').attr('value');
		var descriptionFr = $('#txtDescriptionFr').attr('value');
		var descriptionEn = $('#txtDescriptionEn').attr('value');
		var date  = $('#txtDate').attr('value');
		var dateStart  = $('#txtDateStart').attr('value');
		var dateEnd  = $('#txtDateEnd').attr('value');
		var week  = $('#optWeek').attr('value');
		var frequency  = $('#optFrequency').attr('value');
		var link  = $('#txtLink').attr('value');
		var image  = $('#txtImage').attr('value');
		var image2  = $('#txtFlyer').attr('value');
		var flash  = $('#txtFlash').attr('value');
		var price  = $('#txtPrice').attr('value');
		
		var stages = [];
		$(":input[name='chkStages[]']:checked").each(function(i){
			stages[i] = $(this).attr('value');
		});
		
		var show = 0;
		if($('#chkShow').is(':checked')){
			show = 1;
		}
	
		$.ajax({
			url: "gestion/ajax/event/saveEvent.php",
			async: false,
			type: "POST",
			data: ({
				uid:uid,
				similar:similar,
				type:type,
				nameFr:nameFr,
				nameEn:nameEn,
				descriptionFr:descriptionFr,
				descriptionEn:descriptionEn,
				image:image,
				image2:image2,
				link:link,
				date:date,
				dateStart:dateStart,
				dateEnd:dateEnd,
				frequency:frequency,
				week:week,
				price:price,
				'stages[]':stages,
				show:show,
				flash:flash
			}),
			success: function(data){
				if(returnType==1){
					document.location.href = "index.php?id="+PAGE_LIST_EVENTS+"&L="+getLang();
				}
				else if(returnType==0)
				{
					createFormEvent(uid);
				}
					
				if(parseInt(data) != 0){
					$('#message_error').hide();
					$('#message_success').show();
				}
				else{
					$('#message_success').hide();
					$('#message_error').show();
				}
			}
		});
	}
}
function validateFormEvent(){
	var type = parseInt($('#optType').attr('value'));
	var nameFr = $('#txtNameFr').attr('value');
	var nameEn = $('#txtNameEn').attr('value');
	var descriptionFr = $('#txtDescriptionFr').attr('value');
	var descriptionEn = $('#txtDescriptionEn').attr('value');
	var date  = $('#txtDate').attr('value');
	var dateStart  = $('#txtDateStart').attr('value');
	var dateEnd  = $('#txtDateEnd').attr('value');
	var image  = $('#txtImage').attr('value');
	
	var stages = [];
	$(":input[name='chkStages[]']:checked").each(function(i){
		stages[i] = $(this).attr('value');
	});
	
	var valid = true;
	
	if(nameFr==''){
		valid = false;
		$('#errorNameFr').show();
	}
	else{
		$('#errorNameFr').hide();
	}
	// if(nameEn==''){
		// valid = false;
		// $('#errorNameEn').show();
	// }
	// else{
		// $('#errorNameEn').hide();
	// }
	if(descriptionFr==''){
		valid = false;
		$('#errorDescriptionFr').show();
	}
	else{
		$('#errorDescriptionFr').hide();
	}
	// if(descriptionEn==''){
		// valid = false;
		// $('#errorDescriptionEn').show();
	// }
	// else{
		// $('#errorDescriptionEn').hide();
	// }
	if(type == 1 || type == 2){
		if(date==''){
			valid = false;
			$('#errorDate').show();
		}
		else{
			$('#errorDate').hide();
		}
	}
	else if(type == 3){
		if(dateStart==''){
			valid = false;
			$('#errorDateStart').show();
		}
		else{
			$('#errorDateStart').hide();
		}
		if(dateEnd==''){
			valid = false;
			$('#errorDateEnd').show();
		}
		else{
			$('#errorDateEnd').hide();
		}
	}
	if(image==''){
		valid = false;
		$('#errorImage').show();
	}
	else{
		$('#errorImage').hide();
	}
	if(stages.length==0){
		valid = false;
		$('#errorStages').show();
	}
	else{
		$('#errorStages').hide();
	}
	
	return valid;
}

function deleteEvent(uid){
	if(checkLogin()){
		$('#dialogDeleteEvent').dialog({
			resizable: false,
			draggable: false,
			autoOpen: true,
			height:100,
			width:350,
			modal: true,
			close: function(ev, ui) {
				$(this).dialog("destroy");
			},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				"Non": function(){
					$(this).dialog('destroy');
				},
				"Oui": function() {
					$(this).dialog('destroy');
					$.ajax({
						url: "gestion/ajax/event/countSimilarEvents.php",
						async: false,
						type: "POST",
						data: ({uid:uid}),
						success: function(data){
							var similarEvents = parseInt(data);
							if(similarEvents > 0){
								$('#similarEventsContainer').html(similarEvents);
								$('#dialogDeleteSimilarEvents').dialog({
									resizable: false,
									draggable: false,
									autoOpen: true,
									height:100,
									width:350,
									modal: true,
									close: function(ev, ui) {
										$(this).dialog("destroy");
										deleteEvent2(uid,0);
									},
									overlay: {
										backgroundColor: '#000',
										opacity: 0.5
									},
									buttons: {
										"Non": function(){
											$(this).dialog('destroy');
											deleteEvent2(uid,0);
										},
										"Oui": function() {
											$(this).dialog('destroy');
											deleteEvent2(uid,1);
										}
									}
								});
							}
							else{
								deleteEvent2(uid,0);
							}
						}
					});
				}
			}
		});
	}
}
function deleteEvent2(uid, similar){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/event/deleteEvent.php",
			async: false,
			type: "POST",
			data: ({uid:uid,similar:similar}),
			success: function(data){
				gridEvents.update();
			}
		});
	}
}
function loadListEvents(){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/loadGrid.php",
			async: false,
			type: "POST",
			data: ({name: 'gridEvents'}),
			success: function(data){
				var search = '';
				var sort = 1;
				var side = 'desc';
				var page = 1;
				var limit = 10;
				if(data != ''){
					var config = data.split('|');
					search = config[FD_GRID_SEARCH];
					sort = parseInt(config[FD_GRID_SORT]);
					side = config[FD_GRID_SIDE];
					page = parseInt(config[FD_GRID_PAGE]);
					limit = parseInt(config[FD_GRID_LIMIT]);
				}
				$('#contentListEvents').empty();
				$('#contentListEvents').fdGrid({
					lang: getLangName(),
					rows: limit,
					url: 'gestion/ajax/event/listEvents.php',
					configUrl: 'gestion/ajax/saveGrid.php',
					name: 'gridEvents',
					page: page,
					sortCol: sort,
					sortOrder: side,
					filter: search,
					navBarAlign: 'left',
					navBarLocation: 'bottom',
					callback: function(g){
						gridEvents = g;
						setEventListEvents();
					}
				});
			}
		});
	}
}
function setEventListEvents(){
	$(".createFormEvent").click(function (){
		var id = $(this).attr('id');
		var uid = id.split('-');
		if(uid[1]==0){
			document.location.href = "index.php?id="+PAGE_FORM_EVENT+"&L="+getLang();
		}
		else{
			document.location.href = "index.php?id="+PAGE_FORM_EVENT+"&uid="+uid[1]+"&L="+getLang();
		}
		return false;
	});
	
	$(".deleteEvent").click(function (){
		var id = $(this).attr('id');
		var uid = id.split('-');
		deleteEvent(uid[1]);
		return false;
	});
}
/*END EVENT*/

/*START RESERVATION*/

	/* Reservation impossible */
function loadPannelReservationImpossible(){
	$('#containerReservationImpossible').html('</div><div id="containerReservationImpossibleList"></div><div id="containerReservationImpossibleForm"></div>');
	loadPannelReservationImpossibleForm(0);
	loadPannelReservationImpossibleList();
}

function loadPannelReservationImpossibleForm(uid){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/reservation/loadPannelReservationImpossibleForm.php",
			async: false,
			type: "POST",
			data: ({uid:uid}),
			success: function(data){
				$('#containerReservationImpossibleForm').html(data);
				setEventFormReservationsImpossibles();
			}
		});
	}
}
var gridReservationsImpossibles = null;
function loadPannelReservationImpossibleList(){
	if(checkLogin()){
		$.ajax({
			url:"gestion/ajax/loadGrid.php",
			async:false,
			type:"POST",
			data:({name: 'gridReservationsImpossibles'}),
			success:function(data){
				var search = '';
				var sort = 0;
				var side = 'asc';
				var page = 1;
				var limit = 10;
				if(data != ''){
					var config = data.split('|');
					search = config[FD_GRID_SEARCH];
					sort = parseInt(config[FD_GRID_SORT]);
					side = config[FD_GRID_SIDE];
					page = parseInt(config[FD_GRID_PAGE]);
					limit = parseInt(config[FD_GRID_LIMIT]);
				}
				$('#containerReservationImpossibleList').empty();
				$('#containerReservationImpossibleList').fdGrid({
					lang: getLangName(),
					rows: limit,
					url: 'gestion/ajax/reservation/loadPannelReservationImpossibleList.php',
					configUrl: 'gestion/ajax/saveGrid.php',
					name: 'gridReservationsImpossibles',
					page: page,
					sortCol: sort,
					sortOrder: side,
					filter: search,
					navBarAlign: 'left',
					navBarLocation: 'bottom',
					callback: function(g){
						gridReservationsImpossibles = g;
						setEventListReservationsImpossibles();
					}
				});
				// alert(data)
			}
		});
	}
}
function setEventListReservationsImpossibles(){
	$('.createFormReservationImpossible').click(function(){
		var id = $(this).attr('id');
		var tabUid = id.split("-");
		loadPannelReservationImpossibleForm(tabUid[1]);
		return false;
	});
	$('.deleteReservationImpossible').click(function(){
		var id = $(this).attr('id');
		var tabUid = id.split("-");
		deleteReservationImpossible(tabUid[1]);
		return false;
	});
}
function deleteReservationImpossible(uid){
	if(checkLogin()){
		$('#dialogDeleteReservationImpossible').dialog({
			resizable: false,
			draggable: false,
			autoOpen: true,
			height:100,
			width:350,
			modal: true,
			close: function(ev, ui) {
				$(this).dialog("destroy");
			},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				"Non": function(){
					$(this).dialog('destroy');
				},
				"Oui": function() {
					$(this).dialog('destroy');
					$.ajax({
						url: "gestion/ajax/reservation/deleteReservationImpossible.php",
						async: false,
						type: "POST",
						data: ({uid:uid}),
						success: function(data){
							gridReservationsImpossibles.update();
						}
					});
				}
			}
		});
	}
}
function setEventFormReservationsImpossibles(){

	$('#txt_date_reservation_impossible').datepicker($.extend({}, 
		$.datepicker.regional[DATEPICKER_LANG], {
			dateFormat: "yy-mm-dd", 
			showOn: "both", 
			yearRange: '-0:+2',
			minDate: '0',
			buttonImage: "gestion/images/icons/calendar.gif", 
			buttonImageOnly: true,
			changeMonth: true,
			changeYear: true 
		}
	));
	
	$('.btnSave').click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		saveFormReservationImpossible(uid[1],0);
	});
	
	$('.btnSaveNew').click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		saveFormReservationImpossible(uid[1],1);
	});
	
	$('.btnNew').click(function(){
	var id = $(this).attr('id');
		var uid = id.split('-');
		loadPannelReservationImpossibleForm(0);
	});
}

function saveFormReservationImpossible(uid,endType){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/reservation/saveReservationImpossible.php",
			async: false,
			type: "POST",
			data: ({
				uid:uid,
				date:$('#txt_date_reservation_impossible').attr('value'),
				raison:$('#txt_raison_impossible').attr('value')
			}),
			success: function(data){
				
				tabData = data.split("|");
				tabData[0] = parseInt(tabData[0]);
				if(tabData[0] == 0){
					if(endType==1)
						loadPannelReservationImpossibleForm(0);
					else if(endType==0)
						loadPannelReservationImpossibleForm(tabData[1]);
						
					$('#message_success').show();
				}else{
					$('#message_error').show();
				}
			}
		});
	}	
	gridReservationsImpossibles.update();
}
// var gridReservations = null;
// function loadListReservations(){
	// if(checkLogin()){
		// $.ajax({
			// url:"gestion/ajax/loadGrid.php",
			// async:false,
			// type:"POST",
			// data:({name: 'gridReservations'}),
			// success:function(data){
				// var search = '';
				// var sort = 0;
				// var side = 'asc';
				// var page = 1;
				// var limit = 10;
				// if(data != ''){
					// var config = data.split('|');
					// search = config[FD_GRID_SEARCH];
					// sort = parseInt(config[FD_GRID_SORT]);
					// side = config[FD_GRID_SIDE];
					// page = parseInt(config[FD_GRID_PAGE]);
					// limit = parseInt(config[FD_GRID_LIMIT]);
				// }
				// $('#contentListReservations').empty();
				// alert("avant fdGrid");
				// $('#contentListReservations').fdGrid({
					// lang: getLangName(),
					// rows: limit,
					// url: 'gestion/ajax/reservation/listReservations.php',
					// configUrl: 'gestion/ajax/saveGrid.php',
					// name: 'gridReservations',
					// page: page,
					// sortCol: sort,
					// sortOrder: side,
					// filter: search,
					// navBarAlign: 'left',
					// navBarLocation: 'bottom',
					// callback: function(g){
						// alert("ici");
						// gridReservations = g;
						// alert(gridReservations);
						// setEventListReservations2();
					// }
				// });
				// alert("Apres fdgrid");
				// alert(data)
			// }
		// });
	// }
// }

function setEventListReservations2(){
	
	$('.deleteReservation').click(function(){
		var id = $(this).attr('id');
		var tabUid = id.split("-");
		deleteReservation(tabUid[1]);
		return false;
	});
	
	// $('.createFormReservation').click(function(){
		// var id = $(this).attr('id');
		// var tabUid = id.split("-");
		// if(tabUid[1]!=0){
			// document.location.href = "index.php?id="+PAGE_FORM_RESERVATION+"&uid="+tabUid[1]+"&L="+getLang();
		// }else{
			// document.location.href = "index.php?id="+PAGE_FORM_RESERVATION+"&L="+getLang();
		// }
		// return false;
	// });
}

function deleteReservation(uid){
	$('#dialogDeleteReservation').dialog({
		resizable: false,
		draggable: false,
		autoOpen: true,
		height:100,
		width:350,
		modal: true,
		close: function(ev, ui) {
			$(this).dialog("destroy");
		},
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			"Non": function(){
				$(this).dialog('destroy');
			},
			"Oui": function() {
				$(this).dialog('destroy');
				$.ajax({
					url: "gestion/ajax/reservation/deleteReservation.php",
					async: false,
					type: "POST",
					data: ({uid:uid}),
					success: function(data){
						gridListReservations.update();
						loadDivSectionByDate($('#txt_date_reservation').attr('value'));
					}
				});
			}
		}
	});
}

function loadFormReservation(uid){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/reservation/formReservation.php",
			async: false,
			type: "POST",
			data: ({uid:uid}),
			success: function(data){
				$("#contentFormReservation").empty();
				$("#contentFormReservation").html(data);
				
				loadDivSectionByDate($('#txt_date_reservation').attr('value'));
			}
		});
		
		$('#txt_date_reservation').datepicker($.extend({}, 
			$.datepicker.regional[DATEPICKER_LANG], {
				dateFormat: "yy-mm-dd", 
				showOn: "both", 
				yearRange: '-0:+1',
				minDate: '0',
				buttonImage: "gestion/images/icons/calendar.gif", 
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true 
			}
		));
		
		$('#txt_date_reservation').focus(function(){
			if(verifChangementPanelReservation()){
				$('#dialogChangeContact').dialog({
					resizable: false,
					draggable: false,
					autoOpen: true,
					height:100,
					width:350,
					modal: true,
					close: function(ev, ui) {
						$(this).dialog("destroy");
					},
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					buttons: {
						"Non": function(){
							$(this).dialog('destroy');
						},
						"Oui": function() {
							$(this).dialog('destroy');
							
							$('#txt_date_reservation').change(function(){
								loadDivSectionByDate($(this).attr('value'));
							});
						}
					}
				});
			}else{
				$(this).change(function(){
					loadDivSectionByDate($(this).attr('value'));
				});
			}
		});
		
		$('.btnSave').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			saveReservation(uid[1],0);
		});
		
		$('.btnSaveClose').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			saveReservation(uid[1],1);
		});
		
		$('.btnClose').click(function(){
			document.location.href = "index.php?id="+PAGE_LIST_RESERVATION+"&L="+getLang();
		});
		
		
	}
}


function saveReservation(uid, returnType){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/reservation/saveReservation.php",
			async: false,
			type: "POST",
			data: ({
				uid:uid,
				date:$('#txt_date_reservation').attr('value'),
				status:$('#optStatus').attr('value'),
				section:'',
				courriel:$('#txt_client_email').attr('value'),
				telephone:$('#txt_client_phone').attr('value'),
				prenom:$('#txt_client_name').attr('value'),
				nom:$('#txt_client_lastname').attr('value')
			}),
			success: function(data){
				alert(data);
				// tabData = data.split("|");
				// tabData[0] = parseInt(tabData[0]);
				// if(tabData[0] == 0){
					// if(returnType==1)
						// document.location.href = 'index.php?id='+PAGE_LIST_SONGS+"&L="+getLang();
					// else if(returnType==0)
						// createFormSong(tabData[1]);
						
					// $('#messageSongSuccess').show();
				// }else{
					// $('#messageSongError').show();
				// }
			}
		});
	}
}

function saveReservation2(uid){
	var confirmer = ($('#chk_confirmed').attr('checked'))?1:0;
	var payer = ($('#chk_paid').attr('checked'))?1:0;
	var dateNow = $('#txt_date_reservation').attr('value');
	
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/reservation/saveReservation2.php",
			async: false,
			type: "POST",
			data: ({
				uid:uid,
				date:$('#txt_date_reservation').attr('value'),
				status:$('#optStatus').attr('value'),
				confirmer:confirmer,
				payer:payer,
				sections:$('#txt_client_reservation').attr('value'),
				courriel:$('#txt_client_email').attr('value'),
				telephone:$('#txt_client_phone').attr('value'),
				prenom:$('#txt_client_name').attr('value'),
				nom:$('#txt_client_lastname').attr('value')
			}),
			success: function(data){
				if(data=="Err-1"){
				
				}else if(data==""){
					
				}
				synchroniserPanels();
				loadPannelReservation(dateNow);
				// goToReservationToShow(uid);
				loadFromPanelCont(uid,confirmer);
				gridListReservations.update();
			}
		});
	}
}

// function goToReservationToShow(uid){
	// $('.bloc_p,#cont-'+uid).trigger('click');
// }

function validateFormReservation(){
	var valid = true;
	
	var txt_sections = $('#txt_client_reservation').attr('value');
	var txt_email = $('#txt_client_email').attr('value');
	
	if(txt_sections == ''){
		valid = false;
	}
	if(!isEmail(txt_email)){
		valid = false;
		
	}
	
	return valid;
}

var dateBeforeChange = "";
function setInitEventPanel(){
	
	$('#txt_date_reservation').live('change',function(){
		if(dateBeforeChange!= ""){
			if(verifChangementPanelReservation()){
				$('#dialogChangeContact').dialog({
					resizable: false,
					draggable: false,
					autoOpen: true,
					height:100,
					width:350,
					modal: true,
					close: function(ev, ui) {
						$(this).dialog("destroy");
					},
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					buttons: {
						"Non": function(){
							$(this).dialog('destroy');
							$('#txt_date_reservation').attr("value",dateBeforeChange);
						},
						"Oui": function() {
							$(this).dialog('destroy');
							
							loadDivSectionByDate($('#txt_date_reservation').attr('value'));
							synchroniserPanels();
						}
					}
				});
			}else{
				loadDivSectionByDate($(this).attr('value'));
			}
		}else{
			alert("Non setter");
		}
	});
	
	$('.bloc_p').live("click",function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		
		if(verifChangementPanelReservation()){
			$('#dialogChangeContact').dialog({
				resizable: false,
				draggable: false,
				autoOpen: true,
				height:100,
				width:350,
				modal: true,
				close: function(ev, ui) {
					$(this).dialog("destroy");
				},
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: {
					"Non": function(){
						$(this).dialog('destroy');
					},
					"Oui": function() {
						$(this).dialog('destroy');
						
						/* SAME AS ME 1*/
						if(uid[1] != "0"){
							loadFromPanelCont(uid[1],0);
						}else{
							if(uid[0] == "contR"){
								loadFromPanelCont(0,1);
							}else{
								loadFromPanelCont(0,0);
							}
						}
					}
				}
			});
		}else{
			/* SAME AS ME 1*/
			if(uid[1] != "0"){
				loadFromPanelCont(uid[1],0);
			}else{
				if(uid[0] == "contR"){
					loadFromPanelCont(0,1);
				}else{
					loadFromPanelCont(0,0);
				}
			}
		}
	});
	
	$('.bloc_p').live("mouseover",function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		if(uid[1]!= 0)
			showSectionOfContact(uid[1]);
	});
	
	$('.btnSave').live("click",function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		saveReservation2(uid[1]);
	});
}
var gridListReservations = null;
function loadInitPannelReservation(){
	$('#contentFormReservation').html('<div id="contentTopListReseration"></div><div id="contentBottomPannelReservation"></div>');
	
	if(checkLogin()){
		$.ajax({
			url:"gestion/ajax/loadGrid.php",
			async:false,
			type:"POST",
			data:({name: 'gridListReservations'}),
			success:function(data){
				var search = '';
				var sort = 0;
				var side = 'asc';
				var page = 1;
				var limit = 10;
				if(data != ''){
					var config = data.split('|');
					search = config[FD_GRID_SEARCH];
					sort = parseInt(config[FD_GRID_SORT]);
					side = config[FD_GRID_SIDE];
					page = parseInt(config[FD_GRID_PAGE]);
					limit = parseInt(config[FD_GRID_LIMIT]);
				}
				$('#contentTopListReseration').empty();
				$('#contentTopListReseration').fdGrid({
					lang: getLangName(),
					rows: limit,
					url: 'gestion/ajax/reservation/listReservations.php',
					configUrl: 'gestion/ajax/saveGrid.php',
					name: 'gridListReservations',
					page: page,
					sortCol: sort,
					sortOrder: side,
					filter: search,
					navBarAlign: 'left',
					navBarLocation: 'bottom',
					callback: function(g){
						gridListReservations = g;
						setEventListReservations2();
					}
				});
			}
		});
		
		$.ajax({
			url: "gestion/ajax/reservation/pannelReservation.php",
			async: false,
			type: "POST",
			data: ({}),
			success: function(data){
				$("#contentBottomPannelReservation").empty();
				$("#contentBottomPannelReservation").html(data);
				
				loadDivSectionByDate($('#txt_date_reservation').attr('value'));
			}
		});
		$('#txt_date_reservation').datepicker($.extend({}, 
			$.datepicker.regional[DATEPICKER_LANG], {
				dateFormat: "yy-mm-dd", 
				showOn: "focus", 
				yearRange: '-0:+1',
				minDate: '0',
				buttonImage: "gestion/images/icons/calendar.gif", 
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true,
				beforeShow: function(inpout, inst){
					dateBeforeChange = $(this).attr("value");
				}
			}
		));
		setInitEventPanel();
	}
}

function loadPannelReservation(dateNow){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/reservation/pannelReservation.php",
			async: false,
			type: "POST",
			data: ({dateNow:dateNow}),
			success: function(data){
				$("#contentBottomPannelReservation").empty();
				$("#contentBottomPannelReservation").html(data);
				
				loadDivSectionByDate(dateNow);
			}
		});
		$('#txt_date_reservation').datepicker($.extend({}, 
			$.datepicker.regional[DATEPICKER_LANG], {
				dateFormat: "yy-mm-dd", 
				showOn: "focus", 
				yearRange: '-0:+1',
				minDate: '0',
				buttonImage: "gestion/images/icons/calendar.gif", 
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true,
				beforeShow: function(inpout, inst){
					dateBeforeChange = $(this).attr("value");
				}
			}
		));
	}
}


function showSectionOfContact(uid){
	
}

function loadFromPanelCont(uid,specialType){
	$('.bloc_person').removeClass('bloc_person_selected');
	$('.section_box').removeClass('section_selected');
	if(uid == 0){
		resetFormPanel();
		$(".btnSave").attr('id','uid-0');
		if(specialType == 1){
			$("#chk_confirmed").attr("checked","checked");
		}
		synchroniserPanels();
	}else{
		$("#formulaire_client").empty();
		$('#cont-'+uid+'').addClass('bloc_person_selected');
		$.ajax({
			url: "gestion/ajax/reservation/loadFromPanelContact.php",
			async: false,
			type: "POST",
			data: ({reservation:uid}),
			success: function(data){
				$("#formulaire_client").empty();
				$("#formulaire_client").html(data);
				viewSectionFromContact();
				synchroniserPanels();
			}
		});
	}
}

/* À faire après un save ou après un load */
function synchroniserPanels(){
	$('#txt_client_name_verif').attr('value',$('#txt_client_name').attr('value'));
	$('#txt_client_lastname_verif').attr('value',$('#txt_client_lastname').attr('value'));
	$('#txt_client_email_verif').attr('value',$('#txt_client_email').attr('value'));
	$('#txt_client_phone_verif').attr('value',$('#txt_client_phone').attr('value'));
	$('#txt_client_reservation_verif').attr('value',$('#txt_client_reservation').attr('value'));
	
	
	/*A COMPLETER*/
}

function viewSectionFromContact(){
	$('.section_selected').removeClass("section_selected");
	
	var listSections = $('#txt_client_reservation').attr('value');
	var tabSections = listSections.split('-');
	
	for(var i=0;i<tabSections.length;i++){
		$('#sectionId-'+tabSections[i]+'').addClass("section_selected");
	}
}

function loadDivSectionByDate(date){
	$("#list_reserved_person").empty();
	$.ajax({
		url: "gestion/ajax/reservation/loadDivReservedPerson.php",
		async: false,
		type: "POST",
		data: ({date:date}),
		success: function(data){
			$("#list_reserved_person").empty();
			$("#list_reserved_person").html(data);
		}
	});
	$("#list_waiting_person").empty();
	$.ajax({
		url: "gestion/ajax/reservation/loadDivWaitingPerson.php",
		async: false,
		type: "POST",
		data: ({date:date}),
		success: function(data){
			$("#list_waiting_person").empty();
			$("#list_waiting_person").html(data);
		}
	});
	
	$("#id_map_box").empty();
	$("#id_map_box").html(LOADING_PANEL);
	$.ajax({
		url: "gestion/ajax/reservation/loadDivSectionByDay.php",
		async: false,
		type: "POST",
		data: ({date:date}),
		success: function(data){
			$('.blank_loading').fadeOut('slow',function(){
				$("#id_map_box").empty();
				$("#id_map_box").html(data);
				
				
				$(".section_box").mouseover(function(){
					
					var id = $(this).attr('id');
					var tabId = id.split('-');
					// alert('Allo toi !' + tabId[1]);
				}); 
				
				$('.section_box').click(function(){
					if($(this).hasClass("section_selected")){
						$(this).removeClass("section_selected");
						addOrRemoveSectionSelection($(this));
						/*A COMPLETER*/
					}else{
						$(this).addClass("section_selected");
						addOrRemoveSectionSelection($(this));
						/*A COMPLETER*/
					}
				});
			});
		}
	});
	
	resetFormPanel();
	synchroniserPanels();
}

function resetFormPanel(){
	$(':input','#formulaire_client')
		.not(':button, :submit, :reset, :hidden')
		.val('')
		.removeAttr('checked')
		.removeAttr('selected');
}

function addOrRemoveSectionSelection(element){
	var uid = element.attr("id");
	var tabUid = uid.split("-");
	var goodUid = tabUid[1];
	
	var txtUid = $('#txt_client_reservation').attr('value');
	
	var existTabUid = txtUid.split("-");
	
	if(existTabUid.in_array(goodUid) == -1){
		existTabUid.push(goodUid);	
	}else{
		var pos = existTabUid.in_array(goodUid);
		existTabUid[pos] = '';
	}
	var newArr = [];
	existTabUid.sort(function(a,b){return a - b});
	for(var o=0;o<existTabUid.length;o++){
		if(existTabUid[o]!=''){
			newArr.push(existTabUid[o]);
		}
	}
	
	var newTxtUid = newArr.join("-");
	
	$('#txt_client_reservation').attr('value',newTxtUid);
}


function verifChangementPanelReservation(){
	var modif = false;
	
	if($('#txt_client_name_verif').attr('value') != $('#txt_client_name').attr('value'))
		modif = true;
	if($('#txt_client_lastname_verif').attr('value') != $('#txt_client_lastname').attr('value'))
		modif = true;
	if($('#txt_client_email_verif').attr('value') != $('#txt_client_email').attr('value'))
		modif = true;
	if($('#txt_client_phone_verif').attr('value') != $('#txt_client_phone').attr('value'))
		modif = true;
	if($('#txt_client_reservation_verif').attr('value') != $('#txt_client_reservation').attr('value'))
		modif = true;
	/*A COMPLETER*/
	
	return modif;
}

/*END RESERVATION*/

/*START SONG*/
var gridSongs = null;
function createFormSong(uid){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/song/formSong.php",
			async: false,
			type: "POST",
			data: ({uid:uid}),
			success: function(data){
				$("#contentFormSong").empty();
				$("#contentFormSong").html(data);
			}
		});
		
		$('.btnSave').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			saveSong(uid[1],0);
		});
		
		$('.btnSaveClose').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			saveSong(uid[1],1);
		});
		
		$('.btnClose').click(function(){
			document.location.href = "index.php?id="+PAGE_LIST_SONGS+"&L="+getLang();
		});
		
		$('.removeSongUpload').click(function(){
			$('#resultSongUpload').empty();
			$('#resultSongUpload').html('<input type="file" name="song" size="45" /><input type="submit" class="button" value="'+UPLOAD_BUTTON+'" />');
			$('#txtSong').attr('value','');
			return false;
		});
		
		$('form#uploadSong').ajaxForm({
			beforeSubmit: function(){
				$('#secretLoad').html('<img src="gestion/images/loading.gif" />');
				/*Loading*/
			},
			success: function(e) {
				if(e != '')
				{
					$('#secretLoad').empty();
					$('#resultSongUpload').empty();
					$('#resultSongUpload').html('<div><table cellpadding="0" cellspacing="0" border="0"><tr><td valign="middle"><a href="gestion/files/_temp/'+e+'" target="_blank">'+VIEW_SONG+'</a></td><td valign="middle" style="padding-left:5px;"><a href="" class="removeSongUpload"><img src="gestion/images/icons/delete.png" alt="'+DELETE_LINK+'" title="'+DELETE_LINK+'" border="0" /></a></td></tr></table></div>');
					$('#txtSong').attr('value',e);
					
					$('.removeSongUpload').click(function(){
						$('#resultSongUpload').empty();
						$('#resultSongUpload').html('<input type="file" name="song" size="45" /><input type="submit" class="button" value="'+UPLOAD_BUTTON+'" />');
						$('#txtSong').attr('value','');
						return false;
					});
				}
			}
		});
	}
}
function saveSong(uid, returnType){
	if(checkLogin()){
		if(validateFormSong()){
			$.ajax({
				url: "gestion/ajax/song/saveSong.php",
				async: false,
				type: "POST",
				data: ({
					uid:uid,
					title:$('#txtTitle').attr('value'),
					artist:$('#txtArtist').attr('value'),
					year:$('#txtYear').attr('value'),
					album:$('#txtAlbum').attr('value'),
					gender:$('#txtGender').attr('value'),
					song:$('#txtSong').attr('value')
				}),
				success: function(data){
					tabData = data.split("|");
					tabData[0] = parseInt(tabData[0]);
					if(tabData[0] == 0){
						if(returnType==1)
							document.location.href = 'index.php?id='+PAGE_LIST_SONGS+"&L="+getLang();
						else if(returnType==0)
							createFormSong(tabData[1]);
							
						$('#messageSongSuccess').show();
					}else{
						$('#messageSongError').show();
					}
				}
			});
		}
		else{
			$('#message_success').hide();
			$('#message_error').show();
		}
	}
}

function validateFormSong(){
	var song  = $('#txtSong').attr('value');
	var valid = true;
	
	if(song==''){
		valid = false;
		$('#errorSong').show();
	}
	else{
		$('#errorSong').hide();
	}
	
	return valid;
}
function deleteSong(uid){
	if(checkLogin()){
		$('#dialogDeleteSong').dialog({
			resizable: false,
			draggable: false,
			autoOpen: true,
			height:100,
			width:350,
			modal: true,
			close: function(ev, ui) {
				$(this).dialog("destroy");
			},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				"Non": function(){
					$(this).dialog('destroy');
				},
				"Oui": function() {
					$(this).dialog('destroy');
					$.ajax({
						url: "gestion/ajax/song/deleteSong.php",
						async: false,
						type: "POST",
						data: ({uid:uid}),
						success: function(data){
							gridSongs.update();
						}
					});
				}
			}
		});
	}
}
function loadListSongs(){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/loadGrid.php",
			async: false,
			type: "POST",
			data: ({name: 'gridSongs'}),
			success: function(data){
				var search = '';
				var sort = 0;
				var side = 'desc';
				var page = 1;
				var limit = 10;
				if(data != ''){
					var config = data.split('|');
					search = config[FD_GRID_SEARCH];
					sort = parseInt(config[FD_GRID_SORT]);
					side = config[FD_GRID_SIDE];
					page = parseInt(config[FD_GRID_PAGE]);
					limit = parseInt(config[FD_GRID_LIMIT]);
				}
				$('#contentListSongs').empty();
				$('#contentListSongs').fdGrid({
					lang: getLangName(),
					rows: limit,
					url: 'gestion/ajax/song/listSongs.php',
					configUrl: 'gestion/ajax/saveGrid.php',
					name: 'gridSongs',
					page: page,
					sortCol: sort,
					sortCols:[],
					sortOrder: side,
					filter: search,
					navBarAlign: 'left',
					navBarLocation: 'bottom',
					callback: function(g){
						gridSongs = g;
						setEventListSongs();
					}
				});
			}
		});
	}
}
function setEventListSongs(){
	var priority = $('#priority').attr('value');

	$(".changePriorityUpSong").click(function (){
		var id = $(this).attr('id');
		var uid = id.split('-');
		changePrioritySong(priority,uid[1],0);
		return false;
	});
	
	$(".changePriorityDownSong").click(function (){
		var id = $(this).attr('id');
		var uid = id.split('-');
		changePrioritySong(priority,uid[1],1);
		return false;
	});
	
	$(".changePrioritySong").click(function (){
		var id = $(this).attr('id');
		var uid = id.split('-');
		$('#priority').attr('value',uid[1]);
		gridSongs.update({priority:$('#priority').attr('value')});
		return false;
	});
	
	$(".exitPrioritySong").click(function (){
		var id = $(this).attr('id');
		var uid = id.split('-');
		$('#priority').attr('value','');																							   
		gridSongs.update({priority:$('#priority').attr('value')});
		return false;
	});
	
	$(".createFormSong").click(function (){
		var id = $(this).attr('id');
		var uid = id.split('-');
		if(uid[1]==0){
			document.location.href = "index.php?id="+PAGE_FORM_SONG+"&L="+getLang();
		}
		else{
			document.location.href = "index.php?id="+PAGE_FORM_SONG+"&uid="+uid[1]+"&L="+getLang();
		}
		return false;
	});
	
	
	$(".deleteSong").click(function (){
		var id = $(this).attr('id');
		var uid = id.split('-');
		deleteSong(uid[1]);
		return false;
	});
}

function changePrioritySong(uidFrom, uidTo, side){
	$.ajax({
		url: "gestion/ajax/song/changePrioritySong.php",
		async: false,
		type: "POST",
		data: ({uidFrom:uidFrom,uidTo:uidTo}),
		success: function(data){
			$('#priority').attr('value','');																							   
			gridSongs.update({priority:$('#priority').attr('value')});
		}
	});
}

/*END SONG*/

/*START ALBUM*/
var gridAlbums = null;
function createFormAlbum(uid){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/album/formAlbum.php",
			async: false,
			type: "POST",
			data: ({uid:uid}),
			success: function(data){
				$("#contentFormAlbum").empty();
				$("#contentFormAlbum").html(data);
			}
		});
		
		$('.btnSave').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			saveAlbum(uid[1],0);
		});
		
		$('.btnSaveClose').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			saveAlbum(uid[1],1);
		});
		
		$('.btnClose').click(function(){
			document.location.href = "index.php?id="+PAGE_LIST_ALBUMS+"&L="+getLang();
		});
		
		$('.deleteImage').click(function(){
			var uid = $(this).attr('id').split('-');
			$('#imageContainer-'+uid[1]).remove();
			return false;
		});
		
		$("#contentImages").sortable({
			placeholder: 'placeHolder'
		});
		$("#contentImages").disableSelection();
		
		$("#txtDate").datepicker($.extend({}, 
			$.datepicker.regional[DATEPICKER_LANG], {
				dateFormat: "yy-mm-dd", 
				showOn: "both", 
				yearRange: '-10:+10',
				buttonImage: "gestion/images/icons/calendar.gif", 
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true 
			}
		));
		
		$('#txtImages').uploadify({
			uploader: 'gestion/js/jquery/plugins/jquery.uploadify/uploadify.swf',
			script: 'gestion/js/jquery/plugins/jquery.uploadify/uploadify.php',
			folder: 'gestion/files/_temp/',
			cancelImg: 'gestion/js/jquery/plugins/jquery.uploadify/cancel.png',
			multi: true,
			auto: true,
			fileExt: '*.jpg',
			fileDesc: 'Image (*.jpg)',
			simUploadLimit: 2,
			buttonText: 'Parcourir',
			onComplete: function(event,queueID,fileObj,response,data){
				$.ajax({
					url: "gestion/ajax/thumb.php",
					data: ({width:100,height:100,image:'gestion/files/_temp/'+fileObj.name}),
					async: false,
					type: "POST",
					success: function(data){
						var nb = 0;
						$(".image").each(function(){										
							nb++;
						});
						
						var uid = nb + 1;
						$('#contentImages').append('<li id="imageContainer-'+uid+'" class="imageContainer"><table cellspacing="0" cellpadding="0" width="100%"><tr><td><img class="image" src="'+data+'" border="0"></td></tr><tr><td align="center"><a id="image-'+uid+'" class="deleteImage" href="">['+DELETE_LINK+']</a></td></tr></table></li>');
						
						$('.deleteImage').click(function(){
							var uid = $(this).attr('id').split('-');
							$('#imageContainer-'+uid[1]).remove();
							return false;
						});
					}
				});
			}
		});
	}
}
function saveAlbum(uid, returnType){
	if(checkLogin()){
		if(validateFormAlbum()){
			var titleFr = $('#txtTitleFr').attr('value');
			var titleEn = $('#txtTitleEn').attr('value');
			var date = $('#txtDate').attr('value');
			
			var images = [];
			$(".image").each(function(i){		
				var infos = $(this).attr('src').split('/');
				images[i] = infos[infos.length-1];
			});
		
			$.ajax({
				url: "gestion/ajax/album/saveAlbum.php",
				async: false,
				type: "POST",
				data: ({
					uid:uid,
					titleFr:titleFr,
					titleEn:titleEn,
					'images[]':images,
					date:date
				}),
				success: function(data){
					if(returnType==1){
						document.location.href = "index.php?id="+PAGE_LIST_ALBUMS+"&L="+getLang();
					}
					else if(returnType==0)
					{
						createFormAlbum(uid);
					}
						
					if(parseInt(data) != 0){
						$('#message_error').hide();
						$('#message_success').show();
					}
					else{
						$('#message_success').hide();
						$('#message_error').show();
					}
				}
			});
		}
		else{
			$('#message_success').hide();
			$('#message_error').show();
		}
	}
}
function validateFormAlbum(){
	var titleFr = $('#txtTitleFr').attr('value');
	var titleEn = $('#txtTitleEn').attr('value');
	var date = $('#txtDate').attr('value');
	
	var valid = true;
	
	if(titleFr==''){
		valid = false;
		$('#errorTitleFr').show();
	}
	else{
		$('#errorTitleFr').hide();
	}
	// if(titleEn==''){
		// valid = false;
		// $('#errorTitleEn').show();
	// }
	// else{
		// $('#errorTitleEn').hide();
	// }
	
	if(date==''){
		valid = false;
		$('#errorDate').show();
	}
	else{
		$('#errorDate').hide();
	}
	
	return valid;
}
function deleteAlbum(uid){
	if(checkLogin()){
		$('#dialogDeleteAlbum').dialog({
			resizable: false,
			draggable: false,
			autoOpen: true,
			height:100,
			width:350,
			modal: true,
			close: function(ev, ui) {
				$(this).dialog("destroy");
			},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				"Non": function(){
					$(this).dialog('destroy');
				},
				"Oui": function() {
					$(this).dialog('destroy');
					$.ajax({
						url: "gestion/ajax/album/deleteAlbum.php",
						async: false,
						type: "POST",
						data: ({uid:uid}),
						success: function(data){
							gridAlbums.update();
						}
					});
				}
			}
		});
	}
}
function loadListAlbums(){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/loadGrid.php",
			async: false,
			type: "POST",
			data: ({name: 'gridAlbums'}),
			success: function(data){
				var search = '';
				var sort = 1;
				var side = 'desc';
				var page = 1;
				var limit = 10;
				if(data != ''){
					var config = data.split('|');
					search = config[FD_GRID_SEARCH];
					sort = parseInt(config[FD_GRID_SORT]);
					side = config[FD_GRID_SIDE];
					page = parseInt(config[FD_GRID_PAGE]);
					limit = parseInt(config[FD_GRID_LIMIT]);
				}
				$('#contentListAlbums').empty();
				$('#contentListAlbums').fdGrid({
					lang: getLangName(),
					rows: limit,
					url: 'gestion/ajax/album/listAlbums.php',
					configUrl: 'gestion/ajax/saveGrid.php',
					name: 'gridAlbums',
					page: page,
					sortCol: sort,
					sortOrder: side,
					filter: search,
					navBarAlign: 'left',
					navBarLocation: 'bottom',
					callback: function(g){
						gridAlbums = g;
						setAlbumListAlbums();
					}
				});
			}
		});
	}
}
function setAlbumListAlbums(){
	$(".createFormAlbum").click(function (){
		var id = $(this).attr('id');
		var uid = id.split('-');
		if(uid[1]==0){
			document.location.href = "index.php?id="+PAGE_FORM_ALBUM+"&L="+getLang();
		}
		else{
			document.location.href = "index.php?id="+PAGE_FORM_ALBUM+"&uid="+uid[1]+"&L="+getLang();
		}
		return false;
	});
	
	$(".deleteAlbum").click(function (){
		var id = $(this).attr('id');
		var uid = id.split('-');
		deleteAlbum(uid[1]);
		return false;
	});
}
/*END ALBUM*/

/*START CONFIG*/
function createFormConfig(){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/config/formConfig.php",
			async: false,
			type: "POST",
			success: function(data){
				$("#contentFormConfig").empty();
				$("#contentFormConfig").html(data);

				$('.deleteHomeImage').click(function(){
					var id = $(this).attr('id');
					var uid = id.split('-');
					deleteHomeImage(uid[1]);
					return false;
				});
				
				$('.deletePageImage').click(function(){
					var id = $(this).attr('id');
					var uid = id.split('-');
					deletePageImage(uid[1]);
					return false;
				});
				
				$('.deleteHomeSong').click(function(){
					var id = $(this).attr('id');
					var uid = id.split('-');
					deleteHomeSong(uid[1]);
					return false;
				});
				
				$('#btnUpload').click(function(){
					if($('#file').attr('value') != ''){
						$('#btnUpload').attr('disabled','disabled');
						$('.message').hide();
					}
				});
				
				$('#btnUpload2').click(function(){
					if($('#file2').attr('value') != ''){
						$('#btnUpload2').attr('disabled','disabled');
						$('.message').hide();
					}
				});
				
				$('#btnUpload3').click(function(){
					if($('#file3').attr('value') != ''){
						$('#btnUpload3').attr('disabled','disabled');
						$('.message').hide();
					}
				});
				
				$('form#upload').ajaxForm({
					success: function(e) {
						if(e != '')
						{
							$('#btnUpload').removeAttr("disabled");
							$('#file').attr('value','');
							$('.message').hide();
								
							$.ajax({
								url: "gestion/ajax/thumb.php",
								data: ({width:100,height:100,image:'gestion/files/_temp/'+e}),
								async: false,
								type: "POST",
								success: function(data){
									var nb = 0;
									$(".homeImage").each(function(){										
										nb++;
									});
									
									var uid = nb + 1;
									var code = '<li class="homeImageContainer" id="homeImage-'+uid+'"><table cellspacing="0" cellpadding="0" width="100%"><tr><td><input class="homeImageValue" type="hidden" value="'+e+'"><img class="homeImage" src="'+data+'" border="0"></td></tr><tr><td align="center"><a class="deleteHomeImage" id="uid-'+uid+'" href="">['+DELETE_LINK+']</a></td></tr></table></li>';
									if(uid == 1){
										$('#homeGalleryContainer').empty();
										$('#homeGalleryContainer').append('<div align="center"><ul class="homeGallery" id="homeGallery"></ul></div>');
									}
									$('#homeGallery').append(code);
									
									
									$('.deleteHomeImage').click(function(){
										var id = $(this).attr('id');
										var uid = id.split('-');
										deleteHomeImage(uid[1]);
										return false;
									});
								}
							});
						}
					}
				});
				
				$('form#upload2').ajaxForm({
					success: function(e) {
						if(e != '')
						{
							$('#btnUpload2').removeAttr("disabled");
							$('#file2').attr('value','');
							$('.message').hide();
								
							$.ajax({
								url: "gestion/ajax/thumb.php",
								data: ({width:100,height:100,image:'gestion/files/_temp/'+e}),
								async: false,
								type: "POST",
								success: function(data){
									var nb = 0;
									$(".pageImage").each(function(){										
										nb++;
									});
									
									var uid = nb + 1;
									var code = '<li class="pageImageContainer" id="pageImage-'+uid+'"><table cellspacing="0" cellpadding="0" width="100%"><tr><td><input class="pageImageValue" type="hidden" value="'+e+'"><img class="pageImage" src="'+data+'" border="0"></td></tr><tr><td align="center"><a class="deletePageImage" id="uid-'+uid+'" href="">['+DELETE_LINK+']</a></td></tr></table></li>';
									if(uid == 1){
										$('#pageGalleryContainer').empty();
										$('#pageGalleryContainer').append('<div align="center"><ul class="pageGallery" id="pageGallery"></ul></div>');
									}
									$('#pageGallery').append(code);
									
									
									$('.deletePageImage').click(function(){
										var id = $(this).attr('id');
										var uid = id.split('-');
										deletePageImage(uid[1]);
										return false;
									});
								}
							});
						}
					}
				});
				
				$('form#upload3').ajaxForm({
					success: function(e) {
						if(e != '')
						{
							$('#btnUpload3').removeAttr("disabled");
							$('#file3').attr('value','');
							$('.message').hide();
							
							$.ajax({
								url: "gestion/ajax/mp3.php",
								data: ({file:'gestion/files/_temp/'+e}),
								async: false,
								type: "POST",
								success: function(data){
									var nb = 0;
									$(".homeSong").each(function(){										
										nb++;
									});
									
									var uid = nb + 1;
									var code = '<li class="homeSongContainer" id="song-'+uid+'"><table cellspacing="0" cellpadding="0" width="100%"><tr><td><input class="homeSongValue" type="hidden" value="'+e+'"><div class="homeSong">'+data+'</div></td></tr><tr><td align="center"><a class="deleteHomeSong" id="uid-'+uid+'" href="">['+DELETE_LINK+']</a></td></tr></table></li>';
									if(uid == 1){
										$('#playlist').empty();
										$('#playlist').append('<div align="center"><ul class="homePlaylist" id="homePlaylist"></ul></div>');
									}
									$('#homePlaylist').append(code);
									
									$('.deleteHomeSong').click(function(){
										var id = $(this).attr('id');
										var uid = id.split('-');
										deleteHomeSong(uid[1]);
										return false;
									});
								}
							});
						}
					}
				});
			}
		});
		
		$('.btnSave').click(function(){
			saveConfig();
		});
		
		$("#homePlaylist").sortable({
			placeholder: 'homePlaylistPlaceHolder'
		});
		$("#homePlaylist").disableSelection();
		
		
		/*EME*/
		$('.deleteExternalMessengerBanner').click(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			deleteExternalMessengerBanner(uid[1]);
			return false;
		});
		
		$('#btnUploadExternalMessengerBanner').click(function(){
			if($('#fileExternalMessengerBanner').attr('value') != ''){
				$('#btnUploadExternalMessengerBanner').attr('disabled','disabled');
				$('.message').hide();
			}
		});
		
		$('form#uploadExternalMessengerBanner').ajaxForm({
			success: function(e) {
				if(e != '')
				{
					$('#btnUploadExternalMessengerBanner').removeAttr("disabled");
					$('#fileExternalMessengerBanner').attr('value','');
					$('.message').hide();
					
					$.ajax({
						url: "gestion/ajax/thumb.php",
						data: ({width:250,height:50,image:'gestion/files/_temp/'+e}),
						async: false,
						type: "POST",
						success: function(data){
							var nb = 0;
							$(".eme_banner").each(function(){										
								nb++;
							});
							
							var uid = nb + 1;
							var code = '<li class="eme_bannerContainer" id="banner-'+uid+'"><table cellspacing="0" cellpadding="0" width="100%"><tr><td><input class="eme_bannerValue" type="hidden" value="'+e+'"><img class="eme_banner" src="'+data+'" border="0"></td></tr><tr><td align="center"><a class="deleteExternalMessengerBanner" id="uid-'+uid+'" href="">['+DELETE_LINK+']</a></td></tr></table></li>';
							if(uid == 1){
								$('#eme_BannersContainer').empty();
								$('#eme_BannersContainer').append('<div align="center"><ul class="eme_bannersGallery" id="eme_bannersGallery"></ul></div>');
							}
							$('#eme_bannersGallery').append(code);
							
							$('.deleteExternalMessengerBanner').click(function(){
								var id = $(this).attr('id');
								var uid = id.split('-');
								deleteExternalMessengerBanner(uid[1]);
								return false;
							});
						}
					});
				}
			}
		});
		
		$("#eme_bannersGallery").sortable({
			placeholder: 'eme_bannerPlaceHolder'
		});
		$("#eme_bannersGallery").disableSelection();
		/*EME*/
	}
}
function saveConfig(){
	if(checkLogin()){
		var songs = [];
		var nb = 0;
		$(".homeSongValue").each(function(){	
			songs[nb] = $(this).attr('value');
			nb++;
		});
		
		var externalMessengerBanners = [];
		var nb = 0;
		$(".eme_bannerValue").each(function(){	
			externalMessengerBanners[nb] = $(this).attr('value');
			nb++;
		});
		
		var event = $('#optEvent').attr('value');
		var upcomingEvent1 = $('#optUpcomingEvent1').attr('value');
		var upcomingEvent2 = $('#optUpcomingEvent2').attr('value');
		
		var mailVip = $('#txt_mail_vip').attr('value');
		var mailLimo = $('#txt_mail_limo').attr('value');
		var mailHotel = $('#txt_mail_hotel').attr('value');
		
		if(validateFormConfig()){
			$.ajax({
				url: "gestion/ajax/config/saveConfig.php",
				data: ({
					'songs[]':songs,
					'externalMessengerBanners[]':externalMessengerBanners,
					event:event,
					upcomingEvent1:upcomingEvent1,
					upcomingEvent2:upcomingEvent2,
					mailVip:mailVip,
					mailLimo:mailLimo,
					mailHotel:mailHotel
				}),
				async: false,
				type: "POST",
				success: function(data){
					createFormConfig();
					$('#message_error').hide();
					$('#message_success').show();
				}
			});
		}
		else{
			$('#message_success').hide();
			$('#message_error').show();
		}
	}
}
function validateFormConfig(){
	var valid = true;
	return valid;
}
function deleteHomeSong(uid){
	if(checkLogin()){
		$('#song-'+uid).remove();
		
		var nb = 0;
		$(".homeSong").each(function(){										
			nb++;
		});
		if(nb == 0){
			$('#playlist').empty();
			$('#playlist').html('<div class="homePlaylist" id="homePlaylist" align="center">Il n\'y a aucune chanson présentement</div><input type="hidden" id="txtSongs" value="">');
		}
	}
}
function deleteExternalMessengerBanner(uid){
	if(checkLogin()){
		$('#banner-'+uid).remove();
		
		var nb = 0;
		$(".eme_banner").each(function(){										
			nb++;
		});
		if(nb == 0){
			$('#eme_bannersGallery').empty();
			$('#eme_bannersGallery').html('Il n\'y a aucune bannière présentement');
		}
	}
}
/*END CONFIG*/

/*START EME*/
var PAGE_EXTERNAL_MESSENGER = 127;

function createDisplayExternalMessenger(){
	$.ajax({
		url: "gestion/ajax/eme/displayExternalMessenger.php",
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplayExternalMessenger").empty();
			$("#contentDisplayExternalMessenger").html(data);
			
			$(':radio[name="typeRecipient"]').change(function(){
				$('#errorRecipient').hide();
				switch(parseInt($(this).attr('value'))){
					case 0:
						$('#contactRecipient').show();
						$('#subscriberRecipient').hide();
						$('#otherRecipient').hide();
						break;
					case 1:
						$('#contactRecipient').hide();
						$('#subscriberRecipient').show();
						$('#otherRecipient').hide();
						break;
					case 2:
						$('#contactRecipient').hide();
						$('#subscriberRecipient').hide();
						$('#otherRecipient').show();
						break;
				}
			});
			
			$('#chkAllContacts').change(function(){
				$('#errorRecipient').hide();
				if($(this).attr('checked')){
					$('#listContacts').hide();
				}
				else{
					$('#listContacts').show();
				}
			});
			
			$('#chkAllSubscribers').change(function(){
				$('#errorRecipient').hide();
				if($(this).attr('checked')){
					$('#listSubscribers').hide();
				}
				else{
					$('#listSubscribers').show();
				}
			});
			
			$('#optContacts').change(function(){
				$('#errorRecipient').hide();
				if($(this).attr('value') != 0){
					if(validateRecipient($(this).attr('value'))){
						$('#resultRecipients').append('<div class="recipient eme_recipient" id="recipient-'+$(this).attr('value')+'">- '+$("#optContacts option:selected").text()+'</a><a href="" class="removeRecipient"><img class="eme_textMiddle" src="gestion/images/icons/delete.png" alt="'+DELETE_LINK+'" title="'+DELETE_LINK+'" border="0" /></a></div>');
						
						$('.removeRecipient').click(function(){
							$(this).parent().remove();
							return false;
						});
					}
				}
				$(this).attr('value',0);
			});
			
			$('#optGroups').change(function(){
				var group = $(this).attr('value');
				$('#errorRecipient').hide();
				if($(this).attr('value') != 0){
					$.ajax({
						url: "gestion/ajax/eme/loadListUsers.php",
						data: ({group:group}),
						async: false,
						type: "POST",
						success: function(data){
							if(data != ''){
								var recipients = data.split('|');
								for(i=0;i<recipients.length;i++){
									var infos = recipients[i].split(' - ');
									if(validateRecipient(infos[0])){
										$('#resultRecipients').append('<div class="recipient eme_recipient" id="recipient-'+infos[0]+'">- '+infos[1]+'</a><a href="" class="removeRecipient"><img class="eme_textMiddle" src="gestion/images/icons/delete.png" alt="'+DELETE_LINK+'" title="'+DELETE_LINK+'" border="0" /></a></div>');
							
										$('.removeRecipient').click(function(){
											$(this).parent().remove();
											return false;
										});
									}
								}
							}
						}
					});
				}
				$(this).attr('value',0);
			});
			
			$('form#uploadFiles').ajaxForm({
				success: function(e){
					if(e != ''){
						$('#resultFilesUpload').append('<div>- <a class="file" href="gestion/files/_temp/'+e+'" target="_blank">'+e+'</a><a href="" class="removeFile"><img class="eme_textMiddle" src="gestion/images/icons/delete.png" alt="'+DELETE_LINK+'" title="'+DELETE_LINK+'" border="0" /></a></div>');
						$('#file').attr('value','');
						
						$('.removeFile').click(function(){
							$(this).parent().remove();
							return false;
						});
					}
				}
			});
			
			$(':radio[name="typeRecipient"]:first').attr('checked','checked');
			$(':radio[name="typeRecipient"]:first').change();
			
			$(':radio[name="banner"]:first').attr('checked','checked');
			$(':radio[name="banner"]:first').change();
			
			$('#txtMessage').wysiwyg();
			
			$('#btnSend').click(function(){
				sendExternalMessage();
			});
		}
	});
}
function validateRecipient(recipient){
	var valid = true;
	
	$('.recipient').each(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		if(recipient == uid[1]){
			valid = false;
		}
	});
	
	return valid;
}
function validateExternalMessage(){
	var typeRecipient = $(':radio[name="typeRecipient"]:checked').attr('value');
	var title = $('#txtTitle').attr('value');
	var message = $('#txtMessage').attr('value');
	var lang = $('#optLangs').attr('value');
	
	var recipients = [];
	if(typeRecipient == 0 && !$('#chkAllContacts').attr('checked')){
		$('.recipient').each(function(){
			var id = $(this).attr('id');
			var uid = id.split('-');
			recipients[recipients.length] = uid[1];
		});
	}
	else if(typeRecipient == 2){
		recipients = $('#txtRecipients').attr('value');
	}
	
	var valid = true;
	
	if(title==''){
		valid = false;
		$('#errorTitle').show();
	}
	else{
		$('#errorTitle').hide();
	}
	if(message==''){
		valid = false;
		$('#errorMessage').show();
	}
	else{
		$('#errorMessage').hide();
	}
	if(typeRecipient == 0 && !$('#chkAllContacts').attr('checked')){
		if(recipients.length == 0){
			valid = false;
			$('#errorRecipient').show();
		}
		else{
			$('#errorRecipient').hide();
		}
	}
	else if(typeRecipient == 1 && !$('#chkAllSubscribers').attr('checked')){
		if(lang == 0){
			valid = false;
			$('#errorRecipient').show();
		}
		else{
			$('#errorRecipient').hide();
		}
	}
	else if(typeRecipient == 2){
		if(recipients == ''){
			valid = false;
			$('#errorRecipient').show();
		}
		else{
			$('#errorRecipient').hide();
		}
	}
	
	return valid;
}
function sendExternalMessage(){
	if(checkLogin()){
		$('.eme_error').hide();
		$('.eme_success').hide();
		if(validateExternalMessage()){
			var typeRecipient = $(':radio[name="typeRecipient"]:checked').attr('value');
			var title = $('#txtTitle').attr('value');
			var message = $('#txtMessage').attr('value');
			
			var banner = '';
			if($(':radio[name="banner"]:checked').attr('value') != 0){
				banner = $('#banner-'+$(':radio[name="banner"]:checked').attr('value')).attr('value');
			}

			var langs = [];
			if(typeRecipient == 1){
				if($('#chkAllSubscribers').attr('checked')){
					$('#optLangs option').each(function(){
						if($(this).attr('value') != 0){
							langs[langs.length] = $(this).attr('value');
						}
					});
				}
				else{
					if($('#optLangs').attr('value') != 0){
						langs[langs.length] = $('#optLangs').attr('value');
					}
				}
			}
			
			var recipients = [];
			if(typeRecipient == 0 && !$('#chkAllContacts').attr('checked')){
				$('.recipient').each(function(){
					var id = $(this).attr('id');
					var uid = id.split('-');
					recipients[recipients.length] = uid[1];
				});
			}
			else if(typeRecipient == 0 && $('#chkAllContacts').attr('checked')){
				$('#optContacts option').each(function(){
					if($(this).attr('value') != 0){
						recipients[recipients.length] = $(this).attr('value');
					}
				});
			}
			else if(typeRecipient == 2){
				recipients = $('#txtRecipients').attr('value').split(';');
			}

			var files  = [];
			$('.file').each(function(){
				var file = $(this).attr('href').split('/');
				files[files.length] = file[file.length-1];
			});
			
			$.ajax({
				url: "gestion/ajax/eme/sendExternalMessage.php",
				async: false,
				type: "POST",
				data: ({
					typeRecipient:typeRecipient,
					banner:banner,
					title:title,
					message:message,
					'langs[]':langs,
					'recipients[]':recipients,
					'files[]':files
				}),
				success: function(data){			
					switch(parseInt(data)){
						case 0:
							$('#messageSuccess').show();
							break;
						case 1:
							$('#messageError').show();
							break;
					}
				}
			});
		}
	}
}
function createDisplaySubscribeMessenger(){
	$.ajax({
		url: "gestion/ajax/eme/displaySubscribeMessenger.php",
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplaySubscribeMessenger").empty();
			$("#contentDisplaySubscribeMessenger").html(data);
			
			$('.subscribeMessenger a').click(function(){
				$('#dialogSubscribeMessenger').dialog({
					resizable: false,
					draggable: false,
					autoOpen: true,
					closeOnEscape: true,
					minHeight: 120,
					height: 120,
					width: 380,
					modal: true,
					close: function() { $(this).dialog("destroy"); },
					open: function(){
						$('.eme_error').hide();
						$('.eme_success').hide();
					}
				});
				return false;
			});
			
			$('#btnSend').click(function(){
				saveSubscription();
			});
		}
	});
}
function validateSubscribtion(){
	var email = $('#txtEmail').attr('value');
	
	var valid = true;
	
	if(email==''){
		valid = false;
		$('#errorEmail').show();
		$('#errorEmailInvalid').hide();
	}
	else if(!isEmail(email)){
		valid = false;
		$('#errorEmail').hide();
		$('#errorEmailInvalid').show();
	}
	else{
		$('#errorEmail').hide();
		$('#errorEmailInvalid').hide();
	}
	
	return valid;
}
function saveSubscription(){
	$('.eme_error').hide();
	$('.eme_success').hide();
	if(validateSubscribtion()){
		var email = $('#txtEmail').attr('value');
		$.ajax({
			url: "gestion/ajax/eme/saveSubscription.php",
			data: ({
				email:email
			}),
			async: false,
			type: "POST",
			success: function(data){
				switch(parseInt(data)){
					case 0:
						$('#txtEmail').attr('value','');
						$('#messageSuccess').show();
						break;
					case 1:
						$('#messageError').show();
						break;
					case 2:
						$('#errorEmailExist').show();
						break;
				}
			}
		});
	}
}
function createDisplayUnsubscribeMessenger(uid,key){
	$.ajax({
		url: "gestion/ajax/eme/displayUnsubscribeMessenger.php",
		data: ({uid:uid,key:key}),
		async: false,
		type: "POST",
		success: function(data){
			$("#contentDisplayUnsubscribeMessenger").empty();
			$("#contentDisplayUnsubscribeMessenger").html(data);
			deleteSubscription();
		}
	});
}
function deleteSubscription(){
	var uid = $('#uid').attr('value');
	var key = $('#key').attr('value');
	
	$('.eme_error').hide();
	$('.eme_success').hide();
	$.ajax({
		url: "gestion/ajax/eme/deleteSubscription.php",
		data: ({uid:uid,key:key}),
		async: false,
		type: "POST",
		success: function(data){
			switch(parseInt(data)){
				case 0:
					$('#messageSuccess').show();
					break;
				case 1:
					$('#messageError').show();
					break;
			}
		}
	});
}
/*END EME*/

/*START EGU*/
var PAGE_FORM_LOGIN = 103;
var PAGE_FORM_CONTACT = 113;
var PAGE_FORM_GROUP = 115;
var PAGE_LIST_CONTACTS = 114;
var PAGE_LIST_GROUPS = 116;
var PAGE_VIEW_CONTACT = 117;

function checkLogin(){
	var value = false;
	$.ajax({
		url: "gestion/ajax/egu/login/doCheckLogin.php",
		async: false,
		type: "POST",
		success: function(data){
			if(data == 0){
				doDisconnect();
			}
			else{
				value = true;
			}
		}
	});
	return value;
}

function createFormLogin(){
	var pageId = $('#pageId').attr('value');
	var userId = $('#userId').attr('value');
	var redirect_url = jQuery.url.attr("source");
	
	$.ajax({
		url: "gestion/ajax/egu/login/formLogin.php",
		data: ({pageId:pageId,redirect_url:redirect_url}),
		async: false,
		type: "POST",
		success: function(data){
			$("#contentFormLogin").empty();
			$("#contentFormLogin").html(data);
			
			$('#txtUserLogin').focus();
	
			$('#txtPasswordLogin').keypress(function(e){
				var code;
				if(!e)
					var e = window.event;
				if(e.keyCode) 
					code = e.keyCode;
				else if(e.which) 
					code = e.which;	
				if(code==13)
					doLogin();
			});
			
			$('#submit').click(function(){
				doLogin();
			});
		}
	});
}

function createFormConnected(){
	if(checkLogin()){
		var pageId = $('#pageId').attr('value');
		var userId = $('#userId').attr('value');

		$.ajax({
			url: "gestion/ajax/egu/login/formConnected.php",
			data: ({pageId:pageId,userId:userId}),
			async: false,
			type: "POST",
			success: function(data){
				$("#contentFormConnected").empty();
				$("#contentFormConnected").html(data);
				
				$('#disconnect').click(function(){
					doDisconnect();
					return false;
				});
				
				$.jFastMenu("#menu");
			}
		});
	}
}

function createFormForgotPassword(){
	$.ajax({
		url: "gestion/ajax/egu/login/formForgotPassword.php",
		async: false,
		type: "POST",
		success: function(data){
			$("#contentFormForgotPassword").empty();
			$("#contentFormForgotPassword").html(data);
			
			$('#btnForgotPassword').click(function(){
				doForgotPassword();
			});
		}
	});
}

function createFormResendActivation(){
	$.ajax({
		url: "gestion/ajax/egu/login/formResendActivation.php",
		async: false,
		type: "POST",
		success: function(data){
			$("#contentFormResendActivation").empty();
			$("#contentFormResendActivation").html(data);
			
			$('#btnResendActivation').click(function(){
				doResendActivation();
			});
		}
	});
}

function createFormActivation(uid,key){
	$.ajax({
		url: "gestion/ajax/egu/login/formActivation.php",
		data: ({uid:uid,key:key}),
		async: false,
		type: "POST",
		success: function(data){
			$("#contentFormActivation").empty();
			$("#contentFormActivation").html(data);
			doActivation();
		}
	});
}

function createFormRegister(){
	var pageId = $('#pageId').attr('value');
	
	$.ajax({
		url: "gestion/ajax/egu/login/formRegister.php",
		data: ({pageId:pageId}),
		async: false,
		type: "POST",
		success: function(data){
			$("#contentFormRegister").empty();
			$("#contentFormRegister").html(data);
			
			$('#btnRegister').click(function(){
				doRegister();
			});
		}
	});
}


function createFormProfil(){
	if(checkLogin()){
		var userId = $('#userId').attr('value');
		
		$.ajax({
			url: "gestion/ajax/egu/contact/formProfil.php",
			data: ({uid:userId}),
			async: false,
			type: "POST",
			success: function(data){	
				$("#contentFormProfil").empty();
				$("#contentFormProfil").html(data);
				
				$('.btnSave').click(function(){
					var id = $(this).attr('id');
					var uid = id.split('-');
					saveProfil(uid[1]);
				});
			}
		});
	}
}

var gridContacts = null;
var returnType = 0;
var returnUid = 0;

function loadListContacts(group){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/loadGrid.php",
			async: false,
			type: "POST",
			data: ({name: 'gridContacts'}),
			success: function(data){
				var search = '';
				var sort = 0;
				var side = 'asc';
				var page = 1;
				var limit = 10;
				if(data != ''){
					var config = data.split('|');
					search = config[0];
					sort = parseInt(config[1]);
					side = config[2];
					page = parseInt(config[3]);
					limit = parseInt(config[4]);
				}
				$('#contentListContacts').empty();
				$('#contentListContacts').fdGrid({
					lang: getLangName(),
					rows: limit,
					url: "gestion/ajax/egu/contact/listContacts.php?group="+group,
					configUrl: 'gestion/ajax/saveGrid.php',
					name: 'gridContacts',
					page: page,
					sortCol: sort,
					sortOrder: side,
					filter: search,
					navBarAlign: 'left',
					navBarLocation: 'bottom',
					callback: function(g){
						setEventListContacts();
						gridContacts = g;
					}
				});
			}
		});
	}
}

function loadListGroups(){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/loadGrid.php",
			async: false,
			type: "POST",
			data: ({name: 'gridGroups'}),
			success: function(data){
				var search = '';
				var sort = 0;
				var side = 'asc';
				var page = 1;
				var limit = 10;
				if(data != ''){
					var config = data.split('|');
					search = config[0];
					sort = parseInt(config[1]);
					side = config[2];
					page = parseInt(config[3]);
					limit = parseInt(config[4]);
				}
				$('#contentListGroups').empty();
				$('#contentListGroups').fdGrid({
					lang: getLangName(),
					rows: limit,
					url: "gestion/ajax/egu/group/listGroups.php",
					configUrl: 'gestion/ajax/saveGrid.php',
					name: 'gridGroups',
					page: page,
					sortCol: sort,
					sortOrder: side,
					filter: search,
					navBarAlign: 'left',
					navBarLocation: 'bottom',
					callback: function(){
						setEventListGroups();
					}
				});
			}
		});
	}
}

function loadListActivationRequests(){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/loadGrid.php",
			async: false,
			type: "POST",
			data: ({name: 'gridGroups'}),
			success: function(data){
				var search = '';
				var sort = 0;
				var side = 'asc';
				var page = 1;
				var limit = 10;
				if(data != ''){
					var config = data.split('|');
					search = config[0];
					sort = parseInt(config[1]);
					side = config[2];
					page = parseInt(config[3]);
					limit = parseInt(config[4]);
				}
				$('#contentListActivationRequests').empty();
				$('#contentListActivationRequests').fdGrid({
					lang: getLangName(),
					rows: limit,
					url: "gestion/ajax/egu/contact/listActivationRequests.php",
					configUrl: 'gestion/ajax/saveGrid.php',
					name: 'gridActivationRequests',
					page: page,
					sortCol: sort,
					sortOrder: side,
					filter: search,
					navBarAlign: 'left',
					navBarLocation: 'bottom',
					callback: function(){
						setEventListActivationRequests();
					}
				});
			}
		});
	}
}

function setEventListActivationRequests(){
	$('.acceptActivationRequest').click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		acceptActivationRequest(uid[1]);
		return false;
	});	
	
	$('.deleteActivationRequest').click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		deleteActivationRequest(uid[1]);
		return false;
	});	
}

function setEventListGroups(){
	$('.editGroup').click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		if(uid[1]==0){
			document.location.href = 'index.php?id='+PAGE_FORM_GROUP+"&L="+getLang();
		}
		else{
			document.location.href = 'index.php?id='+PAGE_FORM_GROUP+"&uid="+uid[1]+"&L="+getLang();
		}
		return false;
	});

	$('.deleteGroup').click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		deleteGroup(uid[1]);
		return false;
	});	

}

function setEventListContacts(){
	$('.viewContact').click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		if(uid[1]==0){
			document.location.href = 'index.php?id='+PAGE_VIEW_CONTACT+"&L="+getLang();
		}
		else{
			document.location.href = 'index.php?id='+PAGE_VIEW_CONTACT+"&uid="+uid[1]+"&L="+getLang();
		}
		return false;
	});

	$('.editContact').click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		if(uid[1]==0){
			document.location.href = 'index.php?id='+PAGE_FORM_CONTACT+"&L="+getLang();
		}
		else{
			document.location.href = 'index.php?id='+PAGE_FORM_CONTACT+"&uid="+uid[1]+"&L="+getLang();
		}
		return false;
	});

	$('.deleteContact').click(function(){
		var id = $(this).attr('id');
		var uid = id.split('-');
		deleteContact(uid[1]);
		return false;
	});

	$('#groups').change(function(){
		var group = $('#groups').attr('value');
		loadListContacts(group);
	});
}

function createFormGroup(uid){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/egu/group/formGroup.php",
			data: ({uid:uid}),
			async: false,
			type: "POST",
			success: function(data){
				$('#contentFormGroup').html(data);

				$('.listGroup').click(function(){
					document.location.href = 'index.php?id='+PAGE_LIST_GROUPS+"&L="+getLang();
					return false;
				});
				
				$('.save:first').click(function(){
					var id = $(this).attr('id');
					var uid = id.split('-');
					returnType = 0;
					returnUid = uid[1];
					saveGroup(uid[1]);
					return false;
				});
		
				$('.save:last').click(function(){
					var id = $(this).attr('id');
					var uid = id.split('-');
					returnType = 1;
					returnUid = uid[1];
					saveGroup(uid[1]);
					return false;
				});
				
				$('.close').click(function(){
					document.location.href = 'index.php?id='+PAGE_LIST_GROUPS+"&L="+getLang();
					return false;
				});

			}
		});
	}
}

function createFormContact(uid){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/egu/contact/formContact.php",
			data: ({uid:uid}),
			async: false,
			type: "POST",
			success: function(data){
				$('#contentFormContact').html(data);
				$("#dateExpiration").datepicker($.extend({}, 
					$.datepicker.regional[DATEPICKER_LANG], { 
						dateFormat: "yy-mm-dd", 
						showOn: "both", 
						buttonImage: "images/icons/calendar.gif", 
						buttonImageOnly: true,
						changeMonth: true,
						changeYear: true 
					}
				));


				$('.listContact').click(function(){
					document.location.href = 'index.php?id='+PAGE_LIST_CONTACTS+"&L="+getLang();
					return false;
				});
				
				$('.save:first').click(function(){
					var id = $(this).attr('id');
					var uid = id.split('-');
					returnType = 0;
					returnUid = uid[1];
					saveContact(uid[1]);
					return false;
				});
		
				$('.save:last').click(function(){
					var id = $(this).attr('id');
					var uid = id.split('-');
					returnType = 1;
					returnUid = uid[1];
					saveContact(uid[1]);
					return false;
				});
				
				$('.close').click(function(){
					document.location.href = 'index.php?id='+PAGE_LIST_CONTACTS+"&L="+getLang();
					return false;
				});

			}
		});
	}
}

function acceptActivationRequest(uid){
	$('#dialogAccept').dialog({
			resizable: false,
			draggable: false,
			autoOpen: true,
			height:"auto",
			width:350,
			modal: true,
			close: function(ev, ui) {
					$(this).dialog("destroy");
				},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
				},
			buttons: {
				"Non": function(){
					$(this).dialog('destroy');
				},
				"Oui": function() {
					$(this).dialog('destroy');
					$.post("gestion/ajax/egu/contact/acceptActivationRequest.php", {uid:uid},function(data){
						loadListActivationRequests();
					});
				}
			}
		});
}

function saveGroup(uid){
	if(checkLogin()){
		var name = $('#name').attr('value');

		if(validateFormGroup()){
			$.ajax({
				url: "gestion/ajax/egu/group/saveGroup.php",
				data: ({uid:uid,name:name}),
				async: false,
				type: "POST",
				success: function(data){
					$('egu_message').addClass('egu_hidden');
					if(returnType==0){
						if(returnUid!=0)
							createFormGroup(returnUid);
					}
					else if(returnType==1)
						document.location.href = 'index.php?id='+PAGE_LIST_GROUPS+"&L="+getLang();
					
					switch(parseInt(data)){
						case 0:
							$('#messageSuccessSave').removeClass('egu_hidden');
							break;
						case 1:
							$('#messageSuccessModify').removeClass('egu_hidden');
							break;
					}
				}
			});
		}
	}
}

function validateFormGroup(){
	var name = $('#name').attr('value');
	var valid = true;
	
	$('.egu_message').addClass('egu_hidden');
	
	if(name == ''){
		valid = false;
		$('#errorEmptyName').removeClass('egu_hidden');
	}
	
	if(valid == false)
		$('#errorMessage').removeClass('egu_hidden');
	
	return valid;
}

function saveContact(uid){
	if(checkLogin()){
		var company = $('#company').attr('value');
		var firstname = $('#firstname').attr('value');
		var name = $('#name').attr('value');
		var username = $('#username').attr('value');
		var email = $('#email').attr('value');
		var password = $('#password').attr('value');
		var title = $('#title').attr('value');
		var fonction = $('#fonction').attr('value');
		var address = $('#address').attr('value');
		var zip = $('#zip').attr('value');
		var city = $('#city').attr('value');
		var country = $('#country').attr('value');
		var telephone1 = $('#telephone1').attr('value');
		var extension1 = $('#extension1').attr('value');
		var telephone2 = $('#telephone2').attr('value');
		var extension2 = $('#extension2').attr('value');
		var fax = $('#fax').attr('value');
		var link = $('#link').attr('value');
		var other = $('#other').attr('value');
		var disable = $('#disable').attr('value');
		
		var groups = [];
		var nb = 0;
		$(":checkbox[name='chkGroups[]']").each(function(){	
			if(this.checked){
				groups[nb] = this.value;
				nb++;
			}
		});

		if(validateFormContact()){
			$.ajax({
				url: "gestion/ajax/egu/contact/saveContact.php",
				data: ({uid:uid,company:company,firstname:firstname,name:name,username:username,email:email,password:password,title:title,fonction:fonction,country:country,address:address,zip:zip,city:city,country:country,telephone1:telephone1,extension1:extension1,telephone2:telephone2,extension2:extension2,fax:fax,link:link,disable:disable,other:other,'groups[]':groups}),
				async: false,
				type: "POST",
				success: function(data){
					$('.egu_message').hide();
					switch(parseInt(data)){
						case 0:
							if(returnType==0){
								if(returnUid!=0){
									createFormContact(returnUid);
								}
							}else if(returnType==1){
								document.location.href = 'index.php?id='+PAGE_LIST_CONTACTS+"&L="+getLang();
							}
							$('#messageContactSuccess').show();
							break;
						case 1:
							$('#messageContactError').show();
							break;
						case 2:
							$('#messageContactErrorMailExist').show();
							break;	
						case 3:
							$('#messageContactErrorUserExist').show();
							break;	
					}
				}
			});
		}
	}
}

function viewContact(uid){
	if(checkLogin()){
		$.ajax({
			url: "gestion/ajax/egu/contact/viewContact.php",
			data: ({uid:uid}),
			async: false,
			type: "POST",
			success: function(data){
				$('#contentViewContact').html(data);
				
				$('.listContact').click(function(){
					document.location.href = 'index.php?id='+PAGE_LIST_CONTACTS+"&L="+getLang();
					return false;
				});
			}
		});
	}
}

function deleteActivationRequest(uid){
	if(checkLogin()){
		$('#dialogDelete').dialog({
			resizable: false,
			draggable: false,
			autoOpen: true,
			height:"auto",
			width:350,
			modal: true,
			close: function(ev, ui) {
					$(this).dialog("destroy");
				},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
				},
			buttons: {
				"Non": function(){
					$(this).dialog('destroy');
				},
				"Oui": function() {
					$(this).dialog('destroy');
					$.post("gestion/ajax/egu/contact/deleteActivationRequest.php", {uid:uid},function(data){
						loadListActivationRequests();
					});
				}
			}
		});
	}
}


function deleteGroup(uid){
	if(checkLogin()){
		$('#dialog').dialog({
			resizable: false,
			draggable: false,
			autoOpen: true,
			height:"auto",
			width:350,
			modal: true,
			close: function(ev, ui) {
					$(this).dialog("destroy");
				},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
				},
			buttons: {
				"Non": function(){
					$(this).dialog('destroy');
				},
				"Oui": function() {
					$(this).dialog('destroy');
					$.post("gestion/ajax/egu/group/deleteGroups.php", {uid:uid},function(data){
						loadListGroups();
					});
				}
			}
		});
	}
}

function deleteContact(uid){
	if(checkLogin()){
		var group = $('#groups').attr('value');

		$('#dialog').dialog({
			resizable: false,
			draggable: false,
			autoOpen: true,
			height:"auto",
			width:350,
			modal: true,
			close: function(ev, ui) {
					$(this).dialog("destroy");
				},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
				},
			buttons: {
				"Non": function(){
					$(this).dialog('destroy');
				},
				"Oui": function() {
					$(this).dialog('destroy');
					$.post("gestion/ajax/egu/contact/deleteContacts.php", {uid:uid},function(data){
						if(gridContacts != null)
							gridContacts.update();
						else
							loadListContacts(group);
					});
				}
			}
		});
	}
}

function saveProfil(uid){
	if(checkLogin()){
		var company = $('#company').attr('value');
		var firstname = $('#firstname').attr('value');
		var name = $('#name').attr('value');
		var email = $('#email').attr('value');
		var pass = $('#pass').attr('value');
		var address = $('#address').attr('value');
		var zip = $('#zip').attr('value');
		var city = $('#city').attr('value');
		var telephone = $('#telephone').attr('value');
		var poste = $('#poste').attr('value');
		var fax = $('#fax').attr('value');
		
		if(validateFormProfil()){
			$.ajax({
				url: "gestion/ajax/egu/contact/saveProfil.php",
				data: ({uid:uid,company:company,firstname:firstname,name:name,email:email,pass:pass,address:address,zip:zip,city:city,telephone:telephone,poste:poste,fax:fax}),
				async: false,
				type: "POST",
				success: function(data){
					$('.egu_message').hide();
					switch(parseInt(data)){
						case 0:
							$('#messageProfilSuccess').show();
							break;
						case 1:
							$('#messageProfilError').show();
							break;
						case 2:
							$('#messageProfilErrorMailExist').show();
							break;	
					} 
				}
			});
		}
	}
}

function validateFormProfil(){
	var company = $('#company').attr('value');
	var firstname = $('#firstname').attr('value');
	var name = $('#name').attr('value');
	var email = $('#email').attr('value');
	var valid = true;
	
	$('.egu_message').addClass('egu_hidden');
	
	if(name==''){
		valid = false;
		$('#errorName').removeClass('egu_hidden');
	}else{
		$('#errorName').addClass('egu_hidden');
	}
	
	if(firstname==''){
		valid = false;
		$('#errorFirstName').removeClass('egu_hidden');
	}else{
		$('#errorFirstName').addClass('egu_hidden');
	}
	
	if(email==''){
		valid = false;
		$('#errorEmail').removeClass('egu_hidden');
	}else{
		$('#errorEmail').addClass('egu_hidden');
		if(isEmail(email)){
			$('#errorNotEmail').addClass('egu_hidden');
		}else{
			valid = false;
			$('#errorNotEmail').removeClass('egu_hidden');
		}
	}
	
	if(company==''){
		valid = false;
		$('#errorCompany').removeClass('egu_hidden');
	}else{
		$('#errorCompany').addClass('egu_hidden');
	}

	
	return valid;
}

function doLogin(){
	var user = $('#txtUserLogin').attr('value');
	var pass = $('#txtPasswordLogin').attr('value');
	
	if(validateFormLogin()){
		$.ajax({
			url: "gestion/ajax/egu/login/doLogin.php",
			data: ({user:user,pass:pass}),
			async: false,
			type: "POST",
			success: function(data){
				$('.egu_message').hide();
				var dataArray = data.split("|");
				switch(parseInt(dataArray[0])){
					case 0:
						var logintype = $('#logintype').attr('value');
						var pid = $('#pid').attr('value');
						var pageId = $('#pageId').attr('value');
						var redirect_url = $('#redirect_url').attr('value');
						if(validateFormLogin()){
							$.ajax({
								url: "index.php?id="+pageId+'&L='+getLang(),
								data: ({user:user,pass:pass,logintype:logintype,pid:pid,redirect_url:redirect_url}),
								async: false,
								type: "POST",
								success: function(data){
									$('#userId').attr('value',parseInt(dataArray[1]));
									if(pageId == PAGE_FORM_LOGIN){
										document.location.href = 'index.php?id='+parseInt(dataArray[2])+'&L='+getLang(); 
									}
									else{
										document.location.href = redirect_url+'&L='+getLang(); 
									}
								}
							});
						}
						break;
					case 1: 
						$('#messageLogin1').show();
						break;
					case 2: 
						$('#messageLogin2').show();
						break;	
					case 3: 
						$('#messageLogin3').show();
						break;	
				}
			}
		});
	}
}

function doDisconnect(){
	var logintype = $('#logintype').attr('value');
	var pid = $('#pid').attr('value');
	var pageId = $('#pageId').attr('value');
	
	$.ajax({
		url: "gestion/ajax/egu/login/doDisconnect.php",
		async: false,
		type: "POST",
		success: function(data){
			$.ajax({
				url: "index.php?id="+pageId+'&L='+getLang(),
				data: ({logintype:logintype,pid:pid}),
				async: false,
				type: "POST",
				success: function(data){
					$('#userId').attr('value',0);
					document.location.href = 'index.php?id='+PAGE_FORM_LOGIN+'&L='+getLang(); 
				}
			});
		}
	});
}

function doForgotPassword(){
	var user = $('#txtUserForgotPassword').attr('value');
	
	if(validateFormForgotPassword()){
		$.ajax({
			url: "gestion/ajax/egu/login/doForgotPassword.php",
			data: ({user:user}),
			async: false,
			type: "POST",
			success: function(data){
				switch(parseInt(data)){
					case 0:
						$('.egu_message'). addClass('egu_hidden');
						$('#messageForgotPasswordSuccess').removeClass('egu_hidden');
						$('#txtUserForgotPassword').attr('value','');
						break;
					case 1: 
						$('.egu_message'). addClass('egu_hidden');
						$('#messageForgotPasswordBadEmail').removeClass('egu_hidden');
						break;
				}
			}
		});
	}
}

function doResendActivation(){
	var user = $('#txtUserResendActivation').attr('value');
	
	if(validateFormResendActivation()){
		$.ajax({
			url: "gestion/ajax/egu/login/doResendActivation.php",
			data: ({user:user}),
			async: false,
			type: "POST",
			success: function(data){
				switch(parseInt(data)){
					case 0:
						/*Succès*/
						$('.egu_message').addClass('egu_hidden');
						$('#messageResendActivationSuccess').removeClass('egu_hidden');
						$('#txtUserResendActivation').attr('value','');
						break;
					case 1: 
						/*Courriel invalide*/
						$('.egu_message').addClass('egu_hidden');
						$('#messageResendActivationInvalidMail').removeClass('egu_hidden');
						break;
				}
			}
		});
	}
}

function doActivation(){
	var uid = $('#uid').attr('value');
	var key = $('#key').attr('value');
	
	$.ajax({
		url: "gestion/ajax/egu/login/doActivation.php",
		data: ({uid:uid,key:key}),
		async: false,
		type: "POST",
		success: function(data){
			switch(parseInt(data)){
				case 0:
					$('#messageActivation2').hide();
					$('#messageActivation1').show();
					break;
				case 1:
					$('#messageActivation1').hide();
					$('#messageActivation2').show();
					break;
			}
		}
	});
}

function doRegister(){
	var company = $('#company').attr('value');
	var name = $('#name').attr('value');
	var firstname = $('#firstname').attr('value');
	var email = $('#email').attr('value');
	var username = $('#email').attr('value');
	var password = $('#password').attr('value');
	var city = $('#city').attr('value');
	var address = $('#address').attr('value');
	var postal_code = $('#postal_code').attr('value');
	var country = $('#country').attr('value');
	var telephone1 = $('#telephone1').attr('value');
	var extension1 = $('#extension1').attr('value');
	if(validateFormRegister()){
		$.ajax({
			url: "gestion/ajax/egu/login/doRegister.php",
			data: ({company:company,
					name:name,
					firstname:firstname,
					password:password,
					username:username,
					email:email,
					city:city,
					address:address,
					postal_code:postal_code,
					telephone1:telephone1,
					country:country,
					extension1:extension1}),
			async: false,
			type: "POST",
			success: function(data){
				$('.egu_message').hide();
				switch(parseInt(data)){
					case 0:
						$('#company').attr('value','');
						$('#name').attr('value','');
						$('#firstname').attr('value','');
						$('#email').attr('value','');
						$('#password').attr('value','');
						$('#city').attr('value','');
						$('#address').attr('value','');
						$('#postal_code').attr('value','');
						$('#country').attr('value','');
						$('#telephone1').attr('value','');
						$('#extension1').attr('value','');
						$('#messageRegisterSuccess').show();
						break;
					case 1:	
						$('#errorRegister').show();
						break;
					case 2:	
						$('#errorEmailAlreadyExist').show();
						break;
				}
			}
		});
	}	
}

function validateFormLogin(){
	var user = $('#txtUserLogin').attr('value');
	var pass = $('#txtPasswordLogin').attr('value');
	var valid = true;
	
	if(user=='' || pass==''){
		valid = false;
		$('.egu_message').addClass('egu_hidden');
		$('#messageLogin').removeClass('egu_hidden');
	}
	
	if(valid){
		$('#messageLogin').addClass('egu_hidden');
	}
	
	return valid;
}

function validateFormForgotPassword(){
	var user = $('#txtUserForgotPassword').attr('value');
	var valid = true;
	
	if(user==''){
		valid = false;
		$('.egu_message').addClass('egu_hidden');
		$('#messageForgotPasswordEmptyEmail').removeClass('egu_hidden');
	}else{
		$('#messageForgotPasswordEmptyEmail').addClass('egu_hidden');
	}

	return valid;
}

function validateFormResendActivation(){
	var user = $('#txtUserResendActivation').attr('value');
	var valid = true;
	
	if(user==''){
		valid = false;
		$('.egu_message').addClass('egu_hidden');
		$('#messageResendActivationEmptyMail').removeClass('egu_hidden');
	}else{
		$('#messageResendActivationEmptyMail').addClass('egu_hidden');
	}

	return valid;
}

function validateFormRegister(){
	var company = $('#company').attr('value');
	var name = $('#name').attr('value');
	var firstname = $('#firstname').attr('value');
	var email = $('#email').attr('value');
	var password = $('#password').attr('value');
	var city = $('#city').attr('value');
	var address = $('#address').attr('value');
	var postal_code = $('#postal_code').attr('value');
	var country = $('#country').attr('value');
	var telephone1 = $('#telephone1').attr('value');
	
	var valid = true;
	
	$('.egu_message').addClass('egu_hidden');
	
	if(name==''){
		valid = false;
		$('#errorName').removeClass('egu_hidden');
	}
	else{
		$('#errorName').addClass('egu_hidden');
	}
	
	if(firstname==''){
		valid = false;
		$('#errorFirstName').removeClass('egu_hidden');
	}
	else{
		$('#errorFirstName').addClass('egu_hidden');
	}
	
	if(password==''){
		valid = false;
		$('#errorPassword').removeClass('egu_hidden');
	}
	else{
		$('#errorPassword').addClass('egu_hidden');
	}
	
	if(email==''){
		valid = false;
		$('#errorEmail').removeClass('egu_hidden');
	}
	else{
		$('#errorEmail').addClass('egu_hidden');
		if(isEmail(email)){
			$('#errorNotEmail').addClass('egu_hidden');
		}else{
			valid = false;
			$('#errorNotEmail').removeClass('egu_hidden');
		}
	}
	
	if(company==''){
		valid = false;
		$('#errorCompany').removeClass('egu_hidden');
	}
	else{
		$('#errorCompany').addClass('egu_hidden');
	}
	
	if(city==''){
		valid = false;
		$('#errorCity').removeClass('egu_hidden');
	}
	else{
		$('#errorCity').addClass('egu_hidden');
	}
	
	if(address==''){
		valid = false;
		$('#errorAddress').removeClass('egu_hidden');
	}
	else{
		$('#errorAddress').addClass('egu_hidden');
	}
	
	if(postal_code==''){
		valid = false;
		$('#errorPostal_code').removeClass('egu_hidden');
	}
	else{
		$('#errorPostal_code').addClass('egu_hidden');
	}
	
	if(country==''){
		valid = false;
		$('#errorCountry').removeClass('egu_hidden');
	}
	else{
		$('#errorCountry').addClass('egu_hidden');
	}
	
	if(telephone1==''){
		valid = false;
		$('#errorTelephone1').removeClass('egu_hidden');
	}
	else{
		$('#errorTelephone1').addClass('egu_hidden');
	}

	return valid;
}

function validateFormContact(){
	var name = $('#name').attr('value');
	var firstname = $('#firstname').attr('value');
	var valid = true;
	
	$('.egu_message').addClass('egu_hidden');
	
	if(name==''){
		valid = false;
		$('#errorName').removeClass('egu_hidden');
	}else{
		$('#errorName').addClass('egu_hidden');
	}
	
	if(firstname==''){
		valid = false;
		$('#errorFirstName').removeClass('egu_hidden');
	}else{
		$('#errorFirstName').addClass('egu_hidden');
	}
	
	if(valid == false)
		$('#messageError').removeClass('egu_hidden');

	return valid;
}
/*END EGU*/