/* --- get query string --- */
function getQueryString(varname) {
	var st = unescape(location.search);
	if (st.indexOf(varname) != -1){
		var tempst = st.substring(st.indexOf(varname + "=") + varname.length + 1,st.length);
		if (tempst.indexOf("&") != -1) {
			var newtemp = tempst.substring(0, tempst.indexOf("&"));
			return newtemp;
		} else {
			return tempst;
		}
	} else {
		return("");
	}
}

// this function gets the cookie, if it exists
function getCookie(name) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring(0, name.length))) {
		return null;
	}
	if (start == -1) return null;
	var end = document.cookie.indexOf(";", len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
}

function setCookie(name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime(today.getTime());
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires));
	document.cookie = name+'='+escape(value) + ((expires) ? ';expires=' + expires_date.toGMTString() : '') + ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '') + ((secure) ? ';secure' : '' );
}

function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + '=' + ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '') + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	}
}

/* --- finds an elements position --- */
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];
}

/* --- swap images in main menu --- */
function swapMenuImage(e) {
	// get source element of the event
	if (!e) var e = window.event;
	target = (e.target) ? e.target : e.srcElement;
	if (!target) return;

	if (!target.orgSrc) {
		target.orgSrc = target.src;
		if (target.orgSrc.indexOf("_on.gif") > 0) return;
		if (target.orgSrc.indexOf("_off.gif") < 0) return;
		target.src = target.src.replace("_off.gif", "_on.gif");
	} else {
		target.src = target.orgSrc;
		target.orgSrc = null;
	}
}

/* --- clock --- */
function updateClock() {
	var elm, d, h, m, s, delimiter, outString;

	elm = document.getElementById("clock");

	// get hours and minutes
	d = new Date();
	h = d.getHours();
	m = d.getMinutes();
	s = d.getSeconds();

	// delimiter = "<div class=\"delimiter\">" + (s % 2 == 0 ? ":" : " ") + "</div>";

	outString = "<div class=\"left\">" + (h < 10 ? "0" + h : h) + "</div>";
	outString += "<div class=\"delimiter\">" + (s % 2 == 0 ? ":" : "&nbsp;") + "</div>";
	outString += "<div class=\"left\">" + (m < 10 ? "0" + m : m) + "</div>";

	elm.innerHTML = outString;
	elm.style.visibility = "visible";
	window.setTimeout(updateClock, 1000);

	return;
}

function moveMarker(from, to) {
	if (fromSection > toSection) {
		if (from <= to) {
			clearTimeout(timer);
			return true;
		}
	}

	if (toSection > fromSection) {
		if (from >= to) {
			clearTimeout(timer);
			return true;
		}
	}

	k = 0.45;
	//	k = k * k * (3 - 2 * k); // apply easing (original formula)
	k = k * k * (2 * k); // apply easing
	_x = parseInt((to - from) * k);

	if (fromSection > toSection) {
		if (_x > -1) _x = -1;
	} else {
		if (_x < 1) _x = 1;
	}

	elmBus.style.left = parseInt(elmBus.style.left) + _x + "px";
	timer = setTimeout("moveMarker(" + parseInt(elmBus.style.left) + "," + to + ")", 10);
	return;
}

function positionMarker() {
	var elm;

	elmBus = document.getElementById("bus");
	if (fromSection == 0) {
		fromPos = 0;
	} else {
		elm = document.getElementById("menuItem" + fromSection);
		fromPos = findPos(elm)[0] - offset;
	}

	// position marker at start
	elmBus.style.left = fromPos + "px";
	elmBus.style.display = "block";

	if (fromSection != toSection) {
		if (toSection == 0) {
			toPos = 0;
		} else {
			elm = document.getElementById("menuItem" + toSection);
			toPos = findPos(elm)[0] - offset;
		}
		moveMarker(fromPos, toPos);
	}
	return;
}

/* --- this is the IFRAMe version, don't use, at least not yet
function submitRouteSearchForm() {
	var i, elm, nodes;
	var urlString = "movia.dk.(19).html?"

	// find form element
	if (elm = document.getElementById("routeSearchForm")) {
		// loop thru all child nodes
		nodes = elm.getElementsByTagName("input");
		for (i = 0; i < nodes.length - 1; i++) {
			// form element named 'url' must be first in the form
			if (nodes[i].name == "url") {
				urlString += "url=" + nodes[i].value;
			}	else {
				// build query string
				if (nodes[i].type != "radio" || (nodes[i].type == "radio" && nodes[i].checked)) {
					urlString += (nodes[i].value) ? "&" + nodes[i].name + "=" + nodes[i].value : "";
				}
			}
		}
		location.href = urlString;
	}

	return;
}
--- */

