var DClass = new Class({
	initialize:function(e,options){
		var elem = $(e)
	  $extend(elem,this)
		elem.init.bind(elem)(options)
		return elem
	}
})

function $stop(event){ (new Event(event)).preventDefault()}
//try{window.ie6 = Client.Engine.ie6}catch(e){}
if( typeof(Client) != 'undefined' && Client.Engine.ie6) window.ie6 = true

// Element.extend
// ================================================
Element.extend({
	visible:function(){
		return this.getStyle('display') == 'block'
	},
	highlight:function(){
		var current_color = this.getStyle('backgroundColor')
		if(current_color == 'transparent')var trans = '#FFFFFF'
    var highlight_fx = $(this).effect('backgroundColor')
    
    highlight_fx.start(trans || current_color,'#ffff99').chain(function(){
    	highlight_fx.start('#ffff99',trans || current_color)
    }).chain(function(){
    	this.setStyle('backgroundColor',current_color)
    }.bind(this))
    return this
	},
	fade_and_remove:function(){
		return new Fx.Style(this,'opacity',{onComplete:this.remove.bind(this)}).start(1,0)
	},
	setEvent:function(type,fn){
		this.removeEvents(type)
		this.addEvent(type,fn)
	},
	show:function(){ this.style.display = '' },
	hide:function(){ this.style.display = 'none' },
	serialize: function(key) {
		key = key || this.id
		return this.getChildren().map(function(el, i) { return key+'[]=' + el.id.split('_')[1] }).join('&')
	}
})
Element.create = function(text,options){
	return new Element('span').setHTML(text).getChildren()[0]
}

Event.addBehavior = function(behaviours){
	var apply_behaviors = function(){ for( id in behaviours)behaviours[id].bind($(id))() }
	if(window.domReadyFired)apply_behaviors()
	else window.addEvent('domready',function(){
		window.domReadyFired = true
		apply_behaviors()
	})
}

Fx.Slide = Fx.Slide.extend({
	initialize: function(el, options){
		options = options || {}
		options.onComplete = function(){
			if(this.showing)this.wrapper.setStyle('height','')
		}
		this.showing = true
		this.parent(el,options)
		if(!el.visible()){
		  el.show()
		  this.hide()
		  this.showing = false
		}
	},
	slideIn:function(mode){
		this.showing = true
		this.parent(mode)
	},
	slideOut:function(mode){
		this.showing = false
		this.parent(mode)
	}
})

var Rounder = new Class({
  elements_to_round:[],
  initialize:function(){
    this.elements_to_round = $$('#content .container')
    //if(window.ie6)this.elements_to_fix_alpha = $$('.tiny_products a.img')
  },
  round_all:function(){
    this.elements_to_round.each(function(e){this.round_elem(e)}.bind(this))
    
    /*
    if(window.ie6){
      this.elements_to_fix_alpha.each(function(e){ this.fix_alpha(e) }.bind(this))
      if($('header-banner'))this.fix_alpha($('header-banner'))
    }
    */
  },
  fix_alpha:function(e){
    img = e.getStyle('backgroundImage').match(/url\(([^)]+)\)/)[1]
    e.style.backgroundImage = ''
    e.setStyle('filter',"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+img+"', sizingMethod='crop')")
  },
  round_elem:function(elem){
    var bottom = new Element('div', {'class': 'bottom'})
    bottom.injectInside(elem);
    /*var top = new Element('div',{'class':'top'})
    if(elem.hasClass('middle'))top.setHTML('<span></span>')
    top.injectTop(elem)
    this.stripe(elem)
    if(!elem.hasClass('image')){
      var bottom = new Element('div',{'class':'bottom'})
      if(elem.hasClass('middle'))bottom.setHTML('<span></span>')
      bottom.injectInside(elem)
    }*/
  },
  stripe:function(elem){
    new Element('div',{'class':'stripe'}).injectTop(elem)
  }
})

