/* *******************************
	AJAX script for KMT
*/

var body;
var loader;
var target;
var retFunc;

var verifyResult = false;
var verifyDone = false;

/* *****************************************************************
  		creates the request
*/
function contentRequest(url, targetId, funcId)
{
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		request = new ActiveXObject("MSXML2.XMLHTTP");
	}
	// cache attributes
	target = targetId;
	retFunc = funcId;
	
	request.onreadystatechange = onContentResponse;
	sendRequest(url);
}

/* *****************************************************************
		sends a verifycation request
*/
function verifyRequest(url, targetId, funcId)
{
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		request = new ActiveXObject("MSXML2.XMLHTTP");
	}

	verifyResult = false;
	verifyDone = false;
	retFunc = funcId;
	target = targetId;

	request.onreadystatechange = onVerifyResponse;
	sendRequest(url);
}

/* *****************************************************************
		send the request to server
*/
function sendRequest(url)
{
	request.open("GET", url, true);
	request.send(null);
}

/* *****************************************************************
		checks what state request is in
*/
function checkReadyState(obj)
{
	if (obj.readyState == 0) { ShowLoadDialog("Sending Request");	}
	if (obj.readyState == 1) { ShowLoadDialog("Loading Response.");	}
	if (obj.readyState == 2) { ShowLoadDialog("Response Loaded..");	}
	if (obj.readyState == 3) { ShowLoadDialog("Response Ready...");	}
	if (obj.readyState == 4) {
		if (obj.status == 200) { // all OK
			return true;
		}
		else if (obj.status == 404) { // file not found erroe
			document.getElementById( ((target) ? target : "extra") ).innerHTML = "Recvested file was not found";
		} else { // some other problem
			document.getElementById( ((target) ? target : "extra") ).innerHTML = "Problem retrieving the file<br />Error status: " + obj.status;
		}

		return false;
	}
}

/* *****************************************************************
		runned when request gets a packets
*/
function onContentResponse() 
{
	if (checkReadyState(request)) {

		KillLoadDialog();

		// if custom function has been set
		if (retFunc != null) {

			// if responce content is NOT text or html
			if (request.getResponseHeader('Content-Type').indexOf("text/xml") > -1)	retFunc( request.responseXML );
			else									retFunc( request.responseText );
		}
		else
			document.getElementById(target).innerHTML = request.responseText;
	}
}

/* *****************************************************************
		runned when request gets a packets
*/
function onVerifyResponse() 
{
	if (request.readyState == 0) { ShowLoadDialog("Sending Request");	}
	if (request.readyState == 1) { ShowLoadDialog("Loading Response.");	}
	if (request.readyState == 2) { ShowLoadDialog("Response Loaded..");	}
	if (request.readyState == 3) { ShowLoadDialog("Response Ready...");	}
	if (request.readyState == 4) {
		verifyDone = true;

		if (request.status == 200) // all OK
		{
			// if return message contains html message, then
			if(request.getResponseHeader('Content-Type').indexOf("text/html") < 0)
			{
				verifyResult = true;
			}
			else
			{
				verifyResult = false;
			}

		} else if (request.status == 404) // all OK
		{
			verifyResult = false; 

		} else // file not found or some other problem
		{
			return false;
		}

		KillLoadDialog();

		if (retFunc != null) {
			retFunc( target );
		}
	}

	return false;
}

/* *****************************************************************
		shows load dialog
*/
function ShowLoadDialog(msg) 
{
	// create a div
	loader = document.createElement('div');
	// set css style
	loader.style.position   = 'absolute';
	loader.style.top        = '45.3%';
	loader.style.left       = '54.6%';
	loader.style.width      = '300px';
	loader.style.lineHeight = '100px';
	loader.style.textAlign  = 'center';
	loader.style.border     = '2px solid #005DAD';
	loader.style.background = '#ffffff';
	// insert message
	loader.appendChild( document.createTextNode(msg) );
	// append into code
	//body.appendChild(loader);
}

/* *****************************************************************
		kills load dialog
*/
function KillLoadDialog() 
{
	// remove the loader
	//body.removeChild(loader);
}

/* *****************************************************************
Custom format functions:
Pass with request to run this function (function needs to take the
responseXML as a parameter and a targetId has to be set to insert
values)
*/

/* *****************************************************************
		get contact information
*/
function getContact(content)
{
	// get and cache the selected value
	var index = document.getElementById("contactSelect").selectedIndex;

	if (index > 0) {
		var area = content.getElementsByTagName('Areas')[index - 1];
		var email;

		// get and insert contactInfo
		var contactInfo = area.getElementsByTagName('ContactText')[0].firstChild.data + '\n';
//		document.getElementById(target).innerHTML = contactInfo;

		// cache element and remove any old contactdata
		var elm = document.getElementById(target);
		elm.className = "";
		elm.innerHTML = "<div id=\"content\">";

		// format and insert line by line of the text
		var firstLine = true;
		while(contactInfo.length > 0) {
			var seperator = contactInfo.indexOf('\n');
			elm.innerHTML += (firstLine ? "<strong>" : "") + contactInfo.substring(0, seperator) + (firstLine ? "</strong>" : "");

			contactInfo = contactInfo.substring(seperator + 1);

			if (firstLine)			firstLine = false;
			if(contactInfo.length > 0)	elm.innerHTML += "<br />"
		}

		elm.innerHTML += "</div>";

		// get and change emailadress in form
		if (email = area.getElementsByTagName('ContactEmail')[0].firstChild.data)
			sendToAdress = email;

	} else {
		document.getElementById(target).innerHTML = "";
		document.getElementById(target).className = "contactTextPre";
	}
}

