var BUS_NO;
var BUS_STOP;
var FROM_STOP;
var TO_STOP;
var STATICMAP_GLOBAL_PATH = "http://maps.google.com/staticmap?key=ABQIAAAABiB_FPBzrb-glbRLSDPbehRYO-9KJQB2kFVUL1LyZdWGiLBYnBQYvldW2sKZE8UevPtEzuSMlXdvMQ";
var MapTitle="";
var staticMapURL ="";
var GDLG = 0;
var staticMapURLs = [];
var CURCTX ="";
var SEARCHRESULTDIVTOMAIL ="";
var SEARCHGRIDS = 0;
var staticMapURLs2 = new Array();
var TRANSITMETROIMAGE ="<img src = 'images/Train.png'  border='0' title ='This trip uses a Metro' />"; 
var TRANSITBUSIMAGE ="<img src = 'images/bus_stop.png'  border='0' title ='This trip uses a Bus' />"; 
function DoSearch()
{
search1 = document.getElementById("txtsearch1").value;
if (document.getElementById("txtsearch2") != null)
search2 = document.getElementById("txtsearch2").value;

 

  var found_it;
for (var i=0; i<document.form1.search.length; i++)  { 
if (document.form1.search[i].checked)  {
found_it = document.form1.search[i].id;
  
} 
} 
  switch(found_it) 
   {  
    case 'rdSrchBusStop':   
        GetBusStopDetails(search1);
        break;

    case 'rdSrchBusNo':   
         GetBusNoDetails(search1);
     break;
    case 'rdSrchBusRoute':   
        GetBusRoute(search1, search2);
        break;

    case 'rdSrchBusStopLookup':   
        showPostcodeLookup();
     break;
    default:   
       // showRouteSearch(); 
     break;
    }



}

function disableSearch()
{
 document.getElementById("btnSearch").disabled =true;
 document.getElementById("imgWait").style.display ='block';
}
function enableSearch()
{
 document.getElementById("btnSearch").disabled =false;
 document.getElementById("imgWait").style.display ='none';
}
function GetBusNoDetails(busno)
{

if ( busno == "Enter Route No")
    busno ="";
    
	if(busno.length == 0)
	{
		alert("Please enter the Bus / Train / Metro No  to find its details.");
		return;
	}
    BUS_NO = busno;


    //showProgressBox("Searching Bus no");
    disableSearch();
	Imap.WebServices.BusSvc.GetBusNoDetails(document.getElementById("hidLogId").value, busno,$find('AutoCompleteEx')._contextKey, SucceededBusDetailsResults, handleFailedBusNoDetails);
	
}

// This is the callback function invoked if the Web service
// succeeded.
// It accepts the result object as a parameter.

function SucceededBusDetailsResults(result, eventArgs)
{	
	    enableSearch();
    	var resHtml = "";
    	resHtml = DisplaySucceededBusDetailsResults("Details of No: " + BUS_NO, result);
        displaySearchResultsGrid(resHtml,MapTitle,true,false,'','');
}

function displaySearchResultsGrid(resHtml,MapTitle, hasRoutemap,isRouteSearch,place1,place2)
{
    	if (resHtml == 1)
    	return;
    	document.getElementById("table5").style.display = "block";
    	document.getElementById("table5").style.visibility =  "visible";
    	document.getElementById("space4").style.display = "none";
        document.getElementById("infodlg").style.display = "none";
        document.getElementById("TdAdbig").style.display = "none";
       document.getElementById("space4").style.visibility = "hidden";
     document.getElementById("infodlg").style.visibility = "hidden";
    document.getElementById("TdAdbig").style.visibility = "hidden";
    
    	var  mapLink ='';
    	var  mapImage ='';
    	
    	GDLG = GDLG + 1;
        if(hasRoutemap)
        {
    	mapLink = "<a  class='SearchToolImages' id ='aid"+ GDLG + "' href='javascript:onclick=ShowStaticMap(tblmapdata"+ GDLG +");'> View Route Map Journey</a>"  ;
    	mapImage ="<img  class='SearchToolImages' id ='iid"+ GDLG + "' style='cursor:pointer' src='images/view-map2.png' alt ='view map' onclick='ShowStaticMap(tblmapdata"+ GDLG +")'/>";
    	}
    	var alink = '<img id =imgs' +GDLG +' src="images/copy.gif" border="0" class="SearchToolImages" title ="Copy this search" onclick="copySrcRsltpane(h' + GDLG + ')"/><a id =amail' +GDLG +' href="form.aspx" class="lbOn"><img id =imgs' +GDLG +' src="images/send.gif" border="0" title="mail this search" /></a><img class="SearchToolImages" id =imgc' +GDLG +' src="images/print.gif" border="0" title ="Print this search" onclick="printSrcRsltpane(h' + GDLG + ')"/><img class="SearchToolImages" id =imgi' +GDLG +' src="images/expanded.png" border="0"  title ="Expand/Collapse"  onclick="animatedcollapse.toggle(' + GDLG + ')" /><img class="SearchToolImages" id =imgx' +GDLG +' src="images/close.jpg" border="0"  title ="Close this search" onclick="closeSrcRsltpane(h' + GDLG + ')"/>';
	    if(!isRouteSearch)
	    resHtml =  "<table cellspacing='0' cellpadding='0%' class='SearchTitleTable'><tr><td  title ='Expand/Collapse' onclick='animatedcollapse.toggle("+GDLG+")'; class='SearchTitleTableData'   > " +MapTitle+ "</td><td class='SearchTitleTabledataTools' >"+ alink+"</td></tr></table><div id ='" + GDLG+"'> <table  cellspacing='0' cellpadding='0%' class='SearchResultsTabledata1'><tr  align='center'><td class='dlg'   width ='900px' style='text-align:center' colspan ='2' >"+mapLink + mapImage+"</td></tr><tr   style='text-align:center'><td class='dlg'   width ='90%' style='text-align:center' ><center> " +resHtml+" </center></td><td id='tblmapdata"+ GDLG +"' class='dlg'   width ='900px' valign='top' align='center'> </td></tr></table></td><td class='SearchResultsTabledata2' id = 'rtResultsGSec"+ GDLG +"' valign='top'> </tr></table>";
	    else
	    resHtml =  "<table  cellspacing='0' cellpadding='0%' class='SearchTitleTable'><tr><td  title ='Expand/Collapse' onclick='animatedcollapse.toggle("+GDLG+")'; class='SearchTitleTableData'   > " +MapTitle+ "</td><td class='SearchTitleTabledataTools' >"+ alink+"</td></tr></table><div id ='" + GDLG+"'> <table  cellspacing='0' cellpadding='0%' class='SearchResultsTabledata1'><tr  align='center'><td rowspan = 2 class='RTSearchResultsTabledata1'   width='450px' id = 'rtResults' >  <table  cellspacing='0' cellpadding='0%' class='RTSearchTitleTableData'><tr  align='center'><td class='dlg' align='center' colspan ='2'   width ='900px'>"+mapLink + mapImage+"</td></tr><tr  align='center'><td  width='450px' class='dlg' align='center' >" +resHtml+"</td></tr></table></td><td  width='450px' class='RTSearchResultsTabledata2'  id = 'rtResultsGSec"+ GDLG +"' valign='top'></td> </tr><tr  class='dlg'><td   class='dlg'  width='450px' id='tblmapdata"+ GDLG +"' valign='top' class='dlg' style='align='center'> </td></tr></table>";
        var resultsgrd;

		resultsgrd = document.getElementById("results").insertBefore(document.createElement("div"), document.getElementById("h"+(GDLG-1)));
        resultsgrd.id = "h"+ GDLG;
        resultsgrd.className ='dlg';
        resultsgrd.innerHTML  = resHtml;
//.insertBefore(newElement, referenceElement)

		
	    //results.innerHTML = resHtml;;//  + results.innerHTML;

	    animatedcollapse.uninit();
    	animatedcollapse.addDiv(GDLG, 'fade=0,speed=400,group=pets');
    	animatedcollapse.init();
    	animatedcollapse.show(GDLG);
    	var adtitle ='Local listings';
    	var adtext ='You can display your local listing free here';
    	var adstring ='';
    	if(place1.length > 0)
    	adtitle=adtitle + ' for ' + place1;
        adstring = "<table id = 'adt" +GDLG + "' class ='dlgE' cellspacing='0' cellpadding='0%'><tr><td>"+ adtitle +"</td></tr><tr><td>"+ adtext+"</td></tr>";   
    	
    	if(place2.length > 0)
    	{
    	  	var adtitle ='Local listings';
    	    adtitle=adtitle + ' for ' + place2;
           adstring = adstring  + "<tr><td>"+ adtitle +"</td></tr><tr><td>"+ adtext+"</td></tr>";   
	
    	}
    	adstring = adstring  + "</table>"; 
    	/**
    		adgrd = document.getElementById("AdText").insertBefore(document.createElement("div"), document.getElementById("ad"+(GDLG-1)));
            adgrd.id =  'ad' +GDLG;
            adgrd.innerHTML  = adstring;
    	
    	if (document.getElementById('ad' +GDLG) == null)
    	{
    		adgrd = document.getElementById("AdText").insertBefore(document.createElement("div"), document.getElementById("ad"+(GDLG-1)));
    	    adgrd.id =  'ad' +GDLG;
  	
    	}
    	    adgrd = document.getElementById('ad' +GDLG);
            adgrd.innerHTML  = adstring;*/
    	SEARCHGRIDS =SEARCHGRIDS+1;
    	
    	//document.getElementById("tdad").innerHTML = '<iframe src="ad.htm" width="468px" height="60px" frameborder="0" marginwidth ="0px" marginheight="0px" scrolling="no"></iframe>';
    	  //  	document.write( '<script type="text/javascript"><!--google_ad_client = "pub-4086457364603165";/* red text banner */google_ad_slot = "0006699116";google_ad_width = 468;google_ad_height = 60;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>');
initialize();
//document.location.hash = "#City="+ document.getElementById("hidCity").value+ "&MapTitle=" + MapTitle;
}

