﻿// imposta larghezza del container al 
// x% della risoluzione dello schermo
// -- la larghezza impostata resta fissa --
// indice --> valore da 0 a 1
// 0 = 0% ; 0.5 = 50% ; 1 = 100%
// elemento --> stringa IDElemento
function ImpostaLarghezza(indice, IdElemento)
{
  larghezza = screen.width;
  //larghezza=document.body.clientWidth;
  $e(IdElemento).style.width = larghezza * indice;
}

// --------------------------------------------
function RecuperaLarghezza(indice)
{
  return screen.width * indice;
}

// --------------------------------------------  
// restituisce elemento passato per ID
// cross-browser
function ElementoDaId(id_elemento)
{
  // elemento da restituire
  var elemento;
  
  // se esiste il metodo getElementById
  // questo if sarà diverso da false, null o undefined
  // e sarà quindi considerato valido, come un true
  if (document.getElementById) 
    elemento = document.getElementById(id_elemento);
  
  // altrimenti è necessario usare un vecchio sistema
  else 
    elemento = document.all[id_elemento];
  
  // restituzione elemento
  return elemento;
}

// --------------------------------------------
// scrive all'interno di un elemento
// viene passato l'Id dell'elemento e il contenuto
// sa inserire
// idem $setHtml('id_elemento', 'contenuto')
function ImpostaContenuto(id_elment, contenuto)
{
  var e = ElementoDaId(id_elment);
  e.innerHTML = contenuto;
  return true;
}

// --------------------------------------------
// restituisce il contenuto di un elemnto
// idem --> $html(id_elemento')
function RestituisceContenuto(id_element)
{
  var e = ElementoDaId(id_element);
  return e.innerHTML;
}

