/* CONSOLE */

if( typeof window.console == "undefined" )
{
 window.console = {};
 window.console.log = function(){};
}


/* MAIN */

$(document).ready
(
 function()
 {
  // Ajax
  $.ajaxSetup
   ({
    beforeSend: function( xhr, obj )
                {
                 if( obj.type == "POST" )
                 {
                  ViGiSITE.core.startLoading();
                 }
                },
    complete: function()
              {
               ViGiSITE.core.stopLoading();
               ViGiSITE.core.initTableList();
              },
    dataFilter: function( data, type )
                {
                 try
                 {
                  data = jQuery.parseJSON( data );
                  data = ViGiSITE.core.ViGiSITECode( data );
                 }
                 catch(e)
                 {
                  ViGiSITE.core.ViGiSITECodeShow( "Return syntax error", e );
                 }
                 
                 return data;
                }
   });
  
  
  // Search
  $("div#search a.open_close").mouseover
   (
    function()
    {
     if( $(this).parent().hasClass( "closed" ) )
     {
      $(this).parent().animate({ width: "210px" });
      $(this).parent().removeClass( "closed" );
     }
     return false;
    }
   );
  $("div#search a.open_close").click
   (
    function()
    {
     if( !$(this).parent().hasClass( "closed" ) )
     {
      $(this).parent().animate({ width: "0" });
      $(this).parent().addClass( "closed" );
     }
     return false;
    }
   );
  
  
  // Menu
  $("div#menu h3").click
   (
    function()
    {
     $(this).toggleClass( "closed" );
     $(this).next().slideToggle();
     return false;
    }
   );
  
  
  // Help
  if( $("div#help").length == 1 )
  {
   $("div#help a.label").click( function()
                                {
                                 $(this).parent().stop();
                                 
                                 if( $(this).parent().css( "width" ) == "0px" )
                                 {
                                  $(this).parent().css({ width: "350px", "border-left-width": "1px" });
                                  $(this).next( "div.content" ).show();
                                 }
                                 else
                                 {
                                  $(this).next( "div.content" ).hide();
                                  $(this).parent().css({ width: "0px", "border-left-width": "0px" });
                                 }
                                } );
   
   if( $("div#help div.content h3").length > 1 )
    $("div#help div.content > div").not( "h3" ).hide();
   else
    $("div#help div.content h3").addClass( "opened" );
   
   $("div#help div.content h3" ).click( function()
                                        {
                                         $(this).next( "div" ).toggle();
                                         $(this).toggleClass( "opened" );
                                        } );
  }
  
  
  // Lists
  $("table.list tbody tr[contextmenu]").mouseup( function()
                                                   {
                                                    $(this).parent().children( "tr.selected" ).removeClass( "selected" );
                                                    $(this).toggleClass( "selected" );
                                                    return true;
                                                   } );
  
  // Styles
  ViGiSITE.core.initTableList =
   function()
   {
    $("table.list:not(.init)").each( function( i, table )
                                     {
                                      $(table).children( "thead" ).children().each( function( i, element )
                                                                                    {
                                                                                     $(element).children( "th:first" ).addClass( "first" );
                                                                                     $(element).children( "th:last" ).addClass( "last" );
                                                                                    } );
                                      $(table).children( "tbody" ).children( ":odd" ).addClass( "odd" );
                                      $(table).children( "tbody" ).children().each( function( i, element )
                                                                                    {
                                                                                     $(element).children( "td:first" ).addClass( "first" );
                                                                                     $(element).children( "td:last" ).addClass( "last" );
                                                                                    } );
                                      $(table).children( "tbody" ).children( ":last" ).addClass( "last" );
                                      
                                      $(table).addClass( "init" );
                                     } );
   };
  ViGiSITE.core.initTableList();
  $("div#container").mousedown( function(){ $("table.list tbody tr[contextmenu]").removeClass( "selected" ); } );
  
  
  // Inputs date
  $.datepicker.regional['fr'] = { clearText: 'Effacer', clearStatus: '',
                                  closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
                                  prevText: '&lt;Pr&eacute;c', prevStatus: 'Voir le mois pr&eacute;c&eacute;dent',
                                  nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
                                  currentText: 'Courant', currentStatus: 'Voir le mois courant',
                                  monthNames: ['Janvier','F&eacute;vrier','Mars','Avril','Mai','Juin',	'Juillet','Ao$ucirc;t','Septembre','Octobre','Novembre','D&eacute;cembre'],
                                  monthNamesShort: ['Jan','F&eacute;v','Mar','Avr','Mai','Jun','Jul','Ao&ucirc;','Sep','Oct','Nov','D&eacute;c'],
                                  monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre ann&eacute;e',
                                  weekHeader: 'Sm', weekStatus: '',
                                  dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
                                  dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
                                  dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
                                  dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
                                  dateFormat: 'dd/mm/yy', firstDay: 1, 
                                  initStatus: 'Choisir la date', isRTL: false };
  $.datepicker.setDefaults( $.extend( {}, 
                                      { changeMonth: true,
                                        changeYear: true,
                                        // yearRange: "1900:2009",
                                        dateFormat: "dd/mm/yy",
                                        showOtherMonths: true,
                                        showAnim: "slideDown",
                                        duration: 'fast',
                                        showOn: "button",
                                        buttonImage: "/templates/common/imgs/icons/calendar.gif",
                                        buttonImageOnly: true,
                                        firstDay: 1,
                                        gotoCurrent: true,
                                        constrainInput: true,
                                        showButtonPanel: true }, 
                                      $.datepicker.regional['fr'] ) );
  if( $("input[type=text].date").length > 0 )
   $("input[type=text].date").datepicker( $.datepicker.regional['fr'] );
  
  
  // Function serializeJSON
  $.fn.serializeJSON =
   function( separator )
   {
    var datas = {};
    var datas_temp = $(this).serializeArray();
    
    separator = ( typeof separator != "undefined" ? separator : "," );
    
    $.each( datas_temp,
            function( i, value )
            {
             if( eval( 'typeof datas["' + value.name + '"]' ) == "undefined" )
              eval( 'datas["' + value.name + '"] = value.value;' );
             else
              eval( 'datas["' + value.name + '"] = ( datas["' + value.name + '"].toString() + "' + separator + '" + value.value.toString() );' );
            });
    delete datas_temp;
    
    datas = $.extend( datas, ( typeof PART != "undefined" && !isNaN( PART ) ? { part: PART } : {} ) );
    
    return datas;
   };
  
  
  // Function serializeJSONenumerate
  $.fn.serializeJSONArray =
   function()
   {
    var datas = {};
    var datas_temp = $(this).serializeArray();
    
    $.each( datas_temp,
            function( i, value )
            {
             if( eval( 'typeof datas["' + value.name + '[]"]' ) == "undefined" )
              eval( 'datas["' + value.name + '[]"] = new Array;' );
             
             eval( 'datas["' + value.name + '[]"].push( value.value );' );
            });
    delete datas_temp;
    
    datas = $.extend( datas, ( typeof PART != "undefined" && !isNaN( PART ) ? { part: PART } : {} ) );
    
    return datas;
   };
  
  
  // Position element to center of the page
  $.fn.centerToScreen =
   function( withoutAnimation )
   {
    var posTop = ( $(window).height() - $(this).outerHeight() ) / 2 - 10 + $(document).scrollTop();
    var posLeft = ( $(window).width() - $(this).outerWidth() ) / 2 + $(document).scrollLeft();
    
    $(this).stop();
    
    if( withoutAnimation === true )
     $(this).css( { top: posTop, left: posLeft } );
    else
     $(this).animate( { top: posTop, left: posLeft } );
   };
  
  
  // Change order
  $.fn.updateOrder = function( selector ){ $(selector).children( "option[value=" + $(this).val() + "]:selected" ).parent( "select" ).not( $(this) ).val( parseInt( $(this).val() ) + 1 ).change(); };
 }
);



