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

// Wizard related functions
var wizard;
var wizardId = "wizard";
var wizardPage = '';

// this var is used by the editboxes focusing and blurring to block the buttons state while editing
var wizardButtonsState = '';

// this string represents all select controls that depend on the value of other select controls and must be updated after
// their content has been changed
var pendingOperations = "<queue></queue>";

var mutexCheckboxState = 0;

var initWizardDone;

var debug = false;

function writeDebugMessage(messageToWrite){
	document.writeln("<div><pre>" + messageToWrite + "</pre></div>");
}

// this function adds a pending opertation, that tells to the control with specified id to update its selectedIndex when
// it refreshes its options after an ajax call
function addPendingOperation(doc, root, id, value) {

	var operation = doc.createElement("operation");

	// access attributes (empty)
	var attributes = operation.getAttributes();

	// create new attribute
	var idAttr = doc.createAttribute("id");
	idAttr.setNodeValue(id);				
	attributes.setNamedItem(idAttr); // add attribute to attribute collection			

	// create new attribute
	var valueAttr = doc.createAttribute("value");
	valueAttr.setNodeValue(value);	
	attributes.setNamedItem(valueAttr); // add attribute to attribute collection			

	root.appendChild(operation);
}

// fires onchange event on a input
function fireChangeEvent(control){
	try{
		if (BrowserDetect.browser == "Explorer"){		
			control.fireEvent('onchange');
		}
		else{
			var evt = document.createEvent('HTMLEvents');
			evt.initEvent('change', true, true);
			control.dispatchEvent(evt);	
		}
	}
	catch (e){
		alert('FireChangeEvent ' + e);
	}
}

// fires onclick event on a input
function fireClickEvent(control) {
	try{
		if (BrowserDetect.browser == "Explorer") {
			control.fireEvent('onclick');
		}
		else {
			var evt = document.createEvent("MouseEvents");
			evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
			control.dispatchEvent(evt);	
		}
	}
	catch (e){
		alert('FireClickEvent ' + e);
	}		
}

// fires a checkbox onclick event and sets check state
function fireCheckboxEvent(dest, value) {
	try{
		if (BrowserDetect.browser == "Explorer") {
			dest.checked = value;
			fireClickEvent(dest);
		}
		else {
			fireClickEvent(dest);
			dest.checked = value;
		}
	}
	catch (e){
		alert('FireCheckboxEvent ' + e);
	}	
}

// fires a radiobox onclick event and sets check state
function fireRadioboxEvent(dest, value) {
	try{
		dest.checked = value;
		fireClickEvent(dest);			
	}
	catch (e){
		alert('FireRadioboxEvent ' + e);
	}	
}

