/**
 * @author Loops <pierrot at nvision dot lu>
 *
 * Custom javascript function used for Carre Rotondes web site.
 *
 * These functions are used to load block, news detail and events
 * detail helping AJAX and jQuery.
 */    

/* VARIABLES */
         
/**
 * An collections or propreties used as default margin for block drop area definition
 *
 * @var    object
 * @access global
 */
var dropAreaMargins = { 'top' : 6 }

/**
 * An collections of propreties of default settings to use for jScrollPane
 *
 * @var     object
 * @access  global
 */
var jScrollPaneSettings = {
                            scrollbarWidth: 9 , // Width of the scrollbar
                            dragMaxHeight: 15 , // Maximum height of the scrollbar drag
                            maintainPosition: true , // Default value, just to be sure that this setting is alterable
                            reinitialiseOnImageLoad: true // Reinitialize scrollbar on image load
                          };                          
                          
/**
 * Global array to save height from block expanding
 *
 * @var    object
 * @access global
 */
var blocksInitialHeightByIds = {};

/* FUNCTIONS */

/**
 * Restore onClick to focus event on input, textarea, select and button.
 * Use to fix Firefox 2 bug on form load helping AJAX.
 *
 */ 
function restoreFocus( elementDef )
{
  jQuery(elementDef+' input').bind( 'click' , function(e){ this.focus(); } );
  jQuery(elementDef+' textarea').bind( 'click' , function(e){ this.focus(); } );
  jQuery(elementDef+' select').bind( 'click' , function(e){ this.focus(); } );
  jQuery(elementDef+' button').bind( 'click' , function(e){ this.focus(); } );
}

/**
 * Determine position for block appearence.
 */
function blockPosition( polyId , blockId )
{
  if( jQuery('#'+polyId).css('display') !== 'none' )
  {
    var polyPos = jQuery('#'+polyId).position();
    var w = jQuery('.main').width();
    var h = jQuery('.main').height();
    var blockVal  = {'v':polyPos.left,'h':polyPos.top};
    var blockProp = {'v':'left','h':'top'};
    var bw = jQuery('#'+blockId).width();
    var bh = jQuery('#'+blockId).height();
    if( blockVal.v > w/2 )
    {
      blockVal.v = w - blockVal.v - jQuery('#'+polyId).width();
      blockProp.v = 'right';
    }
    /* Check if height is available */
    if( blockVal.h + bh > h )
    {
      blockVal.h = h - bh;
    }
    /*
    if( blockVal.h > h/2 )
    {
      blockVal.h = h - blockVal.h - jQuery('#'+polyId).height();
      blockProp.h = 'bottom';
    }
    */
    if( blockVal.h < dropAreaMargins.top )
    {
      blockVal.h = dropAreaMargins.top;
    }
    jQuery('#'+blockId).css(blockProp.v,blockVal.v+'px');
    jQuery('#'+blockId).css(blockProp.h,blockVal.h+'px');
    /* Show block */
    jQuery('#'+blockId).show();
    jQuery('#'+polyId).hide();
  }
} 

/**
 * Load a block helping its id and blocksUrlByIds object
 *
 */
