if (typeof(DEBUG)=='undefined') {
	var DEBUG = false;
	if ($(document).getUrlParam && $(document).getUrlParam('DEBUG') == 'true') {
		DEBUG = true;
	}
}
if (typeof(debug)=='undefined') {
	function debug(s) {
		if (DEBUG === true) {
			alert(s);
		}
	};
}
/* *********** Focus  HP ************ */
function setjCarouselLite() {
	var numberItem = $(".focusLancio ul li").length;
	if(numberItem > 1) {
		$("#LancioPrincipale .focusLancio").jCarouselLite({
			auto:	10000,
		//	auto:	false,
			btnNext: "#LancioPrincipale .next",
			btnPrev: "#LancioPrincipale .prev",
			speed: 1500,
			visible: 1,
			easing: "easeOutBack"
		});
	} else {
		$("#LancioPrincipale .next img").attr("src","/dl/RaiSport/images/btn_lancioprincipale_dx_off.png");
		$("#LancioPrincipale .prev img").attr("src","/dl/RaiSport/images/btn_lancioprincipale_sx_off.png");
		$("#LancioPrincipale .focusLancio").css("visibility","visible");
	}
}
/* *********** Ricerca  ************ */
function doClear(cerca) {
		if (cerca.value == cerca.defaultValue) {
			cerca.value = ""
		}
	}
/* *********** Schede HP  ************ */
function setjCarouselSchede() {
	var numberItem = $("#Scomparsi ul li").length;
	if(numberItem > 4) {
		$("#Scomparsi .Schede").jCarouselLite({
			auto:	false,
			btnNext: "#Scomparsi .next",
			btnPrev: "#Scomparsi .prev",
			speed: 1000,
			visible: 4,
			scroll: 4,
			easing: "easeOutBack"
		});
		} else {
			$("#Scomparsi .next img").attr("src","/dl/RaiSport/images/btn_lancioprincipale_dx_off.png");
			$("#Scomparsi .prev img").attr("src","/dl/RaiSport/images/btn_lancioprincipale_sx_off.png");
			$("#Scomparsi .Schede").css("visibility","visible");
		}
	}
/* *********** Contatti HP  ************ */
	function setContatti(){
		var span = $(".ContattoTop li span");
		$('.ContattoTop li.primo').show();
	    span.click(function() {
			$('.ContattoTop li').hide();
			var info = $(this).attr("class");
			$('.ContattoTop li.'+info).show();
			$('.ContattoTop').addClass('ContattoExp');
	    });
		$('.ContattoTop li span.close').click(function() {
			$('.ContattoTop li').hide();
			$('.ContattoTop').removeClass('ContattoExp');
			$('.ContattoTop li.primo').show();
	    });
	}
/* *********** clvSchedePagination  ************ */
var schedeOptions = new Array();
var schedeUpdateNielsen = false;

function schedeInitPagination() {
	/* create pagination element */
	//schedeOptions.itemsPerPage = $(".SchedaBigMid li .miniScheda").length > 0 ? 11 : 13;
	schedeOptions.itemsPerPage = 15;
	schedeOptions.itemCount = $(".SchedaBigMid li").length; // first element always shown
	schedeOptions.anchor = ".SchedaBigMid"

	$(".SchedaBigMid .paginazione").pagination(schedeOptions.itemCount, {
		items_per_page: schedeOptions.itemsPerPage,
		num_edge_entries: 5,
		num_display_entries: schedeOptions.itemsPerPage,
		prev_text:"&lt;",
		next_text:"&gt;",
		link_to: schedeOptions.anchor,
		callback: schedePageselectCallback
	});
	schedePageselectCallback(0, $(".SchedaBigMid .paginazione"));
}

