var __ajax_pending_requests__ = new Object();
var __ajax_counter__ = 0;

function isSet(v) {
	try { eval(v + ';'); return true;}
	catch(ex) { return false; }
}

function exist(id_obj)
{
	if(document.getElementById(id_obj)) return true;
	else return false;
}

function is_checked(obj_id)
{
        if(document.getElementById(obj_id)) // intanto controllo che esista quell'ID
        {
                var obj = document.getElementById(obj_id);
                // poi controllo che sia di tipo checkbox o di tipo radiobutton
                if(obj.getAttribute('type') == 'checkbox' || obj.getAttribute('type') == 'radio')
                        if(obj.checked) // e infine se è selezionato
                                return true;
        }
        
        return false;
}

function hg(id) { return document.getElementById(id); }

function field_control(callback,reload_url)
{	reset_asterisk();
	var arraycampi=form_obj.getElementsByTagName('input');
	var elem_name;
	var elem_value;
	var elem_type;
	var elem_id;
	
	div_form.style.display = 'none';
	div_loading.style.display = 'block';
	document.body.style.display='none';
	document.body.style.display='block';
	for (i = 0; i < arraycampi.length; i++) {
		elem_type=arraycampi[i].getAttribute('type');
		if((elem_type!="button")&&(elem_type!="hidden")&&(elem_type!="reset"))
		{
			elem_id=arraycampi[i].getAttribute('id');
			if (elem_id == null) continue;
			elem_name=arraycampi[i].getAttribute('name');
			elem_value=arraycampi[i].value;
			
			if(elem_value=='' && document.getElementById('ast_'+elem_name)){
					div_loading.style.display = 'none';
					div_form.style.display = 'block';
					document.getElementById('ast_'+elem_name).innerHTML = '*';
					print_error(js_dic_NOALLFIELDS);
					return false;
			}

			// Controllo email
			if(elem_id.indexOf('mail')>=0 && document.getElementById('ast_'+elem_name))
			{if (!emailControl(elem_value)) {
			  div_loading.style.display = 'none';
			  document.getElementById('ast_'+elem_name).innerHTML = '*';
			  div_form.style.display = 'block';
			  print_error(js_dic_NOEMAIL);
		          return false;
		         }
		        
			}
			
			// Controllo della login
			if(elem_id.indexOf('login')>=0 && document.getElementById('ast_'+elem_name))
			{	
				if(elem_value.length<5 || elem_value.length>12)
					{	
						document.getElementById('ast_'+elem_name).innerHTML = '*';
						print_error(js_dic_PWDUSERWRONG);
						div_loading.style.display = 'none';
						div_form.style.display = 'block';
						return false;
					}
			}			
			// Controllo delle password
			if(elem_id.indexOf('password')>=0 && document.getElementById('ast_'+elem_name))
			{	
				if(!pwd_control(elem_name,elem_name.replace('password','repwd')))
				{	div_loading.style.display = 'none';
					div_form.style.display = 'block';
					return false;
				}
			}
		}
	}
	callback(reload_url);
}

// Controllo delle password
function pwd_control(password,repwd)	{
	var pwd1=document.getElementById(password).value;
	var pwd2=document.getElementById(repwd).value
	if(pwd1!=pwd2) print_error(js_dic_PWDNOMATCH);
	
	if(pwd1.length<5 || pwd2.length<5 || pwd1.length>12 || pwd2.length>12)
		{	
			document.getElementById('ast_'+repwd).innerHTML = '*';
			document.getElementById('ast_'+password).innerHTML = '*';
			print_error(js_dic_PWDUSERWRONG);
			return false;
		}
	else if(pwd1!=pwd2)
		{	
			document.getElementById('ast_'+repwd).innerHTML = '*';
			document.getElementById('ast_'+password).innerHTML = '*';
			print_error(js_dic_PWDNOMATCH);
			return false;
		}
	else
		return true;

}

