periodicCheckInterval = 30000;

tooltipOff = false;

function tooltip()
{
  var d = document;
  var E = d.documentElement;
  var b = d.body;

  if (!E) return;
  var a = this;
  if (!a.title) return;
  
  if (a.t) delete(a.t);
  
  a.origiTitle = a.title;

  a.t = $("#tooltip");
  if (a.t.length == 0) a.t = $("<div>").get(0);
  else a.t = a.t[0];

  a.t.innerHTML = a.title.replace(/\|/g,"<br />");

  a.t.id = "tooltip";
  a.t.className = "tooltipDiv";
  a.t.style.display = 'block';

  a.onmouseover = function(e)
  {
    this.title = "";
    this.onmousemove(e);
    b.appendChild(this.t);
  };
  a.onmouseout = function(x)
  {
    this.title = this.origiTitle;
    $('#tooltip').remove();
  };
  a.onmousemove=function(e)
  {
    e=e||event;
    with(this.t.style)
    {
      left=e.clientX+(E.scrollLeft||b.scrollLeft)+2 - Math.max(0, 2-((E.clientWidth||b.parentNode.clientWidth)-e.clientX-this.t.offsetWidth)) +"px";
      var dogtt = 20-((E.clientHeight||b.parentNode.clientHeight)-e.clientY-this.t.offsetHeight);
      top=e.clientY+(E.scrollTop||b.scrollTop) - (dogtt<0?0:(30+this.t.offsetHeight)) +"px";
    };
  };
};

function userTooltip()
{
  var d = document;
  var E = d.documentElement;
  var b = d.body;

  if (!E) return;
  var a = this;
  if (!a.title) return;
  a.origiTitle = a.title;

  a.t = $("#userToolTip").clone()[0];

  var datas = a.title.split("|:");

  a.t.innerHTML = a.t.innerHTML.
                  replace(/::name::/g, datas[0]).
                  replace(/(file:\/\/\/)?::src::/g, "/getimg/" + datas[1] + "-0").
                  replace(/::place::/g, datas[2]);

  a.t.id = "userToolTipDiv";
  a.t.style.display = 'block';

  a.onmouseover = function(e)
  {
    this.title = "";
    this.onmousemove(e);
    b.appendChild(this.t);
  };
  a.onmouseout = function(x)
  {
    this.title = this.origiTitle;
    $('#userToolTipDiv').remove();
  };
  a.onmousemove=function(e)
  {
    e=e||event;
    with(this.t.style)
    {
      left=e.clientX+(E.scrollLeft||b.scrollLeft)+2 - Math.max(0, 2-((E.clientWidth||b.parentNode.clientWidth)-e.clientX-this.t.offsetWidth)) +"px";
      var dogtt = 20-((E.clientHeight||b.parentNode.clientHeight)-e.clientY-this.t.offsetHeight);
      top=e.clientY+(E.scrollTop||b.scrollTop) - (dogtt<0?0:(30+this.t.offsetHeight)) +"px";
    };
  };
};

function voteTooltip()
{
  var d = document;
  var E = d.documentElement;
  var b = d.body;

  if (!E) return;
  var a = this;
  if (!a.title) return;
  a.origiTitle = a.title;

  a.t = $("#voteToolTip").clone()[0];

  var datas = a.title.split("|:");

  $(".jBubbleContent", $(a.t)).html(a.title);

  a.t.id = "voteToolTipDiv";
  a.t.style.display = 'block';

  a.onmouseover = function(e)
  {
    this.title = "";
    this.onmousemove(e);
    b.appendChild(this.t);
    this.t.w = $(this.t).width() / 2;
  };
  a.onmouseout = function(x)
  {
    this.title = this.origiTitle;
    $('#voteToolTipDiv').remove();
  };
  a.onmousemove=function(e)
  {
    if (!this.t.w || this.t.w == 0) return;
    e=e||event;
    with(this.t.style)
    {
      left=e.clientX+(E.scrollLeft||b.scrollLeft)+2 - Math.max(0, 2-((E.clientWidth||b.parentNode.clientWidth)-e.clientX-this.t.offsetWidth))- this.t.w +"px";
      var dogtt = 20-((E.clientHeight||b.parentNode.clientHeight)-e.clientY-this.t.offsetHeight);
      top=e.clientY+(E.scrollTop||b.scrollTop) - (dogtt<0?0:(30+this.t.offsetHeight)) - 33 + "px";
    };
  };
};