// Loading
ViGiSITE.core.iLoading = 0;

ViGiSITE.core.startLoading =
 function()
 {
  if( ViGiSITE.core.iLoading == 0 )
  {
   $("body").append('<div id="loading" />');
   $("body").css( "cursor", "wait" );
   $("a").css( "cursor", "progress" );
   
   $(window).bind( "resize.loading", 
                   function()
                   {
                    // Resize background
                    $("div#loading").css({ top: $(document).scrollTop(), 
                                           left: $(document).scrollLeft(), 
                                           height: $(window).height(), 
                                           width: $(window).width() });
                   } );
   $(window).trigger( "resize.loading" );
  }
  
  ViGiSITE.core.iLoading++;
 };
 
ViGiSITE.core.stopLoading =
 function()
 {
  ViGiSITE.core.iLoading--;
  
  if( ViGiSITE.core.iLoading <= 0 )
  {
   $("div#loading").remove();
   ViGiSITE.core.iLoading = 0;
   $("body").css( "cursor", "" );
   $("a").css( "cursor", "" );
   $(window).unbind( "resize.loading" );
  }
 };


// ViGiSITECode

ViGiSITE.core.ViGiSITECode = 
 function( data )
 {
  var codes = {};
  var errorCodes = "";
  var errorDescription = "";
  
  if( typeof data.ViGiSITECode != "undefined" )
  {
   if( typeof data.ViGiSITECode.codes != "undefined" )
   {
    var nbViGiSITECode = 0;
    
    $.each( data.ViGiSITECode.codes, 
            function( i, value )
            {
             switch( i )
             {
              case '0': errorCodes = value; break;
              case '1': errorCodes += " (" + value; break;
              default: errorCodes += ", " + value; break;
             }
             
             nbViGiSITECode++;
            } );
    
    if( nbViGiSITECode > 1 )
     errorCodes += ")";
    
    // Description
    if( typeof data.ViGiSITECode.description != "undefined" && data.ViGiSITECode.description != "" )
     errorDescription = data.ViGiSITECode.description;
    
    ViGiSITE.core.ViGiSITECodeShow( errorCodes, errorDescription );
    data.status = false;
   }
   else
   {
    data.status = true;
   }
  }
  else
  {
   data.status = true;
  }
  
  return data;
 };

