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

// list object
var list;

// current selected section id
var selectedSection = 0;
// current selected section style
var oldStyle = "";
// wizard dimensions
var wizardDimensions;

// show or not the wizard using dhtmlwindow
var useOldStyleWizard = true;

function loadList() {

	list = new dhtmlXTreeObject("listbox","100%","100%",0);
	list.setImagePath("dhtmlxTree/imgs/");
	list.enableDragAndDrop(false);
	list.setOnClickHandler(doOnSelectSection);
	list.setOnDblClickHandler(doOnEditSection);
	list.loadXML("loadlist.php");
}

// MAPPING BETWEEN STANDARD SECTIONS HTML ID NAMES AND STANDARD SECTIONS LIST ID NAMES
// The two following functions define a correspondence
// retrieves node id from div id (string)
function getId(name) {
	if (name == "author")
		return 100;
	if (name == "date")
		return 200;
	if (name == "detail")
		return 300;
	if (name == "object")
		return 800;
	if (name == "totals")
		return 900;
	if (name == "sections")
		return 1000;
		
	var id = parseInt(name);
	if (!isNaN(id))
		return id;
	return name;
}

// retrieves div id (string) from node id
function getName(id) {

	if (id == 100)
		return "author";
	if (id == 200)
		return "date";
	if (id == 300)
		return "detail";
	if (id == 800)
		return "object";
	if (id == 900)
		return "totals";
	if (id == 1000)
		return "sections";
		
	return id;
}

// add list section at the end
function addListSection(sectionId, sectionText) {

	if (!list.hasChildren(1000))
		list.insertNewChild(1000,sectionId,sectionText,0,0,0,0,"");
	else {
		var childs = "" + list.getAllSubItems(1000);
		var items = childs.split(",");
		list.insertNewNext(parseInt(items[items.length - 1]),sectionId,sectionText,0,0,0,0,"");
	}    
    
    // retrieve section name 
    if(sectionText == "")
    {       
        var pars = "action=listSetSectionTitle&sectionId=" + sectionId;
        new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: listSetSectionTitle});         
    }
}

function listSetSectionTitle(param)
{
    //alert(param.responseText);
    
    if(param.responseText != "")
    {
        var sep = param.responseText.indexOf(';');
        
        var id = param.responseText.substr(0, sep);
        var title = param.responseText.substr(sep+1, param.responseText.length-sep-1);
        
        list.setItemText(id, title, title);
        list.selectItem(id, true, false);
        //alert(title);
    }
}

// a note can be inserted if the currentSection is not occupied and it isn't a multiple of 100 (used for sections)
function noteSectionAvailable(currentSection) {

	if (list.getIndexById(currentSection) != null)
		return false;
	if ((currentSection % 100) == 0)
		return false;
	return true;
}

// insert a section after the one passed
function insertListSection(sectionId, newSectionId, sectionText) {
	list.insertNewNext(sectionId, newSectionId, sectionText,0,0,0,0,"");
}

// check if it is possible to add a note: selectedSection + 1 must be free
function setNoteAvailability() {

	$('addNote').disabled = selectedSection <= 1000 || !noteSectionAvailable(selectedSection + 1);
}

///////////////////////////////////////////////////////////////////////////////////////////////////

// "Adeguamento della tariffa secondo il Decreto Bersani" wizard close event: launch calculation
function evaluateAdaptSection() {

    if(useOldStyleWizard)
	    wizard.hide();
    else
        wizard.close();

	// create wrapped XML and encode it
	var wrappedData = wrapXML(lastSectionControlsXML);
	var pars = 'action=adaptCalculate&sectionId=' + selectedSection + '&xml=' + encodeURIComponent(wrappedData);

	if (checkURL(pars))
		new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: updateSection});
}