// This is the callback function invoked if the Web service
// failed.
// It accepts the error object as a parameter.

function handleFailedBusNoDetails(error)
{
	// Display the error.    
	//unloadProgressBox();
	enableSearch();
	alert("Bus/Train/Metro No Detail Service Connection Error: " + error.get_message() + '. Please submit your query again.');
}

function DisplaySucceededBusDetailsResults(titled, places)
{

	var resHtml = "";
	var latitude;
	var longitude;
    var latlonString ="";
     var MarketString ="";
	var title;
    var firsttime = true;
    var BusStopTitle ="";
     var TransitTitle ="";
     var TransitImg ="";
    var ImageUrl ;
    var MarkerCount; 
    var departure = "";
	/**  if there are no results, display the error message and return */
	if(places == null)
	{
		alert("There were no results for the specified route No, please check your query.");
		return 1;
	}

	if(places.BusStops == null)
	{
		alert("There were no results for the specified Route No, please check your query.");
		return 1;
	}
	if(places.BusStops.length == 0)
	{
		alert("There were no results for the specified Route no, please check your query.");
		return 1;
	}


	
     latlonString="";
	/**  Create an entry for each VEPlace in the result set */
	for(var p = 0; p < places.BusStops.length; p++)
	{

			/**  Gather some info up front */
		var place = places.BusStops[p];
		BusStop = place.StopName;
		var Origin =  places.Origin;
		var Destination =  places.Destination;

		if (firsttime)
		{

            var JourneyTime = places.JourneyTime;
            var ServiceType = places.ServiceType;
            var TransitType = places.TransitType;
            var ChangeTransitType = places.ChangeTransitType;
            
            if (TransitType == "Metro")
            {
                BusStopTitle = "Stations";
                TransitTitle = "Metro";
                TransitImg = TRANSITMETROIMAGE;
            }
            else if (TransitType == "Train")
            {
                BusStopTitle = "Stations";
                TransitTitle = "Train";
                TransitImg = TRANSITMETROIMAGE;
            }
            else
            {
                BusStopTitle= "Bus Stops";
                TransitTitle = "Bus";
                TransitImg =TRANSITBUSIMAGE;
            }
            if (ChangeTransitType == "Metro")
            {
                BusStopTitle = BusStopTitle + "/Stations[Metro]";
                TransitTitle = TransitTitle + "/Metro";
                TransitImg = TransitImg + TRANSITMETROIMAGE;
            }
            else if (ChangeTransitType == "Train")
            {
                BusStopTitle = BusStopTitle + "/Stations[Train]";
                TransitTitle = TransitTitle + "/Train";
                TransitImg = TransitImg + TRANSITMETROIMAGE;
            }
            else if ((ChangeTransitType == "") || (ChangeTransitType == "null") && (places.ChangeBusNo != "") && (places.ChangeBusNo != "null"))
            {
                 BusStopTitle= BusStopTitle + "/Bus Stops";
                TransitTitle = TransitTitle + "/Bus";
                TransitImg =TransitImg + TRANSITBUSIMAGE;
            }
           var str=places.Fare;
            if (str == null)
                str ="";
            var Fare =str.replace(new RegExp('<Stage',"g"), ''); ;
               Fare =Fare.replace(new RegExp('<stage',"g"), ''); ;
             Fare =Fare.replace(new RegExp('<br>',"g"), ''); ;
            Fare =Fare.replace(new RegExp('<fareInfo>',"g"), ''); ;
            Fare =Fare.replace(new RegExp('</ Stage>',"g"), ';'); ;
            
              Fare =Fare.replace(new RegExp('</ stage>',"g"), ';'); ;
             Fare =Fare.replace(new RegExp('>',"g"), ' for stage '); ;

             Fare =Fare.replace(new RegExp('>',"g"), ' for stage '); ;

             if (Fare=='0')
                Fare="NA";
             if (Fare=="")
                Fare="NA"; 
            var Distance = places.Distance ;
             if (Distance == null)
                Distance ="";
             if (Distance=='0')
                Distance="NA";
             if (Distance=="")
                Distance="NA"; 
            var DepartureFromO = places.DepartureFromO.replace(new RegExp(',',"g"), ', '); ;
            var DepartureFromD = places.DepartureFromD.replace(new RegExp(',',"g"), ', '); ;
            
    
            resHtml = resHtml + "<div class ='dlg' ><table>";
            resHtml = resHtml + "<tr class='dlg'><td class='dlgB' width= 150pxpx;>";
            resHtml = resHtml + "Origin:";  
            resHtml = resHtml + "</td><td class='dlg' width= 250px;>";
            resHtml = resHtml + Origin;
            resHtml = resHtml + "</td></tr><tr class='dlg'><td class='dlgB' width= 150px;>";
            resHtml = resHtml + "Destination:";  
            resHtml = resHtml + "</td><td class='dlg' width= 250px;>";
            resHtml = resHtml + Destination;
            resHtml = resHtml + "</td></tr><tr class='dlg'><td class='dlgB' width= 150px;>";
            resHtml = resHtml + "Distance:";
            resHtml = resHtml + "</td><td class='dlg' width= 250px;>";
            resHtml = resHtml + Distance + " Kms";
            resHtml = resHtml + "</td></tr><tr class='dlg'><td class='dlgB' width= 150px;>";
            resHtml = resHtml + "JourneyTime:";  
            resHtml = resHtml + "</td><td class='dlg' width= 250px;>";
            resHtml = resHtml + JourneyTime;
            resHtml = resHtml + "</td></tr></table>";
            resHtml = resHtml + "<table>";
		    resHtml = resHtml + "<tr class='dlg'><th class='dlg' width= 150px;>";
		    		    resHtml = resHtml +  places.TransitMode;
		    resHtml = resHtml + "</th>";
		    resHtml = resHtml + "<th class='dlg' width= 250px;> ";
		    resHtml = resHtml + places.TotalStops + " " +BusStopTitle;
		    resHtml = resHtml + "</th>" 
		    if (place.Departure.trim() !="")
		    {
		     resHtml = resHtml + "<th class='dlg' width=50px;> ";
		    resHtml = resHtml + "Timings";
		    resHtml = resHtml + "</th>" 
		    }
		     place.Departure.trim()

        firsttime=false;
        }      
      

		latitude = place.Latitude.trim();
		longitude = place.Longitude.trim();
		departure = place.Departure.trim();
        title =BusStop;
        if ((latitude != "null") && (longitude != "null") && (latitude != "") && (longitude != ""))
        { 
        latlonString = latlonString + latitude + "," + longitude + "|";
        
        if (p ==0)
        MarketString= MarketString + latitude + "," + longitude + ",midgreens|";
        else if (p ==places.BusStops.length - 1)
        MarketString= MarketString + latitude + "," + longitude + ",midredd|";
        else
        MarketString= MarketString + latitude + "," + longitude + ",tinyblue|";
        }
		ImageUrl = "";
		/**  create the info box description
		var desc = "Latitude: " + latitude + "<br/>" + "Longitude: " + longitude;  */
        var desc =  TransitTitle+ " No:" + BUS_NO;
        var numberImage ="";
        var ttext ="";

		    		var	    tem = title.replace(/ /gi, "%20"); 
        	    var tttext =   '<a href=javascript:GetBusStopDetails("' + tem + '");>'	 + title + "</a>";

		    numberImage =p + 1;
            ttext = tttext;

	
		/**  Add the information to the resultsDiv html, including a link */

		/**  that recenters the map over the pin */
		resHtml = resHtml + "<tr class='dlg'><td class='dlg' width= 150pxpx;>";
		resHtml = resHtml + numberImage + "</td><td class='dlg' width= 250px;> ";
		resHtml = resHtml + ttext+ "</td><td class='dlg'> ";
        resHtml = resHtml + departure;

		resHtml = resHtml + "</td></tr>";

		
	}

	resHtml = resHtml + "</table>";
	
	
            	resHtml = resHtml + "<table>";
            resHtml = resHtml + "<tr class='dlg'><td class='dlgB' width= 150pxpx;>";
            resHtml = resHtml + "Fare:";
            resHtml = resHtml + "</td><td class='dlg' width= 250px;>";
            resHtml = resHtml + Fare;
            resHtml = resHtml + "</td></tr><tr class='dlg'><td class='dlgB' width= 150pxpx;>";
            resHtml = resHtml + "ServiceType:";  
            resHtml = resHtml + "</td><td class='dlg' width= 250px;>";
            resHtml = resHtml + ServiceType;
            resHtml = resHtml + "</td></tr><tr class='dlg'><td class='dlgB' width= 150px;>";
            resHtml = resHtml + "Departure From Origin:";  
            resHtml = resHtml + "</td><td class='dlg' width= 250px;>";
            resHtml = resHtml + DepartureFromO;
            resHtml = resHtml + "</td></tr><tr class='dlg'><td class='dlgB' width= 150px;>";
            resHtml = resHtml + "Departure From Destination:";  
            resHtml = resHtml + "</td><td class='dlg' width= 250px;>";
            resHtml = resHtml + DepartureFromD;
            resHtml = resHtml + "</td></tr></table></div>";
           

            staticMapURL = STATICMAP_GLOBAL_PATH + "&path=rgb:0x000f0f,weight:3|"+latlonString+"&markers="+MarketString+"&size=450x400";
            staticMapURLs.push(staticMapURL);
            staticMapURLs2[GDLG+1]= staticMapURL;

            MapTitle = TransitImg+ "Journey with " + TransitTitle +" No : "+places.BusNo ;
            return resHtml;


}
function ShowStaticMap( ctrl)
{
var id = ctrl.id;
id = id.replace("tblmapdata","");

document.getElementById("aid"+ id).style.visibility = "hidden";
document.getElementById("aid"+ id).style.display = "none"
document.getElementById("iid"+ id).style.visibility = "hidden";
document.getElementById("iid"+ id).style.display = "none"

//if(id -1 >= staticMapURLs.length)
//return;
if(staticMapURLs2[id] == "")
return;

var	newHTML = '';

	newHTML = newHTML + '<div align="center" style="background-color: #ffe4e1;;" >';
	newHTML = newHTML + '<img src="'+staticMapURLs2[id] +'"  width="450px" height="400px"></img>';
	newHTML = newHTML + '</div>';
	/**	    animatedcollapse.uninit();
document.getElementById("tblmapdata1").innerHTML  =newHTML;
	var mObj = document.getElementById("tblmapdata1").appendChild(document.createElement("div"));
	mObj.id = "he"+ GDLG;
mObj.innerHTML  =newHTML;
*/
	    ctrl.innerHTML = newHTML;
	/**	    animatedcollapse.uninit();
    	
    	animatedcollapse.init();
    	animatedcollapse.show(GDLG)*/

}

