/* map it functionality */
MapItOptions = Object.extend({
    fileLoadingImage:        'images/loading.gif',     
    fileBottomNavCloseImage: 'images/closelabel.gif',

    overlayOpacity: 0.8,   // controls transparency of shadow overlay

    animate: true,         // toggles resizing animations
    resizeSpeed: 7,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)

    borderSize: 10,         //if you adjust the padding in the CSS, you will need to update this variable

	// When grouping images this is used to write: Image # of #.
	// Change it for non-english localization
	labelImage: "Image",
	labelOf: "of"
}, window.MapItOptions || {});

var MapIt = Class.create();
MapIt.prototype = {

  lightbox: undefined,
  overlay: undefined,
  
  hideAll: function(){
		
		
				Element.hide("mapit-lightbox")
		
		
	},

  loadmap:function(json) {
    
    //console.dir(json);
    
    $('mimageDataContainer').innerHTML = '<div id="map_canvas"></div><span class="mapitframe mapittop"></span><span class="mapitframe mapitleft"></span><span class="mapitframe mapitright"></span><span class="mapitframe mapitbot"></span>';
    
    if (GBrowserIsCompatible()) {
        var map = new GMap2($('map_canvas'));
        //map.setCenter(new GLatLng(37.4419, -122.1419), 13);
        //map.setUIToDefault();
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        
        var geocoder = new GClientGeocoder();
        var address2 = "";
        var mapaddress2 = "";
        
        if (json.address2 != '') {
          address2 = unescape(json.address2) + '<br/>';
          mapaddress2 = unescape(json.address2) + ',';
        }
        var phone = "";
        if (json.phone) {
         phone = json.phone + '<br/>'; 
        }
        
        var actual = unescape(json.address) + ',' + mapaddress2 + unescape(json.city) + ',' + json.state;
        var html = '<div class="map-info"><strong>' + unescape(json.name) + '</strong><br/>' + phone + unescape(json.address) + '<br/>' + address2 +  unescape(json.city) + ', ' + json.state + ' ' + json.zip + "<br/><br/></div>";
        
        //console.log(actual);
        
        var ico = new GIcon(G_DEFAULT_ICON);
    
        ico.image = '/template_images/hvcb/mapit/google_maps_sitecontent.png';
        ico.shadow = '';
        //ico.shadow = '/template_images/hvcb/googlemaps/pin_bg.png';
        ico.iconSize = new GSize(32, 32);
        //ico.shadowSize = new GSize(52, 35);
         
        markerOptions = { icon:ico };        
        
        json.point = new GLatLng(json.lat, json.lng);
        
        mapZoom = (json.zoom) ? json.zoom : 13;
        
        if (json.lat != '' && json.lng != '') {
          
          var offset = new GSize(8, -8);
          var marker = new GMarker(json.point, markerOptions);
          if('hideMarker' in json){
            map.setCenter(json.point,  mapZoom);
          }
          else{
            map.setCenter(json.point,  mapZoom);
            map.addOverlay(marker);
          }
          if(json.onEvent){
            GEvent.addListener(marker, 'click', function(){
                map.openInfoWindowHtml(json.point, html, {pixelOffset:offset});
            });
          }
          else{
            map.openInfoWindowHtml(json.point, html, {pixelOffset:offset}); 
          }
        } else {
        
          //console.log('address');
          
          geocoder.getLatLng(
            actual,
            function(pnt) {
              if (!pnt) {
                alert(json.address + " not found");
              } else {
                
                 
                  var offset = new GSize(8, -8);
                //  var marker = new GMarker(pnt, markerOptions);
                  var marker = new GMarker(pnt, markerOptions);
                   map.setCenter(pnt,  13);
                   GEvent.addListener(marker, 'click', function(){
                       
                       map.openInfoWindowHtml(pnt, html, {pixelOffset:offset});
                   });          
                  
                  map.addOverlay(marker);
                  map.openInfoWindowHtml(pnt, html,{pixelOffset:offset});
              }
            }
          );
   
        }
        
        
    }
    
  },
  
  
  reload:function() {
     var links = $$('.mapit-link');
     var self = this;
     this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0;
     this.overlayDuration = LightboxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration

    
     links.each(function(linkItem) {
        // override other lightboxes
        linkItem.json = linkItem.title;
        //linkItem.removeAttribute('title');
        linkItem.stopObserving('click');
        

        
        
        Event.observe(linkItem, 'click', function(e) {
            
            
           self.start(linkItem);
           self.loadmap(linkItem.json.evalJSON());
           
           
           
           Event.stop(e);
        
        });
    });
     
     
    
  },
  
  initialize:function() {
    var links = $$('.mapit-link');
    var self = this;
    
    this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0;
    this.overlayDuration = LightboxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration

    
    links.each(function(linkItem) {
        // override other lightboxes
        linkItem.json = linkItem.title;
        //linkItem.removeAttribute('title');
        linkItem.stopObserving('click');
        
        
        
        Event.observe(linkItem, 'click', function(e) {
            
            
           self.start(linkItem);
           self.loadmap(linkItem.json.evalJSON());
           
           
           
           Event.stop(e);
        
        });
    });
    
    
    
    
    this.initBox();	
    this.hideAll();
		
    
    
    /* from lightbox */
   
    
    
  },
  
  start:function(link) {
    
    var arrayPageSize = Lightbox.prototype.getPageSize();
    $('mapit-overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
    new Effect.Appear($('mapit-overlay'), { duration: this.overlayDuration, from: 0.0, to: MapItOptions.overlayOpacity });
    
    
    
    var arrayPageScroll = document.viewport.getScrollOffsets();
    var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
    var lightboxLeft = arrayPageScroll[0];
    $('mapit-lightbox').setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();
     $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
    
  },
  

  
  
  initBox:function() {
    
    
    
    var objBody = $$('body')[0];
    
    Event.observe(objBody, 'unload', function() {
       GUnload(); 
    });
    
    objBody.appendChild(Builder.node('div',{id:'mapit-overlay'}));
    objBody.appendChild(Builder.node('div',{id:'mapit-lightbox'}, [
      
          Builder.node('div', {className:'overlay'},[
            
            
            Builder.node('div', {id:'mimageDataContainer'}, [
              
                Builder.node('div',{id:'mimageDetails'}, [
                  Builder.node('div', {id:'map_canvas', width:'500px', height:'300px'}),
                ])
                
            ]),
            
            Builder.node('div', {className:'clear'})
            
          ]),
          // FIXME: add phrasepack
          Builder.node('div', {className:'bottom'}, [ 
             Builder.node('span',{id:'mclosewin'},[ 
               Builder.node('a',{href: '#', id:'mbottomNavClose'}, 'CLOSE'),
                 ' X'
             ])
          ])
        
        
      ]));
    
    
    
      this.lightbox = $('mapit-lightbox');
      this.overlay = $('mapit-overlay');
    
      //$('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
      
      
      $('mclosewin').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
      $('mapit-overlay').hide().observe('click', (function() { this.end(); }).bind(this));
      $('mapit-lightbox').hide().observe('click', (function(event) { if (event.element().id == 'mapit-lightbox') this.end(); }).bind(this));
    
      var th = this;
      (function(){
          var ids = 
              'mapit-overlay mapit-lightbox innerImageContainer outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 
              'galleryCopy imageDataContainer imageData imageDetails caption numberDisplay hireslink bottomNav bottomNavClose';   
          $w(ids).each(function(id){ th[id] = $(id); });
      }).defer();      
    
  },
  
  
  end: function() {
        //this.disableKeyboardNav();
        this.lightbox.hide();
        new Effect.Fade(this.overlay, { duration: this.overlayDuration });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
  }
  
  
};

var objMapIt = null;
Event.observe(window, 'load', function() {
    objMapIt = new MapIt();
});

