﻿/*

AUTHOR:     Shenouda Andrawis (SA)
CREATED: 

*/
var DEFAULT_ENTER_SUBURB= "Enter a Suburb";
var DEFAULT_ENTER_START_DESTINATION ="Please enter a Start and Destination address"
var POSTCODE_INVALID = "The Postcode that was entered is not valid. Please try again";
var MULTIPLE_RESULTS = "Multiple results were found. Please select the best match from the list";
var NO_LOCATION = "No match found. Please enter a suburb or postcode";
var NO_SERVICESTATIONS_FOUND = "We could not find any requested Service Stations along the route";
var markers = new Array();//array of markers used for user clicks on icon to show the popup
var CANPERFORMROUTE = false; //set to true when all the returned address are found (ie no multiple results or errors found in the address)

var AustraliaZoomLevel = 4; //Zoom level before it starts doing a map search
var ZoomToValue = 15; 
var routeList = [];

var map;
var isPopupVisible = false;

function OnLoad(){
       //Hide Multiple Results 
       document.getElementById("CmbMultipleAddress1").style.display="none";
       document.getElementById("CmbMultipleAddress2").style.display="none";
       document.getElementById("CmbMultipleAddress3").style.display="none";  
       init();
       document.getElementById("map").style.display="none"; 
}

function SetInit(){
    document.getElementById("mainMap").style.display='none';
    document.getElementById("map").style.display='block';
}
function init() {  
       document.getElementById("map").style.height="450px"
       document.getElementById("map").style.width="865px"
       document.getElementById("map").style.display="";
       document.getElementById("map").style.background="#f0f0f0 url('images/gridlines.gif') repeat";
       document.getElementById("map").style.border="solid 1px #42848e"; //Sets the border to load when div is loaded (anomaly at first load)
       map = new MapDS.Map( "map", { navigation: MapDS.MapOptions.Navigation.PanZoomBar } );  
       map.setCentre( new MapDS.LatLng( -28.5, 133.5 ), AustraliaZoomLevel);  
       ExecuteZoomListener();
}  


function ExecuteZoomListener(){
//Restrict min zoom level to go no further out than map on load. 
      map.addListener( MapDS.Events.OnEndZoom, function(e) {  
      
         if (map.getZoom() < AustraliaZoomLevel){
            map.setCentre( new MapDS.LatLng( -28.5, 133.5 ), AustraliaZoomLevel);  
         }  
      }        
     );
          
}


function SearchClick(){
    if (document.getElementById("map").style.display=='none'){
        document.getElementById("mainMap").style.display='none';
        document.getElementById("map").style.display='block';
    }
    detectMultipleResults();
    
}