function loadBlock( polyId , initial , callback )
{ 
  var blockId = polyId.replace(/poly$/,'block');
  try
  { 
    if( document.getElementById( blockId ) )
    {

      /* Set position */
      blockPosition( polyId , blockId );
      /* Set z-index */
      jQuery('#'+blockId).css('z-index',( new Date().getHours() * 10000 ) + ( new Date().getMinutes() * 100 ) + ( new Date().getSeconds() ));
      // Initial tab
      if( initial && typeof initial == 'number' && initial > 0 )
      {
        jQuery('#'+blockId).triggerTab( initial , callback );
      }
    }
    else
    {
      if( undefined === blocksUrlByIds[blockId] )
      {
        throw 'Block "' + blockId + '" is not defined.';
      }

      var local_initial = tabDefaultPositionBySpace[blockId];      
      
      /* Lauch AJAX request */
      jQuery.post( 
        /* Requested URL */
        blocksUrlByIds[blockId] , 
        /* Data to Post */
        {} , 
        /* Callback function */
        function( data, textStatus )
        {
          /* Append data to main content */
          jQuery('.main').append(data);
          /* Set position */
          blockPosition( polyId , blockId );
          /* Set z-index */
          jQuery('#'+blockId).css('z-index', ( new Date().getHours() * 10000 ) + ( new Date().getMinutes() * 100 ) + ( new Date().getSeconds() ) );          
          /* Load tabs */  
          jQuery('#'+blockId).tabs( {
              initial: parseInt(local_initial),
              fxSlide: true, 
              fxFade: true, 
              fxSpeed: 'fast', 
              remote: true,
              spinner: '',
              /* bookmarkable: true, */ /* don't know how to use it */
              onShow: function( link , toShow , toHide )
              {       
                
                /* Restore initial height for parent block */
                if( jQuery('#'+toHide.id).parents('.block').hasClass('detailed') )
                {
                  jQuery('#'+toHide.id).parents('.block').removeClass('detailed');
                  if( blocksInitialHeightByIds[jQuery('#'+toHide.id).parents('.block').attr('id')] )
                  {
                    jQuery('#'+toHide.id+' .jScrollPaneContainer').css( 'height' , blocksInitialHeightByIds[jQuery('#'+toHide.id).parents('.block').attr('id')] );
                    jQuery('#'+toHide.id+' .container').css( 'height' , blocksInitialHeightByIds[jQuery('#'+toHide.id).parents('.block').attr('id')] );
                  }
                }
                /* Check for sub navigation */
                if( jQuery('#'+toShow.id+' .sub-nav').length > 0 )
                {
                  /* Load sub-tabs */  
                  jQuery('#'+toShow.id+' .sub-nav').tabs( {
                    fxSlide: true, 
                    fxFade: true, 
                    fxSpeed: 'fast', 
                    remote: true,
                    spinner: '',
                    /* bookmarkable: true, */ /* don't know how to use it */
                    onShow: function( link , toShow , toHide )
                    {
                      /* Restore initial height for parent block */
                      if( jQuery('#'+toHide.id).parents('.block').hasClass('detailed') )
                      {
                        jQuery('#'+toHide.id).parents('.block').removeClass('detailed');
                        if( blocksInitialHeightByIds[jQuery('#'+toHide.id).parents('.block').attr('id')] )
                        {
                          jQuery('#'+toHide.id+' .jScrollPaneContainer').css( 'height' , blocksInitialHeightByIds[jQuery('#'+toHide.id).parents('.block').attr('id')] );
                          jQuery('#'+toHide.id+' .container').css( 'height' , blocksInitialHeightByIds[jQuery('#'+toHide.id).parents('.block').attr('id')] );
                        }
                      }
                      /* Load scrollpane */
                      jQuery('#'+toShow.id+' .container').jScrollPane( jScrollPaneSettings );
                      /* Restore focus on click */
                      restoreFocus( '#'+toShow.id+' .container' );
                    }, 
                    onLoad: function( hash )
                    {     
                      /* Load scrollpane */
                      jQuery(hash+' .container').jScrollPane( jScrollPaneSettings );
                      /* Restore focus on click */
                      restoreFocus( hash+' .container' );
                      // Initial tab
                      
                      if( initial && typeof initial == 'number' && initial > 0 )
                      {
                        jQuery('#'+toShow.id).triggerTab( initial , callback );
                      } 
                    }
                  } );
                  
                  /* Load scrollpane just for sub container */
                  jQuery('#'+toShow.id+' .sub-nav .container').jScrollPane( jScrollPaneSettings ); 
                  /* Restore focus on click */
                  restoreFocus( '#'+toShow.id+' .sub-nav .container' );
                }
                else
                {
                  /* Load scrollpane */
                  jQuery('#'+toShow.id+' .container').jScrollPane( jScrollPaneSettings );
                  /* Restore focus on click */
                  restoreFocus( '#'+toShow.id+' .container' );
                }
                
              }, 
              onLoad: function( hash )
              {           
                /* Check for sub navigation */
                if( jQuery(hash+' .sub-nav').length > 0 )
                {       
                  /* Load sub-tabs */
                  jQuery(hash+' .sub-nav').tabs( {
                    fxSlide: true, 
                    fxFade: true, 
                    fxSpeed: 'fast', 
                    remote: true,
                    spinner: '',
                    /* bookmarkable: true, */ /* don't know how to use it */
                    onShow: function( link , toShow , toHide )
                    {        
                      /* Restore initial height for parent block */
                      if( jQuery('#'+toHide.id).parents('.block').hasClass('detailed') )
                      {
                        jQuery('#'+toHide.id).parents('.block').removeClass('detailed');
                        if( blocksInitialHeightByIds[jQuery('#'+toHide.id).parents('.block').attr('id')] )
                        {
                          jQuery('#'+toHide.id+' .jScrollPaneContainer').css( 'height' , blocksInitialHeightByIds[jQuery('#'+toHide.id).parents('.block').attr('id')] );
                          jQuery('#'+toHide.id+' .container').css( 'height' , blocksInitialHeightByIds[jQuery('#'+toHide.id).parents('.block').attr('id')] );
                        }
                      }
                      /* Load scrollpane */
                      jQuery('#'+toShow.id+' .container').jScrollPane( jScrollPaneSettings );
                      /* Restore focus on click */
                      restoreFocus( '#'+toShow.id+' .container' );
                    }, 
                    onLoad: function( hash )
                    {
                      /* Load scrollpane */
                      jQuery(hash+' .container').jScrollPane( jScrollPaneSettings );
                      /* Restore focus on click */
                      restoreFocus( hash+' .container' );
                    }
                  } ); 
                  
                  /* Load scrollpane just for sub container */
                  jQuery(hash+' .sub-nav .container').jScrollPane( jScrollPaneSettings );  
                  /* Restore focus on click */
                  restoreFocus( hash+' .sub-nav .container' );
                }
                else
                {            
                  /* Load scrollpane */
                  jQuery(hash+' .container').jScrollPane( jScrollPaneSettings );
                  /* Restore focus on click */
                  restoreFocus( hash+' .container' );
                }
                
                // Initial tab
                if( initial && typeof initial == 'number' && initial > 0 )
                {
                  jQuery(hash).parents('.block').triggerTab( initial , callback );
                }
              }
            } );               
          /* Enable easyDrag */       
          jQuery('#'+blockId).easydrag();
          jQuery('#'+blockId).setHandler('ul.tabs-nav');
          jQuery('#'+blockId).setDropArea('.main' , dropAreaMargins );
        } ,
        /* Type of received data */
        'html' );
    }
  }
  catch( msg )
  {
    alert( msg );
  }
}