function reset_asterisk()
{	document.getElementById('error').style.visibility = 'hidden';
	document.getElementById('error_bis').style.visibility = 'hidden';
	var arraycampi=form_obj.getElementsByTagName('input');
	var elem_name;
	var elem_type;
	
	for (i = 0; i < arraycampi.length; i++) {
		elem_type=arraycampi[i].getAttribute('type');
		if((elem_type!="button")&&(elem_type!="hidden")&&(elem_type!="reset"))
		{	
			elem_name=arraycampi[i].getAttribute('name');
			if(document.getElementById('ast_'+elem_name)) document.getElementById('ast_'+elem_name).innerHTML = '';
		}
	}	
}

function struct_length(struct)	{
	        var lunghezza = 0;
         	for(i in struct)
         	 lunghezza++;
         	return lunghezza;
}

var _pieces = new Array();
function toDocument(struct,encode)	{
	var xml_request = '<?xml version="1.0" encoding="'+encode+'" ?>';
	_toDocument(struct);
	for(i in _pieces) {
		var elt = _pieces[i];
		xml_request += elt;
	}	
	return xml_request;
}

function _toDocument(struct) {
    //la variabile e' null
    if (struct == null) {
        _pieces[_pieces.length] = '<element type="NIL">NIL</element>';
    }
    //la variabile e' una stringa
    else if (typeof(struct) == 'string' || struct instanceof String) {
        var value=struct.replace(/&/gi, '&amp;').replace(/</gi, '&lt;').replace(/>/gi, '&gt;');
        _pieces[_pieces.length] = '<element type="string">'+value+'</element>';
    }
    //la varibile e' un numero
    else if (typeof(struct) == 'number' || struct instanceof Number) {
        //controllo se e' intero o no
        if (/\./.test(struct.toString()))
            _pieces[_pieces.length] = '<element type="float">'+struct+'</element>';
        else
            _pieces[_pieces.length] = '<element type="integer">'+struct+'</element>';
    }
    //la variabile e' un booleano
    else if(typeof(struct) == 'boolean' || struct instanceof Boolean) {
        var value = (struct === true) ? 'True' : 'False';
        _pieces[_pieces.length] = '<element type="boolean">'+value+'</element>';
    }
    //la variabile e' un oggetto
    else if(typeof(struct) == 'object') {
        //controllo se e' una lista o altro
        //se la lunghezza non esiste o e' zero
        //o e' una lista vuota o non e' una lista
        //in entrambi i casi va bene trattare come dizionario
        //visto che php non distingue
        if (struct.length != undefined && struct.length > 0) {
            _pieces[_pieces.length] = '<sequence length="'+struct.length+'">';
            for (var i in struct) {
                var elt = struct[i];
                _pieces[_pieces.length] = '<item>';
                _toDocument(elt);
                _pieces[_pieces.length] = '</item>';
            }
            _pieces[_pieces.length] = '</sequence>';
        }
        else {
            _pieces[_pieces.length] = '<map length="'+struct_length(struct)+'">';
            for(var key in struct) {
                var value = struct[key];
                _pieces[_pieces.length] = '<key name="'+key+'">';
                _toDocument(value);
                _pieces[_pieces.length] = '</key>';
            }
            _pieces[_pieces.length] = '</map>';
        }
    }
}

function fromDocument(elem)	{
	var tag_name = elem.nodeName;
        if(tag_name=='element') {
	        	// Text handling
		        if(elem.firstChild) var value = elem.firstChild.data;
		        else var value = '';
		        //var type = elem.getAttribute('type');
		        return value;
	        }
        else if(tag_name=='sequence') {
		        // Sequence handling
		        var _array_pieces = new Array();
		        var items = elem.childNodes;
		        for(var i=0; i<items.length; i++) {
		            _array_pieces[_array_pieces.length]=fromDocument(items[i].firstChild);
		        }
		        return _array_pieces;
	        }
	 else if(tag_name=='map') {
		        // Map handling
		        var _array_pieces = new Array();
		        var keys = elem.childNodes;
		        for(var i=0; i<keys.length; i++) {
		            var k = keys[i].getAttribute('name');
		            _array_pieces[k]=fromDocument(keys[i].firstChild);
		        }
		        return _array_pieces;
	        }	
}