function schedePageselectCallback(page_id, panel) {
	// nasconde il link PaginaPrecedente se siamo alla prima pagina
	$("span.prev.current", panel).css('visibility', 'hidden');
	// nasconde il link PaginaSuccessiva se siamo all'ultima pagina
	$("span.next.current", panel).css('visibility', 'hidden');

	// duplica i link di navigazione nei due div .pagineTop e .pagineBottom
	// qui abbiamo un solo pannello con i link della paginazione: non serve clonare.
	//var p1 = panel.clone(true);
	//var p2 = panel.clone(true);
	//$(".SchedaBigMid .paginazione").empty().append(p1.children());
	//$("#Pageschede .pagineBottom").empty().append(p2.children());

	// effettua la paginazione vera e propria
	var from = (page_id * schedeOptions.itemsPerPage)-1;
	$(".SchedaBigMid li").hide();
	var items = $(".SchedaBigMid li:gt("+from+"):lt("+schedeOptions.itemsPerPage+")");
	items.show();
	$('img', items).trigger('pagedIn');

	// scroll up solo se .SchedaBigMid non e' visibile (es: al primo caricamento)
	if ( $('html,body').scrollTop() > $( '.SchedaBigMid' ).offset().top)
		$('html,body').animate( {scrollTop: $( '.SchedaBigMid' ).offset().top}, 500  );

	if (schedeUpdateNielsen) {
		var url = window.location+'#page='+page_id;
		setNielsen(url);
	}
	schedeUpdateNielsen = true;
	return false;
}
/* ********* Fine clvSchedePagination ********* */

/* *********** clvVideoPagination  ************ */
function setvideojCarouselLite() {
	var numberItem = $(".Box ul li").length;
	if(numberItem > 3) {
		$(".VideoBox .Box").jCarouselLite({
		//	auto:	10000,
			auto:	false,
			btnNext: ".VideoBox .next",
			btnPrev: ".VideoBox .prev",
			speed: 1500,
			scroll: 3,
			visible: 3,
			vertical: true
		});
	} else {
		$(".VideoBox .next img").css("visibility","hidden");
		$(".VideoBox .prev img").css("visibility","hidden");
		$(".VideoBox .Box").css("visibility","visible");
	}
}
/* ********* Fine clvVideoPagination ********* */
function loadVideo(videoUrl) {
		$('.LancioMid').html('Video');
		var focusContent = $('#videoFocus').html();
		$('#videoFocus').html("");
		$('#videoFocus').addClass("bgPlayer");
		$('#videoFocus').media({
				type: 'wmv',
			    width:     319,
			    height:    274,
				autoplay:  true,
				bgColor: '#E9E2DD',
			    src:       videoUrl
		});
		$('#videoFocus').click(function() {
			$('#videoFocus').removeClass("bgPlayer");
			$('.LancioMid').html('Focus');
			$('#videoFocus').html("");
			$('#videoFocus').html(focusContent);
	    });
	}

/* *********** Media Video/Foto  ************ */
function setjCarouselMedia() {
	var numberItem = $("#mediaCLV ul li").length;
	if(numberItem > 4) {
		$("#mediaCLV .mediaItems").jCarouselLite({
			auto:	false,
			btnNext: "#mediaCLV .next",
			btnPrev: "#mediaCLV .prev",
			speed: 1000,
			visible: 4,
			scroll: 4
		});
		} else {
			$("#mediaCLV .next img").css("visibility","hidden");
			$("#mediaCLV .prev img").css("visibility","hidden");
			$("#mediaCLV .mediaItems").css("visibility","visible");
		}
	}

/* ********* hover miniScheda ********* */
function setMiniSchedeHover() {
	$('.miniScheda').each(function() {
		if ($(this).data('hoverSet') != true) {
			$(this).hover(function(){
				$(this).addClass('miniSchedaHover');
			},
			function(){
				$(this).removeClass('miniSchedaHover');
			});
		}
		$(this).data('hoverSet', true);
	});
}
$(setMiniSchedeHover);


/* ********* Nielsen ********* */
function setNielsen(url) {
	$("#nielsen img").attr("src","//secure-it.imrworldwide.com/cgi-bin/m?ci=rainet-it&cg=0&si="+urlencode(url));
}

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';

    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }

    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });

    return ret;
}
/* ********* CLV Ricerca ********** */
/* usato anche in altre pagine, che non sono altro che viste non filtrate */


function decodeEntities(s) {
	// meglio far lavorare il browser :P (decodifica anche le entita' testuali), ma con IE non funge :(
	//var n = $('<span>'+s+'</span>');
	//return n.text();
	var i = s.indexOf('&#');
	var t = '';
	while (i>=0) {
		t += s.substring(0, i);
		s = s.substring(i+2);
		var j = s.indexOf(';');
		if (j>=0) {
			var e = s.substring(0, j);
			s = s.substring(j+1);
			var c = null;
			eval('c = String.fromCharCode("'+e+'");'); // gestione eccezioni ;)
			if (c == null || c == '' || c == '\000')
				t += '&#'+e+';';
			else
				t += c;
		} else {
			t += '&#'+s;
		}
		i = s.indexOf('&#');
	}
	return t==''?s:t;
}