/* *****************************************************************
		parse and insert observer diagram
*/
function getShareObject(content)
{
	// Retrive and parse the info
}

function getExcelObject(content)
{
	// Retrive and show dowload of recived file
}


/* --------------------------------------------------------
		scripts for KMT
*/

var msie = navigator.userAgent.toLowerCase().indexOf("msie") >= 0;
var opera = navigator.userAgent.toLowerCase().indexOf("opera") >= 0;
var browserIsIE = msie && !opera;

/* --------------------------------------------------------
		validate form
*/
function validateForm1(formId) {
	var formError = false;

	if (!validateFormEmail("email")) {
		formError = true;
		document.getElementById("email").style.backgroundColor = "#fffea1";
	}

	if (validateFormEmpty("name")) {
		formError = true;
		document.getElementById("name").style.backgroundColor = "#fffea1";
	} else {
		document.getElementById("name").style.backgroundColor = "white";
	}

/*
	if (!validateFormCheckbox("testBox")) {
	}
*/

	if (formError) {
		document.getElementById("formErrorText").style.display = "block";
		return false;
	}

	// form valid, submit it
	document.forms[formId].submit();
}

/* --------------------------------------------------------
		validate email-adress
*/
function validateFormEmail(elmId) {
	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var regex = new RegExp(emailReg);
	return regex.test(document.getElementById(elmId).value); // returns true if pass
}

/* --------------------------------------------------------
		check for empty input field
*/
function validateFormEmpty(elmId) {
	if (document.getElementById(elmId).value.length > 0) {
		return false; // not empty
	} else {
		return true; // empty
	}
}

/* --------------------------------------------------------
		check is input is a number
*/
function validateFormNumberInput(key) {
	var charCode = (key.which) ? key.which : event.keyCode;

	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		return false;
	}

	return true;
}

/* --------------------------------------------------------
		check for checked checkbox <-- \o/
*/
function validateFormCheckbox(elmId) {
	if (document.getElementById(elmId).checked) {
		return true; // checked
	} else {
		return false; // not checked
	}
}

/* --------------------------------------------------------
		imageMouseOver
*/
function imageMouseOver(e) {
	var x;
	// get source element of the event
	if (!e) var e = window.event;
	target = (e.target) ? e.target : e.srcElement;
	if (!target) return;

	if (target.src.indexOf("active") < 0) {
		x = target.src.substring(0, target.src.indexOf(".gif"));
		target.src = x + "_hover.gif";
	}
	return false;
}

/* --------------------------------------------------------
		imageMouseOut
*/
function imageMouseOut(e) {
	var x;
	// get source element of the event
	if (!e) var e = window.event;
	target = (e.target) ? e.target : e.srcElement;
	if (!target) return;

	if (target.src.indexOf("_hover") >= 0) {
		x = target.src.substring(0, target.src.indexOf("_hover.gif"));
		target.src = x + ".gif";
	}
	return false;
}

/* -----------------------------------------------------------------
		get inner height of browser window
*/
function getWindowInnerHeight() {
	var x;

	if (self.innerHeight) {
		x = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		x = document.documentElement.clientHeight;
	} else if (document.body) {
		x = document.body.clientHeight;
	}
	return x;
}

/* -----------------------------------------------------------------
		get inner width of browser window
*/
function getWindowInnerWidth() {
	var x;

	if (self.innerWidth) {
		x = self.innerWidth;
	} else if (document.documentElement && document.documentElement.clientWidth) {
		x = document.documentElement.clientWidth;
	} else if (document.body) {
		x = document.body.clientWidth;
	}
	return x;
}

/* -----------------------------------------------------------------
		hide large image (image gallery)
*/
function hideLargeImage() {
	var elm;

	if (!(elm = document.getElementById("zoomLayer"))) return;
	elm.style.visibility = "hidden";

	return false;
}

/* --------------------------------------------------------
		country select dropdown
*/
function countrySelect(e) {
	var x;
	if (!e) var e = window.event;
	var target = (e.target) ? e.target : e.srcElement;
	if (e.type == "submit") {
		x = findChildNodeByName(target, "SELECT")
		location.href = x.options[x.selectedIndex].value;
	} else if (target && target.options[target.selectedIndex].value != "") {
		//location.href = target.options[target.selectedIndex].value

		location.href = target.options[target.selectedIndex].value + location.pathname.substring(14);
	}
	return false;
}