function xml_request(struct,url_xml_rpc,encoding,callback,params) {
	request = toDocument(struct,encoding);
	_pieces = new Array();
	var messenger = XmlHttp.create();
	messenger.open("POST", url_xml_rpc, true);
	messenger.onreadystatechange = function() {
        if(messenger.readyState == 4) {
            if (!__ajax_pending_requests__[__ajax_index__]) return;
            delete __ajax_pending_requests__[__ajax_index__];
            try {
                try {
                    messenger.responseXML.documentElement.getElementsByTagName('map')[0].firstChild;
                    var res = fromDocument(messenger.responseXML.documentElement);
                }
                catch(ex) { 
                    var res = JSON.parse(messenger.responseText, function (k, v) { return v; });
                }
			}
            catch(ex) {
		    	//alert(messenger.responseText);
			    if (__ajax_errors__)
                    print_error(js_dic_ERRORSESSION);
			    return false;
			}
            if (params == undefined)
                callback(res['response']['result'],struct['header']['type']);
            else
                callback(res['response']['result'],struct['header']['type'],params);
			}
	}
    var __ajax_index__ = __ajax_counter__;
	__ajax_pending_requests__[__ajax_index__] = messenger ;
	__ajax_counter__++;
	messenger.setRequestHeader("Content-Type", "text/html");
	messenger.send(request);
}

function html_request(struct,url_xml_rpc,encoding,callback,where) {
	request = toDocument(struct,encoding);
	_pieces = new Array();
	var template = XmlDocument.create();
	template.loadXML(request);
	//alert(request);
	var messenger = XmlHttp.create();
	messenger.open("POST", url_xml_rpc, true);
	messenger.onreadystatechange = function() {
                if(messenger.readyState == 4) {
                    if (!__ajax_pending_requests__[__ajax_index__]) return;
                    delete __ajax_pending_requests__[__ajax_index__];
					//alert(messenger.responseText);
					callback(messenger.responseText,where);
				}
	}
	var __ajax_index__ = __ajax_counter__;
	__ajax_pending_requests__[__ajax_index__] = messenger ;
	__ajax_counter__++;
	messenger.setRequestHeader("Content-Type", "text/html");
	messenger.send(template.xml);
}

var __ajax_errors__ = true;
function abortAjaxRequests() {
	__ajax_errors__ = false;
    for (index in __ajax_pending_requests__) {
        __ajax_pending_requests__[index].abort();
    }
}

function print_error(text)	{
	document.getElementById('error_text').innerHTML = text;
	document.getElementById('error').style.visibility = 'visible';
	document.getElementById('error_text_bis').innerHTML = text;
	document.getElementById('error_bis').style.visibility = 'visible';
}

function print_warning(text)	{
	var warning=document.getElementById('warning');
	if(warning)
	{
		warning.innerHTML = text;
		warning.style.visibility = 'visible';
	}
}

function hide_error()	{
	document.getElementById('error').style.visibility = 'hidden';
	document.getElementById('error_bis').style.visibility = 'hidden';
}

function hide_warning()	{
	var warning=document.getElementById('warning');
	if(warning)
		warning.style.visibility = 'hidden';
}

function capitalize(str)
{
 if(!str) return '';
 str=str.toLowerCase();
 var ap = str.split(' ');
 var new_str='';
 for(var i = 0; i<ap.length; i++)
  new_str+=ap[i].substr(0,1).toUpperCase()+ap[i].substr(1,ap[i].length-1)+' ';
 return new_str.substr(0,new_str.length-1);
}

