$(document).ready(function() {
  selector_init('.selector');
  
	ajaxify_links('a.ajax');
	scrollify_local_links('a[href*=#]');
  color_links('#contents a');
  color_links('.topmenu#navigation a, #footer a');
  $('#new_time').hide();
  $('#show_time_form').click(function(){
    $('#time').css("color", "#555");
    $('#time.current').css("background-color", "#efd");
    $('#new_time').show();
  });
  
	//$('table.sortable').tablesorter();
});

function selector_init(selector) {
  $(selector).change(function() {
	  $(this).find('option').each(function() {
			$('.selectable#'+this.value).hide();
			$('.selectable.'+this.value).hide();
	  });
		$(this).find('option:selected').each(function() {
			$('.selectable#'+this.value).show();
			$('.selectable.'+this.value).show();
		});
	}).change();
}

function color_links(links){
  $(links).each(function(){
    if(!$(this).hasClass("no_coloring")){
      $(this).hover(
        function(){
          $(this).css("color", "#d00");
        },
        function(){
          $(this).css("color", "#ddd");
        })
      .css("color", "#ddd")
      .wrapInner("<span></span>");
    }
  });
}

function ajaxify_links(links) {
	$(links).click(function() {
	  var rel = this.rel.split("-->");
		$(rel[1]).load(this.href + " " + rel[0]);
		$(rel[1]).ajaxComplete(function(){
		  color_links($(this).find('a'));
	  	ajaxify_links($(this).find('a.ajax'));
	    scrollify_local_links($(this).find('a[href*=#]'));
		});
		return false;
	});
}

function scrollify_local_links(links) {
	// Enable smooth scrolling for in-page links.
	$(links).each(function() {
		if ((this.host == location.host || this.host == location.hostname) &&
			this.pathname == location.pathname &&
			this.hash.replace(/#/,'').length) {
			var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
			var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
			if ($target) {
				var targetOffset = $target.offset().top - 15;
				$(this).click(function() {
					$('html, body').animate({scrollTop: targetOffset}, 400);
					return false;
				});
			}
		}
	});
}