$(function() {
  // Regisztráció típusválasztás
  $('#person-reg').livequery(function(){
    $('#account-attributes').removeClass('company');
    $('#account-attributes').addClass('person');
  });

  $('#person-reg').click(function(e) {
    $('#account-attributes').removeClass('company');
    $('#account-attributes').addClass('person');
  });
  $('#company-reg').click(function(e) {
    $('#account-attributes').removeClass('person');
    $('#account-attributes').addClass('company');
  });
  var chb;
  if ((chb = $('#person-reg').get(0)) && chb.checked) {
    $('#account-attributes').addClass('person');
  } else if ((chb = $('#company-reg').get(0)) && chb.checked) {
    $('#account-attributes').addClass('company');
  }

  // Dolog bezárás rel attribútum alapján
  $('a.close').livequery('click', function(e) {
    e.preventDefault();
    var parent = $(this).attr('rel') + ":eq(0)";
    var removed = $(this).parents(parent).hide("slow");
    removed.remove('slow');
    // Ha utolsó flash volt, akkor containert is eltávolítjuk
    if (removed.parents('#flash')) {
      var flashes = $('#flash > div');
      if (flashes.length == 0) {
        $('#flash').remove();
      }
    }
  });

  // Skin chooser
  $('#skins').hide();
  $('.choose-skin').click(function(e) {
    e.preventDefault();
    $('#skins').slideToggle();
    $('#skins').css({minWidth: '0', position: 'relative', clear: 'both'});
  });
  $('#skins li.skin-option a').click(function(e) {
    e.preventDefault();
    $('#page_skin').val($(this).attr('rel'));
    $('#skins li.skin-option').removeClass('selected');
    $(this).parents('li.skin-option').addClass('selected');
  });

  // Source editing
  $('#source-edit-form').submit(function(e) {
    e.preventDefault();
    var form = $(this);
    var action = form.attr('action');
    var target = form.data('target') || "#preview";
    var statusMessage = form.find('.tools .status');
    var buttons = form.find('.tools').find('button, input[type=submit], input[type=reset]');
    var submitParam = {};
    if ($(this).attr('name') != "") {
      submitParam[$(this).attr('name')] = $(this).val();
    }
    statusMessage.html(t(target == "#preview" ? 'creating_preview' : 'saving_page') + ', ' + t('please_wait'));
    form.find('.ajax-comm').html("");
    buttons.each(function() {$(this).get(0).disabled = true;})
    $.ajax({
      url: action,
      type: form.attr('method') || 'GET',
      data: $.param(form.formToArray())+'&'+$.param(submitParam),
      dataType: 'html',
      success: function(data, status) {
        if (target == "#preview") {
          $('#source-edit, #preview-button, #pipe-button').hide();
          $('#edit-button').show();
          $("#preview").html(data).show();
          var errors = $('#preview .source-errors');
          if (errors.length > 0) {
            form.find('#comm .source-errors').html(errors.remove().html()).show();
          } else {
            form.find('.source-errors').html('').hide();
          }
          // ad preview
          $('#preview').find('textarea.ad-content').hide();
          $('#preview').find('.show-ad').click(function(e) {
            e.preventDefault();
            var adDiv = $(this).parents('div.ad:first');
            var content = $(this).parents('div.content:first').find('textarea.ad-content');
            adDiv.html(content.val());
            content.remove();
          });

          $('#preview').attr('class',$('#page').attr('class'));
        } else {
          $('#'+target).html(data);
          form.find('.source-errors').html('').hide();
        }
        $('#comm .ajax-comm').remove();
        var comm = $('#'+target+' .ajax-comm');
        if (comm.length > 0) {
          $('#comm').append(comm);
        }
      },
      complete: function(request, status) {
        if (request.status == 422) {
          form.find('.source-errors').html(request.responseText).show();
        }
        statusMessage.html('');
        buttons.each(function() {$(this).get(0).disabled = false;})
      }
    });
  });
  // set submit params
  $('#source-edit-form input[type=submit]').livequery('click', function(e) {
    var name = $(this).attr('name');
    var form = $(this).parents('form');
    if (name) {
      var sval_input = form.find('.submit-value');
      if (sval_input.length == 0) {
        sval_input = form.append('<input type="hidden" name="" class="submit-value"/>').find('.submit-value');
      }
      sval_input.attr('name', name);
      sval_input.attr('value', $(this).val());
    }
    form.data('target', '#'+($(this).attr('id') || $(this).attr('class')).split("-button")[0]);
  });
  $('#edit-button').click(function(e) {
    e.preventDefault();
    $('#preview, #edit-button').hide();
    $('#source-edit, #preview-button, #pipe-button').show();
  });
  $('#pipe-button').click(function(e) {
    e.preventDefault();
    var pipe = "|";
    var ctrl = $('#page_source').get(0);
    if (document.selection) {
      ctrl.focus();
      sel = document.selection.createRange();
      sel.text = pipe;
    } else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
      ctrl.focus();
      var startPos = ctrl.selectionStart;
      var endPos = ctrl.selectionEnd;
      ctrl.value = ctrl.value.substring(0, startPos) + pipe + ctrl.value.substring(endPos, ctrl.value.length);
      ctrl.setSelectionRange(startPos+1, startPos+1);
    } else {
      ctrl.value += myValue;
    }
  });
  $('.source-edit-button').livequery('click', function(e) {
    $('#source-edit-form').data('target', 'preview');
  });
  $('.source-edit-button').livequery('click', function(e) {
    if (!confirm(t('save_confirm'))) {
      e.preventDefault();
    } else {
      $('#source-edit-form').data('target', 'source-edit');
    }
  });
  $('#reset-button').click(function(e) {
    if (!confirm(t('reset_confirm'))) {
      e.preventDefault();
    }
  });
  $('#edit-button, #source-edit-form .source-errors').hide();
  // Admin tools toggle
  $('#toggle-admin a').click(function(e) {
    $('.admin-tools > div:eq(1)').toggle();
  });
  $('.admin-tools > div:eq(1)').hide();
  if ($.browser.mozilla) {
    $('#source-edit textarea.source').livequery(function() {
      $(this).lineNumbers().css({
        backgroundColor: '#444',
        color: '#60bff3'
      });
    });
  }

  // Hibához ugrás
  $('a.edit-error').livequery('click', function(e) {
    e.preventDefault();
    var rel;
    if (rel = $(this).attr('rel')) {
      rel = rel.split(",");
      var pos = rel[0]-0, line = rel[1]-0, ctrl = $('#page_source').get(0);
      var source_lines = $('#page_source').val().split("\n");
      for (var i = 0; i < line-1; i++) {
        if (m = source_lines[i].match(/^[ \t]*#.*$/)) {
          pos += m[0].length;
        }
      }
      if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos, pos);
      } else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
      }
    }
  });
  $('a.broken').livequery('click', function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    var pos = $('#page_source').val().indexOf(href);
    if (pos != -1) {
      var ctrl = $('#page_source').get(0);
      if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos, pos+href.length);
      } else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos+href.length);
        range.moveStart('character', pos);
        range.select();
      }
    }
  });

  //Scroll to top
  $('a.top').click(function(){
    scroll(0,0);
  });

  //Variants
  /*$('#variants a, #header h1 a').click(function(e) {
    var href = $(this).attr('href');
    $.cookie('erste_link', href, {path: '/', domain: document.location.hostname});
  });*/
  
  //home
  if ($('body').hasClass('page-home')) {
    $.cookie('erste_link', $('#header h1 a').attr('href') , {path: '/', domain: document.location.hostname});
  }
  
  //manner
  if ($('body').hasClass('page-manner')) {
    $.cookie('erste_link', $('#variants li.manner a').attr('href'), {path: '/', domain: document.location.hostname});
  }

  //frauen
  if ($('body').hasClass('page-frauen')) {
    $.cookie('erste_link', $('#variants li.frauen a').attr('href'), {path: '/', domain: document.location.hostname});
  }

  //kinder
  if ($('body').hasClass('page-kinder')) {
    $.cookie('erste_link', $('#variants li.kinder a').attr('href'), {path: '/', domain: document.location.hostname});
  }

  //senior
  if ($('body').hasClass('page-senior')) {
    $.cookie('erste_link', $('#variants li.senior a').attr('href'), {path: '/', domain: document.location.hostname});
  }

  
  if ($.cookie('erste_link')) {
    $('.ersteseite a').attr('href', $.cookie('erste_link'));
  } else {
    $('.ersteseite a').attr('href', $('#header h1 a').attr('href'));
  }

  //rss box
  $('.feed-box').livequery(function(){
    
    feed_url = escape($(this).find("input[name='feed-url']").val());

    feed_limit = $(this).find("input[name='feed-limit']").val();
    container = $(this).find('.content');
    //feed_title = $(this).find('.title span');
    $.getFeed({
      target: container,
      limit: feed_limit,
      url: '/feed/' + feed_url,
      success: function(feed, target, limit) {
        //console.log(container.get(0));
      
        container = target;
        feed_title = container.prevAll('h2').find('span');
        //console.log(feed_title.html());
        //console.info(container);
        if($.trim(feed_title.html()) == "&nbsp;"){
          container.prevAll('h2').find('span').html(feed.title);
        } 

        /*container.html('<h3>'
        + '<a href="'
        + feed.link
        + '">'
        + feed.title
        + '</a>'
        + '</h3>');*/
        container.html('');
        var html = '';
        html += '<ul>';
        for(var i = 0; i < feed.items.length && i < limit; i++) {
        
            var item = feed.items[i];
            
            html += '<li>'
            + '<a href="'
            + item.link
            + '">'
            + item.title
            + '</a>'
        }
        html += '</ul>';
        container.append(html);
     },
     http_status: function(http_status, target){
        if(http_status.status == '424'){
          target.html('<h2 class="feed-error">' + http_status.responseText + '</h2>');
        }
     }
    });
  });
 

  // select links from toc
  $('.toc-content li a').click(function(e){
    e.preventDefault();
    var href = $(this).attr('href');
    //TODO substring gsub
    var anchor = href.substring(1);
    
    $('#page .selected').removeClass('selected');
    
    $("a[name='"+anchor+"']").next('div').each(function(i){
      if(i == 0){
        $(document).scrollTop($(this).offset().top);
      }
      $(this).addClass('selected');

      $(this).effect("bounce", { times: 1, distance: 3 }, 500);
      //$(this).effect("pulsate", { times: -1, opacity: 0.5 }, 1500)    
      });
  });

  // TOS elfogadasa
  if( $('#page_terms_of_use_accepted').length > 0) {

    $('#page_submit').attr('disabled','disabled'); 
    $('#page_terms_of_use_accepted').change(function(){
      if ($(this).attr('checked')){
        $('#page_submit').removeAttr('disabled');
      } else {
        $('#page_submit').attr('disabled','disabled'); 
      }
    });
  }

  if (document.body.style.MozBorderRadius !== undefined || document.body.style.WebkitBorderRadius !== undefined) {
    var prop = document.body.style.MozBorderRadius !== undefined ? 'MozBorderRadius' : 'WebkitBorderRadius';
    $.fn.extend({
      borderPulsate: function(count, duration, radius, finish) {
        if (count == undefined) count = 3;
        if (!duration) duration = 500;
        if (!radius) radius = 10;
        var elem = $(this);
        var up = {}; up[prop] = radius;
        var down = {}; down[prop] = 0;
        elem.animate(up, duration, function() {
          var callb = count > 0 || count == -1 ? function() {setTimeout(function() {elem.borderPulsate(count > 0 ? count-1 : -1, duration, radius, finish)}, 13);} : finish;
          elem.animate(down, duration, callb);
        });
      }
    });
  }

  /*$('.box h2').livequery('dblclick', function(e) {
    var box = $(this).parent().css({border: '2px solid #60BFF3', backgroundColor: '#B8B8B8', margin: '-2px -2px 17px -2px'});
    box.borderPulsate(3, 300, 22, function() {
      box.css({borderWidth: 0, backgroundColor: 'transparent', margin: '0 0 19px 0'});
    });
  });*/

  //18+ check
  // FIXME hova redirecteljunk ha false
  if($('#page').hasClass('adult')) {
    if ($.cookie('adult') != 'true') {
      var accept_button = "<button id=\'accept\'>"+Localization.accept_button+"</button>";
      var decline_button = "<button id=\'decline\'>"+Localization.decline_button+"</button>";
      var image_adult = "<img src=\'/images/18.png\' class=\'warning_pic\'\/>";
      $.facebox(image_adult+Localization.adult_confirm + accept_button + decline_button);
    } else {
      $('body').removeClass('adult_confirm_require');
    }

    $('#facebox button').livequery('click', function(){
      ans = $(this).attr('id');
      if( ans == 'accept' ){
        $(document).trigger('close.facebox')
        $('body').removeClass('adult_confirm_require');
        $().stickFooter();
        $.cookie('adult', true);
        return true;
      }
      if( ans == 'decline' ) {
        $(document).trigger('close.facebox')
        document.location = 'http://zanzaa.at';
        return false;
      }
    });
  }
  
  // set adult checkbox if 18+ category is selected
  $('#page-category-18').change(function(e) {
    var adult = $('#page_adult');
    if (adult.length > 0 && $(this).get(0).checked) {
      adult.get(0).checked = true;
    }
  });

  if($('#new_account_session').length > 0) {
    $('#account_session_email').focus();
  }

  function sortNumber(a,b)
  {
    return a - b;
  }

  // Set the highest column to defaul at TOC
  if($('#toc').length > 0){
    var cols = [];
    $('#toc .content ul').each(function(){
      if($(this).height() != 0){
        cols.push($(this).height());
      }
    });
    $('#toc .content ul').css({height: cols.sort(sortNumber).pop() +'px'});
  }


  if($('#admin').length > 0) {
    $("#main form input[type='text']:first").focus();
    $("#main form input[type='password']:first").focus();
    $("#main form textarea:first").focus();

    $("#syntax_help_link").livequery('click', function(e){
      e.preventDefault();
      txa = $('#page_source')
      pos = [txa.offset().left + txa.width() - 400 , txa.offset().top - 300]
      console.log(pos);
      $("#syntax_help_content").dialog({ closeOnEscape: true, position: pos, height: 450, width: 400, maxWidth: 400, title: 'syntax help '});
      $("#syntax_help_content").show();
    });
  }

  // open links in new tab
  $("a[rel*='external']").livequery(function(){
    $(this).attr('target','_blank');
  });

  // editor links
  $("#more-editor-link").livequery('click', function(){
      $(this).parent().remove();
      $('ul.editor_links li').removeClass('hidden');
  });
  
  $(".box .content .link-cat a").livequery(function(){
    $(this).append(" <img src='/images/more_link.png'/>"); 
  });
   
