var Context = "";                 // il contesto attuale
var Contexts = new Array();       // array con l'elenco dei contesti possibili
var ContextsMap = new Array();    // array con la mappa delle modifiche al posizionamento dei contesti
var debug = "";
var EnableDebug = false;
var characters = "abcdefghijklmnopqrstuvwxyz";
var DefaultContext = 0;
var CurLang = 'en-us';
//
var uaIE;
var uaFirefox;
var uaChrome;
var uaSafari;
var uaSafariVer;
//
// mappa degli spostamenti di posizione dei contesti
// ******************************

ContextsMap[0] = 1;
ContextsMap[1] = 3;
ContextsMap[2] = 4;
ContextsMap[3] = 6; 
ContextsMap[4] = 7; 
ContextsMap[5] = 2;
ContextsMap[6] = 9;
ContextsMap[7] = 12;
ContextsMap[8] = 13; 
ContextsMap[9] = 14;
ContextsMap[10] = 15;
ContextsMap[11] = 10;
ContextsMap[12] = 8; 
ContextsMap[13] = 11;
ContextsMap[14] = 16;
ContextsMap[15] = 5;
ContextsMap[16] = 17;
ContextsMap[17] = 18;
ContextsMap[18] = 19;
//
// ogni contesto ha come valore l'elenco delle keywork che lo identificano
Contexts[0] = "ria|rich internet application|rich internet|rich internet app";
Contexts[1] = "cross browser|internet explorer firefox|firefox safari|firefox chrome|ie ffx";
Contexts[2] = "flex builder|adobe flex|flex ria|flex development|silverlight development|live scroll|ajax datagrid";
Contexts[3] = "access web|visual access|access for web";
Contexts[4] = "web report|web reports|web reporting|web visual|web chart";
Contexts[5] = "ajax|ajax framework|ajax frameworks|ajax asp|ajax xml|using ajax|ajax web|ajax c%23|ajax vb";
Contexts[6] = "java c%23|java net|java vb|java visual basic";
Contexts[7] = "ajax control|web control|web component|ajax widget|web toolkit|web gui|webgui|web form|treeview|asp treeview";
Contexts[8] = "cross database|oracle sql server|oracle db2|database conversion|oracle mysql|oracle postgres|postgres mysql|access sql server|access oracle|access mysql|access postgres";
Contexts[9] = "erwin|er win|database diagram|er schema";
Contexts[10] = "enterprise software|enterprise application|enterprise web";
Contexts[11] = "one click|one|deploy|publishing|install|update";
Contexts[12] = "client server web|web windows";
Contexts[13] = "translation|translate|traduzion|tradurre|multi lingua|multilingua|multi-lingua|multi language|multilanguage|multi-language";
Contexts[14] = "web rad|ajax rad|rad|ajax ide";
Contexts[15] = "ipad|iphone|android|windows phone|phone7";
Contexts[16] = "soa|service oriented architecture|web service";
Contexts[17] = "web application security";
Contexts[18] = "webtop|web top|web desktop";

// **************************************************
// cerca il contesto nella stringa passata
// torna la posizione del contesto nell'array o -1 se nessun contesto è stato identificato
// **************************************************
function ParseKW(s)
{
  var res = -1;
  //
  // cerco due volte in tutti i contesti una delle combinazione di parole specificate
  // l'array dei contesti è ordinato da quello con più token a quello con meno token
  for (var c = 1; c <= 2; c++)
  {
    // parto da 1 perché il percorso 0 non esiste
    for (var i = 0; i < Contexts.length; i++)
    {
      // cerco in ognuno dei token del contesto
      var tokens = Contexts[i].split("|");
      for (var t = 0; t < tokens.length; t++)
      {
        if (tokens[t].replace(" ", "") == "")
          continue;
        //
        // cerco ogni subtoken 
        var ok = true;
        var subTokens = tokens[t].split(" ");
        for (var st = 0; st < subTokens.length; st++)
        {
          if (subTokens[st].replace(" ", "") == "")
            continue;
          //
          var idx = s.indexOf(subTokens[st]);
          //
          // il token deve essere presente nella stringa
          ok = (ok || c==2) && (idx >= 0);
          //
          // il carattere precedente al token dev'essere un carattere speciale (+, ., -)
          // questo per riconoscere "kw=web+ria" e non "webberia"
          ok = ok && ((characters.indexOf(s.charAt(idx-1)) < 0) || idx == 0);
          //
          // se ho trovato tutti i subToken il contesto è riconosciuto
          // al secondo giro mi accontento di una parola qualsiasi
          if (ok && (st == (subTokens.length-1) || c==2))
          {
            // prendo la posizione dell'i-esimo contesto ed esco dal ciclo
            res = i;
            return res;
          }
          else
            continue;
        }
      }
    }
  }
  //
  // torno il risultato (-1 se non ho trovato niente)
  return res;
}

