/**
 * 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 ad una lista di Digital
**/
function initDigitalList()
{
	/* imposta i pulsanti per il cambio del tipo di visualizzazione della lista */
	$('#view-choices a').click
	(
		function(){ setListViewStyle( this ); return false; }
	);
	/* imposta le azioni relative al click sui checkbox */
	$( '#products-result-list input[type=checkbox]' ).click
	(
		function(){ productsListCheckboxStatusChanged( $( this ) ); }
	);
	/* mostra la lista di comparazione se sono presenti degli elementi */
	if( $( '#list-footer ul li h4' ).length > 0 )
	{
		$( '#list-footer a.panel-close-button' ).click
		(
			function(){ removeCompareItem( $( this ).parent() ); return false; }
		);
		$( '#list-footer' ).show();
	}
	/* gestisce il click sul pulsante di ricerca */
	$( '#filter-go-button').click
	(
		function() { filterButtonClicked( this ); return false; }
	);
	/* submit ricerca avanzata */
	$( '#advanced-search-form' ).submit
	(
		function(){ return advancedSearchSubmit(); }
	);

	$('#refine-links select').slice( 2, 5 ).each
	(
		function()
		{
			autoAdjustSelectSize( $(this), 100, true );
		}
	);
	$('#refine-links select').slice( 0, 2 ).each
	(
		function()
		{
			autoAdjustSelectSize( $(this), 100, false );
		}
	);
}

/**
 * Gestice il click sul pulsante dei filtri di ricerca
**/
function advancedSearchSubmit()
{
	/* stringa di ricerca */
	var s = $('#advanced-search-form-input').val();
	/* id della categoria */
	var c = $('#advanced-search-form-cat').val();
	/* id del produttore */
	var m = $('#advanced-search-form-mak').val();
	/* se la categoria e il produttore sono impostati */
	if( c != '' && m != '' )
	{
		/* cerca comunque */
		return true;
	} else {
		/* altrimenti, il testo deve essere lungo almeno 3 caratteri */
		if( $.trim( s ).length < 2 )
		{
			showAlert( 'Devi inserire almeno due caratteri!' );
			return false;
		} else {
			return true;
		}
	}
}

/**
 * Gestice il click sul pulsante dei filtri di ricerca
 *
 * @param link, object, required, Il riferimento al pulsante
**/
function filterButtonClicked( link )
{
	var filters = $( '#refine-links select:not(.manufacturers-select)' );
	var filter;
	var search = new Array();
	for( var i = 0; i < filters.length; i++ )
	{
		filter = $( filters[ i ] );
		/* id = filter.attr( 'id' ).substr( filter.attr( 'id' ).lastIndexOf( '-' ) + 1 ); */
		if( filter.val() != '' )
		{
			search.push( filter.val() );
		}
	}
	var cleaned = CURRENT_PAGE_URL.match( /\.html$/ );
	var qmarked = CURRENT_PAGE_URL.match( /\.html\?$/ );

	var maker_id = $( '#refine-links .manufacturers-select' ).val();
	var query_params = new Array();
	if( maker_id != '' && maker_id != undefined )
	{
		query_params.push( 'mi=' + maker_id );
	}
	if( search.length > 0 )
	{
		query_params.push( 'attr=' + Base64.encode( search.join( '|' ) ) ) ;
	}
	query_params = query_params.join('&');

	var search_string = CURRENT_PAGE_URL
	if( query_params != '' )
	{
		if( cleaned )
		{
			search_string += '?' + query_params;
		} else if( qmarked )
		{
			search_string += query_params;
		} else {
			search_string += '&' + query_params;
		}
	}
	if( search_string.match( /\.html\?$/ ) )
	{
		search_string = search_string.substr( 0, search_string.length - 1 );
	}
	window.location.href = search_string.split( '&amp;' ).join( '&' );
}

