// Requires effects.js

function YTShader(target) {
  this.target = $(target)
  this.target.addClassName('YTShader')
  this.video = this.target.select('object').first()
  this.video.remove()

  this.expStyle = {
    width: this.video.getStyle('width'),
    height: this.video.getStyle('height')
  }
  this.video.setStyle(YTShader.cntStyle)

  this.button = new Element('div', { style: YTShader.btnStyle })
  var bt = new Element('p', { style: 'margin:0;padding:0 0.5em;font-weight:bold' })
  bt.insert(this.target.readAttribute('title') || 'Play video')
  this.target.writeAttribute('title', 'Play video')
  this.button.insert(bt)

  this.target.insert(this.button)
  this.target.ytShader = this
  bt.ytShader = this
  this.button.observe('click', function(e) { e.element().up('.YTShader').ytShader.expand() })
}

YTShader.cntStyle = { width: '30px', height: '25px' }
YTShader.btnStyle = 'height:' + YTShader.cntStyle.height +';padding-left:' + YTShader.cntStyle.width + ';background:url(/images/vid_shader.png) top left no-repeat;display:table-cell;vertical-align:middle;cursor:pointer'

YTShader.expandCurrent = function() {
  YTShader.current.video.morph(YTShader.current.expStyle, { afterFinish: YTShader.playCurrent })
}

YTShader.playCurrent = function(e) {
  YTShader.current.video.playVideo && YTShader.current.video.playVideo()
  YTShader.current.showCloseButton()
}

YTShader.resetCurrent = function() {
  YTShader.current.video.remove()
  YTShader.current.target.insert(YTShader.current.button)
}

YTShader.init = function() {
  $$('.youtube').each(function(vid) { new YTShader(vid) })
}


YTShader.prototype.expand = function() {
  this.button.remove()
  this.target.insert({ 'top': this.video })
  YTShader.current = this
  setTimeout("YTShader.expandCurrent()", 600)
}

YTShader.prototype.showCloseButton = function() {
  if (!this.closeButton) {
    this.closeButton = new Element('div', { 'style': 'display:none', 'title': 'Hide video', 'class': 'yt_control_bay' })
    this.closeButton.insert(new Element('input', { 'type': 'button', 'value': 'X', 'style': 'color:red;font-weight:bold;background-color:#EEE;border:1px solid #AAA;padding: 1px 6px;margin:0' }))
    this.target.insert(this.closeButton)
    this.closeButton.down('input').observe('click', function(e) { e.element().up('.YTShader').ytShader.contract() })
  }
  this.closeButton.slideDown()
}

YTShader.prototype.contract = function() {
  this.video.pauseVideo && this.video.pauseVideo()
  this.closeButton.slideUp()
  YTShader.current = this
  this.video.morph(YTShader.cntStyle, { afterFinish: YTShader.resetCurrent })
}
