var debug = function (str) {
    // if (window.console) { console.log(str); }
}

var Video = {
  list : {},
  // get video abstraction set up for ajaxing when we can
  getVideo : function (videoId) {
    if (video = this.list[videoId]) {
      return video;
    };
  },
  dispatchEvent : function (eventName, data) {
    $(document).trigger(eventName + '.video_tracker', data);
  }
}

Video.Player = function (options) {
  // if (!options.width || !options.height) {
  //   throw 'VideoPlayer requires width and height to be set';
  // }
  options = options || {};
  defaults = {
    'target': '#video-player',
    'video_details': '#video-details',
    'video_share': '#video-share',
    'bgcolor': '151515',
    'append_id': '',
    'add_hash_to_url': false
  };
  this.options = $.extend(defaults, options);
  var video_player = this;
  var that = this;
  
  this.options['width'] = Number($('[width]', this.options.target).attr('width'));
  this.options['height'] = Number($('[height]', this.options.target).attr('height'));  
  
  function swf() {
    return swfobject.getObjectById('video_player_swf' + video_player.options.append_id);
  }
  

  // TODO: Make this happen faster; The swf must be fully loaded for swfobject.get by id to work
  $(window).load(function() {
    setup_swf();
    });

  function setup_swf() {
    if (video_player.options.ad_control != undefined) {
      swf().setAdControl(video_player.options.ad_control);      
    };
  }
  
  // Send to Actionscript.
  function sendToActionscript (flv, auto_play) {
    var obj = { 'flv': flv, 'auto_play':auto_play? auto_play: false };
    swf().sendToActionscript(obj);
  }
  
  var insertFlv = function(flv, autoplay) {
    var options = that.options;
    template_opts = { 'flv':flv, 'height':options.height, 'width':options.width, 'append_id':options.append_id }
    var template = $.template('<div class="flash-player-required-message" id="flash-required-message-replace{{ append_id }}" style="width:{{ width }}px; height:{{ height }}px; background:#ddd;">' +
      '<p style="text-align:center; padding:20px">Adobe Flash player 9 is required to view this video <br> <a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>' +
      '</div>')
    $(options.target).html(template.apply(template_opts));
    var flashvars = {
      flv: flv,
      auto_play: 'true',
      height: options.height,
      width: options.width
    };
    var params = {
      salign: "lt",
      allowFullScreen: 'true',
      allowScriptAccess: 'always'
    };
    var attributes = {
      id: "video_player_swf" + options.append_id
    };    
    swfobject.embedSWF("http://media.ljworld.com/flash/video_player_prototype.swf", 'flash-required-message-replace'+options.append_id, options.width, options.height, "9.0.28","http://media.ljworld.com/flash/expressInstall.swf", flashvars, params, attributes);
  } 

  var insertMov = function(mov) {
    template_opts = { 'mov':mov, 'height':that.options.height, 'width':that.options.width, 'bgcolor':that.options.bgcolor, 'append_id':that.options.append_id }
    var template = $.template('<div class="video-embed-wrapper"><embed type="video/quicktime" bgcolor="{{ bgcolor }}" style="display:block" src="{{ mov }}" id="video_player_mov{{ append_id }}" scale="aspect" autostart="true" height="{{ height }}" width="{{ width }}"></div>'  );
    $(that.options.target).html(template.apply(template_opts));
  }
  
  var scrollIntoView = function(selector) {
    debug('scroll into view: ' + selector)
    var offset = $(selector).offset().top;
    debug('offset: ' + offset);
    var scrolly = typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement.scrollTop;
    debug('scrolly: ' + scrolly);
    if (offset < scrolly) {
        $('html,body').animate({scrollTop: offset - 20}, 500);        
    }
  }    
 
  this.applyDetails = function(video) {
    var options = that.options;
    $(options.video_details + " .title").html(video.title);
    $(options.video_details + " .tease," + options.video_details + " .caption").html(video.caption);
    $(options.video_details + " .date").html(video.date);
    if (video.credit) {
      $(options.video_details + " .credit-wrapper").show();      
      $(options.video_details + " .credit").html(video.credit);
    } else {
      $(options.video_details + " .credit-wrapper").hide();
    }
    $(options.video_details + " a.link").attr('href', video.get_absolute_url);
    $(options.video_details + " .comments").html(video.comment_text);
    $(options.video_details + " a.comments").attr('href', video.get_absolute_url + '#comments');
  }
  
  this.applyVideoShare = function(video) {
    var options = that.options;
    $(options.video_share + " a.mailfriend").attr('href', video.mailfrield_url);
    $(options.video_share + " .url input").attr('value', 'http://' + location.host + video.get_absolute_url);
    if (video.embed_url) {
        $(options.video_share + " .embed").show();
        $(options.video_share + " .embed input")[0].value = video.embed;
    } else {
        $(options.video_share + " .embed").hide();        
    }
  }
 
  applyVideo = function(videoId) {
    video = Video.getVideo(videoId);    
    if (!video) {
      return false
    }
    that.applyDetails(video);
    that.applyVideoShare(video);

    try { $('#video_player_mov' + that.options.append_id)[0].Stop(); } catch(err) {  }  // Attempt to stop a quicktime movie & ignore failures

    if ($('#video_player_swf' + that.options.append_id)[0] && video.flv_url) {
        debug('play flv: '+ video.flv_url);
        sendToActionscript(video.flv_url, true);
    } else if (video.flv_url) {        
        debug('insert flv / target: ' + that.options.target);
        insertFlv(video.flv_url);
    } else if (video.video_url) {
        debug('insert mov / target: ' + that.options.target);
        insertMov(video.video_url);
    }

    scrollIntoView(that.options.target);
    if (that.options.add_hash_to_url) {
      location.hash = '#video-' + video.id;
    }
    
    $(document).trigger('activate.video', [video, that.options]);
  } 
  this.activateVideo = applyVideo;
  

  this.activateHashVideo = function() {
    $(window).load(function() {
      if (anchorVideo = location.hash.match(/#(video-\d+)/)) { 
        applyVideo(anchorVideo[1]);
        debug('Anchor video: ' + anchorVideo[1]);      
      } 
    });
  }
  
  
  this.addPlaylist = function(selector) {
    debug('Adding playlist "' + selector + '" for: ' + that.options.target );
    $(function() {

      $(selector).click(function(e) {
        var target = $(e.target);
        if (target.hasClass('video') && target.attr('rel')) {
            var videoId = target.attr('rel')
        } else {
            var parent = $(target).parents('.video');
            var videoId = parent.attr('rel')
        }
        if (videoId) {
          that.activateVideo(videoId);
        e.preventDefault();
        }
      });
    });

    $(document).bind('activate.video', function (e, video, options) {
      if (options && options.target == that.options.target) {
        debug('magic trigger: ' + video)
        $(selector + ' .video.active').removeClass('active');
        $(selector + " .video[rel='video-" + video.id +"']").addClass('active');
      };
    }); 
  } 
}


