var searchController = function() {
  this.searchForm = $('search');
  this.searchField = this.searchForm.query;
  
  this.focusSearchField = function () {
    if (this.value == this.title) { this.value = ''; } 
  }
  
  this.blurSearchField = function() {
    if (this.value == '') { this.value = this.title; }
  }
  
  this.checkSearchEntry = function() {
    if (this.query.value == '' || this.query.value == this.query.title) { 
      alert("Please enter some search terms");
      return false;
    } else {
      return true;
    }
  }
  
  if (searchForm) {
    this.searchField.onfocus = this.focusSearchField;
    this.searchField.onblur = this.blurSearchField;
    this.searchForm.onsubmit = this.checkSearchEntry;
  }
}

function getURLParam(strURL, strParamName){
  this.strReturn = "";
  this.strURL = strURL;
  if ( strURL.indexOf("?") > -1 ){
    var strQueryString = strURL.substr(strURL.indexOf("?"));
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if ( 
aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        this.strReturn = aParam[1];
        break;
      }
    }
  }
  return this.strReturn;
}

function mediaPlayerController() {
    
    var videos = $$('.mb_video');
    videos.each(function(item){ 
    item.addEvent('click', function(){
      
      var videoPath = getURLParam(item.href, 'video');
      var posterPath = getURLParam(item.href, 'poster');
      var widescreen = 290;
      if (getURLParam(item.href, 'widescreen') == 'false') {
        widescreen = 380;
      }
      
      var videoContainer = new Element('div', {'id':'mbVideo'});
      var p = new Element('p');
      var downloadLink = new Element('a', {'href':videoPath, 'text':'Download video (mp4)', 'class': 'download'});
      
      var obj = new Swiff('/video/player.swf', {
        id: 'swfPlayer',
        width: 480,
        height: widescreen,
        params: {
          wmode: 'opaque',
          bgcolor: '#fff',
          allowfullscreen: 'true',
          movie: '/video/player.swf',
          quality: 'high',
          allowScriptAccess: 'sameDomain'
        },
        vars: {
          file: videoPath,
          image: posterPath,
          autostart: 'false'
        }
      });
      
      obj.inject(videoContainer);
      downloadLink.inject(p);
      p.inject(videoContainer);
      
      mediaBoxOverlay.show(videoContainer, {cloneContent: false});
      
      return false;
    });
    
  });
  
  if (videos.length > 0) var mediaBoxOverlay = new Overlay( { destroyContent: true } );
}

  
window.addEvent('domready', function() {
	searchController();
	mediaPlayerController();
 });