/**
 * Switcha il generatore di captcha sulla versione testo
 */
function recaptchaText() {
	if(typeof(Recaptcha) != 'undefined') {
		Recaptcha.switch_type('image');
	}
}

/**
 * Switcha il generatore di captcha sulla versione audio
 */
function recaptchaAudio() {
	if(typeof(Recaptcha) != 'undefined') {
		Recaptcha.switch_type('audio');
	}
}
/**
 * Nasconde l'helptip quando il puntatore del mouse non si trova pi� sul punto interrogativo.
 */
function hidehelptip() {
	$('#helptip').hide('fast');
}
/**
 * Sostituisce l'html contenuto nell'elemento con classe hreplace con l'immagine fornita nei metadata messi come classe.
 */
function hReplace() {
	$('.hreplace').each(function(){
		var data = $.metadata.get(this);
		$(this).css({'background-image':'url(\''+data.imgurl+'\')', 'width':data.width+'px', 'height':data.height+'px'});
		$(this).html('');
	});
}
/**
 * Funzione richiamata all'hover dei punti interrogativi.
 * Il messaggio da mostrare viene reperito tramite l'attributo rel impostato
 * nel link tramite smarty.
 */
function showhelptip(obj) {
	log('showhelptip');
	var html = $(obj).attr('rel');
	if(typeof(html) != 'undefined') {
		if($('#helptip').size() == 0) {
			$div = $('<div></div>').appendTo($('body'));
			$div.addClass('helptip_box');
			$div.addClass('notice');
			$div.attr({'id':'helptip'});
		} else {
			$div = $('#helptip');
		}

		$div.css({'top':$(obj).offset().top+'px',
							'left':($(obj).offset().left+20)+'px'
						 });
		$div.show('fast');
		$div.html(html);
	}
}
/**
 * Passato l'evento del keyup la funzione verifica se il valore fornito è tra quelli
 * accettati
 *
 * @param event e
 * @param string allowed_chars contiene una regex sulla quale viene confrontato il carattere
 */
function restricted(e, allowed_chars) {
	log('restricted(e, allowed_chars)');
	log('e:'+e);
	key = (e.charCode) ? e.charCode : e.which;

	log("key_code:"+key);

	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) return true;

	keychar = String.fromCharCode(key);
	log("keychar:"+keychar);

	re = new RegExp(allowed_chars+'{1}');

	if(re.test(keychar)) {
		if(debug) log('OK');
		return true;
	}

	if(debug) log('KO');
	return false;
}
/**
 * Funzione che fa da wrapper al componente ui.dialog.js (sostituisce il confirm)
 */
function modal_confirm(title, question, okfunct, cancelfunct) {
	if(typeof(cancelfunct) == 'undefined') {
		cancelfunct = function() {
			$(this).dialog('close').remove();
		}
	}

	$('<div>'+question+'</div>').dialog({
		title: title,
		modal : true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			Ok : okfunct,
			Cancel : cancelfunct
		}
	});
}

/**
 * Funzione che fa da wrapper al componente ui.dialog.js (sostituisce l'alert)
 */
function modal_dialog(title, contenuto) {
	$('<div>'+contenuto+'<br /><br /></div>').dialog({
		title: title,
		modal : true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Ok': function() {
				$(this).dialog('close').remove();
			}
		}
	});
}

/**
 * Recupera la chiave di traduzione corrispondente a modulo.chiave forniti.
 */
function getLang(module, key) {
	if(typeof(Lang[module]) == 'undefined') {
		str = 'Lang Module '+module+' not found ('+module+"."+key+')';
		if(typeof(console) != 'undefined') {
			error(str);
		}
		return module+"."+key;
	} else {
		if(typeof(Lang[module][key]) == 'undefined') {
			str = 'Key '+key+' not found in module '+module;
			if(typeof(console) != 'undefined') {
				error(str);
			}
			return module+"."+key;
		} else {
			return Lang[module][key];
		}
	}
}
/**
 * Wrapper per firebug, viene mostrato un errore in rosso in console
 */
function error(str) {
 if(typeof(console) != 'undefined') {
	 console.error(str);
 }
}
/**
 * Wrapper per firebug, viene usato per i log, viene attivato solo se la variabile
 * globale "debug" è settata a true
 */
function log(str) {
 if(debug) {
	 if(typeof(console) != 'undefined') {
		 console.info(str);
	 }
 }
}
/**
 * Sistema dopo il caricamento l'attributo tabindex per i campi input, saltando i link di help.
 */
function tabindexinit() {
	$elementi = $(':input');
	var i = 0
	$elementi.each(function() {
		$(this).attr({'tabindex':i});
		i = i+1;
	});
	i = $elementi.size()
	$elementi = $('a');
	$elementi.each(function() {
		$(this).attr({'tabindex':i});
		i++;
	});
}

function preloadImages() {
	k = 0;
	$('.rollover').each(function() {
		i = new Image();
		i.src = $(this).attr('rel');
		img_array[k] = i;
		k++;
	});
}
function rolloverimg(obj) {
	$link_over = $(obj);
	new_img_url = $link_over.attr('rel');
	$img_obj = $('img', $link_over);
	swap_img = $img_obj.attr('src');
	$img_obj.attr({'src':new_img_url});
}

