/*
// Function List:

function pointToTrip(id)
function selectTable(id)
function ClearReadOnly()
function OperatorSelectionSetSelection(select, type)
function removeUseOnly(select, obj)
function disableOtherOP(type1, type2, obj)
function changeImg(obj)
function changeColor(parObj, obj)
function findeO(obj)
function viewFootpath(obj, route, pos)
function collapsingSummary()
function viewCarrier(type)
function addCarriers()
function removeCarriers(name, type, carrierType)
function removePrefer()

// **** calendar
function PadSpaces(TheString)
function NumLeapYears(StartYear, EndYear)
function IsLeapYear(Year)
function Trim(TheString)
function DetermineMonthIdx()
function FindNewYearStartingDay(Year)
function FindNumDaysInMonth(Year, Month)
function FindMonthStartDay(NewYearDay, Year, Month)
function FillCalendar(type)
function IncDecYear(step, type)
function IncDecMonth(val, type)
function checkDate(obj)

function isNumeric(strString)
function changeMapText(obj, type, line, coords)
function insertDate(obj, type)
function expandContractAll(elem, style)
function applyFootpathTravelTime(e) 
function applyAgencies() 
function applyAgency(id) 
function fixLegend(obj) 
function findBox(type, headerText, request)
function findBoxOutput(type)
function setPoint(usage)
function cancelPoint(usage)
function checkLandmarkOnLoad()
function blockTabContent(type)
function setTripFuctionDesc(e) 
function doSomethingWithSpanClasses(theClass, style) 
function hideFeedbackEmailForm()
function findFeedbackPos(e)
function showAnnouncements(e, head, content) 
function showCustomizedSchedule(e,sourceobjid)
function onCustomizedSchedule(response) 
function checkValidFeedbackForm(form,sourcebtnid)
function sendFeedback()
function spamPrompt()
function checkValidURL(value)
function closeFeedbackForm(e)

function trim(subject) 
function sendMailAFriend() 
function validateMailForSpam()
function alertForSpamMail()
function sendMail() 
function closeMailAFriend(e) 

function changeMapHelpLink(newId)
function changeHelpLink(linkId, helpId)
function depsEarlier(e, session, id, time, date) 
function depsLater(e, session, id, time, date) 
function customizedScheduleEarlier(e)
function customizedScheduleLater(e)
function findPos(obj) 

function createHelpOverlay(e, header, content, obj, align)
function applyOnChangeSpeedChange() 
function onFootpathTravelTime(e) 
function attachEventListener(target, eventType, functionRef, capture)
function checkanyObjFilter(callingelement)//Mantis Issue-3386
function checkNameInputOnSubmit()
function sendPOIRequest(place, name, session, state, type, request, divId)
function sendPOICoordRequest(req)
function onPlaceSelectionCallback(response)
function onPoiSelectionCallback(request)
function beautifyMap(coords) 
function viewNextPois(objId)
function viewPrevPois(objId)
function getNearbyAttractions(omc, placeID, x, y, divId)
function sendPOIHierarchyRequest(x, y, session, state, type, request, divId)
function sendPOIHierarchyRequestCallback(request)
function showSubHierarchy(obj)
function sendNewPOICoordRequest(obj)
function goBackToOriginalBubbleContent(obj)
function checkInitialTab() 
function checkForTicker() 
function moveTicker() 
function getTickerFetchUrl() 
function showTransitProviders()
function checkSelMOT(obj)
function intervalAnnouncement()
function reloadAnnouncement()
function onReloadAnnoncementCallback(response)
function SingleSelect(regex,current)
function SelectUseOnlyUptoNItems(regex,current,numItems)
function setSelectedUseOnly(regex)
function ClearUseOnlyOPSelection()
function ClearMustExclOPSelection()
function disableMustExclOP()
function disableUseOnlyOP()
function SelectMustExcUptoNItems(regex,current,numItems)
function setSelectedMustExc(regex)
sfHover = function() 
function showLayer()
function getElementsByClassName( strClassName, obj ) 

function PrintAgencies() 
function formatPrintContent(content) 
function getPrintHeader() 
function getPrintFooter() 
function PrintAnnouncement() 
function PrintScheduleBubble()
function expandShortNames(content)
function expandShortNamesForRoutes(content)
function GetStationName(stopID)
function PrintScheduledDeparturesBubble(stopID)
function PrintAllFacilities(stopID)
function PrintFacilities(stopID)
function PrintFacility(stopID)
function PrintHelpBubble()

function checkRailLines(mdvMapVal)
function trimEmail(str)
ChangePageTitle =function(title)
ChangeTabTitle =function(tabindx)
SendMailClick= function(btnemail)
function closeRailFerrySelection(usage,type)

function showTripFeedBack(feedbtnid,emailbtnid)
function closeFeedBack(feedbtnid,emailbtnid)
function showNrsFeedBack(feedbtnid,blnstops)
function showTripEmail(emailbtnid)
function SetTripSearchLinkIndexes(btnid,blnReset)
setFocusById =function (elementid)
function hideSelect()
function  hideSelectDm()
function showSelectDm()
function showSelect()

function focusonMobilelink()
function hideMobileTool()
function showMobileTool()
function HideStartEndButton()
function ResetToDefault()
function validateOriginDestination()

*/


var legId = '';

var storedOrig ='';
var storedDest ='';
var storedVia ='';
var storedDM='';

var storedDivId='';
var originalBubbleContent='';

var createLayer='0';

var ticker = null;

var selectedUseOnly = new Array(); //Mantis 3089
var mustExcOpOnly = new Array(); //Mantis 3089

var PrintWindowParams="width=1000,height=780,location=no,menubar=yes,resizeble=no,scrollbars=yes,status=yes,toolbar=no,fullscreen=no"; //Mantis 3146

if (typeof String.prototype.trim != 'function')
	String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function pointToTrip(id)
{    
    if(legId != id)
	{
	   
        document.getElementById('tableTrip_' +id).style.cursor='pointer';
        document.getElementById('tableTrip_' +id).style.cursor='hand';        
    }
    else
    {
        document.getElementById('tableTrip_' +id).style.cursor='';
    }
}

function selectTable(id, markID, mode){

	var markTblID = id;
	
	if(markID){
		markTblID = markID + id;
	}
    

	if(legId != markTblID)
	{
		
		document.getElementById('tableTrip_' +markTblID).style.backgroundColor ='#c6e8f4';
		
		if(document.getElementById('tableTripNext_' +markTblID)){
			document.getElementById('tableTripNext_' +markTblID).style.backgroundColor ='#c6e8f4';
		}
		
		if(!mode || mode!='LEASTCOST'){
			document.getElementById('tableTripHidden_' +id).style.backgroundColor ='#c6e8f4';
			document.getElementById('tableHidden_' +id).style.display ='';
		}
		
		 for(var i=0; i< document.getElementById('tableTrip_' +markTblID).childNodes.length; i++){
			if(document.getElementById('tableTrip_' +markTblID).childNodes[i]){
				if(document.getElementById('tableTrip_' +markTblID).childNodes[i].style){
					document.getElementById('tableTrip_' +markTblID).childNodes[i].style.borderTop = 'solid #2082a2 1px';
					
					if(document.getElementById('tableTripNext_' +markTblID)){
						document.getElementById('tableTripTdNext_' +markTblID).style.borderBottom = 'solid #2082a2 1px';
					}
					else{
						document.getElementById('tableTrip_' +markTblID).childNodes[i].style.borderBottom = 'solid #2082a2 1px';
					}
					
					if(!mode || mode!='LEASTCOST'){
						document.getElementById('tableTripHidden_' +id).childNodes[i].style.borderTop = 'solid #2082a2 1px';
						document.getElementById('tableTripHidden_' +id).childNodes[i].style.borderBottom = 'solid #2082a2 1px';
					}
					
				}
			}
		}
		
		if(document.getElementById('tableTripNext_' +markTblID)){
			document.getElementById('tableTripTdNext_' +markTblID).style.borderBottom = 'solid #2082a2 1px';
		}
		
		document.getElementById('itineraryBox_' +id).style.display ='block';
		if(document.getElementById('spanTable_' +id)){
			document.getElementById('spanTable_' +id).style.fontWeight ='bold';
			document.getElementById('spanTable_' +id).style.textDecoration ='none';
			document.getElementById('spanTableHidden_' +id).style.fontWeight ='bold';
			document.getElementById('spanTableHidden_' +id).style.textDecoration ='none';
		}

		// reset the last selected trip 
		if(document.getElementById('tableTrip_' +legId)){
			document.getElementById('tableTrip_' +legId).style.backgroundColor ='';
			
			for(var i=0; i< document.getElementById('tableTrip_' +id).childNodes.length; i++){
				if(document.getElementById('tableTrip_' +legId).childNodes[i]){
					if(document.getElementById('tableTrip_' +legId).childNodes[i].style){
						document.getElementById('tableTrip_' +legId).childNodes[i].style.borderTop = 'none';
						document.getElementById('tableTrip_' +legId).childNodes[i].style.borderBottom = 'none';
					}
				}
			} 
			
			if(document.getElementById('tableTripNext_' +legId)){
				document.getElementById('tableTripNext_' +legId).style.backgroundColor ='';
			}
			
			if(document.getElementById('tableTripNext_' +legId)){
				document.getElementById('tableTripTdNext_' +legId).style.borderBottom = 'none';
			}
			
			if(!mode || mode!='LEASTCOST'){
				document.getElementById('tableHidden_' +legId).style.display ='none';
			}
			
			// hide the last detail trip 
			if(isNaN(legId) && legId.indexOf('_')){
				legId = parseInt(legId.substring(legId.indexOf('_')+1));
			}
			
			if(legId != id){
				document.getElementById('itineraryBox_' +legId).style.display ='none';
				if(document.getElementById('spanTable_' +legId)){
					document.getElementById('spanTable_' +legId).style.fontWeight ='normal';
					document.getElementById('spanTable_' +legId).style.textDecoration ='underline';
				}
			}
			
		}
			
		if(markID){
			legId = markID + id;
		}
		else{
			legId = id;
		}
		
	}
	
}

// this function expand / collapse the the least cost trips in the summary
function expandCollapseLCTrips(state, pos, e){

	var cheapest = document.getElementById('leastCostSum_1');
	if (cheapest && cheapest.getAttribute('level') == '0')
		cheapest = document.getElementById('leastCostSum_2');

	var arrdep = document.getElementById('itdTripDateTimeDepArr');
	var arrpos = null;
	
	if (cheapest && arrdep && arrdep.value == 'arr') {
		var containers = cheapest.getElementsByClassName('container');		
		if (containers.length > 0) {
			var c = containers[containers.length-1];
			arrpos = c.id.substr(10);
		}
	}
	
	if(state=='collapse'){
		document.getElementById('tableTrip_click_' + pos).style.display='';
		
		if(document.getElementById('tableTripNext_click_' + pos)){
			document.getElementById('tableTripNext_click_' + pos).style.display='';
		}
		
		document.getElementById('thisFareCat_' + pos).style.display='none';
		selectTable(pos, 'click_', 'LEASTCOST');
	}
	else{
		document.getElementById('tableTrip_click_' + pos).style.display='none';
		
		if(document.getElementById('tableTripNext_click_' + pos)){
			document.getElementById('tableTripNext_click_' + pos).style.display='none';
		}
		
		document.getElementById('thisFareCat_' + pos).style.display='';
		
		if (arrpos)
			pos = arrpos;
		
		selectTable(pos, '', 'LEASTCOST');
	}
	
	if(e == 'load'){
		return false;
	}
	
	
	if (!e) var e = window.event;
	//e.cancelBubble is supported by IE - this will kill the bubbling process.
	e.cancelBubble = true;
	e.returnValue = false;
	
	//e.stopPropagation works only in Firefox.
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	}

}

function ClearReadOnly()
{
	var count = 0;
	var useOnlyOP = document.forms[0].useOnlyOP;
	var preferInclOP = document.forms[0].preferInclOP;
	var mustExclOP = document.forms[0].mustExclOP;

	if (preferInclOP && mustExclOP) 
	{
	
		for (var iIndex = 0; iIndex < useOnlyOP.length; iIndex++)

			if(useOnlyOP[iIndex] && useOnlyOP[iIndex].checked==true)
			{
				useOnlyOP[iIndex].checked=false;
				useOnlyOP[iIndex].disabled=false;
				useOnlyOP[iIndex].parentNode.style.color='#3f3f3f';
				++count
			}
			
		if (count > 0) {

			for (var iIndex = 0; iIndex < preferInclOP.length; iIndex++)

				if(preferInclOP[iIndex])
				{
					preferInclOP[iIndex].disabled=false;
					preferInclOP[iIndex].parentNode.style.color='#3f3f3f';
				}

			for (var iIndex = 0; iIndex < mustExclOP.length; iIndex++)

				if(mustExclOP[iIndex])
				{
					mustExclOP[iIndex].disabled=false;
					mustExclOP[iIndex].parentNode.style.color='#3f3f3f';
				}
		}
	}
}

function OperatorSelectionSetSelection(select, type)
{

	var obj = document.forms[0].preferInclOP;
	
	var useOnlyOP = document.forms[0].useOnlyOP;
	var preferInclOP = document.forms[0].preferInclOP;
	var mustExclOP = document.forms[0].mustExclOP;
	

	
	if(type=='mustExclOP')
	{
		obj = document.forms[0].mustExclOP;
	}
	else if(type=='useOnlyOP'){
		obj = document.forms[0].useOnlyOP;
	}

	
	if (obj)
	{
		for (var iIndex = 0; iIndex < obj.length; iIndex++)
		
			if(obj[iIndex].checked==true){

				obj[iIndex].checked=select;

				document.forms[0].preferInclOP[iIndex].disabled=false;
				document.forms[0].mustExclOP[iIndex].disabled=false;
				document.forms[0].useOnlyOP[iIndex].disabled=false;

				document.forms[0].preferInclOP[iIndex].parentNode.style.color='#3f3f3f';
				document.forms[0].mustExclOP[iIndex].parentNode.style.color='#3f3f3f';
				document.forms[0].useOnlyOP[iIndex].parentNode.style.color='#3f3f3f';
		
			}
	}
	
	var count = 0;

	if (useOnlyOP)
	{
		for (var iIndex = 0; iIndex < preferInclOP.length; iIndex++)

			if(preferInclOP[iIndex] && preferInclOP[iIndex].checked==true)
			{
				++count
			}



		for (var iIndex = 0; iIndex < mustExclOP.length; iIndex++)

			if(mustExclOP[iIndex] && mustExclOP[iIndex].checked==true)
			{
				++count
			}



		if (useOnlyOP && count > 0)
		{
			for (var iIndex = 0; iIndex < useOnlyOP.length; iIndex++)

				if(useOnlyOP[iIndex])
				{
					useOnlyOP[iIndex].disabled=true;
					useOnlyOP[iIndex].parentNode.style.color='#999999';
				}
		}	
		else if(count == 0){

			for (var iIndex = 0; iIndex < useOnlyOP.length; iIndex++)

				if(useOnlyOP[iIndex])
				{
					useOnlyOP[iIndex].disabled=false;
					useOnlyOP[iIndex].parentNode.style.color='#3f3f3f';
				}
		}

	}

	
}


function removeUseOnly(select, obj)
{

	var useOnlyOP = document.forms[0].useOnlyOP;
	var preferInclOP = document.forms[0].preferInclOP;
	var mustExclOP = document.forms[0].mustExclOP;
	
	var count = 0;
	
		if (useOnlyOP)
		{
			for (var iIndex = 0; iIndex < useOnlyOP.length; iIndex++)

				if(useOnlyOP[iIndex].checked==true)
				{
					++count;
				}
		}
		
		if (preferInclOP)
		{
			for (var iIndex = 0; iIndex < preferInclOP.length; iIndex++)

				if(preferInclOP[iIndex] && obj.checked==true)
				{
					preferInclOP[iIndex].disabled=true;
					preferInclOP[iIndex].parentNode.style.color='#999999';
				}
				else if(preferInclOP[iIndex] && count == 0){
					preferInclOP[iIndex].disabled=false;
					preferInclOP[iIndex].parentNode.style.color='#3f3f3f';
				}
		}
		
		if (mustExclOP)
		{
			for (var iIndex = 0; iIndex < mustExclOP.length; iIndex++)

				if(mustExclOP[iIndex] && obj.checked==true)
				{
					mustExclOP[iIndex].disabled=true;
					mustExclOP[iIndex].parentNode.style.color='#999999';
				}
				else if(mustExclOP[iIndex] && count == 0){
					mustExclOP[iIndex].disabled=false;
					mustExclOP[iIndex].parentNode.style.color='#3f3f3f';
				}				
		}
}





function disableOtherOP(type1, type2, obj){

	var id=  obj.value.split(':');
	var useOnlyOP = document.forms[0].useOnlyOP;
	var preferInclOP = document.forms[0].preferInclOP;
	var mustExclOP = document.forms[0].mustExclOP;
	

	if(obj.checked==true){
		document.getElementById(type1 + '_'+ id[2]).disabled=true;
		document.getElementById('span' + type1 + '_'+ id[2]).style.color='#999999';
		
		document.getElementById(type2 + '_'+ id[2]).disabled=true;
		document.getElementById('span' + type2 + '_'+ id[2]).style.color='#999999';
	}
	else{
		document.getElementById(type1 + '_'+ id[2]).disabled=false;
		document.getElementById('span' + type1 + '_'+ id[2]).style.color='#3f3f3f';
		
		document.getElementById(type2 + '_'+ id[2]).disabled=false;
		document.getElementById('span' + type2 + '_'+ id[2]).style.color='#3f3f3f';
	}
	
	
	if(type2=='useOnlyOP'){

		var count = 0;
		
		if (useOnlyOP)
		{
			for (var iIndex = 0; iIndex < preferInclOP.length; iIndex++)

				if(preferInclOP[iIndex] && preferInclOP[iIndex].checked==true)
				{
					++count
				}
				
			
			
			for (var iIndex = 0; iIndex < mustExclOP.length; iIndex++)

				if(mustExclOP[iIndex] && mustExclOP[iIndex].checked==true)
				{
					++count
				}
				
			
			if (useOnlyOP && count > 0)
			{
				for (var iIndex = 0; iIndex < useOnlyOP.length; iIndex++)

					if(useOnlyOP[iIndex])
					{
						useOnlyOP[iIndex].disabled=true;
						useOnlyOP[iIndex].parentNode.style.color='#999999';
					}
			}	
			else if(count == 0){
			
				for (var iIndex = 0; iIndex < useOnlyOP.length; iIndex++)

					if(useOnlyOP[iIndex])
					{
						useOnlyOP[iIndex].disabled=false;
						useOnlyOP[iIndex].parentNode.style.color='#3f3f3f';
					}
			
			
			}
			
		}
		
	}
	
	checkSelMOT('OP');

}


function changeImg(obj){

	if(obj.className=='routesListingBox'){
		obj.className='routesListingBox routesListingBoxOn';
	}
	else{
		obj.className='routesListingBox';
	}
}

function changeColor(parObj, obj){
	if(parObj.className=='routesListingBox'){
		obj.style.color='#702E30';
	}
	else{
		obj.style.color='#3F3F3F';
	}
}



function findeO(obj){
var oPos = 0;

	if(obj!=null){
		if (obj.offsetParent)
		{
		while (obj.offsetParent)
		{
		oPos += obj.offsetTop
		obj = obj.offsetParent;
		}
		}
		else if (obj.y)
		oPos += obj.y;
		return oPos;
	}
}


function viewFootpath(obj, route, pos){

	if(obj.className=='routeTable' || obj.className==''){
		obj.className='routeTableOn';
		document.getElementById('footpathDetails_' + route + '_' + pos).style.display='';
	}
	else{
		obj.className='routeTable';
		document.getElementById('footpathDetails_' + route + '_' + pos).style.display='none';
	}

}

