/***************************/
/***** Diego Gonzalez ******/
/**** Media Consulting *****/
/***************************/

// JavaScript Document
function setKey(evt)
{
    var key 
    if (navigator.appName == "Netscape"){
       key = evt.which;
     }else{
       key = evt.keyCode;
    }
    return key;
}

/*Funzione che permette solo l'inserimento del caratteri numerici all'interno di una text box*/
function soloNumeri(evt) 
{
	key = setKey(evt);
	return (key < 13 || (key >= 48 && key <= 57))
}

/////////////////////////////
// PERMETTE LETTERE E NUMERI //
/////////////////////////////
function AceptNumLett(evt){
    key = setKey(evt);
	return (key <= 13 || (key >= 65 && key <= 90) || (key >= 97 && key <= 122) || (key >= 48 && key <= 57)); 
} 

///////////////////////////////////////////////
// PERMETTE caratteri per page name E NUMERI //
///////////////////////////////////////////////
function CharPageName(evt){
    key = setKey(evt);
	return (key == 45 || key == 95 || key <= 13 || (key >= 65 && key <= 90) || (key >= 97 && key <= 122) || (key >= 48 && key <= 57)); 
} 

///////////////////////////////////////////////
// PERMETTE caratteri per page name E NUMERI //
///////////////////////////////////////////////
function CharPageKeys(evt){
    key = setKey(evt);
	return (key == 91 ||key == 93 || key == 44 || key <= 13 || key <= 34 || (key >= 65 && key <= 90) || (key >= 97 && key <= 122) || (key >= 48 && key <= 57)); 
} 

/////////////////////////////
// PERMETTE LETTERE E NUMERI + " ", "," "."//
/////////////////////////////
function CharPageDescription(evt){
    key = setKey(evt);
	return (key <= 13 || key == 46 || key == 44  || key == 32 || (key >= 65 && key <= 90) || (key >= 97 && key <= 122) || (key >= 48 && key <= 57)); 
}


/////////////////////////////
// PERMETTE LETTERE E NUMERI + " "//
/////////////////////////////
function AceptNumLettSpazio(evt){
    key = setKey(evt);
	return (key <= 13 || key == 32 || (key >= 65 && key <= 90) || (key >= 97 && key <= 122) || (key >= 48 && key <= 57)); 
}

//////////////////////
// NUMERI CON PUNTO //
//////////////////////
function soloNumericonPunto(evt) {
	key = setKey(evt);
	return (key < 13 || key == 46  || (key >= 48 && key <= 57))
}


//////////////////////
//Desabilita l'invio//
//////////////////////
function noInvio (evt) {	
    key = setKey(evt);
	return (key != 13 );
}

var myhttp = null;
var DivContenitore;
var boosostituzione;
var dasostituire;

/*
La funzione getByAjax, se ne ocupa di fare una riquiesta http tramite java
i parametri in input sono
MyUrl	-	Url di richiesta
DivContenitoreAjax	-	Nome del div dove sara inserito il contenuto
datidasostituire	-	nel caso che questa variabile si diversa da vuoto ('') saranno sostituiti
	i valori alla sinistra dei due punti (:) con il valore alla destra dei due punti (:)
	La formatazione di questo parametro e: [VALORE ORIGINALE]:[NUOVO VALORE][;][VALORE ORIGINALE]:[NUOVO VALORE]
	NB. L'ULTIMO DI QUESTI VALORI "NON DEVE PORTARE" IL PUNTO E VIRGOGA (;)
*/

function getByAjax(MyUrl, DivContenitoreAjax, datidasostituire)
{
	if(myhttp == null)
	{
		myhttp = getXMLHTTPRequest()
		if (MyUrl.indexOf('?') != -1)
		{
			modUrl = MyUrl + '&A=' + parseInt(Math.random()*999999);
		}
		else
		{
			modUrl = MyUrl + '?A=' + parseInt(Math.random()*999999);
		}
		myhttp.open ("GET", modUrl , true);
	
		DivContenitore = DivContenitoreAjax;
		myhttp.onreadystatechange = useHttpResponse;
		if (datidasostituire != null && datidasostituire != '')
		{
			boosostituzione = true;
			dasostituire = datidasostituire;
		} 
		else
		{
			boosostituzione = false;
			dasostituire = '';
		}
		myhttp.send(null);
	}
	else
	{
		setTimeout(
				   function()
				   {
					   getByAjax(MyUrl, DivContenitoreAjax, datidasostituire);
					   }
				   ,500);
	}
}