//  var kinderBoxes = ['spiele', 'lernen','lieder', 'fernseehen', 'kocken', 'basteln', 'marchen', 'ausmalbilder', 'tiere', 'eltern', 'suchmaschinen', 'indoor']
//  $('.column .box').each(function(index){
//    $(this).addClass(kinderBoxes[index]);
//  });
  
  if($('.page-kinder').length > 0) {
    $('.column .box li.link').livequery('click', function(e){
      e.preventDefault();
      window.open($(this).find('a').attr('href'));
    });
  }

  $('#nav li a').livequery('click', function(){
    $(this).blur();
  });

  // ie7 fix li
  $('.category .first li:empty').livequery(function(){
     $(this).addClass('empty');
  });

  $().stickFooter();

  $('.info-box a.popup').livequery('click',function(e){
    e.preventDefault();
    var url =$(this).attr('href');
    $.facebox('<iframe width=500px height=350px src='+url+'/>');
  });

  
  $(document).bind('beforeReveal.facebox', function(){
    $('object').css('visibility','hidden');
  });
 
  $(document).bind('close.facebox', function(){
    $('object').css('visibility','visible');
  });

  //$('.tooltip').livequery(function(){
    //$('.tooltip .ttip_header').corner('top');
    //$('.tooltip .ttip_body').corner('bottom');
  //});

  //objects = document.getElementsByTagName("object");
  //for (var i = 0; i < objects.length; i++)
  // {
  //  objects[i].outerHTML = objects[i].outerHTML;
  //}
  //alert('a'); 
  

  // Set the wmode attribute on flash elements, and recreate them 
  $('embed').attr('wmode','transparent');$('object').each(function(){$(this).after($(this).clone()); $(this).remove();});

});