// "Adeguamento della tariffa secondo il Decreto Bersani" wizard launch
function listInitAdaptWindow(param) {

	//var html = param.responseText;
	dumpString(param.responseText, 2);

	if (!checkWizard())
		return false;

	// reset wizard page (that could be not empty if the user closed the window without finishing)
	wizardPage = '';
	// launch wizard
    if(useOldStyleWizard)
    {
	    wizard = dhtmlwindow.open(wizardId, 'div', 'wizard-div', lastSectionTitle, wizardDimensions); // WIZARD_OPTIONS); 
    }
    else
    {
        wizard = new DHTMLSuite.modalMessage( {isModal:true} );    // We only create one object of this class
        wizard.setWaitMessage('Caricamento dati - attendere prego....');
        wizard.setShadowOffset(5);    // Large shadow
        wizard.setSize(640,480);
        //wizard.setCssClassMessageBox("newdrag-contentarea");
        wizard.setShadowDivVisible(true); 
    
        DHTMLSuite.commonObj.setCssCacheStatus(true);
        //wizard.setHtmlContent("<input name='init' value='10'><p><a href='#' onclick='closeWizardWindow();return false'>Close</a></p>");
        
        wizard.setDomReference('wizard-div');
        wizard.display(true);
    }

	// init wizard values with the XML loaded form server (does nothing if this is a new item because xml doesn't contain values)
	initWizardValues(lastSectionControlsXML);
	// init wizard state firing contols events
	initWizardEvents(lastSectionControlsXML);
    
    //init wizard form validator
    initWizardFormValidator(lastSectionFormsXML);    

}

// "Adeguamento della tariffa secondo il Decreto Bersani" xml response
function responseAdaptSection(param) {
	
	var doc = createDomParser(param.responseText);	
	if (doc == null)
		return;
	var root = doc.getDocumentElement();

	if (root.getNodeName() == "stop") {
	
		alert("L'adeguamento non e' applicabile a questa prestazione");
		return;
	}
	
	lastSectionControlsXML = param.responseText;

	// other params are manually set
	lastSectionFormsXML = "<forms><form id=\"page1\" /></forms>";
	lastSectionTitle = 'Applica una riduzione/aumento alla prestazione';
	wizardDimensions = 'width=450,height=350,center=1,resize=1,scrolling=1';

	var pars = "action=listLaunchAdapt";
	new Ajax.Updater("wizard-div", PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: listInitAdaptWindow});
	
}

// "Adeguamento della tariffa secondo il Decreto Bersani" entry point
function adaptSection() {

	if ((selectedSection % 100) == 0) {
		// edit totals properties
		/*if (sectionId == 900) {
			var pars = 'action=listDblClick&sectionId=' + sectionId;
			new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: totalsWizardInit});
		}*/
		if (selectedSection > 1000) {
			var pars = 'action=listAdaptSection&sectionId=' + selectedSection;
			new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseAdaptSection});
		}
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////

//MANAGE DIFFERENT SECTIONS
function manageDifferentVersionWindow(param) {
	var wizDesc;
	if (param == null || param == "")
		return;

	// other params are manually set
	//lastSectionFormsXML = "<forms><form id=\"page1\" /></forms>";
	//lastSectionTitle = 'Aggiornamento della versione corrente';
	//wizardDimensions = 'width=440,height=130,center=1,resize=1,scrolling=1';
	wizDesc =  "<wizard id=\"versionWiz\" text=\"Aggiornamento dell'onorario alla versione corrente\" window_size=\"width=640px,height=500px,center=1,resize=1,scrolling=1\">" + 
    						"<form id=\"page1\" header=\"\">" +
    						param + 
    						"</form></wizard>";	

    						
	wizardDimensions = 'width=640px,height=500px,center=1,resize=1,scrolling=1';
	lastSectionTitle = "Aggiornamento dell'onorario alla versione corrente";
	lastSectionControlsXML = "<controls></controls>";
	//lastSectionFormsXML = "<forms><form id=\"page1\"></forms>";    					
    lastSectionFormsXML = "";
    
	var pars = "action=listLaunchVersion&xml=" + encodeURIComponent(wizDesc);
	//alert(wizDesc);
	//if (checkURL(pars))
	//{name: "johnny", color: "blue"}
	//new Ajax.Updater("wizard-div", PHP_RESPONSE_FILE, {method: 'post', parameters: pars, onFailure: reportError, onComplete: listInitWindow});
	
	new Ajax.Updater("wizard-div", PHP_RESPONSE_FILE, {method: 'post', postBody: pars, onFailure: reportError, onComplete: listInitWindow});
	//listInitWindow(param);
}

////////////////////////////////////////////////////////////////////////////////////////////////////

