
/*
 * @version Id: utilScripts.js 22/feb/07
 * @package Parcelle
 * @copyright Copyright (C) 2007 Andrea Bizzotto - Tecnobit S.R.L. All rights reserved.
 * @license 
 * Created on 22/feb/07
 */

// CONSTANTS
var PHP_RESPONSE_FILE = "requests.php";
var WIZARD_OPTIONS = "width=640px,height=480px,center=1,resize=1,scrolling=1"; 
                    //"width=640px,height=480px,left=300px,top=100px,resize=1,scrolling=1";

var TOTALS_WIZARD_OPTIONS = "width=625px,height=595px,left=300px,top=10px,resize=1,scrolling=1";

// TODO: update pixel width if content width is changed
var TABLE_WIDTH = BrowserDetect.browser == "Explorer" ? "100%"/*780px*/ : "100%";

var FONT_SIZE = "12px";

var STR_SAVE_ERROR = "Si e' verificato un errore temporaneo.\nProvare a salvare nuovamente la parcella.\nDettagli\n";

// demoMode tells if the demo user is working. It is set in wizardEngine.js::endWizard
var demoMode = false;
// demoInsert tells if the current item has to be inserted.
// It is set in treeEvents.js::treeCallback() and listEvents.js::listCallback()
var demoInsert = true;

// this var is used to tell client to anchor another section to the one being inserted
// it is set in createSection if specified in the xml
var nextSectionLinked = '';

// this var is set in initEvents.js::pageInit and tells if the user wants strict or loose save mode
var parcelSaveMode = "strict";

var debugMode = false;

// this vars are used to reference openwindows, timeout and counter after parcel export.
var openWindowRef;
var timeOutRef;
var counterRef;
//
// GENERAL PURPOSE FUNCTIONS

// function added to fix IE feature upper-casing all tags in FCKEditor
// used also for compatibility in stylesParser.js::createNewStyle
function convertTagsToLowerCase(html) {
	
	return html.toLowerCase();
}

function updateEditor(html) {
	
	if (checkNewHTML(html) == true)
		setEditorHTML(html);	
	else
		alert("Errore nella struttura HTML.\nL'operazione non puo' essere effettuata");
}

function debugErrorResponseMessage(param) {

	if (param.responseText.length > 2)
		alert("*" + param.responseText + "*");
}

function dumpResponse(param) {

	dumpString(param.responseText, 1);
}

function reportError(param) {
	if (param.responseText.length > 0)
		alert(param.responseText);
	else
	{
		alert('Ajax.onFailure');
		alert(param.status + " " + param.statusText);
	}
	setCursor("auto");
}

function createDomParser(xml) {

	var parser = new DOMImplementation();
	try {
		var xmlDomDoc = parser.loadXML(xml);
		return xmlDomDoc;
	}
	catch(e)
	{
	  alert("ERROR utilScripts.js::createDomParser exception:" + e + "\nDetails:\n" + xml);
	}
	return null;
}

function dumpString(str, target) {

	var controlId = target == 1 ? 'dump1' : 'dump2';
	if ($(controlId) != null)
		$(controlId).value = str;
}

// function to be called to verify that url length does not exceed IE maximum length
function checkURL(url) {

	if (BrowserDetect.browser == 'Explorer' && url.length > 2048) {
		//window.error('ERRORE GRAVE: URL troppo lungo. Contattare gli amministratori di sistema');
		alert('ERRORE GRAVE: URL troppo lungo. Contattare gli amministratori di sistema');
		return false;
	}
	return true;
}

function checkWizard() {
	if ($('wizard-div') != null && $('wizard-div').innerHTML == "") {

		alert("Attenzione: Il browser utilizzato non supporta alcune funzionalita' necessarie ad un corretto funzionamento.\nChiudere la parcella ed installare Firefox dal menu' principale.");
		return false;
	}
	return true;
}