function postByAjax(MyUrl, DivContenitoreAjax, datidasostituire)
{
	if(myhttp == null)
	{
        if (MyUrl.indexOf('?') != -1)
        {
	        modUrl = MyUrl + '&A=' + parseInt(Math.random()*999999);
        }
        else
        {
	        modUrl = MyUrl + '?A=' + parseInt(Math.random()*999999);
        }

        myhttp = getXMLHTTPRequest()
	    myhttp.open ("POST", modUrl , true);
	    var contentType = "application/x-www-form-urlencoded; ; charset=UTF-8;";
	    myhttp.setRequestHeader("Content-Type", contentType);
	    aler('aca esta el problema devo separar el comentario della variable en querystring');
	    query = MyUrl.substring(MyUrl.indexOf('?')+2)
	    myhttp.send(escape(query));
	    
	    DivContenitoreAjax = 'ctl00_colonna_centrale_Commenta_vota_Alto_divGetPost';
	    DivContenitore = DivContenitoreAjax;
	    myhttp.onreadystatechange = useHttpResponse;
	    if (datidasostituire != null && datidasostituire != '')
	    {
		    boosostituzione = true;
		    dasostituire = datidasostituire;
	    } 
	    else
	    {
		    boosostituzione = false;
		    dasostituire = '';
	    }
    }
    else
    {
	    setTimeout(
			       function()
			       {
				       postByAjax(MyUrl, DivContenitoreAjax, datidasostituire);
				       }
			       ,500);
    }
}


function getXMLHTTPRequest()
{
	var req = false;
	try 
	{
		req = new XMLHttpRequest();  // ALtri Browser come Firefox
	}
	
	catch(err1)
	{
		try
			{
				req = new ActiveXObject("Msxml2.XMLHTTP"); // vecche I.E.
			}	
		catch(err2)
		{
			try
			{
				req = new ActiveXObject("Microsoft.XMLHTTP"); // altre I.E.
			}
			catch(err3)
			{
				req = false;
			}
		}	
	}
	return req;
}
	
function useHttpResponse () 
{ 
//sono interessato al valore 4 di readyState ovvero caricato
	if (myhttp.readyState == 4) 
	{
		if (myhttp.status == 200) {
			//è OK per cui lancio qualcosa
		
			//recupero le informazioni sottoforma di stringa
			var mytext= myhttp.responseText;
			//Tratto la Stringa
			
			if (boosostituzione == true && dasostituire != '')
			{
				//Prendo tutti i parametri e converto in un array
				arrparametri = '';
				arrparametri = dasostituire.split(';');
				//percorrotutto l'array
				for (posarrasost = 0; posarrasost  < arrparametri.length; posarrasost ++)
				{
					/*Ricavo la posizione dei due punti*/
					pospunti = arrparametri[posarrasost].indexOf(':');
					/*Ricavo il valore originale*/
					valoreoriginale = arrparametri[posarrasost].substring(0, pospunti)
					/*Ricavo il nuovo valore */
					valorenuovo = arrparametri[posarrasost].substring(pospunti+1);
					intIndexOfMatch = -1
					intIndexOfMatch = mytext.indexOf(valoreoriginale);
					while (intIndexOfMatch > 0){
						// Relace out the current instance.
						mytext = mytext.replace(valoreoriginale, valorenuovo)
						// Get the index of any next matching substring.
						intIndexOfMatch = mytext.indexOf(valoreoriginale);
					}
				}
			}
			//alert(mytext);
			document.getElementById(DivContenitore).innerHTML = mytext;
			myhttp = null;
		}
		else
		{
			//Messaggio di errore
			document.getElementById(DivContenitore).innerHTML = "Si è verificato un errore: " + myhttp.statusText;
			myhttp = null;
		}
	}else
	{ 
		// cioè stato è diverso da 4 visualizzo loader
		document.getElementById(DivContenitore).innerHTML = '<div class="carica" align=center><img src="/Img/ajax-loader.gif"/></div>'
	}
}
	
function compilasotto(obj)
{
	if (document.getElementById('tbElencoSottoCategorie') != null)
	{
		if (obj.checked)
		{
			document.getElementById('tbElencoSottoCategorie').value += obj.value + "; ";
			enabdisabselctcat()

		}
		else
		{
			document.getElementById('tbElencoSottoCategorie').value = document.getElementById('tbElencoSottoCategorie').value.replace(obj.value + '; ', '');
			enabdisabselctcat()
		}
	}
	else
	{
		alert('Manca il campo tbElencoSottoCategorie');
	}
}

function enabdisabselctcat()
{
	if (document.getElementById('tbElencoSottoCategorie'))
	{
		if (document.getElementById('tbElencoSottoCategorie').value != '')
		{
			document.getElementById('Categoria').readonly = true;
		}
		else
		{
			document.getElementById('Categoria').readonly = false;
		}
	}
}

function addLoadEvent(func, param) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') 
	{
		window.onload = function (){func(param)};
	}
	else
	{
		window.onload = function() {
		if (oldonload)
		{
			oldonload();
		}
			func(param);
		}
	}
}