function GetBusStopDetails(BusStopName)
{
if ( BusStopName == "Enter Stop/Station")
    BusStopName ="";
    
	if(BusStopName.length == 0)
	{
		alert("Please enter the BusStopName to find its location.");
		return;
	}


    BUS_STOP = BusStopName;
    //showProgressBox("Getting Bus Stop Details");
    disableSearch();
	Imap.WebServices.BusSvc.GetBusStopDetails(document.getElementById("hidLogId").value,BusStopName,$find('AutoCompleteEx')._contextKey, SucceededBusStopDetailsResults, handleFailedBusStopDetails);
	
}

// This is the callback function invoked if the Web service
// succeeded.
// It accepts the result object as a parameter.

function SucceededBusStopDetailsResults(result, eventArgs)
{
   	enableSearch();
   	 //unloadProgressBox();
	DisplaySucceededBusStopDetailsResults(result);

}

// This is the callback function invoked if the Web service
// failed.
// It accepts the error object as a parameter.

function handleFailedBusStopDetails(error)
{
	// Display the error.    
    //unloadProgressBox();
    alert("Stop/Stn.Detail Service Connection Error: " + error.get_message() + '. Please submit your query again.');
	enableSearch();
}

function DisplaySucceededBusStopDetailsResults(BusStopDetails)
{
  enableSearch();
	var resHtml = "";
	var latitude;
	var longitude;
    var latlonString;
	var title;
	var title2;	
	var desc ="";
    var firsttime = true;
    var mcounter = -1;  /** marker is placed from index 0*/
    var numberImage;
    var ImageUrl;
  
	/**  if there are no results, display the error message and return */
	if(BusStopDetails == null)
	{
		alert("There were no results for the specified Bus Stop/Stn., please check your query.");
		return;
	}
     var  BusesDetails =BusStopDetails.BusesDetails;
	if(BusesDetails == null)
	{
		alert("There were no results for the specified Bus Stop/Stn., please check your query.");
		return;
	}
	if(BusesDetails.length == 0)
	{
		alert("There were no results for the specified Bus Stop/Stn., please check your query.");
		return;
	}	
	
	resHtml = resHtml + "<div class ='dlg' ><table>";
 
	/**  Create an entry for each VEPlace in the result set */
	for(var p = 0; p < BusesDetails.length; p++)
	{
               
		/**  Gather some info up front */
		var busdetails = BusesDetails[p];

		var BusNo = busdetails.BusNo;
		if (firsttime)
		{

		var currentStop = busdetails.CurrentStop.StopName;
		var currentStopLat = busdetails.CurrentStop.Latitude;
		var currentStopLon = busdetails.CurrentStop.Longitude;	
		title =currentStop;

		var ttext;


		   
	        numberImage ="";	
	        
	        
	        ttext = currentStop + " (" + (BusesDetails.length) + " Routes.)";


		
		
		resHtml = resHtml + "<tr class='dlg'><td class='dlg' width= 50px;>";
		resHtml = resHtml + numberImage + "</td>";
		resHtml = resHtml + "<td class='dlg' width= 150px;> ";
		resHtml = resHtml + "Search location";
		resHtml = resHtml + "</td>"
		resHtml = resHtml + "<td class='dlg' width= 150px;> ";
		resHtml = resHtml + ttext;
		resHtml = resHtml + "</td><td class='dlg' width= 150px;> </td>"
		resHtml = resHtml + "</tr>";
		resHtml = resHtml + "<tr class='dlg'>";
		resHtml = resHtml + "<th class='dlg' width= 40px;></th> <th class='dlg' width= 140px;> ";
		resHtml = resHtml + "No#";
		resHtml = resHtml + "</th>"
		resHtml = resHtml + "<th class='dlg' width= 150px;> ";
		resHtml = resHtml + "Start Stop/Stn.";
		resHtml = resHtml + "</th>"
		resHtml = resHtml + "<th class='dlg' width= 150px;> ";
		resHtml = resHtml + "Last Stop/Stn.";
		resHtml = resHtml + "</th>"		
		resHtml = resHtml + "</tr>";
		
		firsttime = false;	
		}
		
		var StartStop = busdetails.StartStop.StopName;
		var StartStopLat = busdetails.StartStop.Latitude;
		var StartStopLon = busdetails.StartStop.Longitude;	
		var LastStop = busdetails.LastStop.StopName;
		var LastStopLat = busdetails.LastStop.Latitude;
		var LastStopLon = busdetails.LastStop.Longitude;		
		title =StartStop;
		title2 =LastStop;	
		var ttext1 ="";
		
        	  var tem = StartStop.replace(/ /gi, "%20"); 
        	 ttext1 =   '<a href=javascript:GetBusStopDetails("' + tem + '");>'	 + StartStop + "</a>";

		        numberImage ="";

	    	 var temz = BusNo.replace(/ /gi, "%20"); 
		resHtml = resHtml + "<tr class='dlg'>";
		resHtml = resHtml + "<td class='dlg' width= 40px;> ";
		resHtml = resHtml + (p + 1) + ".</td><td class='dlg' width= 150px;> "+ "<a href=javascript:GetBusNoDetails('" + temz  + "');>";
		resHtml = resHtml + BusNo;
		resHtml = resHtml + "</a></td>";
		resHtml = resHtml + "<td class='dlg' width= 150px;> ";
		resHtml = resHtml + numberImage + ttext1;
		resHtml = resHtml + "</a></td>";		


        var ttext3 ="";
        
        	 numberImage ="";	
        	 tem = LastStop.replace(/ /gi, "%20"); 
        	 ttext3 =   '<a href=javascript:GetBusStopDetails("' + tem + '");>'	 + LastStop + "</a>";

			


       

		resHtml = resHtml + "<td class='dlg' width= 150px;> ";
		resHtml = resHtml + numberImage + ttext3;
		resHtml = resHtml + "</td>";	
		
/**		resHtml = resHtml + "<a href='javascript:GotoLocation(" + latitude + "," + longitude + ", 13" + ");'>";
		resHtml = resHtml + LastStop;
		resHtml = resHtml + "</a></td>";	
		if(trackLatitude)
		{
			resHtml = resHtml + "<td class='dlg'>Distance: " + place.Distance + "</td>";
		}*/	

		resHtml = resHtml + "</tr>";

		
	}

	resHtml = resHtml + "</table></div>";
	    	MapTitle = "Stn/Stop Details of " + currentStop +"";
	    			staticMapURLs.push("");
      displaySearchResultsGrid(resHtml,MapTitle,false,false,BUS_STOP,'');
      /**
        GDLG = GDLG + 1;
    	var  mapLink = ""  ;
    	var  mapImage ="";

    	var alink = '<img id =imgi' +GDLG +' src="images/expanded.png" border="0" />';
	
	    resHtml =  "<Div id ='h"+ GDLG + "'><table title ='Expand/Collapse' onclick='animatedcollapse.toggle("+GDLG+")'; cellspacing='0' cellpadding='0%' style='cursor:pointer; border:  #ff0000 thick groove ; background: rgb(255, 255, 255) none repeat scroll 0% 0%; border-collapse: collapse;'><tr><td class='dlg' width='800px' style='text-align :center;background-color: #d00600;color: #ffffff;' > " +MapTitle+ "</td><td class='dlgC'  style='text-align :right' width='100px'>"+ alink+"</td></tr></table><div id ='" + GDLG+"'> <table  cellspacing='0' cellpadding='0%' style=' border: 0px none ; background: rgb(255, 255, 255) none repeat scroll 0% 0%; border-collapse: collapse;' align = 'center'><tr  align='center'><td class='dlg' align='center' colspan ='2'   width ='900px' >"+mapLink + mapImage+"</td></tr><tr  align='center'><td class='dlg' align='center' width ='90%'>" +resHtml+"</td><td   width ='900px' id='tblmapdata"+ GDLG +"' class='dlg' align='center'> </td></tr></table></div></div>";

		var results = document.getElementById("results");
	    results.innerHTML = resHtml  + results.innerHTML;

	    animatedcollapse.uninit();
    	animatedcollapse.addDiv(GDLG, 'fade=0,speed=400,group=pets');
    	animatedcollapse.init();
    	animatedcollapse.show(GDLG)	*/


}