try { console.log(''); } catch(e) { console = { log: function() {} } }

jQuery.fn.extend({
  lineNumbers: function(options) {
    var editor = jQuery(this);
    var container = editor.wrap('<div></div>')
                      .parent().css('position', 'relative');
    var fontSize = Number(editor.css('font-size').replace('px', ''));

    if (options === undefined) options = {};
    options = $.extend({
      limit: 1000
    }, options || {});
    var digits = Math.round(Math.log(options.limit-1) / Math.log(10));
    if (options.width === undefined) {
      options.width = fontSize*(10/13) * digits;
    }

    editor.attr('wrap', 'off').css({
      whiteSpace: "nowrap", overflow: "auto",
      width: (editor.width() - options.width - fontSize/3) + 'px', padding: '0 0 0 ' + (options.width + fontSize/3) + 'px'
    });
    var numbers = editor.parent().append('<textarea class="numbers" disabled="disabled"></textarea>').find('textarea.numbers');
    numbers.css({
      position: 'absolute',
      top: (fontSize/2) + 'px',
      left: '0px',
      margin: '0',
      padding: '0 0 0 ' + (fontSize/6) + 'px',
      width: options.width + 'px',
      height: editor.height() + 'px'
    });
    var s = "";
    for (var i = 1; i < options.limit; i++) {
      s += "        ".slice(0, digits - String(i).length) + i + "\n";
    }
    numbers.val(s).attr('wrap', 'off').css({whiteSpace: "nowrap", overflow: "hidden"});
    editor.scroll(function(e) {
      numbers.scrollTop($(this).scrollTop());
    });
    return numbers;
  }
});

jQuery.fn.stickFooter = function(){
  // stick footer if container height is smaller than page
  if(document.documentElement.clientHeight > ($('.container').height() + $('.top_line').height() + $('#footer').height() + $('.bottom_line').height() )){
    $('#footer').addClass('stick-footer');
    $('.bottom_line').addClass('stick-bottomline');
  } else {
    if ($('#footer').hasClass('stick-footer')){
      $('#footer').removeClass('stick-footer');
      $('.bottom_line').removeClass('stick-bottomline');
    }
  }
}
