var gCurrentFilm = 0;
var gDate = undefined;
var gSorties = undefined;
var gFilmTimerId = undefined;
var gRetryTimerId = undefined;
var gRefreshTimerId = undefined;
var gPollDateTimerId = undefined;

var gSettings = {
	docked:{
		width:"130px",
		height:"253px"
	},
	undocked:{
		width:"400px",
		height:"242px"
	}
}

function getSortiesData()
{
	clearTimeouts();
	showMessage("chargement...");
	var xhr = new Ajax.Request(URL_GADGET_SORTIES,
		{
			method:"get",
			parameters:"f=json&e=1",
			onComplete:handleSortiesResponse
		}
	);
}

function getNetAccess()
{
	clearTimeouts();
	showMessage("test de connectivité...");
	var xhr = new Ajax.Request(URL_NET_ACCESS,
		{
			method:"get",
			onComplete:handleNetAccess
		}
	);
}

function handleNetAccess(xhr)
{
	if (xhr.status == 404)
		getVersion();
	else
	{
		showMessage("pas de connectivité ; " + buildRefreshNotice("procGadgetCore", MSEC_RETRY));
		gRetryTimerId = window.setTimeout(procGadgetCore, MSEC_RETRY);
		hideControls();
		return;
	}
}

function handleSortiesResponse(xhr)
{
	if (xhr.status > 400)
	{
		showMessage("erreur de communication avec le serveur ; " + buildRefreshNotice("procGadgetCore", MSEC_RETRY));
		gRetryTimerId = window.setTimeout(procGadgetCore, MSEC_RETRY);
		hideControls();
		return;
	}
	
	try
	{
		var result = eval("(" + xhr.responseText + ")");
		gSorties = result.data;
		gDate = parseDate(result.date);
	}
	catch(e)
	{
		showMessage("impossible d'interpréter les données ; " + buildRefreshNotice("procGadgetCore", MSEC_RETRY));
		gRetryTimerId = window.setTimeout(procGadgetCore, MSEC_RETRY);
		hideControls();
		return;
	}
	
	showDate(gDate);
	fillImageCache();
	gPollDateTimerId = window.setInterval(pollDate, MSEC_POLL_DATE);
	gRefreshTimerId = window.setTimeout(procGadgetCore, MSEC_REFRESH_DATA);

	switch (gSorties.status)
	{
		case -1:
			showMessage("erreur serveur lors de la récupération des données ; " + buildRefreshNotice("procGadgetCore", MSEC_RETRY));
			gRetryTimerId = window.setTimeout(procGadgetCore, MSEC_RETRY);
			hideControls();
			break;
		case -2:
			showMessage("aucune donnée ; " + buildRefreshNotice("procGadgetCore", MSEC_RETRY));
			gRetryTimerId = window.setTimeout(procGadgetCore, MSEC_RETRY);
			hideControls();
			break;
		default:
			if (gSorties.count > 0)
			{
				gCurrentFilm = 0;
				showCurrentFilm();
				playFilm();
			}
			break;
	}
}

function pollDate()
{
	var now = new Date();
	if (now.getTime() - gDate.getTime() > 604800000)
		procGadgetCore();
}

function buildRefreshNotice(getFunctionName, msec)
{
	return "nouvelle tentative dans <a href='JavaScript:" + getFunctionName + "();' title='maintenant'>"+ formatMSec(msec) +"</a>";
}

function fillImageCache()
{
	emptyImageCache();
	for (i=0;i<gSorties.count;i++)
	{
		var film = gSorties.rows[i];
		new Insertion.Bottom("divImageCache", "<img id='img" + film.cFilm + "' src='" + film.Affichette + "' class='affichette' onclick='JavaScript:launchUrl(\"http://www.allocine.fr/film/fichefilm_gen_cfilm=" + film.cFilm + ".html\")' title='" + film.TitreSimpleAffichage + " sur www.allocine.fr'/>");
	}
}

function emptyImageCache()
{
	$("divImageCache").innerHTML = "";
}

function hideAffichettes()
{
	var imgs = document.getElementsByClassName("affichette", "divImageCache");
	for (i=0;i<imgs.length;i++)
		imgs[i].style.display = "none";
}

function showAffichette(filmId)
{
	hideAffichettes();
	var img = $("img" + filmId)
	img.style.display = "block";
}

function showDate(d)
{
	var div = $("divDate");
	if (d instanceof Date)
	{
		div.innerHTML = "sorties du " + (System.Gadget.docked?d.formatShort():d.formatLong());
		div.style.display = "block";
	}
	else
		div.style.display = "none";
}

function hideContent()
{
	hideAffichettes();
	$("divContent").style.display = "none";
}

function showContent()
{
	$("divContent").style.display = "block";
}

