/**
*	Hereinside we put all the js functions used to make possible the use
*	of the Newsletter module from inside
*	a zigpopup.
*/

/**
 * showNewsletter function
 * oConfig looks like: {title:'text',content:'text'}
 */
function showNewsletter(oForm, sRegUri)
{	
	new Ajax.Request(sRegUri, {
		method:'post',
		asynchronous : true,
		evalScripts: true,
		onSuccess: function(transport, oJson){
			// Fixed: the old JSON object was limited in kb size, that's why we get now back the response as 
			// plain text and folowing parse the json text object.
			var sHtmlText = transport.responseText;
			
			var oConfig = {title: "NIEUWSBRIEF KOOPWONINGEN" ,content: sHtmlText};
			
			oPopup = new NewsletterPopup($('popupNews'));
			oPopup.setTitle(oConfig.title);
			oPopup.setContent(oConfig.content);
			oPopup.bBlocking = true;
			
			oPopup.show();
			
			// This is to evaluate all JavaScript code from the inside of the Ajax Request at the template side.
			transport.responseText.evalScripts();
		}
	});
	
	return false;
}

/**
*	Handler of the submitted un-re/gistration form
*
*	@param string sRegUri destination URI of the submitted form
*/
function submitRegistrationForm(oForm, sRegUri)
{
	// First, let's load the selected value for the radiobutton "aanhef".
	var aanhef;
	for(i = 0; i< oForm.aanhef.length; i++)
	{
		if(oForm.aanhef[i].checked)
		{
			aanhef = oForm.aanhef[i].value;
		}
	}
	//console.log(aanhef, oForm.firstname.value, oForm.lastname.value, oForm.email.value, oForm.group.value);
	
	new Ajax.Request(sRegUri, {
		method: 'post',
		asynchronous : false,
		parameters: {
			aanhef: aanhef,
			firstname: oForm.firstname.value,
			lastname: oForm.lastname.value,
			email: oForm.email.value,
			group: oForm.group.value
		},
		onSuccess: function(transport, oJson){
			// Fixed: the old JSON object was limited in kb size, that's why we get now back the response as 
			// plain text and folowing parse the json text object.
			sHtmlText = transport.responseText;
			
			var oConfig = {title: "NIEUWSBRIEF KOOPWONINGEN" ,content: sHtmlText};
			
			oPopup = new NewsletterPopup($('popupNews'));
			oPopup.setTitle(oConfig.title);
			oPopup.setContent(oConfig.content);
			oPopup.bBlocking = true;
			oPopup.hideOverlay();
			oPopup.show();
		}
	});
	return false;
	// This return false is important to avoid the html form-submission and enable it only thought ajax.
	//return false;
}

/**
 * NewsletterPopup class
 * depends on prototype/scriptaculous.
 * This class derives by ZigPopup class.
 *
 * @author Giovanni Bolognese <gbolognese@zigwebsoftware.nl>
 * @version 1.0
 * @copyright Copyright (c) 2010, Zig Websoftware
 */ 

