Array.indexOf = function(arr, obj)
  {
    for(var i=0; i<arr.length; i++)
    {
       if(arr[i]==obj) return i;
    }
	
    return -1;

  };

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

//var jquerydia = false;
jQuery.extend(jQuery.expr[':'], {
    focus: function(element) { 
        return element == document.activeElement; 
    }
});

(function($){
	$.fn.isSelectable = function()
	{
		return true;
		//return this.attr("unselectable") == "on" || this.css("MozUserSelect") == "none";
	};
})( jQuery );


$(document).ready(function(){
	ui.init();
});

jQuery.atsc = {
	debug: function(txt)
	{
		if(typeof(console) != "undefined" && typeof(console.log) != "undefined")
		{
			console.log(txt);
		}
	},
	xml: {
		processXMLMessage: function(xmlDoc)
		{
			var error												= $(xmlDoc).find("error").text();
			if (error == "")										{ error = $(xmlDoc).find("error").attr("msg"); }
			if (error != "")
			{
				setTimeout(function(){ alert(error); }, 0);
				return false;
			}
			
			var msg													= $(xmlDoc).find("msg").text();
			if (msg == "")											{ msg = $(xmlDoc).find("msg").attr("msg"); }
			if (msg != "")
			{
				alert(msg);
			}
			
			try														{ processFilesInXMLMessage(xmlDoc); }
			catch (ex)												{}
			
			var url													= $(xmlDoc).find("url").text();
			if (url != "")
			{
				showPreviousFrame(false, url); // <- dit is nog niet getest! -JB
				return false;
			}
			
			return true;
		},
		xmlToString: function(xmlDoc)
		{
			xmlDoc													= $(xmlDoc)[0];
			var xmlstr												= xmlDoc.xml ? xmlDoc.xml : (new XMLSerializer()).serializeToString(xmlDoc);
			return xmlstr;
		}
	},
	string: {
		validateRegex: function(pattern, test)
		{
			if (typeof(pattern) == "string")						{ pattern = new RegExp(pattern, "ig"); }
			var matches												= pattern.exec(test);
			return (matches && matches.length > 0 && matches[0] == test);
		},
		toChar: function(charCode, shiftKey, raltKey)
		{
			var c = charCode;
			
			if(c == 110){ return "."; } //Numpad .
			if(raltKey && c == 53)
			{
				return "\u20AC";
			}
			
			if(shiftKey)
			{
				switch(c)
				{
					case 49:
						return "!";
						break;
					case 50:
						return "@";
						break;
					case 51:
						return "#";
						break;
					case 52:
						return "$";
						break;
					case 53:
						return "%";
						break;
					case 54:
						return "^";
						break;
					case 55:
						return "&";
						break;
					case 56:
						return "*";
						break;
					case 57:
						return "(";
						break;
					case 48:
						return ")";
						break;
					
					case 190:
						return ">";
						break;
					case 186:
						return ":";
						break;
					case 188:
						return "<";
						break;
					case 191:
						return "?";
						break;
					case 192:
						return "~";
						break;
					case 219:
						return "{";
						break;
					case 220:
						return "|";
						break;
					case 221:
						return "}";
						break;
					case 222:
						return "\"";
						break;
				}
			}
			else
			{
				switch(c)
				{
					case 190:
						return ".";
						break;
					case 186:
						return ";";
						break;
					case 188:
						return ",";
						break;
					case 191:
						return "/";
						break;
					case 192:
						return "`";
						break;
					case 219:
						return "[";
						break;
					case 220:
						return "\\";
						break;
					case 221:
						return "]";
						break;
					case 222:
						return "'";
						break;
				}
			}
			
			//Numpad 0 - 9
			if(c >= 96 && c <= 105){ c -= 48; }
			
			//Out of bounds; don't return anything.
			if(c < 48 || c > 90){ return ""; }
			
			return String.fromCharCode(c);
		}
	},
	
	window: {
		getWindowFromFrame: function(elem)
		{
			try
			{
				var iframe											= window.frames[$(elem).attr("name")];
				
				if(!iframe)											{ return null; }
				if(typeof(iframe.window) != "undefined")			{ return iframe.window; }			//at least in IE9
				if(typeof(iframe.contentWindow) != "undefined")		{ return iframe.contentWindow; }	//other browsers
			}
			catch(e)												{ $.atsc.debug(e.message); }
			return null;
		},
		
		getWindowFromIFrame: function(elem)
		{
			try
			{
				var iframe											= window.frames[$(elem).attr("name")];
				
				if(!iframe)											{ return null; }
				if(typeof(iframe.window) != "undefined")			{ return iframe.window; }			//at least in IE9
				if(typeof(iframe.contentWindow) != "undefined")		{ return iframe.contentWindow; }	//other browsers
			}
			catch(e)												{ $.atsc.debug(e.message); }
			return null;
		},
		
		getIFrameFromWindow: function(wnd)
		{
			var iframe												= null;
			$("iframe").each(function(){
				if($.atsc.window.getWindowFromIFrame(this) == wnd)
				{
					iframe											= $(this);
					return false;
				}
			});
			
			return iframe;
		},
		
		/**
		 * @desc Gets the width & height for the current window.
		 * @return dictionary A dictionary containing "width" and "height" parameters.
		 */
		getDimensions: function(){
			var dimensions = {width: 0, height: 0};
			if(document.documentElement)
			{
				dimensions.width = document.documentElement.offsetWidth;
				dimensions.height = document.documentElement.offsetHeight;
			}
			else
			{
				dimensions.width = window.innerWidth;
				dimensions.height = window.innerHeight;
			}
			return dimensions;
		}/*,
		showModal: function()
		{
			var curDoc = getFrame(getCurrentFrameName()).document;
			var elem = $("#_modal_bg_div_", curDoc);
			if(!elem.length)
			{
				elem = $("<div id=\"_modal_bg_div_\" style=\"position: fixed; left: 0px; top: 0px; right: 0px; bottom: 0px; background-color: #CCC;\"></div>");
				elem.keydown(function(){ return false; });
				elem.keyup(function(){ return false; });
				elem.keypress(function(){ return false; });
				$("body", curDoc).append(elem);
			}
			
			elem.show();
			elem.focus();
		},
		hideModal: function()
		{
			var curDoc = getFrame(getCurrentFrameName()).document;
			var elem = $("#_modal_bg_div_", curDoc);
			if(elem.length)
			{
				elem.hide();
				$("body", curDoc).focus();
			}
		}
		*/
	},
	
	event: {
		/**
		 * @desc Prevents the default action from being executed in an event.
		 * @param jQuery.Event e
		 */
		preventDefault: function(e, stopPropagation){
			if(typeof(e.originalEvent) != "undefined")
			{
				e.preventDefault();
				if(IE)	{ try { e.originalEvent.keyCode = 0; } catch(ex){} }
				
				if(stopPropagation)
				{
					e.stopPropagation();
				}
			}
			else
			{
				if(IE)
				{
					try { e.keyCode = 0; } catch(ex){}
					if(stopPropagation)	{ e.cancelBubble = true; }
				}
				
				try					{ e.preventDefault(); } catch(ex){}
				if(stopPropagation)	{ try { e.stopPropagation(); } catch(ex){} }
				
			}
		},
		
		isNavigationKey: function(which, ctrlKey, altKey, shiftKey)
		{
			if(typeof(which) == "object")
			{
				ctrlKey = which.ctrlKey;
				altKey = which.altKey;
				shiftKey = which.shiftKey;
				which = which.which;
			}
			
			//PgUp/PgDn + Home/End + Arrow Keys
			if(which >= 33 && which <= 40)
			{
				return true;
			}
			
			//WinKey + ContextMenu
			if(which >= 91 && which <= 93)
			{
				return true;
			}
			
			//          Shift            Ctrl           Alt            CapsLock       Numlock
			if(which == 16 || which == 17 || which == 18 || which == 20 || which == 144)
			{
				return true;
			}
			
			//          VolDown         VolUp           ScrollLock      Pause
			if(which == 174 || which == 175 || which == 145 || which == 19)
			{
				return true;
			}
			
			//Escape Key
			if(which == 27)
			{
				return true;
			}
			
			//Ctrl      +          C
			if(ctrlKey && which == 67)
			{
				return true;
			}
			
			return false;
		},
		
		isLeftAlt: function(e)
		{
			if($.browser.msie) //Trident
			{
				return (e.originalEvent ? e.originalEvent.altLeft : e.altLeft);
			}
			else if($.browser.mozilla || $.browser.webkit) //Gecko
			{
				//Hacky workaround:
				return e.altKey && !e.ctrlKey;
				
				/*
				 * There is a bug in WebKit
				 * (at least in Google Chrome
				 * v13.0.782.112 m) and in Mozilla
				 * (at least in v 3.6.18) that causes
				 * the ctrlKey property to always
				 * be set to "true" if the right
				 * alt key is pressed, even when
				 * the Ctrl key is not being pressed.
				 */
			}
			else if($.browser.opera) //Presto; unsupported
			{
				/*
				for(var i in e.originalEvent)
				{
					alert(i + " = " + e.originalEvent[i]);
				}
				*/
				return true;
			}
		}
	},
	
	dialog: {
		dialogIdCounter: 0,
		dialogExists: 0,
		
		/**
		 * @desc Hides all currently opened dialog windows.
		 */
		closeAll: function(){
			for(var i = 0; i < $.atsc.dialog.dialogIdCounter; i++)
			{
				$("#dialog_" + i).dialog("close");
			}
		},
		
		/**
		 * @desc Completely destroys all existing dialog windows.
		 */
		destroyAll: function(){
			for(var i = 0; i < dialogIdCounter; i++)
			{
				var dialog = $("#dialog_" + id);
				dialog.dialog("close");
				dialog.remove();
			}
		},
		
		exists: function(){ return jQuery.atsc.dialog.dialogExists > 0; },
		
		focus: function(id){
			if(!id)
			{
				id = $.atsc.dialog.dialogIdCounter - 1;
			}
			
			var dialog = $("#dialog_" + id);
			var func = dialog.dialog("option", "setFocus");
			if(typeof func == "function")
			{
				func.call(dialog);
			}
		},
		
		focusButton: function(id){
			var dialog = $("#dialog_" + id);
			var currentButtonId = dialog.dialog("option", "focusButton");
			var lstButtons = $("#dialog_" + id + "_parent" + " > .ui-dialog-buttonpane .ui-button");
			
			if(lstButtons.length > 0 && currentButtonId >= 0 && currentButtonId <= lstButtons.length)
			{
				var button = $(lstButtons[currentButtonId]);
				button.focus();
			}
			else
			{
				dialog.focus();
			}
		},
		
		/**
		 * @desc Creates a regular dialog window.
		 * For creating a modal dialog window, see makeModalDialog
		 * @param dictionary options A list of options to use.
		 * @return dialog The dialog element that belongs to this window.
		 */
		make: function(options)
		{
			var targetWindow = ui.window.getFrame(getCurrentFrameName());
			if(typeof(targetWindow) != "undefined" && window != targetWindow)
			{
				return targetWindow.jQuery.atsc.dialog.make(options);
			}
			
			//If a dialog window needs to be displayed directly after switching to a different frame,
			//we need to wait a moment because otherwise the dialog window will be invisible.
			//In addition this check does not need to occur when we're using UITable frame
			//in lookup mode (in a record), otherwise functionality such as Ctrl+O in UITable fails.
			if((typeof(ui.table) == "undefined" || !ui.table.lookup_mode) && (wt.focusCurrentFrameDone == false && document != wt.document))
			{
				setTimeout(function(){$.atsc.dialog.make(options);}, 100);
				return;
			}
			
			//Generate a new dialog ID
			var id = $.atsc.dialog.dialogIdCounter++;
			var dialogId = "dialog_" + id;
			
			//The default settings are specified here.
			//All of the settings from the jQuery UI Dialog function are supported.
			var settings = {
				width: 600,
				minHeight: 275,
				setFocus: function(){
					$.atsc.dialog.focusButton(id);
				},
				
				onKeyDown: null,
				
				autoOpen: true,
				modal: false,
				closeOnEscape: true,
				draggable: true,
				resizable: true,
				
				//Special case: If set to true, destroys the parent dialog element upon close.
				destroyOnClose: true,
				
				//Special case: If set to false, the "x" in the corner is removed.
				closable: true,
				
				//Special case: If set to true, the text in the center can be selected.
				selectable: true,
				
				title: "Venster",
				buttons: [
					{
						text: "OK",
						click: function(){
							$(this).dialog("close");
						}
					}
				],
				
				//Special case: This should be set to the ID of the default button.
				//(Use the above array, index starting at 0.)
				//Set to -1 to disable. This will cause the Enter key to no longer respond to input.
				defaultButton: 0,
				
				html: "<p>Welkom bij dit venster. De inhoud kan nu worden gevuld door de \"html\" parameter in te vullen.</p><p>Veel succes!</p>"
			};
			
			//If the user has specified any options, let them override the settings.
			if(options)
			{
				$.fn.extend(settings, options);
			}
			
			//This is so that the programmer can retrieve the ID later on.
			settings["dialogId"] = id;
			
			//Make sure the focus is on the default button.
			settings["focusButton"] = settings["defaultButton"];
			
			//This must always be set to false (but remember if it was true).
			var autoOpen = settings["autoOpen"];
			settings["autoOpen"] = false;
			
			//Store the functions for open/close because we'll override them later.
			var funcOpen = settings["open"];
			var funcClose = settings["close"];
			
			//Create the dialog element and apply the settings above.
			var dialogElem = $("<div id=\"" + dialogId + "\"></div>").insertAfter("body");
			dialogElem.css("overflow", "auto");
			dialogElem.dialog(settings);
			
			//Store the HTML from the settings in the dialog window.
			dialogElem.html(settings["html"]);
			
			//Get the element generated by the jQuery UI extension.
			var dialogGenElem = dialogElem.parent();
			$(dialogGenElem).attr("id", dialogId + "_parent");
			
			/** Hotkeys */
			var lstHotkeys = new Array();
			
			//Pass 1: Add every existing hotkey to the above list.
			$(".ui-dialog-buttonpane .ui-button", dialogGenElem).each(function(index){
				//If this button already has a hotkey, add it to the list.
				if(settings["buttons"][index].hotkey)
				{
					lstHotkeys.push(settings["buttons"][index].hotkey);
				}
			});
			
			//Pass 2: Generate new hotkeys for those that don't have any.
			//This also adds the hotkeyPos variable to the button.
			$(".ui-dialog-buttonpane .ui-button", dialogGenElem).each(function(index){
				var hotkey = settings["buttons"][index].hotkey;
				var text = $(this).text();
				
				//No hotkey was specified, so let's generate it.
				if(!hotkey)
				{
					var pos = 0;
					while(pos != null && pos < text.length)
					{
						hotkey = text.substring(pos, pos + 1);
						
						//A space is not a valid hotkey.
						if(hotkey == " ")
						{
							hotkey = null;
							pos++;
							continue;
						}
						
						//Make sure the same key isn't used twice!
						var i = null;
						for(i = 0; i < lstHotkeys.length; i++)
						{
							if(lstHotkeys[i].toLowerCase() == hotkey.toLowerCase())
							{
								break;
							}
						}
						
						if(i >= 0 && i < lstHotkeys.length)
						{
							//The key is being used, so continue.
							hotkey = null; //this is required so it will be null if no valid key is found
							pos++;
							continue;
						}
						else
						{
							//The key isn't in use, so let's mark it and break out of the while loop.
							lstHotkeys.push(hotkey);
							break;
						}
					}
				}
				
				//We have a valid hotkey, so let's use it.
				if(hotkey)
				{
					settings["buttons"][index].hotkeyPos = text.indexOf(hotkey);
					if(settings["buttons"][index].hotkeyPos >= 0)
					{
						hotkey = hotkey.toUpperCase();
						settings["buttons"][index].hotkey = hotkey;
					}
					else
					{
						settings["buttons"][index].hotkey = null;
						settings["buttons"][index].hotkeyPos = null;
					}
				}
			});
			
			/** Opening/Closing */
			
			//Override the "open" function with our own implementation.
			settings["open"] = function(event, ui){
				$.atsc.dialog.dialogExists++;
				
				//If this window can't be closed, hide the X in the corner
				$("#" + $(this).attr("id") + "_parent .ui-dialog-titlebar-close").toggle($(this).dialog("option", "closable"));
				
				//If you click outside of the dialog window, set the focus to the current button
				$(".ui-widget-overlay").click(function(){
					$.atsc.dialog.focusButton(id);
				});
				
				$("#" + dialogId).dialog("isDocumentSelectable", $(document).isSelectable());
				//alert("BEFORE: " + $(document).isSelectable());
				
				//If this dialog window is selectable, enable selection for the "html" bit only.
				if($(this).dialog("option", "selectable"))
				{
					$(document).enableSelection();
					$("#" + dialogId + "_parent .ui-dialog-titlebar").disableSelection();
					$("#" + dialogId + "_parent .ui-dialog-buttonpane").disableSelection();
				}
				else
				{
					$(document).disableSelection();
				}
				
				//alert("AFTER: " + $(document).isSelectable());
				
				if(funcOpen){ funcOpen(event, ui); }
				$.atsc.dialog.focus(id);
			};
			
			//Override the "close" function with our own implementation.
			settings["close"] = function(event, ui){
				$.atsc.dialog.dialogExists--;
				
				if($("#" + dialogId).dialog("isDocumentSelectable"))
				{
					$(document).enableSelection();
				}
				else
				{
					$(document).disableSelection();
				}
				
				if(typeof(specificDialogClose) == "function"){ specificDialogClose(event, ui); }
				if(funcClose){ funcClose(event, ui); }
				
				//If the destroyOnClose parameter is used, remove the entire dialog element.
				if($("#" + dialogId).dialog("option", "destroyOnClose"))
				{
					$("#" + dialogId).remove();
				}
				
				focusCurrentFrame();
			};
			
			//Save the new settings in the dialog window.
			//This will regenerate the button divs.
			dialogElem.dialog(settings);
			
			//Pass 3: Perform misc. actions on the buttons and finish adding hotkeys.
			$("#" + dialogId + "_parent" + " > .ui-dialog-buttonpane .ui-button").each(function(index){
				//Each button gets its own ID.
				$(this).attr("id", dialogId + "_button_" + index);
				
				//When the focus is on this button, set the focusButton option accordingly.
				$(this).focus(function(){
					$("#" + dialogId).dialog("option", "focusButton", index);
				});
				
				//Finish up the hotkeys by adding an underscore (_).
				var hotkey = settings["buttons"][index].hotkey;
				var hotkeyPos = settings["buttons"][index].hotkeyPos;
				var text = $(this).text();
				
				if(hotkey)
				{
					var html = text.substring(0, hotkeyPos) + "<u>" + text.substring(hotkeyPos, hotkeyPos + 1) + "</u>" + text.substring(hotkeyPos + 1);
					$("#" + dialogId + "_button_" + index + " .ui-button-text").html(html);
				}
			});
			
			//Handles key presses for the dialog window.
			dialogGenElem.keydown(function(e){
				var keyDownFunc = $("#" + dialogId).dialog("option", "onKeyDown");
				if(typeof(keyDownFunc) == "function" && !keyDownFunc(e))
				{
					$.atsc.event.preventDefault(e, true);
					return false;
				}
				switch(e.which)
				{
					//The following keys are handled by the jQuery UI extension:
					case 27: //Escape: Closes the dialog window (if enabled)
						$.atsc.event.preventDefault(e, true);
						
						return;
						break;
					case 116:
						return;
						break;
				}
				
				// Get the currently selected item.
				var focusedElement											= $(":focus");
				if(!focusedElement.length)									{ focusedElement = null; }
				
				var tagName													= "";
				if(focusedElement != null)									{ tagName = focusedElement.get(0).tagName.toUpperCase(); }
				
				var lstButtons												= $("#" + dialogId).dialog("option", "buttons");
				var lstButtonElements										= $("#" + dialogId + "_parent" + " > .ui-dialog-buttonpane .ui-button");
				// If the item that currently has focus is NOT a button:
				if ((!focusedElement || !focusedElement.hasClass("modalbutton")) && (lstButtons.length <= 0 || lstButtonElements.index($(focusedElement)) == -1))
				{
					// And either the Enter is not being pressed or the item is not a <select> or <input> element.
					// (We want to allow users to use the Enter key to submit the dialog if they're in a select
					// or input element, but prevent any other action.)
					if (e.which != 13 || (tagName != "SELECT" && tagName != "INPUT"))
					{
						// And the Tab key is not being pressed (tab is always allowed).
						if (e.which != 9)
						{
							// Then perform the default action.
							//$.atsc.debug("Not found; aborting");
							return true;
						}
					}
					
					// Exception: If Ctrl+Tab or Ctrl+Shift+Tab is pressed,
					// the default action will be performed instead of continuing.
					// (The only remaining case where the Ctrl key will have no effect
					// would be if a button has focus.)
					if (e.which == 9 && e.ctrlKey)							{ return true; }
				}

				// Prevent the default action. At this point we are committing ourselves to carry out
				// dialog-related actions.
				$.atsc.event.preventDefault(e, true);
				
				switch (e.which)
				{
					// Press the current button (if any buttons exist)
					case 13: // Enter
						var currentButtonId = $("#" + dialogId).dialog("option", "focusButton");
						
						$.atsc.event.preventDefault(e, true);
						
						if(lstButtonElements.length > 0 && currentButtonId >= 0 && currentButtonId < lstButtonElements.length)
						{
							var button = $(lstButtonElements[currentButtonId]);
							button.click();
						}
						
						break;
					
					// This emulates the 'Tab' key (and Shift+Tab).
					// It's needed in order to be able to move through any elements within the dialog
					// as well as the button pane below it.
					case 9: // Tab
						var SELECTOR										= "input, select, textarea, button";
						
						var elements										= $(SELECTOR, $("#" + dialogId));
						elements											= $.merge(elements, lstButtonElements);
						var focusedIndex									= elements.index($(focusedElement));
						var newIndex										= focusedIndex + (e.shiftKey ? -1 : 1);
						
						if (newIndex >= elements.length)					{ newIndex = 0; }
						else if (newIndex < 0)								{ newIndex = elements.length - 1; }
						
						$(focusedElement).blur();
						
						var element											= elements.eq(newIndex);
						
						if (element != null && element.length > 0)
						{
							var index										= newIndex;
							currentButton									= null;
							
							while (element && element.length > 0 && (!$.atsc.isItemVisible(element) || element.get(0) == focusedElement))
							{
								index										+= (e.shiftKey ? -1 : 1);
								element										= elements.eq(index);
							}
							
							if (element != null && element.length > 0)		{ element.focus(); }
						}
						
						break;
					
					//This moves within the button pane. It is only ever used when the button pane is selected,
					//and will have no effect if another item within the dialog is active.
					case 37: //Left Arrow
					//case 38: //Up Arrow
					case 39: //Right Arrow
					//case 40: //Down Arrow
						var currentButton										= $("#" + dialogId).dialog("option", "focusButton");
						
						if (!currentButton)										{ currentButton = 0; }
						
						if (lstButtonElements.length > 0)
						{
							var button											= $(lstButtonElements[currentButton]);
							button.blur();
							
							if (e.which == 37)									{ currentButton--; }
							else												{ currentButton++; }
							
							if (currentButton >= lstButtonElements.length)		{ currentButton = 0; }
							else if (currentButton < 0)							{ currentButton = lstButtonElements.length - 1; }
							
							var button											= $(lstButtonElements[currentButton]);
							button.focus();
						}
						
						return;
						break;
					
					//For all other keys, try to find a hotkey
					default:
						var lstButtonElements									= $("#" + dialogId + "_parent" + " > .ui-dialog-buttonpane .ui-button");
						var lstButtons											= $("#" + dialogId).dialog("option", "buttons");
						
						for (var i = 0; i < lstButtons.length; i++)
						{
							var button											= lstButtons[i];
							if(button.hotkey && button.hotkey.charCodeAt(0) == e.which)
							{
								var buttonElem									= lstButtonElements[i];
								buttonElem.click();
								
								return;
							}
						}
						
						return;
						break;
				}
			});
			
			//If the autoOpen parameter is set to true, we'll open the dialog immediately.
			if(autoOpen){ dialogElem.dialog("open"); }
			
			//This function returns the dialog element. (Not the parent!)
			return dialogElem;
		},
		
		/**
		 * @desc Forward function for creating a modal dialog window.
		 * @param dictionary options A list of options to use.
		 * @return dialog The dialog element that belongs to this window.
		 */
		makeModal: function(options){
			var settings = {
				modal: true,
				closeOnEscape: false,
				draggable: false,
				resizable: false,
				closable: false,
				selectable: false
			};
			
			//If the user has specified any options, let them override the settings.
			if(options)
			{
				$.fn.extend(settings, options);
			}
			
			return $.atsc.dialog.make(settings);
		}
	},
	isItemVisible: function(item)
	{
		if (!item)																	{ return false; }
		item																		= jQuery(item);
		if(item.length == 0)														{ return false; }
		
		var visible																	= true;
	
		visible																		= visible && (item.css("visibility") != "hidden");
		visible																		= visible && (item.css("display") != "none");
		visible																		= visible && (typeof(item.get(0).type) == "undefined" || item.get(0).type != "hidden");
		
		if(false)
		{
			var debugmsg															= "";
			if(typeof(item.get(0).id) == "undefined" || !item.get(0).id)			{ debugmsg = "[no id]"; }
			else																	{ debugmsg = item.attr("id"); }
			debugmsg																+= " (" + item.get(0).tagName + "): ";
			debugmsg																+= visible + " (visibility: " + item.css("visibility") + ", display: " + item.css("display") + ", type: " + item.get(0).type + ")";
			$.atsc.debug(debugmsg);
		}
	
		if (!visible)																{ return false; }
		else
		{
			var parentitem															= item.parent();
			if (parentitem.length > 0 && parentitem.get(0).tagName != "HTML")		{ return jQuery.atsc.isItemVisible(parentitem); }
			else																	{ return true; }
		}
	}
};

