var journeyPlanner = {};

// ==================================================================
// This function enables/disables the computation of monomodal
// trips.
// ==================================================================

function checkPublicTransport()	{
	if(document.forms[0].option_2.checked == true) 
		document.forms[0].calcNumberOfTrips.value='4';
	else 
		document.forms[0].calcNumberOfTrips.value='0';
}


// ==================================================================
// This function displays/hides the options link for a certain mean  
// of transport.
// ==================================================================

function toggleOption(id,display) {
	if(document.getElementById(id)) {
		if(display)
			document.getElementById(id).style.display = 'inline';
		else
			document.getElementById(id).style.display = 'none';
	}
}


// ==================================================================
// This function initializes the option links.
// ==================================================================

function initializeOptions(noOfOptions) {
	for (var i=1; i<=noOfOptions; i++) {
		if (document.getElementById('optionLink_' + i) && document.getElementById('option_' + i))
			if (document.getElementById('option_' + i).checked)
				document.getElementById('optionLink_' + i).style.display = 'inline';
			else
				document.getElementById('optionLink_' + i).style.display = 'none';	
	}
}


// ==================================================================
// This function sets the hight for the input blocking div. 
// ==================================================================
function setHeight () {
	if (document.getElementById('blockInput')) {
		var windowHeight;

		if (document.documentElement && document.documentElement.scrollHeight) // Explorer 6 Strict Mode
			windowHeight = document.documentElement.scrollHeight;
		else // other Explorers
			windowHeight = document.body.offsetHeight;

		document.getElementById('blockInput').style.height = windowHeight + 'px';
	}
}



// ==================================================================
// This function sets the car options. The sum of the traveltime,
// cost and distance factor is 100. 
// ==================================================================

function setCarOptions() {
	if (document.getElementById('fastestCar') && document.getElementById('shortestCar') && document.getElementById('traveltimeFactorCar') && document.getElementById('distanceFactorCar')) {
		if (document.getElementById('shortestCar').checked) {
			document.getElementById('traveltimeFactorCar').value = '0';
			document.getElementById('distanceFactorCar').value = '100';
		}
		else {
			document.getElementById('traveltimeFactorCar').value = '100';
			document.getElementById('distanceFactorCar').value = '0';
		}
	}
}


// ==================================================================
// This function sets the walking speed if the walking speed in
// monomodal options is changed.
// ==================================================================

function setChangeSpeed() {
	if(document.getElementById('changeSpeed') && document.getElementById('speedFactorPedestrian')) {
		var speed = document.getElementById('speedFactorPedestrian').value;
		if (speed > 100) 
			document.getElementById('changeSpeed').value = 'fast';
		else if (speed < 100)
			document.getElementById('changeSpeed').value = 'slow';
		else
			document.getElementById('changeSpeed').value = 'normal';
	}
}


// ==================================================================
// This function sets the walking speed in monomodal walking options.
// ==================================================================

function setSpeedPedestrian() {
	if(document.getElementById('changeSpeed') && document.getElementById('speedFactorPedestrian')) {
		var speed = document.getElementById('changeSpeed').value;
		if (speed == 'fast') 
			document.getElementById('speedFactorPedestrian').value = '125';
		else if (speed == 'slow')
			document.getElementById('speedFactorPedestrian').value = '75';
		else
			document.getElementById('speedFactorPedestrian').value = '100';
	}
}									


// ==================================================================
// This function opens the detailview of a Journey, displays the
// journey on the map and closes the detailview of all other
// journeys.
// ==================================================================