// --------------------------------------------
function ControllaEmail(valore)
{
  var espressione = /^[_a-z0-9+-]+(\.[_a-z0-9+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/;
  if (!espressione.test(valore)) 
  {
    return false;
  }
  else 
  {
    return true;
  }
}

// --------------------------------------------
// == AJAX == //

// Cross-browser ==========================
function prendiElementoDaId(id_elemento)
{
  // elemento da restituire
  var elemento;
  
  // se esiste il metodo getElementById
  // questo if sarà diverso da false, null o undefined
  // e sarà quindi considerato valido, come un true
  if (document.getElementById) 
    elemento = document.getElementById(id_elemento);
  
  // altrimenti è necessario usare un vecchio sistema
  else 
    elemento = document.all[id_elemento];
  
  // restituzione elemento
  return elemento;
}

// --------------------------------------------
/* Copyright(C) 2005,2006,2007 Salvatore Sanfilippo <antirez@gmail.com>
 * All Rights Reserved. */
// Create the XML HTTP request object. We try to be
// more cross-browser as possible.
function CreaXmlHttpReq(handler)
{
  var xmlhttp = null;
  try 
  {
    xmlhttp = new XMLHttpRequest();
  } 
  catch (e) 
  {
    try 
    {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch (e) 
    {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  xmlhttp.onreadystatechange = handler;
  return xmlhttp;
}

// --------------------------------------------
// An handler that does nothing, used for AJAX requests that
// don't require a reply and are non-critical about error conditions.
function DummyHandler()
{
  return true;
}

// --------------------------------------------
// Shortcut for creating a GET request and get the reply
// This few lines of code can make Ajax stuff much more trivial
// to write, and... to avoid patterns in programs is sane!
function ajaxGet(url, handler)
{
  var a = new Array("placeholder");
  for (var j = 2; j < arguments.length; j++) 
  {
    a[a.length] = arguments[j];
  }
  var ajax_req = CreaXmlHttpReq(DummyHandler);
  var myhandler = function()
  {
    var content = ajaxOk(ajax_req);
    if (content !== false) 
    {
      a[0] = content;
      try 
      {
        return handler.apply(this, a);
      } 
      catch (e) 
      {
        return myDummyApply(handler, a);
      }
    }
  }
  ajax_req.onreadystatechange = myhandler;
  ajax_req.open("GET", url);
  ajax_req.send(null);
}

// --------------------------------------------
// IE 5.0 does not support the apply() method of the function object,
// we resort to this eval-based solution that sucks because it is not
// capable of preserving 'this' and is ugly as hell, but it works for us.
function myDummyApply(funcname, args)
{
  var e = "funcname(";
  for (var i = 0; i < args.length; i++) 
  {
    e += "args[" + i + "]";
    if (i + 1 != args.length) 
    {
      e += ",";
    }
  }
  e += ");"
  return eval(e);
}

// --------------------------------------------
// Add a random parameter to the get request to avoid
// IE caching madness.
function ajaxGetRand(url, handler)
{
  url += (url.indexOf("?") == -1) ? "?" : "&";
  url += "rand=" + escape(Math.random());
  arguments[0] = url;
  try 
  {
    return ajaxGet.apply(this, arguments);
  } 
  catch (e) 
  {
    return myDummyApply(ajaxGet, arguments);
  }
}

// --------------------------------------------
function ajaxOk(req)
{
  if (req.readyState == 4 && req.status == 200) 
  {
    return req.responseText;
  }
  else 
  {
    return false;
  }
}

// --------------------------------------------
// POST METOD ==========================================
// by Guillermo Lovotrico http://www.studiolovotrico.net
function ajaxPost(url, params, handler)
{
  var a = new Array("placeholder");
  for (var j = 2; j < arguments.length; j++) 
  {
    a[a.length] = arguments[j];
  }
  var ajax_req = CreaXmlHttpReq(DummyHandler);
  var myhandler = function()
  {
    var content = ajaxOk(ajax_req);
    if (content !== false) 
    {
      a[0] = content;
      try 
      {
        return handler.apply(this, a);
      } 
      catch (e) 
      {
        return myDummyApply(handler, a);
      }
    }
  }
  
  ajax_req.onreadystatechange = myhandler;
  ajax_req.open("POST", url, true);
  ajax_req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  ajax_req.setRequestHeader("Content-length", params.length);
  ajax_req.setRequestHeader("Connection", "close");
  ajax_req.send(params);
}

//==================================================
// Ajax -> Una variante che imposta il contenuto di un elemento
// by Guillermo Lovotrico http://www.studiolovotrico.net

function MyAjax(metod, url, params, element_id, prop, append, sep)
{
  var e = $e(element_id); // imposta elemento
  var s = sep ? sep : ''; // imposta separatore (in caso di append) 
  var valuevuoto = (e.value) ? true : false; // controlla che ci sia un valore
  var innerHTMLvuoto = (e.innerHTML) ? true : false; // controlla che ci sia un valore
  // imposta prop --> default 'innerHTML'
  if (!prop) 
  {
    prop = 'innerHTML';
  }
  
  // controlla 'metod' --> default 'POST'
  if (metod == 'GET') 
  {
    if (params) 
    {
      url += '?' + params;
    }
    
    ajaxGetRand(url, function(x)
    {
      switch (prop)
      {
        case 'innerHTML':
          if (append) 
          {
            e.innerHTML += (innerHTMLvuoto ? sep : '') + x;
          }
          else 
          {
            e.innerHTML = x;
          }
          break;
          
        case 'value':
          if (append) 
          {
            e.value += (valuevuoto ? sep : '') + x;
          }
          else 
          {
            e.value = x;
          }
          break;
      }
      
    });
  }
  else 
  {
    // metodo 'POST'
    ajaxPost(url, params, function(x)
    {
      switch (prop)
      {
        case 'innerHTML':
          if (append) 
          {
            e.innerHTML += (innerHTMLvuoto ? sep : '') + x;
          }
          else 
          {
            e.innerHTML = x;
          }
          break;
          
        case 'value':
          if (append) 
          {
            e.value += (valuevuoto ? sep : '') + x;
          }
          else 
          {
            e.value = x;
          }
          break;
      }
    });
  }
}

// --------------------------------------------
function AjaxAlert(metod, url, params)
{
  if (!url) 
  {
    return false;
  }
  
  if (metod == 'GET') 
  {
    ajaxGetRand(url + (params ? '?' + params : ''), function(x)
    {
      alert(x);
    });
  }
  else 
    if (!metod || metod == 'POST') 
    {
      ajaxPost(url, params, function(x)
      {
        alert(x);
      });
    }
}

// --------------------------------------------
function AjaxAlertSimple(url)
{
  ajaxGetRand(url, function(x)
  {
    alert(x);
  });
}

// --------------------------------------------
function $elemento(id)
{
  return prendiElementoDaId(id);
}

// --------------------------------------------
function $e(id)
{
  return prendiElementoDaId(id);
}

// --------------------------------------------
function $value(id)
{
  return prendiElementoDaId(id).value;
}

// --------------------------------------------
function $focus(id)
{
  return prendiElementoDaId(id).focus();
}

// --------------------------------------------
function $html(id)
{
  return prendiElementoDaId(id).innerHTML;
}

// --------------------------------------------
function $Html(id)
{
  return prendiElementoDaId(id).innerHTML;
}

// --------------------------------------------
function $HTML(id)
{
  return prendiElementoDaId(id).innerHTML;
}

// --------------------------------------------
function $sethtml(id, html)
{
  prendiElementoDaId(id).innerHTML = html;
}

// --------------------------------------------
function $setHtml(id, html)
{
  prendiElementoDaId(id).innerHTML = html;
}

// --------------------------------------------
function $apphtml(id, html)
{
  prendiElementoDaId(id).innerHTML += html;
}

// --------------------------------------------
function $appHtml(id, html)
{
  prendiElementoDaId(id).innerHTML += html;
}

// --------------------------------------------
function ltrim(stringa)
{
  while (stringa.substring(0, 1) == ' ') 
  {
    stringa = stringa.substring(1, stringa.length);
  }
  return stringa;
}

function rtrim(stringa)
{
  while (stringa.substring(stringa.length - 1, stringa.length) == ' ') 
  {
    stringa = stringa.substring(0, stringa.length - 1);
  }
  return 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;
}
/* *********************************************************************************** */
/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}