/* ********************************************************************************
						'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;
		}
	};
};



/* ********************************************************************************
					PRENDO VALORI DALLA QUERY STRING
******************************************************************************** */
function getParameterByName(name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
};



/* ********************************************************************************
						JGROWL - NOTICE, WARNING, ERROR
******************************************************************************** */
function showNotice(text, title){ $.jGrowl(text, { header: title, theme: 'notice' }) };
function showWarning(text, title){ $.jGrowl(text, { header: title, sticky: true, theme: 'warning' }) };
function showError(text, title){ $.jGrowl(text, { header: title, sticky: true, theme: 'error' }) };



/* ********************************************************************************
									IS INTEGER
******************************************************************************** */
function isInteger(s){
	if ( s == null) return false;
	var i;
	for(i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if(((c < "0") || (c > "9"))) return false;
	}
	return true;
};



$(document).ready(function(){

	if($(".flashNotice").length == 1) { showNotice( $(".flashNotice").html(), "Informazione" ); };
	if($(".flashWarning").length == 1) { showWarning( $(".flashWarning").html(), "Attenzione" ); };
	if($(".flashError").length == 1) { showError( $(".flashError").html(), "Problema" ); };

	/* MOSTRA NASCONDI DIV */	
	$(".mostra_nascondi")
		.click(function(){
			$('.searchMethod').hide();
			var div_da_nascondere = $(this).attr('rel');
			$('#' + div_da_nascondere).fadeIn();
			return false;
	});
	
	/* ********************************************************************************
							VALIDAZIONE CHECKBOX PRIVACY
	******************************************************************************** */
	$('form').submit(function(){
		if ( $(':checkbox.privacy').is(':not(:checked)') ){
			showError('E\' necessario accettare l\'informativa sulla privacy.', 'Attenzione');
			return false;
		}
	});


	/* ********************************************************************************
								DEV-TOP-BAR DI SVILUPPO
	******************************************************************************** */
	$('#devTopBar')
		.show()
		.find('a')
			.each(function(){
				if ( location.pathname.indexOf( $(this).attr('href') ) != -1 ){
					$(this).addClass('selected');
				};
			})
			.end()
		.find('#chiudi')
			.click(function(){
				$('#devTopBar').slideUp(1000);
				$('body').animate({marginTop: '20px'}, 1000);
			});


	$("#devBarFastEdit").live('click', function() {
		location.href = location.href + "?fastEdit=1";
	});

	$("#devBarFastEditH1").live('submit', function() {
		$.ajax({url: '/admin/cms/ajax_devbar_edit',
			data: $(this).serialize(),
			dataType: 'json',
			success: function(result) {
				if(result.res == 'ok') {
					$("#devBarFastEditH1").replaceWith( "<h1>" + $("#cms_page_page_title").val() + "</h1>" );
					showNotice('Valore modificato');
				} else {
					showWarning('Non &egrave; stato possibile salvare le informazioni');
				}
			}
		});
		return false;
	});

	$("#devBarFastEditContent").live('submit', function() {
		$.ajax({url: '/admin/cms/ajax_devbar_edit',
			data: $(this).serialize(),
			dataType: 'json',
			success: function(result) {
				if(result.res == 'ok') {
					$("#devBarFastEditContent").replaceWith($("#cms_page_page_contents").val());
					showNotice('Valore modificato');
				} else {
					showWarning('Non &egrave; stato possibile salvare le informazioni');
				}
			}
		});
		return false;
	});

	
	// 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(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.png) 0 -16px'
			})
			.click(function (){ 
				$(this).parent().slideUp(function(){
					$('.dropDownContent').hide();
					$('.dropDownTrigger[class~=selected]').removeClass('selected');
				});
			})
			.appendTo($('.dropDownWrapper'));
	
	
	
	
	/* ********************************************************************************
									MB MENU - BARRANAV
	******************************************************************************** */
	$('#barraNav').buildMenu({
		menuSelector:".overlay"
		, template:""
		, menuWidth:220
		, openOnRight:false
		, containment:'window'
		, iconPath:"ico/"
		, hasImages:false
		, fadeInTime:0
		, fadeOutTime:200
		, menuTop:0
		, menuLeft:0
		, submenuTop:0
		, submenuLeft:4
		, opacity:1
		, shadow: false
		, shadowColor: "black"
		, shadowOpacity: 1
		, openOnClick:false
		, closeOnMouseOut: true
		, closeAfter:300
		, minZindex: "auto"
		, hoverIntent:0 //if you use jquery.hoverIntent.js set this to time in milliseconds; 0= false;
        , submenuHoverIntent: 0 //if you use jquery.hoverIntent.js set this to time in milliseconds; 0= false;
	});
	
	
	/* ********************************************************************************
										COLORBOX
	******************************************************************************** */
	//COLOR BOX
	$(".outsidehtml").colorbox({width:"900px", height:"490px", iframe:true, open: true, overlayClose: true, });
	
	
	// DEFAULT: carico il contenuto via ajax (n.b.: la pagina chiamata non deve essere una pagina completa di tag html, head, ecc.)
	$('a[class~=colorbox]').colorbox();

	// PHOTOGALLERY
	$('#photoGallery a[class~=colorbox]').colorbox({ maxWidth: "90%", maxHeight: "90%" });
	
	//COLOR BOX
	$("a[rel='foto']").colorbox({
		transition:"elastic"
		, slideshow: true
		, slideshowSpeed: 3000
		, opacity: 0.95		
	});
	

	// APPLICATO AI PULSANTI
	$(':button[class~=colorbox]').click(function(){ $.colorbox({ href: $(this).attr('href') }) });

	// IFRAME (in colorbox): apro una pag esterna completa di tag html, head, ecc.
	$('[class~="cBoxIframe"]').colorbox({iframe: true, width: '80%', height: '90%' });

	// INLINE: apre un elemento (il cui ID è definito nell'href con #) contenuto nella pagina del chiamante
	$('.showDiv').colorbox({ inline: true, href: function(){ return $(this).attr('href') } });

	//COLOR BOX
    $("#privacy")
		.colorbox({ 
			width:"80%"
			, height:"80%"
			, iframe:true
			, opacity: 0.80
		});

	/* ********************************************************************************
										TOOLTIP
	******************************************************************************** */
	// piccolo nero
	$('.tip[title]').tooltip({ effect: 'slide', predelay: 100, delay: 0 }).dynamic();
	// grande nero
	$('.tip2[title]').tooltip({ tipClass: 'tooltip2', effect: 'slide', predelay: 100, delay: 0 }).dynamic();
	// piccolo bianco
	$('.tip3[title]').tooltip({ tipClass: 'tooltip3', effect: 'slide', predelay: 100, delay: 0 }).dynamic();
	// grande bianco
	$('.tip4[title]').tooltip({ tipClass: 'tooltip4', effect: 'slide', predelay: 100, delay: 0 }).dynamic();
	// classe "TODO" per comunicazione di note interne
	$('.todo[title]')
		.tooltip({ effect: 'fade', tipClass: 'tooltipTodo', predelay: 0, delay: 0 })
		.dynamic();
	

	/* ********************************************************************************
									FOOTER DI SVILUPPO
	******************************************************************************** */
	if (location.href.indexOf('oth.org') != -1){ // SE SONO IN LOCALE
		$('body').css({ marginBottom: '55px' });
		$('#devFooter')
			.show()
			.find('a')
				.each(function(){
					if ( location.pathname.indexOf( $(this).attr('href') ) != -1 ){
						$(this).addClass('selected');
					};
				})
				.end()
			.find('#chiudi')
				.click(function() {
					$('#devFooter').slideUp({duration: 1000, easing: 'easeOutBounce'});
					$('body').css('marginBottom','20px');
				});
	};

	$("#colDxContactForm").live('submit', function() {
		$("#colDxContactForm .formError").remove();
		$.ajax({url: "/frontend/ajax_contatti",
			dataType: 'json',
			data: $(this).serialize(),
			success: function(result) {
				if(result.res == 'ok') {
					location.href = result.href;
				} else {
					showWarning(result.msg, '');	
					$.each(result.form_error, function(index, value) {
						var txt = "#contact_" + value[0];
						$(txt).before("<div class='formError'>" + value[1] + "</div>");
					});
				}
			}
		});
		return false;
	});

	/* ********************************************************************************
										ACCORDION
	******************************************************************************** */
	$('.pane').hide();
	$("#accordion").tabs("#accordion div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null});
	
	
	/* ********************************************************************************
										SLIDESHOW
	******************************************************************************** */
	$('#slideHomePager').tabs('#slideHomeImages > a', {
		current: 'selected'
		, effect: 'fade'
		, rotate: true
	}).slideshow({
		autoplay: true
        , clickable: false
	});

	
	// STILE: "FEATURES":
		// evidenzio la riga al passaggio del mouse
		$(".orari tbody tr").hover(
			function(){ $(this).find('td').css({background: '#ffc'}) }
			, function(){ $(this).find('td').css({background: '#fff'}) }
		);
		

});