var NewsletterPopup = Class.create(
{	
    /**
     * popup is blocking?
     * @var boolean bBlocking
     */
	bBlocking: false,

    /**
     * keep popup in center by vertical scrolling?
     * @var boolean bVerticalScroll
     */
	bVerticalScroll: true,	
	
	/**
     * the popup DOM node we want to attach our functionality to
     * @var object oPopupNode
     */
	oPopupNode: null,
	
	/**
     * the overlay DOM node
     * @var object oOverlay
     */	
	oOverlay: null,

	/**
     * the popup's header node
     * @var object oMoveNode
     */		
	oMoveNode: null,
	

	/**
     * the popup's header close node
     * @var object oMoveNode
     */		
	oHeaderCloseNode: null,
	

	/**
     * the popup's title node
     * @var object oTitleNode
     */		
	oTitleNode: null,

	/**
     * the popup's content node
     * @var object oContentNode
     */		
	oContentNode: null,

	/**
     * duration of popup show/hide action
     * @var double fShowHideDuration
     */		
	fShowHideDuration: 0.5,

	/**
     * default title of popup
     * @var string sTitle
     */		
	sDefaultTitle: null,

	/**
     * minumum width of popup
     * @var int iMinWidth
     */		
	iMinWidth: 0,		
	
	/**
     * display mode (block or inline)
     * @var string sDisplayMode
     */		
	sDisplayMode: 'block',		
	
    /**
     * initializes the popup
     *
	 * @param object oPopupNode the dom node we want to attach to
	 * @param array aOptions some options
     * @return void
     */	
	initialize: function(oPopupNode, aOptions) 
	{	
		if (aOptions && typeof(aOptions.blocking) == 'boolean')
		{
			this.bBlocking = aOptions.blocking;
		}

		if (aOptions && typeof(aOptions.minWidth) !== 'undefined')
		{
			this.iMinWidth = parseInt(aOptions.minWidth, 10);
		}		

		if (aOptions && typeof(aOptions.verticalScroll) == 'boolean')
		{
			this.bVerticalScroll = aOptions.verticalScroll;
		}

		if (typeof(oPopupNode) == 'undefined' || oPopupNode == null)
		{	
			if (typeof(console) !== 'undefined')
			{
				console.error('could not initialize popup: dom node not found');		
			}
		}
		else if (oPopupNode.id == null || oPopupNode.id == '')
		{
			if (typeof(console) !== 'undefined')
			{
				console.error('could not initialize popup: dom node needs id attribute');		
			}
		}
		else
		{						
			this.oPopupNode = oPopupNode;
			this.preparePopupNode();
		}
	},

	/**
     * change the "display mode" to inline or block, default block
     *
	 * @param string sMode the mode, inline or block
     * @return void
     */	
	setDisplayMode: function(sMode)
	{
		this.sDisplayMode = sMode;
	},	
	
	/**
     * change width of popup
     *
	 * @param int iWidth the width in pixels
	 * @param function oCompleteHandler the action to perform after resizing, optional
     * @return void
     */	
	setWidth: function(iWidth, oCompleteHandler)
	{	
		// parent div should be at least this.iMinWidth wide
		var iPopupWidth = Math.max(iWidth, this.iMinWidth);

		// resize popup node		
		new Effect.Morph(this.oPopupNode, {
			style: 'width: ' + iPopupWidth.toString() + 'px',
			duration: 0.4
		});			
		
		
		// also resize and position content node
		// take in a account any borders the content node might have when calculating its width
		var sBorderLeft = this.oContentNode.getStyle('borderLeftWidth');
		var sBorderRight = this.oContentNode.getStyle('borderRightWidth');	
		var iBorderCorrection = 0;
		
		if (typeof(sBorderLeft) != 'undefined' && sBorderLeft != null && sBorderLeft != '')
		{
			iBorderCorrection += parseInt(sBorderLeft, 10);
		}

		if (typeof(sBorderRight) != 'undefined' && sBorderRight != null && sBorderRight != '')
		{
			iBorderCorrection += parseInt(sBorderRight, 10);
		}

		this.oPopupNode.parentNode.style.top = ''; // force re-positioning
		this.positionOverlay();
				
		new Effect.Morph(this.oContentNode, {
				style: 'width: ' + (iWidth-iBorderCorrection).toString() + 'px',
				duration: 0.4,
				afterFinish: oCompleteHandler
		});
	
	},

	/**
     * to be overriden, display appropiate nodes for specific type of 
     *
	 * @param void
     * @return void
     */	
	showNodes: function()
	{
		
	},
	
	/**
     * prepares the popup node
	 * applies some necessary styling, and tries to find various nodes
     *
	 * @param void
     * @return void
     */	
	preparePopupNode: function()
	{		
		this.oPopupNode.style.zIndex = "990";

		// try to find nodes in this.oPopupNode
		this.oTitleNode					= $(this.oPopupNode.select('.NewsPopup_title')[0]);
		this.sDefaultTitle 				= (this.oTitleNode ? this.oTitleNode.innerHTML : '');
		
		this.oContentNode				= $(this.oPopupNode.select('.NewsPopup_content')[0]);
		this.oMoveNode					= $(this.oPopupNode.select('.NewsPopup_move')[0]);
		this.oHeaderCloseNode			= $(this.oPopupNode.select('.NewsPopup_headerClose')[0]);
		
		// first, we hide all optional nodes and remove all previous listeners these nodes might have
		this.oPopupNode.select("[class^='NewsPopup_']").each(function(oEl) {
			//oEl.style.display = 'none';
			oEl.stopObserving();
		});

		// show nodes which are always used
		if (this.oContentNode)
		{
			this.oContentNode.style.display = this.sDisplayMode;			

			// min width set? make sure content node is at least this wide
			if (this.iMinWidth > 0)
			{
				this.oContentNode.style.minWidth = this.iMinWidth.toString() + 'px';
			}
		}
		
		if (this.bBlocking == false)
		{
			if (this.oHeaderCloseNode)
			{
				this.oHeaderCloseNode.style.display = this.sDisplayMode;
			}
		}
		
		// now we ask our subclass to show its appropiate nodes		
		this.showNodes();	
				
		// set shared listeners for all popups
		this.oPopupNode.select('.ZigPopup_move').each(function(oEl) 
		{	
			new Draggable(this.oPopupNode, {handle: oEl});
		}.bind(this));		

		// now we ask our subclass to set its subclass specific listeners
		this.setListeners();	
	},


	/**
     * set appropiate listeners for specific type of popup
     *
	 * @param void
     * @return void
     */		
	setListeners: function()
	{
		document.observe('keydown', function(oEvent)
		{
			this.handleKeypress(oEvent);
		}.bind(this));

		$(this.oPopupNode.parentNode).observe('click', function(oEvent)
		{
			// Close popup when clicking on the Close button and nowhere else
			if ( oEvent.target == $('popupCloseNews') )
			{
				this.hide();				
			}
		}.bind(this));
	},

	
	/**
     * handle keypress
     *
	 * @param object oEvent the keypress' event
     * @return void
     */
	handleKeypress: function(oEvent)
	{	
		if (oEvent.keyCode == Event.KEY_ESC && this.bBlocking == false)
		{
			this.hide();
		}
	},

	
	/**
     * sets content in the content node, if found
     *
	 * @param string sHtml
     * @return void
     */		
	setContent: function(sHtml)
	{
		if (this.oContentNode)
		{
			this.oContentNode.innerHTML = sHtml;
		}
		else 
		{
			// console.log('could not set content, contentNode not found');
		}
	},

	/**
     * sets label in the ok button node
     *
	 * @param string sLabel
     * @return void
     */		
	setLabelOkButton: function(sLabel)
	{
		if (this.oOkButtonNode)
		{
			this.oOkButtonNode.innerHTML = sLabel;
		}
		else 
		{
			// console.log('could not set ok button label, Node not found');
		}
	},	
	
	/**
     * sets content in the title node, if found
     *
	 * @param string sHtml
     * @return void
     */			
	setTitle: function(sHtml)
	{
		if (this.oTitleNode)
		{
			this.oTitleNode.innerHTML = sHtml;
		}
		else 
		{
			// console.log('could not set title, contentNode not found');
		}
	},

	/**
     * shows the overlay and popup
     *
     * @return void
     */			
	show: function()
	{	
		this.showOverlay();	
		this.oPopupNode.appear({duration: this.fShowHideDuration});
	},

	/**
     * hides the overlay and popup
     *
	 * @param void
     * @return void
     */			
	hide: function()
	{
		document.stopObserving(); // stop listening to keypresses
		this.hideOverlay();		
		this.oPopupNode.fade({duration: this.fShowHideDuration});
		
		// wait a little before cleanup, until we are sure the fade is done
		var doCleanUp = function() 
		{
			this.cleanUp();
		}.bind(this);
		
		doCleanUp.delay(0.4);
	},

	/**
     * clean up, removes all nodes and listeners
     *
	 * @param void
     * @return void
     */	
	cleanUp: function()
	{		

		// reset top, for correct positioning the next time
		this.oPopupNode.parentNode.style.top = '';

		// restore default title
		if (this.oTitleNode)
		{
			this.oTitleNode.innerHTML = this.sDefaultTitle;
		}

		// empty content
		if (this.oContentNode)
		{
			this.oContentNode.innerHTML = '';
		}

		// delete calculated dimensions so the dimensions from the original styling will be used the next time
		this.oPopupNode.style.width = null;
		this.oPopupNode.style.height = null;
		this.oContentNode.style.width = null;
		this.oContentNode.style.height = null;		
		this.oContentNode.style.minWidth = null;
		
		// remove overlay
		if (this.oOverlay)
		{
			this.oOverlay.stopObserving();
			this.oOverlay.parentNode.removeChild(this.oOverlay);
			this.oOverlay = null;
		}
		
		// remove popupnode
		$(this.oPopupNode.parentNode).stopObserving();
		
		if (this.oPopupNode)
		{
			// remove listeners
			this.oPopupNode.select("[class^='ZigPopup_']").each(function(oEl) {
				oEl.style.display = 'none';
				oEl.stopObserving();
			});	
		}	
	},

	/**
     * shows the overlay
     *
	 * @param void
     * @return void
     */		
	showOverlay: function()
	{
		if (this.oOverlay == null)
		{
			this.initOverlay();
		}
		
		this.oOverlay.style.display = this.sDisplayMode;
	},

	/**
     * hides the overlay
     *
	 * @param void
     * @return void
     */		
	hideOverlay: function()
	{
		if (this.oOverlay != null)
		{
			$(this.oOverlay).fade({duration: this.fShowHideDuration});
		}
	},

	/**
     * initializes the overlay, creates dom node with correct styling
	 * also sets some necessary event listeners
     *
	 * @param void
     * @return void
     */		
	initOverlay: function()
	{	
		this.oOverlay = $("popupOverlay");
		
		if (this.oOverlay == null)
		{
			this.oOverlay = document.createElement('div');
			this.oOverlay.style.background = '#000';
			this.oOverlay.style.display = 'none';
			this.oOverlay.style.position = 'absolute';
			this.oOverlay.style.zIndex = "900";
			
			if (Prototype.Browser.IE)
			{
				this.oOverlay.style.filter = 'alpha(opacity=60)';
			}
			else
			{
				this.oOverlay.style.opacity = 0.6;		
			}	

			document.body.appendChild(this.oOverlay);
		}
		this.positionOverlay();

		// add listeners so overlay will correct itself after scroll/resize
		Event.observe(window, 'scroll', function() {
			this.positionOverlay();
		}.bind(this));

		Event.observe(window, 'resize', function() {
			this.positionOverlay();
		}.bind(this));

		if (this.bBlocking == false)
		{
			// add listener for closing popup
			$(this.oOverlay).observe('click', function() {
				this.hide();
			}.bind(this));
		}
	},

	/**
     * positions the overlay and popup, called after a scroll or resize
     *
	 * @param void
     * @return void
     */		
	positionOverlay: function()
	{	
		if (this.oOverlay != null)
		{	
			var iScrollX = $(document.body).cumulativeScrollOffset()[0];
			var iScrollY = $(document.body).cumulativeScrollOffset()[1];
			
			var iPopupHeight = this.oPopupNode.getHeight();
			var iPopupWidth = this.oPopupNode.getWidth();
			
			// we also nede to take in account a title node which might be above the popup node	
			
			if ($('popupTitleNews'))
			{
				var iTitleAbovePopup = this.oPopupNode.viewportOffset()[1] - $('popupTitleNews').viewportOffset()[1];
		
				if (iTitleAbovePopup > 0)
				{
					iPopupHeight += iTitleAbovePopup;	
				}
			}
			
			var iTop = iScrollY + Math.round((document.viewport.getDimensions().height - iPopupHeight) / 2);
			iTop = Math.max(iTop, 4) + (iTitleAbovePopup > 0 ? iTitleAbovePopup : 0);
			
			// position the popup's parent, left is done by css, top we have to calculate
			// initial positioning is done always, we only re-position the popup if it fits on the screen and vertical scroll is true		
					
			if (this.oPopupNode.parentNode.style.top == '' || (this.bVerticalScroll == true && 
						iPopupHeight < document.viewport.getHeight() &&
						iPopupWidth < document.viewport.getWidth()))
			{
				this.oPopupNode.parentNode.style.top = iTop.toString()+'px';
			}
			
			this.oOverlay.style.top = iScrollY.toString() + "px";
			this.oOverlay.style.left = iScrollX.toString() + "px";
			
			this.oOverlay.style.width = document.viewport.getDimensions().width.toString()+'px';
			this.oOverlay.style.height = document.viewport.getDimensions().height.toString()+'px';					
		}
	}
	
});