function openDetailview(index,noOfRoutes,sessionID,requestID){
	// open detailview of the journey in the result section
	for (var i=1; i <= noOfRoutes; i++) {
		if(document.getElementById('overview_' + i) && document.getElementById('detail_' + i)) {
			document.getElementById('overview_' + i).style.display='block';
			document.getElementById('detail_' + i).style.display='none';
		}
	}
	if (document.getElementById('detail_' + index) && document.getElementById('overview_' + index)) {
		document.getElementById('detail_' + index).style.display='block';
		document.getElementById('overview_' + index).style.display='none';
	}

	// remove park and ride symbols
	if(mdvMap.markerLayer) 
		mdvMap.parkAndRideLayer.removeAllMarkers();
	
	// show the journey on the map
	try { 
		mdvMap.displayJourney(sessionID, requestID, index);
	}
	catch (e){}
	
	// display wizard button
	if (document.getElementById('wizard'))
		document.getElementById('wizard').style.display='inline';
	// store open journey 
	if(document.getElementById('itdLPxx_displayJourney'))
		document.getElementById('itdLPxx_displayJourney').value = index;
}


// ==================================================================
// This function closes the detailview of a journey.
// ==================================================================

function closeDetailview(index){
	// hide the journey in the result section
	if (document.getElementById('detail_' + index) && document.getElementById('overview_' + index)) {
		document.getElementById('detail_' + index).style.display='none';
		document.getElementById('overview_' + index).style.display='block';
	}
	// clear the map
	mdvMap.clearJourney();
	// hide wizard button
	if (document.getElementById('wizard'))
		document.getElementById('wizard').style.display='none';
	// empty storage of open journey	
	if(document.getElementById('itdLPxx_displayJourney'))
		document.getElementById('itdLPxx_displayJourney').value = '';
}


// ==================================================================
// This function opens or closes the detailed IT journey description
// of a partial route.
// ==================================================================

function togglePathDescription (id, open, close) {
	if (document.getElementById(id)) {
		if (document.getElementById(id).style.display!='block' && document.getElementById(close) && document.getElementById(close).style.display!='block' && document.getElementById(open)) {
			document.getElementById(id).style.display='block';
			document.getElementById(close).style.display='block';
			document.getElementById(open).style.display='none';
		}
		else if (document.getElementById(open) && document.getElementById(open).style.display=='none' && document.getElementById(close)) {
			document.getElementById(id).style.display='none';
			document.getElementById(close).style.display='none';
			document.getElementById(open).style.display='block';
		}
	}
		
}


// ==================================================================
// This function markes a selected odv of journey planner deteailview
// and shows the corresponding tooltip on the map.
// ==================================================================

function toggleTooltip (id, noOfPartialRoutes) {
	var odv = id.split('_');
	var route = odv[1];
	var partialRoute = odv[2] - 1;
	var usage;
	if(odv[3] == 2)
		usage = 'arrival';
	else
		usage = 'departure'
	
	var layer = mdvMap.mdvMap.getLayer('efa_trip');	
	var polylines = layer.getPolylines();
	var offset = 0;
	
	for (offset = 0; offset < polylines.length; offset++) {
		if (polylines[offset])
			break;
	}
	
	if (!polylines[partialRoute+offset].markers[usage].toolTip.isVisible()) {
		// centre point and open tooltip
		if (!mdvMap.mdvMap.getCentre().equals(polylines[partialRoute+offset].markers[usage].getCoords())) {
			mdvMap.mdvMap.setCentre(polylines[partialRoute+offset].markers[usage].getCoords().clone());
			mdvMap.mdvMap.update();
		}
		polylines[partialRoute+offset].markers[usage].toolTip.display();
		// set marker in route detailview on selected point
		if (document.getElementById(id)) {
			// removes all markers in route detailview
			closeTooltip (route, noOfPartialRoutes);
			// set marker in detailview
			document.getElementById(id).className = 'selectedRow';
		}
	} 
	else {
		// centre point and open/close tooltip
		polylines[partialRoute+offset].markers[usage].toolTip.hide();
	
		// set marker in route detailview on selected point
		if (document.getElementById(id)) {
			// removes all markers in route detailview
			closeTooltip (route, noOfPartialRoutes);
	
		}
	}
}


// ==================================================================
// This function removes the marker of the selected odv of journey
// planer detailview and closes the tooltip on the map.
// ==================================================================

