var ie =		(navigator.appName.indexOf('Explorer')>-1);
var isIE  =		(navigator.appVersion.indexOf("MSIE") != -1);
var isIE7  =	(navigator.appVersion.indexOf("MSIE 7") != -1);
var isWin =		(navigator.appVersion.toLowerCase().indexOf("win") != -1);
var isOpera =	(navigator.userAgent.indexOf("Opera") != -1);
var isWebkit =	(navigator.userAgent.toLowerCase().indexOf("webkit") != -1);

var langstrings = {
	nl: {
		notice: "Melding",
		tinymce_title: "Tinymce wysiwyg",
		ok: "Ok",
		cancel: "Annuleer"
	},
	en: {
		notice: "Notice",
		tinymce_title: "Tinymce wysiwyg",
		ok: "Ok",
		cancel: "Cancel"
	}
};

(function($) {
	$.extend($.ui.dialog.prototype, {
		rx_trigger: function(func,data) {
			func(this,data);
		},
		rx_returnData: function(data) {
			if (typeof(this.options['returnData']) == "function") {
				this.uiDialog.find('.ui-dialog-content').trigger('returnData', data);
			} else if (this.options['popupOnElem'] && typeof(data) != "object" && typeof(data) != "undefined") {
				this.options['popupOnElem'].value = data;
			}
		}
	});
})(jQuery);

// Helper functions

function windowWidth() {
	if(!window.opera && document.documentElement && document.documentElement.clientWidth)
	return document.documentElement.clientWidth;
	else if(document.body && document.body.clientWidth)
	return document.body.clientWidth;
	else if(window.innerWidth) {
		return (document.width>window.innerWidth) ? window.innerWidth-16 : window.innerWidth;
	}
	return 0;
}

function windowHeight() {
	if(!window.opera && document.documentElement && document.documentElement.clientHeight)
	return document.documentElement.clientHeight;
	else if(document.body && document.body.clientHeight)
	return document.body.clientHeight;
	else if(window.innerHeight) {
		return (document.height>window.innerHeight) ? window.innerHeight-=16 : window.innerHeight;
	}
	return 0;
}

