/**

 * ZigPopup
 */
function showPopup(oConfig)
{	
	if(typeof(oConfig) == 'object')
	{
		if(typeof(oConfig.title) == 'undefined')
		{
			oConfig.title = '';
		}
		oPopup = new ZigPopup($('popup'));
		oPopup.setTitle(oConfig.title);
		oPopup.setContent(oConfig.content);
		
		oPopup.show();
	}
}

/**
 * ZigPopup Alert function
 * oConfig looks like: {title:'text',content:'text'}
 */
function showAlertPopup(oConfig)
{	
	if(typeof(oConfig) == 'object')
	{
		if(typeof(oConfig.title) == 'undefined')
		{
			oConfig.title = '';
		}	
		var oAlertPopup = new ZigAlertPopup($('popup'));
		oAlertPopup.setTitle(oConfig.title);
		oAlertPopup.setContent(oConfig.content);
		oAlertPopup.show.bind(oAlertPopup).delay(0.2); // delay a little to prevent IE dom node bug
	}
}

/**
 * ZigPopup Confirm function
 * 
 */
function showConfirmPopup(oConfig)
{			
	var oConfirmPopup = new ZigConfirmPopup($('popup'));

	if(typeof(oConfig) == 'object')
	{
		if(typeof(oConfig.title) == 'undefined')
		{
			oConfig.title = '';
		}

		oConfirmPopup.setTitle(oConfig.title);
		oConfirmPopup.setContent(oConfig.content);
		
		if(typeof(oConfig.location) != 'undefined')
		{
			oConfirmPopup.setOkHandler(function() {
					document.location = oConfig.location;
				}
			);
		}
		
		oConfirmPopup.show();
	}
	
}

/**
 * CKEditor set a selected value from a dropdown in the editor (used in edit Email view)
 * 
 * @param sValue
 * @param sElementId
 */
function insertSelectedValueInField(sValue,sElementId)
{
	var oEditor = CKEDITOR.instances[sElementId];
	
	// Check the active editing mode.
	if (oEditor && oEditor.mode == 'wysiwyg' )
	{
		// Insert the desired HTML.
		oEditor.insertHtml( sValue );
	}
	else
	{
		$(sElementId).innerHTML += sValue;
	}
}

/**
 * check if a user exists
 * 
 * @param string sRequestUrl
 * @param string sCsn
 * @param string sLastname
 * @param string sBirthdate (YYYY-MM-dd)
 * @param string sError
 * @return
 */
function isExistingUser(sRequestUrl,sCsn,sLastname,sBirthdate,sError)
{
	//default a user exists
	var bExists = true; 

	var oRequest = new Ajax.Request(sRequestUrl+'?format=json&csn=' + sCsn + '&lastname=' + sLastname + '&birthdate=' + sBirthdate,
						{
							method: 'get',
							asynchronous : false,
							onSuccess: function(oTransport,oJson)
							{
								oJson = oTransport.responseJSON;

								if(oJson.double.doubleCsn || oJson.double.doubleNameBirthdate)
								{
									showAlertPopup({content:sError});
								}
								else
								{
									bExists = false;
								}
							},
							onFailure: function()
							{
								showAlertPopup({content:sError});
							}
							
						}
					);

	return bExists;
}

/**
 * get address call
 * 
 */
