//GLOBALS
var w3c = (document.getElementById) ? 1:0;
var ns4 = (document.layers) ? 1:0;	//browser detect for NS4 & W3C standards
var hasCookies = false;
var baseColor = '#FFFFFF';

// verifica se il browser accetta i cookie
if (document.cookie == '') {
	document.cookie = 'hasCookies=yes';
	if (document.cookie.indexOf('hasCookies=yes') != -1) hasCookies = true;
} else
	hasCookies = true;

/**

getObject: restituisce il rifeirmento ad un oggetto
---------------------------------------------------

INPUT:
sObj					id o nome dell'oggetto

OUTPUT: riferimento all'oggetto

**/
function getObject(sObj) {
	var theObj;
	if (w3c)
		theObj = document.getElementById(sObj);
	else if (ns4)
		theObj = eval("document." + sObj);
	return theObj;
}

function getObjectClass(obj){
	if (typeof obj != "object" || obj === null) return false;
	else return /(\w+)\(/.exec(obj.constructor.toString())[1];
}

/* parseUri JS v0.1, by Steven Levithan (http://badassery.blogspot.com)
Splits any well-formed URI into the following parts (all are optional):
----------------------
source (since the exec() method returns backreference 0 [i.e., the entire match] as key 0, we might as well use it)
protocol (scheme)
authority (includes both the domain and port)
	domain (part of the authority; can be an IP address)
	port (part of the authority)
path (includes both the directory path and filename)
	directoryPath (part of the path; supports directories with periods, and without a trailing backslash)
	fileName (part of the path)
query (does not include the leading question mark)
anchor (fragment)

*/
function parseUri(sourceUri){
	var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
	var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
	var uri = {};

	for(var i = 0; i < 10; i++){
		uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
	}

	// Always end directoryPath with a trailing backslash if a path was present in the source URI
	// Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
	if(uri.directoryPath.length > 0){
		uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
	}

	return uri;
}

// get browser size
function getBrowserSize() {
	var iWidth = 0;
	var iHeight = 0;
	if (ns4) {
		iWidth = window.innerWidth;
		iHeight = window.innerHeight;
	} else {
		iWidth = document.body.clientWidth;
		iHeight = document.body.clientHeight;
	}
	return iWidth + 'x' + iHeight;
}

// swaps text in a layer.
function swapText(sText, sDivID, sInnerDivID) {
	var sContent = "<span class=\"commandDesc\">" + sText + "</span>";
	if (w3c) {
		var theObj = getObject(sDivID);
		if (theObj) theObj.innerHTML = sText;
	} else if (ns4) {
		var innerObj = divID + ".document." + sInnerDivID;
		var theObj = getObject(innerObj);
		if (theObj) {
			theObj.document.open();
			theObj.document.write(sContent);
			theObj.document.close();
		}
	}
}

// sets a cookie in the browser.
function setCookie(sName, sValue, iHours, sPath) {
	if (hasCookies) {
		var numHours = false;
		if (iHours) {
			if ((typeof(iHours) == 'string') && Date.parse(iHours)) numHours = iHours;
			else if (typeof(iHours) == 'number') numHours = (new Date((new Date()).getTime() + iHours * 3600000)).toGMTString();
		}
		document.cookie = sName + '=' + escape(sValue) + (numHours ? (';expires=' + numHours) : '') + ((sPath) ? (';path=' + sPath) : (''));
	}
}

// reads a cookie from the browser
function readCookie(name) {
	if (document.cookie == '') return '';
	else {
		var firstChar, lastChar;
		var theBigCookie = document.cookie;
		firstChar = theBigCookie.indexOf(name);
		if (firstChar != -1) {
			firstChar += name.length + 1;
			lastChar = theBigCookie.indexOf(';', firstChar);
			if (lastChar == -1) lastChar = theBigCookie.length;
			return unescape(theBigCookie.substring(firstChar, lastChar));
		} else
			return '';
	}
}

//	Netscape 4 resize fix
function WM_netscapeCssFix() {
	if (document.WM.WM_netscapeCssFix.initWindowWidth != window.innerWidth || document.WM.WM_netscapeCssFix.initWindowHeight != window.innerHeight) {
		document.location = document.location;
	}
}

function WM_netscapeCssFixCheckIn() {
	if ((navigator.appName == 'Netscape') && (parseInt(navigator.appVersion) == 4)) {
		if (typeof document.WM == 'undefined') {
			document.WM = new Object;
		}
		if (typeof document.WM.WM_scaleFont == 'undefined') {
			document.WM.WM_netscapeCssFix = new Object;
			document.WM.WM_netscapeCssFix.initWindowWidth = window.innerWidth;
			document.WM.WM_netscapeCssFix.initWindowHeight = window.innerHeight;
		}
		window.onresize = WM_netscapeCssFix;
	}
}

WM_netscapeCssFixCheckIn();

function MM_swapImgRestore() { //v3.0
	var i, x, a = document.MM_sr;
	for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

function MM_preloadImages() { //v3.0
	if (document.images) {
		if (!document.MM_p) document.MM_p = new Array();
		var i, j = document.MM_p.length;
		for (i = 0; i < arguments.length; i++) {
			if (arguments[i].indexOf("#")!=0) {
				document.MM_p[j] = new Image;
				document.MM_p[j++].src = arguments[i];
			}
		}
	}
}

function MM_findObj(n, d) { //v4.0
	var p, i, x;
	if (!d) d = document;
	if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
		d = parent.frames[n.substring(p + 1)].document;
		n = n.substring(0,p);
	}
	if (!(x = d[n]) && d.all) x = d.all[n];
	for (i=0; !x && i < d.forms.length; i++) x = d.forms[i][n];
	for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
	if (!x && document.getElementById) x = document.getElementById(n);
	return x;
}

function MM_swapImage() { //v3.0
	var i, j = 0, x, a = MM_swapImage.arguments;
	document.MM_sr = new Array;
	for (i = 0; i < (a.length - 2); i += 3)
		if ((x = MM_findObj(a[i])) != null) {
			document.MM_sr[j++] = x;
			if (!x.oSrc) x.oSrc = x.src;
			x.src = a[i + 2];
		}
}

// Remove an array item at n
// 0-based
function MM_removeNthArrayItem(oArray, n) {
	var lhs = new Array();
	if (n > 0) lhs = oArray.slice(0, n);
	var rhs = new Array();
	if (n < oArray.length) rhs = oArray.slice(n + 1);
	var result = lhs.concat(rhs);
	return result;
}

// Does the array contain the given string?
function MM_arrayContainsString(oArray, sItem) {
	if (!oArray) return false;
	for (i = 0; i < oArray.length; i++) {
		if (oArray[i] == sItem) return true;
	}
	return false;
}

// Restituisce l'indice dell'elemento cercato, se esiste
function MMJ_arrayContainedStringIndex(oArray, sItem) {
	if (!oArray) return -1;
	var i = 0;
	for (i = 0; i < oArray.length; i++) {
		if (oArray[i] == sItem) return i;
	}
	return -1;
}

// remove the given string from the array of strings
function MM_removeStringFromArray(array, sItem) {
	if (!oArray) return null;
	for (i = 0; i < oArray.length; i++) {
		if (oArray[i] == sItem) return MM_removeNthArrayItem(oArray, i);
	}
	return oArray;
}

// a selectedItems array is kept in the form. It is an array of strings, each
// string being the name of a checkbox image. It doesn't actually have to be
// the name="foo" attribute of the HTML object itself, just any arbitrary name
// that is associated with this checkbox. The image name is the actual name of the image.
function MM_toggleItem(form, itemName, imageName, theme) {
	if (form.selectedItems == null) form.selectedItems = new Array();
	if (MM_arrayContainsString(form.selectedItems, itemName)) {
		form.selectedItems = MM_removeStringFromArray(form.selectedItems, itemName);
		document[imageName].src = '../themes/'+theme+'/checkbox_off_16.gif';
		//MM_swapImage(imageName, '', '../themes/'+theme+'/checkbox_off_16.gif', '1');
	} else {
		form.selectedItems[form.selectedItems.length] = itemName;
		document[imageName].src = '../themes/'+theme+'/checkbox_on_16.gif';
		//MM_swapImage(imageName, '', '../themes/'+theme+'/checkbox_on_16.gif', '1');
	}
	MM_updateButtons2(form, form.selectedItems);
}

function MM_selectAllItems(oForm, theme) {
	oForm.selectedItems = new Array();
	if (oForm.checkboxes) {
		var checkboxCount = oForm.checkboxes.length;
		for (i = 0; i < checkboxCount; i++) {
			var checkbox = oForm.checkboxes[i];
			if (-1 == document[checkbox.mImageName].src.indexOf('dim_16.gif')) {
				document[checkbox.mImageName].src = '../themes/'+theme+'/checkbox_on_16.gif';
				oForm.selectedItems[oForm.selectedItems.length] = checkbox.mName;
			}
		}
	}
	MM_updateButtons2(form, form.selectedItems);
}

function MM_deselectAllItems(oForm, theme) {
	oForm.selectedItems = new Array();
	if (oForm.checkboxes) {
		var checkboxCount = oForm.checkboxes.length;
		for (i = 0; i < checkboxCount; i++) {
			var checkbox = oForm.checkboxes[i];
			if (-1 == document[checkbox.mImageName].src.indexOf('dim_16.gif')) {
				document[checkbox.mImageName].src = '../themes/'+theme+'/checkbox_off_16.gif';
			}
		}
	}
	MM_updateButtons2(oForm, form.selectedItems);
}

// If all items are selected, deselect all. Otherwise select all.
function MM_toggleSelectedItems(oForm, theme) {
	if (!oForm.selectedItems) oForm.selectedItems = new Array();
	if (oForm.checkboxes) {
		if (oForm.selectedItems.length == oForm.checkboxes.length - MM_countDisabledCheckboxes(oForm))
			MM_deselectAllItems(oForm, theme);
		else
			MM_selectAllItems(oForm, theme);
	}
}

// counts the number of disabled checkboxes - used for deselect all
function MM_countDisabledCheckboxes(oForm) {
	disabledCount = 0;
	if (oForm.checkboxes) {
		for (i = 0; i < oForm.checkboxes.length; i++) {
			oCheckbox = oForm.checkboxes[i];
			if (-1 != document[oCheckbox.mImageName].src.indexOf('dim_16.gif')) {
				disabledCount++;
			}
		}
	}
	return disabledCount;
}

///// Funzioni MultiMedia

// seleziona o deseleziona tutti gli elementi
function MMJ_toggleSelectedItems(oForm, sSwitchElementName, sPrefix) {
	var aSelectedItems = new Array();
	var oElem = oForm.elements[sSwitchElementName];
	var bValue = false;
	var bMatches = false;
	var re = null;
	if (oElem && oElem.type && oElem.type == "checkbox") bValue = oElem.checked;
	try { if (sPrefix.length) re = new RegExp(sPrefix, "i"); } catch (e) {}
	for (var i = 0, j = 0; i < oForm.elements.length; i++) {
		oElem = oForm.elements[i];
		if (oElem && oElem.type && oElem.type == "checkbox") {
			if (re) bMatches = oElem.name.match(re);
			else  bMatches = true;
			if (bMatches) {
				oElem.checked = bValue;
				if (oElem.name != sSwitchElementName && bValue) aSelectedItems[j++] = oElem;
			}
		}
	}
	MMJ_updateButtons2(oForm, aSelectedItems);
}

// restituisce il valore del primo elemento selezionato
function MMJ_getFirstSelectedItem(oForm, sSwitchElementName, sPrefix) {
	var bMatches = false;
	var re = null;
	try { if (sPrefix.length) re = new RegExp(sPrefix, "i"); } catch (e) {}
	for (i = 0; i < oForm.elements.length; i++) {
		var oElem = oForm.elements[i];
		if (oElem && oElem.type && oElem.type == "checkbox") {
			if (re) bMatches = oElem.name.match(re);
			else  bMatches = true;
			if (bMatches && oElem.name != sSwitchElementName && oElem.checked) return oElem.value;
		}
	}
	return null;
}

// restituisce il valore dell'elemento se questo è l'unico selezionato
function MMJ_getUniqueSelectedItem(oForm, sSwitchElementName, sPrefix) {
	var val = null;
	var iCount = 0;
	var bMatches = false;
	var re = null;
	try { if (sPrefix.length) re = new RegExp(sPrefix, "i"); } catch (e) {}
	for (var i = 0; i < oForm.elements.length; i++) {
		var oElem = oForm.elements[i];
		if (oElem && oElem.type && oElem.type == "checkbox") {
			if (re) bMatches = oElem.name.match(re);
			else  bMatches = true;
			if (bMatches && oElem.name != sSwitchElementName && oElem.checked) {
				iCount++;
				if (iCount == 1) val = oElem.value;
				else val = null;
			}
		}
	}
	return val;
}

function MMJ_toggleSelection(oForm, sSwitchElementName, sPrefix) {
	var aSelectedItems = new Array();
	var bMatches = false;
	var re = null;
	try { if (sPrefix.length) re = new RegExp(sPrefix, "i"); } catch (e) {}
	for (var i = 0, j = 0; i < oForm.elements.length; i++) {
		var oElem = oForm.elements[i];
		if (oElem && oElem.type && oElem.type == "checkbox") {
			if (re) bMatches = oElem.name.match(re);
			else  bMatches = true;
			if (bMatches && oElem.name != sSwitchElementName && oElem.checked) aSelectedItems[j++] = oForm.elements[i];
		}
	}
	MMJ_updateButtons2(oForm, aSelectedItems);
}

function MMJ_toggleUniqueSelection(oForm, sPrefix) {
	var aSelectedItems = new Array();
	var bMatches = false;
	var re = null;
	try { if (sPrefix.length) re = new RegExp(sPrefix, "i"); } catch (e) {}
	for (var i = 0, j = 0; i < oForm.elements.length; i++) {
		var oElem = oForm.elements[i];
		if (oElem && oElem.type && oElem.type == "checkbox") {
			if (re) bMatches = oElem.name.match(re);
			else  bMatches = true;
			if (bMatches && oElem.checked) aSelectedItems[j++] = oForm.elements[i];
		}
	}
	MMJ_updateButtons2(oForm, aSelectedItems);
}

// visualizza/nasconde una sezione
// ATTENZIONE: il valore del cookie va sincronizzato con quello utilizzato nella
//			   funzione Section->set_collapsable nella libreria if_section.class.php
function MMJ_toggleVisible(visibleElementID, toggleIconID, toggleIconVisible, toggleIconNotVisible) {
	var theElem = getObject(visibleElementID);
	if (theElem) {
		var theIcon = getObject(toggleIconID);
		var theCookie = readCookie(visibleElementID);
		var sElementStatus = "c";
		if (theElem.style.display == "none") sElementStatus = "e";
		else if (theCookie == "e") sElementStatus = "c";
		setCookie(visibleElementID, sElementStatus, 48, "/");
		if (sElementStatus == "c") {
			theElem.style.display = "none";
			if (theIcon) theIcon.src = toggleIconNotVisible;
		} else {
			theElem.style.display = "block";
			if (theIcon) theIcon.src = toggleIconVisible;
		}
	}
	window.status = "";
}

// imposta la visibilità di un elemento
function MMJ_setVisible(visibleElementID, toggleIconID, toggleIconVisible, toggleIconNotVisible, elementStatus, displayBlock, useCookie) {
	theElem = getObject(visibleElementID);
	if (theElem) {
		theIcon = getObject(toggleIconID);
		if (useCookie) elementStatus = (readCookie(visibleElementID) == 'e');
		if (elementStatus) {
			theElem.style.display = (displayBlock ? "block" : "inline");
			if (useCookie) setCookie(visibleElementID, "c", 48, "/");
			if (theIcon) theIcon.src = toggleIconVisible;
		} else {
			theElem.style.display = "none";
			if (useCookie) setCookie(visibleElementID, "e", 48, "/");
			if (theIcon) theIcon.src = toggleIconNotVisible;
		}
	}
	window.status = "";
}

// visualizza il menu indicato e nasconde gli altri
// function MMJ_showMenu(menuIndex, menuPrefix, menuCount, displayBlock) {
//	var oActive = getObject(menuPrefix + menuIndex);
//	for (i = 1; i <= menuCount; i++) {
//		if (oMenu = getObject(menuPrefix + i)) oMenu.style.display = 'none';
//	}
//	if (oActive && menuIndex >= 0) {
//		oActive.style.display = (displayBlock ? 'block' : 'inline');
//		//setTimeout("MMJ_showMenu(null,'" + menuPrefix + "'," + menuCount + "," + displayBlock + ")", 5000);
//	}
// }


// imposta il valore di un elemento
function MMJ_setValue(visibleElementID, newValue) {
	var theElem = getObject(visibleElementID);
	if (theElem) {
		if (theElem.value) {	// input type text, area, button...
			alert('input');
			theElem.value = newValue;
		} else if (theElem.selected) {	// input type select
			alert('select');
			theElem.selected = newValue;
		} else if (theElem.innerHTML) { // altri tag
			alert('other');
			theElem.innerHTML = newValue;
		}
	}
}

// imposta il messaggio della Status Bar
function MMJ_setStatus(sMessage) {
	if (typeof(sMessage) == "string") window.status = sMessage;
	return true;
}

/*function MMJ_toggleVisible(visibleElementID, toggleIconID, toggleIconVisible, toggleIconNotVisible) {
	var theElem = getObject(visibleElementID);
	var theIcon = getObject(toggleIconID);
	if (theElem) {

		if (theElem.style.display == "none") {
			theElem.style.display = "";
			theIcon.src = toggleIconVisible;
		} else {
			theElem.style.display = "none";
			theIcon.src = toggleIconNotVisible;
		}
	}
	window.status = '';
}*/

// bottone sensibile
function MMJCommandButton(sName, sDescription, sAction, bEnabled, sEnabledImage, sOverImage, sDisabledImage, bEnableOnNoSelection, bEnableOnSingleSelection, bEnableOnMultipleSelection, sEnabledCheckSelectionJS, bConfirmation, sConfirmationMessage) {
	this.mName = sName; 														// nome dell'immagine
	this.mDesc = sDescription			;										// descrizione dell'immagine
	this.mAction = sAction; 													// azione da compiere al click
	this.mEnabled = bEnabled;													// flag: icona inizialmente abilitata?
	this.mEnabledImage = sEnabledImage; 										// immagine icona abilitata (stringa)
	this.mOverImage = sOverImage;												// immagine icona selezionata (stringa)
	this.mDisabledImage = sDisabledImage;										// immagine icona disabilitata (stringa)
	this.mEnabledOnNoSelection = bEnableOnNoSelection;							// pulsante abilitato su "nessuna selezione"
	this.mEnabledOnSingleSelection = bEnableOnSingleSelection;					// pulsante abilitato su "selezione singola"
	this.mEnabledOnMultipleSelection = bEnableOnMultipleSelection;				// pulsante abilitato su "selezione multipla"
	if (sEnabledCheckSelectionJS) { 											// codice da valutare per abilitare il pulsante
		this.mEnabledCheckSelectionJS = eval(sEnabledCheckSelectionJS);
	} else {
		this.mEnabledCheckSelectionJS = '';
	}
	this.mConfirmation = bConfirmation; 										// flag: richiede conferma?
	this.mConfirmationMessage = (bConfirmation ? sConfirmationMessage : "");	// messaggio di conferma
	this.update = MMJCommandButton_update;
	this.over = MMJCommandButton_over;
	this.out = MMJCommandButton_out;
	this.click = MMJCommandButton_click;
}

function MMJCommandButton_over() {
	if (this.mEnabled) {
		document[this.mName].src = this.mOverImage;
	}
	window.status = this.mDesc;
}

function MMJCommandButton_out() {
	if (this.mEnabled) {
		document[this.mName].src = this.mEnabledImage;
	}
	window.status = "";
}

function MMJCommandButton_click() {
	if (this.mEnabled) {
		if (this.mConfirmation) {
			if (!confirm(this.mConfirmationMessage)) {
				return;
			}
		}
		if ((this.mAction.indexOf('javascript') == 0) || (this.mAction.indexOf('Javascript') == 0)) {
			try {
				eval(this.mAction.substring(this.mAction.indexOf(':') + 1));
			} catch (e) {
				alert();
			}
		} else {
			window.location = this.mAction;
		}
	}
	window.status = "";
}

function MMJCommandButton_update(aSelectedItems) {
	var bEnable = false;
	var bIsEnabled = true;
	if (this.mEnabledCheckSelectionJS != '' && typeof(this.mEnabledCheckSelectionJS) == 'function') {
		bIsEnabled = this.mEnabledCheckSelectionJS(aSelectedItems);
	}
	if (aSelectedItems.length == 0) {
		bEnable = this.mEnabledOnNoSelection && bIsEnabled;
	}
	if (aSelectedItems.length == 1) {
		bEnable = this.mEnabledOnSingleSelection && bIsEnabled;
	}
	if (aSelectedItems.length > 1) {
		bEnable = this.mEnabledOnMultipleSelection && bIsEnabled;
	}
	if (document[this.mName]) {
		document[this.mName].src = (bEnable ? this.mEnabledImage : this.mDisabledImage);
	}
	this.mEnabled = bEnable;
}

function MMJ_getButton(oForm, sButtonName) {
	if (oForm.buttons) {
		for (var i = 0; i < oForm.buttons.length; i++) {
			if (oForm.buttons[i]) {
				if (oForm.buttons[i].mName == sButtonName) return oForm.buttons[i];
			}
		}
	}
	return null;
}

function MMJ_updateButtons(oForm) {
	var dummy = new Array();
	MMJ_updateButtons2(oForm, dummy);
}

function MMJ_updateButtons2(oForm, aSelectedItems) {
	if (oForm.buttons) {
		for (var i = 0; i < oForm.buttons.length; i++) {
			if (oForm.buttons[i]) oForm.buttons[i].update(aSelectedItems);
		}
	}
}

// supporto multilingua
function MMJLanguage(sName, sLanguage, sReferer, oForm, bSelected) {
	this.mName = sName;
	this.mLanguage = sLanguage;
	this.mOwnerForm = oForm;
	this.mReferer = sReferer;
	this.mSelected = bSelected;
	this.mLastState = bSelected;
	this.click = MMJLanguage_click;
}

function MMJLanguage_click() {
	this.mSelected = true;
	this.mLastState = false;
	MMJ_updateLanguages(this.mOwnerForm, this.mName);
}

function MMJ_updateLanguages(oForm, sName) {
	if (oForm.languages) {
		var oLan;
		var obj;
		for (var i = 0; i < oForm.languages.length; i++) {
			oLan = oForm.languages[i];
			oLan.mSelected = (oLan.mSelected && !oLan.mLastState);
			oLan.mLastState = oLan.mSelected;
			if (oLan.mName === sName) {
				obj = getObject(oLan.mReferer);
				if (obj) obj.style.display = (oLan.mSelected ? 'block' : 'none');
				if (oLan.mSelected) MMJ_selectFocused(oForm.elements[sName + '_' + oLan.mLanguage]);
			}
		}
	}
}

function MMJ_getLanguage(oForm, sName, sLanguage) {
	if (oForm.languages) {
		var oLan;
		for (var i = 0; i < oForm.languages.length; i++) {
			oLan = oForm.languages[i];
			if (oLan.mName == sName && oLan.mLanguage === sLanguage) return oLan;
		}
	}
	return null;
}

function MMJ_syncAllLanguages(oForm, sLanguage) {
	if (oForm.languages) {
		var oLan;
		var obj;
		for (var i = 0; i < oForm.languages.length; i++) {
			oLan = oForm.languages[i];
			obj = getObject(oLan.mReferer);
			oLan.mSelected = (oLan.mLanguage == sLanguage);
			oLan.mLastState = oLan.mSelected;
			if (obj) obj.style.display = (oLan.mSelected ? 'block' : 'none');
		}
	}
}
// fine supporto multilingua

/**

MMJ_setEvidenceColor: imposta il valore della variabile globale baseColor
------------------------------------------------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
oColor					colore da impostare

OUTPUT: void

**/
function MMJ_setEvidenceColor(sColor) {
	baseColor = sColor;
}

/**

MMJ_switchBackgroundColor: scambia il colore di sfondo dell'elemento con quello della variabile globale baseColor
-----------------------------------------------------------------------------------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
oElement				elemento da modificare

OUTPUT: void

**/
function MMJ_switchBackgroundColor(oElement) {
	if (oElement) {
		var tmp = oElement.style.backgroundColor;
		oElement.style.backgroundColor = baseColor;
		baseColor = tmp;
	}
}

/**

MMJ_countChars: conta i caratteri presenti nell'elemento specificato e aggiorna il contatore
--------------------------------------------------------------------------------------------
author: Luca Beltrame
updated: 2006/06/13

INPUT:
oElement				elemento da selezionare
oCounter				contatore
iMaxLenght				lunghezza massima del testo

OUTPUT: void

**/
function MMJ_countChars(oElement, oCounter, iMaxLength) {
	if (oElement && oCounter && iMaxLenght > 0) {
		var len = oElement.value.length;
		var chars = ((len > iMaxLength) ? 0 : iMaxLength - len);
		oCounter.value = chars;
		return chars;
	}
	return -1;
}

/**

MMJ_selectFocused: sposta il focus sull'elemento specificato
------------------------------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
oElement				elemento da selezionare

OUTPUT: void

**/
function MMJ_selectFocused(oElement) {
//	alert(oElement.name);
	if (oElement) {
		try {
			if (oElement.type && (oElement.type == "text" || oElement.type == "textarea") && oElement.value != "") oElement.select();
			oElement.focus();
		} catch (e) {}
	}
}

/*

MMJ_setVisibility: imposta la visibilità dell'elemento specificato
------------------------------------------------------------------
author: Luca Beltrame
updated: 2007/10/19

INPUT:
oElement				elemento da visualizzare
bVisible				impostazione di visibilità
sClass					classe del CSS da attribuire all'elemento

OUTPUT: void

*/
function MMJ_setVisibility(oElement, bVisible, sClass) {
	if (oElement) {
		try {
			if (bVisible) {
				oElement.style.display = 'block';
				oElement.style.visibility = 'visible';
			} else {
				oElement.style.display = 'none';
				oElement.style.visibility = 'hidden';
			}
			if (sClass) {
				oElement.setAttribute('class', sClass);
				oElement.setAttribute('className', sClass);
			}
		} catch (e) {}
	}
}

/*

MMJ_getVisibility: restituisce la visibilità dell'elemento specificato
----------------------------------------------------------------------
author: Luca Beltrame
updated: 2005/12/16

INPUT:
oElement				elemento da visualizzare

OUTPUT: boolean
		impostazione di visibilità dell'elemento

*/
function MMJ_getVisibility(oElement) {
	if (oElement) {
		try {
			return (oElement.style.display == 'block' && oElement.style.visibility == 'visible');
		} catch (e) {}
	}
	return false;
}

/**

MMJ_mmcode_title: codificata l'inserimento di un titolo in un messaggio del CRM
-------------------------------------------------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
oArea					TextArea di destinazione
oTitle					titolo (Text o altro)

OUTPUT: void

**/
function MMJ_mmcode_title(oArea, oTitle) {
	if (oArea && oTitle) {
		oArea.value = oArea.value + '{TITLE="' + oTitle.value + '"}';
		oTitle.value = '';
	}
}

/**

MMJ_mmcode_URL: codificata l'inserimento di un URL in un messaggio del CRM
--------------------------------------------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
oArea					TextArea di destinazione
oURL					URL (Text o altro)
oDesc					descrizione URL (Text o altro)

OUTPUT: void

**/
function MMJ_mmcode_URL(oArea, oURL, oDesc) {
	if (oArea && oURL && oDesc) {
		oArea.value = oArea.value + '{URL="' + oURL.value + '"="' + oDesc.value + '"}';
		oURL.value = '';
		oDesc.value = '';
	}
}

/**

MMJ_mmcode_mail: codificata l'inserimento di un indirizzo e-mail in un messaggio del CRM
----------------------------------------------------------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
oArea					TextArea di destinazione
oMail					indirizzo e-mail (Text o altro)
oDesc					descrizione e-mail (Text o altro)

OUTPUT: void

**/
function MMJ_mmcode_mail(oArea, oMail, oDesc) {
	if (oArea && oMail && oDesc) {
		oArea.value = oArea.value + '{MAIL="' + oMail.value + '"="' + oDesc.value + '"}';
		oMail.value = '';
		oDesc.value = '';
	}
}

/**

MMJ_mmcode_image: codificata l'inserimento di un'immagine in un messaggio del CRM
---------------------------------------------------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
oArea					TextArea di destinazione
oImage					origine immagine (Select o File)
oLeft					RadioButton di allineamento dell'immagine a sinistra
oCenter 				RadioButton di allineamento dell'immagine al centro
oRight					RadioButton di allineamento dell'immagine a destra

OUTPUT: void

**/
function MMJ_mmcode_image(oArea, oImage, oLeft, oCenter, oRight) {
	if (oArea && oImage) {
		var imgValue = '';
		var align = '';
		if (oImage.type == "select-one") {
			var imgValue = oImage.options[oImage.selectedIndex].text;
		} else if (oImage.type == "file") {
			var imgValue = oImage.value;
			imgValue = imgValue.replace(/\\/g, '/');
			var parts = imgValue.split('/');
			imgValue = parts[parts.length - 1];
		}
		if (oLeft.checked) align = "left";
		else if (oCenter.checked) align = "center";
		else if (oRight.checked) align = "right";
		if (imgValue != '' && align != '') {
			oArea.value = oArea.value + '{IMAGE="' + align + '"="' + imgValue + '"}';
		}
	}
}

/**

MMJ_addOption: aggiunge un'opzione alla Select fornita
------------------------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
oSelect 				Select su cui operare
sText					descrizione dell'opzione
sValue					valore dell'opzione
bUnique 				inserire l'opzione solo se non è già presente il valore fornito?

OUTPUT: boolean
		restituisce True se l'inserimento ha avuto successo, False altrimenti

**/
function MMJ_addOption(oSelect, sText, sValue, bUnique) {
	if (oSelect) {
		var bFound = (sText == '' || sValue == '');
		if (bUnique) {
			for (var i = 0; i < oSelect.length; i++) {
				if(oSelect.options[i].value == sValue && oSelect.options[i].text == sText)
					bFound = true;
			}
		}
		if (!bFound)
			oSelect.options[oSelect.length] = new Option(sText, sValue);
		return (!bFound);
	} else {
		return false;
	}
}

/**

MMJ_copyOptions: copia le opzioni dalla Select di origine inserendole in quella di destinazione
-----------------------------------------------------------------------------------------------
author: Luca Beltrame
updated: 2008/08/29

INPUT:
oSelectFrom 			Select di origine
oSelectTo				Select di destinazione
bSelectedOnly			copiare solo le opzioni selezionate?
bUnique 				inserire l'opzione solo se non è già presente il valore fornito?

OUTPUT: void

**/
function MMJ_copyOptions(oSelectFrom, oSelectTo, bSelectedOnly, bUnique) {
	if (oSelectFrom && oSelectTo) {
		var oOption;
		var bFound = false;
		var j;
		for (var i = 0; i < oSelectFrom.length; i++) {
			oOption = oSelectFrom.options[i];
			if ((bSelectedOnly && oOption.selected) || !bSelectedOnly) {
				if (bUnique) {
					for (j = 0; j < oSelectTo.length; j++) {
						if (oSelectTo.options[j].value == oOption.value && oSelectTo.options[j].text == oOption.text)
							bFound = true;
					}
				}
				if (!bFound)
					oSelectTo.options[oSelectTo.length] = new Option(oOption.text, oOption.value);
			}
		}
	}
}

/**

MMJ_removeOptions: rimuove le opzioni dalla Select fornita ai parametri specificati
-----------------------------------------------------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
oSelect 				Select su cui operare
bSelectedOnly			rimuovere solo le opzioni selezionate?
sValue					valore delle opzioni da rimuovere

Se bSelectedOnly è falso e sValue è vuoto, rimuove tutte le opzioni
Se bSelectedOnly è vero e sValue è vuoto, rimuove solo le opzioni selezionate
Se bSelectedOnly è vero e sValue è valorizzato, rimuove solo le opzioni selezionate che hanno valore sValue
Se bSelectedOnly è false e sValue è valorizzato, rimuove solo le opzioni che hanno valore sValue

OUTPUT: void

**/
function MMJ_removeOptions(oSelect, bSelectedOnly, sValue) {
	if (oSelect) {
		var bRemove = false;
		for (var i = oSelect.options.length - 1; i >= 0; i--) {
			if (sValue) {
				bRemove = (sValue == oSelect.options[i].value);
			} else {
				if (bSelectedOnly && oSelect.options[i].selected)
					bRemove = true;
				else if(!bSelectedOnly)
					bRemove = true;
				else
					bRemove = false;
			}
			if (bRemove) oSelect.options[i] = null;
		}
	}
}

/**

MMJ_getOptionsValues: restituisce la lista dei valori della Select fornita
--------------------------------------------------------------------------
author: Luca Beltrame
updated: 2007/08/30

INPUT:
oSelect 				Select su cui operare
sSeparator				stringa di separazione tra elementi della lista
bSelectedOnly			solo le opzioni selezionate?

OUTPUT: lista delle opzioni sotto forma di stringa di valori e descrizioni
		<valore1><separatore><valore2><separatore>...<separatore><valoreN>

**/
function MMJ_getOptionsValues(oSelect, sSeparator, bSelectedOnly) {
	var sList = '';
	if (oSelect) {
		var oOption;
		for (var i = 0; i < oSelect.length; i++) {
			oOption = oSelect.options[i];
			if ((bSelectedOnly && oOption.selected) || !bSelectedOnly)
				sList += sSeparator + oOption.value;
		}
		sList = sList.substr(1);
	}
	return sList;
}

/**

MMJ_getOptionsList: restituisce la lista delle opzioni della Select fornita
---------------------------------------------------------------------------
author: Luca Beltrame
updated: 2008/08/29

INPUT:
oSelect 				Select su cui operare
sSeparator1 			stringa di separazione tra elementi della lista
sSeparator2 			stringa di separazione tra valore e descrizione
bSelectedOnly			solo le opzioni selezionate?

OUTPUT: lista delle opzioni sotto forma di stringa di valori e descrizioni
		<valore1><separatore2><descrizione1><separatore1><valore2><separatore2><descrizione2>...
		...<separatore1><valoreN><separatore2><descrizioneN>

**/
function MMJ_getOptionsList(oSelect, sSeparator1, sSeparator2) {
	var sList = '';
	if (oSelect) {
		for (var i = 0; i < oSelect.options.length; i++) {
			sList = sList + sSeparator1 + oSelect.options[i].value + sSeparator2 + oSelect.options[i].text;
		}
		sList = sList.substring(1, sList.length);
	}
	return sList;
}

/**

MMJ_popup: apre una finestra di popup
-------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
sTarget 				URL destinazione
sName					nome della finestra
sWidth					larghezza (in pixel o in percentuale) (default=400)
sHeight 				altezza (in pixel o in percentual) (default=300)
bResizable				popup ridimensionabile?
bScrollbars 			mostra le barre di scorrimento
iTop					margine superiore (in pixel)
iLeft					margine sinistro (in pixel)
bInternal				dimensioni interne? (default=false)

OUTPUT: void

**/
function MMJ_popup(sTarget, sName, sWidth, sHeight, bResizable, bScrollbars, iTop, iLeft, bInternal) {
	var re = new RegExp("^(100|([0-9]{1,2}(.[0-9]+)?))%$");
	var size = re.exec(sWidth);
	if (size) {
		sWidth = Math.ceil(screen.width * size[1] * 0.01);
		iLeft = 0;
	} else if (isNaN(sWidth)) {
		sWidth = document.width;
	} else {
		sWidth = Math.abs(sWidth);
	}
	size = re.exec(sHeight);
	if (size) {
		sHeight = Math.ceil(screen.height * size[1] * 0.01);
		iTop = 0;
	} else if (isNaN(sHeight)) {
		sHeight = document.height;
	} else {
		sHeight = Math.abs(sHeight);
	}
	var sParams = "menubar=0,toolbar=0,location=0,status=0";
	if (bResizable) sParams += ",resizable=1";
	else sParams += ",resizable=0";
	if (bScrollbars) sParams += ",scrollbars=1";
	else sParams += ",scrollbars=0";
	if (bInternal) {
		// hack per IE
		if (self.innerWidth == undefined) {
			sParams += ",width=" + (sWidth + 20);
			sParams += ",height=" + (sHeight + 6);
		}
		sParams += ",innerwidth=" + sWidth;
		sParams += ",innerheight=" + sHeight;
	} else {
		sParams += ",width=" + sWidth;
		sParams += ",height=" + sHeight;
	}
	if (iTop > 0) sParams += ",top=" + iTop;
	if (iLeft > 0) sParams += ",left=" + iLeft;
	return window.open(sTarget, sName, sParams);
}

/**

MMJ_syncSelect: sincronizza i valori di due Select gerarchiche
--------------------------------------------------------------
author: Luca Beltrame
updated: 2005/07/19

INPUT:
oSelMain				Select principale
oSelSub 				Select secondaria
bUseMain				sincronizzare in base a Select principale?
bForceValue 			forzare il valore della Select sincronizzata al primo valore
						corretto?
sSeparator				stringa di separazione tra valore principale e secondario

OUTPUT: void

**/
function MMJ_syncSelect(oSelMain, oSelSub, bUseMain, bForceValue, sSeparator) {
	var sVal1 = oSelMain.options[oSelMain.selectedIndex].value;
	var sVal2 = oSelSub.options[oSelSub.selectedIndex].value;
	var re = new RegExp("^" + sVal1 + sSeparator);
	var aResults = sVal2.match(re);
	if (aResults[0].length == 0) {
		var oSel;
		var bFound = false;
		var i = 0;
		if (bUseMain) {
			oSel = oSelSub;
		} else {
			oSel = oSelMain;
			re = new RegExp("^" + sVal2.substring(0, sVal2.indexOf(sSeparator)));
		}
		if (bForceValue) {
			while (i < oSel.options.length && !bFound) {
				aResults = oSel.options[i++].value.match(re);
				if (aResults) bFound = (aResults[0].length > 0);
			}
			if (bFound) oSel.selectedIndex = i - 1;
			else oSel.selectedIndex = 0;
		} else {
			oSel.selectedIndex = 0;
		}
	}
}

/**

MMJ_clearValues: resetta i valori della Form indicata
-----------------------------------------------------
author: Luca Beltrame
updated: 2007/01/04

INPUT:
oForm					Form da resettare
sPrefix 				prefisso degli elementi della Form da resettare, oppure,
						se preceduto da '!', da non resettare
						(se sPrefix.lenght=0 resetta tutti gli elementi)
bForceEmpty 			se true, ignora il valore di default degli elementi
						altrimenti lo mantiene

OUTPUT: void

**/
function MMJ_clearValues(oForm, sPrefix, bForceEmpty) {
	if (oForm) {
		var oElem;
		var bPreserve = (bForceEmpty ? false : true);
		var bPrefixLike = true;
		if (!sPrefix) sPrefix = "";
		if (sPrefix.charAt(0) == "!") {
			bPrefixLike = false;
			sPrefix = sPrefix.substring(1, sPrefix.length);
		}
		for (var i = 0; i < oForm.elements.length; i++) {
			oElem = oForm.elements[i];
			// a: bPrefixLike
			// b: name.substring(0,sPrefix.length) === sPrefix
			// !(a xor b)
			if (sPrefix.length == 0 || !(bPrefixLike ^ (oElem.name.substring(0, sPrefix.length) === sPrefix))) {
				switch (oElem.type) {
					case "hidden":
					case "password":
					case "text":
					case "textarea":
						oElem.value = "";
						break;
					case "select-one":
					case "select-multiple":
						var j = 0;
						var defaultIndex = -1;
						while (bPreserve && j < oElem.options.length && defaultIndex < 0) {
							if (oElem.options[j].defaultSelected) defaultIndex = j;
							j++;
						}
						oElem.selectedIndex = (defaultIndex < 0 ? 0 : defaultIndex);
						break;
					case "checkbox":
					case "radio":
						if (bPreserve) oElem.checked = oElem.defaultChecked;
						else oElem.checked = false;
						break;
				}
			}
		}
	}
}

/**

MMJ_getElementValue: ottiene il valore dell'elemento della form
---------------------------------------------------------------
author: Luca Beltrame
updated: 2005/10/14

INPUT:
oElement				elemento
bValue					flag: se true ottiene il valore dell'elemento, se false la chiave

OUTPUT: il valore dell'elemento fornito, null se non è
		del tipo corretto oppure undefined se sono verificati errori

**/
function MMJ_getElementValue(oElement, bValue) {
	if (oElement) {
		switch (oElement.type) {
			case 'hidden':
			case 'password':
			case 'text':
				return oElement.value;
			case 'textarea':
				if ((typeof tinyMCE)=='undefined') return oElement.value;
				else return tinyMCE.getContent();
			case 'file':
				return oElement.value;
			case 'select-one':
				var iIndex = oElement.selectedIndex;
				if (iIndex < 0) {
					return null;
				} else {
					if (bValue) return oElement.options[iIndex].text;
					else return oElement.options[iIndex].value;
				}
			case 'select-multiple':
				var aSelected = new Array();
				for (var i = 0; i < oElement.options.length; ++i) {
					if (oElement.options[i].selected) {
						if (bValue) aSelected.push(oElement.options[i].text);
						else aSelected.push(oElement.options[i].value);
					}
				}
				if (aSelected.length > 0) return aSelected;
				else return null;
			case 'checkbox':
			case 'radio':
				if (bValue) return (oElement.checked ? oElement.value : '');
				else return oElement.checked;
			default:
				return oElement.innerHTML;
		}
	}
	return undefined;
}

/**

MMJ_setElementValue: imposta il valore fornito all'elemento della form
----------------------------------------------------------------------
author: Luca Beltrame
updated: 2005/10/14

INPUT:
oElement				elemento

OUTPUT: il valore dell'elemento fornito, null se non è
		del tipo corretto oppure undefined se sono verificati errori

**/
function MMJ_setElementValue(oElement, newValue) {
	if (oElement) {
		switch (oElement.type) {
			case 'hidden':
			case 'password':
			case 'text':
			case 'textarea':
				oElement.value = newValue;
				break;
			case 'select-multiple':
				if (getObjectClass(newValue) == 'Array') {
					var iIndex = 0;
					while (iIndex < oElement.options.length)
						oElement.options[iIndex++].selected = false;
					var oldHandler = oElement.onChange;
					oElement.onChange = null;
					for (var i = 0; i < newValue.length; ++i) {
						iIndex = 0;
						while (iIndex < oElement.options.length && !bFound) {
							if (oElement.options[iIndex].value == newValue[i])
								oElement.options[iIndex].selected = true;
							iIndex++;
						}
					}
					oElement.onChange = oldHandler;
				} else if (isNaN(newValue)) {
					var iIndex = 0;
					var bFound = false;
					while (iIndex < oElement.options.length && !bFound) {
						bFound = (oElement.options[iIndex++].value == newValue);
					}
					if (bFound) iIndex--;
					else iIndex = 0;
					oElement.selectedIndex = iIndex;
				} else if (newValue != null) {
					oElement.selectedIndex = Number(newValue);
				}
				break;
			case 'select-one':
				if (isNaN(newValue)) {
					var iIndex = 0;
					var bFound = false;
					while (iIndex < oElement.options.length && !bFound) {
						bFound = (oElement.options[iIndex++].value == newValue);
					}
					if (bFound) iIndex--;
					else iIndex = 0;
					oElement.selectedIndex = iIndex;
				} else if (newValue != null) {
					oElement.selectedIndex = Number(newValue);
				}
				
				break;
			case 'checkbox':
			case 'radio':
				oElement.checked = (newValue ? true : false);
				break;
			default:
				oElement.innerHTML = newValue;
		}
	}
}

function MMJ_getAllElementsQuerystring(oForm) {
	var out = new Array;
	if (oForm) {
		var val = false;
		var j = 0;
		for (i = 0; i < oForm.elements.length; i++) {
			val = MMJ_getElementValue(oForm.elements[i]);
			if (val) out[j++] = oForm.elements[i].name + "=" + val;
		}
	}
	return out.join("&");
}

// imposta i valori predefiniti di checkbox e radio button: se iNum è positivo, imposta tutti quelli con prefisso sElem
function MMJ_setDefault(oForm, sElem, iNum) {
	if (oForm) {
		var oElem = null;
		if (iNum > 0) {
			for (var i = 0; i < iNum; i++) {
				oElem = oForm.elements[sElem + i];
				if (oElem.type == "radio" || oElem.type == "checkbox") oElem.defaultChecked = true;
			}
		} else {
			oElem = oForm.elements[sElem];
			if (oElem.type == "radio" || oElem.type == "checkbox") oElem.defaultChecked = true;
		}
	}
}

function MMJ_setElementLock(oElement, bLocked) {
	if (oElement) {
		try {
			oElement.disabled = bLocked;
			oElement.readOnly = bLocked;
		} catch(e) {}
	}
}

