//*******************************************************************
//****       js javascript-Datei             (c) VRN GmbH        ****
//****       für VRN Fahrplanauskunft          01.02.2011        ****
//*******************************************************************

var cheat = '';
document.onkeydown = check_key;
var mouseDown = 0;

document.onmousedown = function() { 
    mouseDown = 1;
}

document.onmouseup = function() {
    mouseDown = 0;
}

initBase64();

function set_date() {
	var day, month, year;
	var Name = new Array("So", "Mo", "Di", "Mi", "Do", "Fr", "Sa");
		
	if ($('psParamSampleDate')) {
		heute = new Date();
		day = heute.getDate();
		day =((day < 10) ? "0" : "") + day;
		month = heute.getMonth() + 1;
		month =((month < 10) ? "0" : "") + month;
		year = heute.getFullYear();
		$('psParamSampleDate').value = year + month + day;
		$('date_ps').value = day + '.' + month + '.' + year;
		$('date_ps').style.color = '#000000';
	} else {
		day = $('itdDateDay').value;
		splitday = day.split(", ");
		if (splitday[1])
			day = splitday[1];
	
		month = $('itdDateMonth').value;
		year = $('itdDateYear').value;
		
		if (year.length == 4)
			year_s = year.substr(2,2);
		else year_s = year;
		
		heute = new Date(year, month - 1, day);
		wd = heute.getDay();
	
		timeString = Name[wd] + ", " + day + "." + month + "." + year_s;
	
		$('date').value = timeString;
	}
}

function dateUpDown(upOrDown) { 
	var tag;
	var monat;
	var jahr;
	var Name = new Array("So", "Mo", "Di", "Mi", "Do", "Fr", "Sa");
	
	date = $('date').value;
	splitString = date.split(".");
	splitday = splitString[0].split(", ");
	
	tag = splitday[1];
	monat = splitString[1];
	jahr = splitString[2];

	var jahrIntWert = parseInt("20" + jahr);

	if (jahrIntWert >= 0 && jahrIntWert <= 75) { 
		jahrIntWert = 2000 + jahrIntWert; 
	} else {
	    if (jahrIntWert > 75 && jahrIntWert <= 99) { 
	    	jahrIntWert = 1900 + jahrIntWert; 
	    }
	}

	monat = monat - 1;  

	heute = new Date(jahrIntWert, monat, tag);
	var millisecunden = heute.getTime();

	if (upOrDown == 'up') { 
		if (millisecunden == 1256421600000) { 
			millisecunden = 1256426000000; 
		}
		millisecunden = millisecunden + 86400000; 
	}

	if (upOrDown == 'down' ) { 
		millisecunden = millisecunden - (24*60*60*1000); 
	}
	
	heute.setTime(millisecunden);
	
	wd = heute.getDay();

	tag = heute.getDate();
	tag =((tag < 10) ? "0" : "") + tag;

	monat = heute.getMonth() + 1;
	monat =((monat < 10) ? "0" : "") + monat;

	jahr = "" + heute.getFullYear();
	//alert ("Heute ist " + Name[wd]) ;

	$('date').value = Name[wd]+ ", " + tag + "." + monat + "." + jahr.substr(2,2);
}

function timeUpDown(upOrDown, obj) { 
	var tag;
	var monat;
	var jahr;
	var Name = new Array("So", "Mo", "Di", "Mi", "Do", "Fr", "Sa");
	var date = new Date();
	var hours = date.getHours();
	var minutes = date.getMinutes();

	hours =((hours < 10) ? "0" : "") + hours;
	minutes =((minutes < 10) ? "0" : "") + minutes;

	time = $(obj).value;

	splitString = time.split(":");
	hour = splitString[0];
	minute = splitString[1];
	
	if (time.length != '5' && time.indexOf(':') < 1) {
		if (time.length == '4') {
			$(obj).value = time.substr(0,2) + ":" + time.substr(2,2);
		} else if (time.length == '3') {
			$(obj).value = "0" + time.substr(0,1) + ":" + time.substr(1,2);
		} else if (time.length == '2') {
			$(obj).value = time.substr(0,2) + ":00";
		} else if (time.length == '1') {
			$(obj).value = "0" + time.substr(0,1) + ":00";
		} else {
			alert("Uhrzeit bitte im Format hh:mm eingeben.");
			$(obj).value = hours + ":" + minutes;
			return;
		}
	} else if (time.indexOf(':') < 1) {
		alert("Uhrzeit bitte im Format hh:mm eingeben.");
		$(obj).value = hours + ":" + minutes;
		return;
	} else if (isNaN(hour) || isNaN(minute)) {
		alert("Uhrzeit bitte im Format hh:mm eingeben.");
		$(obj).value = hours + ":" + minutes;
		return;
	}
	
	time = $(obj).value;

	splitString = time.split(":");
	hour = splitString[0];
	minute = splitString[1];
	
	minute = Math.ceil(minute / 10) * 10;
	
	hour_msec = hour * 1000 * 60 * 60;
	minute_msec = minute * 1000 * 60;
	time_msec = hour_msec + minute_msec;

	pos = get_caret_pos($(obj));

	if (upOrDown == 'up') { 
		if (time_msec >= 85860000)
			time_msec = 0;
		else
			if (pos > 3) {	
				time_msec = time_msec + (1000 * 60 * 10);
			} else {
				time_msec = time_msec + (6000 * 60 * 10);
			} 
	}

	if (upOrDown == 'down' ) { 	
		if (time_msec <= 540000)
			time_msec = 86400000;
		else	
			if (pos > 3) {	
				time_msec = time_msec - (1000 * 60 * 10); 
			} else {
				time_msec = time_msec - (6000 * 60 * 10); 
			}
	}

	hour_tmp = Math.floor((time_msec / (1000 *60 * 60)) % 60);
	minute_tmp = Math.floor((time_msec / (1000 *60)) % 60);

	if (hour_tmp >= 0 && hour_tmp < 10) { 
		hour_tmp = "0"+hour_tmp; 
	}

	if (minute_tmp >= 0 && minute_tmp < 10) { 
		minute_tmp = "0"+minute_tmp; 
	}

	$(obj).value = hour_tmp+ ":" + minute_tmp;
	set_caret_pos($(obj), pos);
}

function clear_value(obj) {
	if (obj.value == 'Ort+Haltestelle / Straße Nr. / interessanter Ort') {
		obj.value = '';
	} else if (obj.value == 'Liniennummer') {
		obj.value = '';
	} 
}

