/* 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 alla pagina del prodotto
**/
function initDevice()
{
	jQuery( '.product-users-rate-info .info-link' ).live( 'click', averageVoteInfo );
	jQuery( '.product-users-rate-info .info-vote' ).live( 'click', setUserVote );
	jQuery( '#user-rate-slider' )
		.slider( { min: 0, max: 10, step: 0.2, value: 0 } )
		.bind( 'slide', updateSlider )
	;
}

/**
 * Aggiorna il valore dello slider
**/
function updateSlider( event, ui )
{
	var value = ui.value;
	if( value == parseInt( value ) )
	{
		value = value + ".0";
	}
	jQuery( '.user-rate-current-vote' ).html( value );
	return true;
}

/**
 * Informa gli utenti sulla media voto
**/
function averageVoteInfo()
{
	showAlert( 'La media voto viene calcolata a partire da un minimo di 3 voti espressi', 'alert' );
	return false;
}

/**
 * Setta il voto dell'utente
**/
function setUserVote()
{
	var vote = jQuery( '#user-rate-slider' ).slider( 'value' );
	if( vote == 0 )
	{
		return showAlert( 'Seleziona un voto da 1 a 10', 'alert' );
	}
	jQuery( '.user-rate-slider-container, .users-rate, .product-users-rate-info' ).fadeTo('normal', '0.2');
	showAjaxLoader( jQuery( '.product-users-rate' ) );
	
	jQuery.ajax
	(
		{
			type: 'POST',
			url: SITE_PATH + 'a/ajax.php',
			data: 'c=device&m=addUserVote&product=' + PRODUCT_ID + '&vote=' + vote,
			success: function( result )
			{
				hideAjaxLoader( jQuery( '.product-users-rate' ) );
				jQuery( '.user-rate-slider-container, .users-rate, .product-users-rate-info' ).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;

					default:

						updateUsersAverageVote( result );
						showAlert( "Il tuo voto \xE8 stato correttamente inserito" );
				}
			}
		}
	);
	return false;
}

/**
 * Aggiorna il voto dell'utente
**/
function updateUsersAverageVote( result )
{
	var temp = result.split( '-' );
	if( temp[0] != '0' )
	{
		jQuery( '.users-rate strong' ).replaceWith
		(
			'<strong>' + temp[0] + '<span>\/10<\/span><\/strong>'
		);
	}
	jQuery( '#user-rate-slider' ).unbind().slider( 'destroy' ).replaceWith
	(
		'<span class="user-rate-notice">Il tuo voto &egrave;<\/span>'
	);
	jQuery( '.info-vote' ).replaceWith
	(
		'<a href="#" title="Media voto" class="info-link">Media voto<\/a>'
	);
}

/**
 * Associa la funzione initDevice all'evento onload della pagina
**/
jQuery( document ).ready( initDevice );
