/**
 * GESTISCE IL TOGGLE DELL'ESPANSIONE DEL DIV CATEGORIA
 * @param selettore
 * @return
 */
function manageSelettore(selettore)
{
	var targetRes = "div_sottocategoria_"+selettore;
	var targetSelApri   = "selettore_"+selettore+"_apri";	
	var targetSelChiudi = "selettore_"+selettore+"_chiudi";	

	//alert(targetRes);
	if ($(targetRes).style.display == "inline")
	{
		$(targetRes).style.display       = "none";
		$(targetSelApri).style.display   = "inline";
		$(targetSelChiudi).style.display = "none";
	}
	else
	{
		$(targetRes).style.display       = "inline";
		$(targetSelApri).style.display   = "none";
		$(targetSelChiudi).style.display = "inline";
	}
}

/**
 * KEY PRESSED HANDLER - gestisce il submit di un form intercettando l'invio da un input text
 * @param event
 * @return
 */
function keyPressedHandler(event)
{
	var key = event.which || event.keyCode;
	switch (key) {
		case Event.KEY_RETURN:
			return true;
	}
	return false;
}

/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   interger  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
var marked_row = new Array;
function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function

//---------------------------------------------------------------------- //
//-- Gestione della validazione dei form                              -- //
//-- v.2 - S.Puricelli - marzo 2009									  -- //
//---------------------------------------------------------------------- //
function validateForm(typeEsito, nome_form)
{
	//alert(typeEsito)
	var allInput = Form.getElements( nome_form );
	return executeValidateForm(typeEsito, allInput, nome_form);
}

function executeValidateForm(typeEsito, allInput, nome_form)
{
	//var allInput = $A($$('input'));
	typeEsito    = (typeEsito == "") ? "alert" : typeEsito;
	var target	 = typeEsito;
	var esito    = "OK";
	var messaggi = 
		new Array(
				"e' obbligatorio e deve essere valorizzato", 								// 0
				"deve essere un numero intero",												// 1
				"non ha un formato valido (Es. 25.10%)",									// 2
				"non ha un formato valido (Es. 25,10 E)",									// 3
				"non pu&ograve; essere pari a 0",											// 4
				"non ha un formato valido (Es. username@dominio.it)",						// 5
				"non coincidono"															// 6
				);

	allInput.each(function(i, index) 
	{
		if (i.getAttribute("validationType") && esito == "OK") 
		{
			var validationType = i.getAttribute("validationType");
				validationType = validationType.split(".");
			var validationLabel = i.getAttribute("validationLabel");

			validationType.each(function(type, x)
				{
					if (esito == "OK")
					{
						var vType = type.split("-");
						var vTmp  = $(i).value;
						
						//alert(vType[0])
						switch (vType[0]) {
						case "notEmpty":						
							if (isBlank ($F(i))) {
								esito = "KO";
								if (typeEsito == "alert")
									alert("Il campo " + validationLabel + " " + messaggi[vType[1]]);
								else
									$(target).innerHTML = "Il campo " + validationLabel + " " + messaggi[vType[1]];
								$(i).focus();
								return false;
							}
							break;
						case "text":
							
							break;
						case "isDouble":
							if ($F(i).indexOf(",") >= 0)   vTmp = $F(i).gsub(',', '.');
							if ($F(i).indexOf("%") >= 0) { vTmp = $F(i).gsub('%', ''); $(i).value = $F(i).gsub('%', ''); } 
							if ($F(i).indexOf("€") >= 0) { vTmp = $F(i).gsub('€', ''); $(i).value = $F(i).gsub('€', ''); }
							
							if (!isBlank (vTmp) && isNaN(vTmp) && !IsDouble(vTmp)) {
								esito = "KO";
								if (typeEsito == "alert")
									alert("Il campo " + validationLabel + " " + messaggi[vType[1]]);
								else
									$(target).innerHTML = "Il campo " + validationLabel + " " + messaggi[vType[1]];
								return false;
							}
						break;
						case "isInt":
							if (!isBlank ($F(i)) && !isInt($F(i))) {
								esito = "KO";
								if (typeEsito == "alert")
									alert("Il campo " + validationLabel + " " + messaggi[vType[1]]);
								else
									$(target).innerHTML = "Il campo " + validationLabel + " " + messaggi[vType[1]];
								return false;
							}
						break;
						case "notNull":
							if ($F(i).indexOf(",") >= 0)   vTmp = $F(i).gsub(',', '.');
							if (vTmp == null || Math.round(vTmp) == 0) {
								esito = "KO";
								if (typeEsito == "alert")
									alert("Il campo " + validationLabel + " " + messaggi[vType[1]]);
								else
									$(target).innerHTML = "Il campo " + validationLabel + " " + messaggi[vType[1]];
								return false;
							}
						break;
						case "eMail":
							if ( !isBlank($F(i)) && !eMailCheck( $F(i) ) ) {
								esito = "KO";
								if (typeEsito == "alert")
									alert("Il campo " + validationLabel + " " + messaggi[vType[1]]);
								else
									$(target).innerHTML = "Il campo " + validationLabel + " " + messaggi[vType[1]];
								$(i).value = "";
								$(i).focus();
								return false;
							}
						break;
						case "Equals":
							// due campi devono essere uguali // Equals-6-pwd // tipoControllo-tipoMsg-inputDiParagone
							var labelInputDiParagone = $(vType[2]).getAttribute("validationLabel");
							if ( $F(vType[2]) != $F(i) ) {
								esito = "KO";
								if (typeEsito == "alert")
									alert("I campi " + labelInputDiParagone + " e " + validationLabel + " " + messaggi[vType[1]]);
								else
									$(target).innerHTML = "I campi " + labelInputDiParagone + " e " + validationLabel + " " + messaggi[vType[1]];
								$(i).value = "";
								$(vType[2]).value = "";
								$(vType[2]).focus();
								return false;
							}
						break;
						case "mandatoryRadio":
							var allRadio = $(nome_form).getInputs('radio', $(i).name);
							var atLeastOneChecked = false;
							
							allRadio.each(function(radio, z) {
								if ($(radio).checked)
									atLeastOneChecked = true;
							});
							if (!atLeastOneChecked)
							{
								if (typeEsito == "alert")
									alert("Il campo " + validationLabel + " " + messaggi[vType[1]]);
								else
									$(target).innerHTML = "Il campo " + validationLabel + " " + messaggi[vType[1]];
								esito = "KO";
								return false;
							}
							break;

						default:
							break;
						}
					}
				}
			);
		}
	});
	if (esito == "KO") return false;
	else return true;
}

