var MortgageCalc = Behavior.create({
  
  initialize : function(opts) {
    if (! opts ) 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.getStyle('left'));
    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_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;
    }
  }
});


Object.extend( ZoomPhoto, {
  zoomed_img : '#photo_viewer > img',
  src_find : 'icon.jpg',
  src_replace : 'medium.jpg'
});
