/**
 * Code by Giancarlo "GM" Moschitta (info@myphp.it) and Negatyve (http://www.negatyve.com)
 * Powered by jQuery (http://jquery.com))
**/
/**
 * Avvia tutti gli script necessari a Digital
**/
function initDigital()
{
	preloadImages
	(
		SITE_PATH + 'layout/links/business-digital-link-background-over.png',
		SITE_PATH + 'layout/links/business-digital-link-background-up.png',
		SITE_PATH + 'layout/links/www-digital-link-background-over.png',
		SITE_PATH + 'layout/links/www-digital-link-background-up.png',
		SITE_PATH + 'layout/links/home-digital-link-background-over.png',
		SITE_PATH + 'layout/links/home-digital-link-background-up.png',
		SITE_PATH + 'layout/' + SUBDOMAIN + '/ajax-loader.gif'
	);

	$( '#logo, #digital-version-links' ).pngFix();

	$( 'a[rel="external"]' ).click( openExternalLink );
	$( '.navigation-print' ).click( openExternalLink );
	
	$( 'input[name="e"]' ).hint();
	
	$( '.newsletter-box-send' ).click
	(
		function(){ return newsletterButtonClicked( $( this ) ); }
	);
	var currentSelectedClassId = $( '#products-navigation > li > span' ).attr( 'id' );

	if( currentSelectedClassId )
	{
		$( '#prod-nav-' + getClassNumericId( currentSelectedClassId ) ).show();
	}

	$( '#products-navigation > li > a,#products-navigation > li > span' ).mouseover
	(
		function() { navigateClass( this ); }
	);

	$( '.prod-nav-select-container > select' ).change
	(
		function(){ return gotoSelectedPage( this, 'category' ); }
	).each
	(
		function()
		{
			autoAdjustSelectSize( $(this), 200, false );
		}
	);
	$( '#sel-networksite' ).change
	(
		function(){ changeNetworkSite(); }
	);
	$( '#visit-network-site a' ).click
	(
		function(){ changeNetworkSite(); return false; }
	);
	$('#header-search-form').submit
	(
		function()
		{
			var s = $('#header-search-form-input').val();
			if( $.trim( s ).length < 2 )
			{
				showAlert( 'Devi inserire almeno due caratteri!' );
				return false;
			} else {
				return true;
			} 
		}
	);
}

/**
 * Verifica se una variabile č definita?
**/
function isDefined( variable )
{
	return typeof( variable ) != 'undefined';
}


/**
 * Gestisce il click sui pulsante del box newsletter
 *
 * @param link, jQuery, required, Il riferimento al pulsante
**/
function newsletterButtonClicked( button )
{
	var mail = $.trim( $( 'input[name="e"]' ).val() );
	if( mail.match(/^([a-z0-9_\.-])+@(([a-z0-9_-])+\.)+[a-z]{2,6}$/i) == null )
	{
		showAlert('Inserisci un indirizzo email!');
		return false;
	} else {
		return true;
	}
}

/**
 * Imposta la visibilitā dei banner
 *
 * @param visibility, boolean, required, True per rendere visibili i banner
**/
function setBannersVisibility( visibility )
{
	if( visibility )
	{
		$('.banner > div').show();
		$('#leaderboard-banner').css( 'height', 'auto' );
	} else {
		$('#leaderboard-banner').css( 'height', $('#leaderboard-banner').height() + 'px' );
		$('.banner > div').hide();
	}
}

/**
 * Imposta la visibilitā del pulsante "vai" dei filtri
 *
 * @param visibility, boolean, required, True per rendere il pulsante visibile
**/
function setFilterButtonVisibility( visibility )
{
	if( visibility )
	{
		$('#filter-go-button').show();
	} else {
		$('#filter-go-button').hide();
	}
}

/**
 * Gestice il combobox per visitare gli altri siti del network
**/
function changeNetworkSite()
{
	var value = $( '#sel-networksite' ).val();
	if( value != '' )
	{
		window.location.href = value + '/';
	}
}

/**
 * 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( "Digital.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 isIE6 = $.browser.msie && Number( $.browser.version.split('.')[0] ) <= 6;
	switch( type )
	{
		case 'alert': default:
			if( isIE6 )
			{
				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 )
			{
				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;
	}
}

/**
 * Recupera il cookie di comparazione
 *
 * @return json
**/
function getCompareCookie()
{
	/* crea l'oggetto di risposta */
	var result = { 'type' : '', 'id' : '', 'products' : new Array() };
	/* recupera il cookie */
	var content = $.cookie( 'compare_list_items' );
	/* se il cookie non esiste */
	if( content == null ){ return result; }
	/* se il cookie č vuoto */
	if( content.length == 0 ){ return result; }
	/* recupera i tokens */
	var tokens = content.split( '|div|' );
	/* se non sono due */
	if( tokens.length != 2 ){ return result; }
	/* recupera la zona */
	var zone = tokens[ 0 ].split( '|typ|' );
	/* se la zona non contiene due elementi */
	if( zone.length != 2 ){ return result; }
	/* assegna i valori */
	result.type = zone[ 0 ];
	result.id = zone[ 1 ];
	result.products = tokens[ 1 ].split( '|prod|' );
	/* restituisce il risultato */
	return result;
}

