//****************************************************************//
//****       CSS Layout-Datei             (c) VRN GmbH        ****//
//****       für VRN Fahrplanauskunft      15.01.2008         ****//
//****************************************************************//

var dFocus = false;
var hFocus = false;
var mFocus = false;

function hour2(upOrDown)
 { 
	var hour;
	var minute;
	var tag;
	var monat;
	var jahr;

	date = document.eingabe.date.value;
	hour = document.eingabe.itdTimeHour.value;
	minute = document.eingabe.itdTimeMinute.value;

	splitString = date.split(".");

	tag = splitString[0];
	monat = splitString[1];
	jahr = splitString[2];

	var jahrIntWert = parseInt(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, hour, minute);
	var millisecunden = heute.getTime();

	if (upOrDown == 'up_hour')
	{ millisecunden = millisecunden + (60*60*1000); }

	if (upOrDown == 'down_hour' )
	{ millisecunden = millisecunden - (60*60*1000); }

	if (upOrDown == 'up_minute')
	{ millisecunden = millisecunden + (60*1000); }

	if (upOrDown == 'down_minute' )
	{ millisecunden = millisecunden - (60*1000); }

	heute.setTime(millisecunden);

	hour = heute.getHours();
	if (hour >= 0 && hour < 10)
	{ 
		hour = "0"+hour; 
	}

	minute = heute.getMinutes();
	if (minute >= 0 && minute < 10)
	{ minute = "0"+minute; }
	
	document.eingabe.itdTimeHour.value = hour;
	document.eingabe.itdTimeMinute.value = minute;
}

function set_date2()
{
	var day, month, year;
	
	if (document.eingabe.action != 'XSLT_PS_REQUEST2')
	{
		day = document.eingabe.itdDateDay.value;
		month = document.eingabe.itdDateMonth.value;
		year = document.eingabe.itdDateYear.value;

		timeString = day + "." + month + "." + year;
	//	alert(timeString);
		document.eingabe.date.value = timeString;
		}

}

function submit_date2()
{
	var mydate = document.eingabe.date.value;

	splitString = mydate.split(".");

	document.eingabe.itdDateDay.value=splitString[0];
	document.eingabe.itdDateMonth.value=splitString[1];
	document.eingabe.itdDateYear.value=splitString[2];
//	alert(splitString);
}

function setkey() 
{
//
}

document.onkeydown = findTaste;

function findTaste(Ereignis) 
{
  if (!Ereignis)
    Ereignis = window.event;
  if (Ereignis.which) {
    Tastencode = Ereignis.which;
  } else if (Ereignis.keyCode) {
    Tastencode = Ereignis.keyCode;
  }
	findkey(Tastencode);
}

function findkey(Tastencode)
{
//debugger;
	if ((Tastencode == 38) && (dFocus == true))
	{
		dateUpDown('up');
	}

	if ((Tastencode == 40) && (dFocus == true))
	{
		dateUpDown('down');
	}

	if ((Tastencode == 38) && (hFocus == true))
	{
		hour('up_hour');
	}
	
	if ((Tastencode == 40) && (hFocus == true))
	{
		hour('down_hour');
	}

	if ((Tastencode == 38) && (mFocus == true))
	{
		hour('up_minute');
	}
	
	if ((Tastencode == 40) && (mFocus == true))
	{
		hour('down_minute');
	}
	if ((Tastencode == 13) && ((document.eingabe.itdLPxx_mapusage.value == "Trip") || (document.eingabe.itdLPxx_mapusage.value == "dm")))
	{
		if (document.forms[0].itdLPxx_options.value == 0)
		{
			check_value_2();
		} else {
			check_value();
		}
		submit_date();
		setTimeout("document.eingabe.submit()",500);
	}
	if ((Tastencode == 13) && (document.eingabe.itdLPxx_mapusage.value == "ps_Trip"))
	{
		check_value_2();
		setsampledate();
		document.eingabe.submit();
	}
	if ((Tastencode == 13) && (document.eingabe.itdLPxx_mapusage.value == "car_Trip"))
	{
		check_value_2();
		document.eingabe.submit();
	}
	if ((Tastencode == 113) && (document.eingabe.itdLPxx_mapusage.value == "Trip"))
	{
		location.href="XSLT_TRIP_REQUEST2?language=de";
	}
	if ((Tastencode == 13) && ((document.eingabe.itdLPxx_mapusage.value == "stt") || (document.eingabe.itdLPxx_mapusage.value == "ttb") || (document.eingabe.itdLPxx_mapusage.value == "rop") || (document.eingabe.itdLPxx_mapusage.value == "ss")))
	{
		check_value();
		document.eingabe.submit();
	}
	if ((Tastencode == 113) && (document.eingabe.itdLPxx_mapusage.value == "stt"))
	{
		location.href="XSLT_STT_REQUEST?language=de";
	}
	if ((Tastencode == 113) && (document.eingabe.itdLPxx_mapusage.value == "ttb"))
	{
		location.href="XSLT_TTB_REQUEST?language=de";
	}
	if ((Tastencode == 113) && (document.eingabe.itdLPxx_mapusage.value == "rop"))
	{
		location.href="XSLT_TTB_REQUEST?language=de";
	}
	if ((Tastencode == 113) && (document.eingabe.itdLPxx_mapusage.value == "dm"))
	{
		location.href="XSLT_DM_REQUEST?language=de";
	}
	if ((Tastencode == 113) && (document.eingabe.itdLPxx_mapusage.value == "ss"))
	{
		location.href="XSLT_SCREEN_SAVER_REQUEST?language=de";
	}

//	alert(event.keyCode+' : '+String.fromCharCode(event.keyCode));
}