//Detect if the user has done a previous search and detect if it has returned multiple results
//If a multiple results list does not exsist then perform Geocode of Addresses
function detectMultipleResults(){

var Suburb1 = document.getElementById("txtSuburb1").value;
var Suburb2 = document.getElementById("txtSuburb2").value;
document.getElementById("lblError").innerHTML =""
// Check to see if there is a Start and Destination otherwise throw an error
if ((Suburb1 != DEFAULT_ENTER_SUBURB) && (Suburb2 != DEFAULT_ENTER_SUBURB)) {

         var CmbMultipleAddress1=document.getElementById("CmbMultipleAddress1");
         var CmbMultipleAddress2=document.getElementById("CmbMultipleAddress2"); 
         var CmbMultipleAddress3=document.getElementById("CmbMultipleAddress3"); 
         
            //is there a multiple result for Start Address?
            if(CmbMultipleAddress1.style.display=='block') 
            {
                var text = CmbMultipleAddress1.options[CmbMultipleAddress1.selectedIndex].text;
                if(text.indexOf(", ") > 0){
                       var index=0;
                       var splitMessage = text.split(", ");                   
                      document.getElementById("txtSuburb1").value = splitMessage[0] + " "+ splitMessage[1];           
                      document.getElementById("ddState1").value = splitMessage[2];  
                      document.form1.SearchState1.value = splitMessage[2]; 
                      document.form1.SearchPostcode1.value = splitMessage[1];
                      document.form1.SearchSuburb1.value = splitMessage[0];                                      
                 }
                
                var stuffs=CmbMultipleAddress1.options[CmbMultipleAddress1.selectedIndex].value.split("***");
                routeList.push( {"Y":stuffs[1], "X": stuffs[0]} );
                CmbMultipleAddress1.style.display='none';     
            }
            
            //is there a multiple result for Via Address?
            if(CmbMultipleAddress3.style.display=='block')  
            {
            
                var text3 = CmbMultipleAddress3.options[CmbMultipleAddress3.selectedIndex].text;
                if(text3.indexOf(", ") > 0){
                       var index=0;
                       var splitMessage = text3.split(", ");                   
                       document.getElementById("txtSuburb3").value = splitMessage[0] + " "+ splitMessage[1];            
                       document.getElementById("ddState3").value = splitMessage[2]; 
                       document.form1.SearchState3.value = splitMessage[2]; 
                       document.form1.SearchPostcode3.value = splitMessage[1];
                        document.form1.SearchSuburb3.value = splitMessage[0];                                        
                 }
                
                 var stuffs=CmbMultipleAddress3.options[CmbMultipleAddress3.selectedIndex].value.split("***");
                 routeList.push( {"Y":stuffs[1], "X": stuffs[0]} );
                 CmbMultipleAddress3.style.display='none';
                 
             }
            
            
            
            //is there a multiple result for Destination Address?
            if(CmbMultipleAddress2.style.display=='block')  
            {
                var text2 = CmbMultipleAddress2.options[CmbMultipleAddress2.selectedIndex].text;
                if(text2.indexOf(", ") > 0){
                       var index=0;
                       var splitMessage = text2.split(", ");                   
                       document.getElementById("txtSuburb2").value = splitMessage[0] + " "+ splitMessage[1];            
                       document.getElementById("ddState2").value = splitMessage[2]; 
                       document.form1.SearchState2.value = splitMessage[2]; 
                       document.form1.SearchPostcode2.value = splitMessage[1];
                       document.form1.SearchSuburb2.value = splitMessage[0];                                        
                 }
                
                var stuffs=CmbMultipleAddress2.options[CmbMultipleAddress2.selectedIndex].value.split("***");
                routeList.push( {"Y":stuffs[1], "X": stuffs[0]} );
                CmbMultipleAddress2.style.display='none';
                
             }

            
    //if there are no multiple results do Geocode of addresses
    if((CmbMultipleAddress2.style.display=='none')|| (CmbMultipleAddress2.style.display=='none')|| (CmbMultipleAddress1.style.display=='none'))
    {
        routeList = [];
        FindAddress()
    }   
}else{
    //Else show an error message say Enter a start and enter address
    document.getElementById("lblError").innerHTML= DEFAULT_ENTER_START_DESTINATION;
}     

}



//Calls a QuickLocate(TM) Webservice Geocode
function FindAddress()
{
    // Make JSON object for all the controls initialise filter variables
    var AddressObj = {Suburb1: document.getElementById("txtSuburb1").value,   
                      State1: document.getElementById("ddState1").value, 
                      Suburb2: document.getElementById("txtSuburb2").value,   
                      State2: document.getElementById("ddState2").value, 
                      Suburb3: document.getElementById("txtSuburb3").value,   
                      State3: document.getElementById("ddState3").value
                      }  
                      
    //Clean up the fields from default values
    if (AddressObj.State1 == "State...") {AddressObj.State1="";}
    if (AddressObj.State2 == "State...") {AddressObj.State2="";}
    if (AddressObj.State3 == "State...") {AddressObj.State3="";}
    if (AddressObj.Suburb1 == DEFAULT_ENTER_SUBURB) {AddressObj.Suburb1="";}
    if (AddressObj.Suburb2 == DEFAULT_ENTER_SUBURB) {AddressObj.Suburb2="";}
    if (AddressObj.Suburb3 == DEFAULT_ENTER_SUBURB) {AddressObj.Suburb3="";}

    //console.log(RawStreet +","+ RawSuburb +","+ RawPostcode +","+ RawState)
    //Webservice Address
   CaltexService.FindRouteAddress(AddressObj, FindAddressResultsCallback, FindNoResultsCallback);
  
}


