$(document).ready(init);

function init()
{
  $('#content').append('<div style="clear:both"/>');

  // sidebar
  $('#sidebar_hide').click(sidebarHide);
  $('#sidebar_show').click(sidebarShow);
  setSidebar($.cookie('nosidebar'));

  // style
  setStyle($.cookie('style'));

  // layout
  setLayout($.cookie('layout'));

  positionCommentSyntax();

  $('.showhide').click(show_hide);
  $('.showhide').each(function(){ $('#' + $(this).attr('rel')).hide(); });

  $('#change_tags').ajaxForm({dataType: 'json', url: '/xml/blog-change-tags', success: blog_tags_update});
  $('#blog_edit').ajaxForm({dataType: 'json', url: '/xml/blog-update', success: blog_update});
  $('#pict_edit').ajaxForm({dataType: 'json', url: '/xml/pict-update', success: pict_update});

  $('#comment-add').ajaxForm({dataType: 'json', url: '/xml/comment', success: comment_update, beforeSubmit: comment_validate});

  $('.comment-reply').click(commentReply);

  setCommentsView($.cookie("comments_style"));
}

function setSidebar(hidden)
{
  if (hidden)
  {
    $('#sidebar').hide();
    $('#sidebar_hide').hide();
    $('#content').css('margin-right', '0px');
  }
  else
    $('#sidebar_show').hide();
}

function sidebarHide(event)
{
  $.cookie('nosidebar', 1, { path: '/', expires: 300 });
  event.preventDefault();
  $('#sidebar').fadeOut('fast', function() {
    $('#content').css('margin-right', '0px');
    $('#sidebar_hide').hide();
    $('#sidebar_show').show();
  });
}

function sidebarShow(event)
{
  $.cookie('nosidebar', null, { path: '/' });
  event.preventDefault();
  $('#sidebar').fadeIn('fast');
  $('#sidebar_show').hide();
  $('#sidebar_hide').show();
  $('#content').css('margin-right', '200px');
}

function setStyle(name)
{
  if ($('#setstyle-'+name).hasClass('active'))
    return;

  if (name)
    // set or refresh cookie
    $.cookie("style", name, { path: '/', expires: 300 });
  else
    // set default style
    name = 'Light';

  $('link[rel$=stylesheet][title]:not([title='+name+'])').attr('disabled', 'disabled');
  $('link[rel$=stylesheet][title='+name+']').removeAttr('disabled');

  switchSelect('setstyle', name);
}

function setLayout(name)
{
  if ($('#setlayout-'+name).hasClass('active'))
    return;

  if (name)
    // set or refresh cookie
    $.cookie("layout", name, { path: '/', expires: 300 });
  else
    // set default layout
    name = 'fixed';

  if (name == 'fixed')
    $('#page').addClass('fixed');
  else
    $('#page').removeClass('fixed');

  switchSelect('setlayout', name);
}

function switchSelect(sname, iname)
{
  $('.'+sname+':not([href])').each(function(){ $(this).removeClass('active').attr('href', $(this).attr('alt')) });
  $('#'+sname+'-'+iname).each(function(){ $(this).addClass('active').attr('alt', $(this).attr('href')).removeAttr('href'); });
}

function commentsView(name)
{
  $.cookie("comments_style", name, { path: '/', expires: 300 });
  document.location.reload(false);
}

function setCommentsView(name)
{
  if (!name)
    name = 'flat';

  $('#comments-view-'+name).addClass('active').removeAttr('href');

  if (name == 'threads')
    makeHierarchicalComments();
  else
    makeFlatComments();
}

function show_hide(event)
{
  event.preventDefault();
  var target = $( '#' + $(this).attr('rel') );
  target.toggle();
  $(this).toggleClass('showhide_hide');
  if ($(this).hasClass('showhide_jump') && target.is(':visible'))
  {
    window.location.hash = target.attr('id');
  }
}

function blog_update(data)
{
  $("#blog_content").html(data.content);
  $("h1").text(data.title);
  if (data.saved)
  {
    $("#blog_edit").hide("fast");
    $("#show_blog_edit").toggleClass('showhide_hide');
  }
}