var isBlank_re = /\S/;
function isBlank (s) {
	return String (s).search (isBlank_re) == -1;
}

IsDouble = function(Value) {
	//var n = trim(Value);
	//return n.length>0 && !(/[^0-9.]/).test(n) && (/\.\d/).test(n);
	
	return (/^(?=.*[1-9].*$)\d{0,7}(?:\.\d{0,9})?$/).test(Value);
}

function isInt(x) 
{
 var y=parseInt(x);
 if (isNaN(y)) return false;
 return x==y && x.toString()==y.toString();
}

function trim(s)
{
	return s.replace(/^\s+|\s+$/g, "");
}

function eMailCheck( str )
{
	var at		= "@";
	var dot		= ".";
	var lat		= str.indexOf(at);
	var lstr	= str.length;
	var ldot	= str.indexOf(dot);
	
	switch ( true )
	{
		case ( str.indexOf(at) == -1 ):
		case ( str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr ):
		case ( str.indexOf(dot)== -1 || str.indexOf(dot)== 0 || str.indexOf(dot) == lstr ):
		case ( str.indexOf(at,(lat+1)) != -1 ):
		case ( str.substring(lat-1,lat) == dot || str.substring(lat+1,lat+2) == dot ):
		case ( str.indexOf(dot,(lat+2)) == -1 ):
		case ( str.indexOf(" ")!=-1 ):
			return false;
			break;
	}
	return true;
}
//---------------------------------------------------------------------- //

//---------------------------------------------------------------------- //
//-- visualizza una immagine data in dimensioni ridotte stabilite ------ //
//---------------------------------------------------------------------- //
function resizeImage ( img, iwidth, iheight )
{	
	/**
	 * prende i dati da una immagine esistente 
	 * e setta le dimensioni massime da darle
	 */
	var image     = $(img);
	var percRiduzione = "";
	// var width     = Math.round(image.width);
	// var height 	  = Math.round(image.height);
	var width     = image.width;
	var height 	  = image.height;
	var maxWidth  = iwidth; // larghezza massima della copertina
	var maxHeight = iheight; // altezza massima della copertina
	
	if ( width > height )
	{
		// -- calcolo la percentuale di riduzione sulla larghezza -- //
		//alert("riduzione in larghezza con larghezza immagine: " + width);
		percRiduzione = maxWidth * 100 / width;
		percRiduzione = Math.round( 100 - percRiduzione );
	}
	else
	{
		// -- calcolo la percentuale di riduzione sull'altezza -- //
		//alert("riduzione in altezza con altezza immagine: " + height);
		percRiduzione = maxHeight * 100 / height;
		percRiduzione = Math.round( 100 - percRiduzione );		
	}	
	
	// -- applico la percentuale di riduzione ai due lati -- //
	var newWidth  = width  - (width  * percRiduzione / 100);
	var newHeight = height - (height * percRiduzione / 100);
	
	// -- applico il resize all'immagine -- //
	//document.write('<img src="' + img + '" width="' + newWidth + '" height="' + newHeight + '" />');
	image.setAttribute("width",  newWidth);
	image.setAttribute("height", newHeight);	
	
	/*
	if (getElem(img)) {
		getElem(img).style.display='inline';
		//alert('if '+image.width+' == '+Math.round(newWidth)+' && '+image.height+' == '+Math.round(newHeight));
	} else {
		sInt = setInterval(resizeCover ( ''+img+'', ''+iwidth+'', ''+iheight+'' ),1000);
		//alert('else '+image.width+' == '+Math.round(newWidth)+' && '+image.height+' == '+Math.round(newHeight));		
	}	
	*/
}
//---------------------------------------------------------------------- //