function show_via() {
	if ($("via").style.display=='block') {
		if ($("itdLPxx_mdvMap").value == 'origin' || $("itdLPxx_mdvMap").value == 'destination') {
			$j('#via').slideUp('slow', function() {$("via").style.display = "none";$("itdLPxx_show_via").value = '0';check_value();submit_date_time();document.forms[0].submit();});
			$("odvs").style.height = "652px";
		} else if ($("itdLPxx_mdvMap").value == 'via') {
			$j('#Map_via').slideUp('slow', function() {$("close_Map_via").style.display = "none";});
			$j('#via').slideUp('slow', function() {$("via").style.display = "none";$("itdLPxx_show_via").value = '0';check_value();submit_date_time();document.forms[0].submit();});
			$("odvs").style.height = "160px";
		} else {
			$j('#via').slideUp('slow', function() {$("via").style.display = "none";$("itdLPxx_show_via").value = '0';check_value();submit_date_time();document.forms[0].submit();});
			$("odvs").style.height = "160px";
		}
	} else {
		document.eingabe.itdLPxx_show_via.value = '1';
		if ($("itdLPxx_mdvMap").value == 'origin' || $("itdLPxx_mdvMap").value == 'destination') {
			$j('#via').slideDown('slow', function() {$("via").style.display = "block";$("itdLPxx_show_via").value = '1';check_value();submit_date_time();document.forms[0].submit();});
			$("odvs").style.height = "672px";
		} else if ($("itdLPxx_mdvMap").value == 'via') {
			$j('#Map_via').slideDown('slow', function() {$("close_Map_via").style.display = "block";});
			$j('#via').slideDown('slow', function() {$("via").style.display = "block";$("itdLPxx_show_via").value = '1';check_value();submit_date_time();document.forms[0].submit();});
			$("odvs").style.height = "672px";
		} else {
			$j('#via').slideDown('slow', function() {$("via").style.display = "block";$("itdLPxx_show_via").value = '1';check_value();submit_date_time();document.forms[0].submit();});
			$("odvs").style.height = "180px";
		}
	}	
}

function show_map(obj) {
	$('vrn' + obj).style.display = "block"
	$('close_' + obj).style.display = "block";
	$j('#' + obj).slideDown('slow', function() {;document.forms[0].submit();});
}

function close_map(obj) {
	$('close_' + obj).style.display = "none";
	$j('#' + obj).slideUp('slow', function() {$('vrn' + obj).style.display = "none";document.forms[0].submit();});
}

function set_selected(obj) {
	option = $(obj).getElementsByTagName("option");
	for(d = 0; d < option.length; d++) {
		if(option[d].selected == true) {
			$("select_" + obj).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
		}
	}
}

function show_mot_options(pos) {
	Drag.init($("mot_options"));
	top_tmp = find_top($("trip_duration_" + pos));
	left_tmp = find_left($("trip_duration_" + pos));

	$("mot_options").style.top = top_tmp + 'px';
	$("mot_options").style.left = left_tmp + 'px';
	$j('#mot_options').slideDown('slow', function() {$("itdLPxx_show_options_response").value = '1';});
}

function close_mot_options() {
	$j('#mot_options').slideUp('slow', function() {$("itdLPxx_show_options_response").value = '0'; document.forms[0].submit();});
}

function show_hint(pos) {
	Drag.init($("hint_window_" + pos));
	top_tmp = find_top($("hint_" + pos));
	left_tmp = find_left($("hint_" + pos)) - 275;

	$("hint_window_" + pos).style.top = top_tmp + 'px';
	$("hint_window_" + pos).style.left = left_tmp + 'px';
	$j('#hint_window_' + pos).slideDown('slow', function() {});
}

function show_hint2(pos) {
	Drag.init($("hint2_window_" + pos));
	top_tmp = find_top($("hint_" + pos));
	left_tmp = find_left($("hint_" + pos)) - 275;

	$("hint2_window_" + pos).style.top = top_tmp + 'px';
	$("hint2_window_" + pos).style.left = left_tmp + 'px';
	$j('#hint2_window_' + pos).slideDown('slow', function() {});
}

function close_hint(pos) {
	$j('#hint_window_' + pos).slideUp('slow', function() {});
}

function close_hint2(pos) {
	$j('#hint2_window_' + pos).slideUp('slow', function() {});
}

function show_products(Ereignis, name, pos) {
	var div_tmp = name + pos;
	var div = 'show_' + div_tmp;
	var x_y = mouse_pos(Ereignis);
	div_top =  x_y.top - 5;
	if(name == 'change_time_') {
		div_left = x_y.left - 450;
	} else {
		div_left = x_y.left - 10;
	}
	
	if ($(div).innerHTML == "")
		$(div).innerHTML = '<div  class="content_15_1">nicht verfügbar</div>';
		//$(div).style.display = 'none';
	else {
		Drag.init($(div));
		$(div).style.top =  div_top + 'px';
		$(div).style.left = div_left + 'px';
		$j('#' + div).slideDown('slow', function() {});
	}
}

function hide_products(name, pos) {
	var div = 'show_' + name + pos;
	$j('#' + div).slideUp('slow', function() {$(div).style.display = 'none';});
}

function close_products_divs(event) {
  	var targ;
	if (!event) var event = window.event;
	if (event.target) targ = event.target;
	else if (event.srcElement) targ = event.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	
    var divs = document.getElementsByTagName('div');
     
    for (var i = 0, ele; ele = divs[i]; i++) {
        if (ele.id.indexOf('_dep_') > -1) {
			if (targ.nodeName == "TD")
	            ele.style.display = 'none';
        }
        if (ele.id.indexOf('_arr_') > -1) {
			if (targ.nodeName == "TD")
	            ele.style.display = 'none';
        }
        if (ele.id.indexOf('line_') > -1) {
			if (targ.nodeName == "TD")
	            ele.style.display = 'none';
        }
    }
}

function show_tickets(Ereignis, name, pos) {
	var div_tmp = name + pos;
	var div = 'show_' + div_tmp;
	var x_y = mouse_pos(Ereignis);
	div_top =  x_y.top - 5;
	div_left = x_y.left - 325;
	Drag.init($(div));
	$(div).style.top =  div_top + 'px';
	$(div).style.left = div_left + 'px';
	$j('#' + div).slideDown('slow', function() {});
}

function toggle_route(pos) {
	var image = $("route_image_" + pos).src;
	
	//$j('#route_'+ pos).toggle('slow', function() {$j('#route_spacer_'+ pos).toggle('slow', function() {});});

	if (image.indexOf('_1') == -1) {
		$("route_image_" + pos).src = 'images/response/arrow_1.png';
		$("route_image_" + pos).title = 'Details ausblenden';
		$j('#route_' + pos).slideDown('slow', function() {$("route_" + pos).style.display = 'inline';$("route_spacer_" + pos).style.display = 'none';});
		$("printselect" + pos).checked = 'CHECKED';
		$("printselect_" + pos).src = 'images/request/check.png';
	} else {
		$("route_image_" + pos).src = 'images/response/arrow_2.png';
		$("route_image_" + pos).title = 'Details einblenden';
		$j('#route_' + pos).slideUp('slow', function() {$("route_" + pos).style.display = 'none';$("route_spacer_" + pos).style.display = 'inline';});
		$("printselect" + pos).checked = '';
		$("printselect_" + pos).src = 'images/request/no_check.png';
	}
}

