/**
 * In questo file si trovano oggetti, funzioni e costanti di utilita' generale
 */

var MWUtility = new Object();

/**
 * Escapa tutti gli apostrofi e le virgolette per rendere la stringa compatibile con la generazione dinamica di codice javascript 
 */
MWUtility.escapeForCodeGeneration = function(inputString)
{

	inputString = inputString.replace(/'/g, "@^#");
	inputString = inputString.replace(/"/g, "#^@");

	return inputString;	
}

MWUtility.unescapeForCodeGeneration = function(inputString)
{
	var ret = inputString.replace(/@\^#/g, "'").replace(/#\^@/g, "\"");

	return ret;	
}
/**
 * Usato 'a runtime' dal codice generato
 */
MWUtility.concatenateApos = function(strArr)
{
	var t = 0;
	var str= '';
	for(t = 0; t< strArr.length - 1; t++)
	{
		str += strArr[t] + "\'";
	}
	str += strArr[t];
	return str;
}

/**
 * Usato 'a runtime' dal codice generato
 */
MWUtility.concatenateQuot = function(strArr)
{
	var t = 0;
	var str= '';
	for(t = 0; t< strArr.length - 1; t++)
	{
		str += strArr[t] + '\"';
	}
	str += strArr[t];
	return str;
}

/**
 * Ritorna un oggetto Date a partire da una stringa formattata yyyy-mm-dd
 */
MWUtility.parseXMLDate = function(date_yyyy_mm_dd)
{
	var splitted = date_yyyy_mm_dd.split('-');

	if (splitted.length != 3)
		return null;

	return  new Date(splitted[0], splitted[1] - 1, splitted[2]);
}

/**
 * converte aaaa-mm-dd in dd/mm/aaaa
 * ATTENZIONE!!! Quando la data contiene anche un'ora questo codice e' BACATO!! Bisogna considerare la timezone!
 *               Utilizzare la conversione via java
 */
MWUtility.swapDate = function(data)
{
	var splitted = data.split('-');
	
	if (splitted.length != 3)
		return '';
	
	var ddd = splitted[2];
	if (ddd.search('T') > -1)
		ddd = ddd.substr(0, ddd.search('T'))
	
	return ddd + '/' + splitted[1] + '/' + splitted[0];
}

/**
 * Removes leading and trailing spaces from the passed string. Also removes
 * consecutive spaces and replaces it with one space. If something besides
 * a string is passed in (null, custom object, etc.) then return the input.
 */
MWUtility.trim = function (inputString)
{
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " " || ch=="\n" || ch=="\r" || ch=="\t") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " " || ch=="\n" || ch=="\r" || ch=="\t") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }

   return retValue; // Return the trimmed string back to the user
}

/**
 * Verifica che l'oggetto passato sia una stringa di lunghezza almeno 1.
 */
MWUtility.isNotEmptyString = function (inputString)
{
   if (typeof inputString != "string") { return false; }
   
   return (inputString.length > 0);
}

MWUtility.getFirstElementByTagName = function (nodo, nomeTag)
{
    if (nodo == null || nodo == undefined)
        return null;
           
    for (var i=nodo.firstChild; i != null; i=i.nextSibling)
       if (i.nodeType == Node.ELEMENT_NODE && i.tagName == nomeTag)
       {
           return i;
           break;
       }
    
    return null;
}
 
//prende un nodo e si costruisce il testo contenuto
MWUtility.mergeText = function (node)
{
    var testo = '';
    
    if (node == null || node == undefined)
        return testo;
    
    if (node.nodeType == Node.ELEMENT_NODE)
    {
        clds = node.childNodes;
        
        for (var i=0; i < clds.length; i++)
            testo = testo + clds[i].nodeValue;
    }
    else if (node.nodeType == Node.TEXT_NODE)
        testo = node.value;
        
    return testo;
}

// cerca il tag nel node, e restituisce il suo contenuto o quello dell'attributo se indicato
MWUtility.getText = function (node, tag, attribute)
{
  nodes = node.getElementsByTagName(tag);
  
  if (nodes == null || nodes.length != 1)
  {
      //alert('Tag not found: xml=' + node + ', xml-name=' + node.nodeName + ', tag=' + tag + ', nodes=' + nodes.length);
      
      return '';
  }
  else if (attribute == null || attribute == undefined)
      return MWUtility.mergeText(nodes[0]);
  else
      return nodes[0].getAttribute(attribute);
}