function setCursor(cursorType) {		
	document.body.style.cursor = cursorType;	
	$('treebox').style.cursor = cursorType;
	$('listbox').style.cursor = cursorType;
	$('editor-div').style.cursor = cursorType;
	//
	$('bottom-left').style.cursor = cursorType;
	$('content').style.cursor = cursorType;	
	$('object').style.cursor = cursorType;
	$('totals').style.cursor = cursorType;
	$('upper-left').style.cursor = cursorType;
	$('left').style.cursor = cursorType;

}
/*
function setCursorType(x, cursorType){
	var x = document.getElementsByTagName("div");
	setCursorType(x, cursorType);
	//
	var x = document.getElementsByTagName("p");
	setCursorType(x, cursorType);
	//
	var x = document.getElementsByTagName("table");
	setCursorType(x, cursorType);	

	if (x != null){
		for (i=0;i<x.length;i++)
		{
			if (x[i] != null){
				if (x[i].style != null){
					x[i].style.cursor = cursorType;
				}
			}		
		} 		
	}
}
*/
// ------------------------------ FUNCTIONS TO CREATE SECTION HTML -----------------------------
/*
 * XML format. Temporary, handles "Adeguamento Bersani". See requests.php::calc()
 * <sectionData>
 *    <section total=$total [more=$item]>
 *       <item header="" title="" content="" />
 *       <item header="" title="" content="" />
 *       .....
 *    </section>
 *    <adapt body="" value="" />
 * </sectionData>
 */

// functions used to save HTML to server
function createSectionText(xml) {

	var i, j, k, header = '', title = '', content = '', summary = '';
	var doc = createDomParser(xml);
	if (doc == null)
		return -1;
	
	var root = doc.getDocumentElement();
	
	if (root.getNodeName() == "error") {
		alert(root.getFirstChild().getNodeValue() + "\nContattare gli amministratori di sistema");
		return false;
	}
	
	var sectionText =
		//"<table border=\"0\" cellspacing=\"0\" cellpadding=\"2\" style=\"width: " + TABLE_WIDTH + "; margin:0;table-layout:fixed;empty-cells:show;\"><tbody>";
		"<table class=\"secTable\"><tbody>";
	var adaptBody = '';
	var adaptExpBody = '';
	var adaptValue = '';
	var adaptHeader = '';
	var adaptIncDecrDescr = '';
	
	// reverse read: <adapt> must be read before <section>
	for (k = root.getChildNodes().getLength() - 1; k >= 0; k--) {
	
		var currentItem = root.getChildNodes().item(k);
		// read section total
		var attributes = currentItem.getAttributes();

		if (currentItem.getNodeName() == "adapt") {

			var adaptHeaderItem = attributes.getNamedItem("header");
			adaptHeader = adaptHeaderItem != null ? adaptHeaderItem.getNodeValue() : "Errore";
			
			var adaptBodyItem = attributes.getNamedItem("body");
			adaptBody = adaptBodyItem != null ? adaptBodyItem.getNodeValue() : "Errore";

			var adaptExpBodyItem = attributes.getNamedItem("exp_body");
			adaptExpBody = adaptExpBodyItem != null ? adaptExpBodyItem.getNodeValue() : "Errore";
						
			var adaptValueItem = attributes.getNamedItem("value");
			adaptValue = adaptValueItem != null ? adaptValueItem.getNodeValue() : "Errore";

			var adaptIncDecrDescrItem = attributes.getNamedItem("inc_dec");
			adaptIncDecrDescr = adaptIncDecrDescrItem != null ? adaptIncDecrDescrItem.getNodeValue() : "Errore";
						
		}		
		else if (currentItem.getNodeName() == "section") {
			/*
			var isLawyer, isLayerItem = attributes.getNamedItem("isALawyer");
			isLawyer = isLayerItem != null ? isLayerItem.getNodeValue() : "Errore";
			
			if (isLawyer == 'Y'){
				sectionText +=
					"<tr>" +
					"<td class=\"secTFCol\">" + 
					"<b>Articolo</b>" + 
					"</td><td class=\"";
				
				sectionText += "secSTColR\"";				
				sectionText += "\">Contenuto";
				//
				sectionText +=
					"</td><td class=\"secTTCol\">Spesa 1" + 
		            
		            "</td><td class=\"secTTCol\">Spesa 2</td></tr>";
				
			}
			else{
			*/
			var total, totalItem = attributes.getNamedItem("total");
			total = totalItem != null ? totalItem.getNodeValue() : "Errore";
			
			// NOTE: THIS CODE ALLOWS A SECTION TO BE POSSIBLY FOLLOWED BY ANOTHER ONE
			var more = attributes.getNamedItem("more");
			nextSectionLinked = more != null ? more.getNodeValue() : '';
			// END NOTE
			
			var childs = currentItem.getChildNodes();
			for (i = 0; i < childs.getLength(); i++) {
					
				// read all subsection data
				var attributes = childs.item(i).getAttributes();
		
				var header, headerItem = attributes.getNamedItem("header");        
				header = headerItem != null ? headerItem.getNodeValue() : "Errore";
		
		        var sectionTotalItem = attributes.getNamedItem("total");        
				
		        var alignType, alignTypeItem = attributes.getNamedItem("align_type");        
				alignType = alignTypeItem != null ? alignTypeItem.getNodeValue() : "";		
		
				// NOTE: It is not possible to specify table width: 100% because of another bug of Internet Explorer
				// other attributes placed by default by pinEdit: cellspacing=\"0\" cellpadding=\"0\" border=\"0\"
				sectionText +=
					"<tr>" +
					"<td class=\"secTFCol\">" + 
					"<b>" + header + "</b>" + 
					"</td><td class=\"";
				
				// BEGIN CPERON MODIFY
				if (alignType == "right"){
					sectionText += "secSTColR\"";
				}
				else {
					sectionText += "secSTColL\"";
				}
				
				sectionText += "\">";

				var rootContent, rootContentItem = attributes.getNamedItem("content");
				rootContent = rootContentItem != null ? rootContentItem.getNodeValue() : "";

				if (rootContent != ""){
					sectionText += rootContent ;
				}
				
				// END CPERON MODIFY
				
				var subChilds = childs.item(i).getChildNodes();
				for (j = 0; j < subChilds.getLength(); j++) {
					
					// read all subsection data
					var attributes = subChilds.item(j).getAttributes();
					
					var content, contentItem = attributes.getNamedItem("content");
					content = contentItem != null ? contentItem.getNodeValue() : "Errore";
					
					sectionText += "<p >" + content + "</p>";
				}
					
		        var totalText = "";        
		        if(sectionTotalItem != null)
		           totalText = sectionTotalItem.getNodeValue(); 
		              
				sectionText +=
					"</td><td class=\"secTTCol\">" + 
		            totalText + 
		            "</td></tr>";
			}
			// two totals	
			sectionText +=
				"<tr>" +
				"<td class=\"secFTCol\"></td>" + 
				"<td class=\"secSTColL\"></td>" + 
				"<td class=\"secTTCol\">" + 
				
				total + 
				"</td></tr>";
			if (adaptBody != "" || adaptExpBody != "") {
				var adjustmentDescr;
				//
				if (adaptIncDecrDescr == "reduction"){
					adjustmentDescr = "Riduzione";
				}
				else{
					adjustmentDescr = "Aumento";
				}
				
				//append header				
				if (adaptHeader != ""){
					adaptHeader = "<p>" + adaptHeader + "</p>";
				}
				//append body				
				if (adaptBody != ""){
					adaptBody = "<p>" + adaptBody + "</p>";
				}
				//append expensise body				
				if (adaptExpBody != ""){
					adaptExpBody = "<p>" + adaptExpBody + "</p>";
				}
								
				//
				sectionText +=
					"<tr>" +
					"<td class=\"secTFCol\"><strong>" + adjustmentDescr + "</strong></td>" + 
					"<td class=\"secSTColL\">" + adaptHeader + adaptBody + adaptExpBody +"</td>" + 
					"<td class=\"secTTCol\"></td>" + 					 
					"</tr>"+					
					"<tr>" +
					"<td class=\"secFTCol\"></td>" + 
					"<td class=\"secSTColR\">" + adjustmentDescr + "</td>" + 
					"<td class=\"secTTCol\">" + 					
					adaptValue + 
					"</td></tr>";
			}
		
			sectionText += "</tbody></table>";
		}
	}	
	return sectionText;
}

