

function getBrowserType()
{
	try{this.AgentName=navigator.userAgent.toLowerCase();}catch(e){this.AgentName="";}
	if (this.IsDom&&navigator.appName=="Netscape")
		return("n4");
	else if (this.AgentName.indexOf("safari")>=0)
		return("sf");
	else if (this.AgentName.indexOf("opera")>=0)
		return("op");
	else if (this.AgentName.indexOf("mac")>=0)
		return("mc");
	else return("ie");
}

function getBrowserTypeOLD()
{
	
	var retValue = 'n4'; // valore di default se non riconosce nessun tipo
	
	if ( (navigator.userAgent.toLowerCase().indexOf('msie') + 1) ) 
		// Internet explorer
		retValue = 'ie';
	else
		if (!(navigator.userAgent.toLowerCase().indexOf('compatible') + 1)) 
			// Netscape 4 o 6
			if (navigator.userAgent.toLowerCase().charAt(8)==4)
				// Netscape 4
				retValue = 'n4'; 
			else 
				if (navigator.userAgent.toLowerCase().charAt(8)==5)
					// Netscape 6
					retValue = 'n6';
					
	return(retValue);
}


function findRootFrame(currentFrame)
{
	return(window.top);
}


function refreshTopBarFrame()
{
	// aggiorno il frame topbar
	if (window.top.frames['topbar'])
		window.top.frames['topbar'].window.location.reload();
}

function refreshDesktopFrame()
{
	// aggiorno il frame topbar
	if (window.top.frames['desktop'])
		window.top.frames['desktop'].window.location.reload();
}

function redirectDesktopFrame(sUrl)
{
	// aggiorno il frame topbar
	if (window.top.frames['desktop'])
		window.top.frames['desktop'].window.location = sUrl;
}


function setFrameUrl(frame, url)
{
	// aggiorno il frame specificato
	if (frame)
	{
		frame.location = url;
	}
}


function SetUniqueRadioButton(nameregex, current)
{
   re = new RegExp(nameregex);
   for(i = 0; i < document.forms[0].elements.length; i++)
   {
      elm = document.forms[0].elements[i]
      if (elm.type == 'radio')
      {
         if (re.test(elm.name))
         {
            elm.checked = false;
         }
      }
   }
   current.checked = true;
}


function redirectTabSelected(oTab)
{
	if (oTab != null)
	{
		if ((oTab.Key != null) && (oTab.Key != ""))
		{
			// ottengo la url attuale
			var sOriginalUrl = String(this.location);
			var sUrl = "";
			
			// ottengo il parametro eventualmente gia' presente e lo cancello
			var iPos = sOriginalUrl.indexOf("Tab=");
			if (iPos != -1)
			{
				sUrl = sOriginalUrl.substring(0, iPos);
			}
			else
			{
				sUrl = sOriginalUrl;
			}
			
			// aggiungo il parametro del tab selezionato
			if (sOriginalUrl.indexOf('?') != -1)
			{
				sUrl = sUrl + "&Tab=" + oTab.Key;
			}
			else
			{
				sUrl = sUrl + "?Tab=" + oTab.Key;
			}
			
			// effettuo il redirect
			this.location = sUrl;
		}
	}
}


function redirectIFrameAuto(sUrl)
{
	//alert(this._currentframe.name);
	switch (this.name)
	{
		case 'IFrameLoginUrl':
			var sOriginalUrl = String(this.parent.location);
			var iParamStart = sOriginalUrl.indexOf('IFrameLoginUrl');
			if (iParamStart != -1)
			{
				iParamStart += 14;
				sParamText = sOriginalUrl.substring(iParamStart);
				
				var iParamEnd = sParamText.indexOf('&');
				if (iParamEnd == -1)
				{
					iParamEnd = sOriginalUrl.length;
				}
				
				sUrl = sOriginalUrl.substring(0, iParamStart) + escape(sUrl) + sOriginalUrl.substring(iParamEnd);
			}
			else
			{
				if (sOriginalUrl.indexOf('?') != -1)
				{
					sUrl = sOriginalUrl + "&IFrameMainUrl=" + escape(sUrl);
				}
				else
				{
					sUrl = sOriginalUrl + "?IFrameMainUrl=" + escape(sUrl);
				}
			}
			this.parent.location = sUrl;
			break;
		case 'IFrameMainUrl':
			var sOriginalUrl = String(this.parent.location);
			var iParamStart = sOriginalUrl.indexOf('IFrameMainUrl');
			if (iParamStart != -1)
			{
				iParamStart += 14;
				sParamText = sOriginalUrl.substring(iParamStart);
				
				var iParamEnd = sParamText.indexOf('&');
				if (iParamEnd == -1)
				{
					iParamEnd = sOriginalUrl.length;
				}
				
				sUrl = sOriginalUrl.substring(0, iParamStart) + escape(sUrl) + sOriginalUrl.substring(iParamEnd);
			}
			else
			{
				if (sOriginalUrl.indexOf('?') != -1)
				{
					sUrl = sOriginalUrl + "&IFrameMainUrl=" + escape(sUrl);
				}
				else
				{
					sUrl = sOriginalUrl + "?IFrameMainUrl=" + escape(sUrl);
				}
			}
			this.parent.location = sUrl;
			break;
		default:
			this.location = sUrl;
			break;
	}
}


// ************ IFRAME auto resize

