//jQuery(document).ready(function() {
//jQuery(function() {
$(function() {  
    
  var timer = {}  
  var q_timer = {}
      
  // Search   
  $('#search-form').submit(function(e){        
    e.preventDefault()    
  })
  
  $('#q').keyup(function(e){    
    $.clearTimer(q_timer)          
    q_timer = $.timer(200, function() {
      ui.search($('#q').val())      
    })                          
  })
  
  
  // Rating
  ui.bind_rating($(".rating"))
  
  
  // Tooltips Start
  $("#categories li a").hover(
    function () {      
      $(this).next().fadeIn(60)
    }, 
    function () {            
      $(this).next().stop()
      $(this).next().css('opacity', 1.0)
      $(this).next().fadeOut(100)
    }
  )
  
  
  // Method labels
  $(".method-menu li").hover(
    function () {      
      $(this).addClass('current')
      $(this).children('.more').show()
      $(this).css("z-index", 100)      
    }, 
    function () {            
      $(this).removeClass('current')
      $(this).children('.more').hide()
      $(this).css("z-index", 90)
    }    
  )
  
  $(".method-menu li").click(function(){    
    document.location = $(this).children("a:first").attr('href')
  })


  // Overlay pages
  $(".overlay").click(function(e){    
    
    var link = $(this)
    
    var id = link.attr('id')
    var overlay_id = "overlay_"+id
    var url = '/pages/'+id.split('_')[1]
    
    var overlay = ui.get_overlay_container()
    
    overlay.css('left', (link.offset().left+link.width()) - overlay.width())
    overlay.show()
    overlay.children(".page:visible").hide()
    
    ui.reset_search()

    // Load    
    if (overlay.children("#"+overlay_id).length == 0) {
      overlay.children('.status').show()      
      $.ajax({
         url: url,
         type: 'GET',
         success: function(html){           
           overlay.children('.status').hide()

           overlay.append(html)
           ui.bind_close_overlay_link()
           ui.bind_hover_tools_table()
         }
      })          
    // Already loaded  
    } else {
      overlay.children("#"+overlay_id).show()
    }
    pageTracker._trackPageview(link.attr('href'))
    e.preventDefault()    
  })
  
  
  // Method body text
  $("div.method li:has(ol)").each(function(){
    var li = $(this)
    li.children('ol').hide()
    
    li.children('ol').before(' <a href="?examples" class="examples">+ Eksempler</a>')
    
    li.children("a.examples").click(function(e){
      var link = $(this)
      
      if (li.children('ol:visible').length != 0) {
        li.children('ol').hide('fast')
        link.html('+ Eksempler')
      } else {
        li.children('ol').show('fast')
        link.html('-')
        
      }
      
      e.preventDefault()
    })
  })
  
  // Hide add to tools if in tools
  $('.rating').each(function(){
    var page_id = $(this).attr('id').split('_')[1]
    if (jQuery.inArray(page_id, ui.parse_methods_cookie()) != -1)
      $(".add-to-tools").hide()
  })
  
  var tools_timer = {} 
  
  // Bind click on add to tools
  $(".add-to-tools a").click(function(e){
    var container = $(this).parent()
    container.html('Tilføjer…')
    $.ajax({
       url: $(this).attr('href'),
       type: 'PUT',
       success: function(html){
         container.html('Denne metode er nu tilføjet dine verktøjer')
         tools_timer = $.timer(4000, function() {           
           container.fadeOut(100)
         })                  
       }
    })    
    e.preventDefault()
  })


  // All links to files - target => blank
  $(".method-container").find('a').each(function(){
    if ($(this).attr('href').search(/^\/assets\//) != -1) {
      $(this).attr('target', '_blank')
    }
  })

})

var ui = {
  
  
  search: function(q) {
    
    if ($('#search-result').length == 0)
      $('body').append('<div id="search-result"></div>')

    var container = $("#search-result")
    container.css('left', ($('#search-form').offset().left+$('#search-form').width()) - container.width())    

    if (q!='') {
      
      $.ajax({
        beforeSend: function(){$('#loading').show()},
        url: '/search',
        type: 'GET',
        data: $('#search-form').serialize(),
        complete: function() {$('#loading').hide()},
        success: function(html){ 
          $('#overlay:visible').hide()

          container.html(html)
          container.show()

          ui.bind_hover_tools_table()
          ui.bind_close_search_link()          
        }
      })      
    }
  },
  
  
  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('_')[1]
        
      if (jQuery.inArray(rating_id, ui.parse_rating_cookie()) == -1) {
        r.find("a").hover(function(){
          $(this).prevAll().andSelf().addClass('active')  
        },function(){
          $(this).prevAll().andSelf().removeClass('active')
        })      
      } else {
        r.addClass('rated')
      }

      r.find("a").click(function(e){    
        var link = $(this)
      
        if (jQuery.inArray(rating_id, ui.parse_rating_cookie()) == -1) {        
          link.parent().find('p').html('Sender stemme')
          $.ajax({
             url: link.attr('href'),
             type: 'POST',
             success: function(html) {   
               var container = link.parent()
             
               link.siblings('a').andSelf().remove()
               container.append(html)
             
               timer = $.timer(400, function() {
                 container.find('p').fadeOut(100)
               })
             
               ui.bind_rating(container)           
             }
          })
        } else {

          link.parent().find('p').html('Du kan kun stemme en gang').show()
        
          timer = $.timer(400, function() {
            link.parent().find('p').fadeOut(300)
          })
                
        }     
        e.preventDefault()    
      })
    }
  },
  
  parse_rating_cookie: function() {
    if ($.cookie('ratings') == null)
      return [] 
  
    return $.cookie('ratings').split(',')
  },

  parse_methods_cookie: function() {
    if ($.cookie('methods') == null)
      return [] 
  
    return $.cookie('methods').split(',')
  },

  
  get_overlay_container: function() {
    if ($('#overlay').length == 0) {
      $('body').append('<div id="overlay"><div class="status">Henter…</div></div>')
    } 
    return $('#overlay')
  },
  
  bind_close_overlay_link: function() {
    $('.page a.close').click(function(e){
      $('#overlay').hide()
      e.preventDefault()    
    })
  },
  
  
  bind_close_search_link: function() {
    $('#search-result a.close').click(function(e){
      ui.reset_search()
      e.preventDefault()    
    })    
  },
  
  bind_hover_tools_table: function() {    
    
    $("table.tools td").click(function(){
      document.location = $(this).parents("tr:first").children('td:last').children('a:first').attr('href')
      e.preventDefault()          
    })    
    
    $("table.tools tr").hover(
      function () {      
        $(this).addClass('current')
      }, 
      function () {            
        $(this).removeClass('current')
      }
    )
    
  },
  
  reset_search: function() {
    $("#search-result:visible").hide()
    $("#search-result:visible").html('')    
    $("#q").val('')
  }
}