function rolloutimg(obj) {
	// questo if evita il baco che si verifica nel caso in cui
	// al caricamento della pagina ci si trovi già su un area sensibile
	if(swap_img != "") {
		$link_over = $(obj);
		$img_obj = $('img', $link_over);
		$img_obj.attr({'src':swap_img});
		swap_img = "";
	}
}


function openModalBenessere(obj) {

	if($('#map_node').length == 0) {
		$('<div id="map_node" class="loading"></div>').appendTo($('body'));
	}

	buttons  = {};
	buttons[getLang('base', 'CANCEL')] = function() { $('#map_node').dialog('destroy'); };

	$('#map_node').dialog({
		title: '',
		modal : true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		close: function(event, ui) { $('#map_node').dialog('destroy'); },
		position: new Array('center', 20, 'center', 0) ,
		minHeight: 250,
		maxHeight: 350,
		width: 600
	});
	
	$.get($(obj).attr('href'), function(ret) {
		$('#map_node').removeClass('loading').html($('#descrizione_mappa', ret).html());
		
		$('#ui-dialog-title-map_node').html($('h2', ret).html())
		if($('.photo_cont img').length > 0) {
			$('.photo_cont').after('<div id="nav">').cycle({
				fx:     'scrollUp', 
				speed:  'slow', 
				timeout: 0, 
				pager:  '#nav' 
				});
		}
		
	});
	
}

function sprintf( ) {
		// Return a formatted string
		//
		// version: 905.3122
		// discuss at: http://phpjs.org/functions/sprintf
		// +   original by: Ash Searle (http://hexmen.com/blog/)
		// + namespaced by: Michael White (http://getsprink.com)
		// +    tweaked by: Jack
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +      input by: Paulo Ricardo F. Santos
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +      input by: Brett Zamir (http://brett-zamir.me)
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// *     example 1: sprintf("%01.2f", 123.1);
		// *     returns 1: 123.10
		// *     example 2: sprintf("[%10s]", 'monkey');
		// *     returns 2: '[    monkey]'
		// *     example 3: sprintf("[%'#10s]", 'monkey');
		// *     returns 3: '[####monkey]'
		var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
		var a = arguments, i = 0, format = a[i++];

		// pad()
		var pad = function(str, len, chr, leftJustify) {
				if (!chr) {chr = ' ';}
				var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
				return leftJustify ? str + padding : padding + str;
		};

		// justify()
		var justify = function(value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
				var diff = minWidth - value.length;
				if (diff > 0) {
						if (leftJustify || !zeroPad) {
								value = pad(value, minWidth, customPadChar, leftJustify);
						} else {
								value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
						}
				}
				return value;
		};

		// formatBaseX()
		var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
				// Note: casts negative numbers to positive ones
				var number = value >>> 0;
				prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
				value = prefix + pad(number.toString(base), precision || 0, '0', false);
				return justify(value, prefix, leftJustify, minWidth, zeroPad);
		};

		// formatString()
		var formatString = function(value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
				if (precision != null) {
						value = value.slice(0, precision);
				}
				return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
		};

		// doFormat()
		var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) {
				var number;
				var prefix;
				var method;
				var textTransform;
				var value;

				if (substring == '%%') {return '%';}

				// parse flags
				var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
				var flagsl = flags.length;
				for (var j = 0; flags && j < flagsl; j++) {
						switch (flags.charAt(j)) {
								case ' ': positivePrefix = ' '; break;
								case '+': positivePrefix = '+'; break;
								case '-': leftJustify = true; break;
								case "'": customPadChar = flags.charAt(j+1); break;
								case '0': zeroPad = true; break;
								case '#': prefixBaseX = true; break;
						}
				}

				// parameters may be null, undefined, empty-string or real valued
				// we want to ignore null, undefined and empty-string values
				if (!minWidth) {
						minWidth = 0;
				} else if (minWidth == '*') {
						minWidth = +a[i++];
				} else if (minWidth.charAt(0) == '*') {
						minWidth = +a[minWidth.slice(1, -1)];
				} else {
						minWidth = +minWidth;
				}

				// Note: undocumented perl feature:
				if (minWidth < 0) {
						minWidth = -minWidth;
						leftJustify = true;
				}

				if (!isFinite(minWidth)) {
						throw new Error('sprintf: (minimum-)width must be finite');
				}

				if (!precision) {
						precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
				} else if (precision == '*') {
						precision = +a[i++];
				} else if (precision.charAt(0) == '*') {
						precision = +a[precision.slice(1, -1)];
				} else {
						precision = +precision;
				}

				// grab value using valueIndex if required?
				value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

				switch (type) {
						case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
						case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
						case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
						case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
						case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
						case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
						case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
						case 'i':
						case 'd':
								number = parseInt(+value, 10);
								prefix = number < 0 ? '-' : positivePrefix;
								value = prefix + pad(String(Math.abs(number)), precision, '0', false);
								return justify(value, prefix, leftJustify, minWidth, zeroPad);
						case 'e':
						case 'E':
						case 'f':
						case 'F':
						case 'g':
						case 'G':
								number = +value;
								prefix = number < 0 ? '-' : positivePrefix;
								method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
								textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
								value = prefix + Math.abs(number)[method](precision);
								return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
						default: return substring;
				}
		};

		return format.replace(regex, doFormat);
}


function afterCSS3(className, string) {
	if($.browser.msie && parseInt($.browser.version) < 8) {
		$('.'+className).each(function() {
			$(this).html($(this).html()+string);
		});
	}
}