// *******************************
// Gestisce il cambio di posizione dei contesti cercando nella mappa, per 
// poter servire sempre nello stesso modo i link esterni
// ritorna la nuova posizione del vecchio indice
// *******************************
function DecodeContext(c)
{
  try
  {
    if (ContextsMap[c])
      return ContextsMap[c];
    else
      return c;
  }
  catch (ex) 
  {
    return c;
  }
}

function FindContext()
{
  try
  {
    debug = "";
    //
    CheckUserAgent();
    //
    // cerco prima nel parametro ctx
    debug += "<br><b>ctx: </b>" + GetURLParam("ctx");
    var c = parseInt(GetURLParam("ctx"), 10);
    if (c == "" && c != 0)
      c = -1;
    //
    // porto l'indice a 0 based
    c -= 1;
    //
    if (!Contexts[c])
      c = -1;
    //
    if (c >= 0)
    {
			// evento per Google Analytics
			var val = Contexts[c];
			if (pageTracker)
				pageTracker._trackEvent('Contesti', 'CTX', val);
			//
      debug += "<font color=red> ho scelto c: </font>" + c;
      c = DecodeContext(c);
      debug += "<font color=maroon> e l'ho decodificato con: " + c + "</font>";
			debug += "<br>Trak event: Contesti-CTX: " + val;
    }
    //
    // se non ho trovato cerco nelle keywork
    debug += "<br><b>kw: </b>" + GetURLParam("kw");
    if (c == -1)
    {
      var kw = GetURLParam("kw")
      if (kw != "")
        c = ParseKW(kw);
      //
      if (c > -1)
			{
				// evento per Google Analytics
				var val = Contexts[c];
				if (pageTracker)
				pageTracker._trackEvent('Contesti', 'KW', val);
				//
        debug += "<font color=red> ho scelto c: </font>" + c;
				c = DecodeContext(c);
				debug += "<font color=maroon> e l'ho decodificato con: " + c + "</font>";
				debug += "<br>Trak event: Contesti-KW: " + val;
			}
    }
    //
    // se non ho trovato il contesto cerco nell'url
    if (c == -1)
    {
      var u = document.location.href;
      if (u.indexOf("?") > 0)
        u = u.substr(0, u.lastIndexOf("?"));
      debug += "<br><b>location: </b>" + u;
      if (c == -1 || c.length == 0)
      {
        c = ParseKW(u);
        //
        if (c > -1)
				{
					// evento per Google Analytics
					var val = Contexts[c];
					if (pageTracker)
						pageTracker._trackEvent('Contesti', 'URL', val);
					//
          debug += "<font color=red> ho scelto c: </font>" + c;
					c = DecodeContext(c);
					debug += "<font color=maroon> e l'ho decodificato con: " + c + "</font>";
					debug += "<br>Trak event: Contesti-URL: " + val;
				}
      }
    }
    //
    // se non ho trovato il contesto cerco anche nel referrer
    if (c == -1)
    {
      var r = document.referrer;
      if (r.indexOf("?") > 0)
        r = r.substr(r.lastIndexOf("?"));
      debug += "<br><b>referrer: </b>" + r;
      if (c == -1)
      {
        c = ParseKW(r);
        //
        if (c > -1)
				{
					// evento per Google Analytics, solo se non vengo da progamma.com
					if (document.referrer.indexOf('progamma.') <= 0 && document.referrer.indexOf('instantdeveloper.') <= 0)
					{
						var val = Contexts[c];
						if (pageTracker)
							pageTracker._trackEvent('Contesti', 'Referrer', val);
					}
					//
          debug += "<font color=red> ho scelto c: </font>" + c;
					c = DecodeContext(c);
					debug += "<font color=maroon> e l'ho decodificato con: " + c + "</font>";
					debug += "<br>Trak event: Contesti-Referrer: " + val;
				}
      }
    }
    //
    //
    if (c == -1)
      c = DefaultContext;
    //
    // se ho trovato il contesto avviso l'utente
    if (c > -1)
    {
			//
			debug += "<br>Ritornato: "+c;
			if (EnableDebug)
			{
				var dbg = document.getElementById("MyDebug");
				if (dbg)
					dbg.innerHTML = debug;
			}
      return parseInt(c);
    }
  }
  catch (ex) { }
  //
  return 0;
}