function collapsingSummary(){

	if(document.getElementById('collapsingSummary').className==='inactive' || document.getElementById('collapsingSummary').className===''){
		document.getElementById('collapsingSummary').className='active';
		document.getElementById('ScrollDiv').style.display='';
		document.getElementById('ScrollDivHidden').style.display='none';
	}
	else{
		document.getElementById('collapsingSummary').className='inactive';
		document.getElementById('ScrollDiv').style.display='none';
		document.getElementById('ScrollDivHidden').style.display='';
	}


}


function viewCarrier(type){

	if(type=='Rail'){
		document.getElementById('busCarriers').style.display='none';
		document.getElementById('railCarriers').style.display='';
		document.getElementById('ferryCarriers').style.display='none';
	}
	else if(type=='Ferry'){
		document.getElementById('busCarriers').style.display='none';
		document.getElementById('railCarriers').style.display='none';
		document.getElementById('ferryCarriers').style.display='';
	}
	else{
		document.getElementById('busCarriers').style.display='';
		document.getElementById('railCarriers').style.display='none';
		document.getElementById('ferryCarriers').style.display='none';
	}
	
	
//	removeUseOnly()
	

}



function addCarriers()
{

	var countOp = document.getElementById('countOperator').select;
	
	
	//operatorSelection
	
	var carrierType = document.forms[0].carrier.value;
	
	var elements = document.forms[0].elements.length;
	
	
	 for (var i = 0; i <= elements; i++)
	{		

		if(document.forms[0].elements[i]){
	
			if(document.forms[0].elements[i].type == 'checkbox'){

				var opValue = document.forms[0].elements[i].value.split(':');

				var id = opValue[1];

				if(document.getElementById('operator' + carrierType +'_' +id)){
					if(document.getElementById('operator' + carrierType +'_' +id).checked==true && document.getElementById('useOnlyCheckbox').checked==true){
						var selection = document.getElementById('only');
						var opName = document.getElementById('operator' + carrierType +'_' +id).value.split(':');
						var newspan = document.createElement('span');
						if(document.getElementById('only').innerHTML.indexOf(opName[0]) =='-1'){
							document.getElementById('spanOperator' + carrierType +'_' +id).style.color="#979797";
							document.getElementById('operator' + carrierType +'_' +id).disabled="disabled";
							document.getElementById('operator' + carrierType +'_' +id).checked= false;

							newspan.setAttribute("id", "remove_" + opName[1]);
							newspan.innerHTML = opName[0] + " <a href=\"javascript:removeCarriers('" + opName[1] + "', 'only', '" + carrierType +"')\">&#171; remove</a><input type=\"hidden\" name=\"useOnlyOP\" value=\"oak:" + opName[0] + ":" + opName[1] +"\" /> <br />";
							selection.appendChild(newspan);
						}
					}
				}

				if(document.getElementById('operator' + carrierType +'_' +id)){
					if(document.getElementById('operator' + carrierType +'_' +id).checked==true && document.getElementById('mustExcludeCheckbox').checked==true){
						var selection = document.getElementById('exclude');
						var opName = document.getElementById('operator' + carrierType +'_' +id).value.split(':');
						var newspan = document.createElement('span');

						//alert(document.getElementById('exclude').innerHTML.indexOf(opName[0]));
						if(document.getElementById('exclude').innerHTML.indexOf(opName[0]) =='-1'){
							document.getElementById('spanOperator' + carrierType +'_' +id).style.color="#979797";
							document.getElementById('operator' + carrierType +'_' +id).disabled="disabled";
							document.getElementById('operator' + carrierType +'_' +id).checked= false;

							newspan.setAttribute("id", "remove_" + opName[1]);
							newspan.innerHTML = opName[0] + " <a href=\"javascript:removeCarriers('" + opName[1] + "', 'exclude', '"  + carrierType +"')\">&#171; remove</a><input type=\"hidden\" name=\"mustExclOP\" value=\"oak:" + opName[0] + ":" + opName[1] +"\" /><br />";
							selection.appendChild(newspan);
						}
					}
				}

				if(document.getElementById('operator' + carrierType +'_' +id)){
					if(document.getElementById('operator' + carrierType +'_' +id).checked==true && document.getElementById('preferIncludeCheckbox').checked==true){
						var selection = document.getElementById('include');
						var opName = document.getElementById('operator' + carrierType +'_' +id).value.split(':');
						var newspan = document.createElement('span');
						if(document.getElementById('include').innerHTML.indexOf(opName[0]) =='-1'){
							document.getElementById('spanOperator' + carrierType +'_' +id).style.color="#979797";
							document.getElementById('operator' + carrierType +'_' +id).disabled="disabled";
							document.getElementById('operator' + carrierType +'_' +id).checked= false;


							newspan.setAttribute("id", "remove_" + opName[1]);
							newspan.innerHTML = opName[0] + " <a href=\"javascript:removeCarriers('" + opName[1] + "', 'include',  '"  + carrierType +"')\">&#171; remove</a><input type=\"hidden\" name=\"preferInclOP\" value=\"oak:" + opName[0] + ":" + opName[1] +"\" /><br />";
							selection.appendChild(newspan);
						}
					}
				}

			}
		
		}
	} 
}



function removeCarriers(name, type, carrierType)
{
  var spanId = document.getElementById('remove_' +name);
  
  var remove = document.getElementById(type).removeChild(spanId);
  
	document.getElementById('spanOperator' + carrierType +'_' +name).style.color="#3F3F3F";
	document.getElementById('operator' + carrierType +'_' + name).disabled= false;	
}


function removePrefer(){

	document.getElementById('include').innerHTML = '';
	document.getElementById('exclude').innerHTML = '';
	
	
	var carrierType = document.forms[0].carrier.value;
	
	var elements = document.forms[0].elements.length;
	
	
	
	 for (var i = 0; i <= elements; i++)
	{		

		if(document.forms[0].elements[i]){
	
			if(document.forms[0].elements[i].type == 'checkbox' ){

			
				if(document.forms[0].elements[i].id.indexOf('operator' + carrierType)!='-1'){
				
					var name = document.forms[0].elements[i].id.split('_');

					
							document.getElementById('spanOperator' + carrierType +'_' +name[1]).style.color="#3F3F3F";
							document.forms[0].elements[i].disabled= false;
							document.forms[0].elements[i].checked= false;

				}


			}
		
		}
	} 
	
	
	
}



/* *****************  */
/* **** calendar ***  */
/* *****************  */

Months = new Array(12);
Months[0] = "January";
Months[1] = "Febuary";
Months[2] = "March";
Months[3] = "April";
Months[4] = "May";
Months[5] = "June";
Months[6] = "July";
Months[7] = "August";
Months[8] = "September";
Months[9] = "October";
Months[10] = "November";
Months[11] = "December";


function PadSpaces(TheString)
{
        var Spaces = "             ";
        len = Math.round((9 - TheString.length)/2);

        return Spaces.substring(0,len) + TheString;
}

function NumLeapYears(StartYear, EndYear)
{
        var LeapYears, i;

        if (EndYear >= StartYear){
                for(LeapYears = 0; StartYear <= EndYear; StartYear++)
                if (IsLeapYear(StartYear)) LeapYears++;
        }else{
        for(LeapYears = 0; EndYear <= StartYear; EndYear++)
                if (IsLeapYear(EndYear)) LeapYears++;
        }
        return LeapYears;
}

function IsLeapYear(Year)
{
        if(Math.round(Year/4) == Year/4){
                if(Math.round(Year/100) == Year/100){
                        if(Math.round(Year/400) == Year/400)
                                return true;
                        else return false;
                }else return true;
        }
        return false;
}

function Trim(TheString)
{
        var len;

        len = TheString.length;
        while(TheString.substring(0,1) == " "){ //trim left
                TheString = TheString.substring(1, len);
                len = TheString.length;
        }

        while(TheString.substring(len-1, len) == " "){ //trim right
                TheString = TheString.substring(0, len-1);
                len = TheString.length;
        }
        return TheString;
}

function DetermineMonthIdx()
{
        var i, month, month_s, len;


        month = Trim(document.getElementById('hiddenMonth').value);
        len = month.length;

        for( i = 0; i <12; i++){
                month_s = Months[i].substring(0,len);
                if (month_s.toUpperCase() == month.toUpperCase())
                        return (i);
        }
        return -1;
}


function FindNewYearStartingDay(Year)
{
        var LeapYears, Years, Day;

        LeapYears = NumLeapYears(1995, Year);

        if  (Year >=1995)
                Years = (Year -1995)+LeapYears;
        else    Years = (Year -1995)-LeapYears;

        if  (Year >=1995)
                Day = Math.round(((Years/7 - Math.floor(Years/7))*7)+.1);
        else    Day = Math.round(((Years/7 -  Math.ceil(Years/7))*7)-.1);

        if (Year >=1995){
                if(IsLeapYear(Year)) Day--;
        }else Day += 7;

        if(Day < 0) Day = 6;
        if(Day > 6) Day = 0;
        return Day;
}

function FindNumDaysInMonth(Year, Month)
{
        if(Month == 1){
                if(IsLeapYear(Year)) return 29;
                else return 28;
        }else{
                if(Month >6) Month++;
                if(Month/2 == Math.round(Month/2))  return 31;
        }
 return 30;
}

function FindMonthStartDay(NewYearDay, Year, Month)
{
        var MonthStartDay;

        AddArray = new Array(12);

        AddArray[0]=0;AddArray[1]=3;AddArray[2]=3;AddArray[3]=6;
        AddArray[4]=1;AddArray[5]=4;AddArray[6]=6;AddArray[7]=2;
        AddArray[8]=5;AddArray[9]=0;AddArray[10]=3;AddArray[11]=5;

        MonthStartDay = NewYearDay + AddArray[Month];
        if(IsLeapYear(Year)  && (Month ) > 1) MonthStartDay ++;

        if (MonthStartDay > 6) MonthStartDay -= 7;

        return MonthStartDay;
}

function FillCalendar(type)
{
        var monthText=document.getElementById('month' + type).innerHTML;
		var yrText=document.getElementById('year' + type).innerHTML;
		
        var Year, Month, Midx, NewYearDay, MonthStartDay;
        var NumDaysInMonth, i, t, x;
        

       	Year = parseFloat(document.getElementById('hiddenYear' +type).value);
        Month = document.getElementById('hiddenMonth' +type).value;

        Midx  =  DetermineMonthIdx();
        if (Midx == -1){
                alert ("Can't recognize that month");
                return;
        }

        NewYearDay = FindNewYearStartingDay(Year);
        MonthStartDay = FindMonthStartDay(NewYearDay, Year,  Midx);
        NumDaysInMonth = FindNumDaysInMonth(Year, Midx);

        var allMyPrettyDivs = document.getElementsByTagName('div');
       
       
		var date=new Date(); 
		var dd=date.getDate(); 
		var mm=date.getMonth(); 
		var yy=date.getYear(); 
		var weekday=date.getDay(); 
		
		var dayLast=date.getDate(); 
		var monthLast=date.getMonth(); 
		var yearLast=date.getYear(); 
		
		
		if(date.getDate() +21 > NumDaysInMonth){
			dayLast = (dd + 20) - FindNumDaysInMonth(Year, Midx);
			monthLast = mm +1 
			
			if(monthLast==12){
				monthLast = 0;
				yearLast = yearLast +1;
			}
			
		}
		else{
			dayLast = date.getDate() +20;
		}

		
		if (yy < 999){
			 yy += 1900;
			 yearLast+= 1900;
		 }


        for(i = 0;  i < allMyPrettyDivs.length;  i++){

			if(i==0){
				x = 0;
			}

			if(allMyPrettyDivs[i].className == "row11" +type || allMyPrettyDivs[i].className == "row11before" +type || allMyPrettyDivs[i].className == "withoutDay"+type || allMyPrettyDivs[i].className == "row11today"+type){

				t = x + 1 - MonthStartDay;

				if ( t >= 1  &&  t <= NumDaysInMonth)
				{
						
						
						if(dd == t && mm ==  Midx && yy == Year){
						    
							allMyPrettyDivs[i].innerHTML = "<a class='row11today' href='javascript:;' title='" + yrText + " " + monthText + " "+ t + "' id='a_day_"+ t + "'>"+ t+"</a>";
							allMyPrettyDivs[i].className = "row11today"+type;
							allMyPrettyDivs[i].disabled = false;
							
							
							allMyPrettyDivs[i].onclick = function (e) {
							
							if(this.className=='row11before'){
								return false;
							}
							
							
							var monthNumber = Midx + 1; 

							var dayVal=this.innerHTML.split('>')[1].split('<')[0];
                            var dayDate = dayVal;
							var monthDate = Midx + 1;
                           	if(dayDate.length==1)dayDate ='0' + dayDate;

							if(monthDate < 10)monthDate ='0' + monthDate;
							
							/* month + day + year */
							document.getElementById('monthDayYearField'+type).value = monthNumber + '/' + dayDate + '/' + Year;
							document.getElementById('itdDate'+type).value = Year + '' + monthDate +'' + dayDate;
							document.getElementById('calendar-border'+type).style.display='none';
							document.getElementById('monthDayYearField'+type).focus();
							};
							
						}
						else if(dd > t && mm ==  Midx && yy == Year || mm >  Midx && yy == Year || yy > Year){
							allMyPrettyDivs[i].className = "row11before"+type;
							allMyPrettyDivs[i].disabled = true;
							allMyPrettyDivs[i].innerHTML = t;
						}  
						
						else if(dayLast < t && monthLast ==  Midx && yearLast == Year || 
							monthLast <  Midx && yearLast == Year || 
							yearLast < Year ||
							dayLast < t && monthLast >  Midx && yearLast > Year){
							allMyPrettyDivs[i].className = "row11before"+type;
							allMyPrettyDivs[i].disabled = true;
							allMyPrettyDivs[i].innerHTML =  t;
						} 

						
						else{
							allMyPrettyDivs[i].className = "row11"+type;
							allMyPrettyDivs[i].disabled = false;
							allMyPrettyDivs[i].innerHTML = "<a href='javascript:;' title='" + yrText + " " + monthText + " "+ t + "' class='row11"+ type + "' id='a_day_"+ t + "'>"+ t+"</a>";
							
							allMyPrettyDivs[i].onclick = function (e) {
							
							
							if(this.className=='row11before'){
								return false;
							}
							
							
							var monthNumber = Midx + 1; 
                            var dayVal=this.innerHTML.split('>')[1].split('<')[0];
                            var dayDate = dayVal;
							var monthDate = Midx + 1;
							
							var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday", "Sunday");
							
							var weekdayNumber = this.id.split('-');
                           	if(dayDate.length==1)dayDate ='0' + dayDate;
                           
							if(monthDate < 10)monthDate ='0' + monthDate;


							/* month + day + year */
							document.getElementById('weekday'+type).innerHTML = weekday[weekdayNumber[1] -1];
							document.getElementById('monthDayYearField'+type).value = monthNumber + '/' + dayDate + '/' + Year;
							document.getElementById('itdDate'+type).value = Year + '' + monthDate +'' + dayDate;
							document.getElementById('calendar-border'+type).style.display='none';
							document.getElementById('monthDayYearField'+type).focus();
							};
							
						} 
						
				}
				else {
					allMyPrettyDivs[i].innerHTML= " ";
					allMyPrettyDivs[i].className = "withoutDay"+type;
				}
				x = x+1;
		 	}

        }
}


function IncDecYear(step, type)
{
	val =0;

	if(DetermineMonthIdx()=='11' && step=='next'){
		val = 1;
	}

	if(DetermineMonthIdx()=='0' && step=='prev'){
		val = -1;
	}

        var valNum = parseInt(val);
        var valNum2 = parseInt(document.getElementById('hiddenYear').value)
        document.getElementById('hiddenYear').value = valNum2 + valNum;
        document.getElementById('year').innerHTML = valNum2 + valNum;

        FillCalendar(type)
        
        
        
     if(step=='prev'){
    	 IncDecMonth(-1, type);
     }
     else{
     	IncDecMonth(1, type);
     }
}



function IncDecMonth(val, type)
{
        var valNum = parseInt(val);
        var Midx  =  DetermineMonthIdx();
        
        var MonthSave = DetermineMonthIdx();

        Midx += valNum;
        if(Midx > 11) Midx = 0;
        if(Midx < 0)  Midx = 11;

        document.getElementById('hiddenMonth').value = PadSpaces(Months[Midx]);
        document.getElementById('month' + type).innerHTML = PadSpaces(Months[Midx]);

        FillCalendar(type);
}


function checkDate(obj){

	if (obj.id=='itdTimeHour') {
		var hour = parseInt(obj.value);
		
		if(isNaN(hour) || !isNumeric(obj.value)){
			obj.value = 1;
		}
		else if(hour < 0)
		{
			hour = Math.abs(hour);
			obj.value = hour;
		}
		else if(hour > 12)
		{
			while (hour > 12) {
				hour -= 12;
			}	

			obj.value = hour;
		}
	}

	if (obj.id=='itdTimeMinute') {
		var minute = parseInt(obj.value);
		
		if(isNaN(minute) || !isNumeric(obj.value)){
			obj.value = '00';
		}
		else if(minute < 0)
		{
			minute = Math.abs(minute);
			obj.value = minute;
		}
		else if(minute > 59)
		{
			while (minute > 59) {
				minute -= 59;
			}	
			
			obj.value = minute;
		}
	}
	
}

function isNumeric(strString)
   //  check for valid numeric strings	
{
	var strValidChars = "0123456789.-";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	  {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1)
		 {
		 blnResult = false;
		 }
	  }
	return blnResult;
}

function changeMapText(obj, type, line, coords){


	if(obj.innerHTML=='Map It'){
	
		obj.innerHTML= 'Unmap It';
		obj.href= "javascript:mdvOAKMapHelper.mapIt(this, " + type +",'"+ line +"', '" + coords + "');";
	}
	else{
		obj.innerHTML= 'Map It';
		obj.href= 'javascript:mdvOAKMapHelper.unmapIt();';
	}

};



