
// Driving Direction globals
var g_strDestFullAddress = null;
var g_objDestLatLong   = null;
var g_strFromAddress  = null;
var g_objFromAddress  = null;
var g_objFromLocation = null;
var g_objFromLatLong  = null;
var g_strMainMapObjId = 'resultmap';
var g_pAreaMap        = null;

function doMyC21DrivingDirections(){
    try{
        RfgCreateMap('resultmap', 'RoadVE', true, g_objDestLatLong.Latitude, g_objDestLatLong.Longitude, 14, false, false);
        //g_MapService.ShowDetailOnMouseOver( false );
        //g_MapService.AddVEPushpinOnMouseOver( RfgShowSearchTooltip);
        g_pAreaMap = RfgGetMapById('resultmap');
        GenerateRouteFromLocation( g_objFromLatLong, g_objDestLatLong )
    }catch (e){
    }
}

function InitializeDirections() {
   try {
      g_strDestFullAddress = g_strDestAddress + ", " + g_strDestCity + ", " + g_strDestState + " " + g_strDestZip;
      PreselectDropDownItem(document.getElementById('fstate'), g_strDestState);
   } catch (e) {
   }
   try {
      RfgCreateMap('resultmap', 'RoadVE', true, g_objDestLatLong.Latitude, g_objDestLatLong.Longitude, 14, false, false );
      //g_MapService.ShowDetailOnMouseOver( false );
      //g_MapService.AddVEPushpinOnMouseOver( RfgShowSearchTooltip);

      RfgShowDetailOnMouseOver( false );
      RfgAddVEPushpinOnMouseOver( RfgShowSearchTooltip );


      g_pAreaMap = RfgGetMapById('resultmap');
      RfgAddPushPin("resultmap", g_objDestLatLong.Latitude, g_objDestLatLong.Longitude, escape(g_strPushPinText), '', '/images/map/house.gif');
   } catch (e) {
   }
   
}
function InitializeMiniMap() {
   var minimapId = "minimap";
   try {
      g_strMMFullAddress = g_strMMAddress + ", " + g_strMMCity + ", " + g_strMMState + " " + g_strMMZip;
   } catch (e) {}
   try {
      RfgCreateMap(minimapId, 'RoadVE', false, g_objMMLatLong.Latitude, g_objMMLatLong.Longitude, 14, false, false );
      RfgShowDetailOnMouseOver( false );
      RfgAddVEPushpinOnMouseOver( RfgShowSearchTooltip );
      RfgShowMapDashboard( minimapId, false );

      g_pAreaMap = RfgGetMapById('minimap');
      RfgAddPushPin(minimapId, g_objMMLatLong.Latitude, g_objMMLatLong.Longitude, escape(g_strMMPushPinText), '', '/images/map/house.gif');
   } catch (e) {}
   
}
function PreselectDropDownItem(object, item)
{
   if (object == null) {
      return;
   }
   var total = object.length;
   object.selectedIndex = 2;
   value = object.options[object.selectedIndex].value;
   for (i=0;i<total;i++) {
      object.selectedIndex =i ;
      local_value = object.options[object.selectedIndex].value;
      if (local_value == item ) {
         break;
      } else {
         continue;
      }
   }
}

function ShowWaitMessage()
{
   RfgShowWaitDialog(g_strMainMapObjId, true, "Calculating Route");
}

function HideWaitMessage()
{
   RfgHideWaitDialog(g_strMainMapObjId);
}

function ShowRouteOnMapCallback(routeResults)
{
   HideWaitMessage();
   var pElement = document.getElementById( "drivinginstructions");
   if( pElement ){
      pElement.innerHTML = BuildDrivingDirectionsText( routeResults, g_strFromAddress, g_strDestFullAddress, g_bDisplaySave);
   }
}

function GenerateRouteFromLocation( objFromLatLong, objToLocation )
{
    try {
       RfgGenerateRoute( g_strMainMapObjId, objFromLatLong, objToLocation, QUICKEST_ROUTE, "ShowRouteOnMapCallback" );
    } catch ( e ) {
       HideWaitMessage();
       alert( e.message );
    }
}

