//
// Author:	Martijn Polak <martijn.polak@amgate.com>
// Description: General htmlcontrols javascript functions.
//

// -- Init -------------------------------------------------------------------------------------------------------------------------------------

if (typeof(selectedItems) == 'undefined') var selectedItems = new Array();
if (typeof(errorMessages) == 'undefined') var errorMessages = new Array();
if (typeof(regularExpressions) == 'undefined') var regularExpressions = new Array();
var useMac = (navigator.platform.substr(0,3) == "Mac");
var debugWindow;
var winNew;

// -- Form functions ---------------------------------------------------------------------------------------------------------------------------

function submitForm(form, button) {

	if (form) if (autoCheckForm(form)) {
		if (document.getElementById(button)) document.getElementById(button).value = 'pressed';
		form.submit();
		return true;
	}

	return false;

}

function checkPassword(loggedin) {
	
	var compare = true;
	var pwn = document.getElementById('usr_password');
	var pwo = document.getElementById('password_old');
	var pwc = document.getElementById('password_confirm');
	
	if (pwn && pwo && pwc) compare = (!loggedin || pwn.value != pwo.value || pwc.value.length > 0);
	
	if (compare) return compareFields('usr_password','password_confirm');
	else return true;
	
}

function compareFields(field1_id, field2_id) {

	field1 = document.getElementById(field1_id);
	field2 = document.getElementById(field2_id);

	if (field1 && typeof(field1) != 'undefined' && field2 && typeof(field2) != 'undefined') {
		if (field1.value != field2.value) {
			alert(error_compare + '\n' + getFieldLabel(field1) + '\n' + getFieldLabel(field2));
			return false;
		}
	}
	
	return true;
	
}

function autoCheckForm (frmObject) {

  	var cElement;
  	var tmpLoop;
  	var isMandatory;
  	var missFields = "";
	var tValue;
	retVal = true;

	for (tmpLoop = 0; tmpLoop < frmObject.elements.length; ++tmpLoop) {

		cElement = frmObject.elements[tmpLoop];

		if (typeof(cElement) != "undefined" && cElement && typeof(cElement.value) != "undefined") {

			isMandatory = false;
			tValue = sTrim(cElement.value);
			
			if (document.getElementById(cElement.id + '_mandatory')) {
				isMandatory = true;
			} else {
				isMandatory = false;
			}

			if (((regularExpressions[cElement.id] && tValue.length > 0 && !regularExpressions[cElement.id].test(cElement.value)) || (isMandatory && tValue == '')) && (!cElement.readOnly) && (!cElement.disabled) && ((cElement.type == "file" && !document.getElementById(cElement.id + "_PREVIEW")) || cElement.type == "password" || cElement.type == "no_radio" || cElement.type == "text" || cElement.type == "textarea" || cElement.type == "hidden")) {
				missFields += getFieldLabel(cElement) + "\n";
				retVal = false;
			}
			
		}
	}

	if (!retVal) alert(error_missing + '\n' + missFields.replace(/&nbsp;/ig,""));
	return retVal;

}

// -- General functions-------------------------------------------------------------------------------------------------------------------------

// Returns the label of a field created with the html class (the contents of the first column in the container row)
function getFieldLabel(fieldObject) {
	var elm;
	//if ((elm = document.getElementById(fieldObject.name + '_fieldlabel'))) return elm.value;
	if ((elm = document.getElementById(fieldObject.id + '_ctrl_container'))) return elm.getAttribute('lb');
	//return document.getElementById(fieldObject.name + '_fieldlabel').value;
}

// Pad a string with a certain character
function strPad(padString, padNum) {
	var retVal = new String();
	for (var tmpLoop = 0; tmpLoop < padNum; ++tmpLoop) retVal += padString;
	return retVal;
}

// Simon's manual trim function:
function sTrim(sString) {

	sFirst = sString.substr(0,1)
	while (sFirst.indexOf(" ")!=-1) {
		sString =sString.substr(1,sString.length-1);
		sFirst = sString.substr(0,1)
  	}

  	sLast = sString.substr(sString.length-1,1)
  	while (sLast.indexOf(" ")!=-1) {
		sString =sString.substr(0,sString.length-1)
		sLast = sString.substr(sString.length-1,1)
  	}

  	return sString;

}

// Strips all html tags from a string
// Note: IE5 doesn't support ungreedy expressions (.*?) !
function removeHTML(inString) {
	return inString.replace(/(<{1}([\w\/"=\s]+)>|&([\w\/"=\s]+);){1}/ig, "");
}

// Strips all html from a string
function removeAllHTML(inString) {
	return inString.replace(/<(.*)?>/ig, "");
}

// Handles pressing of the del key on certain readonly fields
function delHandler(event, objectID, delTime) {

	if (navigator.appName == "Netscape") {
		if (event.which == 46) var targetObject = event.target;
	} else {
		if (event.keyCode == 46) var targetObject = event.srcElement;
	}

	if (targetObject) {

		if (delTime) {
			targetObject.innerHTML = "";
			if (objectID) updateTimeValue(objectID);
		} else {
			targetObject.value = "";
			if (objectID) {
				if (document.getElementById(objectID)) document.getElementById(objectID).value = "";
			}
		}
	}

	return true;

}