/* --------------------------------------------------------
		share display drop down
*/
function shareDisplay(e) {
	if (!e) var e = window.event;
	var target = (e.target) ? e.target : e.srcElement;
	if (target.options[target.selectedIndex].value == "select") {
		if (elm = document.getElementById("shareDisplayInputDates")) elm.style.display = "block";
	} else {
		if (elm = document.getElementById("shareDisplayInputDates")) elm.style.display = "none";
	}
	return;
}

/* --------------------------------------------------------
		sitemap functionality
*/
var expandedNode = null;

function sitemap(e) {
	var elm, x, y = null;

	if (!e) var e = window.event;
	var target = (e.target) ? e.target : e.srcElement;

	if (target.nodeName == "IMG" || (target.nodeName == "A" && target.href.indexOf("#") > -1)) {
		// clicked on expand menu or link is empty or pointing to same page - expand/contract menu
		x = (target.parentNode.nodeName == "LI") ? target.parentNode : target.parentNode.parentNode;

		// get parent UL element
		elm = findParentNodeByName(target, "UL");
		//elm = document.getElementById("navigationList");
		for (i = 0; i < elm.childNodes.length; i++) {
			if (elm.childNodes[i].nodeName == "LI") {
				if (x == elm.childNodes[i]) {
					// this is the element that triggered event
					//elm.childNodes[i].className = (elm.childNodes[i].className == "selected" ? "" : "selected");
					elm.childNodes[i].className = "selected";
					if (imgElm = findChildNodeByName(elm.childNodes[i], "IMG")) {
						imgElm.setAttribute("src", "media/navigation/blank.gif");
					}
					y = elm.childNodes[i];
				}
			}
		}
		if (expandedNode && expandedNode != y) {
			expandedNode.className = "";
			// makes previous selected category unclickable, will expand instead
			expandedNode.childNodes[0].href += "#";
			if (imgElm = findChildNodeByName(expandedNode, "IMG")) {
				imgElm.setAttribute("src", "media/navigation/plus_blue.gif");
			}
		}
		if (y) expandedNode = y;

		// make category link clickable
		target.href = target.href.substring(0, target.href.length - 1);
		target.style.cursor = 'pointer';

		return false;
	}
	return true;
}

function containsDOM(container, containee) {
	var isParent = false;
	do {
		if ((isParent = container == containee))
			break;
		containee = containee.parentNode;
	}
	while (containee != null);
	return isParent;
}

function checkMouseEnter(element, evt) {
//	if (!evt) var evt = window.event;
	if (element.contains && evt.fromElement) {
		return !element.contains(evt.fromElement);
	} else if (evt.relatedTarget) {
		return !containsDOM(element, evt.relatedTarget);
	}
}

function checkMouseLeave(element, evt) {
//	if (!evt) var evt = window.event;
	if (element.contains && evt.toElement) {
		return !element.contains(evt.toElement);
	} else if (evt.relatedTarget) {
		return !containsDOM(element, evt.relatedTarget);
	}
}

function findChildNodeByName(elm, name) {
	var i, x;

	for (i = 0; i < elm.childNodes.length; i++) {
		if (elm.childNodes[i].nodeName == name) {
			return elm.childNodes[i];
		}
		if (elm.childNodes[i].hasChildNodes) {
			if (x = findChildNodeByName(elm.childNodes[i], name)) return x;
		}
	}
	return null;
}

function findParentNodeByName(elm, name) {
	var x;

	if (elm.parentNode) {
		if (elm.parentNode.nodeName != name) {
			if (x = findParentNodeByName(elm.parentNode, name)) return x;
		} else {
			return elm.parentNode;
		}
	}
	return null;
}


/* --------------------------------------------------------
		show medium image when clicking on thumbnail
*/
var imageCurrentlyShown;
var oldTarget = null;
var imageSrc = null;

function showMediumImage(e) {
	if (!e) var e = window.event;
	var target = (e.target) ? e.target : e.srcElement;

	setupImages(target);

	return false;
}

/* --------------------------------------------------------
		show previous image in thumb list
*/
function showPrevImage(e) {
	var thumb = document.getElementById("thumbnail0").src;

	// find current mediumImage in thumb list
	index = 0;
	SIZE = document.getElementById("thumbnails").getElementsByTagName("img").length;

	for (i = 1; i < SIZE; i++, index++)
	{
		if(thumb == oldTarget.src)	break;

		thumb = document.getElementById("thumbnail" + i).src;
	}

	if (thumb != null)
	{
		index = (index - 1 < 0) ? SIZE - 1 : index - 1;
		var target = document.getElementById("thumbnail" + index);

		setupImages(target);
	}

	return false;
}