function insertDate(obj, type){

	var date = obj.value;
	var insertDate = date.split('/');
	
	var Year, Month, Midx, NewYearDay, MonthStartDay;
	var NumDaysInMonth, i, t, x;
        

	Year = parseFloat(document.getElementById('hiddenYear' +type.toUpperCase()).value);
	Month = document.getElementById('hiddenMonth' +type.toUpperCase()).value;

	Midx  =  DetermineMonthIdx();
	if (Midx == -1){
			alert ("Can't recognize that month");
			return;
	}

	NewYearDay = FindNewYearStartingDay(Year);
	MonthStartDay = FindMonthStartDay(NewYearDay, Year,  Midx);
	NumDaysInMonth = FindNumDaysInMonth(Year, Midx);

   
	var today=new Date(); 
	var dd=today.getDate(); 
	var mm=today.getMonth() +1; 
	var yy=today.getYear(); 
	
	var dayLast=today.getDate(); 
	var monthLast=today.getMonth() +1; 
	var yearLast=today.getYear(); 
	
	
	if(today.getDate() +21 > NumDaysInMonth){
		dayLast = (dd + 21) - FindNumDaysInMonth(Year, Midx -1);
		monthLast = mm +1 
	}
	else{
		dayLast = today.getDate() +21;
	}

	if (yy < 999){
		 yy += 1900;
		 yearLast+= 1900;
	 }
	 
	
	var s = new Date(parseFloat(insertDate[2]), parseFloat(insertDate[0])-1, parseFloat(insertDate[1]));
		s.setHours(0);
		s.setMinutes(0);
		s.setSeconds(0);
		s.setMilliseconds(0);

	var selectionDate = Date.parse(s);
		
	var	t = new Date();
		t.setHours(0);
		t.setMinutes(0);
		t.setSeconds(0);
		t.setMilliseconds(0);
	var today = Date.parse(t);
		today += 3 * 7 * 24 * 60 * 60 * 1000;

	var isInvalid = today - selectionDate < 0;
	
	if(date.indexOf('/')=='-1'){

		if(dd.length==1)dd = '0' +dd;
		if(mm.length==1)mm = '0' +mm;
		
		if(type=='dm'){
			document.forms[1].itdDate.value = yy + '' + mm + ''+ dd; 
			obj.value = mm + '/' + dd + '/'+ yy; 
		}
		else if(type=='rs'){
			obj.value = mm + '/' + dd + '/'+ yy; 
		}
		else{
			document.forms[0].itdDate.value = yy + '' + mm + ''+ dd; 
			obj.value = mm + '/' + dd + '/'+ yy; 
		}
	}
	/*else if(dd > parseFloat(insertDate[1]) && mm ==  parseFloat(insertDate[0]) && yy == parseFloat(insertDate[2]) || mm >  parseFloat(insertDate[0]) && yy == parseFloat(insertDate[2]) || yy > parseFloat(insertDate[2])){
		alert('The date entered is in the past. It has been reset to today.');
		obj.value = mm + '/' + dd + '/'+ yy; 
	}  */
						
	else if(isInvalid){
		alert('The date entered is beyond the three week look-ahead period, which is the farthest advance date allowed due to periodically changing schedules. The date you selected has been reset to today\'s date.');
		obj.value = mm + '/' + dd + '/'+ yy; 
	} 
	
	else{
	
		if(dd > parseFloat(insertDate[1]) && mm ==  parseFloat(insertDate[0]) && yy == parseFloat(insertDate[2]) || mm >  parseFloat(insertDate[0]) && yy == parseFloat(insertDate[2]) || yy > parseFloat(insertDate[2])){
		alert('Please note that the date you entered for your itinerary has already passed.')
		}  
	
		
		if(isNaN(insertDate[0]) || insertDate[0] > 12 || insertDate[0] <= 0){
			insertDate[0] = mm;
		}
		
		if(isNaN(insertDate[1]) || insertDate[1] > NumDaysInMonth || insertDate[1] <= 0){
			insertDate[1] = dd;
		}
		
		if(isNaN(insertDate[2]) || insertDate[2] <= 0){
			insertDate[2] = yy;
		}
		
		if(insertDate[0] && insertDate[1]){
			if(insertDate[0].length==1)insertDate[0]='0' + insertDate[0];
			if(insertDate[1].length==1)insertDate[1]='0' + insertDate[1];
			
			if(type=='dm'){
				document.forms[1].itdDate.value = insertDate[2] + '' + insertDate[0] + ''+ insertDate[1]; 
				obj.value = insertDate[0] + '/' + insertDate[1] + '/'+ insertDate[2]; 
			}
			else if(type=='rs'){
				obj.value = insertDate[0] + '/' + insertDate[1] + '/'+ insertDate[2]; 
			}
			else{
				document.forms[0].itdDate.value = insertDate[2] + '' + insertDate[0] + ''+ insertDate[1]; 
				obj.value = insertDate[0] + '/' + insertDate[1] + '/'+ insertDate[2]; 
			}
		}
	
	}
	
};


function expandContractAll(elem, style){

	var nodeChild = document.getElementById(elem).childNodes.length;
	
	for(var i=0;i<nodeChild;i++){

		
		if(document.getElementById(elem).childNodes[i].tagName=='DIV'){
				
			var nodeChildChild = document.getElementById(elem).childNodes[i].childNodes.length;
		
			for(var y=0; y <nodeChildChild; y++){
				if(document.getElementById(elem).childNodes[i].childNodes[y].tagName=='DIV'){
					document.getElementById(elem).childNodes[i].childNodes[y].style.display=style;
				}
			}
			
			if(style=='block'){
				document.getElementById(elem).childNodes[i].className='routesListingBox routesListingBoxOn';
			}
			else{
				document.getElementById(elem).childNodes[i].className='routesListingBox';
			}
		}

	}

}

function applyFootpathTravelTime(e) {
	var t 	= document.getElementsByName('travelTime');
	
	if (!t || t.length <= 0)
		return;
	
	for (var r=1; r <= countRoutes; r++) {
		var cumTime = 0;
		for (var i=0; i < t.length; i++) {
			var ti = t[i];
			if (parseInt(ti.id.substring(11)) != r)
				continue;
				
			cumTime += parseInt(ti.innerHTML);
		}
		
		var o = document.getElementById('travelTime_overview_' + r);
		if (o) {
			var str = '';
			
			if (cumTime / 60 >= 1) {
				if (parseInt(cumTime / 60) < 10)
					str = '0' + parseInt(cumTime / 60);
				else
					str = parseInt(cumTime / 60);
			} else {
				str = '00';
			}
			
			str += ':';
			
			if (cumTime % 60 < 10)
				str += '0' + cumTime % 60;
			else
				str += cumTime % 60;
			
			o.innerHTML = str;
		}
	}
}

function applyAgencies() {
	for (var i=1; i <= 50; i++) {		
		applyAgency('railStops_' + i);
		
		applyAgency('busStops_' + i);

		applyAgency('ferryStops_' + i);		
	}
}
function applyAgency(id) {
	var a = [];
	var obj = document.getElementById(id);
	
	if (obj == null)
		return null;	
	
	for (var i=1; i <= 50; i++) {
		var c=document.getElementById(id + '_' + i)
		if (c && c.firstChild)
			a.push(c.firstChild.nodeValue.trim());
	}
	
	a.sort();
	
	var e = null;
	var u = [];
	while (e = a.pop()) {
		if (u.length == 0 || u[0] != e) {
			u.unshift(e);
		}
	}
	
	var str = u.join(', ');
	
	var target = document.getElementById('label' + id);
		target = target.firstChild;
	if (target.nodeType == 3 && str.length > 0) {
		target.nodeValue = target.nodeValue + ' ' + String.fromCharCode(8212) + ' ' + str;
	}
}

function fixLegend(obj) {
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	
	if (version >= 5.5 && version < 7 && obj.src.indexOf('fw/mdv/transparent.gif') < 0) {
		var src = obj.src;
		obj.style.width  = obj.width + 'px';
		obj.style.height = obj.height + 'px';
		
		obj.src = 'fw/mdv/transparent.gif';
		obj.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' +src+ '\')';
	}
}



function findBox(type, headerText, request){
    var   isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') ;  //mantis# 3647
	mdvEventLog.trigger('SECTION1_LOCATION_POP_UP_FORM_SHOWN', 'index.html', '');
	
	document.getElementById('findLandmark' + request +'Link').style.color='#ffffff';
	document.getElementById('findPopularDestination' + request +'Link').style.color='#ffffff';
	if(request!='Output'){
		document.getElementById('findRailStation' + request +'Link').style.color='#ffffff';
		document.getElementById('findFerryLanding' + request +'Link').style.color='#ffffff';
	}
	
	document.getElementById('findLandmark' + request +'Input').style.display='none';
	document.getElementById('findPopularDestination' + request +'Input').style.display='none';
	if(request!='Output'){
		document.getElementById('findRailStation' + request +'Input').style.display='none';
		document.getElementById('findFerryLanding' + request +'Input').style.display='none';
	}

	document.getElementById(type + request +'Link').style.color='#24475A';
	document.getElementById(type + request +'Input').style.display='block';
	
	//document.getElementById('findBox' + request).style.zIndex = '999'; //mantis #3933: change zindex in screen.css
	document.getElementById('findBox' + request).style.display='block';
	
	if(request!='Output'){
		document.getElementById('findBox' + request +'Header').innerHTML=headerText;
		var hiddenlinkin_fBox=document.getElementById('a_hidden_findBox' + request +'Header');
		hiddenlinkin_fBox.style.display='';
		hiddenlinkin_fBox.title="Beginning of "+ headerText;
		hiddenlinkin_fBox.focus();
		hiddenlinkin_fBox.hideFocus=true;
	}


	if(document.getElementById('a_close_railferrypop'+request)!=null)
	{
       
	     var closelink_railferrypop=document.getElementById('a_close_railferrypop'+ request);
	     closelink_railferrypop.style.display='';
	     closelink_railferrypop.onclick=function(){closeRailFerrySelection(request,type);}
	}
	if(document.getElementById('btncancel_railferrypop'+request)!=null)
	{
       
	     var cancel_railferrypop=document.getElementById('btncancel_railferrypop'+ request);
	     cancel_railferrypop.style.display='';
	     cancel_railferrypop.onclick=function(){closeRailFerrySelection(request,type);}
	}
	    
	    
	if(request=='Output'){
		document.getElementById('findBox' + request).style.backgroundImage= 'url(fw/' + type + request + '.jpg)';
	}
	else{
		switch (type)
	    {
	        // #4321 changing the display order for locaion selector for RailStation / FerryLanding / Lanmark options
	        case "findRailStation":
	            document.getElementById('findBox' + request).style.backgroundImage= 'url(fw/' + 'findLandmark' + '.jpg)';
	            mdvEventLog.trigger('SECTION1_RAIL_STATIONS_LINK', 'index.html', '');	
	            break;
	         case "findFerryLanding":           
	            document.getElementById('findBox' + request).style.backgroundImage= 'url(fw/' + 'findRailStation' + '.jpg)';
	            mdvEventLog.trigger('SECTION1_FERRY_LANDINGS_LINK', 'index.html', '');	
	            break;
	         case "findLandmark":
	            document.getElementById('findBox' + request).style.backgroundImage= 'url(fw/' + 'findFerryLanding' + '.jpg)';
	            mdvEventLog.trigger('SECTION1_LANDMARKS_LINK', 'index.html', '');	
	            break;
	        default:
	            document.getElementById('findBox' + request).style.backgroundImage= 'url(fw/' + type + '.jpg)';
	    }
	}
	
	
	
	if(request=='DM'){
	    if (isIE6 != -1)
          {        
             hideSelectDm();  //mantis# 3647
          }
		document.forms['dmRequest'].itdLPxx_findObjectType.value = type;
	}
	else{
	    if (isIE6 != -1)
            {
              hideSelect();  //mantis# 3647
            }
		document.forms[0].itdLPxx_findObjectType.value = type;
	}
}



function findBoxOutput(type){

	var element = document.getElementById(storedDivId);


	if(type=='findLandmark'){
	
		element.lastChild.lastChild.lastChild.lastChild.lastChild.style.display='none'
		element.lastChild.lastChild.lastChild.lastChild.firstChild.style.display='block'

		element.firstChild.firstChild.firstChild.lastChild.firstChild.style.color='#ffffff';
		element.firstChild.firstChild.firstChild.firstChild.firstChild.style.color='#24475A';
		
		element.firstChild.style.background='url(fw/findLandmarkOutput.jpg) no-repeat left top';
	
		
	}
	else if(type=='findPopularDestination'){
		element.lastChild.lastChild.lastChild.lastChild.lastChild.style.display='block'
		element.lastChild.lastChild.lastChild.lastChild.firstChild.style.display='none'
		
		element.firstChild.firstChild.firstChild.lastChild.firstChild.style.color='#24475A';
		element.firstChild.firstChild.firstChild.firstChild.firstChild.style.color='#ffffff';
		
		element.firstChild.style.background='url(fw/findPopularDestinationOutput.jpg) no-repeat left top';
	
	}


}



// set point values in request form 
function setPoint(usage){
	var form = document.forms[0];
	var   isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') ; //mantis#: 3647
	if(usage=='dm'){
		form = document.forms['dmRequest'];
	} 
	
	var setName = document.getElementById('name_' + usage);
	var setPlace = document.getElementById('place_' + usage);
	setName.focus();
	var activeType = form.itdLPxx_findObjectType.value;
	var getName = 'name' + activeType.substring(4);
	
	var bs = 'businessSelector';
	
	if(usage=='dm'){
		getName += 'DM';
		bs += 'DM';
	}
	
	var businessSelector = document.getElementById(bs);
	
	if(document.getElementById(getName) && document.getElementById(getName).value.indexOf('Select ')== '-1')
	{
		var nameValues = document.getElementById(getName).value.split(':');

		if(nameValues=='-1' || nameValues=='Localities without Landmarks')
			return;
			
		if(usage=='origin'){
			storedOrig = document.getElementById(getName).value;
		}
		else if(usage=='destination'){
			storedDest = document.getElementById(getName).value;
		}
		else if(usage=='dm'){
			storedDM= document.getElementById(getName).value;
		}
		else if(usage=='via'){
			storedVia = document.getElementById(getName).value;
		}
		
		setName.value = nameValues[0];
		setPlace.value = '';
		setName.style.color = '#000000';
			
		if(usage=='via'){
			document.getElementById('itdLPxx_additonalOptions').value = '1';
		} 
	
	} else if (businessSelector && businessSelector.length > 0) {
		var name = businessSelector[businessSelector.selectedIndex].value;
		var nameValues = name.split('_');
		
			name = nameValues[0] + ':coord:' + nameValues[2];
		
		if(usage=='origin'){
			storedOrig = name;
		}
		else if(usage=='destination'){
			storedDest = name;
		}
		else if(usage=='dm'){
			storedDM= name;
		}
		else if(usage=='via'){
			storedVia = name;
		}

		setName.value = nameValues[0];
		setName.style.color = '#000000';
			
		if(usage=='via'){
			document.getElementById('itdLPxx_additonalOptions').value = '1';
		} 
	}
	
	if (document.getElementById('findBox'))
		{document.getElementById('findBox').style.display = 'none';
          if (isIE6 != -1)
          {
      	   	 showSelect();  //mantis# 3647
           }
	    }
	if (document.getElementById('findBoxDM'))
		{document.getElementById('findBoxDM').style.display = 'none';
          if (isIE6 != -1)
          {
             showSelectDm(); //mantis# 3647
          }
		}
	
}
function cancelPoint(usage){
	var   isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') ;
	if (document.getElementById('findBox'))
		{document.getElementById('findBox').style.display = 'none';
		  if (isIE6 != -1)
          {
          	 showSelect();  //mantis# 3647
          }
		}
	
	if (document.getElementById('findBoxDM'))
		{document.getElementById('findBoxDM').style.display = 'none';
		    if (isIE6 != -1)
              {
              	 showSelectDm(); //mantis# 3647
              }
		}		
		
	if (document.getElementById('findBoxOutput'))
		document.getElementById('findBoxOutput').style.display = 'none';
		

	// Temp: Disabled.
	return;
	
	var form = document.forms[0];
	
	if(usage=='dm'){
		form = document.forms[1];
	}


	if(document.getElementById('nameState_' + usage)){
		if(document.getElementById('nameState_' + usage).value){
			document.getElementById('nameInfo_' + usage).value='';
			if(document.getElementById('placeInfo_' + usage)){
				document.getElementById('placeInfo_' + usage).value='';
			}
		}
	}


	form.itdLPxx_findObjectBox.value = '';
	form.execInst.value = 'verifyOnly';
	form.submit();
}


function checkLandmarkOnLoad(){

	if(document.forms[0]){
		if(document.forms[0].itdLPxx_findObjectBox){

			usage = document.forms[0].itdLPxx_findObjectBox.value;

			if(document.forms[0].itdLPxx_findObjectBox.value != ''){

				if(document.getElementById('nameState_' + usage).value=='identified'){
					document.getElementById('findBox').style.display='none';
				}
			}
		
		}
	}
}



function blockTabContent(type){


	for(i=1; i < 6; i++){
	
		if(type==i){
			if(document.getElementById('tab' +  i + 'Content')){
				document.getElementById('tab' +  i + 'Content').style.display='block';
			}
		}
		else{
		
			if(document.getElementById('tab' +  i + 'Content')){
				document.getElementById('tab' +  i + 'Content').style.display='none';
			}
		}
	}


}

function setTripFuctionDesc(e) {
	var spans = document.getElementsByTagName('span');
	var fDesc = null;
	var index = 1;
	
	for (var i=0; i < spans.length; i++) {
		var s = spans[i];		
		
		if (s.id.indexOf('spanTable_') < 0)
			continue;
		
		if (fDesc != s.firstChild.nodeValue)
			index = 1;				
		
		fDesc = s.firstChild.nodeValue;
		s.firstChild.nodeValue += index;
		
		index++;
	}

	var fDesc = null;
	
	for (var i=0; i < spans.length; i++) {
		var s = spans[i];		
		
		if (s.id.indexOf('spanTableHidden_') < 0)
			continue;
		
		if (fDesc != s.firstChild.nodeValue)
			index = 1;				
		
		fDesc = s.firstChild.nodeValue;
		s.firstChild.nodeValue += index;
		
		index++;
	}
	
	
	var fDesc = null;

	for (var i=0; i < spans.length; i++) {
		var s = spans[i];		
		
		if (s.id.indexOf('spanDetails_') < 0)
			continue;
		
		if (fDesc != s.firstChild.nodeValue)
			index = 1;				
		
		fDesc = s.firstChild.nodeValue;
		s.firstChild.nodeValue += index;
		
		index++;
	}
}

//Create an array 
var allPageTags = new Array(); 

function doSomethingWithSpanClasses(theClass, style) {

	if(style==true){
		style='';
	}
	else if(style==false){
		style='none';
	}

	//Populate the array with all the page tags
	var allPageTags=document.getElementsByTagName("span");
	
	for (i=0; i<allPageTags.length; i++) {
	
		//Pick out the tags with our class name
		if (allPageTags[i].className==theClass) {
		
			//Manipulate this in whatever way you want
			allPageTags[i].style.display= style;
			allPageTags[i].style.visibility= 'visible';
			
		}
	}
} 



function hideFeedbackEmailForm(){

	if(document.getElementById('feedbackForm'))document.getElementById('feedbackForm').style.display='none';
	
	if(document.getElementById('mailAFriendForm'))document.getElementById('mailAFriendForm').style.display='none';

}


function findFeedbackPos(e){

   e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    } 
    
	document.getElementById('feedbackForm').style.top = cursor.y + 'px';

}

function showAnnouncements(e, head, content) {
   e = e || window.event;
   var src = e.srcElement ? e.srcElement : e.target;
   
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
	
	var p = src;
	var offset = 0;
	
	while (p) {
		offset += p.offsetLeft;	
		p = p.offsetParent;
	}	
	
	if (content.indexOf('announcement_content_') != -1) {
		var temp = document.getElementById(content);
		if (temp && temp.innerHTML.length > 0)
			content = temp.innerHTML;
	} else if (content.indexOf('ann_') != -1) {
		var temp = document.getElementById(content);
		if (temp && temp.value.length > 0)
			content = temp.value;
		if(head.length > 35){
		    head = head.substring(0,35).trim() + '...';
	    }
	}
	
	var text = head;
	
	if(head.length > 78){
		text = head.substring(0,78) + '...';
	}
	
	document.getElementById('announcementBubbleHead').innerHTML = text;
	document.getElementById('announcementBubbleHead').title = head;
	
	document.getElementById('announcementBubbleContent').innerHTML = content;
	document.getElementById('announcementBubbleContent').style.fontSize = '13px';

	document.getElementById('announcementBubble').style.display='';
	document.getElementById('announcementBubble').style.top = cursor.y - 30 + 'px';
	document.getElementById('announcementBubble').style.left = offset + 'px';
}