/**
 * Setta il cookie di comparazione
 *
 * @param type
 * @param id
 * @param products
**/
function setCompareCookie( type, id, products )
{
	$.cookie( 'compare_list_items', type + '|typ|' + id + '|div|' + products.join('|prod|'), { path: '/' } );
}

/**
 * Resetta il cookie di comparazione
**/
function resetCompareCookie()
{
	$.cookie( 'compare_list_items', null, { path: '/' } );
}

/**
 * Salva nei cookie un elemento della lista di comparazione
 *
 * @param product, string, required, L'id del prodotto da salvare
 * @param type, string, required, Il tipo di pagina da cui proviene la scrittura (category|product)
 * @param category, string, required, L'id della categoria o della pagina da cui proviene la scrittura
 *
 * @return boolean
**/
function insertCompareListItem( product, type, id )
{
	product = product.substr( product.lastIndexOf( '-' ) + 1 );
	/* recupera il cookie */
	var cookie = getCompareCookie();
	if( cookie.products.length == 0)
	{
		/* scrive l'elemento */
		setCompareCookie( type, id, new Array( product ) );
		return 'success';
	}
	/* se la categoria ha un id diverso */
	if( String( cookie.id ) != id )
	{
		/*
		var userchoice = showAlert
		(
			'Il prodotto selezionato appartiene ad una categoria diversa da quella dei prodotti selezionati in precedenza.\n' +
			'Dal momento che č possibile confrontare solo prodotti della stessa categoria,\naggiungendo questo la lista verrā ' +
			'prima resettata.\n\nSei sicuro di voler aggiungere questo elemento alla lista?'
			,
			'confirm'
		);
		*/

		var userchoice = false;
		showAlert
		(
			'<p style="text-align:justify;">' +
			'Il prodotto selezionato appartiene ad una categoria diversa da quella dei prodotti selezionati in precedenza.<br /><br />' +
			'Dal momento che č possibile confrontare solo prodotti della stessa categoria,\ndevi prima rimuovere quelli giā selezionati.' +
			'</p><p style="text-align:justify;">' +
			'N.B. controlla di non avere altre liste di comparazione in un\'altra pagina del browser.' +
			'</p>'
		);
		if( userchoice )
		{
			setCompareCookie( type, id, new Array( product ) );
			return 'reset';
		} else {
			return 'rejected';
		}
	}
	/* verifica che l'elemento non sia giā presente */
	var exists = false;
	for( var i = 0; i < cookie.products.length; i++ )
	{
		if( cookie.products[i].toLowerCase() == product.toLowerCase() )
		{
			exists = true;
			break;
		}
	}
	/* se l'elemento non č presente */
	if( !exists )
	{
		/* aggiunge l'elemento */
		cookie.products.push( product );
		setCompareCookie( type, id, cookie.products );
		return 'success';
	} else {
		return 'status';
	}
}

/**
 * Cancella dai cookie un elemento della lista di comparazione
 *
 * @param id, string, required, L'id da cancellare
**/
function deleteCompareListItem( id )
{
	id = id.substr( id.lastIndexOf('-') + 1 );
	/* recupera il cookie */
	var cookie = getCompareCookie();
	/* se il cookie contiene dei prodotti */
	if( cookie.products.length > 0 )
	{
		/* cicla gli elementi per cancellare l'eventuale id passato */
		for( var i = 0; i < cookie.products.length; i++ )
		{
			if( cookie.products[i].toLowerCase() == id.toLowerCase() )
			{
				cookie.products.splice( i, 1 );
				break;
			}
		}
		if( cookie.products.length > 0 )
		{
			setCompareCookie( cookie.type, cookie.id, cookie.products );
		} else {
			resetCompareCookie();
		}
	}
}

/**
 * Restituisce l'id di un prodotto dal link
 *
 * @param link, string, required, Il link alla pagina del prodotto
 * @return string
**/
function getProductIdByLink( link )
{
	var link_els = link.match(/\/prodotti\/S([0-9]+)\//);
	return 'S' + link_els[1];
}

/**
 * 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;
}

/**
 * Restituisce l'id numerico della classe dall'id dell'elemento
 *
 * @param id, string, required, L'id dell'elemento
 * @return int
**/
function getClassNumericId( id )
{
	return Number( getLinkName( id ) );
}

/**
 * Restituisce il nome del link
 *
 * @param id, string, required, L'id dell'elemento
 * @return string
**/
function getLinkName( id )
{
	if( isDefined( id ) )
	{
		return id.substr( id.lastIndexOf( '-' ) + 1 );
	} else {
		return '';
	}
}

/**
 * Mostra i link alle categorie della classe indicata
 *
 * @param link, object, required, Il link che ha invocato il metodo
**/
function navigateClass( link )
{
	$( '#products-navigation > li > a' ).removeAttr( 'class' );

	var currentLink = $( link );
	var currentLinkId = currentLink.attr( 'id' );

	currentLink.addClass( 'selected' );

	$( '.prod-nav-content' ).hide();
	$( '#prod-nav-' + getClassNumericId( currentLinkId ) ).show();
}

/**
 * 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 )
{
	switch( type )
	{
		case 'category':
			var link = $( item ).val();
			if( link != '' )
			{
				window.location.href = link;
			}
			break;
	}
}

/**
 * Associa la funzione initDigital all'evento onload della pagina
**/
$( document ).ready( initDigital );