if (parseInt(navigator.appVersion)>3) {
 document.onmousedown = mouseDown;
// if (navigator.appName=="Netscape") 
// document.captureEvents(Event.mouseDown);
}

function mouseDown(e) 
{
	var altPressed=0;
	var button;
	var ServerID = document.eingabe.Server.value;
	var SessionID = document.eingabe.sessionID.value;
	var url_xml;

	SessionID = "?sessionID=" + SessionID + "&command=formatToXML";
	if (parseInt(navigator.appVersion)>3) 
	{
		if (navigator.appName=="Netscape") 
		{
			shiftPressed=e.shiftKey;
			altPressed  =e.altKey;
			ctrlPressed =e.ctrlKey;
			button= e.button;
		} 
		else 	
		{
			shiftPressed=event.shiftKey;
			altPressed  =event.altKey;
			ctrlPressed =event.ctrlKey;
			button= event.button;
//			self.status=""
//			+  "shiftKey="+event.shiftKey 
//			+", altKey="  +event.altKey 
//			+", ctrlKey=" +event.ctrlKey 
		}

	if (altPressed)
	{
		alert ("Fahrplanauskunft wurde auf " + ServerID + " berechnet...");
		//window.clipboardData.setData('Text', SessionID);
		if (button =="2")
		{
			switch (ServerID) 
			{
				case 'VRN9_1': 
					url_xml = "efa9-1.vrn.de/vrn/XSLT_TRIP_REQUEST2" + SessionID;
					showxml = window.open(url_xml,"showxml","width=1024,height=768, scrollbars"); 
					break;
				case 'VRN9_2': 
					url_xml = "efa9-2.vrn.de/vrn/XSLT_TRIP_REQUEST2" + SessionID;
					showxml = window.open(url_xml,"showxml","width=1024,height=768, scrollbars"); 
					break;
				case 'VRN9_3': 
					url_xml = "efa9-3.vrn.de/vrn/XSLT_TRIP_REQUEST2" + SessionID;
					showxml = window.open(url_xml,"showxml","width=1024,height=768, scrollbars"); 
					break;
				case 'VRN9_4': 
					url_xml = "efa9-4.vrn.de/vrn/XSLT_TRIP_REQUEST2" + SessionID;
					showxml = window.open(url_xml,"showxml","width=1024,height=768, scrollbars"); 
					break;
				case 'VRN9_test': 
					url_xml = "efa9-test.vrn.de/vrn/XSLT_TRIP_REQUEST2" + SessionID;
					showxml = window.open(url_xml,"showxml","width=1024,height=768, scrollbars"); 
					break;
			}
		}
	}
}
	return true;
}

function checkEnter(event)
{ 	
	var code = 0;
	code = event.keyCode;
	if (code==13)
	{
		winContent = window.open('', 'fahrplan', 'left=300, top=150, width=650, height=488, toolbar=yes, scrollbars=yes, resizable=yes, menubar=no')         
		document.forms[0].submit();
	}
}

function check_submit()
{
	getEvent=event.keyCode;
    if (getEvent == "13") 
	{
//		window.status = "Enter gedr�
		document.forms[0].submit();
		return false;
     } else {
		return true;
    }
}

function NewWindow(mypage, myname, w, h) 
{
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars=yes,resizable=yes,toolbar=yes'
	winContent = window.open(mypage, myname, winprops)
	winContent.focus();
}

function anfrage()
{
	document.forms[0].submit();
}

function anfrage_fahrplan()
{
	winContent = window.open('', 'fahrplan', 'left=300, top=150, width=650, height=488, toolbar=yes, scrollbars=yes, resizable=yes, menubar=no')         
	document.forms[0].submit();
}

function anfrage_options()
{
	winContent = window.open('http://efa9.vrn.de/vrn/XSLT_TRIP_REQUEST2?language=de&ptOptionsActive=1', 'fahrplan', 'left=300, top=150, width=650, height=488, toolbar=yes, scrollbars=yes, resizable=yes, menubar=no');
}

function newWindow(newContent)
 {
  winContent = window.open(newContent, 'VRN_Plan', 'left=300, top=150, width=650, height=488, toolbar=yes, scrollbars=yes, resizable=yes, menubar=no')         
 }

function newWindow2(newContent)
 {
  winContent = window.open(newContent, 'Homepage_VRN_GmbH', 'left=400, top=150, width=450, height=488, toolbar=yes, scrollbars=yes, resizable=yes, menubar=no')         
 }

function news(newContent)
 {
  winContent = window.open(newContent, 'Homepage_VRN_GmbH', 'left=100, top=50, width=800, height=600, toolbar=yes, scrollbars=yes, resizable=yes, menubar=no')         
 }


function uhrzeit() {

	Wochentagname = new Array("Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag");
	var day, month, year, hours, minutes, seconds, ap;
	var intHours, intMinutes, intSeconds, intDay, intMonth, intYear;
	var today;

	today = new Date();

	intHours = today.getHours();
	intMinutes = today.getMinutes();
	intSeconds = today.getSeconds();
	intDay = today.getDate();
	intYear = today.getYear();
	intMonth = today.getMonth() + 1;

	year = intYear;

	if (intHours < 10) {
		hours = "0"+intHours;
	} else {
		hours = intHours;
	}

	if (intMinutes < 10) {
		minutes = "0"+intMinutes;
	} else {
		minutes = intMinutes;
	}

	if (intMonth < 10) {
		month = "0"+intMonth;
	} else {
		month = intMonth;
	} 

	if (intDay < 10) {
		day = "0"+intDay;
	} else {
		day = intDay;
	} 

	timeString = hours+minutes+seconds;
	document.fahrplanauskunft.itdTimeHour.value = hours;
	document.fahrplanauskunft.itdTimeMinute.value = minutes;
	document.fahrplanauskunft.itdDateDay.value = day;
	document.fahrplanauskunft.itdDateMonth.value = month;
	document.fahrplanauskunft.itdDateYear.value = year;
}