function showCustomizedSchedule(e,sourceobjid){
   var tabidx=0;
   e = e || window.event;
   var src = e.srcElement ? e.srcElement : e.target;
   
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    } 
    if(sourceobjid)
    {
        var objsource=document.getElementById(sourceobjid);
        tabidx=objsource.getAttribute("tabIndex");
    }
    

	document.getElementById('customizedSchedule').style.display='';
	document.getElementById('customizedSchedule').style.top = cursor.y - 30 + 'px';
	document.getElementById('customizedSchedule').style.left = cursor.x + 40 + 'px';
    var objstart=document.getElementById("a_schedule_popupstart");
	objstart.focus();
	objstart.setAttribute("tabIndex",parseInt(tabidx)+1);
	var objend=document.getElementById("a_schedule_popupclose");
	objend.setAttribute("tabIndex",parseInt(tabidx)+1);
	objend.onclick=function(){document.getElementById('customizedSchedule').style.display='none';document.getElementById(sourceobjid).focus();}
	var objclose=document.getElementById("a_schedule_closepopup");
	objclose.onclick=function(){document.getElementById('customizedSchedule').style.display='none';document.getElementById(sourceobjid).focus();}
	var sessionID = document.getElementById('sessionID_mail');
	var requestID = document.getElementById('requestID_mail');
	var customizedScheduleContent = document.getElementById('customizedScheduleContent');
	
	customizedScheduleContent.innerHTML = 'Loading...';

	var id = src.id;
	var leg = src.getAttribute('leg');
		leg = leg.split(':');
		
	var link = src.getAttribute('link');
	var temp = link.split('=');
		temp = temp[temp.length-1];
		
		mdvEventLog.trigger('SECTION1_ITINERARY_SCHEDULE', 'itinerary.html', temp);
	
	var URL = 'XSLT_TRIP_REQUEST2';
	var _params = { language: 'en', itdLPxx_provider: 'schedule', command: id, sessionID: sessionID.value, requestID: requestID.value, itdLPxx_leg: leg[0] + '_' + leg[1] + '_' + leg[2], itdLPxx_time: leg[3] + ':' + leg[4], itdLPxx_extHref: link };
		_params = $H(_params);
		_params = _params.toQueryString();
	var _ajax = new Ajax.Request(URL, { method: 'post', parameters: _params, onComplete: onCustomizedSchedule.bind(customizedScheduleContent) });
}

function onCustomizedSchedule(response) {
    var inernalError = response.responseText.indexOf('error');
	var sessionExpired = response.responseText.indexOf('SECTION1_SESSION_EXPIRED');

    if (inernalError >= 0 || sessionExpired >= 0) 
	{
		this.innerHTML = "<p>An internal error occurred. </p><p> Please select one of the tabs or links in the <br/>header or footer to continue.</p>";
	}	
	else
	{
	    this.innerHTML = response.responseText;
	}
}


function checkValidFeedbackForm(form,sourcebtnid){

	var sessionID = document.forms[form].sessionID;
	var requestID = document.forms[form].requestID;
	var emailName = document.getElementById('emailName_feedback');
	var addEmailAddress = document.getElementById('addEmailAddress_feedback');
	var emailSubject = document.getElementById('emailSubject_feedback');
	var itdMPxx_Feedback = document.getElementById('itdMPxx_Feedback');

	var mail = document.forms[form].addEmailAddress.value.trim();
	var message = document.forms[form].itdMPxx_Feedback.value;
	var expression = /^[_a-zA-Z0-9-](\.{0,1}[_a-zA-Z0-9-])*@([a-zA-Z0-9-]{1,}\.){0,}[a-zA-Z0-9-]{2,}(\.[a-zA-Z]{2,4}){1,2}$/;
	
	//var expressionMessageURL = /\w[\w|\.|\-]+\.[_a-zA-Z0-9-]+\.[a-zA-Z]{2,4}/;
	var expressionMessageEmail = /\w[\w|\.|\-]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,4}/;
	
	if(!expression.exec(mail))
	{
		document.getElementById('feedbackError').style.display='';
		document.getElementById('feedbackErrorHeader').innerHTML ='E-mail Address is Required';
		document.getElementById('feedbackErrorContent').innerHTML = 'Sorry for any inconvienience, but the subject is important for us to categorize your feedback and allocate it to the correct people. Please enter a subject line and then hit the send button';
		document.getElementById('feedbackSubmit').style.display='none';
		if(document.getElementById('a_close_feedbackerror'))
		document.getElementById('a_close_feedbackerror').focus();
		return false;
	}
	
	else if(expressionMessageEmail.exec(emailSubject.value) || checkValidURL(emailSubject.value) > 0 ){
		document.getElementById('feedbackError').style.display='';
		document.getElementById('feedbackErrorHeader').innerHTML ='Subject is invalid';
		document.getElementById('feedbackErrorContent').innerHTML = 'Links and email addresses are not allowed in subject.<br/><br/><br/><br/>';
		document.getElementById('feedbackSubmit').style.display='none';
		if(document.getElementById('a_close_feedbackerror'))
		document.getElementById('a_close_feedbackerror').focus();
		return false;
	}
	
	else if(expressionMessageEmail.exec(message) || checkValidURL(message) > 0 ){
		document.getElementById('feedbackError').style.display='';
		document.getElementById('feedbackErrorHeader').innerHTML ='Message is invalid';
		document.getElementById('feedbackErrorContent').innerHTML = 'Links and email addresses are not allowed in message.<br/><br/><br/><br/>';
		document.getElementById('feedbackSubmit').style.display='none';
		if(document.getElementById('a_close_feedbackerror'))
		document.getElementById('a_close_feedbackerror').focus();
		return false;
	}
	
	else if(document.forms[form].emailSubject.value=='Enter a subject line for your feedback' || document.forms[form].emailSubject.value==''){
		document.getElementById('feedbackError').style.display='';
		document.getElementById('feedbackErrorHeader').innerHTML ='Subject is Required';
		document.getElementById('feedbackErrorContent').innerHTML = 'Sorry for any inconvienience, but the subject is important for us to categorize your feedback and allocate it to the correct people. Please enter a subject line and then hit the send button';
		document.getElementById('feedbackSubmit').style.display='none';	
		if(document.getElementById('a_close_feedbackerror'))
		document.getElementById('a_close_feedbackerror').focus();
		return false;														
	}
	else
	{
	    // Method added to check for spam
	    if(message.length > 0)
		{
		 var URL = 'http://transit.511.org/services/utils/AntiSpamCheckForEmail.aspx?';
		 var _params = { emailAddress: mail, emailSubject: document.forms[form].emailSubject.value, emailMessage: message};
			_params = $H(_params);
			_params = _params.toQueryString();
			
			URL += _params;
			
		 var img = new Image();
		 img.onload = sendFeedback;
		 img.onerror = spamPrompt;
		 img.src = URL;
	    }
		else
		 {
		   sendFeedback();
		 }
	}	
}
function sendFeedback()
{
		var ref = document.getElementById('ref');
		var URL = 'http://transit.511.org/services/utils/logsuggestions.aspx?';
		var baseURL = 'http://tripplanner.transit.511.org/mtc/XSLT_TRIP_REQUEST2?language=en';
		var emailName = document.getElementById('emailName_feedback').value;
		var addEmailAddress = document.getElementById('addEmailAddress_feedback').value;
		var emailSubject = document.getElementById('emailSubject_feedback').value;
		var itdMPxx_Feedback = document.getElementById('itdMPxx_Feedback').value;
		
		var _params = { emailName: emailName, addEmailAddress: addEmailAddress, emailSubject: emailSubject, itdMPxx_Feedback: itdMPxx_Feedback, ref: baseURL + ref.value };
			_params = $H(_params);
			_params = _params.toQueryString();
			
			URL += _params;
			
		var img = new Image();
		img.onload = closeFeedbackForm;
		/* Mantis Issue 0003599 */
		//img.onerror = closeFeedbackForm;
		img.onerror = spamPrompt;
		img.src = URL;
		//var _ajax = new Ajax.Request(URL, { method: 'post', parameters: _params, onComplete: closeFeedbackForm});		
		document.getElementById(sourcebtnid).focus();
		return true;	
}

/* Mantis Issue 0003599 */
function spamPrompt()
{
		document.getElementById('feedbackError').style.display='';
		document.getElementById('feedbackErrorHeader').innerHTML ='Spam Message';
		document.getElementById('feedbackErrorContent').innerHTML = 'Your feedback/message has been identified as spam and will not be delivered.';
		document.getElementById('feedbackSubmit').style.display='none';	
		if(document.getElementById('a_close_feedbackerror'))
		document.getElementById('a_close_feedbackerror').focus();
}
function checkValidURL(value){

	var expression= /\w[\w|\.|\-]+\.[_a-zA-Z0-9-]+\.[a-zA-Z]{2,4}/;
	var inputString = value.split(' ');
	var stringLenght = inputString.length;
	var countURL = 0;


	if(expression.exec(value))
	{	
		for(var i =0; i < stringLenght; i++){
		
			if(expression.exec(inputString[i])){
			
				if(expression.exec(inputString[i]).input.indexOf('transit.511.org')=='-1'){
					countURL+=1;
				}
			}
		}	
	}

	return countURL;
}



function closeFeedbackForm(e){
	if (document.getElementById('feedbackForm'))
		document.getElementById('feedbackForm').style.display='none';	
}

/* function sendMailAFriend() {
	var sessionID = document.getElementById('sessionID_mail');
	var requestID = document.getElementById('requestID_mail');
	var emailAddress = document.getElementById('emailAddress_mail');
	var emailSubject = document.getElementById('emailSubject_mail');
	var addEmailAddress = document.getElementById('addEmailAddress_mail');
	var riderCategory = document.getElementById('riderCategory');
	
	if (emailAddress && emailSubject && addEmailAddress) {
		var URL = 'XSLT_TRIP_REQUEST';
		var _params = { 
			sessionID: sessionID.value,
			requestID: requestID.value,
			emailAddress: emailAddress.value,
			emailSubject: emailSubject.value,
			addEmailAddress: addEmailAddress.value,
			ptOptionsActive: 1,
			itOptionsActive: 1,
			command: 'mailAFriend',
			sendEmail: 1,
			useProxFootSearch: 1,
			coordListOutputFormat: 'STRING',
			anySigWhenPerfectNoOtherMatches: 1, 
			itdLPxx_riderCategory: riderCategory.value,
			nextDepsPerLeg: 1
		};
			_params = $H(_params);
			_params = _params.toQueryString();
		
		var _ajax = new Ajax.Request(URL, { method: 'post', parameters: _params });
		closeMailAFriend();
	}
}*/

/* 4089 start */
function trim(subject) {
    var sub = subject.value;
    sub = escape(sub.replace(/\s+/g, " "));
    sub = sub.replace(/%A0/g, ' ');
    sub = unescape(sub);
    return sub;
}
/* 4089 end */


function sendMailAFriend() 
{
	var emailMessage = document.getElementById('addEmailMsg_mail').value;
    if(emailMessage.length > 1 && emailMessage != "Enter your message")
	 {
	   validateMailForSpam();
	 }
	 else
	 {
		sendMail();
	 }
}
function validateMailForSpam()
{
        var URL = 'http://transit.511.org/services/utils/AntiSpamCheckForEmail.aspx?';
      
       
		var emailAddress = document.getElementById('emailAddress_mail');
	    var emailSubject = document.getElementById('emailSubject_mail');
	    var emailMessage = document.getElementById('addEmailMsg_mail');
	    
		
		var _params = {emailMessage: emailMessage.value};
			_params = $H(_params);
			_params = _params.toQueryString();
			
			URL += _params;
			
		var img = new Image();
		img.onload = sendMail;
		img.onerror = alertForSpamMail;
		img.src = URL;
		
}
function alertForSpamMail()
{
    alert('Your email message has been identified as spam and will not be delivered');
}
function sendMail() {
	var sessionID = document.getElementById('sessionID_mail');
	var requestID = document.getElementById('requestID_mail');
	var emailAddress = document.getElementById('emailAddress_mail');
	var emailSubject = document.getElementById('emailSubject_mail');
	var addEmailAddress = document.getElementById('addEmailAddress_mail');
	var riderCategory = document.getElementById('riderCategory');
	var addEmailMsg_mail = document.getElementById('addEmailMsg_mail');
	var contentType_mail = document.getElementById('contentType_mail');

	/* 4089 start */
	if (emailSubject != "") {
	    emailSubject.value = trim(emailSubject);
	}
	/* 4089 end */
	
	if (emailAddress && emailSubject && addEmailAddress) {
		var URL = 'XSLT_TRIP_REQUEST';
		var _params = { 
			sessionID: sessionID.value,
			requestID: requestID.value,
			itdLPxx_mail_contentType: (!contentType_mail.checked) ? 'text/plain' : 'text/html',
			itdLPxx_mail_to: emailAddress.value,
			itdLPxx_mail_subject: emailSubject.value,
			/*addEmailAddress: addEmailAddress.value,*/
			itdLPxx_mail_msg: addEmailMsg_mail.value,
			itdLPxx_homepage: 'mailView',
			ptOptionsActive: 1,
			itOptionsActive: 1,
			command: 'saveXML',
			saveXMLPool: 'MailAFriend',
			/*sendEmail: 1,*/
			useProxFootSearch: 1,
			coordListOutputFormat: 'STRING',
			anySigWhenPerfectNoOtherMatches: 1, 
			itdLPxx_riderCategory: riderCategory.value,
			nextDepsPerLeg: 1,
			tripSelection: 'on'
		};
		
		_params['tripSelector' + legId] = 'on';
		
		_params = $H(_params);
		_params = _params.toQueryString();
		
		var _ajax = new Ajax.Request(URL, { method: 'post', parameters: _params });
		closeMailAFriend();
	}
}



function closeMailAFriend(e) {
	if (document.getElementById('mailAFriendForm'))
		document.getElementById('mailAFriendForm').style.display='none';	
}

function changeMapHelpLink(newId){

	if(document.getElementById('mapHelpLink')){
		document.getElementById('mapHelpLink').name = newId;
	}
}

function changeHelpLink(linkId, helpId){

	if(document.getElementById(linkId)){
		document.getElementById(linkId).name = helpId;
	}
}

function depsEarlier(e, session, id, time, date) {
	var _params = { language: 'en', sessionID: session, itdLPxx_provider: 'tooltip', command: 'dmPrev' };

	_params = $H(_params);
	_params = _params.toQueryString();
	
	var element = document.getElementById('stop_' + id);

	var _ajax = new Ajax.Request('XSLT_DM_REQUEST', { method: 'post', parameters: _params, onComplete: mdvOAKMapHelper.onToolTipCallback.bind(element) });
}

function depsLater(e, session, id, time, date) {
	var _params = { language: 'en', sessionID: session, itdLPxx_provider: 'tooltip', itdDate: date, itdTime: time, mode: 'direct' };

	_params = $H(_params);
	_params = _params.toQueryString();
	
	var element = document.getElementById('stop_' + id);
	
	var _ajax = new Ajax.Request('XSLT_DM_REQUEST', { method: 'post', parameters: _params, onComplete: mdvOAKMapHelper.onToolTipCallback.bind(element) });
}

function customizedScheduleEarlier(e){
	e = e || window.event;
	
	var delta = 2;
	var entries = 4;
	
	var times = [];
	var departureTimes = document.getElementById('departureTimes');
	var arrivalTimes = document.getElementById('arrivalTimes');
	var firstActive = -1;

	for (var i=0; i < departureTimes.childNodes.length; i++) {
		var dep = departureTimes.childNodes[i];
		var arr = arrivalTimes.childNodes[i];
		var isActive = dep.className=='currentTime';
		
		if (firstActive == -1 && isActive)
			firstActive = i;
		
		times.push({ dep: dep, arr: arr, active: isActive });
	}
	
	firstActive -= delta;
	if (firstActive < 0)
		firstActive = 0;
		
	for (var i=0; i < times.length; i++) {
		var t = times[i];
		
		if (i >= firstActive && i < (firstActive + entries)) {
			t.dep.className = 'currentTime';
			t.arr.className = 'currentTime';
		} else {
			t.dep.className = 'earlierTime';
			t.arr.className = 'earlierTime';
		}
	}
}

function customizedScheduleLater(e){
   e = e || window.event;
	var delta = 2;
	var entries = 4;
	
	var times = [];
	var departureTimes = document.getElementById('departureTimes');
	var arrivalTimes = document.getElementById('arrivalTimes');
	var firstActive = -1;

	for (var i=0; i < departureTimes.childNodes.length; i++) {
		var dep = departureTimes.childNodes[i];
		var arr = arrivalTimes.childNodes[i];
		var isActive = dep.className=='currentTime';
		
		if (firstActive == -1 && isActive)
			firstActive = i;
		
		times.push({ dep: dep, arr: arr, active: isActive });
	}
	
	
	firstActive += delta;
	if (firstActive > times.length -4)
		firstActive = times.length - 4;
		
	for (var i=0; i < times.length; i++) {
		var t = times[i];
		
		if (i >= firstActive && i < (firstActive + entries)) {
			t.dep.className = 'currentTime';
			t.arr.className = 'currentTime';
		} else {
			t.dep.className = 'earlierTime';
			t.arr.className = 'earlierTime';
		}
	}
}

// find position of an object
function findPos(obj) 
{
	var curleft = curtop = 0;
    if (obj.offsetParent) 
    {
        do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
			// single = here is not a typo, we are not checking equality
		} while (obj = obj.offsetParent);
    }
	return [curleft,curtop];
}


// Create a Help Overlay
// e        - click event, used to get the mouse coordinates for pop up placement
// header   - value to look up in helpText associative array for use as the Pop Up Header
// content  - value to look up in helpText associative array for use as the Pop Up Content 
// obj      - expected to be this - the object calling this function as an onclick event handler.  
// align    - defaults to the right of the opening element, "left"
function createHelpOverlay(e, header, content, obj, align)
{
	var tabidx=0;
	if(obj)
	{
	    if(obj.name!='')
		{
		    header= obj.name +'header'
		    content= obj.name +'content'
		}
		tabidx=obj.getAttribute("tabIndex");
    }
	
	popupDivID = "div_help";
	callingelementid = obj.id;

    // make sure popup is hidden
	document.getElementById(popupDivID).style.display = 'none';
	
	if(header==''|| !header){
		header= 'default_header'
	}
	if(content==''|| !content){
		content= 'default_content'
	}
	
	// determine horizontal offset
	var helpAlign = 0;
	if(align=='left'){
		helpAlign = 340;
	}

    // determine coordinates
//    e = e || window.event;
    //var src = e.srcElement ? e.srcElement : e.target;
    var cursor = {x:0, y:0};
//    if (e.pageX || e.pageY) {
//        cursor.x = e.pageX;
//        cursor.y = e.pageY;
//    } 
//    else {
//        var de = document.documentElement;
//        var b = document.body;
//        cursor.x = e.clientX + 
//            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
//        cursor.y = e.clientY + 
//            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
//    } 
    var pos = findPos(obj);
    cursor.x = pos[0];
    cursor.y = pos[1];
//    alert (cursor.x + ", " + cursor.y);
    
    // lookup header and content and insert into popup
    document.getElementById('helpHeader').innerHTML= helpText[header];
    document.getElementById('helpContent').innerHTML=helpText[content] ;

    // move the popup inline in the DOM following the anchor used to generate it.

    // $().after($()) -- An element in the DOM can also be selected and inserted after another element
    // If an element selected this way is inserted elsewhere, it will be moved rather than cloned
//    jQuery("#" + callingelementid).after(jQuery("#" + popupDivID)); // insert a new one
   
    // display the popup
    document.getElementById(popupDivID).style.display = '';
    
    // assign close/end PopUp click event
    var objclose=document.getElementById('a_help_close');
    if (objclose == null)
        alert("can't find a_help_close ");
    else
    {
        objclose.onclick = function() {
            document.getElementById(popupDivID).style.display = 'none';
            if (obj != null)
                obj.focus();
            //document.getElementById(obj.id).focus();
        }
        objclose.title="Close " + helpText[header].replace(/&mdash;/, '-') + " simulated dialog" ;
    }
    var objend=document.getElementById('a_help_end');
    objend.onclick = function ()
    {
        document.getElementById(popupDivID).style.display = 'none';
        document.getElementById(obj.id).focus();
    }
    //objend.setAttribute("tabIndex",parseInt(tabidx)+2);
    
    // set PopUp position
    document.getElementById(popupDivID).style.top = cursor.y + 'px';
    document.getElementById(popupDivID).style.left = cursor.x - helpAlign + 'px';
	
	// initialize the a_help_start anchor with title, give it focus, etc.
	//var objstart=document.getElementById('a_help_start');
    var objstart = document.getElementById(popupDivID);
	//objstart.title="Beginning of "+  helpText[header].replace(/&mdash;/, '-')+ " simulated dialog" ;
	objstart.focus();
	//objstart.setAttribute("tabIndex",parseInt(tabidx)+1);
	//objstart.hideFocus=true;
}

