/**
 * Cocoon Forms
 * Javascript Overrides - NO-DOJO EDITION!
 *
 * Principle Inc.
*/


// Turn ON or OFF debugging to console.
// Requires console support (Firefox+Firebug, Safari).
var debug = false;
if (debug) {
	if (!window.console.log && !window.console.dirxml) {
		// you don't have Firebug
		debug = false;
	}
}



// Create the namespaces we need.
var pi = window.pi || {};
pi.forms = {};
var cocoon = window.cocoon || {};
cocoon.forms = cocoon.forms || {};
cocoon.ajax = cocoon.ajax || {};


/**
 * Form Tooltips
 */
pi.forms.tooltip = {
	settings: {
		offset: {
			x: 7,
			y: -20
		},
		maxWidth: 300
	},
	_position: function (oTip, oAnchor) {
		var tip = oTip,
			a = oAnchor;
		
		// enforce max-width
		if (this.settings.maxWidth && this.settings.maxWidth > 0) {
			if (tip.width() > this.settings.maxWidth) {
				tip.css({
					width: this.settings.maxWidth + 'px',
					height: 'auto'
				});
			}
		}
		
		// set position
		tip.css({
			left: a.position().left + this.settings.offset.x,
			top: a.position().top + this.settings.offset.y
		});
		
		// adjust position if tooltip would appear offscreen
		var pos = {tip: {}, win: {}};
		//var pageSize = WIZ.getPageSize();
		
		pos.tip.left = parseInt(tip.css('left'), 10);
		pos.tip.top = parseInt(tip.css('top'), 10);
		pos.tip.right = pos.tip.left + tip.width();
		//pos.tip.bottom = pos.tip.top + tip.height();
		
		var diffRight = pos.tip.right - $(window).width();
		//var diffBottom = pos.tip.bottom - $(window).height();
		
		if ( diffRight > 0 ) {
			tip.css('left', pos.tip.left - diffRight - 45 + 'px'); // 45px is an arbitrary amount of clearance from the right edge.
		}
		//if ( diffBottom > 0 ) {
		//	tip.css('top', pos.tip.top - diffBottom + 'px');
		//}
		
	},	
	show: function (anchor) {
		$("div.form_message_help").hide(); // hide all the opened tip before opening a new one - kenny
		
		var a = $(anchor),
			tip;
		
		// which message to show?
		if (a.hasClass('form_error')) {
			tip = a.siblings("div.form_message_error");
		} else {
			tip = a.siblings("div.form_message_help");
		}
		
		this._position(tip, a);
		tip.show();
	},
	hide: function (anchor) {
		var a = $(anchor);
		var tip;
		
		// which message to hide?
		if (a.hasClass('form_error')) {
			tip = a.siblings("div.form_message_error");
		} else {
			tip = a.siblings("div.form_message_help");
		}
		
		tip.hide();
		
	}
};



/**
 * Get the parent form of an element
 *
 * NOTE: Introduced in 2.1.11, replaces forms_getForm
 */
cocoon.forms.getForm = function(element) {
    while(element != null && element.tagName != null && element.tagName.toLowerCase() != "form") {
        element = element.parentNode;
    }
    return element;
}



/**
 * Submits a form.
 * This function is designed to submit the form when called from scripts (onchange handlers etc.)
 *
 * NOTE: Introduced in 2.1.11, replaces forms_submitForm
 *
 * @param element   the DOM Node that is triggering this submit
 * @param name      (Optional) tell CForms the name of the submitting element
 * @param params    (Optional) an Associative Array of parameters to add to the submitted form
 *
 */
cocoon.forms.submitForm = function(element, name, params) {
	var form = this.getForm(element);
    if (form == null) {
        alert("Cannot find form for " + element);
        return;
    }

    if (!name) name = element.name;

	if (debug) console.log('AJAX mode requested?', form.getAttribute('ajax')); ////////////////////////////////////////

	// Here is where must choose whether to submit via AJAX or not.
	// We check the form's ajax attribute to determine this:
	//   <form ajax="true"...		= Ajax submit.
	//   <form ajax="false"...		= Traditional submit.
	if (form.getAttribute('ajax')) {
		if (debug) console.log('Calling cocoon.forms.AjaxForm.submit()'); ////////////////////////////////////////
        // Delegate to the AjaxForm widget
        cocoon.forms.AjaxForm.submit(form, name, params);
    } else {
		if (debug) console.log('Calling cocoon.forms.fullPageSubmit()'); ////////////////////////////////////////
        // Regular submit. There is no *Form widget available

        // A form's onsubmit is only called when submit is triggered by user action, but not when
        // called by a script. So call it now, cancelling the submit if it returns false
        if (!form.onsubmit || form.onsubmit() != false) {     // call the user's onSubmit handler
            cocoon.forms.fullPageSubmit(form, name, params);
        }
    }
}



