var isIE = (navigator.appName.indexOf("Microsoft") >= 0);
var isNokia = (navigator.userAgent.indexOf("SymbianOS") > -1 && navigator.userAgent.indexOf("Nokia") > -1);
/*
 * VARIABILI
 */
var startX;			/* Posizione Iniziale del Mouse */
var startWidth;		/* Larghezza iniziale dell'oggetto */
var resizeTD;		/* oggetto TD da ridimensionare */
var timeSessionID = 0;

/**
 * Schermo
**/
var Screen_ResolutionX;
var Screen_ResolutionY;
if (navigator.appName.indexOf("Microsoft") >= 0) {
	Screen_ResolutionX = screen.width;
	Screen_ResolutionY = screen.height;
}
if (navigator.appName.indexOf("Netscape") >= 0) {
	Screen_ResolutionX = screen.availWidth;
	Screen_ResolutionY = screen.availHeight;
}
/**
 * Funzioni JavaScript
**/
function OnBlurNumeric(obj)
{
	return OnBlurNumeric(obj, -1, -1)
}
function OnBlurNumeric(obj, interi, decimali)
{
	var bRet = false;
	var i;
	if (obj != null) {
		if ( trim(obj.value) == "") {
			obj.value = "";
		} else {
			/* trovo : "," e "." (numero formattato) */
			if ( (i=obj.value.indexOf(".")) > -1 ) {
				if ( (i=obj.value.indexOf(",")) > -1 ) {
					obj.value = obj.value.replace(".", "");
				}
			}
			if ( !isNaN(obj.value.replace(",", ".")) ) {
				obj.value = obj.value.replace(",", ".");
				bRet = true;
			} else {
				obj.value = "";
				LampeggioErrore(obj);
			}
		}
	}

	return bRet;
}
function trim(str) {
	return ltrim(rtrim(str));
}
function ltrim(str) {
	while (str.charAt(0)==' ') { str=str.substring(1); }
	return str;
} 
function rtrim(str) {
	while (str.charAt(str.length-1)==' ') { str = str.substring(0, str.length-1); }
	return str;
}
function LampeggioErrore(input)
{
	//se non faccio cosi' si si commette un errore in fase di lampeggio
	//prende come colore quello sbagliato e rimane sull'errore.
	var CssClassErr = 'TextBox_Error';
	var ok_className = 'TextBox';
	var input_name = input.name;

	if (document.all(input_name).className != CssClassErr) ok_className = document.all(input_name).className;
	setTimeout("document.all('" + input_name + "').className = '" + CssClassErr + "'; ", 0);
	setTimeout("document.all('" + input_name + "').className = '" + ok_className + "'; ", 500);
	setTimeout("document.all('" + input_name + "').className = '" + CssClassErr + "'; ", 1000);
	setTimeout("document.all('" + input_name + "').className = '" + ok_className + "'; ", 1500);
}
function switch_ReadOnly(obj, readonly)
{
	if (obj.className == 'TextBox' || obj.className == 'TextBox_ReadOnly') {
		obj.className = readonly?'TextBox_ReadOnly':'TextBox';
	}
	obj.readOnly = readonly;
}
function document_all(name)
{
	return document.all(name)
}
function select_set_option(ddl, valore)
{
	var opts = getDDLText_Options(ddl);
	for (var i = 0; i < opts.length; i++) {
		if (opts[i].value == valore)
			setDDLText_Option(ddl, i);
		else if (opts[i].selected)
			opts[i].selected = false;

	}
}
function aprihelp_DOText(sInputID, sReturnInputName, sSQL, sFieldsSearch, bSearchNow)
{
	var stringa;
	stringa = 'SQL=' + sSQL + 'FieldsSearch=' + sFieldsSearch;
	if (bSearchNow)
		stringa = stringa + '&cmdCerca=cmdCerca';
	aprihelpOpen(sReturnInputName, stringa);
}
function aprihelp_DOText(sInputID, sReturnInputName, sTableTypeClass, sQuery)
{
	// se disabilitato o è ReadOnly oppure stà facendo il post-back
    if (!document.getElementById(sInputID).disabled)
	{
		var stringa;
		stringa = 'TableTypeClass=' + sTableTypeClass + sQuery;
		aprihelpOpen(sReturnInputName, stringa);
	}
}
function aprihelpOpen(sReturnInputName, sQuery)
{
	var PageName = getApplicationPath() + 'List.aspx?returnInput=' + sReturnInputName;
	var pos = PageName.indexOf('?');

	if (pos > 0)
		var stringa = PageName + '&';
	else
		var stringa = PageName + '?';
	stringa = stringa + sQuery;

	popup = window.open(stringa, 'help', 'height=580,width=580,resizable=yes,status=no,toolbar=no,menubar=no,scrollbars=yes,location=no');
	popup.focus();
}
function getApplicationPath()
{
	var sret;
	var s;
	s = document.location.pathname.toString();
	var pos;
	pos = s.indexOf("/", 1);
	if (!(pos < 0))
	{
		sret = s.substring(0, (pos+1));
	}
	return sret;
}