function GetBusRoute(from, to)
{
if ( from == "From [Origin]")
    from ="";
    
if ( to == "To (Destination)")
    to ="";

FROM_STOP = from;
TO_STOP = to ;
	if(from.length == 0)
	{
		alert("Please enter the from to find the directions");
		return;
	}
	if(to.length == 0)
	{
		alert("Please enter the to to find the directions");
		return;
	}	



		disableSearch();
	    //showProgressBox("Searching Bus routes for the destination");
		Imap.WebServices.BusSvc.GetRoute(document.getElementById("hidLogId").value,from, to,$find('AutoCompleteEx')._contextKey, SucceededRouteSearchResults, handleFailedRouteSearch);
	
}

// This is the callback function invoked if the Web service
// succeeded.
// It accepts the result object as a parameter.

function SucceededRouteSearchResults(result, eventArgs)
{
   // unloadProgressBox();
	enableSearch();
	DisplaySucceededRouteSearchResults(result);

}

// This is the callback function invoked if the Web service
// failed.
// It accepts the error object as a parameter.

function handleFailedRouteSearch(error)
{
	enableSearch();
	// unloadProgressBox();
	// Display the error.    
	alert("Route Search Service Connection Error: " + error.get_message() + '. Please submit your query again.');
}

function DisplaySucceededRouteSearchResults(busStopDetails)
{

	var resHtml = "";
	var latitude;
	var longitude;
    var latlonString;
	var title;
	var title2;	
	var desc ="";
    var firsttime = true;
    var mcounter = -1;  /** marker is placed from index 0*/
    var numberImage ="";
    var ImageUrl;
    var ChangeBusNo;
    var PChangeStop;
    var PChangeStopLat;
    var PChangeStopLon;
    var PChangeBusNo ="";
     var PBusNo ="";
     var BusNo;
     var mmCounter;
     var FirstStop ="";
     var TransitImg ="";
          var LastStop ="";
     	    enableSearch();
     	    var SearchGoogleMaps = true;
    var temp;
    BusStopDetails = busStopDetails;
	/**  if there are no results, display the error message and return */
	if(BusStopDetails == null)
	{
		alert("There were no results for the specified direction search, please check your query.");
		return;
	}

	if(BusStopDetails.BusesDetails == null)
	{
		alert("There were no results for the specified direction search, please check your query.");
		return;
	}

	if(BusStopDetails.TotalBusNoCount == 0)
	{
		alert("There were no results for the specified direction search, please check your query.");
		return;
	}
	resHtml = resHtml + "<div class ='dlg' >";

	/**  Create an entry for each VEPlace in the result set */
	for(var p = 0; p < BusStopDetails.BusesDetails.length; p++)
	{

               
		/**  Gather some info up front */
		var busdetails = BusStopDetails.BusesDetails[p];

		BusNo = busdetails.BusNo;
		if (firsttime)
		{
		    var FirstStop = busdetails.StartStop.StopName;
		    var FirstStopLat = busdetails.StartStop.Latitude;
		    var FirstStopLon = busdetails.StartStop.Longitude;	
		    LastStop = busdetails.LastStop.StopName;
		    LastStopLat = busdetails.LastStop.Latitude;
		    LastStopLon = busdetails.LastStop.Longitude;
		    if ((LastStopLat != "null") && (LastStopLat != "null") && (LastStopLat != "") && (LastStopLat != "") && (LastStopLon != "null") && (LastStopLon != "null") && (LastStopLon != "") && (LastStopLon != "") && (FirstStopLat != "null") && (FirstStopLat != "null") && (FirstStopLat != "") && (FirstStopLat != "") && (FirstStopLon != "null") && (FirstStopLon != "null") && (FirstStopLon != "") && (FirstStopLon != ""))
		    GetGoogleRouteByLatLon(FirstStopLat,FirstStopLon,LastStopLat,LastStopLon);
		    else
		    SearchGoogleMaps =false;
		    title =FirstStop;
        	  var tem = FirstStop.replace(/ /gi, "%20"); 
        	 var tttext =   '<a href=javascript:GetBusStopDetails("' + tem + '");>'	 + FirstStop + "</a>";


		       
		        numberImage = numberImage +   tttext;		

  		    //resHtml = resHtml + "<tr class='dlg'><td class='dlg' width= 50px;></td><td class='dlg' width= 50px;>";

            mcounter = mcounter + 1;

            
		    title =LastStop;
        	   tem = title.replace(/ /gi, "%20"); 
        	  tttext =   '<a href=javascript:GetBusStopDetails("' + tem + '");>'	 + title + "</a>";

		        numberImage = numberImage +  " to: " + tttext + " ";


            numberImage = numberImage + "We have " + BusStopDetails.TotalBusNoCount +  " Routes";
            if (SearchGoogleMaps)
	        resHtml = resHtml + numberImage + "<table>";
            else
            resHtml = resHtml + numberImage + "<table style='width=900px'>";
		    mcounter = mcounter + 1;	
            PChangeStop = busdetails.ChangeStop.StopName;
            
            var RouteType = busdetails.RouteType;
             if (RouteType == 'I')
             {
 		        resHtml = resHtml + "<tr class='dlg'>";
		        resHtml = resHtml + "<th class='dlg' width= 50px;> ";
		        resHtml = resHtml + "No.";
		        resHtml = resHtml + "</th>"
		        resHtml = resHtml + "<th class='dlg' width= 70px;> ";
		        resHtml = resHtml + "Stop/Stn. to Change";
		        resHtml = resHtml + "</th>"
		        resHtml = resHtml + "<th class='dlg' width= 400px; style='text-align:left;'> ";
		        resHtml = resHtml + "Change to";
		        resHtml = resHtml + "</th>"		
		        resHtml = resHtml + "</tr>";            
   
             
             }
             else
             {
             resHtml = resHtml + "<tr class='dlg'>";
		    resHtml = resHtml + "<th class='dlg' width= 300px;> ";
		    resHtml = resHtml + "No.";
		    resHtml = resHtml + "</th>"
		    resHtml = resHtml + "</tr>";    
                var latlonString =  FirstStopLat + "|" + FirstStopLon + ","	+  LastStopLat + "|" + LastStopLon  + "," ;
		        
             }
		    firsttime = false;	
		}
        var RouteType = busdetails.RouteType;
	    if (RouteType == 'I')
	    {
		    var ChangeStop = busdetails.ChangeStop.StopName;
		    ChangeStopLat = busdetails.ChangeStop.Latitude;
		    ChangeStopLon = busdetails.ChangeStop.Longitude;	
            ChangeBusNo = busdetails.ChangeBusNo;
	   	    BusNo = busdetails.BusNo;	    
    	   	
	        if ((ChangeStop != PChangeStop) || (BusStopDetails.BusesDetails.length -1 ==p))
	        {

        		
		        title =PChangeStop;
			    desc = "Catch No: " + PBusNo + " Change No:" + PChangeBusNo;

			        numberImage ="";
			    tem = title.replace(/ /gi, "%20"); 
        	    tttext =   '<a href=javascript:GetBusStopDetails("' + tem + '");>'	 + title + "</a>";
	
			        ttext = tttext;
    		    if (busdetails.TransitType == "Metro")
                {
                    TransitImg =TRANSITMETROIMAGE;
                }
                else if (busdetails.TransitType == "Train")
                {
                    TransitImg =TRANSITMETROIMAGE;
                }
                else
                {
                    TransitImg =TRANSITBUSIMAGE;
                }
                      if (ChangeStop == PChangeStop)
                         {
                     		if (busdetails.ChangeTransitType == "Metro")
                            {
                                TransitImg =TRANSITMETROIMAGE;
                            }
                            else if (busdetails.ChangeTransitType == "Train")
                            {
                                TransitImg =TRANSITMETROIMAGE;
                            }
                            else
                            {
                                TransitImg =TRANSITBUSIMAGE;
                            }

                 		    PChangeStop = 	ChangeStop;
	                        PChangeStopLat = ChangeStopLat;
	                        PChangeStopLon = ChangeStopLon;
	                        PBusNo = BusNo ;
	                          tem = ChangeBusNo.replace(/ /gi, "%20"); 
	                          var temz = PBusNo.replace(/ /gi, "%20"); 
	                      if ((busdetails.TransitType == "Metro") || (busdetails.ChangeTransitType == "Train"))
		                  temp =  TransitImg+"<a href=javascript:GetBusNoDetails('" + tem  + "');>";
		                  else
		                  temp =  "<a href=javascript:GetBusNoDetails('" + tem  + "');>";
	                        temp = temp + ChangeBusNo;
	                        var t1= '"' + FirstStop.replace(/ /gi, "%20")+ '","' + temz+ '","' + ChangeStop.replace(/ /gi, "%20")+ '","' + tem+ '","' + LastStop.replace(/ /gi, "%20")+ '"';
	                        var rtLink = "<a class='SearchToolImages' href=javascript:GetRouteFromPoints(" +t1+ ");>Route</a>";
	                        temp = temp + "</a>&nbsp; "+rtLink+"<img class='SearchToolImages' style='cursor:pointer' src='images/mapsicon.png' alt ='view map' onclick='GetRouteFromPoints("+t1+")'/>&nbsp;"   ;

		                     temp = temp + " ";
		                    PChangeBusNo = PChangeBusNo + ", " + temp;
                 }
	            
    	         var temz1 = PBusNo.replace(/ /gi, "%20"); 
	            resHtml = resHtml + "<tr class='dlg'>";
		        resHtml = resHtml + "<td class='dlg' width= 50px style='border-bottom: #cc0099 1px dotted;'> ";
		        if ((busdetails.TransitType == "Metro") || (busdetails.ChangeTransitType == "Train"))
		        resHtml = resHtml + TransitImg+"<a href=javascript:GetBusNoDetails('" + temz1  + "');>";
		        else
		        resHtml = resHtml + "<a href=javascript:GetBusNoDetails('" + temz1  + "');>";
		        resHtml = resHtml + PBusNo;
		        resHtml = resHtml + "</a></td>";
		        resHtml = resHtml + "<td class='dlg' width= 70px; style='border-left: #cc0099 1px dotted;border-bottom: #cc0099 1px dotted;'> ";
		        resHtml = resHtml + ttext;
		        resHtml = resHtml + "</td>";
		        resHtml = resHtml + "<td class='dlg' width= 400px; style='border-left: #cc0099 1px dotted;border-bottom: #cc0099 1px dotted;'> ";
		        resHtml = resHtml + PChangeBusNo;
		        resHtml = resHtml + "</td>";
		        mcounter = mcounter + 1;
		        PChangeBusNo ="";
		        var latlonString =  FirstStopLat + "|" + FirstStopLon + ","	+  PChangeStopLat + "|" + PChangeStopLon + "," +  LastStopLat + "|" + LastStopLon  + "," ;
		        resHtml = resHtml + "</tr>";
            }	
    		
    		if (busdetails.ChangeTransitType == "Metro")
            {
                TransitImg =TRANSITMETROIMAGE;
            }
            else if (busdetails.ChangeTransitType == "Train")
            {
                TransitImg =TRANSITMETROIMAGE;
            }
            else
            {
                TransitImg =TRANSITBUSIMAGE;
            }

            
		    PChangeStop = 	ChangeStop;
	        PChangeStopLat = ChangeStopLat;
	        PChangeStopLon = ChangeStopLon;
	        PBusNo = BusNo ;
	          tem = ChangeBusNo.replace(/ /gi, "%20"); 
	          var temz = PBusNo.replace(/ /gi, "%20"); 
            if ((busdetails.TransitType == "Metro") || (busdetails.ChangeTransitType == "Train"))
		    temp =  TransitImg+"<a href=javascript:GetBusNoDetails('" + tem  + "');>";
		    else
		     temp =  "<a href=javascript:GetBusNoDetails('" + tem  + "');>";
	        temp = temp + ChangeBusNo;
	        var t1= '"' + FirstStop.replace(/ /gi, "%20")+ '","' + temz+ '","' + ChangeStop.replace(/ /gi, "%20")+ '","' + tem+ '","' + LastStop.replace(/ /gi, "%20")+ '"';
	        var rtLink = "<a class='SearchToolImages' href=javascript:GetRouteFromPoints(" +t1+ ");>Route</a>";
	        temp = temp + "</a>&nbsp; "+rtLink+"<img class='SearchToolImages' style='cursor:pointer' src='images/mapsicon.png' alt ='view map' onclick='GetRouteFromPoints("+t1+")'/>&nbsp;"   ;

		     temp = temp + " ";
		    PChangeBusNo = PChangeBusNo + ", " + temp;
		    
		    
		    
        }
        else
        {
    		if (busdetails.TransitType == "Metro")
            {
                TransitImg =TRANSITMETROIMAGE;
            }
    		else if (busdetails.TransitType == "Train")
            {
                TransitImg =TRANSITMETROIMAGE;
            }
            else
            {
                TransitImg =TRANSITBUSIMAGE;
            }
        var temz = busdetails.BusNo.replace(/ /gi, "%20"); 
          if ((busdetails.TransitType == "Metro") || (busdetails.ChangeTransitType == "Train"))
              temp = TransitImg + "<a href=javascript:GetBusNoDetails('" +temz  + "');>";
              else
               temp =  "<a href=javascript:GetBusNoDetails('" +temz  + "');>";
	        temp = temp +  busdetails.BusNo;
	        temp = temp + "</a>";
		     temp = temp + " ";
		     if (PBusNo =="")
		      PBusNo =  temp;   
		     else
		        PBusNo = PBusNo + ", " + temp;   
        }

	
	}
     if (RouteType != 'I')
     {
        resHtml = resHtml + "<tr class='dlg'>";
        resHtml = resHtml + "<td class='dlg' width= 300px;> ";
        resHtml = resHtml + PBusNo + "</td></tr>";
     
     }

	resHtml = resHtml + "</table></div>";
        staticMapURLs.push("");
         staticMapURLs2[GDLG] = staticMapURL;
        MapTitle = "Route Details from " + FirstStop + " to " + LastStop  +"";
          displaySearchResultsGrid(resHtml,MapTitle,false,true, FirstStop, LastStop);
          /**
        GDLG = GDLG + 1;
    	var  mapLink = ""  ;
    	var  mapImage ="";
    	var alink = '<img id =imgi' +GDLG +' src="images/expanded.png" border="0" />';
	    
	    resHtml =  "<Div id ='h"+ GDLG + "'><table  title ='Expand/Collapse' onclick='animatedcollapse.toggle("+GDLG+")'; cellspacing='0' cellpadding='0%' style='cursor:pointer; border:  #ff0000 thick groove ; background: rgb(255, 255, 255) none repeat scroll 0% 0%; border-collapse: collapse;'><tr><td class='dlg' width='800px' style='text-align :center;background-color: #d00600;color: #ffffff;' > " +MapTitle+ "</td><td class='dlgC'  style='text-align :right' width='100px'>"+ alink+"</td></tr></table><div id ='" + GDLG+"'><table cellspacing='0' cellpadding='0%' style=' border: 0px none ; background: rgb(255, 255, 255) none repeat scroll 0% 0%; border-collapse: collapse;'><tr><td class='dlg' width='450px' id = 'rtResults' style=' border-right: #cc0099 1px solid;border-bottom: #cc0099 1px solid;' >  <table  cellspacing='0' cellpadding='0%' style=' border: 0px none ; background: rgb(255, 255, 255) none repeat scroll 0% 0%; border-collapse: collapse;' align = 'center'><tr  align='center'><td class='dlg' align='center' colspan ='2'   width ='900px'>"+mapLink + mapImage+"</td></tr><tr  align='center'><td  class='dlg' align='center' >" +resHtml+"</td><td    id='tblmapdata"+ GDLG +"' class='dlg' style='align='center'> </td></tr></table></td><td class='dlg' style='border-bottom: #cc0099 1px solid;'  id = 'rtResults2' valign='top'> </tr></table></div></div>";
		var results = document.getElementById("results");
	     results.innerHTML = resHtml  + results.innerHTML;

	    animatedcollapse.uninit();
    	animatedcollapse.addDiv(GDLG, 'fade=0,speed=400,group=pets');
    	animatedcollapse.init();
    	animatedcollapse.show(GDLG)	*/

}