/**
 * Internal function
 * Submits a form using a full page submit
 *
 * @param form      the form DOM Node that is being submitted
 * @param name      tell CForms the name of the submitting widget
 * @param params    an Associative Array of parameters to add to the submitted form
 *
 */
cocoon.forms.fullPageSubmit = function(form, name, params) {
	if (!params) params = {}; // create if not passed.

    // Send the identifier of the widget that triggered the submit
    params["forms_submit_id"] = name;
    // call CForm's onSubmit handlers - allow them to stop the form by returning false
    if (cocoon.forms.callOnSubmitHandlers(form)) {   
        for (var param in params) { // add extra params to the form
            var input = form[param] || document.createElement("input");
            input.setAttribute("type", "hidden");
            input.setAttribute("name", param);
            input.setAttribute("value", params[param]);
            if (!form[param]) form.appendChild(input);
        }
        form.submit();
    }
}



/**
 * onLoad Handlers
 * Manage functions that should be called when the page has loaded
 *
 * NOTE: Introduced in 2.1.11, replaces forms_onloadHandlers
 */
cocoon.forms.onLoadHandlers = new Array();



/**
 * add an onLoad Hander
 *
 * NOTE: Introduced in 2.1.11, replaces forms_onloadHandlers.push
 */
cocoon.forms.addOnLoadHandler = function(handler) {
    if (handler && typeof(handler.forms_onload) == "function") {
        cocoon.forms.onLoadHandlers.push(handler);
    }
}



/**
 * call the onLoad Handlers (typically this function is passed to dojo.addOnLoad)
 *
 * NOTE: Introduced in 2.1.11, replaces forms_onloadHandlers.push
 */
cocoon.forms.callOnLoadHandlers = function() {
    for (var i = 0; i < cocoon.forms.onLoadHandlers.length; i++) {
        cocoon.forms.onLoadHandlers[i].forms_onload();
    }
    // Reset it (we do not need them anymore)
    cocoon.forms.onLoadHandlers = new Array();
}



/**
 * onSubmit Handlers
 * Manage functions that should be called before the form is submitted
 * If an onSubmit Handler returns false, the form will not be submitted
 * NB. onSubmit Handlers are not currently called for Ajax forms
 *
 * NOTE: Introduced in 2.1.11, replaces forms_onsubmitHandlers.push
 */
cocoon.forms.onSubmitHandlers = {};



/**
 * add an onSubmit Handler
 *
 * NOTE: Introduced in 2.1.11, replaces forms_onsubmitHandlers.push
 *
 * @param element  the form control adding the handler
 * @param handler  the handler
 */
cocoon.forms.addOnSubmitHandler = function(element, handler) {
    if (handler && typeof(handler.forms_onsubmit) == "function") {
        var form = this.getForm(element);
        if (form) {
            var id = form.getAttribute("id");
            if (id) {
                if (!cocoon.forms.onSubmitHandlers[id]) cocoon.forms.onSubmitHandlers[id] = new Array();
                cocoon.forms.onSubmitHandlers[id].push(handler);
            } else {
                if (dojo) dojo.debug("WARNING: SubmitHandler not added. There is no id attribute on your form.");
            }
        }
    }
}



/**
 * call the onSubmit Handlers
 *
 * NOTE: Introduced in 2.1.11, replaces forms_onsubmit
 *
 * @param form      the form (DOMNode) being submitted
 */