function closeTooltip (route, noOfPartialRoutes) {
	for (var partialRoute=1; partialRoute<=noOfPartialRoutes; partialRoute++) {
		for (var point=1; point<=2; point++) {
			if (document.getElementById('odv_' + route + '_' + partialRoute + '_' + point )) {
				if (partialRoute % 2 == 0) 
					document.getElementById('odv_' + route + '_' + partialRoute + '_' + point ).className = 'evenRow point';
				else 
					document.getElementById('odv_' + route + '_' + partialRoute + '_' + point ).className = 'oddRow point';
			}	

		}
	}
}


// ==================================================================
// This function returns the clients time - hour.
// ==================================================================

function returnHours () {
	var date = new Date();
	var hours = date.getHours();
	return hours;
}


// ==================================================================
// This function returns the clients time - minutes.
// ==================================================================

function returnMinutes () {
	var date = new Date();
	var minutes = date.getMinutes();
	return minutes;
}


// ==================================================================
// This function returns the clients date - day.
// ==================================================================

function returnDay () {
	var date = new Date();
	var day = date.getDate();
	if (day < 10)
		day = '0' + day;
	return day;
}


// ==================================================================
// This function returns the clients date - month.
// ==================================================================

function returnMonth () {
	var date = new Date();
	var month = date.getMonth() + 1;
	if (month < 10)
		month = '0' + month;
	return month;
}


// ==================================================================
// This function returns the clients date - year.
// ==================================================================

function returnYear () {
	var date = new Date();
	var year = date.getFullYear();
	return year;
}
						

// ==================================================================
// This function sets the example for origin/destination.
// ==================================================================

function setOdvExample (name, usage) {
	if (document.getElementById('name_' + usage))
		document.getElementById('name_' + usage).value= decode_utf8(name);
	if (document.forms[0].execInst){
		document.forms[0].execInst.value='verifyOnly';
		document.forms[0].submit();
	}
}


// ==================================================================
// This function sets the example for departure/arrival date and
// time.
// ==================================================================

function setDateTimeExample (hours, minutes, day, month, year, usage) {
	if (usage == 'arr' && document.getElementById('arrival')) 
		document.getElementById('arrival').checked = 'checked'; 
	else if (document.getElementById('departure')) 
		document.getElementById('departure').checked = 'checked';
	if(document.forms[0].itdTimeHour)
		document.forms[0].itdTimeHour.value = hours;
	if(document.forms[0].itdTimeMinute)
		document.forms[0].itdTimeMinute.value = minutes;
	if(document.forms[0].itdDateDay)
		document.forms[0].itdDateDay.value = day;
	if(document.forms[0].itdDateMonth)
		document.forms[0].itdDateMonth.value = month;
	if(document.forms[0].itdDateYear)
		document.forms[0].itdDateYear.value = year;
}


// ==================================================================
// This selects/deseclts public transport as an example option.
// ==================================================================

function togglePT (selectPT) {
	if (document.getElementById('selectPT') && document.getElementById('deselectPT') && document.getElementById('option_2'))  {
		// select
		if (selectPT) {
			document.getElementById('selectPT').style.display = 'none'; 
			document.getElementById('deselectPT').style.display = 'block'; 
			document.getElementById('option_2').checked = 'checked';
			if (document.getElementById('optionsPT')) 
				document.getElementById('optionsPT').style.display = 'block';
			toggleOption('optionLink_2',true);			
		}
		// deselect 
		else {
			document.getElementById('selectPT').style.display = 'block'; 
			document.getElementById('deselectPT').style.display = 'none'; 	
			document.getElementById('option_2').checked = '';
			if (document.getElementById('optionsPT')) 
				document.getElementById('optionsPT').style.display = 'none';
			toggleOption('optionLink_2',false);
		}	
	}
}


// ==================================================================
// This selects/deseclts walk as an example option.
// ==================================================================