function show_routes() {
    var divs = document.getElementsByTagName('div');

    for (var i = 0, ele; ele = divs[i]; i++) {
		pos = ele.id.split("route_");
		if (ele.id.indexOf('route_') > -1) {
			$("route_image_" + pos[1]).src = 'images/response/arrow_1.png';
			$("route_image_" + pos[1]).title = 'Details ausblenden';
		 	$(ele.id).style.display = 'inline';
			$("route_spacer_" + pos[1]).style.display = 'none';	
			$("printselect" + pos[1]).checked = 'CHECKED';
			$("printselect_" + pos[1]).src = 'images/request/check.png';
		}
	}
}

function hide_routes() {
    var divs = document.getElementsByTagName('div');

    for (var i = 0, ele; ele = divs[i]; i++) {
		pos = ele.id.split("route_");
		if (ele.id.indexOf('route_') > -1) {
			$("route_image_" + pos[1]).src = 'images/response/arrow_2.png';
			$("route_image_" + pos[1]).title = 'Details einblenden';
		 	$(ele.id).style.display = 'none';
			$("route_spacer_" + pos[1]).style.display = 'inline';	
			$("printselect" + pos[1]).checked = '';
			$("printselect_" + pos[1]).src = 'images/request/no_check.png';
		}
	}
}

function show_stops() {
    var divs = document.getElementsByTagName('tr');

    for (var i = 0, ele; ele = divs[i]; i++) {
		if (ele.id.indexOf('stop_sequence_') > -1) {
			$(ele.id).style.display = 'inline';
		}
	}
}

function hide_stops() {
    var divs = document.getElementsByTagName('tr');

    for (var i = 0, ele; ele = divs[i]; i++) {
		if (ele.id.indexOf('stop_sequence_') > -1) {
			$(ele.id).style.display = 'none';
		}
	}
}

function show_stop_sequence(pos) {
	var div = 'stop_sequence_' + pos;

 	$j("#" + div).toggle('slow'); 
}

function show_options_response() {
	$("table_wait").style.opacity = "0.2";
	$("table_wait").style.filter = "alpha(opacity = 10)";
	$("wait_options").style.backgroundImage = 'url(images/response/wait.gif)';
	
	top_tmp = find_top($("mot_options"));
	left_tmp = find_left($("mot_options"));
		
	$("itdLPxx_show_options_response").value = 'true:'+ top_tmp + ':' + left_tmp;
	document.forms[0].submit();
}

function show_clear(usage) {
 	$('clear_' + usage).style.display = 'inline';
 	$('mapimage_' + usage).style.position = 'relative';
 	$('mapimage_' + usage).style.left = '-11px';
	$('odvInput_' + usage).focus();
}

function show_clear_2(usage) {
 	$('clear_' + usage).style.display = 'inline';
	$('odvInput_' + usage).focus();
}

function hide_clear(usage) {
 	$('clear_' + usage).style.display = 'none';
 	$('mapimage_' + usage).style.position = 'relative';
 	$('mapimage_' + usage).style.left = '0px';
}

function hide_clear_2(usage) {
 	$('clear_' + usage).style.display = 'none';
}

function clear_setfocus(usage) {
	$('odvInput_' + usage).value='';
	obj = $('odvInput_' + usage);
	setTimeout("obj.focus()" , 100); ;
}

function check(obj) { 
	var image = $(obj).src;
	var input = 'incl' + obj;
	
	if (image.indexOf('no') == -1) {
		$(obj).src = 'images/request/no_check.png'
		$(input).checked = '';
	} else {
		$(obj).src = 'images/request/check.png'
		$(input).checked = 'CHECKED';
	}
}

function check_2(obj) {
	var image = $(obj).src;
	var input = obj.replace('_', '');

	if (image.indexOf('no') == -1) {
		$(obj).src = 'images/request/no_check.png'
		$(input).checked = '';
	} else {
		$(obj).src = 'images/request/check.png'
		$(input).checked = 'CHECKED';
	}
}

function check_print(obj) {
	var image = $(obj).src;
    var divs = document.getElementsByTagName('div');

	if (obj == 'print') {
		$('print').src = 'images/request/radio.png'
	    for (var i = 0, ele; ele = divs[i]; i++) {
    	    if (ele.id.indexOf('hint_') > -1) {
	            ele.style.display = 'block';
    	    }
		}
		$('no_print').src = 'images/request/no_radio.png'
	} else {
		$('print').src = 'images/request/no_radio.png'
	    for (var i = 0, ele; ele = divs[i]; i++) {
    	    if (ele.id.indexOf('hint_') > -1) {
	            ele.style.display = 'none';
    	    }
		}
		$('no_print').src = 'images/request/radio.png'
	}
}

function check_radio_1(obj) {
	if (obj == 'dep') {
		$("dep").src = 'images/request/radio.png'
		$("arr").src = 'images/request/no_radio.png'
		$("input_dep").checked = 'CHECKED';
		$("input_arr").checked = '';
	} else {
		$("dep").src = 'images/request/no_radio.png'
		$("arr").src = 'images/request/radio.png'
		$("input_dep").checked = '';
		$("input_arr").checked = 'CHECKED';
	}
}

function check_radio_2(obj) {
	if (obj == '402') {
		$("402").src = 'images/request/radio.png'
		$("401").src = 'images/request/no_radio.png'
		$("400").src = 'images/request/no_radio.png'
		$("input_402").checked = 'CHECKED';
		$("input_401").checked = '';
		$("input_400").checked = '';
	} else  if (obj == '401') {
		$("402").src = 'images/request/no_radio.png'
		$("401").src = 'images/request/radio.png'
		$("400").src = 'images/request/no_radio.png'
		$("input_402").checked = '';
		$("input_401").checked = 'CHECKED';
		$("input_400").checked = '';
	} else {
		$("402").src = 'images/request/no_radio.png'
		$("401").src = 'images/request/no_radio.png'
		$("400").src = 'images/request/radio.png'
		$("input_402").checked = '';
		$("input_401").checked = '';
		$("input_400").checked = 'CHECKED';
	}
}

function check_radio_3(obj) {
	if (obj == 'presentation_stt') {
		$("presentation_stt").src = 'images/request/radio.png'
		$("presentation_station").src = 'images/request/no_radio.png'
		$("itdLPxx_presentation_stt").value = 'STT';
	} else {
		$("presentation_stt").src = 'images/request/no_radio.png'
		$("presentation_station").src = 'images/request/radio.png'
		$("itdLPxx_presentation_stt").value = 'STATIONTT';
	}
}