function submitRouteSearchForm() {
	var i, elm, nodes;
	var urlString = null;

	// find form element
	if (elm = document.getElementById("routeSearchForm")) {
		// loop thru all child nodes
		nodes = elm.getElementsByTagName("input");
		for (i = 0; i <= nodes.length - 1; i++) {
			// form element named 'url' must be first in the form
			if (nodes[i].name == "url") {
				urlString = nodes[i].value;
			} else {
				// build query string
			    if (nodes[i].type != "radio" || (nodes[i].type == "radio" && nodes[i].checked)) {
			        if (nodes[i].value.indexOf("fx. Adresse") == 0) {
			            urlString += "&" + nodes[i].name + "=";
			        } else {
			            urlString += (nodes[i].value) ? "&" + nodes[i].name + "=" + nodes[i].value : "";
			        }
			        if (nodes[i].name == "requestboth" && nodes[i].value == "yes") {
			            urlString += "&showDateTimeFieldForReturnJourney=yes";
			        }
			    }
			}
		}
		window.open(urlString, "externalWindow", "width=1024,height=600,scrollbars,resizable");
	}
	return false;
}

function processLocalEnterKey(e,o) {
    if (null == e)
        e = window.event;
    if (e.keyCode == 13) {
        document.getElementById(o).click(); 
    }
}