function applyOnChangeSpeedChange() {
	var inputs = document.getElementsByName('changeSpeed');
	
	for (var i=0; i < inputs.length; i++) {
		var input = inputs[i];
		
		attachEventListener(input, 'click', onFootpathTravelTime, false);
	}
}

function onFootpathTravelTime(e) {
	e = e || window.event;
	var src = e.srcElement ? e.srcElement : e.target;

	if (src.checked==false)
		return;
		
	var mot = document.getElementsByName('trITMOTvalue');
	
	for (var i=0; i < mot.length; i++) {
		var selector = mot[i];

		for (var o=0; o < selector.length; o++) {
			var option = selector[o];

			if (option.oldValue == null)
				option.oldValue = option.value;

			switch (src.value) {
				case 'slow':
					// 0.75
					option.value = Math.floor(0.5 + (option.oldValue / 0.75));
					break;
				
				case 'fast':
					// 1.3
					option.value = Math.floor(0.5 + (option.oldValue / 1.3));
					break;
					
				default:
					option.value = option.oldValue;
					break;
			}
		}
	}
}

function attachEventListener(target, eventType, functionRef, capture)
{
  if (typeof target.addEventListener != "undefined")
  {
	target.addEventListener(eventType, functionRef, capture);
  }
  else if (typeof target.attachEvent != "undefined")
  {
	target.attachEvent("on" + eventType, functionRef);
  }
  else
  {
	eventType = "on" + eventType;

	if (typeof target[eventType] == "function")
	{
	  var oldListener = target[eventType];

	  target[eventType] = function()
	  {
		oldListener();

		return  functionRef();
	  }
	}
	else
	{
	  target[eventType] = functionRef;
	}
  }

  return true; 
}


function checkanyObjFilter(callingelement)//Mantis Issue-3386
{
    
    switch (callingelement.id)
    {   
        case "name_origin":
            document.getElementById('anyObjFilter_origin').value='0';
        break;
        case "name_destination":
            document.getElementById('anyObjFilter_destination').value='0';
        break;    
    }
    
}


function checkNameInputOnSubmit(){
	var nameOrig = document.getElementById('name_origin');
	// var placeOrig = document.getElementById('place_origin');
	var nameDest = document.getElementById('name_destination');
	var nameDM = document.getElementById('name_dm');
	var nameVia = document.getElementById('name_via');
	
	var storedOrigValues = storedOrig.split(':');
	var storedDestValues = storedDest.split(':');
	var storedDMValues = storedDM.split(':');
	var storedViaValues = storedVia.split(':');
	
	if (nameOrig && nameOrig.value == storedOrigValues[0] && storedOrigValues[1]) {
		var typeOrig = document.getElementById('type_origin');		
		var nameInfoOrig = document.getElementById('nameInfo_origin');
		var placeInfoOrig = document.getElementById('placeInfo_origin');
		
		typeOrig.value = storedOrigValues[1];
		nameInfoOrig.value = storedOrigValues[2];
		// place for poi
		if(storedOrigValues[3] && storedOrigValues[1] != 'coord'){
			placeInfoOrig.value = storedOrigValues[3] + ':' + storedOrigValues[4];
		} else if (storedOrigValues[1] == 'coord') {
			var name = storedOrigValues[2] + ':' + storedOrigValues[3] + ':' + storedOrigValues[4] + ':' + storedOrigValues[0]

			typeOrig.value = storedOrigValues[1];
			nameInfoOrig.value = name;
		}
	}

	if (nameDest && nameDest.value == storedDestValues[0] && storedDestValues[1]) {
		var typeDest = document.getElementById('type_destination');		
		var nameInfoDest = document.getElementById('nameInfo_destination');
		var placeInfoDest = document.getElementById('placeInfo_destination');

		typeDest.value = storedDestValues[1];
		nameInfoDest.value = storedDestValues[2];
		// place for poi
		if(storedDestValues[3] && storedDestValues[1] != 'coord'){
			placeInfoDest.value = storedDestValues[3] + ':' + storedDestValues[4];
		} else if (storedDestValues[1] == 'coord') {
			var name = storedDestValues[2] + ':' + storedDestValues[3] + ':' + storedDestValues[4] + ':' + storedDestValues[0]

			typeDest.value = storedDestValues[1];
			nameInfoDest.value = name;
		}
	}
	
	if (nameDM && nameDM.value == storedDMValues[0] && storedDMValues[1]) {
		var typeDM = document.getElementById('type_dm');		
		var nameInfoDM = document.getElementById('nameInfo_dm');
		var placeInfoDM = document.getElementById('placeInfo_dm');

		typeDM.value = storedDMValues[1];
		nameInfoDM.value = storedDMValues[2];
		// place for poi
		if(storedDMValues[3] && storedDMValues[1] != 'coord'){
			placeInfoDM.value = storedDMValues[3] + ':' + storedDMValues[4];
		} else if (storedDMValues[1] == 'coord') {
			var name = storedDMValues[2] + ':' + storedDMValues[3] + ':' + storedDMValues[4] + ':' + storedDMValues[0]

			typeDM.value = storedDMValues[1];
			nameInfoDM.value = name;
		}
	}
	
	if (nameVia && nameVia.value == storedViaValues[0] && storedViaValues[1]) {

		var typeVia = document.getElementById('type_via');		
		var nameInfoVia = document.getElementById('nameInfo_via');
		var placeInfoVia = document.getElementById('placeInfo_via');

		typeVia.value = storedViaValues[1];
		nameInfoVia.value = storedViaValues[2];
		// place for poi
		if(storedViaValues[3] && storedViaValues[1] != 'coord'){
			placeInfoVia.value = storedViaValues[3] + ':' + storedViaValues[4];
		} else if (storedViaValues[1] == 'coord') {
			var name = storedViaValues[2] + ':' + storedViaValues[3] + ':' + storedViaValues[4] + ':' + storedViaValues[0]

			typeVia.value = storedViaValues[1];
			nameInfoVia.value = name;
		}
	}

}


/* get the pois  and hierarchies*/
function sendPOIRequest(place, name, session, state, type, request, divId){

	var form = document.forms[0];
	
	if(usage=='dm'){
		form = document.forms['dmRequest'];
	} 

	var activeType = form.itdLPxx_findObjectType.value;

	var URL = 'XSLT_TRIP_REQUEST2';
	var _params = { 
		sessionID: session,
		requestID: 0,
		command: '',
		execInst: 'verifyOnly',
		placeInfo_origin: place,
		type_origin: type,
		itdLPxx_homepage: 'poiSelection',
		name_origin: name,
		itdLPxx_requestType: request,
		itdLPxx_findObjectType: activeType
	};
		
	if(state=='list'){
		_params['nameState_origin'] = 'list';
		_params['placeState_origin'] = 'identified';
	}
		
		
	_params = $H(_params);
	_params = _params.toQueryString();
		
	var element = document.getElementById('reloadPoiSelection' + request);
	
	if(request=='Output'){
		document.getElementById(storedDivId).style.display='';
		element = document.getElementById(storedDivId).lastChild.lastChild.lastChild.firstChild.firstChild.lastChild.lastChild;
	}
	
	var _ajax = new Ajax.Request(URL, { method: 'post', parameters: _params, onComplete: onPlaceSelectionCallback.bind(element) });
}

/* get the pois  for the map */
function sendPOICoordRequest(req){
	
	var subH = document.getElementById('nameLandmark' + req).options[document.getElementById('nameLandmark' + req).selectedIndex];
	var mainH = document.getElementById('nameMainLandmark' + req).options[document.getElementById('nameMainLandmark' + req).selectedIndex];

	if(subH.value=='-1'){
        $(storedDivId).lastChild.lastChild.lastChild.firstChild.firstChild.firstChild.style.display='block';
		return false
	}
	else if(subH.value =='all'){
		storedPOIHierarchy = mainH.innerHTML;
	}
    
    $(storedDivId).lastChild.lastChild.lastChild.firstChild.firstChild.firstChild.style.display='none';

	var coord = document.getElementById('saveCoord').value;

	var URL = '../lite/XSLT_COORD_REQUEST';
	var _params = { 
		language: 'en',
		coord: coord,
		inclFilter: '1',
		type_1: 'POI_POINT',
		radius_1: '804',
		inclDrawClasses_1:'39:40:41:42:43:44:45:46:47:48:49:50:51:52:53:54:55:56:57:58:59:60:61:62:63:64:65:66:67:68:69:70:71:72:73:74:75:76:77:78:79:80',
		coordListOutputFormat:'STRING',
		mapNameOutput: 'MTCV',
		hideBannerInfo:'1'
	};
	
	var childes = document.getElementById(storedDivId).lastChild.lastChild.lastChild.firstChild.firstChild.lastChild.lastChild.childNodes;
	
	/* for (var i =0; i < childes.length; i ++){
		if(childes[i].name=='searchRadius'){
			_params['radius_1'] = childes[i].value;
		}
	} */
	
	_params = $H(_params);
	_params = _params.toQueryString();
	
	var _ajax = new Ajax.Request(URL, { method: 'post', parameters: _params, onComplete: onPoiSelectionCallback});
}

/* Reload the select boxes */
function onPlaceSelectionCallback(response){
	this.innerHTML = response.responseText;
}

function onPoiSelectionCallback(request){
	
 	var json = null;
 	var efa = null;
 	
	// Check if we need to use the prototype lib.
 	if (request && request.responseText)	{
 		json = request.responseText;
 	// Otherwise use jQuery lib.
 	} else if (request) {
 		json = request;
 	}
 	
 	eval('efa = ' + json + ';'); 	

	var i = 0;
	var b = 0;
	var imgNum = 1;
    
    if(efa.pins[i] || efa.pins.pin){
        var p = efa.pins[i] || efa.pins.pin;	
    }
    else{
        var p = efa.coordInfo.pins[i] || efa.coordInfo.pins.pin;	
    }
    
	var insertTableText ='';
	var poiLayer = mdvOAKMapHelper.mdvMap.getLayer('efa_pois');
	var displayUnderMapBox=0;
    
	var bcoords = new Array();
    	bcoords['x'] =  new Array();
    	bcoords['y'] =  new Array();
        
		if(efa.coordInfo){
            bcoords['x'].push(efa.coordInfo.request.coords.x);
            bcoords['y'].push(efa.coordInfo.request.coords.y);
        }
      
	insertTableText += '<a href="javascript:void(0)" onclick="mdvOAKMapHelper.mdvMap.getLayer(\'efa_pois\').removeAllMarkers();document.getElementById(\'tbl_underMapBox\').style.display=\'none\'" style="padding-left:5px;">Clear Nearby Attractions</a>';
	
	insertTableText += '<table class="underMapLegend" id="tbl_underMapLegend" cellpadding="0" cellspacing="0">';
		
	if(createLayer=='0' && !poiLayer){
	
		poiLayer = mdvOAKMapHelper.mdvMap.createLayer('efa_pois');
		poiLayer.setZIndex(2);
		mdvOAKMapHelper.mdvMap.addLayer(poiLayer);
			
		createLayer='1';
	}
	else{
		createLayer='1';
		poiLayer = mdvOAKMapHelper.mdvMap.getLayer('efa_pois');
	}
		
	poiLayer.removeAllMarkers();
	
    var sortObj = new Object();
        
    if(efa.coordInfo){
        
        for (var d=0; d < efa.coordInfo.pins.length; d++) {
            if (sortObj[efa.coordInfo.pins[d].coords] !== undefined) {
                sortObj[efa.coordInfo.pins[d].coords].push(efa.coordInfo.pins[d])
            } 
            else {
                sortObj[efa.coordInfo.pins[d].coords] = [efa.coordInfo.pins[d]];
            }
        }
    }
    else{
        for (var d=0; d < efa.pins.length; d++) {
            if (sortObj[efa.pins[d].coords] !== undefined) {
                sortObj[efa.pins[d].coords].push(efa.pins[d])
            } 
            else {
                sortObj[efa.pins[d].coords] = [efa.pins[d]];
            }
        }
    }

    
	while (p) {
    
        if(p.coords){
		
            var tmpImg  = new Image();
            var coordList = p.coords.split(',');
            var coords = new MDVCoordinates('MTCV',
            coordList[0],
            coordList[1]);
            
            var pos = 0.5;
            var poiName = p.desc;
            
            if(poiName&& poiName.length > 35){
                poiName = poiName.substring(0,35) + '...'
            }
            
            var text  = '<span id="BeginDialogContent" class="hiddenText_508">Beginning of dialog content</span>';
                text += '<div class="smallHeader">';
                text += poiName;
                text += '</div>'
                text += '<div class="content" id="poi_' + p.id + '">';
                text += '<br/>';
                text += '<a href="javascript:getNearbyAttractions(\'91075670\',\'0\',' + coordList[0] +',' + coordList[1] +',\'poi_' + p.id +'\');">Nearby Attractions</a>';
                text += '<br/>';
                text += '<br/>';
                text += '<a href="javascript:mdvOAKMapHelper.zoomIn(new MDVCoordinates(\'MTCV\', ' + coordList[0] + ', ' + coordList[1] + '));">Zoom in</a>';
                text += '<br/>';
                text += '<br/>';
                
                text += '<a href="javascript:mdvOAKMapHelper.planTo('+ p.gisID+ ', \'poiID\',' + p.omc +');">Plan a trip to this location</a>';
                text += '<br/>';
                text += '<a href="javascript:mdvOAKMapHelper.planFrom('+ p.gisID+ ', \'poiID\',' + p.omc +');">Plan a trip from this location</a>';
                text += '<br/><br/>';
                text += '<a href="javascript:mdvOAKMapHelper.nearbyStops('+ p.gisID+ ', \'poiID\',' + p.omc +');">Nearby Stops and Routes</a>';
                

               if(p.attrs[5] && p.attrs[5].value == storedPOIHierarchy  
                    || p.attrs[4] && p.attrs[4].value == storedPOIHierarchy
                    || p.attrs[3] && p.attrs[3].value == storedPOIHierarchy
                    || p.attrs[2] && p.attrs[2].value == storedPOIHierarchy){
                      
                        if(sortObj[p.coords].length > 1)
                        {
                            var sCoord = 0;
                            
                            for(var c=0; c < sortObj[p.coords].length; c++)
                            {
                                var so = sortObj[p.coords][c];
                                if(so.attrs[5] && so.attrs[5].value == storedPOIHierarchy 
                                     || so.attrs[3] && so.attrs[3].value == storedPOIHierarchy
                                     || so.attrs[2] && so.attrs[2].value == storedPOIHierarchy)
                                {
                                     
                                    if(so.desc != p.desc)
                                    {
                                        text += '<br/><br/>';
                                        text += '<a href="javascript:void(0);" onclick="mdvOAKMapHelper.mdvMap.getLayer(\'efa_pois\').markers['+sCoord+'].toolTip.display()" style="text-decoration: none;">';
                                        text += '<strong>' + so.desc +'</strong>';
                                        text += '</a>';
                                    }
                                    sCoord++
                                }
                            }
                            text += '<span class="hiddenText_508">End of dialog content</span>';
                        }
                    
                        tmpImg.src = 'fw/mdv/points/poi' + imgNum + '.gif';
                    
                        /* table below the map */
                        if(b % 2 == 0 && b < 10){
                            insertTableText += '<tr id="tr_dest_page_' + b/2 +'" class="active">';
                        }
                        else if (b % 2 == 0){
                            insertTableText += '<tr id="tr_dest_page_' + b/2 +'" class="inActive">';
                        }
                        insertTableText += '<td class="itemAll" valign="top" style="background-image:url(';
                        insertTableText += tmpImg.src;
                        insertTableText += ')">';
                        insertTableText += '<a href="javascript:void(0);" onclick="mdvOAKMapHelper.mdvMap.getLayer(\'efa_pois\').markers['+b+'].toolTip.display()" style="text-decoration: none;">';
                        insertTableText += '<strong>' + p.desc +'</strong>';
                        insertTableText += '</a>';
                        //insertTableText += '<br/>' + p.attrs[3].value + ' - ' + p.attrs[2].value + '<br/>';
                        insertTableText += '<br/>' + p.attrs[3].value + '<br/>';
                        insertTableText += '</td>';
                        if(b % 2 != 0){
                            insertTableText += '</tr>';
                        }
                        
                        var poiPin = mdvOAKMapHelper.mdvMap.createMarker(coords, pos, tmpImg.src);
                            poiPin.setToolTip(mdvOAKMapHelper.mdvMap.createToolTip(new MDVPoint(320, 202), text));
                        
                        displayUnderMapBox = 1;
                        
                        bcoords['x'].push(coords.x);
                        bcoords['y'].push(coords.y);
                        
                        poiLayer.addMarker(poiPin, false);
                        imgNum ++;
                        b++;
                }
           
        
        }
        
            i++;
        
            if(efa.coordInfo){
                p = efa.coordInfo.pins[i];	
            }
            else{
                p = efa.pins[i];	
            }
        
		
	}
    
    if(bcoords.x.length > 1 && bcoords.y.length > 1){
        beautifyMap(bcoords)
    }
    
	mdvOAKMapHelper.mdvMap.update();
	
	insertTableText += '</table>';
	
	if(poiLayer.markers.length > 10){
	
		var poiListIndex = poiLayer.markers.length;
	
		insertTableText +='<div class="underMapPageNavBox"><table width="100%"><tbody><tr><td style="width: 100%; text-align: right;" id="underMapPageNavBoxA"><a id="next_5_' + poiListIndex +'" href="javascript:void(0);" onclick="viewNextPois(this.id)">Next &gt;&gt;</a></td></tr></tbody></table></div>';
	} 
	

	if(displayUnderMapBox==1){
		document.getElementById('errorTbl_underMapBox').style.display='none';
		document.getElementById('tbl_underMapBox').style.display='';
		document.getElementById('div_dest_page').innerHTML = insertTableText;
		
		if(mdvOAKMapHelper.mdvMap.markerLayer.markers.length > 0){
			mdvOAKMapHelper.mdvMap.markerLayer.hideToolTips()
		}

		
		if(mdvOAKMapHelper.mdvMap.getLayer('efa_trip').markers.length > 0){
			mdvOAKMapHelper.mdvMap.getLayer('efa_trip').hideToolTips()
		}
		
		if(mdvOAKMapHelper.mdvMap.getLayer('railSystems') && 
            mdvOAKMapHelper.mdvMap.getLayer('railSystems').markers.length > 0){
			mdvOAKMapHelper.mdvMap.getLayer('railSystems').hideToolTips()
		}
		
	}
	else{
	
		document.getElementById('tbl_underMapBox').style.display='none';
		document.getElementById('div_dest_page').innerHTML = '';
		document.getElementById('errorTbl_underMapBox').style.display='';
		document.getElementById('errorTbl_underMapBox').innerHTML='No landmarks in category ' + storedPOIHierarchy + ' found';
		//alert('No landmarks were found');
	
	}
	
}


