/* 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()
{
	jQuery( '#site-search-form' ).submit(
		function() {
			if( jQuery( '#site-search-form-input' ).val() == 'Cerca nel sito' ) {
				alert( 'Digita qualcosa nel campo di testo' );
				jQuery( '#site-search-form-input' ).val( '' ).focus();
				return false;
			}
			return true;
		}
	)
	var isIE6 = jQuery.browser.msie && Number( jQuery.browser.version.split('.')[0] ) <= 6;

	jQuery( 'a[rel="external"]' ).click( openExternalLink );
	jQuery( 'input.hinted' ).hint();
	setAdvBoxStylesAndActions();
	setSuggestedProductsBoxStylesAndActions();
	if( !isIE6 )
	{
		setResourcePicturesNavigation();
		setProductPicturesNavigation();
	}
	if( typeof PROD_PICS_NAV != 'undefined' )
	{
		preloadImages( PROD_PICS_NAV );
	}
	jQuery( '.gallery-images-list .selected' ).css( 'opacity', '0.3' );

	jQuery( 'select[name=cscls]' ).change( load_search_form_class_categories );
	jQuery( '#content-search-form-send' ).click( start_search );
	jQuery( '#sel-networksite' ).change( changeNetworkSite );
	jQuery( '#visit-network-site a' ).click( changeNetworkSite );
	jQuery( '#newsletter-box form' ).submit( checkNewsletterBox );
	jQuery( '#newsletter-box form .radio-container input' ).click
	(
		function()
		{
			jQuery( this ).parent().parent().children( '.label' ).css( { color:'#ffffff', textDecoration: 'none' } );
		}
	);
	jQuery( '#newsletter-box-email' ).focus
	(
		function()
		{
			jQuery( this ).css( 'color', '#8e8e8e' );
		}
	);
	var enlarge_picture = jQuery( 'a.enlarge-picture' );
	if( enlarge_picture.length > 0 )
	{
		enlarge_picture.fancybox();
	}
}

function checkNewsletterBox()
{
	var n = jQuery( this );
	var p = parseInt( jQuery( 'input[name=trattamento_privacy]:checked').val(), 10 ) === 1;
	var c = jQuery( 'input[name=n_inviadem]:checked').val() != undefined;
	var e = true;
	
	if( !p )
	{
		jQuery( '#newsletter-box form #divprivacy .label' ).css( { color:'#dd0000', textDecoration: 'underline' } );
		e = false;
	}
	if( !c )
	{
		jQuery( '#newsletter-box form #divcommercial .label' ).css( { color:'#dd0000', textDecoration: 'underline' } );
		e = false;
	}
	
	if( jQuery( '#newsletter-box-email' ).val().match(/^([a-z0-9_\.-])+@(([a-z0-9_-])+\.)+[a-z]{2,6}$/i) == null )
	{
		jQuery( '#newsletter-box-email' ).css( 'color', '#ff0000' );
		e = false;
	}
	return e;
}

function start_search()
{
	var man_id = jQuery( 'select[name=csman]' ).val().match( /^([0-9]+)$/ );
	var cls_id = jQuery( 'select[name=cscls]' ).val().match( /^([0-9]+)$/ );
	var cat_id = jQuery( 'select[name=cscat]' ).val().match( /^([0-9]+)\|(.+)$/ );

	var page_location = window.location.protocol + '//' + window.location.host + '/ricerca/'
	var qs = new Array();
	if( man_id != null && man_id[1] != 0 )
	{
		qs.push( 'mi=' + man_id[1] );
	}
	if( cls_id != null && cls_id[1] != 0 )
	{
		qs.push( 'cli=' + cls_id[1] );
	}
	if( cat_id != null && cat_id[1] != 0 )
	{
		qs.push( 'ci=' + cat_id[1] );
	}
	window.location.href = page_location + ( qs.length > 0 ? '?qs=' + Base64.encode( qs.join( '|' ) ) : '' );
	return false;
}
function load_search_form_class_categories()
{
	var cls_select = jQuery( this );
	var cat_select = jQuery( 'select[name=cscat]' );
	var class_selected = cls_select.val();
	if( class_selected == 0 )
	{
		cat_select.val( '0' ).attr( 'disabled', 'disabled' ).children( ':gt(0)' ).remove();
		return;
	}
	var button = jQuery( '#content-search-form-send' );
	button.attr( 'disabled', 'disabled' );
	cls_select.attr( 'disabled', 'disabled' );
	cat_select.attr( 'disabled', 'disabled' );
	var selected_element = jQuery( 'option:selected', cat_select );
	var current_label = selected_element.html();
	selected_element.html( 'Loading...' );
	jQuery.ajax
	(
		{
			type: 'POST',
			url: SITE_PATH + 'a/ajax.php',
			data: 'c=dati&m=getClassCategories&wait=1&class_id=' + class_selected,
			success: function( result )
			{
				if( result == '' || ajaxError( result ) )
				{
					cat_select.val( '0' ).attr( 'disabled', 'disabled' ).children( ':gt(0)' ).remove();
					return false;
				}
				selected_element.html( current_label );
				cls_select.removeAttr( 'disabled' );
				cat_select.removeAttr( 'disabled' ).children( ':gt(0)' ).remove().end().append( result );
				button.removeAttr( 'disabled' );
			}
		}
	);
}

/**
 * Setta gli stili e le azioni del box adv
**/
function setAdvBoxStylesAndActions()
{
	var li = jQuery( '.adv-box-menu li' );
	li.each
	(
		function( i )
		{
			jQuery( this ).css( { position:'absolute',top:'0',left:(i * 65 ) + 'px',zIndex:i } );
		}
	);
	jQuery( '.adv-box-menu li.selected' ).css( 'z-index', li.length + 1 );
	jQuery( '.adv-box-menu a' ).live( 'click', advBoxMenuLinkClicked );
	jQuery( '.scroll-pane' ).jScrollPane
	(
		{ scrollbarWidth:10, dragMaxHeight:51, dragMinHeight:51 }
	);
}

