var LocalMap = Behavior.create({

  initialize : function(options) {
    if (GBrowserIsCompatible()) {
      var view = options.startingView;
      this.map = new GMap2(this.element);
      this.map.setCenter( new GLatLng(view.lat, view.lon), view.zoom );
      this.map.addControl( new GSmallMapControl() );
      this.fixTeleAtlasOverlay();
      LocalMap.PropertyMarker.clickable = view.options.clickable ? true : false;
      var properties = options.properties;
      if (properties.length) this.addProperties(properties);
    }
  },

  addProperties : function(properties) {
    this.propertyMarkers = $A(properties).map( function(p) {
      return new LocalMap.PropertyMarker(p);
    });
    if (this.propertyMarkers.length > 0) {
      this.markerManager = new GMarkerManager(this.map);
      this.markerManager.addMarkers( this.propertyMarkers, 11 );
      this.markerManager.refresh();
    }
  },

  fixTeleAtlasOverlay : function() {
    var customTiles = new GTileLayerOverlay(
      new GTileLayer(null, null, null, {
        tileUrlTemplate: 'http://maps.ontrackmedia.ca/{Z}/{X}-{Y}.png',
        isPng:false
      })
    );
    this.map.addOverlay( customTiles );
  }

});


LocalMap.PropertyIcon = {
  image:  "/images/map/house.png",
  iconSize : new GSize(38,29),
  iconAnchor : new GPoint(12,28)
};
Object.extend( LocalMap.PropertyIcon, GIcon );

LocalMap.PropertyMarker = function(listing) {
    this.latlng = new GLatLng(parseFloat(listing.lat), parseFloat(listing.lon));
    this.listing = listing;
    GMarker.apply(this, [this.latlng, {icon: LocalMap.PropertyIcon} ] );
};
LocalMap.PropertyMarker.prototype = new GMarker( new GLatLng(0,0) );

LocalMap.PropertyMarker.prototype.initialize = function(map) {
  GMarker.prototype.initialize.call(this, map);
  if ( LocalMap.PropertyMarker.clickable ) {
    GEvent.addListener( this, 'click', function() {
      var mapinfo = document.createElement('div');
      mapinfo.className = 'mapinfo';
      map.openInfoWindowHtml( this.latlng, this.infoWindowContent() );
    });
  }
};

LocalMap.PropertyMarker.prototype.infoWindowContent = function() {
  var mapinfo = document.createElement('div');
  mapinfo.className = 'mapinfo';
  var addressLink = this.listing.address.link('/listings/'+this.listing.id);
  var imgLink = ('<img height="60" width="80" src="'+this.listing.photo+'" alt="" />').link('/listings/'+this.listing.id);
  mapinfo.innerHTML += imgLink;
  mapinfo.innerHTML += '<h4>' + addressLink + '</h4>';
  return mapinfo;
}

Event.observe(window, 'unload', GUnload );


var MortgageCalc = Behavior.create({
  
  initialize : function(opts) {
    var self = this;
    self.calculate();
    if (opts.toggle)  {
      self.element.hide();
      var toggle = $$(opts.toggle)[0];
      MortgageCalc.Toggle.attach( toggle, self );
    }
    new Form.Observer( this.element, 0.5, self.calculate.bind(self) );
  },
  
  formatPrice : function(number,decimalPoints) {
  	if(!(number>0)) return '—';
  	if(!decimalPoints) return Math.round(number);
  	var num = Math.round((number * Math.pow(10,decimalPoints))).toString();
  	return num.slice(0,-1*decimalPoints) + "." + num.slice(-1*decimalPoints)
  },
  
  to_i : function(field) {
    return parseInt( field.value.gsub(/[^0-9\.]/, '') );
  },

  calculate : function() {
    var mortgageAmount =  this.to_i( $('mortgage_amount') ) - 
                          this.to_i( $('mortgage_down_payment') );
    var monthlyInterest = $('mortgage_rate').value / 1200;
    var base = 1;
    var mbase = 1 + monthlyInterest;
    for ( i=0; i < $('mortgage_term').value * 12; i++) { base = base * mbase; }
    var monthly = mortgageAmount * monthlyInterest / ( 1-(1/base) );
    $('mortgage_payment').innerHTML = this.formatPrice(monthly,2);
  }  
});

MortgageCalc.Toggle = Behavior.create({
  initialize : function(form) {
    this.calcForm = form.element;
  },
  
  onclick : function(e) {
    var self = this;
    Effect.toggle(self.calcForm,'slide',{duration:0.5});
    Event.stop(e);
    return false;
  }
});