var CLVRicerca = {};

CLVRicerca.titoloPagina = "Ricerca";
CLVRicerca.updateNielsen = false;
CLVRicerca.xmlContent = null;
CLVRicerca.filters = null;
CLVRicerca.xmlName = null;

CLVRicerca.setFilters = function(filters) {
	CLVRicerca.filters = filters;
}
CLVRicerca.setXml = function(fname, catname) {
	CLVRicerca.xmlName = fname;
	CLVRicerca.catname = catname;
	$('#Center .sezione span.categoria').html(CLVRicerca.titoloPagina);
	// non la mostriamo: non sappiamo cosa/come cercare :(
	//$('#formRicerca .SelectCLV:eq(1)').show(); // mostra la select per l'edizione
	$('#formRicerca .TestoContenuto').show(); // mostra i campi della ricerca
	$('#formRicerca .Aggiornamenti').show();
	$('#formRicerca .Anagrafica').show();
	$('#formRicerca .go').show();

	// imposta i link corretti per l'ordinamento, in base all'xml selezionato
	switch(fname) {
		case '/dl/clv/ricerca/Page-2dc1371f-d652-4fad-9be2-a6ec0f1b1d72.html': /*Scomparsi*/
			$('.spanSort').html('Ordina per <span onclick="CLVRicerca.applySort(\'titolo\', this);">Cognome</span> <span onclick="CLVRicerca.applySort(\'data_PMO\', this);">Data prima messa in onda</span> <span onclick="CLVRicerca.applySort(\'data_Scomparsa\', this);">Data scomparsa</span>');
			break;
		case '/dl/clv/ricerca/Page-979431e9-eb21-422b-9556-46e07e8d65c2.html': /*Appelli Web*/
			$('.spanSort').html('Ordina per <span onclick="CLVRicerca.applySort(\'titolo\', this);">Cognome</span> <span onclick="CLVRicerca.applySort(\'data_PMO\', this);">Data prima messa in onda</span> <span onclick="CLVRicerca.applySort(\'data_Scomparsa\', this);">Data scomparsa</span>');
			break;
		case '/dl/clv/ricerca/Page-0355f5ac-10b1-4792-9a61-98e172a5b099.html': /*Auto pirata*/
			$('.spanSort').html('Ordina per <span onclick="CLVRicerca.applySort(\'titolo\', this);">Cognome</span> <span onclick="CLVRicerca.applySort(\'data_Tv\', this);">Data Pubblicazione</span> <span onclick="CLVRicerca.applySort(\'data_Incidente\', this);">Data incidente</span>');
			break;
		case '/dl/clv/ricerca/Page-6232e4ac-31d8-49bb-b86d-80e01a84e65f.html': /*Misteri*/
			$('.spanSort').html('Ordina per <span onclick="CLVRicerca.applySort(\'titolo\', this);">Titolo</span> <span onclick="CLVRicerca.applySort(\'data_PMO\', this);">Data prima messa in onda</span>');
			break;
		case '/dl/clv/ricerca/Page-e428523e-cc18-415c-8391-d48385a4ec91.html': /*Dove sei?*/
			$('.spanSort').html('Ordina per <span onclick="CLVRicerca.applySort(\'titolo\', this);">Titolo</span> <span onclick="CLVRicerca.applySort(\'data_PMO\', this);">Data prima messa in onda</span>');
			break;
		case '/dl/clv/ricerca/Page-8f7491e1-8c93-488d-8876-dd0eb7cbaeb2.html': /*Corpi senza nome*/
			$('.spanSort').html('Ordina per <span onclick="CLVRicerca.applySort(\'titolo\', this);">Cognome</span> <span onclick="CLVRicerca.applySort(\'data_PMO\', this);">Data prima messa in onda</span> <span onclick="CLVRicerca.applySort(\'data_Scomparsa\', this);">Data scomparsa</span>');
			break;
		case '/dl/clv/ricerca/Page-be252cc9-58bf-4c2f-91f7-122a06bce81f.html': /*Li riconoscete? */
			$('.spanSort').html('Ordina per <span onclick="CLVRicerca.applySort(\'titolo\', this);">Cognome</span> <span onclick="CLVRicerca.applySort(\'data_PMO\', this);">Data prima messa in onda</span> <span onclick="CLVRicerca.applySort(\'data_Scomparsa\', this);">Data scomparsa</span>');
			break;
		default:
			$('.spanSort').html('Ordina per <span onclick="CLVRicerca.applySort(\'titolo\', this);">Cognome</span> <span onclick="CLVRicerca.applySort(\'data_PMO\', this);">Data prima messa in onda</span> <span onclick="CLVRicerca.applySort(\'data_Scomparsa\', this);">Data scomparsa</span>');
	}
}