// *************************************
// Get cookie value

// name: name of cookie to read
// *************************************
function GetCookie(name) 
{
  // cookie value is after name+"="
  var toSearch = name + "=";
  //
  // a cookie for this document must be present
  if (document.cookie.length > 0) 
  {
    // specified cookie must be present, name+"=" must be found in cookie
    begin = document.cookie.indexOf(toSearch);
    if (begin != -1) 
    {
      // search end of cookie value (first ; after cookie name)
      // move forward the search beginning and perform search
      begin += toSearch.length;
      end = document.cookie.indexOf(";", begin);
      //
      // positioning end of value with ";" position if found, end of cookie otherwise
      end = (end == -1) ? document.cookie.length : end;
      //
      // return cookie value unescaped
      return unescape(document.cookie.substring(begin, end));
    }
  }
  //
  // empty string if no cookie was found
  return "";
}

// **********************************************
// Set an expiring cookie
//
// name: name of cookie to set
// value: value of cookie
// expireDays: number of days before expiration of cookie
// **********************************************
function SetCookie(name, value, expireDays) 
{
  var today = new Date();
  var expirationDate = new Date();
  //
  // calculate expiration date
  expirationDate.setTime(today.getTime() + 24 * expireDays * 3600000);
  //
  // add a cookie specifying expiration date
  document.cookie = name + "=" + escape(value) + ";path=/; expires=" + expirationDate.toGMTString();
}

function GetURLParam(strParamName)
{
  var strReturn = "";    // initially empty string
  //
  // look for parameters, "?" must be present
  var strHref = window.location.href;
  var commaPos = strHref.indexOf("?");
  if (commaPos > -1 )
  {
    // get all url after "?", in lower case
    var strQueryString = strHref.substr(commaPos).toLowerCase();
    //
    // look for specified parameter
    var ParamPos = strQueryString.indexOf(strParamName.toLowerCase() + "=");
    if (ParamPos > -1 )
    {
      // get right part of query string, first param now is the desired one
      var ParamString = strQueryString.substr(ParamPos);
      //
      // split token using "=" as delimiter
      var aParam = ParamString.split("=");
      //
      // 2nd token is value to return
      strReturn = aParam[1];
      //
      // remove possible next params
      if (strReturn.indexOf('&') > 0)
      {
        strReturn = strReturn.substr(0, strReturn.indexOf('&'));
      }
    }
  }
  //
  // return unescaped found value
  return unescape(strReturn);
}

// ********************************************
// verifica lo user agent, se minore di IE6 mostra un messaggio
// ********************************************
function CheckUserAgent()
{
  debug += "Browser: " + navigator.userAgent;
  //
  if (navigator.userAgent.indexOf("MSIE /6") > 0)
    debug += "warning!";
}


function HLMenu(obj, hl)
{
  try
  {
    document.getElementById("trmenu"+obj).className = "TRMenu" + ((hl) ? "Selected" : "");
    document.getElementById("tdmenu"+obj).className = "TDMenu" + ((hl) ? "Selected" : "");
  }
  catch (ex) {}
}