ViGiSITE.core.ViGiSITECodeShow =
 function( errorCodes, errorDescription )
 {
  if( $("#vigisitecode").length == 0 )
  {
   $("body").append( '<div id="vigisitecode_background"></div>\n'
                   + '<div id="vigisitecode">\n'
                   + ' <a class="close"></a>\n'
                   + ' <img class="error" src="/templates/common/imgs/blank.gif" />\n'
                   + ' <h1>Rapport d\'erreurs</h1>\n'
                   + ' <textarea readonly="readonly"></textarea>\n'
                   + '</div>\n' );
   $("div#vigisitecode_background").attr( "overflow", $("body").css( "overflow" ) );
   $("body").css({ overflow: "hidden" });
   
   $(window).bind( "resize.vigisitecode", 
                   function()
                   {
                    // Center alert
                    $("div#vigisitecode").centerToScreen();
                    
                    // Resize background
                    $("div#vigisitecode_background").animate({ top: $(document).scrollTop(), 
                                                               left: $(document).scrollLeft(), 
                                                               height: $(window).height(), 
                                                               width: $(window).width() });
                   } );
   
   $("div#vigisitecode").centerToScreen( true );
   $("div#vigisitecode_background").css({ top: $(document).scrollTop(), 
                                          left: $(document).scrollLeft(), 
                                          height: $(window).height(), 
                                          width: $(window).width() });
   
   $("a.close", "div#vigisitecode").one( "click", function()
                                                  {
                                                   $("body").css({ overflow: $("#vigisitecode_background").attr( "overflow" ) });
                                                   $("div#vigisitecode, div#vigisitecode_background").remove();
                                                   $(window).unbind( "resize.vigisitecode" );
                                                  } );
   $("textarea", "div#vigisitecode").val( 'Erreurs\n'
                                       + '----------------------------------------\n'
                                       + ( typeof errorCodes == "undefined" || errorCodes == '' ? 'Erreur inconnue' : errorCodes ) + '\n'
                                       + '\n'
                                       + 'Description\n'
                                       + '----------------------------------------\n'
                                       + ( typeof errorDescription == "undefined" || errorDescription == '' ? 'Aucune description' : errorDescription ) + '\n'
                                       + '\n'
                                       + 'User-agent\n'
                                       + '----------------------------------------\n'
                                       + navigator.userAgent );
  }
 };


// calculSizeOfImage