////////////////////////////////////////////////////////////////////////
// FUNZIONE che solo permete l'inseriemnto di una data in un text box //
// UTILIZZO: onKeyUp = "this.value=formateadata(this.value);"        //
//
// 1.0.1 - #002 - 04/05/2005 - sostutito il nome della variabile di nome long in longvar: long generava un errore in Mozilla
//
////////////////////////////////////////////////////////////////////////

function IsNumeric(valor) 
{ 
var log=valor.length; var sw="S"; 
for (x=0; x<log; x++) 
{ v1=valor.substr(x,1); 
v2 = parseInt(v1); 
//Compruebo si es un valor numérico 
if (isNaN(v2)) { sw= "N";} 
} 
if (sw=="S") {return true;} else {return false; } 
} 

var primerslap=false; 
var segundoslap=false; 
function formateadata(fecha) 
{ 
			var longvar = fecha.length; 
			var dia; 
			var mes; 
			var ano; 
			
			if ((longvar>=2) && (primerslap==false)) { dia=fecha.substr(0,2); 
			if ((IsNumeric(dia)==true) && (dia<=31) && (dia!="00")) { fecha=fecha.substr(0,2)+"/"+fecha.substr(3,7); primerslap=true; } 
			else { fecha=""; primerslap=false;} 
			} 
			else 
			{ dia=fecha.substr(0,1); 
			if (IsNumeric(dia)==false) 
			{fecha="";} 
			if ((longvar<=2) && (primerslap=true)) {fecha=fecha.substr(0,1); primerslap=false; } 
			} 
			if ((longvar>=5) && (segundoslap==false)) 
			{ mes=fecha.substr(3,2); 
			if ((IsNumeric(mes)==true) &&(mes<=12) && (mes!="00")) { fecha=fecha.substr(0,5)+"/"+fecha.substr(6,4); segundoslap=true; } 
			else { fecha=fecha.substr(0,3);; segundoslap=false;} 
			} 
			else { if ((longvar<=5) && (segundoslap=true)) { fecha=fecha.substr(0,4); segundoslap=false; } } 
			if (longvar>=7) 
			{ ano=fecha.substr(6,4); 
			if (IsNumeric(ano)==false) { fecha=fecha.substr(0,6); } 
			else { if (longvar==10){ if ((ano==0) || (ano<1900) || (ano>2100)) { fecha=fecha.substr(0,6); } } } 
			} 
			
			if (longvar>=10) 
			{ 
			fecha=fecha.substr(0,10); 
			dia=fecha.substr(0,2); 
			mes=fecha.substr(3,2); 
			ano=fecha.substr(6,4); 
			// Año no viciesto y es febrero y el dia es mayor a 28 
			if ( (ano%4 != 0) && (mes ==02) && (dia > 28) ) { fecha=fecha.substr(0,2)+"/"; } 
			} 
			return (fecha); 
} 

///////////////////////////////////////////////////////////////////
// FUNZIONE CHE REEMPLAZA DELLE STRINGHE 						//
// UTTIOLIZZO: replacestr(stringa,da_sostituire,per_sostituto)	//
// Diego J. M. Gonzalez											//
///////////////////////////////////////////////////////////////////
function replacestr(stringa,da_sostituire,per_sostituto) {
	out = da_sostituire; // replace this
	add = per_sostituto; // with this
	temp = '' + stringa; // temporary holder
	while (temp.indexOf(out)>-1) {
	pos= temp.indexOf(out);
	temp = "" + (temp.substring(0, pos) + add +
	temp.substring((pos + out.length), temp.length));
	}
	return(temp);
}

function PerElimina()
{
    var valToReturnConf;
    valToReturnConf = false;
    ConfElimina = confirm('ATTENZIONE!!!\n\nVeramente si vuole cancellare la voce selezionata?');
    if (ConfElimina)
    {
        valToReturnConf = true;
    }
    else
    {
        valToReturnConf = false;
    }
    return valToReturnConf;
}

function onlydataupload(obj, extensions, divdasostituire)
{
    var objUpload=eval(obj);
    var sUpload=objUpload.value;
    var errore = false;
    
    try
    {
        MyHtml = document.getElementById(divdasostituire).innerHTML.toLowerCase();
        MyHtml = MyHtml.replace('value=' + objUpload.value.toLowerCase(), '');
    }
    catch(e)
    {
        errore = true;
    }

    if(errore != true && sUpload!="")
	{
	    var iExt="";
	    var iDot="";
        if (navigator.appName == "Netscape")
        {
		    iExt=1;
		    iDot=sUpload.indexOf(".");
		}
		else
		{
		    iExt=sUpload.indexOf('\\');
		    iDot=sUpload.indexOf(".");
		}
        if((iExt < 0 ) || (iDot < 0))
		{
            alert("Invalid File Path for Upload!");
            objUpload.focus();
            return false; 
        }
        if(iDot > 0)
		{
            var aUpload=sUpload.split(".");
            //if(aUpload[aUpload.length-1]!=extensions)
            if(extensions.toLowerCase().indexOf(aUpload[aUpload.length-1].toLowerCase()) == -1)
			{
                alert("Solo files del tipo: " + extensions.toUpperCase());
                /*objUpload.focus();
                alert('1) - ' + MyHtml);
                objUpload.outerHTML = "";
                alert('2) - ' + objUpload.outerHTML);*/
                document.getElementById(divdasostituire).innerHTML = '';
                document.getElementById(divdasostituire).innerHTML = MyHtml;
                return false; 
            }
        }
    }
}