// ******************************************
// Fade passed object to the specified opacity level, at specified speed
//
// Arguments:
// id : HTML object id
// op : new opacity for the object, 100 is completely visible and 0 is transparent
// speed: opacity gap for each Fade() cycle, it represents speed of fading effect
// ******************************************
function Fade(id, op, speed)
{
  // must specify positive values
  if (op < 0 || speed < 0)
    return;
  //
  // there could be errors retrieving HTML object 
  try
  {
    // retrieve HTML specified object
    var obj = document.getElementById(id);
    //
    // calculate new speed, initially equal to speed argument (without decimal)
    var newSpeed = Math.round(speed);
    //
    // remove possible decimal value
    op = Math.round(op);
    //
    // get current object's opacity level
    var curOp = GetOpacity(obj);
    //
    // clear possible previous timer on html object, 
    // there could be an opposite fading pending
    clearTimeout(obj.timeOut);
    //
    // I've to decrease opacity level, change sign to speed
    if (op < curOp)
      newSpeed = newSpeed * -1;
    //
    // I've to reach 100 from a lower current opacity, 
    // and new values is greater than 100
    // calculate newSpeed to reach 100, no more
    if ((curOp + newSpeed) > 100)
    {
      newSpeed = 100 - curOp;
    }
    else  
    {
      // I've to reach a level lower opacity from a greater current value, 
      // and I would go negative.
      // I calculate newSpeed to reach exactly 0
      if ((curOp + newSpeed) < 0)
      {
        newSpeed = 0 - curOp;
      }
    }
    //
    // calculate new opacity
    var newOp = curOp + newSpeed;
    //
    // set object opacity
    SetOpacity(obj, newOp);
    //
    // haven't reached specified opacity level 
    if (newOp != op)
    {
      // set a timeout to cycle again after 20 ms
      obj.timeOut = setTimeout("Fade('"+id+"', " + op + ", " + speed +")", 20);
    }
		else
		{
			var obj = document.getElementById(id);
			if (obj.tagName.toLowerCase() == "div" && obj.NextBackground != null && obj.NextBackground != "")
			{
				var newOp = (obj.NextOp) ? obj.NextOp : 100;
				obj.style.backgroundImage = "url(" + obj.NextBackground + ")";
				obj.NextBackground = null;
				setTimeout("Fade('"+id+"', " + newOp + ", " + speed + ");", 20);
			}
		}
    //
    // I've just reached full opacity, use removeAttribute('filter') to 
    // make IE reuse ClearType (it's automatically disabled on HTML object with filter attribute)
    if (GetOpacity(obj) == 100)
      obj.style.removeAttribute('filter');
  }
  catch (ex) {}    // do nothing on error
}

// ******************************************
// Set passed HTML object opacity level
//
// obj: HTML object
// op: desired opacity level from 0 to 100 (as percentual)
// ******************************************
function SetOpacity(obj, op)
{
  // handle possible firefox decimal values for opacity
  // a value between 0 and 1 is a logical 0
  if (op > 0 && op <= 1)
    op = 0;
  //
  if (IsIE())
    obj.style.filter="alpha(opacity="+op+")";
  if (IsFirefox())
    obj.style.MozOpacity = op/101;
  if (IsSafari())
    obj.style.opacity = op/100;
  if (IsChrome())
    obj.style.opacity = op/100;
}

// ******************************************
// Get passed HTML object opacity level
// returns a value between 0 and 100 (as percentual)
//
// obj: HTML object
// ******************************************
function GetOpacity(obj)
{
  // there could be errors in reading opacity
  try
  {  
    var op = 100;
    //
    // internet explorer uses filter:aplha
    // mozilla style browsers use MoxOpacity
    if (IsIE())
      op = obj.filters['alpha'].Opacity;
    if (IsFirefox())
      op = obj.style.MozOpacity * 100;
    if (IsSafari())
      op = obj.style.opacity *100;
    if (IsChrome())
      op = obj.style.opacity * 100;
    //
    // return, handling possible decimal values returned by browser
    return Math.round(op);
  }
  catch (ex)
  {
    // in error case consider always no transparency
    return 100;
  }
}

function ShowCurrent()
{
  if (currPage >= 0)
	{
		if (document.getElementById("trmenu" + currPage) && document.getElementById("tdmenu" + currPage))
		{
			document.getElementById("tdmenu" + currPage).className = "TDMenuCurrent";
			document.getElementById("trmenu" + currPage).onmouseover = null;
			document.getElementById("trmenu" + currPage).onmouseout = null;
		}
	}
}

// *************************
// Chiude tutte le tabelle dell'array TblArray
// ***************************
function chiudiTabelle(nome)
{
	var i = 0;
	//
	for (i=0; i<TblArray.length; i++)
	{
		var chiudere;
		if ((nome != null) && (TblArray[i] == nome))
			continue;
		//
		chiudere = swapTable(TblArray[i], 0);
		if (chiudere) 
		{
			swapTable(TblArray[i], false);
		}
	}
}

