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.options['returnData'](null,data);
			} else if (this.options['popupOnElem'] && typeof(data) != "object" && typeof(data) != "undefined") {
				this.options['popupOnElem'].value = data;
			}
			this.uiDialog.triggerHandler('returnData',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");
	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')
	};

	dialog_options = $.extend(dialog_options, options);
	$("#" + elm.id).dialog(dialog_options);

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

		$("#" + elm.id).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.id).bind('dialogclose', function(event, ui) {
		$(elm).html('');
		$(this).dialog('destroy');
		document.body.removeChild(elm);
	});

	// Handige returndata trigger
	if(typeof(options['returnData']) != 'undefined') {
		$("#" + elm.id).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
	));
	$("#" + alert_div.id).dialog('open');
	return $("#" + alert_div.id);
}

// 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.id).bind('OnConfirm', options['OnConfirm']);
	if(typeof(options['OnCancel']) != 'undefined')  $("#" + alert_div.id).bind('OnCancel',  options['OnCancel']);
	$("#" + alert_div.id).dialog('open');
	return $("#" + alert_div.id);
}

//  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 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() {$(page_container).RX_resizeToContent();$(page_container).trigger("OnResize");}, 200);});

	$(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.id);
	$("#" + frame_div.id).dialog('open');

	return $("#" + frame_div.id);
}

// Create a dialog from a uniquely created div-element and set some default properties.
function rx_tinymce_dialog(options) {
	
	var elm = document.createElement("div");
	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;
	}
	if (!options['form']) {
		var fld = "textarea[name="+options['field']+"]";
	} else {
		var fld = $(options['form']).find("textarea[name="+options['field']+"]");
	}
	var ta = typeof(options['ta']) != 'undefined' ? options['ta'] : ta;
	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.id).dialog(dialog_options);

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

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

	return elm;
}

// 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();}
		});

		$("#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);
					}, 500);
				}
			} else {
				up.uploaded_all = false;
			}
		});

		setTimeout(function() {dialog.dialog('open')}, 500);
	}

}





// Jquery Extension

(function($) {

	$.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.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 : 0,
			minHeight : 0,
			maxWidth : 0,
			maxHeight : 0
		};

		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') {
				if(!options.maxWidth) options.maxWidth = $(window).width() - 70;
				if(!options.maxHeight) options.maxHeight = $(window).height() - 70;
				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) {
						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';
					/* Dit gaat fout als je met kleine content start en on the fly de content vergroot. Dan moet er een scrollbar komen...
					if(content_region.height <= options.maxHeight) {
						if(typeof(elm.style.overflowY) != 'undefined') obj.get(0).style.overflowY = 'hidden';
					}
					*/
					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) 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);