function check_radio_4(obj) {
	if (obj == 'mo_fr') {
		$("mo_fr").src = 'images/request/radio.png'
		$("sa").src = 'images/request/no_radio.png'
		$("so").src = 'images/request/no_radio.png'
		$("psParamWeekday_mo_fr").checked = 'CHECKED';
		$("psParamWeekday_sa").checked = '';
		$("psParamWeekday_so").checked = '';
	} else  if (obj == 'sa') {
		$("mo_fr").src = 'images/request/no_radio.png'
		$("sa").src = 'images/request/radio.png'
		$("so").src = 'images/request/no_radio.png'
		$("psParamWeekday_mo_fr").checked = '';
		$("psParamWeekday_sa").checked = 'CHECKED';
		$("psParamWeekday_so").checked = '';
	} else {
		$("mo_fr").src = 'images/request/no_radio.png'
		$("sa").src = 'images/request/no_radio.png'
		$("so").src = 'images/request/radio.png'
		$("psParamWeekday_mo_fr").checked = '';
		$("psParamWeekday_sa").checked = '';
		$("psParamWeekday_so").checked = 'CHECKED';
	}
}

function check_value() {
	var mapusage = document.eingabe.itdLPxx_mapusage.value;
	if(! (mapusage == 'stt' || mapusage == 'ttb' || mapusage == 'rop' || mapusage == 'dm' || mapusage == 'ss')) {
		if (document.eingabe.nameState_origin.value == 'empty') {
			var nameorigin = document.eingabe.name_origin.value;
		}
		if (document.eingabe.nameState_destination.value  == 'empty') {
			var namedestination = document.eingabe.name_destination.value;
		}
		if ($("odvInput_via")) {
			if (document.eingabe.nameState_via.value  == 'empty') {
				var namevia = document.eingabe.name_via.value;
			}
		}
		if (nameorigin == 'Ort+Haltestelle / Straße Nr. / interessanter Ort') {
			document.eingabe.name_origin.value = '';
		}
		if (namedestination == 'Ort+Haltestelle / Straße Nr. / interessanter Ort') {
			document.eingabe.name_destination.value = '';
		}		
		if ($("odvInput_via")) {
			if (namevia == 'Ort+Haltestelle / Straße Nr. / interessanter Ort') {
				document.eingabe.name_via.value = '';
			}
		}
	} else if (document.eingabe.itdLPxx_mapusage.value == 'ttb') {
		if (document.eingabe.nameState_ttb.value == 'empty') {
			var namettb = document.eingabe.name_ttb.value;
		}
		if (namettb == 'Ort+Haltestelle / Straße Nr. / interessanter Ort') {
			document.eingabe.name_ttb.value = '';
		}
	} else if (document.eingabe.itdLPxx_mapusage.value == 'rop') {
		if (document.eingabe.nameState_rop.value == 'empty') {
			var namerop = document.eingabe.name_rop.value;
		}
		if (namerop == 'Ort+Haltestelle / Straße Nr. / interessanter Ort') {
			document.eingabe.name_rop.value = '';
		}
	} else if (document.eingabe.itdLPxx_mapusage.value == 'stt') {
		if (document.eingabe.nameState_stt.value == 'empty') {
			var namestt = document.eingabe.name_stt.value;
		}
		if (namestt == 'Ort+Haltestelle / Straße Nr. / interessanter Ort') {
			document.eingabe.name_stt.value = '';
		}
	} else if (document.eingabe.itdLPxx_mapusage.value == 'dm') {
		if (document.eingabe.nameState_dm.value == 'empty') {
			var namedm = document.eingabe.name_dm.value;
		}
		if (namedm == 'Ort+Haltestelle / Straße Nr. / interessanter Ort') {
			document.eingabe.name_dm.value = '';
		}
	} else if (document.eingabe.itdLPxx_mapusage.value == 'ss') {
		if (document.eingabe.nameState_ss.value == 'empty') {
			var namess = document.eingabe.name_ss.value;
		}
		if (namess == 'Ort+Haltestelle / Straße Nr. / interessanter Ort') {
			document.eingabe.name_ss.value = '';
		}
	} 	
}

function submit_date_time(usage) {
	var mydate = $('date').value;
	var mytime = $('time').value;

	var date = new Date();
	var hours = date.getHours();
	var minutes = date.getMinutes();

	hours =((hours < 10) ? "0" : "") + hours;
	minutes =((minutes < 10) ? "0" : "") + minutes;

	splitString = mytime.split(":");
	hour = splitString[0];
	minute = splitString[1];

	if (mytime.length != '5' && mytime.indexOf(':') < 1) {
		if (mytime.length == '4') {
			$('time').value = mytime.substr(0,2) + ":" + mytime.substr(2,2);
		} else if (mytime.length == '3') {
			$('time').value = "0" + mytime.substr(0,1) + ":" + mytime.substr(1,2);
		} else if (mytime.length == '2') {
			$('time').value = mytime.substr(0,2) + ":00";
		} else if (mytime.length == '1') {
			$('time').value = "0" + mytime.substr(0,1) + ":00";
		} else {
			alert("Uhrzeit bitte im Format hh:mm eingeben.");
			$('time').value = hours + ":" + minutes;
			return false;
		}
	} else if (mytime.indexOf(':') < 1) {
		alert("Uhrzeit bitte im Format hh:mm eingeben.");
		$('time').value = hours + ":" + minutes;
		return false;
	} else if (isNaN(hour) || isNaN(minute)) {
		alert("Uhrzeit bitte im Format hh:mm eingeben.");
		$('time').value = hours + ":" + minutes;
		return false;
	}
	
	mytime = $('time').value;
	splitString = mytime.split(":");
	hour = splitString[0];
	minute = splitString[1];

	splitdate = mydate.split(".");
	splittime = mytime.split(":");

	if (parseInt(hour) > '23') {
		alert("Uhrzeit nicht korrekt, bitte überprüfen Sie Ihre Eingabe.");
		$('time').value = hours + ":" + minutes;
		return false;
	}

	if (parseInt(minute) > '59') {
		alert("Uhrzeit nicht korrekt, bitte überprüfen Sie Ihre Eingabe.");
		$('time').value = hours + ":" + minutes;
		return false;
	}

	if (mydate.length == '12') {
		dayefa =splitdate[0].split(", ");
		if (dayefa[1])
			document.eingabe.itdDateDay.value=dayefa[1];
		else
			document.eingabe.itdDateDay.value=splitdate[0];
		document.eingabe.itdDateMonth.value=splitdate[1];
		document.eingabe.itdDateYear.value=splitdate[2];
		document.eingabe.itdTimeHour.value=splittime[0];
		document.eingabe.itdTimeMinute.value=splittime[1];
	} else if (mydate.length == '8') {
		splitdate_2 = mydate.split(".");
		document.eingabe.itdDateDay.value=splitdate_2[0];
		document.eingabe.itdDateMonth.value=splitdate_2[1];
		document.eingabe.itdDateYear.value=splitdate_2[2];
		document.eingabe.itdTimeHour.value=splittime[0];
		document.eingabe.itdTimeMinute.value=splittime[1];
	} else if (mydate.length == '10') {
		splitdate_2 = mydate.split(".");
		document.eingabe.itdDateDay.value=splitdate_2[0];
		document.eingabe.itdDateMonth.value=splitdate_2[1];
		document.eingabe.itdDateYear.value=splitdate_2[2];
		document.eingabe.itdTimeHour.value=splittime[0];
		document.eingabe.itdTimeMinute.value=splittime[1];
	}
	if (!usage)
		document.forms[0].submit();
}