/* ***************************************** */
/* *******************************************************
/scripts/forms/enablefield.js"
 */
function toggleField( element, enabled )
{
    element.disabled = !enabled;
    if( document.all ) element.style.backgroundColor = element.disabled ? '#EEEEEE' : '';
}

function checkFieldStatus( form, fields, enabled )
{
    postRun = new Array();
    for( i =0; i < fields.length; i++ )
    {
        //phparray
        if( form.elements[fields[i]] == null )
        {
            //we gaan door de form iteraten om te kijken of er elementen zijn die beginnen met de opgegeven naam
            for( j = 0; j < form.elements.length; j++ )
            {
                //naam van veld moet beginnen met opgegeven naam, en char daarna moet een [ zijn.
                if( form.elements[j].name.indexOf( fields[i] ) == 0 && form.elements[j].name.charAt( fields[i].length ) == "[" )
                {
                    toggleField( form.elements[j], enabled );
                }
            }
        }
        //normaal
        else if( form.elements[fields[i]].name != null )
        {
            toggleField( form.elements[fields[i]], enabled );
        }
        //jsarray
        else if( form.elements[fields[i]].length != null )
        {
            for( j = 0; j < form.elements[fields[i]].length; j++ )
            {
                toggleField( form.elements[fields[i]][j], enabled );
                if( form.elements[fields[i]][j].onclick != null)
                {
                    if( form.elements[fields[i]][j].checked )
                    {
                        postRun.unshift( form.elements[fields[i]][j] );
                    }
                }
            }
        }
    }

    for( i = 0; i < postRun.length; i++ )
    {
        postRun[i].click( );
    }
}

