var cookiename = "tripcast"; // Name of cookie with origin and destination
var expiredays = 14; // Do not use cookie after 14 days
var nPeriodsBefore = 1; // number of traveltimes to calculate before specified time
var nPeriodsAfter = 1; // number of traveltimes to calculate after specified time

// This function is called when window is loaded and handles initialization
function load() {
	initForm();
	createResultsTable();
}

function AJAXInteraction(url, callback) {
	var req = init();
	req.onreadystatechange = processRequest;
	function init() {
		try {
			// Opera 8.0+, Firefox, Safari
			return new XMLHttpRequest();
		} catch (e) {
			// Internet Explorer Browsers
			try {
				return new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					return new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					// Something went wrong
					alert("Your browser broke!");
					return false;
				}
			}
		}
	}
	function processRequest() {
		// readyState of 4 signifies request is complete
		if (req.readyState == 4) {
			// status of 200 signifies successful HTTP call
			if (req.status == 200) {
				if (callback) {
					if (req.responseXML == null) {
						callback(req.responseText);
					} else {
						callback(req.responseXML);
					}
				}
			}
		}
	}
	this.doGet = function() {
		// make a HTTP GET request to the URL asynchronously
		req.open("GET", url, true);
		req.send(null);
	}
}

function sendform() {
	// time
	try{
	initResultsTable();
	var dateselector = document.getElementById('dateselector');
	var hourselector = document.getElementById('hourselector');
	var minuteselector = document.getElementById('minuteselector');
	var date = new Date(dateselector.value);
	var value = date.getFullYear().toString()
			+ zeropadd((date.getMonth() + 1).toString())
			+ zeropadd(date.getDate().toString());

	var time = "";
	for (var i=-nPeriodsBefore;i<=nPeriodsAfter;i++){
		time = time + changeTime(getTime(), i * 15 * 60 * 1000) + ";"
        // WIJZ ZIJPP 20090827 strip "00"
	}

	// start address
	var zip_from = document.getElementById('zip_from').value;
    zip_from = encodeURIComponent(zip_from);

	// destination address
	var zip_to = document.getElementById('zip_to').value;
    zip_to = encodeURIComponent(zip_to);

	// departure or arrival
	var depart = document.getElementById('departselector').value;
	// reliability
	var reliability = document.getElementById('reliabilityselector').value;
	
	// display information while calculation traveltime
	// clearMessage();
	changeBodyClass('loading');

	// Call tripcast and display results
	var ajax;
	var queryString = "TripCast?from=" + zip_from + "&to=" + zip_to
			+ "&depart=" + depart + "&time=" + time + "&reliability=" + reliability;
	// expected
	// traveltime

	var url = './proxy.php?yws_path=' + encodeURIComponent(queryString);

	ajax = new AJAXInteraction(url, printTravelTime);
	ajax.doGet();
	}catch(e){alert(e)};
}

function printTravelTime(xml) {
	if (!handleErrors(xml)) {
		changeBodyClass('standby');
		routeDuration(xml);
	} else {
		changeBodyClass('error');
		showError(xml);
	}
}

function returnTrip() {
	// interchange source and destination in form
	var zip_from = document.getElementById('zip_from').value;
	var zip_to = document.getElementById('zip_to').value;
	document.getElementById('zip_from').value = zip_to;
	document.getElementById('zip_to').value = zip_from;

}

function handleErrors(xml) {
	// result/code == 0 means no error
	var err = (xml.getElementsByTagName("code")[0].childNodes[0].nodeValue != 0);
	return err;
}

function changeBodyClass(to) {
	// change body class, to make busy indicator visible
	document.body.className = to;
	return false;
}

function createResultsTable() {
	// get the reference for the body
	var body = document.getElementsByTagName("body")[0];

	// creates a <table> element and a <tbody> element
	var tbl = document.createElement("table");
	var tblBody = document.createElement("tbody");

	var row, cell, cellText;
	// creating all cells
	var N = nPeriodsBefore + nPeriodsAfter + 1 + 1;
	for ( var j = 0; j < N; j++) {
		// creates a table row
		row = document.createElement("tr");

		for ( var i = 0; i < 3; i++) {
			// Create a <td> element and a text node, make the text
			// node the contents of the <td>, and put the <td> at
			// the end of the table row
			cell = document.createElement("td");

			cellText = document.createTextNode("");
			cell.appendChild(cellText);

			row.appendChild(cell);
		}

		// add the row to the end of the table body
		tblBody.appendChild(row);
	}

	// put the <tbody> in the <table>
	tbl.appendChild(tblBody);

	document.getElementById("results").appendChild(tbl);

	// sets the border attribute of tbl to 0;
	tbl.setAttribute("border", "0");

	var footer = document.createElement("div");
	footer.setAttribute("id","footer");
	footer.appendChild(document.createTextNode(""));
	document.getElementById("results").appendChild(footer);
	
	initResultsTable();
	
}