function toggleWalk (selectWalk) {
	if (document.getElementById('selectWalk') && document.getElementById('deselectWalk') && document.getElementById('option_3'))  {
		// select
		if (selectWalk) {
			document.getElementById('selectWalk').style.display = 'none'; 
			document.getElementById('deselectWalk').style.display = 'block'; 
			document.getElementById('option_3').checked = 'checked';
			if (document.getElementById('optionsWalk')) 
				document.getElementById('optionsWalk').style.display = 'block';	
			toggleOption('optionLink_3',true);
		}
		// deselect 
		else {
			document.getElementById('selectWalk').style.display = 'block'; 
			document.getElementById('deselectWalk').style.display = 'none'; 	
			document.getElementById('option_3').checked = '';
			if (document.getElementById('optionsWalk')) 
				document.getElementById('optionsWalk').style.display = 'none';
			toggleOption('optionLink_3',false);
		}	
	}
}


// ==================================================================
// This function selects least interchanges option as an example of
// pt options.
// ==================================================================

function ptLeastChangesExample () {
	openAdvancedOption('advancedOptions_2');
	if(document.forms[0].routeType && document.forms[0].routeType.options[1])
		document.forms[0].routeType.options[1].selected = 'selected';
}


// ==================================================================
// This function selects no solid stairs option as an example of
// pt options.
// ==================================================================

function ptNoStairsExample () {
	openAdvancedOption('advancedOptions_2');
	if(document.forms[0].noSolidStairs)
		document.forms[0].noSolidStairs.checked = 'checked';
}


// ==================================================================
// This function sets the speed of monomodal walks to slow as an 
// example for walk options.
// ==================================================================

function walkSpeedExample () { 
	openAdvancedOption('advancedOptions_3');
	if(document.forms[0].speedPedestrian.options[2])
		document.forms[0].speedPedestrian.options[2].selected = 'selected';
}


// ==================================================================
// This function toggles the cycling route option.
// ==================================================================

function toggleCyclingRouteType (routeType, active) {
	// reset all cycling rout options and descriptions
	document.getElementById('preferGreenTracks').value = '0';
	document.getElementById('preferAsphaltTracks').value = '0';
	document.getElementById('usePseudoRouting').value = '0';
	document.getElementById('useElevationData').value = '0';
	// activate selected route type 
	if (active) {
		if (routeType == 'leisureRoute') {
			document.getElementById('preferGreenTracks').value = '1';
			document.getElementById('useElevationData').value = '1';
			document.getElementById('usePseudoRouting').value = '1';
			document.getElementById('speedFactorBicycle').value = '100';
		}
		else if (routeType == 'advancedRoute') {
			document.getElementById('preferAsphaltTracks').value = '1';
			document.getElementById('speedFactorBicycle').value = '133';
		}
		else if (routeType == 'saveRoute') {
			document.getElementById('usePseudoRouting').value = '1';
			document.getElementById('speedFactorBicycle').value = '100';
		}
	}
}


// ==================================================================
// This function gets the park + ride places and garages for a monomodal
// car journey and displays them on the map.
// ==================================================================

function parkingSearch (parkingSearchCenter) {
	var parkings = new MDVEFAParkingSearch('XSLT_PARKOBJECT_REQUEST');
	parkings.getParkings (parkingSearchCenter);
	if (document.getElementById('itdLPxx_showParking'))
		document.getElementById('itdLPxx_showParking').value = parkingSearchCenter;
}


// ==================================================================
// This removes the parkings if the monomodal car journey is closed.
// ==================================================================

function removeParkings () {
	mdvMap.parkAndRideLayer.removeAllMarkers();
}


// ==================================================================
// This function can be overwritten to disable the example for walking 
// options selection/deselection.
// ==================================================================

function disableDeselectWalk() { }


// ==================================================================
// This function can be overwritten to add functionality before 
// submit.
// ==================================================================

function preSubmit() {}


// ==================================================================
// This function gets the elevation profile.
// ==================================================================