ViGiSITE.core.calculSizeOfImage = 
 function( newWidth, newHeight, originalWidth, originalHeight, evenIfMoreBig, fillSpace )
 {
  if( typeof evenIfMoreBig == undefined ) evenIfMoreBig = false;
  if( typeof fillSpace == undefined ) fillSpace = false;
  
  var size = {};
  var caculSize = function( newWidth, newHeight, originalWidth, originalHeight )
                  {
                   var size = { "width": 0, "height": 0 };
                   
                   if( newWidth == null )
                   {
                    size.height = newHeight;
                    size.width = Math.ceil( newHeight * originalWidth / originalHeight );
                   }
                   else
                   {
                    size.width = newWidth;
                    size.height = Math.ceil( newWidth * originalHeight / originalWidth );
                   }
                   
                   return size;
                  };
  
  if( ( newWidth != null && newWidth < originalWidth )
   || ( newHeight != null && newHeight < originalHeight )
   || evenIfMoreBig == true )
  {
   if( newWidth != null && newHeight != null )
   {
    size = caculSize( newWidth, null, originalWidth, originalHeight );
    
    if( ( fillSpace && ( size.height < newHeight || size.width < newWidth ) )
     || ( !fillSpace && ( size.height > newHeight || size.width > newWidth ) ) )
     size = caculSize( null, newHeight, originalWidth, originalHeight );
   }
   else if( newWidth == null )
    size = caculSize( null, newHeight, originalWidth, originalHeight );
   else if( newHeight == null )
    size = caculSize( newWidth, null, originalWidth, originalHeight );
  }
  else
  {
   size.width = originalWidth;
   size.height = originalHeight;
  }
  
  return size;
 };


// ViGiSITE Prompt

ViGiSITE.core.prompt = 
 function( message, buttons, icon, className )
 {
  buttons = buttons || null;
  icon = icon || "default";
  className = ( ' ' + className ) || null;
  
  if( buttons == null )
  {
   buttons = { "OK": { className: "little", default_button: true } };
  }
  
  if( $("#vigisitealerts").length == 0 )
  {
   $("body").append( '<div id="vigisitealerts"></div>' );
   $("div#vigisitealerts").attr( "overflow", $("body").css( "overflow" ) );
   $("body").css({ overflow: "hidden" });
   $(window).bind( "resize.vigisitealerts", 
                   function()
                   {
                    // Center alert
                    $("div#vigisitealerts div.vigisitealert").centerToScreen();
                    
                    // Resize background
                    $("div#vigisitealerts div.vigisitealert_background").animate({ top: $(document).scrollTop(), 
                                                                                   left: $(document).scrollLeft(), 
                                                                                   height: $(window).height(), 
                                                                                   width: $(window).width() });
                   } );
  }
  
  $("#vigisitealerts").append( '<div class="vigisitealert_background"></div>\n'
                             + '<div class="vigisitealert' + className + '">\n'
                             + ' <a class="close"></a>\n'
                             + ' <p class="content ' + icon + '"></p>\n'
                             + ' <div class="buttons"></div>\n'
                             + '</div>\n' );
  $("div#vigisitealerts div.vigisitealert_background:last").css({ top: $(document).scrollTop(), 
                                                                  left: $(document).scrollLeft(), 
                                                                  height: $(window).height(), 
                                                                  width: $(window).width() });
  $("div#vigisitealerts div.vigisitealert:last p").html( message );
  $("div#vigisitealerts div.vigisitealert:last").centerToScreen(true);
  
  // Buttons
  $.each( buttons,
          function( name, options )
          {
           $("#vigisitealerts div.vigisitealert:last div.buttons").append( '<button name="' + name + '">' + name + '</button>' );
           $("#vigisitealerts div.vigisitealert:last div.buttons button:last")
            .attr( "id", options.id ? options.id : "" )
            .addClass( options.default_button === true ? "selected" : "" )
            .addClass( options.className )
            .click( function()
                    {
                     var close = false;
                     
                     if( $.isFunction( options.callback ) )
                      close = options.callback( $("#vigisitealerts div.vigisitealert:last") );
                     else
                      close = true;
                     
                     if( close == true || typeof close == "undefined" )
                      $(this).parents( "div.vigisitealert" ).children( "a.close" ).click();
                    } );
           
           if( options.default_button === true )
            $("#vigisitealerts div.vigisitealert:last div.buttons button:last").focus();
          } );
  
  // Close button
  $("#vigisitealerts div.vigisitealert:last a.close")
   .click( function()
           {
            $(this).parent( "div.vigisitealert" ).prev( "div.vigisitealert_background" ).remove();
            $(this).parent( "div.vigisitealert" ).remove();
            
            if( $("#vigisitealerts").children().length == 0 )
            {
             $("body").css({ overflow: $("#vigisitealerts").attr( "overflow" ) });
             $("#vigisitealerts").remove();
             $(window).unbind( "resize.vigisitealerts" );
            }
           } );
 };


