// Check if the category list appears on the page.
// If it does, we need to do some work to make sure that
// the visible categories don't exceed the width of the
// category-bar, and put the excess ones into the drop-down
// at the end of the list.
function adjustCategoryBar() {
  if($('ul#category').length > 0) {

    var visible_width = 0; // A counter for the total width of the currently visible elements.
    var available_width = $('ul#category').width(); // The predefined width of the visible categories.

    // For each visible tag...
    $('ul#category li a').each(function() {

      // Calculate the accumulating width of the visible elements.
      var li_width = $(this.parentNode).width();

      // If this is the first li that exceeded the available_width,
      // adjust the category width to the previous visible_width.
      if(visible_width < available_width && visible_width + li_width > available_width) {
        $('ul#category').width(visible_width);
      }

      visible_width += li_width;

      // If the current width of the visible elements exceeds the available width then...
      if(visible_width > available_width) {

        // Move this LI tag into the category drop-down at the end of the list.
        $('ul#category li ul').append($(this.parentNode));
      }
    });

    // Check that the currently selected tag is visible,
    // and if not, prepend it to the list.
    var selected_tag = $('ul#category li ul li a.selected');
    if(selected_tag.length > 0) {
      $('ul#category').prepend(selected_tag[0].parentNode);
      adjustCategoryBar();
    }
  }
}

top.Menu = {
  isReady: false,

  addContent: function(body) {
    $(body).html(top.menu_html);
  },

  resizeHeight: function(height) {
    height += 2;
//    console.info("Trying to resize to ", height, " from ", $('#menu').height() )
    $('#menu').height( height );
  },

  snapIntoPosition: function() {
    var offset = $("#category").offset();
    offset.top += $("#category").height();
    $('#menu').css( offset );
  },

  startTracking: function() {
    Menu.open = true;
  },

  mouseLeave: function() {
    Menu.hide();
  },

  show: function() {
    Menu.snapIntoPosition();
    Menu.startTracking();
    $("#menu").show();
  },

  hide: function() {
    $("#menu").hide();
    Menu.open = false;
  },

  navigateTo: function(url) {
//    console.info(url);
    location.href = url;
  }
}

// Page setup
// $(adjustCategoryBar);
if(jQuery == $) {

  $(function() {
    // BEHAVIOUR: Flash Notifications
    //jQuery.highlightFade.default.speed = 1000;

    notifications = {
      '.notice': '#8888ee',
      '.warning': '#ff0000'
    }

    for(var selector in notifications) {
      $(selector).each(function(notification) {
        if(this.getAttribute('highlighted') == null && this.style.display != 'none') {
          $(this).highlightFade(notifications[selector]);
          this.setAttribute('highlighted', true);
        }
      });
    }
  });

  $(function() {
   /**
    * Totally need to look at Ken's style defs here and figure out if I can just use show() & hide()
    */
   $("#ftpOptionsButton").click(function() {
    $(this).addClass("ftpOptionsOn").removeClass("ftpOptions");
    $("#instantDownloadButton").removeClass("instantDownloadOn").addClass("instantDownload");
    $("#instantDownloadOptions, #instantFTP").hide();
    $("#ftpOptions").show();
   });

   $("#instantDownloadButton").click(function() {
    $(this).addClass("instantDownloadOn").removeClass("instantDownload");
    $("#ftpOptionsButton").removeClass("ftpOptionsOn").addClass("ftpOptions");
    $("#instantDownloadOptions").show();
    $("#ftpOptions, #instantFTP").hide();
   });

   $("#createInstantFTP").click(function(){
    $("#ftpOptions").hide();
    $("#instantFTP").show();
   });

   $("#instantFTPSubmit").click(function() {
    $.post($("#instant_ftp_emails")[0].action,
     $("input[@name='instant_ftp[email][]']").serialize(),
     function(data) {
      $("#instantFTP").empty().append(data);
     }
    );
    return false;
   });
  });

  function markPaginators() {
    $('#pagination a').click(function() {
      $('#videoList').load(this.href, null, markPaginators);
      return false;
    });
  }

  $(markPaginators);

  // Form validation for videos...
  $(function(){
    $("#video_filename").after('<div id="video_filename_error" class="error-message" style="display:none;">&nbsp;</div>');

    $("#video_filename").blur(function(){
      var errMsg = validateFilename();
      if(errMsg != $("#video_filename_error").html() )
        $("#video_filename_error").slideUp(200, function(){
          $("#video_filename_error").html(errMsg);
          if(errMsg != '') $("#video_filename_error").slideDown(200);
        });
    });

    $("#video-form").submit(function(){
      if(validateFilename() == '')
        return true;
      else {
        $("#video_filename").highlightFade()
        $("#video_filename").blur();
        return false;
      }
    })


    try {
      $("#video_filename").blur();
    } catch(ignore) {}
  });


}

function validateFilename() {
  var value = $("#video_filename").val();
  var errMsg = '';
  if( value == '' )
    errMsg = "<span>^</span> Filename can't be empty.";
  else if( value.indexOf('.') > 0 )
    errMsg = "<span>^</span> Please don't add a file extension to the Filename.";
  else if( /\W/.test(value) )
    errMsg = "<span>^</span> Filename can't have whitespace.";
  return errMsg;
}

jQuery.fn.hoverClass = function(c) {
    return this.each(function(){
        $(this).hover(
            function() { $(this).addClass(c);  },
            function() { $(this).removeClass(c); }
        );
    });
};

$(document).ready(function(){
 $(".Nav").superfish({
  animation : { opacity:"show"}
 });
});