function initResultsTable() {
	div = document.getElementById("results");

	table = div.getElementsByTagName("table")[0];
	tablebody = table.getElementsByTagName("tbody")[0];
	row = tablebody.getElementsByTagName("tr")[0];

	var N = nPeriodsBefore + nPeriodsAfter + 2;
	for ( var i = 0; i < N; i++) {
		row = tablebody.getElementsByTagName("tr")[i];

		row.getElementsByTagName("td")[0].childNodes[0].data = "";
		row.getElementsByTagName("td")[1].childNodes[0].data = "";
		row.getElementsByTagName("td")[2].childNodes[0].data = "";
	}

	// Init footer
	var footer = document.getElementById("footer");
	footer.firstChild.nodeValue = "";
}

// === route duration ===
function routeDuration(xml) {
	var row, cel, depart, duration, arrive;
	var table = div.getElementsByTagName("table")[0];
	var tbody = table.getElementsByTagName("tbody")[0];
	var preformat = xml.getElementsByTagName("preformat");
	
	// Get tableheader
	row = tbody.getElementsByTagName("tr")[0];
	cel = row.getElementsByTagName("td")[0];
	cel.childNodes[0].data = "Vertrek";
	cel = row.getElementsByTagName("td")[1];
	cel.childNodes[0].data = "Aankomst";
	cel = row.getElementsByTagName("td")[2];
	cel.childNodes[0].data = "Reistijd";
	
	for ( var i = 0; i < preformat.length; i++) {
		row = tbody.getElementsByTagName("tr")[i + 1];

		cel = row.getElementsByTagName("td")[0];
		depart = preformat[i].childNodes[1].childNodes[0].nodeValue;
		cel.childNodes[0].data = depart;

		cel = row.getElementsByTagName("td")[1];
		arrive = preformat[i].childNodes[3].childNodes[0].nodeValue;
		cel.childNodes[0].data = arrive;

		cel = row.getElementsByTagName("td")[2];
		duration = preformat[i].childNodes[2].childNodes[0].nodeValue;
		cel.childNodes[0].data = duration;
	}

	var footer = document.getElementById("footer");
	footer.firstChild.nodeValue = "Actuele reistijd: " + xml.getElementsByTagName("durationnow")[0].firstChild.nodeValue;
}

function clearDetails(xml) {
	document.getElementById("content_container").innerHTML = "";
}

function populateSelectors() {
	populateDaySelector();
	populateHourSelector();
	populateMinuteSelector();
	populateDepartSelector();
}

function populateDaySelector() {
	var daynames = [ 'Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag',
			'Vrijdag', 'Zaterdag' ];
	var monthnames = [ 'januari', 'februari', 'maart', 'april', 'mei', 'juni',
			'juli', 'augustus', 'september', 'oktober', 'november', 'december' ];
	var day = new Date();
	// today
	var millis = day.getTime();
	// milliseconds from 1970
	var dateselector = document.getElementById("dateselector");
	// populate dateselector
	for ( var i = 0; i < 31; i++) {
		var text;
		if (i == 0) {
			text = "Vandaag";
		} else if (i == 1) {
			text = "Morgen";
		} else {
			text = daynames[day.getDay()];
		}
		text = text + " " + day.getDate() + " " + monthnames[day.getMonth()];
		dateselector.options[i] = new Option(text, new Date(day.getFullYear(),
				day.getMonth(), day.getDate()));
		millis = millis + 24 * 60 * 60 * 1000;
		// add one day
		day.setTime(millis);
	}

}

function populateHourSelector() {
	var hourselector = document.getElementById("hourselector");
	var value;
	for ( var i = 0; i < 24; i++) {
		value = zeropadd(i.toString());
		hourselector.options[i] = new Option(value, value);
	}
}

function populateMinuteSelector() {
	var minuteselector = document.getElementById("minuteselector");
	var value;
	for ( var i = 0; i < 12; i++) {
                //WIJZ ZIJPP 20090827 5 min time steps
                p=5*i;
		value = zeropadd(p.toString());
		minuteselector.options[i] = new Option(value, value);

	}
}
 