var getAddress = Class.create({

	sRequestUrl : '',
	oCountry	: null,
	oPostal		: null,
	oHousenumber: null,
	oStreet		: null,
	oCity		: null,
	sError		: 'De door u opgegeven combinatie van postcode en huisnummer kan niet worden gevonden',
	bWbs		: false,
	bRequest	: false,
	bChanged	: false,
	iTimeLastChange : null,
	oUpdater	: null,
	/**
	 * constructor	 
	 */
	initialize: function(sRequestUrl,sCountryField,sPostalField,sHouseNumberField,sStreetField,sCityField,sError,bWbs) 
	{
		this.sRequestUrl 	= sRequestUrl;
		this.oCountry 		= $(sCountryField);
		this.oPostal 		= $(sPostalField);
		this.oHousenumber 	= $(sHouseNumberField);
		this.oStreet 		= $(sStreetField);
		this.oCity 			= $(sCityField);
		this.sError			= sError;
		this.bWbs			= bWbs;
		
		if(this.oCountry && this.oPostal && this.oHousenumber)
		{
			this.oCountry.observe('change',this.request.bind(this));
			this.oPostal.observe('change',this.setActivateRequest.bind(this));
			this.oHousenumber.observe('change',this.setActivateRequest.bind(this));
			//this.oCountry.observe('blur',this.setDoRequest.bind(this));
			this.oPostal.observe('blur',this.setDoRequest.bind(this));
			this.oHousenumber.observe('blur',this.setDoRequest.bind(this));
			this.oCountry.observe('focus',this.setCancelRequest.bind(this));
			this.oPostal.observe('focus',this.setCancelRequest.bind(this));
			this.oHousenumber.observe('focus',this.setCancelRequest.bind(this));
		}
		
		/* Mantis 24346 */
		this.preprocess();
	},
	
	setActivateRequest : function()
	{
		this.bChanged = true;
	},
	
    /**
     * activate the do request
     * 
     * @return void
     */	
	setDoRequest: function()
	{
		this.iTimeLastChange = new Date().getTime();
		this.bDoRequest = true;
	},
	
    /**
     * cancel request
     * 
     * @return void
     */	
	setCancelRequest: function()
	{
		this.bDoRequest = false;
	},

	/**
	* preprocess address fields
	*
	*/
	preprocess : function()
	{
		if(this.oCountry != null && this.oCountry.value != '524')
		{
			this.enable();
		}

		this.oUpdater = new PeriodicalExecuter(
				function(oPE)
				{
					if(this.bDoRequest && this.bChanged)
					{
						var iTimeChanged = new Date().getTime();
						var iTimeDifference = iTimeChanged - this.iTimeLastChange;
						if(iTimeDifference > 500)
						{
							this.bDoRequest = false;
							this.bChanged 	= false;
							this.request();
							
						}
					}
			}.bind(this), 1);
	},
	
	
	
	/**
	* do request to get address
	*
	*/
	request : function()
	{
		if(this.oCountry == null)
		{
			return;
		}
		
		if(this.oCountry.value != '524')
		{
			this.enable();
		}
		else
		{
			this.disable();
			this.loading();
			if(this.oPostal.value && this.oHousenumber.value)
			{
				var oCloneRequest = this;
				
				var oRequest = new Ajax.Request('/portal/core?ajaxcall=getaddress&postalcode='+this.oPostal.value+'&housenumber='+this.oHousenumber.value,
												{
													evalScripts : true,
													onSuccess : function(oTransport,oJson)
																{
																	if(!oJson)
																	{
																		oJson = eval('(' + oTransport.responseText + ')');
																	}
																	
																	if(oJson.error)
																	{
																		oCloneRequest.error(oJson.error);
																	}
																	else if(oJson.street && oJson.city)
																	{
																		oCloneRequest.oStreet.value = oJson.street;
																		oCloneRequest.oCity.value 	= oJson.city;
																	}
																	
																	oCloneRequest.loadingDone();
																},										
													onFailure : function()
																{
																	oCloneRequest.error();
																	oCloneRequest.loadingDone();
																}
				
				});
			}
		}
	},

	/**
	* enable the city field
	* See also .../portal/extend/library/Parkstad/Form/Applicant.php
	*/
	enable: function()
	{
		this.oStreet.disabled 	= false;
		this.oCity.disabled 	= false;
	},
	
	loading : function()
	{
		
		/**
		 * not enabled because of style diff in IE 6 + 7
		 */
		return;
		
		var oInput = document.createElement('input');
		oInput.value			= '...ophalen...';
		oInput.id				= 'formElement-street-overlay-loading';
		oInput.disabled			= 'disabled';
		oInput.style.position 	= 'absolute';
		oInput.style.marginLeft = '240px';
		oInput.style.marginTop 	= '-17px';	
		$('formElement-street').insert(oInput);
		
		var oCityInput = oInput.cloneNode(true);
		oCityInput.id			= 'formElement-city-overlay-loading';
		$('formElement-city').insert(oCityInput);
	},
	
	
	loadingDone : function()
	{
		/**
		 * not enabled because of style diff in IE 6 + 7
		 */
		return;
		
		$('formElement-street-overlay-loading').remove();
		$('formElement-city-overlay-loading').remove();
	},
	
	
	/**
	* disable the city field
	* See also .../portal/extend/library/Parkstad/Form/Applicant.php
	*/
	disable: function()
	{
		this.oStreet.disabled 	= "disabled";
		this.oCity.disabled 	= "disabled";
	},

	/**
	* handle the error and show it
	*/
	error: function(sError)
	{		
		/* Parkstad: Enable street and city for WBS */
		if(this.bWbs)
		{
			this.enable();
		}
		else
		{
			/* Clear street and city */
			this.oStreet.value = '';
			this.oCity.value = '';
		}
		
		showAlertPopup({content:sError});
	}

});