function submit_date_time_ps() {
	if ($('date_ps').value == 'TT.MM.JJJJ') {
		split_time_arr_from = $('time_arr_from').value.split(":");
		$('itdTimeHour_arrFrom').value = split_time_arr_from[0]; 
		$('itdTimeMinute_arrFrom').value = split_time_arr_from[1];

		split_time_arr_to = $('time_arr_to').value.split(":");
		$('itdTimeHour_arrTo').value = split_time_arr_to[0]; 
		$('itdTimeMinute_arrTo').value = split_time_arr_to[1];		
		 
		split_time_dep_from = $('time_dep_from').value.split(":");
		$('itdTimeHour_depFrom').value = split_time_dep_from[0]; 
		$('itdTimeMinute_depFrom').value = split_time_dep_from[1];

		split_time_dep_to = $('time_dep_to').value.split(":");
		$('itdTimeHour_depTo').value = split_time_dep_to[0]; 
		$('itdTimeMinute_depTo').value = split_time_dep_to[1];		
		return;
	} else {
		split_time_arr_from = $('time_arr_from').value.split(":");
		$('itdTimeHour_arrFrom').value = split_time_arr_from[0]; 
		$('itdTimeMinute_arrFrom').value = split_time_arr_from[1];

		split_time_arr_to = $('time_arr_to').value.split(":");
		$('itdTimeHour_arrTo').value = split_time_arr_to[0]; 
		$('itdTimeMinute_arrTo').value = split_time_arr_to[1];		
		 
		split_time_dep_from = $('time_dep_from').value.split(":");
		$('itdTimeHour_depFrom').value = split_time_dep_from[0]; 
		$('itdTimeMinute_depFrom').value = split_time_dep_from[1];

		split_time_dep_to = $('time_dep_to').value.split(":");
		$('itdTimeHour_depTo').value = split_time_dep_to[0]; 
		$('itdTimeMinute_depTo').value = split_time_dep_to[1];		

		splitdate = $('date_ps').value.split(".");
		$('psParamSampleDate').value = splitdate[2] + splitdate[1] + splitdate[0];
	}
}

function trip_retoure() {
	$("itdLPxx_print_view").value = '0';
	var origin = convert_input(escape($("odvInput_origin").value));
	var name_origin = convert_input(escape($("nameValue_origin").value));
	var name_state_origin = $("nameState_origin").value;
	var place_value_origin = $("placeValue_origin").value;
	var place_state_origin = $("placeState_origin").value;
	
	var destination = convert_input(escape($("odvInput_destination").value));
	var name_destination = convert_input(escape($("nameValue_destination").value));
	var name_state_destination = $("nameState_destination").value;
	var place_value_destination = $("placeValue_destination").value;
	var place_state_destination = $("placeState_destination").value;

	$("odvInput_origin").value = unescape(destination);
	$("nameValue_origin").value = unescape(name_destination);
	$("nameState_origin").value = name_state_destination;
	$("placeValue_origin").value = place_value_destination;
	$("placeState_origin").value = place_state_destination;
	
	$("odvInput_destination").value = unescape(origin);
	$("nameValue_destination").value = unescape(name_origin);
	$("nameState_destination").value = name_state_origin;
	$("placeValue_destination").value = place_value_origin;
	$("placeState_destination").value = place_state_origin;

	document.forms[0].submit();
}

function check_key(event) {
	if (!event)
    	event = window.event;
  	if (event.which) {
    	code = event.which;
  	} else if (event.keyCode) {
    	code = event.keyCode;
  	}
	
	var usage = document.body.id;

	if (!usage) {
		return;
	}
	
	var focus = $j(document.activeElement.id);

	switch (code)
	{
		case 13:
			if (usage == 'body_request') {
				check_value();
				submit_date_time(); 
				document.forms[0].submit();
			} else if (usage == 'body_response') {
				convert_input_2();
				submit_date_time(); 
				//document.forms[0].submit();
			} else if (usage == 'body_ps') {
				$('body_ps').className = 'body_2';
				check_value();
				submit_date_time_ps();
				document.forms[0].submit();
			} else if (usage == 'body_ttb') {
				$('body_ttb').className = 'body_2';
				check_value();
				document.forms[0].submit();
			} else if (usage == 'body_rop') {
				$('body_rop').className = 'body_2';
				check_value();
				document.forms[0].submit();
			} else if (usage == 'body_stt') {
				$('body_stt').className = 'body_2';
				check_value();
				document.forms[0].submit();
			} else if (usage == 'body_dm') {
				check_value();
				document.forms[0].submit();
			} else if (usage == 'body_pda_ps') {
				$('body_pda_ps').className = 'body_2';
				check_value();
				submit_date_time_ps();
				document.forms[0].submit();
			} else if (usage == 'body_pda_dm') {
				$('body_pda_dm').className = 'body_2';
				check_value();
				document.forms[0].submit();
			}
		break;
		case 113:
			if (usage == 'body_request') {
				location.href='XSLT_TRIP_REQUEST2?';
			} else if (usage == 'body_response') {
				location.href='XSLT_TRIP_REQUEST2?';
			} else if (usage == 'body_print') {
				location.href='XSLT_TRIP_REQUEST2?';
			} else if (usage == 'body_ps' || usage == 'body_ps_download') {
				location.href='XSLT_PS_REQUEST2?';
			} else if (usage == 'body_ttb' || usage == 'body_ttb_download') {
				location.href='XSLT_TTB_REQUEST?';
			} else if (usage == 'body_rop' || usage == 'body_rop_download') {
				location.href='XSLT_ROP_REQUEST?';
			} else if (usage == 'body_stt' || usage == 'body_stt_download') {
				location.href='XSLT_STT_REQUEST?';
			} else if (usage == 'body_dm') {
				location.href='XSLT_DM_REQUEST?';
			} else if (usage == 'body_pda_ps' || usage == 'body_pda_ps_download') {
				location.href='XSLT_PDA_PS_REQUEST?';
			} else if (usage == 'body_pda_dm' || usage == 'body_pda_dm_download') {
				location.href='XSLT_PDA_DM_REQUEST?';
			}
		break;
		case 107:
			if (usage == 'body_response') {
				if (event.shiftKey) {
					show_stops();
				} else {
					show_routes();
				}
			}
		break;
		case 109:
			if (usage == 'body_response') {
				if (event.shiftKey) {
					hide_stops();
				} else {
					hide_routes();
				}
			}
		break;
		case 38:
			if (usage == 'body_response' && event.shiftKey) {
				document.forms[0].command.value='tripPrev';
				document.forms[0].submit();
			} else if (focus.selector == 'date') {
				dateUpDown('up');
			} else if (focus.selector == 'time') {
				timeUpDown('up', 'time');
			}
		break;
		case 40:
			if (usage == 'body_response' && event.shiftKey) {
				document.forms[0].command.value='tripNext';
				document.forms[0].submit();
			} else if (focus.selector == 'date') {
				dateUpDown('down');
			} else if (focus.selector == 'time') {
				timeUpDown('down', 'time');
			}
		break;
		case 88:
			if (mouseDown == 1 && event.shiftKey) {
				SessionID = document.eingabe.sessionID.value;
				urlxml = "?sessionID=" + SessionID + "&command=formatToXML";
				showxml = window.open(urlxml,"showxml","width=1024,height=768, scrollbars"); 
				mouseDown = 0;
			}
		break;
		case 67:
			if (mouseDown == 1 && event.shiftKey) {
				load_cookie();
			}
		break;
	}
	
	cheat += String.fromCharCode(code);
	if (cheat == 'IDDQD' && usage == 'body_request') {
		cheat = '';
		check_value();
		submit_date_time('trip');
		document.eingabe.execInst.value='verifyOnly';
		document.eingabe.itdLPxx_showMap.value='yes';
		document.forms[0].itdLPxx_mdvMap.value='origin';
		show_map('Map_origin');
	} else if (cheat == 'IDKFA') {
		cheat = '';
		check_value();
		submit_date_time('trip');
		document.eingabe.execInst.value='verifyOnly';
		document.eingabe.itdLPxx_showMap.value='yes';
		document.forms[0].itdLPxx_mdvMap.value='destination';
		show_map('Map_destination');
	}
//	alert(code);
}

