var PriceConfigurator = DClass.extend({
  init:function(options){
    this.form = $(this.id+'_form')
    this.base_price = options.base
    this.perks = $(this.id+'_perks')
    this.total = $(this.id+'_total')
    this.submit = $(this.id+'_submit')
    
    this.perks.getChildren().each(function(perk){
      perk.select = perk.getLast().getLast()
      perk.select.addEvent('change',this.recalculate.bind(this))
    }.bind(this))
    
    this.form.remote = new Ajax(this.form.action,{onSuccess:function(new_cart){
      this.form.reset()
      this.recalculate()
      this.anim(new_cart)
      this.submit.removeClass('progress')
      this.progress = false
    }.bind(this)})
    
    this.form.addEvent('submit',function(event){
      if(!this.progress){
        this.progress = true
        this.form.remote.request(this.form)
        this.submit.addClass('progress')
      }
      $stop(event)
    }.bind(this))
  },
  recalculate:function(){
    total = this.base_price
    this.perks.getChildren().each(function(e){
      val = e.select.options[e.select.selectedIndex].innerHTML.match(/\+\d+\.\d\d/)
      if(val)total += val[0].toFloat()
    })
    tp = this.total.innerHTML.replace(/\d+\.\d\d/,total.toFixed(2))
    if(tp != this.total.innerHTML){
      this.total.innerHTML = tp
      $(this.total.parentNode).highlight()
    }
  },
  anim:function(new_cart){
    clone = Element.create('<img src="/img/add_to_cart.gif"/>')
    $$('body')[0].appendChild(clone)
    clone = $(clone)
    clone.set({'styles':{'position':'absolute', 'top':this.submit.getTop(), 'left':this.submit.getLeft()}})
    fx = new Fx.Styles(clone,{transition:Fx.Transitions.Expo.easeIn, onComplete:function(){
      clone.remove()
      $('cart').replaceWith(Element.create(new_cart)).highlight()
    }})
    fx.start({'top':$('cart').getTop(), 'left':$('cart').getLeft()})
  }
  
})

var ProductImage = DClass.extend({
  init:function(options){
    options = options || {}
    this.del = $(this.id+'_delete')
    this.img = $(this.id+'_img')
    if(this.del){
      this.del.message = options.del_message
      this.del.remote = new Ajax(this.del.href,{'method':'post','onSuccess':function(e){this.fade_and_remove()}.bind(this)})
      this.del.addEvent('click',function(event){
        if(confirm(this.message)){this.remote.request('delete')}
        $stop(event)
      })
    }
    var parts = this.img.href.match(/(.*)\?width=(\d+)&height=(\d+)/)
    this.img.width = parts[2]
    this.img.height = parts[3]
    this.img.url = parts[1]
    this.img.addEvent('click',function(event){
      window.open(this.img.url, null, "scrollbars=yes,resizable=yes,width="+this.img.width+",height="+this.img.height);
      $stop(event);
    }.bind(this))
  }
})
