/*
  Copyright (c) 2008, Mobox Media Inc. All rights reserved.
*/

var BogoMap = {

  load: function() {
    BogoMap.maxItemsInClusterList = 8;
    BogoMap.defaultZoom = 13;
    BogoMap.mapMarkersByOfferId = {}; // store current points in a hash so markers can be tied to list
    
    BogoMap.icon = new GIcon(G_DEFAULT_ICON);
    BogoMap.icon.image = '/images/MapIcon.png';
    BogoMap.icon.shadow = '/images/MapIcon_shadow.png';
    BogoMap.icon.iconSize = new GSize(16, 24);
    BogoMap.icon.shadowSize = new GSize(28, 24);

    BogoMap.featureIcon = new GIcon(G_DEFAULT_ICON);
    BogoMap.featureIcon.image = '/images/MapIconFeatured.png';
    BogoMap.featureIcon.shadow = '/images/MapIconFeatured_shadow.png';
    BogoMap.featureIcon.iconSize = new GSize(21, 32);
    BogoMap.featureIcon.shadowSize = new GSize(37, 32);

    BogoMap.loadClusterIcons();

    // This flag can be set to false to disable map refresh, e.g. when the map is scrolled automatically to show info window. 
    BogoMap.allowMarkerRefresh = true;
    // This flag can be set to false to ignore the param dloc in the query string (to prevent info bubble from always showing)
    BogoMap.allowDirectLink = true;

    $('map_loading').style.display = 'none';
    $('map_reveal').style.display = 'block';
    // BogoMap.resize();
    Event.observe(window, 'resize', BogoMap.resize);
    if (window.location.search.match('dtype=1')) {
      Bogo.showCouponPanel();
    }
  
    BogoMap.map = new GMap2(document.getElementById("map_canvas"));
    BogoMap.map.addControl(new GLargeMapControl());
    BogoMap.map.addControl(new GMapTypeControl());
    GEvent.addListener(BogoMap.map, "moveend", BogoMap.updateView);
    // $('search_hide').observe("click", BogoMap.toggleSidebar);
    BogoMap.map.setCenter(new GLatLng(BogoMap.centerLat, BogoMap.centerLng), BogoMap.defaultZoom);

    BogoMap.clusterer = new ClusterMarker(BogoMap.map, {clusterMarkerClick:BogoMap.showClusterInfoWindow, numberedIconArray:BogoMap.clusterIcons });
    
    // Force refresh to fix IE display bug (footer disappears)
    if (Prototype.Browser.IE) {
      $('footer').setStyle({'display':'none'});
      $('footer').setStyle({'display':''});
    }    
  },
  
  loadClusterIcons: function () {
    BogoMap.clusterIcons = [];
    var icon;
    for (var i=0; i<=30; i++) {
      icon = new GIcon(G_DEFAULT_ICON);
      icon.image = '/images/clusterIcons/'+i+'.png';
      icon.shadow = '/images/clusterIcons/shadow.png';
      icon.iconSize = new GSize(22, 32);
      icon.shadowSize = new GSize(35, 32);
      BogoMap.clusterIcons.push(icon);
    }
  },
  
  showClusterInfoWindow: function (clickData) {
    BogoMap.allowMarkerRefresh = false;
    BogoMap.clusterer.defaultClickAction=function(){
			BogoMap.map.setCenter(clickData.clusterMarker.getLatLng(), BogoMap.map.getBoundsZoomLevel(clickData.clusterMarker.clusterGroupBounds));
			delete BogoMap.clusterer.defaultClickAction;
	  };
    
    var numMarkers = clickData.clusteredMarkers.length;
    var maxToShow = Math.min(numMarkers, BogoMap.maxItemsInClusterList);
    var clusterHtml = '<div id="clusterWindow"><p><a href="#" onclick="BogoMap.clusterer.defaultClickAction();return false;">Zoom in</a> on these '+numMarkers+' locations.</p>';
    clusterHtml += '<ul>';
    for (var i=0; i<maxToShow; i++) {
      clusterHtml += '<li><a href="#" onclick="BogoMap.clusterer.triggerClick('+clickData.clusteredMarkers[i].index+'); return false;">'+clickData.clusteredMarkers[i].getTitle()+'</a></li>';
    }
    if (numMarkers > maxToShow) {
      clusterHtml += '<li style="list-style-type:none">and '+(numMarkers-maxToShow)+' more...</li>';
    }
    clusterHtml += '</ul></div>';
    clickData.clusterMarker.openInfoWindowHtml(clusterHtml);
    setTimeout(function(){BogoMap.allowMarkerRefresh = true;}, 1000);
  },
  
  /**
    address - {String} accepts address, ZIP, city, etc.
    remember - if true, set lat & long in cookie
  */
  updateLocation: function (address, remember, suppressRedraw) {
    var geoCoder = new GClientGeocoder();
    geoCoder.getLatLng(address, function(point) {
      if (point != null) {
        $('location_field').innerHTML = address;
        
        if (!suppressRedraw) {
          BogoMap.map.setCenter(point, BogoMap.defaultZoom);
          Control.Modal.close();
        }

        if (remember) {
          // address = address.replace(',', '%');
          Cookie.set('default_loc', point.lat() + ':' +point.lng() + ':' + escape(address), 365*24*60*60);
        }
        // Save the map's state after location is set (for when user clicks "return to the last result") 
        BogoMap.saveLocationHandler = GEvent.addListener(BogoMap.map, "moveend", BogoMap.saveMapState);
      } else if (!suppressRedraw) {
        if ($('location_not_found')) {
          $('location_not_found').show();
        }
      }
    });

  },
  
  saveMapState: function () {
    BogoMap.map.savePosition();
    GEvent.removeListener(BogoMap.saveLocationHandler);
  },
  
  // toggleSidebar: function () {
  //   var hideLink = $('search_hide');
  //   $('map_sidebar').toggle();
  //   hideLink.toggleClassName('show');
  //   hideLink.innerHTML = (hideLink.hasClassName('show')) ? "Show" : "Hide";
  //   // BogoMap.scheduleResize();
  //   BogoMap.resize();
  // },
  
  render: function() {
    var marker, mapMarkers = [];
    BogoMap.mapMarkersByOfferId = {};
    var i, offerData;
    
    for (var locationData in BogoMap.mapData) {
      marker = BogoMap.addMarker(BogoMap.mapData[locationData]);
      mapMarkers.push(marker);
      offerData = BogoMap.mapData[locationData].offer_data;
      for (i=0; i<offerData.length; i++) {
        BogoMap.mapMarkersByOfferId[offerData[i].offerId] = marker;      
      }
    }

    BogoMap.clusterer.removeMarkers();
    if (mapMarkers.length > 0) {
      BogoMap.clusterer.addMarkers(mapMarkers);
      BogoMap.clusterer.refresh();
    }
    
  },

  // shows an offer detail modal if one is specified in the URL
  showOfferDetail: function() {
    if (BogoMap.allowDirectLink && window.location.search.match('doff=')) {
      var id = window.location.search.match(/doff=([0-9]+)/)[1];
      var div = $('offering_'+id+'_current');
      if (div) {
        var opts = Bogo.modalOpts;
        opts['href'] = div.title;
        var mod = new Control.Modal(div, opts).open();
      }
      BogoMap.allowDirectLink = false;
    }
  },
  
  addMarker: function(pointData) {
    var icon = (pointData.featured == true) ? BogoMap.featureIcon : BogoMap.icon;
    var marker = new GMarker(new GLatLng(pointData.y, pointData.x), {icon: icon, title: pointData.display_name});
    
    // This will allow an infobubble to be shown automatically
    if (BogoMap.allowDirectLink && window.location.search.match('dloc='+pointData.location_id)) {
      BogoMap.allowMarkerRefresh = false;
      BogoMap.infoWindowMarker = marker;
      new Ajax.Request(
        "/map/location_info_window", 
        { 
          parameters: { 
            location_id: pointData.location_id,
            offering_id: pointData.offerId,
            offering_type: Bogo.offeringShown
          }, 
          onComplete: BogoMap.openInfoWindow, method: 'get'
        }
      ); 
      BogoMap.allowDirectLink = false;
    }
    
    GEvent.addListener(marker, "click", function() {
      BogoMap.allowMarkerRefresh = false;
      BogoMap.infoWindowMarker = marker;
      new Ajax.Request(
        "/map/location_info_window", 
        { 
          parameters: { 
            location_id: pointData.location_id,
            offering_id: pointData.offerId,
            offering_type: Bogo.offeringShown
          }, 
          onComplete: BogoMap.openInfoWindow, method: 'get'
        }
      ); 
      
    });
    GEvent.addListener(marker, "infowindowopen", function() {
      BogoMap.toggleOfferingInSidebar(pointData.offerId);
      Bogo.upgradeModalLinks();
    });
    GEvent.addListener(marker, "infowindowclose", function() {
      BogoMap.toggleOfferingInSidebar(pointData.offerId);
    });
    GEvent.addListener(marker, "mouseover", function() {
      marker.setImage((pointData.featured == true) ? '/images/MapIconFeatured_red.png' : '/images/MapIcon_red.png');
    });    
    GEvent.addListener(marker, "mouseout", function() {
      marker.setImage((pointData.featured == true) ? '/images/MapIconFeatured.png' : '/images/MapIcon.png');
    });    
    return marker;
  },
  
  toggleOfferingInSidebar: function (offering_id) {
    var current_o = $('offering_'+offering_id), recent_o = $('offering_'+offering_id+'_recent');
    if (current_o) { current_o.toggleClassName('highlight'); }
    if (recent_o) { recent_o.toggleClassName('highlight'); }
  },
  
  openInfoWindow: function() {
    BogoMap.infoWindowMarker.openInfoWindowHtml(BogoMap.infoWindowHtml, {'onOpenFn': function(){}});
    BogoMap.infoWindowHtml = '';
    Bogo.upgradeModalLinks();
    Bogo.niftyCorners('.map_info_window');
    setTimeout(function(){BogoMap.allowMarkerRefresh = true;}, 1000);
  },
  
  
  updateView: function(force) { 
    if (BogoMap.allowMarkerRefresh == false || 
       (!force && BogoMap.currentView && BogoMap.currentView.equals(BogoMap.map.getBounds()))) {
      return;
    }
    BogoMap.currentView = BogoMap.map.getBounds(); 
    var center = BogoMap.map.getCenter();
    var span =  BogoMap.currentView.toSpan();  
    BogoMap.updateParameters = {
      sw_lat:   BogoMap.currentView.getSouthWest().lat(),
      sw_lng:   BogoMap.currentView.getSouthWest().lng(),
      ne_lat:   BogoMap.currentView.getNorthEast().lat(),
      ne_lng:   BogoMap.currentView.getNorthEast().lng()
    };
    
    var catSale = $('cat_sale'), catCoupon = $('cat_coupon');
    BogoMap.updateParameters.offering_type = $('offering_type').getValue();
    // var catSaleValue = catSale.getValue();
    // var catCouponValue = catCoupon.getValue();
    // BogoMap.updateParameters.cat_sale = catSaleValue == 'Categories' ? '' : catSaleValue;
    // BogoMap.updateParameters.cat_coupon = catCouponValue == 'Categories' ? '' : catCouponValue;
    var catValue = $('cat').getValue();
    BogoMap.updateParameters.cat = (catValue=='Categories') ? '' : catValue;
    BogoMap.updateParameters.q = $('search').getValue();
    
    if ($('search_calendar_end') && $('search_calendar_end').value.length > 0) {
      BogoMap.updateParameters.to_date = new Date($('search_calendar_end').value).toJSON();
      BogoMap.updateParameters.from_date = new Date($('search_calendar_start').value).toJSON();
    }

    if (!BogoMap.updateRunning) {
      BogoMap.updateRunning = true;
      new Ajax.Request("/map/new_update", {parameters:BogoMap.updateParameters, onComplete: BogoMap.updateDone, method: 'get'}); 
      BogoMap.updateParameters = null;
    }
  },
  
  updateDone: function () {
    if (BogoMap.updateParameters){ 
      BogoMap.updateRunning = true;
      new Ajax.Request("/map/new_update", {parameters:BogoMap.updateParameters, onComplete: BogoMap.updateDone, method: 'get'});      
      BogoMap.updateParameters = null;
    } else {
      BogoMap.updateRunning = false;
    }
  },
  
  // tabSelect: function(tab, panel) {
  //   // $('map_panels').childElements().invoke('removeClassName', 'active');
  //   $(panel).addClassName('active');
  //   $$("#map_tabs .nifty_tab").each(function(t){
  //     if (t.id == tab) {
  //       $(t).className = 'nifty_tab map_selected_tab';
  //     } else {
  //       $(t).className = 'nifty_tab map_unselected_tab';
  //     }
  //   });
  // },
  
  scheduleResize: function(millis) {
    millis = millis || 300;
    setTimeout(function(){ BogoMap.resize(); }, millis);
  },
  
  resize: function() {
    var mapCanvas = $('map_canvas'), mapSidebar=$('map_sidebar');

    if (!mapCanvas || !mapSidebar) {
      return;
    }

    /* heights */
    viewportHeight = document.viewport.getHeight();
    canvasHeight = viewportHeight - $('header').getHeight(); // - $('footer').getHeight();
    mapSidebar.style.height = mapCanvas.style.height = canvasHeight + 'px'; // - $('map_topbar').getHeight() + 'px';

    var dealsList = $('deals_list');
    if (dealsList) {
      var dealListPadding = 30;
      var ieCompensation = Prototype.Browser.IE ? 40 : 0;
      var newDealListHeight = (dealsList.getHeight() + mapSidebar.getHeight() - $('sidebar_content').getHeight() - dealListPadding - ieCompensation);
      // alert("Resizing:\n"+dealsList.getHeight()+'+'+mapSidebar.getHeight()+'-'+$('sidebar_content').getHeight()+'-'+dealListPadding+'-'+ieCompensation+'='+newDealListHeight)
      dealsList.style.height = newDealListHeight+'px';
    }
    
    /* widths */
    // Need to set width for sidebar show/hide functionality
    viewportWidth = document.viewport.getWidth();
    // sidebarWidth = (mapSidebar.visible()) ? mapSidebar.getWidth() : 0;
    // mapCanvas.style.width = (viewportWidth - sidebarWidth) + 'px';
    // mapCanvas.style.marginRight = sidebarWidth;

    /* Firefox scrollbars need a little magic when user resizes */
    if (Prototype.Browser.Gecko) {
      if ($("header").getWidth() > viewportWidth || $("footer").getWidth() > viewportWidth) {
        document.body.parentNode.style.overflow = "auto";
      } else {
        document.body.parentNode.style.overflow = "hidden";
      }
    }
  },
  
	showCommentBox: function() {	
		$('comment_text').show();
		$('comment_user').show();
		$('submit_link').show();
	}
  
};