function removeAllSectionsStyle(){
    var oIframe = document.getElementById("mce_editor_0");
    var oDoc = oIframe.contentWindow || oIframe.contentDocument;
    if (oDoc.document) {        
        //getAll section items
        var childs = "" + list.getAllSubItems(1000);
        var items = childs.split(",");
		//resetAllSection Item
		if (items != null){
			var elementById;
			for (var i=0; i < items.length; i++){
				elementById = oDoc.document.getElementById(items[i]);
				if (elementById != null)
					elementById.removeAttribute("style");
			}
		}
    }
}

function setSectionStyle(itemToSet, valueToSet){
    var oIframe = document.getElementById("mce_editor_0");
    var oDoc = oIframe.contentWindow || oIframe.contentDocument;
    if (oDoc.document) {       
    	var elementById; 
		elementById = oDoc.document.getElementById(itemToSet);
		if (elementById != null)
			elementById.style.backgroundColor = valueToSet;		
    }	
}

// When the user clicks on a item of the sections list, that section has to be highlighted
// this function does this updating the old and the new selection
function doOnSelectSection(itemId){

	// if we select again the same section, do nothing
	if (selectedSection == itemId)
		return;		

	$('modify').disabled = itemId <= 1000;
	$('delete').disabled = itemId <= 1000;
	$('adapt').disabled = itemId <= 1000;
	//$('up').disabled = false;
	//$('down').disabled = false;

	// retrieve html code	
	var html = getEditorHTML();
	
	if (html == false) {
		alert('La tariffa contiene degli errori');
		return;		
	}

	var divId;

	try{
		
		// set new style	
		divId = getName(itemId);		
		removeAllSectionsStyle();
		setSectionStyle(divId, '#abf');			
		oldStyle = '#abf';
		selectedSection = itemId;
	}
	catch (e){
		alert('Impossibile selezionare la sezione desiderata');
		// list update
		
		list.deleteItem(divId);

		// delete section from database
		var pars = 'action=listDeleteSection&sectionId=' + divId;
		new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseDeleteSection});	
		
		// check add note availability
		setNoteAvailability();	
		
		return;				
	}
	
	// check add note availability
	setNoteAvailability();	
        
    // scroll to selected section
    scrollToSelectedSection();
    
}

// EVENT HANDLERS FOR COMMAND PANEL
/*
 * section editing: this function is the caller for section modification with the wizard
 * The xml structure is:
 * <data>
 * 	  <title>Wizard Title</title>
 *    <id>Item Id</id>
 *    <controls>
 * 	     <attribute id="attribute 1 id" type="attribute 1 type" value="attribute 1 value" />
 *       ....
 *    </controls>
 *    <forms>
 *	     <form id="form 1 id" srcid="source 1 id" srcvalue="source 1 value" [rule="rule"] />
 *       ....
 *    </forms>
 * </data>
 */
function listCallback(param) {

	//alert(param.responseText);
	
	if (param.responseText == "") {
		alert("La tariffa selezionata non e' valida o non e' ancora stata implementata");
		return;
	}
	
	var doc = createDomParser(param.responseText);	
	if (doc == null)
		return;
	var root = doc.getDocumentElement();
	
	if (root.getNodeName() == "error") {

		alert("Si sta tentando di modificare una prestazione creata con una tariffa scaduta\nRinnovare la tariffa seguente:\n" + root.getFirstChild().getXML());
		return;
	}

	if (root.getNodeName() == "version") {
		var xmlChilds = root.getChildNodes();
		var item = null;
		for (i = 0; i < xmlChilds.getLength(); i++) {
			item = xmlChilds.item(i);
			lastSectionControlsXML += item.getXML();
		}		
		manageDifferentVersionWindow(lastSectionControlsXML);
		//alert("Si sta tentando di modificare una prestazione creata con una tariffa scaduta\nRinnovare la tariffa seguente:\n" + root.getFirstChild().getXML());
		//return;
	}
	else{
	
		dumpString(param.responseText, 1);
				
		var i, xmlChilds = root.getChildNodes();
	    
	    wizardDimensions = WIZARD_OPTIONS; // default size      param.responseText;
		
		// by default, allow insertion
		demoInsert = true;
	
		for (i = 0; i < xmlChilds.getLength(); i++) {
			var item = xmlChilds.item(i);
	        if (item.getNodeName() == TAG_WINSIZE)
	            wizardDimensions = '' + item.getFirstChild().getNodeValue();
	        else if (item.getNodeName() == TAG_TITLE)
				lastSectionTitle = '' + item.getFirstChild().getNodeValue();
			else if (item.getNodeName() == TAG_ITEM_ID)
				lastSectionItem = '' + item.getFirstChild().getNodeValue();
			else if (item.getNodeName() == TAG_CONTROLS)
				lastSectionControlsXML = item.getXML();
			else if (item.getNodeName() == TAG_FORMS)
				lastSectionFormsXML = item.getXML();
		}
		var pars = "action=listLaunchWizard&id=" + lastSectionItem;
		new Ajax.Updater("wizard-div", PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: listInitWindow});
	}	
}