// init wizard values with the XML loaded form server (does nothing if this is a new item because xml doesn't contain values)
function initWizardValues(controlsXML) {

	pendingOperations = "<queue></queue>";
	// access to pending operations XML
	var operationsDoc = createDomParser(pendingOperations);
	if (operationsDoc == null) {
		return;
	}
	var operationsRoot = operationsDoc.getDocumentElement();
	
	// access to controls value XML
	var doc = createDomParser(controlsXML);	
	if (doc == null)
		return;
	var root = doc.getDocumentElement();
	
	var change = '';
	var i, j, xmlChilds = root.getChildNodes();
	for (i = 0; i < xmlChilds.getLength(); i++) {
		var item = xmlChilds.item(i);
		var attributes = item.getAttributes();
		// attributes include "value" if the section is being modified
		var value = '' + attributes.getNamedItem(TAG_CONTROL_VALUE).getNodeValue();
		if (value.length > 0) {
			var id = '' + attributes.getNamedItem(TAG_CONTROL_ID).getNodeValue();	
			var type = '' + attributes.getNamedItem(TAG_CONTROL_TYPE).getNodeValue();
			
			var src = $(id);
		
			switch (type) {
				case TAG_CONTROL_TYPE_SELECT:
					// set a pending update
					if (id == change) {
						addPendingOperation(operationsDoc, operationsRoot, id, value);
						//pendingUpdate = pendingUpdate + id + "|" + value + "|";
					}
					// if the control changes some others, set change in order to add the pending operation
					// in the next step
					var changeAttr = attributes.getNamedItem(TAG_CONTROL_CHANGE);
					for (j = 0; j < src.options.length; j++) {
						if (src.options[j].value == value) {
							src.selectedIndex = j;
							break;
						}
					}
					// set the new change even if src.options.length = 0 (still not loaded).
					// the right selection will be loaded when setComboboxOptions is called
					if (changeAttr != null)
						change = changeAttr.getNodeValue();

					break;
				case TAG_CONTROL_TYPE_EDIT:
					if (value != null){
						value = value.replace(/&#39;/g, "'"); //&#039;
						value = value.replace(/&#34;/g, '"'); //&#039;						
						src.value = value;
					}
					else{
						src.value = value; //&#039;
					}
					break;
				case TAG_CONTROL_TYPE_CHECKBOX:
					if (src.checked != (value == "Y"))
						fireCheckboxEvent(src, (value == "Y"));

					//src.checked = value == "Y" ? true : false;
					break;
				case TAG_CONTROL_TYPE_RADIO:
					//if (value == "Y")
					//	fireCheckboxEvent(src, true);
					var checkedValue = (value == "Y");
					//if (src.checked != checkedValue)
						//fireCheckboxEvent(src, checkedValue);					
					if (checkedValue){
						src.checked = true;
						fireRadioboxEvent(src, true);
						//fireClickEvent(src);
						//fireCheckboxEvent(src, checkedValue);
					}
					else{
						src.checked = false;
					}					
					break;			
			}
		}
	}
	pendingOperations = operationsDoc.getXML();
}

function initWizardEvents(controlsXML) {

	initWizardDone = false;

	var doc = createDomParser(controlsXML);	
	if (doc == null)
		return;
	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(TAG_CONTROL_ID).getNodeValue();		
		var controlType = '' + attributes.getNamedItem(TAG_CONTROL_TYPE).getNodeValue();		

		var control = $(controlId);
		
		switch (controlType) {
			case TAG_CONTROL_TYPE_SELECT:
				break;
			case TAG_CONTROL_TYPE_EDIT:
				break;
			case TAG_CONTROL_TYPE_CHECKBOX:
				// fire the event two times to prevent checkbox state to be inverted
				if (checkMutexToAttribute(control))
					control.title = "notMutex";						
				fireClickEvent(control);
				fireClickEvent(control);
				//reset control title to prevent for ever notMutex
				if (control.title == "notMutex")
					control.title  = "";
				
				break;
			case TAG_CONTROL_TYPE_RADIO:
				// TODO: fire correct event for the group of radiobuttons
				// fire the event only on the active radiobutton
				//fireEvent(controlId, "click");
				//fireClickEvent(control);
				var isSetRadioButtonValue = attributes.getNamedItem(TAG_CONTROL_VALUE).getNodeValue() == "Y";		
				if (isSetRadioButtonValue){
					fireRadioboxEvent(control, true);
					//fireRadioboxEvent(control, true);
					//fireClickEvent(control);
				}
				/*
				if (checkMutexToAttribute(control))
					control.title = "notMutex";						
				fireClickEvent(control);
				fireClickEvent(control);
				//reset control title to prevent for ever notMutex
				if (control.title == "notMutex")
					control.title  = "";				
					*/
				break;
		}
	}

	for (i = 0; i < xmlChilds.getLength(); i++) {
		var item = xmlChilds.item(i);
		var attributes = item.getAttributes();
		var controlId = '' + attributes.getNamedItem(TAG_CONTROL_ID).getNodeValue();		
		var controlType = '' + attributes.getNamedItem(TAG_CONTROL_TYPE).getNodeValue();		

		if (controlType == TAG_CONTROL_TYPE_SELECT) {
			var control = $(controlId);			
			try{
				//use title attribute to prevent combobox mutex during wizardinit.
				if (checkMutexToAttribute(control))
					control.title = "notMutex";		
				fireChangeEvent(control);
			}
			catch(e){
				//alert('Exception');			
			}
		}
	}

	initWizardDone = true;	
}

function initWizardFormValidator(formsXML)
{
	var doc = createDomParser(formsXML);    
    if (doc == null)
        return;
    var root = doc.getDocumentElement();
    
    var i, xmlChilds = root.getChildNodes();      

    for (i = 0; i < xmlChilds.getLength(); i++) {
        var item = xmlChilds.item(i);
        var name = '' + item.getNodeName();
        var attributes = item.getAttributes(); 
        //alert(name);
        if (name == TAG_FORM)
        {
            var form_id = '_' + attributes.getNamedItem(TAG_ITEM_ID).getNodeValue() + '_';
            var formValObj = new DHTMLSuite.formValidator({ formRef:form_id,keyValidation:true,callbackOnFormValid:'lockDisable',callbackOnFormInvalid:'lockEnable' }); //,indicateWithBars:true
        } 
    }
}