CLVRicerca.showFormRicerca = function() {
	$('#RicercaForm').show();
	$('#RicercaRisultati').hide();
}

CLVRicerca.eseguiRicerca = function() {
	// TODO
	/*
	crea i filtri
	carica l'xml corretto in base a quello settato. es: CLVRicerca.loadXml(CLVRicerca.xmlName);
	nasconde div#RicercaForm
	mostra div#RicercaRisultati
	*/
	$('#UlRisultati').empty();
	CLVRicerca.createFilters();
	//$('html,body').animate( {scrollTop: $( '.clv_Ricerca' ).offset().top}, 500  ); // scroll alla form

	var ul = $('#UlRisultati');
	ul.empty();
	$('#RicercaForm').hide();
	$('#RicercaRisultati').show();
	$('#RicercaRisultati .infoStar').hide();
	$("#RicercaRisultati .paginazione").hide();
	$("#RicercaRisultati .paginazione").empty();
	// ricerca in corso....
	$('.resultInfo').show();
	$('.resultInfo').html('<img src="/dl/clv/images/loading.gif" alt="Ricerca in corso..." height="25"/>');
	CLVRicerca.loadXml(CLVRicerca.xmlName);
	$('#RicercaRisultati .infoStar').show();
	$('#RicercaRisultati .paginazione').show();
}

CLVRicerca.createFilters = function() {
	var form = document.getElementById('formRicerca');
	var filters = {};

	$('#formRicerca input').each(function(n,el) {
		var n = this.name;
		if (!n) return;
		var v = $.fieldValue(this);
  		var nameTag = n;
		var valueTag = v;
		if (v!= '' && v !== null && typeof v != 'undefined') {

	//	alert(nameTag+' - '+valueTag);

		filters[''+nameTag+''] = ''+valueTag;
		}
		/*
		var t = this.type;
		if (t == 'checkbox' || t == 'radio')
            	{
		var nameTag = $(this).attr('name');
		var valueTag = $(this).checked;
		alert(nameTag+' - '+valueTag);
		filters[''+nameTag+''] = valueTag;
		}
		else {
		var nameTag = $(this).attr('name');
		var valueTag = $(this).fieldValue();
		if (valueTag !="") {
		alert(nameTag+' - '+valueTag);
		filters[''+nameTag+''] = valueTag;
		}
*/

	});
	 $('#formRicerca select').each(function(n,element){
		var index = element.selectedIndex;
	        if (index > 0) {
		var nameTag = $(this).attr('name');
		var valueTag = $(this).fieldValue();

		//alert(nameTag+' - '+valueTag);

		filters[''+nameTag+''] = ''+valueTag;
		}
	});


	CLVRicerca.setFilters(filters);
}

CLVRicerca.loadXml = function(fname) {
CLVRicerca.timeLoadingStarted = new Date().getTime();
	$('<div></div>').load(fname, function() {CLVRicerca.xmlContent = $(this); CLVRicerca.applyFilter()})
}

CLVRicerca.parseDate = function(dateString) {
	var m = dateString.match(/^([0-9]*)\/([0-9]*)\/([0-9]*)$/);
	if (m == null)
		return null;

	/*m[1] = parseInt(m[1]);
	m[2] = parseInt(m[2]);
	m[3] = parseInt(m[3]);
	var t = m[3]+'/'+(m[2]<10?'0':'')+m[2]+'/'+(m[1]<10?'0':'')+m[1];*/
	var t = m[3]+'/'+m[2]+'/'+m[1];
	return t;
}
/**
	value: valore da controllare
	threshold: soglia da considerare
	lessThan: boolean, indica se valutare il valore come minore o maggiore della soglia

	return boolean
*/
CLVRicerca.filterDate = function(value, threshold, lessThan) {
	var t = CLVRicerca.parseDate(threshold);
	//alert('t['+t+']');
	if (t == null)
		return true; // filtro non valido: lo ignoro e accetto tutto.
	var b = false;
	var a = value.split(',');
	// basta che vada bene una...
	/* TODO: attenzione: se viene selezionato un range di date (nei DUE campi From e To) e le date nel valore sono multiple, potrebbero esserci problemi e matchare date errate (in particolare se la data nel campo To viene scelta precedente al campo From).
	 */
	for (i in a) {
		var v = CLVRicerca.parseDate($.trim(a[i]));
		//alert('v['+v+']')
		if (v != null) {
			if (lessThan)
				b = b || (v <= t);
			else
				b = b || (v >= t);
		}
		//alert('b['+(b?'true':'false')+']');
	}
	return b;
}