$(function ()
{
  $('.tooltip').each(tooltip);
  //addEvent(window,'load',userTooltip);

  $('.userToolTip').each(userTooltip);

   /**
    * Js-es hover
    */
  $('.xbgreen').hover(function()
  {
    $(this).removeClass('xbgreen').addClass('xbgreenhover');
  }, function()
  {
    $(this).removeClass('xbgreenhover').addClass('xbgreen');
  });

  $('.xbgreenwhite').hover(function()
  {
    $(this).removeClass('xbgreenwhite').addClass('xbgreenwhitehover');
  }, function()
  {
    $(this).removeClass('xbgreenwhitehover').addClass('xbgreenwhite');
  });

  $('.xbgray').hover(function()
  {
    $(this).removeClass('xbgray').addClass('xbgrayhover');
  }, function()
  {
    $(this).removeClass('xbgrayhover').addClass('xbgray');
  });


  /**
   * For IE
   */
  selectBox('select');

  /**
   * Láthatóság állítgató kis kütymők
   */
  visibilityClick = function(e)
  {
    if (!visibilityContextMenu) return;

    var span = this;
    var $content = $('.content:eq(0)');
    var contentOffset = elementOffsetPosition($content[0]);

    var bounding = {x1: contentOffset.x + 10,
                    y1: contentOffset.y + 10,
                    x2: 0,
                    y2: 0};

    var pos = {x: e.pageX, y: e.pageY+10};

    bounding.x2 = bounding.x1 + $content.width() - 20;
    bounding.y2 = bounding.y1 + $content.height() - 20;

    visibilityContextMenu(pos,
                          bounding,
                          $(this).next('input[type=hidden]')[0],
                          function(selected)
    {
      if (selected == 'notlogged' || selected == 'logged')
        $(span)
          .removeClass('visibleNone')
          .removeClass('visibleHalf')
          .addClass('visibleFull');
      else if (selected == 'relative' || selected == 'custom')
        $(span)
          .removeClass('visibleNone')
          .addClass('visibleHalf')
          .removeClass('visibleFull');
      else
        $(span)
          .addClass('visibleNone')
          .removeClass('visibleHalf')
          .removeClass('visibleFull');
    });
  };
  $('span.visibleNone, span.visibleHalf, span.visibleFull').click(visibilityClick);
  
  /**
   * Periodic Check
   * csak akkor, ha mozog az egér
   */
  $('body').mousemove(function()
  {
    var n = now();
    
    if (typeof lastPeriodicCheckTimestamp == 'undefined')
      lastPeriodicCheckTimestamp = n;

    if (n - lastPeriodicCheckTimestamp > periodicCheckInterval)
    {
      lastPeriodicCheckTimestamp = n;
      periodicCheck();
    };
  });
  

  /*
  $('img[src*=getimg]').parents('a').not('[href*=image]').bind("dblclick", function()
  {
    this.doubleclicked = 1;
    var obj = this;
    
    setTimeout(function()
    {
      delete(obj.doubleclicked)
    }, 600);
    
    if ($(this).metadata().minipicturename && !$('img', this).attr('src').match(/^.*0-[0-4](-\d+)?$/))
    {
      window.location.href = $(this).attr("href");
    };
  });
  
  $('img[src*=getimg]').parents('a').not('[href*=image]').bind("click", function()
  {
    if (window.ctrlKey) return true;
    
    var obj = this;
    
    if (!$(obj).metadata().minipicturename) return true;
    if ($('img', obj).attr('src').match(/\/?getimg\/(.+\D)?0-[0-4](-\d+)?$/)) return true;
    
    setTimeout(function()
    {
      if (obj.doubleclicked)
      {
        window.location.href = obj.href;
        return;
      }
      
      return openMiniPicture($('img', obj).attr('src'), decodeURIComponent($(obj).metadata().minipicturename).replace(/\+/g, '%20'), decodeURIComponent($(obj).metadata().profilepage).replace(/\+/g, '%20'));
    }, 500);

    return false;
  });
  */
});