function createSection(sectionId, xml) {

	var sectionText = createSectionText(xml);
	// invalid xml
	if (sectionText == -1)
		return -1;
	// xml = <error>
	if (sectionText == false)
		return false;
		
	// javascript returns "unknown" if code returns directly the following string, so put it in a var
	var section = "<div id=\"" + sectionId + "\" class=\"section\">" + sectionText + "</div>";

	return section;
}

// function to add a comment to HTML (still not called)
function createNote(sectionId) {

	var section = 
		"<div id=\"" + sectionId + "\" class=\"detNote\">"+
		"<table width=\"100%\" style=\"font: normal 14px arial;padding: 0;\"><tr><td width=\"100%\"><label>Nota</label></td></tr></table></div>";	

	return section;
}
// ------------------------------ END FUNCTIONS TO CREATE SECTION HTML -----------------------------


// ------------------------------- UTIL HTML FUNCTIONS -------------------------------------
// - NORMALIZE AND SAVE PARCEL HTML
// - SEND HTML TO SERVER USING FRAMING
// functionality for framing html content to the server

var parcelOption = 'update';
var lastFrameSent = false;

function trimIndex() {

	var i, k = 0, pos = 1799;
	for (i = pos; i >= 0; i--) {
	
		if (parcelHTML.charAt(i) != '%')
			k++;
		else
			k = 0;
			
		if (k == 2)
			return i + k;
	}
	return 0;
}