CLVRicerca.applyFilter = function(isAsync) {
	// chiamata senza parametri o chiamata sincrona esplicita: rendo la chiamata asincrona
	if (typeof(isAsync) == 'undefined' || isAsync != true) {
		window.setTimeout(
			function() {
				CLVRicerca.applyFilter(true);
			}
			, 10);
		return;
	}

CLVRicerca.timeLoadingFinished = new Date().getTime();
debug('xml loaded in '+(CLVRicerca.timeLoadingFinished - CLVRicerca.timeLoadingStarted)+'ms');

	var filters = $.extend({}, CLVRicerca.filters || {});

	if (!CLVRicerca.xmlContent) return;

	var timeA = new Date().getTime();

	CLVRicerca.risultatoRicerca = $('scheda', CLVRicerca.xmlContent).filter(function() {
		var keepIt = true;
		for (var f in filters) {
			// TODO gestione ad hoc per filtri speciali (range vari, statura, etc)
			var testResult = true;
			var attrValue = $(this).attr(f) || "";
			attrValue = decodeEntities(attrValue.toLowerCase());

			filters[f] = filters[f].toLowerCase();
			if (f == 'updatedFrom' || f == 'scomparsaFrom' || f == 'tvFrom' || f == 'pubblicazioneFrom') {
				if (f = 'updatedFrom') {
					attrValue = $(this).attr('aggiornamenti') || "";
					attrValue = attrValue.split(',');
					attrValue = attrValue[0]; // prendo solo la prima data, che e' la piu' recente (da xsl)
				} else if (f = 'scomparsaFrom') {
					attrValue = $(this).attr('data_Scomparsa') || "";
				} else if (f = 'tvFrom') {
					attrValue = $(this).attr('data_Tv') || "";
				} else if (f = 'pubblicazioneFrom') {
					attrValue = $(this).attr('data_Tv') || "";
				}
				testResult = CLVRicerca.filterDate(attrValue, filters[f], false); // false indica >=
			} else if (f == 'updatedTo' || f == 'scomparsaTo' || f == 'tvTo' || f == 'pubblicazioneTo') {
				if (f = 'updatedTo') {
					attrValue = $(this).attr('aggiornamenti') || "";
					attrValue = attrValue.split(',');
					attrValue = attrValue[0]; // prendo solo la prima data, che e' la piu' recente (da xsl)
				} else if (f = 'scomparsaTo') {
					attrValue = $(this).attr('data_Scomparsa') || "";
				} else if (f = 'tvTo') {
					attrValue = $(this).attr('data_Tv') || "";
				} else if (f = 'pubblicazioneTo') {
					attrValue = $(this).attr('data_Tv') || "";
				}
				testResult = CLVRicerca.filterDate(attrValue, filters[f], true); // true indica <=
			} else if (f == 'statura') {
				//if (DEBUG) { alert(typeof(f)+':'+f+' => '+typeof(filters[f])+':['+filters[f]+'] *** attrValue: '+typeof(attrValue)+':['+attrValue+']'); DEBUG=false;}
				attrValue = parseInt(attrValue);
				if (filters[f] == 'lt_50') {
					testResult = attrValue < 50;
				} else if (filters[f] == 'lt_100') {
					testResult = attrValue >= 50 && attrValue <= 100;
				} else if (filters[f] == 'lt_150') {
					testResult = attrValue >= 100 && attrValue <= 150;
				} else if (filters[f] == 'lt_180') {
					testResult = attrValue >= 150 && attrValue <= 180;
				} else if (filters[f] == 'lt_200') {
					testResult = attrValue >= 180 && attrValue <= 200;
				} else { // filters[f] == 'gt_200'
					testResult = attrValue >= 200;
				}
			} else if (f == 'testoContenuto') {
				// ???
				testResult = attrValue.indexOf(filters[f])>=0;
			} else {
				testResult = attrValue.indexOf(filters[f])>=0;
			}
			keepIt = keepIt && testResult;
		}
		return keepIt;
	});

	var timeB = new Date().getTime();
	debug('filtered in '+(timeB-timeA)+'ms');

	var sortBy = null;
	var asc = true;
	if (CLVRicerca.compareCriteria != null) {
		sortBy = CLVRicerca.compareCriteria;
	}
	if (CLVRicerca.sortAsc != null) {
		asc = CLVRicerca.sortAsc;
	}
	CLVRicerca.sortAndShowItems(sortBy, asc); // criteri di ordinamento ( array!! ), e true/false per asc/desc (true => asc, false => desc)
	// es:
	// CLVRicerca.sortAndShowItems(new Array('data_Tv'), true)
}

