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 ZoomPhoto = Behavior.create({
  
  initialize : function(zoomed_img, find, replace) {
    zoomed_img = zoomed_img || ZoomPhoto.zoomed_img;
    this.zoomed_img = $$(zoomed_img)[0];
    this.find = new RegExp( find || ZoomPhoto.src_find || 'thumb.jpg' );
    this.replace = replace || ZoomPhoto.src_replace || 'large.jpg';
    this.zoomed_src = this.element.src.replace( this.find, this.replace );
  },
  
  onmouseover : function(e) {
    if ( this.zoomed_img.src == this.zoomed_src ) return;
    this._hideImg();
    Event.stop(e);
    return false;
  },
  
  _hideImg : function() {
    var self = this;
    Effect.Fade( self.zoomed_img, 
      { to: 0.05, duration: 0.3, queue: {position:'end',scope:'zoom_photo'},
        beforeStart : function(z) { 
          Effect.Queues.get('zoom_photo').each(function(q){q.cancel()});
        },
        afterFinish : function(z) { 
          self.zoomed_img.src = self.zoomed_src;
        } 
      });
    self._loadImg();
  },
  
  _showImg : function() {
    var self = this;
    Effect.Appear( self.zoomed_img, 
      { queue: {position:'end',scope:'zoom_photo'}} );
  },
  
  _loadImg : function() {
    if (this.img && this.img.complete) {
      this._showImg();
    } else {
      this.img = new Image;
      this.img.onload = this._showImg.bind(this);
      this.img.src = this.zoomed_src;
    }
  }
});



var ListZoomPhoto = Behavior.create({
  
  initialize : function() {
    this.thumb_img    = this.element.select('img')[0];
    if (this.thumb_img.complete ) {
      this.centerImg();
    } else {
      Event.observe( this.thumb_img, 'load', this.centerImg.bind(this) );
    }
  },
  
  centerImg : function() {
    this.top_diff = (this.element.clientHeight / 2) - (this.thumb_img.clientHeight / 2) + 'px';
    this.left_diff = (this.element.clientWidth / 2) - (this.thumb_img.clientWidth / 2) + 'px';
    this.originalWidth = this.thumb_img.clientWidth;
    this.originalHeight = this.thumb_img.clientHeight;
    this.thumb_img.setStyle({ top : this.top_diff, left : this.left_diff });
  },
  
  shouldZoom : function() {
    if ( this.originalWidth > this.element.clientWidth || this.originalHeight > this.element.clientHeight) return true;
  },
  
  onmouseover : function() {
    if ( this.shouldZoom() ) {
      new Effect.Morph( this.thumb_img, { 
        duration: 2.0, 
        queue: {position: 'end', scope: this.thumb_img.src},
        style: { left: '0px', top: '0px', width: this.element.clientWidth + 'px' }
      });      
    }
  },
  
  onmouseout : function() {
    var startScale = (this.element.clientWidth / this.originalWidth);
    var endScale = (this.originalWidth / this.element.clientWidth) * 100;
    new Effect.Morph( this.thumb_img, { 
      duration: 0.2, 
      queue: {position: 'front', scope: this.thumb_img.src, limit: 1}, 
      style: { left: this.left_diff, top: this.top_diff, width: this.originalWidth + 'px' },
      beforeStart : function(z) { 
        Effect.Queues.get(z.element.src).each(function(q){q.cancel()});
      }
    });
  }
  
});


Object.extend( ZoomPhoto, {
  zoomed_img : '#photo_viewer > img',
  src_find : 'x90y60.jpg',
  src_replace : 'x400y300.jpg'
});

Event.addBehavior({
  '#photo_browser .thumb img' : ZoomPhoto,
  '#listings .listing .thumb_viewer' : ListZoomPhoto
});