function selectBox(jqSelector, jqParent)
{
  if ($.browser.msie && $.browser.version > 7) return;
  if ($.browser.msie && $.browser.version == 6)
  {
    selectBoxIE6(jqSelector, jqParent);
    return;
  };
  if (!$.browser.msie && !$.browser.opera) return;

  if (jqParent)
    $elements = $(jqSelector, jqParent);
  else
    $elements = $(jqSelector);
  $elements.each(function()
  {
    if (this.multiple) return;
    var $s = $(this);
    var changeFv = function()
    {
      $('span', $(this).parents('div:eq(0)')).html(this.options[this.selectedIndex].text);
    };

    var checkChange = function()
    {
      if (this.jqLastValue == this.value) return;

      this.jqTitleSpan.html(this.options[this.selectedIndex].text);
      this.jqLastValue = this.value;
    };

    $s
      .before('<div class="selectTextContainer">' + $s[0].options[$s[0].selectedIndex].text + '</div>')
      .bind('change', changeFv)
      .parents('div:eq(0)').css('width', $s.width() + 'px');

    $s[0].jqLastValue = $s.val();
    $s[0].jqTitleSpan = $('div', $s.parents('div:eq(0)'));
    setInterval(function(){checkChange.apply($s[0])}, 200);
  });
};

function selectBoxIE6(jqSelector, jqParent)
{
  if (jqParent)
    $elements = $(jqSelector, jqParent);
  else
    $elements = $(jqSelector);
  $elements.each(function()
  {
    var w = $(this).width() || parseInt($(this).css('width'));
    var h = $(this).height() || parseInt($(this).css('height'));

    $d = $('<div></div>').css(
    {
      'position': 'relative',
      'top':      '4px',
      'overflow': 'hidden',
      'width':    Math.max(0, (w - 5)) + 'px',
      'height':   Math.max(0, (h - (this.multiple ? 5 : 1))) + 'px'
    });

    var css =
      {
        'position': 'absolute',
        'left': this.multiple ? '-3px' : '-2px',
        'top': this.multiple ? '-3px' : '-2px'
      };
    if (this.multiple)
    {
      css.width = w + 'px';
      //css.height = h + 'px';
    };

    $(this)
      .css(css)
      .wrap($d);

    /*
    if (this.multiple)
      $(this).parents('div.textareaContainer:eq(0)').css('height', (h+5) + 'px');
    */
  });
};

function selectBoxUndo(jqSelector, jqParent)
{
  if (jqParent)
    $elements = $(jqSelector, jqParent);
  else
    $elements = $(jqSelector);
  $elements.prev('div').remove();
};


function periodicCheck()
{
  var n = now();
  if (periodicCheck.running &&
      n - periodicCheck.running < 60000)
    return;
    
  periodicCheck.running = n;
  
  $.get("http://" + document.domain + "/ajax.php?act=getPeriodicCheck", function(data)
  {
    if (trim(data) == '') return;
    data = eval("(" + data + ")");

    if (!data.ok)
    {
      delete(data);
      return false;
    };

    if (data.visits > 0 && $('#uj_latogato_nincs').size() > 0)
    {
    	$('#uj_latogato_van span').html(data.visits);
    	$('#uj_latogato_nincs').css('display', 'none');
      $('#uj_latogato_van').css('display', 'inline');
    }
    else
    {
    	$('#uj_latogato_nincs').css('display', 'inline');
      $('#uj_latogato_van').css('display', 'none');
		};

    $(".messageSign").html(data.msg);
    $(".messageSign")[data.msg > 0 ? 'show' : 'hide']();


    titleManager.data.msgCount = data.msg;
    titleManager.data.visitCount = data.visits;
    titleManager.set();

    delete(data);
    
    periodicCheck.running = 0;
  });
};


function autocompleteCreateListUser(values, selected, highlight, limit)
{
  if (!values.length)
    return '<div style="font-style:italic;padding:6px;">Nincs találat</div>';

  var ret = '<ul>';

  var hl = function(txt, highlight)
  {
    highlight = highlight.replace(/^\s*(.*?)\s*$/, '$1');
    var split = highlight.split(/\s+/);
    var replacePattern;
    for (var i in split)
    {
      if (split[i] == "") continue;
      replacePattern = new RegExp('(' + split[i].replace(/\+/g, '\\+') + ')', 'gi');
      txt = txt.replace(replacePattern, '_:=%=:$1:=%=:_');
    };
    replacePattern = new RegExp('_:=%=:', 'gi');
    txt = txt.replace(replacePattern, '<span class="autocompleteHighlight">');
    replacePattern = new RegExp(':=%=:_', 'gi');
    txt = txt.replace(replacePattern, '</span>');
    return txt;
  };

  for (var i = 0;; i++)
  {
    if (!values[i] || i >= limit) break;

    if (i > 0) ret += '<li class="autocompleteSep">&nbsp;</li>';

    ret += '<li' + (i == selected ? ' class="autocompleteSel"' : '') + '>';
    ret += '<img src="getimg/' + values[i].imgId + '-1" alt="" />';
    ret += '<div>' + hl(values[i].name, highlight) + '</div>';
    ret += '<span>' + values[i].city + '</span>';
    ret += '</li>';
  };
  ret += '</ul>';

  return ret;
};