// ajax response retrieves HTML: show the wizard
function listInitWindow(param) {
	setCursor("wait");
	dumpString(param.responseText, 2);

	if (!checkWizard()){
		setCursor("auto");
		return false;
	}
	// reset wizard page (that could be not empty if the user closed the window without finishing)
	wizardPage = '';
	// launch wizard
    if(useOldStyleWizard)
    {
	    wizard = dhtmlwindow.open(wizardId, 'div', 'wizard-div', lastSectionTitle, wizardDimensions); // WIZARD_OPTIONS); 
    }
    else
    {
        wizard = new DHTMLSuite.modalMessage( {isModal:true} );    // We only create one object of this class
        wizard.setWaitMessage('Caricamento dati - attendere prego....');
        wizard.setShadowOffset(5);    // Large shadow
        wizard.setSize(640,480);
        //wizard.setCssClassMessageBox("newdrag-contentarea");
        wizard.setShadowDivVisible(true); 
    
        DHTMLSuite.commonObj.setCssCacheStatus(true);
        //wizard.setHtmlContent("<input name='init' value='10'><p><a href='#' onclick='closeWizardWindow();return false'>Close</a></p>");
        
        wizard.setDomReference('wizard-div');
        wizard.display(true);
    }
    
	// FIXME: check if this code works correctly in all cases for all controls
	// init wizard values with the XML loaded form server (does nothing if this is a new item because xml doesn't contain values)
	initWizardValues(lastSectionControlsXML);
	// init wizard state firing contols events
	
	initWizardEvents(lastSectionControlsXML);

	// initWizardEvents could have changed some controls values: reset the original one
	initWizardValues(lastSectionControlsXML);
    
    //init wizard form validator
    initWizardFormValidator(lastSectionFormsXML); 
    setCursor("auto");
}

function closeWizardWindow()
{
    wizard.close();
    setCursor("auto");
} 

// -------------------------------------  TOTALS OPTIONS -----------------------------------------
function responseTotalsWizardClose(param) {

	if (param.responseText.length > 0) {
		alert(param.responseText);
		//setCursor("auto");
	}
	else
		updateTotals();
}

// totals wizard close
function totalsWizardClose() {

	//setCursor("wait");
	
	hide('totals-div');
	display('WAIT_DIV');			
	if(useOldStyleWizard)
        wizard.hide();
    else
        wizard.close();
	
	// update totals properties and send to the server
	// updateTotals is declared in utilScripts.js
	var result = updateTotalsOptions(lastSectionControlsXML);
	if (result == false)
		return false;
	
	lastSectionControlsXML = result;
	
	dumpString(lastSectionControlsXML, 2);
	// update totals
	var pars = 'action=updateParcelTotalsOptions&xml=' + encodeURIComponent(lastSectionControlsXML);
	//if (checkURL(pars))
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'post', postBody: pars, onFailure: reportError, onComplete: responseTotalsWizardClose});
}

// totals wizard open
function totalsWizardOpen(param) {

	wizardPage = '';
	// launch wizard
    if(useOldStyleWizard)
	{
        wizard = dhtmlwindow.open(wizardId, 'div', 'wizard-div', "Totali", TOTALS_WIZARD_OPTIONS);
    }
    else
    {
        wizard = new DHTMLSuite.modalMessage( {isModal:true} );    // We only create one object of this class
        wizard.setWaitMessage('Caricamento dati - attendere prego....');
        wizard.setShadowOffset(5);    // Large shadow
        wizard.setSize(700,600);
        //wizard.setCssClassMessageBox("newdrag-contentarea");
        wizard.setShadowDivVisible(true); 
    
        DHTMLSuite.commonObj.setCssCacheStatus(true);
        //wizard.setHtmlContent("<input name='init' value='10'><p><a href='#' onclick='closeWizardWindow();return false'>Close</a></p>");
        
        wizard.setDomReference('wizard-div');
        wizard.display(true);
    }
}