// this function beautify the map
function beautifyMap(coords) {

	var x = coords['x'];
	var y = coords['y'];
	
	x.sort(MDVMap_NumSort);
	y.sort(MDVMap_NumSort);
	
	var width  = x[x.length-1] - x[0];
	var height = y[y.length-1] - y[0];
	var newX   = parseInt(x[0]) + Math.floor(0.5 + width/2);
	var newY   = parseInt(y[0]) + Math.floor(0.5 + height/2);     	
	
	var centre = new MDVCoordinates(mdvOAKMapHelper.mdvMap.config.get('mapName'),
		newX, newY);
		
	var zoom = 0;
	var extd = mdvOAKMapHelper.mdvMap.getViewportExtends();
	
	var zls = mdvOAKMapHelper.mdvMap.config.getZoomLevels();
	for (var i=zls.length-1; i >= 0; i--) {
		var zl = zls[i];
		var bWidth = false;
		var bHeight = false;
		
		var vpTiles = new MDVPoint(extd.width / parseInt(zl.get('tileSizeX')),
			extd.height / parseInt(zl.get('tileSizeY')));
		
		var numTiles = new MDVPoint(zl.get('numberOfTilesX'), zl.get('numberOfTilesY'));
		var realExtends = new MDVPoint(zl.get('realWidth'), zl.get('realHeight'));
		
		var tileSize = new MDVPoint(Math.floor(0.5 + realExtends.x / numTiles.x),
			Math.floor(0.5 + realExtends.y / numTiles.y));
			
		var real = new MDVPoint(tileSize.x * vpTiles.x, tileSize.y * vpTiles.y);    		
		
		if (real.x > (width*1.15) && !bWidth) {
			zoom = i;
			bWidth = true;
		}		

		if (real.y > (height*1.15) && !bHeight) {
			zoom = i;
			bHeight = true;
		}
		
		if (bWidth && bHeight)
			break;
	}

	mdvOAKMapHelper.mdvMap.setCentre(centre);
	mdvOAKMapHelper.mdvMap.setZoomLevel(zoom);
};

function viewNextPois(objId){

	var pos = objId.split('_');
	var tableRows = document.getElementById('tbl_underMapLegend').firstChild.childNodes;
	var showTableUntilPos = parseInt(pos[1]) +5;
	var showPrevTableUntilPos = parseInt(pos[1]) -5;
	var showTableLastPos = parseInt(pos[2]);

	for (var i=0; i < tableRows.length; i++) {
	
		if(i >= pos[1] && i < showTableUntilPos){
			tableRows[i].className="active";
		}
		else{
			tableRows[i].className="inActive";
		}
	
	}
	
	if(showTableLastPos/2 > showTableUntilPos && showTableLastPos/2 > showPrevTableUntilPos){
		document.getElementById('underMapPageNavBoxA').innerHTML = '<a id="prev_' + showPrevTableUntilPos + '_' + pos[2] +'" href="javascript:void(0);" onclick="viewPrevPois(this.id)">&lt;&lt;Previous</a>&nbsp;<a id="next_' + showTableUntilPos + '_' + pos[2] +'" href="javascript:void(0);" onclick="viewNextPois(this.id)">Next &gt;&gt;</a>';

	}
	else if(showTableLastPos/2 > showTableUntilPos){
		document.getElementById('underMapPageNavBoxA').innerHTML = '<a id="next_' + showTableUntilPos + '_' + pos[2] +'" href="javascript:void(0);" onclick="viewNextPois(this.id)">Next &gt;&gt;</a>';
	
	}
	else if(showTableLastPos/2 < showTableUntilPos){
		document.getElementById('underMapPageNavBoxA').innerHTML = '<a id="prev_' + showPrevTableUntilPos + '_' + pos[2] +'" href="javascript:void(0);" onclick="viewPrevPois(this.id)">&lt;&lt;Previous</a>';
	
	}
	else{
		document.getElementById('underMapPageNavBoxA').innerHTML = '<a id="prev_' + showPrevTableUntilPos + '_' + pos[2] +'" href="javascript:void(0);" onclick="viewPrevPois(this.id)">&lt;&lt;Previous</a>';
	
	}

}


function viewPrevPois(objId){

	var pos = objId.split('_');
	var tableRows = document.getElementById('tbl_underMapLegend').firstChild.childNodes;
	var showTableUntilPos = parseInt(pos[1]) +5;
	var showPrevTableUntilPos = parseInt(pos[1]) -5;
	var showTableLastPos = parseInt(pos[2]);

	for (var i=0; i < tableRows.length; i++) {
	
		if(i >= pos[1] && i < showTableUntilPos){
			tableRows[i].className="active";
		}
		else{
			tableRows[i].className="inActive";
		}
	
	}

	//if(showTableLastPos/2 > showTableUntilPos && showTableLastPos/2 > showPrevTableUntilPos && showPrevTableUntilPos > 0){
    if(showTableLastPos/2 > showTableUntilPos && showTableLastPos/2 > showPrevTableUntilPos && showPrevTableUntilPos >= 0){
		document.getElementById('underMapPageNavBoxA').innerHTML = '<a id="prev_' + showPrevTableUntilPos + '_' + pos[2] +'" href="javascript:void(0);" onclick="viewPrevPois(this.id)">&lt;&lt;Previous</a>&nbsp;<a id="next_' + showTableUntilPos + '_' + pos[2] +'" href="javascript:void(0);" onclick="viewNextPois(this.id)">Next &gt;&gt;</a>';
	}
	
	else if(showTableLastPos/2 > showTableUntilPos){
		document.getElementById('underMapPageNavBoxA').innerHTML = '<a id="next_' + showTableUntilPos + '_' + pos[2] +'" href="javascript:void(0);" onclick="viewNextPois(this.id)">Next &gt;&gt;</a>';
	
	}
	else if(showTableLastPos/2 < showTableUntilPos){
		document.getElementById('underMapPageNavBoxA').innerHTML = '<a id="prev_' + showPrevTableUntilPos + '_' + pos[2] +'" href="javascript:void(0);" onclick="viewPrevPois(this.id)">&lt;&lt;Previous</a>';
	
	}
	else{
		document.getElementById('underMapPageNavBoxA').innerHTML = '<a id="prev_' + showPrevTableUntilPos + '_' + pos[2] +'" href="javascript:void(0);" onclick="viewPrevPois(this.id)">&lt;&lt;Previous</a>';
	
	}
}


/* BUBBLE Nearby Attraction Link  */
function getNearbyAttractions(omc, placeID, x, y, divId){

    if(omc==''){
        omc = '91075670';
    }

    if(placeID==''){
        placeID = '0';
    }

	if(document.getElementById('findBoxOutputInnerHTML') && document.getElementById(divId)){
	
		if(storedDivId!=divId){
		    try
		    {
		       var pageid = 'index.html';
		       pageid = (window.location && window.location.href && window.location.href.indexOf('homepage=railSystems') >= 0) ? 'index.html' : 'initerary.html'
		    }catch(e){}
		    mdvEventLog.trigger('SECTION1_MAP_NEARBY_ATTRACTIONS_LOCATIONS_LINK', pageid, '');	
			originalBubbleContent = document.getElementById(divId).innerHTML;
		}
			
		document.getElementById(divId).style.display='';

		document.getElementById(divId).innerHTML = document.getElementById('findBoxOutputInnerHTML').innerHTML;
		// delete ids 
		//document.getElementById('findBoxOutputInnerHTML').innerHTML = '<br/>';
		
		document.getElementById('saveCoord').value = x + ':' + y +':MTCV';
		storedDivId = divId;
		sendPOIHierarchyRequest(x, y, 0, 'empty', 'poi', 'Output', divId);
	}
}

/* get the pois  and hierarchies*/
function sendPOIHierarchyRequest(x, y, session, state, type, request, divId){

    var coord = x + ':' + y +':MTCV'
    
	var URL = 'XSLT_COORD_REQUEST';
	var _params = { 
        coord: coord,
        coordListOutputFormat:'STRING',
        inclDrawClasses_1: '',
        radius_1:'805',
        inclDrawClasses_2:'',
        radius_2:'805',
        purpose:'',
        inclFilter:'1',
        coordListFormat: 'STRING',
        max:'-1',
        type_1:'POI_POINT',
        language:'en',
        type_2:'POI_AREA',
        itdLPxx_mdvMapName:'mdvMap_mdvMap_origin',
        hierarchy:'1',
        outputFormat:'JSON'
	};
		
		
	_params = $H(_params);
	_params = _params.toQueryString();
		
	var element = document.getElementById('reloadPoiSelection' + request);

	
	if(request=='Output'){
		document.getElementById(storedDivId).style.display='';
		element = document.getElementById(storedDivId).lastChild.lastChild.lastChild.firstChild.firstChild.lastChild.lastChild;
	}
	
	var _ajax = new Ajax.Request(URL, { method: 'post', parameters: _params, onComplete: sendPOIHierarchyRequestCallback.bind(element) });
}


var tmpReq = null;

/* Reload the select boxes */
function sendPOIHierarchyRequestCallback(request){

     tmpReq = request;

 	var json = null;
 	var efa = null;
 	
	// Check if we need to use the prototype lib.
 	if (request && request.responseText)	{
 		json = request.responseText;
 	// Otherwise use jQuery lib.
 	} else if (request) {
 		json = request;
 	}
 	
 	eval('efa = ' + json + ';'); 
    
    var hierarchy = efa.pins[efa.pins.length-1].poiHierarchyRoot;
    
    var topHierarchy= this.firstChild;
    var subHierarchy= this.childNodes[2];
    
    var button = this.lastChild;
    button.setAttribute('onclick', 'sendNewPOICoordRequest(this)'); 
    button.onclick = function() {sendNewPOICoordRequest(this)};

    
     var newSubEntry = new Option('All Subcategories', 'all', false, false);
      subHierarchy.options[subHierarchy.options.length] = newSubEntry;
    
    if(hierarchy){
        for(var i =0; i < hierarchy.length;i++){            
            if(hierarchy[i].hierarchy.length == 1){
                
                  var newEntry = new Option(hierarchy[i].hierarchyText, hierarchy[i].hierarchy, false, false);
                  topHierarchy.options[topHierarchy.options.length] = newEntry;
            }
            else{
                  var newEntry = new Option(hierarchy[i].hierarchyText, hierarchy[i].hierarchy, false, false);
                  subHierarchy.options[subHierarchy.options.length] = newEntry;
            }
            
        }
    }

    topHierarchy.disabled=false;
    topHierarchy.setAttribute('onclick', 'showSubHierarchy(this)'); 
    topHierarchy.onclick = function() {showSubHierarchy(this)};
    topHierarchy.options[0].value='-2';
    
    if(topHierarchy.selectedIndex!=0){
        subHierarchy.disabled=false;
    }
	
}


function showSubHierarchy(obj){

    if(obj.parentNode.parentNode.firstChild.className=='landmarkErrorMsg'){
        var message = obj.parentNode.parentNode.firstChild;
        message.parentNode.removeChild(message)
    }

    var key = obj.options[obj.selectedIndex].value
    
    if(key.length > 3 || key < 0){
        return false
    }
    
    for(var i =0; i < obj.parentNode.childNodes[2].options.length; i++){
    
        if(obj.parentNode.childNodes[2].options[i].value.substring(0,1) == key){
            obj.parentNode.childNodes[2].options[i].style.display=''
        }
        else if(obj.parentNode.childNodes[2].options[i].value == 'all' ||
        obj.parentNode.childNodes[2].options[i].value == 'Sub Category'){
            obj.parentNode.childNodes[2].options[i].style.display=''
        }
        else{
            obj.parentNode.childNodes[2].options[i].style.display='none'
        }
    }
    
    obj.parentNode.childNodes[2].options[0].innerHTML = 'Select Sub Category';
    obj.parentNode.childNodes[2].options[0].value = '-1';
    obj.parentNode.childNodes[2].disabled=false;
}


/* get the pois  for the map */
function sendNewPOICoordRequest(obj){
    
    var topHierarchy = obj.parentNode.firstChild.options[obj.parentNode.firstChild.options.selectedIndex].value;

    storedPOIHierarchy = obj.parentNode.childNodes[2].options[obj.parentNode.childNodes[2].options.selectedIndex].value;
    
    if(storedPOIHierarchy=='all'){
        storedPOIHierarchy = topHierarchy;
    }
    
    if(storedPOIHierarchy=='-1'){
       var node = obj.parentNode;
       var div = document.createElement('div');
           div.className='landmarkErrorMsg';
           div.style.display='block';
       var txt = document.createTextNode('Please select a subcategory'); 
           div.appendChild(txt); 
           node.parentNode.insertBefore(div, node);

           return false;
    }
    else if(topHierarchy=='-2'){
        
       var node = obj.parentNode;
       var div = document.createElement('div');
           div.className='landmarkErrorMsg';
           div.style.display='block';
       var txt = document.createTextNode('Please select a category'); 
           div.appendChild(txt); 
           node.parentNode.insertBefore(div, node);

           return false;
    }

    try
    {
        var pageid = 'index.html';
        pageid = (window.location && window.location.href && window.location.href.indexOf('homepage=railSystems') >= 0) ? 'index.html' : 'initerary.html'
    }catch(e){}
    mdvEventLog.trigger('SECTION1_MAP_NEARBY_ATTRACTIONS_LOCATIONS_REQUEST', pageid, '');	    
    onPoiSelectionCallback(tmpReq)
}

function goBackToOriginalBubbleContent(obj){
	obj.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML=originalBubbleContent;
}

function checkInitialTab() {
	var valid = true;
	var sessionIDs = document.getElementsByName('sessionID');

	for (var i=0; i < sessionIDs.length; i++) {
		var s = sessionIDs[i];
		if (s && parseInt(s.value) != 0) {
			valid = false;
			break;
		}
	}
	
	if (valid) {
		if (location.href.indexOf('#') > -1) {
			var c = location.href.substring(location.href.indexOf('#')+1)
			var b = document.getElementById('a_' + c);

			if (b && typeof b.onclick == 'function')
				b.onclick.apply();
		}
	}
}

function checkForTicker() {
	//MDVTicker
	
	var emergencyBox = document.getElementById('emergencyBox');
	var emergencyInfo = document.getElementById('emergencyInfo');
	var topOffset = -9;
	
	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
		topOffset--;
	}
	
	if (!emergencyBox || !emergencyInfo)
		return;
		
	ticker = new MDVTicker('transit', emergencyInfo, getTickerFetchUrl);
	ticker._hasData = function () { if (emergencyBox.style.display == 'none') emergencyBox.style.display = 'block'; emergencyInfo.style.top = topOffset + 'px'; };
	ticker._hasNoData = function () { if (emergencyBox.style.display == 'block' || emergencyBox.style.display == '') emergencyBox.style.display = 'none'; };
	ticker.execute();
		
	//window.setInterval(ticker.doScrolling.bind(ticker), document.all ? 60 : 20);
	moveTicker();
	window.setInterval(ticker.update.bind(ticker), 60000);
}

function moveTicker() {
	ticker.doScrolling();
	window.setTimeout(moveTicker, document.all ? 55 : 20);
}

function getTickerFetchUrl() {
	return 'XSLT_REQUEST';
}

function showTransitProviders()
{
	document.getElementById('transitProvidersBubble').style.display='';
	
	//var objstart=document.getElementById("a_start_providerpopup");
	
	// this popup uses tabs which means we need to transfer focus to something with a tabindex.
	var objstart=document.getElementById("transitProvidersBubble");
	objstart.focus();
	
//	var objclose=document.getElementById("a_end_providerpopup");
//	objclose.onclick=function()
//	{
//	    document.getElementById('transitProvidersBubble').style.display='none';
//	    document.getElementById('transitProviders').focus();
//	}
}

function hideTransitProviders()
{
    document.getElementById('transitProvidersBubble').style.display='none';
    document.getElementById('a_TransitProvidersOpenDialog').focus();
}

function checkSelMOT(obj){

	var useOnlyOP = document.forms[0].useOnlyOP;
	var preferInclOP = document.forms[0].preferInclOP;
	var mustExclOP = document.forms[0].mustExclOP;
	var checkedOp = 0;
	/* Added if for 3089 */
	if(useOnlyOP!=undefined)
	{
	    for (var iIndex = 0; iIndex < useOnlyOP.length; iIndex++)

		    if(useOnlyOP[iIndex].checked==true)
		    {
			    checkedOp += 1;
		    }
	}	
	for (var iIndex = 0; iIndex < preferInclOP.length; iIndex++)

		if(preferInclOP[iIndex].checked==true)
		{
			checkedOp += 1;
		}
		
		
	for (var iIndex = 0; iIndex < mustExclOP.length; iIndex++)

		if(mustExclOP[iIndex].checked==true)
		{
			checkedOp += 1;
		}
	
	if(obj.checked==false || checkedOp!='0'){
		if (document.getElementById('selMOT'))
			document.getElementById('selMOT').value='0';
	}
	else{
		if (document.getElementById('selMOT'))
			document.getElementById('selMOT').value='1';
	}

}

// this function reload the announcement messages box 
function intervalAnnouncement(){

	var reloadAnnouncement = document.getElementById('reloadAnnouncement')
	
	if (!reloadAnnouncement ){
		return false;
	}
	
	 window.setInterval('reloadAnnouncement()', 120000);

}

function reloadAnnouncement(){
	
	var URL = 'XSLT_TRIP_REQUEST2';
	var _params = { 
		itdLPxx_homepage: 'refreshAnnoncement'
	};
		
	_params = $H(_params);
	_params = _params.toQueryString();

	var _ajax = new Ajax.Request(URL, { method: 'post', parameters: _params, onComplete: onReloadAnnoncementCallback});

}

function onReloadAnnoncementCallback(response){
	
	document.getElementById('reloadAnnouncement').innerHTML = response.responseText;

}

function SingleSelect(regex,current)
{
    re = new RegExp(regex);
    
    for(i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];
        if (elm.type == 'checkbox') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }        
        }
    }
    current.checked = true;
}
//Mantis 3089
function SelectUseOnlyUptoNItems(regex,current,numItems)
{
    
    if (current.checked == false) 
    {
        for(j = 0; j < selectedUseOnly.length; j++) {
            if (selectedUseOnly[j] == current.id) {
                selectedUseOnly.splice(j,1);
            }
        }
        disableMustExclOP();
        return;
    }
        
    selectedUseOnly.push(current.id);
    if (selectedUseOnly.length > numItems)
        selectedUseOnly.shift();

    re = new RegExp(regex);
    var count=0;
    for(i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];
        if (elm.type == 'checkbox') {
            if (re.test(elm.name)) {
                if (elm.checked) {
                    elm.checked = false;
                    for(j = 0; j < selectedUseOnly.length; j++) {
                        if (selectedUseOnly[j] == elm.id) {
                            elm.checked = true;
                        }
                    }
                }
            }        
        }
    }
    disableMustExclOP();
}

//Mantis 3089
function setSelectedUseOnly(regex)
{
    if(document.forms[0]!=null)
    {
        re = new RegExp(regex);
        for(i = 0; i < document.forms[0].elements.length; i++) 
        {
            elm = document.forms[0].elements[i];
            if (elm.type == 'checkbox') {
                if (re.test(elm.name)) {
                    if (elm.checked) {
                        selectedUseOnly.push(elm.id);
                    }
                }        
            }
        }
    }
}