function getEvent(event)
{
	if (!IE || event != null) return event;
	else return window.event;
}

function getElement(event)
{
	var element;
	if (!IE)  element = event.target;
	else element = event.srcElement;
	return element;
}

function processXMLDoc(urlstr, func, noAlert, async)
{
	var xmlDoc;
	
	if (async == null) async = false; // TH: check b.v. bon, laatste regel in specificInit is isChanged = false, dit klopt niet meer als async = true
	
	try
	{
		urlstr += "&mode="+mode;
	}
	catch (e) {}

	var request = getXMLHttpRequest();
	if (async)
	{
		request.onreadystatechange = function()
		{
			if (request.readyState == 4)
			{
				xmlDoc = executeFuntion(request, func, noAlert);
			}
		}
	}
		
	try
	{			
		request.open('GET', urlstr, async); 
		request.send(null);
		
		if (!async) 
		{
			xmlDoc = executeFuntion(request, func, noAlert); 
		}
	}
	catch (e) {/*alert(e.message);*/} // Let op met alert, je kunt dan de melding: "Het downloaden van de opgegeven bron is mislukt" krijgen

	return xmlDoc; // wordt gebruikt in uitable.js
}

function executeFuntion(request, func, noAlert)
{		
	var resp 	= request.responseText;
	
	var xmlDoc	= string2XML(resp);

	if (xmlDoc.documentElement != null)
	{
		if (func != null) eval(func + "(xmlDoc)");				
	}
	else if (!noAlert) alert(MSG_CONNECTION_SERVER_LOST);
	
	return xmlDoc;
}