// Aggiungi ai preferiti
function addPage() {
	if ((navigator.appName=="Microsoft Internet Explorer")&&(parseInt(navigator.appVersion)>=4)) 
	{
	 window.external.addFavorite('http://www.hotelsprovider.com', 'Hotelsprovider.com');

	}
        else 
        {
	 var msg = eval('top.vuoto.no_addbookmarks_'+top.vuoto.client_language);
	 alert(msg);
        }
         var template = XmlDocument.create();
         var request = '<?xml version="1.0" encoding="UTF-8" ?><query type="add_bookmark">nessun parametro</query>';
         template.loadXML(request);
         var messenger = XmlHttp.create();
         messenger.open("POST", "http://www.hotelsprovider.com/include/xml_request/addBookmark.php", true);
         messenger.setRequestHeader("Content-Type", "text/xml");
         messenger.send(template.xml);
}


//Funzione per la formattazione di un prezzo (in base al locale)
function format_price(price, lingua) {
    var sub = Math.floor(price * 100)/100;
    var comma = ',';//lingua=='it' ? ',' : '.';
    var parts = ('' + sub).split('.');
    var res = '';
    if(parts.length==1) res = parts[0]+comma+'00';
    else if(parts[1].length==1) res = parts[0]+comma+parts[1]+'0';
         else res = parts[0]+comma+parts[1];
    return(res);
}

//Funzione per la formattazione di una data (in base al locale)
function format_data(data, lingua) {
    if(lingua=='it') var res = data.charAt(8)+data.charAt(9)+'/'+data.charAt(5)+data.charAt(6)+'/'+data.charAt(0)+data.charAt(1)+data.charAt(2)+data.charAt(3);
    else var res = data.charAt(0)+data.charAt(1)+data.charAt(2)+data.charAt(3)+'-'+data.charAt(5)+data.charAt(6)+'-'+data.charAt(8)+data.charAt(9);
    return(res);
}

//Funzione per la formattazione di una data e ora (in base al locale)
function format_timestamp(data, lingua) {
    var res = format_data(data, lingua);
    res +=' '+data.charAt(11)+data.charAt(12)+data.charAt(13)+data.charAt(14)+data.charAt(15);
    return(res);
}

//Dato l'ID di un elemento, restituisce la sua posizione [x,y].
function findPos(id) {
  var pos = new Array(0, 0, 0);
  var el = document.getElementById(id);
  var fieldset = 0; // Altezza del fieldset, utilizzata per workaround
  if(!el) el=id;
  var obj = el;
  while(obj.tagName != 'BODY') {
      if(obj.tagName=='FIELDSET') {
          fieldset = obj.offsetTop;
      }
      pos[1] += obj.offsetTop;
      pos[0] += obj.offsetLeft;
      obj = obj.offsetParent;
  }
  pos[2] = fieldset;
  return pos;
}


<!-- Calcola il numero di notti (aaaa-mm-gg) -->
function compute_nights(from,to)
{ 
  var ap = from.split('-');
  var new_from = ap[1]+'/'+ap[2]+'/'+ap[0];
  var ap = to.split('-');
  var new_to = ap[1]+'/'+ap[2]+'/'+ap[0];
  dataa = new Date(new_from);
  datap = new Date(new_to);

  secs = Math.abs(datap.getTime() - dataa.getTime());
  secs = Math.round(secs / (24 * 60 * 60 * 1000));

  return secs;
}

function emailControl(email){
	
if(email=='') return true;

 var at_pos=email.indexOf('@',0);

 if (at_pos == -1) return false;
 else
 {
 	var dot_pos=email.indexOf('.',at_pos);
	if(dot_pos == -1) return false;
	else
	{
		var array_ext=new Array();
		var array_ext=email.substr(dot_pos+1,email.length).split('.');
		var ext=array_ext[array_ext.length-1];

		for (var o = 0; o < js_global_email_ext.length; o++)
		{
	          if (ext == js_global_email_ext[o])
		  return true;
		}
		return false;
	}
 }
}

