var url={n:'', m:'', v:''};
function img_init_url(n, m , v) {
 url={n:n, m:m, v:v};
}

var img_map=[];
var devant = -1;
var tipfocus="Cliquer pour fermer ou déplacer";
var tip="Cliquer pour passer devant et déplacer";

$(function(){
  $('body').keypress(function(e){
    if (devant != -1) { touche(e); }
  });
  // images, popup and co
  $('window').ready(function(){
    if ($(".expandArea")) {
      $('<div></div>').prependTo('body').addClass('expandArea');
    }
    diapo_init();
    ie_poll();
    // premiere image de chaque bloc
    $("table.rpcover").each(function(bloc) {
      recueil_image_change(bloc, 0);
    });
    sablier = new Image();  // "sablier"
	  sablier.src = "../images/sablier.gif";
    $('body').append("<div id='sablier'><img src='"+sablier.src+"' /></div>");
  });

  // pre-remplissage du tableau avec toutes les images de la page
  $(".expandable").each(function(){
    //  On chargera les images (src = $(this).attr('href') plus tard
    $('<img />').appendTo(".expandArea").addClass('ui-widget-content').attr( {'src': ''} ).css( { 'display' : 'none', 'visibility' : 'hidden'} );
    // memoriser les liens miniatures - couvertures --- Nota : img_map.push ne fonctionne pas pour ie
    var index = img_map.length;
    img_map[index]=[];
    img_map[index].ancre = $(this);
    img_map[index].miniature = $(this).children('img');
    img_map[index].couverture = $('.expandArea img').last();
    img_map[index].src = $(this).attr('href');
  });
    
  // ouverture des grands formats
  $(".expandable").bind('click', function(e){
    e.preventDefault(); // empecher le suivi du lien
    couv_affiche($(this));
  });

  // deplacement avec opacité partielle des grands formats
  $(".expandArea img").draggable({
     opacity: 0.75, 
     stack: { group: '.expandArea img', min: 66 },
     stop: function() { couv_focus($(this)); }
  });

  // fermeture ou gain de focus des grands formats
  $('.expandArea img').bind('click', function(e) {
    if (couv_est_devant($(this))) { couv_ferme($(this)); }
    else                          { couv_focus($(this)); }
  });

  // stop/next des mini - Slide
  $(".mini-slide").each(function(index) {
    $(this).find('input').first().bind('click', function(e){
      diapo_stop(index);
    });
    $(this).find('input').eq(1).bind('click', function(e){
      diapo_start_next(index);
    });
  });

  // changement d'image recueil
  $("table.rpcover").each(function(bloc) {
    $(this).find('input').each(function(image) {
      $(this).bind('click', function(e){
        recueil_image_change(bloc, image);
      });
    });
  });
}); 

function couv_affiche (ancre) {
  var index = -1;
  for (var i=0; i < img_map.length; i++) {
    if ((img_map[i].ancre[0] == ancre[0]) && (img_map[i].ancre.attr('href') == ancre.attr('href'))) {
      index = i;
    }
  }

  if (index != -1)
  {
    var x, y;
    if (img_map[index].couverture.css('visibility') != 'visible') {
      /* tests positions */
      // reouverture
      if (devant == -1) { // aucune ouverte
        x = 100;
        y = 20 + ie_offset();
      }
      else {
        // 30 et 50 : les décalages / image précédente
        // 150 et 250 : les limites / bord avant de repartir de l'autre coté de l'écran
        x = img_map[devant].couverture.position().left + 30;
        if (x >= $(window).width() - 150) { x -= $(window).width() - 150; }
        if (x <= 100) { x = 100; }
        y = check_ypos(img_map[devant].couverture.position().top + 15);
        if (y <= 20) { y = 20 + ie_offset(); }
      }
      
      img_map[index].couverture.css({ 'left' : x + 'px', 'top' : y + 'px' });
      img_map[index].couverture.css( { 'display' : 'block' });
      //var debug_msg = "Zone .expandArea : Offset " + $('.expandArea').offset().left + " - " + $('.expandArea').offset().top + " - Position " + $('.expandArea').position().left + " - " + $('.expandArea').position().top + "\n";
      //debug_msg += devant != -1 ? "Image avant : Offset " + img_map[devant].couverture.offset().left + " - " + img_map[devant].couverture.offset().top + " - Position " + img_map[devant].couverture.position().left + " - " + img_map[devant].couverture.position().top + "\n" : ""; 
      //debug_msg += "position retenue : left = " + x + ", top= " + y;
      //alert (debug_msg);
      devant = index;
    }
    couverture = new Image();
		couverture.onload = function(){
       couverture.onload = null;
       couv_agrandir (ancre, index);
    };
    couverture.src = img_map[index].src;
    $('<img />').appendTo(".expandArea").addClass('ui-widget-content').attr( {'src': ''} ).css( { 'display' : 'none', 'visibility' : 'hidden'} );
		$('#sablier').show();

  }
}