function getXMLHttpRequest()
{
	var xhr = null;
		
	try 
	{
		xhr = new XMLHttpRequest(); //IE7+ with and Non-IE		
	} 
	catch (e) 
	{
		xhr = new ActiveXObject("Microsoft.XMLHTTP"); //IE with ActiveX enabled		 
	} 

	return xhr;
}

function getOption(option)
{
	try
	{
		url = IOSERVLETURL + "?action="+GETOPTIONVALUE+"&option="+option+"";
		var xmlDoc = processXMLDoc(url);
		var optionTag = xmlDoc.getElementsByTagName("option")[0];
		return optionTag.getAttribute("value");
	}
	catch (e) { }
	
	return "";
}

function getNodeValue(maintag, i, childtag, xmlDoc)
{
	var value = "";
	var main = xmlDoc.getElementsByTagName(maintag)[i];
	if (main != null)
	{
		var mcn = main.childNodes;
		var mcnl = mcn.length;
		for (j=0;j<mcnl;j++)
		{
			var cn = mcn[j];
			if (cn.nodeType != 1) continue;
			if (cn.nodeName == childtag)
			{
				if (cn.firstChild != null) value = cn.firstChild.nodeValue;
			}
		}
	}
	return value;
}

function getTag(name,xmlDoc)
{
	tags = xmlDoc.getElementsByTagName(name);
	return tags[0];
}

