/* $Id: utils.js,v 1.5 2008/06/05 17:18:13 tagliente Exp $ */

//------------------
// COOKIES
//------------------

var Cookies = {
	init: function () {
		var allCookies = document.cookie.split('; ');
		for (var i=0;i<allCookies.length;i++) {
			var cookiePair = allCookies[i].split('=');
			this[cookiePair[0]] = cookiePair[1];
		}
	},
	create: function (name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/;domain=clickandplay.it";
		this[name] = value;
	},
	erase: function (name) {
		this.create(name,'',-1);
		this[name] = undefined;
	}
};
Cookies.init();

//-----------------------------------
// Metodi di utilita
//-----------------------------------

/**
 * Metodo che assegna una specifica classe ad un elemento div
 * @param name nome del div
 * @param newClass classe da assegnare al div
 */
function changeClassDiv(name,newClass){
	
	theObject = getObject(name);
		
	if(theObject) {
		theObject.className = newClass;
	}
}


/**
 * Metodo di lettura della proprieta' style di un DIV
 * 
 * @param objectId identificatore del div
 * @return proprieta' style richiesta
 * 
 */
function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its
    if(document.getElementById && document.getElementById(objectId)) {
		// W3C DOM
		return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
		// MSIE 4 DOM
		return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
		// NN 4 DOM.. note: this won't find nested layers
		return document.layers[objectId];
    } else {
	return false;
    }
} // getStyleObject

/**
 * Metodo di lettura di un oggetto DIV
 * 
 * @param objectId identificatore del div
 * @return oggetto richiesto
 * 
 */
function getObject(objectId) {
    // cross-browser function to get an object's style object given its
    if(document.getElementById && document.getElementById(objectId)) {
	// W3C DOM
	return document.getElementById(objectId);
    } else if (document.all && document.all(objectId)) {
	// MSIE 4 DOM
	return document.all(objectId);
    } else if (document.layers && document.layers[objectId]) {
	// NN 4 DOM.. note: this won't find nested layers
	return document.layers[objectId];
    } else {
	return false;
    }
} // getStyleObject


/**
 * Metodo che effettua il controllo del tipo di browser usato (defautl MOZILLA)
 *
 * @return costante che identifica il browser
 */
function getBrowserVersion() {

	// if (document.layers) {
	browserType = MOZILLA;
	// }
	if (document.all) {
		var posizioneVersione = navigator.appVersion.indexOf("MSIE");
		
		var versione = navigator.appVersion.substring(posizioneVersione+5,posizioneVersione+6);
			
		// alert(versione);
		
		if(versione<7) {
			browserType = EXPLORER;
		}
	}
	if (window.navigator.userAgent.toLowerCase().match(GECKO)) {
	   browserType= GECKO;
	}
	
	// alert(browserType);
	return browserType;
}


/**
 * Metodo di lettura di una pagina dal server
 * 
 * @param datafile indirizzo della pagina da caricare
 * @return stringa contenente il file richiesto
 * 
 */
function getPage(datafile) {

	var contenuto="";
	
	try {
		if(getBrowserVersion() == EXPLORER){
		contenuto = getPageOldExplorer(datafile);
		}
	else {
		contenuto = getPageMozilla(datafile);
		}
	}catch(ex) {
		// in futuro ci mettiamo qualcosa per tracciare
	}
 	
	return contenuto;
}

/**
 * Metodo di lettura di un file da un server
 * Specifico per browser Explorer
 *
 * @param indirizzo indirizzo del file
 * @return oggetto richiesto
 * 
 */
function getPageOldExplorer(indirizzo) {
	var response;
	objXml = new ActiveXObject("Microsoft.XMLHTTP");
	// objXml = new ActiveXObject("Msxml2.XMLHTTP"); older version
	objXml.open("GET", indirizzo, false);
	objXml.onreadystatechange=function() {
	   if (objXml.readyState==4) {
	       response = objXml.responseText;
	  }
	 }
	objXml.send(null);
	return response;
}

/**
 * Metodo di lettura di un file da un server
 * Specifico per browser mozilla
 *
 * @param indirizzo indirizzo del file
 * @return oggetto richiesto
 * 
 */
function getPageMozilla(indirizzo){	
     objXml = new XMLHttpRequest();
     objXml.open("GET",indirizzo,false);
     objXml.send(null);
     return objXml.responseText ;
     }


//------------------
// GESTIONE DIV
//------------------

/**
 * Metodo di che nasconde un div
 *
 * @param idDiv da nascondere
 * @param driver id dell'oggetto chiamante
 * 
 */
function hideDiv(idDiv) {
  var the_style = getStyleObject(idDiv);
  //the_style.visibility = "hidden";
  the_style.display = "none";
}