/**
 * Setta gli stili e le azioni del box dei prodotti suggeriti
**/
function setSuggestedProductsBoxStylesAndActions()
{
	jQuery( '#suggested-products .menu' ).each
	(
		function()
		{
			var li = jQuery( 'li', jQuery( this ) );
			li.each
			(
				function( i )
				{
					jQuery( this ).css( { position:'absolute',top:'0',left:(i * 90 ) + 'px',zIndex: (li.length - i) } );
				}
			);
			jQuery( 'li.selected', jQuery( this ) ).css( 'z-index', li.length + 1 );
		}
	);
	jQuery( '#suggested-products .menu a' ).live( 'click', suggestedProductsMenuLinkClicked );
}

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

/**
 * Converte le entità html
 *
 * @param s, string, required
**/
function html_entities_decode( s )
{
	var a = jQuery('<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 = jQuery('<div />').html( s );
	var d = a.html();
	a.remove();
	return d;
}

/**
 * Esegue il preload di immagini
**/
function preloadImages()
{
	if( arguments[0] instanceof Array )
	{
		doPreloadImages( arguments[0] );
	} else {
		doPreloadImages( arguments );
	}
}
function doPreloadImages( images )
{
	for( var i = 0; i < images.length; i++ )
	{
		jQuery( '<img />' ).attr( 'src', images[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;
}

/**
 * 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/ajax-loader.gif" alt="" /></div>' );

	var o = jQuery( '#' + 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' );

	jQuery( '#' + 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 = jQuery( '#' + 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( jQuery( this ).attr( 'href' ) );
	return false;
}

/**
 * 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 noPrompt = jQuery.browser.msie && Number( jQuery.browser.version.split('.')[0] ) <= 6 || typeof jQuery.prompt == 'undefined';
	switch( type )
	{
		case 'alert': default:
			if( noPrompt )
			{
				alert( message );
			} else {
				setBannersVisibility( false );
				jQuery.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( noPrompt )
			{
				if( confirm( message ) )
				{
					callback( param );
				}
			} else {
				jQuery.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;
	}
}

/**
 * Gestisce il click sui tab del box ADV
**/
function advBoxMenuLinkClicked()
{
	jQuery( '#adv-box .scroll-pane' ).jScrollPaneRemove();
	var link = jQuery( this );
	var linkParent = link.parent();
	var span = jQuery( 'span', linkParent.parent() );
	var spanParent = span.parent();
	var item = link.attr( 'class' );

	var index = parseInt( spanParent.removeClass( 'selected' ).css( 'z-index' ) ) + 1;

	span.replaceWith( '<a href="#" class="' + span.attr( 'class' ) + '">' + span.html() +  '<\/a>' );
	link.replaceWith( '<span class="' + item + '">' + link.html() +  '<\/span>' );

	linkParent.addClass( 'selected' ).css( 'z-index', index );

	jQuery( '.adv-box-content-row' ).removeClass( 'adv-box-content-row-selected' );
	jQuery( '#adv-box-' + item ).addClass( 'adv-box-content-row-selected' );
	jQuery( '#adv-box .scroll-pane' ).jScrollPane
	(
		{ scrollbarWidth:10, dragMaxHeight:51, dragMinHeight:51 }
	);
	return false;
}

/**
 * Gestisce il click sui tab del box dei prodotti suggeriti
**/
function suggestedProductsMenuLinkClicked()
{
	var link = jQuery( this );
	var linkParent = link.parent();
	var span = jQuery( 'span', linkParent.parent() );
	var spanParent = span.parent();
	var item = link.attr( 'class' );

	var index = parseInt( spanParent.removeClass( 'selected' ).css( 'z-index' ) ) + 1;

	span.replaceWith( '<a href="#" class="' + span.attr( 'class' ) + '">' + span.html() +  '<\/a>' );
	link.replaceWith( '<span class="' + item + '">' + link.html() +  '<\/span>' );
	linkParent.addClass( 'selected' ).css( 'z-index', index );
	linkParent.parent().parent().find( '.suggested-products-content-row' ).removeClass( 'suggested-products-content-row-selected' );
	jQuery( '#suggested-products-' + item ).addClass( 'suggested-products-content-row-selected' );

	return false;
}

/**
 * Imposta la navigazione delle immagini della galleria inline
**/
function setResourcePicturesNavigation()
{
	jQuery( '.resource-inline-pictures a.prev-pic' ).click
	(
		function()
		{
			if( PIC_NAV_CURRENT_POS > 0 )
			{
				jQuery( '.resource-inline-pictures ul' ).animate
				(
					{ left: '-' + (140 * --PIC_NAV_CURRENT_POS ) + 'px' }, 200, 'swing'
				);
			}
			return false;
		}
	);
	jQuery( '.resource-inline-pictures a.next-pic' ).click
	(
		function()
		{
			if( PIC_NAV_CURRENT_POS < jQuery( '.resource-inline-pictures li' ).length - 4 )
			{
				jQuery( '.resource-inline-pictures ul' ).animate
				(
					{ left: '-' + (140 * ++PIC_NAV_CURRENT_POS ) + 'px' }, 200, 'swing'
				);
			}
			return false;
		}
	);
}


/**
 * Imposta la navigazione delle immagini della galleria principale del prodotto
**/
function setProductPicturesNavigation()
{
	jQuery( '.main-product-gallery a.prev-pic' ).click
	(
		function()
		{
			if( PROD_PIC_NAV_CURRENT_POS > 0 )
			{
				jQuery( '.main-product-gallery ul' ).animate
				(
					{ left: '-' + (91 * --PROD_PIC_NAV_CURRENT_POS ) + 'px' }, 200, 'swing'
				);
			}
			return false;
		}
	);
	jQuery( '.main-product-gallery a.next-pic' ).click
	(
		function()
		{
			if( PROD_PIC_NAV_CURRENT_POS < jQuery( '.main-product-gallery li' ).length - 2 )
			{
				jQuery( '.main-product-gallery ul' ).animate
				(
					{ left: '-' + (91 * ++PROD_PIC_NAV_CURRENT_POS ) + 'px' }, 200, 'swing'
				);
			}
			return false;
		}
	);
	jQuery( '.main-product-gallery ul li a' )
		.hover( mainProductGalleryRollOver, mainProductGalleryRollOut )
		.click( function(){ return false; } )
	;
}
function mainProductGalleryRollOver()
{
	var t = jQuery( this ).parent();
	var i = t.parent().children().index( t );
	jQuery( '.main-img-container img' )
		.hide()
		.attr( 'src', PROD_PICS_NAV[i] )
		.removeClass()
		.addClass( 'product-gallery-image' )
		.show()
	;
}
function mainProductGalleryRollOut()
{
	var t = jQuery( this ).parent();
	var i = t.parent().children().index( t );
	jQuery( '.main-img-container img' )
		.hide()
		.attr( 'src', MAIN_PRODUCT_IMAGE )
		.removeClass()
		.addClass( 'product-image' )
		.show()
	;
}


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