function setPars(begin) {
	var option = "&option=" + (begin ? "begin" : parcelOption);
	if (parcelHTML.length == 0) {
		var pars = "action=composeHTML" + option;
		lastFrameSent = true;
	}
	else if (parcelHTML.length <= 1800) {
		var pars = "action=composeHTML" + option + "&code=" + parcelHTML;
		parcelHTML = "";
	}
	else {
		var index = trimIndex();
		var pars = "action=composeHTML" + option + "&code=" + parcelHTML.substring(0, index);
		//var pars = "action=composeHTML" + option + "&code=" + parcelHTML.substring(0, index);
		parcelHTML = parcelHTML.substring(index);
	}
	return pars;
}

// this is the last function called in every client procedure
function responseEndAction(param) {

	var doc = createDomParser(param.responseText);
	var root = doc.getDocumentElement();	
	var attributes = root.getAttributes();
	
	var response = '' + attributes.getNamedItem("response").getNodeValue();
	if (response == CATEGORIES_EXPIRED) {
	
		alert("E' terminato il periodo di validita' delle tariffe acquistate.\nE' necessario rinnovare l'abbonamento per continuare ad utilizzare il servizio.");
		$('cmdFormSubmit').click();
		//$('commandForm').submit();		
	}
/*	else if (response == TIME_NOT_ELAPSED) {
	
		var remaining = '' + attributes.getNamedItem("remaining").getNodeValue();
		var credits = '' + attributes.getNamedItem("credits").getNodeValue();
		//alert("L'accesso ha ancora " + remaining + " minuti di disponibilit�.");
	}
	else if (response == CREDITS_REMOVED) {
	
		var credits = '' + attributes.getNamedItem("credits").getNodeValue();
		var removed = '' + attributes.getNamedItem("removed").getNodeValue();
		alert("Sono stati scalati " + removed + " crediti dal conto.");
	}
	else if (response == INSUFFICIENT_CREDITS) {
			
		var credits = '' + attributes.getNamedItem("credits").getNodeValue();
		alert("E' terminato il numero di accessi a disposizione.\nE' necessario acquistare nuovi crediti per continuare ad utilizzare il servizio.");
		$('commandForm').submit();		
	}*/
}

function callEndAction() {

	// ends started action
	pars = "action=endAction";
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseEndAction});
}

function resendHTML(param) {

	if (param.responseText == "more") {

		if (lastFrameSent == false) {
		
			var pars = setPars(false);	
			new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: resendHTML});
		}
		else {			
			var pos = pars.indexOf("&code");
			var header = pos == -1 ? pars : pars.substring(0, pos);
			alert(STR_SAVE_ERROR + '[lastFrameSent = true, send = more]\n[header = ' + header + ' ]');
		}

		return;	
	}
	
	if (param.responseText == "stop") {

		if (parcelOption == 'save') {
			parcelOption = 'update';
			alert('Parcella salvata');
		}
		// alert('before submit');
		// submit form
		if (parcelOption == 'close'){
			$('cmdFormSubmit').click();
			//$('commandForm').submit();
		}
	}
	// alerts if the server has failed writing html to database
	else if (param.responseText == "break") {
	
		//alert(param.responseText);
		if (parcelOption == 'save') {
			parcelOption = 'update';
		}
		// submit form
		if (parcelOption == 'close') {
			parcelOption = 'update';
		}
		alert(STR_SAVE_ERROR + '[send = break]');		
		
	}
	else{
		//CPERON
		if (debugMode){
			alert('lastFrameSent ' + lastFrameSent);
			alert('Pars ' + pars);
		}
		
		alert(STR_SAVE_ERROR + '[send = ' + param.responseText + ']');
	}
		
	setCursor("auto");
	
	callEndAction();
	
}