/**
 * get url via ajax
 * 
 * onsuccess, open popup with response and let handleAjaxLogin submit the form via ajax
 * 
 * @var string sUrl
 */
function ajaxLogin(sUrl)
{
	var oRequest = new Ajax.Request(sUrl,{
		method		:	'get',
		evalScripts	: 	true,
		onSuccess 	: 	function(oTransport)
						{
								showPopup({content:oTransport.responseText,title:'Inloggen'});
								handleAjaxLogin(oPopup);					
						}
		});
}

/**
 * submit form via ajax
 * 
 * of response is json, reload location with returned url
 * else, show the login form again
 */
function handleAjaxLogin(oPopup)
{
	var oForm = $$('#'+oPopup.oPopupNode.id+' form').first();
	
	if(oForm)
	{									
		oForm.observe('submit',function(e){ 
			
			var oPostedForm = Event.element(e);
			var sForminput 	= oPostedForm.serialize();
			var sFormaction = oPostedForm.action;
			var sFormmethod = oPostedForm.method;	

			Event.stop(e);
			
			var oRequest = new Ajax.Request(
					sFormaction,
					{
						evalScripts	: true,
						method		: sFormmethod,
						parameters	: sForminput,
						onSuccess	: function(oTransport,oJson)
						{
							if(oTransport.getHeader('Content-Type') == 'application/json')
							{
								oJson = eval('(' + oTransport.responseText + ')');		
								document.location = oJson.url;
							}
							else
							{
								oPopup.setContent(oTransport.responseText);
								handleAjaxLogin(oPopup);
							}
						
						},
						onFailure 	: function()
									{
										Popup.setOptions({content: 'Er is een onbekende fout opgetreden'});
									}
					}
				);
			}
		);
	}
}


