var hovered;
var selected;
var bModif = false;
var timer = null;
var delai = 2*60*1000;

function ShowMsg(html,err) {
	msg = $("#message");
	msg.removeClass("messageInfo messageErreur");
	if (err) msg.addClass("messageErreur");
	else msg.addClass("messageInfo");
	msg.html(html);
	msg.slideDown("slow");
}

function HideMsg() {
	msg = $("#message");
	msg.hide();
}

function SelectOption(obj,value) {
	for (i=0; i<obj.options.length; i++) {
		opt = obj.options[i];
		opt.selected = (opt.value==value);
	}
}

function LoadOptions(select,tab,none) {
	if (none) s = "<option value='0'>Aucun</option>";
	else s = "";
	$.each(tab,function(i,obj) {
		s = s + "<option value='"+obj.id+"'>"+obj.code+"</option>";
	});
	select.html(s);    
}

function HideDetails() {
	$("#details2").hide();
	bModif = false;
	HideMsg();  
}

function ShowPilotInfos(json){
	document.fModif.idPilote.value = json.id;
	$("#modification #nomPilote").html(json.prenom+" "+json.nom);
}

function SetTitleClass(titre,c,libelle) {
	titre.removeClass('vert gris rouge violet noir').addClass(c);
	$("div",titre).html(libelle);
}

function GoToBottom() {
	
}

function ShowDetailsConsultation(pla){
	bModif = false;
	blocDetails = $("#details2");
	$("#modification",blocDetails).hide();
	$("#suppression",blocDetails).hide();
	bloc = $("#consultation",blocDetails);
	bloc.hide();
    
	titre = $(".titre",blocDetails);
	switch (pla.tip) {
		case "PIL":
			SetTitleClass(titre,'vert','Réservation pilote');
			// titre.css({backgroundImage:"url('/static/planning/barreVerte2.png')",color:'#000000'});
			// $("div",titre).html("Réservation pilote");
		break;
		case "INS":
			SetTitleClass(titre,'gris','Présence instructeur');
			// titre.css({backgroundImage:"url('/static/planning/barreGrise2.png')",color:'#000000'});
			// $("div",titre).html("Présence instructeur");
		break;
		case "AVN":
			SetTitleClass(titre,'rouge','Indisponibilité avion');
			// titre.css({backgroundImage:"url('/static/planning/barreRouge2.png')",color:'#000000'});
			// $("div",titre).html("Indisponibilité avion");
		break;
	}

	tab = pla.debut.split(",");
	$("#dateDebut",bloc).html(DateIsoToFr(tab[0]));
	$("#heureDebut",bloc).html(tab[1]);
	tab = pla.fin.split(",");
	$("#dateFin",bloc).html(DateIsoToFr(tab[0]));
	$("#heureFin",bloc).html(tab[1]);
	$("#aiSep", bloc).hide();
  
	if (pla.idPilote) {
		pil = pilotes[pla.idPilote];
		$("#codePilote", bloc).html(pil.code);
		$("#nomPilote", bloc).html(pil.nom);
		$("DIV.pilote", bloc).show();
	} else {
		$("DIV.pilote", bloc).hide();
	}

	avn = (pla.idAvion ? avions[pla.idAvion] : null);
	ins = (pla.idInstructeur ? instructeurs[pla.idInstructeur] : null);
	if (avn && ins) {
		s = "<table border='0' cellspacing='0' cellpadding='0' width='100%' class='dates'><tr>"
		  + "<td width='50%' align='right'>"+avn.code+"</td>"
		  + "<td>&nbsp;<img src='/static/planning/plusPlanning.png' style='vertical-align: middle'>&nbsp;</td>"
		  + "<td width='50%' align='left'>"+ins.code+"</td></tr></table>";
	} else {
		if (avn) s = avn.code;
		else s = ins.code;
	}
	$("#avionInst",bloc).html(s);
  
	$("#lienHisto",bloc).attr("href","infosPlage.php?id="+pla.id);
	if (admin || (pla.tip=="PIL")) {
		$("#lienSupprimer",bloc).attr("href","javascript:ShowDetailsSuppression(plages["+pla.id+"]); void(0)");
		$("#lienModifier",bloc).attr("href","javascript:ShowDetailsModification(plages["+pla.id+"]); void(0)");
		$("#lienSupprimer",bloc).show();
		$("#lienModifier",bloc).show();
	} else {
		$("#lienSupprimer",bloc).hide();
		$("#lienModifier",bloc).hide();
	}

	bloc.show();
	blocDetails.show();
	GoToBottom();
}