MWUtility.notValidInput = function(input)
{
	return (input == undefined || input == null) ? true : false; 
}

MWUtility.notEmptyInput = function(input)
{
	if (MWUtility.notValidInput(input)) return false;
	
	return (input.value != '') ? true : false;
}

MWUtility.FirstLetterUpperCase = function(input)
{

	if( !MWUtility.notValidInput(input) && input.value !='')
	{
		var text = input.value;
		var prima = text.substring(0,1);
		var dopo  = text.substring(1,text.length);
		
		prima = prima.toUpperCase();
		
		input.value = prima + dopo;
		
	}
		
}

/**
 * Ordina un array 
 */
MWUtility.sortByAttribute = function(vec, comparator, loBound, hiBound)
{
	if (loBound == null)
	{
		loBound = 0;
		hiBound = vec.length - 1;
	} 
	/**************************************************************
		This function adapted from the algorithm given in:
			Data Abstractions & Structures Using C++, by
			Mark Headington and David Riley, pg. 586.

		Quicksort is the fastest array sorting routine for
		unordered arrays.  Its big O is n log n.
	 **************************************************************/

		var pivot, loSwap, hiSwap, temp;

		// Two items to sort
		if (hiBound - loBound == 1)
		{
			//if (vec[loBound][attributeName] > vec[hiBound][attributeName])
			if (comparator.compare(vec[loBound], vec[hiBound]) > 0) // compare ritorna > 0 se left > right
			{
				temp = vec[loBound];
				vec[loBound] = vec[hiBound];
				vec[hiBound] = temp;
			}
			return;
		}

		// Three or more items to sort
		pivot = vec[parseInt((loBound + hiBound) / 2)];
		vec[parseInt((loBound + hiBound) / 2)] = vec[loBound];
		vec[loBound] = pivot;
		loSwap = loBound + 1;
		hiSwap = hiBound;

		do {
			// Find the right loSwap
			while (loSwap <= hiSwap && comparator.compare(vec[loSwap], pivot) <= 0 ) // compare ritorna <= 0 se left <= right
			//vec[loSwap][attributeName] <= pivot[attributeName])
				loSwap++;

			// Find the right hiSwap
			while (comparator.compare(vec[hiSwap], pivot) > 0)
			//vec[hiSwap][attributeName] > pivot[attributeName])
				hiSwap--;

			// Swap values if loSwap is less than hiSwap
			if (loSwap < hiSwap)
			{
				temp = vec[loSwap];
				vec[loSwap] = vec[hiSwap];
				vec[hiSwap] = temp;
			}
		} while (loSwap < hiSwap);

		vec[loBound] = vec[hiSwap];
		vec[hiSwap] = pivot;


		// Recursively call function...  the beauty of quicksort

		// 2 or more items in first section		
		if (loBound < hiSwap - 1)
			MWUtility.sortByAttribute(vec, comparator, loBound, hiSwap - 1);


		// 2 or more items in second section
		if (hiSwap + 1 < hiBound)
			MWUtility.sortByAttribute(vec, comparator, hiSwap + 1, hiBound);
}

MWUtility.includedFiles = new Array();

/**
 * Se non e' mai stato incluso, include il JS sorgente nella pagina corrente
 */
MWUtility.includiJS = function(src)
{
	for (var i = 0; i < MWUtility.includedFiles.length; i++)
		if (MWUtility.includedFiles[i] == src)
			return false;  //e' gia' stato incluso

	var html_doc = document.getElementsByTagName('head').item(0);
	var js = document.createElement('script');
	js.setAttribute('language', 'javascript');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', src);
	html_doc.appendChild(js);
	MWUtility.includedFiles[MWUtility.includedFiles.length] = src;
	return true;
}

MWUtility.includiCSS = function(src)
{
	for (var i = 0; i < MWUtility.includedFiles.length; i++)
		if (MWUtility.includedFiles[i] == src)
			return false;  //e' gia' stato incluso

	var html_doc = document.getElementsByTagName('head').item(0);
	var css = document.createElement('link');
	css.setAttribute('rel', 'stylesheet');
	css.setAttribute('type', 'text/css');
	css.setAttribute('href', src);
	html_doc.appendChild(css);
	MWUtility.includedFiles[MWUtility.includedFiles.length] = src;
	return true;
}