/**
 * Metodo di che mostra un div  nascosto
 *
 * @param idDiv da mostrare
 * 
 */
function showDiv(idDiv) {	
  var the_style = getStyleObject(idDiv);
  //the_style.visibility = "visible";
  the_style.display = "block";
}

/**
 * Metodo di che sostituisce il contenuto di un div
 *
 * @param idDiv da popolare
 * 
 */
function altercontent(idDiv,content){
	if (document.all) {
		document.all(idDiv).innerHTML=content;
	}
	else if (document.getElementById){
		rng = document.createRange();
		el = document.getElementById(idDiv);
		rng.setStartBefore(el);
		htmlFrag = rng.createContextualFragment(content);
		while (el.hasChildNodes()) el.removeChild(el.lastChild);
			el.appendChild(htmlFrag);
	}
}

// -------------------------
// Varie
// --------------------------

/**
 * Metodo che controlla che una cifra espressa in euro con 2 cifre di centesimi sia
 * maggiore di zero
 * 
 * @param saldo valore da controllare
 *
 * @return true se il saldo e' maggiore di zero
 */
function checkSaldoGTZero(saldo) {	
	var lunghezza = saldo.length;
	var euro = saldo.substring(0,lunghezza-3);	
	var cent = saldo.substring(lunghezza-2,lunghezza);
	var res = euro > 0 || cent > 0;	
	return res;
}

/**
 *  Remove all occurrences of a token in a string
 * @param s  string to be processed
 * @param t  token to be removed
 * @return new string
 */
function remove(s, t) {
  i = s.indexOf(t);
  r = "";
  if (i == -1) return s;
  r += s.substring(0,i) + remove(s.substring(i + t.length), t);
  return r;
 }

/**
 * Metodo che apre una url in una nuova finestra senza barra di navigazione
 * l'altezza della finestra e' sempre compatibile con la risuluzione dello schermo
 * @param url indirizzo da aprire nella finestra
 * @param alt altezza desiderata della finestra
 * @param larg larghezza desiderata della finestra
 * @param nome del popup
 */
function openPopup(url,alt,larg,name) {	
	var maxAlt = detecteHeightRes();
	var maxLarg = 1024;	
	if(alt<maxAlt) {
		maxAlt = alt;
	}	
	if(larg<maxLarg) {
		maxLarg = larg;
	}	
	var features = 'toolbar=no,location=no,directories=no,status=no,menubar=no,' + 
					'scrollbars=yes,resizable=no,width='+maxLarg+',height='+maxAlt; 	
	var popup = window.open ('',name,features);
	var html = getPage(url);
	popup.document.open();
 	popup.document.write(html);
	popup.document.close();
}

/**
 * Metodo di stampa di una pagina
 */
function printCurrentPage() {
   if (navigator.appName.indexOf("Microsoft") > -1 &&
       navigator.appVersion.indexOf("5.") == -1) {
      // IE4
      OLECMDID_PRINT = 6;
      OLECMDEXECOPT_DONTPROMPTUSER = 2;
      OLECMDEXECOPT_PROMPTUSER = 1;
      WebBrowser =
       '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="' +
       'CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
      document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
      WebBrowser1.ExecWB(OLECMDID_PRINT,   OLECMDEXECOPT_PROMPTUSER);
      WebBrowser1.outerHTML = "";
     }
   else {
     // N4 IE5
     window.print();
     }
   }

/**
 * Metodo che legge la risoluzione verticale del monitor di un utente
 *
 * @return risoluzione richiesta
 */
function detecteHeightRes() {
  /*
  ** Check if the browser is running in a low-resolution environment
  ** try to use the screen object (in N4 or e4). If not available, 
  ** try to use Java.If not available, assume low-res.
  ** returns true if in a low-resolution environment (width < 800 pixels)
  */ 	
  var result = 768;  	
  if (self.screen) {
	 result = self.screen.height;
	 }
  else 
    if (navigator.javaEnabled && navigator.javaEnabled()) {
		result =java.awt.Toolkit.getDefaultToolkit().getScreenSize().hight;			
	}     
    result = result - 100;
	return result;
}

/**
 * Metodo che controlla che il valore inserito sia numerico ed intero
 *
 * @param s valore da validare
 * @return true se il valore e' numerico
 */
function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

/**
 * Metodo che apre una url in una nuova finestra senza barra di navigazione
 * l'altezza della finestra e' sempre compatibile con la risuluzione dello schermo
 * @param url indirizzo da aprire nella finestra
 * @param alt altezza desiderata della finestra
 * @param larg larghezza desiderata della finestra
 */
