/**
 * Code by Giancarlo "GM" Moschitta (info@myphp.it) and Negatyve (http://www.negatyve.com)
 * Powered by jQuery (http://jquery.com))
**/
var quickGallPosition = 0;
/**
 * Avvia tutti gli script necessari ad una pagina di prodotto di Digital
**/
function initDigitalProduct()
{

	preloadImages
	(
		SITE_PATH + 'layout/main-info-background-users.png',
		SITE_PATH + 'layout/main-info-background-staff.png'
	);

	var user_data = $.cookie( 'digital_comments_user_data' );
	if(user_data != null)
	{
		var split_user_data = user_data.split("<[SEP]>");
		$('#comment-form-name').val( split_user_data[0] );
		$('#comment-form-mail').val( split_user_data[1] );
		$('#comment-form-site').val( split_user_data[2] );
		$('#vote-comment-form-name').val( split_user_data[0] );
		$('#vote-comment-form-mail').val( split_user_data[1] );
	}
	/* imposta il click sui pulsanti del menu di info del prodotto */
	$('#main-info-menu a').click
	(
		function(){ mainInfoMenuLinkClicked( $(this) ); return false;}
	);
	/* imposta il funzionamento del pager dei commenti */
	$('.product-comments .product-comments-header .pager a').click
	(
		function(){ commentsPageChanged( $( this ) ); return false; }
	);
	/* imposta il gestore del click sul pulsante di invio commenti */
	$('#comment-form-send').click
	(
		function(){ commentsFormSendComment( $(this) ); return false; }
	);
	/* imposta il gestore del click sul pulsante di invio commenti della votazione */
	$('#vote-comment-form-send').click
	(
		function(){ commentsFormSendComment( $(this) ); return false; }
	);
	/* imposta il click sul pulsante vota e back */
	$('.main-info-set-users-rate a, a[href=#users-vote]').click
	(
		function(){ usersVoteLinkClicked( $(this) ); return false; }
	);
	$('.main-info-back a').click
	(
		function(){ usersBackLinkClicked( $(this) ); return false; }
	);
	/* trasforma i radiobutton per lo star rating */
	$(':radio.star').rating( {cancel:'Annulla', cancelValue:0});
	/* imposta il click sul pulsante per la votazione */
	$('#rate-form-send').click
	(
		function(){ voteProduct( $(this) ); return false;}
	);
	/* imposta il click sul notice del voto */
	$('.main-info-average-users-rate a.notice').click
	(
		function(){ showAlert( 'La media voto viene calcolata a partire da un minimo di 3 voti espressi' ); return false;}
	);
	/* imposta il click sul notice del voto */
	$('.main-info-average-staff-rate a.tests-disclaimer').click
	(
		function(){ showAlert( 'Questo voto è dato dalla media delle valutazioni di editori internazionali. Digital.it lo mostra a solo titolo informativo, senza assumersene la responsabilità' ); return false;}
	);
	/* imposta l'azione del pulsante segnala a facebook */
	$( '.share-on-facebook a' ).click( shareOnFacebook );
	/* inizializza la quick gall */
	initQuickGallery();
}

/*******************
* QUICK GALL BLOCK *
*******************/


/**
 * Inizializza la quick gall
**/
function initQuickGallery()
{
	$.easing.easeOutCubic =  function (x, t, b, c, d)
	{
		return c*((t=t/d-1)*t*t + 1) + b;
	};

	var target = $('#main-image img');
	var originalPicture = target.attr('src');

	$('.quick-gall-container a').hover
	(
		function(){ target.attr('src', $(this).attr('href') ); },
		function(){ target.attr('src', originalPicture ); }
	).click( function(){return false;});
	$('.quick-gall-prev').click( function(){ quickGallPrev(); return false; } );
	$('.quick-gall-next').click( function(){ quickGallNext(); return false; } );
}

function quickGallPrev()
{
	/* recupera la lista */
	var ul = $('.quick-gall-container ul');
	/* recupera la posizione */
	var x = Number( ul.css('left').replace( 'px', '' ) );
	if( quickGallPosition < 0 )
	{
		ul.animate( {'left': ( ++quickGallPosition * 65 ) + 'px'}, 300, 'easeOutCubic');
	}
}
function quickGallNext()
{
	/* recupera la lista */
	var ul = $('.quick-gall-container ul');
	/* recupera la posizione */
	var x = Number( ul.css('left').replace( 'px', '' ) );
	var m = $('.quick-gall-container ul li').length - 4;
	if( quickGallPosition > -m )
	{
		ul.animate( {'left': (--quickGallPosition * 65) + 'px' }, 300, 'easeOutCubic');
	}
}