// Trasforma la Y in true e N in false
function toBoolean(str)
{
	if(str=='Y') return true;
	else return false;

}

function currency_symbol(iso)
{
	if(js_dic_CURRENCYSYMBOLS[iso]) return js_dic_CURRENCYSYMBOLS[iso];
	else return iso;
}

function show_obj(obj_id)
{
	document.getElementById(obj_id).style.display = 'block';
}

function hide_obj(obj_id)
{
	document.getElementById(obj_id).style.display = 'none';
}

function abilita(field_id)
{
	document.getElementById(field_id).disabled = false;
}

function disabilita(field_id)
{
	document.getElementById(field_id).disabled = true;
}

// passate due date nel formato gg/mm/aa, ritorna true se la prima è maggiore/uguale della seconda
function after(date1, date2)
{
	var major = new Array();
	var minor = new Array();
	major = date1.split('/');
	minor = date2.split('/');
	
	if(major[2] > minor[2]) return true;	// se l'anno della prima è maggiore allora torna vero
	else if(major[2] < minor[2]) return false; // se l'anno della prima è minore allora torna falso
	else if(major[1] > minor[1]) return true; // a parita' di anno, se il mese della prima è maggiore ritorna vero
	     else if(major[1] < minor[1]) return false;	// se invece è minore torna falso
	     else if(major[0] >= minor[0]) return true; // a parita' di anno e mese, se il primo giorno è maggiore o uguale torno vero
	          else return false;	// altrimenti torno falso
}

// passate due date nel formato gg/mm/aa, ritorna true se la prima è minore/uguale della seconda
function before(date1, date2)
{
	var minor = new Array();
	var major = new Array();
	minor = date1.split('/');
	major = date2.split('/');
	
	if(major[2] > minor[2]) return true;	// se l'anno della prima è maggiore allora torna vero
	else if(major[2] < minor[2]) return false; // se l'anno della prima è minore allora torna falso
	else if(major[1] > minor[1]) return true; // a parita' di anno, se il mese della prima è maggiore ritorna vero
	     else if(major[1] < minor[1]) return false;	// se invece è minore torna falso
	     else if(major[0] >= minor[0]) return true; // a parita' di anno e mese, se il primo giorno è maggiore o uguale torno vero
	          else return false;	// altrimenti torno falso
}

// ritorna true se la data è valida
function isValidDate(day,month,year)
{
	var valid = new Date(year,month-1,day); // decremento il mese * Js
	if((y2k(valid.getYear()) == Number(year)) && (valid.getMonth() == Number(month-1)) && (valid.getDate() == Number(day)))
		return true;
	else
		return false
}
// mi assicuro che l'anno sia di 4 cifre (IE docet)
function y2k(number) 
{
	return (number < 1000) ? number + 1900 : number; 
}

function print_page()
{
	self.print();
}

// FUNZIONE VAR_DUMP PER JAVA SCRIPT//
var box;
function var_dump(obj) {
	box = window.open('','Var_dump','resizable=yes,toolbar=no,scrollbars=yes,width=200,height=200');
	explore(obj,0,0,0,0,0);
	box.document.close();
}

// funzione ricorsiva che esamina l'elemento passato
function explore(obj,eln,inside,level) {
	var index = '';
	var spaces = '';
	for (var i = 0; i < level;i++)
		spaces += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	index += spaces;
	if (inside == 0)
		index += '';
	else
		index += '[' + eln + ']&nbsp;=>&nbsp;';
	if (typeof(obj) == 'number') {
		box.document.write(index + 'number(' + obj + ')<br>');
		return;
	}
	if (typeof(obj) == 'string') {
		box.document.write(index + 'string(' + obj.length + ')&nbsp;"' + obj + '"<br>');
		return;
	}
	if (typeof(obj) == 'object') {
		var count = 0;
		for (var i in obj)
			count++;
		if (count == 0)
			box.document.write(index + 'array(' + count + ')&nbsp;{&nbsp;}<br>');
		else {
			box.document.write(index + 'array(' + count + ')&nbsp;{<br>');
			for (var i in obj) 
				explore(obj[i],i,1,level+1);
			box.document.write(spaces + spaces + '}<br>');
		}
		return;
	}
	return;
}// FINE VAR_DUMP//