//Webservice returns 3 QickLocate Results objects one for each search address fields
function FindAddressResultsCallback(results){
        AddressResult(results.QLResult1, 1)
       // if (results.QLResult3 != null){
        AddressResult(results.QLResult3, 3)
       // }
        AddressResult(results.QLResult2, 2)
 }


//Index 1 - Start 
//Index 2 - Destination
//Index 3 - Via
// this function is run 3 times.
function AddressResult(results, index){
   
    if(index == 1){
    var CmbMultipleAddress=document.getElementById("CmbMultipleAddress1");
    var errorlbl = document.getElementById("addressError1");
    errorlbl.innerHTML =""
    }
    if(index == 2){
    var CmbMultipleAddress=document.getElementById("CmbMultipleAddress2");
    var errorlbl = document.getElementById("addressError2");
    errorlbl.innerHTML =""
    }
    if(index == 3){
    var CmbMultipleAddress=document.getElementById("CmbMultipleAddress3");
    var errorlbl = document.getElementById("addressError3");
    errorlbl.innerHTML =""
    
    }
    
   if (results == null){

   }
   else{
   
   

     
    //if isReadyForRoute is equal to at least 2 (ie 2 X,Y coords) then route
    switch(results.FullResult)
    {
    case 1://Found One Address
       
       //Save Address to hidden input state
       if(index == 1){
       CANPERFORMROUTE = true;
           document.form1.SearchSuburb1.value = results.Locations[0].Suburb;
           //alert( results.Locations[0].Suburb)
           document.form1.SearchState1.value =results.Locations[0].State;
           document.form1.SearchPostcode1.value =results.Locations[0].Postcode;
           routeList.push( {"Y":results.Locations[0].Position.Y, "X": results.Locations[0].Position.X} );
       }
       
       if(index == 2){
           document.form1.SearchSuburb3.value = results.Locations[0].Suburb;
           document.form1.SearchState3.value =results.Locations[0].State;
           document.form1.SearchPostcode3.value =results.Locations[0].Postcode;
           routeList.push( {"Y":results.Locations[0].Position.Y, "X": results.Locations[0].Position.X} );

       }
       
       if(index == 3){
      
   if(results !== null){
           document.form1.SearchSuburb2.value = results.Locations[0].Suburb;
           document.form1.SearchState2.value =results.Locations[0].State;
           document.form1.SearchPostcode2.value =results.Locations[0].Postcode;
           routeList.push( {"Y":results.Locations[0].Position.Y, "X": results.Locations[0].Position.X} );  
}

       }

    break;
    
    case 100://Found Multiple addresses
  
        CmbMultipleAddress.options.length=0;
        CmbMultipleAddress.options.length=results.length-1;
        
        for(var a=0; a<results.Locations.length; a++)//populate the combobox with locations
        {
            var obj;
            obj=new Option(results.Locations[a].Suburb + ", "+  results.Locations[a].Postcode + ", "+ results.Locations[a].State , results.Locations[a].Position.X + "***" + results.Locations[a].Position.Y);
            CmbMultipleAddress[a]=obj;
        }
        CmbMultipleAddress.style.display='block';
        document.getElementById("lblError").innerHTML = MULTIPLE_RESULTS;
        
        if (index == 3){          
                document.form1.SearchState2.value = ""; 
                document.form1.SearchPostcode2.value = "";
                document.form1.SearchSuburb2.value = "";
        
        }

        CANPERFORMROUTE = false;
      
     
    break;
    default://no address or invalid address  

            if (index == 3){          
                document.form1.SearchState2.value = ""; 
                document.form1.SearchPostcode2.value = "";
                document.form1.SearchSuburb2.value = "";
            }
            if((index == 3) && (document.getElementById("txtSuburb3").value== DEFAULT_ENTER_SUBURB)){
             }else{
                errorlbl.innerHTML= NO_LOCATION;     
            }   
    break;
    }  
    
    //after all the address have been geocoded and there are no multiple results ie/all FullResults are found
    //perform a route with 2 or more addresses
    
    if((index == 2) && (CANPERFORMROUTE == true)) {
      //check if anything exists in via

       PerformRoute()
    }
    
       }
}