cocoon.forms.callOnSubmitHandlers = function(form) {
    var id = form.getAttribute("id");
    if (cocoon.forms.onSubmitHandlers == null) {
        // Form already submited, but the new page is not yet loaded. This can happen when
        // the focus is in an input with an "onchange" and the user clicks on a submit button.
        return false;
    }
    if (cocoon.forms.onSubmitHandlers[id] == null) {
        // When addOnSubmitHandler has never been called, there will be no submit handlers
        return true;
    }
    for (var i = 0; i < cocoon.forms.onSubmitHandlers[id].length; i++) {
        if (cocoon.forms.onSubmitHandlers[id][i].forms_onsubmit() == false) {
            // handler cancels the submit
            return false;
            // TODO: should we allow all onsubmithandlers to be called, but then return the aggregate result ?
            //  (bruno): I don't think so, the first cancel operation should cancel it completely (esp. if this
            //           might be the result of some user interaction)
        }
    }
    // clear it
    // TODO: if AjaxForm were to start calling submit handlers, this would need to change
    cocoon.forms.onSubmitHandlers[id] = null;
    return true;
}





/**
 * This is _our_ version of CForms' AjaxForm "Widget".
 * 
 * The original Widget used these resources:
 *   dojo.require("cocoon.forms.SimpleForm");
 *   dojo.require("cocoon.ajax.BUHandler");
 */