// ViGiSITE Prompt Upload

ViGiSITE.core.promptUpload = 
 function( options )
 {
  if( typeof options != "undefined" )
  {
   ViGiSITE.core.prompt( '<div id="fileUploadQueue"></div>',
                        {
                         "Parcourir": { id: "fileUpload" },
                         "Envoyer": { callback: function()
                                                {
                                                 ViGiSITE.core.startLoading();
                                                 $( "button#fileUpload" ).uploadifyUpload();
                                                 
                                                 return false;
                                                }, className: "little" },
                         "Annuler": { className: "little", default_button: true }
                        },
                        "upload" );
   
   // Uploadify
   $("#vigisitealerts div.vigisitealert:last div.buttons button#fileUpload")
    .uploadify({
                uploader: '/system/packages/javascript-jquery-uploadify/uploadify.swf',
                script: ( typeof options.script != "undefined" ? options.script : '' ),
                buttonImg: ( typeof options.buttonImg != "undefined" ? options.buttonImg : '/templates/default/imgs/inputButton_browse.png' ),
                cancelImg: '/templates/common/imgs/icons/delete.png',
                wmode: 'transparent',
                width: 150,
                height: 21,
                queueID: 'fileUploadQueue',
                multi: ( typeof options.multi != "undefined" ? options.multi : true ),
                auto: false,
                sizeLimit: ( typeof options.sizeLimit != "undefined" ? options.sizeLimit : 2097152 ),
                fileDesc: ( typeof options.fileDesc != "undefined" ? options.fileDesc : '' ),
                fileExt: ( typeof options.fileExt != "undefined" ? options.fileExt : '' ),
                fileDataName: 'fileUploaded',
                buttonText: 'Parcourir',
                scriptData: ( typeof options.data != "undefined" ? options.data : '' ),
                onAllComplete: function()
                               {
                                if( typeof options.onAllComplete != "undefined" && $.isFunction( options.onAllComplete ) )
                                 options.onAllComplete();
                                
                                window.setTimeout( function()
                                                   {
                                                    $( "a.close", $( "button#fileUpload" ).parents( "div.vigisitealert" ) ).click();
                                                    ViGiSITE.core.stopLoading();
                                                   },
                                                   100 );
                               },
                onComplete: function(event,queueID,fileObj,response,data)
                            {
                             //console.log( event, queueID, fileObj, response, data );
                             response = eval( '(' + response + ')' );
                             response = ViGiSITE.core.ViGiSITECode( response );
                             
                             if( typeof options.onComplete != "undefined" && $.isFunction( options.onComplete ) )
                             {
                              options.onComplete( response );
                             }
                            }
               });
  }
 };