function FindNoResultsCallback(results){
    //alert("Error:")
}


//Calls the webservice to find the Location returned from the geocoded address.
function PerformRoute()
{
 var errorlbl1 = document.getElementById("addressError1");
 var errorlbl2 = document.getElementById("addressError2");
 var CmbMultipleAddress1=document.getElementById("CmbMultipleAddress1");
 var CmbMultipleAddress2=document.getElementById("CmbMultipleAddress2");
 
  if ((routeList.length >= 2) && (CmbMultipleAddress1.style.display=='none')&& (CmbMultipleAddress2.style.display=='none') && (errorlbl2.innerHTML == "")&& (errorlbl1.innerHTML == "")){
    map.clearMarkers(); 
    map.clearRoutes();   

    // Make JSON object for all the controls initialise filter variables
    var productsFilter = {StoreType:  document.getElementById("dropStore").value,   //store type as string 
                        IsUnleadedPetrol: document.getElementById("chkUnlead").checked, //--- Products
                        IsVortDiesel: document.getElementById("chkVort").checked,
                        IsE10: document.getElementById("chkE10").checked,
                        IsDiesel: document.getElementById("chkDiesel").checked,
                        IsPremUnleaded: document.getElementById("chkPrem").checked,
                        IsBioDiesel:document.getElementById("chkBio").checked,
                        IsVortex95:document.getElementById("chkV95").checked,
                        IsAutoLPG: document.getElementById("chkLPG").checked,
                        IsVortex98: document.getElementById("chk98").checked,
                        IsBBQGas: document.getElementById("chkBBQ").checked,
                        IsStarCash: document.getElementById("chkSC").checked,
                        IsWoolworthsVoucher: document.getElementById("chkWoolworthsVoucher").checked,//--- Services
                        IsParticipatingRetail:document.getElementById("chkParticipatingRetail").checked,
                        IsVoucherLPG: document.getElementById("chkVoucherLPG").checked,
                        IsCarWash: document.getElementById("chkCarWash").checked,
                        IsConvenienceStore: document.getElementById("chkConvenienceStore").checked,
                        IsRestaurant: document.getElementById("chkRestaurant").checked,
                        IsFullService: document.getElementById("chkFullService").checked,
                        Is24Hrs: document.getElementById("chk24Hrs").checked,
                        IsDisabledToilets: document.getElementById("chkDisabledToilet").checked,
                        IsEFTPOS: document.getElementById("chkEFTPOS").checked,
                        IsHonkForAssistance: document.getElementById("chkHonk").checked,
                        IsATM:  document.getElementById("chkATM").checked,
                        IsTruckStop: document.getElementById("chkTruckStop").checked,
                        IsWishCard: document.getElementById("chkWishCard").checked,
                        IsWorkshop: document.getElementById("chkWorkshop").checked,
                        IsEzyBanking: document.getElementById("chkEzyBanking").checked
                        }      
           
     document.getElementById("loadingGif").innerHTML = "<img src='images/ajax-loader2.gif'>"

     //Call webservice with routeList array (ie/ either 2 or 3 X & Y Points) and Products filter
     CaltexService.GetRouteAndPOI(routeList, productsFilter, RouteAndPOIResultsCallback, FindNoResultsCallback);

  } else {
    
    // Call an error to say not enough points to do a route
    
   }
}


