/**
 * Assists Google Map rendering in Hours And Directions Map Locator widget
 */

HoursAndDirectionsMapLocator.prototype = new MapLocator();

function HoursAndDirectionsMapLocator() {
  // holds the reference to the current instance object
  var that = this;
  var markerPath = null;  
  var noDeptInfoFlag = false;
  var OVERLAY_RIGHT_PX = 10;
  
  this.loadMap = function() {
    initialize();
    zoomAndPanMap();    
  };
  
  this.loadDealershipOverlay = function() {
    that.addDealershipOverlay("hoursAndDirectionsOverlay");
    applyOverlayStyles();
    jQuery(document).ready(resizeHoursAndDirectionsOverlay);      
    PortalPopup.popupReady();
    // bindScrollbarEvents();    
    bindEventGetDirection();
    moveCenterOfMap();
  };

  this.setMarkerPath = function(redMarkerPath) {
    markerPath = redMarkerPath;
  };
  
  var initialize = function() {
    /* Assign values from hidden input fields */
    var latitude = jQuery('#latitude').val(), 
        longitude = jQuery('#longitude').val();

    /* If input fields are unavailable, assign values from ContextManager */
    if (latitude.length === 0 && longitude.length === 0 && typeof ContextManager !== 'undefined') {
      latitude = ContextManager.latitude;
      longitude = ContextManager.longitude;
    }
    
    that.firstLocationsLatLng = new GLatLng(latitude, longitude);
    that.currentLatLng = new GLatLng(latitude, longitude);
    if (GBrowserIsCompatible()) {
      var siteLabel = getSiteNameMapOverlay();
      that.setMapDefaults();      
      that.map.addOverlay(createMarker(that.firstLocationsLatLng));
      that.map.addOverlay(siteLabel);
      repostionLongSiteName(siteLabel);      
    }    
  };
  
  var zoomAndPanMap = function() {
    that.map.setZoom(parseInt(jQuery('#zoomLevel').val()));
  };

  /**
   * Place the marker pin in the map as per dealer location's latitude
   * and longitude
   */   
  var createMarker = function(point) {    
    var markerIcon = new GIcon(G_DEFAULT_ICON);
    markerIcon.image = markerPath;
    var markerOptions = {
      icon : markerIcon
    };
    var marker = new GMarker(point, markerOptions);    
    return marker;
  };

  /**
   * Bind scrollbar events
   */
  var bindScrollbarEvents = function() {
    if(this.noDeptInfoFlag) {
      return;
    }
    var hoursAndDirectionsBottomObj = jQuery('#hoursAndDirections_Container');
    hoursAndDirectionsBottomObj.mouseover(function() {
      CustomScroller.setScrollAreaActive('hoursAndDirections');
    });
    
    // In-activate the scroll area
    hoursAndDirectionsBottomObj.mouseout(function() {
      CustomScroller.setScrollAreaInactive('hoursAndDirections');
    });

    // onclick event for the scroll bar track allows the scroll action.
    jQuery('#hoursAndDirections_GripperContainer').click(function(event) {
      CustomScroller.scrollBarTrackClick('hoursAndDirections', event);
    });

    // Start scrolling action on mouse down of the scroll bar gripper.
    jQuery('#hoursAndDirections_Drag').mousedown(function(event) {
      CustomScroller.scrollBarDragStart(event, this.id);
    });

    // Set the scroll's height.
    CustomScroller.setScrollbarHeight('hoursAndDirections');
  };

  /**
   * Resizes the Hours And Departments Overlay.
   */
  var resizeHoursAndDirectionsOverlay = function() {    
    var customScrollHeight = 0;
    var hoursAndDirectionsOverlayObj = jQuery('#hoursAndDirectionsOverlayContent');
    var hoursAndDirectionsTopObj = jQuery('#hoursAndDirectionsTop');
    var hoursAndDirectionsContainerObj = jQuery('#hoursAndDirections_Container');    
    var hoursAndDirectionsContentObj = jQuery('#hoursAndDirections_Content');
    var hoursAndDirectionsScrollBarObj = jQuery('#hoursAndDirections_ScrollBar');
    var hoursAndDirectionsGripperContainerObj = jQuery('#hoursAndDirections_GripperContainer');
    var maxContainerHeight = hoursAndDirectionsOverlayObj.height() - hoursAndDirectionsTopObj.height();

    hoursAndDirectionsContainerObj.css("height", maxContainerHeight + "px");
    hoursAndDirectionsContentObj.css("height", maxContainerHeight  + "px")
        .css('height','100%');  // added for native scrollbar
    hoursAndDirectionsScrollBarObj.css("height", (maxContainerHeight + 2) + "px");
    hoursAndDirectionsGripperContainerObj.css("height", maxContainerHeight + "px");
    
    jQuery("#hoursAndDirections_Container .section").each(function() {
      var currentElement = jQuery(this);  
      /* assuming padding is expressed in pixels */
      customScrollHeight += currentElement.height() + parseInt(currentElement.css("paddingTop")) 
        + parseInt(currentElement.css("paddingBottom"));
    });
    
    if(customScrollHeight == 0) {
      hoursAndDirectionsContainerObj.hide();
      hoursAndDirectionsTopObj.css("border-bottom", "1px solid #DDDDDD");    
    }
     
    if(customScrollHeight < maxContainerHeight || true) { // using native scrollbar
      customScrollHeight = maxContainerHeight;            // using native scrollbar
      var newOverlayHeight = customScrollHeight + hoursAndDirectionsTopObj.height();
      hoursAndDirectionsContentObj.addClass("noScrollBar");
      hoursAndDirectionsOverlayObj.css("height", newOverlayHeight + "px");
      hoursAndDirectionsContainerObj.css("height", customScrollHeight + "px");
      hoursAndDirectionsContentObj.css("height", customScrollHeight  + "px");
      hoursAndDirectionsScrollBarObj.hide();
      this.noDeptInfoFlag = true;
    }
    
    if (!jQuery.browser.msie || jQuery.browser.version >= '6.0') {
      var jQoverlayObj = jQuery(hoursAndDirectionsOverlayObj);
      jQoverlayObj.wrap('<div id="hoursAndDirectionsOverlayContentShadow">');
      var oldTop = jQoverlayObj.css('top');
      var oldRight = jQoverlayObj.css('right');      
      jQoverlayObj.css({
        'top':(jQuery.browser.msie ? '-7px' : '-8px')
        ,'right':'2px'
      });
      jQuery('#hoursAndDirectionsOverlayContentShadow').css({
        'position':'absolute'    
        ,'right':oldRight
        ,'top':parseInt(oldTop)+38+'px'
        ,'overflow':'visible'
        ,'height':hoursAndDirectionsOverlayObj.height()+11+'px'
        ,'width':hoursAndDirectionsOverlayObj.width()+8+'px'
      });
    }
  };
  
  var applyOverlayStyles = function() {
    jQuery(".hoursAndDirections").css('display', 'block');
  };
    
  var bindEventGetDirection = function() {
      jQuery("[id=hoursAndDirectionsGetDirections]").livequery("click", function() {    // Maybe multiples w/this ID until one removed
      var from = jQuery('#fromAddr')
         ,fromAddr = jQuery.trim(from.val());
      if (from.length && !fromAddr) {
          MapDirections.showErrorMessage(INVALID_FROM_ADDRESS);
          from.focus();
      } else {
          EventManager.publish({eventName:'com.cobaltgroup.ws.hndABTest'});
          MapDirections.setOverrideReportingInfo(true);
          MapDirections.showDirectionsPopup(-1,fromAddr);
      }
      return false;                    
    });
  };
  
  /*
   * Moves the center of the map so that marker shows in the center of left edge of the map
   * and left edge of the hours overlay
   */
  var moveCenterOfMap = function() {    
    var widthOfHoursOverlay = jQuery("#hoursAndDirectionsOverlayContent").width();
    var panningAmount = (widthOfHoursOverlay + OVERLAY_RIGHT_PX) / 2;
    var centerInPixels = that.map.fromLatLngToContainerPixel(that.map.getCenter());
    centerInPixels.x = centerInPixels.x + panningAmount;
    that.map.setCenter(that.map.fromContainerPixelToLatLng(centerInPixels));        
  };
  
  var getSiteNameMapOverlay = function() {
    var siteName = jQuery("#siteName").html();
    var siteNameLabel = new ELabel(that.firstLocationsLatLng, siteName, "GMapOverlaySiteName", new GSize(20,-16), 70, 0);
    return siteNameLabel;
  };
  
  var repostionLongSiteName = function(siteLabel) {
    var gMapOverlayObj = jQuery(".GMapOverlaySiteName");
    var availableSpaceForLabel = that.map.fromLatLngToContainerPixel(that.map.getCenter()).x - siteLabel.pixelOffset.width;
    var siteLabelWidth = gMapOverlayObj.width();
    var siteLabelHeight = gMapOverlayObj.height();
    var leftOverWidth = availableSpaceForLabel - siteLabelWidth;
    var increment = 1;
    var newWidth = siteLabelWidth;
        
    while(increment < leftOverWidth) {
      gMapOverlayObj.width(siteLabelWidth + increment);
      var newHeight = gMapOverlayObj.height();
      if (newHeight < siteLabelHeight) {
        siteLabelHeight = newHeight;
        newWidth = siteLabelWidth + increment;
      }
      increment++;
    }
      
    gMapOverlayObj.width(newWidth);
    siteLabel.redraw();  
    
    /**
     * Below snippet is to reposition site label if it get hidden behind map menu on top right side
     */
    var minDistanceFromMapTop = 30; //based on the assumption that map menu height is 19px and top is 7px
    var parentsTop = parseInt(gMapOverlayObj.parent().css("top"));
     
    if (parentsTop < minDistanceFromMapTop) {
      siteLabel.pixelOffset.height += minDistanceFromMapTop - parentsTop;
      siteLabel.redraw();
    }
  };
}