function GetRouteFromPoints(FirstStop,FBusNo,CStop, CBusNo,LStop)
{
	Imap.WebServices.BusSvc.GetRouteFromPoints(document.getElementById("hidLogId").value,FirstStop,FBusNo,CStop, CBusNo,LStop,$find('AutoCompleteEx')._contextKey, SucceededRouteFromPoints, handleFailedGetRouteFromPoints);

}
function SucceededRouteFromPoints(result)
{
    //unloadProgressBox();
    	    enableSearch();
       var resHtml = "";
	    resHtml = DisplaySucceededBusDetailsResults("Journey with BusNo: " + BUS_NO, result);
	     displaySearchResultsGrid(resHtml,MapTitle,true,false,'','');
	    /**
		if (resHtml == 1)
    	return;
    	    
        GDLG = GDLG + 1;
    	var  mapLink = "<a id ='aid"+ GDLG + "' href='javascript:onclick=ShowStaticMap(tblmapdata"+ GDLG +");'> View Route Map Journey</a>"  ;
    	var  mapImage ="<img id ='iid"+ GDLG + "' style='cursor:pointer' src='images/view-map2.png' alt ='view map' onclick='ShowStaticMap(tblmapdata"+ GDLG +")'/>";
    	var alink = '<img id =imgi' +GDLG +' src="images/expanded.png" border="0" />';
	
	    resHtml =  "<Div id ='h"+ GDLG + "'><table  title ='Expand/Collapse' onclick='animatedcollapse.toggle("+GDLG+")'; cellspacing='0' cellpadding='0%' style='cursor:pointer; border: #ff0000 thick groove ; background: rgb(255, 255, 255) none repeat scroll 0% 0%; border-collapse: collapse;'><tr><td class='dlg' style='text-align :center;background-color: #d00600;color: #ffffff;'' width='800px' > " +MapTitle+ "</td><td class='dlgC'  style='text-align :right' width='100px'>"+ alink+"</td></tr></table><div id ='" + GDLG+"'> <table  cellspacing='0' cellpadding='0%' style=' border: 0px none ; background: rgb(255, 255, 255) none repeat scroll 0% 0%; border-collapse: collapse;' align = 'center'><tr  align='center'><td class='dlg' align='center' colspan ='2' style='text-align :center;text-align:center;' width ='900px' >"+mapLink + mapImage+"</td></tr><tr  align='center'><td class='dlg'  align='center'  width ='900px'>" +resHtml+"</td><td id='tblmapdata"+ GDLG +"' class='dlg' align='center'   width ='900px'> </td></tr></table></div></div>";
		var results = document.getElementById("results");
	     results.innerHTML = resHtml  + results.innerHTML;

	    animatedcollapse.uninit();
    	animatedcollapse.addDiv(GDLG, 'fade=0,speed=400,group=pets');
    	animatedcollapse.init();
    	animatedcollapse.show(GDLG)	*/
	

}