/*
 * Per gestire il ridimensionamento delle colonne di una tabella.
 */
function ClearResize(tb) {
	startX = null;
	startWidth = null;
	if (resizeTD != null)
		tb.style.cursor = "default";
	resizeTD = null;
}
function OnMouseUp_TABLE(tb)
{
	ClearResize(tb);
}
function OnMouseMove_TABLE(tb)
{
	if (window.event)
	{
		if (resizeTD != null)
		{
			var newwidth = startWidth + (window.event.x - startX);
			if (newwidth < 0) { newwidth = 0; }
			resizeTD.style.width = newwidth + "px";
		} else {
			// Faccio vedere che posso resizare la colonna.
			var td = getMouseCurrentTD(tb);
			if (td != null)
			{
				//td.style.border
				tb.style.cursor = "w-resize";
			} else {
				tb.style.cursor = "default";
			}
		}
	}
}
function OnMouseDown_TABLE(tb) {
	if (window.event)
	{
		startX = window.event.x;

		resizeTD = getMouseCurrentTD(tb);
		if (resizeTD != null) {
			settableLayout_fixed(tb);
			startWidth = resizeTD.clientWidth;
			tb.style.cursor = "w-resize";
		} else
			ClearResize(tb);
	}
}
/*
 * Per settare la proprieta' tableLayout = "fixed";
 * Devo impostare anche le dimensioni reali, altrimenti la
 * tabella cambia ti aspetto.
 */
function settableLayout_fixed(tb) {
	var oldcursor = tb.style.cursor;
	tb.style.cursor = "wait";
	var trs = tb.getElementsByTagName("TR");
	for (var i = 0; i<trs.length; i++)
		trs[i].style.height = trs[i].clientHeight + "px";
	var ths = tb.getElementsByTagName("TH");
	for (var i = 0; i<ths.length; i++)
		ths[i].style.width = ths[i].clientWidth + "px";
	//
	tb.style.tableLayout = "fixed";
	tb.style.cursor = oldcursor;
}
function getMouseCurrentTD(tb) {
	var tdRet = null;
	if (window.event)
	{
		// Prendo le righe
		var trs = tb.getElementsByTagName("TR");
		// Prendo le colonne della prima riga.
		if (trs.length > 0)
		{
			//Prima prova a vedere se ci sono colonne titolo <th>
			var tds = trs[0].getElementsByTagName("TH");
			//Poi vedo se c'è il <td>
			if (tds.length <= 0)
				tds = trs[0].getElementsByTagName("TD");
			for (var i = 0; i<tds.length; i++) {
				var ioffsetLeft = (getPageLeft(tds[i]) + tds[i].clientWidth);
				if (((ioffsetLeft + 2) > window.event.x) && ((ioffsetLeft - 2) < window.event.x)) {
					tdRet = tds[i];
					break;
				}
			}
		}
	}
	return tdRet;
}
/* Restituiscie in pixel la distanza dall'inizio pagina */
function getPageTop(obj) {
	/*if (NN4){
		return obj.pageY 
	}else{*/
	var ioffsetTop = obj.offsetTop;
	var parent = obj.offsetParent;
	while (parent.offsetParent != null) {
		ioffsetTop += parent.offsetTop;
		parent = parent.offsetParent;
	}
	return ioffsetTop;
	/*}*/
}
/* Restituiscie in pixel la distanza dal bordo sinistro della pagina */
function getPageLeft(obj) {
	/*if (NN4){
		return obj.pageY 
	}else{*/
	var ioffsetLeft = obj.offsetLeft;
	var parent = obj.offsetParent;
	while (parent.offsetParent != null) {
		ioffsetLeft += parent.offsetLeft;
		parent = parent.offsetParent;
	}
	return ioffsetLeft;
	/*}*/
}
/**
 * Serve a gestire lo scadere della sessione.
**/
function SessionCountDown(allsecond, currentsecond) {
	var tickTime = 10; //In secondi
	clearTimeout(timeSessionID);
	
	var obj = document.getElementById('objSessionCountDown');
	//Testo acnhe se il Browser è in linea o no (IE only)
	var IsOnLine = (navigator.onLine || navigator.onLine==undefined);
	if ((currentsecond < allsecond) && (IsOnLine)) {
		var new_txt = Math.round((allsecond - currentsecond) / 60); //Minuti
		innerText(obj, "- " + new_txt + "min");
		//quando manca 1/5
		if (currentsecond >= (allsecond - (allsecond / 5)) && obj.className != "sessionWarning")
			obj.className = "sessionWarning";
		timeSessionID = setTimeout("SessionCountDown(" + allsecond + ", " + (currentsecond+tickTime) + ")", (tickTime * 1000));
	} else if ((currentsecond >= allsecond) || (!IsOnLine)) {
		obj.className = "sessionOff";
		innerText(obj, "");
	}
}
function innerText(obj, text) {
	var new_ch = document.createTextNode(text);
	if (obj.childNodes[0])
		obj.replaceChild(new_ch, obj.childNodes[0]);
	else
		obj.appendChild(new_ch);
}
function getinnerText(obj) {
	var sRet = null;
	if (obj)
		if (obj.childNodes[0])
			sRet = obj.childNodes[0].nodeValue;
	return sRet;
}