function autocompleteCreateSMSListUser(values, selected, highlight, limit)
{
  if (!values.length)
    return '<div style="font-style:italic;padding:6px;">Nincs találat</div>';

  var ret = '<ul>';

  var hl = function(txt, highlight)
  {
    highlight = highlight.replace(/^\s*(.*?)\s*$/, '$1');
    var split = highlight.split(/\s+/);
    var replacePattern;
    for (var i in split)
    {
      if (split[i] == "") continue;
      replacePattern = new RegExp('(' + split[i].replace(/\+/g, '\\+') + ')', 'gi');
      txt = txt.replace(replacePattern, '_:=%=:$1:=%=:_');
    };
    replacePattern = new RegExp('_:=%=:', 'gi');
    txt = txt.replace(replacePattern, '<span class="autocompleteHighlight">');
    replacePattern = new RegExp(':=%=:_', 'gi');
    txt = txt.replace(replacePattern, '</span>');
    return txt;
  };

  for (var i = 0;; i++)
  {
    if (!values[i] || i >= limit) break;

    if (i > 0) ret += '<li class="autocompleteSep">&nbsp;</li>';

    ret += '<li' + (i == selected ? ' class="autocompleteSel"' : '') + '>';
    ret += '<img src="getimg/' + values[i].imgId + '-1" alt="" />';
    ret += '<div>' + hl(values[i].name, highlight) + '</div>';
    ret += '<span>' + values[i].phonenumber + '</span>';
    ret += '</li>';
  };
  ret += '</ul>';

  return ret;
};


function autocompleteOnSelect(values, selected)
{
  $li = $('.autocompleteList ul li:not(.autocompleteSep)');
  var i = 0;
  $li.each(function()
  {
    $(this)[(i == selected) ? 'addClass' : 'removeClass']('autocompleteSel');
    i++;
  });
};
autocompleteOnSelectUser = autocompleteOnSelect;