function showCurrentFilm()
{
	var film = gSorties.rows[gCurrentFilm];
	
	if (!film)
	{
		showMessage("pas de données");
		return;
	}

	hideMessage();
	showContent();
	showControls();

	$("titre").innerHTML = film.TitreSimpleAffichage?film.TitreSimpleAffichage:"";
	showAffichette(film.cFilm);
	$("titreOriginal").innerHTML = (film.TitreOriginalAffichage && (film.TitreOriginalAffichage!=film.TitreSimpleAffichage))?("&nbsp;(" + film.TitreOriginalAffichage + ")"):"";
	$("genre").innerHTML = film.txtGenrePrincipal?film.txtGenrePrincipal:"";
	$("duree").innerHTML = film.Duree?("&nbsp;(" + formatDuree(film.Duree) + ")"):"";
	$("de").innerHTML = film.FilmDeWeb?("De " + film.FilmDeWeb):"";
	$("avec").innerHTML = film.FilmAvecWeb?("Avec " + film.FilmAvecWeb):"";
	$("synopsis").innerHTML = film.SynopsisCourt?film.SynopsisCourt:"";
	$("lienProjection").href = "http://www.allocine.fr/seance/filmcp_gen_cprojection=" + film.cProjection + "&codepostal=null.html"
	$("nbProjection").innerHTML = film.Poids;

	if(film.isVideos == 1)
	{
		$("videos").href = "http://www.allocine.fr/film/video_gen_cfilm=" + film.cFilm + ".html";
	}

	if (film.CritikPressNb > 0)
	{
		$("lienPresse").href = "http://www.allocine.fr/film/revuedepresse_gen_cfilm=" + film.cFilm + ".html";
		$("imgPresse").src = "images/etoile_" + film.NotePresse + ".png";
		$("critiquePresse").style.display = "block";
	}
	else
		$("critiquePresse").style.display = "block";

	if (film.CritikPublicNb > 0)
	{
		$("lienPublic").href = "http://www.allocine.fr/film/critiquepublic_gen_cfilm=" + film.cFilm + ".html";
		$("imgPublic").src = "images/etoile_" + film.NoteCritique + ".png";
		$("critiquePublic").style.display = "block";
	}
	else
		$("critiquePublic").style.display = "none";
		
	
	var elts =  document.getElementsByClassName("personne");
	for (i=0;i<elts.length;i++)
	{
		var e = elts[i];
		if (e.href)
			e.href = e.href.replace("x-gadget://", "http://www.allocine.fr");
	}

	var liens = document.getElementsByClassName("lienFilm");
	for (i=0;i<liens.length;i++)
	{
		var lien = liens[i];
		lien.href = "http://www.allocine.fr/film/fichefilm_gen_cfilm=" + film.cFilm + ".html";
		lien.title = film.TitreSimpleAffichage + " sur www.allocine.fr";
	}

	showCurrentFilmInFlyout();
}

function prevFilm()
{
	gCurrentFilm = (gCurrentFilm==0)?gSorties.count-1:gCurrentFilm-1;
	showCurrentFilm();
}

function nextFilm()
{
	gCurrentFilm = (gCurrentFilm==gSorties.count-1)?0:gCurrentFilm+1;
	showCurrentFilm();
}

function showCurrentFilmInFlyout()
{
	if (System.Gadget.Flyout.show)
	{
		System.Gadget.Flyout.document.parentWindow.film = gSorties.rows[gCurrentFilm];
		System.Gadget.Flyout.document.parentWindow.update();
	}
}

function gadget_onload()
{
	initGadget();
	initGadgetUI();
	procGadgetCore();
}

function initGadget()
{
	System.Gadget.onUndock = procUndock;
	System.Gadget.onDock = procDock;

	System.Gadget.Flyout.file = "flyout.html";
	System.Gadget.Flyout.show = false;

	System.Gadget.Flyout.onShow = procFlyoutShow;
	System.Gadget.Flyout.onHide = procFlyoutHide;
}

function initGadgetUI()
{
	procDock();
}

function procGadgetCore()
{
	hideContent();
	hideControls();
	getNetAccess();
}

function procFlyoutShow()
{
	var ctl = $("ctlToggleFlyOut");

	ctl.title = "masquer détails";
	Element.removeClassName(ctl, "hidden");
	Element.addClassName(ctl, "shown");
}

function procFlyoutHide()
{
	var ctl = $("ctlToggleFlyOut");

	ctl.title = "afficher détails";
	Element.removeClassName(ctl, "shown");
	Element.addClassName(ctl, "hidden");
}

function procUndock()
{
	document.body.style.width = gSettings.undocked.width;
	document.body.style.height = gSettings.undocked.height;

	var bg = $("background");
	
	bg.style.width = document.body.style.width;
	bg.style.height = document.body.style.height;
	bg.src = "url(images/bg-undocked.png)";
	
	showDate(gDate);
	
	var elts =  document.getElementsByClassName("docked");
	for (i=0;i<elts.length;i++)
	{
		var e = elts[i];
		Element.removeClassName(e, "docked");
		Element.addClassName(e, "undocked");
	}
}

