/**
Functions called by the new gallery to build it.
**/
var images_url = [];
var all_location = [];

// map thumbnail image URL to the full-size image URL
var image_mapping = {};

function trigger_img(index){
    // get the img for the given index
    // first trigger the mouseover
    // trigger the click for image with the id image_index+1
    // mouseover.
    showNewInfoGallery(all_location[index][1], all_location[index][0], all_location[index][2], all_location[index][3],
    all_location[index][4], all_location[index][5], all_location[index][6], all_location[index][7], all_location[index][8], all_location[index][9]);
    index+=1;
    id_trigger = 'image_'+index
    $(id_trigger).fireEvent('click'); 
}

function build_gallery(srcs, over){
    // srcs is a list of images url.
    show_pictures(srcs, over);

    // and now check if we need to make the button up and down available...
    check_up_down();

    // trigger for first
    if (all_location.length) {
      showNewInfoGallery(all_location[0][1], all_location[0][0], all_location[0][2], all_location[0][3],
          all_location[0][4], all_location[0][5], all_location[0][6], all_location[0][7], all_location[0][8], all_location[0][9]);
    } 
}

function show_pictures (srcs, on_over) {
  var while_pictures = 1;

  if (images_url.length){
     while_pictures=images_url.length+1;
  }

  var all=0;
  var table_row = undefined;
  var len_table_row = 0;
  var thumbnail_table = document.getElementById('inside');
  while(all < srcs.length) {
    // Get the image url.
    var location = false; 
    if (!on_over){
        var src_img = srcs[all];
    }
    else { 
        var src_img = srcs[all][0];
        var thumb_img = srcs[all][1];
        image_mapping[thumb_img] = src_img;

        // get the location stuff.
        var caption = srcs[all][2];
        var entry_url = srcs[all][3];
        var day = srcs[all][4];
        var mon = srcs[all][5];
        if (srcs[all].length>6){
            var label = srcs[all][6];
            var country= srcs[all][7];
            var lat= srcs[all][8];
            var lon= srcs[all][9];
            var zoom = srcs[all][10];
            var type = srcs[all][11];
            all_location.push([caption, entry_url, day, mon, label, country, lat, lon, zoom, type])
        } 
        else {
            all_location.push([caption, entry_url, day, mon])
        }
    }

    images_url.push(thumb_img)

    // add the new image element.
    if (thumb_img == src_img) {
        class_img = 'unscaled';
    } else {
        class_img = 'prescaled';
    }

    // 4 images per table row
    if (table_row == undefined || len_table_row == 3) {
        table_row = thumbnail_table.insertRow(-1);
        len_table_row = 0;
    } else {
        len_table_row += 1;
    }

    // new TD for this image
    var img_container = table_row.insertCell(-1);
    $(img_container).set('class', 'picture_cell');

    // generate an image element inside a <td> which may be inside a new row
    var new_image = new Element('img', {
			'src': thumb_img,
                        'class': class_img,
			'id': 'image_' + while_pictures,
			'events': {
        'mouseover': function() {
            // display information about the photo under the mouse
            if (on_over){
                i = this.id.replace('image_', '')
                var j=parseInt(i)-1;
                // add the map stuff
                showNewInfoGallery(all_location[j][1], all_location[j][0],
                  all_location[j][2], all_location[j][3],
                  all_location[j][4], all_location[j][5],
                  all_location[j][6], all_location[j][7], all_location[j][8], all_location[j][9]);
            }
        }, 
	'click': function() {
	   // Get the big image, add controler if need too.
           src_img = image_mapping[this.src];
           if (src_img == this.src) {
               $('display_picture_img').innerHTML = "<img src=\"" + src_img + "\" id=\"big_" + this.id + "\" class=\"unscaled\" />";
           } else {
               $('display_picture_img').innerHTML = "<img src=\"" + src_img + "\" id=\"big_" + this.id + "\" />";
           }
	   // fade the main container
	   $('display_picture_container').fade(1);
	   $('display_picture_img').getChildren()[0].fade(.999999);

     // Do the same picture_section (insible)
     $('picture_section').fade(0);

	   $('controls_vert').setStyle('display', 'none');
	   if(this.id.replace('image_', '')==1) {
  	      // We got the first image.
  	      // --> no left control but we do need the right control (XXX could check if multi pictures..)
		$('left_ctr').set('class', 'deact');
		$('right_ctr').set('class', 'activ');
	   } 
	   else if(this.id.replace('image_', '')==images_url.length){
	      // We got the last picture..
	      // No right control but we got the left.
		$('left_ctr').set('class', 'activ');
		$('right_ctr').set('class', 'deact');
	   } else {
            // We need both controls 
		$('left_ctr').set('class', 'activ');
		$('right_ctr').set('class', 'activ');
	   }
	   $('controls_horz').setStyle('display', 'block');

	   // IE6 does not like it....
           //$('left_ctr').tween('margin-left', '286px');
           if(Browser.Engine.trident4) { $('left_ctr').tween('margin-left', '143px'); } 
           else { $('left_ctr').tween('margin-left', '200px'); }					

	 }  // ** End click.

      } // End event.
      
    }); // End new image.
    // add the new image to the table cell
    new_image.inject($(img_container));

    // preload all of the images
    var preload_image = new Element('img', {'src': src_img, 'class': 'hide'});

    // inject in the container.
    preload_image.inject($('container_g'));

    // NOTE: I didn't create an alt attribute because it won't be seen by anyone here anyway.
    while_pictures++;

    all++;

  } // End while
  $('controls_horz').setStyle('display', 'none');
}

