/*******************************************************************************
 *
 * Emanuele Pogliani
 * 26 agosto 2008
 * ValueTeam Spa
 *
 * COMBO AJAX
 *
 ******************************************************************************/





/**
 * request asincrona, restituisce una funzione
 * 
 * esempio d'uso
 * 		asyncRequest('GET', 'foo.php', function(o) {
 * 			console.log(o.responseText);
 *		});
 *
 *		asyncRequest('POST', 'foo.php', function(o) {
 * 			console.log(o.responseText);
 *		}, post_data);
 */
function asyncRequest(method, uri, callback, postData) {
	function handleReadyState(o, callback) {
		if (o && o.readyState == 4 && o.status == 200) {
			if (callback) {
				if (typeof(callback) == 'function') {
					callback(o);
				}
				if (typeof(callback) == 'object') {
					for (var i = 0; i < callback.length; i++) {
						try {
							callback[i](o);
						}
						catch(error) {
						}	
					}
				}					
			}	
  	}
	}
	
	var getXHR = function() {
		var http;
		try {
			http = new XMLHttpRequest;
			getXHR = function() {
				return new XMLHttpRequest;
			};
		}
		catch(e) {
			var msxml = [
				'MSXML2.XMLHTTP.3.0',
      	'MSXML2.XMLHTTP',
      	'Microsoft.XMLHTTP'
	    ];
			for (var i = 0, len = msxml.length; i < len; ++i) {
				try {
					http = new ActiveXObject(msxml[i]);
					getXHR = function() {
						return new ActiveXObject(msxml[i]);
					};
					break;
				}
		    catch(e) {
				}
			}
		}
		return http;
	};				

  var http = getXHR();
	http.open(method, uri, true);
	http.onreadystatechange = function() { handleReadyState(http, callback); };
	http.send(postData || null);
	return http;
}

/**
 * funzione tokenizer che dato un delimitatore e una stringa costruisce il vettore
 * corrispondente
 */
function tokenizer(stringa, delimitatore) {
	var tokens = new Array();
	indiceTokens = 0;
  
	fimStr = stringa.length;
	pos = 0;
	ultimoIndice = 0;

	for ( i = 0; i < fimStr; i++ ) {
		if(stringa.charAt(i) == delimitatore) {
			tokens[indiceTokens] = stringa.substring(pos, i);
			pos = i + 1;
			indiceTokens++;
			ultimoIndice = pos; 
		}
	}
	if (pos < fimStr) {
		tokens[indiceTokens] = stringa.substring(pos, fimStr);
	}
	return tokens;
}

/**
 * funzione che esegue il trim di una stringa elidendo eventuali spazi in testa e in coda alla stringa
 */
function trim(stringa){
  while (stringa.substring(0,1) == ' '){
      stringa = stringa.substring(1, stringa.length);
  }
  while (stringa.substring(stringa.length-1, stringa.length) == ' '){
      stringa = stringa.substring(0,stringa.length-1);
  }
  return stringa;
}

/**
 * imposta un valore specficato in una lista di selezione
 */
function setComboValue(IdObj, valueToSet) {
	var obj = document.getElementById(IdObj);
	if (obj != 'undefined') {
		for (var j = 0; j < obj.options.length; j++) {
			if (obj.options[j].value.split('|')[0] == valueToSet) {																				
				obj.selectedIndex = j;						
				break;
			}
		}
	}
}

/**
 * funzione che data una servlet contente delle options e l'id delle della select popola la select
 * (cross browser)
 */
function writeOptionsFromUrl(servletAddress, idSelect, queryParamName, callback) {
	asyncRequest('GET', servletAddress, new Array(function(o) {
		// mostro le options
		var textVector = o.responseText.replace(/<option value=\"/g,"").replace(/\">/g,"@").replace(/<\/option>/g,"#").replace(/<\/option>/g,"");
		var optionsVector = tokenizer(textVector,'#');	
		
		for (var optionNumber = 0; optionNumber < optionsVector.length; optionNumber++) {
			var optionElement = tokenizer(optionsVector[optionNumber],'@');
			var value = trim(optionElement[0]);
			var text = trim(optionElement[1]);			
			document.getElementById(idSelect).appendChild(createOption(text,value));
		}
		var qsParamValue = getQueryStringParamValue(queryParamName);
		if (qsParamValue != null)
			setTimeout("setComboValue('"+idSelect+"','"+qsParamValue+"');",500);
	}, callback));
	
}

/**
 * restituisce  il valore di una variabile passata in queryString
 */
function getQueryStringParamValue(queryStringParamName) {
	var paramValue = null;
	//seleziona l'elemento se presente nella querystring
	if (queryStringParamName != 'undefined') {
		var hashQueryString = location.href.split('?')[1];
		if (hashQueryString) {
			var parameters = tokenizer(hashQueryString, '&');
			for (var i = 0; i < parameters.length; i++) {
				if (parameters[i].split('=')[0] == queryStringParamName) {
					paramValue = parameters[i].split('=')[1];					
					break;
				}
			}
		}
	}
	return paramValue;
}

/**
 * crea una variabile contente l'oggetto option
 */
function createOption(text, value) {
	var newOption = document.createElement('option');
	newOption.setAttribute('value',value);
	newOption.innerHTML = text;
	return newOption;
}

/**
 * funzione di inizializzazione dell'elemento di selezione
 * imposta la prima option di default
 */
function initSelect(idSelect, defaultText, defaultValue) {
	document.getElementById(idSelect).innerHTML = '';
	document.getElementById(idSelect).appendChild(createOption(defaultText, defaultValue));
}