function submit_psParam() {

	var psParam;
	
	psParam = document.eingabe.psParamSampleYear.value + document.eingabe.psParamSampleMonth.value + document.eingabe.psParamSampleDay.value;
	document.eingabe.psParamSampleDate.value = psParam;
	document.eingabe.submit();
}

// Javascriptcode f?Up Kalender 

calDateFormat    = "DD/MM/yy";
topBackground    = "#FFFFFF";         
bottomBackground = "#FFFFFF";         
tableBGColor     = "#E5EFF9";         
cellColor        = "#C1CBD6";     
headingCellColor = "#712252";         
headingTextColor = "white";         
dateColor        = "314566";          
focusColor       = "#ff0000";       
hoverColor       = "#ff0000";       
fontStyle        = "bold 8pt univers, helvetica";           
headingFontStyle = "bold 8pt univers, helvetica";
bottomBorder  = false;        
tableBorder   = 0;

var isNav = false;
var isIE  = false;
var selectToday  = false;
var rowCount = 0;

if (navigator.appName == "Netscape") {
    isNav = false;
}
else {
    isIE = true;
}
if(isNav == true){
  selectedLanguage = navigator.language;
  }else{
  selectedLanguage = navigator.userLanguage;
}

function doNothing(){
}

function setDateField(dateField) {
        calDateField = dateField;
        inDate = dateField.value;
        setInitialDate();
        calDocTop    = buildTopCalFrame();
        calDocBottom = buildBottomCalFrame();
        calDocFoot   = buildFootCalFrame();
}

function setDateFields(dayField, monthField, yearField, lang) {
		selectedLanguage = lang;
		buildCalParts();
		calDateDay = dayField;
        calDateMonth = monthField;
        calDateYear = yearField;
        inDate = monthField.value+"/"+dayField.value+"/20"+yearField.value;

        setInitialDate();
        calDocTop    = buildTopCalFrame();
	    calDocBottom = buildBottomCalFrame();
        calDocFoot   = buildFootCalFrame();
}

function setInitialDate() {
        calDate = new Date(inDate);
        if (isNaN(calDate)) {
                        calDate = new Date();
    }
        calDay  = calDate.getDate();
                calDate.setDate(1);
}

function showCalendar(dateField) {
        setDateField(dateField);
        calDocFrameset =        "<HTML><HEAD><TITLE>Kalender</TITLE></HEAD>\n" +
        "<FRAMESET ROWS='50,*,30' FRAMEBORDER='0' framespacing='0' border='0'>\n" +
        "  <FRAME NAME='topCalFrame' SRC='javascript:parent.opener.calDocTop' SCROLLING='no' marginwidth='0' marginheight='0'>\n" +
        "  <FRAME NAME='bottomCalFrame' SRC='javascript:parent.opener.calDocBottom' SCROLLING='no' marginwidth='0' marginheight='0'>\n" +
	    "  <FRAME NAME='footCalFrame' SRC='javascript:parent.opener.calDocFoot' SCROLLING='no' marginwidth='0' marginheight='0'>\n" +
        "</FRAMESET>\n";
        top.newWin = window.open("javascript:parent.opener.calDocFrameset", "calWin", winPrefs);
    top.newWin.focus();
}

function buildTopCalFrame() {
        var calDoc =
        "<HTML>" +
        "<HEAD>" +
        "<link rel='stylesheet' type='text/css' href='css/layout_events_vrn.css'>"+
        "<TITLE>" + "Kalender Navigation" + "</TITLE>" +
		"</HEAD>" +
        "<BODY BGCOLOR='" + topBackground + "'>" +
        "<FORM NAME='calControl' onSubmit='return false;'>" +
        "<CENTER>" +
        "<TABLE HEIGHT=100% BORDER=0 HEIGHT=0>" + 
		"<TR><TD>" +
		"<TABLE CELLPADDING=0 CELLSPACING=2 BORDER=0>" +
        "<TR>" +
//        "<TD VALIGN=middle><INPUT class='button'" + "TYPE=BUTTON NAME='previousYear' VALUE='<<' onClick='parent.opener.setPreviousYear()'></TD>" + 
		"<TD VALIGN=middle><INPUT class='button'" + "TYPE=BUTTON NAME='previousMonth' VALUE=' < ' onClick='parent.opener.setPreviousMonth()'></TD>" +
		"<TD VALIGN=middle>" + getMonthSelect() + "</TD>" +
		"<TD VALIGN=middle><INPUT class='text' NAME='year' VALUE='" + calDate.getFullYear() + "'TYPE=TEXT SIZE=4 MAXLENGTH=4 onChange='parent.opener.setYear()'></TD>" +
        "<TD VALIGN=middle><INPUT class='button'" + "TYPE=BUTTON NAME='nextMonth' VALUE=' > ' onClick='parent.opener.setNextMonth()'></TD>" + 
//		"<TD VALIGN=middle><INPUT class='button'" + "TYPE=BUTTON NAME='nextYear' VALUE='>>' onClick='parent.opener.setNextYear()'></TD>" +
		"</TR>" +
        "</TABLE>" +
		"</TD></TR>" + 
		"</TABLE>" +
        "</CENTER>" +
        "</FORM>" +
        "</BODY>" +
        "</HTML>";
    return calDoc;
}

