var BankLocationWidgetVars = {
  bank_url:"",
  bank_hq:"",
  map_city:"",
  map_state:"",
  map_zip:"",
  center_lat:"",
  center_lon:""
};

var BankLocationsWidget = (function() {

  var map, baseIcon;
  var mapWidgetCoordinates = null;
 
  // Create a map object 
 
  function enableMap() {
   
    baseIcon = new GIcon(G_DEFAULT_ICON);  
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);   
    
    map = new google.maps.Map2(document.getElementById("map_canvas"));
  
  }
 
  function centerMapToLocation(address, zoom, callbackFn) {

    geocoder = new GClientGeocoder();
    geocoder.getLatLng(address, function(point) {
      map.setCenter(point,zoom);
      if (callbackFn) {
        callbackFn();
      }
    });
  }

  // Center map to default (entire US) 
  function defaultCenterMap() {
    map.setCenter(new google.maps.LatLng(38, -99.5), 3);
  }


  // Do any map UI setup/postprocessing 
  function setupBankLocationsMap(disableDragging) {

    var customUI = map.getDefaultUI();
    customUI.controls.menumaptypecontrol = false;
    // customUI.controls.scalecontrol = false;
    map.setUI(customUI);

    map.disableScrollWheelZoom();
    if (disableDragging) {
      map.disableDragging();
    }

  }


  function createMarker(point, content) {
    // Create a lettered icon for this point using our icon class

    var letteredIcon = new GIcon(baseIcon);

    // Set up our GMarkerOptions object
    markerOptions = { icon:letteredIcon };
    var marker = new GMarker(point, markerOptions);

    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(content);
   
    });
    return marker;

  }


  /* Get initial branch data from HTML table and plot on map
   * "autoResize" arg determines if map bounds/zoom should be auto calculated

   */
  function initBankLocations(autoZoom, autoCenter) {
    //map = new google.maps.Map2(document.getElementById("map_canvas"));

    if (!autoZoom) autoZoom = false;
    if (!autoCenter) autoCenter = false;

    if (autoCenter) {
      map.setCenter(new GLatLng(BankLocationWidgetVars.center_lat, BankLocationWidgetVars.center_lon), 13);
   
    }

    setupBankLocationsMap(false);
 
 
    // Keep track of map bounds
    var bounds = map.getBounds();
  
    // Get branches from hidden HTMl table
    var branches = $("table#widget_bank_map_locations tr");
    branches.each( function(i) {
  
      var lat = parseFloat($(this).find('.lat').html());
      var lng = parseFloat($(this).find('.lng').html());
      var branch_name = $(this).find(".branch_name").html();
      var address1 = $(this).find(".address1").html();
      var address2 = $(this).find(".address2").html();
   
      var point = new GLatLng(lat,lng);
      bounds.extend(point);

      var content = '<div class="branch_info_bubble"><h3 class="branch_name">'+branch_name+'</h3> <p class="address1">'+address1+'</p> <p class="address2">'+address2+'</p> </div>';

      marker = createMarker(point, content);
      map.addOverlay(marker);
  
    });
 
    if (autoZoom) {
      map.setZoom(map.getBoundsZoomLevel(bounds));
      if (autoCenter)
        map.setCenter(bounds.getCenter());
    }
    map.enableDragging();
  }




  function bankLocationsSearch() {
    geocoder = new GClientGeocoder();
    geocoder.setBaseCountryCode('us');
    //var address = document.getElementById('map_widget_location').value;
    var address = $("#map_widget_location").val();
 
    //$("#bank-map-widget .location_input_box").hide("slide", { direction: "down" }, 300);
    geocoder.getLocations(address, submitNewMapLocation);
  
  }


  function submitNewMapLocation(response) {
    decodedLocation = GeocoderUtils.decodeGeocoderResponse(response);
    gPoint = GeocoderUtils.getLatLngFromGeocoderResponse(response);
    if (gPoint) {
      mapWidgetCoordinates = gPoint;

    }
   
    data = {}
    //$("#map_widget_location").val("");
   
    if (decodedLocation) {
      data.bank_url = BankLocationWidgetVars.bank_url;
      data.city = decodedLocation['city'];
      data.state = decodedLocation['state'];
      data.zip = decodedLocation['zip'];

      BankLocationWidgetVars.map_city = data.city;
      BankLocationWidgetVars.map_state = data.state;
      BankLocationWidgetVars.map_zip = data.zip;

     
      $.getJSON("/ajax/get-bank-locations-widget.json", data, doneGetBankLocations);
      fadeInWidgetMapBusyOverlay(100);
        
        
      if (bankPageType == "main"  ) {
        if (bankProductMix != "national") {
          $.getJSON("/ajax/get-bank-rate-tables.json", data, BankPage.doneGetBankRateTables);
          //fadeInBankRatesOverlay(100);

          $.getJSON("/ajax/get-bank-update-feed.json", data, BankUpdateFeed.doneGetBankUpdateFeed);
        }
      }
        

    }


  }

  /* Process AJAX data from server and plot new branches */
  function doneGetBankLocations(data, textStatus) {
  
    var city = BankLocationWidgetVars.map_city;
    var state = BankLocationWidgetVars.map_state;
    var zip = BankLocationWidgetVars.map_zip;

    var location_str = "";
    var state_only = false;
    if (zip) {
      location_str = zip;
    } else if (city) {
      location_str = city + ", " + state;
    } else if (state) {
      location_str = Constants.STATE_NAMES_MAP[state];
      state_only = true;
    }

    // Change the user-location notice
    var user_location_box = $("#user-location");
    var loc_text = user_location_box.find("span.text");
    if (zip) {
      loc_text.html("Selected zip:")
        } else {
      loc_text.html("Selected location:")
        }
 
    user_location_box.find("a.location").html(location_str);
    user_location_box.show();

    new_location = { city: city,
                     state: state,
                     zip: zip };

    JSONCookies.create('location', new_location, 7);
  

    branches = data.branches;
 
    // Truncate location string for widget box a bit
    widget_location_str = Utils.truncateNice(location_str, 22);
    if (branches.length > 0) {
      $("#bank-map-widget .curr_location_box.show a.location").html(widget_location_str);
      $("#bank-map-widget .curr_location_box.show a.location").removeClass('defaultTextActive');
      // Found some branches, now plot them
   
      map.setCenter(new GLatLng(data.center_lat, data.center_lon), 13);
      map.clearOverlays();

      // Keep track of map bounds
      var bounds = map.getBounds();

      for (var i = 0; i < branches.length; i++) {
        branch = branches[i];
        var point = new GLatLng(branch.lat, branch.lon);
        bounds.extend(point);
        var content = '<div class="branch_info_bubble"><h3 class="branch_name">'+branch.name+'</h3> <p class="address1">'+branch.address+'</p> <p class="address2">'+branch.address2+'</p> </div>';

        marker = createMarker(point, content);
        map.addOverlay(marker);
          
      }
      map.setZoom(map.getBoundsZoomLevel(bounds));
      map.setCenter(bounds.getCenter());
  
      //$("#bank-map-widget .location_input_box").hide();
      //$("#bank-map-widget .curr_location_box").show();
     


      var input_box = $("#bank-map-widget .location_input_box");
      var curr_loc_box = $("#bank-map-widget .curr_location_box.show");

      /*
        input_box.hide("slide", { direction: "down" }, 200, function() {
          curr_loc_box.show("slide", { direction: "down" }, 200);
          });
      */
    
      mapWidgetHeaderFadeOut(input_box, 200, function() {
        curr_loc_box.show("slide", {direction: "down"}, 200);
      });
    

    } else {

      map.clearOverlays();
      var zoomLevel = (state_only) ? 5: 12

        map.setCenter(mapWidgetCoordinates, zoomLevel);

      var input_box = $("#bank-map-widget .location_input_box");
      var curr_loc_box_none = $("#bank-map-widget .curr_location_box.none");
   


      //curr_loc_box_none.find("a.location").html("( " + location_str + " )");
      curr_loc_box_none.find("a.location").html(widget_location_str);
      mapWidgetHeaderFadeOut(input_box, 200, function() {
        curr_loc_box_none.show("slide", {direction: "down"}, 200);
      });

    }
    map.enableDragging();
    fadeOutWidgetMapBusyOverlay();
  }


  function showMapWidgetInput() {

    var location_header = $("#bank-map-widget div.location_header");
    var curr_loc_box = $("#bank-map-widget .curr_location_box:visible");
    var input_box = $("#bank-map-widget .location_input_box");

 
    var callback = function() {
      var input = $("input#map_widget_location");
   
      if (input.val() != input.attr('title')) {
        input.select();
      
      } else {
        //input.addClass('defaultTextActive');
        input.focus();
        //input.blur();
      }
    };
 
    mapWidgetHeaderFadeTransition(curr_loc_box, input_box, 100, 100, callback                            
                                 );
  }


  function mapWidgetHeaderFadeTransition(outgoingElem, incomingElem, fadeInSpeed, fadeOutSpeed, preCallBackFn) {
    var location_header = $("#bank-map-widget div.location_header");
    fadeOverlay = UI.makeOverlayDivExact(location_header, "#bank-map-widget", "transparent", 0, 0, 0, 0, 1.0, true);
    fadeOverlay.addClass('map_widget_loc_overlay');
    fadeOverlay.fadeIn(fadeInSpeed, function() {
      outgoingElem.hide();
      incomingElem.show();
      if (preCallBackFn) {
        preCallBackFn();
      }
    
      $(this).fadeOut(fadeOutSpeed);
    
    });
  }

  function mapWidgetHeaderFadeOut(elem, speed, callBackFn) {
    var location_header = $("#bank-map-widget div.location_header");
    fadeOverlay = UI.makeOverlayDivExact(location_header, "#bank-map-widget", "transparent", 0, 0, 0, 0, 1.0, true);
    fadeOverlay.addClass('map_widget_loc_overlay');
    fadeOverlay.fadeIn(speed, function() {
      elem.hide();
      $(this).remove();
      if (callBackFn) {
        callBackFn();
      }
    });
  }

  function fadeInWidgetMapBusyOverlay( speed ) { 
    var map = $("div#map_canvas")
 

      var busyOverlay = UI.makeOverlayDivExact(map, "#bank-map-widget", "white", 
                                               0,0,0,0, 0.5, true);
    busyOverlay.addClass('map_widget_busy_overlay');
    busyOverlay.fadeIn( speed );

  
  }

  function fadeOutWidgetMapBusyOverlay( speed) {
    $("div.map_widget_busy_overlay").fadeOut(speed, function() { $(this).remove();  });
  }


  return {
    //    init: init,
    enableMap: enableMap,
    centerMapToLocation: centerMapToLocation,
    defaultCenterMap: defaultCenterMap,
    initBankLocations: initBankLocations,
    bankLocationsSearch: bankLocationsSearch,
    showMapWidgetInput: showMapWidgetInput
  }

})();

