//rilevo SO e Browser
SOWIN = (navigator.userAgent.toLowerCase().indexOf("win") > -1) ? 1 : 0;
SOMAC = (navigator.userAgent.toLowerCase().indexOf("mac") > -1) ? 1 : 0;
SOLIN = (navigator.userAgent.toLowerCase().indexOf("linux") > -1) ? 1 : 0;
SOALT = (!SOWIN && !SOMAC && !SOLIN) ? 1 : 0;
OP = ((ind1 = navigator.userAgent.indexOf("Opera")) > -1) ? 1 : 0;
punto = (OP) ? navigator.userAgent.indexOf(".",ind1):0;
OP5 = (OP && parseInt(navigator.userAgent.substr(punto-1)) == 5) ? 1 : 0;
OP6 = (OP && parseInt(navigator.userAgent.substr(punto-1)) == 6) ? 1 : 0;
IE = ((ind2 = navigator.appVersion.indexOf("MSIE")) > -1 && !OP) ? 1 : 0;
IE4 = (IE && parseInt(navigator.appVersion.substr(ind2+5)) == 4) ? 1 : 0;
IE5 = (IE && parseInt(navigator.appVersion.substr(ind2+5)) == 5) ? 1 : 0;
IE6 = (IE && parseInt(navigator.appVersion.substr(ind2+5)) == 6) ? 1 : 0;
NN = (navigator.appName.indexOf("Netscape")>-1) ? 1 : 0;
NN4 = (NN && parseInt(navigator.appVersion)==4) ? 1 : 0;
NN6 = (NN && parseInt(navigator.appVersion)>4) ? 1 : 0;
GE = (navigator.userAgent.toLowerCase().indexOf("gecko")>-1) ? 1 : 0;
//riconosce mozilla, NN6 e tutti i browser basati sul gecko layout engine

/*
* PROTOTYPE
*/
String.prototype.equalsIgnoreCase = matchIgnoreCase;
function matchIgnoreCase(strTerm) {
    var strToSearch = this.toLowerCase();
    strTerm = strTerm.toLowerCase();
    if (strToSearch==strTerm)
        return true
    else
        return false
}

String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'') }

//function trimString(sInString) {
//	sInString = sInString.replace( /^\s+/g, "" );// strip leading
//	return sInString.replace( /\s+$/g, "" );// strip trailing
//}

RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

function JWM_swapImage() {
	var a = JWM_swapImage.arguments;
	document.JWM_tmp = new Array;
	var j = 0;
	for (var i = 0; i < (a.length-1); i+=2) {
		var x = document.getElementById(a[i]);
		document.JWM_tmp[j++] = x;
		if(!x.oSrc) x.oSrc=x.src;
		x.src = a[i+1];
	}
}

function JWM_swapImgRestore() {
	var a = document.JWM_tmp;
	for (var i = 0; a && i < a.length && a[i].oSrc; i++)
		a[i].src = a[i].oSrc;
}

//aggiunge il parametro specificato alla querystring
function addParameter(nome,valore) {
  for (var l = 0; l < document.links.length; l++) {
    var abslink = document.links[l].href.indexOf("http://");
    var intlink = document.links[l].href.indexOf("#");
    var jslink = document.links[l].href.indexOf("javascript:");  //forse va trattato!!!!
    var jwmlink = document.links[l].href.indexOf("http://");   //forse è meglio aggiungere il nome dell'applicazione
    var isjsp = (document.links[l].href.indexOf(".jsp")!=-1)?true:false;
    var separatore = (document.links[l].href.indexOf("?")!=-1)?"&":"?";

    if (intlink==-1 && jslink==-1 && jwmlink!=-1 && isjsp)
      document.links[l].href += separatore+nome+"="+valore;
  }
}

//ritorna undefined se il parametro non è definito
function getParameter(nome) {

   var url = window.location.href;
   var paramsStart = url.indexOf("?");
   if (paramsStart != -1) {
      var paramString = url.substr(paramsStart + 1);
      var tokenStart = paramString.indexOf(nome);

      if (tokenStart != -1) {
         var paramToEnd = paramString.substr(tokenStart + nome.length + 1);
         var delimiterPos = paramToEnd.indexOf("&");

         if (delimiterPos == -1) {
            return paramToEnd;
         } else {
            return paramToEnd.substr(0, delimiterPos);
         }
      }
   }
}

function getParameters() {
   var params = new Array();
   var url = window.location.href;
   var paramsStart = url.indexOf("?");
   var hasMoreParams = true;

   if (paramsStart != -1) {
     var paramString = url.substr(paramsStart + 1);
     var params = paramString.split("&");
     for (var i = 0 ; i < params.length ; i++) {
       var pairArray = params[i].split("=");
       if (pairArray.length == 2) {
         params[pairArray[0]] = pairArray[1];
       }
     }
     return params;
   }
}