function RouteAndPOIResultsCallback(results)
{
    //Clear Route and TableS
    document.getElementById("lblError").innerHTML = "";
    document.getElementById("results").innerHTML = "";
    document.getElementById("loadingGif").innerHTML ="";
    markers = new Array();    
   
  //Create the Route
  //Bounds( left, bottom, right, top )  -->  (West, South, East, North)
    var bounds = new MapDS.Bounds( results.RouteObj.West, results.RouteObj.South, results.RouteObj.East, results.RouteObj.North );
    var myrouteFromWS = new MapDS.Route( null, results.RouteObj.MapFileName , bounds );  
    map.addRoute( myrouteFromWS );
    //alert(results.RouteObj.MapFileName)

    var POITable = "";
    
    
    if(results.CaltexPOIs != null){
        if(results.CaltexPOIs.length > 0){     
             
             //Add the pushpins for each location
             for(var i=0; i<results.CaltexPOIs.length; i++)
             { 
                AddPushPin(results.CaltexPOIs[i]);
             }

             POITable = createPOITable(results.CaltexPOIs)     
             
               }else{
                document.getElementById("lblError").innerHTML = NO_SERVICESTATIONS_FOUND;
        }
    }
             
             AddLocationPushPin(); 
             map.loadBestView();
             map.refresh() 
             
             //CREATE DRIVING DIRECTIONS TABLE
             var totalDistance =  results.RouteObj.Itinerary.Distance<1?(results.RouteObj.Itinerary.Distance*1000)+" m":(formatNumber(results.RouteObj.Itinerary.Distance, 2))+" km"// + "km"
             var totalTime = time(results.RouteObj.Itinerary.DrivingTime)
             var DrvDirStr = "";

             DrvDirStr += '<div class="tabletitle">Driving Directions from: ' + getAddress() +'</div>'
             DrvDirStr += "<table  class='POITable'>"
             DrvDirStr += "<tr><th>Instruction</th><th>Bearing</th><th>Suburb</th><th>Time</th><th>Distance</th></tr>"
             for(var a=0;a<results.RouteObj.Itinerary.Segments[0].Directions.length;a++)
             {
                  var dir=results.RouteObj.Itinerary.Segments[0].Directions[a];
                  DrvDirStr +=  GetRouteInstructions(dir, a) 
             }
             DrvDirStr +="<tr><td></td><td></td><td><b>TOTALS</b></td><td>"+ totalTime +"</td><td>"+ totalDistance +"</td></tr>"
             DrvDirStr += "</table></div>"
          
          
           if(results.CaltexPOIs != null){
        if(results.CaltexPOIs.length > 0){   
             document.getElementById("results").innerHTML +=  POITable + DrvDirStr ; 
            }
            else{
               document.getElementById("results").innerHTML += DrvDirStr ; 
            }
            }
            
           
}



function createPOITable(POI){

var POITable = "";

 POITable +=" <div class='tabletitle'>Search Results For Service Stations on route</div>"
 POITable += "<table class='POITable'>"
 POITable += "<tr><th>Info</th><th>State </th><th>Name</th><th> Address</th><th>Town</th><th> Postcode</th><th> Phone </th><tr>"

 for(var i=0; i<POI.length; i++)
 {  
    POITable += "<tr><td><a href='javascript:DisplayPopup("+ POI[i].X +","+POI[i].Y +","+POI[i].IconIndex+")' /><img src='"+ POI[i].IconPath +"' title='Click to zoom to point and get more information' /></a></td><td>"+ POI[i].State +"</td><td><a href='javascript:DisplayPopup("+ POI[i].X +","+POI[i].Y +","+POI[i].IconIndex+")' />"+ POI[i].Brand +" " + POI[i].LocName +"</a></td>"
    POITable += "<td>"+ POI[i].Address+"</td><td>"+ POI[i].Suburb+"</td><td>"+ POI[i].Postcode+"</td><td>"+ POI[i].Phone+"</td></tr>"
 }
POITable += '</table></div></div>'
return POITable
}


function formatNumber(myNum, numOfDec)
{
    var toDecimal = 1
    for(i=1; i<=numOfDec;i++)
    toDecimal = toDecimal *10
    var myFormattedNum = (Math.round(myNum * toDecimal)/toDecimal).toFixed(numOfDec)
    return(myFormattedNum)
} 