function handleFailedGetRouteFromPoints(resp)
{
	// Display the error.    
	//unloadProgressBox();
	enableSearch();
	alert("GetRouteFromPoints Service Connection Error: " + error.get_message() + '. Please submit your query again.');
}

function button_click()
{
    if(window.event.keyCode==13)
    {
        var Button1=document.getElementById("Button1");
        Button1.click();
        window.event.cancel=true;
    }
}

function showHelp()
{
    var popupboxid1 = "helpbx1" + (GetResultboxCount() + 1);
  //  new popUp(50, 145, 300, 175, popupboxid1,"maphelp.htm", "white", "lightgrey", "9pt sans-serif", "Bangalore Journey Planner Help", "#0084d8", "lightgrey", "gray", "#00468c", "black", true, true, true, true, false, false,'images/min.png','images/max.png','images/close.png','images/resize.jpg', true,'images/copy.png','images/print.png' );
  new popUp(50, 145, 500, 300, popupboxid1, "maphelp.htm", "white", "#00385c", "16pt serif", "Bangalore Journey Planner Help", "#00385c", "white", "lightgrey", "#00568c", "black", true, true, true, true, true, false,'images/min.png','images/max.png','images/close.png','images/resize.jpg');

    hidebox(popupboxid1);
    fadeboxin(popupboxid1);


}
							
function initMenu()
{
}

//onclick call this function to show the secondSection information and hide the others 
function showRouteSearch()
{
trackLatitude =false;
var first = document.getElementById("SearchBusStop").style;
var second = document.getElementById("SrchRouteHd").style;
var third = document.getElementById("SrchBusNo").style;
var fourth = document.getElementById("BusStopLookup").style;


    if (first.display == "block")
    {
        CollapseMenu('SrchBusStopTxt','collapseSearchBusStop');
     }
    if (third.display == "block")
    {
        CollapseMenu('SrchBusNotxt','collapseBusNo');
     }
    if (fourth.display == "block")
    {
        CollapseMenu('BusStopLookuptxt','collapseBusStopLookuptxt');
     }
        second.display = "block";
        ExpandMenu('srchRouteText','collapseBusRoute');
        reArrangeWindows('SrchRouteHd');
}

//onclick call this function to show the secondSection information and hide the others 
function showBusStopSearch()
{
trackLatitude =false;
var first = document.getElementById("SearchBusStop").style;
var second = document.getElementById("SrchRouteHd").style;
var third = document.getElementById("SrchBusNo").style;
var fourth = document.getElementById("BusStopLookup").style;


    if (second.display == "block")
    {
        CollapseMenu('srchRouteText','collapseBusRoute');
     }

    if (third.display == "block")
    {
        CollapseMenu('SrchBusNotxt','collapseBusNo');
     }
    if (fourth.display == "block")
    {
        CollapseMenu('BusStopLookuptxt','collapseBusStopLookuptxt');
     }
   first.display = "block";
   ExpandMenu('SrchBusStopTxt','collapseSearchBusStop');
   reArrangeWindows('SearchBusStop');
}

function showBusNoSearch()
{
trackLatitude =false;
var first = document.getElementById("SearchBusStop").style;
var second = document.getElementById("SrchRouteHd").style;
var third = document.getElementById("SrchBusNo").style;
var fourth = document.getElementById("BusStopLookup").style;


    
    if (second.display == "block")
    {
        CollapseMenu('srchRouteText','collapseBusRoute');
     }

    if (first.display == "block")
    {
        CollapseMenu('SrchBusStopTxt','collapseSearchBusStop');
     }
    if (fourth.display == "block")
    {
        CollapseMenu('BusStopLookuptxt','collapseBusStopLookuptxt');
     }
    third.display = "block";
    ExpandMenu('SrchBusNotxt','collapseBusNo');
    reArrangeWindows('SrchBusNo');
}

function showBusStopLookup()
{
trackLatitude =true;
var first = document.getElementById("SearchBusStop").style;
var second = document.getElementById("SrchRouteHd").style;
var third = document.getElementById("SrchBusNo").style;
var fourth = document.getElementById("BusStopLookup").style;

    
    if (second.display == "block")
    {
        CollapseMenu('srchRouteText','collapseBusRoute');
     }

    if (first.display == "block")
    {
        CollapseMenu('SrchBusStopTxt','collapseSearchBusStop');
     }
    if (third.display == "block")
    {
        CollapseMenu('SrchBusNotxt','collapseBusNo');
     }
    fourth.display = "block";
    ExpandMenu('BusStopLookuptxt','collapseBusStopLookuptxt');
    reArrangeWindows('BusStopLookup');
}

function reArrangeWindows(div)
{
var first = document.getElementById("SearchBusStop");
var second = document.getElementById("SrchRouteHd");
var third = document.getElementById("SrchBusNo");
var fourth = document.getElementById("BusStopLookup");
var divmenuOne = document.getElementById('SrchBusStopTxt');
var divmenuTwo = document.getElementById('srchRouteText');
var divmenuthird = document.getElementById('SrchBusNotxt');
var divmenuFourth = document.getElementById('BusStopLookuptxt');

var prev;
 prev = 340;
    switch(div) 
   {  
    case 'SearchBusStop':   
            if (second.style.display == "block")
                {
                    second.style.top = prev + "px";
                    prev = prev + 30;
                }
            if (first.style.display == "block")
                {
                 first.style.top = prev + "px";
                if ((divmenuOne.style.visibility == "visible") || (divmenuOne.style.visibility == ""))
                    prev = prev + 120;
                else
                    prev = prev + 30;
                }
            if (third.style.display == "block")
                {
                third.style.top = prev + "px";
                 prev = prev + 30;
                }
            if (fourth.style.display == "block")
                {
                fourth.style.top = prev
                }
        break;

    case 'SrchRouteHd':
             if (second.style.display == "block")
                {
                    second.style.top = prev + "px";
                if ((divmenuTwo.style.visibility == "visible") || (divmenuTwo.style.visibility == ""))
                    prev = prev + 140;
                else
                    prev = prev + 40;
                }
            if (first.style.display == "block")
                {
                 first.style.top = prev + "px";
                prev = prev + 30;
                }
            if (third.style.display == "block")
                {
                third.style.top = prev + "px";
                 prev = prev + 30;
                }
            if (fourth.style.display == "block")
                {
                fourth.style.top = prev
                }   
            break; 
     case 'SrchBusNo':  
                if (second.style.display == "block")
                {
                    second.style.top = prev + "px";
                    prev = prev + 30;
                }
            if (first.style.display == "block")
                {
                 first.style.top = prev + "px";
                prev = prev + 30;
                }
            if (third.style.display == "block")
                {
                third.style.top = prev + "px";
                if ((divmenuthird.style.visibility == "visible") || (divmenuthird.style.visibility == ""))
                    prev = prev + 110;
                else
                    prev = prev + 30;
                }
            if (fourth.style.display == "block")
                {
                fourth.style.top = prev
                }  
         break;
     case 'BusStopLookup':   
            if (second.style.display == "block")
                {
                    second.style.top = prev + "px";
                    prev = prev + 30;
                }
            if (first.style.display == "block")
                {
                 first.style.top = prev + "px";
                prev = prev + 30;
                }
            if (third.style.display == "block")
                {
                third.style.top = prev + "px";
                 prev = prev + 30;
                }
            if (fourth.style.display == "block")
                {
                fourth.style.top = prev
                }  
     break;
    default:   
     break;
    }
}