/* --------------------------------------------------------
		show next image in thumb list
*/
function showNextImage(e) {
	var thumb = document.getElementById("thumbnail0").src;

	// find current mediumImage in thumb list
	index = 0;
	SIZE = document.getElementById("thumbnails").getElementsByTagName("img").length;

	for (i = 1; i < SIZE; i++, index++)
	{
		if(thumb == oldTarget.src)	break;

		thumb = document.getElementById("thumbnail" + i).src;
	}

	if (thumb != null)
	{
		index = (index + 1 >= SIZE) ? 0 : index + 1;
		var target = document.getElementById("thumbnail" + index);

		setupImages(target);
	}

	return false;
}

/* --------------------------------------------------------
		setup the medium image and change focus on thumbs
*/
function setupImages(target) {
	imageSrc = target.src;

	var seperator = imageSrc.indexOf("thumbnails");
	var seperator2 = seperator + 11;

	// if image was not an thumbnail
	if (seperator < 0)
	{
		seperator = imageSrc.indexOf("pic/") + 4;
		seperator2 = seperator;
	}
	imageSrc = imageSrc.substring(0, seperator) + "medium/" + imageSrc.substring(seperator2);

	verifyRequest(imageSrc, target, makeImageChange);
}

function makeImageChange(target) {

	if (elm = document.getElementById("mediumImage")) {

		// if image was found on server
		if (verifyResult) {
			elm.src = imageSrc;

			// remove image size attributes
			if (elm.hasAttribute("width"))	elm.removeAttribute("width");
			if (elm.hasAttribute("height")) elm.removeAttribute("height");
		} else {
			var seperator = imageSrc.indexOf("pic/");
			elm.src = imageSrc.substring(0, seperator + 4) + imageSrc.substring(seperator + 11);

			// add image size attributes
			if (!elm.hasAttribute("width"))	 elm.setAttribute("width", "324");
			if (!elm.hasAttribute("height")) elm.setAttribute("height", "324");
		}

		// remember this image name
		imageCurrentlyShown = imageSrc;
	}

	if (browserIsIE) {
		target = target.parentNode;
	}

	if (target.className.indexOf("thumbRight") >= 0) {
		target.className = "active thumbRight";
	} else {
		target.className = "active";
	}

	if (oldTarget && oldTarget != target) {
		if (oldTarget.className.indexOf("thumbRight") >= 0) {
			oldTarget.className = "thumbRight";
		} else {
			oldTarget.className = "";
		}
	}

	target.blur();
	oldTarget = target;
}

/* --------------------------------------------------------
		show large image when clicking on zoom button
*/
function showLargeImage(e) {
	var newWin;

	if (imageCurrentlyShown) {
		// show orginal image
		var seperator = imageCurrentlyShown.indexOf("/medium");
		var large = imageCurrentlyShown.substring(0, seperator) + imageCurrentlyShown.substring(seperator + 7);

		newWin = window.open(large, "largeImageWindow", "resizable")
	}

	return false;
}

/* --------------------------------------------------------
		open file in a new window
*/
function openFile(path) {

	imageMouseOut(window.event);

	var newWin = window.open(path, null, "resizeable");
}


/* --------------------------------------------------------
		open file in a new window
*/
function submitMagazineOrder(e) {
	if (!e) var e = window.event;
	var target = (e.target) ? e.target : e.srcElement;

	/*var Magazines = '';
	var Form = '';
	var list;
	var elm;
	var type;

	// Iterate the checkboxes
	for (i = 0; i < target.orderBox.length; i++) {

		if (target.orderBox[i].checked) {
			Magazines += target.orderBox[i].value + '/';
		}
	}

	//if (Magazines == '') {
	if (target.orderBox.length < 1) {
		alert("No magazine choosen");
		return false;
	}

	Form = '&email=' + target.email.value;
	Form += '&name=' + target.name.value;
	Form += '&adress=' + target.adress.value
	Form += '&postalNumber=' + target.postalNumber.value;
	Form += '&city=' + target.city.value;
	Form += '&sendto=' + target.sendto.value;

	location.href = location.pathname + '?mag=' + Magazines + Form;
	return false;*/
}

/* --------------------------------------------------------
		email form functions
*/

var sendToAdress;

/* --------------------------------------------------------
		calculate stock value
*/
var stockValue;

function storeStockValue(content)
{
	// hide  resultarea
	var resultBox = document.getElementById("resultBox");
	resultBox.style.visibility = "hidden";

	// insert value into variable
	var elm = document.getElementById("stockValue");
	eval( content );

	// parse and round the value to two didgets
	stockValue = Math.round(parseFloat( elm.innerHTML ) * 100) / 100;
}

function calculateStocks()
{
	var elm;
	var form = document.forms["calculator"];

	// hide resultbox
	var resultBox = document.getElementById("resultBox");
	resultBox.style.visibility = "hidden";

	//get values
	var number = parseInt( form.numberOfStocks.value );

//document.write('stockValue(' + stockValue + ')::number(' + number);

	// if values are invalid
	if ( isNaN(number) || isNaN(stockValue) )
		return false;

	//calc stocks value
	var result = Math.round((number * stockValue * 100)) / 100;

	//show result
	if (elm = document.getElementById("stockResult")) {

		result = result.toString();

		var i = (result.lastIndexOf(".") > 0 ? result.indexOf(".") - 1 : result.length - 1);
		for (var sep = 0; i >= 0 ; i--, sep++) {

			if ((sep%3) == 2) {
				result = result.substring(0, i) + " " + result.substring(i);
			}
		}

		elm.innerHTML = result.replace('.', ',');
		resultBox.style.visibility = "visible";
	}

	if (elm = document.getElementById("stockValue")) {
		elm.innerHTML = stockValue.toString().replace('.', ',');
	}

	return false;
}