/*Added 3089 */
function ClearUseOnlyOPSelection()
{

   var useOnlyOP = document.forms[0].useOnlyOP;
   var mustExclOP=document.forms[0].mustExclOP;;
   for (var iIndex = 0; iIndex < useOnlyOP.length; iIndex++)
   {
   		if(useOnlyOP[iIndex].checked==true)
   		{
		    mustExclOP[iIndex].disabled=false;
		}
	    useOnlyOP[iIndex].checked=false;
   }
   selectedUseOnly=[];//Clear array
}
/*Added 3089 */
function ClearMustExclOPSelection()
{

   var useOnlyOP = document.forms[0].useOnlyOP;
   var mustExclOP=document.forms[0].mustExclOP;;
   for (var iIndex = 0; iIndex < mustExclOP.length; iIndex++)
   {
   		if(mustExclOP[iIndex].checked==true)
   		{
		    useOnlyOP[iIndex].disabled=false;
		}
	    mustExclOP[iIndex].checked=false;
   }
  mustExcOpOnly=[];//Clear array
}
function disableMustExclOP()
{

   var useOnlyOP = document.forms[0].useOnlyOP;
   var mustExclOP=document.forms[0].mustExclOP;;
   for (var iIndex = 0; iIndex < useOnlyOP.length; iIndex++)
   {

		if(useOnlyOP[iIndex].checked==true)
		{
			mustExclOP[iIndex].checked=false;
			mustExclOP[iIndex].disabled=true;
			mustExclOP[iIndex].parentNode.style.color='#3f3f3f';
		}
		else
		{
		    mustExclOP[iIndex].disabled=false;
		}
  }
}
function disableUseOnlyOP()
{

   var useOnlyOP = document.forms[0].useOnlyOP;
   var mustExclOP=document.forms[0].mustExclOP;;
   for (var iIndex = 0; iIndex < mustExclOP.length; iIndex++)
   {

		if(mustExclOP[iIndex].checked==true)
		{
			useOnlyOP[iIndex].checked=false;
			useOnlyOP[iIndex].disabled=true;
			useOnlyOP[iIndex].parentNode.style.color='#3f3f3f';
		}
		else
		{
		    useOnlyOP[iIndex].disabled=false;
		}
  }
}
//Mantis 3089
function SelectMustExcUptoNItems(regex,current,numItems)
{
    
    if (current.checked == false) 
    {
        for(j = 0; j < mustExcOpOnly.length; j++) {
            if (mustExcOpOnly[j] == current.id) {
                mustExcOpOnly.splice(j,1);
            }
        }
       disableUseOnlyOP();
        return;
    }
        
    mustExcOpOnly.push(current.id);
    if (mustExcOpOnly.length > numItems)
        mustExcOpOnly.shift();

    re = new RegExp(regex);
    var count=0;
    for(i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];
        if (elm.type == 'checkbox') {
            if (re.test(elm.name)) {
                if (elm.checked) {
                    elm.checked = false;
                    for(j = 0; j < mustExcOpOnly.length; j++) {
                        if (mustExcOpOnly[j] == elm.id) {
                            elm.checked = true;
                        }
                    }
                }
            }        
        }
    }
    disableUseOnlyOP();
}
//Mantis 3089
function setSelectedMustExc(regex)
{
   if(document.forms[0]!=null)
    {
        re = new RegExp(regex);
        for(i = 0; i < document.forms[0].elements.length; i++) {
            elm = document.forms[0].elements[i];
            if (elm.type == 'checkbox') {
                if (re.test(elm.name)) {
                    if (elm.checked) {
                        mustExcOpOnly.push(elm.id);
                    }
                }        
            }
        }
    }    
}
sfHover = function() {
    //4011 - Check for null 
    var nav = document.getElementById("internal-top-nav");
    if (nav != null)
    {
	    var sfEls = nav.getElementsByTagName("LI");
	    for (var i=0; i<sfEls.length; i++) {
		    sfEls[i].onmouseover=function() {
			    this.className+=" sfhover";
		    }
		    sfEls[i].onmouseout=function() {
			    this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		    }
	    }
	}
}
/* Bart Strike Function Added */
function showLayer()
{ 
    toggleLayer('additionalOptions');    
   
    /* Mantis Id:4156 - Start */
    if( document.getElementById('findBox') != null)
    {
        document.getElementById('findBox').style.marginTop='-10px';
    }
    /* Mantis Id:4156 - End */
        
    if(document.getElementById('additionalOptions') && (document.getElementById('additionalOptions').style.display=='block'))
    {
        mdvEventLog.trigger('SECTION1_ADDITIONAL_OPTIONS_LINK', 'index.html', '');
    }
    
    
    /* Uncomment the below four lines for bart over lay strike */
//    if(document.getElementById('additionalOptions').style.display=='none')
//    {
//    document.getElementById('div_additionalOption_cover').style.display='none';
//    }
//    else{
//        document.getElementById('div_additionalOption_cover').style.display='block'
//    }
    return true;
}
if (window.attachEvent) window.attachEvent("onload", sfHover);


//START Function to get elements by class name - iterates through all tag elements on the page
function getElementsByClassName( strClassName, obj ) {
    var ar = arguments[2] || new Array();
    var re = new RegExp("\\b" + strClassName + "\\b", "g");

    if ( re.test(obj.className) ) {
        ar.push( obj );
    }
    for ( var aa = 0; aa < obj.childNodes.length; aa++ )
        getElementsByClassName( strClassName, obj.childNodes[aa], ar );
    
    return ar;
}
//END Function to get elements by class name - iterates through all tag elements on the page
			
function preselectLeastCost()
{
	if (lcRoutePos)
		expandCollapseLCTrips('expand' , lcRoutePos, 'load');
}

attachEventListener(window, 'load', preselectLeastCost, false);
attachEventListener(window, 'load', function(e) {
		var forms = document.forms;
		
		for (var ii=0; ii < forms.length; ii++) {
			attachEventListener(forms[ii], 'submit', function(e){
			
				var routeType = document.getElementById('routeType');
				var intervall = document.getElementById('intervall');
				
				if (routeType && routeType.value == 'LEASTCOST' && intervall) {
					intervall.value = 60;
				} else if (routeType && routeType.value != 'LEASTCOST' && intervall) {
					intervall.value = 0;
				}
				
				var nameVia = document.getElementById('name_via');
				var placeVia = document.getElementById('place_via');
				
				if (nameVia && nameVia.value != '')
					nameVia.value = '';
					
				if (placeVia && placeVia.value != '')
					placeVia.value = '';
				
				return true;
				
			}, false);
		}
		
		var routeType = document.getElementById('routeType');
		var arrDepType = document.getElementById('itdTripDateTimeDepArr');
		/* Lowest Cost Rollback
		if (routeType)
		if(routeType.value=='LEASTCOST') {
			document.getElementById('itdTripDateTimeDepArr').options[1].disabled = true;
		}
		else
		{
			document.getElementById('itdTripDateTimeDepArr').options[1].disabled = false;
		}
				
		
		if (arrDepType)
		if(arrDepType.value=='arr') {
			document.getElementById('routeType').options[3].disabled = true;
		}
		else{
			document.getElementById('routeType').options[3].disabled = false;
		}		
		*/			
			
		if (routeType)
			attachEventListener(routeType, 'change', function(e){
				if(routeType.value=='LEASTCOST') {
					document.getElementById('viaOption').style.display='none';
					document.getElementById('viaHint').style.display='block';
					document.getElementById('itdTripDateTimeDepArr').options[1].disabled = true;
				} else {
					document.getElementById('viaOption').style.display='block';
					document.getElementById('viaHint').style.display='none';
					document.getElementById('itdTripDateTimeDepArr').options[1].disabled = false;
				}				
			});
		/* Lowest Cost Rollback
		if (arrDepType)
		attachEventListener(arrDepType, 'change', function(e){
			if(arrDepType.value=='arr') {
				document.getElementById('routeType').options[3].disabled = true;
			}
			else{
				document.getElementById('routeType').options[3].disabled = false;
			}
							
			});
		    */
	}, false);

//3146 - Begin add
function PrintAgencies() {
	try {
	var ifrm = document.getElementById('ifrmPrint');
	
	var contentBus = document.getElementById('tab1Content').innerHTML;
    contentBus = formatPrintContent(contentBus);

    var contentRail = document.getElementById('tab2Content').innerHTML;
    contentRail = formatPrintContent(contentRail);
    
	var contentFerry = document.getElementById('tab3Content').innerHTML;
    contentFerry = formatPrintContent(contentFerry);

    var contentShuttles = document.getElementById('tab4Content').innerHTML;
    contentShuttles = formatPrintContent(contentShuttles);
    
    var contentOther = document.getElementById('tab5Content').innerHTML;
    contentOther = formatPrintContent(contentOther);
    
    	/* Determine what DOM model to use */
	var printDoc = (ifrm.contentWindow || ifrm.contentDocument);
	if (printDoc.document) {
		printDoc = printDoc.document;
	}

	/* Create a HTML document to go into the iFrame */
	var txt = getPrintHeader();
		txt += "<br/><b>Transit Agencies</b><br/>";

	txt += "<br/><b>Bus Agencies</b>";
	txt += contentBus + "<br/>";
	txt += "<b>Rail Agencies</b>";
	txt += contentRail + "<br/>";	
	txt += "<b>Ferry Agencies</b>";
	txt += contentFerry + "<br/>";		
	txt += "<b>Shuttles</b>";
	contentShuttles = contentShuttles.replace(/<div([^>]*)>/gi, "<div>");
	txt += contentShuttles + "<br/>";		
	txt += "<b>Other Agencies</b>";
	contentOther = contentOther.replace(/<div([^>]*)>/gi, "<div>");
	txt += contentOther + "<br/>";	
	txt += getPrintFooter();	
	printDoc.write(txt);
	printDoc.close();
	
	//Open a print window instead of directly printing using iframe
	win = window.open("", "win1", PrintWindowParams);
	if (win != null) {
    win.document.write(txt);
  	win.document.close();
	}
	}

	catch(e) {
		self.print();
	}
}

function formatPrintContent(content) {

    var anchorEnd = /<\/a>/gi;
    content = content.replace(anchorEnd, "");
    var anchor = /<a([^>]*)>/gi;
    content = content.replace(anchor, "");
    content = content.replace(/\*/g, "");
   return content;
}


function getPrintHeader() {
    var header = "";
    	header += "<html><head><title>Transit.511.org</title>";
	header += "<link media='screen,print' rel='stylesheet' type='text/css' href='css/print.css' />";
	header += "<style type='text/css'> .hiddenText_508 {display:none;} </style>";
//header += "</head><body onload='this.focus(); this.print();'>";  //Use this if iframe used for printing - without print preview window
	header += "</head><body>";
		 header += "<div class='mainLogoBox' style='width:100%;margin-top:10px'>";
		   header += "<table width='693px' cellpadding='0'>";
                header += "<tr>";
                    header += "<td valign='bottom'>";
                    //3146-5
                    //header += "<div style='position:absolute;left:30px;top:18px;'><img src='img/printimages/511-logo.gif' alt='511 - SF Bay Area' class='logo511SFBayArea' /></div><span style='font-size: .95em;font-weight: bold;color: #536b25;width: 200px;position: absolute;left: 100px;top: 55px;'>SF Bay Area</span></td>";
                    header += "<div style='position:absolute;left:30px;top:15px;'><img src='img/printimages/511-logo.gif' alt='511 - SF Bay Area' class='logo511SFBayArea' /></div><span style='font-size: .95em;font-weight: bold;color: #536b25;width: 200px;position: absolute;left: 100px;top: 55px;'></span></td>";
                    header += "<td valign='top' style='padding-left:100px;'><img src='img/printimages/toplogoforprint.jpg' alt='Transit header' /></td>";
                header += "</tr>";
                  header += "<tr>";
                    header += "<td colspan='2' id='td_bannerbottom' style='padding-top:28px!important;vertical-align:top;'>";
                        header += "<img alt='' src='img/printimages/topnav-internal-bg.gif' width='630px' height='30px' />";
                        header += "<br /><br />";
                    header += "</td>";
                header += "</tr>";
        header += "</table>";
     header += "<script type='text/javascript'>";
	    header += "if(navigator.appName == 'Microsoft Internet Explorer')";
       header += "{";
          header += "document.getElementById('td_bannerbottom').style.padding='22px 0 0 0';";
       header += "}";
	  header += "</script>";
		  header += "</div>";
		  
		      header += "<table width='630px' cellpadding='0'><tr><td>"  //3146-5

		  return header;
}


function getPrintFooter() {

    var footer = "";
      footer += "</td></tr></table>" //3146-5
      footer += "<br /><br /><br />";
      footer += "<table width='630px' cellpadding='0'><tr><td>" //3146-5

    
    footer += "<div class='copyrightBox'>";
    footer += "<small><p>&nbsp;&nbsp;&nbsp;Brought to you by <a href='#' style='text-decoration:none;'>MTC</a> and <a href='#' style='text-decoration:none;'>Bay Area Transit Partners</a>";
    footer += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='#' style='text-decoration:none;'>&#169; 2012 Metropolitan Transportation Commission</a></p></small>";
    footer += "</div>";
    footer += "</td></tr></table>" //3146-5
    	footer += "</body></html>";

    return footer;

}


function PrintAnnouncement() {

//3146-5
    //var header = document.getElementById('announcementBubbleHead').title;	
    var header = document.getElementById('announcementBubbleHead').innerHTML;
	var content = document.getElementById('announcementBubbleContent').innerHTML;	
	
	var ifrm = document.getElementById('ifrmPrint');
	
    	/* Determine what DOM model to use */
	var printDoc = (ifrm.contentWindow || ifrm.contentDocument);
	if (printDoc.document) {
		printDoc = printDoc.document;
	}

	/* Create a HTML document to go into the iFrame */
	var txt = getPrintHeader();
    txt += "<br/><b>" + header + "</b><br/><br/>";
    txt += content + "</br>";
	txt += getPrintFooter();	
	
	printDoc.write(txt);
	printDoc.close();
	
	//Open a print window instead of directly printing using iframe
	win = window.open("", "win1", PrintWindowParams);
	if (win != null) {
  	win.document.write(txt);
  	win.document.close();
	}
}

function PrintScheduleBubble(){
	var content = document.getElementById('customizedScheduleContent').innerHTML;	
	
	var ifrm = document.getElementById('ifrmPrint');
	
    	/* Determine what DOM model to use */
	var printDoc = (ifrm.contentWindow || ifrm.contentDocument);
	if (printDoc.document) {
		printDoc = printDoc.document;
	}

	/* Create a HTML document to go into the iFrame */
	var txt = getPrintHeader();
    txt += "<br/><b>Schedule Detail</b><br/><br/>" + expandShortNames(content) + "</br>";
	txt += getPrintFooter();	
	printDoc.write(txt);
	printDoc.close();
	
	//Open a print window instead of directly printing using iframe
	win = window.open("", "win1", PrintWindowParams);
	if (win != null) {
  	win.document.write(txt);
  	win.document.close();
  }
}

//3146-4
function expandShortNames(content){
  //Find title="$1"$2>$3... and replace with $2>$1 (We dont need title. But replace shortened text with title)
  var objRegExp = /title="([^"]*)"([^>]*)>([^\.\.\.]*)\.\.\./gim; 
  var newcontent = content.replace(objRegExp, "$2>$1");
  return newcontent;
}