function AutoVerticalResizeIFrame(sIFrameName)
{			
	/***********************************************
	* IFrame SSI script II- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
	* Visit DynamicDrive.com for hundreds of original DHTML scripts
	* This notice must stay intact for legal use
	***********************************************/

	//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
	//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
	//var iframeids = ["myframe"];
	var iframeids = sIFrameName;

	//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
	var iframehide = "no";

	var getFFVersion = navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
	var FFextraHeight = parseFloat(getFFVersion) >= 0.1 ? 16 : 0; //extra height in px to add to iframe in FireFox 1.0+ browsers

	function resizeCaller() 
	{
		var dyniframe = new Array();
		for (i=0; i<iframeids.length; i++)
		{
			if (document.getElementById)
			{
				resizeIframe(iframeids[i]);
			}
				
			//reveal iframe for lower end browsers? (see var above):
			if ((document.all || document.getElementById) && iframehide=="no")
			{
				var tempobj = document.all ? document.all[iframeids[i]] : document.getElementById(iframeids[i]);
				tempobj.style.display = "block";
			}
		}
	}

	function resizeIframe(frameid)
	{
		var currentfr = document.getElementById(frameid);
		if (currentfr && !window.opera)
		{
			currentfr.style.display = "block";
			if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
			{
				currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight; 
			}
			else if (currentfr.Document && currentfr.Document.body.scrollHeight) //ie5+ syntax
			{
				currentfr.height = currentfr.Document.body.scrollHeight;
			}
			if (currentfr.addEventListener)
			{
				currentfr.addEventListener("load", readjustIframe, false);
			}
			else if (currentfr.attachEvent)
			{
				currentfr.detachEvent("onload", readjustIframe); // Bug fix line
				currentfr.attachEvent("onload", readjustIframe);
			}
		}
	}

	function readjustIframe(loadevt) 
	{
		var crossevt = (window.event) ? event : loadevt;
		var iframeroot = (crossevt.currentTarget) ? crossevt.currentTarget : crossevt.srcElement;
		if (iframeroot)
		{
			resizeIframe(iframeroot.id);
		}
	}

	function loadintoIframe(iframeid, url)
	{
		if (document.getElementById)
		{
			document.getElementById(iframeid).src = url;
		}
	}

	if (window.addEventListener)
	{
		window.addEventListener("load", resizeCaller, false);
	}
	else if (window.attachEvent)
	{
		window.attachEvent("onload", resizeCaller);
	}
	else
	{
		window.onload = resizeCaller;
	}
}
		
// ************


function setHelp(helpText)
{
	// memorizzo il tipo di browser utilizzato dal client
	var browserType = getBrowserType();
	
	// trovo il frame root del nostro sito
	var helpFrame = window.top.frames['topbar'];
					
	// aggiorno il testo del titolo
	if (helpFrame != null)
	{
		switch (browserType)
		{
			case 'ie':
			case 'n6':
				if (helpFrame.document.getElementById('HelpBox') != null)
				{
					helpFrame.document.getElementById('HelpBox').innerHTML = helpText;
					
					if (helpText != '')
					{
						var noInfiniteLoop = 0;
						while ((noInfiniteLoop < 200) && (helpFrame.document.getElementById('HelpBox').offsetHeight > 66))
						{
							
							helpFrame.document.getElementById('HelpBox').innerHTML = '';
							helpFrame.document.getElementById('HelpBox').style.width = helpFrame.document.getElementById('HelpBox').offsetWidth + 10;
							helpFrame.document.getElementById('HelpBox').innerHTML = helpText;
							noInfiniteLoop++;
						}
					}
					else
					{
						helpFrame.document.getElementById('HelpBox').style.width = 260;
						helpFrame.document.getElementById('HelpBox').style.height = 66;
						helpFrame.document.getElementById('HelpBox').style.left = 0;
					}
				}
				break;
			case 'n4':
				if (helpFrame.document.HelpBox != null)
					helpFrame.document.HelpBox.document.open();
					helpFrame.document.HelpBox.document.writeln(helpText);
					helpFrame.document.HelpBox.document.close();
				break;
		}
	}
}

function setFocus(controlToFocus)
{
	if (controlToFocus != null)
	{
		controlToFocus.focus();
	}
}

function goToBasket()
{
	
	if ((window.top.frames['desktop']) && (window.top.frames['topbar']))
		window.top.frames['desktop'].document.location = window.top.frames['topbar'].document.getElementById('BasketLink').href;
	return(false);
}

function refreshBasketPreview(sMainLabel, sBasketURL, sGoToBasketLabel, sOrderNumberLabel, sBasketUID, sBasketAlfacode, sNumRowsLabel, sNumRows, sDateLabel, sDate, sLastInsertedLabel, sLastInserted, bMultiDesktop)
{
	var sBasketPreview = '';
	
	if ((sBasketAlfacode != null) && (sBasketAlfacode != ''))
	{
		sBasketPreview += "<TABLE class='desktop_base12' id='tBasketPreview' cellSpacing='1' cellPadding='1' width='140px' border='0'>";
		sBasketPreview += "<TR>";
		sBasketPreview += "		<TD class='desktop_headingA' vAlign='middle' noWrap align='center' colSpan='2'>";
		sBasketPreview += "			" + sMainLabel + "&nbsp" + "<INPUT class=modifier_smaller type=button onclick='return(goToBasket());' value='" + sGoToBasketLabel + "'>";
		sBasketPreview += "		</TD>";
		sBasketPreview += "</TR>";
		sBasketPreview += "<TR>";
		sBasketPreview += "		<TD class='desktop_base11' noWrap>";
		if (bMultiDesktop == 'true')
			sBasketPreview += "			<span class='modifier_smaller'>" + sOrderNumberLabel + "</span>&nbsp<a id='BasketLink' href='#' onclick='javascript:SetCurrentTabUrl(\"/Basket/AddChange.aspx?eBasketUID=" + sBasketUID + "\");'>" + sBasketAlfacode + "</a>";
		else
			sBasketPreview += "			<span class='modifier_smaller'>" + sOrderNumberLabel + "</span>&nbsp<a id='BasketLink' href='/Basket/AddChange.aspx?eBasketUID=" + sBasketUID + "' target='desktop'>" + sBasketAlfacode + "</a>";
		sBasketPreview += "		</TD>";
		sBasketPreview += "		<TD class='desktop_base11' noWrap>";
		sBasketPreview += "			<span class='modifier_smaller'>" + sNumRowsLabel + "</span>&nbsp;<span class='modifier_smaller'>" + sNumRows + "</span>";
		sBasketPreview += "		</TD>";
		sBasketPreview += "</TR>";
		sBasketPreview += "<TR>";
		//sBasketPreview += "		<TD class='desktop_base11' noWrap>";
		//sBasketPreview += "			<span class='modifier_smaller'>" + sDateLabel + "</span>&nbsp;<span class='modifier_smaller'>" + sDate + "</span>";
		//sBasketPreview += "		</TD>";
		sBasketPreview += "		<TD class='desktop_base11' noWrap colspan='2'>";
		sBasketPreview += "			<span class='modifier_smaller'>" + sLastInsertedLabel + "</span>&nbsp;<span class='modifier_smaller'>" + sLastInserted + "</span>";
		sBasketPreview += "		</TD>";
		sBasketPreview += "</TR>";
		sBasketPreview += "</TABLE>";
	}	
	
	if ((window.top.frames['topbar']) && (window.top.frames['topbar'].document.getElementById('dBasketPreview')))
		window.top.frames['topbar'].document.getElementById('dBasketPreview').innerHTML = sBasketPreview;
}