function buildFootCalFrame() {
        var calDoc =
        "<HTML>" +
        "<HEAD>" +
        "<link rel='stylesheet' type='text/css' href='css/layout_events_vrn.css'>"+
        "<TITLE>" + "Kalender Navigation" + "</TITLE>" +
		"</HEAD>" +
        "<BODY BGCOLOR='" + topBackground + "'>" +
        "<FORM NAME='calControl' onSubmit='return false;'>" +
        "<CENTER>" +
        "<TABLE HEIGHT=100% BORDER=0>" + 
		"<TR><TD VALIGN=middle>" +
		"<INPUT class='button'" + "TYPE=BUTTON NAME='today' VALUE='"+ createToday()+"' onClick='parent.opener.setToday()'>" +
		"</TD></TR>" + 
		"</TABLE>" +
        "</CENTER>" +
        "</FORM>" +
        "</BODY>" +
        "</HTML>";
    return calDoc;
}

function buildBottomCalFrame() {
        var calDoc = calendarBegin;
        month   = calDate.getMonth();
		year = calDate.getFullYear();
        day     = calDay;

		if (selectToday) 
		{
	        day = calDate.getDate();
		}

	var i   = 0;
        var days = getDaysInMonth();
        if (day > days) {
        day = days;
    }
        var firstOfMonth = new Date (year, month, 1);
        var startingPos  = firstOfMonth.getDay();
    days += startingPos;
        var columnCount = 0;

		if (startingPos == 0)
		{
			for (i = 0; i < startingPos + 6; i++) {
		        calDoc += blankCell;
				columnCount++;
			}
		}
		else
		{
			for (i = 0; i < startingPos - 1; i++) {
		        calDoc += blankCell;
				columnCount++;
			}
		}

        var currentDay = 0;
    var dayType    = "weekday";
        for (i = startingPos; i < days; i++) {
	var paddingChar = "&nbsp;";
                if (i-startingPos+1 < 10) {
            padding = "&nbsp;&nbsp;";
        }
        else {
            padding = "&nbsp;";
        }
                currentDay = i-startingPos+1;
                if (currentDay == day) {
                dayType = "focusDay";
        }
        else 
		{
            dayType = "weekDay";
        }
			calDoc += "<TD align=center bgcolor='" + cellColor + "'>" + "<a class='" + dayType + "' href='javascript:parent.opener.returnDate(" +                  currentDay + ")'>" + padding + currentDay + paddingChar + "</a></TD>";
			columnCount++;
            if (columnCount % 7 == 0) 
			{
				rowCount++;
				calDoc += "</TR><TR>";
			}
	    }

        var startingPosTemp = firstOfMonth.getDay();

		if (startingPosTemp != 0)
		{
			days = days;
		} else {
			days = days + 7;
		}

		for (j=days; j<43; j++)  
		{
				calDoc += blankCell;
//				calDoc += j;
				columnCount++;
				if (columnCount % 7 == 0) 
				{
					calDoc += "</TR>";
				}
//				if (i<41) 
//				{
//					calDoc += "<TR>";
//				}
		}
        calDoc += calendarEnd;
		selectToday = false;
        return calDoc;
}

function writeCalendar() {
    calDocBottom = buildBottomCalFrame();
    top.newWin.frames['bottomCalFrame'].document.open();
    top.newWin.frames['bottomCalFrame'].document.write(calDocBottom);
    top.newWin.frames['bottomCalFrame'].document.close();
}

function setToday() {
        calDate = new Date();
        var month = calDate.getMonth();
		var year  = calDate.getFullYear();
		selectToday = true;
        top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex = month;
        top.newWin.frames['topCalFrame'].document.calControl.year.value = year;
        writeCalendar();
}