function GetDirectionsFromForm()
{
    var strError = '';

    if (document.forms.directionsform.fcity.value == '') {
            strError += "\tPlease fill in a city.\n";
    }

    if (document.forms.directionsform.fstate.selectedIndex == 0) {
            strError += "\tPlease select a state.\n";
    }

    if (document.forms.directionsform.fzip.value == '') {
            strError += "\tPlease fill in a valid zip code.\n";
    }


    if (strError != '') {
       alert("Please correct the following problems:\n\n"+strError);
       return false;
    } else {
       g_strFromAddress = document.forms['directionsform'].faddress.value +', '+ document.forms['directionsform'].fcity.value +
                          ', ' + document.forms['directionsform'].fstate.options[document.forms['directionsform'].fstate.selectedIndex].value +
                          ' ' + document.forms['directionsform'].fzip.value;

      try {
          ShowWaitMessage();
          var startAddress = document.getElementById('startAddress');
          var startCity = document.getElementById('startCity');
          var startState = document.getElementById('startState');
          var startZip = document.getElementById('startZip');
          if( startAddress && startCity && startState && startZip ) {
             startAddress.value=document.forms['directionsform'].faddress.value;
             startCity.value=document.forms['directionsform'].fcity.value;
             startState.value=document.forms['directionsform'].fstate.options[document.forms['directionsform'].fstate.selectedIndex].value;
             startZip.value=document.forms['directionsform'].fzip.value;
          }
          g_objFromAddress = new Address(document.forms['directionsform'].faddress.value,
                                         document.forms['directionsform'].fcity.value,
                                         document.forms['directionsform'].fstate.options[document.forms['directionsform'].fstate.selectedIndex].value,
                                         'US',
                                         document.forms['directionsform'].fzip.value, null, null);
          RfgFindLocation( g_strMainMapObjId, g_objFromAddress, true, false, RouteGeoCodeAddressCallback );
      } catch ( e ) {
          HideWaitMessage();
          alert( e.message );
      }
   }
   return false;
}


function RouteGeoCodeAddressCallback( layer, aResults, pPlaces, bHasMore, veErrorMessage )
{
   if( pPlaces && pPlaces.length > 0 ){
      //g_objFromLocation = a_objFindResults.results[0];
      //g_objFromLatLong = g_objFromLocation.latlong;
      //GenerateRouteFromLocation( g_objFromLatLong, g_objPropertyLatLong );
      var result = pPlaces[0];
      var startLat = document.getElementById('startLat');
      var startLong = document.getElementById('startLong');
      if( startLat && startLong ) {
         var tempLatLong = result.LatLong;
         tempLatLong = String(tempLatLong).split(",", 2);
         startLat.value = tempLatLong[0].replace(/^\s+|\s+$/g,"");
         startLong.value = tempLatLong[1].replace(/^\s+|\s+$/g,"");
      }
      GenerateRouteFromLocation( result.LatLong, g_objDestLatLong );
   } else {
      //unable to find start address...
      HideWaitMessage();
      alert("I'm sorry, but we were unable to locate the address you entered.  Please double check your data and try again.");
   }
}


function BuildDrivingDirectionsText( route, startAddress, endAddress, bShowSave )
{
   var content = "<table>";
   try{
      var it = route.Itinerary;
      var distance = document.getElementById('distance');
      if(distance) {
         distance.value = it.Distance;
      }
      var step = 1;
      var rowcount = 0;
   
      content += "<tr class='header'>";
      content += "<td class='step'>#</td>";
      content += "<td class='header'>Driving Directions from " + startAddress + " to " + endAddress +"</td>";
      content += "</tr>";
   
   
      var len = route.Itinerary.Segments.length;
      for(var i = 0; i < len ;i++)
      {
         rowcount++;
         content += "<tr "+ ((rowcount & 1) ? "class='alt'" : "") + ">";
         content += "<td class='step'>" + (i+1) + "</td>";
         content += "<td class='direction'>" + it.Segments[i].Instruction;
         if( it.Segments[i].Instruction == 'Start at ') {
            content += ' '+ startAddress;
         }else if( it.Segments[i].Instruction == 'Arrive at ') {
               content += ' '+ endAddress;
         }
         if( it.Segments[i].Distance > 0 ) {
            content += " -- (";
            content += it.Segments[i].Distance+") ";
            content += it.DistanceUnit+"\n";
         }
         content += "</td>";
         content += "</tr>";
      }
   }catch (e){
      alert( e.message );
   }
   content += "</table>";
   if( bShowSave ) {
      content += '<div class="myc21_button" id="save_directions">\
                     <a onclick="return saveDirectionsToMyC21(this);" href="#">\
                        <img id="save_directions_button" src="/images/myc21/save_but.gif" alt="save">\
                     </a>\
                  </div>';
   }
   return content;
}


