/**
 * Code by Giancarlo "GM" Moschitta (info@myphp.it) and Simone "negatyve" Auteritano (negatyve@negatyve.com)
 * Powered by jQuery (http://jquery.com))
**/
var SHADE_COL = ''
/**
 * Avvia tutti gli script necessari a ManagerOnline.it
**/
function initManager()
{
	$( '#logo' ).pngFix();
	$( '#newsletter-box-email' ).hint();
	$( '#header-search-form-input' ).hint();
	$( '#sel-networksite' ).change( changeNetworkSite );
	$( '#visit-network-site a' ).click( changeNetworkSite );
	$( 'a[rel*="external"]' ).click( openExternalLink );
	$( '.tab-menu a' ).click( tabMenuButtonClicked );
	setScrollPanesStyles();
	setSideBoxesHoverEffect();
	if( SUBDOMAIN == 'manageronline' ) 
	{
		SHADE_COL = '#ffbd00'; 
	} else {
		SHADE_COL = '#009900';
	}
	$( '.multimedia-box li' )
		.css( 'cursor', 'pointer' )
		.hover( addHoverClass, delHoverClass )
		.click( gotoListInnerLink )
	;
	$( '.share-on-facebook a' ).click( shareOnFacebook );
}

/**
 * Gestisce il click sul pulsante "Segnala su Facebook"
**/
function shareOnFacebook()
{
	var u = location.href;
	var t = document.title;
	window.open
	(
		'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t),
		'sharer','toolbar=0,status=0,width=626,height=436'
	);
	return false;
}

/**
 * Gestice il combobox per visitare gli altri siti del network
**/
function changeNetworkSite()
{
	var value = $( '#sel-networksite' ).val();
	if( value != '' )
	{
		window.location.href = value + '/';
	}
	return false;
}

/**
 * Risolve il bug del select di ie
 *
 * @param select, jQuery, required, Il select
 * @param width, int, required, La larghezza del select chiuso
 * @param isFilter, boolean, required, True se il select è un filtro di categoria
**/
function autoAdjustSelectSize( select, width, isFilter )
{
	if( $.browser.msie )
	{
		select.mouseover
		(
			function()
			{
				var s = $( this );
				s.css( 'width', 'auto' );
				if( s.width() < width )
				{
					s.css( 'width', width + 'px' );
				}
				if( isFilter )
				{
					setFilterButtonVisibility( false );
				}
				setAdjustOnMouseOut( $( this ), width, isFilter );
			}
		);
	}
}
function setAdjustOnMouseOut( select, width, isFilter )
{
	select.mouseout
	(
		function(){ $( this ).css( 'width', width + 'px' );setFilterButtonVisibility( true ); }
	).mousedown
	(
		function(){ $(this).unbind( 'mouseout' ); setAdjustOnBlur( $( this ), width, isFilter ); }
	).unbind( 'blur' );
}
function setAdjustOnBlur( select, width, isFilter )
{
	select.blur
	(
		function(){ $( this ).css( 'width', width + 'px' );setFilterButtonVisibility( true ); }
	);
}

/**
 * Converte le entità html
 *
 * @param s, string, required
**/
function html_entities_decode( s )
{
	var a = $('<textarea />').html( s );
	var d = a.val();
	a.remove();
	return d;
}

/**
 * Converte le entità html
 *
 * @param s, string, required
**/
function html_entities_encode( s )
{
	var a = $('<div />').html( s );
	var d = a.html();
	a.remove();
	return d;
}

/**
 * Esegue il preload di immagini
**/
function preloadImages()
{
	for( var i = 0; i < arguments.length; i++ )
	{
		$( '<img />' ).attr( 'src', arguments[i] );
	}
}

/**
 * Sostituisce gli ampersand nel testo passato
 *
 * @param text, string, required, Il testo in cui effettuare la sostituzione
**/
function fixAmpersand( text )
{
    return text.replace("&","<[AMPERSAND]>");
}

