// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

jQuery(document).ready(function($) {
  
  
  function splitTime(a){
    var hours = (Math.floor(a/3600)).toString();
    var minutes = (Math.floor(a/60)-(hours*60)).toString();
    var seconds = (Math.floor(a-(hours*3600)-(minutes*60))).toString();
    if (hours.length < 2) {hours = '0'+hours;}
    if (minutes.length < 2) {minutes = '0'+minutes;}
    if (seconds.length < 2) {seconds = '0'+seconds;}
    var hs=':';
    var ms=':';
    return hours + hs + minutes + ms + seconds;
  }
  
  // admin
  $('body.admin .field p.help').each(function(index, element) {
   $(element).hide();
   var toggleLink = $("<a class='help-toggle'></a>").attr('href', '#');
   $(element).siblings('label').append(toggleLink);
  });
  
  $('body.admin a.help-toggle').live('click', function() {
    $(this).parent().siblings('p.help').toggle();
    return false;
  });
  
  // Admin Help qTips
   $('#person_screen_name').qtip({
      content: "Enter the user's twitter screen name here, omitting the @ symbol.",
      show: 'focus',
      hide: 'blur',
      position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
      style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
   });
   
   $('#person_tag_list').qtip({
       content: "Enter tags separated with commas.",
       show: 'focus',
       hide: 'blur',
       position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
       style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
    });
    
   $('textarea#screen_names').qtip({
       content: "Enter twitter screen names, one per line. You don't need to use the @ symbol.",
       show: 'focus',
       hide: 'blur',
       position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
       style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
    });
    
  $('input#site_name').qtip({
      content: "Enter a name for your directory.",
      show: 'focus',
      hide: 'blur',
      position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
      style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
   });  
     
  $('textarea#site_description').qtip({
     content: "Enter a description for your directory. This will appear in the About Us widget.",
     show: 'focus',
     hide: 'blur',
     position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
     style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
  });
      
  $('input#site_twitter_search_url').qtip({
      content: "Enter your community's Twitter search term.",
      show: 'focus',
      hide: 'blur',
      position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
      style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
   });
  $('textarea#new_stop_words').qtip({
    content: "Enter any custom stop words you would like to prohibit from appearing in your directory's trending topics.",
    show: 'focus',
    hide: 'blur',
    position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
    style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
  });
  $('textarea#site_custom_css').qtip({
    content: "Enter any custom css overrides you would like to use. With normal css syntax, you can completely customize your design.",
    show: 'focus',
    hide: 'blur',
    position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
    style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
  });
  
  $('input#google_web_property_id').qtip({
      content: "If you use Google Analytics you can enter the web property ID here. (UA-XXXXXXX-XX)",
      show: 'focus',
      hide: 'blur',
      position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
      style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
   });
   $('input#site_domain').qtip({
       content: "Set your custom domain here. (ex: http://yourdomain.com) Please ensure you've set up the proper CNAME record with your registrar.",
       show: 'focus',
       hide: 'blur',
       position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
       style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
    });
    
    $('input#new_admin').qtip({
         content: "Enter a twitter username and hit enter to add that person as a directory admin.",
         hide: 'blur',
         position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' } },
         style: { name: 'cream', tip: { corner: 'bottomLeft', size: {x: 8, y : 20 },}  }
      });
  // fix missing twitter avatars
  $('img.avatar').error(function() {    
    $(this).attr('src', '/images/no-image.png');
  });
  

  $('a[class*=timeago]').livequery(function() {
    $(this).timeago();
  });
  
  
  $.each($('input.prompt'), function() {
     $(this).val($(this).attr('title')).addClass('prompted')
      .focus(function() {
        if($(this).val() == $(this).attr('title')) $(this).val('').toggleClass('prompted');
      })
      .blur(function() {
        if($(this).val() == '') $(this).val($(this).attr('title')).toggleClass('prompted');
      });
      
  });
  
  $('select.admin-menu').change(function() {
    if($(this).val().length > 0) {
      window.location.href = $(this).val();
    }
  });

  $('select#admin-menu').change(function() {
    if($(this).val().length > 0)
      window.location.href = $(this).val();
  });
  
  $('ul.tools.views a').live('click', function() {
    var tool = $(this).parent();
    tool.parent('ul').find('li').removeClass('selected');
    tool.addClass('selected');
    if (tool.hasClass('grid')) {
      $('ul.flockers').addClass('grid');
    }
    else {
      $('ul.flockers').removeClass('grid');
    }
    
    return false;
  });
  
  $('#bar-graphs dd').each(function() {
    var bar = $(this);
    var w = bar.css('width').replace('px', '');
    bar.css('width', '0px');
    bar.animate({width: w+'px'}, 1000);
  });
  
  $('p.help, #impact h3').append("<span class='arrow'></span>");
  
  $('body.admin #sidebar ul li a').append("<span class='arrow'></span>");

  $('.flash.success, .flash.error, .flash.notice').oneTime(7500, function() {
    $(this).fadeOut('slow');
  });
  
  $('#reset_time_in_seconds').everyTime(1000, function() {
    var reset_in_seconds = $(this).attr('title');
    if(reset_in_seconds) {
      var resetDate = new Date(reset_in_seconds*1000);
      var resetInSeconds = (resetDate - (new Date()))/1000;
      $(this).text(splitTime(resetInSeconds));
    }
    
  });
  
  
  $('#remaining_hits').everyTime(60000, function() {
    var remaining_hits = $(this);
    $.getJSON('/site/rate_limit_status.json', function(rate_limit_status) {
      remaining_hits.text(rate_limit_status.remaining_hits);
      $('#reset_time_in_seconds').attr('title', rate_limit_status.reset_time_in_seconds);
    });
  });

  // tweetstream voting
  // $('.tweetlinks .vote').click(function(){
  //   $.post("/vote", {status_id: this.id, authenticity_token: $('#authenticity_token').text()}, 
  //     function(data){
  //       $('div#error-vote-count-' + data.status_id).hide("slow");
  //       if (data.error != "") {
  //         $('div#error-vote-count-' + data.status_id).html(data.error).show("slow");
  //       }
  //       else {
  //         $('span#vote-count-' + data.status_id).html("(" + data.count + " votes)").css("background-color", "yellow").animate({opacity: 0.1}, 1000, function(){
  //           $(this).show("slow").animate({opacity: 1.0}, 1000).css("background-color", "");
  //         });
  //         $('span#vote-image-' + data.status_id).html("<img src=\"/images/icons/fugue2/thumb-up-disable.png\" title=\"You already voted for this!\">");
  //         $('div#success-vote-' + data.status_id).html("Thanks for voting!").show("slow").animate({opacity: 1.0}, 3000, function(){
  //           $(this).hide("slow");
  //         });
  //       }
  //     }, "json");
  //     return false;
  // });
  // 
  $('#tag-drilldown form').submit(function() {
    var newTagField = $('#new-tag');
    return !(newTagField.hasClass('prompted') || newTagField.val().length == 0);
  });
  
  
  // put all twitter links in a new window
  $('a[href*=twitter.com]').attr('target', '_blank');
  
  // lightbox for youtube videos
  $('a[href*="youtube."]').click(function(){
    
    $.fancybox({
          'title'     : this.title,
          'titlePosition': 'inside',
    			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
    			'type'			: 'swf',
    			'swf'			: {
    			   	 'wmode'		: 'transparent',
    				'allowfullscreen'	: 'true'
    			}
    });
    return false;
  });
  

  // Create the modal backdrop on document load so all modal tooltips can use it
  $('<div id="qtip-blanket">')
     .css({
        position: 'absolute',
        top: 0, // Use document scrollTop so it's on-screen even if the window is scrolled
        left: 0,
        height: $(document).height(), // Span the full document height...
        width: '100%', // ...and full width

        opacity: 0.7, // Make it slightly transparent
        backgroundColor: 'black',
        zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
     })
     .appendTo(document.body) // Append to the document body
     .hide(); // Hide it initially
     
   
   // lightbox for images
   $('a[rel*=lightbox]').fancybox({
     'titlePosition': 'inside'
   });
  
});