function autocompleteCreateList(values, selected, highlight, limit)
{
  if (!values.length)
    return '<div style="font-style:italic;padding:6px;">Nincs találat</div>';

  var ret = '<ul>';

  var hl = function(txt, highlight)
  {
    highlight = highlight.replace(/^\s*(.*?)\s*$/, '$1');
    var split = highlight.split(/[^\w\dáéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/);
    var replacePattern;
    for (var i in split)
    {
      if (split[i] == "") continue;
      replacePattern = new RegExp('(' + split[i] + ')', 'gi');
      txt = txt.replace(replacePattern, '_:=%=:$1:=%=:_');
    };
    replacePattern = new RegExp('_:=%=:', 'gi');
    txt = txt.replace(replacePattern, '<span class="autocompleteHighlight">');
    replacePattern = new RegExp(':=%=:_', 'gi');
    txt = txt.replace(replacePattern, '</span>');
    return txt;
  };

  for (var i = 0;; i++)
  {
    if (!values[i] || i >= limit) break;

    if (i > 0) ret += '<li class="autocompleteSep">&nbsp;</li>';

    ret += '<li' + (i == selected ? ' class="autocompleteSel"' : '') + '>';
    ret += '<div>' + hl(values[i].text, highlight) + '</div>';
    ret += '<span>' + hl(values[i].altText, highlight) + '</span>';
    ret += '</li>';
  };
  ret += '</ul>';

  return ret;
};


$(function()
{
  if (!userLogged) return;

  /**
   * Sorok hoverezése
   */
  if ($.browser.msie)
  {
    $("table.list tr").hover(function()
    {
      if (!$(this).hasClass("nohover"))
        $(this).addClass("hover");
    }, function()
    {
      $(this).removeClass("hover");
    });
  };

  if (!$('input[name=quicksearch]').length) return;

  $('input[name=quicksearch]').autocomplete({
    ajaxFile               : 'ajax.php?act=autocomplete',
    method                 : 'get',
    queryParam             : 'q',
    limitParam             : 'limit',
    //inputNameParam         : 'type',
    extraParams            : {type: 'user'},

    limit                  : 6,
    onSelect               : autocompleteOnSelectUser,
    onType                 : function()
                             {
                               $('input[name=marital_with_id]').val('');
                             },

    onFinishSelect         : function(values, selected)
                             {
                             		location=values[selected].userId;
                             		return false;
                               //$('input[name=marital_with_id]').val(values[selected].userId);
                             },

    listSelector           : '.autocompleteList',
    listContainerSelector  : '.autocompleteContainer',
    listElementsSelector   : '.autocompleteList ul li:not(.autocompleteSep)',
    listOffset             : {x: -30, y: 1},
    listWidthDiff          : 60,
    /*animateIn              : {style: 'fade', duration: 500},
    animateOut             : {style: 'fade', duration: 500},*/
    animateIn              : null,
    animateOut             : null,

    createListFunct        : autocompleteCreateListUser,
    getInputTextFunct      : function(values, selected){return values[selected].name}
  });
});


function displayRelation(dir)
{
  var $showContainer = (!dir ? $(".pendingRelationsSignedMe") : $(".pendingRelationsSignedByMe"));

  if ($showContainer.css("display") == "block") return;

  var $hideContainer = (dir ? $(".pendingRelationsSignedMe") : $(".pendingRelationsSignedByMe"));

  if (dir)
  {
    $(".tabs li:eq(0)").removeClass("first");
    $(".tabs li:eq(1)").addClass("second");
  }
  else
  {
    $(".tabs li:eq(1)").removeClass("second");
    $(".tabs li:eq(0)").addClass("first");
  };

  $hideContainer.fadeOut("normal", function()
  {
    $showContainer.fadeIn();
  });
};

window.showminipicture = false;

function openMiniPicture(src, name, profilepage)
{
  $('.minipicture table .middleMiddle img[src*=getimg], .minipicture table .middleMiddle img[src*=getpostcard]').remove();
  
  $('.minipicture_bg').css(
  {
    display: 'block',
    height: $('body').height() + 'px'
  });
  
  /*
  var obj = $('div[class^=musicName]').show();
  
  $('embed[id^=player]').each(function()
  {
    this.oldHeight = $(this).height()
    $(this).css({
      visibility : 'hidden',
      height: 0
    });
  })
  
  window.showminipicture = true;
  */

  $('.minipicture').css({
    display: 'none',
    top: window.getScrollY() + Math.max(10, ($(window).height() - 549) / 2) + 'px'
  });
  
  $('.minipicture table .middleMiddle div').css({
    width: '200px',
    height: '200px'
  });
  
  
  if (typeof profilepage != 'undefined')
    $('.minipicture table .bottomMiddle .bottomDiv').html('<a href="' + profilepage + '">' + name + '</a>');
  else
    $('.minipicture table .bottomMiddle .bottomDiv').html('<a href="#" onclick="return selectPostcard(' + src.replace(/^.*?(\d+)\-.*$/, "$1") + ')">Kiválaszt!</a>');
  
  $('.minipicture table .middleMiddle div').show();

  $('.minipicture').show();
  var mw = $('.minipicture table .middleMiddle div').width();
  $('.minipicture').hide();

  $('.minipicPreloader').css({
    top: '68px',
    left: mw / 2 - 32 + 'px'
  });

  $('.minipicPreloader').show();

  var newimg = new Image();
  newimg.src = src.replace(/^(.*\d+-)[0-1](-\d+)?$/, "$13$2");
  newimg.onload = function()
  {
    insertPicture(newimg);
  };
  

  $('.minipicture').fadeIn();
  
  $('body').bind('click', closeMiniPicture);
  
  $('body').bind('keydown', function (e)
  {
    if (e.keyCode == 27) closeMiniPicture();
  });

  
  return false;
};

function insertPicture(newimg)
{
  $(".minipicture table .middleMiddle div").append(newimg);
  
  var w = $(newimg).width();
  var h = $(newimg).height();
  
  $(newimg).hide();
  
  w = Math.max(w, 200);
  
  $('.minipicture table .middleMiddle div').animate(
  {
    width: w + 'px',
    height: h + 'px'
  }, 500, function()
  {
    $(newimg).show();
    $('.minipicPreloader').hide();
  });
  
  $('.minipicPreloader').animate(
  {
    top: (h - 64) / 2 + 'px',
    left: (w - 64) / 2 + 'px'
  }, 500);
};

function closeMiniPicture()
{
  $('.minipicture').fadeOut('normal', function()
  {
    $('.minipicture_bg').hide();
    $('body').unbind("click", closeMiniPicture);

    /*
    $('embed[id^=player]').each(function()
    {
      $(this).css(
      {
        visibility: 'visible',
        height: this.oldHeight + 'px'
      });
      $(this).parents('div:eq(0)').siblings('.musicName').hide();
    });
    window.showminipicture = false;
    */
  });
};