function responseSendHTML(param) {

	// This code tries to send all html in one packet. it generally fails on a 414 error: url too long	
	// So, we must send html in frames of 2000 bytes maximum
	//var pars;
	//if (BrowserDetect.browser != "Explorer") {
	//	pars = "action=composeHTML&option=begin&code=" + parcelHTML;
	//	parcelHTML = "";	
	//}
	//else
	//	pars = setPars(true);
	
	pars = setPars(true);
	//CPERON
	if (debugMode){
		alert('responseSendHTML ' + pars.toString());
	}
	
	//pars = pars.substring(0, 1999)		
	
	//document.write(pars.toString());
	
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: resendHTML});
	
	//CPERON
	if (debugMode){
		alert('AFTER Ajax request ' + param.responseText);
	}
	
}

function sendHTML(html) {

	var pars;
	setCursor("wait");
	
	// restore background color for selected section	
	
	if (selectedSection != 0 && oldStyle != "") {
		divId = getName(selectedSection);
		setSectionStyle(divId, '#abf');
		/*
		divId = getName(selectedSection);
		result = setDivStyle(html, divId, oldStyle);
		if (result == false) {
			alert('Impossibile deselezionare la sezione desiderata');
			return;		
		}
		if (result != -1)
			html = result;
		// elsewhere html is the same
		*/
	}
	
	lastFrameSent = false;
	
	// this is the encoded packet to be sent
	// it will be broken up in frames
	parcelHTML = encodeURIComponent(html);

	// NOTE: this code tries to extract parcel object to write it into the database
	// this field will be shown in the parcel load manager.
	// if the operation is not possible, the code simply skips it and goes directly to html saving
	// elsewhere, html saving is done in "responseSendHTML", after the description has been saved
	var indexes = getParcelDivById(html, "object");

	// if description cannot be set
	if (indexes == false || indexes == -1) {
	
		// skip and go directly to parcel html saving
		pars = setPars(true);
		
		//CPERON
		if (debugMode)
			alert('Send HTML' + pars);
		
		new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: resendHTML});
	}
	else {
		
		var index = indexes.split("-");
		var description = html.substring(index[1], index[2] - 6);
		// first save parcel description
		pars = "action=setDescription&desc=" + encodeURIComponent(description);        
		new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseSendHTML});
	}
	setCursor("auto");
}

function abortCloseParcel(param){
	$('cmdFormSubmit').click();
		//$('commandForm').submit();
}

// function called by navigation.php::<a>Chiudi</a>
function saveParcel(option) {   
	parcelOption = option;
	removeAllSectionsStyle();
	html = getEditorHTML();
	if (html == false) {	
		if (window.confirm("La parcella contiene degli errori e non puo' essere salvata.\nUscire?")) {
			
			var pars = "action=abortParcel";
			new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: abortCloseParcel});
		}
	}
	else
    {
		sendHTML(html);	 
    }    
}
// ------------------------------- END UTIL HTML FUNCTIONS -------------------------------------

// ------------------------------ UTILITY FUNCTIONS TO PROMPT PARCEL HTML ---------------------------
// these two functions allow to retrieve HTML from the database
function responseGetHTML(param) {

	if (param.responseText.length > 0) {
		dumpString(param.responseText, 2);
		dumpString("HTML read successfully", 1);
	}
	else {
		dumpString("HTML read fail", 1);
	}
}

function getDbHTML() {

	var pars = "action=getHTML";
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseGetHTML});
}
// ------------------------------------- END  -----------------------------------------


// -------------------------------------  TOTALS OPTIONS -----------------------------------------
function updateTotalsOptions(xml) {

	var j;
	// update totals properties and send to the server
	var doc = createDomParser(xml);	
	if (doc == null)
		return false;
	var root = doc.getDocumentElement();

	var i, xmlChilds = root.getChildNodes();
	for (i = 0; i < xmlChilds.getLength(); i++) {
		var item = xmlChilds.item(i);
		var attributes = item.getAttributes();
		var controlId = '' + attributes.getNamedItem("id").getNodeValue();
		
		var controlCheck = attributes.getNamedItem("checked");
		if (controlCheck != null) {
			var control = $('check' + controlId);
			if (control != null)
				attributes.getNamedItem("checked").setNodeValue(control.checked ? "Y" : "N");
		}
		var controlPercent = attributes.getNamedItem("percent");
		if (controlPercent != null) {
			var control = $('edit' + controlId);
			if (control != null)
				attributes.getNamedItem("percent").setNodeValue(control.value);
		}
		var controlText = attributes.getNamedItem("text");
		if (controlText != null) {
			var control = $('edit' + controlId);
			if (control != null)
				attributes.getNamedItem("text").setNodeValue(control.value);
		}
		//update totals description
		var controlText = attributes.getNamedItem("name");
		if (controlText != null) {
			var control = $('name-edit' + controlId);
			if (control != null)
				attributes.getNamedItem("name").setNodeValue(control.value);
		}		
	}
	return doc.getXML();
}