/**
 * Load news helping its id
 *
 */
function loadNewsDetail( newsId , summaryNode )
{
  /* Lauch AJAX request */
  jQuery.post( 
    /* Requested URL */
    'news/details/' , 
    /* Data to Post */
    { 'id' : newsId } , 
    /* Callback function */
    function( data, textStatus )
    {
      /* Append data to a created detail block */
      var detailNode = jQuery('<div></div>').attr({'className':'news-detail'}).append( data );
      /* Slide up summary */
      jQuery(summaryNode).slideUp(
        'fast' ,
        function()
        {
          /* Append detail block after summary block */
          jQuery(summaryNode).after( detailNode );
          /* Slide down detail */
          jQuery(detailNode).slideDown(
            'normal' , 
            function()
            {
              /* Go to main block */
              if( ! jQuery(summaryNode).parents('.block').hasClass('detailed') )
              {
                /* Save initial height */
                blocksInitialHeightByIds[jQuery(summaryNode).parents('.block').attr('id')] = jQuery(summaryNode).parents('.jScrollPaneContainer').css( 'height' );
                /* Append new height for parent block */
                jQuery(summaryNode).parents('.block').addClass('detailed');
                /* Append new height for scrollbar container */
                jQuery(summaryNode).parents('.jScrollPaneContainer').css( 'height' , '570px' /*jQuery(summaryNode).parents('.container').css( 'height' )*/ );
              }
              /* Reinitialize jScrollPane */
              jQuery(summaryNode).parents('.container').jScrollPane( jScrollPaneSettings );
            } 
          );
        }
      );
      /* Set back link */
      jQuery(detailNode).find('.back').bind(
        'click' , 
        function(e)
        {
          jQuery(detailNode).slideUp(
            'normal' , 
            function()
            {
              /* Remove detail */
              jQuery(detailNode).remove();
              /* Slide down summary */
              jQuery(summaryNode).slideDown(
                'normal' , 
                function()
                {
                  /* Check if there is some opened news */
                  if( ! jQuery(summaryNode).parents('.block').find('.news-detail').length )
                  {
                    /* Restore initial height for parent block */
                    jQuery(summaryNode).parents('.block').removeClass('detailed');
                    /* Restore initial height for scrollbar container */
                    jQuery(summaryNode).parents('.jScrollPaneContainer').css( 'height' , blocksInitialHeightByIds[jQuery(summaryNode).parents('.block').attr('id')] );
                  }
                  /* Reinitialize jScrollPane */
                  jQuery(summaryNode).parents('.container').jScrollPane( jScrollPaneSettings );
                } 
              );
            } 
          );
        }
      );
    } ,
    /* Type of received data */
    'html' );
}