// totals wizard init
function totalsWizardInit(param) {

	lastSectionControlsXML = param.responseText;
	var pars = "action=listLaunchWizard&id=900";
	new Ajax.Updater("wizard-div", PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: totalsWizardOpen});	
}

// ------------------------------------- END TOTALS OPTIONS -----------------------------------------

// entry point for a section to be edited (include the totals case)
function doOnEditSection(sectionId) {
        var pars;
	if ((sectionId % 100) == 0) {
		// edit totals properties
		if (sectionId == 900) {
			pars = 'action=listDblClick&sectionId=' + sectionId;
			new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: totalsWizardInit});
		}
		if (sectionId > 1000) {
			pars = 'action=listDblClick&sectionId=' + sectionId;			
			new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: listCallback});
		}
	}
}

// this function is called by wizardEngine.js::endWizard(), it closes the wizard and launches the calculation on the server
// At the end of the calculation, the new section is replaced by "updateSection()"
function evaluateModifiedSection() {

    if(useOldStyleWizard)
	    wizard.hide();
    else
        wizard.close();

	// original URL
	var originalPars = 'action=calculate&new=false&sectionId=' + selectedSection + '&itemId=' + lastSectionItem + '&xml=' + encodeURIComponent(lastSectionControlsXML);

	// create wrapped XML and encode it
	var wrappedData = wrapXML(lastSectionControlsXML);
	var pars = 'action=calculate&new=false&sectionId=' + selectedSection + '&itemId=' + lastSectionItem + '&xml=' + encodeURIComponent(wrappedData);

	if (checkURL(pars))
		new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: updateSection});

	dumpString('Original URL data length: ' + originalPars.length + '\nEncoded data length: ' + pars.length + '\n<<DATA>>\n' + wrappedData, 1);
}

function updateSection(param) {

    //alert(param.responseText);
    //return;
    if (demoMode && demoInsert)
    	alert("Attenzione!\nNella versione dimostrativa il calcolo viene eseguito con un importo prefissato dal programma.");
    
	var section = createSectionText(param.responseText);
	if (section == false || section == -1)
		return;
	
	var html = getEditorHTML();


	var indexes = getParcelDivById(html, "" + selectedSection);
			
	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(html, 2);

	// one of the three calls of updateDependentSections
    updateDependentSections(selectedSection);	
	//updateTotals();
	setCursor("auto");
}

// mapping for doubleClick action
function modifySection() {

	doOnEditSection(selectedSection);
}

// note added: save html to server to set new structure
function responseAddNote(param) {
	
	if (param.responseText.length > 0)
		alert(param.responseText);
	
	//removeAllSectionsStyle();
	
	var html = getEditorHTML();

	sendHTML(html);
}
/**/

// add a note after the selected section
function addNoteToSection(){
	//alert('Note addNote position');	
	var html = getEditorHTML();
	var indexes = getParcelDivById(html, "" + selectedSection);
	if (indexes == false || indexes == -1) {
		alert('Impossibile inserire la nota');
		return;
	}
	var index = indexes.split("-");
	html = html.substring(0, index[2]) + createNote("" + (selectedSection + 1)) + html.substring(index[2]);
	updateEditor(html);		
	
	insertListSection(selectedSection, selectedSection + 1, "Nota ");// + (selectedSection + 1));
	// another note cannot be inserted after this
	setNoteAvailability();
	
	var pars = 'action=addNote&sectionId=' + (selectedSection + 1);
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseAddNote});	
}

// section deleted: update dependent sections
function responseDeleteSection(param) {

	// one of the three calls of utilScripts.js::updateDependentSections(exclude)
    updateDependentSections(0);	
}

// delete the section from the editor content and the list control
function deleteSection() {

	// retrieve html code	
	var html = getEditorHTML();
	var divId = getName(selectedSection);
	
	html = removeDiv(html, divId);
	if (html == false || html == -1)
		return false;

	// list update
	list.deleteItem(selectedSection);

	// updateDependentSections automatically updates totals
    html = adjustListAndEditorAppereanceSequence(html);
	
	// update editor and DO NOT save html to server	(it will be done after the totals have being updated)
	updateEditor(html);

	// database update	
	var pars = 'action=listDeleteSection&sectionId=' + selectedSection;
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseDeleteSection});	

	// reset selection
	selectedSection = 0;
	oldStyle = "";
	// update sections count
	sectionsCount--;

	// there is no selection. Disable Note Button
	setNoteAvailability();
    
}

