//
// YouTube
//
var youtube_loggers = {}

function onYouTubePlayerReady(id) {
  
  youtube_loggers[id] = function (state) { 
      if (state == 3) { 
        $('#'+id).flash(function(){
          if(this.getCurrentTime() == 0) {
            stats.watched(id)
          }
        })
      } 
  }    
  $('#'+id).flash(function(){this.addEventListener("onStateChange", "youtube_loggers."+id)});
}


//
// Vimeo
//
function vimeo_player_loaded(id) {  
  $('#'+id).flash(function(){this.api_addEventListener('onPlay','vimeo_on_play')});
}

function vimeo_on_play(id) {
  $('#'+id).flash(function(){
    if(this.api_getCurrentTime() == 0) {
      stats.watched(id)
    }
  })
}


//
// prototype
//
Array.prototype.last = function() {return this[this.length-1]}



//
// Document ready
//
$(function() {  

  ui.insert_players($('.yt, .vimeo'))
  
  // Countdown    
  $('#countdown').epiclock({mode: EC_COUNTDOWN, format: 'V{d / } x{t / } i{m / } s{s}', target: target_date}).clocks(EC_RUN)
  
  // Text aniimation
  /*var texts = ['upload…', 'del…', 'stem…', 'fest!', 'Ny dansk musik']  
  $(document).everyTime("3s", function(i) {    
    $('#countdown-info h1').each(function(){
      $(this).html(texts[i-1])
      if (i == texts.length) { $(this).addClass('last') }        
    })        
  }, texts.length);*/
  
  
  $("a.submitter").click(function(e){
    $(this).parents('form:first').submit()
    e.preventDefault()
  })
  
  // form 
  $('.membership input').click(function(e){
    $("#user-born-year").attr('class', $(this).attr('class'))
  })
  
  
  // Flash
  ui.flash_message()
  
  // Toogle sub menu
  $("a.has-menu").click(function(e){
    $(this).next('ul:visible').slideUp(200)
    $(this).next('ul:hidden').slideDown(200)
    e.preventDefault()    
  })
  
  // Comments
  ui.bind_show_info_links($("a.show-info"))

  // Rating
  ui.bind_rating($(".rating"))

  // Voting
  ui.bind_voting($(".voting"))
  
  $('a.view').click(function(e){
    
    $(this).siblings('.yt').flash(function(){this.stopVideo()})
    $(this).siblings('.vimeo').flash(function(){this.api_pause()})    
    
    var link = $(this)
        
    $.ajax({
       url: link.attr('href'),
       type: 'GET',
       success: function(html) {   
         
         // BG
         ui.bind_bg()
         $('.bg').show()                           
         
         // Video
         $(html).appendTo('body').css({
           'z-index': 200,
           'left': parseInt((($(window).width()-480)/2), 10) + "px",
           'top': ($(document).scrollTop() + 120) + "px"
         })
         

         ui.insert_players($('.viewer').find('.yt, .vimeo'))         
         
         ui.bind_rating($('.viewer').find('.rating'))
         ui.bind_voting($('.viewer').find('.voting'))
         ui.bind_close()
         
         pageTracker._trackPageview(link.attr('href'));
       }
    })
    
    e.preventDefault()
  })
  
  $('a.popup').each(function(){
    $.ajax({
       url: $(this).attr('href'),
       type: 'GET',
       success: function(html) {   

         // Video
         $(html).appendTo('body').css({
           'z-index': 300,
           'left': (parseInt((($(window).width()-480)/2), 10)+60) + "px",
           'top': ($(document).scrollTop() + 120) + "px"
         }).find('a:last').click(function(e){
           $('#countdown-xl').epiclock('destroy')
           $(this).parents('#popup').remove()
           e.preventDefault()
           
         })
         
         $('#countdown-xl').epiclock({mode: EC_COUNTDOWN, format: 'V{<em>d / </em>} x{<em>t / </em>} i{<em>m / </em>} s{<em>s</em>}', target: target_date}).clocks(EC_RUN)

         pageTracker._trackPageview($(this).attr('href'));
       }
    })
  })
  
})