// ***************************************************************
// Apre a chiude una tabella HTML, ritornando se e' aperta o meno
// ***************************************************************
function swapTable(nome, closeAll)
{
	var tbl = document.getElementById(nome);
	var closed = false;
	//
	// 
	if (tbl)
	{
		if (tbl.tagName == "TABLE")
		{
			var rows = tbl.getElementsByTagName("TR");
			var i=0;
			//
			for (i=0; i<rows.length; i++)
			{
				// Salto la prima riga, che considero come il titolo
				if (i == 0) continue;
				//
				rows[i].style.display = (rows[i].style.display == "none") ? ((document.all) ? "block" : "") : "none";
			}
			//
			closed = (rows[i-1].style.display == "none");
		}
		//
		if (closeAll == 1)
		{
			try
			{
				chiudiTabelle(nome);
				//
				document.getElementById(nome).focus();
			}
			catch (ex) {}
		}
		//
		try
		{
			var immagine = document.getElementById('icona'+nome);
			//
			immagine.src = (closed) ? "images/ExpandTbl.gif" : "images/ShrinkTbl.gif";
		}
		catch (ex)	{}
		//
		return (closed) ? false : true;
	}
}

// ************************************
// Prende tutti i tag OBJECT della pagina e gli mette un bordino
// ************************************
function BorderToObjects()
{
  var objs = document.getElementsByTagName("object");
  for (var i = 0; i<objs.length; i++)
  {
    objs[i].style.border = "1px solid #999999";
  }
}

function ScrollUp(id, px)
{
  if (!px)
    px = -5;
  //
  ScrollV(id, px);
}

function ScrollDown(id, px)
{
  if (!px)
    px = 5;
  //
  ScrollV(id, px);
}

function ScrollV(id, px)
{
  var obj = document.getElementById(id + "Div");
  if (obj)
  {
    var cont = document.getElementById(id + "Content");
    var scrollbar= document.getElementById(id + "Scrollbar");
    var perc = 0;
    if (!px)
      px = 5;
    //
    if (obj.scrollTop+px >= 0 && obj.scrollTop+px <= (cont.offsetHeight - obj.offsetHeight))
    {
      obj.scrollTop += px;
      perc = (obj.scrollTop*122)/(cont.offsetHeight - obj.offsetHeight);
      perc = Math.ceil(perc);
      document.getElementById(id + "Cursor").style.marginTop = perc + "px";
      //
      obj.timer = setTimeout("ScrollV('"+id+"', "+px+");", 20);
    }
  }
}

function StopScroll(id)
{
  var obj = document.getElementById(id + "Div");
  if (obj)
  {
    clearTimeout(obj.timer);
  }
}

function ScrollLeft(id, px)
{
  if (!px)
    px = -5;
  //
  ScrollH(id, px);
}

function ScrollRight(id, px)
{
  if (!px)
    px = 5;
  //
  ScrollH(id, px);
}

function ScrollH(id, px, max)
{
  try
  {
    var obj = document.getElementById(id + "Div");
    if (obj)
    {
      if (!px)
        px = 5;
      //
      if (!max)
        max = 0;
      if (max < 0)
        max = 0;
      //
      if (max != obj.scrollLeft)
        obj.scrollLeft += px;
      //
      if (max != obj.scrollLeft)
      {
        obj.timer = setTimeout("ScrollH('"+id+"', "+px+", " + max +");", 20);
      }
      else
      {
        clearTimeout(obj.timer);
        obj.timer = 0;
        OnEndScrollH(id);
      }
      //
      var cursor = document.getElementById(id + "Cursor");
      var cont = document.getElementById(id + "Content");
      var scrollbar = document.getElementById(id + "Scrollbar");
      if (cursor)
      {
        var perc = (obj.scrollLeft*(100))/(cont.offsetWidth - obj.offsetWidth);
        document.getElementById(id + "Cursor").style.marginLeft =  ((scrollbar.clientWidth - cursor.offsetWidth)*perc/100) + "px";
        window.defaultStatus = perc + "% " + document.getElementById(id + "Cursor").style.marginLeft;
      }
    }
  }
  catch (ex)  {}
}