function createNewXMLDocument()
{
	if (document.implementation && document.implementation.createDocument) newDoc = document.implementation.createDocument("", "", null);
	else if (window.ActiveXObject) newDoc = new ActiveXObject("Microsoft.XMLDOM");
	return newDoc;
}

//idem als getParam, maar nu wordt de variabele url lowercase gemaakt
function getParam2(param)
{
	param = param.toLowerCase();
	var url = window.location.search.toLowerCase();
	var stparam = url.indexOf(param + "=");
	var res = "";
	if (stparam > -1)
	{
		var enparam = url.indexOf("&", stparam + param.length);
		if (enparam>-1) res = url.substr(stparam + param.length + 1, enparam - (stparam + param.length + 1));
		else res = url.substr(stparam + param.length + 1);
	}
	return res;
}

function getParam(param)
{
	param = param.toLowerCase();
	var url = window.location.search;

	var stparam = url.indexOf(param + "=");
	var res = "";
	if (stparam > -1)
	{
		var enparam = url.indexOf("&", stparam + param.length);
		if (enparam>-1) res = url.substr(stparam + param.length + 1, enparam - (stparam + param.length + 1));
		else res = url.substr(stparam + param.length + 1);
	}
	return res;
}

function getElementsByTagNames(obj, list) 
{
        if (!obj) var obj = document;
        var tagNames = list.split(',');
        var resultArray = new Array();
        for (var i=0;i<tagNames.length;i++)
        {
                var tags = obj.getElementsByTagName(tagNames[i]);
                for (var j=0;j<tags.length;j++)
                {
                        resultArray.push(tags[j]);
                }
        }
        
        if (resultArray.length > 0)
        {
	        var testNode = resultArray[0];
	        if (testNode.sourceIndex)
	        {
	                resultArray.sort(function (a,b) {
	                                return a.sourceIndex - b.sourceIndex;
	                });
	        }
	        else if (testNode.compareDocumentPosition)
	        {
	                resultArray.sort(function (a,b) {
	                                return 3 - (a.compareDocumentPosition(b) & 6);
	                });
	        }
	    }
	    
	    return resultArray;
}

