var _a = {
	
	_working: '<span class="working"> Bezig ...</span>',

	_formToHash: function(form) {

		var params = Form.serializeElements(Form.getElements(form), true);
		return params;

	},

	setFormMessage: function(form, msg, b) {

		var msgContainer = typeof(form.msgContainerElement) == "undefined" 
				? (form.down('fieldset') ? form.down('fieldset') : form)
				: form.msgContainerElement;

		// if there's more than one fieldset, we will put the message back into
		// form tag
		if (form.down('fieldset', 1)) msgContainer = form;

		Try.these( 
			function() { $(msgContainer).down('span.msg').update(msg) },
			function() { 
				new Insertion.Top(msgContainer, '<span class="msg" />');
				$(msgContainer).down('span.msg').update(msg);
			}
		);

		var target = $(msgContainer).getElementsBySelector('span.msg')[0];

		return target;
	},
	postForm: function(form, msgTarget, callBack) {

		var params = _a._formToHash(form);
		params['_ajax'] = '1';

		if (params['Delete'] && !confirm('Weet je zeker dat je wilt verwijderen?')) {
			return false;
		}
		if (params['ConfirmMessage'] && !confirm(params['ConfirmMessage'])) return false;

		try {
			if (msgTarget) $(msgTarget).innerHTML = this._working;
		} catch (e) {
			alert('Error finding msgTarget '+msgTarget+': ' + e);
			return false;
		}

		Form.disable(form);
		// always wait half a second before actually posting. This fixes any potential
		// problems with various other form handlers (such as those used by TinyMCE)
		var me = this;

		setTimeout(function() {
			me._doCall(form.action, params, function(r, text, status, doc) {

				if (form.hasClassName('alertError') && status == 0) {
					_a.setFormMessage(form, '');
					alert(text);
				} else if (msgTarget) {

					$(msgTarget).innerHTML = text;
					if (form.hasClassName('applyBehaviour')) Behaviour.applyFrom($(msgTarget));

				}

				Form.enable(form);

				if (status == 1) {
					// perhaps handle some kind of other handler thingus?
					if (form.hasClassName('replaceParent')) {
					
						if (form.hasClassName('replacePage')) {
							var target = $(form.parentNode);
							alert(target);
						}
						
						var target = $(form.parentNode);

						// before updating content, kill any tinyMce editors
						target.getElementsBySelector('textarea.tiny_area').each(function(ty) {
							tinyMCE.execCommand('mceRemoveControl', true, ty.id);
						});
						// update text
						target.update(text);
						
						// apply behaviour
						Behaviour.applyFrom(target);
						

					} else if (form.hasClassName('removeTableRow')) {
		
						var row = form.up('tr');
						row.remove();

					} else {
						//Form.reset(form);
					}
				}

				try {
					// consider doing some math to check if message span is visible
					// if (msgTarget && !form.hasClassName('noscroll')) Element.scrollTo($(msgTarget.parentNode));
				} catch (e) {alert(e);};
				try{
					$('schoolRefresh').submit();
				}catch(e){
					
				}
				if (callBack) return callBack(form, r, text, status, doc);

			});
		}, 500);
			
		return true;
	},

	submitUploadForm: function(form, msgTarget, required) {
		var ok = true;
		try {
			for(var i = 0; i < required.length; i++) {
				if (required[i].value == "") ok = false;
			}
		} catch (e) { 
			alert(e); 
		};

		if (ok) {
			$(msgTarget).innerHTML = 'Uploading ...';
			// cannot submit disabled form, but disabled looks good :[
			setTimeout(function() {
				Form.disable(form);
			}, 1000);
			return true;
		} else {
			$(msgTarget).innerHTML = 'Please select a file';
		}

		return false;
	},

	_parseXmlString: function(text) {

		var tags = { resStatus: 0, resContent: '' };
		if (text) {
			try {
				$A(Xparse(text).contents[0].contents).each(function(ct) {
					if (ct.contents) tags[ct.name] = ct.contents[0].value;
				});
			} catch(e) {
				tags['resContent'] = e.message;
			}
		};

		return tags;

	},

	_doCall: function(target, params, cb, timeOut) {
		
	//	alert(target);	
	//	alert(params);
	//	alert(cb);
	//	alert(timeOut);
		
		params['_ajax'] = 1;
		var r = new Ajax.Request(target, {

			parameters: params,

			on200: function(req) {

				var text = req.responseText;
				var doc,status;
				try {
					doc 	= eval('(' + req.responseText + ')');
					status 	= doc.status;
					text	= doc.content == undefined ? '' : doc.content;

					Debug.write("Return from " + target + ", status = " + status + ", contentLength = " + text.length);

				} catch(e) {

					doc 	= {};
					status 	= false;
					text	= '<div class="error_msg">Onbekend antwoord ontvangen van de server: ' + req.responseText + '</div>';
					//text	= target + '-' + params + '-' + cb + '-' + timeOut;

					Debug.error(e);
				}

				if (cb) return cb(req, text, status, doc);

			},
			on500: function(r) {
				alert('Error 500: ' + t.statusText + "\n\n" + t.responseText);
			},
			on404: function(t) {
				alert('Error 404: location "' + t.statusText + '" was not found.');
			},
			onFailure: function(t) {
				alert('Error ' + t.status + ' -- ' + t.statusText);
			}
		});

	},

	call: function(target, method, params, cb) {
	
		params['_ajaxCall'] = method;
		this._doCall(target, params, cb);

	},

	goFormAction: function(form) {
		Form.disable(form);

		document.location.href = form.action;
		
		return false;
	}

};

Behaviour.register({

	'a.ajax': function(el) {

		el.onclick = function() {
			_a.call(el.href, '', {}, function(r, text, status) {
				
				if (status) {
					
					Try.these(function() {
						$(el).up('.contentParent').update(text);
					}, 
					function() {
						el.parentNode.update(text);
					});
				} else {
					alert(text);
				}

			});
			return false;
		};
	},
  'div.default_complaint_button': function (el) {
          Event.observe(el, 'click', function() {
		                  var newWin = window.open("/front/studio/klacht/?ID="+this.id, "popup" + Math.round(Math.random() * 1000),'height=526, width=350, menubar=no, scrollbars=yes, location=no, resizable=no, status=no, titlebar=yes'); //menubar en status en location stonden uit
						                  newWin.focus();
										                  });
														      },
															  
	'a.basicAjaxCall': function(el) {

		el.onclick = function() {
			var ID = el.href.replace(/^.*#/, '');
			_a.call(el.href, '', { ID: ID}, function(r, text, status) {
				
				if (status) {
					el.parentNode.update(text);
				} else {
					alert(text);
				}

			});
			return false;
		};

	}
});

function callToOverlay(target, method, params, maximize) {

	var overlay = addOverlayElement();
	var title	= '&nbsp;';

	overlay.setTitle(title);
	overlay.setContent('<div class="opening_overlay">&nbsp;</div>');

	_a.call(target, method, params, function(r, text, status) {
		if ((status*1) == 0) {
			overlay.close();
			alert(text);
		} else {
			overlay.setActive();
			overlay.setContent(text);
			if (maximize) overlay.maximize();
		}
	});


	return overlay;
}