/******************
* MAIN INFO BLOCK *
******************/


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

/**
 * Gestisce il click sul pulsante del voto
 *
 * @param button, jQuery, required, Il pulsante "vota"
**/
function voteProduct( button )
{
	var vote = $('[name=product-user-rating]').val();
	if( vote == 0 )
	{
		return showAlert( 'Seleziona un voto da 1 a 10' );
	}
	$('#users-vote form').fadeTo('normal', '0.4');
	showAjaxLoader( $('#users-vote') );
	$.ajax
	(
		{
			type: 'POST',
			url: SITE_PATH + 'a/ajax.php',
			data: 'c=prodotti&m=addUserVote&product=' + PRODUCT_ID + '&vote=' + vote,
			success: function( result )
			{
				hideAjaxLoader( $('#users-vote') );
				$('#users-vote form').fadeTo('fast', '1.0');
				if( ajaxError( result ) )
				{
					return false;
				}
				switch( result )
				{
					case '0':

						showAlert( "Impossibile registrare il voto" );
						break;

					case '-1':

						showAlert( "Non puoi votare di nuovo" );
						break;

					case '-2':

						noticeUsersAverageVote( result );
						showAlert( "Il tuo voto \xE8 stato correttamente inserito" );
						break;

					default:

						updateUsersAverageVote( result );
						showAlert( "Il tuo voto \xE8 stato correttamente inserito" );
				}
			}
		}
	);
}


/**
 * Aggiorna il voto medio degli utenti nell'area giudizi
 *
 * @param vote, string, required, Il voto medio
**/
function updateUsersAverageVote( vote )
{
	var v = Math.round( Number( vote ) );
	/* recupera il contenitore */
	var c = $('#users-rate .users-rate-votes');
	/* lo svuota */
	c.empty();
	/* crea i nuovi elementi */
	c.append('<span class="feature-label">Voto generale</span>');
	c.append('<img class="rate-img" src="' + SITE_PATH + 'layout/rates-users/rate-' + v + '.gif" alt="' + v + '" />');
	c.append('<span class="feature-rate">' + v + '</span>');
	/* resetta il voto */
	$('#rating-form .cancel').click();
	$('#rating-form').remove();
	$('#users-vote > strong').empty().html( 'Prodotto gi&agrave; votato: prova nuovamente pi&ugrave; tardi.' ).addClass('already-voted');
	$('.main-info-average-users-rate .label').empty().html('Voto utenti');
	$('.main-info-average-users-rate a.notice').remove();
	$('.main-info-average-users-rate').append
	(
		'<p class="value"><span class="info-rate">' + vote + '</span><span class="info-total">/10</span></p>'
	);
	/* apre la tab dei giudizi utenti */
	usersBackLinkClicked( null );
}
function noticeUsersAverageVote( vote )
{
	/* resetta il voto */
	$('#rating-form .cancel').click();
	$('#rating-form').remove();
	$('#users-vote > strong').empty().html( 'Prodotto gi&agrave; votato: prova nuovamente pi&ugrave; tardi.' ).addClass('already-voted');
	/* apre la tab dei giudizi utenti */
	usersBackLinkClicked( null );
}

/**
 * Gestisce il click sul link "vota"
**/
function usersVoteLinkClicked( link )
{
	/* nasconde tutti i pannelli */
	$('.main-info-panel').hide();
	/* mostra il pannello della votazione */
	$('#users-vote').show();
	$('#main-info').removeClass().addClass('users-vote-style');
	toggleMainInfoItemsClass();
	mainInfoLinkToSpan( $('li.users-vote a') );
}

/**
 * Gestisce il click sul link "back"
**/
function usersBackLinkClicked( link )
{
	/* nasconde tutti i pannelli */
	$('.main-info-panel').hide();
	/* mostra il pannello della votazione */
	$('#users-rate').show();
	$('#main-info').removeClass().addClass('users-rate-style');
	toggleMainInfoItemsClass();
	mainInfoSpanToLink( $('li.users-vote span') );
}