CLVRicerca.compareCriteria = null;
CLVRicerca.sortAsc = true;
CLVRicerca.defaultCompareCriteria = new Array('titolo', 'cognome', 'nome');
CLVRicerca.debug = false;
CLVRicerca.comparations = 0;
CLVRicerca.compareItems = function(a, b) {
	if (CLVRicerca.compareCriteria == null)
		CLVRicerca.compareCriteria = CLVRicerca.defaultCompareCriteria;
	var c = CLVRicerca.compareCriteria;
	var lt = -1;
	var gt = 1;
	if (!CLVRicerca.sortAsc) {
		lt = 1;
		gt = -1;
	}
	CLVRicerca.comparations++;
	for (i in c) {
		var vc = c[i];
		var va = $(a).attr(vc);
		var vb = $(b).attr(vc);
		if (vc == 'data_Tv' || vc == 'data_scomparsa') {
			va = va.split(',');
			va = CLVRicerca.parseDate($.trim(va[0])) || '';
			vb = vb.split(',');
			vb = CLVRicerca.parseDate($.trim(vb[0])) || '';
		}
		if ( va < vb ) {
			return lt; // Less than 0: Sort "a" to be a lower index than "b"
		} else if ( va > vb ) {
			return gt; // Greater than 0: Sort "b" to be a lower index than "a"
		}
		// else: continua con il prossimo criterio di confronto
	}
	return 0; // Zero: "a" and "b" should be considered equal, and no sorting performed.
}

CLVRicerca.sortAndShowItems = function(sortBy, asc) {
	var elementi = CLVRicerca.risultatoRicerca;

	//debug('sortAndShowItems');

	CLVRicerca.compareCriteria = sortBy;
	CLVRicerca.sortAsc = asc;
	//debug('2: '+typeof(CLVRicerca.compareCriteria)+'\n['+CLVRicerca.compareCriteria+']');
	//debug('2: '+typeof(CLVRicerca.sortAsc)+'\n['+CLVRicerca.sortAsc+']');
	CLVRicerca.comparations = 0;

	//debug('sorting');

	var timeA = new Date().getTime();
	debug('criteria:\n'+CLVRicerca.compareCriteria);
	elementi = $(elementi.get().sort(CLVRicerca.compareItems));
	var timeB = new Date().getTime();

	debug('sorted in '+(timeB-timeA)+'ms');

	timeA = new Date().getTime();
	var items = CLVRicerca.buildItems(elementi);
	timeB = new Date().getTime();

	debug('elements created in '+(timeB-timeA)+'ms');

	// conta elementi
	var totalResult = elementi.length;

	if (CLVRicerca.titoloPagina != "Ricerca") {
		$('.resultInfo').hide();
	} else {
		$('.resultInfo').html('Totale risultati: '+totalResult);
	}

	$('li', items).hide();
	var ul = $('#UlRisultati');
	ul.empty();
	ul.append(items.children());
	$('li img', ul).one('pagedIn', function(){
		var s = $(this).attr('src');
		var t = '/dl/images/1229108470011tappoclv.jpg?'; // path img tappo
		if (s.indexOf(t)>=0) { // s contiene t (potrebbe avere www.rai.it davanti...
			s = s.substring(s.indexOf(t)+t.length);
			$(this).replaceWith('<img src="'+s+'" />');
			//$(this).attr('src', s);
		}
	});
	CLVRicerca.pagination.init();
}