window.addEvent('domready',function(){(this.rounder = new Rounder()).round_all()})

var HidableForm = DClass.extend({
  init:function(options){
    this.anim = new Fx.Slide(this);
    $(options.trigger).addEvent('click',function(event){
      this.anim.toggle()
      $stop(event)
    }.bind(this))
  }
})


var AjaxMessage = new Class({
  message:function(text,type){
    type = type || 'error'
    text = text.responseText || text
    message = Element.create('<div class="container ajax-message '+type+'"><div class="top"></div><div class="content">'+text+'</div><div class="bottom"></div></div>').injectTop($('content'))
    message.addEvent('click',function(){this.fade_and_remove()})
    message.highlight()
  },
  show_progress:function(where){
    where = where || this
    elem = Element.create('<img src="/img/progress.gif" class="progress" alt="progress" />')
    $(where).adopt(elem)
  },
  hide_progress:function(){
    $$('#'+this.id+' img.progress').each(function(e){e.remove()})
  }
})


var CartItem = DClass.extend({
  init:function(){
    this.remote = new Ajax(this.href, {
      method:'post',
      onSuccess:function(new_cart){
        this.getFirst().setAttribute('src','/img/add_to_cart.gif')
        this.anim.bind(this)(new_cart)
        this.blur()
      }.bind(this),
      onFailure:this.message
    })
    this.addEvent('click',function(event){
      this.getFirst().setAttribute('src','/img/add_to_cart_progress.gif')
      this.remote.request('ADDTOCART')
      $stop(event)
    })
  },
  anim:function(new_cart){
    clone = Element.create('<img src="/img/add_to_cart.gif"/>')
    $$('body')[0].appendChild(clone)
    clone = $(clone)
    adjust_left = 0
    adjust_top = 0
    if(window.ie)adjust_left = $(this.parentNode.parentNode).offsetWidth*0.55
    if(window.ie7)adjust_top =85
    if(window.ie6)adjust_top =60
    clone.set({'styles':{'position':'absolute', 'top':this.getTop()-adjust_top, 'left':this.getLeft()-adjust_left}})
    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 CartListItem = DClass.extend({
  init:function(options){
    this.base_price = options.base_price
    this.perks = $(this.id+'_perks')
    this.total = $(this.id+'_total')
    this.delete_btn = $(this.id+'_delete')
    
    this.delete_btn.remote = new Ajax(this.delete_btn.href,{
      data:'DELETE',
      onSuccess:function(){
        this.fade_and_remove()
        CartList.items.remove(this)
        CartList.instance.recalculate()
      }.bind(this)
    })
    
    this.quantity = $(this.id+'_quantity')
    this.total_price = options.base_price * this.quantity.value.toInt()
    
    CartList.items.push(this)
    
    this.perks.getChildren().each(function(perk){
      perk.select = perk.getLast().getLast()
      perk.select.addEvent('change',function(){
        CartList.instance.send_changes(this)
      }.bind(this))
    }.bind(this))
    
    this.delete_btn.addEvent('click',function(event){
      this.remote.request();
      $stop(event)
    })
    
    this.quantity.addEvent('change',function(){
      this.quantity.value = this.quantity.value.match(/\d+/) ? this.quantity.value.match(/\d+/) : '1'
      CartList.instance.send_changes(this)
      
    }.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()
    })
    this.total_price = total
    
    
    tp = this.total.innerHTML.replace(/\d+\.\d\d/,this.total_price.toFixed(2))
    if(tp != this.total.innerHTML){
      this.total.innerHTML = tp
      $(this.total.parentNode).highlight()
    }
  }
})

var CartList = DClass.extend({
  init:function(){
    this.total = $(this.id+'_total')
    this.save_btn = $(this.id+'_controls').getFirst()
    this.save_btn.remove()
    this.remote = new Ajax(this.action+'/')
    this.continue_btn = $(this.id+'_continue')
    this.continue_btn.fx = new Fx.Style(this.continue_btn,'opacity')
    
    CartList.instance = $(this)
  },
  
  stop_if_empty:function(){
    if(!CartList.items.length)this.continue_btn.fx.start(1,0)
  },
  
  send_changes:function(initer){
    initer.addClass('progress')
    this.remote.addEvent('onSuccess',function(r){
      initer.recalculate()
      initer.removeClass('progress')
      this.recalculate()
    }.bind(this))
    this.remote.request(this)
  },
  recalculate:function(){
    this.stop_if_empty(this)
    
    total = 0
    CartList.items.each(function(e){
      total += e.total_price*e.quantity.value.toInt()
    })
    tp = this.total.innerHTML.replace(/\d+\.\d\d/,total.toFixed(2))
    if(tp != this.total.innerHTML){
      this.total.innerHTML = tp
      this.total.highlight()
    }
  }
})

CartList.items = []

var Subscription = DClass.extend({
  init:function(){
    this.form = this.getFirst();
    this.form.remote = new Ajax(this.form.action, {onFailure:this.update.bind(this), onSuccess:this.update.bind(this)})
    this.form.addEvent('submit',function(event){
      this.remote.request(this)
      $stop(event)
    })
  },
  update:function(response){
    this.replaceWith(Element.create(response.responseText || response))
    new_elem = $('newsletter')
    new Subscription(new_elem)
    rounder.round_elem(new_elem)
    new_elem.form.getFirst().highlight()
  }
})

var PromoCardReferral = DClass.extend({
  init:function(other_input){
    this.addEvent('change',function(event){
      if(this.options[this.selectedIndex].value == 'other')other_input.show()
      else other_input.hide()
    })
  }
})

var CategoriesTree = DClass.extend({
  init:function(options){
    return
    
    this.single = $(options.single)
    
    this.elements = this.getChildren()
    this.triggers = $$('#'+this.id+' h3 a')
    this.contents = $$('#'+this.id+' .category-content')
    this.elements.each(function(e,i){
      new CategoryTreeElem(e, {trigger:this.triggers[i], content:this.contents[i]})
    }.bind(this))
    
    if(this.single){
      this.trigger = $(options.trigger)
      this.trigger.img = this.trigger.getLast()
      this.fx = new Fx.Slide(this)
      this.single_fx = new Fx.Slide(this.single)
      this.trigger.img.addEvent('click',function(e){
        this.fx.toggle()
        this.single_fx.toggle()
        if(this.fx.showing)this.trigger.img.src = this.trigger.img.src.replace('expand','collapse')
        else this.trigger.img.src = this.trigger.img.src.replace('collapse','expand')        
      }.bind(this))
      
      new CategoryTreeElem(this.single, {trigger:$$('#'+this.single.id+' h3 img')[0], content:$$('#'+this.single.id+' .category-content')[0]})
    }
  }
})

var CategoryTreeElem = DClass.extend({
  init:function(options){
    this.trigger = options.trigger
    this.content = options.content
    this.fx = new Fx.Slide(this.content)
    this.trigger.addEvent('click',function(e){
      this.fx.toggle()
      //if(this.fx.showing)this.trigger.src = this.trigger.src.replace('expand','collapse')
      //else this.trigger.src = this.trigger.src.replace('collapse','expand')
      $stop(e)
    }.bind(this))
  }
})

var JobPositionItem = DClass.extend({
  init:function(options){
    this.text_content = $(this.id+'_text')
    this.position_title = $(this.id+'_title')
    this.anim_content = new Fx.Slide(this.text_content,{transition:Fx.Transitions.Quad.easeOut})
    this.position_title.addEvent('click',function(ev){
      $stop(ev)
      this.anim_content.toggle()
      this.position_title.getParent().toggleClass('open')
    }.bind(this))
  }
})


var SortBySelect = DClass.extend({
  init:function(options){
    this.addEvent('change',function(){
      this.form.submit();
    })
  }
})

var ClientImage = 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))
  }
})