function sortOptions(what)
{
    var copyOption = new Array();
    for (var i = 0; i < what.options.length; i++)
        copyOption[i] = new Array(what[i].value, what[i].text);

    copyOption.sort(function(a,b) { return a[0]-b[0]; });

    for (var i = what.options.length-1; i > -1; i--)
        what.options[i] = null;

    for (var i=0; i < copyOption.length; i++)
        var defaultSelected = false;
		var selected = false;
		var text = copyOption[i][1];
		var value = copyOption[i][0];
		var optionName = new Option(text, value, defaultSelected, selected)
		what.options[object.length] = optionName;
		what.options[object.length-1].selected = false;

}

function ListBoxNotPresentToPresent(NotPresent, Present)
{
	for (x = 0; x < NotPresent.length; x++)
	{
		if (NotPresent.options[x].selected)
		{
			Present.options[Present.length] = new Option(NotPresent.options[x].text, NotPresent.options[x].value);
			NotPresent.options[x] = null;
			x--;
		}
	}
	//sortOptions(Present);
}

function ListBoxNotPresentToPresentAll(NotPresent, Present)
{
	while (NotPresent.length > 0)
	{
		Present.options[Present.length] = new Option(NotPresent.options[0].text, NotPresent.options[0].value);
		NotPresent.options[0] = null;
	}
	//sortOptions(Present);
}

function ListBoxPresentToNotPresent(NotPresent, Present)
{
	for (x = 0; x < Present.length; x++)
	{
		if (Present.options[x].selected)
		{
			NotPresent.options[NotPresent.length] = new Option(Present.options[x].text, Present.options[x].value);
			Present.options[x] = null;
			x--;
		}
	}
	//sortOptions(NotPresent);
}

function ListBoxPresentToNotPresentAll(NotPresent, Present)
{
	while (Present.length > 0)
	{
		NotPresent.options[NotPresent.length] = new Option(Present.options[0].text, Present.options[0].value);
		Present.options[0] = null;
	}
	//sortOptions(Present);
}


function textAreaMaxLength_OnKeyPress(textBox, maxLength)
{
	if (maxLength && textBox.value.length > maxLength-1)
		return false;
}

function textAreaMaxLength_OnPaste(textBox, maxLength)
{
	if (maxLength)
		return false;
}

function textAreaMaxLength_OnBeforePaste(textBox, maxLength)
{
	if (maxLength)
	{
		maxLength = parseInt(maxLength);
		var oTR = document.selection.createRange();
		var iInsertLength = maxLength - textBox.value.length + oTR.text.length;
		var sData = window.clipboardData.getData("Text").substr(0, iInsertLength);
		oTR.text = sData;
		
		return false;
	}
}

function PrintPageOLD() {  
	var IE = (navigator.appName == "Microsoft Internet Explorer");   
	var VERSION = parseInt(navigator.appVersion);
	if (VERSION > 3)
	{    
		if (IE)
		{     	
			var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';      
			document.body.insertAdjacentHTML('beforeEnd', WebBrowser);       	
			WebBrowser1.ExecWB(6, 2);      	
			WebBrowser1.outerHTML = "";      
		}    
		else
		{
			self.print();    
		}  
	}  
	else
	{ 
		alert("Printer not supported");
	}
}

function PrintPage() {  
	var IE = (navigator.appName == "Microsoft Internet Explorer");   
	var VERSION = parseInt(navigator.appVersion);
	if (VERSION > 3)
	{    
		self.print();    
	}  
	else
	{ 
		alert("Printer not supported");
	}
}

function encryptPassword()
{
	setMaxDigits(128);
	key = new RSAKeyPair(
	"010001",
	"",
	"aa21803c85279ecb21275c1fff004992250c68e633cc05102ccd53d116f6fff6ce9af75b61f2e8e5e2e683247e25cb6e6f3c9b98f163d318ef3b97f15a124d4b"
	);

	var sPassword = sSessionCheckcode + document.getElementById('tbPassword').value;
	if (sPassword.length <= 60)
	{
		//var sEncryptedPassword = encryptedString(key, sPassword);
		var sEncryptedPassword = encryptedString(key, "alkjfasl;fdjl;askjfdlajslf;jasdl;jfl;asjfljasl;fdjl;asjf;ljasl;dfjlasjfljopwehtyp9ow4y8et9p8y4398ty498yt84t98y489yt498yt0000077777");
		document.getElementById('tbPassword').value = sEncryptedPassword;
	}
}