var Bogo = {
  opacity: 0.8, /* modal */
  debug: false,  

  showChangeLocationForm: function () {
    new Control.Modal($('change_location_modal'), {opacity: Bogo.opacity, ajaxMethod: 'get', onSuccess: Bogo.loadModal, fade: true, fadeDuration: 0.5}).open();
  },

  load: function() {
    var noticeShown = Bogo.openNoticeModal();

    Bogo.modalOpts = {opacity: Bogo.opacity, ajaxMethod: 'get', onSuccess: Bogo.loadModal, fade: true, fadeDuration: 0.5};

    if (!noticeShown && !Cookie.get('default_loc') && $('location_field')) {
      Bogo.showChangeLocationForm();
      // set cookie even if they don't confirm.
      BogoMap.updateLocation($('location_field').innerHTML, true, true);
    } 
    Bogo.niftyCorners();
    Bogo.upgradeModalLinks();
    Bogo.addSearchFormHandlers();
    Bogo.locationEditSetup();
    Bogo.loginHeaderSetup();
    if ($("map_canvas")) {
      BogoMap.load();
    }
    if ($("ie6_fix_canvas") && Prototype.Browser.IE) {
      Bogo.ie6FixCanvasHeight();
      Event.observe(window, 'resize', Bogo.ie6FixCanvasHeight);
    }

  },
  
  addSearchFormHandlers: function () {
    var kws;
    if (kws = $('keyword_search')) {
      kws.observe('submit', function(evt){
        Event.stop(evt);
        BogoMap.updateView(true);
      });
    }
  },
  
  addAutoComplete: function () {
    //new Ajax.Autocompleter(id_of_text_field, id_of_div_to_populate, url, options);
  },
  
  ie6FixCanvasHeight: function() {
    if (!$('header') || !$('footer')) { return; }
    canvasHeight = document.viewport.getHeight();
    canvasHeight -= $('header').getHeight();
    canvasHeight -= $('footer').getHeight();
    $("ie6_fix_canvas").style.height = canvasHeight + 'px';
  },
  
  openNoticeModal: function() {
    if (notice_div = $("notice")) {
      notice_div.hide();
      Control.Modal.open(notice_div.innerHTML, {opacity: Bogo.opacity});
      return true;
    } else {
      return false;
    }
  },
  
  upgradeModalLinks: function() {
    var opts = Bogo.modalOpts;
    $$("a.modal").each(function(link){
      var mod = new Control.Modal(link, opts);
    });
    // Sidebar offers:
    $$("div.offering").each(function(div){
      // Add Modal
      opts['href'] = div.title;
      var mod = new Control.Modal(div, opts );
      // Add hover
      var title = div.title;
      if (title) {
        var offerId = title.match(/[0-9]+$/)[0];
        var marker = BogoMap.mapMarkersByOfferId[offerId];
        var icon = marker.getIcon();
        div.observe('mouseover', function (evt) {
          try { // markers won't be present on map if they're clustered
            marker.setImage((icon==BogoMap.featureIcon) ? '/images/MapIconFeatured_red.png' : '/images/MapIcon_red.png');
          } catch (e) {}
        });
        div.observe('mouseout', function (evt) {
          try {
            marker.setImage((icon==BogoMap.featureIcon) ? '/images/MapIconFeatured.png' : '/images/MapIcon.png');
          } catch (e) {}
        });
        // NOTE no longer used -- can't pop info bubbble when markers are clustered
        // var locationId = title.match(/location_id=([0-9]+)/)[1];
        // div.observe('click', function (evt) {
        //   BogoMap.infoWindowMarker = marker;
        //   BogoMap.allowMarkerRefresh = false;
        //   new Ajax.Request("/map/location_info_window", {parameters:
        //     {location_id:  locationId, offering_id: offerId}, onComplete: BogoMap.openInfoWindow, method: 'get'}); 
        // });
      }
    });

    // need to resize in case the extra content has added a scrollbar to the view.
    BogoMap.resize();
  },

  loadModal: function() {
    Bogo.upgradeModalLinks();
    Bogo.niftyCorners('#modal_container');
  },  
  
  niftyCorners: function(base) {
    if (!base) {
      // Nifty("#identity", "bl");
      Nifty("#offering_footer", "big br bl");
      base = 'html';
    }
    Nifty(base + " .nifty");
    Nifty(base + " .nifty_top", "top");
    Nifty(base + " .nifty_bottom", "bottom");
    Nifty(base + " .nifty_big_transparent", "big transparent");
    
    if (!(Prototype.Browser.IE && window.navigator.userAgent.match(/MSIE\s+7/))) {
      // IE7 sees bad rendering bugs in the tab layout if this is used. Just skip it.
      Nifty(base + " .nifty_small_transparent", "small transparent");
    }
    Nifty(base + " .nifty_tab", "transparent top");
    Nifty(base + " .same_height", "same-height none");
  },
  
  locationEditSetup: function () {
    if ($('location_field')) {
      var locationEditor = new Ajax.InPlaceEditor( $('location_field'), 
                                                    '/map/location_edit_in_place', 
                                                    { ajaxOptions: {},
                                                      externalControl: $('change_location'), 
                                                      highlightcolor: '#555555', 
                                                      highlightendcolor: '#333333', 
                                                      onComplete: function(transport, element) {
                                                        if (transport) {
                                                          BogoMap.updateLocation(transport.responseText, true);
                                                        }
                                                      }
                                                    });
    }
  },
  
  loginHeaderSetup: function () {
    Bogo.emailField = $$('#header_login input[type="text"]')[0];
    Bogo.passwordField = $$('#header_login input[type="password"]')[0];
    if (Bogo.emailField && Bogo.passwordField) {
      Bogo.defaultEmail = Bogo.emailField.value;
      Bogo.defaultPassword = Bogo.passwordField.value;
      $$('#header_login input').each(function(input){
        input.observe('focus', Bogo.clearLoginDefaults);
      });
      $$('#header_login input').each(function(input){
        input.observe('blur', Bogo.setLoginDefaults);
      });
    }
  },
  
  clearLoginDefaults: function () {
    if (Bogo.emailField.value==Bogo.defaultEmail && Bogo.passwordField.value==Bogo.defaultPassword) {
      $$('#header_login input').invoke('clear');
    }
  },
  
  setLoginDefaults: function () {
    if (Bogo.emailField.value=='' && Bogo.passwordField.value=='') {
      Bogo.emailField.value = Bogo.defaultEmail;
      Bogo.passwordField.value = Bogo.defaultPassword;
    }
  },
  
  // Calendar UI widget for search sidebar
  displayDateSelected: function () {
    var start = $('search_calendar_start').value;
    var end = $('search_calendar_end').value;
    var result = '';
    if (start && start.length > 0) { result += 'Starting: '+start+'<br>'; }
    if (end && end.length > 0) { result += 'Ending: '+end; }
    $('date_selected').innerHTML = result;
    if (result.length > 0) {
      $('date_selected').show();
      $('search_calendar_clear').show();
    } else {
      $('date_selected').hide();
      $('search_calendar_clear').hide();
    }
  },
  
  text_field_clear: function(id) {
	  var textField = $(id);
	  if (textField) {
	    var defaultURLText = textField.value;
	    textField.observe('focus', function () {
	      if (textField.value == defaultURLText) { textField.value = ''; }
	    });
	    textField.observe('blur', function () {
	      if (textField.value == '') { textField.value=defaultURLText; }
	    });
	  }
  },
  
  showCouponPanel: function () {
    var couponTab = $('coupons'), couponPanel = $('coupon_panel');
    var salesTab = $('sales'), salesPanel = $('sales_panel');
    var offeringType = $('offering_type');
    couponTab.addClassName('active');
    salesTab.removeClassName('active');
    salesPanel.hide();
    couponPanel.show();
    offeringType.setValue(Bogo.couponType);
  },
  
  showSalePanel: function () {
    var couponTab = $('coupons'), couponPanel = $('coupon_panel');
    var salesTab = $('sales'), salesPanel = $('sales_panel');
    var offeringType = $('offering_type');
    couponTab.removeClassName('active');
    salesTab.addClassName('active');
    salesPanel.show();
    couponPanel.hide();
    offeringType.setValue(Bogo.saleType);
  }

};

//Event.observe(window, 'load', Bogo.load);
