var disabled_keys = false;

///////////////////////////////////////////////////////////////////////////
//
//  Comments show/hide
//

function show_add_comments() {
  $('#addcommentsopt').hide();
  $('#addcomments').show();
  location.hash = 'addcomment';
  $('#addcommentnick').focus();
  disabled_keys = true;
}

function hide_add_comments() {
  $('#addcommentopt').show();
  $('#addcomments').hide();
  $('input, textarea')
    .focus(function () { disabled_keys = true; })
    .blur(function () { disabled_keys = false; });
}

///////////////////////////////////////////////////////////////////////////
//
//  Prev/up/next links management
//

var nextlink = "";
var prevlink = "";
var timeout;

function load_relative(href) {
  var href;
  if ($('base').attr('href').substr($('base').attr('href').length - 1) == '/'
      && href.charAt(0) == '/')
    href = href.substr(1);
  location.href = $('base').attr('href') + href;
}

function load_prev() {
  if (prevlink == "")
    return false;

  if (hidden) {
    var form = $('<form action="' + prevlink + '" method="post">');
    form.append($('<input name="nohead" type="hidden">'));
    if (hidden_more)
      form.append($('<input name="nohead_at_all", type="hidden">'));
    form.appendTo($('body'));
    form.submit();
  } else {
    load_relative(prevlink);
  }
  return false;
}

function load_next() {
  if (nextlink == "")
    return false;

  if (hidden) {
    var form = $('<form action="' + nextlink + '" method="post">');
    form.append($('<input name="nohead" type="hidden">'));
    if (hidden_more)
      form.append($('<input name="nohead_at_all" type="hidden">'));
    form.appendTo($('body'));
    form.submit();
  } else {
    load_relative(nextlink);
  }
  return false;
}

var commentaction = "";
var modcommentaction = "";

function add_nohead_links() {
  $('#prevlink').attr('href', prevlink).click(load_prev);
  $('#nextlink').attr('href', nextlink).click(load_next);
  $('#commentform').attr('action', commentaction)
    .append($('<input name="nohead" type="hidden">'));
  $('#modcommentform').attr('action', modcommentaction)
    .append($('<input name="nohead" type="hidden">'));
}

///////////////////////////////////////////////////////////////////////////
//
//  Header show/hide
//

function show_header() {
  $('#head').show();
  $('#prepic').show();
  $('#sizetoggle').show();
  $('#picheader').show();
  $('#picture').unbind('click');
  $('#picture').click(hide_header);
  $('#prevlink').unbind('click');
  $('#nextlink').unbind('click');
  $('#commentform').remove('[name="nohead"]');
  $('#modcommentform').remove('[name="nohead"]');
  hidden = false;
  rescale_picture();
  place_instructions();
}

function hide_header() {
  $('#head').hide();
  if (hidden_more)
    $('#prepic').hide();
  else {
    $('#prepic').show();
    $('#sizetoggle').hide();
    $('#picheader').hide();
  }
  $('#picture').unbind('click');
  $('#picture').click(show_header);
  add_nohead_links();
  hidden = true;
  rescale_picture();
  place_instructions();
}

///////////////////////////////////////////////////////////////////////////
//
//  Help instructions management
//

var fade_degree = 0;
var fading_in = false;
var fading = false;
var auto_fading_out = false;

function place_instructions() {
  if ($('#instructions').length == 0) {
    $('<div id="instructions">' +
      ('prev: <b>backspace</b>    ' +
       'toggle header: <b>h/H/click</b>    ' +
       'up: <b>u</b>    ' +
       'fit: <b>f</b>    ' +
       'full HD: <b>F</b>    ' +
       'next: <b>space</b>').replace(/ /g, '&nbsp;') + '</div>')
      .insertBefore('.pic');
  }
  $('#instructions').css({
    'left': Math.round($('#picture').offset().left) +
      $('#picture').outerWidth() / 2 -
      $('#instructions').width() / 2 + 'px',
    'top': Math.round($('#picture').offset().top) + 7 + 'px'
  });
}