/* --------------------------------------------------------
*/

function shareQuery(response) {
	var elm = document.getElementById(target);

//	elm.innerHTML = '<div id="shareInfo"> \n Share holder information:&nbsp; \n <strong>KMT</strong>&nbsp;138.50 \n</div>';
//	elm.innerHTML = '<script language="javascript" src=' + '<div id="shareInfo"> \n Share holder information:&nbsp; \n <strong>KMT</strong>&nbsp;138.50 \n</div>' + '</script>';

	eval(response);
}

function shareGraphQuery(response) {
	var elm = document.getElementById(target);

//	elm.innerHTML = '<div id="shareInfo"> \n Share holder information:&nbsp; \n <strong>KMT</strong>&nbsp;138.50 \n</div>';
//	elm.innerHTML = '<script language="javascript" src=' + '<div id="shareInfo"> \n Share holder information:&nbsp; \n <strong>KMT</strong>&nbsp;138.50 \n</div>' + '</script>';

	eval(response);
}


/* --------------------------------------------------------
		Observer functions for subscription
*/

function subscribe() {
	var obj = document.forms['aspform'];
	obj.elements['avsl'].value = "";
	obj.submit();
}

function unsubscribe() {
	var obj = document.forms['aspform'];
	obj.elements['avsl'].value = "yes";
	obj.submit();
}

function validateEmail(){
	var email ="";
	var obj = document.forms['CustomerProfile'];
	email = obj.elements['Email'].value;
	if(email ==""){
		alert("Email is a required field.");
		return false;
	}
	return true;
}

function subsc() {
  if (!validateEmail()) 
  {
  	return false;
  }
  document.forms['CustomerProfile'].elements['SubscribeAction'].value=1;
  document.forms['CustomerProfile'].submit();
}

function unsubsc() {
  if (!validateEmail()) 
  {
  	return false;
  }
  document.forms['CustomerProfile'].elements['SubscribeAction'].value=0;
  document.forms['CustomerProfile'].submit();
  return true;
}


/* --------------------------------------------------------

*/
var shareHistoryUrl;