///////////////////////////// campi obbligatory

function ValidateThis(control, sControlList, sDefaultColor, sWarningColor, sWarningText)
{
	okToGo = true;
	
	// aggiungo un terminatore anche in fondo alla stringa con i controlli
	sControlList += ";";
	
	iIndex = Math.max(sControlList.indexOf(';'), 0);
	sToken = sControlList.substr(0, iIndex);
	sControlList = sControlList.substr(iIndex + 1);
	while ((sToken != null) && (sToken != ''))
	{
		// processo il token
		sFieldLabel = "l" + sToken;
		sField = sToken;
		
		if (sToken.indexOf(',') != -1)
		{
			sFieldLabel = sToken.subsrt(0, sToken.indexOf(','));
			sField = sToken.substr(sToken.indexOf(','));
		}
		
		// azzero il colore della label
		document.getElementById(sFieldLabel).style.color = sDefaultColor;
		
		// controllo se il campo e' stato specificato
		if (document.getElementById(sField))
		{
			switch (document.getElementById(sField).type)
			{
				case 'text':
				case 'password':
					// textbox
					if (document.getElementById(sField).value == '')
					{
						okToGo = false;
						document.getElementById(sFieldLabel).style.color = sWarningColor;
					}
					break;
				case 'checkbox':
					// checkbox
					if (document.getElementById(sField).checked == false)
					{
						okToGo = false;
						document.getElementById(sFieldLabel).style.color = sWarningColor;
					}
					break;
			}
		}
		
		// prendo il token successivo
		iIndex = Math.max(sControlList.indexOf(';'), 0);
		sToken = sControlList.substr(0, iIndex);
		sControlList = sControlList.substr(iIndex + 1);
	}
	
	if (okToGo)
	{
		//CreateInfoLayer('Invio in corso...');
		control.disabled = true;
		document.forms[0].submit();
		
		return true;
	}
	else
	{
		alert(sWarningText);
		return false;
	}
}

///////////////////////////// validazione campi

function fieldOnlyNumbers(e) 
{
    var unicode = e.charCode ? e.charCode : e.keyCode;
    if ((unicode != 8) && (unicode != 9))
    {
         // if the key isn't the backspace key (which we should allow) 
        if ((unicode < 48) || (unicode > 57)) // if not a number
            return false //disable key press 
    }
}

///////////////////////////// Captcha

function generateCaptcha() {
    var car, min, max, dif, lun, inc;
    car = "abcdefghijklmnopqrstuvwxyz";
    car += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    car += "1234567890";
    min = 5;
    max = 5;
    dif = max - min;
    lun = Math.round((Math.random() * dif) + min);
    inc = 0;
    cod = "";
    while (inc < lun) {
        cod += car.charAt(Math.round(Math.random() * car.length));
        inc++;
    }

    document.getElementById("captcha").innerText = cod;
}

function validateCaptcha(inputValue) {
    var captchaValue = document.getElementById("captcha").innerText;
    if (inputValue != captchaValue)
    {
        return false
    }
    else
    {
        return true;
    }
}

///////////////////////////// gestione tab

function SetCurrentTabUrl(sUrl, sLabel)
{
	var MainTabsCount = 4;
	var SubTabsCount = 10;
	
	var desktop = window.top.frames['desktop'];
	
	// procedo solo con la giusta versione del browser
	if (getBrowserType() == 'ie')
	{
		// se ancora non abbiamo la pagina per il multidesktop la carico
		if ((desktop.igtab_getTabById == null) || (desktop.igtab_getTabById("uwtMain") == null))
			desktop.window.location = '/MultiDesktop.aspx?FirstUrl=' + URLencode(sUrl);

		if ((desktop.igtab_getTabById != null) && (desktop.igtab_getTabById("uwtMain") != null))
		{
			var webTab = desktop.igtab_getTabById("uwtMain");
			var iCurrentTabIndex = webTab.getSelectedIndex();
			var iMainTabIndex = Math.floor(iCurrentTabIndex / SubTabsCount) * SubTabsCount;
			
			// setto il tab
			webTab.Tabs[iMainTabIndex].setTargetUrl('about:blank');
			if (sUrl.indexOf('?') != -1)
				webTab.Tabs[iMainTabIndex].setTargetUrl(sUrl + '&TabID=' + iMainTabIndex);
			else
				webTab.Tabs[iMainTabIndex].setTargetUrl(sUrl + '?TabID=' + iMainTabIndex);
			
			//if (sLabel != "")
			//	webTab.Tabs[iMainTabIndex].setText(sLabel);
				
			// seleziono il tab
			if (iMainTabIndex != iCurrentTabIndex)
				webTab.setSelectedIndex(iMainTabIndex);
		}
	}
	else
		desktop.location = sUrl;
}

function SetCurrentTabSubTabUrl(sUrl, sLabel)
{
	var MainTabsCount = 4;
	var SubTabsCount = 10;
	
	var desktop = window.top.frames['desktop'];
	
	// procedo solo con la giusta versione del browser
	if (getBrowserType() == 'ie')
	{
		if ((desktop.igtab_getTabById != null) && (desktop.igtab_getTabById("uwtMain") != null))
		{
			// pulisco l'url da eventuali TabID che non ci interessano
			sUrl = sUrl.replace("TabID=", "OldTabID=");
			
			var webTab = desktop.igtab_getTabById("uwtMain");
			var iCurrentTabIndex = webTab.getSelectedIndex();
			var iMainTabIndex = Math.floor(iCurrentTabIndex / SubTabsCount) * SubTabsCount;
			var iSubTabIndex = iMainTabIndex + 1;
			while ((iSubTabIndex < (iMainTabIndex + SubTabsCount)) && (webTab.Tabs[iSubTabIndex].visible))
				iSubTabIndex++;
			
			// innanzitutto azzero il tab
			webTab.Tabs[iSubTabIndex].setTargetUrl('about:blank');
			
			// setto il tab
			if (sUrl.indexOf('?') != -1)
				webTab.Tabs[iSubTabIndex].setTargetUrl(sUrl + '&TabID=' + iSubTabIndex);
			else
				webTab.Tabs[iSubTabIndex].setTargetUrl(sUrl + '?TabID=' + iSubTabIndex);
			//if (sLabel != "")
			//	webTab.Tabs[iSubTabIndex].setText(sLabel);
				
			// seleziono il tab
			if (iSubTabIndex != iCurrentTabIndex)
			{
				webTab.Tabs[iSubTabIndex].setVisible(true);
				webTab.setSelectedIndex(iSubTabIndex);
			}
		}
	}
	else
		desktop.location = sUrl;
}