// Play the slide show.
function play_slide(){
   // show the main image.
   // --> show_pictures click...

   // and switch every 5s to start with.
   // --> Can look at how the end function is done (DOM ready.)
   // we need the same controls as for the 
   // big map.
   // --> play stop faster slower....
}

// Check if we need or not to add the button  to navigate up and down for the gallery...
function check_up_down(){
    // We want 5 rows and 4 pictures by row.
    // We play it safe and / by 3...
    var rows = Math.ceil(images_url.length/3);
    var vertical_moves = 0;
    if(rows>5) {
      $('up').set('class', 'activ');
      $('down').set('class', 'activ');
      $('up').addEvent('click', function(event){
		  if(!$('up').hasClass('deact')) {
			    vertical_moves--;
          $('down').set('class', 'activ');
          $('inside').tween('margin-top', '-'+ (64 * vertical_moves) +'px');
          if (vertical_moves==0) {
				     $('up').set('class', 'deact');
			    }
		  }
	    }); // End Event up click.

      $('down').addEvent('click', function(event){
		      if(!$('down').hasClass('deact')) {
			        vertical_moves++;
              $('up').set('class', 'activ');
			        $('inside').tween('margin-top', '-'+ (64 * vertical_moves) +'px');
			        // 
			        if(vertical_moves == (rows-5)) {
                  // add a bit more to see the last picture...    
                  $('inside').tween('margin-top', '-'+ (64 * vertical_moves+40) +'px');
				          $('down').set('class', 'deact');
			        }
		      }
	    }); // End event down click.
    } else {
      // We got more than 5 row....
      $('up').set('class', 'deact');
      $('down').set('class', 'deact');
    }
}