function updatedUserTotalsOptions(param) {
	
	if (param.responseText == "")
		alert('I totali sono stati aggiornati');
	else
		alert(param.responseText);
}

function responseSetUserTotalsOptions(param) {

	// update totals properties and send to the server
	var userTotals = updateTotalsOptions(param.responseText);	
	if (userTotals == false)
		return false;
		
	// update totals
	var pars = 'action=updateUserTotals&xml=' + encodeURIComponent(userTotals);
	//if (checkURL(pars))
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'post', postBody: pars, onFailure: reportError, onComplete: updatedUserTotalsOptions});
}

function setUserTotalsOptions() {
	var pars = 'action=loadUserTotals';
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseSetUserTotalsOptions});
}

function responseResetUserTotalsOptions(param) {
	$('totals-form').submit();
}

function resetUserTotalsOptions() {
	var pars = 'action=resetUserTotals';
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseResetUserTotalsOptions});
}
// ------------------------------------- END TOTALS OPTIONS -----------------------------------------

// ------------------------------------- BEGIN PREFERENCES -----------------------------------------

function resetUserPreferencesOptions(parentSeqId) {
	var pars = 'action=resetUserPreferences&parentSeqId=' + parentSeqId;
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseResetUserPreferencesOptions});
}

function responseResetUserPreferencesOptions(param) {
	$('preferences-form').submit();
}

function setUserPreferencesOptions() {
	//
	var pars = $('preferences-form').serialize() + "&action=updatePreferences";
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete:  responseSetUserPreferencesOptions});
}

function responseSetUserPreferencesOptions(param) {
	var responseText = param.responseText;
	//
	if (responseText != null){
		if (responseText.indexOf('<error>') == -1){
			//write custom message based on udated preference
			alert('I parametri di ' + responseText + ' sono stati aggiornati');
		}
		else{
			alert(param.responseText);	
		}
	}
	else{
		alert("Si e' verificato un errore nell'aggiornamento delle preferenze");
	}	
}


// ------------------------------------- END PREFERENCES -----------------------------------------

// -------------------------------------- TOTALS CALCULATION --------------------------------------
/*
 * param contains an xml with all totals data to be set in the totals section of the parcel
 * XML Data:
 * <totals>
 *    <row desc='$desc' value='$euro $value' />
 *    <row desc='$desc' value='$euro $value' />
 *    <row desc='$desc' value='$euro $value' />
 * </totals>
 */
function responseUpdateTotals(param) {
	setCursor("wait");	
	xml = param.responseText;
	
	//alert(param.responseText);
	var doc = createDomParser(xml);
	var root = doc.getDocumentElement();
	
	if (root.getNodeName() == "error") {
		alert(responseRoot.getFirstChild().getNodeValue() + "\nContattare gli amministratori di sistema");
		return false;
	}
	var totalsHTML =
		"<table border=\"0\" cellspacing=\"0\" cellpadding=\"2\" style='width:" + TABLE_WIDTH + "; margin:0;'>";
	var childs = root.getChildNodes();
	for (i = 0; i < childs.getLength(); i++) {
		var attributes = childs.item(i).getAttributes();
		var desc = attributes.getNamedItem("desc").getNodeValue();
		var value = attributes.getNamedItem("value").getNodeValue();
		var note = attributes.getNamedItem("note");
		var note_value = "";
		var startFromFirstCol = (null != attributes.getNamedItem("startFromFirst"));
		
		if (note != null)
			note_value = attributes.getNamedItem("note").getNodeValue();
		
		if (note_value == ""){		
				totalsHTML += "<tr><td class='totColWide'>";
			    if (startFromFirstCol)
					   totalsHTML += desc; 			    					  
				totalsHTML += "</td><td class='totColNarrowCenter'>";
			    if (startFromFirstCol)
					   totalsHTML += value; 
				totalsHTML += "</td><td class='totColWide'>";
			    if (!startFromFirstCol)
					   totalsHTML += desc; 
				totalsHTML +="</td><td class='totColNarrowRight'>" ;
			    if (!startFromFirstCol)
					   totalsHTML += value; 
				totalsHTML += "</td></tr>";			
		}
		else {
			totalsHTML += "<tr><td colspan=\"4\" class='totNote'>" + note_value + "</td></tr>";						
		}			
	}
	totalsHTML += "</table>";
	
	//dumpString(totalsHTML, 2);
	
	//removeAllSectionsStyle();
	
	var html = getEditorHTML();

	totalsDiv = getParcelDivById(html, "totals");
	if (totalsDiv == false)
		return false;
	var pos = totalsDiv.split("-");
	// TODO check totals to be non-empty
	
	//alert(html.substring(pos[1]));
	html = html.substring(0, pos[1]) + totalsHTML + html.substring(pos[2] - 6);
	updateEditor(html);

	
	if (parcelSaveMode == "strict")
		sendHTML(html);
	else
		callEndAction();

	setCursor("auto");
}