function OnEndScrollH(id)
{
}

function SelTD(divid, idx)
{
  if (idx >= minIdx && idx <= maxIdx && idx != curr)
  {
    var div = document.getElementById(divid + "Div");
    var td = document.getElementById(divid + "" + idx);
    //
    if (div)
    {
      if (!div.timer || div.timer == 0)
      {
        SelectTD(divid + "" + curr, false);
        if (idx >= minIdx && idx <= maxIdx)
        {
          if (div && td)
          {
            var max = td.offsetWidth * (idx-((idx == maxIdx)? 3:2));
            ScrollH(divid, ((curr > idx) ? -10 : 10), max);
            curr = idx;
          }
        }
        SelectTD(divid + "" + curr, true);
      }
      //
      ShowExample(idx);
    }
    //
    document.getElementById(divid + "ScrollLeftIMG").style.display = (curr <= minIdx+1) ? "none": "";
    document.getElementById(divid + "ScrollRightIMG").style.display = (curr >= maxIdx-1) ? "none": "";  
    //
    // se presente un array di comandi da passare all'applicazione lo faccio
    if (CMDArray && CMDArrayIFrame)
    {
      try
      {
        SetIFrameCMD(CMDArrayIFrame, CMDArray[idx-1]);
      }
      catch (ex) {}
    }
  }
}

function PrevTD(divid)
{
  SelTD(divid, curr-1);
}

function NextTD(divid)
{
  SelTD(divid, curr+1); 
}

function SelectTD(id, hl)
{
  var td = document.getElementById(id);
  if (td)
  {
    td.className = "TDSlide" + ((hl) ? "Selected" : "");
  }
}

function HighlightTD(id, idx,  hl)
{
  if (idx ==  curr)
    return;
  //
  var td = document.getElementById(id + "" + idx);
  if (td)
  {
    td.className = "TDSlide" + ((hl) ? "HL" : "");
  }
}

var curr = 0;
var minIdx = 1;
var maxIdx = 1;

function ShowExample(idx)
{
  try
  {
    HideAll();
    document.getElementById("ex"+idx).style.display = "inline-block";
    SetOpacity(document.getElementById("ex"+idx), 0);
    Fade("ex"+idx, 100, 10);
    //
    // lancio anche l'evento locale
    OnShowExample(idx);
  }
  catch (ex) {}
}

function OnShowExample(idx)
{
}

function HideAll()
{
	for (var i=minIdx; i<=maxIdx; i++)
	{
		try
		{
			document.getElementById("ex"+i).style.display = "none";
		}
		catch (ex) { alert(i + ": " + ex.message); }
	}
}

// ****************************************
// Manda una mail ad un utente di progamma.com
// ****************************************
function InviaMail(user, domain)
{
  var d = "progamma.com";
  //
  if (domain)
    d = domain;
	//
	document.location = 'mailto:' + user + "@" + d;
}

function SwapFrame(idx, h)
{
  document.getElementById("iframe" + idx).style.height = h + "px";
  document.getElementById("iframediv" + idx).style.display = "none";
}

function HighlightP(idx, hl)
{
  var p = document.getElementById("p" + idx);
  if (p)
    p.className = ((hl) ? "PHL" : "");
}

function HighlightAllP(hl)
{
  for (var i = 0; i< 100; i++)
  {
    var p = document.getElementById("p"+i);
    if (p)
      HighlightP(i, hl);
  }
}

function SetIFrameCMD(iframeid, cmd)
{
  var iframe = document.getElementById(iframeid);
  if (iframe)
  {
    var c = iframe.contentWindow;
    if (c.RD3_DesktopManager)
    {
      var e = new c.IDEvent("cmd", c.RD3_DesktopManager.WebEntryPoint.Identifier, null, c.RD3_Glb.EVENT_ACTIVE, cmd)
    }
  }
}

function SetIFrameURL(iframeid, url)
{
  var iframe = document.getElementById(iframeid);
  if (iframe)
  {
    iframe.src = url;
    //iframe.document.location.reload();
  }
}

// **********************************************
// Torna true se il browser è InternetExplorer
// **********************************************
function IsIE()
{
	if (uaIE==undefined)
		uaIE = navigator.userAgent.indexOf("MSIE")>-1;
	return uaIE;
}