/*POI Map Functions*/


/*
TODO make all these vars specifically for poi map
var g_pMainSearchMap = null;
var g_iMapPreviewPosLeft = 0;
var g_iMapPreviewPosRight = 0;
var g_iMapPreviewPosTop = 0;
var g_iMapPreviewPosBottom = 0;
var g_bMapPreviewCancelCloseRequest = false;
var g_bMapPreviewTimeoutActive = false;
var g_bMapPreviewVisible = false;
var g_objMapPreview = new Object();*/

var g_pPoiMap = null;
var g_aPOIs = new Array();
var g_bInitPoiMap = false;
var g_iMaxZoomLevel = 18;
function InitializePoiMap() {
   if(g_bInitPoiMap == true) {
      return false;
   }
   g_bInitPoiMap = true;
   var poimapId = "poi_map";
   try {
      g_strPOIFullAddress = g_strPOIAddress + ", " + g_strPOICity + ", " + g_strPOIState + " " + g_strPOIZip;
   } catch (e) {}
   try {
      RfgCreateMap(poimapId, 'RoadVE', false, g_objPOILatLong.Latitude, g_objPOILatLong.Longitude, 12, false, false );
      RfgShowDetailOnMouseOver( false );
      RfgShowMapDashboard( poimapId, false );
      //TODO:  RfgAddVEPushpinOnMouseOver( ShowOHMapMouseOver );
   
      RfgAddVEPushpinOnMouseOver( ShowPoiMapMouseOver );
      //RfgAttachMapEvent( 'poi_map', Events.ONMOUSEWHEEL, ReturnTrue );

      g_pPoiMap = RfgGetMapById(poimapId);
      poiAddPushPin(g_objPOILatLong, '/images/map/house.gif', 'property0', 'PROPERTY');
      //RfgAddPushPin(poimapId, g_objPOILatLong.Latitude, g_objPOILatLong.Longitude, escape(g_strPOIPushPinText), '', '/images/map/house.gif');
   } catch (e) {}
   initPOIArrays();
   return false;
}

function PoiZoomIn()
{
   if( g_pPoiMap ) {
      var iCurrentZoom = g_pPoiMap.GetZoomLevel();
      if( iCurrentZoom < g_iMaxZoomLevel) {
         g_pPoiMap.SetZoomLevel(iCurrentZoom+1);
      } else {
         alert( 'You can not zoom-in any further' );
      }
   } else {
      alert(g_strLoadingTxt);
   }
}