// Returns an address from the hidden input fields to display
function getAddress(){

        var streetAddress = "";
        if (document.form1.SearchSuburb1.value != "") {
            streetAddress += document.form1.SearchSuburb1.value +", "
        }
        if (document.form1.SearchPostcode1.value != "") {
            streetAddress += document.form1.SearchPostcode1.value +", "
        }
        if (document.form1.SearchState1.value !=""){
          streetAddress += document.form1.SearchState1.value +" to "
        }
        if (document.form1.SearchSuburb2.value != "") {
            streetAddress += document.form1.SearchSuburb2.value +", "
        }
        if (document.form1.SearchPostcode2.value != "") {
            streetAddress += document.form1.SearchPostcode2.value +", "
        }
        if (document.form1.SearchState2.value !=""){
          streetAddress += document.form1.SearchState2.value +" to "
        }        
        if (document.form1.SearchSuburb3.value != "") {
            streetAddress += document.form1.SearchSuburb3.value +", "
        }
        if (document.form1.SearchPostcode3.value != "") {
            streetAddress += document.form1.SearchPostcode3.value +", "
        }
        if (document.form1.SearchState3.value !=""){
          streetAddress += document.form1.SearchState3.value 
        }
        return streetAddress;
}


//get Address according to index
function getAddressIndexed(index){
        var streetAddress = "";
        index +=1
        if (index == 1){
            if (document.form1.SearchSuburb1.value != "") {
                streetAddress += document.form1.SearchSuburb1.value +", "
            }
            if (document.form1.SearchPostcode1.value != "") {
                streetAddress += document.form1.SearchPostcode1.value +", "
            }
            if (document.form1.SearchState1.value !=""){
              streetAddress += document.form1.SearchState1.value 
            }
        }

        if (index == 2){
            if (document.form1.SearchSuburb2.value != "") {
                streetAddress += document.form1.SearchSuburb2.value +", "
            }else{
                 streetAddress += document.form1.SearchSuburb3.value +", "
            }
            if (document.form1.SearchPostcode2.value != "") {
                streetAddress += document.form1.SearchPostcode2.value +", "
            }else{
                streetAddress += document.form1.SearchPostcode3.value +", "

            }
            if (document.form1.SearchState2.value !=""){
              streetAddress += document.form1.SearchState2.value 
            }else{
              streetAddress += document.form1.SearchState3.value +", "
            }
        }
        
        if (index == 3){
            if (document.form1.SearchSuburb3.value != "") {
                streetAddress += document.form1.SearchSuburb3.value +", "
            }
            if (document.form1.SearchPostcode3.value != "") {
                streetAddress += document.form1.SearchPostcode3.value +", "
            }
            if (document.form1.SearchState3.value !=""){
              streetAddress += document.form1.SearchState3.value
            }
        }
        return streetAddress;
}



//adds POI pushpins (max 10)
function AddPushPin(mapPOI){
   // var size = new MapDS.Size( 25, 28 );
    var size = new MapDS.Size( 25, 25 );
    //offset is topleft -height - 7 pix or so 
    var offset = new MapDS.Pixel(0,-25);
    var locPin = new MapDS.Icon( mapPOI.IconPath, size, offset );
    var mkr = new MapDS.Marker( new MapDS.LatLng( mapPOI.Y, mapPOI.X ), locPin.clone(), { popupDisplayMode: MapDS.MarkerOptions.PopupDisplayMode.Hover}  );

    mkr.setPopupContent( mapPOI.PopupContent );  
    markers.push(mkr);
    map.addMarker( mkr ); 
}

//Adds location pushpin to map
function AddLocationPushPin(){

 for(var a=0;a<routeList.length;a++)
 {
    var centerX =parseFloat(routeList[a].X);
    var centerY = parseFloat(routeList[a].Y);
  //  alert(getAddressIndexed(a))
    var streetAddress = "<table class='popupLocation' ><tr><td>" + getAddressIndexed(a) +"</td></tr></table>";
    var startImg =""

    if (a == 0) {startImg = 'images/marker/tear-drop-routestart.png';}
      
    if (a == 1)
    {   if (routeList.length == 3)
        {            startImg= 'images/marker/orange-drop.png';
        }else{
             startImg= 'images/marker/tear-drop-routeend.png';

        }       
    }

    if ((routeList.length == 3) && (a == 2)) {var startImg= 'images/marker/tear-drop-routeend.png'}

   
    var size = new MapDS.Size( 25, 35 );
    var offset = new MapDS.Pixel(-13,-30);
    var locPin = new MapDS.Icon( startImg, size, offset );
    var mkr = new MapDS.Marker( new MapDS.LatLng( centerY, centerX ), locPin.clone(), { popupDisplayMode: MapDS.MarkerOptions.PopupDisplayMode.Hover}  ); 
    mkr.setPopupContent( streetAddress );  
    map.addMarker( mkr ); 
    
  }
}


