window.BOA = {
    data: null,
    markers: [],
   
   default_page: 'nearest', 
   current_page: '',
   default_content_type: 'bc',
   current_content_type: '',
   widget_id: null,
   widget_visible: true,
   direction_pattern: 'http://maps.google.com/maps?f=d&source=s_d&saddr=#from_lat#+#from_lng#&daddr=#to_lat#+#to_lng#',
   carousel : null,
   

    setWidgetId: function(widget_id) {
		BOA.widget_id = widget_id;
	},
	
	init: function(data) {
		BOA.data = data;
		BOA.container = $('#boa-container');
		BOA.addEventListeners();
		BOA.changeDisplayPage();
    if(window.page.getCookie('boa_checkbox') == "true")
    {
      BOA.toggleMarkers(true);
      $('#boa_toggle').attr('checked','checked');
    }
    window.page.fireEvent(window.page.Events.WIDGET_RESIZED, BOA.widget_id);
	},
	
	addEventListeners: function() {
		$('#boa-current-page').click(BOA.showPageSelector);
		$('input[name="content-type"]', BOA.container).click(BOA.chnageContentType);
		$('#boa-pages-selector li').click(function(){
	      $('#boa-pages-selector li').removeClass('active-item');
	      $(this).addClass('active-item');
	      $('#boa-pages-selector').hide();
	      $('#boa-current-page').html($(this).html());
	      BOA.changeDisplayPage($(this).attr('page'));
		});
		$(document.body).click(function(event){
       
			if (event.target.id != 'boa-current-page' 
					&& !$('#boa-pages-selector').find(event.target).length
					&& $('#boa-pages-selector').is(':visible')
					) {
				$('#boa-pages-selector').slideUp();
			}
			return true;
		});
		$('#boa_toggle').click(function(){
		  window.page.setCookie('boa_checkbox',$(this).attr('checked'));
		  BOA.toggleMarkers($(this).attr('checked'));
		});
		
		page.addEventListener(page.Events.WIDGETS_COLUMN_CHANGED, BOA.onOrderChanged);
		page.addEventListener(page.Events.WIDGET_EXPANDED, BOA.onWidgetExpanded);
		page.addEventListener(page.Events.WIDGET_COLLAPSED, BOA.onWidgetCollapsed);
	},
	
	toggleMarkers: function(checked) {
	  (checked) ? BOA.showMarkers() : BOA.hideMarkers();
	},
  
	onWidgetExpanded: function(widget_id) {
		if (widget_id == BOA.widget_id) {
			BOA.widget_visible = true;
			if (BOA.need_recalc) {
				BOA.recalcCarousel();
				BOA.need_recalc = false;
			}
		}
	},
	
	onWidgetCollapsed: function(widget_id) {
		if (widget_id == BOA.widget_id) {
			BOA.widget_visible = false;
		}
	},
	
	onOrderChanged: function(widget_id) {
		if (widget_id == BOA.widget_id) {
			if (BOA.widget_visible) {
				BOA.recalcCarousel();
			}else{
				BOA.need_recalc = true;
			}
		}
	},
	
  recalcCarousel: function() {
		BOA.changeDisplayPage();
  },
  
  getDirection: function(index, type) {
    if (type in BOA.data) {
      if (index < BOA.data[type].length) {
        var to = BOA.data[type][index];
        var from = window.t_location;
        var url = BOA.direction_pattern.replace('#from_lat#', from.latitude)
                    .replace('#from_lng#', from.longitude)
                    .replace('#to_lng#', to.longitude)
                    .replace('#to_lat#', to.latitude);
       window.open(url);
      }
    }
  },
  
  
  changeDisplayPage: function(page) {
     
     if (page == undefined) {
       page = BOA.current_page?BOA.current_page:BOA.default_page;
     }
     
     switch (page) {
       case 'nearest':
         BOA.showNearest();
         break;
       case 'services':
         BOA.showServices();
         break;
       case 'about':
         BOA.showAbout();
         break;
      case 'search':
         BOA.showSearchForm();
         break;
       default:
         BOA.changeDisplayPage(BOA.default_page);
     }
  },
  
  showNearest: function(content_type) {
    if (content_type == undefined) {
      content_type = BOA.current_content_type?BOA.current_content_type:BOA.default_content_type;
    }
    switch (content_type) {
      case 'bc':
        BOA.showBankingCenters();
        $('#content-type-bc').attr('checked', true);
        break;
      case 'atm':
        BOA.showAtms();
        $('#content-type-atm').attr('checked', true);
        break;
      default:
        BOA.showNearest(BOA.default_content_type);
    }
    BOA.current_page = 'nearest';
  },
  
  showServices: function() {
    BOA.setHeader('Contact Us');
    $('#boa-content').html($('#services_pattern').html());
    BOA.current_page = 'services';
  },
  
  showAbout: function() {
    BOA.setHeader('About Bank of America');
    $('#boa-content').html($('#about_pattern').html());
    BOA.current_page = 'about';
  },
  
  showPageSelector: function() {
    $('#boa-pages-selector').slideToggle();
  },
  
  chnageContentType: function() {
    //$('#boa_toggle').attr('checked','checked');
    BOA.showNearest($(this).val());
  },
  
  showSearchForm: function() {
    BOA.setHeader('Search Location');
    var c = $('#boa-content');
    c.html($('#search_pattern').html());
    BOA.current_page = 'search';
    $('.search-from', c).submit(BOA.chnageLocation);
    $('.back-to-nearest', c).click(BOA.returnToNearest);
    
  },
  
  chnageLocation: function() {
    return false;
  },
  
  returnToNearest: function() {
    return false;
  },

  setItemNumber: function(carousel, item, index, state) {
    $('#boa-cur-item').html(index);
  },
  
  showAtms: function() {
	var markers = [];
    if ('atm' in BOA.data && BOA.data.atm.length) {
      var header = 'Nearest locations - showing <span id="boa-cur-item">1</span> of ' + BOA.data.atm.length;
      $('#boa-content').html('<div class="boa-carousel-container"><ul class="boa-carousel"></ul></div>');
      var size = $('#boa-content').width();
      $('.boa-carousel-container', BOA.container).css('width', size);
      var c = $('.boa-carousel', BOA.container);
      var pattern = $('#atm_item_pattern').html();
      
      for (var i=0;i<BOA.data.atm.length;i++) {
      	var html = pattern.replace('#distance#', BOA.data.atm[i].distance)
          .replace('#street#', BOA.data.atm[i].address.street)
          .replace('#city#', BOA.data.atm[i].address.city)
          .replace('#state#', BOA.data.atm[i].address.stateProv)
          .replace('#postal_code#', BOA.data.atm[i].address.postal)
          .replace('#index#', i);
          c.append(html);
          if(BOA.data.atm[i].hours_24 != undefined && BOA.data.atm[i].hours_24 == 'Y')
          {
            $('#open_24h').show();
          }
          else
          {
            $('#open_24h').hide();
          }

           markers.push({
            lat: BOA.data.atm[i].latitude,
            lng: BOA.data.atm[i].longitude
          });
      }
      $('li', c).css('width', size);
      c.jcarousel({
        itemVisibleInCallback: BOA.setItemNumber,
        size: BOA.data.atm.length,
        scroll: 1
      });
    }else{
      var header = 'Nearest locations - no banking centers';
      $('#boa-content').html('No ATM\'s for this location');
    }
    
    BOA.setHeader(header);
    BOA.addMarkers(markers, BOA.getAtmIcon());
    BOA.current_content_type = 'atm';
  },
  
  showBankingCenters: function() {
	var markers = [];
    if ('bc' in BOA.data && BOA.data.bc.length) {
      var header = 'Nearest locations - showing <span id="boa-cur-item">1</span> of ' + BOA.data.bc.length;
      $('#boa-content').html('<div class="boa-carousel-container"><ul class="boa-carousel"></ul></div>');
      var size = $('#boa-content').width();
      $('.boa-carousel-container', BOA.container).css('width', size);
      var c = $('.boa-carousel', BOA.container);
      var pattern = $('#bc_item_pattern').html();
      

      for (var i=0;i<BOA.data.bc.length;i++) {
      	var html = pattern.replace('#distance#', BOA.data.bc[i].distance)
          .replace('#street#', BOA.data.bc[i].address.street)
          .replace('#city#', BOA.data.bc[i].address.city)
          .replace('#state#', BOA.data.bc[i].address.stateProv)
          .replace('#postal_code#', BOA.data.bc[i].address.postal)
          .replace('#lobby#', BOA.data.bc[i].lobby)
          .replace('#index#', i)
          .replace('#width#', size);
          
          if(BOA.data.bc[i].is_by_appointment == 'Y')
          {
            html = html.replace('#appointment_link#',BOA.data.bc[i].is_by_appointment_url);
          }

          c.append(html);
          
          if(BOA.data.bc[i].is_by_appointment == undefined || BOA.data.bc[i].is_by_appointment == 'N')
          {
            $('.delim',c).remove();
          }

          markers.push({
            lat: BOA.data.bc[i].latitude,
            lng: BOA.data.bc[i].longitude
          });
      }
      $('li', c).css('width', size);
      
      c.jcarousel({
        itemVisibleInCallback: BOA.setItemNumber,
        size: BOA.data.bc.length,
        scroll: 1
      });
    }else{
      var header = 'Nearest locations - no banking centers';
      $('#boa-content').html('No banking centers for this location');
    }
    
    BOA.setHeader(header);
    BOA.addMarkers(markers, BOA.getBCIcon());
    BOA.current_content_type = 'bc';
  },
  
  getAtmIcon: function() {
    var icon = new GIcon();
    icon.image  = '/images/atm_icon.gif';
    icon.iconSize = new GSize(30, 15);
    icon.iconAnchor = new GPoint(15, 15);
    return icon;
  },
  
  getBCIcon: function() {
    var icon = new GIcon();
    icon.image  = '/images/atm_icon.gif';
    icon.iconSize = new GSize(30, 15);
    icon.iconAnchor = new GPoint(15, 15);
    return icon;
  },
  
  setHeader: function(text) {
    $('#boa-content-header').html(text);
  },
  
  addMarkers: function(markers, icon) {
    /*bounds = new GLatLngBounds();
    bounds.extend(new GLatLng(t_location.latitude,t_location.longitude));*/
    for (var i=0;i<BOA.markers.length;i++) {
    	map.removeOverlay(BOA.markers[i]);
    }
    BOA.markers = [];
    
    for (var i=0;i<markers.length;i++) {
    	var latlng = new GLatLng(markers[i].lat, markers[i].lng)
    	//bounds.extend(latlng);
    	var marker = new GMarker(latlng,{"icon": icon});
    	//map.addOverlay(marker);
    	BOA.markers.push(marker);
    }
    /*map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());*/
    if ($('#boa_toggle').attr('checked')) {
    	BOA.showMarkers();
    }
  },
  
  showMarkers: function()
  {
    bounds = new GLatLngBounds();
    bounds.extend(new GLatLng(t_location.latitude,t_location.longitude));
    for (var i=0;i<BOA.markers.length;i++) {
      map.removeOverlay(BOA.markers[i]);
    }
    
    for (var i=0;i<BOA.markers.length;i++) {
      bounds.extend(BOA.markers[i].getLatLng());
      map.addOverlay(BOA.markers[i]);
    }
    
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());
  },
  
  hideMarkers: function()
  {
    for (var i=0;i<BOA.markers.length;i++) {
      map.removeOverlay(BOA.markers[i]);
    }
    
    map.setCenter(window.t_location.latitude, window.t_location.longitude);
  }
};