function CollapseMenu(div,image)
{
var divmenu = document.getElementById(div);

    if (divmenu.style.visibility == "hidden")
        return;
    var imageEle = document.getElementById(image);
    divmenu.style.visibility = "hidden";
    imageEle.innerHTML = '<img  src="images/expand2.png" alt="expand Search" />';
    document.getElementById(div).style.display = "none"
    switch(div) 
   {  
    case 'srchRouteText':   
        reArrangeWindows('SrchRouteHd');
        break;
    case 'SrchBusStopTxt':   
         reArrangeWindows('SearchBusStop');
            break; 
     case 'SrchBusNotxt':   
         reArrangeWindows('SrchBusNo');
         break;
     case 'BusStopLookuptxt':   
        reArrangeWindows('BusStopLookup');   
     break;
    default:   
     break;
    }

}
function ExpandMenu(div,image)
{
var divmenu = document.getElementById(div);
var imageEle = document.getElementById(image);
if ((divmenu.style.visibility == "visible") || (divmenu.style.visibility == ""))
        return;
    divmenu.style.visibility = "visible";
    document.getElementById(div).style.display = "block"
    imageEle.innerHTML = '<img  src="images/collapse2.png" alt="Collapse Search" />';

    switch(div) 
   {  
    case 'srchRouteText':   
        CollapseMenu('SrchBusStopTxt','collapseSearchBusStop');
        CollapseMenu('SrchBusNotxt','collapseBusNo');
        CollapseMenu('BusStopLookuptxt','collapseBusStopLookuptxt');
        reArrangeWindows('SrchRouteHd');
        break;

    case 'SrchBusStopTxt':   
        CollapseMenu('SrchBusNotxt','collapseBusNo');
        CollapseMenu('BusStopLookuptxt','collapseBusStopLookuptxt');
        CollapseMenu('srchRouteText','collapseBusRoute');
         reArrangeWindows('SearchBusStop');
            break; 
     case 'SrchBusNotxt':   
        CollapseMenu('BusStopLookuptxt','collapseBusStopLookuptxt');
        CollapseMenu('srchRouteText','collapseBusRoute');
        CollapseMenu('SrchBusStopTxt','collapseSearchBusStop');
         reArrangeWindows('SrchBusNo');
         break;
     case 'BusStopLookuptxt':   
        CollapseMenu('srchRouteText','collapseBusRoute');
        CollapseMenu('SrchBusStopTxt','collapseSearchBusStop');
        CollapseMenu('SrchBusNotxt','collapseBusNo');   
        reArrangeWindows('BusStopLookup');   
     break;
    default:   
     break;
    }
    
    
}
function toggleMenu(div,image)
{

var divmenu = document.getElementById(div);
  if ((divmenu.style.visibility == "visible") || (divmenu.style.visibility == ""))
    CollapseMenu(div,image);
  else
    ExpandMenu(div,image);
    

}
function closeMenu(div)
{
document.getElementById(div).style.display = "none";
reArrangeWindows(div);
}
function closead()
{
document.getElementById("m0").style.display = "none";
}
function showProgressBox(progressText)
{
var popupboxid ="prog1";
  var Image ='<img id="imgprogId" height="25" alt="Please Wait..." src="Images/engine.gif" width="25"/>';
  
  
  	var resHtml = "<div class ='pdlg' ><table>";
		resHtml = resHtml +  "<tr class='pdlg'><td class='pdlg' width= 50px;>";
		resHtml = resHtml + Image + "</td></tr><tr class='pdlg'>";
		resHtml = resHtml +  "<td class='pdlg' width= 50px;>";
	    resHtml = resHtml + progressText + "</td>";
	    		resHtml = resHtml + "</tr></table></div>";
//progressText + '<img id="imgPostCodeSearch" style="VISIBILITY: hidden" height="25" alt="Please Wait..." src="Images/engine.gif" width="25"/>';
new popUp(750, 50, 250, 100, popupboxid,resHtml, "white", "#00385c", "9pt serif", null, "#00385c", "white", "lightgrey", "#00568c", "black", true, false, false, false, false, false,'','','','');
//new popUp(left_position, top_position, width, height, id_of_box, content_text, content_bgcolor, content_text_color, content_font_stylestring, title_text, title_bgcolor, title_text_color, border_color,  scrollbar_color, shadow_color, is_hidden_on_start, is_draggable, is_resizeable, show_old, is_external, disable_on_return , min_image, max_image, close_image, resize_image);


}

function unloadProgressBox()
{
	        try
	        {
            unloadbox("prog1");
	         }
	            catch(err){}

}

function GetVERouteByLatLon( flat, flon, tlat, tlon){ 

try{

 if (ve_map == undefined)
	        {
	            drawVE(CURRENT_LAT_POSITION, CURRENT_LON_POSITION, CURRENT_ZOOM_LEVEL, CURRENT_MAP_TYPE);
	            document.getElementById('VeMap').style.display = "none";
			    document.getElementById('ve').style.visibility = "hidden";
	        }		
	     }
	     catch(err)
	     {}
	     MakeVisibleGGMap()

	try
	{
		var x;
            locations = new Array();
			var x = new VELatLong(flat, flon);
			locations.push(x);
			x = new VELatLong(tlat, tlon);
			locations.push(x);


		var unit;
		unit = VERouteDistanceUnit.Kilometer;
		var options = new VERouteOptions;
		options.DrawRoute = true;
		options.SetBestMapView = true;
		options.RouteCallback = onGotRoute;
		options.DistanceUnit = unit;
		options.ShowDisambiguation = false;
		ve_map.DeleteRoute();
		ve_map.GetDirections(locations, options);
	}

	catch(err)
	{

		/**alert("Error!directions",err.message); */
	}

}
function GetGoogleRouteByLatLon( flat, flon, tlat, tlon){ 


                gdir = new GDirections(); 
                
            GEvent.addListener(gdir, "load", onGDirectionsLoad2);
			GEvent.addListener(gdir, "error", handleErrors);


var p = new GLatLng(flat.trim().substring(0,5), flon.trim().substring(0,5));
var q = new GLatLng(tlat.trim().substring(0,5), tlon.trim().substring(0,5));
                var pointsArray = [p,q]; 
               gdir.loadFromWaypoints(pointsArray,{getSteps: true,getPolyline:true}); 
               var  numRoutes = gdir.getNumRoutes(); 

                //gdir.load('from: Waypoint1@'+flat+','+flon+' to: Waypoint2@'+tlat+','+tlon);
             // directions.load('from: Waypoint1@21.742149,100.337218 to: Waypoint2@15.740815,100.3267');
        } 