var ui = {
    
  insert_players: function(containers) {
    if (containers.length > 0) {
      containers.each(function(){

        var v_id = $(this).find("p:first").html()
        var c_id = $(this).attr('id')    
        
        var autoplay = (c_id.split('_').length > 2) ? 1 : 0
        
        // YouTube
        if ($(this).hasClass('yt')) {            
          $(this).flash({ 
            swf: 'http://www.youtube.com/v/'+v_id,
            params: { allowScriptAccess: "always", wmode: 'opaque'},   
            flashvars: {enablejsapi: '1', autoplay: autoplay, allowScriptAccess: "always", playerapiid: c_id, showinfo: 0 },   
            height: $(this).height(), width: $(this).width() })
        }
        
        // Vimeo
        if ($(this).hasClass('vimeo')) {
          $(this).flash({ 
            swf: 'http://vimeo.com/moogaloop.swf',
            params: { allowScriptAccess: "always", wmode: 'opaque'},   
            flashvars: {js_onLoad: 'vimeo_player_loaded', clip_id: v_id, js_api: 1, js_swf_id: c_id, autoplay: autoplay, allowScriptAccess: "always", show_title: 0 },   
            height: $(this).height(), width: $(this).width() })
        }

      })
    }
  },
  
  
  flash_message: function(message) {
    // XHR?
    if (message != undefined) {
      $("<div class=\"flashmessage\" style=\"display: none\"><p>"+message+"</p></div>").appendTo('body').fadeIn('normal', function(){
        $(this).oneTime(5000, function(){
          $(this).fadeOut('fast')
        })        
      })
    } else {
      $('.flashmessage').fadeIn('normal', function(){
        $(this).oneTime(5000, function(){
          $(this).fadeOut('fast')
        })
      })          
    }
    
  },
  
  bind_show_info_links: function(links) {
    links.click(function(e){
      var link = $(this)
      
      if (link.parents('.video:first').find(".comments").length > 0) {
        link.parents('.video:first').find(".comments, .links, .share").remove()
        link.html('mere info')
      } else {
        link.html('henter info…')
        $.ajax({
           url: link.attr('href'),
           type: 'GET',
           success: function(html) {   
             link.html('mindre info')
             ui.bind_comments_form($(html).appendTo(link.parents('.video:first')).find('form'))
             
             pageTracker._trackPageview(link.attr('href'))
           }
        })        
      }      
      
      e.preventDefault()
    })
  },
  
  bind_comments_form: function(form) {
    if (form.length > 0) {
      form.submit(function(e){
        form.find('input.ctrl').val('Sender...')
        $.ajax({
          url: $(form).attr('action'),
          type: 'POST',
          data: $(form).serialize(),
          success: function(html) {   
            var container = $(form).parents('.comments')
            
            container.html(html)
            ui.bind_comments_form(container.find('form'))              

           }
        })
                
        e.preventDefault()
      })
    }    
  },
  
  
  bind_bg: function() {

    if ($('.bg').length == 0) {
      $('<div class="bg"></div>').appendTo('body').show().click(function(e){
        
        $(this).hide()
        $("body > .viewer").remove()
        
        e.preventDefault()
      })
      
      $(".bg").css('width', $(document).width()+"px")
      $(".bg").css('height', $(document).height()+"px")
    }
    

  },
  
  bind_close: function(){
    $('a.done').click(function(e){

      $('.bg').hide()
      $("body > .viewer").remove()
      
      e.preventDefault()
    })
  },
    
  bind_rating: function(r) {
    
    if (r.length != 0) {
      
      if(r.find('p').length == 0) {
        r.prepend('<p></p>')
      }
        
      var rating_id = r.attr('id').split('_')[2]
        
      r.find("a").hover(function(){
        $(this).prevAll().andSelf().addClass('active')  
      },function(){
        $(this).prevAll().andSelf().removeClass('active')
      })      

      r.find("a").click(function(e){    
        var link = $(this)
      
        if (link.parent().hasClass('artist')) {
          link.parent().find('p').html('Sender rating…').show()
          $.ajax({
             url: link.attr('href'),
             type: 'POST',
             success: function(html) {   
               var container = link.parent()
             
               link.siblings('a, span').andSelf().remove()
               container.append(html)
               
               container.addClass('rated')
             
               container.oneTime(400, function() {
                $(this).find('p').fadeOut(100)
               })
                          
               ui.bind_rating(container)
               
               var link_parts = link.attr('href').split('/')               
               pageTracker._trackPageview('/vote/value/'+link_parts.last())
               pageTracker._trackPageview('/vote/video/'+link_parts[link_parts.length-2])
               
               pageTracker._trackPageview(link.attr('href'))               
             }
          })
        } else {          
        
          link.parent().find('p').html('Log ind for at rate').show()
        
          link.oneTime(800, function() {
            $(this).parent().find('p').fadeOut(300)
          })
                          
        }     
        e.preventDefault()    
      })
    }
  },
  
  bind_voting: function(r) {
    
    r.each(function(){
      var container = $(this)
      var voting_id = $(this).attr('id').split('_')[2]
        
      container.find("a:first").click(function(e){    
        var vote_url = $(this).attr('href')
      
        if (container.hasClass('artist')) {
          container.html('Sender stemme…')
          $.ajax({
             url: vote_url,
             type: 'POST',
             success: function(html) {   
               container.html(html)                             
                                                      
               pageTracker._trackPageview(vote_url)               
             }
          })
        } else {                  
          container.html('Log ind først')        
        }     
        e.preventDefault()    
      })
      
      
    })
  }
}

stats = {
 watched: function(id) {
   var parts = id.split("_")
   var v_id = parts[parts.length-1]
   if (parseInt(v_id, 10) > 0) {
     $.ajax({
       url: '/videos/'+v_id+'/watch',
       type: 'GET',
       success: function(html) {
         pageTracker._trackPageview('/watch/'+v_id)
         pageTracker._trackPageview('/videos/'+v_id+'/watch')         
       }
     })
   }
 } 
}