function updateTotals() {

	var pars = 'action=updateTotals';
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseUpdateTotals});
}

/* Warning: the following XML is temporary and is the new DTD including the "Adeguamento Bersani" option. See requests.php::calc()
 *
 * <sections>
 *    <sectionData>
 *       <section id="section_id" total="total">
 *          <item header="item_header">
 *             <row content="content"/>
 *          </item>
 *       </section>
 *       <adapt body="" value="" />
 *    </sectionData>
 *    <sectionData>
 *       <section id="section_id" total="total">
 *        ....
 *       </section>
 *       <adapt body="" value="" />
 *    </sectionData>
 *    .....
 * </sections>
 */
function responseDependentSections(param) {

	var html = getEditorHTML();

	var doc = createDomParser(param.responseText);	
	if (doc == null)
		return;
	
	setCursor("wait");
	var root = doc.getDocumentElement();

	var i, j, rootChilds = root.getChildNodes();
    
    // <sections>
	for (i = 0; i < rootChilds.getLength(); i++) {
	
	    // <sectionData>
		var sectionData = rootChilds.item(i);

		for (j = 0; j < sectionData.getChildNodes().getLength(); j++) {

			// <section> or <adapt>
			var currentItem = sectionData.getChildNodes().item(j);
			
			// <section>
			if (currentItem.getNodeName() == "section") {

				var attributes = currentItem.getAttributes();
	
				var sectionId = '' + attributes.getNamedItem("id").getNodeValue();
		
				// NOTE: all sectionData XML must be passed to createSectionText(), which adds the adaption row if present
				var sectionsXML = '' + sectionData.getXML();
		
				var section = createSectionText(sectionsXML);
				if (section == false)
					return;
				
				var indexes = getParcelDivById(html, "" + sectionId);
						
				if (indexes != false && indexes != -1) {
			
					var index = indexes.split("-");
					//alert("left:\n" + html.substring(0, index[1]) + "\nsection\n" + section + "\nright\n" + html.substring(index[1]));
					html = html.substring(0, index[1]) + section + html.substring(index[2] - 6);
				}
			}
		}
	}
	
	updateEditor(html);
	//sendHTML(html);
	dumpString(param.responseText, 2);

	updateTotals();
	setCursor("auto");
}

function updateDependentSections(exclude)
{
    var pars = 'action=updateDependentSections&exclude=' + exclude;
    new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseDependentSections});
}
// ------------------------------------END TOTALS CALCULATION --------------------------------------


/*
 *  Remove all occurrences of a token in a string
 *    s  string to be processed
 *    t  token to be removed
 *  returns new string
 */
/*function remove(s, t) {
	i = s.indexOf(t);
	r = "";
	if (i == -1) return s;
	r += s.substring(0,i) + remove(s.substring(i + t.length), t);
	return r;
}*/

// ------------------------------------ EXPORT ---------------------------------------------------------
function exportParcel(type)
{
    if(type=='html')
    {
        var pars = 'action=printHTML';
        new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responsePrintHTML});
    }
    else if(type=='pdf')
    {
        //var pars = 'action=printPDF';
        //new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responsePrintPDF});    
        var win = window.open('outputPDF.php', 'Parcella', 'menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=800,width=680', false);
        //win.document.write(param.responseText);    
    }
    else if(type=='rtf')
    {
        //alert('Funzionalit� non ancora disponibile');
        var win = window.open('phprtflite/rtf/expToRtf.php', 'Parcella', 'menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=300,width=380', false);
        //var win = window.open('expToRtf.php', 'Parcella', 'menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=300,width=380', false);
    }   
    else if(type=='DB')
    {
        var win = window.open('impexp/expParcelDB.php', 'Parcella', 'menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=300,width=380', false);
		openWindowRef = win;
		counterRef = 0;
		timeOutRef = setTimeout("checkTimeOut()", 3000);
    }       
    else if(type=='file')
    {
        var win = window.open('outputHTML.php', 'Parcella', 'menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=800,width=680', false);
        //var pars = 'action=outputHTML';
        //new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseOutputHTML});        
    }     
}

