
/*
 * @version Id: treeEvents.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
 */

//tree object
var tree;

var parcel;
var sectionsCount = 0;
var lastSection = 1100;
var lastSectionItem;
var lastSectionTitle;
var lastSectionControlsXML;
var lastSectionFormsXML;
var wizardDimensions;

// shows URL data length when the wizard data is sent
// useful to test if length approaches 2048 bytes
var debugShowPackedDataLength = false;

//load tree on page
function loadTree(){
	tree = new dhtmlXTreeObject("treebox","100%","100%",0);
	tree.setImagePath("dhtmlxTree/imgs/");
	tree.enableDragAndDrop(false);
	//tree.setOnClickHandler(doOnSelect);
	tree.setOnDblClickHandler(doOnDoubleClick);
	tree.loadXML("tariffe.php");
}


// Javascript callbacks (Prototype)



// 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 inserted by "insertSection()"
function evaluateNewSection() {

	wizard.hide();

	// original URL
	var pars = 'action=calculate&new=true&sectionId=' + lastSection + '&itemId=' + lastSectionItem + '&xml=' + encodeURIComponent(lastSectionControlsXML);

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

	if (BrowserDetect.browser == 'Explorer' && encodedPars.length > 2048)
		alert('ERRORE GRAVE: URL troppo lungo. Contattare gli amministratori di sistema');
		
	if (debugShowPackedDataLength)
		alert("Lunghezza URL calcolo: " + encodedPars.length);
        
	new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: encodedPars, onFailure: reportError, onComplete: insertSection});

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

function responseInsertSectionError(param) {

}
/*
 * this function is called by "treeEvents.js::evaluateNewSection()" after the section has been calculated
 * the param value contains the data in XML format to be inserted in the new section
 * The format is as follows:
 * <section>
 *    <header>$header</header>
 *    <title>$title</title>
 *    <content>$content</content>
 *    <summary>$summary</summary>
 * </section>
 */
function insertSection(param) {

    //alert(param.responseText);
    //return;
    
    if (param.responseText == "<demo/>")
    	return;
    	
    if (demoMode && demoInsert)
    	alert("Attenzione!\nNella versione dimostrativa il calcolo viene eseguito con un importo prefissato dal programma.");
    
	//setCursor("wait");
	
	dumpString(param.responseText, 1);
	var section = createSection(lastSection, param.responseText);

	// this happens when the php calculation has errors, so responseText does not contain a valid XML string
	// the section cannot be inserted so it must be deleted also in the server
	if (section == -1) {
		var pars = 'action=listDeleteSection&sectionId=' + lastSection;
		new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: responseInsertSectionError});
		return;
	}
	// xml simply contains the error tag: do nothing
	if (section == false)
		return;
	

	var html = getEditorHTML();
	dumpString(html, 2);

	// insert before totals
	var result = getParcelDivById(html, "totals");
	var pos = result.split("-");
	// go back by section closing </div> length
	var insertPos = pos[0] - 6;
	//var insertPos = pos[0] - 6;
	html = html.substring(0, insertPos) + section + html.substring(insertPos);

	addListSection(lastSection, "");//"Sez.");// + lastSection);
	
	lastSection = lastSection + 100;
	sectionsCount++;
	
	updateEditor(html);
	dumpString(html, 2);

	// one of the three calls of updateDependentSections
	updateDependentSections(lastSection - 100);
	
	//updateTotals();
	setCursor("auto");
}