/**
 * Load event helping its id
 *
 */
function loadEventDetail( eventId , listElement , polyIdToLoad )
{
  if( polyIdToLoad && typeof polyIdToLoad == 'string' )
  {
    var blockIdToLoad = polyIdToLoad.replace(/poly$/,'block');
    if( jQuery('#'+blockIdToLoad+' .event-detail').length > 0 )
    {
      /* IE bug fix */
      var tmp1 = jQuery('#'+blockIdToLoad+' .event-detail').css( 'display' ) === 'block';
      var tmp2 = jQuery('#'+blockIdToLoad+' .event-detail').parent().parent().parent().css( 'display' ) === 'block';
      if( tmp1 && tmp2 )
      {
        jQuery('#'+blockIdToLoad+' .event-detail .back:eq(0)').trigger('click');
      }
    }
    loadBlock( polyIdToLoad , 2 , function( hash ){
        loadEventDetail( eventId , jQuery('#'+blockIdToLoad+' .events-list-container').get(0) );
      });
  }
  else
  { 
    /* Lauch AJAX request */
    jQuery.post( 
      /* Requested URL */
      'event/details/' , 
      /* Data to Post */
      { 'id' : eventId } , 
      /* Callback function */
      function( data, textStatus )
      {
        /* Append data to a created detail block */
        var detailNode = jQuery('<div></div>').attr({'className':'event-detail'}).append( data );
            
        /* Slide up parent block */
        jQuery(listElement).slideUp(
          'fast' ,
            function()
            {
              /* Append detail block in parent block */
              jQuery(listElement).after( detailNode );
              /* remove event search */
              jQuery(detailNode).parents('.tabs-container').children('.events-search').slideUp();
              /* Slide down detail */
              jQuery(detailNode).slideDown(
                'normal' , 
                function()
                {
                  /* Save initial height */
                  blocksInitialHeightByIds[jQuery(listElement).parents('.block').attr('id')] = jQuery(listElement).parents('.jScrollPaneContainer').css( 'height' );
                  /* Happend new height for parent block */
                  jQuery(listElement).parents('.block').addClass('detailed');
                  /* Append new height for scrollbar container */
                  jQuery(listElement).parents('.jScrollPaneContainer').css( 'height' , '530px' /*jQuery(summaryNode).parents('.container').css( 'height' )*/ );
                  /* Reinitialize jScrollPane */
                  jScrollPaneSettings.maintainPosition = false;
                  jQuery(listElement).parents('.container').jScrollPane( jScrollPaneSettings );
                  jScrollPaneSettings.maintainPosition = true;
                } 
              );
              /* Set back link */
              jQuery(detailNode).find('.back').bind(
                'click' , 
                function(e)
                {
                  /* Slide up parent block */
                  jQuery(detailNode).slideUp(
                    'fast' ,
                    function()
                    {
                      /* Remove detail */
                      jQuery(detailNode).remove();
                      /* Slide down list */
                      jQuery(listElement).slideDown(
                        'normal' , 
                        function()
                        {
                          /* Restore search */
                          jQuery(listElement).parents('.tabs-container').children('.events-search').slideDown();   
                          /* Restore initial height for parent block */
                          jQuery(listElement).parents('.block').removeClass('detailed');
                          /* Restore initial height for scrollbar container */
                          jQuery(listElement).parents('.jScrollPaneContainer').css( 'height' , blocksInitialHeightByIds[jQuery(listElement).parents('.block').attr('id')] );
                          /* Reinitialize jScrollPane */
                          jScrollPaneSettings.maintainPosition = false;
                          jQuery(listElement).parents('.container').jScrollPane( jScrollPaneSettings );
                          jScrollPaneSettings.maintainPosition = true;
                        }
                      );
                    }
                  );
                }
              );
            }
          );
        
        } ,
        /* Type of received data */
        'html' );
   }
}

/**
 * Load pics helping its id
 *
 */