function addNewMarkerGallery(lat, lon, title, zoom, type){
    if (!lat){
         // Nothing to do.
         return false;
    }
    if (!title){
        title=''
    }

    // Move the marker
    var coor = new GLatLng(lat, lon);
    if (!MARKER){
        var icon = new GIcon();
        icon.image = "/default/images/icon_map_past_location"
        icon.iconAnchor = new GPoint(0, 30);
        icon.infoWindowAnchor = new GPoint(10, 4);
        MARKER = new GMarker(coor, {id:'ekit', icon:icon, title:title});

        // init the marker
        MAP.addOverlay(MARKER);
    }
    MARKER.setPoint(coor)
    // ****
    // and reset the label.
    // $('mtgt_ekit').attr('title', title)
    // MARKER.attr('title', title);
    // ****    
    if (type == 'satellite'){
        MAP.setMapType(G_SATELLITE_MAP);
    }
    else if (type == 'map'){
        MAP.setMapType(G_NORMAL_MAP);
    }
    else if (type == 'hybrid'){
        MAP.setMapType(G_HYBRID_MAP);
    }
    else if (type =='terrain'){
        MAP.setMapType(G_PHYSICAL_MAP);
    }
    MAP.setCenter(coor,zoom);
}
  function showNewInfoGallery(url, caption, day, mon, label, country, lat, lon, zoom, type){
     // We want to show the last icon in a different color.
    if (!caption.length){caption='&nbsp;'}

    $('caption_date_day').innerHTML = day;
    $('caption_date_mon').innerHTML = mon;
    $('caption_img').innerHTML = '<b>' + caption + '</b>';
    $('caption_link').innerHTML = '<a href="' + url + '">View entry</a>';

    if (label == undefined) {label = '';}

    $('caption_entry_link').innerHTML = label

    //$('location_label').innerHTML='';
    if (lat !=''){
        // add the marker.
        addNewMarkerGallery(lat, lon, country+' '+label, zoom, type);  
    }
    
}


function set_current_image(current_image, current_id) {
      current_image.fade('hide');

      // the ids are 1-index, not 0-index
      var current_index = current_id - 1;

      // get the url for the given id.
      var thumb_img = images_url[current_index];
      var src_img = image_mapping[thumb_img];
      current_image.set('src', src_img);
      if (src_img == thumb_img) {
         current_image.set('class', 'unscaled');
      } else {
         current_image.erase('class');
      }
      current_image.fade(1);
      current_image.set('id', 'big_image_' + current_id);

      // get the map stuf as well.
      var j = current_index;
      showNewInfoGallery(all_location[j][1], all_location[j][0], all_location[j][2], all_location[j][3],
          all_location[j][4], all_location[j][5], all_location[j][6], all_location[j][7], all_location[j][8], all_location[j][9]);
}

/**
 What to do when DOM is ready !!!!
**/
window.addEvent('domready', function() {	

  // Fade the div use for the big picture.
  $('display_picture_container').fade('hide');

  var current_id = 1;

  // Add onclick events for the cursor.
  $('left_ctr').addEvent('click', function() {
    if(!$('left_ctr').hasClass('deact')) {
      current_image = $('display_picture_img').getChildren()[0]
      var current_id = current_image.id;
      current_id = current_id.replace('big_image_', '');
      current_id--;

      set_current_image(current_image, current_id);
      if (current_id == 1) { 
          $('left_ctr').set('class', 'deact'); 
      }
      $('right_ctr').set('class', 'activ');
    }
  });

  $('right_ctr').addEvent('click', function() {
    if(!$('right_ctr').hasClass('deact')) {
      current_image = $('display_picture_img').getChildren()[0];
      current_id = current_image.id;
      current_id = current_id.replace('big_image_', '');
      current_id++;

      set_current_image(current_image, current_id);

      $('left_ctr').set('class', 'activ'); 
      if (current_id == images_url.length) { 
          $('right_ctr').set('class', 'deact'); 
      }
    }
  }); // End event

  $('display_picture_img').addEvent('click', function() {
    $('display_picture_container').fade(0);
    $('display_picture_img').getChildren()[0].fade(0);
    // and re fade the background.
     $('picture_section').fade(1);

    //$('up').setStyle('margin-left', '286px');
    if(Browser.Engine.trident4) { $('up').setStyle('margin-left', '143px'); } else { $('up').setStyle('margin-left', '286px'); }
    $('controls_horz').setStyle('display', 'none');
    $('controls_vert').setStyle('display', 'block');
    $('left_ctr').setStyle('margin-left', '7px');
    $('up').tween('margin-left', '7px');
  }); // End event

}); // End window event...