function ShowDetailsModification(pla,crea) {
	if (cMode && ((typeof idPiloteConnecte) == "undefined")) {
		alert ("Vous devez vous identifier\r\npour modifier une réservation.");
		return;
	}

	bModif = true;

	blocDetails = $("#details2");
	$("#consultation",blocDetails).hide();
	$("#suppression",blocDetails).hide();
	bloc = $("#modification",blocDetails);
	bloc.hide();

	titre = $(".titre",blocDetails);
	switch (pla.tip) {
		case "PIL":
			if (crea) {
				SetTitleClass(titre,'violet','Nouvelle réservation');
				// titre.css({backgroundImage:"url('/static/planning/barreViolette2.png')",color:'#000000'});
				// $("div",titre).html("Nouvelle réservation");
			} else {
				SetTitleClass(titre,'vert','Réservation pilote');
				// titre.css({backgroundImage:"url('/static/planning/barreVerte2.png')",color:'#000000'});
				// $("div",titre).html("Réservation pilote");
			}
			$("#avion",bloc).show();
			$("#aiSep",bloc).show();
			$("#instructeur",bloc).show();
		break;
		case "INS":
			SetTitleClass(titre,'gris',crea?"Nouvelle présence inst.":"Présence instructeur");
			// titre.css({backgroundImage:"url('/static/planning/barreGrise2.png')",color:'#000000'});
			// $("div",titre).html();
			$("#avion",bloc).hide();
			$("#aiSep",bloc).hide();
			$("#instructeur",bloc).show();
		break;
		case "AVN":
			SetTitleClass(titre,'rouge',crea?"Nouvelle indispo. avion":"Indisponibilité avion");
			// titre.css({backgroundImage:"url('/static/planning/barreRouge2.png')",color:'#000000'});
			// $("div",titre).html();
			$("#avion",bloc).show();
			$("#aiSep",bloc).hide();
			$("#instructeur",bloc).hide();
		break;
	} 
  
	tab = pla.debut.split(",");
	document.fModif.dateDebut.value = DateIsoToFr(tab[0]);
	if (tab[1].length==4) tab[1] = "0"+tab[1];
	SelectOption(document.fModif.heureDebut,tab[1]);  
	tab = pla.fin.split(",");
	document.fModif.dateFin.value = DateIsoToFr(tab[0]);
	if (tab[1].length==4) tab[1] = "0"+tab[1];
	SelectOption(document.fModif.heureFin,tab[1]);
	if (pla.idPilote) {
		if (crea) {
			document.fModif.idPilote.value = idPiloteConnecte;
			document.fModif.codePilote.value = codePiloteConnecte;
			$("#nomPilote",bloc).html(nomPiloteConnecte);
		} else {
			pil = pilotes[pla.idPilote];
			document.fModif.idPilote.value = pil.id;
			document.fModif.codePilote.value = pil.code;
			$("#nomPilote",bloc).html(pil.nom);
		}
		$("DIV.pilote", bloc).show();
	} else {
		$("DIV.pilote", bloc).hide();
	} 
  
	if (pla.tip != "INS") {
		LoadOptions($("#avion", bloc), avions, false);
		SelectOption($("#avion", bloc).get(0),pla.idAvion);
	}
	if (pla.tip != "AVN") {
		LoadOptions($("#instructeur", bloc), instructeurs, true);
		SelectOption($("#instructeur", bloc).get(0),pla.idInstructeur);
	}

	document.fModif.idPlage.value = pla.id;
	document.fModif.tip.value = pla.tip;
	if (crea) {
		document.fModif.op.value = "creationPlage";
		$("#lienAnnuler",bloc).attr("href","javascript:HideDetails(); void(0)");
	} else { 
		document.fModif.op.value = "modificationPlage";
		$("#lienAnnuler",bloc).attr("href","javascript:ShowDetailsConsultation(plages["+pla.id+"]); void(0)");
	}

	bloc.show();
	blocDetails.show();
	GoToBottom();
}