function loadPicsDetail( picsId , listElement )
{
  /* Lauch AJAX request */
  jQuery.post( 
    /* Requested URL */
    'pics/details/' , 
    /* Data to Post */
    { 'id' : picsId } , 
    /* Callback function */
    function( data, textStatus )
    {
      /* Append data to a created detail block */
      var detailNode = jQuery('<div></div>').attr({'className':'pics-detail'}).append( data );
      /* Slide up parent block */
      jQuery(listElement).slideUp(
        'fast' ,
          function()
          {
            /* Append detail block in parent block */
            jQuery(listElement).after( detailNode );
            tb_init('a.thickbox');
            /* Slide down detail */
            jQuery(detailNode).slideDown(
              'normal' , 
              function()
              {  
                /* Exception for pics loaded from pics block */
                if (jQuery(listElement).parent('#pics-block') != "undefined")
                {
                  /* get details and put it under the second menu */
                  jQuery('#pics-block .container .pics-detail .left-box:eq(0)').insertAfter('#pics-block .sub-nav .tabs-nav:eq(0)');
                } 
                
                /* Save initial height */
                blocksInitialHeightByIds[jQuery(listElement).parents('.block').attr('id')] = jQuery(listElement).parents('.jScrollPaneContainer').css( 'height' );
                /* Happend new height for parent block */
                jQuery(listElement).parents('.block').addClass('detailed');
                /* Reinitialize jScrollPane */           
                jScrollPaneSettings.maintainPosition = false;
                jQuery(listElement).parents('.container').jScrollPane( jScrollPaneSettings );
                jScrollPaneSettings.maintainPosition = true;
                
                                                             
              } 
            );
            
            /* Set back link */
            jQuery(detailNode).find('.back').bind(
              'click' , 
              function(e)
              {
                /* Slide up parent block */
                jQuery(detailNode).slideUp(
                  'fast' ,
                  function()
                  {
                    /* Remove detail */
                    jQuery(detailNode).remove();
                    
                    /* Exception for pics loaded from pics block */
                    if (jQuery(listElement).parent('#pics-block') != "undefined")
                    {
                      hidePicsDetails();
                    }
                    
                    /* Slide down list */
                    jQuery(listElement).slideDown(
                      'normal' , 
                      function()
                      {
                        
                        /* Restore initial height for parent block */
                        jQuery(listElement).parents('.block').removeClass('detailed');
                        /* Restore initial height for scrollbar container */
                        jQuery(listElement).parents('.jScrollPaneContainer').css( 'height' , blocksInitialHeightByIds[jQuery(listElement).parents('.block').attr('id')] );
                        /* Reinitialize jScrollPane */
                        jScrollPaneSettings.maintainPosition = false;
                        jQuery(listElement).parents('.container').jScrollPane( jScrollPaneSettings );
                        jScrollPaneSettings.maintainPosition = true;
                        
                      }
                    );
                  }
                );
              }
            );
          }
        );
      } ,
      /* Type of received data */
      'html' );
}

function hidePicsDetails(){
  /* get details and put it under the second menu */
  jQuery('#pics-block .sub-nav .left-box:eq(0)').slideUp(
    'fast', 
    function()
    {
      jQuery('#pics-block .sub-nav .left-box:eq(0)').remove();
    }
  );
}

/**
 * Close block helping its id
 *
 */
function closeBlock( blockId )
{
  var polyId = blockId.replace(/block$/,'poly');
  var blockPos = jQuery('#'+blockId).position();
  var w = jQuery('.main').width();
  var h = jQuery('.main').height();
  var polyVals  = {
    'left': 'auto',
    'bottom': 'auto',
    'right': jQuery('.main').width()-blockPos.left-jQuery('#'+blockId).width(),
    'top':   blockPos.top
  };
  /* Hide block */
  jQuery('#'+blockId).hide();
  /* Set position */
  jQuery('#'+polyId).css( polyVals );
  /* Set z-index */
  jQuery('#'+polyId).css('z-index', ( new Date().getHours() * 10000 ) + ( new Date().getMinutes() * 100 ) + ( new Date().getSeconds() ) );          
  /* Show polygone */
  jQuery('#'+polyId).show();
}

/*
function relaunchTb(el){
  alert('passe');
  var t = el.title || el.name || null;
  var a = el.href || el.alt;
  var g = el.rel || false;
  tb_show(t,a,g);
  this.blur();
  return false;
}
*/