// Lightbox container
ViGiSITE.core.lightbox =
 function( params )
 {
  params = $.extend( {}, ViGiSITE.core.lightbox.defaultParameters, params );
  
  if( $("div#lightbox").length == 0 )
  {
   $("body").append( '<div id="lightbox_background"></div>\n'
                   + '<div id="lightbox">\n'
                   + params.defaultContent
                   + ' <a href="#" id="lightbox_close">Fermer</a>\n'
                   + '</div>\n' );

   $("div#lightbox_background").attr( "overflow", $("body").css( "overflow" ) );
   $("body").css( { "overflow": "hidden" } );
   
   $("div#lightbox_background").css(
    {
     "top": $(document).scrollTop(), 
     "left": $(document).scrollLeft(), 
     "height": $(window).height(), 
     "width": $(window).width()
    } );

   $("div#lightbox").centerToScreen( true );
   
   $("div#lightbox").bind( "lightbox.destruct", function()
    {
     if( $.isFunction( params.destructEvent ) )
      params.destructEvent( myLightbox );
     
     $(window).unbind( "resize.lightbox" );
     $("body").css(
      {
       "overflow": $("#lightbox_background").attr( "overflow" )
      } );
     $("div#lightbox_background, div#lightbox").remove();
     
     $(window).trigger( "resize" );
    } );
    
   var myLightbox = $("div#lightbox");
   
   $(window).bind( "resize.lightbox", function()
    {
     // Resize background
     $("div#lightbox_background").css(
      {
       "top": $(document).scrollTop(), 
       "left": $(document).scrollLeft(), 
       "height": $(window).height(), 
       "width": $(window).width()
      } );
      
     var newSize = 
      {
       "height": $(window).height() - 100,
       "width": $(window).width() - 100
      };
     
     if( $.isFunction( params.resizeEvent ) )
      params.resizeEvent( myLightbox, newSize );

     var posTop = ( $(window).height() - ( newSize.height ) ) / 2 - 10 + $(document).scrollTop();
     var posLeft = ( $(window).width() - ( newSize.width ) ) / 2 + $(document).scrollLeft();
     
     myLightbox.animate(
      {
       "top": posTop,
       "left": posLeft
      } );
    } );
    
   $("#lightbox_close").bind( 'click', function()
   {
    myLightbox.trigger( "lightbox.destruct" );
    return false;
   } );
   
   if( $.isFunction( params.loadEvent ) )
    params.loadEvent( myLightbox );
  }
 };
 
// Lightbox default parameters
ViGiSITE.core.lightbox.defaultParameters = 
 {
  'defaultContent' : '',
  'resizeEvent': function( lightbox, newSize ){},
  'loadEvent': function( lightbox ){},
  'destructEvent': function( lightbox ){}
 };

 
/*
 * Screenshot
 *
 * images: string | [ string, ... ] | [ imageObject, ... ]
 * imageObject: { "uri": string, "description": string }
 * startIndex: integer, 0 <= startIndex <= images.length
 */
 