CLVRicerca.buildItems = function(items) {
	var ul = $('<ul></ul>');
	for (var i=0; i<items.length; i++) {
		//var l = CLVRicerca.buildItemHtml(items.get(i));
		var l = $('<li></li>');
		l.data('scheda', items.get(i));
		l.one('pagedIn', function() {
			var n = CLVRicerca.buildItemHtml($(this).data('scheda'));
			var img = $('img', n);
			var s = img.attr('src');
			var t = '/dl/images/1229108470011tappoclv.jpg?'; // path img tappo
			if (s.indexOf(t)>=0) { // s contiene t (potrebbe avere www.rai.it davanti...
				s = s.substring(s.indexOf(t)+t.length);
				if (s.length==0) {
					s = '/dl/images/1229108470011tappoclv.jpg';
				}
				img.replaceWith('<img src="'+s+'" />');
			}
			$(this).replaceWith(n);
			setMiniSchedeHover();
		});
		ul.append(l);
	}
	return ul;
}

CLVRicerca.elementi = new Array(
		{nome: 'soprannome', label: 'Soprannome: '},
		{nome: 'sesso', label: 'Sesso: '},
		{nome: 'eta_scomparsa', label: 'Et&agrave;: '},
		{nome: 'data_Nascita', label: 'Data di nascita: '},
		{nome: 'luogo_Nascita', label: 'Origine / luogo di nascita: '},
		{nome: 'nazionalita', label: 'Naz.: '},
		{nome: 'corporatura', label: 'Corporatura: '},
		{nome: 'peso', label: 'Peso: '},
		{nome: 'statura', label: 'Statura: '},
		{nome: 'occhi', label: 'Occhi: '},
		{nome: 'capelli', label: 'Capelli: '},
		{nome: 'abbigliamento', label: 'Abbigliamento: '},
		{nome: 'segni_particolari', label: 'Segni particolari: '},
		{nome: 'veicolo', label: 'Veicolo: '},
		{nome: 'circostanze', label: 'Circostanze: '},
		{nome: 'descrizione', label: 'Descrizione: '},
		{nome: 'data_Scomparsa', label: 'Data scomparsa: '},
		{nome: 'luogo_Scomparsa', label: 'Luogo scomparsa: '},
		{nome: 'aggiornamenti', label: 'Aggiornamenti: '},
		{nome: 'esito', label: 'Esito: '},
		{nome: 'data_Esito', label: 'Data esito: '},
		{nome: 'edizione', label: 'Edizione: '},
		{nome: 'data_Tv', label: 'Data messa in onda: '}
	);

CLVRicerca.buildItemHtml = function(item) {
	item = $(item);

	var cat = item.attr('categoria');

	var pathImgTappo = '/dl/images/1229108470011tappoclv.jpg';

	var e = '<li><a title="Link alla Scheda" target="_top" href="'+item.attr('link_Scheda')+'"><div class="miniScheda"><div class="contAll">';

	//var l = $('<li></li>');
	//var a = l.append($('<a title="Link alla Scheda" target="_top" href="'+item.attr('link_Scheda')+'"></a>'));
	//var d = a.append($('<div class="miniScheda"></div>'));

	//d.append($('<img alt="Scomparso" height="88" width="77" src="'+item.attr('foto')+'" />'));
	e+='<div class="contImg"><img alt="Scomparso" height="88" width="77" src="'+pathImgTappo+'?'+item.attr('foto')+'" /></div>';
	var s = '';
	if (item.attr('titolo') != null && item.attr('titolo') != '') {
		s = item.attr('titolo');
	} else {
		if (item.attr('nome') != null)
			s += item.attr('nome')+' ';
		/*if (item.attr('soprannome') != null)
			s += item.attr('soprannome')+' ';*/
		if (item.attr('cognome') != null)
			s += item.attr('cognome')+' ';
	}
	//d.append($('<h2>'+s+'</h2>'));
	e += '<h2>'+s+'</h2><p>'

	for (var i in CLVRicerca.elementi) {
		// skip eta_scomparsa per la categoria dove_sei
		if (!(CLVRicerca.elementi[i].nome == 'eta_scomparsa' && $.trim(item.attr(CLVRicerca.elementi[i].nome)) == '')) {
			var t = CLVRicerca.elementi[i].label;
			var v = $.trim(item.attr(CLVRicerca.elementi[i].nome));
			if ('eta_scomparsa' == CLVRicerca.elementi[i].nome) v = v + '*';
			if (t != null && t.length>0 && v != null && v.length>0) {
				//d.append($('<span class="info"><b>'+t+'</b>'+v+'<br /></span>'));
				e+='<span class="info"><b>'+t+'</b>'+v+'<br /></span>';
			}
		}
	}
	e+="</p></div></div></a></li>";
	var l = $(e);
	return l;
}