//popup functionality
function DisplayPopup(X, Y, popupIndex){
    X = parseFloat(X);
    Y = parseFloat(Y);
    map.setCentre( new MapDS.LatLng( Y, X ), ZoomToValue ); 
    markers[(popupIndex-1)].showPopup();
    window.scrollTo(0,0); 
}


//original map button functionality
function OriginalMap(){
//would have utilised map.restoreView(); but this shows the view without the search sometimes results come back different since 
//it searches around the center point, instead just call the original search.
    if  (document.getElementById("map").style.display!="none"){
    SearchClick();
    }else{//do nothing
    }
}


function ClearClick(){ 
    if (document.getElementById("map").style.display =='block'){
        document.getElementById("map").style.display ='none';
        document.getElementById("mainMap").style.display ='block';
    }
    document.getElementById("CmbMultipleAddress1").style.display="none";
    document.getElementById("CmbMultipleAddress2").style.display="none";
    document.getElementById("CmbMultipleAddress3").style.display="none";
    document.getElementById("addressError1").innerHTML="";
    document.getElementById("addressError2").innerHTML="";
    document.getElementById("addressError3").innerHTML="";
    document.getElementById("lblError").innerHTML ="";    
    document.getElementById("results").innerHTML ="";
    document.getElementById("resultsHeaderText").innerHTML="";
    
    document.getElementById("form1").reset();
    map.clearMarkers();    
    map.clearRoutes();
    map.setCentre( new MapDS.LatLng( -28.5, 133.5 ), AustraliaZoomLevel);
    if (openAccordion != ""){runAccordion(1,335);}
  
 
}

//open help file in a new window
function LaunchScrollWindow(url, id, x, y)
{ 
  window.open(url, id, "resizable=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,width="+x+",height="+y);
}



//Wipes the text field clean when condition is meet.
function txtFocus(idname)
{ 
    if (idname.value == DEFAULT_ENTER_SUBURB)
    {
        idname.value  = '';
    }
}

//Puts default text in box if it is null.
function txtBlur(idname)
{
   //Check to see if box is empty
    if (idname.value == "")
    {
        //check to see which text box is focused
        idname.value = DEFAULT_ENTER_SUBURB;
              
    }
   
}


//Removes the tags in the AddressLine of the route because it contains sheilds
//Cleans the object from all HTML. 
function removeHTMLTags(htmlString)
{
     if(htmlString){
          var mydiv = document.createElement("div");
           mydiv.innerHTML = htmlString;
 
            if (document.all) // IE Stuff
            {
                return mydiv.innerText;
               
            }   
            else // Mozilla does not work with innerText
            {
                return mydiv.textContent;
            }                           
      }
} 