function print_routes() {
	var input = document.getElementsByName('tripSelector');
	var indices = 'print:';
	
    for (var i = 0, ele; ele = input[i]; i++) {
		if (input[i].checked) {
			tmp = input[i].id.split("printselect");
			indices += tmp[1] + ':';
		}
	} 
	
	if (indices == 'print:') {
		alert("Keine Fahrt für den Ausdruck markiert, bitte zuvor Fahrt markieren...");
		return;
	}
	
	$('itdLPxx_print_view').value = '1';
	$('itdLPxx_print_indices').value = indices;
	$('nameValue_origin').value = $('odvInput_origin').value;
	$('nameValue_destination').value = $('odvInput_destination').value;
	$('nameState_origin').value = 'identified';
	$('nameState_destination').value = 'identified';
	$('command').value = 'tripNext';
	
	document.forms[0].submit();
}

function makelink_db(input_string) {
	var salt = "aPl$1&4.E;,#lxiK";
	var url;
	splitString = input_string.split(":");

	sstart = splitString[0];
	sziel = splitString[1];
	swaben = splitString[2];
	sticket = splitString[3];
	sprice = splitString[4];
	sps = splitString[5];

	input_string_salt = sstart + sziel + swaben + sticket + sprice + sps + salt;
	hash = hex_md5(input_string_salt);
//	alert (input_string);
//	alert (input_string_salt);
//	alert (hash);
	
	url = "https://www.bahnabo.de/vrn/exchange.php?Start=" + sstart + "&Ziel=" + sziel + "&Waben=" + swaben + "&Ticket=" + sticket + "&Preis=" + sprice + "&Preisstufe=" + sps + "&h=" + hash;
	newWindow = window.open(url, 'NewWindow', 'toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=800,height=600,');
}

function odvSuggest(value, usage) {
	if(value.length > 3) {
		var _params = { 
			language: 'de',
			locationServerActive: '1',
			anyObjFilter_sf: '126',
			anyMaxSizeHitList: '550',
			anyHitListReductionLimit: '20',
			reducedAnyPostcodeObjFilter_sf: '64',
			reducedAnyTooManyObjFilter_sf: '2',
			reducedAnyWithoutAddressObjFilter_sf: '103',
			itdLPxx_checkText: value,
			itdLPxx_usage: usage,
			type_sf: 'stop',
			name_sf: value
		};
		var ajax = new Ajax.Request('/lite/XSLT_STOPFINDER_REQUEST', { method: 'post', parameters: _params, onComplete: odvSuggest_onAjaxComplete });
	} else {
		$('odvSuggest_' + usage).innerHTML = '';
	}
}

function odvSuggest_onAjaxComplete(response) {
	var json = null;
 	var efa = null;
	var inner = '';

	// Check if we need to use the prototype lib.
 	if (response && response.responseText) {
 		json = response.responseText;
 	// Otherwise use jQuery lib.
 	} else if (response) {
 		json = response;
 	}
 	
 	eval('efa = ' + json + ';'); 	

	var usage = efa.parameters[1].value;
	$('odvSuggest_' + usage).innerHTML = '';

	if(!efa.stopFinder) {
		return false;
	}
	
	var length = efa.stopFinder.length
	
	if(efa.stopFinder.point) {
		length = 1;
	}
	
	// sort result list if more than one hit 
	if(length > 1) {
		efa.stopFinder.sort(typeComparison);
	}
		
	for(i=0;i < length; i ++) {
		var point =  efa.stopFinder[i] || efa.stopFinder.point;
		
		if(point.type!='loc') {
		
			var ptRef =  point.ref;
			
			if(point.type=='street' && !ptRef.coords) {
				break;
			}

			 if(!ptRef.coords) {
				ptRef.coords='0,0';
			}  
		
			var name = '';
			var type= '';
			var add= '';
			var txtPlace = '';
			
			if(point.ref.place) {
				txtPlace = point.ref.place + ', ';
			}
			//var txt = txtPlace + point.name;
			var txt = point.name;
			var place = "\'" + point.ref.omc + ':' + point.ref.placeID + "\'";
			var ptCoords =  ptRef.coords.split(',');
			
			switch(point.type)
			{
				case 'stop': 
					name = "\'" +ptRef.id + "\'" ; 
					type = "\'stopID\'"; 
					break;
				case 'poi': 
					name = "\'" +ptRef.id + "\'" ; 
					type = "\'poiID\'"; 
					break;
				case 'street':
					name = "\'streetID:" +ptRef.id + '::' + ptRef.omc + "\'" ; 
					type = "\'address\'"; 
					break;
				case 'address': 
					name = "\'"  +ptCoords[0] + ':' +ptCoords[1]  + ":" + mapNameDef + ":" + replaceSigns(txt) + "\'"; 
					type = "\'coord\'";
					break;
				default: 
					name = "\'"  +ptCoords[0] + ':'+ptCoords[1]  + ":" + mapNameDef + ":" + replaceSigns(txt) + "\'"; 
					type = "\'coord\'";
					break;
			}
			
			var href ='javascript:document.forms[0].nameInfo_' + usage +'.value=' + name +';'
				href += 'document.forms[0].typeInfo_' + usage +'.value=' + type+ ';'
				href +='document.forms[0].placeInfo_' + usage +'.value=' + place +';'
				href +='check_value();submit_date_time();document.forms[0].submit();'
			
			inner += '<a style="color:#000000;text-decoration:none;" href=' + href +'>' + add +  txt + '</a><br>';
			$('odvSuggest_' + usage).update(inner);
			$('odvSuggest_' + usage).innerHTML;
			input_top = find_top($('odvInput_' + usage));
			input_top =input_top + 20;
			input_left = find_left($('odvInput_' + usage));
			input_left =input_left + 1;
			$('odvSuggest_' + usage).style.top = input_top + 'px';
			$('odvSuggest_' + usage).style.left = input_left + 'px';
			$('odvSuggest_' + usage).style.overflow = 'auto';
			$('odvSuggest_' + usage).style.display = 'block';
		}
	}
}