function blog_tags_update(data)
{
  $("#change_tags").hide("fast");
  $("#show_change_tags").toggleClass('showhide_hide');
}
function pict_update(data)
{
  $("#pict_content").html(data.content);
  $("h1").text(data.title);
  if (data.saved)
  {
    $("#pict_edit").hide("fast");
    $("#show_pict_edit").toggleClass('showhide_hide');
  }
}

function comment_update(data)
{
  $("#comment-message").html('');

  if (data.status == 'preview')
  {
    $("#comment-preview .comment").show();
    $("#comment-preview .comment-body").html(data.content);
    if (data.www)
    {
      $("#comment-preview .WWW").show();
      $("#comment-preview .WWW a").attr('href', data.www).html(data.author);
      $("#comment-preview .JustName").hide();
    }
    else
    {
      $("#comment-preview .JustName").show().html(data.author);
      $("#comment-preview .WWW").hide();
    }
  }
  if (data.status == 'saved')
  {
    $("#comment-add").hide("fast");
    $("#show-comment-add").removeClass('showhide_hide');
    location.reload(true);
  }
  if (data.status == 'duplicate')
  {
    $("#comment-message").html('<strong>Komentář již byl odeslán.</strong>');
  }
  if (data.status == 'error')
  {
    $("#comment-message").html('<span class="error">Interní chyba. Kontaktujte administrátora.</span>');
  }
  window.location.hash = 'show-comment-add';
}

function comment_validate(formData, jqForm, options)
{
  var form = jqForm[0];
  if (!form.c_author.value || !form.c_source.value)
  {
    $("#comment-message").html('Prosím, vyplňte jméno a obsah komentáře.');
    return false;
  }
  $("#comment-message").html('Odesílám...');
  return true;
}

function makeHierarchicalComments()
{
  $('#comments .comment[rel]').each(function(){
    $(this).css('margin', '8px');
    $('#' + $(this).attr('rel') ).append($(this));
  });
}

function makeFlatComments()
{
  var i = 1;
  $('#comments .comment').each(function(){
    $(this).attr('alt', i);
    var id = $(this).attr('id').substr(8);
    $(this).find('.comment-head').prepend('<a href="#comment-'+id+'">['+i+']</a>');
    $(this).find('.comment-reply').attr('alt', i);
    i++;
  });
  $('#comments .comment[rel]').each(function(){
    var parent = $('#' + $(this).attr('rel'));
    var num = parent.attr('alt');
    var id = parent.attr('id').substr(8);
    var name = parent.find('.comment-head>span:first').text();
    var prep = $('<div><a href="#comment-'+id+'"></a></div>');
    prep.children().text('↪ [' + num + '] ' + name + ':');
    $(this).find('.comment-body').prepend(prep);
  });
}

function commentReply()
{
  var id = $(this).attr('rel').substr(8);
  var num = id;
  if ($(this).attr('alt'))
    num = '['+$(this).attr('alt')+']';
  if ($('#comment-add').is(':hidden'))
  {
    $('#comment-add').show();
    $('#show-comment-add').addClass('showhide_hide');
  }
  window.location.hash = 'show-comment-add';
  $('#comment-reply-info').show();
  $('#comment-reply-info span').text(num);
  $('#comment-reply-info a').attr('href', '#comment-'+id);
  $('#comment-reply-info input').attr('value', id);
}

function positionCommentSyntax()
{
  if (!$('#comment-add').length)
    return;
  var oarea = $('#comment-add').find('textarea');
  var osynt = $('#show-comment-syntax');
  var ssynx = oarea.width() - osynt.position().left + oarea.position().left - osynt.width();
  osynt.css('position', 'relative').css('left', ssynx+'px');
  var synw = $('#page').width() - oarea.width() - (oarea.position().left - $('#page').position().left) * 2;
  if (synw < 200) synw = 200;
  if (synw > 300) synw = 300;
  var os = $('#comment-syntax');
  os.css('width', synw + 'px');
  os.css('height', oarea.height()+'px');
  os.css('position', 'absolute');
  os.css('left', 8 + oarea.offset().left + oarea.width() + 'px');
  os.hide();
}

function toggleSyntax()
{
  var oarea = $('#comment-add').find('textarea');
  $('#comment-syntax')
    .css('left', 8 + oarea.offset().left + oarea.width() + 'px')
    .css('top', 1 + oarea.position().top + 'px')
    .toggle();
}