function PoiZoomOut()
{
   if( g_pPoiMap ) {
      var iCurrentZoom = g_pPoiMap.GetZoomLevel();
      if( iCurrentZoom > 3 ) {
         g_pPoiMap.SetZoomLevel(iCurrentZoom-1);
      } else {
         alert( 'You can not zoom-out any further' );
      }
   } else {
      alert(g_strLoadingTxt);
   }
}
function initPOIArrays(){
   g_aPOIs['coffee'] = new Array();
   g_aPOIs['school'] = new Array();
   g_aPOIs['transportation'] = new Array();
   g_aPOIs['restaurant'] = new Array();
   g_aPOIs['park'] = new Array();
}
function findPOI(strId){
   var p = findPOIInArrays(g_aPOIs['coffee'], strId);
   if( p ) return p;
   p = findPOIInArrays(g_aPOIs['school'], strId);
   if( p ) return p;
   p = findPOIInArrays(g_aPOIs['transportation'], strId);
   if( p ) return p;
   p = findPOIInArrays(g_aPOIs['restaurant'], strId);
   if( p ) return p;
   p = findPOIInArrays(g_aPOIs['park'], strId);
   if( p ) return p;
   p = findPOIInTable(strId);
   if( p ) return p;
   return null;
}
function findPOIInTable(strId){
   var e = document.getElementById('latitude_'+ strId);
   if( !e ) return null;

   var p = new Object();
   p.LatLong = new Object();

   p.LatLong.Latitude = e.innerHTML;
   p.LatLong.Longitude = document.getElementById('longitude_'+ strId).innerHTML;
   p.Name = document.getElementById('name_'+ strId).innerHTML;
   p.Description = document.getElementById('description_'+ strId).innerHTML;
   p.Phone = document.getElementById('phone_'+ strId).innerHTML;
   p.typeCode = document.getElementById('typecode_'+ strId).innerHTML;
   p.inTable = 'true';

   return p;
}
function findPOIInArrays(resultsArray, strId){
   for(i = 0; i < resultsArray.length; i++){
      if( resultsArray[i].id == strId) return resultsArray[i];
   }
   return null;
}
function getPOITypeCode(searchTerm){
   var strTypeCode = '';
   if(searchTerm == 'school') strTypeCode = 'S';
   else if(searchTerm == 'transportation') strTypeCode = 'T';
   else if(searchTerm == 'park') strTypeCode = 'P';
   else if(searchTerm == 'restaurant') strTypeCode = 'R';
   else if(searchTerm == 'coffee') strTypeCode = 'C';
   return strTypeCode;
}
//  A VEShapeLayer Class object. If shapeLayer was supplied, it should be the same object.
//  An array of VEFindResult Class objects.
//  An array of VEPlace Class objects.
//  A Boolean value indicating whether there are more results after the current set.
//  A String containing a possible error message.
function handlePOI(layer, resultsArray, places, hasMore, veErrorMessage, searchTerm){
   var strIcon = getPOIIcon(searchTerm);
   if(veErrorMessage != null && veErrorMessage != '') alert(veErrorMessage);
   if( resultsArray != null ){
      for(i = 0; i < resultsArray.length; i++){
         //Name, Description, Phone, LatLong
         //RfgAddPushPin("resultmap", resultsArray[i].LatLong.Latitude, resultsArray[i].LatLong.Longitude, '', '', strIcon);
         resultsArray[i].shape = poiAddPushPin(resultsArray[i].LatLong, strIcon, (searchTerm+i), 'POI');
         //resultsArray[i].id = resultsArray[i].shape.GetId();
         resultsArray[i].typeCode = getPOITypeCode(searchTerm);
         resultsArray[i].inTable = 'false';
         resultsArray[i].id = (searchTerm+i);
         g_aPOIs[searchTerm].push(resultsArray[i]);
      }
   } else {
      alert('Sorry, but no results were found.');
   }
}
function poiAddPushPin(latlong, strIcon, strId, strType) 
{
   try{
      g_iPushPinSeq++;
      var vePushpin = new VEShape(VEShapeType.Pushpin, latlong);
      if (strIcon!=null && strIcon!=""){
          vePushpin.SetCustomIcon(strIcon);
      }
      if (strId == null ){
         vePushpin.SetTitle(vePushpin.GetID());
      } else if(strId != ""){
          vePushpin.SetTitle(strId);
      }
      if (strIcon!=null && strIcon!=""){
          vePushpin.SetCustomIcon(strIcon);
      }
      if (strType!=null && strType!=""){
          vePushpin.SetDescription(strType);
      }
      g_pPoiMap.AddShape(vePushpin);
      return vePushpin;
   } catch( xE ){
      if( g_bShowErrorInformation ) {
         alert( xE.message );
      }
   }
}
function poiSearch(pCB, searchTerm){
   if(pCB.checked == false) {
      deletePoiPushpins(searchTerm);
      g_aPOIs[searchTerm] = new Array();
      return;
   }
   try{
      var pFunction = function(layer, resultsArray, places, hasMore, veErrorMessage){
         handlePOI(layer, resultsArray, places, hasMore, veErrorMessage, searchTerm);
      };
      g_pPoiMap.Find(searchTerm, g_pPoiMap.GetMapView(), null, null, 0, 20, true, false, false, false, pFunction);

   }catch (e){
      alert(e.message);
   }
}
function deletePoiPushpins(searchTerm){
   for(i = 0; i < g_aPOIs[searchTerm].length; i++){
      g_pPoiMap.DeleteShape(g_aPOIs[searchTerm][i].shape);
   }
}