ViGiSITE.core.screenshot =
 function( images, startIndex )
 {
  ViGiSITE.core.lightbox( {
   'defaultContent': ' <img src="/templates/common/imgs/blank.gif" />\n'
                   + ' <a href="#" id="lightbox_next" class="disabled"></a>\n'
                   + ' <a href="#" id="lightbox_prev" class="disabled"></a>\n',
   'resizeEvent': function( lightbox, newSize )
    {
     var image = lightbox.children( "img" );
     
     // Resize photo
     tmpNewSize = ViGiSITE.core.calculSizeOfImage( newSize.width, newSize.height, image.attr( "naturalWidth" ), image.attr( "naturalHeight" ) );
     
     if( tmpNewSize.width > image.attr( "naturalWidth" ) || tmpNewSize.height > image.attr( "naturalHeight" ) )
     {
      tmpNewSize.width = image.attr( "naturalWidth" );
      tmpNewSize.height = image.attr( "naturalHeight" );
     }
     
     newSize.width = tmpNewSize.width + ( lightbox.outerWidth() -  image.outerWidth() );
     newSize.height = tmpNewSize.height + ( lightbox.outerHeight() -  image.outerHeight() );
     
     image.animate(
      { 
       "width": tmpNewSize.width + "px",
       "height": tmpNewSize.height + "px"
      }, function()
      {
       $(this).css( "visibility", "visible" );
       lightbox.children( "p.description" ).show( "fast" );
      } );
    },
   'loadEvent': function( lightbox )
    {
     var myImg = new Image;
     myImg.onload = function()
      {
       if( typeof myImg.naturalWidth == "undefined" )
       {
        myImg.naturalWidth = myImg.width;
        myImg.naturalHeight = myImg.height;
       }
       
       $(myImg).css(
        {
         "background": "none",
         "visibility": "hidden"
        } );
        
       lightbox.children( "img" ).replaceWith( myImg );
       
       $(window).trigger( "resize.lightbox" );
      };
     
     if( $.isArray( images ) )
     {
      var uris = [];
      var descriptions = [];
      
      var atLeastOneDescription = false;
      
      for( var i in images )
      {
       if( typeof images[ i ] == "string" )
       {
        uris[ i ] = images[ i ];
        descriptions[ i ] = "";
       }
       else
       {
        uris[ i ] = ( typeof images[ i ].uri == "string" ? images[ i ].uri : "" );
        descriptions[ i ] = ( typeof images[ i ].description == "string" ? images[ i ].description : "" );
        
        // Compatibility with old implementations
        if( !atLeastOneDescription && $.trim( descriptions[ i ] ) )
         atLeastOneDescription = true;
       }
      }
      
      lightbox.data( "screenshot.uris", uris );
      lightbox.data( "screenshot.descriptions", descriptions );
      
      if( atLeastOneDescription )
       lightbox.append( $("<p/>").addClass( "description" ).css( "display", "none" ) );
     }
     else if( typeof images == "string" )
     {
      lightbox.data( "screenshot.uris", [ images ] );
     }
     
     if( lightbox.data( "screenshot.uris" ).length > 0 )
     {
      var firstSelected = typeof startIndex == "number" ? startIndex : 0;
      lightbox.data( "screenshot.selected", firstSelected );
      
      myImg.src = lightbox.data( "screenshot.uris" )[ firstSelected ];
      lightbox.children( "p.description" ).html( lightbox.data( "screenshot.descriptions" )[ firstSelected ] );

      if( firstSelected > 0 )
       $("a#lightbox_prev", lightbox).removeClass( "disabled" );
       
      if( firstSelected < lightbox.data( "screenshot.uris" ).length - 1 )
       $("a#lightbox_next", lightbox).removeClass( "disabled" );
      
      $("a#lightbox_next,a#lightbox_prev", lightbox).css( "display", "" );
      
      if( lightbox.data( "screenshot.uris" ).length > 1 )
      {
       $("a#lightbox_next", lightbox).bind( "click", function()
       {
        var selected = lightbox.data( "screenshot.selected" );
        
        if( selected < lightbox.data( "screenshot.uris" ).length - 1 )
        {
         lightbox.data( "screenshot.selected", ++selected );

         lightbox.children( "p.description" ).hide( "fast" );
         lightbox.children( "img" ).fadeTo( "fast", 0.0, function()
          {
           var myImg = new Image;
           myImg.onload = function()
            {
             if( typeof myImg.naturalWidth == "undefined" )
             {
              myImg.naturalWidth = myImg.width;
              myImg.naturalHeight = myImg.height;
             }
             
             $(myImg).css(
              {
               "background": "none",
               "visibility": "hidden",
               "width": lightbox.children( "img" ).width(),
               "height": lightbox.children( "img" ).height()
              } );
              
             lightbox.children( "img" ).replaceWith( myImg );
             
             $("a#lightbox_prev", lightbox).removeClass( "disabled" );
             if( selected == lightbox.data( "screenshot.uris" ).length - 1 )
              $("a#lightbox_next", lightbox).addClass( "disabled" );
             
             $(window).trigger( "resize.lightbox" );
            };
           
           myImg.src = lightbox.data( "screenshot.uris" )[ selected ];
           lightbox.children( "p.description" ).html( lightbox.data( "screenshot.descriptions" )[ selected ] );
          } );
        }
        
        return false;
       } );
       
       $("a#lightbox_prev", lightbox).bind( "click", function()
       {
        var selected = lightbox.data( "screenshot.selected" );
        
        if( selected > 0 )
        {
         lightbox.data( "screenshot.selected",--selected );
         
         lightbox.children( "p.description" ).hide( "fast" );
         lightbox.children( "img" ).fadeTo( "fast", 0.0, function()
          {
           var myImg = new Image;
           myImg.onload = function()
            {
             if( typeof myImg.naturalWidth == "undefined" )
             {
              myImg.naturalWidth = myImg.width;
              myImg.naturalHeight = myImg.height;
             }
             
             $(myImg).css(
              {
               "background": "none",
               "visibility": "hidden",
               "width": lightbox.children( "img" ).width(),
               "height": lightbox.children( "img" ).height()
              } );
              
             lightbox.children( "img" ).replaceWith( myImg );
             
             $("a#lightbox_next", lightbox).removeClass( "disabled" );
             if( selected == 0 )
              $("a#lightbox_prev", lightbox).addClass( "disabled" );
              
             $(window).trigger( "resize.lightbox" );
            };
            
           myImg.src = lightbox.data( "screenshot.uris" )[ selected ];
           lightbox.children( "p.description" ).html( lightbox.data( "screenshot.descriptions" )[ selected ] );
          } );
        }
        
        return false;
       } );
      }
     }
    }
  } );
 };