function openHelpPopup(url,larg,alt) {	
	var features = "toolbar=no,location=no,directories=no,status=no,menubar=no," + 
					"scrollbars=yes,resizable=no,width="+larg+",height="+alt; 	
	var popup = window.open(url,null,features,true);
	popup.focus();
}

/**
 * Metodo che apre una url in una nuova finestra senza barra di navigazione
 * l'altezza della finestra e' sempre compatibile con la risuluzione dello schermo
 * @param url indirizzo da aprire nella finestra
 * @param alt altezza desiderata della finestra
 * @param larg larghezza desiderata della finestra
 */
function openScontrinoPopup(url,larg,alt) {	
	var features = "toolbar=no,location=no,directories=no,status=no,menubar=no," + 
					"scrollbars=yes,resizable=yes,width="+larg+",height="+alt; 	
	var popup = window.open(url,'scontrino',features,true);
	popup.focus();
}


/**
 * Metodo che apre una url in una nuova finestra senza barra di navigazione
 * l'altezza della finestra e' sempre compatibile con la risuluzione dello schermo
 * @param url indirizzo da aprire nella finestra
 * @param alt altezza desiderata della finestra
 * @param larg larghezza desiderata della finestra
 */
function openStatistichePopup(url,larg,alt) {	
	var features = "toolbar=no,location=no,directories=no,status=no,menubar=no," + 
					"scrollbars=yes,resizable=yes,width="+larg+",height="+alt; 	
	var popup = window.open(url,'statistiche',features,true);
	popup.focus();
}

/**
 * Metodo che apre una url in una nuova finestra senza barra di navigazione
 * l'altezza della finestra e' sempre compatibile con la risuluzione dello schermo
 * @param url indirizzo da aprire nella finestra
 * @param alt altezza desiderata della finestra
 * @param larg larghezza desiderata della finestra
 */
function openLiveScorePopup(url,larg,alt) {	
	var features = "toolbar=no,location=no,directories=no,status=no,menubar=no," + 
					"scrollbars=yes,resizable=no,width="+larg+",height="+alt; 	
	var popup = window.open(url,'livescore',features,true);
	popup.focus();
}

/**
 * Metodo che apre una url in una nuova finestra senza barra di navigazione
 * l'altezza della finestra e' sempre compatibile con la risuluzione dello schermo
 * @param url indirizzo da aprire nella finestra
 * @param alt altezza desiderata della finestra
 * @param larg larghezza desiderata della finestra
 */
function openRisultatiPopup(url,larg,alt) {	
	var features = "toolbar=no,location=no,directories=no,status=no,menubar=no," + 
					"scrollbars=yes,resizable=no,width="+larg+",height="+alt; 	
	var popup = window.open(url,'risultati',features,true);
	popup.focus();
}

/**
 * Metodo che apre una url in una nuova finestra senza barra di navigazione
 * l'altezza della finestra e' sempre compatibile con la risuluzione dello schermo
 * @param url indirizzo da aprire nella finestra
 * @param alt altezza desiderata della finestra
 * @param larg larghezza desiderata della finestra
 * @param nome nome del popup
 */
function openRemotePopup(url,larg,alt,nome) {	
	var features = "toolbar=no,location=no,directories=no,status=no,menubar=no," + 
					"scrollbars=yes,resizable=yes,width="+larg+",height="+alt; 	
	var popup = window.open(url,nome,features,true);
	popup.focus();
}

/**
 * Metodo che effettua il refresh del saldo visualizzato nella user-box
 */
function reloadSaldo() {
	Cookies.erase(NOME_COOKIE_SERVIZIO);
	window.location.reload();
}

/**
 * Metodo che effettua il refresh del cookie utilizzato nella user-box
 */
function reloadSCookie() {		
	Cookies.erase(NOME_COOKIE_SERVIZIO);
}

/**
 * Metodo che effettua il controllo preventivo della presenza delle proprieta'
 * necessarie al funzionamento di GateKeeper
 * Salva il parametro di login in caso di checkbox attiva
 *
 * @param form form su cui si controlla la presenza delle proprieta'
 */
function checkGKFields(form) {
	if ((form.gkl.value=='')||(form.gkp.value=='')) {
		var redirUrl = "/info/login.html?isEmpty";		
		self.location.href = redirUrl;
		return false;
	} else {	
		// set cookie if box remember checked
        if (form.chboxrem.checked){
	    var cookieValue = form.gkl.value;			
			Cookies.create(NOME_COOKIE_RICORDA_LOGIN,cookieValue,365);           
        } else {
            Cookies.erase(NOME_COOKIE_RICORDA_LOGIN);
        }
	}
	return true;
}