//  3. Using Route, Steps, get the last step
function onGDirectionsLoad2(){

var latlonString ="";
var MarketString ="";
  var nrroutes = gdir.getNumRoutes();
 		for(var j = 0; j < nrroutes; j++)
		{   
            var route = gdir.getRoute(0);
            var nrsteps = route.getNumSteps();

            var steps = "<table class= 'dlg' width ='400px'><tr><th class = 'dlg'>No</td><th class = 'dlg'>Description</td><th class = 'dlg'>Distance</td><th class = 'dlg'>Time</td></th>";
                          
            var turns = "";
            var routeinfo = "";
            
            routeinfo += turns + "Total distance:";
            routeinfo += route.getSummaryHtml() + " ";

 		    for(var i = 0; i < nrsteps; i++)
		    {   
        
                var step = route.getStep(i);
                legDistance = step.getDistance();
                turns +=legDistance;
                var  numberImage ="";	
                steps += "<tr><td class= 'dlg'>"+ (i+1) + ". </td><td class= 'dlg'>" + step.getDescriptionHtml() + "</td><td class= 'dlg'>" + step.getDistance().html + "</td><td class= 'dlg'>" + step.getDuration().html  + "</td></tr>";
                var	latitude = step.getLatLng().lat();
		        var longitude = step.getLatLng().lng();
                latlonString = latlonString + latitude + "," + longitude + "|";

        if (i ==0)
        MarketString= MarketString + latitude + "," + longitude + ",midgreens|";
        else if (i == nrsteps -1)
        MarketString= MarketString + latitude + "," + longitude + ",midredd|";
        else
        MarketString= MarketString + latitude + "," + longitude + ",tinyblue|";
         
            }
    
        }
        steps +=  "</table>";
        routeinfo += "<Div align ='left'><b>Steps:</b>" + steps+ "</div>";
        if("" != "")
        routeinfo += "<br/><b>Note:</b><br/>" + "";
        //routeinfo = "<div class ='dlg' >" + routeinfo  + "</div>";
        var resHtml = routeinfo;
        staticMapURL = STATICMAP_GLOBAL_PATH + "&path=rgb:0x000f0f,weight:3|"+latlonString+"&markers="+MarketString+"&size=450x400";
        staticMapURLs2[GDLG] = staticMapURL;
        staticMapURLs.push(staticMapURL);
        
                MapTitle = "<b>Google Maps: By Drive  from " + FROM_STOP + " to " + TO_STOP + "</b>";

       // GDLG = GDLG + 1;
    	var  mapLink = "<a class='SearchToolImages'id ='aid"+ GDLG + "' href='javascript:onclick=ShowStaticMap(tblmapdata"+ GDLG +");'> View Route Map Journey</a>"  ;
    	var  mapImage ="<img class='SearchToolImages' id ='iid"+ GDLG + "' style='cursor:pointer' src='images/view-map2.png' alt ='view map' onclick='ShowStaticMap(tblmapdata"+ GDLG +")'/>";
    	var alink = '<img class="SearchToolImages" id =imgi' +GDLG +' src="images/expanded.png" border="0" />';
	
        resHtml =  "<Div id ='hg"+ GDLG + "'><table  cellspacing='0' cellpadding='0%' class='SearchResultsTabledata2'><tr><td class='dlg' width='800px' style='text-align :center;' > " +MapTitle+ "</td><td class='dlg' width='100px'></td></tr></table><div id ='" + GDLG+"'> <table  cellspacing='0' cellpadding='0%' style='SearchResultsTabledata2'><tr  align='center'><td class='dlg'    width ='900px' align='center' colspan ='2' >"+mapLink + mapImage+"</td></tr><tr  align='center'><td class='dlg'    width ='90%' align='center' >" +resHtml+"</td></tr></table></div></div>";
		
		var results = document.getElementById("rtResultsGSec"+ GDLG);
	     results.innerHTML = resHtml  ;
	    enableSearch();


}
// This is the callback function invoked if the Web service
// failed.
// It accepts the error object as a parameter.

function handleFailedBusNoDetailsTest(error)
{
	// Display the error.    
	alert("Route No Detail Service Connection Error: " + error.get_message() + '. Please submit your query again.');
}

// handle GDirection errors
function handleErrors()
{
if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

//  else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//    alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

}
   function setContext(ctx)
   {
   CURCTX =ctx;
        $find('AutoCompleteEx').set_contextKey(ctx);
        if ($find('AutoCompleteEx2') != null)
            $find('AutoCompleteEx2').set_contextKey(ctx);
       // document.location.hash = "#City="+document.activeElement.defaultValue.replace(new RegExp('rdSrch',"g"), ''); ;


   }

       function doClick(buttonName,e)
    {
    

        var key;

         if(window.event)
              key = window.event.keyCode;     /**IE*/

         else
              key = e.which;     /**firefox */

    
        if (key == 13)
        {

            var btn = document.getElementById(buttonName);
            if (btn != null)
            { 

                btn.click();
                event.keyCode = 0
            }
        }
        
         }
   
          function doChange(e)
    {
    
           // document.getElementById("AdText").innerHTML ="Local listings for " + e.srcElement.value;    
           
   }
   
function closeSrcRsltpane(div)
{
//div="";
SEARCHGRIDS =SEARCHGRIDS-1;
try
{  var did = div.id;  
var dd = document.getElementById(did); 
 var p = div.parentNode ? div.parentNode : div.parentElement;
        p.removeChild(div);


  var adid = 'ad' + div.id.substring(1,div.id.length);   
     var ad = document.getElementById(adid);
        var s = ad.parentNode ? ad.parentNode : ad.parentElement;
        s.removeChild(ad);

}
catch(ex){}
    if(SEARCHGRIDS ==0)
{

    document.getElementById("results").innerHTML="";
     document.getElementById("table5").style.display = "none";
          document.getElementById("table5").style.visibility = "hidden";
     document.getElementById("space4").style.display = "block";
     document.getElementById("infodlg").style.display = "block";
    document.getElementById("TdAdbig").style.display = "block";
         document.getElementById("space4").style.visibility = "visible";
     document.getElementById("infodlg").style.visibility = "visible";
    document.getElementById("TdAdbig").style.visibility = "visible";
    


}  
     /**   var p = div.parentNode ? div.parentNode : div.parentElement;
        p.removeChild(div);
   
        var s = ad.parentNode ? ad.parentNode : ad.parentElement;
        s.removeChild(ad);*/

//        var divs = document.getElementsByClassName('SearchTitleTable') ;

//        if (divs.length ==0)
//        {
//        document.getElementById("table5").style.display = "none";
//        }

}

function printSrcRsltpane(div)
{
	var a = window.open('', '', 'menubar=1,scrollbars=1,width=500,height=400');
	a.document.open("text/html");
	a.document.write('<html><head><link id="modid" href="css/LmodulePrint.css" type="text/css" rel="stylesheet"/><style type="text/css">body{font:normal 10px verdana,arial;} #frame{background-image:none;background-color:#FFFFFF;}</style></head><body style="padding-left:20px;background-image:none;background-color:#FFFFFF;">');
	a.document.write(customizeHTMLForMail(div.innerHTML));
	a.document.write('<img src = "</body></html>');
	a.document.close();
	a.print();
}

function copySrcRsltpane(Div)
{
	window.clipboardData.setData("Text", Div.innerText);
}
function MailSrcRsltpane (txtSenderName,txtSenderEmail,txtRecieverName,txtRecieverEmail,txtEmailMessage, chkupdateme,div)
{
 if(! jscaptchaSubmit2(document.forms[1]))
 return;

//deactivate();
	   var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm._doPostBack('UpdatePanel1',  'SendRouteMail'  + "$" + txtSenderName.value + "$" + txtSenderEmail.value + "$" + txtRecieverName.value + "$" + txtRecieverEmail.value + "$" + txtEmailMessage.value + "$" + chkupdateme.checked + "$" + getEMail(document.getElementById(SEARCHRESULTDIVTOMAIL).innerHTML)+ "$" + getEMailforLog(document.getElementById(SEARCHRESULTDIVTOMAIL).innerHTML) );
}
function dummy(a,b,c,d)
{

}

function getEMail(htmltodisplay)
{
return  getcss() + customizeHTMLForMail(htmltodisplay) +"<br/>Route Search by<br/><a href ='http://tellmyroute.com'><img src ='http://tellmyroute.com/images/tellmyroute.png'></img></a><br /><br />Disclaimer:<br />You have recieved this mail as you were refered at <a href ='http://tellmyroute.com'>www.tellmyroute.com </a>. If you have got this mail by error or you are a victim of spam please mail to admin at tellmyroute dot com.<br />We have made the search as accurate as possible, however due to the nature of commuting business discrepancies can happen. Please check with your local transport center for more accurate data.";

}
function getEMailforLog(htmltodisplay)
{
return  htmltodisplay;

}
function customizeHTMLForMail(htmltodisplay)
{
	 	    htmltodisplay = htmltodisplay.replace(new RegExp('SearchTitleTabledataTools',"g"), 'SearchTTabledataToolsDIS'); 
	 	 	htmltodisplay =htmltodisplay.replace(new RegExp('SearchTitleTableData',"g"), 'SearchTTableData2'); 
	 	 	htmltodisplay =htmltodisplay.replace(new RegExp('SearchToolImages',"g"), 'SearchToolImagesDIS'); 
	 	 	htmltodisplay =htmltodisplay.replace(new RegExp('animatedcollapse.toggle',"g"), 'dummy'); 
	 	 	htmltodisplay =htmltodisplay.replace(new RegExp('GetBusStopDetails',"g"), 'dummy'); 
	 	 	htmltodisplay =htmltodisplay.replace(new RegExp('GetBusNoDetails',"g"), 'dummy'); 
	 	 	htmltodisplay =htmltodisplay.replace(new RegExp('MarkerClick',"g"), 'dummy'); 
	        htmltodisplay =htmltodisplay.replace(new RegExp('ShowStaticMap',"g"), 'dummy');
	 	    htmltodisplay =htmltodisplay.replace(new RegExp('GetRouteFromPoints',"g"), 'dummy');
	 	    htmltodisplay =htmltodisplay.replace(new RegExp('SearchTitleTable',"g"), 'SearchTTitleTable');
	 	    htmltodisplay =htmltodisplay.replace(new RegExp('form.aspx',"g"), '');
	 	return htmltodisplay;
	 	}
	 	

////function __doPostBack(eventTarget, eventArgument) {
////if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
////theForm.__EVENTTARGET.value = eventTarget;
////theForm.__EVENTARGUMENT.value = eventArgument;
////theForm.submit();
//}
//}