function adjustListAndEditorAppereanceSequence(html){
	//
	var concatStr = "";
	if (list.hasChildren(1000)){
		
		var childs = "" + list.getAllSubItems(1000);
		var items = childs.split(",");
		var listSequence = 1;		
		if (items != null){
			var listItemId;
			var notIsNote = false;
			//concatStr += "Items.length " + items.length;
			for (i = 0; i < items.length; i++){				
				listItemId = list.getItemText(items[i]);
				//concatStr += "|" + listItemId + "|" + listSequence + "|" + items[i] + ";";
				//alert(listItemId + ' ' + items[i]);
				if (listItemId == ""){
					notIsNote = false;	
				}
				else{
					if (listItemId.indexOf("Nota") > -1){
						notIsNote = false;
					}
					else{
						notIsNote = true;
					}					
				}
				if (notIsNote){	
					//list.setItemText(items[i], listSequence, listSequence);
					list.setItemText(items[i], listSequence, "Prestazione - " + listSequence + " + " + listItemId);
					//
					html = html.replace("Prestazione " + listItemId, "Prestazione " + listSequence);
					listSequence++;
				}
			}
			//alert(concatStr);
		}
	}
	else {
			//error
	}
	//alert(concatStr);
	return html;
}    

/*
Return a number from a section Id. Use for update section id in html editor.
*/
function getNumberFromSectionID($section_id){
	return ($section_id / 100) -10;
}

// if a parcel totals should be reloaded, update the field in database.
function responseCheckParcelAppearUpdated(param) {	
	if (param.responseText == "0"){
		var concatStr = "";
		var html = getEditorHTML();
		if (list.hasChildren(1000)){
			
			var childs = "" + list.getAllSubItems(1000);
			var items = childs.split(",");
			var listSequence = 1;
			var strToSearch;
			var strToReplace;
			var valueFromSectionId;
			if (items != null){
				var listItemId;
				var notIsNote = false;
				//
				for (i = 0; i < items.length; i++){				
					
					listItemId = list.getItemText(items[i]);
					//alert("ItemID " + listItemId + " " + items[i]);
					//
					if (listItemId == ""){
						notIsNote = false;	
					}
					else{
						if (listItemId.indexOf("Nota") > -1){
							notIsNote = false;
						}
						else{
							notIsNote = true;
						}					
					}
					if (notIsNote){	
						//
						valueFromSectionId = getNumberFromSectionID(items[i]);
						strToSearch = "Prestazione " + valueFromSectionId;
						strToReplace = "Prestazione " + listSequence;						
						html = html.replace(strToSearch, strToReplace);

						strToSearch = "Prestazione&nbsp;" + valueFromSectionId;
						strToReplace = "Prestazione&nbsp;" + listSequence;
						html = html.replace(strToSearch, strToReplace);
						
						listSequence++;
					}
				}
			}
		}
		else {
				//error
		}
		updateEditor(html);
	}
}

// placeholders for up and down buttons
//function upSection() {
//
//	alert('sectionTreeEvents.js::upSection() placeholder');
//}
//
//function downSection() {
//
//	alert('sectionTreeEvents.js::downSection() placeholder');
//}

function testComplete(param) {

	alert(param.responseText);
	var callback = document.getElementById('callback');	
}

//call parcel abort
function callParcelAbort(){
	var pars = "action=abortParcel";
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: abortCloseParcel});
}

// function to reset parcel structure or to exit in case of a critical error
function resetParcel(param) {
	var vConf;
	if (param == 'noAdvise'){
		vConf = true;
	}
	else{
		vConf = window.confirm('Utilizzare questo comando se si sono verificati degli errori nel salvataggio della parcella.\nChiudere la parcella senza salvare?');
	}
	//if (window.confirm('La parcella non pue' essere recuperata.\nSare' possibile continuare la sessione di lavoro.')) {
	if (vConf) {
		callParcelAbort();
	}
}

