var popup_shown = null;
var delayed_popup_timer = null;
var bindings_loaded = false;

$(document).ready(function() {

  // hoverable (delete/edit icons)
  $('.hoverable').hover(function(){
    $(this).find('.hover').show();
  }, function(){
    $(this).find('.hover').hide();
  }).find('.hover').hide();
  
  // login trigger (in header)
  $('#login_trigger').click(function(){
    $('#login_menu').hide();
    $('#login_form').show();
    return false;
  });
  
  // profile settings popup-menu
  $('.mp-level2-anchor').hover(
      function(){
        clearTimeout(delayed_popup_timer);
        delayed_popup_timer = null;
        $('.mp-level2-anchor').not(this).children('ul').hide();
        $(this).children('ul').fadeIn('fast'); 
      }, 
      function(){ delayedHide($(this).children('ul'), 1000); } 
  );
    
  // auto-disappearing in forms
  $('.clear-on-focus').attr('xdefval', function(){ 
    return $(this).val(); 
  }).focus(function() {
    if ($(this).val() == $(this).attr('xdefval')) {
      $(this).val('');
    }
  });
  
  // mark all error form fields
  $('ul.errors').prevAll('input[type!=button], select, textarea')
    .addClass('field-error')
    .focus(function(){
      $(this).removeClass('field-error');
  }); 

  // [zavinac] -> @
  $('#poi div.box-record div, #poi-detail div, .mail-safe').each(function(){
    if ($(this).html().match(/ \[zavináč\] /)) {
      $(this).html($(this).html().replace(/ \[zavináč\] /, '@'));
    }
  });
  
  // MsgBoxes for operations
  $('.popup-friendship').click(popup_friendship);
  $('.popup-invite').click(popup_invite);
  $('.popup-newmsg').click(popup_newmsg);
  $('.popup-import-contact').click(popup_import_contact);
  $('#friendship, #invite, #newmsg, #import-contact').children('img').click(function(){
    $(this).parent('div').hide();
    popup_shown = null;
  });
      
  // confirmation links YES/NO
  $('.to-be-confirmed').click(confirm_link);
  
  // "back" link
  $('#top-back').prepend('<div class="back" style="float:right"><a href="javascript:history.back()">zpět</a></div>');
  
  // tree table
  if(typeof $.fn.treeTable != 'undefined') {
    $('#treetable').treeTable({initialState:'expanded'});
  } 
    
  // MsgBox for club-entry
  $('#enter-submit').toggle(function(){
    var xy = $(this).offset();
    $('#club-entry-popup').css('left', xy.left-200).css('top', xy.top+30).show('fast', function(){
      $(this).find('textarea').focus();
      popup_make_visible(this);
    });
    return false;
  }, function(){
    $('#club-entry-popup').hide('fast');
    return false;
  });
  $('#club-entry-popup').children('img').click(function(){
    $(this).parent('div').hide();
  });
  
  // hide popups by pressing ESC
  document.onkeydown = function(e){
    if (!e) {
      e = window.event;
    }
    if (e.keyCode == 27) {
      $('.popup').removeAttr('x-shown').hide();
      return false;    
    }
    return true;
  };
  
  // dashboard news switcher
  $('#newsType').change(function(){
    $(this).closest('form').submit();
  });

  // links for unauthorized users (login / register)
  $('.must-login').click(must_login);
  
  // make all tinyMCE links open to "_blank"
  $('td.notice-text, .tmce, div.action-desc, div.mw, td.post-text, div.survey-desc')
    .find('p:not(.binding) a:not(.to-detail)').attr('target', '_blank');
    
  // footer links to target _top
  $('#ftr a:not([target])').attr('target', '_top');
  
}); // document.ready()

function popup_friendship(){ return popup_msgbox('#friendship', $(this)); }
function popup_invite(){ return popup_msgbox('#invite', $(this)); }
function popup_newmsg(){ return popup_msgbox('#newmsg', $(this)); }
function popup_import_contact(){ return popup_msgbox('#import-contact', $(this)); }
function popup_msgbox(box, src){
  var action = src.attr('href');
  if (popup_shown && popup_shown == action) {
    $(box).hide('fast');
    popup_shown = null;
  }
  else {
    $('#friendship, #invite, #newmsg, #import-contact').hide();
    var xy = src.offset();
    var pageXY = $('#page').offset();
    xy.left = Math.min(xy.left, pageXY.left + (980-480));
    var uid = src.attr('x-uid');
    var fullname = src.attr('x-fullname');
    popup_shown = action;
    var formAction = $(box).find(':header span').text(fullname).end().find('form').attr('action');
    formAction = formAction.replace(/:\d+$/, ':'+uid);
    if (box == '#newmsg') {
      // ajax load all possible bindings
      if (!bindings_loaded) {
        load_bindings();
        bindings_loaded = true;
      } else { // reset all popups
        $('#ajbi select').val(0);
      }
    }
    $(box).find('form').attr('action', formAction).end()
      .css('left', xy.left).css('top', xy.top+15).show('fast', function(){
      if (box == '#newmsg') {
        tinyMCE.execCommand('mceAddControl', false, 'msg_text');
        tinyMCE.execCommand('mceFocus', false, 'msg_text');
      } else {
        $(this).find('textarea').focus();
      }
      popup_make_visible(this);
    });
  }
  return false;  
}