function populateDepartSelector() {
	var departselector = document.getElementById("departselector");
	departselector.options[0] = new Option("Aankomst", 0);
	departselector.options[1] = new Option("Vertrek", 1);
	departselector.selectedIndex = 1;
}

function setDateFields(time) {
	var hourselector = document.getElementById("hourselector");
	var minuteselector = document.getElementById("minuteselector");
	var dateselector = document.getElementById('dateselector');
	hourselector.selectedIndex = (time.getHours()) % 24;
	minuteselector.selectedIndex = Math.ceil((time.getMinutes()) / 5) % 12;
	// 5 minute intervals
	var time = new Date(time.getFullYear(), time.getMonth(), time.getDate());
	for ( var i = 0; dateselector.options.length; i++) {
		if (time == dateselector.options[i].value) {
			dateselector.selectedIndex = i;
			break;
		}
	}
}
function getTime() {
	var hourselector = document.getElementById("hourselector");
	var minuteselector = document.getElementById("minuteselector");
	var dateselector = document.getElementById('dateselector');
	var time = new Date(dateselector.value);
	time.setHours(hourselector.value);
	time.setMinutes(minuteselector.value);
	return time;
}

function changeTime(date, deltat) {
	var millis = date.getMilliseconds();
	millis = millis + deltat;
	date.setMilliseconds(millis);
	var value = date.getFullYear().toString()
			+ zeropadd((date.getMonth() + 1).toString())
			+ zeropadd(date.getDate().toString())
			+ zeropadd(date.getHours().toString())
			+ zeropadd(date.getMinutes().toString());
	return value;

}

function zeropadd(nr) {
	if (nr.length == 1) {
		nr = "0" + nr;
	}
	return nr;
}

function clearMessage() {
	var resultscontainer = document.getElementById("results");
	resultscontainer.style.display = 'none';
	resultscontainer.innerHTML = "";
}
function showMessage(msg) {
	var resultscontainer = document.getElementById("results");
	resultscontainer.style.display = 'block';
	resultscontainer.innerHTML = msg;
}
function clearError() {
	var resultscontainer = document.getElementById("results");
	resultscontainer.style.display = 'none';
	resultscontainer.innerHTML = "";
}
function showError(xml) {
	var text = xml.getElementsByTagName("text")[0].childNodes[0].nodeValue;
	var code = xml.getElementsByTagName("code")[0].childNodes[0].nodeValue;
	var error_container = document.getElementById("errortext");
	error_container.innerHTML = text;

}
function clearAll() {
	clearMessage();
	clearError();
}

function initForm() {

	// Initialize form with blanco origin and destination
	var zip_from = "";
	var zip_to = "";

	// Look for the cookie
	if (document.cookie.length > 0) {
		cookieStart = document.cookie.indexOf(cookiename + "=");
		if (cookieStart != -1) {
			cookieStart += cookiename.length + 1;
			cookieEnd = document.cookie.indexOf(";", cookieStart);
			if (cookieEnd == -1) {
				cookieEnd = document.cookie.length;
			}
			cookietext = document.cookie.substring(cookieStart, cookieEnd);

			// Create stored variables with origin and destination
			bits = cookietext.split("|");
			zip_from = bits[0];
			zip_to = bits[1];
		}
	}

	// Set origin and destination
	document.getElementById('zip_from').value = zip_from;
	document.getElementById('zip_to').value = zip_to;
	// Fill selectors with options (depending on the time)
	populateSelectors();
	// Adjust selected time (30 minutes later)
	var time = new Date();
	// today
	var millis = time.getTime(); // milliseconds from 1970

        //WIJZ ZIJPP 20090827: use current time as departure time
	//millis = millis + 30 * 60 * 1000; // add 30 minutes
	//time.setTime(millis);
        //End WIJZ ZIJPP

	// Set selected time
	setDateFields(time);
}

function setCookie() {
	// Get origin and destination
	zip_from = document.getElementById('zip_from').value;
	zip_to = document.getElementById('zip_to').value;

	// Make cookie text
	var cookietext = cookiename + "=" + zip_from + "|" + zip_to;

	// Add extra argument 'expires'
	if (expiredays) {
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + expiredays);
		cookietext += ";expires=" + exdate.toGMTString();
	}

	// Write cookie
	document.cookie = cookietext;

}
