// F1 front-end/back-end toggle
	if (document.all) {
		document.onhelp = function() {
			location.href = '/admin/';
			return false;
		}
	} else {
		document.onkeydown = function (evt) {
			if (evt.keyCode == '112') {
				location.href = '/admin/';
				return false;
			}
		}
	};

	// NAZIONALITA' ITALIANA O STRANIERA: GESTISCO I CAMPI
	function domesticForeignToggle(data, reg){
		
		if(data.show == 'foreign') { // caso nazionalita' straniera
			$('tr#region, tr#city').hide(); // nascondo i campi user_region_name ed user_city_id
			if ($('#city2').size() == 0){ // se city2 non esiste gia'
				// creo il campo di testo user[city_name]
				if(reg == 0) // se sto in modifica profilo utente
					$('#country').after('<tr id="city2"><td class="label">Citt&agrave;</td><td><input type="text" size="30" name="artist[city_name]" id="artist_city_name" class="data"></td></tr>');
				else // se sto in registrazione
					$('#country').after('<tr id="city2"><td class="label">Citt&agrave;</td><td><input type="text" size="30" name="user[city_name]" id="user_city_name" class="data"></td></tr>');
			};
		} else { // caso nazionalita' italiana
			$('tr#region, tr#city').show(); // mostro i campi user_region_name ed user_city_id
			$('#city2').remove(); // rimuovo l'eventuale campo city2
		};
	};


