
// JsLint Global Objects
/*global Ext AV */

if(!AV.MAPS) {AV.MAPS = {}; }
AV.MAPS.LocalSearchMap = function() {

//=============== PRIVATE VARIABLES ========================================================
   
  //$$$$$$$$$$$$$$$ SET TO TRUE FOR PRODUCTION $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
  var enableTokens = true;


  var map = null;           
  var theWhat;
  var theWhere;   
  var searchValue;              //used to record the search value for each search
  
  var mapCenter = null;
  
  var max_zoom_level = 0;       //these are set dynamically based on where the zoom level reached by the Find() method
  var min_zoom_level = 0;       //otherwise, we would end up loading more tiles if we rezoomed after the map loads.
  var z_in_trans_div_top = '75px';
  var z_out_trans_div_top = '105px';
  var minimap_width = '150px';
  var minimap_height = '150px';
  var minimap_trans_width = '145px';
  var minimap_trans_height = '145px';
  var minimap_collapsed_width = '20px';
  var minimap_collapsed_height = '20px';
  var minimap_is_expanded = true;
  var results = null;
  var current_layer = null;
  var current_pin='images/pushpin.png';
  var first_load = true;
  var minimap_yoffset;
  
  var layers = {};
  
  var layer = function(data) {                    
                this.layer = new VEShapeLayer();
                this.populated = false;
                this.name = data.name;
                this.icon = data.icon;
              };
              
  var layer_data = [
    {'name':'restaurant', 'icon':'icon-Restaurants'}, 
    {'name': 'bar', 'icon':'icon-Bars'}, 
    {'name': 'coffee', 'icon':'icon-Coffee-Shops'}, 
    {'name': 'high_school', 'icon':'icon-High-Schools'}, 
    {'name': 'middle_school', 'icon':'icon-Middle-Schools'}, 
    {'name': 'elementary_school', 'icon':'icon-Elementary'}, 
    {'name': 'grocery_store', 'icon':'icon-Grocery-Stores'},
    {'name': 'department_store', 'icon':'icon-Department-Stores'}, 
    {'name': 'book_store', 'icon':'icon-Book-Stores'}, 
    {'name': 'drug_store', 'icon':'icon-Drug-Stores'}, 
    {'name': 'liquor_store', 'icon':'icon-Wine-and-Liquor'}, 
    {'name': 'movie_theater', 'icon':'icon-Movie-Theaters'}, 
    {'name': 'health_club', 'icon':'icon-Health-Clubs'},
    {'name': 'golf_course', 'icon':'icon-Golf-Courses'}, 
    {'name': 'sports_stadium', 'icon':'icon-Sports-Stadiums'}, 
    {'name': 'recreation', 'icon':'icon-Recreation'},
    {'name': 'tourist_attraction', 'icon':'icon-Tourist-Attraction'}, 
    {'name': 'clinic', 'icon':'icon-Clinics'}, 
    {'name': 'hospital', 'icon':'icon-Hospitals'},
    {'name': 'postoffice', 'icon':'icon-Post-Office'}, 
    {'name': 'public_library', 'icon':'icon-Public-Libraries'}, 
    {'name': 'fire_department', 'icon':'icon-Fire-Departments'}, 
    {'name': 'police_department', 'icon':'icon-Police-Departments'}, 
    {'name': 'court', 'icon':'icon-Courts'}, 
    {'name': 'airport', 'icon':'icon-Airports'},
    {'name': 'bank', 'icon':'icon-Banks'}, 
    {'name': 'laundry', 'icon':'icon-Laundry'}, 
    {'name': 'church', 'icon':'icon-Places-of-Worship'}, 
    {'name': 'unlisted', 'icon':''}
  ];                             
            
  for(var i = 0; i < layer_data.length; i++) {
    layers[layer_data[i].name] = new layer(layer_data[i]);
  }                                                           

  //IE 6 Hack
  var image_extension = '.png';
  
  if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
    var ieversion=new Number(RegExp.$1); // capture x.x portion and store as a number
    if (ieversion<7)  { image_extension = '.gif';   }
  }   
  
  //=============== PRIVATE FUNCTIONS ===========================
  function GetMap(map_token) {
  
    map = new VEMap('myMap');             
     
    //Enable For PRoduction ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if((typeof(map_token) !== "undefined") && map_token !== '' && map_token !== null) {       
       map.SetClientToken(map_token);  
    }
    
    var options = new VEMapOptions();
    options.EnableBirdseye = false;
    options.EnableDashboardLabels = true;
    options.LoadBaseTiles = true;
    
    map.LoadMap(null, min_zoom_level, VEMapStyle.Road, 0, VEMapMode.Mode2D, 0, 0, options);                      
    InitUI();    
    
    AttachMapEvents();                                   
    
    //alert('here');  //DOES LOADING THE MAP above count as tiles?
            
    map.Find( theWhat,
              theWhere,
              null,
              null,
              0,
              1,
              false,      //specifies whether the resulting pushpins are visible-
              true,
              false,      //useDefaultDisambiguation --whether the map control displays a disambiguation box when multiple location matches are possible
              true,
              function(layer, resultsArray, places, hasMore, veErrorMessage) {
                        //This callback only gets called if there is a "What" value
                          if(resultsArray) {                             
                          
                            for(var i = 0; i < resultsArray.length; i++) {                            
                                var pin = new VEShape(VEShapeType.Pushpin, resultsArray[i].LatLong);                
                                pin.SetTitle(resultsArray[i].Name);                                
                                pin.SetDescription(GetAssnInfoBoxTemplate(resultsArray[i].Name, resultsArray[i].Description));                       
                                pin.SetCustomIcon(current_pin);                                                                       
                                layer.AddShape(pin);
                            }                                                                          
                            
                            SetZoomLevels();
                           
                          }   
                       });                           
                     
     //Hack to show a pin for non-LocalSearch searches.  The Find() method only shows pins when there is a 
    //"WHAT" value and that WHAT is a "Business".
    if(theWhat === null || theWhat === '') { 
      if(theWhat === null) { map.AttachEvent("onchangeview", AddPin); }
           
      if(first_load === true) {
        first_load = false;       
        //timeout required because the Find() method sets zoom, but has not yet finished.   
        setTimeout("AV.MAPS.LocalSearchMap.setZoomLevels()", 500);
      }  
    }
        
    //Add Layers
    for(var i = 0; i < layer_data.length; i++) {
      map.AddShapeLayer(layers[layer_data[i].name].layer);
    }                         
  }        
  
  //Add Pin for a non-business address (i.e. member address)
  function AddPin() {
    map.DetachEvent("onchangeview", AddPin);
    var pin = new VEShape(VEShapeType.Pushpin, map.GetCenter());    
    
	  if(theWhat && theWhat !== '') {
	    pin.SetTitle(theWhat);
	  }
	  else {
	    pin.SetTitle('Address');
	  }

	  //Ticket 85173 replaced line below with the following line for better positioning
	  //pin.SetCustomIcon('images/pushpin.png');
	  pin.SetCustomIcon("<img src='images/pushpin.png' style='position:relative; top:-16px; left:10px;'");	  
	  pin.SetDescription(GetAssnInfoBoxTemplate('', theWhere));
	  map.AddShape(pin);        	 
  }
  
  function SetZoomLevels() {
    min_zoom_level = map.GetZoomLevel();
    max_zoom_level = min_zoom_level + 1; 
  }
  
  function KeyCheck(e){                         
    //For the keyboard and mouse events, the custom function is executed before the default action is executed. 
    //If the custom function returns false, the default action is executed. 
    //If the custom function returns true, the default action is not executed. 
    //For example, if you have attached the onLeftMouseDoubleClick event, then your custom function is executed first. 
    //If it returns false, the default map behavior, which is to zoom-in, is executed. If it returns true, the zoom-in behavior is disabled.
    var KeyID = (window.event) ? event.keyCode : e.keyCode;   
    switch(KeyID) {   
      case 107: case 187: case 109: case 189:           
        return true;            
        break;                                                
    } 
    
    return false;
  }           
  
  function EndZoomHandler(e) {      //Only allow one zoom
    var z = map.GetZoomLevel();             
    
    var z_in_btn = document.getElementById('z_in_trans_div');   
    var z_out_btn = document.getElementById('z_out_trans_div');   
    var zoomPlusWrapper = document.getElementById('MSVE_navAction_zoomPlusWrapper');
    var zoomMinusWrapper = document.getElementById('MSVE_navAction_zoomMinusWrapper');    
    
    if( z === max_zoom_level ) {        
      //move trasparent div (block zoom)
      z_in_btn.style.top = z_in_trans_div_top;  
      zoomPlusWrapper.style.filter = 'alpha(opacity=40)';   //lessen opacity IE
      zoomPlusWrapper.style.opacity = '0.4';                //lessen opacity FF
      
      //allow zoom out
      z_out_btn.style.top = '0px'; 
      zoomMinusWrapper.style.filter = 'alpha(opacity=100)';
      zoomMinusWrapper.style.opacity = '1.0';
    }
    else{      
                
      z_in_btn.style.top = '0px';       //move trasparent div (unblock zoom in)
      zoomPlusWrapper.style.filter = 'alpha(opacity=100)';
      zoomPlusWrapper.style.opacity = '1.0';
    
      //block zoom out
      z_out_btn.style.top = z_out_trans_div_top; 
      zoomMinusWrapper.style.filter = 'alpha(opacity=40)';  
      zoomMinusWrapper.style.opacity = '0.4';       
    }  
    
    mapCenter = map.GetCenter();  //store Map center              
  }      
  
  // When the mouse is used, the DisableMap function will get called. 
  //Returning true will disable the mousedown event, which disables panning.
  function DisableMap() { return true; }          
  
  function getZoomTransparentDiv(id) {
     var transDiv = document.createElement('div');
     transDiv.setAttribute('id', id);      
     transDiv.style.position = 'absolute';    
     transDiv.style.width = '30px';
     transDiv.style.height = '30px';
     //transDiv.style.filter = 'alpha(opacity: 0.3)'; //setting this causes the clicks to NOT be blocked??
     transDiv.style.zIndex = '1000';
     transDiv.style.top = '0';    
     transDiv.style.left = '0';
     transDiv.style.bottom = '0';  
     
     return transDiv;
  }
  
  function getMinimapTransparentDiv(id) {
     var transDiv = document.createElement('div');
     transDiv.setAttribute('id', id);      
     transDiv.style.position = 'absolute';    
     transDiv.style.width = minimap_trans_width;
     transDiv.style.height = minimap_trans_height;       
     transDiv.style.zIndex = '1000';  
     transDiv.style.left = '0';
     transDiv.style.top = '0';    
     transDiv.style.bottom = '0';  
     transDiv.style.backgroundColor = "#777777";  //without bgcolor, clicks/drags are not blocked in IE??
     transDiv.style.filter = 'alpha(opacity=0)';
     transDiv.style.opacity = '0.0';
     
     return transDiv;
  }
  
  function getMinimapResizeTransparentDiv(id) {
     var transDiv = document.createElement('div');
     transDiv.setAttribute('id', id);      
     transDiv.style.position = 'absolute';    
     transDiv.style.width = minimap_collapsed_width;
     transDiv.style.height = minimap_collapsed_height;        
     transDiv.style.zIndex = '1010';  
     transDiv.style.top = '0';    
     //transDiv.style.bottom = '0';  
     transDiv.style.right = '0';  
     transDiv.style.backgroundColor = "#777777";  //without bgcolor, clicks/drags are not blocked in IE??
     transDiv.style.filter = 'alpha(opacity=0)';
     transDiv.style.opacity = '0.0';
     transDiv.title = 'Hide the mini map';
     //transDiv.attributes.expanded = true;
     
     return transDiv;
  }
  
  function AttachMapEvents(){
    map.AttachEvent("ontokenerror", HandleTokenError);
    map.AttachEvent("ontokenexpire", HandleTokenExpire);
    map.AttachEvent("onendzoom",EndZoomHandler);                                 
    map.AttachEvent("ondoubleclick", DisableMap);
    map.AttachEvent('onkeydown', KeyCheck);     
    map.AttachEvent("onmousewheel", DisableMap);
    map.AttachEvent("onmousedown", DisableMap); 
    
    AV.MAPS.Log.attachLogEvents(map);   
  } 
  
  function HandleTokenError() { alert('Your Map Token is invalid.'); }
  
  function HandleTokenExpire() { alert('Your Map Token has expired'); }
    
  function InitUI() {                
    
    //Add miniMap
    map.ShowMiniMap(0, 0);                              
    
    // Align the position of the Mini Map
    ModifyMiniMap();             
    
    //Add transparent Divs for zoom buttons
    var zoomParentEl = document.getElementById('MSVE_navAction_zoomPlusWrapper').parentElement;                                                               
    zoomParentEl.appendChild(getZoomTransparentDiv('z_in_trans_div'));
    zoomParentEl.appendChild(getZoomTransparentDiv('z_out_trans_div'));
    
    //change zoom titles
    document.getElementById('MSVE_navAction_tinyZoomBar_plus').title = 'Zoom in.';
    document.getElementById('MSVE_navAction_tinyZoomBar_minus').title = 'Zoom out.';
    
    //set zoom button opacity 
    var zoomPlusWrapper = document.getElementById('MSVE_navAction_zoomPlusWrapper');
    zoomPlusWrapper.style.filter = 'alpha(opacity=100)';  //IE
    zoomPlusWrapper.style.opacity = '1.0';                //FF

    var zoomMinusWrapper = document.getElementById('MSVE_navAction_zoomMinusWrapper');
    zoomMinusWrapper.style.filter = 'alpha(opacity=40)';
    zoomMinusWrapper.style.opacity = '0.4';
                  
    //HIDE Compass
    document.getElementById('Compass').style.display = 'none';
    
    //Fixes IE issue where the leftBar does not extend far enough downward--lengthen the leftBackground   
    var leftBgd = document.getElementById('MSVE_navAction_leftBackground');
    leftBgd.style.height = '130px';
    leftBgd.style.padding = '0px 0 0';
  }  
  
  function ModifyMiniMap() {
    // Realign the position of the Mini Map so it appears
    // where we want it 
    var minimap = document.getElementById("MSVE_minimap");          
  
    //set offset
    minimap_yoffset = (GetMapHeight() - minimap.offsetHeight);
    map.ShowMiniMap(0, minimap_yoffset);
    
    //disable mimimap
    minimap.appendChild(getMinimapTransparentDiv('minimap_trans_div'));   
                   
    //move the resize button to the top right
    var minimapResize = document.getElementById("MSVE_minimap_resize");        
    minimapResize.style.top = '4px';
    minimapResize.style.right = '4px';
    minimapResize.style.width = '16px';
    minimapResize.style.height = '16px';
    minimapResize.style.backgroundImage = 'url(images/map-close.gif)';
    
    
    //disable resize functionality and create our own
    var minimap_resize_trans = getMinimapResizeTransparentDiv('minimap_resize_trans_div');    
    minimap.appendChild(minimap_resize_trans);    
    minimap_resize_trans.onclick = toggleMinimap;
    
    //Hide Minimap if the top of MSVE_minimap is less than the 
    //top of MSVE_navAction_zoomMinusWrapper minus the height of MSVE_navAction_zoomMinusWrapper,
    var zoomMinusWrapper = document.getElementById('MSVE_navAction_zoomMinusWrapper');
    if(minimap.offsetTop < zoomMinusWrapper.offsetTop + zoomMinusWrapper.offsetHeight) {
      toggleMinimap();
    }
    
    //Hide "R" and "H" buttons in minimap
    document.getElementById('MSVE_minimap_style_wrapper').style.display = "none";
  }      
  
  function toggleMinimap(e) {
    var minimap = document.getElementById("MSVE_minimap");   
    var minimapResize = document.getElementById("MSVE_minimap_resize"); 
    
    if(minimap_is_expanded === true) {
        minimap.style.width = minimap_collapsed_width;
        minimap.style.height = minimap_collapsed_height;
        minimap.style.top = GetMapHeight() - minimap_collapsed_height.replace(/px/i, '');
        this.title = 'Show the mini map';
        minimap_is_expanded = false;
        minimapResize.style.backgroundImage = 'url(images/map-open.gif)';
        minimapResize.style.top = '0px';
        minimapResize.style.right = '2px';
      }
      else {            
        minimap.style.width = minimap_width;
        minimap.style.height = minimap_height;
        minimap.style.top = minimap_yoffset;
        this.title = 'Hide the mini map';
        minimap_is_expanded = true;
        minimapResize.style.backgroundImage = 'url(images/map-close.gif)';
        minimapResize.style.top = '4px';
        minimapResize.style.right = '4px';
      }
  }
  
  function GetMapHeight() {   
    // Get the Height of the Map as an integer
    return document.getElementById("myMap").offsetHeight;
  }
  
  function GetInfoBoxTemplate(name, address) {
    var template = [];
    var encAddress = encodeURI(address);
    template.push('<div style="background-color: #E4EDF3; padding-left: 5px;">' + address + '</div>');
    template.push('<br/>');
    template.push('<div><a href="http://www.bing.com/maps/default.aspx?where1=' + encAddress + '" target="_blank">Directions</a></div>');
    
    return template.join('');
  }   
  
  function GetAssnInfoBoxTemplate(name, address) {
    var template = [];
    var encAddress = encodeURI(address);
    var image = document.getElementById('assn_img');
    var image_tag = "";
    
    if(image && image.value != '') { image_tag = "<img src=" + image.value + "></img>"; }
    
    template.push('<div style="background-color: #E4EDF3;">' + address + '</div>');
    template.push('<br/>');
    template.push('<div>' + image_tag + '</div>');
    template.push('<div><a href="http://www.bing.com/maps/default.aspx?where1=' + encAddress + '" target="_blank">Directions</a></div>');
    
    return template.join('');
  }         
     
  function Find(what, where) {
    
    searchValue = what;
    
    try {
      results = map.Find(what,
                    where,
                    null,
                    null,
                    0,
                    20,
                    false,      //specifies whether the resulting pushpins are visible--false so that the default pins are not shown and we can add custom pins
                    true,
                    false,      //useDefaultDisambiguation --whether the map control displays a disambiguation box when multiple location matches are possible
                    true,
                    results_call_back);
   }
   catch(e) { alert(e.message); }
  }

  function results_call_back(layer, resultsArray, places, hasMore, veErrorMessage) {    
  
    if(!current_layer) { current_layer = layer; }       

    if(resultsArray) {
    
      //'<div style="padding: 0px 0px 0px 20px;">{Description} <a href="http://www.bing.com/maps/default.aspx?where1={encDescription}" target="_blank"><img src="/images/icons/MapIcon.gif"/></a></div>',
      
      var tpl = new Ext.XTemplate( 
        '<div style="padding: 10px 0px 0px 10px;">',     
          '<h2><span style="FONT-WEIGHT: bold;">Search Value: ' + searchValue + '</span></h2>',  
          '<div style="padding: 10px 0px 0px 0px;"></div>',
          '<tpl for=".">',       
              '<div class="clsBodyText" style="padding: 4px 0px 4px 10px; FONT-WEIGHT: bold;">{#}. {Name}<span style="padding-left: 4px;"class="clsInstructions"> ({dist} miles) </span></div>',  // use current array index to autonumber
              '<div style="padding: 0px 0px 0px 30px;"><a href="http://www.bing.com/maps/default.aspx?where1={encDescription}" target="_blank">{Description}</a></div>',
          '</tpl>',
        '</div>'
      );
         
      //copy array
      var temp_resultsArray = resultsArray.slice(0,resultsArray.length);       
    
      //add the pins and populate Result panel
      for(var i = 0; i < resultsArray.length; i++) {
          var pin = new VEShape(VEShapeType.Pushpin, resultsArray[i].LatLong);                
          pin.SetTitle(resultsArray[i].Name);
          pin.SetDescription(GetInfoBoxTemplate(resultsArray[i].Name, resultsArray[i].Description));              
          //pin.SetMoreInfoURL("http://www.bing.com/maps/default.aspx?where1=" + resultsArray[i].Description);
          //pin.SetLineColor(new VEColor(0,150,100,1.0));
          //pin.SetFillColor(new VEColor(0,100,150,0.5));
          pin.SetCustomIcon(current_pin);                                        
          current_layer.AddShape(pin);          
          
          //calculate relative distance from center of map     
          //var distance = Math.abs(mapCenter.Latitude - resultsArray[i].LatLong.Latitude) + Math.abs(mapCenter.Longitude - resultsArray[i].LatLong.Longitude);
          
          //calculate distance in miles (great circle method)
          //var distance = 3963.1 * Math.acos(Math.sin(mapCenter.Latitude) * Math.sin(resultsArray[i].LatLong.Latitude) + Math.cos(mapCenter.Latitude) * Math.cos(resultsArray[i].LatLong.Latitude) * Math.cos(mapCenter.Longitude - resultsArray[i].LatLong.Longitude));
          
          //calculate distance in miles (great circle method)         NOTE: distances do not take into account the driving route 
          //convert degrees to radians
          var A = mapCenter.Latitude / 57.29577951;
          var B = mapCenter.Longitude / 57.29577951;
          var C = resultsArray[i].LatLong.Latitude / 57.29577951;
          var D = resultsArray[i].LatLong.Longitude / 57.29577951;
          
          var distance = 3963.1 * Math.acos(Math.sin(A) * Math.sin(C) + Math.cos(A) * Math.cos(C) * Math.cos(B - D));
          
          temp_resultsArray[i].dist =  distance.toFixed(2);  //custom property used to sort Results list
          temp_resultsArray[i].encDescription = encodeURI(temp_resultsArray[i].Description);                    
      }
      
      //sort array based on the custom "dist" property of each object, 
      //so that the closest results to the center of the map are displayed first
      temp_resultsArray.sort(function(a, b) { return a.dist - b.dist;} );
      
      tpl.overwrite(Ext.getCmp('panelResults').body, temp_resultsArray, true); 
    }  
    
    //LOG search transaction
    AV.MAPS.Log.writeLogSearchTransaction('1', searchValue);
    searchValue = '';                 
  }

  function search_unlisted() {          
    //clear before searching
    layers['unlisted'].layer.DeleteAllShapes();
    layers['unlisted'].populated = false;
    
    var search_text = document.getElementById('txt_search').value;
    if(search_text !== '') {
      var oSearch = {
                      'checked':      true,
                      'value':        'unlisted',
                      'search_value': search_text,
                      'icon':         'pushpin'                    
                    };
                    
      toggle_search(oSearch);
      //setTimeout("document.getElementById('myMap').focus()", 250);
    }
  }
  
  function clear_unlisted() {
    layers['unlisted'].layer.DeleteAllShapes();
    document.getElementById('txt_search').value = '';
  }                           

  function toggle_search(chk) {
    var objLayer = layers[chk.value];
    
    if(chk.checked === true) {                              
      //Set current layer.  If the layer has not been populated, do the search to populate it 
      //If the check box is unchecked, hide the layer
                
      current_layer = objLayer.layer;
      if(objLayer.populated === false) { 
        Find(chk.attributes ? chk.attributes.search_value.nodeValue : chk.search_value, theWhere);
        objLayer.populated = true; 
        
        if(objLayer.icon === '') { current_pin='images/pushpin.png'; }
        else { current_pin='images/' + objLayer.icon + image_extension; }

      }          
      else { current_layer.Show(); }                   
    }
    else { objLayer.layer.Hide(); }                
  } 
  
  function get_zoom_level() { return map.GetZoomLevel(); }
  
  function set_zoom_level(zoom_level) { map.SetZoomLevel(zoom_level); }
  
  function set_zoom_levels() { SetZoomLevels(); }
  
  function successToken(response, options) {    
    AV.MAPS.Log.setUsedToken(1);
    GetMap(response.responseText); 
  }
  
  function failToken(response, options) { Ext.Msg.alert('Failure', 'Could not get the Bing Token.');  }
  
  /*
  function get_tile_count() { 
    //FOR DEBUGGING/COUNTING TILES
    //Ext.Msg.alert(arTiles.length.toString(), arTiles.join(String.fromCharCode(13)));   
    arTiles = GetUniqueValues(arTiles);
    return arTiles.length; 
  }  
  */
      
  return {
    init: function(strLocation, get_token) {               
    
      if(enableTokens === false) { get_token = enableTokens; }
      
      //SET THE "WHAT" And "WHERE"
      var elAssnName = document.getElementById('assn_name');      
      theWhat = elAssnName ? elAssnName.value : null;      
      theWhere =  strLocation;
      
       //use zip by default if no address information exists
      if( theWhere === '' ) { theWhere = document.getElementById('zip').value; }  
      
      if((typeof(Ext) === "undefined")) {
        GetMap(); //get map without using token
      }
      else {
                          
        Ext.onReady(function() {                                      
          if(get_token === true) {
            //GET TOKEN   //if get_token is true and Ext Exists                                      
            Ext.Ajax.request({
               url: '../BingMaps/GetBingToken.aspx',
               //url: 'GetBingToken.aspx',
               success: successToken,            
               failure: failToken,                       
               params: { assn_id: document.getElementById('assn_id').value }  
            });   
          } 
          else { GetMap(); /*get map without using token */ } 
                                     
        }, this);
              
      }                                       
      
    },
    
    toggleSearch: function(chk) { toggle_search(chk); },
    
    searchUnlisted: function() { search_unlisted(); },
    
    clearUnlisted: function() { clear_unlisted(); },
    
    getZoomLevel: function() { return get_zoom_level(); },
    
    setZoomLevel: function(zoom_level) { set_zoom_level(zoom_level); },
    
    setZoomLevels: function() { set_zoom_levels(); }/*,
    
    getTileCount: function() { return get_tile_count(); }*/
        
  };    
}();

AttachEvent(document, "keypress", captureEnter, false);

function captureEnterFunction() { AV.MAPS.LocalSearchMap.searchUnlisted(); }

//Fix for displaying the tooltip/popup in the right place after scrolling the main window.
Gimme.Screen.getScrollPosition = function() {
  var position = { x: 0, y: 0 };

  // window.pageYOffset is used by Firefox and Mozilla browsers, Safari, Opera, and Konqueror
  if (typeof window.pageYOffset !== 'undefined') {
                  position.x = window.pageXOffset;
                  position.y = window.pageYOffset;
  }
  // document.documentElement.scrollTop is used by IE6 in standards-compliant mode
  else if (!Gimme.Browser.isInQuirksMode && typeof document.documentElement.scrollTop !== 'undefined') {
                  position.x = document.documentElement.scrollLeft;
                  position.y = document.documentElement.scrollTop;
  }
  // document.body.scrollTop is used by IE6 in "Quirks" mode
  else if (typeof document.body.scrollTop !== 'undefined') {
                  position.x = document.body.scrollLeft;
                  position.y = document.body.scrollTop;
  }

  return position;
}; 
  