cocoon.forms.AjaxForm = {
    // widget properties
    widgetType: "AjaxForm",

    /**
     * Submit the form via Ajax.
     * Choose the right transport depending on the widgets in the form and the browser's capabilities.
     *
     * @param name the name of the widget that triggered the submit (if any)
     * @param params an object containing additional parameters to be added to the form data (optional)
     */
    submit: function(form, name, params) {
		if (debug) console.log("OK, let's try to submit via AJAX...");
		
		var that = this; // for passing our context to the $.ajax() function.
		
        if (!params) params = {};                               /* create if not passed */
        
        // TODO: should CForm's onSubmit handlers be called for Ajax events ?
        //if (cocoon.forms.callOnSubmitHandlers(form)) == false) return; /* call CForm's onSubmit handlers */
        
        // Provide feedback that something is happening.
        document.body.style.cursor = "wait";
        
        // The "ajax-action" attribute specifies an alternate submit location used in Ajax mode.
        // This allows to use Ajax in the portal where forms are normally posted to the portal URL.
        var uri = form.getAttribute("ajax-action");
        if (!uri) uri = form.action;
        if (uri == "") uri = document.location;
		
        params["forms_submit_id"] = name;                       /* name of the button doing the submit */
        params["cocoon-ajax"] = true;                           /* tell Cocoon we want AJAX-style browser updates */
		
		
		// Let's assemble the data string we want to post:
		var formData = '';
		
		// Add in the extra parameters:
		for (var i in params) {
			formData += i + '=' + params[i] + '&';
		}
		
		// Serialize the form values and add them in:
		formData += $(form).serialize();
		
		
		
        //if (dojo.io.formHasFile(form)) {                        /* check for file-upload fields */
        //    dojo.require("dojo.io.IframeIO");                   /* using IframeIO as we have file-upload fields */
        //    mimetype = "text/html";                             /* a different mime-type is required for IframeIO */
        //}
		
		
		
		// Show some debug info before making the AJAX request
		$(document).bind("ajaxSend", function (event, XMLHttpRequest, ajaxOptions) {
			if (debug) {
				console.group('WHAT ARE WE SENDING?');
				console.log('event: ', event);
				console.log('XHR Object: ', XMLHttpRequest);
				console.log('ajaxOptions: ', ajaxOptions);
				console.groupEnd();
			}
		});
		
		// Make the AJAX request
		$.ajax({
			url: uri,
			type: "POST",
			data: formData,
			//contentType: 'application/x-www-form-urlencoded', // this is default anyway!
			dataType: 'xml',
			success: function (data, textStatus) {
				// data could be xmlDoc, jsonObj, html, text, etc...
				this; // the options for this ajax request
				
				if (debug) {
					console.group('WHAT ARE WE GETTING?');
					console.info('Success');
					console.log('textStatus: ', textStatus);
					console.log('data: ', data);
					console.dirxml(data);
					console.groupEnd();
				}
				
				// call the function that handles the server response
				//that._handleBrowserUpdate(this, name, type, data);
				that._handleBrowserUpdate(form, name, data);
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				// typically only one of textStatus or errorThrown will have info
				this; // the options for this ajax request
				
				if (debug) {
					console.group('WHAT ARE WE GETTING?');
					console.error('Error');
					console.log('textStatus: ', textStatus);
					console.log('errorThrown: ', errorThrown);
					console.log('XHR Object: ', XMLHttpRequest);
					console.groupEnd();
				}
			}
		});
		
        //dojo.io.bind({
        //    url: uri,
        //    handle: dojo.lang.hitch(this, function(type, data) { this._handleBrowserUpdate(this, name, type, data) }),
        //    method: "post",
        //    mimetype: mimetype,                                 /* the mimetype of the response */
        //    content: params,                                    /* add extra params to the form */
        //    formNode: form,                                     /* the form */
        //    sendTransport: true                                 /* tell cocoon what transport we are using */
        //});
		
		
        // Toggle the click target off, so it does not get resubmitted if another submit is fired before this has finished
        // NB. This must be done after the form is assembled by dojo, or certain onChange handlers may fail
        // Avoid the use of widget.lastClickTarget as it may already be out of date
        if (form[name]) form[name].disabled = true;
    },
    
    /**
     * Handle the server's BrowserUpdate response.
     * Update the part of the form referenced by ids in the reponse.
     */
    _handleBrowserUpdate: function(form, name, data, type) {
		
        // Restore normal cursor
        document.body.style.cursor = "auto";
		
        // Attempt to re-enable the click target
		if (form[name]) form[name].disabled = false;
		
        // get a BrowsewrUpdateHandler which will replace the updated parts of the form
        var updater = cocoon.ajax.BUHandler;
		updater.processResponse(data);
    },
    //_handleBrowserUpdate: function(widget, name, type, data) {
    //    // Restore normal cursor
    //    document.body.style.cursor = "auto";
    //    // Attempt to re-enable the click target
    //    if (this.domNode[name]) this.domNode[name].disabled = false;
    //    // get a BrowsewrUpdateHandler which will replace the updated parts of the form
    //    var updater = new cocoon.ajax.BUHandler();
    //    if (type == "load") {
    //        if (!data) {
    //            cocoon.ajax.BUHandler.handleError("No xml answer", data);
    //            return;
    //        }
    //        // add the continue handler for CForms
    //        updater.handlers['continue'] = function() { widget._continue(); } 
    //        // Handle browser update directives
    //        updater.processResponse(data);
    //    } else if (type == "error") {
    //        updater.handleError("Request failed", data);
    //    } else {
    //        dojo.debug("WARNING: dojo.io.bind returned an unhandled state : " + type);
    //    }
    //},
	
    /**
     * Handle the server continue message.
     * The server is signalling in a BrowserUpdate response that the CForm is finished.
     * Return an acknowledgement to the continuation so cocoon.sendForm may complete.
     */
    _continue: function() {
		alert('CALLING _continue()');
		
        var form = this.domNode;
        if (form.method.toLowerCase() == "post") {
            // Create a fake form and post it
            var div = document.createElement("div");
            var content = "<form action='" + form.action + "' method='POST'>" +
                                "<input type='hidden' name='cocoon-ajax-continue' value='true'/>";
            if (form.elements["continuation-id"]) {
                content += "<input type='hidden' name='continuation-id' value='" +
                        form.elements["continuation-id"].value + "'/>";
            }
            content += "</form>";
            div.innerHTML = content;
            document.body.appendChild(div);
            div.firstChild.submit();
        } else {            
            // Redirect to the form's action URL
            var contParam = '?cocoon-ajax-continue=true';
            if (form.elements["continuation-id"]) {
                contParam += "&continuation-id=" + form.elements["continuation-id"].value;
            }
            window.location.href = form.action + contParam;
        }
    }
};





/**
 *
 * This is _our_ version of CForms' BUHandler module.
 * 
 */
