/**
 * @author Loops <pierrot at nvision dot lu>
 *
 * Custom javascript function used for Carre Rotondes web site.
 *
 * These functions are used to search block that appears behind
 * an empty area of another block.
 */
 
function sortZIndex( a , b )
{
  var aZ = jQuery(a).css( 'z-index' );
  var bZ = jQuery(b).css( 'z-index' );
  if( isNaN( bZ ) && isNaN( aZ ) )
  {
    return 0;
  }
  else if( isNaN( aZ ) )
  {
    return -1;
  }
  else if( isNaN( bZ ) )
  {
    return 1;
  }
  else
  {
    return parseInt( new Number(jQuery(a).css('z-index')) - new Number(jQuery(b).css('z-index')) );
  }
} 
 
function searchPoly( e , emptyArea )
{
  var behindBlocks = [];
  
  jQuery('.draggable').each(
    function()
    {
      if( this.id !== emptyArea.parentNode.parentNode.id )
      {
        var p = jQuery(this).windowPosition();
        var w = jQuery(this).width();
        var h = jQuery(this).height();
        
        if( e.pageX > p.x && e.pageX < p.x + w 
         && e.pageY > p.y && e.pageY < p.y + h )
        {
          behindBlocks.push( this );
        }
      }
    }
  );
  
  behindBlocks.sort( sortZIndex ).reverse();
  
  var dataToPost = {};
  
  var p = {};
  for( var i = 0, iMax = behindBlocks.length; i < iMax; i++ )
  {
    p = jQuery(behindBlocks[i]).windowPosition();
    dataToPost['blocks[' + behindBlocks[i].id + '][position]'] = p.x + ',' + p.y;
    dataToPost['blocks[' + behindBlocks[i].id + '][coordinates]'] = jQuery(behindBlocks[i]).find('map>area.drag-handler').attr('coords');
  }
  
  dataToPost['mouse[x]'] = e.pageX;
  dataToPost['mouse[y]'] = e.pageY;
  
  /* launch AJAX determination */
  jQuery.post(
    /* Requested URL */
    'default/determinate/' , 
    /* Data to Post */
    dataToPost , 
    /* Callback function */
    function( data, textStatus )
    {
      if( jQuery('#'+data).length > 0 )
      {
        jQuery('#'+data).css('z-index', ( new Date().getHours() * 10000 ) + ( new Date().getMinutes() * 100 ) + ( new Date().getSeconds() ) );
        jQuery('#'+data).triggerDrag(e);
        jQuery(emptyArea.parentNode.parentNode.id).bind('mouseup' , function(){ jQuery('#'+data).triggerDrop(e); } );
      }
    } ,
    /* Type of received data */
    'text'
  );
}