// mostrano i puntini animati dopo la scritta loading
function show_loading()
{
	if(document.getElementById('loading'))
	{
	var loading = document.getElementById('loading');
	loading.innerHTML = '';
	loading.style.display = 'block';
	loading.innerHTML = js_dic_LOADING;
	write_loading('');
	}
}

function write_loading(dots)
{
	var loading = document.getElementById('loading');
	dots += '.';
	
	// limito la scrittura di puntini
	if(loading.innerHTML == js_dic_LOADING+'...')
		loading.innerHTML = js_dic_LOADING;
	else
		loading.innerHTML += '.';
	// metto un controllo per fermare l'esecuzione ciclica
	if(dots != '..........')
		window.setTimeout('write_loading(\''+dots+'\')', 1500);
}
function hide_loading()
{
	if(document.getElementById('loading'))
		document.getElementById('loading').style.display='none';
}

// funzione per la creazione del menu dei comandi
// pre: riceve un array "commands" di n array associativi con due campi: label, action;
//	inoltre possono essere specificati: la label del primo elemento (che non sarà mai
//	una azione), il name della select (di default=commands_menu), l'id (di default=commands_menu)
// post:select con il menu dei comandi
function commands_menu(commands, c_first_element, c_name, c_id, c_class){
	// inizializzo le variabili
	var c_menu_name = '';
	var c_menu_id = '';
	var c_menu_first_element = '--'+js_dic_COMMANDS+'--';
	var c_menu_class = 'commands_menu';
	if (c_name)
		c_menu_name = c_name;
	if (c_id)
		c_menu_id = c_id;
	if (c_first_element)
		c_menu_first_element = c_first_element;
	if (c_class)
		c_menu_class = c_class;
	
	// inizializzo la select
	var command_menu_code = '<select id='+c_menu_id+' name='+c_menu_name+' class="'+c_menu_class+'" onChange="eval(this.value)">';
	// opzione base
	command_menu_code+= '<option value="">'+c_menu_first_element+'</option>';
	// ciclo sull'array per creare tutte le opzioni
	for (i in commands)
		command_menu_code+= '<option value="'+commands[i]['action']+'">'+commands[i]['label']+'</option>';
	// chiudo la select
	command_menu_code+= '</select>';
	// ritorno il codice con la select popolata!
	return command_menu_code;
}


// Funzione per il controllo sui dati inseriti che devono essere di tipo "number". Elem rappresenta l'id dell'elemento da cui proviene l'input 
// (original_class la sua classe di stile che in caso di inserimento di dati non corretti, a seguito di una evidenziazione dell'errore, verrebbe persa).
// Type rappresenta il tipo del numero default float. Default_value è il valore di default (default 0) che viene impostato al posto di un numero errato.
// Se viene dato il valore "admit_null" a default_value viene ammesso un valore nullo
// La funzione sostituisce le virgole con il punto.
function is_number(number, elem, type, default_value, original_class){
	// controllo se esiste una classe
	if (!original_class)
		original_class = '';
	// se non è settato il default impostalo a 0
	if (!default_value)
		default_value = 0;
	// controllo se viene definito il type del numero
	if (!type)
		type = 'float';
	// altrimenti se non è ammesso un valore e number non è null
	if(number.length>0){
		// sostituisco eventuali virgole con il punto
		number = number.replace(new RegExp(/,/gi),'.');
		// se non è un numero reimposto il value al suo valore di default
		if (isNaN(number)){
			document.getElementById(elem).value = default_value;
			document.getElementById(elem).className = ' hightlight';
		}
		else{
			if (type == 'float')
				document.getElementById(elem).value = number;	// così modifico anche eventuali numeri formattati con la virgola
			else
				document.getElementById(elem).value = parseInt(number);	 // così modifico il numero impostandolo a numero intero
			document.getElementById(elem).className = original_class;
		}
	}
	else if(default_value != 'admit_null'){
		document.getElementById(elem).value = default_value;
		document.getElementById(elem).className = ' hightlight';
	}
}