/**
 * Scrive un log nella finestra di firebug
 *
 * @param t, string, required, La stringa da loggare
**/
function debug( t )
{
	if ( window.console && window.console.log )
	{
		window.console.log( "ManagerOnline.it: " + t );
	}
}

/**
 * Gestore degli errori ajax
 *
 * @param result, string, required, Il testo da verificare
 * @return boolean
**/
function ajaxError( result )
{
	var isError = false, errorString = '', match;
	if( result.match(/^Error:/i) )
	{
		isError = true;
		errorString = result.replace('Error:','');
	}
	else if( match = result.match(/<b>(Notice|Warning)<\/b>/i ) )
	{
		isError = true;
		errorString = '';/*match[ 0 ];*/
	}
	if( isError && errorString != '' )
	{
		showAlert( errorString, 'alert' );
	}
	return isError;
}

/**
 * Wrapper dei dialogs di default
 *
 * @param message, string, required, Il messaggio da visualizzare
 * @param type, string, required, Il tipo di Dialog
**/
function showAlert( message, type )
{
	var valid = typeof $.prompt !== 'undefined';
	var isIE6 = $.browser.msie && Number( $.browser.version.split('.')[0] ) <= 6;
	switch( type )
	{
		case 'alert': default:
			if( isIE6 || !valid )
			{
				alert( message );
			} else {
				setBannersVisibility( false );
				$.prompt
				(
					message,
					{
						prefix:'dgi',
						opacity:0.4,
						show:'fadeIn',
						overlayspeed:'fast',
						callback: function( v, m ) { setBannersVisibility( true ); }
					}
				);
			}
			break;

		case 'prompt':
			return window.prompt( message );
			break;

		case 'confirm':
			var callback = arguments[2];
			var param = arguments[3];
			if( isIE6 || !valid )
			{
				if( confirm( message ) )
				{
					callback( param );
				}
			} else {
				$.prompt
				(
					message,
					{
						prefix:'dgi',
						opacity:0.4,
						show:'fadeIn',
						overlayspeed:'fast',
						buttons: { Ok: true, Annulla: false },
						callback: function( v, m)
						{
							if( v ){
								callback( param );
							}
							setBannersVisibility( true );
						}
					}
				);
			}
			break;
	}
}


/**
 * Mostra l'ajax loader nell'elemento indicato
 *
 * @param e, object, required, L'elemento nel quale mostrare il loader
 * @param w, int, optional, L'eventuale larghezza del contenitore
 * @param h, int, optional, L'eventuale altezza del contenitore
**/
function showAjaxLoader( e, w, h )
{
	hideAjaxLoader( e, true );
	var id = e.attr('id');
	var x = (w != undefined && w != 0 ? w : e.width() );
	var y = (h != undefined && h != 0 ? h : e.height() );

	e.append( '<div id="' + ( id + '-ajax-loader' )+ '"><img src="' + SITE_PATH + 'layout/' + SUBDOMAIN + '/ajax-loader.gif" alt="" /></div>' );

	var o = $( '#' + id + '-ajax-loader' );
	o.css( 'position', 'absolute' );
	o.css( 'top', '0px' );
	o.css( 'left', '0px' );
	o.css( 'z-index', '999' );
	o.css( 'width', x + 'px' );
	o.css( 'height', y + 'px' );

	$( '#' + id + '-ajax-loader > img' ).css
	({
		position:'absolute',
		top:( ( y - 32 ) / 2 ) + 'px',
		left:( ( x - 32 ) / 2 ) + 'px'
	});
}

/**
 * Nasconde l'ajax loader nell'elemento indicato
 *
 * @param e, object, required,  L'elemento nel quale nascondere il loader
 * @param s, boolean, optional, True per non eseguire l'animazione di chiusura
**/
function hideAjaxLoader( e, s )
{
	var loader = $( '#' + e.attr('id') + '-ajax-loader' );

	s = true;

	if( s )
	{
		loader.remove();
	} else {
		loader.fadeOut
		(
			'slow',
			function(){ loader.remove(); }
		);
	}
}