function CloseCurrentSubTab(sUrl, bRefreshMainTab)
{
	var MainTabsCount = 4;
	var SubTabsCount = 10;
	
	var desktop = window.top.frames['desktop'];
	
	// procedo solo con la giusta versione del browser
	if (getBrowserType() == 'ie')
	{
		if ((desktop.igtab_getTabById != null) && (desktop.igtab_getTabById("uwtMain") != null))
		{
			var webTab = desktop.igtab_getTabById("uwtMain");
			var iCurrentTabIndex = webTab.getSelectedIndex();
			var iMainTabIndex = Math.floor(iCurrentTabIndex / SubTabsCount) * SubTabsCount;
			
			// se e' un subtab lo chiudo
			if (iMainTabIndex != iCurrentTabIndex)
			{
				// se richiesto e se il maintab e' pertinente, aggiorno il main tab
				if (bRefreshMainTab)
				{
					if (webTab.Tabs[iMainTabIndex].getTargetUrl().indexOf(sUrl.substring(0, sUrl.indexOf('.aspx'))) != -1)
					{
						sCurrentMainTabUrl = webTab.Tabs[iMainTabIndex].getTargetUrl();
						webTab.Tabs[iMainTabIndex].setTargetUrl('about:blank');
						webTab.Tabs[iMainTabIndex].setTargetUrl(sCurrentMainTabUrl);
					}
				}
				
				// azzero il tab
				webTab.setSelectedIndex(iCurrentTabIndex - 1);
				webTab.Tabs[iCurrentTabIndex].setTargetUrl('about:blank');
				webTab.Tabs[iCurrentTabIndex].setVisible(false);
			}
			else
			{
				// effettuo il redirect all'url specificata
				if (sUrl.indexOf('?') != -1)
					webTab.Tabs[iCurrentTabIndex].setTargetUrl(sUrl + '&TabID=' + iCurrentTabIndex);
				else
					webTab.Tabs[iCurrentTabIndex].setTargetUrl(sUrl + '?TabID=' + iCurrentTabIndex);
			}
		}
	}
	else
		desktop.location = sUrl;
}

function SetCurrentTabUrlStaticFrames(sUrl)
{
	var desktop = window.top.frames['desktop'];
	
	// se ancora non abbiamo la pagina per il multidesktop la carico
	if ((desktop.igtab_getTabById == null) || (desktop.igtab_getTabById("uwtMain") == null))
		desktop.window.location = '/MultiDesktop.aspx?FirstUrl=' + URLencode(sUrl);

	if ((desktop.igtab_getTabById != null) && (desktop.igtab_getTabById("uwtMain") != null))
	{
		var webTab = desktop.igtab_getTabById("uwtMain");
		var iCurrentTabIndex = webTab.getSelectedIndex();
		if (sUrl.indexOf('?') != -1)
			webTab.Tabs[iCurrentTabIndex].setTargetUrl(sUrl + '&TabID=' + iCurrentTabIndex);
		else
			webTab.Tabs[iCurrentTabIndex].setTargetUrl(sUrl + '?TabID=' + iCurrentTabIndex);
	}
}



///////////////////////////// utility per i layer

function CreateInfoLayerAndDisableButton(text, tagToDisable)
{
	makeLayer('layerInfo', ((document.body.clientWidth - 300) / 2) + document.body.scrollLeft, ((document.body.clientHeight - 100) / 2) + document.body.scrollTop, 300, 100, '#f9f9f9', 1, 1, '<TABLE width="300px" height="100px" align="center" valign="middle" borderColor="black" cellSpacing="1" cellPadding="1" border="2"><TR><TD align="center" class="desktop_headingTitleA">' + text + '</TD></TR></TABLE>');
	//tagToDisable.disabled = true;
	//document.Form1.submit();
	
	return false;
}

function CreateInfoLayer(text)
{
	makeLayer('layerInfo', ((document.body.clientWidth - 300) / 2) + document.body.scrollLeft, ((document.body.clientHeight - 100) / 2) + document.body.scrollTop, 300, 100, '#f9f9f9', 1, 1, '<TABLE width="300px" height="100px" align="center" valign="middle" borderColor="black" cellSpacing="1" cellPadding="1" border="2"><TR><TD align="center" class="desktop_headingTitleA">' + text + '</TD></TR></TABLE>');
	
	return false;
}

function CreateInfoLayerHideSelects(text)
{
	makeLayer('layerInfo', ((document.body.clientWidth - 300) / 2) + document.body.scrollLeft, ((document.body.clientHeight - 100) / 2) + document.body.scrollTop, 300, 100, '#f9f9f9', 1, 1, '<TABLE width="300px" height="100px" align="center" valign="middle" borderColor="black" cellSpacing="1" cellPadding="1" border="2"><TR><TD align="center" class="desktop_headingTitleA">' + text + '</TD></TR></TABLE>');
	hideSelects();
	
	return false;
}