cocoon.ajax.BUHandler = {
	ELEMENT_NODE: 1, // alias for DOM nodeType constant
	highlight: null, // Default highlight effect (none)
	
	processResponse: function(doc) {
		//var base = doc.documentElement;
		var that = this; // for passing our context into the $.each() function.
		
		//var nodes = [];
		//var ELEMENT_NODE = 1; // alias for DOM nodeType constant
		//console.log('*************', $(doc));
		//nodes = $(doc).children();

		$.each(doc.documentElement.childNodes, function() {
			that.handlers.replace(this);
		});

		//nodes.each(function () {
			////alert(this);
			//that.handlers.replace(this);
		//})
		
		//console.group('processResponse()');
		//console.log('base: ', base);
		//console.groupEnd();
		//
		//if (base.nodeName.toLowerCase() == 'bu:document') {
		//	nodes = base.childNodes;
		//	console.log('got response using: XMLHTTPTransport');
		//} else {
		//	base = $(doc).find("#browser-update");
		//	if (base.length > 1) {
		//		nodes = base.childNodes;
		//		console.log("got response using: IframeTransport");
		//	} else {
		//		this.handleError("No response data found", doc);
		//	}
		//}
		//
		//for (var i = 0; i < nodes.length; i++) {
		//	var node = nodes[i];
		//	
		//	if (node.nodeType == ELEMENT_NODE) {
		//		var handler = node.nodeName.replace(/.*:/, "").toLowerCase();
		//		
		//		if (handler == "textarea") {
		//			alert('I think we need to write some code here. (mg)');
		//			handler = node.getAttribute("name");
		//		}
		//		
		//		var handlerFunc = this.handlers[handler];
		//		
		//		if (handlerFunc) {
		//			handlerFunc(node);
		//		} else {
		//			alert('No handler function for this type of BU. (mg)');
		//			//this.handleError("No handler found for element " + handler, doc);
		//		}
		//	}
		//}
	},
	
	//processResponse: function(doc) {
	//	var base = doc.documentElement;		
	//	
	//	var nodes = [];
	//	if (base.nodeName.toLowerCase() == "bu:document") {
	//		nodes = base.childNodes;
	//		dojo.debug("got response using: XMLHTTPTransport");
	//	} else {
	//		base = dojo.byId("browser-update", doc);
	//		if (base) {
	//			nodes = base.childNodes;
	//			dojo.debug("got response using: IframeTransport");
	//		} else {
	//			this.handleError("No response data found", doc);
	//		}
	//	}
	//	for (var i = 0; i < nodes.length; i++) {
	//		var node = nodes[i];
	//		if (node.nodeType == dojo.dom.ELEMENT_NODE) {
	//			var handler = node.nodeName.replace(/.*:/, "").toLowerCase();
	//			if (handler == "textarea") handler = node.getAttribute("name");
	//			var handlerFunc = this.handlers[handler];
	//			if (handlerFunc) {
	//				handlerFunc(node);
	//			} else {
	//				this.handleError("No handler found for element " + handler, doc);
	//			}
	//		}
	//	}
	//},
	
	handleError: function(message, response) {
		alert('Call to cocoon.ajax.BUHandler.handleError() \n We need to write this function. (mg)');
		
		//if (confirm(message + "\nShow server response?")) {
		//	var w = window.open(undefined, "Cocoon Error", "location=no,resizable=yes,scrollbars=yes");
		//	if (w == undefined) {
		//		alert("You must allow popups from this server to display the response.");
		//	} else {
		//		var doc = w.document;
		//		if (response.responseText) {
		//			doc.open();
		//			doc.write(response.responseText);
		//			doc.close();
		//		} else if (response.childNodes) {
		//			dojo.dom.copyChildren(doc,response);
		//		}
		//	}
		//}
	},

	handlers: {
		replace: function(element) {

			var oldElem = document.getElementById(element.getAttribute('id'));

			//var newElem = $(element).children()[0];

			var newElem = element.firstChild;
			while( newElem.nodeType != 1 ) { // 1 == ELEMENT
				newElem = newElem.nextSibling;
			}

			if( newElem.nodeType != 1 ) {
				alert('Call to cocoon.ajax.BUHandler.handlers() \n No "FIRST ELEMENT" child node found in source');
			}
			
			cocoon.ajax.insertion.replace(oldElem, newElem);
			
			return;
		
		
			//var id = element.getAttribute("id");
			//if (!id) {
			//	alert("no id found on update element");
			//	return;
			//}
			//
			//// Get the first child element (the first child may be some text!)
			//var firstChild = $(element).children()[0];
			//
			//if (!firstChild) {
			//	alert ('no replacement element found in BU response pkg.');
			//	return;
			//}
			//
			//if (!firstChild && element.nodeName.toLowerCase() == "textarea") {
			//	firstChild = dojo.dom.createDocumentFromText(element.value).documentElement;
			//}
			//
			//var oldElement = document.getElementById(id);
			//
			//if (!oldElement) {
			//	alert("no element '" + id + "' in source document");
			//	return;
			//}
			//
			//console.log('firstChild=', firstChild);
			//console.dirxml(firstChild);
			//
			//var newElement = cocoon.ajax.insertion.replace(oldElement, firstChild);
			
			// This is some highlighting thingie we'll worry about later,
			// if we need to (mg).
			//if (typeof(cocoon.ajax.BUHandler.highlight) == "function") {
			//	cocoon.ajax.BUHandler.highlight(newElement);
			//}
		}
	}	
};