var PhotoCarousel = Behavior.create({
  
  initialize : function() {
    this.clickQueue = $A();
    this.scroller = this.element.getElementsByClassName('scroller')[0];
    var t = this.scroller.getElementsByClassName('thumb')[0];
    this.margins = parseInt(t.getStyle('margin-left')) + parseInt(t.getStyle('margin-right'));
    this.thumbWidth = t.clientWidth + this.margins;
    this.viewport = t.parentNode;
    this.thumbsCount = this.scroller.getElementsByClassName('thumb').length;
    this.allThumbsWidth = this.thumbsCount * this.thumbWidth;
    if ( this.scroller.clientWidth < this.allThumbsWidth ) {
      new PhotoCarousel.ScrollArrow(this.element.getElementsByClassName('scroll_thumb_left')[0], this);
      new PhotoCarousel.ScrollArrow(this.element.getElementsByClassName('scroll_thumb_right')[0], this);      
    }
  },
  
  scroll : function(way) {
    this.clickQueue.push( way );
    if (this.clickQueue.length > 1) return false;
    this._move( way );
  },
  
  _move : function(way) {
    if (! way) return false;
    var self = this;
    new Effect.Move( self.viewport,
      { x: self._moveSize(way), mode: 'relative', duration: 0.2,
        queue: {position:'end', scope: 'photo_browser'},
        afterFinish: function(mv) {
          self.clickQueue.shift();
          self._move( self.clickQueue.last() );            
        }
      });
  },
  
  _moveSize : function(way) {
    var leftOffset = parseInt(this.viewport.offsetLeft);
    if (way == 'left') {
      return (this.scroller.clientWidth - this.allThumbsWidth) < leftOffset -this.margins ? 0-this.thumbWidth : 0;
    } else if (way == 'right') {
      return leftOffset < 0 ? this.thumbWidth : 0;
    }
  }
});

PhotoCarousel.ScrollArrow = Behavior.create({
  
  initialize : function(carousel) {
    this.carousel = carousel;
  },
  
  onclick : function(e) {
    var source = Event.element(e);
    if (source.hasClassName('scroll_thumb_left'))   return this.carousel.scroll('right');
    if (source.hasClassName('scroll_thumb_right'))  return this.carousel.scroll('left');
    Event.stop(e);
    return false;
  }
});

var ZoomPhoto = Behavior.create({
  
  initialize : function(zoomed_element, find, replace) {
    var zoomed_element = zoomed_element || ZoomPhoto.zoomed_element;
    var find = new RegExp( find || ZoomPhoto.src_find || 'thumb.jpg' );
    var replace = replace || ZoomPhoto.src_replace || 'large.jpg';
    this.zoomed_element = $$(zoomed_element)[0];
    this.img = new Image;
    this.img.src = this.element.src.replace( find, replace );
  },
  
  onmouseover : function(e) {
    Event.stop(e);
    if ( this.zoomed_element.src == this.img.src ) return;
    this._hideImg();
  },
  
  _hideImg : function() {
    var self = this;
    Effect.Fade( self.zoomed_element, 
      { to: 0.05, duration: 0.5, queue: {position:'end',scope:'zoom_photo'},
        beforeStart : function(z) { 
          Effect.Queues.get('zoom_photo').each(function(q){q.cancel()});
        },
        afterFinish : function(z) { 
          self._showImg();
        } 
      });
  },
  
  _showImg : function() {
    var self = this;
    Effect.Fade( self.zoomed_element, 
      { from: 0.05, to: 1, duration: 1.5, queue: {position:'end',scope:'zoom_photo'},
        beforeStart : function(z) {
          self.zoomed_element.src = self.img.src;
        }
      });
  }
});


Object.extend( ZoomPhoto, {
  zoomed_element : '#photo_viewer > img',
  src_find : 'icon.jpg',
  src_replace : 'medium.jpg'
});


Object.extend( ZoomPhoto, {
  zoomed_element : '#photo_viewer > img',
  src_find : 'icon.jpg',
  src_replace : 'medium.jpg'
});

Event.addBehavior({
  '#mortgage_calc' : MortgageCalc({ toggle : '#show_mortgage_calc' }),
  '#photo_carousel' : PhotoCarousel(),
  '#photo_carousel .thumb img' : ZoomPhoto()
});