//3146-6
function expandShortNamesForRoutes(content){
  //In Facilities-Routes tab, the ... is enclosed within a span element which has the title.
  //Find (>$1 title="$2">...</span>) and replace with (>$2) (We dont need inner span element. But replace with title of inner span element)
  var objRegExp = />([^"]*)title="([^"]*)"([^>]*)>([^\.\.\.]*)\.\.\.<\/span>/gim; 
  var newcontent = content.replace(objRegExp, ">$2");
  return newcontent;
}

function GetStationName(stopID){
    var stationSelect = document.getElementById('stationSelect');	
    if (stationSelect == null)
        return "";
    for (var i=0; i < stationSelect.options.length; i++) {
        if (stationSelect[i].value == stopID)
            return stationSelect[i].text;
    }
    return "";
}


function PrintScheduledDeparturesBubble(stopID){
    var stopName = GetStationName(stopID);
    if (stopName == "")
        stopName = document.getElementById('span_' + stopID).innerHTML;	

	var content = document.getElementById('stop_' + stopID).innerHTML;	
	
	var ifrm = document.getElementById('ifrmPrint');
	
    	/* Determine what DOM model to use */
	var printDoc = (ifrm.contentWindow || ifrm.contentDocument);
	if (printDoc.document) {
		printDoc = printDoc.document;
	}

	/* Create a HTML document to go into the iFrame */
		var txt = getPrintHeader();
    txt += "<br/>Scheduled Departures from '" + stopName + "'</br>";
    txt += "<br/>" + expandShortNames(content) + "</br>";
	txt += getPrintFooter();	
	printDoc.write(txt);
	printDoc.close();
	
	//Open a print window instead of directly printing using iframe
	win = window.open("", "win1", PrintWindowParams);
	if (win != null) {
  	win.document.write(txt);	
  	win.document.close();
	}
}

function PrintAllFacilities(stopID){

    var divParking = document.getElementById("printParking");
    mdvOAKMapHelper.fetchFacilities('parking', stopID, divParking);
    
    var divCycling = document.getElementById("printCycling");
    mdvOAKMapHelper.fetchFacilities('cycling', stopID, divCycling);

    var divRoutes = document.getElementById("printRoutes");
    mdvOAKMapHelper.fetchFacilities('routes', stopID, divRoutes);

    var divFeatures = document.getElementById("printFeatures");
    mdvOAKMapHelper.fetchFacilities('features', stopID, divFeatures);
    
    //setTimeout("PrintFacilities(stopID)", 5000);
       var stop = stopID;
   setTimeout(function () {PrintFacilities(stop);}, 2000);
    }
    
    
function PrintFacilities(stopID){

    var divParking = document.getElementById("printParking");
    
    var divCycling = document.getElementById("printCycling");

    var divRoutes = document.getElementById("printRoutes");

    var divFeatures = document.getElementById("printFeatures");

    //var stopAddress = document.getElementById('fInfo_' + stopID).innerHTML;
    var stop = '';
    	var arr = stopID.split('_');	
	   if (arr.length >= 1)
		    stop = arr[0];

    var stopName = '';
    
    //3146-5
    stopName = GetStationName(stop);
    if (stopName == '')
    {
        var spanObj = document.getElementById("span_" + stop);
    
        if (spanObj != null)
            stopName = spanObj.innerHTML;
        else
        {
            var obj = document.getElementById("fInfo_" + stop);
            var stopName = '';
            var parent = obj.parentNode.parentNode;
            for (var i=0; i < parent.childNodes.length; i++)
            {
                if (parent.childNodes[i].className == "largeHeader")
                    stopName = parent.childNodes[i].innerHTML;
            } 
        } 
    }

    	
	var ifrm = document.getElementById('ifrmPrint');
	
    	/* Determine what DOM model to use */
	var printDoc = (ifrm.contentWindow || ifrm.contentDocument);
	if (printDoc.document) {
		printDoc = printDoc.document;
	}

	/* Create a HTML document to go into the iFrame */
		var txt = getPrintHeader();
    txt += "<br/><b>Facilities for Stop: " + stopName + "</b></br>";
    txt += "<br/><b>Parking</b></br>";
    txt += divParking.innerHTML + "<br/>";
    txt += "<br/><b>Cycling</b></br>";
    txt += divCycling.innerHTML + "<br/>";
    txt += "<br/><b>Routes Served</b></br>";
    txt += expandShortNamesForRoutes(divRoutes.innerHTML) + "<br/>";
    txt += "<br/><b>Station Features</b></br>";
    txt += divFeatures.innerHTML + "<br/>";

	txt += getPrintFooter();	
	printDoc.write(txt);
	printDoc.close();
	
	//Open a print window instead of directly printing using iframe
	var win = window.open("", "win1", PrintWindowParams);
	if (win != null) {
  	win.document.write(txt);
  	win.document.close();
	}
}


function PrintFacility(stopID){

    //var stopAddress = document.getElementById("fInfo_" + stopID).innerHTML;
    var content = document.getElementById("fContent_" + stopID).innerHTML;
    var stopName = '';
    
    /*
    var obj = document.getElementById("fInfo_" + stopID);

    var parent = bubble.parentNode.parentNode;
    for (var i=0; i < parent.childNodes.length; i++)
    {
        if (parent.childNodes[i].className == "largeHeader")
            stopName = parent.childNodes[i].innerHTML;
    } 
    */
    
    stopName = document.getElementById("span_" + stopID).innerHTML;

    	
	/* Determine what tab is in use to get the title */
	var bubble = document.getElementById("bubbleBg_" + stopID);
	var title = '';
	if (bubble.style.background.indexOf("facilities1") > -1) 
	    title = "Parking";
	if (bubble.style.background.indexOf("facilities2") > -1) 
	    title = "Cycling";	
	if (bubble.style.background.indexOf("facilities3") > -1) 
	    title = "Routes Served";	
	if (bubble.style.background.indexOf("facilities4") > -1) 
	    title = "Station Features";	    
    	
	var ifrm = document.getElementById('ifrmPrint');
	
    	/* Determine what DOM model to use */
	var printDoc = (ifrm.contentWindow || ifrm.contentDocument);
	if (printDoc.document) {
		printDoc = printDoc.document;
	}

	/* Create a HTML document to go into the iFrame */
		var txt = getPrintHeader();
    txt += "<br/>Facilities for Stop '" + stopName + "'</br>";
    //txt += "<br/><br/>" + stopAddress + "<br/>";
    txt += "<br/><b>" + title + "</b></br>";
    txt += content + "<br/>";

	txt += getPrintFooter();	
	printDoc.write(txt);
	printDoc.close();
	
	//Open a print window instead of directly printing using iframe
	win = window.open("", "win1", PrintWindowParams);
	if (win != null) {
  	win.document.write(txt);
  	win.document.close();
	}
}

function PrintHelpBubble(){
    var header = document.getElementById('helpHeader').innerHTML;
    
    var content = document.getElementById('helpContent').innerHTML;
    	
	var ifrm = document.getElementById('ifrmPrint');
	
    	/* Determine what DOM model to use */
	var printDoc = (ifrm.contentWindow || ifrm.contentDocument);
	if (printDoc.document) {
		printDoc = printDoc.document;
	}

	/* Create a HTML document to go into the iFrame */
	var txt = getPrintHeader();
    txt += "<br/><b>" + header + "</b><br/><br/>";
    txt += content + "</br>";
	txt += getPrintFooter();	
	printDoc.write(txt);
	printDoc.close();
	
	//Open a print window instead of directly printing using iframe
	win = window.open("", "win1", PrintWindowParams);
	if (win != null) {
  	win.document.write(txt);
  	win.document.close();
	}
}

function checkRailLines(mdvMapVal){
    var result = mdvMapVal.match(/lines: \[(.*)\]/);
    if (result != null) {
        var lines = result[1].split(",");
        for (var i=0; i < lines.length; i++) {
            lines[i] = lines[i].trim();
            var elem = document.getElementById('line_' + lines[i].trim());
            if (elem !=null)
                elem.checked = true;
        }
        lines.sort(function (a, b) { return parseInt(a) - parseInt(b); });
        var str = lines.join(",");
        
        if (str.indexOf('1,2,3,4,5') > -1)
            document.getElementById('grp_1').checked = true;
        if (str.indexOf('6,7,8') > -1)
            document.getElementById('grp_2').checked = true;
        if (str.indexOf('9,10,11') > -1)
            document.getElementById('grp_3').checked = true;
        if (str.indexOf('12,13,14,15,16,17,18,19') > -1)
            document.getElementById('grp_4').checked = true;
        if (str.indexOf('26,27,28') > -1)
            document.getElementById('grp_5').checked = true;       
            
    }
    
    document.getElementById("tblRailCheckBoxes").width = 600;
    
             //Disable all checkboxes
    for (var i=1; i < 29; i++) {
        var elem = document.getElementById('line_' + i);
        if (elem != null)
            elem.enabled = false;
    }
    
    for (var i=1; i < 6; i++) {
        var elem = document.getElementById('grp_' + i);
        if (elem != null)
            elem.enabled = false;
    }
}
//3146 - End Add


attachEventListener(document, 'load', fixLegend, false);
attachEventListener(window, 'load', applyAgencies, false);
attachEventListener(window, 'load', applyFootpathTravelTime, false);
attachEventListener(window, 'load', applyOnChangeSpeedChange, false);
attachEventListener(window, 'load', checkInitialTab, false);
attachEventListener(window, 'load', checkForTicker, false);
attachEventListener(window, 'load', intervalAnnouncement, false);

//Mantis Issue: 0003473  Starts Here
function trimEmail(str){
	var	str = str.replace(/^\s\s*/,''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	str= str.slice(0, i + 1);
	i = str.length;
	if(i>0)
	{
	    if(str.charAt(i-1)==',') 
	        str= str.slice(0, i-1);
    	
	    if(str.charAt(i-1)==';') 
	        str= str.slice(0, i-1);
	}
  return str;
}
//Mantis Issue: 0003473  Ends Here

/* 508-function starts here */
ChangePageTitle =function(title)
{
    if(title!=null && title!="")
        window.document.title=title;
}
ChangeTabTitle =function(tabindx)
{
    if(document.getElementById('a_tab1Selected'))
      changetitletext('a_tab1Selected','Plan a Trip - Tab');
    
    if(document.getElementById('a_tab2Selected'))
        changetitletext('a_tab2Selected','Nearby Stops and Routes - Tab');
    
    if(document.getElementById('a_tab3Selected'))
    {
        if(document.getElementById('a_tab3Selected').innerHTML=="Real-Time Departures")
            changetitletext('a_tab3Selected','Real-Time Departures - Tab');
        else 
            changetitletext('a_tab3Selected','Rail Systems - Tab');
    }
    
  if(tabindx==1)
    if(document.getElementById('a_tab1Selected'))
       changetitletext('a_tab1Selected','Plan a Trip - Tab - Selected');
   
  if(tabindx==2)
    if(document.getElementById('a_tab2Selected'))
        changetitletext('a_tab2Selected','Nearby Stops and Routes - Tab - Selected');
        
    if(document.getElementById('nearbyInstructions'))
    {
       if(document.getElementById('nearbyInstructions').style.display!='none')
       {
           
            if(document.getElementById("a_nrs_instructionstart"))
            {
                document.getElementById("a_nrs_instructionstart").focus();
            }
       }
     }
 
  if(tabindx==3)
    if(document.getElementById('a_tab3Selected'))
    {
        if(document.getElementById('a_tab3Selected').innerHTML=="Real-Time Departures")
            changetitletext('a_tab3Selected','Real-Time Departures - Tab - Selected');
        else 
            changetitletext('a_tab3Selected','Rail Systems - Tab - Selected');
    }
   
   function changetitletext(elementid,txt)
      {
        var objelement=document.getElementById(elementid);
        for( var idx = 0; idx < objelement.attributes.length; idx++ ) 
        {
          if( objelement.attributes[idx].nodeName.toLowerCase() == 'title' )
          {
              objelement.attributes[idx].nodeValue=txt;
          }
        }

      }
      
      
      
    if(document.getElementById('tbl_underMapBox')){
        document.getElementById('tbl_underMapBox').style.display='none';
    }
      
}
SendMailClick= function(btnemail)
{
   // Mantis Issue:0003473 Starts Here 
      var mail = trimEmail(document.forms['formMailAFriend'].emailAddress.value.trim());
      //var filter=/^.+@.+\..{2,3}$/
      //if (!filter.test(mail))
      //Mantis Issue:0004027 Starts Here
      var expression = /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/;
      if (!expression.exec(mail))  // Mantis Issue:0004027 Ends Here
      {
          alert('Please enter a valid email address!');
          return false;
      }
      else 
      {
          sendMailAFriend();
          mdvEventLog.trigger('SECTION1_ITINERARY_EMAILED', 'itinerary.html', '');
          document.getElementById(btnemail).focus();
          return true;
      }
      		
  // Mantis Issue:0003473 Ends Here 

   
   
//    var mail = document.forms['formMailAFriend'].emailAddress.value.trim();
//    var expression = /^[_a-zA-Z0-9-](\.{0,1}[_a-zA-Z0-9-])*@([a-zA-Z0-9-]{1,}\.){0,}[a-zA-Z0-9-]{2,}(\.[a-zA-Z]{2,4}){1,2}$/;
//    if(!expression.exec(mail))
//        {
//            alert('Please enter a valid email address!');
//            return false;
//        }
//     else
//        {
//            sendMailAFriend();
//            mdvEventLog.trigger('SECTION1_ITINERARY_EMAILED', 'itinerary.html', '');
//            document.getElementById(btnemail).focus();
//            return true;
//        }

}
function closeRailFerrySelection(usage,type){

	var   isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') ;  //mantis# 3647
	if (document.getElementById('findBox')!=null)
	{
	    if(document.getElementById('findBox').style.display=='block')
	    {    
	   
	        document.getElementById('findBox').style.display = 'none';
	        if(type=='findRailStation')
	        {
		        document.getElementById('a_rail_selectlink_trip').style.display='';
		        document.getElementById('a_rail_selectlink_trip').focus();
		    }
	        if(type=='findFerryLanding')
	        {
		        document.getElementById('a_ferry_selectlink_trip').style.display='';
		        document.getElementById('a_ferry_selectlink_trip').focus();
		    }	
	    }
	}
	if (document.getElementById('findBoxDM')!=null)
	{
		
		if(document.getElementById('findBoxDM').style.display=='block')
		{
		
		    document.getElementById('findBoxDM').style.display = 'none';
		    if(type=='findRailStation')
		    {
		        document.getElementById('a_rail_selectlink_nrs').style.display='';
		        document.getElementById('a_rail_selectlink_nrs').focus();
		    }
	        if(type=='findFerryLanding')
	        {
		        document.getElementById('a_ferry_selectlink_nrs').style.display='';
		        document.getElementById('a_ferry_selectlink_nrs').focus();	
		    }
		 }
	}
	
	if (document.getElementById('findBox'))
		{document.getElementById('findBox').style.display = 'none';
		  if (isIE6 != -1)
          {
          	 showSelect();  //mantis# 3647
          }
		}
	
	if (document.getElementById('findBoxDM'))
		{document.getElementById('findBoxDM').style.display = 'none';
		    if (isIE6 != -1)
              {
              	 showSelectDm(); //mantis# 3647
              }
		}		
	
		
	if (document.getElementById('findBoxOutput'))
		document.getElementById('findBoxOutput').style.display = 'none';
		
   	// Temp: Disabled.
	return;
	
	var form = document.forms[0];
	
	if(usage=='dm'){
		form = document.forms[1];
	}


	if(document.getElementById('nameState_' + usage)){
		if(document.getElementById('nameState_' + usage).value){
			document.getElementById('nameInfo_' + usage).value='';
			if(document.getElementById('placeInfo_' + usage)){
				document.getElementById('placeInfo_' + usage).value='';
			}
		}
	}


	form.itdLPxx_findObjectBox.value = '';
	form.execInst.value = 'verifyOnly';
	form.submit();
	
}
function showTripFeedBack(feedbtnid,emailbtnid)
{
    document.getElementById('feedbackForm').style.display='';
    document.getElementById('emailName_feedback').focus();
    document.getElementById('mailAFriendForm').style.display='none';
    var objclosebtn=document.getElementById("a_close_feedbackform");
    objclosebtn.onclick = function () {closeFeedBack(feedbtnid,emailbtnid);}
    var objhiddenclose=document.getElementById("a_feedback_end");
    objhiddenclose.onclick = function () {closeFeedBack(feedbtnid,emailbtnid);}
    var objsendfdbackbtn=document.getElementById("btn_tripsendfeedback");
    objsendfdbackbtn.onclick = function () {
        if(checkValidFeedbackForm(4,feedbtnid))
        {
            var objemailbtn=document.getElementById(emailbtnid);
            objemailbtn.setAttribute("tabIndex","1071");
            SetTripSearchLinkIndexes(feedbtnid,true);
        }
    }
    var objemailbtn=document.getElementById(emailbtnid);
    objemailbtn.setAttribute("tabIndex","1080");
    SetTripSearchLinkIndexes(feedbtnid,false);
    
}
function closeFeedBack(feedbtnid,emailbtnid)
{
        document.getElementById(feedbtnid).style.display='';
        document.getElementById(feedbtnid).focus();
        document.getElementById('feedbackForm').style.display='none';
        if(emailbtnid!='null')
        {
            var objemailbtn=document.getElementById(emailbtnid);
            objemailbtn.setAttribute("tabIndex","1071"); 
            SetTripSearchLinkIndexes(emailbtnid,true);
        }
}
function showNrsFeedBack(feedbtnid,blnstops)
{
   document.getElementById('feedbackForm').style.display='';
   document.getElementById('emailName_feedback').focus();
   var objclosebtn=document.getElementById("a_close_feedback_nrs");
   objclosebtn.onclick = function () {closeFeedBack(feedbtnid,'null');}
   var objhiddenclose=document.getElementById("a_feedback_end");
   objhiddenclose.onclick = function () {closeFeedBack(feedbtnid,'null');}
   
   if(blnstops=='0')
   {
    document.getElementById('feedbackForm').style.top = '600px';
   }
   var objsendfdbackbtn=document.getElementById("btn_nrssendfeedback");
   objsendfdbackbtn.onclick = function () {checkValidFeedbackForm(3,feedbtnid);}
}
function showTripEmail(emailbtnid)
{
    document.getElementById('mailAFriendForm').style.display='';
    document.getElementById('emailAddress_mail').focus(); 
    document.getElementById('feedbackForm').style.display='none'
    var objclosebtn=document.getElementById("btn_close_emailform");
    objclosebtn.onclick =function (){
        document.getElementById('mailAFriendForm').style.display='none';
        var objemailbtn=document.getElementById(emailbtnid);
        objemailbtn.setAttribute("tabIndex","1071"); 
        objemailbtn.focus();
        SetTripSearchLinkIndexes(emailbtnid,true);
        
    }
    var objhiddenclose=document.getElementById("a_email_end");
    objhiddenclose.onclick = function () {
        document.getElementById('mailAFriendForm').style.display='none';
        var objemailbtn=document.getElementById(emailbtnid);
        objemailbtn.setAttribute("tabIndex","1071"); 
        objemailbtn.focus();
        SetTripSearchLinkIndexes(emailbtnid,true);
    }
    var objSendEmailbtn=document.getElementById("btn_sendmail");
    objSendEmailbtn.onclick =function (){
        if(SendMailClick(emailbtnid))
        {
            
            var objemailbtn=document.getElementById(emailbtnid);
            objemailbtn.setAttribute("tabIndex","1071"); 
            SetTripSearchLinkIndexes(emailbtnid,true);
        }
        
    }
    var objemailbtn=document.getElementById(emailbtnid);
    objemailbtn.setAttribute("tabIndex","1080");
    SetTripSearchLinkIndexes(emailbtnid,false);
}
function SetTripSearchLinkIndexes(btnid,blnReset)
{
     var idx=btnid.split("_")[3];
     var objreversetrip=document.getElementById('a_reversetrip_'+ idx);
     var objonwardtrip=document.getElementById('a_onwardtrip_'+ idx);
     var objrevisetrip=document.getElementById('a_revisesearch_'+ idx);
     var objnewtrip=document.getElementById('a_newsearch_'+ idx);
     if(blnReset==true)
     {
        objreversetrip.setAttribute("tabIndex","1072");
        objonwardtrip.setAttribute("tabIndex","1073");
        objrevisetrip.setAttribute("tabIndex","1074");
        objnewtrip.setAttribute("tabIndex","1075");
     }
     else
     {
        objreversetrip.setAttribute("tabIndex","1090");
        objonwardtrip.setAttribute("tabIndex","1091");
        objrevisetrip.setAttribute("tabIndex","1092");
        objnewtrip.setAttribute("tabIndex","1093");
     }
}
setFocusById =function (elementid)
{
    
    if(document.getElementById(elementid)!=null)
        document.getElementById(elementid).focus();
}
/* 508-function ends here */

//mantis# 3647 start
function hideSelect()
{
    if (document.getElementsByName('itdTripDateTimeDepArr'))
	   {document.getElementsByName('itdTripDateTimeDepArr').item(0).style.display = 'none';}
    if (document.getElementsByName('routeType'))
       {document.getElementsByName('routeType').item(0).style.display = 'none';}
	if (document.getElementsByName('itdLPxx_riderCategory'))
	   {document.getElementsByName('itdLPxx_riderCategory').item(0).style.display = 'none';}	
	if (document.getElementsByName('itdLPxx_TimeAMPM'))
       {document.getElementsByName('itdLPxx_TimeAMPM').item(0).style.display = 'none';}
	if (document.getElementsByName('trITMOTvalue'))
	   {
	     document.getElementsByName('trITMOTvalue').item(0).style.display = 'none';
	     }
}

function  hideSelectDm()
{
   if (document.getElementsByName('itdLPxx_TimeAMPM'))
       {document.getElementsByName('itdLPxx_TimeAMPM').item(1).style.display = 'none';}
   if (document.getElementsByName('trITMOTvalue'))
	   {
	     document.getElementsByName('trITMOTvalue').item(1).style.display = 'none';}

}

function showSelectDm()
{
	if (document.getElementsByName('itdLPxx_TimeAMPM'))
       {document.getElementsByName('itdLPxx_TimeAMPM').item(1).style.display = '';}
	if (document.getElementsByName('trITMOTvalue'))
	   {document.getElementsByName('trITMOTvalue').item(1).style.display = '';	    
	   }
}

function showSelect()
{
    if (document.getElementsByName('itdTripDateTimeDepArr'))
	   {document.getElementsByName('itdTripDateTimeDepArr').item(0).style.display = '';}
    if (document.getElementsByName('routeType'))
       {document.getElementsByName('routeType').item(0).style.display = '';}
	if (document.getElementsByName('itdLPxx_riderCategory'))
	   {document.getElementsByName('itdLPxx_riderCategory').item(0).style.display = '';}	
	if (document.getElementsByName('itdLPxx_TimeAMPM'))
       {document.getElementsByName('itdLPxx_TimeAMPM').item(0).style.display = '';}
	if (document.getElementsByName('trITMOTvalue'))
	   {document.getElementsByName('trITMOTvalue').item(0).style.display = '';}
}
//mantis# 3647 end

//mantis # 3681 mobile start
function focusonMobilelink()
{
   var mobilePage = document.getElementById("mlink");
   if (mobilePage != null) document.getElementById("mlink").focus();   
}
//mantis # 3681 mobile end
//mantis #3980: add mobiletool link
function hideMobileTool(){
	if(document.getElementById('mobileToolDiv'))
	{document.getElementById('mobileToolDiv').style.display='none';	}
}
function showMobileTool(){
	if(document.getElementById('mobileToolDiv'))
	{document.getElementById('mobileToolDiv').style.display='';	}
}
//mantis #3980: end

function HideStartEndButton()
{
     document.getElementById('btnSetAsStart').style.display = 'none';
	 document.getElementById('btnSetAsEnd').style.display = 'none';
}
function ResetToDefault()
{
  document.getElementById('nameRailStation').selectedIndex = 0;	
  document.getElementById('nameFerryLanding').selectedIndex = 0;
  document.getElementById('placeInfo').value='';
  document.getElementById('nameMainLandmark').selectedIndex = 0;
  document.getElementById('nameMainLandmark').disabled = true;
  document.getElementById('nameInfoSubHierarchy').selectedIndex = 0;
  document.getElementById('nameInfoSubHierarchy').disabled = true;
  document.getElementById('nameLandmark').selectedIndex = 0;
  document.getElementById('nameLandmark').disabled = true;
  document.getElementById('btnSetAsStart').style.display='none';
  document.getElementById('btnSetAsEnd').style.display='none';
  
}

//mantis # 3951
function validateOriginDestination()
{
   if(document.getElementById('name_origin').value.length > 0 && document.getElementById('name_origin').value !='Address, Intersection or Landmark') 
   { 
       if(document.getElementById('name_destination').value.length > 0 && document.getElementById('name_destination').value !='Address, Intersection or Landmark')
	   {
		  
		  checkNameInputOnSubmit();if(document.getElementById('findBox').style.display=='block')setPoint('origin');
	   }
	   else
	   {
	    alert(" Please enter the Start and End Locations");
		return false;
	   }
   }
   else 
   { 
       
        alert(" Please enter the Start and End Locations");
		return false;
   }
}

function ClearRttBubble()
{
    try
    {
        var rttBubble = document.getElementById('realTimeBubble');        
        if (rttBubble) 
        {
            rttBubble.style.display = 'none';
        }
    }
    catch(e){}   
}


