/**
 * Main java script library for the Micklagard site.
 *
 * @author Fredric Rylander, <fredric at rylander dot nu>
 * @copyright Copyright (c) 2007, Fredric Rylander
 * @date 2007-06-21
 * @version 1.0
 */

/** Holder for registered onLoad-functions. */
var onLoadFunctions = new Array();

/**
 * Helper function for adding onLoad-functions.
 * @param function funcPtr Pointer to the function to add.
 */
function addOnLoadFunction(funcPtr)
{
	onLoadFunctions.push(funcPtr);
}

/**
 * Checks if the browser is up to needed tasks, else complains.
 */
function browserCheck()
{
	if (!document.getElementById)
		return alert('Din webbl&auml;sare &auml;r f&ouml;r gammal f&ouml;r denna funktion!\n\nDu beh&ouml;ver &aring;tminstone: Internet Explorer 5, Firefox 1 eller Opera 9.');
}

/**
 * Fires the registered onLoad-functions.
 * @param function funcPtr Pointer to an extra onLoad-function.
 */
function doOnLoad(funcPtr)
{
	if (funcPtr)
		funcPtr();
	for (var i=0; i < onLoadFunctions.length; i++)
		if (onLoadFunctions[i])
			onLoadFunctions[i]();
}

/**
 * Finds the absolute position of the given object.
 *
 * @param object obj The object whoīs position to return.
 */
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];
}

/**
 * Focuses on the first available text or password input element.
 */
function focusFirst()
{
	if (document.forms[0])
		for (var i = 0; i < document.forms[0].length; i++) {
			var elm = document.forms[0].elements[i];
			if (!elm.disabled && (elm.type == 'textarea' | elm.type == 'text' | elm.type == 'password')) {
				elm.focus();
				elm.select();
				return;
			}
		}
}
addOnLoadFunction(focusFirst);

/**
 * Hides the avatar created in 'showAvatarBig()'.
 */
function hideAvatarBig()
{
	if (!document.getElementById)
		return;

	var img = document.getElementById('zoomImg');
	if (img)
		img.style.display = 'none';
}

/**
 * Checks if the given two elementsī string values are equal.
 * Will also show/hide the description for the given field 'element2'.
 *
 * @param element1 One of the input.text elements to validate.
 * @param element2 The second of the input.text elements to validate.
 * @return bool TRUE if the string values are equal, else FALSE.
 */
function isContentEqual(element1, element2)
{
	if (!element1 || !element2) {
		alert('isContentEqual(): One of the elements to verify is not specified!');
		return false;
	}

	// If their contents are equal.
	if (element1.value == element2.value) {
		showElement(element2.name + 'Desc', false);
		return true;
	}

	// Not equal.
	showElement(element2.name + 'Desc', true);
	element2.select();
	element2.focus();
	return false;
}

/**
 * Checks if the given elementīs string value validates as an e-mail address.
 * Will also show/hide the description for the given field.
 *
 * @param element The input.text element to validate.
 * @param bool allowEmpty If set to true the URL is okay if validated or empty.
 * @return bool TRUE if the string was validated, else FALSE.
 */
function isEmail(element, allowEmpty)
{
	if (!element || (allowEmpty && element.value == ''))
		return true;

	var regex = /^[\w-\.]+@[\w-\.]+\.[\w]{2,4}$/;
	
	// If itīs an email address.
	if (regex.test(element.value)) {
		showElement(element.name + 'Desc', false);
		return true;
	}

	// Not an email address.
	showElement(element.name + 'Desc', true);
	element.select();
	element.focus();
	return false;
}

/**
 * Ensure that the given input elementīs value is a number and within the specified bounds, else show an error message.
 *
 * @param object element The form text element whoīs value should be validated.
 * @param int min The minimum bound.
 * @param int max The maximum bound.
 * @return bool Success status.
 */
function isNumberInt(element, min, max)
{
	// If within bounds.
	var regex = /^\d+$/;
	if (element.value != '' && (!regex.test(element.value) || parseInt(element.value) == NaN)) {
		showElement(element.name + 'Desc', true);
		element.select();
		element.focus();
		return false;
	}
	// We now know itīs a number.
	var value = parseInt(element.value);
	if (value < min || value > max) {
		showElement(element.name + 'Desc', true);
		element.select();
		element.focus();
		return false;
	}

	// All seems okay.
	showElement(element.name + 'Desc', false);
	return true;
}