function procDock()
{
	document.body.style.width = gSettings.docked.width;
	document.body.style.height = gSettings.docked.height;

	var bg = $("background");

	bg.style.width = document.body.style.width;
	bg.style.height = document.body.style.height;
	bg.src = "url(images/bg-docked.png)";

	showDate(gDate);

	var elts =  document.getElementsByClassName("undocked");
	for (i=0;i<elts.length;i++)
	{
		var e = elts[i];
		Element.removeClassName(e, "undocked");
		Element.addClassName(e, "docked");
	}
}

function toggleFlyout()
{
	if (!System.Gadget.Flyout.show)
	{
		System.Gadget.Flyout.show = true;
		window.setTimeout(showCurrentFilmInFlyout, 1000);
	}
	else
		System.Gadget.Flyout.show = false;
}

function togglePause()
{
	if (gFilmTimerId == undefined)
		playFilm();
	else
		pauseFilm();
}

function playFilm()
{
	gFilmTimerId = window.setInterval(nextFilm, MSEC_ROLL_FILM);

	var ctl = $("ctlTogglePause");
	Element.removeClassName(ctl, "paused");
	Element.addClassName(ctl, "playing");
	ctl.title = "mettre en pause";
}

function pauseFilm()
{
	window.clearInterval(gFilmTimerId);
	gFilmTimerId = undefined;

	var ctl = $("ctlTogglePause");
	Element.removeClassName(ctl, "playing");
	Element.addClassName(ctl, "paused");
	ctl.title = "jouer";
}

function clickNext()
{
	pauseFilm();
	nextFilm();
}

function clickPrev()
{
	pauseFilm();
	prevFilm();
}

// --- version checking ---

function versionCompare(v1, v2)
{
	var ar1 = v1.split(".");
	var ar2 = v2.split(".");

	for (i=0;i<ar2.length;i++)
	{
		if (parseInt(ar2[i]) > parseInt(ar1[i]))
			return true;
	}
	return false;
}

function clearTimeouts()
{
	if (gFilmTimerId != undefined)
	{
		window.clearInterval(gFilmTimerId);
		gFilmTimerId = undefined;
	}
	if (gRetryTimerId != undefined)
	{
		window.clearTimeout(gRetryTimerId);
		gRetryTimerId = undefined;
	}
	if (gRefreshTimerId != undefined)
	{
		window.clearInterval(gRefreshTimerId);
		gRefreshTimerId = undefined;
	}
	if (gPollDateTimerId != undefined)
	{
		window.clearInterval(gPollDateTimerId);
		gPollDateTimerId = undefined;
	}
}

function getVersion()
{
	clearTimeouts();
	showMessage("vérification de la version du gadget");
	var xhr = new Ajax.Request(URL_GADGET_VERSION,
		{
			method:"get",
			onComplete:handleVersionResponse
		}
	);
}

function handleVersionResponse(xhr)
{
	if (xhr.status > 400)
	{
		showMessage("erreur de communication avec le serveur ; " + buildRefreshNotice("procGadgetCore", MSEC_RETRY));
		gRetryTimerId = window.setTimeout(procGadgetCore, MSEC_RETRY);
		return;
	}

	try
	{
		var v = eval("(" + xhr.responseText + ")");
	}
	catch(e)
	{
		showMessage("impossible d'interpréter les données ; " + buildRefreshNotice("procGadgetCore", MSEC_RETRY));
		gRetryTimerId = window.setTimeout(procGadgetCore, MSEC_RETRY);
		return;
	}
	
	if (versionCompare(System.Gadget.version, v.version))
	{
		showMessage("une nouvelle version du gadget est disponible");
		launchUrl(URL_GADGET_DOWNLOAD);
	}

	if (!versionCompare(System.Gadget.version, v.lastCompatibleVersion))
		getSortiesData();
	else
		showMessage("votre version du gadget AlloCiné doit être mise à jour");
}

// --- recherche ---

function procRechercheFocus()
{
	var motcle_ = $("motcle_");
	motcle_.value = $F("motcle");
	motcle_.select();
}

function procRechercheBlur()
{
	var motcle_ = $("motcle_");
	if ($F("motcle") == "")
	{
		Element.addClassName(motcle_, "empty");
		motcle_.value = "rechercher...";
	}
	else
		Element.removeClassName(motcle_, "empty");
}

function procRechercheKeyUp()
{
	var motcle_ = $("motcle_");
	Element.removeClassName(motcle_, "empty");
	$("motcle").value = motcle_.value;
}

function showMessage(s)
{
	hideContent();
	hideControls();
	var div = $("divMessage");
	div.innerHTML = s;
	div.style.display = "block";
}

function hideMessage()
{
	$("divMessage").style.display = "none";
}

function hideControls()
{
	$("divControls").style.display = "none";
}

function showControls()
{
	$("divControls").style.display = "block";
}