function doElevationProfile (routeIdx, sessionID, requestID, virtDir, position) {
	// elevation profiles of different routes might not be the same
    /*if (mdvLib.$('advancedOptions_elevationProfile1') && position === 1) {
        openAdvancedOption('advancedOptions_elevationProfile1');
        return;
    }
	if (mdvLib.$('advancedOptions_elevationProfile2') && position === 2) {
        openAdvancedOption('advancedOptions_elevationProfile2');
        return;
    }*/

	journeyPlanner.elevPos = position;
	
    var _params = {
        sessionID: sessionID,
        requestID: requestID,
        imageFormat: 'PNG',
        purpose: 'RRP',
        command: 'ElevationProfile:'+routeIdx,
        itdLPxx_elevationProfileViaAjax: 'yes',
		imageWidth: '470',
		imageHeight: '350'
    };
    
    var _ajax = mdvLib.ajax({host: '/' + virtDir + '/XSLT_TRIP_REQUEST2', method: 'get', parameters: _params, onComplete: elevationProfileOnComplete}); 
};

function elevationProfileOnComplete (res) {   
    // strip newlines, CR, LF
    function _clean(str) {
        return str.replace(/[\n\r\t]/g, '');
    }
 
    var result = _clean(res.responseText);
  
    // use regExp from mdv.py
    re = /<efa +class=["\']efa_building_block["\'] +id=["\'](\w+)["\']>(.*?)<\/efa>/g;
	var tmp = result;
	var out = '';
	    
    // we're interested only in the contents 
    // within the <efa> block, not the id
	while (tmp = re.exec(result)) {
		out += tmp[2];
	}
		
    var div = document.createElement('div');
        div.id = 'tmpDiv';
        div.className = 'its-efa-popupblock';
        div.innerHTML = out;
        
    document.body.appendChild(div);
    
	if (journeyPlanner.elevPos === '1') {
		openAdvancedOption('advancedOptions_elevationProfile1');
	}
	else {
		openAdvancedOption('advancedOptions_elevationProfile2');
	}
};


// ==================================================================
// This function gets the GPX track.
// ==================================================================

function doGPXTrack (routeIdx, sessionID, requestID, virtDir) {
    if (mdvLib.$('advancedOptions_gpx')) {
        openAdvancedOption('advancedOptions_gpx');
        return;
    }
	
    var _params = {
        sessionID: sessionID,
        requestID: requestID,
        command: 'GPXTrack:'+routeIdx,
        itdLPxx_gpx: 'true'
    };
    
    var _ajax = mdvLib.ajax({host: '/' + virtDir + '/XSLT_TRIP_REQUEST2', method: 'get', parameters: _params, onComplete: gpxTrackOnComplete}); 
};

function gpxTrackOnComplete (res) {   
    // strip newlines, CR, LF
    function _clean(str) {
        return str.replace(/[\n\r\t]/g, '');
    }
 
    var result = _clean(res.responseText);
  
    // use regExp from mdv.py
    var re = /<efa +class=["\']efa_building_block["\'] +id=["\'](\w+)["\']>(.*?)<\/efa>/g;
	var tmp = result;
	    
    // we're interested only in the contents 
    // within the <efa> block, not the id
	if (result.indexOf('<efa') > -1) {
		tmp = re.exec(result)[2] || 'Sorry, but a server error occurred while fetching the gpx data.';
	}
		
    var div = document.createElement('div');
        div.id = 'tmpDiv';
        div.className = 'its-efa-popupblock';
        div.innerHTML = tmp;
        
    document.body.appendChild(div);
    
    openAdvancedOption('advancedOptions_gpx');
};

// ==================================================================
// This function opens the first trip if only one trip available.
// ==================================================================

function openFirstJourney() {
	// Find the first journey. Consider that there might be alternative journeys which are not displayed.
	for (var id=1; id<10; id++) {
		if (document.getElementById('overview_' + id)) {
			if(document.getElementById('overview_' + id).getElementsByTagName('div')[0] && typeof(document.getElementById('overview_' + id).getElementsByTagName('div')[0].onclick)=='function') 
				document.getElementById('overview_' + id).getElementsByTagName('div')[0].onclick();
			else if (typeof(document.getElementById('overview_' + id).getElementsByTagName('a')[0].onclick)=='function')
				document.getElementById('overview_' + id).getElementsByTagName('a')[0].onclick();
			break;
		}
	}
}