function setYear() {
        var year  = top.newWin.frames['topCalFrame'].document.calControl.year.value;
        if (isFourDigitYear(year)) {
        calDate.setFullYear(year);
        writeCalendar();
    }
    else {
                top.newWin.frames['topCalFrame'].document.calControl.year.focus();
        top.newWin.frames['topCalFrame'].document.calControl.year.select();
    }
}
function setCurrentMonth() {
    var month = top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex;
	var tempMonth = 
	calDate.setMonth(month);
    writeCalendar();
}
function setPreviousYear() {
    var year  = top.newWin.frames['topCalFrame'].document.calControl.year.value;
    if (isFourDigitYear(year) && year > 1000) {
        year--;
        calDate.setFullYear(year);
        top.newWin.frames['topCalFrame'].document.calControl.year.value = year;
        writeCalendar();
    }
}
function setPreviousMonth() {
    var year  = top.newWin.frames['topCalFrame'].document.calControl.year.value;
    if (isFourDigitYear(year)) {
        var month = top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex;
                if (month == 0) {
            month = 11;
            if (year > 1000) {
                year--;
                calDate.setFullYear(year);
                top.newWin.frames['topCalFrame'].document.calControl.year.value = year;
            }
        }
        else {
            month--;
        }
        calDate.setMonth(month);
        top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex = month;
        writeCalendar();
    }
}
function setNextMonth() {
    var year = top.newWin.frames['topCalFrame'].document.calControl.year.value;
    if (isFourDigitYear(year)) {
        var month = top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex;
                if (month == 11) {
            month = 0;
            year++;
            calDate.setFullYear(year);
            top.newWin.frames['topCalFrame'].document.calControl.year.value = year;
        }
        else {
            month++;
        }
        calDate.setMonth(month);
        top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex = month;
        writeCalendar();
    }
}
function setNextYear() {
    var year  = top.newWin.frames['topCalFrame'].document.calControl.year.value;
    if (isFourDigitYear(year)) {
        year++;
        calDate.setFullYear(year);
        top.newWin.frames['topCalFrame'].document.calControl.year.value = year;
        writeCalendar();
    }
}
function getDaysInMonth()  {
    var days;
    var month = calDate.getMonth()+1;
    var year  = calDate.getFullYear();
        if (month==1 || month==3 || month==5 || month==7 || month==8 ||
        month==10 || month==12)  {
        days=31;
    }
        else if (month==4 || month==6 || month==9 || month==11) {
        days=30;
    }
        else if (month==2)  {
        if (isLeapYear(year)) {
            days=29;
        }
                else {
            days=28;
        }
    }
    return (days);
}
function isLeapYear (Year) {
    if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
        return (true);
    }
    else {
        return (false);
    }
}
function isFourDigitYear(year) {
    if (year.length != 4) {
        top.newWin.frames['topCalFrame'].document.calControl.year.value = calDate.getFullYear();
        top.newWin.frames['topCalFrame'].document.calControl.year.select();
        top.newWin.frames['topCalFrame'].document.calControl.year.focus();
    }
    else {
        return true;
    }
}
function getMonthSelect() {
        if (selectedLanguage == "fr") {
        monthArray = new Array('Janvier', 'F?ier', 'Mars', 'Avril', 'Mai', 'Juin',
                               'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'D?mbre');
    }
        else if (selectedLanguage == "de") {
        monthArray = new Array('Januar', 'Februar', 'M?', 'April', 'Mai', 'Juni',
                               'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember');
    }
        else if (selectedLanguage == "es") {
        monthArray = new Array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
                               'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
    }
        else if (selectedLanguage == "kk") {
        monthArray = new Array('Januar', 'Februar', 'M?', 'April', 'Mai', 'Juni',
                               'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember');
    }
        else {
        monthArray = new Array('January', 'February', 'March', 'April', 'May', 'June',
                               'July', 'August', 'September', 'October', 'November', 'December');
    }
        var activeMonth = calDate.getMonth();
        monthSelect = "<SELECT class='text' NAME='month' onChange='parent.opener.setCurrentMonth()'>";
        for (i in monthArray) {
                if (i == activeMonth) {
            monthSelect += "<OPTION SELECTED>" + monthArray[i] + "\n";
        }
        else {
            monthSelect += "<OPTION>" + monthArray[i] + "\n";
        }
    }
    monthSelect += "</SELECT>";
        return monthSelect;
}
function createWeekdayList() {
        if (selectedLanguage == "fr") {
        weekdayList  = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
        weekdayArray = new Array('Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa');
    }
        else if (selectedLanguage == "de") {
        weekdayList  = new Array('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag');
        weekdayArray = new Array('Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So');
//        weekdayArray = new Array('So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa');
    }
        else if (selectedLanguage == "es") {
        weekdayList  = new Array('Domingo', 'Lunes', 'Martes', 'Mi?oles', 'Jueves', 'Viernes', 'S?do')
        weekdayArray = new Array('Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa');
    }
	    else if (selectedLanguage == "kk") {
        weekdayList  = new Array('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag');
        weekdayArray = new Array('Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So');
//        weekdayArray = new Array('So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa');
    }
    else {
        weekdayList  = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        weekdayArray = new Array('Su','Mo','Tu','We','Th','Fr','Sa');
    }
        var weekdays = "<TR BGCOLOR='" + headingCellColor + "'>";
        for (i in weekdayArray) {
        weekdays += "<TD class='heading' align=center>" + weekdayArray[i] + "</TD>";
    }
    weekdays += "</TR>";
        return weekdays;
}

function createToday() {
        if (selectedLanguage == "fr") {
        today = 'Aujourd\'hui';
    }
        else if (selectedLanguage == "de") {
        today = 'Heute';    }
        else if (selectedLanguage == "kk") {
        today = 'Heute';   }
        else if (selectedLanguage == "es") {
        today = 'Oje';   }
    else {
        today = 'Today';   }
    return today;
}

function buildCalParts() {
        weekdays = createWeekdayList();
        blankCell = "<TD align=center bgcolor='" + cellColor + "'>&nbsp;&nbsp;&nbsp;</TD>";
        calendarBegin =
        "<HTML>" +
        "<HEAD>" +
                "<STYLE type='text/css'>" +
        "<!--" +
        "TD.heading { text-decoration: none; color:" + headingTextColor + "; text-decoration: none; font: " + headingFontStyle + "; }" +
        "A.focusDay:link { color: " + focusColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "A.focusDay:hover { color: " + focusColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "A.focusDay:visited { color: " + focusColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "A.weekday:link { color: " + dateColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "A.weekday:hover { color: " + hoverColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "A.weekday { color: " + dateColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "-->" +
        "</STYLE>" +
         "<TITLE>" + "Kalender Blatt"+
				"</TITLE>" +
				"</HEAD>" +
        "<BODY BGCOLOR='" + bottomBackground + "'>" +
        "<CENTER>";
                if (isNav) {
            calendarBegin +=                "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=" + tableBorder + " ALIGN=CENTER BGCOLOR='" + tableBGColor + "'><TR><TD>";
        }
                calendarBegin +=
            "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=" + tableBorder + " ALIGN=CENTER BGCOLOR='" + tableBGColor + "'>" +
            weekdays +
            "<TR>";
        calendarEnd = "";
                if (bottomBorder) {
            calendarEnd += "<TR></TR>";
        }
                if (isNav) {
            calendarEnd += "</TD></TR></TABLE>";
        }
                calendarEnd +=
            "</TABLE>" +
            "</CENTER>" +
            "</BODY>" +
            "</HTML>";
}
function jsReplace(inString, find, replace) {
    var outString = "";
    if (!inString) {
        return "";
    }
        if (inString.indexOf(find) != -1) {
                t = inString.split(find);
                return (t.join(replace));
    }
    else {
        return inString;
    }
}
function makeTwoDigit(inValue) {
    var numVal = parseInt(inValue, 10);
        if (numVal < 10) {
                return("0" + numVal);
    }
    else {
        return numVal;
    }
}
function returnDate(inDay)
{
    calDate.setDate(inDay);
    var day           = calDate.getDate();
    var month         = calDate.getMonth()+1;
    var year          = calDate.getFullYear();
    var monthString   = monthArray[calDate.getMonth()];
    var monthAbbrev   = monthString.substring(0,3);
    var weekday       = weekdayList[calDate.getDay()];
    var weekdayAbbrev = weekday.substring(0,3);
    outDate = calDateFormat;
        if (calDateFormat.indexOf("DD") != -1) {
        day = makeTwoDigit(day);
        outDate = jsReplace(outDate, "DD", day);
    }
        else if (calDateFormat.indexOf("dd") != -1) {
        outDate = jsReplace(outDate, "dd", day);
    }
        if (calDateFormat.indexOf("MM") != -1) {
        month = makeTwoDigit(month);
        outDate = jsReplace(outDate, "MM", month);
    }
        else if (calDateFormat.indexOf("mm") != -1) {
        outDate = jsReplace(outDate, "mm", month);
    }
        if (calDateFormat.indexOf("yyyy") != -1) {
        outDate = jsReplace(outDate, "yyyy", year);
    }
        else if (calDateFormat.indexOf("yy") != -1) {
        var yearString = "" + year;
        var yearString = yearString.substring(2,4);
        outDate = jsReplace(outDate, "yy", yearString);
    }
        else if (calDateFormat.indexOf("YY") != -1) {
        outDate = jsReplace(outDate, "YY", year);
    }
        if (calDateFormat.indexOf("Month") != -1) {
        outDate = jsReplace(outDate, "Month", monthString);
    }
        else if (calDateFormat.indexOf("month") != -1) {
        outDate = jsReplace(outDate, "month", monthString.toLowerCase());
    }
        else if (calDateFormat.indexOf("MONTH") != -1) {
        outDate = jsReplace(outDate, "MONTH", monthString.toUpperCase());
    }
        if (calDateFormat.indexOf("Mon") != -1) {
        outDate = jsReplace(outDate, "Mon", monthAbbrev);
    }
        else if (calDateFormat.indexOf("mon") != -1) {
        outDate = jsReplace(outDate, "mon", monthAbbrev.toLowerCase());
    }
        else if (calDateFormat.indexOf("MON") != -1) {
        outDate = jsReplace(outDate, "MON", monthAbbrev.toUpperCase());
    }
        if (calDateFormat.indexOf("Weekday") != -1) {
        outDate = jsReplace(outDate, "Weekday", weekday);
    }
        else if (calDateFormat.indexOf("weekday") != -1) {
        outDate = jsReplace(outDate, "weekday", weekday.toLowerCase());
    }
        else if (calDateFormat.indexOf("WEEKDAY") != -1) {
        outDate = jsReplace(outDate, "WEEKDAY", weekday.toUpperCase());
    }
        if (calDateFormat.indexOf("Wkdy") != -1) {
        outDate = jsReplace(outDate, "Wkdy", weekdayAbbrev);
    }
        else if (calDateFormat.indexOf("wkdy") != -1) {
        outDate = jsReplace(outDate, "wkdy", weekdayAbbrev.toLowerCase());
    }
        else if (calDateFormat.indexOf("WKDY") != -1) {
        outDate = jsReplace(outDate, "WKDY", weekdayAbbrev.toUpperCase());
    }
    calDateDay.value= outDate.substring(0,2);
    calDateMonth.value = outDate.substring(3,5);
    calDateYear.value = outDate.substring(6,8);
    top.newWin.close();
}
function initDateTime(dayField, monthField, yearField, hourField, minuteField)
{
    if(hourField == null || minuteField == null){
    		inDate = monthField.value+"/"+dayField.value+"/20"+yearField.value;
		}else{
        inDate = monthField.value+"/"+dayField.value+"/20"+yearField.value+" "+hourField.value+":"+minuteField.value;
		}
    setInitialDate();
    var day           = calDay;
    var month         = calDate.getMonth()+1;
    var year          = calDate.getFullYear();
    var yearString 		= "" + year;
    var yearString 		= yearString.substring(2,4);
		var hour 			 	  = calDate.getHours();
		var minutes 			= calDate.getMinutes();
		hour = makeTwoDigit(hour);
		minutes = makeTwoDigit(minutes);
		day = makeTwoDigit(day);
    month = makeTwoDigit(month);
		dayField.value = day;
		monthField.value = month;
		yearField.value = yearString;
		if(hourField != null && minuteField != null){
		   hourField.value = hour;
		   minuteField.value = minutes;
		}
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////                                 set input focus on the forms                                                        /////                          
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function setInputFocus()
{
	if (document.forms[0])
	{		
		// set focus PS
		if (document.forms[0].nameState_origin.value=="empty" && document.forms[0].placeState_origin.value=="empty")
		{ 
			document.forms[0].place_origin.focus(); 
		}

		// trip planner date
//		if (document.forms[0].itdDateDay)
//		{
//			if (document.forms[0].itdDateDay && document.forms[0].nameState_origin && document.forms[0].nameState_origin.value=="empty" && document.forms[0].placeState_origin && document.forms[0].placeState_origin.value=="empty" && document.forms[0].nameState_destination && document.forms[0].nameState_destination.value=="empty" && document.forms[0].placeState_destination && document.forms[0].placeState_destination.value=="empty")
//			{ 
//				document.forms[0].itdDateDay.focus(); 
//			}
//		}

		// personal timetable weekday
		else if (document.forms[0].psParamWeekday && document.forms[0].psParamWeekday.type!="hidden" && document.forms[0].nameState_origin && document.forms[0].nameState_origin.value=="empty" && document.forms[0].placeState_origin && document.forms[0].placeState_origin.value=="empty" && document.forms[0].nameState_destination && document.forms[0].nameState_destination.value=="empty" && document.forms[0].placeState_destination && document.forms[0].placeState_destination.value=="empty")
		{ document.getElementById("psParamWeekday").focus(); }
		
		// personal timetable for pda time
		else if (document.forms[0].itdTimeHour_arrFrom && document.forms[0].nameState_origin && document.forms[0].nameState_origin.value=="empty" && document.forms[0].placeState_origin && document.forms[0].placeState_origin.value=="empty" && document.forms[0].nameState_destination && document.forms[0].nameState_destination.value=="empty" && document.forms[0].placeState_destination && document.forms[0].placeState_destination.value=="empty")
		{ document.forms[0].itdTimeHour_arrFrom.focus(); }
		
		// origin place
//		else if (document.forms[0].place_origin && document.forms[0].place_origin.type!="empty")
//		{ document.forms[0].name_origin.focus(); }

		// origin name
//		else if (document.forms[0].name_origin && document.forms[0].name_origin.type!="hidden")
//		{ document.forms[0].name_origin.focus(); }

		// destination name
//		else if (document.forms[0].name_destination && document.forms[0].name_destination.type!="hidden")
//		{ document.forms[0].name_destination.focus(); }
		
		// itinerary
		else if (document.getElementById("tripPrev"))
		{ document.getElementById("tripPrev").focus(); }

		// fares
		else if (document.getElementById("fare"))
		{ document.getElementById("fare").focus(); }

		// download file
		else if (document.getElementById("download"))
		{ document.getElementById("download").focus(); }

		// download reset button
		else if (document.getElementById("downloadReset"))
		{ document.getElementById("downloadReset").focus(); }

		// map request
		else if (document.forms[0].stopSelector)
		{ document.forms[0].stopSelector.focus(); }
		
		// stop timetable type
		else if (document.forms[0].type_stt && document.forms[0].nameState_stt.value=="empty")
		{ document.getElementById("stop").focus(); }
		
		// stop timetable odv
		else if (document.forms[0].name_stt && document.forms[0].name_stt.type!="hidden")
		{ document.forms[0].name_stt.focus(); }
		
		// assigned stop stt
		else if (document.forms[0].assignedStop_stt && document.forms[0].assignedStop_stt.type!="hidden")
		{ document.forms[0].assignedStop_stt[0].focus(); }
		
		// departure monitor date
		else if (document.forms[0].itdDateDay && document.forms[0].nameState_dm && document.forms[0].nameState_dm.value=="empty" && document.forms[0].placeState_dm && document.forms[0].placeState_dm.value=="empty")
		{ document.forms[0].itdDateDay.focus(); }
		
		// departure monitor odv
		else if (document.forms[0].name_dm && document.forms[0].name_dm.type!="hidden")
		{ document.forms[0].name_dm.focus(); }
		
		// line selection
		else if (document.forms[0].dmLineSelection)
		{ document.forms[0].dmLineSelection.focus(); }
		
		// assigned stop dm
		else if (document.forms[0].assignedStop_dm && document.forms[0].assignedStop_dm.type!="hidden")
		{ document.forms[0].assignedStop_dm[0].focus(); }
		
		// dm for pda
		else if (document.forms[0].name_ss && document.forms[0].name_ss.type!="hidden")
		{ document.forms[0].name_ss.focus(); }
		
		// dm for pda assigned stop
		else if (document.forms[0].assignedStop_ss && document.forms[0].assignedStop_ss.type!="hidden")
		{ document.forms[0].assignedStop_ss[0].focus(); }
		
		// pda E-Mail address
		else if (document.forms[0].emailAddress && document.forms[0].emailAddress.type!="hidden")
		{ document.forms[0].emailAddress.focus(); }
		
		// pda reset button
		else if (document.getElementById("pdaReset"))
		{ document.getElementById("pdaReset").focus(); }
		
		// timetable book
		else if (document.forms[0].lineName && document.forms[0].lineName.type!="hidden")
		{ document.forms[0].lineName.focus(); }
		
		// timetable book line selection
		else if (document.forms[0].lineSelIndex)
		{ document.forms[0].lineSelIndex.focus(); }
		
		// login
		else if (document.forms[0].netUsername && document.forms[0].netUsername.type!="hidden")
		{ document.forms[0].netUsername.focus(); }

		// first login and personal profile person
		else if (document.forms[0].ppPersonName && document.forms[0].ppPersonName.type!="hidden")
		{ document.forms[0].ppPersonName.focus(); }

		// personal profil odv
		else if (document.forms[0].ppOdvIdentifier && document.forms[0].ppOdvIdentifier.type!="hidden")
		{ document.forms[0].ppOdvIdentifier.focus(); }

		// personal profil options
		else if (document.forms[0].ppPTComfortMaxChanges && document.forms[0].ppPTComfortMaxChanges.type!="hidden")
		{ document.forms[0].ppPTComfortMaxChanges[0].focus(); }

		// personal profil configuration
		else if (document.forms[0].ppPTConfigurationSenderInfo && document.forms[0].ppPTConfigurationSenderInfo.type!="hidden")
		{ document.forms[0].ppPTConfigurationSenderInfo.focus(); }

		// print options
		else if (document.forms[0].psParamAddressName && document.forms[0].psParamAddressName.type!="hidden")
		{ document.forms[0].psParamAddressName.focus(); }
		
						
	}
	
}

/////////////////////////////////////////////////////////////////////////////////////
// Verify Date
function showdate1( year, month, date )
{
      if (date < 10) {
	date = "0" + date;
      }
      else {
	date = date;
      }

      if (month < 10) {
	month = "0" + month;
      }
      else {
	month = month;
      }

      year = year + "";
      if (year.length > 2) {
      	year = year.substring(3,4);
	if (year < 10){
		year = "0" + year;
	}
	else {
		year = year;
	}
       }
       else{
	  if (year < 10){
		year = "0" + year;
	  }
	  else {
		year = year;
	  }
	}

      	document.forms[0].itdDateYear.value = year;
      	document.forms[0].itdDateMonth.value = month;
      	document.forms[0].itdDateDay.value = date;
}

//////////////////////////////////////////////////////////////////////
//Set dmLineSelection All of true
function preSubmit(){
	if (document.forms[0].dmLineSelection && document.forms[0].dmLineSelection.value == 'all') {
		document.forms[0].dmLineSelectionAll.value = 1;
	}
}

///////////////////////////////////////////////////////////////////////
//Function Up Down arrows
function dateUpDown2(upOrDown) { 
	var tag;
	var monat;
	var jahr;
	var Name = new Array("Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag");
	
	date = document.eingabe.date.value;
	splitString = date.split(".");

	tag = splitString[0];
	monat = splitString[1];
	jahr = splitString[2];

	var jahrIntWert = parseInt(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')
	{ millisecunden = millisecunden + (24*60*60*1000); }

	if (upOrDown == 'down' )
	{ millisecunden = millisecunden - (24*60*60*1000); }

	heute.setTime(millisecunden);

	tag = heute.getDate();
	wd = heute.getDay();
	
	if (tag > 0 && tag < 10)
	{ tag = "0"+tag; }

	monat = heute.getMonth() + 1;
	if (monat > 0 && monat < 10)
	{ monat = "0"+monat; }

	jahr = "" + heute.getFullYear();
//	jahr = jahr.substr(2,2);

//	document.forms[0].itdDateDay.value = tag;
//	document.forms[0].itdDateMonth.value = monat;
//  document.forms[0].itdDateYear.value = jahr;
    //alert ("Heute ist " + Name[wd]) ;

	document.eingabe.date.value = tag + "." + monat + "." + jahr;
}

////////////////////////////////////////////////////////////////////////////////////////
// submit a form out of a combo box (IE Version only)
function checkReturnKey()
{
	if (window.event && window.event.keyCode==13)
	{		
		if (document.forms[0].execInst) {
			document.forms[0].execInst.value='normal';
		}
		if (document.forms[0].dmLineSelection && document.forms[0].dmLineSelection.value == 'all') {
			document.forms[0].dmLineSelectionAll.value = 1;
		}
		document.forms[0].submit();
	}
}

////////////////////////////////////////////////////////////////////////////////////////
// Uhr bei der Ausgabe von der Abfahrtstafeln anzeigen

function Uhr_anzeigen()
{ 
	var Datum = new Date() 
	var std = Datum.getHours() 
	var min = Datum.getMinutes() 
	var sec = Datum.getSeconds() 
	Zeit = ((std < 10) ? " 0" : " ") + std 
	Zeit += ((min < 10) ? ":0" : ":") + min 
	Zeit += ((sec < 10) ? ":0" : ":") + sec 
	document.uhr.zeit.value = Zeit 
	timerid = setTimeout("Uhr_anzeigen()",1000) 
} 

function findPosition(obj)
{
	imgOffsetTop=0;imgOffsetLeft=0;

	do 
	{
		imgOffsetTop+=obj.offsetTop;
		imgOffsetLeft+=obj.offsetLeft;
		obj=obj.offsetParent;
	} while (obj.tagName != "BODY" && obj);
}

function setTime()
{
	var doc=document;
	var texttafel = document.getElementById("texttafel");

	if(doc.images)
	{
		var img = doc.images["background"];
		findPosition(img);
		var objLeft = imgOffsetLeft - 317;
		var objLeft_2 = imgOffsetLeft - 163;
		//	alert(objLeft);
		var objTop  = imgOffsetTop  + 263;
		var objTop_2  = imgOffsetTop  + 363;
		//	alert(objTop);
	}
	
	document.uhr.style.position = "absolute";
	document.uhr.style.left = objLeft + "px";
	document.uhr.style.top = objTop + "px";

	texttafel.style.position = "absolute";
	texttafel.style.left = objLeft_2 + "px";
	texttafel.style.top = objTop_2 + "px";
}

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,');
}



/*
 * 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;
}