function ShowDetailsCreation (date,heure,idIns,idAvn) {
	pla = {};
	h1 = parseInt(heure);
	h2 = h1 + 1;
	pla.id = 0;
	pla.debut = date+","+h1+":00";
	pla.fin = date+","+h2+":00";
	if (!admin) {
		pla.tip = "PIL";
		pla.idPilote = idPiloteConnecte;
	} else {
		if (idIns) pla.tip = "INS";
		if (idAvn) pla.tip = "AVN";
	}
	pla.idAvion = (idAvn ? idAvn : 0);
	pla.idInstructeur = (idIns ? idIns : 0);
	ShowDetailsModification(pla,true);
}

function ShowDetailsSuppression(pla) {
	if (cMode && ((typeof idPiloteConnecte) == "undefined")) {
		alert ("Vous devez vous identifier\r\npour supprimer une réservation.");
		return;
	}

	bModif = false;
	blocDetails = $("#details2");
	$("#consultation",blocDetails).hide();
	$("#modification",blocDetails).hide();
	bloc = $("#suppression",blocDetails);
	bloc.hide();

	titre = $("#details2 .titre");
	SetTitleClass(titre,'noir',"Suppression");
	// titre.css({backgroundImage:"url('/static/planning/barreNoire2.png')",color:'#FFFFFF'});
	// $("div",titre).html("Suppression"); 

	document.fSupp.idPlage.value = pla.id;
	document.fSupp.tip.value = pla.tip;
	document.fSupp.motif.value = "";
	$("#lienAnnuler",bloc).attr("href","javascript:ShowDetailsConsultation(plages["+pla.id+"]); void(0)");

	$("#consultation",blocDetails).hide();
	$("#modification",blocDetails).hide();
	bloc.show();
	blocDetails.show();
	GoToBottom();
}

function onCalendarHover(){
	$(this).addClass("hover");
}

function onCalendarOut(){
	$(this).removeClass("hover");
}

function onCalendarClick(){
	$("table.calendar td.sel").removeClass("sel");
	$(this).parent().addClass("sel");
	id = $(this).attr("id");
	window.location = "?date=" + id + calParams;
}

function onPlanningHover(){
	if (!$(this).is(".c")) 
		return;
	idPla = $(this).attr("idPla");
	pla = (idPla ? plages[idPla] : null);
	if (idPla && (admin || (pla.tip != "INS"))) 
		hovered = $("table.planning td[idPla='" + idPla + "']");
	else 
		hovered = $(this);
	hovered.addClass("hover");
}

function onPlanningOut(){
	if (hovered) 
		hovered.removeClass("hover");
}

function onCellClick(event,date,heure,idIns,idAvn) {
	if (!bModif) ShowDetailsCreation(date,heure,idIns,idAvn);
	else {
		h = parseInt(heure);

		if (!event.ctrlKey) {
			s = h + ":00";
			if (s.length==4) s = "0"+s;	
			document.fModif.dateDebut.value = DateIsoToFr(date);
			SelectOption(document.fModif.heureDebut,s); 
			h++;
			s = h + ":00";
			if (s.length==4) s = "0"+s;	
			document.fModif.dateFin.value = DateIsoToFr(date);
			SelectOption(document.fModif.heureFin,s); 
		} else {
			h++;
			s = h + ":00";
			if (s.length==4) s = "0"+s;	
			document.fModif.dateFin.value = DateIsoToFr(date);
			SelectOption(document.fModif.heureFin,s);
		}
		if (idAvn) SelectOption($("#avion",bloc).get(0),idAvn);
		if (idIns) SelectOption($("#instructeur",bloc).get(0),idIns);
	}
}