/**
 * Aggiunge o rimuove la classe hidden dagli elementi
**/
function toggleMainInfoItemsClass()
{
	$('.main-info-set-users-rate').toggleClass('hidden');
	$('.main-info-back').toggleClass('hidden');
	/*$('li.users-vote').toggleClass('hidden'); */
	$('li.users-rate, li.staff-rate').toggleClass('hidden');
	if( $('li.users-rate a').html() )
	{
		mainInfoLinkToSpan( $('li.users-rate a') );
		mainInfoSpanToLink( $('li.staff-rate span') );
	}
}

/**
 * Gestisce il click sui link del main info menu
 *
 * @param link, jQuery, required, Il link cliccato
**/
function mainInfoMenuLinkClicked( link )
{
	var style= link.parent().attr('class');
	mainInfoSpanToLink( $('#main-info-menu .selected span') );
	mainInfoLinkToSpan( link );
	$('#main-info').removeClass().addClass( style + '-style' );
	/* nasconde tutti i pannelli */
	$('.main-info-panel').hide();
	/* mostra il pannello selezionato */
	$('#' + style).show();
}

/**
 * Converte un link del box main info in span
 *
 * @param link, jQuery, required, Il link da convertire
**/
function mainInfoLinkToSpan( link )
{
	/* recupera il <li> contenitore */
	var li = link.parent();
	/* seleziona il parent del link cliccato */
	li.addClass('selected');
	/* recupera il testo del link */
	var text = link.html();
	/* trasforma il link in span */
	link.replaceWith('<span>' + text + '</span>');
	return li.find('span');
}

/**
 * Converte un link del box main info in span
 *
 * @param link, jQuery, required, Lo span da convertire
**/
function mainInfoSpanToLink( span )
{
	/* recupera il <li> parent dello span */
	var li = span.parent();
	/* deseleziona il li contenitore */
	li.removeClass('selected');
	/* recupera la classe del contenitore */
	var style = li.attr('class');
	/* recupera il contenuto dello span */
	var text = span.html();
	/* trasforma lo span in un link */
	span.replaceWith('<a href="#' + style + '" title="' + text + '">' + text + '</a>');
	/* imposta il click del link appena creato */
	return li.find('a').click
	(
		function(){ mainInfoMenuLinkClicked( $(this) ); return false;}
	);
}


/*****************
* COMMENTS BLOCK *
*****************/


/**
 * Gestisce il click sul pulsante di invio commento del form dei commenti
 *
 * @param button, jQuery, required, Il pulsante cliccato
**/
function commentsFormSendComment( button )
{
	var prefix = button.attr('id').replace('comment-form-send', '');
	var errors = checkCommentFields
	(
		[
			{type:'name', field:$('#' + prefix + 'comment-form-name')},
			{type:'mail', field:$('#' + prefix + 'comment-form-mail')},
			{type:'area', field:$('#' + prefix + 'comment-form-area')}
		]
	);
	if( errors == 0 )
	{
		insertComment
		(
			$('#' + prefix + 'comment-form-name').val(),
			$('#' + prefix + 'comment-form-mail').val(),
			prefix == '' ? $('#' + prefix + 'comment-form-site').val() : '',
			$('#' + prefix + 'comment-form-area').val(),
			prefix == '' ? $('#' + prefix + 'comment-form-check:checked').length : 0
		);
	}
}

/**
 * Inserisce il commento di un utente
 *
 * @param name, string, required, Il nome del commentatore
 * @param mail, string, required, L'indirizzo email
 * @param site, string, required, Il sito
 * @param area, string, required, Il corpo del commento
 * @param send, int, required, Se inviare o no le notifiche sulle risposte
**/
function insertComment( name, mail, site, area, send )
{
	var querystring = '';
	querystring += '&product=' + PRODUCT_ID;
	querystring += "&name=" + fixAmpersand( $.trim( name ) );
	querystring += "&mail=" + $.trim( mail );
	querystring += "&site=" + fixAmpersand( $.trim( site ) );
	querystring += "&area=" + fixAmpersand( $.trim( area ) );
	querystring += "&send=" + send;

	$('.comments-content form').fadeTo('normal', '0.4');
	$('#users-vote form').fadeTo('normal', '0.4');
	showAjaxLoader( $('.product-comments') );
	showAjaxLoader( $('#users-vote') );
	$.ajax
	(
		{
			type: 'POST',
			url: SITE_PATH + 'a/ajax.php',
			data: 'c=prodotti&m=insertComment' + querystring,
			success: function( result )
			{
				hideAjaxLoader( $('.product-comments') );
				hideAjaxLoader( $('#users-vote') );
				if( ajaxError( result ) )
				{
					return false;
				}
				var temp = result.split('<|>');
				$('.comments-content form').fadeTo('slow', '1.0');
				$('#users-vote form').fadeTo('slow', '1.0');
				var response = temp.shift();
				if( temp.length > 0 )
				{
					replaceCommentsPage( temp.join('<|>') );
				}
				switch( response )
				{
					case "1":
						showAlert( "Il tuo commento \xE8 in attesa di essere approvato" );
					    break;
					case "2":
						showAlert( "Il tuo commento \xE8 stato correttamente inserito" );
					    break;
					default:
					    break;
				}
				$('#comment-form-area').val('');
				$('#vote-comment-form-area').val('');
			}
		}
	);
}