/**
 * Associato ad un tag <a>, ne apre il link in una nuova finestra
**/
function openExternalLink()
{
	window.open( $( this ).attr( 'href' ) );
	return false;
}

/**
 * Richiama una pagina html
 *
 * @param item, object, required, L'elemento selezionato
 * @oaram type, string, required, Il tipo di risorsa a cui redirigere la pagina
**/
function gotoSelectedPage( item, type )
{
	if( typeof type == 'undefined' )
	{
		type = 'default';
	}
	switch( type )
	{
		case 'default':
			window.location.href = item;
			break;
	}
	return false;
}

/**
 * Imposta gli stili degli scrollpane
**/
function setScrollPanesStyles()
{
	$( '.scroll-pane' ).jScrollPane
	(
		{ scrollbarWidth:14, dragMaxHeight:36, dragMinHeight:36 }
	);
}

/**
 * Setta il rollover sugli elementi dei box laterali
**/
function setSideBoxesHoverEffect()
{
	$( '#subdomain-side-box .scroll-list-items ul li' ).each
	(
		function()
		{
			$( this )
				.hover
				(
					function(){ $( this ).addClass( 'hovered' ); },
					function(){ $( this ).removeClass( 'hovered' ); }
				)
				.css( 'cursor', 'pointer' )
				.click
				(
					function()
					{
						gotoSelectedPage( $( this ).find( 'a.title' ).attr( 'href' ) );
					}
				)
			;
		}
	);
	$( '#resources-side-box .scroll-list-items ul li' ).each
	(
		function()
		{
			$( this )
				.hover
				(
					function(){ $( this ).addClass( 'hovered' ); },
					function(){ $( this ).removeClass( 'hovered' ); }
				)
				.css( 'cursor', 'pointer' )
				.click
				(
					function()
					{
						gotoSelectedPage( $( this ).find( 'a.title' ).attr( 'href' ) );
					}
				)
			;
		}
	);
}

/**
 * Gestisce il click su un pulsante di un tab menu
**/
function tabMenuButtonClicked()
{
	var linkContainer = $( this ).parent();
	var spanContainer = linkContainer.parent().find( '.selected' );
	var linkText = $( this ).html();
	var spanText = spanContainer.find( 'span' ).html();

	tabMenuButtonAction( linkContainer.attr( 'id' ) );

	spanContainer.removeClass( 'selected' );
	linkContainer.addClass( 'selected' );

	spanContainer.find( 'span' ).replaceWith( '<a href="#" title="' + spanText + '">' + spanText + '</a>' );
	spanContainer.find( 'a' ).click( tabMenuButtonClicked );
	$( this ).replaceWith( '<span>' + linkText + '</span>' );

	return false;
}

/**
 * Gestisce il cambio di contenuto di un box laterale in base al pulsante cliccato 
**/
function tabMenuButtonAction( id )
{
	var box = $( '#' + id ).parent().parent();
	var pane = 
	box.find( '.scroll-list-items ul' ).removeClass( 'hidden' ).hide();
	$( '#' + id + '-content' ).show();
	box.find( '.scroll-pane' ).jScrollPane
	(
		{ scrollbarWidth:14, dragMaxHeight:36, dragMinHeight:36 }
	);
}

/**
 * Imposta la visibilità dei banner
 *
 * @param visibility, boolean, required, True per rendere visibili i banner
**/
function setBannersVisibility( visibility )
{
	if( visibility )
	{
	} else {
	}
}

/**
 * Aggiunte la classe hovered all'elemento
**/
function addHoverClass()
{
	$( this ).addClass( 'hovered' );
}

/**
 * Rimuove la classe hovered dell'elemento
**/
function delHoverClass()
{
	$( this ).removeClass( 'hovered' );
}

/**
 * Redirige la pagina al link interno all'elemento della lista
**/
function gotoListInnerLink()
{
	gotoSelectedPage( $( this ).find( 'a' ).attr( 'href' ) );
}

/**
 * Associa la funzione initManager all'evento onload della pagina
**/
$( document ).ready( initManager );