function getPOIIcon(searchTerm){
   var strIcon = '';
   if(searchTerm == 'school' || searchTerm == 'S') strIcon = '/images/openhouse/abc-ylw.gif';
   else if(searchTerm == 'transportation' || searchTerm == 'T') strIcon = '/images/openhouse/bus-ylw.gif';
   else if(searchTerm == 'park' || searchTerm == 'P') strIcon = '/images/openhouse/tree-ylw.gif';
   else if(searchTerm == 'restaurant' || searchTerm == 'R') strIcon = '/images/openhouse/kitchen-ylw.gif';
   else if(searchTerm == 'coffee' || searchTerm == 'C') strIcon = '/images/openhouse/coffee-ylw.gif';
   return strIcon;
}
function ShowPoiMapMouseOver( iWrongXPos, iWrongYPos, strEncId, strEncType){
   if( strEncId == null || strEncId == '') return; //block popup for starting location

   strId = unescape(strEncId);
   strType = unescape(strEncType);
   var pPreviewDiv = '';
   var prevPopupname = '';

   if(strType == 'POI') {
      prevPopupname = g_pPoiMap.popupname;
      g_pPoiMap.popupname = 'poimappopup';
   } else {
      prevPopupname = g_pPoiMap.popupname;
      g_pPoiMap.popupname = 'poipropertypopup';
   }
   var pPreviewDiv = document.getElementById( g_pPoiMap.popupname );
   if( pPreviewDiv ) {
      if ( g_bMapPreviewVisible ) {
         if( g_objMapPreview ) {
            if( g_objMapPreview.popupname == prevPopupname &&
                g_objMapPreview.iXPos == iWrongXPos &&
                g_objMapPreview.iYPos == iWrongYPos &&
                g_objMapPreview.strId == strId ) {
               //This is the same as last time, do NOTHING
               return;
            }
         }
         var p = document.getElementById(prevPopupname);
         if( p ) {
            p.style.display = 'none';
         }
         HideMapPreview();
      }

      g_bMapPreviewVisible = true;
      g_bMapPreviewCancelCloseRequest = true;
      g_bMapPreviewTimeoutActive = true;
      g_bMapPreviewNeedsRepositioned = false;

      if( g_objMapPreview ) {
         g_objMapPreview.iXPos = iWrongXPos;
         g_objMapPreview.iYPos = iWrongYPos;
         g_objMapPreview.strId = strId;
      }

      var fLat = 0.0;
      var fLon = 0.0;
      var pTemp;
      if(strType == 'POI') {
         //see if it is in the table first!!!
         //most will make it here...
         var poi = findPOI(strId);
         if( poi ) {
            fLat = poi.LatLong.Latitude;
            fLon = poi.LatLong.Longitude;
            var html = '<b>'+ poi.Name +'</b><br/>'+ poi.Description +'<br/>'+ poi.Phone +'<br/>';
            var icon = getPOIIcon(poi.typeCode);
            SetInnerHtml('poimappopupimg', '<img src="'+ icon +'" border="0" />');
            SetInnerHtml('poimappopupdetails', html);
         }
      }else{
         fLat = g_objPOILatLong.Latitude;
         fLon = g_objPOILatLong.Longitude;
      }
      //var pPixel = g_pMainSearchMap.LatLongToRoundedPixel( fLat, fLon );
      var pPixel = RfgPixelFromLatLong( 'poi_map', fLat, fLon );
      var intX = pPixel.x;
      var intY = pPixel.y;
      RfgSetObjectPosition(pPreviewDiv, intX, intY);
      pPreviewDiv.style.display = 'block';
      RemoveClass( g_objMapPreview.popupname, 'hide' );

      if( !window.event ) {
         //We did not get a proper location!
         if( document.addEventListener ) {
            document.addEventListener('mousemove', MoveMapPreview, true );
         } else {
            document.attachEvent( 'onmousemove', MoveMapPreview );
            document.attachEvent( 'onmouseover', MoveMapPreview );
            document.attachEvent( 'onmouseout', MoveMapPreview );
         }
      } else {
         setTimeout( BeginShowPoiMapPreview, 400 );  
      }
   }
}
function BeginShowPoiMapPreview()
{
   // this function ensures enough time has passed for the block to render before reading the size
   var pPreviewDiv = document.getElementById( g_pPoiMap.popupname );
   if ( pPreviewDiv != null ) {
      g_iMapPreviewPosLeft = RfgFindPosX(pPreviewDiv);
      g_iMapPreviewPosRight = g_iMapPreviewPosLeft + RfgFindWidth(pPreviewDiv);
      g_iMapPreviewPosTop = RfgFindPosY(pPreviewDiv) - 30;
      g_iMapPreviewPosBottom = g_iMapPreviewPosTop + RfgFindHeight(pPreviewDiv) + 30;

      if( document.addEventListener ) {
         document.addEventListener('mousemove', TrackPoiMapPreview, true );
      } else {
         document.attachEvent( 'onmousemove', TrackPoiMapPreview );
      }
      setTimeout( RequestHidePoiMapPreview, 400 );
   }
}
function RequestHidePoiMapPreview()
{  
   var pPreviewDiv = document.getElementById( g_pPoiMap.popupname );
   if ( pPreviewDiv != null ) {     
      g_bMapPreviewTimeoutActive = false;
      if( ! g_bMapPreviewCancelCloseRequest ) {
         HidePoiMapPreview();
      }
   }
}
function HidePoiMapPreview()
{  
   var pPreviewDiv = document.getElementById( g_pPoiMap.popupname );
   if ( pPreviewDiv != null ) {
      if( document.removeEventListener ) {
         document.removeEventListener('mousemove', TrackPoiMapPreview, true );         
      } else {
         document.detachEvent('onmousemove', TrackPoiMapPreview );
         document.detachEvent('onmouseover', TrackPoiMapPreview );
         document.detachEvent('onmouseout', TrackPoiMapPreview );
      }
      pPreviewDiv.style.display = 'none';
      g_bMapPreviewVisible = false;
      g_bMapPreviewCurrentId = "";
      g_objMapPreview.strTrKey = '';
   }
}
function TrackPoiMapPreview( event )
{
   var pPreviewDiv = document.getElementById( g_pPoiMap.popupname );
   if ( pPreviewDiv != null ) {

      var tempX = RfgGetMouseXPosition(event, 0);
      var tempY = RfgGetMouseYPosition(event, 0);
      //in ie7 - not 6 - popup is relative to map, not page...adjust mouse position
      if( g_pBrowser.bIsMsIe && g_pBrowser.fVersionMajor > 6) {
         tempX = tempX - g_iIEMapOffsetX;
         tempY = tempY - g_iIEMapOffsetY;
      }

      if( tempX < g_iMapPreviewPosLeft || tempX > g_iMapPreviewPosRight ){            
         if( ! g_bMapPreviewTimeoutActive ) {
            g_bMapPreviewCancelCloseRequest = false;
            setTimeout( RequestHidePoiMapPreview, 400 );
            g_bMapPreviewTimeoutActive = true;
         }            
         return;
      }

      if( tempY < g_iMapPreviewPosTop || tempY > g_iMapPreviewPosBottom ){            
         if( ! g_bMapPreviewTimeoutActive ) {
            g_bMapPreviewCancelCloseRequest = false;
            setTimeout( RequestHidePoiMapPreview, 400 );
            g_bMapPreviewTimeoutActive = true;
         }
         return;
      }

      g_bMapPreviewCancelCloseRequest = true;
   }
}