/**
 * Esegue il controllo sui campi di un form di invio commento
 *
 * @param fields, array, required, L'array di campi da controllare
**/
function checkCommentFields( fields )
{
	var type, field, value, errors = 0;
	for( var i = 0; i < fields.length; i++ )
	{
		field = fields[i].field;
		value = field.val();
		wrong = false;
		switch( fields[i].type )
		{
			case 'name': case 'area':

				wrong = $.trim( value ) == '';
				break;

			case 'mail':

				wrong = $.trim( value ) == '' || value.match(/^([a-z0-9_\.-])+@(([a-z0-9_-])+\.)+[a-z]{2,6}$/i) == null;
				break;

			case 'site':

				break;

		}
		if( wrong )
		{
			errors++;
			setFieldErrorColor( field );
		}
	}
	return errors;
}

/**
 * Imposta il colore di errore sul campo di un form
 *
 * @param field, jQuery, required, Il campo da evidenziare
**/
function setFieldErrorColor( field )
{
	var container = field.parent();
	var color = field.css('color');
	var backgroundColor = container.css('background-color');

	field.css('color', '#fff');
	container.css('background-color', '#f00'); /*#586626*/

	field.focus
	(
		function()
		{
			$(this).unbind('focus');
			$(this).css('color', color);
			$(this).parent().css('background-color', backgroundColor);
		}
	);
}
/**
 * Gestisce il cambio di pagina dei commenti
 *
 * @param link, jQuery, required, Il link del pager che è stato cliccato
**/
function commentsPageChanged( link )
{
	var href = link.attr('href');
	var page = href.substr( href.lastIndexOf('-') + 1 );
	getCommentsPage( page );
}

/**
 * Recupera una pagina dei commenti
 *
 * @param page, int, required, Il numero di pagina
**/
function getCommentsPage( page )
{
	showAjaxLoader( $('.product-comments') );
	$.ajax
	(
		{
			type: 'POST',
			url: SITE_PATH + 'a/ajax.php',
			data: 'c=prodotti&m=getCommentsPage&product=' + PRODUCT_ID + '&page='+ page,
			success: function( result )
			{
				hideAjaxLoader( $('.product-comments') );
				if( ajaxError( result ) )
				{
					return false;
				}
				replaceCommentsPage( result );
			}
		}
	);
}

/**
 * Rimpiazza la pagina dei commenti
 *
 * @param result, string, required, Il contenuto della pagina
**/
function replaceCommentsPage( result )
{
	/* rimuove la lista dei commenti */
	$('#comments').remove();
	/* recupera l'header del box */
	var header = $('.product-comments .product-comments-header');
	/* rimuove il pager */
	header.find('.pager').remove();
	/* splitta il risultato */
	var temp = result.split('<|>');
	/* inserisce i commenti */
	$('.product-comments .comments-forum-disclaimer').after( temp[0] );
	/*$('.product-comments .comments-content').hide().fadeIn('slow'); */
	if( temp.length > 1 )
	{
		/* inserisce il pager se presente */
		if( temp[1] != '' )
		{
			/* inserisce il pager */
			header.append( temp[1] );
			/* imposta il funzionamento del pager dei commenti */
			header.find('.pager a').click
			(
				function(){ commentsPageChanged( $( this ) ); return false; }
			);
		}
		/* inserisce l'ultimo commento se presente */
		if( temp.length > 2 && temp[2] != '' )
		{
			/* recupera il contenitore */
			var c = $('#users-rate .last-comment');
			/* lo svuota */
			c.empty();
			/* inserisce gli elementi */
			c.append('<span class="last-comment-label">Ultimo commento:</span>');
			c.append('<p class="users-last-comment">' + temp[2] + '</p>');
			c.append('<a class="all-comments" href="#comments" title="Tutti i commenti">Tutti i commenti &raquo;</a>');
		}
	}
}

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