/**
 * Avvia tutti gli script necessari ad una lista di offerte di Adsl.HTML.it
**/
function initAdslOffersList()
{
	if( typeof(EMPTY_COMPARE_LIST) == 'undefined' )
	{
		EMPTY_COMPARE_LIST = 'La lista &egrave; vuota';
	}
	$( '#offers-list input[type=checkbox], #offer-info-compare input[type=checkbox]' ).click
	(
		function(){ offersListCheckboxStatusChanged( $( this ) ); }
	);
	$('#compare-list-summary .foot-link-container .list-clear-button a').click
	(
		function()
		{
			var choice = showAlert
			(
				'Sei sicuro di voler svuotare la lista di comparazione?',
				'confirm', resetCompareCookie
			);
			if( choice )
			{
				resetCompareCookie();
			}
			return false;
		}
	);
	assignRemoveItemHandler( $('#compare-list-summary .compare-items a') );
}

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

/**
 * Assegna il gestore di evento per la rimozione di un elemento dalla lista
 *
 * @param link, jQuery, required, L'elemento a cui assegnare il gestore
**/
function assignRemoveItemHandler( link )
{
	link.click
	(
		function()
		{
			var id = $( this ).attr('href').split('-').pop();
			var choice = showAlert
			(
				'Sei sicuro di voler rimuovere questa offerta dalla lista di comparazione?',
				'confirm', deleteCompareListItem, id
			);
			if( choice )
			{
				deleteCompareListItem( id );
			}
			return false;
		}
	);
}

/**
 * Recupera il cookie di comparazione
 *
 * @return json
**/
function getCompareCookie()
{
	var content = $.cookie( 'adsl_compare_offers_' + SUBDOMAIN );
	if( content == null ){ return new Array(); }
	if( content.length == 0 ){ return new Array(); }
	return content.split( '-' );
}

/**
 * Setta il cookie di comparazione
 *
 * @param offers, array, required, L'array di id delle offerte
**/
function setCompareCookie( offers )
{
	$.cookie( 'adsl_compare_offers_' + SUBDOMAIN, offers.join('-'), { path: '/' } );
}

/**
 * Resetta il cookie di comparazione
**/
function resetCompareCookie()
{
	$.cookie( 'adsl_compare_offers_' + SUBDOMAIN, null, { path: '/' } );
	$( '#offers-list input[type=checkbox], #offer-info-compare input[type=checkbox]' ).removeAttr('checked');
	$( '#compare-list-summary .compare-items' ).empty().append('<li class="empty-list"><span>' + EMPTY_COMPARE_LIST + '</span></li>');
	$( '#compare-list-summary .foot-link-container a').addClass('hidden');
}

/**
 * Gestice il cambio di selezione di un checkbox
 *
 * @param checkbox, object, required, L'elemento cliccato
**/
function offersListCheckboxStatusChanged( checkbox )
{
	var checked = checkbox.attr('checked') ? true : false;
	/* se l'elemento non è selezionato */
	if( !checked )
	{
		removeCompareItem( checkbox );
	} else
	{

		var offers = getCompareCookie();
		if( offers.length >= 4 )
		{
			showAlert( 'Attenzione: puoi selezionare al massimo 4 offerte', 'alert' );
			checkbox.removeAttr( 'checked' );
		} else {
			/* aggiunge il nuovo elemento */
			addCompareItem( checkbox );
		}
	}
}

/**
 * Rimuove un elemento della lista di comparazione
 *
 * @param checkbox, object, required, L'elemento da rimuovere
**/
function removeCompareItem( checkbox )
{
	var id = checkbox.attr('id').split('-').pop();
	deleteCompareListItem( id );
}

/**
 * Aggiunge un elemento al comparatore
 *
 * @param checkbox, object, required, Il checkbox di selezione dell'elemento
**/
function addCompareItem( checkbox )
{
	var id = checkbox.attr('id').split('-').pop();
	var inserted = insertCompareListItem( id );
	switch( inserted )
	{
		case 'rejected':

			checkbox.removeAttr( 'checked' );
			break;

		default:
			setCompareListSummary( id );
	}
}

/**
 * Aggiunge un elemento al riepilogo della lista di comparazione
 *
 * @param id, int, required, L'id dell'offerta da aggiungere
**/
function setCompareListSummary( id )
{
	var list = $( '#compare-list-summary' );
	list.find( 'ul li.empty-list' ).remove();
	list.find('.foot-link-container a').removeAttr('class');
	var offer_name = 'Offerta';
	if( $( '#offers-list #offer-' + id ).length )
	{
		offer_name = $( '#offers-list #offer-' + id ).parent().parent().find('td.name p a').html();
	} else {
		offer_name = $( '.offer-info-head h1 .name').html();
	}
	list.children('ul.compare-items').append
	(
		'<li><a href="#remove-' + id + '" title="Rimuovi"><span>Rimuovi</span> ' + offer_name + ' <span>dalla lista</span></a></li>'
	);
	assignRemoveItemHandler( $( 'a[href=#remove-' + id + ']' ) );
}

/**
 * Salva nei cookie un elemento della lista di comparazione
 *
 * @param offer, int, required, L'id dell'offerta da salvare
 *
 * @return boolean
**/
function insertCompareListItem( offer )
{
	/* recupera il cookie */
	var offers = getCompareCookie();
	if( offers.length == 0 )
	{
		/* scrive l'elemento */
		setCompareCookie( new Array( offer ) );
		return 'success';
	}
	/* verifica che l'elemento non sia già presente */
	var exists = false;
	for( var i = 0; i < offers.length; i++ )
	{
		if( offers[i] == offer )
		{
			exists = true;
			break;
		}
	}
	/* se l'elemento non è presente */
	if( !exists )
	{
		/* aggiunge l'elemento */
		offers.push( offer );
		setCompareCookie( offers );
		return 'success';
	} else {
		return 'status';
	}
}

/**
 * Cancella dai cookie un elemento della lista di comparazione
 *
 * @param id, string, required, L'id da cancellare
**/
function deleteCompareListItem( offer )
{
	/* recupera il cookie */
	var offers = getCompareCookie();
	/* se il cookie contiene delle offerte */
	if( offers.length > 0 )
	{
		/* cicla gli elementi per cancellare l'eventuale id passato */
		for( var i = 0; i < offers.length; i++ )
		{
			if( offers[i] == offer )
			{
				offers.splice( i, 1 );
				break;
			}
		}
		$( '#offers-list #offer-' + offer ).removeAttr( 'checked' );
		$( 'a[href=#remove-' + offer + ']' ).parent().remove();
		if( offers.length > 0 )
		{
			setCompareCookie( offers );
		} else {
			resetCompareCookie();
		}
		var list = $('#compare-list-summary');
		if( list.find('ul.compare-items li').length == 0 )
		{
			list.find('.foot-link-container a').addClass('hidden');
			list.find('ul').append('<li class="empty-list"><span>' + EMPTY_COMPARE_LIST + '</span></li>');
		}
	}
}