Ajax.AutocompleterSelect = Class.create({
	
	oSelect: null,
	oOptionsOverlaySelect: null,
	oOriginalOptions: [],	
	oText: null,
	
	sUrl: null,
	onSelect: null,
	
	sSearchText: 'search',
	
	initialize: function(oSelect, aOptions) 
	{
		this.oSelect = $(oSelect);
		this.oOriginalOptions = Object.clone(this.oSelect.options);
		
		if (typeof(aOptions) != 'undefined')
		{
			if (typeof(aOptions.sUrl) === 'string')
			{
				this.setUrl(aOptions.sUrl, true);
			}
			
			if (typeof(aOptions.onSelect) == 'function')
			{
				this.onSelect = aOptions.onSelect;
			}		
			
			if (typeof(aOptions.sSearchText) == 'string')
			{
				this.sSearchText = aOptions.sSearchText;
			}					
		}
			
		
		// create textfield for searching
		this.oText = document.createElement('input')
		this.oText = $(this.oText);
		this.oText.type = 'text';		
		this.oText.id = this.oSelect.id + '_search';
		this.oText.style.border = 'none';

		if (this.oSelect.selectedIndex > 0)
		{
			// show pre-selected option
			this.oText.style.color = '#000';
			this.oText.value = this.oSelect.options[this.oSelect.selectedIndex].text;
		}
		else
		{		
			this.oText.style.color = '#444';		
			this.oText.value = this.sSearchText;
		}
		
		// dimensions of text box based on the size of the selectbox
		this.oText.style.width = (this.oSelect.getDimensions().width - 24).toString() + 'px';
		this.oText.style.height = (this.oSelect.getDimensions().height - 2).toString() + 'px';
		
		// add text box to dom
		this.oSelect.parentNode.appendChild(this.oText);
				
		// fix relative position of the textbox
		var offsetX = this.oSelect.cumulativeOffset()[0] - this.oText.cumulativeOffset()[0];
		var offsetY = this.oSelect.cumulativeOffset()[1] - this.oText.cumulativeOffset()[1];
		this.oText.style.position = 'relative';
		this.oText.style.left = (offsetX+2).toString() + 'px';
		this.oText.style.top = (offsetY+1).toString() + 'px';		
		this.oText.style.marginBottom = (offsetY+2).toString() + 'px';
		this.oText.style.paddingLeft = '2px';
		this.oText.setAttribute('autocomplete', 'off');
		
		// overlay to display options while typing		
		this.oOptionsOverlaySelect = document.createElement('select');
		this.oOptionsOverlaySelect.size = 6;
		this.oOptionsOverlaySelect = $(this.oOptionsOverlaySelect);

		// width of overlay based on the size of the selectbox
		this.oOptionsOverlaySelect.style.width = (this.oSelect.getDimensions().width).toString() + 'px';
		this.oOptionsOverlaySelect.style.height = '80px';

		// add the overlay select to dom
		document.body.appendChild(this.oOptionsOverlaySelect);		
		
		// we fix the position later, just before showing
		this.oOptionsOverlaySelect.style.position = 'absolute';		
		this.oOptionsOverlaySelect.style.display = 'none';
		
		// various listeners
		this.oText.observe('focus', function()
		{	
			this.oText.style.color = '#000';
			this.oText.value = '';
			this.oSelect.selectedIndex = 0;
		}.bind(this));

		this.oText.observe('blur', function()
		{
			// wait a little until we know which element received focus after this blur
			// if it's not or selectbox overlay, we want to trigger the "select box changed" code
			var blurDelay = function()
			{
				
				if (document.activeElement != this.oOptionsOverlaySelect)
				{
					this.selectBoxChanged();
				}
			}.bind(this);
			
			blurDelay.delay(0.4);
				
		}.bind(this));		

		this.oText.observe('keyup', function(oEvent)
		{				
			if (oEvent.keyCode == Event.KEY_DOWN)
			{
				// down key while typing? place focus on selectbox overlay
				this.oOptionsOverlaySelect.selectedIndex = 0;
				this.oOptionsOverlaySelect.focus();
				return;
			}
		
			// wait a little to see if we stopped typing
			this.sOldSearchValue = this.oText.value
			
			var searchDelay = function(sOldValue)
			{	
				if (this.sOldSearchValue == this.oText.value)
				{	
					this.sOldSearchValue = null;
					// we seem to have stopped typing, so call search url
					
					new Ajax.Request(this.sUrl, {
						method: 'post',
						parameters: {search: this.oText.value},
						onSuccess: function(response) 
						{
							var aResults = response.responseText.evalJSON().aResults;

							// fill selectbox with these options
							this.oSelect.options.length = 0;
		
							for (var iId in aResults)
							{
								var oOption = document.createElement("option");
								oOption.text = aResults[iId];
								oOption.value = iId;
								
								this.oSelect.options.add(oOption);
							}
							
							this.showOverlaySelect();
							
						}.bind(this)
					});
				}
			}.bind(this);

			searchDelay.delay(0.6);
						
		}.bind(this));			
		
		this.oSelect.observe('focus', function()
		{
			this.oOptionsOverlaySelect.style.display = 'none';
		}.bind(this));

		this.oSelect.observe('change', function()
		{
			this.selectBoxChanged();
		}.bind(this));
		
		
		this.oOptionsOverlaySelect.observe('keyup', function(oEvent)
		{				
			if (oEvent.keyCode == Event.KEY_RETURN)
			{
				this.oSelect.selectedIndex = this.oOptionsOverlaySelect.selectedIndex;	
				this.oOptionsOverlaySelect.style.display = 'none';
				this.selectBoxChanged();				
			}			
		}.bind(this));	
		
		this.oOptionsOverlaySelect.observe('mouseup', function()
		{	
			this.oSelect.selectedIndex = this.oOptionsOverlaySelect.selectedIndex;	
			this.oOptionsOverlaySelect.style.display = 'none';
			this.selectBoxChanged();						
		}.bind(this));			
	},
	
	showOverlaySelect: function()
	{
		this.oOptionsOverlaySelect.options.length = 0;
		
		for (var i = 0 ; i < this.oSelect.options.length ; i++)
		{
			var oOption = document.createElement("option");
			oOption.text = this.oSelect.options[i].text;
			oOption.value = this.oSelect.options[i].value;
			
			this.oOptionsOverlaySelect.options[i] = oOption;
		}
		
		// fix absolute position of overlay, and make it visible
		this.oOptionsOverlaySelect.style.left = this.oSelect.cumulativeOffset()[0].toString() + 'px';	
		this.oOptionsOverlaySelect.style.top = (this.oSelect.cumulativeOffset()[1] + this.oSelect.getDimensions().height-1).toString() + 'px';				
		this.oOptionsOverlaySelect.style.display = 'inline';
	},
	
	restoreOriginalOptions: function(iSelectId)
	{
		this.oSelect.options.length = 0;
		
		var iSelectedIndex = 0;
		
		for (var i = 0 ; i < this.oOriginalOptions.length ; i++)
		{
			var oOption = document.createElement("option");
			oOption.text = this.oOriginalOptions[i].text;
			oOption.value = this.oOriginalOptions[i].value;
			
			this.oSelect.options.add(oOption);
			
			if (iSelectId == this.oOriginalOptions[i].value)
			{
				iSelectedIndex = i;
			}
		}
		
		this.oSelect.selectedIndex = iSelectedIndex;
	},
	
	selectBoxChanged: function()
	{	
		this.oOptionsOverlaySelect.style.display = 'none';
					
		var iId = parseInt(this.oSelect.options[this.oSelect.selectedIndex].value, 10);
		var sLabel = this.oSelect.options[this.oSelect.selectedIndex].text;
		
		this.restoreOriginalOptions(iId);						
		
		this.oText.style.color = '#000';
		this.oText.value = sLabel;
		
		if (this.onSelect != null)
		{
			this.onSelect.apply(this, [iId]);
		}
	},
	
	setUrl: function(sUrl, bSkipRetrieve)
	{
		this.sUrl = sUrl;	
		
		if (typeof(bSkipRetrieve) == 'undefined' || bSkipRetrieve === false)
		{
			// retrieve items for this new url, without a search
			
			new Ajax.Request(this.sUrl, {
				method: 'get',
				onSuccess: function(response) 
				{
					var aResults = response.responseText.evalJSON().aResults;

					// fill selectbox with these options and overwrite the original options
					this.oSelect.options.length = 0;
						
					// first empty option
					var oOption = document.createElement("option");
					oOption.text = '';
					oOption.value = '';					
					this.oSelect.options.add(oOption);					
					
					for (var iId in aResults)
					{
						var oOption = document.createElement("option");
						oOption.text = aResults[iId];
						oOption.value = iId;
						
						this.oSelect.options.add(oOption);
					}
					
					this.oOriginalOptions = Object.clone(this.oSelect.options);
					
				}.bind(this)
			});
			

		}
	}

});