function init() {
	var elm, i, qs;

	// clock update function
	if (elm = document.getElementById("clock")) {
		updateClock();
	}

	// image swapping in main menu
	for (var i = 1; i <= 5; i++) {
		if (elm = document.getElementById("menuItem" + i)) {
			elm.onmouseover = swapMenuImage;
			elm.onmouseout = swapMenuImage;
		}
	}

	// populate 'date' field
	if (elm = document.getElementById("REQ0JourneyDate")) {
		var jsCurrentDate = new Date();
		var jsDay = jsCurrentDate.getDate();
		var jsMonth = eval(jsCurrentDate.getMonth() +1);
		var jsYear = eval(jsCurrentDate.getFullYear() % 100);
		var jsDayOutput = ((jsDay < 10) ? "0" + jsDay : jsDay);
		var jsMonthOutput = ((jsMonth < 10) ? "0" + jsMonth : jsMonth);
		var jsYearOutput = ((jsYear < 10) ? "0" + jsYear : jsYear);
		var jsDateOutput =  (jsDayOutput + "/" + jsMonthOutput + "/" + jsYearOutput);
		elm.value = jsDateOutput;
	}

	// populate 'return date' field
	if (elm = document.getElementById("REQ1JourneyDate")) {
	    var jsCurrentDate = new Date();
	    var jsDay = jsCurrentDate.getDate();
	    var jsMonth = eval(jsCurrentDate.getMonth() + 1);
	    var jsYear = eval(jsCurrentDate.getFullYear() % 100);
	    var jsDayOutput = ((jsDay < 10) ? "0" + jsDay : jsDay);
	    var jsMonthOutput = ((jsMonth < 10) ? "0" + jsMonth : jsMonth);
	    var jsYearOutput = ((jsYear < 10) ? "0" + jsYear : jsYear);
	    var jsDateOutput = (jsDayOutput + "/" + jsMonthOutput + "/" + jsYearOutput);
	    elm.value = jsDateOutput;
	}

	// populate 'time' field
	if (elm = document.getElementById("REQ0JourneyTime")) {
		var jsCurrentTime = new Date();
		var jsHours = jsCurrentTime.getHours();
		var jsMinutes = jsCurrentTime.getMinutes();
		var jsHoursOutput = ((jsHours < 10) ? "0" + jsHours : jsHours);
		var jsMinutesOutput = ((jsMinutes < 10) ? "0" + jsMinutes : jsMinutes);
		var jsTimeOutput =  (jsHoursOutput + ":" + jsMinutesOutput);
		elm.value = jsTimeOutput;
	}

	// populate 'return time' field
	if (elm = document.getElementById("REQ1JourneyTime")) {
	    var jsCurrentTime = new Date();
	    var jsHours = jsCurrentTime.getHours();
	    var jsMinutes = jsCurrentTime.getMinutes();
	    var jsHoursOutput = ((jsHours < 10) ? "0" + jsHours : jsHours);
	    var jsMinutesOutput = ((jsMinutes < 10) ? "0" + jsMinutes : jsMinutes);
	    var jsTimeOutput = (jsHoursOutput + ":" + jsMinutesOutput);
	    elm.value = jsTimeOutput;
	}

	// onclick for searchRouteForm submit button
	/*
	if (elm = document.getElementById("routeSearchAdvancedFormSubmit")) {
		elm.onclick = submitRouteSearchForm;
	}
	*/

	// rejseplan iframe
	if (elm = document.getElementById("rejseplan")) {
		qs = location.search;
		if (qs.indexOf("http://") > 0) {
			elm.src = qs.substring(qs.indexOf("http://"), qs.length);
		}
	}

	// hightlight active menu item
	sPath = location.href.toLowerCase();
	currentActiveTopNavItem = 0;
	maxNumberTopNavElements = 0;
	// match topNav images with location
	if (elm = document.getElementById("topNav")) {
		childElements = elm.getElementsByTagName("A");
		maxNumberTopNavElements = childElements.length;
		for (var i = 0; i < childElements.length; i++) {
			s = childElements[i].firstChild.src;
			if (s.indexOf("_off.gif") >= 0) {
				s = s.substring(s.indexOf("menu_") + 5, s.indexOf("_off.gif"));
			} else if (s.indexOf("_on.gif") >= 0) {
				s = s.substring(s.indexOf("menu_") + 5, s.indexOf("_on.gif"));
			}
			s = "/" + s.replace("_", "/") + "/";
			if (sPath.indexOf(s) >= 0) {
				childElements[i].firstChild.src = childElements[i].firstChild.src.replace("_off.gif", "_on.gif");
				currentActiveTopNavItem = i + 1;
			}
		}
	}

	if (maxNumberTopNavElements > 0) { // if 0 we're probably on a popup page
		// get settings for bus marker
		fromSection = getCookie("BusCookie");
		if (fromSection > maxNumberTopNavElements) {
			fromSection = 0;
		}
		toSection = currentActiveTopNavItem;
	}

	// display map1 or map2 depending on querystring
	if ((getQueryString("zoom") == "true") && (elm = document.getElementById("webmap2"))) {
		document.getElementById("webmap1").style.display = "none";
		elm.style.display = "block";
	} else if (elm = document.getElementById("webmap1")) {
		document.getElementById("webmap2").style.display = "none";
		elm.style.display = "block";
	}

	// handle clicks in image map on 'köreplaner' pages
	if (elm = document.getElementById("webkort_Map1")) {
		if (typeof(cityInputId) != "undefined" && cityInputId.length > 0) {
			for (i = 0; i < elm.childNodes.length; i++) {
				if (elm.childNodes[i].tagName == "AREA") {
					elm.childNodes[i].onclick = function() {
						if (x = document.getElementById(cityInputId)) x.value = this.title;
					}
				}
			}
		}
	}

	// handle clicks in image map on 'köreplaner' pages
	if (elm = document.getElementById("webkort_Map2")) {
		if (typeof(cityInputId) != "undefined" && cityInputId.length > 0) {
			for (i = 0; i < elm.childNodes.length; i++) {
				if (elm.childNodes[i].tagName == "AREA") {
					elm.childNodes[i].onclick = function() {
						if (x = document.getElementById(cityInputId)) x.value = this.title;
					}
				}
			}
		}
	}

	if (maxNumberTopNavElements > 0) { // if 0 we're probably on a popup page
		// set bus cookie
		setCookie("BusCookie", currentActiveTopNavItem, null, "/", null, null);
	}

	// animate the 'bus'
	if (elm = document.getElementById("bus")) {
		if (typeof(fromSection) != "undefined" && typeof(toSection) != "undefined") {
			if (fromSection != null && toSection != null) {
				offset = findPos(document.getElementById("topNav"))[0] - 30;
				positionMarker();
			}
		}
	}

	if (elm = document.getElementById("MitMoviaInfo")) {
	    elm.onclick = function() {
	        document.location.href = "http://www.moviatrafik.dk/Service/Personligservice/Pages/NewUser.aspx"
	    }
	}

	return;
}
function expand(obj) {
	if (elm = document.getElementById(obj)) {
		if (elm.visible != true) {
			elm.style.display = "block";
			elm.visible = true;
		} else {
			elm.style.display = "none";
			elm.visible = false;
		}
	}
}
function collapseExpand(openCloseId, changeId, idNumber) {
  var exp, lbl;
  if (exp = document.getElementById(changeId + idNumber)) {
    if (exp.visible != true && exp.visible != "true" && exp.visible != undefined) {
        exp.style.display = "block";
        exp.visible = true;
    } else {
        exp.style.display = "none";
        exp.visible = false;
    }
  }
  if (lbl = document.getElementById(openCloseId + idNumber)) {
    if (exp.visible == false || exp.visible == undefined) {
      lbl.innerHTML = "Åben";
      lbl.title = "Åben";
    }
    else {
      lbl.innerHTML = "Luk";
      lbl.title = "Luk";
    }
  }
}

var timer = null;
var elmBus = null;

/* attach event / add event listener */ 
if (window.attachEvent) {
	window.attachEvent("onload", init); // the IE way
} else if (window.addEventListener) {
	window.addEventListener("load", init, false); // W3C compliant browsers
}