// Show screenshot
/*ViGiSITE.core.screenshot = 
 function( uri )
 {
  if( $("#screenshot").length == 0 )
  {
   $("body").append( '<div id="screenshot_background"></div>\n'
                   + '<div id="screenshot">\n'
                   + ' <img src="/templates/common/imgs/blank.gif" />\n'
                   + '</div>\n' );
   $("div#screenshot_background").attr( "overflow", $("body").css( "overflow" ) );
   $("body").css({ overflow: "hidden" });
   
   $("div#screenshot_background").css({ top: $(document).scrollTop(), 
                                        left: $(document).scrollLeft(), 
                                        height: $(window).height(), 
                                        width: $(window).width() });
   $("div#screenshot").centerToScreen( true );
   
   $(window).bind( "resize.screenshot", function(){ $("div#screenshot img").trigger( "resizeImg" ); } );
   $("div#screenshot img").live( "resizeImg",
                                 function()
                                 {
                                  // Resize background
                                  $("div#screenshot_background").css({ top: $(document).scrollTop(), 
                                                                       left: $(document).scrollLeft(), 
                                                                       height: $(window).height(), 
                                                                       width: $(window).width() });
                                  
                                  // Resize photo
                                  var newSize = ViGiSITE.core.calculSizeOfImage( $(window).width() - 100, $(window).height() - 100, $(this).attr("naturalWidth"), $(this).attr("naturalHeight") );
                                  if( newSize.width > $(this).attr("naturalWidth") || newSize.height > $(this).attr("naturalHeight") )
                                  {
                                   newSize.width = $(this).attr("naturalWidth");
                                   newSize.height = $(this).attr("naturalHeight");
                                  }
                                  var paddingX = $(this).parent().outerWidth() - $(this).outerWidth();
                                  var paddingY = $(this).parent().outerHeight() - $(this).outerHeight();
                                  var posTop = ( $(window).height() - ( newSize.height + paddingY ) ) / 2 - 10 + $(document).scrollTop();
                                  var posLeft = ( $(window).width() - ( newSize.width + paddingX ) ) / 2 + $(document).scrollLeft();
                                  
                                  $(this).animate({ width: newSize.width + "px", height: newSize.height + "px" });
                                  $(this).parent().animate({ top: posTop, left: posLeft });
                                 } )
                          .live( "click",
                                 function(e)
                                 {
                                  if( e.button == 0 )
                                  {
                                   $(window).unbind( "resize.screenshot" );
                                   $(this).die( "click" );
                                   $(this).die( "resizeImg" );
                                   
                                   $("body").css({ overflow: $("#screenshot_background").attr( "overflow" ) });
                                   $("div#screenshot_background, div#screenshot").remove();
                                  }
                                  else
                                  {
                                   return false;
                                  }
                                 } );
   
   var myImg = new Image;
       myImg.onload = function()
                      {
                       var newSize = ViGiSITE.core.calculSizeOfImage( $(window).width() - 100, $(window).height() - 100, myImg.width, myImg.height );
                       if( newSize.width > myImg.width || newSize.height > myImg.height )
                       {
                        newSize.width = myImg.width;
                        newSize.height = myImg.height;
                       }
                       var paddingX = $(this).parent().outerWidth() - $(this).outerWidth();
                       var paddingY = $(this).parent().outerHeight() - $(this).outerHeight();
                       var posTop = ( $(window).height() - ( newSize.height + paddingY ) ) / 2 - 10 + $(document).scrollTop();
                       var posLeft = ( $(window).width() - ( newSize.width + paddingX ) ) / 2 + $(document).scrollLeft();
                       
                       $(myImg).css({ background: "none", visibility: "hidden" });
                       $("div#screenshot img").replaceWith( myImg );
                       
                       $("div#screenshot img").animate({ width: newSize.width + "px", height: newSize.height + "px" }, function(){ $(this).css( "visibility", "visible" ); });
                       $("div#screenshot").animate({ top: posTop, left: posLeft });
                      };
       myImg.src = uri;
  }
 };*/