function getColValue(obj) {
	var c=0;
	obj.prevAll().each(function() {c++;});
	return cols[c];
}

function onPlanningClick(event){
	HideMsg();
	if (selected) selected.removeClass("selected");
	if (!($(this).is(".c"))) return;
	if ($(this).is(".i") && !admin) return;

	idPla = $(this).attr("idPla");
	pla = (idPla ? plages[idPla] : null);

	if (cMode) {
		clearTimeout(timer);
		timer = setTimeout("Refresh()",delai);
	}

	idIns = $(this).attr("idIns");
	if (!idIns) {
		table = $(this).parents("TABLE").get(0);
		idIns = $(table).attr("idIns");
	}
	// if (idIns && !admin) return;
	if (!admin) idIns = (pla ? pla.idInstructeur : null);
  
	if (pla && (admin || (pla.tip!="INS"))) {
		selected = $("table.planning td[idPla='" + idPla + "']");
		selected.addClass("selected");
		ShowDetailsConsultation(pla);
	} else {
		if (cMode && ((typeof idPiloteConnecte) == "undefined")) {
			alert ("Vous devez vous identifier\r\npour enregistrer une réservation.");
			return;
		}
		  
		selected = $(this);
		selected.addClass("selected");
		date = $(this).parents("table.planning").attr("dte");
		if (!date) date = getColValue($(this));
		heure = $(this).parent().attr("heure");
		idAvn = $(this).attr("idAvn");
		if (!idAvn) {
		  table = $(this).parents("TABLE").get(0);
		  idAvn = $(table).attr("idAvn");
		}        
		onCellClick(event,date,heure,idIns,idAvn);
	}
}

function OnPilotCodeChange() {
	if (cMode) {
		clearTimeout(timer);
		timer = setTimeout("Refresh()",delai);
	}
	AjxGetPilotInfos(this.value);
}

function OnVDClick() {
	checked = $(this).attr('checked')?true:false;
	if (checked) {
		$("#tVD").show();
	} else {
		$("#tVD").hide();
	}
}

function AjxGetPilotInfos(value) {
	$.ajax({
		url: "/ajax/getPilotInfos.php",
		type: "POST",
		data: {	code: value },
		dataType: "json",
		error: function(XMLHttpRequest, textStatus, errorThrown){ alert("Erreur : "+textStatus); },
		success: function(json){ ShowPilotInfos(json); }
	});
}

function DateIsoToFr(s) {
	var tab;
	tab = s.split("-");
	y = tab[0];
	tab[0] = tab[2];
	tab[2] = y;
	return tab.join("/");
}

function Refresh() {
	window.location = "index.php?op=logout";
}

function ShowPilots() {
	if (cMode) {
		clearTimeout(timer);
		timer = setTimeout("Refresh()",delai);
	}
	// window.open("listePilotes.php","ChoixPilote","scrollbars=yes, menubar=no, status=no, menubar=no, left=300, width=400, height=500");
}

function SetPilotCode(code) {
	$("#iCodePilote").val(code);
	$("#lienPilotes").colorbox.close();
	AjxGetPilotInfos(code);
}

$(document).ready(function(){
	// calendrier : hover
	$("table.calendar div").hover(onCalendarHover, onCalendarOut);
	// calendrier : clic sur date
	$("table.calendar div").click(onCalendarClick);
	// planning : hover
	$("table.planning td").hover(onPlanningHover, onPlanningOut);
	// planning : clic
	$("table.planning td").click(onPlanningClick);
	// details : modification code pilote
	$("#iCodePilote").keyup(OnPilotCodeChange);
	// details : click sur VD
	$("#cVD").click(OnVDClick);
	if (cMode) timer = setTimeout("Refresh()",delai);
});