// passato il nome di un menù select ne ritorna il testo della voce selezionata
function get_select_name(selectname)
{
	var name = '';
	var select = document.getElementById(selectname);
	var options = select.options;
	for(var o=0; o<options.length; o++)
		if(options[o].selected)
			name = options[o].text;
	return name;
}

// ritorna un array di valori da determinati hidden tag che hanno l'id che inizia per il valore passato
// utile per ottenere l'array di id in quelle pagine in cui ci sono liste di elementi
function get_id_list(match)
{
	var elements = document.getElementsByTagName('input');
	var id_list = new Array();

	//prelevo i codici delle meetingpointype esistenti dagli hidden tag e li metto in un array
	for(i=0;i<elements.length;i++)
	{
		if(elements[i].getAttribute('type')=='hidden')
		{
			if(elements[i].getAttribute('id').match(match) && elements[i].getAttribute('id').indexOf(match) == 0)
				if(elements[i].getAttribute('value') != '')
					id_list[id_list.length]=elements[i].getAttribute('value');
		}
	}
	
	return id_list;
}

// controlla che tipo di display fare sulle righe di una tabella in base al tipo di browser
function display_for_browser() {
	if(navigator.appName == 'Microsoft Internet Explorer')
		return 'block';
	else
		return 'table-row';
}

// We don't want to trip JUST spaces, but also tabs,
// line feeds, etc.  Add anything else you want to
// "trim" here in Whitespace
function LTrim(str)
{
  var whitespace = new String(" \t\n\r");
  var s = new String(str);
  if (whitespace.indexOf(s.charAt(0)) != -1) {
    // We have a string with leading blank(s)...
    var j=0, i = s.length;
    // Iterate from the far left of string until we
    // don't have any more whitespace...
    while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
    j++;
    // Get the substring from the first non-whitespace
    // character to the end of the string...
    s = s.substring(j, i);
  }
  return s;
}
function RTrim(str)
{
  var whitespace = new String(" \t\n\r");
  var s = new String(str);
  if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
    // We have a string with trailing blank(s)...
    var i = s.length - 1;       // Get length of string
    // Iterate from the far right of string until we
    // don't have any more whitespace...
    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
      i--;
    // Get the substring from the front of the string to
    // where the last non-whitespace character is...
    s = s.substring(0, i+1);
  }
  return s;
}

function Trim(str) { return RTrim(LTrim(str)); }

// dato il value di un elemento di form, lo converte in un float
function getFloat(value)
{
	return Number(0.0 + value.replace(',','.'));
}

// se esiste, ritorna il value di un elemento della pagina
// (da usare SOLO con elementi che ammettono un value, ovviamente!)
function get_value(obj_id)
{
        if(document.getElementById(obj_id))
                return document.getElementById(obj_id).value;
        else
                return false;
}