function close_odv_divs() {
	$j('#odvSuggest_origin').slideUp('slow', function() {});
	$j('#odvSuggest_destination').slideUp('slow', function() {});
	$j('#odvSuggest_via').slideUp('slow', function() {});
}

function typeComparison(a, b) {
	if(a.type == 'stop') {
		a.sortPos = 1
	}
	else if(a.type == 'poi') {
		a.sortPos = 2
	}
	else {
		a.sortPos = 3
	} 
	
	if(b.type == 'stop') {
		b.sortPos = 1
	}
	else if(b.type == 'poi') {
		b.sortPos = 2
	}
	else {
		b.sortPos = 3
	} 
   return a.sortPos > b.sortPos; 
}

function replaceSigns(txt) {
	txt = txt.replace(/Ãœ/g, "&#220;");
	txt = txt.replace(/Ã–/g, "&#246;");
	txt = txt.replace(/Ã„/g, "&#196;"); 
	txt = txt.replace(/Ã¼/g, "&#252;");
	txt = txt.replace(/Ã¶/g, "&#246;");
	txt = txt.replace(/Ã¤/g, "&#228;"); 
	txt = txt.replace(/ÃŸ/g, "&#223;"); 
	txt = txt.replace(/ /g, "&#160;");  
	return txt;
}

function find_left(obj) {
	var Pos_t = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			Pos_t += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}	
	else if (obj.x)
		Pos_t += obj.x;
	return Pos_t;
}

function find_top(obj) {
	var Pos_l = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			Pos_l += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
	Pos_l += obj.y;
	return Pos_l;
}

function mouse_pos(e) {
	if(!e) e = window.event;
	var body = (window.document.compatMode && window.document.compatMode == "CSS1Compat") ? 
	window.document.documentElement : window.document.body;
	return {
	// Position im Dokument
	top: e.pageY ? e.pageY : e.clientY + body.scrollTop - body.clientTop,
	left: e.pageX ? e.pageX : e.clientX + body.scrollLeft  - body.clientLeft
	};
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds) {
      break;
    }
  }
}


//******************************************************************
//****       help functions for the layout						****
//******************************************************************

var Drag = {
	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.style.cursor = 'move';
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};

/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s) { return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s) { return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s) { return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test() {
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len) {
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16) {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);
}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t) {
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}

function md5_ff(a, b, c, d, x, s, t) {
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}

function md5_gg(a, b, c, d, x, s, t) {
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}

function md5_hh(a, b, c, d, x, s, t) {
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}

