var diapo_array;
var diapo_pos = 0;
var diapo_max =  0;

function initImgSearch (e)
{
	// Requete ajax
	var req = new Ajax.Request('scripts/img_search.php',
		{
			onSuccess: function(t)
			{
                var reponse = t.responseText;
                if(reponse != '')
                {
                    diapo_array = eval('(' +reponse + ')');
                    diapo_max = diapo_array.length;
                    imgChange();
                }
			}
		});
}
function imgChange ()
{
    var img_src = diapo_array[diapo_pos][3];
    var d_href =diapo_array[diapo_pos][2];

   	if (!$('adm_diapo_news').empty())
	{
		// Effacement de imgb et passage de imga en imgb
		if ($('imgb')){ $('imgb').remove()};
		Element.writeAttribute('imga',{ id: 'imgb'});
		// creation de la nouvelle image et insertion
		var r_href = "";
		if (d_href != 0){r_href = ' href="'+d_href+'"';}
		$('imgb').insert({before: '<a id="imga"'+r_href+'><img src="'+img_src+'" alt=""/></a>'});
		// transition entre de imgb vers imga
		new Effect.Parallel(
			[
				new Effect.Opacity('imgb', {sync: true, from:1, to: 0, fps: 30}),
				new Effect.Opacity('imga', {sync: true, from:0, to: 1, fps: 30})
			],
			{
				duration: 2,
				afterFinish: function()
				{
					Element.setStyle('imgb', {display: 'none'});
					diapo_pos++;
                    if (diapo_pos == diapo_max) diapo_pos = 0;
					setTimeout("imgChange()",2000); //default:2000
				}
			});
	}
	else
	{
		// Cas de l'initialisation: premiere image
		var r_href = "";
		if (d_href != 0){r_href = ' href="'+d_href+'"';}
		$('adm_diapo_news').insert({bottom: '<a id="imga"'+r_href+'><img src="'+img_src+'" alt=""/></a>'});
		$('imga').setStyle('opacity: 0');
		new Effect.Opacity('imga',
			{
				duration: 1, from:0, to: 1, fps: 30,
				afterFinish:function()
				{
                    diapo_pos++;
                    if (diapo_pos == diapo_max) diapo_pos = 0;
					setTimeout("imgChange()",2000); //default:2000
				}
			});
	}
}

document.observe('dom:loaded', initImgSearch);