//Returns the entire route itinerary that is formated 
// Itinerary = results.RouteObj.Itinerary.Segments[0].Directions[a] 
// where index is need to show the instruction numbers on the left.
function GetRouteInstructions(Itinerary, index)
{

   var roadLine = " <b>"+ removeHTMLTags(Itinerary.Address.AddressLine) +"</b>"; 
   var bearingWords = GetBearingInWords(Itinerary.Bearing)
   var suburb = Itinerary.Address.PrimaryCity
   var runDistance = Itinerary.Distance<1?(Itinerary.Distance*1000)+"m":(Itinerary.Distance)+"km";
   var runTime = Itinerary.Duration>60?Math.floor(Itinerary.Duration/60)+":"+(Itinerary.Duration%60)+" min":(Itinerary.Duration)+" sec" //TODO ROUND OFF KM ALSO TIME
 
 if(Itinerary.FormattedInstruction != '')
 {


   var addressStr =""
   switch (Itinerary.FormattedInstruction.trim().toUpperCase())
    {
        case "START ON":
            addressStr= "Head <b>" + bearingWords + "</b> on"
        break; 
        case "TURN LEFT":
            addressStr= "Turn <b>left</b> at"
        break; 
        case "TURN RIGHT":
            addressStr= "Turn <b>right</b> at "
        break; 
        case "CONTINUES AS":
            addressStr= "Continue along"
        break; 
        case "CONTINUE AS":
            addressStr= "Continue along"
        break; 
        case "CONTINUE":
            addressStr= "Continue along"
        break; 
        case "PASS THROUGH":
            addressStr= "Pass through to"
        break; 
        case "STAY ON":
            addressStr= "Stay on"
        break; 
        case "BEAR LEFT":
            addressStr= "Bear <b>left</b> at"
        break; 
        case "BEAR RIGHT":
            addressStr= "Bear <b>right</b> at"
        break; 
        case "TURN BACK TO YOUR RIGHT":
            addressStr= "Turn back to your <b>right</b> at"
        break; 
        case "TURN BACK TO YOUR LEFT":
            addressStr= "Turn back to your <b>left</b> at"
        break; 
        case "TURN BACK TO YOUR LEFT":
            addressStr= "Turn back to your <b>left</b> at"
        break; 
        case "FINISH ON":
            addressStr= "Finish on"
        break; 
        default:
            addressStr= Itinerary.FormattedInstruction;
    }
    
    index = index + 1 +". ";
    return "<tr><td><a href='javascript:goToTurn("+Itinerary.LatLong.Latitude +","+ Itinerary.LatLong.Longitude +")' />" + index + addressStr + roadLine +"</a></td><td>"+ bearingWords +"</td><td>"+ suburb +"</td><td>"+ runTime +"</td><td>"+ runDistance +"</td></tr>"    

  }else{
      return "<tr><td>" + index + "<a href='javascript:goToTurn("+routeList[1].Y +","+ routeList[1].X +")' /> Via Point reached - "+ getAddressIndexed(1) +"<a></td><td></td><td></td><td>"+ runTime +"</td><td>"+ runDistance +"</td></tr>"    
  }  
  
}


function goToTurn(Y, X){
    map.setCentre( new MapDS.LatLng( Y, X ), ZoomToValue ); 
    window.scrollTo(0,0)
}


function GetBearingInWords(bearing){
    
    switch (bearing.trim().toUpperCase())
    {
    case "N":
        return "North"
    break;
    case "NE":
        return "North East"
    break;
    case "E":
        return "East"
    break;
    case "SE":
        return "South East"
    break;
    case "S":
        return "South"
    break;
    case "SW":
        return "South West"
    break;
    case "W":
        return "West"
    break;
    case "NW":
        return "North West"
    break;
    default: 
        return bearing.trim().toUpperCase()
    }  
}



// -- Functions for getting from seconds to hours
    function two(x) {return ((x>9)?"":"0")+x}
    
    function three(x) {return ((x>99)?"":"0")+((x>9)?"":"0")+x}

    function time(sec) {
    var t
    var min = Math.floor(sec/60)
    sec = sec % 60
    t = two(sec) + " sec "
    var hr = Math.floor(min/60)
    min = min % 60
    if (min != 0){
    t = two(min) + " min " + t
    }
    hr = hr % 60
    if (hr != 0){
    t = two(hr) + " hr " + t
    }
    return t
    }
// --

function checkEnter(e){ //e is event object passed from function invocation

    var characterCode //literal character code will be stored in this variable
    if(e && e.which){ //if which property of event object is supported (NN4)
        e = e
        characterCode = e.which; //character code is contained in NN4's which property
    }
    else{
    if (window.event) {e=event;} 
    characterCode = e.keyCode;//character code is contained in IE's keyCode property
    }

    if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
        SearchClick();
    return false;
    }
    else{
    return true;
    }

}

function Print(){
window.print();
}


window.onload = OnLoad;