function HideInfoLayer()
{
	deleteLayer('layerInfo');
	
	return false;
}

function makeLayer(id, left, top, width, height, bgColor, visible, zIndex, innerText)
{
	if (document.layers)
	{
		if (document.layers[id])
		{
			alert('Layer with this ID already exists!');
			return;
		}
		var LR = document.layers[id] = new Layer(width);
		LR.name = id;
		LR.left = left;
		LR.top = top;
		LR.clip.height = height;
		LR.visibility = (null == visible || 1 == visible ? 'show' : 'hide');
		if (null != zIndex)
			LR.zIndex = zIndex;
		if (null != bgColor)
			LR.bgColor = bgColor;
			
		document.layers[id].document.write(innerText);
	}
	else if (document.all)
	{
		if (document.all[id])
		{
			//alert(document.all[id].innerHTML);
			alert('Attenzione: basta premere il pulsante una volta\nAttention: just click the button once');
			document.all[id].innerHTML = innerText;
		}
		else
		{
			var LR = '\n<DIV id=' + id + ' style="position:absolute'
			+ '; left:' + left
			+ '; top:' + top
			+ '; width:' + width
			+ '; height:' + height
			+ '; clip:rect(0,' + width + ',' + height + ',0)'
			+ '; visibility:' + (null == visible || 1 == visible ? 'visible':'hidden')
			+ (null == zIndex  ? '' : '; z-index:' + zIndex)
			+ (null == bgColor ? '' : '; background-color:' + bgColor)
			+ '">' + innerText + '</DIV>';
			document.body.insertAdjacentHTML("BeforeEnd", LR);
		}
	}
}

function deleteLayer(id)
{
	if (document.layers && document.layers[id])
	{
		document.layers[id].visibility = 'hide';
		delete document.layers[id];
	}
	if (document.all && document.all[id])
	{
		document.all[id].innerHTML='';
		document.all[id].outerHTML='';
	}
}

function hideSelects()
{ 
	var action = 'hidden';
	if (navigator.appName.indexOf("MSIE"))
	{
		for (var S = 0; S < document.forms.length; S++)
		{
			for (var R = 0; R < document.forms[S].length; R++)
			{
				if (document.forms[S].elements[R].options) 
				{
					document.forms[S].elements[R].style.visibility = action;
				}
			}
		} 
	}
}

function showSelects()
{ 
	var action = 'visible';
	if (navigator.appName.indexOf("MSIE"))
	{
		for (var S = 0; S < document.forms.length; S++)
		{
			for (var R = 0; R < document.forms[S].length; R++)
			{
				if (document.forms[S].elements[R].options) 
				{
					document.forms[S].elements[R].style.visibility = action;
				}
			}
		} 
	}
}



///////////////////////////// IFRAME autoridimensionanti

// http://solo.dc3.com/tw/HandlingIframes.html

function resizeToFit(that)
{
    var objNode = (typeof(this.nodeName) == 'undefined') ? that : this ;
    var objIframe = window.parent.document.getElementById('resizeToFit');
    var intScrollX, intScrollY, intWinWidth, intWinHeight, intMaxWidth, intMaxHeight;
    
    var intWhileCount = 0;
    do
    {
        // scroll the document by 1 pixel
        window.scrollTo(1, 1);
        // measure the scroll position            
        intScrollX = (document.all) ? document.body.scrollLeft : window.pageXOffset ;
        intScrollY = (document.all) ? document.body.scrollTop : window.pageYOffset ;
        // measure window size
        intWinWidth = (document.all) ? document.body.offsetWidth : window.innerWidth ;
        intWinHeight = (document.all) ? document.body.offsetHeight : window.innerHeight ;
        // if the scroll position is not 0
        if (intScrollX > 0)
        {
            // make the window larger
            window.resizeBy(32, 0);
            // make the iframe larger
            if (objIframe != null && !document.all)
            {
				objIframe.style.width = (objIframe.style.width=='') ? '64px' : (parseInt(objIframe.style.width) + 32) + 'px';
			}
        }
        if (intScrollY > 0)
        {
            // make the window larger
            window.resizeBy(0, 32);
            // make the iframe larger
            if (objIframe != null && !document.all)
            {
				objIframe.style.height = (objIframe.style.height=='') ? '64px' : (parseInt(objIframe.style.height) + 32) + 'px';
			}
        } 
        // count the steps
        intWhileCount += 1;
    }
    while ((intScrollX > 0 || intScrollY > 0) && intWhileCount < 900);
}

function waitToFit()
{
    setTimeout("resizeToFit()", 100);    
}

//onload = waitToFit;

// ------------------ metodo alternativo

function adjustIFrameSize (iframeWindow)
{
	if (iframeWindow.document.height)
	{
		var iframeElement = document.getElementById(iframeWindow.name);
		iframeElement.style.height = iframeWindow.document.height + 'px';
		iframeElement.style.width = iframeWindow.document.width + 'px';
	}
	else if (document.all) 
	{
		var iframeElement = document.all[iframeWindow.name];
		if (iframeWindow.document.compatMode && iframeWindow.document.compatMode != 'BackCompat') 
		{
			iframeElement.style.height = iframeWindow.document.documentElement.scrollHeight + 5 + 'px';
			iframeElement.style.width = iframeWindow.document.documentElement.scrollWidth + 5 + 'px';
		}
		else
		{
			iframeElement.style.height = iframeWindow.document.body.scrollHeight + 5 + 'px';
			iframeElement.style.width = iframeWindow.document.body.scrollWidth + 5 + 'px';
		}
	}
}


// <iframe name="iframeName" id="iframeName" marginwidth="0" marginheight="0" src="test20020403.html"><a href="test20020403.html">page</a></iframe>
// Note that the <iframe> tag has both name and id attribute set to the 
// same value. This is necessary to allow the iframe window object to 
// find the corresponding <iframe> element.