/**
 * Gestice il cambio di selezione di un checkbox
 *
 * @param checkbox, object, required, L'elemento cliccato
**/
function productsListCheckboxStatusChanged( checkbox )
{
	var checked = checkbox.attr('checked') ? true : false;
	/* recupera l'id del checkbox */
	var id = checkbox.attr( 'id' );
	/* se l'elemento non è selezionato */
	if( !checked )
	{
		removeCompareItem( $( '#item-' + id ) );
	} else
	{
		var total = $( '#list-footer ul li h4' ).length;
		if( total == 5 )
		{
			showAlert( 'Attenzione: puoi selezionare al massimo 5 prodotti', 'alert' );
			checkbox.removeAttr( 'checked' );
		} else {
			/* rimuove l'elemento testuale */
			$('#list-footer .no-items' ).remove();
			/* se l'elemento non esiste già */
			if( $( '#item-' + id ).html() == null )
			{
				/* aggiunge il nuovo elemento */
				addCompareItem( checkbox );
			}
		}
	}
}

/**
 * Rimuove un elemento della lista di comparazione
 *
 * @param item, object, required, L'elemento da rimuovere
**/
function removeCompareItem( item )
{
	if( item.html() != null )
	{
		var id = item.attr('id').substr( 5 );
		$( '#' + id ).removeAttr( 'checked' );
		item.remove();
		deleteCompareListItem( id );
	}
	if( $( '#list-footer ul li' ).length == 0 )
	{
		$( '#list-footer ul' ).append( '<li class="no-items hidden"><span>Nessun elemento selezionato</span></li>' );
		$( '#list-footer' ).hide();
	}
}

/**
 * Aggiunge un elemento al comparatore
 *
 * @param checkbox, object, required, Il checkbox di selezione dell'elemento

**/
function addCompareItem( checkbox )
{
	var id = checkbox.attr('id');
	var category = checkbox.parent().find( '.product-category' ).attr( 'class' );
	category = category.split( ' hidden' ).join( '' ).split( 'product-category ' ).join( '' );
	category = category.substr( category.lastIndexOf( '-' ) + 1);

	var inserted = insertCompareListItem( id, 'category', category );

	switch( inserted )
	{
		case 'reset': /* il reset prevede l'esecuzione successiva del success */

			clearCompareList( checkbox );

		case 'success':

			createCompareItemGhost( id, checkbox );
			break;

		case 'rejected':

			checkbox.removeAttr( 'checked' );
			break;

		default:
	}
}

/**
 * Svuota la lista di comparazione
**/
function clearCompareList( checkbox )
{
	$( '#list-footer ul li' ).remove();
	checkbox.parent().parent().find('input[type=checkbox]').removeAttr('checked');
}

/**
 * Crea la finestra del prodotto nella lista di comparazione
 *
 * @param id, string, required, L'id del prodotto
 * @param checkbox, jQuery, required, Il checkbox di selezione
**/
function createCompareItemGhost( id, checkbox )
{
	var image = checkbox.parent().find('.product-img').clone();
	var link = checkbox.parent().find('h4').clone();
	checkbox.removeAttr('checked').attr('checked','checked');

	var li = $( '<li id="item-' + id + '"></li>' );
	li.html( '<a href="#" class="form-styled-button panel-close-button" title="Rimuovi"><span class="hidden">Chiudi</span></a>' );

	li.append( image );
	li.append( link );
	li.find( 'a.panel-close-button' ).click
	(
		function(){ removeCompareItem( $( this ).parent() ); return false; }
	);
	$( '#list-footer ul ').append( $( li ) );
	$( '#list-footer' ).show();
}

/**
 * Cambia la modalità di visualizzazione della lista
 *
 * @param link, object, required, Il link scelto
**/
function setListViewStyle( link )
{
	var href = $( link ).attr( 'href' );
	var style = href.substr( 1, 4 );

	$( '#products-result-list, #news-result-list, #videos-result-list, #reviews-result-list, #alatest-result-list' ).removeClass
	( 'grid' ).removeClass( 'list' ).addClass( style );
	$( '#view-choices li' ).removeClass( 'selected' );
	$( link ).parent().addClass( 'selected' );

	$.cookie( 'products_list_view', style, { path: '/' } );
}