CLVRicerca.hlSelectItem = function(elem) {
	$('.Desc', $(elem).parent()).css('fontWeight', 'normal');
	$(elem).css('fontWeight', 'bold');;
}
CLVRicerca.pagination = {}
CLVRicerca.pagination.options = {
	itemsPerPage: 15,
	anchor: "#RicercaRisultati"
}
CLVRicerca.pagination.init = function() {
	/* create pagination element */
	CLVRicerca.pagination.options.itemCount = $("#UlRisultati li").length;

	$("#RicercaRisultati .paginazione").pagination(CLVRicerca.pagination.options.itemCount, {
		items_per_page: CLVRicerca.pagination.options.itemsPerPage,
		num_edge_entries: 5,
		num_display_entries: CLVRicerca.pagination.options.itemsPerPage,
		prev_text:"&lt;",
		next_text:"&gt;",
		link_to: CLVRicerca.pagination.options.anchor,
		callback: CLVRicerca.pagination.callback
	});
	CLVRicerca.pagination.callback(0, $("#RicercaRisultati .paginazione"));
}

CLVRicerca.pagination.callback = function(page_id, panel) {
	// nasconde il link PaginaPrecedente se siamo alla prima pagina
	$("span.prev.current", panel).css('visibility', 'hidden');
	// nasconde il link PaginaSuccessiva se siamo all'ultima pagina
	$("span.next.current", panel).css('visibility', 'hidden');
	if ($('a', panel).length <= 0) // nessun link -> una sola pagina
		panel.hide();
	else
		panel.show();

	// effettua la paginazione vera e propria
	var from = (page_id * CLVRicerca.pagination.options.itemsPerPage)-1;
	$("#UlRisultati li").hide();
	var items = $("#UlRisultati li:gt("+from+"):lt("+CLVRicerca.pagination.options.itemsPerPage+")");
	items.show();
	$('img', items).trigger('pagedIn');
	items.trigger('pagedIn');

	// scroll up solo se .SchedaBigMid non e' visibile (es: al primo caricamento)
	if ( $('html,body').scrollTop() > $( '#RicercaRisultati' ).offset().top)
		$('html,body').animate( {scrollTop: $( '#RicercaRisultati' ).offset().top}, 500  );

	if (CLVRicerca.updateNielsen) {
		var url = window.location+'#catName='+CLVRicerca.catname+'&page='+page_id;
		setNielsen(url);
	}
	CLVRicerca.updateNielsen = true;

	return false;
}

CLVRicerca.applySort = function(name, elem) {
	// 'titolo', this
	elem = $(elem);
	var sortFields = null;
	/*if (name == 'titolo') {
		sortFields = new Array('titolo', 'cognome', 'nome');
	} else if (name == 'data_tv') {
		sortFields = new Array('data_Tv');
	} else if (name == 'data_scomparsa') {
		sortFields = new Array('data_scomparsa');
	}*/
	name = name.toLowerCase();
	switch(name) {
		case "titolo":
			CLVRicerca.compareCriteria = new Array('titolo', 'cognome', 'nome');
			CLVRicerca.sortAsc = true;
			break;
		case "data_Tv":
		case "data_tv":
			CLVRicerca.compareCriteria = new Array('data_Tv');
			CLVRicerca.sortAsc = false;
			break;
		case "data_Incidente":
		case "data_incidente":
			CLVRicerca.compareCriteria = new Array('data_Incidente');
			CLVRicerca.sortAsc = false;
			break;
		case "data_Scomparsa":
		case "data_scomparsa":
			CLVRicerca.compareCriteria = new Array('data_Scomparsa');
			CLVRicerca.sortAsc = false;
			break;
		case "data_PMO":
		case "data_pmo":
			CLVRicerca.compareCriteria = new Array('data_PMO');
			CLVRicerca.sortAsc = false;
			break;
		case "data_UMO":
		case "data_umo":
			CLVRicerca.compareCriteria = new Array('data_UMO');
			CLVRicerca.sortAsc = false;
			break;
		default:
			CLVRicerca.compareCriteria = null;
			CLVRicerca.sortAsc = true;
	}
	sortFields = CLVRicerca.compareCriteria;
	asc = CLVRicerca.sortAsc;

	var asc = true;
	//if (elem.data('sortedAsc'))
	//	asc = false;

	elem.data('sortedAsc', asc);

	debug('sort by '+name+'\n'+sortFields);

	CLVRicerca.sortAndShowItems(sortFields, asc);
}