$(document).ready(function() {
    

	/* FUNZIONI USATE IN REGISTRAZIONE */
	$("#user_country_id").change(function() {
		$.ajax({
			url: '/frontend/ajax_country_select',
			data: 'country_id=' + $(this).val(),
			dataType: 'json',
			success: function(data) {
				if(data.res == 'ok') {
					domesticForeignToggle(data);
				} else {
					alert(data.msg);
				}
			}
		});	
	});

	$("#user_region_name").change(function() {
		$.ajax({
			url: '/frontend/ajax_region_select',
			data: 'region=' + $(this).val(),
			dataType: 'json',
			success: function(data) {
				if(data.res == 'ok') {
					// riempio la select user_city_id con i valori ritornati come "data.result"
					$('#user_city_id').empty(); // svuoto la select con le citta'
					$.each(data.result, function(i){ // per ogni citta' ritornata
						$('#user_city_id').append( // creo nella select...
							$('<option></option>') // la option con i suoi attributi
								.attr({
									value: data.result[i][1]
								})
								.html(data.result[i][0])
						)
					});
				} else {
					alert( data.msg );
				}
			}
		});
	});


	/* FUNZIONI USATE IN MODIFICA PROFILO  */
	$("#artist_country_id").change(function() {
		$.ajax({
			url: '/frontend/ajax_country_select',
			data: 'country_id=' + $(this).val(),
			dataType: 'json',
			success: function(data) {
				if(data.res == 'ok') {
					domesticForeignToggle(data, 0);
				} else {
					alert(data.msg);
				}
			}
		});	
	});

	$("#artist_region_name").change(function() {
		$.ajax({
			url: '/frontend/ajax_region_select',
			data: 'region=' + $(this).val(),
			dataType: 'json',
			success: function(data) {
				if(data.res == 'ok') {
					// riempio la select user_city_id con i valori ritornati come "data.result"
					$('#artist_city_id').empty(); // svuoto la select con le citta'
					$.each(data.result, function(i){ // per ogni citta' ritornata
						$('#artist_city_id').append( // creo nella select...
							$('<option></option>') // la option con i suoi attributi
								.attr({
									value: data.result[i][1]
								})
								.html(data.result[i][0])
						)
					});
				} else {
					alert( data.msg );
				}
			}
		});
	});

	// CYCLE (most rated in home)
	$("#cycle .mostRated:not(:first)").hide(); // TEMP
	/* DA RIATTIVARE
		$("#cycle").cycle({
			fx: "fade"
			, timeout: 5000
			, speed: 2000
		});
	*/
	
	
	// COLOR PICKER
		$("#colorPickerWrapper").append('<div id="colorSelector2"><div></div></div>');
		$('#colorSelector2').ColorPicker({
			onShow: function (colpkr) {
				$(colpkr).fadeIn(500);
				return false;
			},
			onHide: function (colpkr) {
				$(colpkr).fadeOut(500);
				return false;
			},
			onChange: function (hsb, hex, rgb) {
				$('#colorSelector2 div').css('backgroundColor', '#' + hex);
				/* passo l'esadecimale ad un campo hidden */
				$('input[name="artwork[border_hex]"]').val(hex);
			}
		});
	
	
	// FACEBOX
		$('a[rel*=facebox]').facebox();
	
	
	// VOTAZIONE OPERA
		$(".votazione a").click(function(){
			switch ($(this).text()) {
				case '1':
					$.ajax({ url: artwork_vote1_url, cache: false, success: function(str){$("div.votazione").html(str)} })
					break;
				case '2':
					$.ajax({ url: artwork_vote2_url, cache: false, success: function(str){$("div.votazione").html(str)} })
					break;
				case '3':
					$.ajax({ url: artwork_vote3_url, cache: false, success: function(str){$("div.votazione").html(str)} })
					break;
				case '4':
					$.ajax({ url: artwork_vote4_url, cache: false, success: function(str){$("div.votazione").html(str)} })
					break;
				case '5':
					$.ajax({ url: artwork_vote5_url, cache: false, success: function(str){$("div.votazione").html(str)} })
					break;
			}
		});
	

	// COMMENTI FORM SLIDE
		$("#commentAddButton")
			.click(function(){
				$("#comment_add_form").slideToggle();
			})
			.hover(function(){
				$(this).css({cursor: "pointer"})
			});
	
	
	// CLUETIP: TESTO DI ESEMPIO DI UN CAMPO al click sull'icona 'i' nelle form
		$("form td:has(i)") // per tutti i TD (che contengono un tag I) discendenti di una FORM
			.filter(function(i){ // escludo tutti i casi in cui il tag I sia vuoto
				return $(this).find("i").text() != ""
			})
			.find("i") // per tutti i I
				.hide() // nascondi 
			.end() // torno al TD
			.append('<a class="inputTip"><img src="/images/info.png" style="vertical-align: middle; margin-bottom: 2px"></a>') // aggiungo link con icona
			.each(function(){ // per ogni TD
				tipText = $(this).find("i").text(); // assegno il contenuto del tag I ad una var
				$(this).find("a.inputTip").attr("title", tipText); // ... e lo passo al title del link per essere visualizzato nel tip
			})
			.find("a.inputTip") // per tutti i link con classe inputTip
			.cluetip({ // chiamo il plugin che apre il tooltip che si prendera' il contenuto dall'attributo TITLE di cui sopra
				splitTitle: "|"
				, width: 300
				, cursor: "pointer"
				, fx: { open: "fadeIn", openSpeed: "normal"}
			});
	// CLUETIP: scegli la tecnica
	$('#scegliTecnica').cluetip({
		activation: "click"
		, splitTitle: "|"
		, fx: { open: "fadeIn", openSpeed: "normal"}
		, width: 400
		, positionBy: 'mouse'
	});


	/* ********************************************************************************
										DROPDOWN
	******************************************************************************** */
	// gestione delle aperture varie
	var hoverIntentConfig = {
		over:
			function(){
				$('.dropDownTrigger').removeClass('selected'); // spengo i pulsanti
				$('.dropDownWrapper')
					.stop(false,true) // interrompo eventuali altre animazioni non completate
					.hide() // nascondo tutti i wrapper
					.filter('[rel='+ $(this).attr("rel") +']') // trovo il corrispondente da aprire (che abbia lo stesso 'rel' del trigger) e...
						.slideDown('fast', function(){ // ... lo mostro
							$(this).find('.dropDownContent').fadeIn();
						});
				$(this).addClass('selected'); // ... accendo il relativo pulsante
			}
		, out: function(){}
		, interval: 30
	};
	$('.dropDownTrigger').hoverIntent(hoverIntentConfig);
	// chiudo tutto se clicco fuori e rimuovo il selected...
	$('body').click(function(){
		$('.dropDownWrapper').slideUp('fast', function(){
			$('.dropDownContent').hide();
			$('.dropDownTrigger[class~=selected]').removeClass('selected');
		});
	});
	// ... e NON se clicco nel contenuto di un dropdown
	$('[class*=dropDown]').click(function(event){ event.stopPropagation(); });
	
	// PULSANTE DI CHIUSURA (di tutti i dropdown)
	$('<div>')
		.css({
			position: 'absolute'
			, top: '15px'
			, right: '20px'
			, cursor: 'pointer'
			, width: '16px'
			, height: '16px'
			, background: 'url(/images/ui-icons_ffffff_256x240) 0 -16px'
		})
		.click(function (){ 
			$(this).parent().slideUp('fast', function(){
				$('.dropDownContent').hide();
				$('.dropDownTrigger[class~=selected]').removeClass('selected');
			});
		})
		.appendTo($('.dropDownWrapper'));


	/* ********************************************************************************
				RISTRUTTURO IN COLONNE I RISULTATI DI ARTISTI ED OPERE
	******************************************************************************** */
	var allLinks = []; var perCol = []; var inCol1 = []; var inCol2 = [];

	$('.columnize')
		.each(function(i){
			allLinks[i] = $(this).find('a'); // tutti i link
			perCol[i] = parseInt(allLinks[i].size()/2)+1; // link per colonna
			inCol1[i] = allLinks[i].slice(0, perCol[i]); // colleziono i link della 1a colonna...
			inCol2[i] = allLinks[i].slice(perCol[i], allLinks[i].size()); // e della 2a
			inCol1[i].appendTo($(this)).wrapAll('<ul></ul>').wrap('<li></li>'); // wrappo i link un elenco puntato ed appendo la colonna al contenitore (x2)
			inCol2[i].appendTo($(this)).wrapAll('<ul></ul>').wrap('<li></li>'); 
		})
		.append('<br clear="all">')
		.show()
		.find('ul:last')
			.css({ marginRight: 0 }); // levo il margino destro alla col dx
	;


	/* ********************************************************************************
							'COCCARDA' PER I PRIMI CLASSIFICATI
	******************************************************************************** */
	$('a.ribbon1').each(function(){ $(this).append('<img src="/images/ribbon-1.png">') });
	$('a.ribbon2').each(function(){ $(this).append('<img src="/images/ribbon-2.png">') });
	$('a.ribbon3').each(function(){ $(this).append('<img src="/images/ribbon-3.png">') });
	$('a.ribbon4').each(function(){ $(this).append('<img src="/images/ribbon-4.png">') });


});