function scrollToSelectedSection()
{
    //document.location = "#pippo";
    //var objDiv = document.getElementById("1100");//editor-div");
    //alert(objDiv.offsetHeight);
    //objDiv.scrollTop = objDiv.scrollHeight;
    
    //var objDiv = document.getElementById("editor-div");
    //objDiv.scrollIntoView(true);
    //var objDiv = document.getElementById("mce_editor_0");
    //objDiv.scrollIntoView(true);
    //$('1100').scrollIntoView(true);
    //objDiv.scrollBy(0,50);
    //window.frames.mce_editor_0.scrollBy(0,100);
    //alert(window.frames.mce_editor_0.content.document.getElementById("1100").offsetParent);//scrollIntoView(true); 
    //alert("ffff");    
    //window.frames.mce_editor_0.scroll(100, 100);
    //alert(objDiv.scrollTop);//parentNode.parentNode.parentNode.scrollTop
    //objDiv.parentNode.parentNode.parentNode.parentNode.scrollTop = 1000;
    
    //alert(selectedSection);
   
    //alert(curr_section);
    
    var oIframe = document.getElementById("mce_editor_0");
    var oDoc = oIframe.contentWindow || oIframe.contentDocument;
    if (oDoc.document) {
        oDoc = oDoc.document;
        var pos = oDoc.getElementById("author").scrollHeight + oDoc.getElementById("date").scrollHeight + oDoc.getElementById("detail").scrollHeight;
        pos = pos + oDoc.getElementById("object").scrollHeight;
        
        var childs = "" + list.getAllSubItems(1000);
        var items = childs.split(",");
        var curr_section = items[0];
        var i=1;
        var divs_height = 0;
        while(curr_section != selectedSection && curr_section != "")
        {
           pos = pos + oDoc.getElementById(curr_section).scrollHeight;
           curr_section = items[i];
           //alert(curr_section);
           i++;
        }
        
        
        window.frames.mce_editor_0.scrollTo(0, pos);
    }
}

/* ------------------------------------- DISCLAIMER ------------------------------------------ */

function toggleDisclaimer(srcId, destId) {

	var src = $(srcId);
	var dest = $(destId);
	
	dest.disabled = !src.checked;		
}
	
/* ----------------------------- BEGIN GENERIC WIZARD FUNCTIONS ---------------------------- */

/*
	Open a wizard and manage controls
*/
function openWizard(wizType) {
	//
	if (wizType == 'importDB') {
		lastSectionTitle = 'Importazione parcelle';
		var pars = 'action=listLaunchGenWizard&wizId=importDB';
		new Ajax.Updater("wizard-div", PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: openWizardInitWindow});
	}
}


function openWizardInitWindow(param) {
	dumpString(param.responseText, 2);	
	if (!checkWizard()){
		//setCursor("auto");
		return false;
	}		
	// reset wizard page (that could be not empty if the user closed the window without finishing)
	wizardPage = '';
	// launch wizard	
	wizardDimensions = 'width=420,height=160,center=1,resize=1,scrolling=1';	
	wizard = dhtmlwindow.open(wizardId, 'div', 'wizard-div', lastSectionTitle, wizardDimensions); 
    //setCursor("auto");
}

function importDBClose() {
	setCursor("wait");
	//submit iframe form to upload file
	//$('fUpIFrame').contentDocument.forms['importDBForm'].submit();
	var iFrame = document.getElementById("fUpIFrame");
	if (iFrame != null){
		iFrame.contentWindow.document.forms['importDBForm'].submit();
	}

	//$('fUpIFrame').document.forms['importDBForm'].submit();
	hide('totals-div');
	display('WAIT_DIV');			
	wizard.hide();
}
/* This function is called from child iframe. This function show a message to user */
function importDBResponse(param, parcelID){
	if (param == 'ok'){
		//alert("Importazione avvenuta con successo!");
		//update parcel into browser: reload it.		
		var pars = "action=openParcel&id=" + parcelID;
		new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: reloadParcelResponse});
	}
	else{
		alert('Si sono verificati degli errori nell\'importazione del file locale.\n' + param);
	}
}
/**/
function reloadParcelResponse(param){
	//
	$('cmdFormSubmit').click();
	//$('commandForm').submit();
}




/* ----------------------------- END GENERIC WIZARD FUNCTIONS ---------------------------- */