function md5_ii(a, b, c, d, x, s, t) {
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data) {
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++) {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y) {
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt) {
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str) {
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin) {
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray) {
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++) {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray) {
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3) {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++) {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

var enc64List, dec64List;
// Load the lookup arrays once
function initBase64() {
    enc64List = new Array();
    dec64List = new Array();
    var i;
    for (i = 0; i < 26; i++) {
        enc64List[enc64List.length] = String.fromCharCode(65 + i);
    }
    for (i = 0; i < 26; i++) {
        enc64List[enc64List.length] = String.fromCharCode(97 + i);
    }
    for (i = 0; i < 10; i++) {
        enc64List[enc64List.length] = String.fromCharCode(48 + i);
    }
    enc64List[enc64List.length] = "+";
    enc64List[enc64List.length] = "/";
    for (i = 0; i < 128; i++) {
        dec64List[dec64List.length] = -1;
    }
    for (i = 0; i < 64; i++) {
        dec64List[enc64List[i].charCodeAt(0)] = i;
    }
}

function base64Encode(str) {
    var c, d, e, end = 0;
    var u, v, w, x;
    var ptr = -1;
    var input = str.split("");
    var output = "";
    while(end == 0) {
        c = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : 
            ((end = 1) ? 0 : 0);
    	if (c == 160)
    		c = 32;
        d = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : 
            ((end += 1) ? 0 : 0);
    	if (d == 160)
    		d = 32;
        e = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : 
            ((end += 1) ? 0 : 0);
    	if (e == 160)
    		e = 32;
        u = enc64List[c >> 2];
        v = enc64List[(0x00000003 & c) << 4 | d >> 4];
        w = enc64List[(0x0000000F & d) << 2 | e >> 6];
        x = enc64List[e & 0x0000003F];
        
        // handle padding to even out unevenly divisible string lengths
        if (end >= 1) {x = "=";}
        if (end == 2) {w = "=";}
        
        if (end < 3) {output += u + v + w + x;}
    }
    // format for 76-character line lengths per RFC
    var formattedOutput = "";
    var lineLength = 76;
    while (output.length > lineLength) {
      formattedOutput += output.substring(0, lineLength) + "\n";
      output = output.substring(lineLength);
    }
    formattedOutput += output;
    return formattedOutput;
}

function base64Decode(str) {
    var c=0, d=0, e=0, f=0, i=0, n=0;
    var input = str.split("");
    var output = "";
    var ptr = 0;
    do {
        f = input[ptr++].charCodeAt(0);
        i = dec64List[f];
        if ( f >= 0 && f < 128 && i != -1 ) {
            if ( n % 4 == 0 ) {
                c = i << 2;
            } else if ( n % 4 == 1 ) {
                c = c | ( i >> 4 );
                d = ( i & 0x0000000F ) << 4;
            } else if ( n % 4 == 2 ) {
                d = d | ( i >> 2 );
                e = ( i & 0x00000003 ) << 6;
            } else {
                e = e | i;
            }
            n++;
            if ( n % 4 == 0 ) {
                output += String.fromCharCode(c) + 
                          String.fromCharCode(d) + 
                          String.fromCharCode(e);
            }
        }
    }
    while (typeof input[ptr] != "undefined");
    output += (n % 4 == 3) ? String.fromCharCode(c) + String.fromCharCode(d) : 
              ((n % 4 == 2) ? String.fromCharCode(c) : "");
    return output;
}

function get_caret_pos (ctrl) {
	var CaretPos = 0;	// IE Support
	if (document.selection) {
	ctrl.focus ();
		var Sel = document.selection.createRange ();
		Sel.moveStart ('character', -ctrl.value.length);
		CaretPos = Sel.text.length;
	}
	// Firefox support
	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
		CaretPos = ctrl.selectionStart;
	return (CaretPos);
}

function set_caret_pos(ctrl, pos) {
  	if(ctrl.setSelectionRange) {
		ctrl.focus();
		ctrl.setSelectionRange(pos,pos);
	}
	else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

function set_cookie(stop) {
	var date = new Date();
	var expire = date.getTime() + (56 * 24 * 60 * 60 * 1000);
	var i=0  
   	var suche = "Haltestellen="
   	var cookie_val;
   	if (stop.indexOf("aus Karte") > 1)
   		return false;
   	stop = base64Encode(stop);
   	while (i<document.cookie.length) {
    	if (document.cookie.substring(i, i+suche.length)==suche) {
        	var ende = document.cookie.indexOf(";", i+suche.length)
         	ende = (ende>-1) ? ende : document.cookie.length
         	var cookie = document.cookie.substring(i+suche.length, ende)
      	}
		i++
   	}
	
	if (cookie)	{
		var arr_cookie = cookie.split("$");
		if (arr_cookie.length < 11) {
			var new_arr_cookie = [];
			for (var i = 0; i < arr_cookie.length; i++) {
				var cur_value = arr_cookie[i];
				var next_value = arr_cookie[i+1];
				if ((cur_value != next_value) && (cur_value != "")) 
					new_arr_cookie.push(cur_value);
		 	}
		} else {
			var new_arr_cookie = [];
			for (var i = 1; i < arr_cookie.length; i++) {
				var cur_value = arr_cookie[i];
				var next_value = arr_cookie[i+1];
				if ((cur_value != next_value) && (cur_value != ""))
					new_arr_cookie.push(cur_value);
			}
		}
	}

	date.setTime(expire);
	if (cookie)	{	
		cookie_val = suche;
		for (var i = 0; i < new_arr_cookie.length; i++)	{
			if (stop != new_arr_cookie[i])
				cookie_val = cookie_val + new_arr_cookie[i] + "$";
		}
		cookie_val = cookie_val + stop + "$";
	} else {
		cookie_val = suche + stop + "$";
	}
	document.cookie = cookie_val + "; expires=" + date.toGMTString();
}

function load_cookie() {
	var i=0  
   	var suche = "Haltestellen="
   	while (i<document.cookie.length) {
    	if (document.cookie.substring(i, i+suche.length)==suche) {
        	var ende = document.cookie.indexOf(";", i+suche.length)
         	ende = (ende>-1) ? ende : document.cookie.length
         	var cookie = document.cookie.substring(i+suche.length, ende)
      	}
		i++
   	}
	alert(base64Decode(cookie));	
}

function show_cookie(usage) {
	var i=0  
   	var suche = "Haltestellen="
   	var div_innerHTML = ''
   	while (i<document.cookie.length) {
    	if (document.cookie.substring(i, i+suche.length)==suche) {
        	var ende = document.cookie.indexOf(";", i+suche.length)
         	ende = (ende>-1) ? ende : document.cookie.length
         	var cookie = document.cookie.substring(i+suche.length, ende)
      	}
		i++
   	}

	if (cookie)	{	
		var div_cookie = cookie.split('$');
//		for (i=0; i < div_cookie.length - 1; i++) {
		for (i = div_cookie.length - 2; i > -1; i--) {
			div_tmp = "<div onmouseout=this.className='div_6_9_1'; onmouseover=this.className='div_6_9_2'; class='div_6_9_1' onclick=$('odvInput_" + usage + "').value=";
			div_tmp_2 = base64Decode(div_cookie[i]);
			div_tmp_2 = div_tmp_2.replace(/,/g, "%2C");
			div_tmp_2 = div_tmp_2.replace(/ /g, "%20");
			div_innerHTML += div_tmp + "'" + div_tmp_2 + "';decode_input('" + usage + "');>" + base64Decode(div_cookie[i]) + "</div>";
		}	
		
		div_innerHTML += "<div style='border-top: 1px solid #E4E4E4; margin-top: 3px;'/>"; 
		div_innerHTML += "<div onmouseout=this.className='div_6_9_3'; onmouseover=this.className='div_6_9_4'; class='div_6_9_3' onclick='delete_cookie()'><i>Liste löschen...</i></div>"; 
		$("cookie_" + usage).innerHTML = div_innerHTML;
	   	$("cookie_" + usage).style.display = 'block';
	}
}

function delete_cookie() {
  var date = new Date();
  var expire = -1; //minus 1 millisekunden
  var verfall = new Date(date.getTime() - expire);
  document.cookie = "Haltestellen=delete; expires=" + verfall.toGMTString() + ";";
	
}
function decode_input(usage) {
	var input = $("odvInput_" + usage).value;
	input = input.replace(/%2C/g, ",");
	input = input.replace(/%20/g, " ");
	$("odvInput_" + usage).value = input;
	$("cookie_" + usage).style.display = 'none';
}

function clear_div_cookie(usage) {
	if ($(usage))
		$(usage).style.display = 'none';
}

function convert_input(input) {
	input = input.replace(/%2C/g, ","); 
	input = input.replace(/%A0/g, " "); 
	return input;
}

function convert_input_2() {
	if ($("odvInput_origin")) {
		input = $("odvInput_origin").value;
		input = escape(input);
		input =	input.replace(/%2C/g, ","); 
		input = input.replace(/%A0/g, " "); 
		input = unescape(input);
		$("odvInput_origin").value = input;
	}

	if ($("odvInput_destination")) {
		input = $("odvInput_destination").value;
		input = escape(input);
		input =	input.replace(/%2C/g, ","); 
		input = input.replace(/%A0/g, " "); 
		input = unescape(input);
		$("odvInput_destination").value = input;
	}
}