//funzione per sostituire ' e " con caratteri compatibili con javascript e html
function smartescape(string) {
    string = string.replace(new RegExp(/"/gi),'&quot;');
    string = string.replace(new RegExp(/</gi),'&lt;');
    string = string.replace(new RegExp(/>/gi),'&gt;');
    string = string.replace(new RegExp(/'/gi),"\\'");
    return string
}

//funzione simile a htmlentities
function e_h(string) {
    string = string.replace(new RegExp(/&/gi),'&amp;');
    string = string.replace(new RegExp(/"/gi),'&quot;');
    string = string.replace(new RegExp(/</gi),'&lt;');
    string = string.replace(new RegExp(/>/gi),'&gt;');
    return string
}

function hide_selects() {
    var selects = document.getElementsByTagName('select');
    for (var i = 0; i < selects.length; i++)
        selects[i].style.visibility = 'hidden';
}

function show_selects() {
    var selects = document.getElementsByTagName('select');
    for (var i = 0; i < selects.length; i++)
        selects[i].style.visibility = 'visible';
}


//FUNZIONE SPRINTF() PER JAVASCRIPT

/* uso = sprintf('stringa da sostituire', array(par1,par3,...)) */

function sprintf()
{
   if (!arguments || arguments.length < 1 || !RegExp)
   {
      return;
   }
   var str = arguments[0];
   var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
   var a = b = [], numSubstitutions = -1, numMatches = 0;
   while (a = re.exec(str))
   {
      var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
      var pPrecision = a[5], pType = a[6], rightPart = a[7];

      numMatches++;
      if (pType == '%')
      {
         subst = '%';
      }
      else
      {
         numSubstitutions++;
         if (numSubstitutions >= arguments[1].length)
         {
            alert('Error! Not enough function arguments for the number of substitution parameters in string.');
            return ''
         }
         var param = arguments[1][numSubstitutions];
         var pad = '';
                if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
           else if (pPad) pad = pPad;
         var justifyRight = true;
                if (pJustify && pJustify === "-") justifyRight = false;
         var minLength = -1;
                if (pMinLength) minLength = parseInt(pMinLength);
         var precision = -1;
                if (pPrecision && pType == 'f')
                   precision = parseInt(pPrecision.substring(1));
         var subst = param;
         switch (pType)
         {
         case 'b':
            subst = parseInt(param).toString(2);
            break;
         case 'c':
            subst = String.fromCharCode(parseInt(param));
            break;
         case 'd':
            subst = parseInt(param) ? parseInt(param) : 0;
            break;
         case 'u':
            subst = Math.abs(param);
            break;
         case 'f':
            subst = (precision > -1)
             ? Math.round(parseFloat(param) * Math.pow(10, precision))
              / Math.pow(10, precision)
             : parseFloat(param);
            break;
         case 'o':
            subst = parseInt(param).toString(8);
            break;
         case 's':
            subst = param;
            break;
         case 'x':
            subst = ('' + parseInt(param).toString(16)).toLowerCase();
            break;
         case 'X':
            subst = ('' + parseInt(param).toString(16)).toUpperCase();
            break;
         }
         var padLeft = minLength - subst.toString().length;
         if (padLeft > 0)
         {
            var arrTmp = new Array(padLeft+1);
            var padding = arrTmp.join(pad?pad:" ");
         }
         else
         {
            var padding = "";
         }
      }
      str = leftpart + padding + subst + rightPart;
   }
   return str;
}
//FINE FUNZIONE SPRINTF()
function session_keep_alive()	{
	var url_xml_rpc_=js_global_root_url+'xml_rpc/call.php';
	var struct_param_=new Array();
	struct_param_['header']=new Array();
	struct_param_['query']=new Array();
	struct_param_['header']['version']='1.0.0';
	struct_param_['header']['product']='session';
	struct_param_['header']['sessid']=sessid;
	var iso_encoding_='utf-8';
	struct_param_['header']['type']='keep_alive';
	xml_request(struct_param_,url_xml_rpc_,iso_encoding_,no_action);
}

// Nessuna azione
function no_action()	{
	setTimeout(session_keep_alive,300000);
	return true;	
}

function in_array(element, array){
    try {
        for (var i = 0; i < array.length; i++)
            if (array[i] == element) return true;
    }
    catch(ex) {
        for (var i in array)
            if (array[i] == element) return true;
    }
    return false;
}

// passati giorno, mese e anno, ritorna il codice del giorno della settimana corrispondente
function get_week_day(day, month, year)
{
        month = Number(month)-1;
        var currentdate = new Date(year, month, day, 0, 0, 0);
        return currentdate.getUTCDay();
}