$(document).ready(function() {
    ATEL.init();
    $.ajaxSetup({
        data: {
            authenticity_token: AUTH_TOKEN
        }
    });
});

ATEL = {
    init: function() {
        // focus on searchfield if available
        $("#query_content").focus();

        // Open lightbox when clicking on a recommend link
        $('.recommend').each(function() {
            this.href = '#TB_inline?width=500&height=500&inlineId=recommend_lightbox';
        });

        // Select embed code in input field when clicking it
        $('input#embed').click(function() {
            this.select();
        });

        // No flash activated fallback
        $('.noflash').show();

        /* Live check if email is already verified */
        var comment_email_verified;
        $('#comment_email').blur(function(){
          var comment_email_field = $(this);
          var comment_email_status = $('.input_row .comment_email_status');
          $.getJSON('/email_verifications/check?email='+comment_email_field.val(), function(data){
            if(data.verified == true){
              comment_email_verified = true;
              var image = '<img src="/images/layout/ico-email-verified.png" alt="E-Mail Status" />';
              comment_email_status.html(image + " " + data.message);
            } else if(data.verified == false){
              comment_email_verified = false
              var image = '<img src="/images/layout/ico-email-not-verified.png" alt="E-Mail Status" />';
              comment_email_status.html(image + " " + data.message);
            }else{
              comment_email_verified = false;
              comment_email_status.html('');
            }
          });         
        });

        /* User notification that the email really, truly must be valid */
        $('form#new_comment').submit(function(){
          var answer;

          if(comment_email_verified == true){
            return true;
          } else{
            answer = confirm(loc_email_verification_your_email+": "+$('#comment_email').val()+"\n\n"+loc_email_verification_confirm);
          }
          
          if(answer == true){
            return true
          } else {
            return false;
          }
        });

        // Bind ajax form events
        this.bindRecommendationFormEvents();
        this.bindPollFormEvents();
        this.insertRatingStars();

        // Bind video list events
        if($('#main-wrap.videos.index').length > 0){
          this.bindVideoListEvents();
          this.bindVideoFilterEvents();
        }

        // Bind Event Videos list events
        if($('#main-wrap.events.show').length > 0){
          this.bindVideoListEvents();
          this.bindVideoFilterEvents();
        }
 
        // Automatically print page
        if (window.location.href.match(/\?print=true/)) {
            window.print();
        }

        // Comments
        // Hide all comments except the 2 most recent 
        // unless an anchor for the comments is presend (hash)
        if (!window.location.hash.match(/#comment-\d+/)) {
            var comment_lis = $('div.videos .comment-container ul.comments li');
            var comment_count = comment_lis.length;
            var comment_lis_to_hide = comment_lis.filter(function(index) {
                // return index < comment_count - 2;
                return index > 1;
            });
            comment_lis_to_hide.each(function() {
                $(this).hide();
            });
            
            // Insert toggle links
            if (comment_count > 2) {
                $('#show-comments').append('<img id="toggle_image" alt="' + loc_toggle_comments_on + '" src="/images/layout/ico-plus.gif"/>');
                $('ul.comments').after("<div class='comments_footer clearfix'><div class='toggle-comments'><a id='toggle_link' href='javascript:void(0)'>" + loc_toggle_comments_on + "</a></div></div>");
            }
        }


        // Toggle visibility of comments
        $('.toggle-comments').click(function() {
            comment_lis_to_hide.slideToggle(function(){
                if($('#toggle_image').attr('alt') == loc_toggle_comments_off){
                    $('#toggle_image').replaceWith('<img id="toggle_image" alt="' + loc_toggle_comments_on + '" src="/images/layout/ico-plus.gif"/>');
                    $('#toggle_link').replaceWith('<a id="toggle_link" href="javascript:void(0)">' + loc_toggle_comments_on + '</a>');
                }else{
                    $('#toggle_image').replaceWith('<img id="toggle_image" alt="' + loc_toggle_comments_off + '" src="/images/layout/ico-minus.gif"/>');
                    $('#toggle_link').replaceWith('<a id="toggle_link" href="javascript:void(0)">' + loc_toggle_comments_off + '</a>');
                }
            });
            return false;
        });

        $('ul#social_bookmarks li a').click(function() {
            window.open($(this).attr('href'));
            return false;
        });


        $('#sb_google').click(function() {
            window.open('http://www.google.com/bookmarks/mark?op=add&hl=de&bkmk=' + encodeURIComponent(this.currentUrl) + '&annotation=&labels=&title=' + encodeURIComponent(document.title));
        });

        // Set initial descriptions for input fields
        $('input#query').labelify();
        $('input.subscription_field').labelify();
        $('input#list_query').labelify();

        // External Links
        $("a[rel*='external']").ATEL_LinkExt();
    },

    insertRatingStars: function(){
      $('div.scouts-rating input.submit').hide();
      $('.vote_rate').hide();
      $('.scouts-rating-status').html($('.vote_rate').attr('value'));
      $('.scouts-rating-status').show();

      // Jquery Star rating plugin: http://www.fyneworks.com/jquery/star-rating/#tab-Overview      
      $('div.scouts-rating input.stars').rating(
        {
          required: true, // disable cancel button
          callback: function(value, element){
            
            var container = $(element).parents('.scouts-rating:first');
            var url = container.find('form').attr('action');
            container.html(ATEL.loaderHtml());

            $.post(url, {
                rating: value
            }, function(data) {
              container.replaceWith(data);
              ATEL.insertRatingStars();
            });
          }
        }
      );     
    },

    // Ajaxify recommendation form in lightbox
    // Only do it if the form is in a hidden lightbox container
    bindRecommendationFormEvents: function() {
        $('#recommend_lightbox #new_recommendation').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#TB_ajaxContent .sendafriend',
                success: ATEL.bindRecommendationFormEvents
            });
            return false;
        });

      $('form .show-notice').mouseover(function(){
        $('form .notice-receivers').parent().css({position: 'relative'});
        $('form .notice-receivers').css('display','block');
      });
      $('form .show-notice').mouseout(function(){
        $('form .notice-receivers').css('display','none');
      });
    },

    // Send poll, show poll results
    bindPollFormEvents: function() {
        $('#polling_form').submit(function() {
            var selected_vote_id = $("#polling_form input:checked").attr('value');
            $.post(this.action, {
                poll_option_id: selected_vote_id
            }, function(data) {
                $('#poll_replace').html(data);
                ATEL.bindPollFormEvents();
            });
            return false;
        });
    },

  showVideoListLoader: function(){
    $('.list-overview-container').html(ATEL.loaderHtml());
  },

  bindVideoListEvents: function(){
    // make ajax request for search results
    $('.list_search_form').unbind('submit').submit(function() {

        // Reset sort burrons
        $('div.list-sorting a').each(function() {
            $(this).removeClass('active');
        });

        ATEL.showVideoListLoader();
        var search_url = 'query=' + $('#list_query').val();
        if($('#event_id').val()){
          search_url += '&event_id=' + $('#event_id').val();
        }

        $.get(this.action, search_url, function(res) {
          $('.list-overview-container').html(res);
          ATEL.bindVideoListEvents();
        });
        return false;
    });

    // Video list
    // Per page links
    $('div.list-overview-container ul.per_page_switch li a').unbind('click').click(function(){
      ATEL.showVideoListLoader();
      $('.list-overview-container').load(this.href + " .list-overview-container", ATEL.bindVideoListEvents);
      return false;
    });

    // Video list
    // Pagination
    $('div.list-overview-container div.pagination a').unbind('click').click(function(){
      ATEL.showVideoListLoader();
      $('.list-overview-container').load(this.href + " .list-overview-container", ATEL.bindVideoListEvents);
      return false;
    });    
  },

  bindVideoFilterEvents: function() {
    // Sort filters
    $('div.list-sorting a').click(function() {
        ATEL.showVideoListLoader();
        $('.list-overview-container').load(this.href + " .list-overview-container", ATEL.bindVideoListEvents);
        $('#list_query').val('').labelify(); // reset search field
        $('div.list-sorting a').each(function() {
            $(this).removeClass('active');
        });
        $(this).addClass('active');
        return false;
    });
  },

  loaderHtml: function(){
    return '<img src="/images/loading.gif" alt="loading" title="loading" class="loading" />';    
  },

  currentUrl: function() {
      var retURL = '' + location.href;
      retURL = retURL.replace(/&?SID=[0-9a-f]+/g, "");
      retURL = retURL.replace(/\?$/g, "");
      return retURL;
  }
};

/**
 * jQuery-Plugin
 * Adds atttributes class="external" and target="blank" to tag
 */
$.fn.ATEL_LinkExt = function() {
  $(this).each(function() {
    $(this).addClass('external').attr('target', '_blank');
  });
};