// **********************************************
// Torna true se il browser è Safari
// **********************************************
function IsSafari(ver)
{
	if (uaSafari==undefined)
	{
		uaSafari = navigator.userAgent.indexOf("Safari")>-1 && navigator.userAgent.indexOf("Chrome") < 0;
		uaSafariVer = parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("Version/")+8));
	}
	//
	if (!ver)
  	return uaSafari;
  else
    return (uaSafari && uaSafariVer==ver);
}


// **********************************************
// Torna true se il browser è Safari
// **********************************************
function IsFirefox()
{
	if (uaFirefox==undefined)
		uaFirefox = navigator.userAgent.indexOf("Firefox")>-1;
	return uaFirefox;
}


// **********************************************
// Torna true se il browser è Chrome
// **********************************************
function IsChrome()
{
	if (uaChrome==undefined)
		uaChrome = navigator.userAgent.indexOf("Safari")>-1 && navigator.userAgent.indexOf("Chrome") > -1;
	return uaChrome;
}

function Animate(obj, type, direction, duration, start, stop)
{
  if (obj)
  {
    obj.AnimationType = type;
    obj.AnimationDuration = duration;
    obj.AnimationDirection = direction;
    obj.AnimationStart = start;
    obj.AnimationStop = stop;
    obj.AnimationStartDate = new Date();
    obj.AnimationTimer = window.setInterval("ObjTick('"+ obj.id+"')", 10)
  }
}

function ObjTick(id)
{
  var obj = document.getElementById(id);
  var d = new Date(); // Istante attuale
 var perc = (d-obj.AnimationStartDate)/obj.AnimationDuration; // Percentuale di completamento (da 0 a 1)
 //
 // Interpolazione quadratica
 perc = Math.sqrt(perc);
 if (perc>=1)
 { 
   perc = 1;
   window.clearInterval(obj.AnimationTimer);
  }
  //
 ObjAnimationTick(obj, perc);
}

function ObjAnimationTick(obj, perc)
{
  if (obj.AnimationType == "fade")
  {
    if (obj.AnimationDirection == "in")
      SetOpacity(obj, perc*obj.AnimationStop);
    else
      SetOpacity(obj, obj.AnimationStop-(perc*obj.AnimationStop));
  }
  //
  if (obj.AnimationType == "scroll")
  {
    if (obj.AnimationDirection == "ver")
      obj.scrollTop = obj.AnimationStart + (perc*(obj.AnimationStop-obj.AnimationStart));
    if (obj.AnimationDirection == "hor")
      obj.scrollLeft = obj.AnimationStart + (perc*(obj.AnimationStop-obj.AnimationStart));
  }
  //
  if (obj.AnimationType == "fold")
  {
    obj.style.height = obj.AnimationStart + (perc*(obj.AnimationStop-obj.AnimationStart)) + "px";
  }
  //
  if (obj.AnimationType == "move")
  {
    if (obj.AnimationDirection == "up" || obj.AnimationDirection == "down")
      obj.style.top = obj.AnimationStart + (perc*(obj.AnimationStop-obj.AnimationStart));
	  if (obj.AnimationDirection == "left" || obj.AnimationDirection == "right")
      obj.style.marginLeft = obj.AnimationStart + (perc*(obj.AnimationStop-obj.AnimationStart)) + "px";
  }
}

function AdjustImage()
{
	var id = document.getElementById("imageDiv");
	var si = document.getElementById("shownImage");
	var w = (document.documentElement.offsetWidth) ? document.documentElement.offsetWidth : window.innerWidth;
	var h = (document.documentElement.clientHeight) ? document.documentElement.clientHeight : window.innerHeight;
	id.style.display = "";
	si.style.display = "";
	//
	// rimpicciolisco l'immagine se devo
	if (si.offsetWidth > w)
	{
		si.style.width = (w * 0.9) + "px";
	}
	//
	var left = (w - si.offsetWidth)/2;
	var top = (h - si.offsetHeight)/2 + document.body.scrollTop;
	if (top - document.documentElement.scrollTop < 10)
		top = 10 + document.documentElement.scrollTop;
	id.style.left = left + "px";
	id.style.top = top + "px";
}