/* --------------------------------------------------------
		attach event handlers on load
*/
function doOnLoad() {
	var elm, list, x, i, j;

	/*if (elm = document.getElementsByTagName('body')[0])
		body = elm;*/

        /* share info */
	if (elm = document.getElementById("shareInfoPre")) {

		var locale = location.pathname.substring(9);
		locale = locale.substring(0, locale.indexOf('_')).toUpperCase();

		var query = '/opencms/system/modules/com.kmt/resources/ajaxproxy.jsp?url=http://wpy.observer.se/client/kmt/ShareGraph/ShareTickerSmall.aspx?wpymodulecode=SHARETICKER!lang=' + locale;

		//elm.innerHTML = query;
		//alert(query);
		contentRequest(query, 'shareInfoPre', shareQuery);

	}

	if (elm = document.getElementById("shareGraphInfo")) {

		var locale = location.pathname.substring(9);
		locale = locale.substring(0, locale.indexOf('_')).toUpperCase();

		var query = '/opencms/system/modules/com.kmt/resources/ajaxproxy.jsp?url=http://wpy.observer.se/client/kmt/ShareGraph/ShareTicker.aspx?wpymodulecode=SHARETICKER!lang=' + locale;

		//elm.innerHTML = query;
		//alert(query);
		contentRequest(query, 'shareGraphInfo',  shareGraphQuery);

		ShareGraphInit();
	}

	/* menu tabs */
	for (i = 1; i <= 10; i++) {
		if (elm = document.getElementById("menuTab" + i)) {
			elm.onmouseover = imageMouseOver;
			elm.onmouseout = imageMouseOut;
		}
	}

	/* submenu */
	if (list = document.getElementsByTagName('li'))	{
		// try and find a selected subitem in list
		for (i = 1; i <= list.length; i++) {

			elm = list.item( (i - 1) );
			if (elm.className.indexOf('selected') > -1 && elm.id.indexOf("_") > -1) {
				// modify parent elements link element
				var e = elm.parentNode.parentNode.childNodes[0]; //.getElementByTagName('a');
			
				var url = location.pathname;
				if (url.lastIndexOf('index.html') > -1) {
					url = url.substring(0, url.lastIndexOf('/') - 1);
				}

				/*if (url.lastIndexOf('/') >= url.length - 1) {
					url = url.substring(0, url.length - 2);
				}

				e.href = url.substring(0, url.lastIndexOf('/') + 1);*/
				e.href = url;

				e.style.cursor = "pointer";
				break;
			}
		}
	}

	/* site search - submit button */
	if (elm = document.getElementById("siteSearchSubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}

	/* news search submit */
	if (elm = document.getElementById("newsSearchSubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}

	/* news subscribe submit */
	if (elm = document.getElementById("newsSubscribeSubmit")) {
		elm.onmouseover = function(e) {
			imageMouseOver(e);

			if (!e) var e = window.event;
			target = (e.target) ? e.target : e.srcElement;

			var newElement   = document.createElement("input");
			newElement.type  = "hidden";
			newElement.name  = "sendto";
			newElement.id    = "sendto";
			newElement.value = sendToAdress;

			target.parentNode.appendChild(newElement);
		}

		elm.onmouseout = function(e) {
			imageMouseOut(e);		

			if (!e) var e = window.event;
			target = (e.target) ? e.target : e.srcElement;

			target.parentNode.removeChild( document.getElementById("sendto") );
		}
	}

	if (elm = document.getElementById("formNewsSubscribe")) {
		elm.onsubmit = function(e) {
			if (!e) var e = window.event;
			target = (e.target) ? e.target : e.srcElement;

			var f;
			for (i=1; i <= 10; i++) {
				f = document.getElementById("optionalField" + i + "my");

				if (!f)
					continue;
				else {
					// check mandatory (is field not empty)
					if (f.value.length > 0) {
						f.name = f.name.substring(0, f.name.length - 2);
					}
					else {
						/* Mark mandatory field label that wasn't filled, and information fields */
						f.previousSibling.previousSibling.style.color = '#FF0000';

						var t = document.getElementById("mandatoryFields");
						t.style.color = '#FF0000';

						return false;
					}
				}
			}
			return true;
		}
	}

	/* share display submit */
	if (elm = document.getElementById("shareDisplaySubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}

	/* share display submit */
	if (elm = document.getElementById("shareDownloadSubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}

	/* general form submit */
	if (elm = document.getElementById("formSubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}

	/* emailform submit */
	if (elm = document.getElementById("emailFormSubmit")) {
		elm.onmouseover = function(e) {
			imageMouseOver(e);

			if (!e) var e = window.event;
			target = (e.target) ? e.target : e.srcElement;

			var newElement   = document.createElement("input");
			newElement.type  = "hidden";
			newElement.name  = "sendto";
			newElement.id    = "sendto";
			newElement.value = sendToAdress;

			target.parentNode.appendChild(newElement);
		}

		elm.onmouseout = function(e) {
			imageMouseOut(e);		

			if (!e) var e = window.event;
			target = (e.target) ? e.target : e.srcElement;

			target.parentNode.removeChild( document.getElementById("sendto") );
		}
	}

	/* flags in quick navigation */
	for (i = 1; i <= 10; i++) {
		if (elm = document.getElementById("flag" + i)) {
			elm.onmouseover = imageMouseOver;
			elm.onmouseout = imageMouseOut;
			elm.onchange = countrySelect;
		}
	}

	/* promotion boxes,  */
	for (i = 1; i <= 9; i++) {
		if (elm = document.getElementById("promoBox" + i)) {
			elm.onmouseover = function(e) {
				e = e ? e : window.event;
				target = (e.target) ? e.target : e.srcElement;
				if (target.parentNode.nodeName == "P") {
					target.style.textDecoration = "underline";
					// get first H1 child node
					if (x = findChildNodeByName(this, "H1")) {
						// find the A node
						if (x = findChildNodeByName(x, "A")) {
							x.style.textDecoration = "none";
						}
					}
				}
				if (checkMouseEnter(this, e)) {
					if (this.className.indexOf("type2") >= 0) {
						this.className = "box type2 boxHover clearfix";
					} else {
						this.className = "box boxHover clearfix";
					}
					// get first H1 child node
					if (x = findChildNodeByName(this, "H1")) {
						// find the A node
						if (x = findChildNodeByName(x, "A")) {
							x.style.textDecoration = "underline";
						}
					}
					this.style.cursor = "pointer";
				}
			}
			elm.onmouseout = function(e) {
				e = e ? e : window.event;
				target = (e.target) ? e.target : e.srcElement;
				if (target.parentNode.nodeName == "P") {
					target.style.textDecoration = "none";
					// get first H1 child node
					if (x = findChildNodeByName(this, "H1")) {
						// find the A node
						if (x = findChildNodeByName(x, "A")) {
							x.style.textDecoration = "underline";
						}
					}
				}
				if (checkMouseLeave(this, e)) {
					if (this.className.indexOf("type2") >= 0) {
						this.className = "box type2 clearfix";
					} else {
						this.className = "box clearfix";
					}
					// get first H1 child node
					if (x = findChildNodeByName(this, "H1")) {
						// find the A node
						if (x = findChildNodeByName(x, "A")) {
							x.style.textDecoration = "";
						}
					}
					this.style.cursor = "default";
				}
			}
			// redirect to first url given
			elm.onclick = function() {
				location.href = findChildNodeByName(this, "A");
			}
		}
	}

	/* promotion boxes (home page)  */
	for (i = 1; i <= 9; i++) {
		if (elm = document.getElementById("promoBoxHome" + i)) {
			elm.onmouseover = function(e) {
				e = e ? e : window.event;
				target = (e.target) ? e.target : e.srcElement;
				if (checkMouseEnter(this, e)) {
					if (this.className.indexOf("type2") >= 0) {
						this.className = "box type2 boxHover clearfix";
					} else {
						this.className = "box boxHover clearfix";
					}
				}
			}
			elm.onmouseout = function(e) {
				e = e ? e : window.event;
				target = (e.target) ? e.target : e.srcElement;
				if (checkMouseLeave(this, e)) {
					if (this.className.indexOf("type2") >= 0) {
						this.className = "box type2 clearfix";
					} else {
						this.className = "box clearfix";
					}
				}
			}
		}
	}

	/* promotion boxes (home page global startpage)  */
	for (i = 1; i <= 9; i++) {
		if (elm = document.getElementById("promoBoxHomeStart" + i)) {
			elm.onmouseover = function(e) {
				e = e ? e : window.event;
				target = (e.target) ? e.target : e.srcElement;
				if (checkMouseEnter(this, e)) {
					if (this.className.indexOf("type2") >= 0) {
						this.className = "box type2 boxHover clearfix";
					} else {
						this.className = "box boxHover clearfix";
					}
				}
			}
			elm.onmouseout = function(e) {
				e = e ? e : window.event;
				target = (e.target) ? e.target : e.srcElement;
				if (checkMouseLeave(this, e)) {
					if (this.className.indexOf("type2") >= 0) {
						this.className = "box type2 clearfix";
					} else {
						this.className = "box clearfix";
					}
				}
			}
		}
	}


	/* country select dropdown */
	if (elm = document.getElementById("countrySelect")) {
		//elm.onchange = countrySelect;

		elm.onchange = function(e) {
			//
			var x;
			if (!e) var e = window.event;
			var target = (e.target) ? e.target : e.srcElement;
			if (e.type == "submit") {
				x = findChildNodeByName(target, "SELECT");
				location.href = x.options[x.selectedIndex].value;
			} else if (target && target.options[target.selectedIndex].value != "") {
					location.href = target.options[target.selectedIndex].value;

					//location.href = target.options[target.selectedIndex].value + location.pathname.substring(14);
			}
			return false;
		}
	}

	/* company site select dropdown */
	if (elm = document.getElementById("companysiteSelect")) {
		//elm.onchange = countrySelect;

		elm.onchange = function(e) {
			//
			var x;
			if (!e) var e = window.event;
			var target = (e.target) ? e.target : e.srcElement;
			if (e.type == "submit") {
				x = findChildNodeByName(target, "SELECT");
				location.href = x.options[x.selectedIndex].value;
			} else if (target && target.options[target.selectedIndex].value != "") {
					location.href = target.options[target.selectedIndex].value;

					//location.href = target.options[target.selectedIndex].value + location.pathname.substring(14);
			}
			return false;
		}
	}

	/* share display drop down */
	if (elm = document.getElementById("shareDisplaySelectPeriod")) {
		if (elm.options[elm.selectedIndex].value == "select") {
			if (x = document.getElementById("shareDisplayInputDates")) x.style.display = "block";
		} else {
			if (x = document.getElementById("shareDisplayInputDates")) x.style.display = "none";
		}
		elm.onchange = shareDisplay;
	}

	/* alternate country selector */
	if (elm = document.getElementById("formCountrySelect2")) {
		elm.onsubmit = countrySelect;
	}

	/* contact selector */
/*	if (elm = document.getElementById("formContactSelect")) {
		elm.onsubmit = countrySelect;
	}

	if (elm = document.getElementById("contactSelect")) {
		elm.onchange = function() {
			contentRequest('contactareas.xml', 'contactText', getContact);
		}
	}*/

	/* image gallery functionality */
	if (elm = document.getElementById("thumbnails")) {
		for (i = 0; i < elm.childNodes.length; i++) {
			if (elm.childNodes[i].nodeName == "A") {
				elm.childNodes[i].onclick = showMediumImage;
			}
		}
	}

	if (elm = document.getElementById("zoomButton")) {
		elm.onclick = showLargeImage;
	}

	if (elm = document.getElementById("prevButton")) {
		elm.onclick = showPrevImage;
	}

	if (elm = document.getElementById("nextButton")) {
		elm.onclick = showNextImage;
	}

	if (elm = document.getElementById("thumbnail0")) {
		oldTarget = elm;
		imageCurrentlyShown = elm;
	}

	/* email forms */
	if (elm = document.getElementById("sendto")) {
		sendToAdress = elm.value;

		// remove the element that hold the adress
		elm.parentNode.removeChild(elm);
	}

	/* back button */
	if (elm = document.getElementById("backButton")) {
		elm.onclick = function() {
			history.go(-1);
			return false;
		}
	}

	/* calculate form */
	if (elm = document.getElementById("calculatorForm")) {

		elm.onsubmit = function(e) {
/*			var target;
			if (!e) var e = window.event;
			target = (e.target) ? e.target : e.srcElement;*/

			calculateStocks()

			return false;
		}
	}


	if (elm = document.getElementById("dateSelector")) {
		// get todays stocks by default
		var form = document.forms["calculator"];

		var option = form.dateSelector.options[form.dateSelector.selectedIndex].value; 
		var currency;
		for (i=0; i < form.currency.length; i++) {

			if (form.currency[i].checked) {
				currency = form.currency[i].value;
			}
		}
		var url = 'http://se.yhp.waymaker.net/KMT/new/calc/sharehistoryinc.asp?date=' + option + '!currency=' + currency;
		contentRequest('/opencms/system/modules/com.kmt/resources/ajaxproxy.jsp?url=' + url, null, storeStockValue);

		//get selected dates stockvalue
		elm.onchange = function(e) {
			e = e ? e : window.event;
			target = (e.target) ? e.target : e.srcElement;

			// get todays stocks by default
			var form = document.forms["calculator"];

			var option = form.dateSelector.options[form.dateSelector.selectedIndex].value; 
			var currency;
			for (i=0; i < form.currency.length; i++) {

				if (form.currency[i].checked) {
					currency = form.currency[i].value;
				}
			}
			var url = 'http://se.yhp.waymaker.net/KMT/new/calc/sharehistoryinc.asp?date=' + option + '!currency=' + currency;
			contentRequest('/opencms/system/modules/com.kmt/resources/ajaxproxy.jsp?url=' + url, null, storeStockValue);
		}
	}

	for (i = 1; i <= 10; i++) {
		if (elm = document.getElementById("currency" + i)) {
				// 
				elm.onchange = function(e) {
				e = e ? e : window.event;
				target = (e.target) ? e.target : e.srcElement;

				// get todays stocks by default
				var form = document.forms["calculator"];

				var option = form.dateSelector.options[form.dateSelector.selectedIndex].value; 
				var currency;
				for (i=0; i < form.currency.length; i++) {

					if (form.currency[i].checked) {
						currency = form.currency[i].value;
					}
				}
				var url = 'http://se.yhp.waymaker.net/KMT/new/calc/sharehistoryinc.asp?date=' + option + '!currency=' + currency;
				contentRequest('/opencms/system/modules/com.kmt/resources/ajaxproxy.jsp?url=' + url, null, storeStockValue);
			}
		}
	}


	if (elm = document.getElementById("stocksField")) {
		elm.onkeypress = validateFormNumberInput;
	}

	if (elm = document.getElementById("calcSubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}

        if (elm = document.getElementById("orderButtonSubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}

        if (elm = document.getElementById("subscribeButtonSubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}

        if (elm = document.getElementById("unsubscribeButtonSubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}

        if (elm = document.getElementById("subscribe2ButtonSubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}

        if (elm = document.getElementById("unsubscribe2ButtonSubmit")) {
		elm.onmouseover = imageMouseOver;
		elm.onmouseout = imageMouseOut;
	}


	/* news magazines download button */
	for (i = 1; i <= 20; i++) {
		if (elm = document.getElementById("dlMag" + i)) {
			elm.onmouseover = function(e) {
				e = e ? e : window.event;
				target = (e.target) ? e.target : e.srcElement;

				if (checkMouseEnter(this, e)) {
					imageMouseOver(e);
					target.style.cursor = "pointer";
				}
			}
			elm.onmouseout = function(e) {
				e = e ? e : window.event;
				target = (e.target) ? e.target : e.srcElement;

				if (checkMouseLeave(this, e)) {
					imageMouseOut(e);
					target.style.cursor = "default";
				}
			}
		}
	}

	/* news order form */
	if (elm = document.getElementById("orderMagForm")) {
		elm.onsubmit = submitMagazineOrder;
	}

	/* news order button */
	if (elm = document.getElementById("orderMagSubmit")) {
		elm.onmouseover = function(e) {
			e = e ? e : window.event;
			target = (e.target) ? e.target : e.srcElement;

			imageMouseOver(e);
			target.style.cursor = "pointer";
		}
		elm.onmouseout = function(e) {
			e = e ? e : window.event;
			target = (e.target) ? e.target : e.srcElement;

			imageMouseOut(e);
			target.style.cursor = "default";
		}
	}

	/* sitemap */
	for (i = 1; i <= 10; i++) {
		if (elm = document.getElementById("sitemapArea" + i)) {

			if (list = elm.getElementsByTagName('li')) {
				var item;
				for (j = 0; j < list.length; j++) {
					item = list.item(j)
					
					item.onclick = sitemap;
				}
			}
		}
	}

	return false;
}

window.onload = doOnLoad;
