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\.]/, ''), 10 );
  },

  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'),10) + parseInt(t.getStyle('margin-right'),10);
    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 );
    return true;
  },
  
  _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() );
      }
    });
    return true;
  },
  
  _moveSize : function(way) {
    var leftOffset = parseInt(this.viewport.offsetLeft,10);
    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 : 'large.jpg'
});