function triggerEnableField( id )
{
    document.getElementById( id ).click( );
}

function createFieldSubmit( frm )
{
    inp = document.createElement( "input" );
    inp.type = "hidden";
    inp.name = "__--fieldsubmit--__";
    inp.value = "1";
    frm.appendChild( inp );
}
/* *******************************************************
/scripts/forms/forms.js
 */

if (!Array.prototype.each)
{
	Array.prototype.formFormEach = function(fun)
	{
		var len = this.length;

		if (typeof fun != "function")
		{
			throw new TypeError();
		}

		var thisp = arguments[1];

		for (var i = 0; i<len; i++)
		{
			if (i in this)
			{
				fun.call(thisp, this[i], i, this);
			}
		}
	};
}

		var form_fields = Array();
		var form_conditions = Array();
		var form_field_subfields = Array();
		var form_field_multipleValuesAllowed = Array();
		var form_field_mulValues = Array();
		var form_field_currentFocus = null;

		function form_field_onkeypress(e)
		{
			var key = 0;

			if (document.layers)
			{
				key = e.which;
			}
			else if (document.all)
			{
				key = window.event.keyCode;
			}
			else
			{
				key = e.which;
			}

			/* keyID = no special char  */
			if (form_field_currentFocus != null)
			{
				var field = document.forms['defaultForm'].elements[form_field_currentFocus];
				var value = field.value;
				var newValue = value;

				if (key == 8) /* Backspace */
				{
					if (value.length == 1)
					{
						value = '';
					}
				}
				else if (key >= 32) /* 32 = spacebar */
				{
					value += 'a';
				}

				/* This even is called before */
				form_value_changed(field, form_field_currentFocus, value, -1);
			}
		}

		document.onkeypress = form_field_onkeypress; 

		function form_field_blur(fieldname)
		{
			if (form_field_currentFocus == fieldname)
			{
				form_field_currentFocus = null;
			}
		}

		function form_field_focus(fieldname)
		{
			form_field_currentFocus = fieldname;
		}

		function form_value_changed(field, fieldname, newValue, newIndex, isChecked)
		{
			var form_fieldsEnabled = Array();

			var strValue = new String(newValue);

			var regex = / |\t|\r|\n/g;

			while(strValue.search(regex) != -1)
			{
				strValue = strValue.replace(" ", "");
				strValue = strValue.replace("\t", "");
				strValue = strValue.replace("\r", "");
				strValue = strValue.replace("\n", "");
			}

			if (form_field_multipleValuesAllowed[fieldname])
			{
				form_field_mulValues[fieldname][newIndex] = isChecked;
			}

			if (form_conditions[fieldname] /*&& form_conditions[fieldname].length > 0*/)
			{
				var index = newIndex;

				var iterator = function(condition)
				{
					if (condition['comparisonMethod'] == 'option_by_value')
					{
						if (
							(form_field_multipleValuesAllowed[fieldname] && form_field_mulValues[fieldname][condition['comparisonValue']])
						||	(!form_field_multipleValuesAllowed[fieldname] && newValue == condition['comparisonValue'])
						)
						{
							form_field_toggle(condition['destField'], true);

							form_fieldsEnabled[condition['destField']] = true;
						}
						else if (!form_fieldsEnabled[condition['destField']])
						{
							form_field_toggle(condition['destField'], false);
						}
					}
					else if (condition['comparisonMethod'] == 'no_value')
					{
						if (form_field_multipleValuesAllowed[fieldname])
						{
							strValue = '';

							for(subIndex in form_field_mulValues[fieldname])
							{
								if (form_field_mulValues[fieldname][subIndex] == true)
								{
									strValue = 'aan';
								}
							}
						}
						
						if (strValue == '')
						{
							form_field_toggle(condition['destField'], true);

							form_fieldsEnabled[condition['destField']] = true;
						}
						else if (!form_fieldsEnabled[condition['destField']])
						{
							form_field_toggle(condition['destField'], false);
						}
					}
					else if (condition['comparisonMethod'] == 'got_value')
					{
						if (form_field_multipleValuesAllowed[fieldname])
						{
							strValue = '';

							for(subIndex in form_field_mulValues[fieldname])
							{
								if (form_field_mulValues[fieldname][subIndex] == true)
								{
									strValue = 'aan';
								}
							}
						}

						if (strValue != '')
						{
							form_field_toggle(condition['destField'], true);

							form_fieldsEnabled[condition['destField']] = true;
						}
						else if (!form_fieldsEnabled[condition['destField']])
						{
							form_field_toggle(condition['destField'], false);
						}
					}
					else if (condition['comparisonMethod'] == 'option_by_number')
					{
						if (
							(form_field_multipleValuesAllowed[fieldname] && form_field_mulValues[fieldname][condition['comparisonValue']])
						||	(!form_field_multipleValuesAllowed[fieldname] && newIndex == condition['comparisonValue'])
						)
						{
							form_field_toggle(condition['destField'], true);

							form_fieldsEnabled[condition['destField']] = true;
						}
						else if (!form_fieldsEnabled[condition['destField']])
						{
							form_field_toggle(condition['destField'], false);
						}
					}
					else
					{
						alert( 'Unknown comparison method: ' + condition['comparisonMethod'] );
					}
				}
			
				if (Array.prototype.each) /* for use with the protoype javascript library */
				{
					form_conditions[fieldname].each(iterator);
				}
				else /* without prototype */
				{
					form_conditions[fieldname].formFormEach(iterator);
				}
			}
		}

		function form_add_condition(sourceField, destField, comparisonMethod, comparisonValue)
		{
			var condition = Array();
			condition['sourceField'] = sourceField;
			condition['destField'] = destField;
			condition['comparisonMethod'] = comparisonMethod;
			condition['comparisonValue'] = comparisonValue;

			if (!form_conditions[sourceField])
			{
				form_conditions[sourceField] = Array();
			}
			
			form_conditions[sourceField].push(condition);
		/*	alert( 	condition['comparisonMethod'] +' toevoegen aan : ' + sourceField);*/
		}

		function form_field_setSubIndexValue(fieldname, index, value)
		{
			if (!form_field_mulValues[fieldname])
			{
				form_field_mulValues[fieldname] = Array();
			}

			form_field_mulValues[fieldname][index] = value;
		}

		function form_field_setAllowMultipleValues(name)
		{
			form_field_multipleValuesAllowed[name] = true;
			
			if (!form_field_mulValues[name])
			{
				form_field_mulValues[name] = Array();
			}
		}

		function form_field_add_subfield(name, subName, value)
		{
			if (!form_field_subfields[name])
			{
				form_field_subfields[name] = Array();
			}

			form_field_subfields[name].push(subName);
		}

		var form_field_grabbingStates = true;
		var form_field_initialState = Array();

		function form_fields_done()
		{
			form_field_grabbingStates = false;
		}

		function form_fields_reset()
		{
			var name;

			for(name in form_field_initialState)
			{
				form_field_toggle(name, form_field_initialState[name]);
			}
		}

		function form_field_toggle(name, state, depth, parentName, optionID)
		{
			if (!depth)
				depth = 1;

			parentName = parentName ? parentName : name;

			if (form_field_subfields[name] && depth != 2)
			{
				for (x in form_field_subfields[name])
				{
					form_field_toggle(form_field_subfields[name][x], state, depth+1, parentName, x);
				}
			}
			else
			{
				if (form_field_grabbingStates)
				{
					form_field_initialState[name] = state;
				}

				var form = document.getElementById('defaultForm');
				var elm = document.getElementById('in_' + name);

				if (elm)
				{
					if (state)
					{
						elm.disabled = false;
						elm.style.backgroundColor = '';
					}
					else
					{
						//elm.value = '';
						elm.selectedIndex = -1;
						elm.disabled = true;
						elm.checked = false;
						elm.style.backgroundColor = '#EEEEEE';

						switch(elm.type)
						{
							case "text":
									elm.value = '';
									form_value_changed(elm, name, elm.value, -1);
								break;

							case "select-one":
									elm.value = '';
									form_value_changed(elm, parentName, elm.value, -1);
								break;

							case "radio":
									form_value_changed(elm, parentName, elm.value, -1, false);
								break;

							case "checkbox":
									form_value_changed(document.getElementById(parentName), parentName, '', optionID, false);
								break;

							default:
								break;
						}
					}
				}
			}
		}

		/* Tooltip functions: */
		
		var cX = 0; 
		var cY = 0;
		
		function UpdateCursorPosition(e)
		{ 
			cX = e.pageX; 
			cY = e.pageY;
		}

		function UpdateCursorPositionDocAll(e)
		{ 
			cX = event.clientX; 
			cY = event.clientY;
		}

		if(document.all) 
		{ 
			document.onmousemove = UpdateCursorPositionDocAll; 
		}
		else 
		{ 
			document.onmousemove = UpdateCursorPosition; 
		}
		
		function AssignPosition(d) 
		{
			d.style.left = (cX+10) + "px";
			d.style.top = (cY+10) + "px";
		}

		function HideContent(d) 
		{
			if(d.length < 1) 
			{ 
				return; 
			}
			
			document.getElementById(d).style.display = "none";
		}
		
		function ShowContent(d) 
		{
			if(d.length < 1) 
			{ 
				return; 
			}

			var dd = document.getElementById(d);
			AssignPosition(dd);
			dd.style.display = "";
		}
		
		function remark(d) 
		{
			if(d.length < 1) 
			{ 
				return; 
			}
			
			var dd = document.getElementById(d);
			AssignPosition(dd);
			
			if (dd.style.display == "block") 
			{ 
				dd.style.display = "none"; 
			}
			else 
			{ 
				dd.style.display = "block"; 
			}
		}		