function checkTimeOut(){	
	if (openWindowRef != null){
		if (!openWindowRef.closed && counterRef < 10){
			//sleep for 1 second before retry			
			counterRef++;
			timeOutRef = setTimeout("checkTimeOut()", 1000);
		}
		else{
			//check if delete exported parcel
		    var pars = 'action=checkDeleteAfterExport';
		    new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseCheckDeleteAfterExport});
		    clearTimeout(timeOutRef);
		}
	}
	else{
		clearTimeout(timeOutRef);
	}
}

// function called by navigation.php::<a>Guida</a>
function openHelp(param) {   
	var win;
	if (param != ""){
			win = window.open(param, 'Guida_in_linea', 'menubar=yes,status=yes,resizable=yes,scrollbars=yes,height=800,width=760', false);
	}
	else{
		win = window.open('help.htm', 'Guida_in_linea', 'menubar=yes,status=yes,resizable=yes,scrollbars=yes,height=800,width=760', false);
	}
		
}
/**
This function is used to increment perform opening files using firefox.
Click on document with link using attribute target="_blank" are very slow to open with firefox.
This function is a usefull workaround.
*/
function openDisciplinaryDocs(docId){
	var win = window.open('compDisciplinary.php?id=' + docId, 'Parcella', 'menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=300,width=380', false);	
}

function responsePrintHTML(param)
{
    //alert(param.responseText);      
    var win = window.open('', 'Parcella', 'toolbar=yes,menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=800,width=680', false);
    win.document.write(param.responseText);    
    win.document.close();
}

function responseOutputHTML(param)
{
    //alert(param.responseText);      
    //var win = window.open('', 'Parcella', 'menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=800,width=680', false);
   // win.document.write(param.responseText);    
}

function responsePrintPDF(param)
{

}

function loadSectionsOptions()
{
    var pars = 'action=loadHeaderHTML';
    new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: loadHeaderHTML});    

    pars = 'action=loadFooterHTML';
    new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: loadFooterHTML});        
}

function loadHeaderHTML(param)
{
    setHeaderHTML(param.responseText); 
}

function loadFooterHTML(param)
{
    setFooterHTML(param.responseText); 
}

function setSectionsOptions()
{
   //getHeaderHTML()
}

function responseCheckDeleteAfterExport(param){
	var responseText = param.responseText;
	if (responseText != null){
		if (responseText != ""){
			if (responseText.indexOf('<error>') == -1){
	        	var deleteAfterExpParams = responseText.split("&");
	        	if (deleteAfterExpParams != null){
	        		if (deleteAfterExpParams.length == 2){
						var tmpSplit;
						var autoDeleteAfterExport, confirmAutoDelete; 
						tmpSplit = deleteAfterExpParams[0].split("=");
						//
						autoDeleteAfterExport = tmpSplit[1];
						//
						tmpSplit = deleteAfterExpParams[1].split("=");
						//
						confirmAutoDelete = tmpSplit[1];
						//
						if (autoDeleteAfterExport == true){
							if (confirmAutoDelete == true){
								if (!window.confirm("Eliminare la parcella?\nQuesta operazione non potra' essere annullata.")) {
									autoDeleteAfterExport = false;
								}		
							}
							if (autoDeleteAfterExport == true){
								var pars = "action=deleteParcel";
								new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseSubmitDeleteParcel});
							}
						}
	        		}
	        	}
			}
			else{
				alert(param.responseText);	
			}			
		}				
	}
	else{
		alert("Si e' in fase di lettura delle preferenze di esportazione");
	}		
}

/*---------------------------------- MANAGE REGISTRATION HELP -----------------------------------*/

//Show and Hide Object using styles
function Hide(objId){
    document.getElementById(objId).style.visibility = 'hidden';
}

function Show(objId, message){	
	document.getElementById(objId).innerHTML = message;
    document.getElementById(objId).style.visibility = 'visible';
}

/*---------------------------------- GENERIC OPEN WINDOW -----------------------------------*/

function openWindow(theLink, height, width)
{
	window.open(theLink, 'Title', 'menubar=no,directories=no,height=' + height + ',width=' + width +',scrollbars=yes');
} 