document.observe("dom:loaded", function()
{	

	if ($('localAuthority'))
	{
		authorityCompleter = new Ajax.AutocompleterSelect($('localAuthority'),	{	
										sUrl: "/portal/customclientdata/frontend/searchlocalauthority?format=json",
										sSearchText: "", // (zoeken...)
										onSelect : function(iId)
										{	
											// update financialAidType selectbox with aidtypes linked to selected authority
											if ($('financialAidType'))
											{
												var sUrl = '/portal/customclientdata/frontend/retrieveaidtypes' +
																(typeof(iId) != 'undefined' ? '?authority='+iId+'&' : '?') + 
																'format=json';
												
												new Ajax.Request(sUrl, {
													method: 'get',
													onSuccess: function(response) 
													{	
														
														var iCurrentTypeId = $('financialAidType').options[$('financialAidType').selectedIndex].value;
														
														$('financialAidType').options.length = 0;
														
														var iSelectedIndex = 0;
														var iCounter = 1;
														
														var aResults = response.responseText.evalJSON().aResults;
														
														for (var iId in aResults)
														{
															var oOption = document.createElement("option");
															oOption.text = aResults[iId];
															oOption.value = iId;
															
															if (iCurrentTypeId == iId)
															{
																iSelectedIndex = iCounter;
															}
															
															
															$('financialAidType').options[iCounter] = oOption;

															iCounter++;
														}
																												
														if (iSelectedIndex > 0 || $('financialAidType').options.length == 1)
														{
															$('financialAidType').selectedIndex = iSelectedIndex;
														}																												
														
													}.bind(this)
												});											
											}
										}
									});
	}
	
	if ($('financialAidType'))
	{	
		$('financialAidType').observe('change', function()
		{
			var iAidTypeId = $('financialAidType').options[$('financialAidType').selectedIndex].value;
			
			// restrict choices	for local authority field
			var sUrl = authorityCompleter.sUrl;
			
			// first strip previous selection, if any
			if (sUrl.indexOf('&type=') > -1)
			{
				sUrl = sUrl.split('&type=').shift();
			}
			
			if (iAidTypeId > 0)
			{
				// now add parameter for selected type
				sUrl += '&type='+iAidTypeId;
			}
			
			authorityCompleter.setUrl(sUrl);
					
		});
	}
});