function fade_in() {
  $('#instructions')
    .stopTime('autofadeout')
    .oneTime(3000, 'autofadeout',
	     function () {
	       fading_in = false;
	       if (fade_degree == 10) {
		 $('#instructions').stopTime('fade');
		 fade_instructions();
	       }
	     });

  fading_in = true;
  if (fade_degree == 0) {
    place_instructions();
    $('#instructions').show();
  }
  if (fade_degree != 10) {
    $('#instructions').stopTime('fade');
    fade_instructions();
  }
}

function fade_instructions() {
  if (!fading_in)
    --fade_degree;
  else
    ++fade_degree;

  var ins = $('#instructions');

  switch (fade_degree) {
  case 0:
    ins.css('color', '#000000').hide();
    break;
  case 1:
    ins.css('color', '#0d0d0d');
    break;
  case 2:
    ins.css('color', '#212121');
    break;
  case 3:
    ins.css('color', '#333333');
    break;
  case 4:
    ins.css('color', '#434343');
    break;
  case 5:
    ins.css('color', '#515151');
    break;
  case 6:
    ins.css('color', '#5d5d5d');
    break;
  case 7:
    ins.css('color', '#676767');
    break;
  case 8:
    ins.css('color', '#6f6f6f');
    break;
  case 9:
    ins.css('color', '#7f7f7f');
    break;
  }

  if (fade_degree != 0 && fade_degree != 10) {
    ins.stopTime('fade');
    ins.oneTime(50, 'fade', fade_instructions);
  }
}

///////////////////////////////////////////////////////////////////////////
//
//  Mouse show/hide
//

function hide_mouse() {
  $('#picture').css('cursor', 'none');
}

function show_mouse(e) {
  $('#picture').css('cursor', 'auto').stopTime('hidecursor')
    .oneTime(500, 'hidecursor', hide_mouse);
  fade_in();
}

///////////////////////////////////////////////////////////////////////////
//
//  Keyboard shortcuts management
//

///////////////////////////////////////////////////////////////////////////
//
//  Picture fitting to the screen management
//

var picturewidth;
var pictureheight;
var picturehdwidth;
var picturehdheight;

function toggle_fit() {
  picturefit = !picturefit;
  rescale_picture();
  if (picturefit)
    $.cookie('picsizefit', '1', { expires: 365,
				  path: '/',
				  domain: '.qult.net' });
  else
    $.cookie('picsizefit', null, { path: '/', domain: '.qult.net' });
  $('#sizetogglelink').empty().append(picturefit ? "don't fit" : "fit");;
}

function rescale_picture() {

  var scale = scale_picture();
  $('#picture').css(scale['css']);
}

///////////////////////////////////////////////////////////////////////////
//
//  Picture loading
//

var picturetitle;
var picturesrc;
var picturecredits;
var loadpicturelater = false;

function load_picture_later(title, src, credits) {
  picturetitle = title;
  picturesrc = src;
  picturecredits = credits;
  loadpicturelater = true;
}

///////////////////////////////////////////////////////////////////////////
//
//  Installation of various functions into the right places
//

function install_hiding() {
  if (hidden)
    add_nohead_links();
  $('#picture').click(hidden ? show_header : hide_header);
}

function install_links() {
  $(window).keypress(function (e) {
    if (disabled_keys)
      return true;

    if (e.which == 70) {
      load_hd();
    } else if (e.which == 104) {
      if (hidden)
	show_header();
      else
	hide_header();
      return false;

    } else if (e.which == 72) {
      hidden_more = !hidden_more;
      hide_header();
      return false;

    } else if (e.which == 102) {
      toggle_fit();
      return false;

    } else if (e.which == 32) {
      load_next();
      return false;

    } else if (e.which == 8) {
      load_prev();
      return false;

    } else if (e.which == 117) {
      location.href = $('#uplink').attr('href');
      return false;
    }
    return true;
  });
  $('#picture').mouseenter(hide_mouse)
    .mousemove(show_mouse).mousedown(show_mouse).attr('title', "");
  $('#prevlink').attr('accesskey', null);
  $('#nextlink').attr('accesskey', null);
  $('#uplink').attr('accesskey', null);
}