/* 
 * this function saves all controls in the lastSectionControlsXML var and launches the wizard providing title from xml
 * 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 treeCallback(param) {
	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();
	
	dumpString(param.responseText, 1);
			
	var i, xmlChilds = root.getChildNodes();
    
    wizardDimensions = WIZARD_OPTIONS; // default size
	
	// by default, allow insertion
	demoInsert = true;
	
	for (i = 0; i < xmlChilds.getLength(); i++) {
		var item = xmlChilds.item(i);
		var name = '' + item.getNodeName();
        if (name == TAG_WINSIZE)
            wizardDimensions = '' + item.getFirstChild().getNodeValue();
        else if (name == TAG_TITLE)
			lastSectionTitle = '' + item.getFirstChild().getNodeValue();
		else if (name == TAG_CONTROLS)
			lastSectionControlsXML = item.getXML();
		else if (name == TAG_FORMS)
			lastSectionFormsXML = item.getXML();
		else if (name == TAG_DEMO) {
			demoInsert = false;
			alert("Attenzione!\nNella versione dimostrativa i dati inseriti nella finestra seguente non produrranno alcun testo in parcella.");
		}
	}
	var pars = "action=treeLaunchWizard&id=" + lastSectionItem;
    
    //alert(PHP_RESPONSE_FILE);
	new Ajax.Updater("wizard-div", PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: treeInitWindow});
}

function treeInitWindow(param) {

    //alert(param.responseText);

    if(param.responseText == "already_inserted")
    {
        alert("Una prestazione di questo tipo e' gia' stata inserita nella parcella, non e' possibile inserirne una nuova");
        setCursor("auto");
        return false;
    }
    
	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
	wizard = dhtmlwindow.open(wizardId, 'div', 'wizard-div', lastSectionTitle, wizardDimensions); // WIZARD_OPTIONS);   
                                    
    //alert(wizardDimensions);
    
    // init wizard state firing contols events
	initWizardEvents(lastSectionControlsXML);
    
    //init wizard form validator
    initWizardFormValidator(lastSectionFormsXML);
    setCursor("auto");
}

function doOnDoubleClick(itemId){
	setCursor("wait");
	// if the node selected has depth = 2, it is a terminal node
	var depth = tree.getLevel(itemId);
	if (depth == 3 || depth == 4 || ((depth == 2) && (!tree.hasChildren(itemId))))  {
		lastSectionItem = itemId;
	
		var pars = 'action=treeDblClick&id=' + itemId;
		//alert(pars);
		new Ajax.Request(PHP_RESPONSE_FILE, {method: 'get', parameters: pars, onFailure: reportError, onComplete: treeCallback});
	}
	else
    {
		alert("Il nodo selezionato non e' una prestazione.");
		setCursor("auto");
    }
}

/*
	Old code for inserting the section with the parser
	// HTML document parsing and new section inserting
	var doc = createDomParser(html);	
	var root = doc.getDocumentElement();
			
	var childs = root.getChildNodes();
	for (i = 0; i < childs.getLength(); i++) {
		var attributes = childs.item(i).getAttributes();
		if (attributes.getNamedItem("id").getNodeValue() == "sections") {

			// new Div
			var divSection = doc.createElement("div");
			
			var divSectionContent = doc.createTextNode(sectionText);
			divSection.appendChild(divSectionContent);			

			// access div attributes (empty)
			var divSectionAttributes = divSection.getAttributes();

			// create new attribute
			var idAttribute = doc.createAttribute("id");
			idAttribute.setNodeValue(lastSection);			
			var retVal = divSectionAttributes.setNamedItem(idAttribute); // add attribute to attribute collection			

			var styleAttribute = doc.createAttribute("style");
			styleAttribute.setNodeValue(
				"margin: 5px 0px 5px 0px;" +
				"border: 1px;" +
				"padding: 5px 5px 5px 5px;" +
				"font: normal bold 12px arial;" +
				"text-align: left;" +
				"background-color: #f8f8f8;"
			);			
			retVal = divSectionAttributes.setNamedItem(styleAttribute); // add attribute to attribute collection			

			// add Div
			childs.item(i).appendChild(divSection);
			
			addListSection(lastSection, lastSection);
			
			lastSection = lastSection + 100;
			break;
		}
	}
	// editor update
	updateEditor(doc.getXML());
*/