var firstClickRow = -1;
var handlingShiftClick = false;

function tdMouseOver( td )
{
    $( td.parentNode ).addClassName( 'rigaSelezionata' );
}

function tdMouseOut( td )
{
    $( td.parentNode ).removeClassName( 'rigaSelezionata' );
}

function selezionaPrimoInput( td )
{
    var tr = td.parentNode;
    var inputs = $( tr ).getElementsBySelector( 'input' );

	if( inputs && ( inputs.length > 0 ))
		inputs[ 0 ].click();
}

function doAction( act )
{
	var f = document.forms[ 0 ];

	f.elements[ 'act' ].value = act;

	f.submit();
	
	return( false );
}

function goTo( act )
{
	location.href = getRootPath() + "?act=" + act;
}

function goToPage( pag )
{
	$( 'page' ).value = pag;

	document.forms[ 0 ].submit();
}

function getRootPath()
{
	return( $F( 'rootPath' ));
}

function enableShiftSelection()
{
    var cbs = $$( '.colonnaCheck input' );
    
    cbs.each( function( cb )
              {
                  Event.observe( cb, 'click', tableSelectionHandler.bindAsEventListener( cb ));
              } );
}

function tableSelectionHandler( event )
{
    if( !handlingShiftClick ) {
        var tr = this;

		if( tr.hasClassName( 'noShiftClick' ))
			return;
        
        handlingShiftClick = true;

        while( tr.tagName != 'TR' )
            tr = tr.parentNode;
            
        if( event.shiftKey && ( firstClickRow >= 0 )) {
            var start = Math.min( tr.rowIndex, firstClickRow );
            var end = Math.max( tr.rowIndex, firstClickRow );
            var table = tr;
        
            while( table.tagName != 'TABLE' )
                table = table.parentNode;

            while( start <= end ) {
                var input;
                
                tr    = table.rows[ start++ ];
                input = tr.cells[ 0 ].getElementsByTagName( 'input' )[0];
                
                // imposta al contrario del valore desiderato
                input.checked = event.ctrlKey;
                
                // imposta il valore corretto e chiama l'eventuale evento associato al click
                input.click();
            }
                
            if( Prototype.Browser.IE ) {
                
                this.checked = !event.ctrlKey;
                
                this.click();
            }
        
        } else
            firstClickRow = tr.rowIndex;
            
        handlingShiftClick = false;
    }
}

function autoEnableActionButtons()
{
    var forTable = $$( '.attivaSuSelezione' );
    
    if( forTable.length > 0 ) {
    
        forTable.each( function( bt ) {
            var tableId = bt.classNames().grep( /tabella.*/ )[0].substr( 7 );
            var cbs = $$( '#' + tableId + ' .colonnaCheck input' );

            cbs.each( function( cb )
                      {
                          Event.observe( cb, 'click', autoEnableButtonsForTable.bindAsEventListener( cb, tableId ));
                      } );
                      
            autoEnableButtonsForTable( null, tableId );
        } );
    }
}

function autoEnableButtonsForTable( event, tableID )
{
    var list = $$( '#' + tableID + ' .colonnaCheck input' );
    var bts = $$( '.attivaSuSelezione.tabella' + tableID );
    var enable = list.anyIsChecked();
	var selectAll = $$( '#' + tableID + ' .selectAll' );
	
	if( selectAll && selectAll.length )
		selectAll[0].checked = false;
    
    if( enable )
        bts.each( Form.Element.enable );
    else
        bts.each( Form.Element.disable );
}

function enableSelectAlls()
{
    var forTable = $$( '.selectAll' );
    
    if( forTable.length > 0 ) {
    
        forTable.each( function( cb ) {
            var tableId = cb.classNames().grep( /table.*/ )[0].substr( 5 );

            Event.observe( cb, 'click', selectAllCheckboxesForTable.bindAsEventListener( cb, tableId ));
        } );
    }
}

function selectAllCheckboxesForTable( event, tableID )
{
    var cbs = $$( '#' + tableID + ' .colonnaCheck input' );
	var checked = this.checked;

	cbs.each( function( cb ) 
	{
		if( cb.checked != checked )
			cb.click();
	} );
	
	this.checked = checked;
}