/**
 *
 * This is _our_ version of CForms' AJAX Insertion module.
 * 
 */
cocoon.ajax.insertion = {

    /**
     * Replaces the reference element
     */
    replace: function (oldElem, newElem) {
		if (debug) {
			console.group('REPLACING...');
			console.log('oldElem: ', oldElem);
			console.log('newElem: ', newElem);
		}
		
		// This method parses the new Element into a String, and then
		// adds it to the DOM.
		//
		// This method works in only a few browsers.
		/////
		//
		//var parentNode = document.getElementById(oldElem.id).parentNode;
		//var newNode = (new XMLSerializer()).serializeToString(newElem);
		//$(oldElem).parent().html(newNode);
		//
		/////
		
		var asText;

		if (typeof XMLSerializer != "undefined")
			asText = (new XMLSerializer()).serializeToString(newElem);
		else if (newElem.xml)
			asText =  newElem.xml;
		else	
			throw "XML.serialize is not supported or can't serialize " + newElem;

		var asObject = $(asText);
					
		$(oldElem).replaceWith(asObject);
		
		//$(oldElem).replaceWith(newElem);
		
		if (debug) {
			console.info('Finished. Element "' + oldElem.id + '" has been updated.');
			console.groupEnd();
		}
    },
	
	/**
	 * Inserts before the reference node
	 */
    before: function (refElt, content) {
		alert('Call to cocoon.ajax.insertion.before() \n We need to write this function. (mg)');
        //return cocoon.ajax.insertionHelper.insert(refElt, content, function(refElt, newElt) {
        //    refElt.parentNode.insertBefore(newElt, refElt);
        //});
    },

	/**
	 * Inserts after the reference node
	 */
    after: function (refElt, content) {
		alert('Call to cocoon.ajax.insertion.after() \n We need to write this function. (mg)');
        //return cocoon.ajax.insertionHelper.insert(refElt, content, function(refElt, newElt) {
        //    // There's no node.insertAfter...
        //    if (refElt.nextSibling) {
        //        refElt.parentNode.insertBefore(newElt, refElt.nextSibling);
        //    } else {
        //        refElt.parentNode.appendChild(newElt);
        //    }
        //});
    },

    /**
     * Inserts at the top of the reference node children (i.e. as the first child)
     */
    top: function (refElt, content) {
		alert('Call to cocoon.ajax.insertion.top() \n We need to write this function. (mg)');
        //return cocoon.ajax.insertionHelper.insert(refElt, content, function(refElt, newElt) {
        //    if (refElt.firstChild) {
        //        refElt.insertBefore(newElt, refElt.firstChild);
        //    } else {
        //        refElt.appendChild(newElt);
        //    }
        //})
    },

    /**
     * Inserts at the bottom of the reference node children (i.e. as the last child)
     */
    bottom: function (refElt, content) {
		alert('Call to cocoon.ajax.insertion.bottom() \n We need to write this function. (mg)');
        //return cocoon.ajax.insertionHelper.insert(refElt, content, function(refElt, newElt) {
        //    refElt.appendChild(newElt);
        //})
    },

    /**
     * Inserts as the contents of the reference node (i.e. replaces all children)
     */
    inside: function (refElt, content) {
		alert('Call to cocoon.ajax.insertion.inside() \n We need to write this function. (mg)');
        //return cocoon.ajax.insertionHelper.insert(refElt, content, function(refElt, newElt) {
        //    // Destroy and remove all children
        //    while (refElt.hasChildNodes()) {
        //        var firstChild = refElt.firstChild;
        //        if (firstChild.nodeType == dojo.dom.ELEMENT_NODE) {
        //            cocoon.ajax.insertionHelper.destroy(firstChild);
        //        }
        //        refElt.removeChild(firstChild);
        //    }
        //
        //    // Insert the new one
        //    refElt.appendChild(newElt);
        //})
    }
};




//eof