function elementGetY (obj) {
	var y = 0;
	var o = obj;
	while (obj.offsetParent) {
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return y;
}





// Dialog functions

// Create a dialog from a uniquely created div-element and set some default properties.
function rx_dialog(options) {
	
	var elm = document.createElement("div");
	var $elm = $(elm);
	elm.id = $elm.guid();
	elm.setAttribute("title", typeof(options['title']) != 'undefined' ? options['title'] : langstrings[rx_lang].notice);
	if(typeof(options['msg']) != 'undefined') elm.innerHTML = options['msg'];
	document.body.appendChild(elm);

	var dialog_options = {
		closeOnEscape: true,
		resizable: false,
		autoOpen: false,
		modal : true,
		width : (typeof(options['width']) != 'undefined' ? options['width'] : 'auto'),
		height : (typeof(options['height']) != 'undefined' ? options['height'] : 'auto'),
		maxWidth : $(window).width()-60,
		maxHeight : $(window).height()-(options.buttons ? 150 : 60 )
	};
	dialog_options = $.extend(dialog_options, options);

	if ( dialog_options.maxWidth || dialog_options.maxHeight ) {
		var fun = function(event, ui) {
			if(dialog_options.maxWidth) $(this).css({'max-width': dialog_options.maxWidth, 'overflow-x': 'auto'});
			if(dialog_options.maxHeight) $(this).css({'max-height': dialog_options.maxHeight, 'overflow-y': 'auto'});
		};

		if (dialog_options.open) {
			var oldfun = dialog_options.open;
			dialog_options.open = function(event, ui) {
				oldfun.call(this,event,ui);
				fun.call(this,event,ui);
			}
		} else {
			dialog_options.open = fun;
  		}
	}

	$elm.dialog(dialog_options);

	// Solve the focus problem with dialog buttons
	var the_widget = $elm.dialog('widget');
	if(dialog_options.buttons) {

		$elm.bind('dialogopen', function(event, ui) {
			the_widget.find('.ui-dialog-buttonpane button[hasfocus=true]:last').focus();
		});

		the_widget
			.bind('keydown', function(e) {
				var found_button = false;

				if(e.keyCode == 37) {
					$(this).find('.ui-dialog-buttonpane :tabbable').each(function() {
						if(found_button) return;
						if($(this).is(':focus')) {
							$(this).prev('button').focus();
							found_button = true;
						}
					});
					e.stopPropagation();
				}
				if(e.keyCode == 39) {
					$(this).find('.ui-dialog-buttonpane :tabbable').each(function() {
						if(found_button) return;
						if($(this).is(':focus')) {
							$(this).next('button').focus();
							found_button = true;
						}
					});
					e.stopPropagation();
				}
			});
	}

	// Bind default events to the dialog
	$elm.bind('dialogclose', function(event, ui) {
		$elm.html('');
		$(this).dialog('destroy');
		document.body.removeChild(elm);
	});

	// Handige returndata trigger
	if(typeof(options['returnData']) != 'undefined') {
		$elm.bind('returnData', options['returnData']);
	}

	return elm;
}

// This function needs jQuery to be loaded. See example dialog in Module Gallery (oldadmin/custom.tpl)
function rx_alert(options) {
	var $alert_div = $(rx_dialog(
		$.extend({
				width : 300,
				bgiframe: true,
				buttons: {
					Ok: function() {$(this).dialog('close');}
				}
			},
			options
	)));
	return $alert_div.dialog('open');
}

// This function needs jQuery to be loaded. See example dialog in Module Topic (@delete_topic) (oldadmin/custom.tpl)
function rx_confirm(options) {
	var buttons = {};
	buttons[langstrings[rx_lang].cancel] = function() {$(this).trigger("OnCancel");$(this).dialog('close');};
	buttons[langstrings[rx_lang].ok] = function() {$(this).trigger("OnConfirm");$(this).dialog('close');}
	var $alert_div = $(rx_dialog(
		$.extend({
				width : 300,
				bgiframe: true,
				buttons: buttons
			},
			options
	)));
	if(typeof(options['OnConfirm']) != 'undefined') $alert_div.bind('OnConfirm', options['OnConfirm']);
	if(typeof(options['OnCancel']) != 'undefined')  $alert_div.bind('OnCancel',  options['OnCancel']);
	return $alert_div.dialog('open');
}

//  This function needs jQuery to be loaded. See example dialog (change_image) in Module Gallery (oldadmin/custom.tpl)
function rx_frame_dialog(options) {
	if ( options.popupOnElem) popupOnElem = options.popupOnElem;
	var frame_div = rx_dialog($.extend({title:''}, options));
	var $frame_div = $(frame_div);

	options.maxWidth = $frame_div.dialog('option', 'maxWidth');
	options.maxHeight = $frame_div.dialog('option', 'maxHeight');

	var page_container = document.createElement("iframe");
	page_container.id = $(page_container).guid();
	page_container.width = options['pc_width'] ? options['pc_width'] : '300';
	page_container.height = options['pc_height'] ? options['pc_height'] : '300';
	page_container.frameBorder = 0;

	function onloadedevent(newfunction) {
		if (page_container.addEventListener) {
			page_container.addEventListener("load", newfunction, false);
		} else if (page_container.attachEvent) {
			page_container.detachEvent("onload", newfunction);
			page_container.attachEvent("onload", newfunction);
		}
	}

	onloadedevent(function() {
		setTimeout(function() {
			if (options.skipfirst_resize) {
				options.skipfirst_resize = false;
				return;
			}
			$(page_container).RX_resizeToContent(options);
			$(page_container).trigger("OnResize");
		}, 200);
		setTimeout(function() {
			if (page_container.contentWindow && page_container.contentWindow.$) {
				page_container.contentWindow.$('body').bind('contentchange', function() {
					$(page_container).RX_resizeToContent(options);
				});
			}
		}, 1000);
	});

	$(page_container).bind("OnResize", function() {
		// fix titlebar width for msie7
		if(isIE7) {
			var $tb = $(this).parent().parent().find(".ui-dialog-titlebar");
			var tot = $tb.outerWidth(true)-$tb.width();
			$tb.width(($(this).parent().get(0).scrollWidth-tot));
		}
		$frame_div.dialog("option", "position", "center");
	});
	
	frame_div.appendChild(page_container);
	page_container.src = options['url'];

	// Save a reference to the jQuery Dialog object.
	// You can access it in your iframe through window.frameElement.dialog_window
	page_container.dialog_window = $frame_div;

	return $frame_div.dialog('open');
}

// Create a dialog from a uniquely created div-element and set some default properties.
function rx_tinymce_dialog(options) {
	
	var elm = document.createElement("div");
	var $elm = $(elm);
	elm.id = $elm.guid();
	elm.setAttribute("title", typeof(options['title']) != 'undefined' ? options['title'] : langstrings[rx_lang].tinymce_title);
	elm.innerHTML = "<div id=\"popup_ta\"></div>";
	document.body.appendChild(elm);
	if (typeof(options['ta']) == 'undefined' ) {
		alert("textarea missing");
		return;
	}
	var ta = options['ta'];
	if (!options['form']) {
		var fld = "textarea[name="+options['field']+"]";
	} else {
		var fld = $(options['form']).find("textarea[name="+options['field']+"]");
	}
	var tp = typeof(options['tp']) != 'undefined' ? options['tp'] : tiny_extra_options();
	//var ed = tinyMCE.get(ta);
	if (typeof(options['resizable']) != 'undefined' && options['resizable']) {
		tp['theme_advanced_resizing'] = true;
	} else {
		tp['theme_advanced_resizing'] = false;
	}
	tp['elements'] = ta;
	
	$("#popup_ta").append('<div id="dv' + ta + '"><form name="ta' + ta + 'form" onSubmit="return false;"><textarea id="' + ta + '" name="' + ta + '" style="width:500px;height:290px;"></textarea></form></div>');
	_tm = {};
	_tm[ta] = 0;
	init_tinymce(_tm,tp);
	
	var buttons = {};
	buttons[langstrings[rx_lang].cancel] = function() { $( this ).dialog( "close" ); };
	buttons[langstrings[rx_lang].ok] = function() {
		var v = $("#"+ta).val();
		if (tinyMCE.get(ta)) {
			v = tinyMCE.get(ta).getContent();
		}
		$(fld).val(rx_base64_encode(v));
		$( this ).dialog( "close" );
	};
	var dialog_options = {
		closeOnEscape: true,
		resizable: false,
		autoOpen: true,
		modal : true,
		width : (typeof(options['width']) != 'undefined' ? options['width'] : 650),
		height : (typeof(options['height']) != 'undefined' ? options['height'] : 438),
		buttons : buttons,
		open: function() {
			v = rx_base64_decode($(fld).val());
			$("#"+ta).val(v);
			showWysiwyg(ta);
		},
		beforeClose: function() {
			removeWysiwyg(ta);
		}
	};

	dialog_options = $.extend(dialog_options, options);
	$elm.dialog(dialog_options);

	// Bind default events to the dialog
	$elm.bind('dialogclose', function(event, ui) {
		$(this).dialog('destroy');
		document.body.removeChild(elm);
	});

	// Handige returndata trigger
	if(typeof(options['returnData']) != 'undefined') $elm.bind('returnData', options['returnData']);

	return elm;
}

// Create a dialog from a uniquely created div-element and set some default properties.
function rx_sticky_dialog(options) {
	
	var elm = document.createElement("div");
	var $elm = $(elm);
	elm.id = $elm.guid();
	elm.setAttribute("title", typeof(options['title']) != 'undefined' ? options['title'] : langstrings[rx_lang].tinymce_title);
	elm.innerHTML = "<div id=\"rxsticky_tinymce\"></div>";
	document.body.appendChild(elm);

	var tp = options['tp'];

	if (typeof(options['resizable']) != 'undefined' && options['resizable']) {
		tp['theme_advanced_resizing'] = true;
	} else {
		tp['theme_advanced_resizing'] = false;
	}
	tp['elements'] = 'rxsticky';
	tp['plugins'] += ',rxtemplate';
	tp["theme_advanced_buttons3"] += ",rxtemplate";
	tp["rxtemplate_url"] = "/admin/sticky/get_templates/";
    $("#rxsticky_tinymce").append('<div id="dv_rxsticky"><form name="ta_rxstickyform" onSubmit="return false;"><input type="hidden" id="rxsticky_tmpl" name="rxsticky_tmpl" value=""><textarea id="rxsticky" name="rxsticky" style="width:500px;height:290px;"></textarea></div>');
	_tm = {};
	_tm['rxsticky'] = 0;
	init_tinymce(_tm,tp);

	var buttons = {};
	buttons[langstrings[rx_lang].cancel] = function() { $( this ).dialog( "close" ); };
	buttons[langstrings[rx_lang].ok] = function() {
		var v = '';
		if (tinyMCE.get('rxsticky')) {
			v = tinyMCE.get('rxsticky').getContent();
		}
		var tmpl = $("#rxsticky_tmpl").val();
		
		$(this).trigger("returnData",[v,tmpl]);
	};
	var dialog_options = {
		closeOnEscape: true,
		resizable: false,
		autoOpen: true,
		modal : true,
		width : (typeof(options['width']) != 'undefined' ? options['width'] : 625),
		height : (typeof(options['height']) != 'undefined' ? options['height'] : 405),
		buttons : buttons,
		open: function() {
			$("#rxsticky").val(options['textblock']);
			$("#rxsticky_tmpl").val(options['template']);
			showWysiwyg('rxsticky');
		},
		beforeClose: function() {
			removeWysiwyg('rxsticky');
		}
	};

	dialog_options = $.extend(dialog_options, options);
	$elm.dialog(dialog_options);
	
	if(typeof(options['returnData']) != 'undefined') $elm.bind('returnData', options['returnData']);
	
	// Bind default events to the dialog
	$elm.bind('dialogclose', function(event, ui) {
		$(this).dialog('destroy');
		document.body.removeChild(elm);
	}).dialog('open');

}

// Create this object in an iframe (created by rx_frame_dialog) to get some object references to the parent-window,iframe-element and jquery-dialog-element
function rx_frame_object() {
	var dlg = window;
	var ok,i = 0;
	while (!ok && i++ < 10) {
		if (dlg.frameElement && dlg.frameElement.dialog_window) {
			dlg = dlg.frameElement;
			ok = 1;
		} else {
			if (dlg.parent) {
				dlg = dlg.parent
			} else { 
				ok = 1;
				break;
			}
		}
	}
	this.iframe = typeof(window.frameElement) != 'undefined' ? window.frameElement : null;
	this.dialog = dlg.dialog_window ? dlg.dialog_window : null;
	this.parentDocument = typeof(parent.document) != 'undefined' ? parent.document : null;
	this.parent = typeof(parent) != 'undefined' ? parent : null;
	this.parentWindow = typeof(parent.document) != 'undefined' ? parent.document : null; // Liever niet gebruiken, want verwarrend. Gebruik parentDocument.
	this.exists=function() { return this.dialog!=null; }
	return this;
}


// This function needs jQuery to be loaded. See example dialog in Module Gallery (oldadmin/custom.tpl)
function rx_upload_dialog(config, refelem) {
	if(rx_lang && plupload_language[rx_lang]) plupload.addI18n(plupload_language[rx_lang]);
	var tmp_conf = $.extend({ filters: plupload_filters }, plupload_config, config.plupload);
	if (tmp_conf.upload_dir) tmp_conf.url += ( tmp_conf.url.indexOf('?')>-1 ? '&' : '?' ) + 'dir=' + tmp_conf.upload_dir;
	if (tmp_conf.cleanotherfiles) tmp_conf.url += ( tmp_conf.url.indexOf('?')>-1 ? '&' : '?' ) + 'cleanotherfiles=1';

	if(document.getElementById("upload_dialog") != null) {
		$("#upload_dialog").dialog('destroy');
		document.body.removeChild(document.getElementById("upload_dialog"));
	}

	CreateDom();
	OpenNewUploadDialog();

	function CreateDom() {
		var upload_dialog = document.createElement("div");
		var batchupload = document.createElement("div");

		upload_dialog.id = 'upload_dialog';
		upload_dialog.style.cssText = "padding:0px !important; overflow: hidden !important; position:relative; height:0px; width:0px;";

		batchupload.id = 'batchupload';
		batchupload.style.cssText = 'width: 600px; height: 300px;';

		upload_dialog.appendChild(batchupload);
		document.body.appendChild(upload_dialog);
	}

	function OpenNewUploadDialog() {
		var dialog = $("#upload_dialog").dialog({
			title : plupload.translate('Upload files'),
			closeOnEscape: true,
			resizable: false,
			width : 600,
			height : 285,
			modal: true,
			autoOpen: false,
			open : function(event, ui) {$("#batchupload").pluploadQueue().refresh();},
			dragStop : function(event, ui) {$("#batchupload").pluploadQueue().refresh();}
		});
		if ( typeof(config.returnData)!='undefined' ) {
			dialog.bind('returnData', config.returnData);
		}					

		$("#batchupload").pluploadQueue(tmp_conf);

		if(typeof(config['plupload']['bind']) != 'undefined') {
			for (bindname in config['plupload']['bind']) {
				$("#batchupload").pluploadQueue().bind(bindname, config['plupload']['bind'][bindname]);
			}
		}
		if ( tmp_conf.singlefile ) {
			$("#batchupload").pluploadQueue().bind("FilesAdded" , function(up, files) {
				i=0;
				while( up.files.length >1 && i<up.files.length) {
					if (up.files[i]!=files[0]) up.removeFile(up.files[i]);
					else i++;
				}
			});
		}
		
		$("#batchupload").pluploadQueue().bind("UploadProgress" , function(up, file) {
			if (up.total.queued == 0 && up.total.percent == 100) {
				if(!up.uploaded_all) {
					up.uploaded_all = true;
					setTimeout(function() {
						up.refelem = refelem;
						up.dialog = dialog;
						up.trigger("UploadFinished", [ up ]);
						dialog.trigger('returnData',[ up ] );
						if ( config.closeOnFinish ) {
							dialog.dialog('close');
						}
					}, 500);
				}
			} else {
				up.uploaded_all = false;
			}
		});

		setTimeout(function() {dialog.dialog('open')}, 500);
	}
	return $("#upload_dialog")[0];
}





// Jquery Extension

// contentchange event
(function() {

	var interval;
	jQuery.event.special.contentchange = {
		setup: function(){
			var self = this,
			$this = $(this),
			$originalContent = $this.html();
			interval = setInterval(function(){
				if($originalContent != $this.html()) {
					$originalContent = $this.html();
					jQuery.event.handle.call(self, {type:'contentchange'});
				}
			},1000);
		},
		teardown: function(){
			clearInterval(interval);
		}
	};
})();

(function($) {

	$.fn.rxRenderImage = function(options, replace_on_fail) {
		$(this).each(function() {
			var elm = $(this);
			if(elm.attr('render-image')) {
				$.ajax({
					url : rgdroot+'/jqajax',
					async: true,
					type: 'POST',
					dataType : 'json',
					data : { jqajax: 'template#render_image', xajaxargs: {  'src' : elm.attr('render-image'), 'params' : options } },
					success : function (r) {
						if(r.status || replace_on_fail) {
							elm.attr('src', r.src);
							elm.trigger('rxRenderImageComplete', [elm.attr('render-image'), r.src]);
						}
					}
				});
			}
		});
		return $(this);
	};

	$.fn.loadScriptFile = function(filename) {
       		if(jQuery.browser.safari ) {
       			jQuery.ajax({
				url : filename,
				dataType : 'script',
				async : false,
				cache : true
			});

       		} else if (jQuery.browser.msie) {
			document.write('<script type="text/javascript" src="'+filename+'"></script>');

		} else {
			var oHead = document.getElementsByTagName('head')[0];
			var oScript = document.createElement('script');
			oScript.type = 'text/javascript';
			oScript.charset = 'utf-8';
			oScript.src = filename;
			oHead.appendChild(oScript);
		}
	};

	$.fn.guid = function() {
		var rx_guid = new Date().getTime().toString(32), i;
		for (i = 0; i < 5; i++) rx_guid += Math.floor(Math.random() * 65535).toString(32);
		return rx_guid;
	};

	$.fn.RX_MakeIntFromCSS = function(value) {
		if (value && value.indexOf("px") > -1) return parseInt(value);
		return 0;
	};

	$.fn.RX_elementRegion = function() {

		// @todo : Scrollbars are not calculated, always return 0

		var obj = this;
		var elm = $(obj.get(0));

		var result = {
			real :       {width : 0, height : 0},
			overhead :   {width : 0, height : 0},
			scrollbars : {width : 0, height : 0},
			padding :    {left :  0, right : 0, top: 0, bottom : 0, width : 0, height : 0},
			margin :     {left :  0, right : 0, top: 0, bottom : 0, width : 0, height : 0},
			border :     {left :  0, right : 0, top: 0, bottom : 0, width : 0, height : 0}
		};

		// Get the padding
		result.padding.left = elm.RX_MakeIntFromCSS(elm.css("paddingLeft"));
		result.padding.right = elm.RX_MakeIntFromCSS(elm.css("paddingRight"));
		result.padding.top = elm.RX_MakeIntFromCSS(elm.css("paddingTop"));
		result.padding.bottom = elm.RX_MakeIntFromCSS(elm.css("paddingBottom"));
		result.padding.width = result.padding.left + result.padding.right;
		result.padding.height = result.padding.top + result.padding.bottom;

		// Get the margin
		result.margin.left = elm.RX_MakeIntFromCSS(elm.css("marginLeft"));
		result.margin.right = elm.RX_MakeIntFromCSS(elm.css("marginRight"));
		result.margin.top = elm.RX_MakeIntFromCSS(elm.css("marginTop"));
		result.margin.bottom = elm.RX_MakeIntFromCSS(elm.css("marginBottom"));
		result.margin.width = result.margin.left + result.margin.right;
		result.margin.height = result.margin.top + result.margin.bottom;

		// Get the margin
		result.border.left = elm.RX_MakeIntFromCSS(elm.css("borderLeftWidth"));
		result.border.right = elm.RX_MakeIntFromCSS(elm.css("borderRightWidth"));
		result.border.top = elm.RX_MakeIntFromCSS(elm.css("borderTopWidth"));
		result.border.bottom = elm.RX_MakeIntFromCSS(elm.css("borderBottomWidth"));
		result.border.width = result.border.left + result.border.right;
		result.border.height = result.border.top + result.border.bottom;

		result.overhead.width  = result.padding.width  + result.margin.width  + result.border.width  + result.scrollbars.width;
		result.overhead.height = result.padding.height + result.margin.height + result.border.height + result.scrollbars.height;

		// clientWidth - Returns the width of the visible area for an object, in pixels. The value contains the width with the padding, but does not include the scrollBar, border, and the margin.
		// See: http://help.dottoro.com/ljmclkbi.php
		result.real.width  = obj.get(0).clientWidth - result.padding.width;

		// clientHeight - Returns the height of the visible area for an object, in pixels. The value contains the height with the padding, but does not include the scrollBar, border, and the margin.
		// See: http://help.dottoro.com/ljcadejj.php
		result.real.height = obj.get(0).clientHeight - result.padding.height;

		return result;
	};

	$.fn.RX_iframeDocument = function() {
		var doc = null;
		var elm = this.get(0);
		if (elm.contentDocument) { //ns6+ & opera syntax
			doc = elm.contentDocument;
		} else if (elm.contentWindow && elm.contentWindow.document) {
 			doc = elm.contentWindow.document;
 		} else if (elm.document) { //ie5+ syntax
 			doc = elm.document;
 		}
		return doc;
	};


	$.fn.RX_contentRegion = function() {

		var result = {
			width : 0,
			height : 0
		};

		var elm = this.get(0);

		if(elm.tagName == 'IFRAME') {
			try {
				var doc = $(this).RX_iframeDocument();
				result.width = $(doc).width();
				result.height = $(doc).height();
			} catch(e) {}

		// We are dealing with a normal element
		} else {
			result.width = elm.offsetWidth;
			result.height = elm.offsetHeight;
		}

		return result;
	};

	$.fn.RX_resizeToContent = function(options) {

		var defaults = {
			width : 0,
			height : 0,
			minWidth : 300,
			minHeight : 0,
			maxWidth : $(window).width() - 60,
			maxHeight : $(window).height() - (options.buttons ? 150 : 60 )
		};

		options = $.extend(defaults, options);

		return this.each(function() {

			var obj = $(this);
			var elm = obj.get(0);
			var resized = false;

			if(typeof(elm.RX_resizeToContent_vars) == 'undefined') {
				elm.RX_resizeToContent_vars = $.extend(defaults, options);
			} else {
				elm.RX_resizeToContent_vars = $.extend(elm.RX_resizeToContent_vars, options);
			}
			options = elm.RX_resizeToContent_vars;

			// for msie7 eerst element_region en daarna content_region - timings issue
			var element_region = obj.RX_elementRegion();
			var content_region = obj.RX_contentRegion();

			if(!options.width) {
				if(content_region.width > element_region.real.width) {
					elm.style.width = ((!options.maxWidth || content_region.width < options.maxWidth) ? content_region.width : options.maxWidth) + 'px';
					if(content_region.width < options.maxWidth) {
						// Is volgens Frank en Paul niet meer nodig anno (14 okt 2011 rond 12:00)
						//if(typeof(elm.style.overflowX) != 'undefined') elm.style.overflowX = 'hidden';
					}
					resized = true;
				}
			} else {
				if(options.width != element_region.width) {
					elm.style.width = options.width + 'px';
					resized = true;
				}
			}

			if(!options.height) {
				if(isWebkit || content_region.height > element_region.real.height) {
					elm.style.height = ((!options.maxHeight || content_region.height < options.maxHeight) ? content_region.height : options.maxHeight) + 'px';
					resized = true;
				}
			} else {
				if(options.height != element_region.height) {
					elm.style.height = options.height + 'px';
					resized = true;
				}
			}

			// If we had a resize, retrieve the new element region
			if(resized) {

				// Check for extra scrollbars that are not needed
				if(parseInt(elm.style.width) < content_region.width && !elm.RX_resizeToContent_vars.heightScrollFix) {
					if(parseInt(elm.style.height) >= content_region.height && parseInt(elm.style.height) < content_region.height + 20) {
						elm.style.height = parseInt(elm.style.height) + 20 + 'px';
						elm.RX_resizeToContent_vars.heightScrollFix = true;
					}
				}

				// Check vertical scrollbars
				if(parseInt(elm.style.height) < content_region.height && !elm.RX_resizeToContent_vars.widthScrollFix) {
					if(parseInt(elm.style.width) >= content_region.width && parseInt(elm.style.width) < content_region.width + 20) {
						elm.style.width = parseInt(elm.style.width) + 20 + 'px';
						elm.RX_resizeToContent_vars.widthScrollFix = true;
					}
				}

				element_region = obj.RX_elementRegion();
			}

			// Check if we have to increase the new region to meet the minWidth and minHeight
			if(options.minWidth && options.minWidth > element_region.real.width) {
				elm.style.width = options.minWidth + 'px';
				resized = true;
			}
			if(options.minHeight && options.minHeight > element_region.real.height) {
				elm.style.height = options.minHeight + 'px';
				resized = true;
			}

			if(resized) obj.trigger("OnResize");

		});

	};

})(jQuery);