/**
 * Funzioni per Gestire i Cookies da JavaScript
**/
function GetCookie(name)
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen)
	{
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
		return getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}
function getCookieVal(offset)
{
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
		endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}
function SetCookie(name, value) 
{
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expdate_default = new Date(); //Default 1 anno
	expdate_default.setTime(expdate_default.getTime() + (24 * 60 * 60 * 1000 * 365));
	var expires = null;//(argc > 2) ? argv[2] : expdate_default;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape(value) +
		((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
		((path == null) ? "" : ("; path=" + path)) +
		((domain == null) ? "" : ("; domain=" + domain)) +
		((secure == true) ? "; secure" : "");
}
function DeleteCookie(name)
{
	var exp = new Date();
	// This cookie is history (changed -1 to make it previous time)
	exp.setTime (exp.getTime() - 1000000000);
	var cval = GetCookie(name);
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
/* Posizione del Puntatore rispetto all'intera pagina */
function MousePointer()
{
	var iebodyreal = (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
	var curX = (!isIE)?e.pageX : (event.x+iebodyreal.scrollLeft);
	var curY = (!isIE)?e.pageY : (event.y+iebodyreal.scrollTop);
	return {x:curX, y:curY};
}
/* Posizione del Puntatore Relativo alla parte Visibile */
function MousePointerCurrent()
{
	var iebodyreal = (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
	var curX = (!isIE)?e.X : (event.x);
	var curY = (!isIE)?e.Y : (event.y);
	return {x:curX, y:curY};
}
function getBody() { return document.getElementsByTagName("body").item(0); }
function SetVisible(obj, visible)
{
	if (visible)
	{
		obj.style.visibility = "visible";
		obj.style.display = "inline";
	}
	else
	{
		obj.style.visibility = "hidden";
		obj.style.display = "none";
	}
}
function IsVisible(obj)
{
	return ((obj.style.visibility == "visible" || obj.style.visibility == "") 
		&& (obj.style.display == "inline" || obj.style.display == ""))
}
/**
 * Mostra l'oggetto passsato come se fosse un tooltip (posizione e style)
**/
function ShowAsToolTip(objectHTML)
{
	objectHTML.style.position = 'absolute';
	objectHTML.style.backgroundColor = 'lightyellow';
	objectHTML.style.border = '1px solid black';
	objectHTML.style.padding = '2px';
	MoveObjectToMouse(objectHTML);
}
function MoveObjectToMouse(objectHTML)
{
	var mp = MousePointer();
	var b = getBody();
	if (b.clientHeight > MousePointerCurrent().y + 14 + objectHTML.clientHeight)
		objectHTML.style.top = (mp.y + 14) + 'px';
	else
		objectHTML.style.top = (mp.y - 6 - objectHTML.clientHeight) + 'px';
	objectHTML.style.left = (mp.x + 12) + 'px';
}
/*
 * Creo il Tootip per l'articolo
 * createobjectID= Nome dell'oggetto da creare (serve per poi ripassarlo al distruttore)
*/
/*function CreateToolTipArticolo(createobjectID, oid_tbBaseProducts)
{
	alert('Non Implementato - Cancellare i file Temporanei del Browser e riprovare');
}*/
function MoveToolTipArticolo(objectID)
{
	var odiv = document.getElementById(objectID);
	if (odiv != null)
		MoveObjectToMouse(odiv);
}
function CreateToolTipArticolo(createobjectID, fileName_tbBaseProducts)
{
	if (fileName_tbBaseProducts == '')
		return;
	var odiv; //Contenitore
	var odettImg; //Immagine (piccola) dell'articolo
	odiv = document.createElement('div');
	odiv.id = createobjectID;
	ShowAsToolTip(odiv);
	// aggiungo l'oggetto al Body HTML
	getBody().appendChild(odiv);

	odettImg = document.createElement('img');
	odettImg.border = '0';
	odettImg.src = fileName_tbBaseProducts;
	odiv.appendChild(odettImg);
}
function DropToolTipArticolo(createobjectID)
{
	var o = document.getElementById(createobjectID);
	if (o != null)
		getBody().removeChild(o);
}