function ShowImage(s, imgSmall)
{
	var w = (document.documentElement.offsetWidth) ? document.documentElement.offsetWidth : window.innerWidth;
	var h = (document.documentElement.clientHeight) ? document.documentElement.clientHeight : window.innerHeight;
	//
	// se non viene specificato il nome dell'immagine cerco il nome del sender e tolgo "-small"
	if (!s || s == "")
	{
		if (imgSmall)
			s = imgSmall.src.replace("-small","");
	  else
		  return;
	}
	//
	var id = document.getElementById("imageDiv");
	var si = document.getElementById("shownImage");
	//
	var sfondo = document.getElementById("sfondoOpaco");
	if (sfondo)
	{
		sfondo.style.top = "0px";
		sfondo.style.left = "0px";
		sfondo.style.width= w + "px";
		sfondo.style.height = document.body.offsetHeight + "px";
		sfondo.style.display = "";
	}
	//
	var ld = document.getElementById("loadingDiv");
	if (ld)
	{
		ld.style.display = "";
		ld.style.top = (((document.documentElement.clientHeight) ? document.documentElement.clientHeight : window.innerHeight) - ld.offsetHeight)/2 + document.body.scrollTop + "px";
		ld.style.left = ((document.body.offsetWidth/2)-(ld.offsetWidth/2)) + "px";
	}
	//
	if (si)
	{
		si.style.height = "auto";
		si.style.width = "auto";
	  si.onload = new Function('AdjustImage();');
		si.src = s;
	}
}

function HideImage()
{
	var si = document.getElementById("shownImage");
	if (si)
	  si.src = "";
	var id = document.getElementById("imageDiv");
	if (id)
		id.style.display = "none";
	var sfondo = document.getElementById("sfondoOpaco");
	if (sfondo)
		sfondo.style.display = "none";
	var ld = document.getElementById("loadingDiv");
	if (ld)
		ld.style.display="none";
}

// *************************************
// Cambia lingua
// *************************************
function SwapLanguage(f, t)
{
  var srvName = "";
  try
  {
    var fromLang = (f == "") ? "" : ("/" + f.toLowerCase());
    var toLang = (t == "") ? "": "/" + t.toLowerCase();
    //
    srvName = window.location.hostname;
    if (srvName == "localhost")
      srvName = "localhost/progamma";    
    //
    // sostituisco la lingua
    var oldUrl = document.location.href;
    var newUrl = oldUrl.toLowerCase().replace(srvName+fromLang, srvName+toLang);
    //
    // se url e' come prima devo cambiare url
    if (newUrl == oldUrl)
    {
      newUrl = oldUrl.replace(srvName, srvName+toLang);
      document.location.href = newUrl;
    }
    //
    if (toLang == '/eng')
      SetCookie('ProGammaLanguage', 'en-us', 7);
    if (toLang == '/ita' || toLang == '')
      SetCookie('ProGammaLanguage', 'it', 7);
    //
    document.location.href = newUrl;
  }
  catch (ex)
  {
    var newUrl = "";
    if (srvName != "")
    	newUrl = "http://"+ srvName +"/"+toLang;
    if (srvName == "localhost")
    	newUrl = "http://localhost/progamma/" + toLang;
    //
    document.location.href = newUrl;
  }
}

function ReadLanguage()
{
  try
  {
		// non faccio niente se c'è un contesto
		if (GetURLParam("ctx") != null && GetURLParam("ctx") != "")
		{
			SetCookie("ProGammaLanguage", "it");
			if (document.location.href.indexOf("/eng") > 0)
				SetCookie("ProGammaLanguage", "en-us");
			return;
		}
		//
    var lang = GetCookie('ProGammaLanguage');
    var langParam = GetURLParam('lang');
    if (langParam > '')
      lang = langParam;
    //
    if (lang == '')
    {
      SetCookie('ProGammaLanguage', (navigator.browserLanguage)?navigator.browserLanguage:navigator.language, 7);
      lang = GetCookie('ProGammaLanguage');
    }
    //
    // nell'url viene usato un valore più human readable
    if (lang == 'ita')
      lang = 'it';
    if (lang == 'eng')
      lang = 'en-us';
    //
    if (lang != CurLang)
    {
      if (lang == 'en-us')
        SwapLanguage('', 'eng');
      if (lang == 'it')
        SwapLanguage('eng', '');
    }
  }
  catch (ex) {}
}