/**
 * Metodo che, data la presenza del campo username ed un cookie di memoria, 
 * prevalorizza il campo stesso
 */
function fillGKFields() {	    
	if (Cookies[NOME_COOKIE_RICORDA_LOGIN]&&document.newreg){
		document.newreg.gkl.value = Cookies[NOME_COOKIE_RICORDA_LOGIN];
		document.newreg.chboxrem.checked = true;
    }
	
}

/**
 * Funzione che prende un nome di FormBean e un nome di action e fa il submit
 * del formbean alla action specificata.
 *
 */
function submitToForButton(Form, theAction) {
	Form.action = theAction;
	Form.submit();
	return true;
}

/**
  * Remove NewLine, CarriageReturn and Tab characters from a String
  * @param  s  string to be processed
  * @return new string
  */
function removeNL(s) {
  
  var r = "";
  for (i=0; i < s.length; i++) {
    if (s.charAt(i) != '\n' &&
        s.charAt(i) != '\r' &&
        s.charAt(i) != '\t') {
      r += s.charAt(i);
      }
    }
  return r;
  }


/**
 * Metodo di trim di una stringa
 *
 * @param strTest - stringa da trimmare
 * @return stringa trimmata
 */
function trim(strTest){
    return lTrim(rTrim(strTest));
}

/**
 * Metodo di trim della parte sinistra di una stringa
 *
 * @param strTest - stringa da trimmare
 * @return stringa trimmata
 */
function lTrim(strTest){
    var s = new String(strTest);
    while(s.substring(0,1) == ' ')
        s = s.substring(1);
    return s;
}

/**
 * Metodo di trim della parte destra di una stringa
 *
 * @param strTest - stringa da trimmare
 * @return stringa trimmata
 */
function rTrim(strTest){
    var s = new String(strTest);
    while(s.substring(s.length - 1) == ' ')
        s = s.substring(0,s.length - 1);
    return s;
}

/**
 * Hand all instances of the Date object to this function for "repairs"
 * fix the bug in Navigator 2.0, Macintosh
 *
 * @param date - any instance of the Date object
 */
function fixDate(date) {
    var base = new Date(0);
    var skew = base.getTime();
    if (skew > 0)
        date.setTime(date.getTime() - skew);
}

/**
  *  Replace a token in a string
  * @param s  string to be processed
  * @param t  token to be found and removed
  * @param u  token to be inserted
  *  @return new String
  */
function replace(s, t, u) {
  var i = s.indexOf(t);
  var r = "";
  if (i == -1) return s;
  r += s.substring(0,i) + u;
  if ( i + t.length < s.length)
    r += replace(s.substring(i + t.length, s.length), t, u);
  return r;
  }

/**
 * Metodo che legge il contenuto di un eventuale parametro nella url
 *
 * @param parametro etichetta del parametro da cercare
 * @return contenuto del parametro cercato
 */
function getUrlParameter(parametro) {
	var searchLoc = document.location.search;
	var lengSearch = searchLoc.length;
	var parameters  = searchLoc.substring(1,lengSearch);
	var parametersArray = parameters.split("&");
	var k = parametersArray.length;
	var result;	
	for (i= 0 ; i < k; i++) {		
		if(parametersArray[i].indexOf(parametro)>=0) {			
			parametersArray1 = parametersArray[i].split("=");
			result = parametersArray1[1];			
		}
	}
	return result;
}

/**
 * Metodo di visualizzazione ed aggiornamento del box di saldo
 *
 * @param webapp front-end che chiama la funzione
 */
function showSaldo(webapp) {

	var styleDiv = getStyleObject(DIV_SALDO);
	
	if(styleDiv.display == 'block') {
		hideSaldo();
	} else {
		/*var partnerField = '';
		var urlChiamata = document.location.href;
		if(urlChiamata.indexOf(PARTNER_PREFIX)>0) {
			partnerField = PARTNER_FIELD+GENERIC_PARNTER;
		} else if(urlChiamata.indexOf(MSN_PREFIX)>0) {
			partnerField = PARTNER_FIELD+MSN_PARTNER;
		
		}
	
		var urlApiCompleta = URL_SALDO+webapp+partnerField;
		*/
		var urlApiCompleta = URL_SALDO+webapp;
		// alert(urlApiCompleta);
		
		var contenutoDiv = getPage(urlApiCompleta);
		
		altercontent(DIV_SALDO,contenutoDiv);
		
		
		styleDiv.display = 'block';
	}
	

}

/**
 * Metodo che nasconde il box saldo
 *
 */
function hideSaldo() {

	var styleDiv = getStyleObject(DIV_SALDO);
	
	styleDiv.display = 'none';
	
}