function makeTablesSortable()
{
    var tables = $$( 'table.sortable' );
    
    for( var i = tables.length - 1; i >= 0; i-- ) {
        var table = tables[ i ];
        
        makeTableSortable( table.id );
    }
}

function makeTableSortable( tableId )
{
    var f = document.forms[ 0 ];
    var sortCol = f.elements[ tableId + 'SortCol' ].value;
    var sortDir = f.elements[ tableId + 'SortDir' ].value;
    var ths = $$( '#' + tableId + ' th.sortable' );
    var img = getSortImg( sortDir );
    var defTH = null, colFound = false;
    
    for( var i = ths.length - 1; i >= 0; i-- ) {
        var th = ths[ i ];
        
        Event.observe( th, 'click', sortTable.bindAsEventListener( th, tableId, th.id ));
        
        if( th.id == sortCol ) {

            th.innerHTML = th.innerHTML + img;
            colFound     = true;
        }
        
        if( Element.hasClassName( th, 'defaultSorting' ) ||
            Element.hasClassName( th, 'defaultSortingDesc' ))
            defTH = th;
    }
    
    if( !colFound && defTH ) {

        sortDir = Element.hasClassName( defTH, 'defaultSortingDesc' ) ? 'desc' : 'asc';
    
        defTH.innerHTML = defTH.innerHTML + getSortImg( sortDir );

        f.elements[ tableId + 'SortCol' ].value = defTH.id;
        f.elements[ tableId + 'SortDir' ].value = sortDir;
    }
}

function getSortImg( sortDir )
{
    var img = '<img src="' + getRootPath() + 'images/Sort';
    
    img += ( sortDir == 'asc' ) ? 'Asc' : 'Dsc';
    img += '.gif">';
    
    return( img );
}

function sortTable( event, tableId, colId )
{
    var f = document.forms[ 0 ];
    var sortCol = f.elements[ tableId + 'SortCol' ].value;
    var sortDir = f.elements[ tableId + 'SortDir' ].value;
    
    if( sortCol == colId )
        f.elements[ tableId + 'SortDir' ].value = ( sortDir == 'asc' ) ? 'desc' : 'asc';
    else {
    
        f.elements[ tableId + 'SortCol' ].value = colId;
        f.elements[ tableId + 'SortDir' ].value = 'asc';
    }
    
    f.submit();
}

function defaultPopupParams( width, height )
{
    var x = parseInt(( screen.availWidth - width ) / 2 );
    var y = parseInt(( screen.availHeight - height ) / 2 );

    return( 'alwaysRaised=yes,dependent=yes,directories=no,hotkeys=no,' +
            'location=no,menubar=no,status=no,scrollbars=yes,toolbar=no,' +
            'resizable=yes,width=' + width + ',height=' + height + ',left=' + x + 
            ',top=' + y );
}

function calSetup( txt, btn, options )
{
	opts = $H( {
		inputField : txt,
		button     : btn,
		ifFormat   : '%d/%m/%Y',
		firstDay   : 1
    } );

	if( options != undefined )
		opts = opts.merge( options );
		
	Calendar.setup( opts.toObject() );
}

function trim(str, chars) 
{
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) 
{
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) 
{
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function getFragment()
{
	var ret = window.location.href.split( '#' );

	if( ret && ( ret.length >= 2 ))
		ret = ret[ 1 ];
	else
		ret = '';
	
	return( ret );
}

function viewportHeight()
{
	return self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);
}

function showFlash( id, width, height, movie )
{
	AC_FL_RunContent( 'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
					  'width', width,
					  'height', height,
					  'src', movie,
					  'quality', 'high',
					  'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
					  'align', 'left',
					  'play', 'true',
					  'loop', 'true',
					  'scale', 'showall',
					  'wmode', 'window',
					  'devicefont', 'false',
					  'id', id,
					  'bgcolor', '#ffffff',
					  'name', id, 
					  'menu', 'true',
					  'allowFullScreen', 'false',
					  'allowScriptAccess','sameDomain',
					  'movie', movie.substring( 0, movie.length - 4 ),
					  'salign', ''
	);
}