/**
 * Checks if the given string validates as an URL.
 * Will also show/hide the description for the given field.
 *
 * @param element The input.text element to validate.
 * @param bool allowEmpty If set to true the URL is okay if validated or empty.
 * @return bool TRUE if the string was validated, else FALSE.
 */
function isUrl(element, allowEmpty)
{
	if (!element || (allowEmpty && (element.value == '' || element.value == 'http://')))
		return true;

	//var regex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	var regex = /^((ftp|http|https):\/\/(\w+:{0,1}\w*@)?)?(\w+\.)?\w+\.\w{2,4}(:[0-9]+)?[\/\w#!:.?+=&%@\-~]*$/;
	
	if (regex.test(element.value)) {
		showElement(element.name + 'Desc', false);
		return true;
	}

	// Not an URL.
	showElement(element.name + 'Desc', true);
	element.select();
	return false;
}

/**
 * Scales the given avatar image so that it is shown in its full size.
 *
 * @param object img The avatar image to re-scale.
 * @param string link An optional link that is assigned to the imageīs onClick-event.
 */
function showAvatarBig(thumbImg, link)
{
	if (!document.getElementById || !document.createElement)
		return;

	var newImg = document.getElementById('zoomImg');
	if (!newImg)
	{
		newImg = document.createElement('img');
		newImg.id = 'zoomImg';
		newImg.className = 'userImage';
		newImg.onmouseout = hideAvatarBig;
		newImg.style.position = 'absolute';
		newImg.style.cursor = 'pointer';
		newImg.zIndex = 1000; // <- som high number.
		
		var div = document.getElementById('pagecontent');
		if (div)
			div.appendChild(newImg);
	}	
	if (newImg)
	{
		newImg.src = thumbImg.src;
		newImg.alt = thumbImg.alt;
		
		var pos = findPos(thumbImg);
		//newImg.style.left = (pos[0] - (newImg.width - thumbImg.width) / 2) + 'px';
		newImg.style.left = (pos[0] - 10) + 'px';
		//newImg.style.top = (pos[1] - (newImg.width - thumbImg.width) / 2) + 'px';
		newImg.style.top = (pos[1] - 5) + 'px';
		newImg.style.display = 'block';

		if (link)
			newImg.onclick = function() { window.location = link; };
	}
}

/**
 * Show or hide the given element.
 *
 * @param string name The name of the element that is about to be shown/hidden.
 * @param bool show If TRUE then shows the specified element, else hides it.
 * @return bool TRUE if the element was able to be shown, else FALSE.
 */
function showElement(name, show)
{
	// Firefox >= 1, NNavigator >= 6, IExplorer >= 4.5
	if (document.getElementById || document.all) {
		var elm = document.all ? document.all[name] : document.getElementById(name);
		if (elm) {
			elm.style.position   = show ? 'relative' : 'absolute';
			elm.style.visibility = show ? 'visible'  : 'hidden';
			return true;
		}
	}

	// NNavigator >= 4
	if (document.layers) {
		var elm = document.layers[name];
		if (elm) {
			elm.position   = show ? 'relative' : 'absolute';
			elm.visibility = show ? 'visible'  : 'hidden';
			return true;
		}
	}

	// Could not show the element.
	return false;
}

/**
 * Replaces all textareas within the current page with the FCKeditor.
 * To use this function, add a TEXTAREA in place of the FCKeditor. Then
 * chain in this onLoad-handler using an in-line script as such:
 *
 * <script type="text/javascript">addOnLoadFunction(useWysiwygEditor);</script>
 */
function useWysiwygEditor()
{
	var textAreas = document.getElementsByTagName('textarea');
	for (var i=0; i < textAreas.length; i++) {
		var oFCKeditor = new FCKeditor(textAreas[i].name);
		oFCKeditor.BasePath = '/FCKeditor/';
		oFCKeditor.Config['CustomConfigurationsPath'] = '/js/fckconfig.js';
		oFCKeditor.ToolbarSet = 'Micklagard';
		oFCKeditor.ReplaceTextarea();
	}
}

/**
 * Ensure that the given input elementīs value is within the specified bounds, else show an error message.
 *
 * @param object element The form input element (text or password) whoīs value should be validated.
 * @param int min The minimum bound.
 * @param int max The maximum bound.
 * @return bool Success status.
 */
function withinBounds(element, min, max)
{
	// If within bounds.
	if (element.value.length >= min && element.value.length <= max) {
		showElement(element.name + 'Desc', false);
		return true;
	}

	// Not within bounds.
	showElement(element.name + 'Desc', true);
	element.select();
	element.focus();
	return false;
}