//////////////////////////////////////////////////////
// FUNZIONE che mi formatta i numeri in Javascript	//
// EXAMPLE :										//
// formatNumber(3, "$0.00")							//
// $3.00											//
// formatNumber(3.14159265, "##0.####")				//
// 3.1416											//
// formatNumber(3.14, "0.0###%")					//
// 314.0%											//
// formatNumber(314159, ",##0.####")				//
// 314,159											//
// formatNumber(31415962, "$,##0.00")				//
// $31,415,962.00									//
// formatNumber(cat43, "0.####%")					//
// null												//
// formatNumber(0.5, "#.00##")						//
// 0.50												//
// formatNumber(0.5, "0.00##")						//
// 0.50												//
// formatNumber(0.5, "00.00##")						//
// 00.50											//
// formatNumber(4.44444, "0.00")					//
// 4.44												//
// formatNumber(5.55555, "0.00")					//
// 5.56												//
// formatNumber(9.99999, "0.00")					//
// 10.00											//
// UTILIZZO: formatNumber([NUMBER], ["FORMAT"])		//
//////////////////////////////////////////////////////

  var separator = ",";  // use comma as 000's separator
  var decpoint = ".";  // use period as decimal point
  var percent = "%";
  var currency = "$";  // use dollar sign for currency

  function formatNumber(number, format, print) {  // use: formatNumber(number, "format")
    if (print) document.write("formatNumber(" + number + ", \"" + format + "\")<br>");

    if (number - 0 != number) return null;  // if number is NaN return null
    var useSeparator = format.indexOf(separator) != -1;  // use separators in number
    var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
    var useCurrency = format.indexOf(currency) != -1;  // use currency format
    var isNegative = (number < 0);
    number = Math.abs (number);
    if (usePercent) number *= 100;
    format = strip(format, separator + percent + currency);  // remove key characters
    number = "" + number;  // convert number input to string

     // split input value into LHS and RHS using decpoint as divider
    var dec = number.indexOf(decpoint) != -1;
    var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
    var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

     // split format string into LHS and RHS using decpoint as divider
    dec = format.indexOf(decpoint) != -1;
    var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
    var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

     // adjust decimal places by cropping or adding zeros to LHS of number
    if (srightEnd.length < nrightEnd.length) {
      var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
      nrightEnd = nrightEnd.substring(0, srightEnd.length);
      if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

 // patch provided by Patti Marcoux 1999/08/06
      while (srightEnd.length > nrightEnd.length) {
        nrightEnd = "0" + nrightEnd;
      }

      if (srightEnd.length < nrightEnd.length) {
        nrightEn = nrightEnd.substring(1);
        nleftEnd = (nleftEnd - 0) + 1;
      }
    } else {
      for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
        if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
        else break;
      }
    }

     // adjust leading zeros
    sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
    while (sleftEnd.length > nleftEnd.length) {
      nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
    }

    if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
    var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
    output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
    if (isNegative) {
      // patch suggested by Tom Denn 25/4/2001
      output = (useCurrency) ? "(" + output + ")" : "-" + output;
    }
    return output;
  }

  function strip(input, chars) {  // strip all characters in 'chars' from input
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++)
      if (chars.indexOf(input.charAt(i)) == -1)
        output += input.charAt(i);
    return output;
  }

  function separate(input, separator) {  // format input using 'separator' to mark 000's
    input = "" + input;
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++) {
      if (i != 0 && (input.length - i) % 3 == 0) output += separator;
      output += input.charAt(i);
    }
    return output;
  }
  
  
    function goThere1(){
    var list = document.forms['aspnetForm'].ctl00_colonna_centrale_DropDownList1;
    location="pagina.aspx?lang="+list.options[list.selectedIndex ].value
    }
    
    function goThere2(){
    var list = document.forms['aspnetForm'].ctl00_colonna_centrale_DropDownList2;
    location="pagina.aspx?lang="+list.options[list.selectedIndex ].value
    }
    
    function goThere3(){
    var list = document.forms['aspnetForm'].ctl00_colonna_centrale_DropDownList3;
    location="pagina.aspx?lang="+list.options[list.selectedIndex ].value
    }
  
  
  