function getElementsByClassName(cname, hint)
{
	var tags;
	if (hint == null) tags = document.all || document.getElementsByTagName('*');
	else tags = document.getElementsByTagName(hint);

	var tagsl = tags.length;
	var classTag = [];
	var j = 0;
	var tagsI;
	var tagsICN;

	for(var i = 0; i < tagsl; i++)
	{
		tagsI = tags[i];
		tagsICN = tagsI.className;
		
		if (tagsICN != null)
		{
			if (tagsICN.indexOf(cname) > -1)
			{
				tagsICNA = tagsICN.split(" ");
	
				var kl = tagsICNA.length;
	
				for(var k = 0; k < kl; k++)
				{	
					if(tagsICNA[k] == cname)
					{
						classTag[j] = tagsI;
						j++;
					}
				}
			}
		}
	}

  	return classTag;
}
function getElementsByType(type, name)
{
	var tags = document.all || document.getElementsByTagName('*');
	var tagsl = tags.length;
	var typeTag = [];
	var j = 0;

	for (var i = 0; i < tagsl; i++)
	{
		if (tags[i].type && tags[i].type != null)
		{
			if (tags[i].type == type)
			{
				if (name != null)
				{
					if (tags[i].name == name) 
					{
						typeTag[j] = tags[i];
						j++;
					}
				}
				else 
				{
					typeTag[j] = tags[i];				
					j++;
				}
			}
		}
  	}
  	return typeTag;
}