function load_bindings() {
  $('div#newmsg table thead').load('/_messages/ajax-new-msg');
}

function delayedHide(what, when){
  clearTimeout(delayed_popup_timer);
  delayed_popup_timer = setTimeout(function(){ what.hide(); }, when);
}

function escapeHTML(s) {
  return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function getPageScroll() {
  if (self.pageYOffset) {
    return {x:self.pageXOffset, y:self.pageYOffset};
  } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
    return {x:document.documentElement.scrollLeft, y:document.documentElement.scrollTop};
  }
  return {x:document.body.scrollLeft, y:document.body.scrollTop};
}

function getViewportSize() {
  if (self.innerHeight) {
    return {w:self.innerWidth, h:self.innerHeight};
  } else if (document.documentElement && document.documentElement.clientHeight) {
    return {w:document.documentElement.clientWidth, h:document.documentElement.clientHeight};
  }
  return {w:document.body.clientWidth, h:document.body.clientHeight};
}

function getPageSize() {  
  var docSize = {w:$('#page').outerWidth(), h:$('#page').outerHeight()};
  var viewportSize = getViewportSize();
  return {w:((docSize.w < viewportSize.w) ? viewportSize.w : docSize.w), 
          h:((docSize.h < viewportSize.h) ? viewportSize.h : docSize.h)};
}

function setCursor(el,st,end) {
  if(el.setSelectionRange) { // Firefox
    el.focus();
    el.setSelectionRange(st,end);
  }
  else { // MSIE
    if(el.createTextRange) {
      range=el.createTextRange();
      range.collapse(true);
      range.moveEnd('character',end);
      range.moveStart('character',st);
      range.select();
    }
  }
}

var sanitize = new Array();
sanitize['á'] = 'a';
sanitize['č'] = 'c';
sanitize['ď'] = 'd';
sanitize['é'] = 'e';
sanitize['ě'] = 'e';
sanitize['í'] = 'i';
sanitize['ľ'] = 'l';
sanitize['ň'] = 'n';
sanitize['ó'] = 'o';
sanitize['ř'] = 'r';
sanitize['š'] = 's';
sanitize['ť'] = 't';
sanitize['ú'] = 'u';
sanitize['ů'] = 'u';
sanitize['ý'] = 'y';
sanitize['ž'] = 'z';

function text_sanitize(str) {
  var text = str.toLowerCase();
  var out = '';
  var i;
  for (i = 0; i < text.length; i++) {
    var ch = text.charAt(i);
    if (sanitize[ch]) {
      out += sanitize[ch];
    } else if (ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9' || ch == '_' || ch == '-') {
      out += ch;
    } else if (ch == ' ') {
      out += '-';
    }
  }
  return out;
}

function popup_make_visible(div) {
  var jqd = $(div);
  var div_h = jqd.outerHeight();
  var div_ofs = jqd.offset().top;
  var vp_h = getViewportSize().h;
  var vp_ofs = getPageScroll().y;
  var delta = (div_ofs+div_h) - (vp_ofs+vp_h);
  if (delta > 0) {
    window.scrollBy(0, delta);
  }
}

function confirm_link(){
  var msg = 'Opravdu ' + $(this).attr('title') + '?';
  var link = $(this).attr('href');
  $.alerts.okButton = "&nbsp;Ano&nbsp;";
  $.alerts.cancelButton = "&nbsp;Ne&nbsp;";
  jConfirm(msg, 'Prosím potvrďte', function(r){
    if (r) {
      window.location.href = link;
    }
  });
  return false;
}

function must_login(){
  var ref = encodeURIComponent(window.location.href);
  var msg = 'Tato funkce je dostupná pouze registrovaným a přihlášeným sousedům.<br/>'+
            'Jste-li již registrován/a, můžete se <a href="/_auth/login?target_url='+ref+'">přihlásit</a>.';
  $.alerts.okButton = "&nbsp;Registrovat se&nbsp;";
  $.alerts.cancelButton = "&nbsp;Storno&nbsp;";
  jConfirm(msg, 'Pouze pro přihlášené', function(r){
    if (r) {
      window.location.href = '/_registration?goto='+ref;
    }
  });
  return false;
}