function couv_agrandir(ancre, ix)
{
  $("#sablier").remove(); // retrait du sablier

  // memo position, taille et padding finals
  target_x = img_map[ix].couverture.position().left;
  target_y = img_map[ix].couverture.position().top;
  target_px = img_map[ix].couverture.css('padding-left');
  target_py = img_map[ix].couverture.css('padding-top');
  target_h = couverture.height; // ou forcer à 550px
  target_h = 550; // ou forcer à 550px
  target_w = 550 * couverture.width / couverture.height;

  // position et taille initiales... modulo les paddings
  start_px = ancre.children('img').css('padding-left');
  start_py = ancre.children('img').css('padding-top');
  start_x = ancre.children('img').offset().left - parseInt(start_px);
  start_y = ancre.children('img').offset().top - parseInt(start_py);
  start_h = ancre.children('img').height();
  start_w = ancre.children('img').width();

/*  msg= "paddings : " + start_px + ", " + start_py + "<br />\n"
  msg += "left de " + start_x + " vers " + target_x;
  alert (msg); */

  // positionner image à la place de la miniature... taille et padding de la petite taille
  img_map[ix].couverture.offset( {'left' : start_x, 'top' : start_y } );
  img_map[ix].couverture.attr( { 'src' : img_map[ix].src } );
  img_map[ix].couverture.height(start_h);
  img_map[ix].couverture.width(start_w);
  img_map[ix].couverture.css( { 'padding-left' : start_px, 'padding-top' : start_py, 'padding-right' : start_px, 'padding-bottom' : start_py  } );
  img_map[ix].couverture.css( { 'display' : 'block', 'visibility' : 'visible', 'cursor' : 'move', 'zIndex' : 66 });
  couv_focus (img_map[ix].couverture); // pour la mettre devant
  
  // deplacer et agrandir la "grande" en position et taille memorisées
  img_map[ix].couverture.animate ( {
    height: target_h,
    width: target_w,
    paddingLeft: target_px,
    paddingRight: target_px,
    paddingTop: target_py,
    paddingBottom: target_py,
    left: target_x,
    top: target_y
  }, 'slow' );

}

function couv_est_devant(image) {
 return (img_map[devant].couverture.css('zIndex') ==  image.css('zIndex'));
}

function couv_focus(image) {
 var zind = -1;
 for (var i=0; i < img_map.length; i++) {
   // recherche zIndex max
   if (img_map[i].couverture.css('visibility') == 'visible' && parseInt(img_map[i].couverture.css('zIndex')) > zind) {
     zind = parseInt(img_map[i].couverture.css('zIndex'));
   }
   if (img_map[i].couverture[0] == image[0]) {
     // c'est elle !
     devant = i;
   }
   // raz des tip (cliquer pour passer devant)
   img_map[i].couverture.attr( { 'title' : tip } );
   img_map[i].couverture.css( { 'cursor' : 'crosshair' });
 }
 zind = parseInt(zind) + 1;
 //alert ("zIndex mis à " + zind);
 image.css( { 'zIndex' : zind, 'cursor' : 'move' } );
 image.attr( { 'title' : tipfocus } );

 // normalement pas utile...
 image.css( { 'display' : 'block', 'visibility' : 'visible' });
}

function couv_ferme(image) {
 image.css({ 'display' : 'none', 'visibility' : 'hidden', 'zIndex' : 1 });
 devant = -1;
 var top = -1;
 for (var i=0; i < img_map.length; i++) {
   if (img_map[i].couverture.css('visibility') == 'visible' && parseInt(img_map[i].couverture.css('zIndex')) > top) {
     top = parseInt(img_map[i].couverture.css('zIndex'));
     devant = i;
   }
 }
 if (devant != -1)
 {
   img_map[devant].couverture.css( { 'cursor' : 'move' } );
   img_map[devant].couverture.attr( { 'title' : tipfocus } );
 }
}

function check_ypos(y)
{
  var max = (ie ? $(document).height() : $(window).height());
  if (y >= max - 250) y -= max - 250;
  return y;
}