// <body onload="if (parent.adjustIFrameSize) parent.adjustIFrameSize(window);"


///////////////////////////// funzioni specifiche

function Appointment_AddChange_SetAppointmentDayPreview(oCalendar, newValue, oEvent)
{
	// ottengo il puntatore al controllo principale
	//alert(oCalendar.uniqueId.substring(0, oCalendar.uniqueId.indexOf('wdcStartDate')).replace(/:/g, 'x').replace(/_/g, 'x') + 'wdcStartDate_input');
	//alert(newValue);
	//wdcCalendar = document.getElementById(oCalendar.uniqueId.substring(0, oCalendar.uniqueId.indexOf('wdcStartDate')).replace(/:/g, 'x').replace(/_/g, 'x') + 'wdcStartDate_input');
	//alert(wdcCalendar.value);
	StartDate = newValue.getYear() + "_" + (newValue.getMonth() + 1) + "_" + newValue.getDate(); //.replace(/-/g, '_');
	StructureUID = GetElementById('ddlStructureUID').options[GetElementById('ddlStructureUID').selectedIndex].value;
	LocalUID = GetElementById(oCalendar.uniqueId.substring(0, oCalendar.uniqueId.indexOf('wdcStartDate')).replace(/:/g, '_') + 'ddlLocalUID').value;
	
	GetElementById('AppointmentDayPreview').innerHTML = AddChange.GetAppointmentDayPreview(StartDate, StructureUID, LocalUID, oCalendar.uniqueId).value;
}

///////////////////////////// datagrid utility

function GetElementById(controlToFind)
{
	return document.getElementById(controlToFind);
}

function GetElementByIdInfragistics(controlToFind)
{
	return igedit_getById(controlToFind);
}

function GetSameRowControl(fromFullName, fromName, toName)
{
	return (fromFullName.replace(fromName, toName));
}

function GetDatagridControl(userControl, datagridName, rowNumber, controlName)
{
	if ((userControl != null) && (userControl != ""))
	{
		foundControl = GetElementById(userControl + "_" + datagridName + "__ctl" + rowNumber + "_" + controlName);
		if (foundControl != null)
			return foundControl;
		foundControl = GetElementById(userControl + ":" + datagridName + ":_ctl" + rowNumber + ":" + controlName);
		if (foundControl != null)
			return foundControl;
		foundControl = GetElementById(userControl + "x" + datagridName + "xxctl" + rowNumber + "x" + controlName);
		if (foundControl != null)
			return foundControl;
	}
	else
	{
		foundControl = GetElementById(datagridName + "__ctl" + rowNumber + "_" + controlName);
		if (foundControl != null)
			return foundControl;
		foundControl = GetElementById( datagridName + ":_ctl" + rowNumber + ":" + controlName);
		if (foundControl != null)
			return foundControl;
		foundControl = GetElementById(datagridName + "xxctl" + rowNumber + "x" + controlName);
		if (foundControl != null)
			return foundControl;
	}
}

function GetDatagridControlInfragistics(userControl, datagridName, rowNumber, controlName)
{
	if ((userControl != null) && (userControl != ""))
	{
		foundControl = GetElementByIdInfragistics(userControl + "_" + datagridName + "__ctl" + rowNumber + "_" + controlName);
		if (foundControl != null)
			return foundControl;
		foundControl = GetElementByIdInfragistics(userControl + ":" + datagridName + ":_ctl" + rowNumber + ":" + controlName);
		if (foundControl != null)
			return foundControl;
		foundControl = GetElementByIdInfragistics(userControl + "x" + datagridName + "xxctl" + rowNumber + "x" + controlName);
		if (foundControl != null)
			return foundControl;
	}
	else
	{
		foundControl = GetElementByIdInfragistics(datagridName + "__ctl" + rowNumber + "_" + controlName);
		if (foundControl != null)
			return foundControl;
		foundControl = GetElementByIdInfragistics( datagridName + ":_ctl" + rowNumber + ":" + controlName);
		if (foundControl != null)
			return foundControl;
		foundControl = GetElementByIdInfragistics(datagridName + "xxctl" + rowNumber + "x" + controlName);
		if (foundControl != null)
			return foundControl;
	}
}


function GetDatagridFocusedControl(userControl, datagridName, controlName)
{
	row = 2;
	while (true)
	{
		if (userControl != '')
		{
			controlToFind = userControl + "_" + datagridName + "__ctl" + row + "_" + controlName;
			controlToFind2 = userControl + "x" + datagridName + "xxctl" + row + "x" + controlName;
		}
		else
		{
			controlToFind = datagridName + "__ctl" + row + "_" + controlName;
			controlToFind2 = datagridName + "xxctl" + row + "x" + controlName;
		}
				
		if ((GetElementById(controlToFind) != null) && (GetElementById(controlToFind).focus))
			return controlToFind;
			
		if ((GetElementById(controlToFind2) != null) && (GetElementById(controlToFind2).focus))
			return controlToFind2;
			
		if ((GetElementById(controlToFind) == null) && (GetElementById(controlToFind2) == null))
			return('');
			
		row++;
	}
}

///////////////////////////// comandi per mostrare/nascondere le righe delle tabelle

function showTableRow(tableRowName)
{
	if (GetElementById(tableRowName) != null)
		GetElementById(tableRowName).style.display = "";
		
	// ciclo per eventuale elementi numerati
	var bFound = true;
	var iCounter = 1;
	while (bFound)
	{
		var element = GetElementById(tableRowName + iCounter);
		if (element != null)
			element.style.display = "";
		else
			bFound = false;
			
		iCounter++;
	}
}