function install_toggle() {
  $('#sizetogglelink')
    .attr('href', 'javascript:toggle_fit()')
    .empty()
    .append(picturefit ? "don't fit" : "fit");

  $('#sizetogglelink')
    .clone()
    .removeAttr('id')
    .attr('href', 'javascript:load_hd()')
    .empty()
    .append("full HD")
    .insertAfter(
      $('<span>')
	.css({ 'padding-left': '1.5ex', 'padding-right': '1ex' })
	.append("|")
	.insertAfter('#sizetogglelink'));
  $(window).resize(rescale_picture);
}

///////////////////////////////////////////////////////////////////////////
//
//  Calls to various functions at end of loading
//

function scale_picture() {
  var roomw = $(window).width() - 2 * 30;
  var roomh = $(window).height() -
    Math.round($('#prepic').offset().top) - $('#prepic').height() - 2 * 30;
  var horizontally = false;
  var vertically = false;

  if (roomw < picturewidth) {
    if (roomh < pictureheight) {
      if (roomw / picturewidth < roomh / pictureheight)
	horizontally = true;
      else
	vertically = true;
    } else
      horizontally = true;
  } else if (roomh < pictureheight)
    vertically = true;

  var combined = [];

  if (picturefit && vertically)
    combined['css'] = {
      'width': (combined['width'] = Math.round(picturewidth *
					       (roomh / pictureheight))) + 'px',
      'height': (combined['height'] = roomh) + 'px'
    };
  else if (picturefit && horizontally)
    combined['css'] = {
      'width': (combined['width'] = roomw) + 'px',
      'height': (combined['height'] = Math.round(pictureheight *
						 (roomw / picturewidth))) + 'px'
    };
  else {
    combined['width'] = picturewidth;
    combined['height'] = pictureheight;
    combined['css'] = { 'width': 'auto', 'height': 'auto' };
  }

  return combined;
}

$(document).ready(function() {
  if (loadpicturelater) {
    var scale = scale_picture();
    var pic = $('<img id="picture" src="' + picturesrc +
		'" alt="[picture]" />');
    pic.css(scale['css'])
      .css({
	'background': 'black',
	'color': 'white'
      });

    $('#piclink')
      .replaceWith($('<div id="picholder" />')
    		   .css({ 'width': (scale['width'] + 60) + 'px',
    			  'height': (scale['height'] + 60) + 'px' })
    		   .append($('<div id="picholderchild">' +
    			     '<div id="picholdergrandchild">loading...' +
    			     '</div></div>')));

    var alreadypassed = false;
    pic.load(function() {
      if (alreadypassed)
	return;
      alreadypassed = true;
      $('#picholder').replaceWith($(this));

      if (picturecredits != "") {
	$(this).after($('<div id="creditswrapper">' +
			'<div id="credits" style="width: ' +
			(scale['width'] + 30) + 'px">' +
			picturecredits + '</div></div>'));
      }

      install_hiding();
      install_links();
    });
    install_toggle();
    if (pic.attr('complete'))
      pic.load();
    $('#picture').show();
  } else {
    install_toggle();
    install_hiding();
    install_links();
  }
});

function load_hd() {
  var hash_suffix = location.href;
  var index = hash_suffix.indexOf($('base').attr('href'));
  if (index == -1)
    return false;
  hash_suffix = hash_suffix.substr($('base').attr('href').length);
  index = hash_suffix.indexOf(cat);
  if (index == -1)
    return false;
  hash_suffix = hash_suffix.substr(cat.length);
  hash_suffix = hash_suffix.replace(/\//, '');
  hash_suffix = hash_suffix.replace(/\.html\??.*/, '');
  location.href = cat + '/?HD#' + hash_suffix;
}