function touche(e) {
  //alert ("touche !");
	var op = null;
	// which ne fonctionne pas avec la 1.4.1 
	// alert (" - type : " + e.type + " - keycode : " + e.keyCode + " - which " + e.which);
	switch (e.keyCode) {
		case 32: // Space
		case 39: // Arrow right
		case 40: // Arrow down
			op = 1;
			break;
		case 8:  // Backspace
		case 37: // Arrow left
		case 38: // Arrow up
			op = -1;
			break;
		case 27: // Escape
			op = 0;
	}

	if (op !== null) { 
    if (e.preventDefault) e.preventDefault();
    else e.returnValue = false;

    if (op == 0) {
      couv_ferme (img_map[devant].couverture);
    } else {
      couv_next (op);
    }
    return false;
  }
  return true;
}

function couv_next (op) {
  var next = devant + op;
  if (next >= img_map.length) next = 0;
  if (next < 0) next = img_map.length - 1;
   
  x = img_map[devant].couverture.css('left');
  y = img_map[devant].couverture.css('top');
  img_map[next].couverture.css({ 'left' : x, 'top' : y });
  
  couv_ferme (img_map[devant].couverture);
  couv_affiche (img_map[next].ancre);
  // on force "devant" (sinon pb - a eclaircir)
  devant = next;
}
/* ////////////////////////////////////////////////////////////////////////////
                         changement d'image bloc recueil
//////////////////////////////////////////////////////////////////////////// */
function recueil_image_change(ix_bloc, ix_image) {
  // on efface toutes les images puis on sélectionne le numéro choisi (index bouton => index ancre)
  $("table.rpcover").eq(ix_bloc).find(".cover").css( { 'display' : 'none', 'visibility' : 'hidden'} );
  $("table.rpcover").eq(ix_bloc).find(".cover").eq(ix_image).css( { 'display' : 'block', 'visibility' : 'visible'} );

  // idem avec les boutons (style default pour tous, puis mise en valeur du choisi) :
  $("table.rpcover").eq(ix_bloc).find("input").attr( 'readonly', false );
  $("table.rpcover").eq(ix_bloc).find("input").removeClass('selected');
  $("table.rpcover").eq(ix_bloc).find("input").eq(ix_image).attr( 'readonly', true );
  $("table.rpcover").eq(ix_bloc).find("input").eq(ix_image).addClass('selected');
}

/* ////////////////////////////////////////////////////////////////////////////
                                  mini-diaporama
//////////////////////////////////////////////////////////////////////////// */
var diapo = [];
var tempo = 10000;
var regular = false;

function diapo_init() {
 $(".mini-slide").each(function(ix, domEle){
    diapo[ix] = []; 
    diapo[ix].nb = $(this).find(".cover").length;
    $(this).find(".cover").css( { 'display' : 'none', 'visibility' : 'hidden'} );
    diapo_start_next(ix);
  });
}

function diapo_start_next(ix) {
  if (diapo[ix].timer) window.clearTimeout(diapo[ix].timer);
  if (diapo[ix].curr === undefined) {
    diapo[ix].curr = diapo[ix].nb - 1 - Math.floor(diapo[ix].nb * Math.random());
  }
  else {
    $(".mini-slide").eq(ix).find(".cover").eq(diapo[ix].curr).css( { 'display' : 'none', 'visibility' : 'hidden'} );
    diapo[ix].curr += 1;
    if (diapo[ix].curr >= diapo[ix].nb || diapo[ix].curr < 0) diapo[ix].curr = 0;
  }
  $(".mini-slide").eq(ix).find(".cover").eq(diapo[ix].curr).css( { 'display' : 'block', 'visibility' : 'visible'} );
  diapo[ix].timer = window.setTimeout("diapo_start_next('"+ix+"')", tempo * (regular == true ? 1 : ( 1 - Math.random()/2))); 
}

function diapo_stop(ix) {
 if (diapo[ix].timer) window.clearTimeout(diapo[ix].timer);
}


/* ////////////////////////////////////////////////////////////////////////////
                    Spécifités IE 6 : pour contourner 'fixed'
//////////////////////////////////////////////////////////////////////////// */
var ie=(document.all && !window.opera);
var last_offset=0;
function ie_poll(){
  if ((ie) && (iev == 6)) {
   
    setInterval("ie_update()", 200);
  }
}
function ie_update() {
  var cur_offset=ie_offset();
  $(".expandArea img").each(function() {
    if ($(this).css('visibility') == 'visible') {
      $(this).css( { 'top' : parseInt($(this).css('top')) + cur_offset - last_offset + 'px' } );
    }
  });
  last_offset = cur_offset;
}
function ie_offset()
{
  return ((ie && (iev == 6)) ? document.documentElement.scrollTop : 0);
}

function iev()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