function hideTableRow(tableRowName)
{
	if (GetElementById(tableRowName) != null)
		GetElementById(tableRowName).style.display = "none";
		
	// ciclo per eventuale elementi numerati
	var bFound = true;
	var iCounter = 1;
	while (bFound)
	{
		var element = GetElementById(tableRowName + iCounter);
		if (element != null)
			element.style.display = "none";
		else
			bFound = false;
			
		iCounter++;
	}
}

function switchTableRowDisplay(tableRowName)
{
	// cambio stato dell'elemento specificato
	if (GetElementById(tableRowName) != null)
	{
		if (GetElementById(tableRowName).style.display == "none")
			GetElementById(tableRowName).style.display = "";
		else
			GetElementById(tableRowName).style.display = "none";
	}
	
	// ciclo per eventuale elementi numerati
	var bFound = true;
	var iCounter = 1;
	while (iCounter < 30)
	{
		var element = GetElementById(tableRowName + iCounter);
		if (element != null)
		{
			if (element.style.display == "none")
				element.style.display = "";
			else
				element.style.display = "none";
		}
		else
			bFound = false;
			
		iCounter++;
	}
	
}

function showDetailTab(dataListName, rowNumber)
{
	// ciclo per eventuale elementi numerati
	var bFound = true;
	var iCounter = 0;
	
	while (bFound)
	{
		var element = GetElementById(dataListName + "__ctl" + iCounter + "_pDetails");
		if (element != null)
		{
			if ((rowNumber == -1) || (iCounter == rowNumber))
			{
				element.style.display = "";
			}
			else
			{
				element.style.display = "none";
			}
		}
		else
		{
			bFound = false;
		}
			
		iCounter++;
	}
}



///////////////////////////// automatismi catalogo/ordini
function bindCheckboxToTextbox(checkbox, textbox)
{
	if ((textbox != null) && (checkbox != null))
	{
		if (!checkbox.checked)
			textbox.value = "";
	}
}

function bindTextboxToCheckbox(textbox, checkbox)
{
	if ((textbox != null) && (checkbox != null))
	{
		if (textbox.value != '')
			checkbox.checked = true;
		else
			checkbox.checked = false;
	}
}


function bindTextboxToTextbox(textbox, textbox2)
{
	if (textbox.value != '')
		textbox2.value = textbox.value;
}


///////////////////////////// cambio valore controlli al volo

function doSubmit()
{
	window.top.frames['desktop'].document.forms[0].submit();
}

function setValueTextBox(controlName, textToSet)
{
	if (window.top.frames['desktop'])
		if (window.top.frames['desktop'].document.getElementById(controlName) != null)
			window.top.frames['desktop'].document.getElementById(controlName).value = textToSet;
}

function setValueDropDownList(controlName, valueToSet)
{
	if (window.top.frames['desktop'])
		if (window.top.frames['desktop'].document.getElementById(controlName) != null)
		{
			control = window.top.frames['desktop'].document.getElementById(controlName);
			for (x = 0; x < control.length; x++)
				if (control.options[x].value == valueToSet)
					control.selectedIndex = x;
		}
}


//////////////////////////// URL Encoding

function URLencode(sStr)
{
    return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g,'%2F');
}



/////////////////////////// cambio icona stato ordine

function UpdateBasketStateIcon(ddlBasketNextStateNameControlName, iNextBasketStateControlName)
{
	// ottengo i puntatori ai controlli richiesti
	ddlBasketNextState = GetElementById(ddlBasketNextStateNameControlName);
	iNextBasketState = GetElementById(iNextBasketStateControlName);
	
	// ottengo lo stato selezionato
	iNextState = ddlBasketNextState.options[ddlBasketNextState.selectedIndex].value;
	
	// a seconda dello stato aggiorno l'icona
	iNextBasketState.style.display = '';
	switch (iNextState)
	{
		case '2':
			iNextBasketState.src = '/Images/SmallIcons/StateOfferActive.gif';
			break;
		case '4':
			iNextBasketState.src = '/Images/SmallIcons/StateOfferAccepted.gif';
			break;
		case '6':
			iNextBasketState.src = '/Images/SmallIcons/StateOfferOld.gif';
			break;
		case '10':
			iNextBasketState.src = '/Images/SmallIcons/StateDraft.gif';
			break;
		case '15':
			iNextBasketState.src = '/Images/SmallIcons/StateToBeReconfirmed.gif';
			break;
		case '20':
		case '30':
			iNextBasketState.src = '/Images/SmallIcons/StateToBeConfirmed.gif';
			break;
		case '40':
			iNextBasketState.src = '/Images/SmallIcons/StateConfirmed.gif';
			break;
		case '45':
			iNextBasketState.src = '/Images/SmallIcons/StatePartiallyEvaded.gif';
			break;
		case '50':
			iNextBasketState.src = '/Images/SmallIcons/StateEvaded.gif';
			break;
		case '60':
			iNextBasketState.src = '/Images/SmallIcons/StateCancelled.gif';
			break;
		default:
			iNextBasketState.style.display = 'none';
			break;	
	}
}

// ************ IFRAME auto resize

function AutoVerticalResizeThisIFrame()
{	
    var getFFVersion = navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
    var FFextraHeight = parseFloat(getFFVersion) >= 0.1 ? 16 : 0; //extra height in px to add to iframe in FireFox 1.0+ browsers		
	var currentfr = parent.document.getElementById(this.name); //parent.frames[this.name]; //document.getElementById(frameid);
	if (currentfr && !window.opera)
	{
		if (currentfr.style && currentfr.style.display) currentfr.style.display = "block";
		if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
		{
			currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight + 30; 
		}
		else if (currentfr.Document && currentfr.Document.body && currentfr.Document.body.scrollHeight) //ie5+ syntax
		{
			currentfr.height = currentfr.Document.body.scrollHeight + 30;
		}
	}
}

// ************
