/**
 * Collection of useful javascript functions.
 *
 * redirect()		- Redirects to another page
 * popup()			- Popups another page
 * setTitle()		- Changes the title of the page, after the header has been loaded.
 * ResizeWindow()	- Resizes the current window
 * autoFocus()		- Gives focus to the first form element on the page
 * showTooltip()	- Shows a html element as tooltip (see also hideTooltip())
 * selectInverse()	- Inverts the selection of check boxes in a form
 * clearBoxes()		- Clears the selection of checkboxes in a form
 */
	/** Redirects the page to the new url. */
	function redirect(url) {
		document.location.href=url;
		document.location.refresh();
	}

	/** Opens a link in a popup window. */
	function popup(url, width, height) {
		var format = "width=" + width + ",height=" + height;
		format = format + ",resizable=yes,scrollbars=yes,status=yes";
		//alert('opening '+url +", format='"+format+"'");
		open(url, '_blank', format);
		return(false);
	}

	function setTitle(newTitle) {
		document.title = "PIDstop > "+newTitle;
	}

	// Resize window method
	function ResizeWindow(new_width, new_height) {
		// This used outer width/height - and we have to compensate with exstra space
		new_width = new_width +30;	// simulate inner width/height
		new_height = new_height +30;

		// Don't make the pop-up bigger than what can be displayed
		if(screen.width <= new_width) new_width = screen.width - 50;
		if(screen.height <= new_height) new_height = screen.height - 50;

		window.moveTo(((screen.width-new_width)/2),((screen.height-new_height)/2))
		window.resizeTo(new_width, new_height)
		self.focus();
	};

	/**
	 * Automatically set focus to first non-hidden form element
	 * Be sure to call this method _after_ the form has been outputted to html, or else the focus can't be set.
	 */
	function autoFocus() {
		if (document.forms.length <= 0) return false; // No form on the page

		var elementCount = document.forms[0].elements.length;
		
		var i=0;
		var doContinue = true;
		while (i<elementCount && doContinue) {
			
			var element = document.forms[0].elements[i];
			if (element.type != "hidden" && element.type != "radio") {
				element.focus();
				//alert('Click! Autofocused on element ' +element.name + " / " +element.type);
				doContinue = false;
			}
			i++;
		}
	}

	var org_class = ""; // original class name
	
	/**
	 * Highlight a single row in the table when mouse hovers the row. Uses 'table_hl' as css class when highlighting
	 *
	 * @param	obj		The row object to hover
	 * @param	state	Boolean		Whether to highlight or remove highlighting
	 *
	 * Usage example:
	 * <tr onmouseover="highlight(this, true)" onmouseout="highlight(this, false)">.....</tr>
	 */
	function highlight(obj, enabled) {
	  if(enabled) {
		  org_class = obj.className;
		  obj.className = 'table_hl';
	  } else {
		  obj.className = org_class;
	  }
	}

	/**
	 * Displays a popup 'help' box, similar to the usual popup when hovering eg a HTML image, but allows more advanced layout.
	 * Note: The tooltip html contentes must be defined as a hidden <div id=...>content</div> where the id of the div matches the 'name' parameter.
	 *
	 * Example usage:
	 * Define the content of the popup:
	 * <div id='MyTip'>
	 *    <b>Tip</b><p>Click this button to view all users in the system, regardless of status.
	 * </div>
	 *
	 * Tip will popup when user hovers the following element:
	 * <input type=button value="Show users" onmouseover="showTooltip('MyTip', event);" onmouseout="hideTooltip('MyTip');">
	 * (the 'event' variable is automatically available for the function call)
	 *
	 * NOTE: Width of the tip element should be 300 pixels (or change the width variable used inside this method)
	 *
	 * @param	name	Id to the element containing the popup html
	 * @param	event	Mouse onhover event where user hovered the mouse
	 * @param	width	Widht of popup window. 300 is default if not specified
	 * @see hideTooltip()
	 */
	function showTooltip(name, event) {
		var width = 300; // Width of help box.
		var margin = 50; // Minimum space between tip and right-side of screen
		var yOffset = 20; // Vertical offset from mark
		// Finds the associated element with the tooltip, and sets it to visible
		document.getElementById(name).style.visibility = 'visible';

		if(event.clientX + width > screen.width - margin) {
			var x = screen.width - (width+margin);
			document.getElementById(name).style.left = x + 'px';
		} else {
			document.getElementById(name).style.left = event.clientX + 'px';
		}
		var y = event.clientY + yOffset;
		document.getElementById(name).style.top = y + 'px';
	}

	/**
	 * Hides the tool tip. Remember to call this when user 'unhovers' a given element
	 * @param	name	ID of html element containing the tooltip.
	 */
	function hideTooltip(name) {
		document.getElementById(name).style.visibility = 'hidden';
	}


	/**
	 * Inverts the selection of checkboxes in a given form.
	 *
	 */
	function selectInverse(formid, groupname) {
		var boxes = getBoxes(formid, groupname);
		//for (var i=0; i<boxes.length; i++) boxes[i].checked = ! boxes[i].checked;
		for (var i=0; i<boxes.length; i++) boxes[i].toggle();
	}

	/**
	 * Clear all checkbox selections in the given form/checkbox group
	 * @see getBoxes() concerning the group name
	 */
	function clearBoxes(formid, groupname) {		
		var boxes = getBoxes(formid, groupname);
		for (var i=0; i<boxes.length; i++) boxes[i].checked = false;
		
	}

	/**
	 * Get's all checkbox selections in the given form/checkbox group
	 *
	 * @param	formid		ID for the form element (<form id=...>)
	 * @param	groupname	(optional) If the group name is supplied, only checkboxes that contains the 'groupname' as part (substring) of 
	 *						their name are affected. Otherwise, all checkboxes in the form are retrieved.
	 *						(This means that this function can be used for more than one checkbox group in the same form)
	 * @return	array		Array containing checkbox elements.
	 */
	function getBoxes(formid, groupname) {
		if (groupname == null) groupname = "";
		form = document.getElementById(formid);
		var boxes = new Array();
		for(var i = 0; i < form.length; i++) {
			var el = form.elements[i];
			//alert('investigatin element ' + el.name);
			if(el.type == "checkbox") {
				if (el.name.indexOf(groupname) >= 0)
					boxes[boxes.length] = el;
			}
		}
		return boxes;
	}

	// Toggles the value of a checkbox
	function toggleChecked() {
		//alert('toggling');
		this.checked = ! this.checked;
	}

	// Adds the toggle method to the HTML input element. Now, you can call toggle() on any checkbox object
	HTMLInputElement.prototype.toggle = toggleChecked;

	/** Returns the number of selected checkboxes. See getBoxes() for parameter info */
	function countSelected(formid, groupname) {
		var count = 0;
		var boxes = getBoxes(formid, groupname);
		for (var i=0; i<boxes.length; i++) if (boxes[i].checked) count++;
		return count;
	}

	/** 
	 * Javascript debugging tool. Creates a new window, and outputs the _current_ html output to this window.
	 * The difference from doing a "view source" in the browser, is that the new window actually represents
	 * the current content, which may have been changed by javascript
	 */
	function debug() {
		var winDebug = open('', '_blank', 'width=800,height=600,resizable=yes');
		var content = document.body.parentNode.innerHTML;
		//var html = "<textarea cols=80 rows=30>" + content + "</textarea>";
		html = "<pre>" + encodeHTML(content) + "</pre>"
		;
		winDebug.document.write(html);
		//winDebug.document.innerText = content;
		winDebug.document.close();

		// Inner function for making sure that html can be shown as text in a document (for debugging)
		function encodeHTML(input) {
			var pattern = /</g;
			var replace = "&lt;";
			var output = input.replace(pattern, replace);
			
			pattern = />/g;
			replace = "&gt;";
			output = output.replace(pattern, replace);
			
			return output;
		}
	}

	/**
	 * Creates text containing all properties (variables and methods) and corresponding values for a given Javascript object.
	 * Insert this text in a text area, show with alert-box or similar for debugging.
	 *
	 * @param	obj	Object that contains properties.
	 * @return	String	Debugging text
	 */
	function print_props(obj) {

		var result = "";
		result += "Properties for object: \n" + obj + "\n\n";
		var j = 0;
		for (var i in obj) {
			try {
				result += "prop " + i + " = " + obj[i] + "\n";
			}
			catch (e) {
				result += "---> prop " + i + "= (NOT ACCESSIBLE) <--- \n"
			}
		}

		return result;
	}

function __test() {alert('External javascript is working')}