function getAttributo(el,attr,isselect) {
  var retval = document.getElementById(el)

  if (retval) {
    if (isselect)
      return eval("retval.options[retval.selectedIndex]."+attr)
    else
      return eval("retval."+attr)
  }
}

function vai(desturl, repl) {
  if (desturl && desturl != "") {
    if (repl)
      document.location.replace(desturl)
    else
      document.location = desturl
  }
}

function hideLayers() {
  var a = hideLayers.arguments;
  for (var i = 0; i < a.length; i++) 
	{
    if (document.getElementById(a[i])) 
		{
      document.getElementById(a[i]).style.display = 'none';
    }
  }
}

function showLayers() {
  var a = showLayers.arguments;
  for (var i = 0; i < a.length; i++) 
	{
    if (document.getElementById(a[i])) 
		{
      document.getElementById(a[i]).style.display = 'block';
    }
  }
}

function showHideLayers() {
  var a = showHideLayers.arguments;
  for (var i = 0; i < a.length; i++) 
	{
    if (document.getElementById(a[i])) 
		{
			if (document.getElementById(a[i]).style.display && document.getElementById(a[i]).style.display == 'block')
			{
				document.getElementById(a[i]).style.display = 'none';
			}
			else
			{
				document.getElementById(a[i]).style.display = 'block';
			}
    }
  }
}

/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
// SCRIPT FOR ALLOWING THE USER TO EASILY BOOKMARK YOUR SITE, BY CLICKING ON A LINK ON THE PAGE.
function bookmarkSite(title, url) {
	if (window.sidebar)
	{
		// firefox
		window.sidebar.addPanel(title, url, "");
	}
	else if (window.opera && window.print)
	{
		// opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
	else if (document.all)
	{
		// ie
		window.external.AddFavorite(url, title);
	}
}

// RITORNA IL RIFERIMENTO ALL'OGGETTO FLASH
function getFlashObject(flashObjectId) {
	var oFlash;

	if (window.document[flashObjectId])
	{
		oFlash = window.document[flashObjectId];
	}
	if (navigator.appName.indexOf("Microsoft Internet") == -1)
	{
		if (document.embeds && document.embeds[flashObjectId])
		{
			oFlash = document.embeds[flashObjectId];
		}
	}
	else
	{
		oFlash = document.getElementById(flashObjectId);
	}

	return oFlash;
}

// conta il max numero di caratteri di una textarea e visualizza nel campo countfield il numero di caratteri ancora permessi
function textCounter( field, countfield, maxlimit ) {

	if (!field || !countfield || !maxlimit) return true;

  if ( field.value.length > maxlimit )
  {
    field.value = field.value.substring( 0, maxlimit );
    // TODO: resource bundle
    alert('Il numero massimo di caratteri permesso è ' + maxlimit + ' per questo campo' );
    return false;
  }
  else
  {
    countfield.value = maxlimit - field.value.length;
  }
}




/*
* JWM
*/

// RICERCA NEL SITO
function cerca(form, id, error) {
	if (document.getElementById(id).value.trim() == '')
	{
		alert(error)
	}
	else
	{
		document.forms[form].submit();
	}
}

// RICERCA EVENTI
function cercaEv(fnome) {
  var campot=document.getElementById('ev_tema');
  document.getElementById('n_tema').value=campot.options[campot.selectedIndex].text;
  var campod=document.getElementById('ev_dest');
  document.getElementById('n_dest').value=campod.options[campod.selectedIndex].text;
  var campom=document.getElementById('ev_mese');
  document.getElementById('n_mese').value=campom.options[campom.selectedIndex].text;
  document.forms[fnome].submit();
}

// ritorna true se una variabile o una funzione è definita
function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

/*
* GESTIONE COOKIE
*/
function createCookie(name, value, days) {
  if (days)
	{
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = '; expires=' + date.toGMTString();
  }
	else
	{
    expires = '';
  }
  document.cookie = name + '=' + value + expires + '; path=/';
}

function readCookie(name) {
  var labelName = name + '=';
  var st = document.cookie.split(';');
  for (var i = 0; i < st.length; i++)
	{
    var token = st[i];
    while (token.charAt(0) == ' ') token = token.substring(1, token.length);
    if (token.indexOf(labelName) == 0)
		{
     return token.substring(labelName.length, token.length);
    }
  }
}

function deleteCookie(name) {
  var expDate = new Date();
  expYear = expDate.getYear();
  expDate.setYear(expYear);
  var expires = '; expires=' + expDate.toGMTString();
  document.cookie = name + '=deleted' + expires + '; path=/';
}

/*
* GESTIONE SONDAGGI
*/
function voteForPoll(idPoll, skipCheck, setCookie, alreadyVotedMsg) {

	if (skipCheck) return true;

	var retVal = readCookie('POLL_' + idPoll);

	if (!retVal || retVal != '1')
	{
		if (setCookie)
		{
			createCookie('POLL_' + idPoll, '1', 7);
		}
	
		return true;
	}
	else
	{
		alert(alreadyVotedMsg);

		return false;
	}
}