function getCheckedItemFromElements(el)
{
	var b = false;
	var j = 0;

	try
	{
		var ell = el.length;
	
		while(!b && j < ell)
		{
			if(el[j].checked)
			{
				b = true;
				return el[j];
			}
			j++;
		}
	}
	catch(e)
	{
		return null;
	}
	if(!b) return null;
}


function replaceAll(str, from, to)
{
    var idx = str.indexOf( from );

    while (idx > -1)
    {
        str = str.replace(from, to);
        idx = str.indexOf(from );
    }

    return str;
}

function corr(v)
{
	var vc = v;

	vc = vc.replace(/\+/g, "_<plus>_");
	vc = vc.replace(/\\/g, "_<backslash>_");
	vc = vc.replace(/\%/g, "_<percent>_");
	vc = vc.replace(/\&/g, "_<ampercent>_");
	vc = vc.replace(/\,/g, "_<comma>_");
	vc = vc.replace(/\'/g, "_<quote>_");

	vc = escape(vc);

	return vc;
}

function transformXMLValue2Normal(v)
{
	var vc = v;

	vc = vc.replace(/_<ampercent>_/g, "&");
	vc = vc.replace(/_<percent>_/g, "%");
	vc = vc.replace(/_<plus>_/g, "+");
	vc = vc.replace(/_<backslash>_/g, "\\");
	vc = vc.replace(/_<quote>_/g, "'");
	vc = vc.replace(/_<comma>_/g, ",");
	vc = vc.replace(/_<tab>_/g, "\t");
	vc = vc.replace(/&lt;/g, "<");
	vc = vc.replace(/&gt;/g, ">");

	return vc;
}

function putMessage()
{
	var inputElem = $("<input type=\"text\" class=\"messageBox\"></input>");
	inputElem.css("width", "100%");
	
	var dialog = $.atsc.dialog.makeModal({
		title: "Bericht verzenden",
		html: "<p>Typ het bericht dat u wilt versturen in het vak hieronder. Dit bericht wordt naar alle aangemelde gebruikers verzonden.</p>",
		autoOpen: false,
		closable: true,
		closeOnEscape: true,
		buttons: [
			{
				text: "Verstuur",
				hotkey: "DNR",
				click: function(){
					$(this).dialog("close");
					
					var message = $(".messageBox", this).val();
					message = corr(message);
					if(message)
					{
						var url = "/MessageServlet?action=0&message=" + message;
						$.ajax({
							type: "GET",
							url: url
						});
					}
				}
			},{
				text: "Annuleren",
				hotkey: "DNR",
				click: function(){
					$(this).dialog("close");
				}
			}
		],
		setFocus: function(){
			$(".messagebox", this).focus();
		},
		width: 400,
		height: 238,
		selectable: true
	});
	dialog.append(inputElem);
	dialog.dialog("open");
}

function swapReadOnlyAndEmpty(fieldId, state, empty, req, check, nr)
{
	try
	{
		if (check == null) check = true;
		var fld        = fieldId

		if (typeof fld == "string") fld = document.getElementById(fieldId);
		
		var fldi       = document.getElementById("i" + fld.id);
		var fldt       = document.getElementById("t" + fld.id);

		if (fld.type == "radio" && nr == null)
		{			
			var r = document.forms[0].elements[fld.name];

			for (var i = 0; i < r.length; i++)
			{
				swapReadOnlyAndEmpty(fieldId, state, empty, req, check, i);
			}			
		}
		else
		{
			if (fld.type == "radio") fld = document.forms[0].elements[fld.name][nr];			

			var classArray = (fld.className).split(" ");

			if (mode == MODE_READ) state = true;
								
			if (empty) 
			{		
				if (fld.type == "radio") fld.checked = "";
				else fld.value = "";
			}			
			
			if (req != null)
			{
				if (req) fld.setAttribute("req", "true");
				else 	 fld.setAttribute("req", "false");
			}
		
			if (state)
			{							 
				var upl		= document.getElementById("UL" + fld.id);
				if (upl)	
				{				
					upl.style.display = "none";
					var upim	  = document.getElementById("im" + fld.id);
					if (upim) upim.style.display = "none";				
				}

				if (fld.type == "radio") fld.disabled = "disabled";

				fld.className = classArray[0]+" readonly";
				fld.readOnly  = "readonly";

				if (fldi != null && !upl) fldi.style.visibility = "hidden";
				if (fldt != null) fldt.style.visibility = "hidden";				
				
				if (empty) fld.setAttribute("fuidvalue", "");
				fld.setAttribute("valid", "true");
			}
			else
			{
				fld.className = classArray[0];
				fld.readOnly  = "";

				if (fldi != null) fldi.style.visibility = "visible";
				if (fldt != null) fldt.style.visibility = "visible";
				
				var upl		= document.getElementById("UL" + fld.id);
				if (upl)	
				{				
					upl.style.display = "inline";
					var upim	  = document.getElementById("im" + fld.id);
					if (upim) upim.style.display = "inline";					
				}

				if (fld.type == "radio") fld.disabled = "";
			
				// fld.oldQmapValue = "_<null>_"; // TH: Als je dit doet dan worden opgezochte waarden die je zelf veranderd weer overschreven, zie omschrijving van klantenbestelregel, onderstaande code voor in de plaats gezet (alleen controle op required)
				if (fld.getAttribute("req") == "true" && fld.value == "") fld.setAttribute("valid", "false");
	
				if (check) checkItem(fld);
			}
			
			setErrorClass(fld);
		}
	}
	catch (e) { alert(e.message+": "+fieldId); }
}
// Wordt gebruikt in EBV
//------------------------------------
// aangepast op 14-04-2005
// Nu kunnen ook waardes meegegeven worden.
function makeFloat(input, val)
{
	try
	{
		if (val == null || !val)
		{
			var value = document.getElementById(input).value.replace(",",".");
			if (value != "") return parseFloat(value);
		}
		else
		{
			if(input != "") return parseFloat(input.replace(",", "."));
		}

		return 0;
	}
	catch(e) { return 0; }
}

function fixed(a)
{
	var a = ""+a;
	return parseFloat(a.replace(",", ".")).toFixed(2).replace(".",",");
}

// Wordt gebruikt in EBV
//----------------------------------
// @param element waarin de velden op readonly gezet moeten worden,
//        of null, dan wordt het complete scherm genomen.
// @param empty : boolean : geeft aan of de velden leeggegooid moeten worden.
function makeAllReadOnly(elem, empty)
{
	var elems  = null;
	if (elem  == null)
	{
		elems = document.forms[0].elements;
	}
	else elems = elem.getElementsByTagName("*");

	if (empty == null) empty = false;

//	var elems  = elem.getElementsByTagName("*");
	var elemsl = elems.length;
	for (var i = 0; i < elemsl; i++)
	{
		if (elems[i].id) try { swapReadOnlyAndEmpty(elems[i].id, true, empty); } catch (e) {}
	}
}

function string2XML(str)
{
	var xmlDoc;
	
	try
	{
		xmlDoc = (new DOMParser()).parseFromString(str, "text/xml");
	}
	catch (e1) // doctype afhankelijk??? onderstaande werkt n.l. in categorie.jsp van A4A en bovenstaande niet
	{
		try
		{
			xmlDoc 			= createNewXMLDocument();
			xmlDoc.async 	= "false";
			xmlDoc.loadXML(str);
		}
		catch (e2) {}
	}

	return xmlDoc;
}

function addPoints(nStr)
{
	nStr += '';
	x = nStr.split(',');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2;
}

function changecss(theClass, element, value) 
{	
	var cssRules;
	
	if (document.all) 	cssRules = 'rules';
	else 				cssRules = 'cssRules';
	 	 
	for (var S = 0; S < document.styleSheets.length; S++)
	{
		var rules		= document.styleSheets[S][cssRules];
		
		for (var R = 0; R < rules.length; R++) 
		{
			var rule	= rules[R];
			
	   		if (rule.selectorText == theClass) rule.style[element] = value;	   		
	  	}
	}	
}

function findPos(obj) 
{
	var curleft = curtop = 0;
	
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	
	return [curleft,curtop];
}

function getAttribute(item, attribute)
{
	var v = null;

	try
	{
		v = item.getAttribute(attribute);
	}
	catch (e) {}
	
	try
	{
		if (v == null) v = item[attribute];
	}
	catch (e) {}
	
	return v;
}

function hasAttribute(item, attribute)
{
	var v = null;

	try
	{
		v = item.hasAttribute(attribute);
	}
	catch (e) {}
	
	try
	{
		if (v == null)
		{
			v = getAttribute(item, attribute);
			if(typeof(v) == "undefined" || !v)
			{
				v = false;
			}
			else
			{
				v = true;
			}
		}
	}
	catch (e) {}
	
	return v;
}

function isContentEditable(item)
{		
	if (IE) return item.isContentEditable; 
	else 	return item.contentEditable != null && item.contentEditable != false && !item.readOnly;
//	else 	return item.contentEditable != null && item.contentEditable != "false" && !item.readOnly; // Werkte niet in CT in safari
}

function getRadioValue(radioField)
{
	var radios					= document.forms[0].elements[radioField];
	var tmp						= "";
	if (radios != null)
	{
		if (!radios.length) //er is maar 1 optie, dus geen array
		{	
			radios					= document.getElementById(radioField+ "_0");		
			if (radios != null)
			{			 
			    if (radios.checked)	tmp		= radios.value;
			}
		}
		else
		{
			tmp					= getCheckedItemFromElements(radios);
			if(tmp != null) tmp			= tmp.value; else tmp = "";
		}
	}
	
	return tmp;
}
/* wellicht deze nieuwe gaan gebruiken ipv bovenstaande
function getRadioValue(radioField)
{
	return $("input[name=" + radioField + "]:checked").val();
}
*/
function setRadioValue(radioField, value)
{
	var radios					= document.forms[0].elements[radioField];
	
	for (var optionCounter = 0; optionCounter < radios.length; optionCounter++)
	{
		if (radios[optionCounter].value == value) radios[optionCounter].checked = true;
	}
}

function sendEmptyRequest()
{
	if (window.location.protocol == 'https:')
	{
		try 
		{
			var request = getXMLHttpRequest();
			request.open('GET', "/IOServlet?action=-1", false);
			request.send(null);
		}
		catch (e) {}
	}
}

function sleep(millis) 
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); } 
	while(curDate-date < millis)
}

function message(t, m, f, buttons)
{
	if(wt.focusCurrentFrameDone || document == wt.document)
	{
		$.atsc.dialog.makeModal({
			title: "U gebruikt een deprecated functie",
			html: "<p><span style=\"color: #FF0000; font-weight: bold;\">Waarschuwing: De \"message\" functie is deprecated. Gebruik in plaats daarvan de functie <tt>$.atsc.dialog.makeModal</tt>.<br />Zie ook: <a href=\"http://jira.atsc.local/browse/MTFRAMEWORK-30\" target=\"_blank\">jira:MTFRAMEWORK-30</a></span></p>"
		});
	}
	else setTimeout("message('" + t + "','" + m + "'," + f + "," + buttons + ")", 100);
}

function callInProgress(xmlhttp) 
{
	if (xmlhttp == null) return false;
	else
	{
		switch (xmlhttp.readyState) 
		{
			case 1: case 2: case 3:
				return true;
				break;
				// Case 4 and 0
			default:
				return false;
				break;
		}
	}
}