// Crossbrowser compatible positioning
// Returns an object containing the total x and y offsets for obj relative to the document
function totalElementOffset(obj) {

	var yOffset = (obj.offsetTop ? obj.offsetTop : 0);
	var xOffset = (obj.offsetLeft ? obj.offsetLeft : 0);
	var elParent = obj.offsetParent;
	var style_overflow;
	var style_height;

	while (elParent) {
		
		//debugPrint(yOffset+' + '+elParent.offsetTop + ' (' + elParent.tagName+':'+elParent.className+') '+getCurrentStyle(elParent, 'overflow'));

		yOffset += (elParent.offsetTop ? elParent.offsetTop : 0);
		xOffset += (elParent.offsetLeft ? elParent.offsetLeft : 0);

		style_overflow = getCurrentStyle(elParent.parentNode, 'overflow');
		style_height = getCurrentStyle(elParent.parentNode, 'height');

		// Fix for resetting the viewport coords when an element has its overflow property set
		if (style_height && style_height.indexOf('px') >= 0 && (style_overflow == 'auto' || style_overflow == 'scroll' || style_overflow == 'hidden')) {
			//debugPrint('BAIL: '+elParent.parentNode.tagName+'=>'+elParent.parentNode.className+' / '+style_height+'=>'+style_overflow);
			break;
		}

		elParent = elParent.offsetParent;

	}

	this.y = yOffset;
	this.x = xOffset;

}

function totalScrollOffset() {
	
	this.x = (window.pageXOffset ? window.pageXOffset : document.body.scrollLeft);
	this.y = (window.pageYOffset ? window.pageYOffset : document.body.scrollTop);
	
}

// click() method toevoegen voor Mozilla
//if  (navigator.appName == "Netscape") {
//	HTMLElement.prototype.click = function() {
//		var evt = this.ownerDocument.createEvent('MouseEvents');
//		evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
//		this.dispatchEvent(evt);
//	}
//}

function getCurrentStyle(elm, propname) {

	if (elm.currentStyle)
		var propval = elm.currentStyle[propname];
	else if (window.getComputedStyle)
		var propval = document.defaultView.getComputedStyle(elm, null).getPropertyValue(propname);

	return propval;

}

// Add properties to an event object to ensure compatibility between IE and Mozilla.
function compatibleEvent(e) {
	
	// This makes sure you can pass an event object to a function as the first argument in a direct function assignment, 
	// which by default works in Mozilla but doesn't in IE.
	if (typeof(e) == 'undefined') e = window.event;
	if (typeof(e) == 'undefined') return;

	// If the input event has already been made compatible we don't need to go though this function again
	if (typeof(e.compatible) != 'undefined') return e;
	
	e.compatible = true;
	if (typeof(e.target) == 'undefined') e.target = e.srcElement;
	if (typeof(e.layerX) == 'undefined') e.layerX = e.offsetX;
	if (typeof(e.layerY) == 'undefined') e.layerY = e.offsetY;
	if (typeof(e.keyCode) == 'undefined') e.keyCode = e.which;

	// The button property will be set as event.mousebutton because event.button is readonly in Mozilla.
	// 1 = left, 2 = right, 4 = middle
	if (typeof e.button == 'undefined') {

		e.mousebutton = event.which;
		if (e.mousebutton == 0) e.mousebutton = 1;
		if (e.mousebutton == 2) e.mousebutton = 4;
		if (e.mousebutton == 3) e.mousebutton = 2;

	} else {
		
		e.mousebutton = e.button;

		// The latest versions of mozilla support event.button but implement them differently from IE
		if (navigator.appName == 'Netscape') {
			if (e.mousebutton == 0) e.mousebutton = 1;
			else if (e.mousebutton == 1) e.mousebutton = 4;
			else if (e.mousebutton == 2) e.mousebutton = 2;
		}
		
	}

	// Use mozilla compatible functions for cancelling events on IE browsers
	if (!e.stopPropagation) e.stopPropagation = function () { window.event.cancelBubble = true };
	if (!e.preventDefault) e.preventDefault = function () { window.event.returnValue = false; };

	return e;

}

// -- Debug window -----------------------------------------------------------------------------------------------------------------------------

function debugPrint(debugText) {
	
	var init = false;

	if (!debugWindow || debugWindow.closed) {

		debugWindow = window.open("", "DebugWindow", "status=no,top=0,left=0,width=250,height=350,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no");
		init = true;
	}
	
	if (debugWindow) {
		if (init) debugWindow.document.write("<font size=\"1\" face=\"arial\"><b>Debug Console</b> [<a href=\"#\" onclick=\"document.getElementById('debugtext').innerHTML='';\" style=\"color: #336699;\">Clear</a>]</font><br><hr noshade style=\"background-color: #ffffff; border-color: #777777; border-size: 1px;\"><div id=\"debugtext\" style=\"font-family: courier new; font-size: 7.5pt;\"></div>");
		//debugWindow.document.write("<font size=\"1\" face=\"arial\">" + debugText + "</font><br>");
		debugWindow.document.getElementById('debugtext').innerHTML += debugText + "<br>";
	}

}
