function session_keepup() {
  window.setTimeout(function(){
    if (document.cookie.indexOf('ISENTER=true') >= 0) {
      $.get('/?session_keepup', function(data) {
        session_keepup()
      });
    }
  }, 5*60*1000);
}

$(document).ready(function(){

  $('form[action="/null"]').attr('action', '');

  $('#login, #volunteers_login').find('label>input').focus(function(){
    $(this).parent('label').find('span').hide();
  }).blur(function(){
    if ($(this).val() == '')
      $(this).parent('label').find('span').show();
  }).each(function(){
    if ($(this).val() != '')
      $(this).parent('label').find('span').hide();
  });

  //$('#random-image').css('backgroundImage', "url('/images/random-image/" + Math.floor(Math.random()*12+1) + ".jpg')");

  $('#menu>ul').menu_horizontal({
    click         : true,
    hideDelay     : 500,
    showDelay     : 200,
    appendText    : ''
  });

  //$("div#leftbar ul:first>li:has(ul)>a").after('<img src="/images/arrow.gif" class="arrow" />');
  var url = window.location + '';
  url = url.replace(/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/, '$9');
  if (url != '/') {
    var cnt = 0;
    $('#menu ul li>a[href="'+url+'"], a#contact[href="'+url+'"]').first().each(function(){
      $(this).addClass('active');
      cnt++;
    });
    if (cnt == 0) {
      url = url.replace(/^\/([^\/]*)(\/.*)?$/g, '$1');
      $('#menu ul li>a[href^="/'+url+'"], a#contact[href^="/'+url+'"]').last().addClass('active');
    }
  } else
    $('#menu ul:first li>a[href="/"], a#contact[href="/"]').first().addClass('active');
  //$("#menu ul:first li:has(ul)").not(':has(.active)').children("ul").not(":has(.active)").hide();
  //$("#menu ul:has(.active)").show(); //:has(.active)
  $('#menu ul li:has(.active)>a').addClass('active');
  //$('#menu ul ul:last').css({right: 0}); // az utolsó menüpontot jobbra zárjuk
  
/*
  // kattintás letiltása
  $('#menu ul li:has(ul)>a').bind('click', function(){
    return false;
  });
*/

  $('#menu ul ul').each(function(){
    var $this = $(this);
    $this.css({marginLeft: '-1000px'})
    var mLeft = ($this.width() - $this.parent('li').width()) / 2;
    mLeft = Math.min(mLeft, $this.parent('li').position().left);
    mLeft = Math.max(mLeft, $this.parent('li').position().left + $this.width() - $this.parents('ul').width());
    $this.css({
      marginLeft: Math.floor(-mLeft) + 'px'
    })
  });

  //title
  $('#menu ul>li>a.active, a#contact.active').first().each(function(){
    $('#title').css('background-image', "url('/images/header" + $(this).attr('href') + ".png')");
    $('#title2').css('background-image', "url('/images/footer" + $(this).attr('href') + ".png')");
  });
  
  //$('div').find('p:first').addClass('first');
  $('#main').each(function(){
    var $$ = $('#main').find('div.content');
    if ($$.length == 1)
      $$.children('p:first').addClass('first');
  });
  //$('#main div').find('p:first').addClass('first');

  $('img[alt^="http://www.youtube.com/"]').each(function(){
    //$(this).replaceWith('<object width="' + $(this).attr('width') + '" height="'+$(this).attr('height')+'"><param name="movie" value="' + $(this).attr('alt') + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="' + $(this).attr('alt') + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + $(this).attr('width') + '" height="' + $(this).attr('height') + '"></embed></object>');
    $(this).replaceWith('<iframe width="' + $(this).attr('width') + '" height="'+$(this).attr('height')+'" src="'+$(this).attr('alt')+'" frameborder="0" allowfullscreen></iframe>');
  }); 

  /*$('a[href^="http"]:not([href^="http://www.hevesisandorszinhaz.hu"])').attr('target', '_blank').each(function(){
    if ($(this).attr('title') != undefined)
      $(this).attr('title', $(this).attr('href'));
  });*/
  $('a[href^="http"]:not([href^="http://www.hevesisandorszinhaz.hu"])').each(function(){
    if ($(this).attr('title') != undefined)
      $(this).attr('title', $(this).attr('href'));
  }).live('click', function (e){
    $(this).attr('target', '_blank');
    return true;
  });

  /* dialog */
  if ($('#dialog').length == 0) {
    $('<div id="dialog"></div>').appendTo('body').dialog({
      autoOpen: false,
      modal: true,
      buttons: { 
        'Ok': function() { $(this).dialog('close'); } 
      }               
    });
  }

  if ($('#dialog-volunteer').length == 0) {
    $('<div id="dialog-volunteer"></div>').appendTo('body').dialog({
      autoOpen: false,
      modal: true,
      'title': 'Kérdés',
      open: function(event, ui) { $(this).removeData('result'); }
    });
  }

  /*ajax volunteer */
  $('a.volunteer').live('click', function(){
    var $$ = $(this);
    var subscribe = $$.attr('href').indexOf('?subscribe=') >= 0;
    function ajaxVolunter(post) {
      $('#loader').css('top', $('html').attr('scrollTop')).show();
      $.ajax({
        url: $$.attr('href').replace('#', ''),
        type: 'get',
        dataType: 'json',
        data: {
          ajaxaction: '',
          post: post
        },
        timeout: 20000,
        cache: false, // don't cache the result
        contentType: "application/json", //tell the server we're looking for json
        success: function(json) {
          try {
          } catch(e) {}
          $('#loader').hide();
          if (json.status == 'success') {
            $('#dialog').dialog( "option", "title", 'Információ' ).html(subscribe ? '<p>A jelentkezésedet sikeresen rögzítettük.</p>' : '<p>A sikeresen leiratkoztál az előadásról.</p>');
            if (typeof json.row != 'undefined') {
              var searchClass = $(json.row).filter('tr:first').attr('class');
              var $tr = $$.parents('table').find('tr.' + searchClass);
              $tr.filter(':first').before(json.row);
              $tr.remove();
            }
          } else if (typeof json.status != undefined && json.status != '')
            $('#dialog').dialog( "option", "title", 'Hiba' ).html(json.status);
          else
            $('#dialog').dialog( "option", "title", 'Hiba' ).html('<p>Hiba történt a mentés során!</p>');
          $('#dialog').dialog('open');
        },
        error: function(json) {
          $('#loader').hide();
          $('#dialog').dialog( "option", "title", 'Hiba' ).html('<p>Hiba történt a mentés során!</p>');
          $('#dialog').dialog('open');
        }
      });
    }
    if (subscribe) {
      $('#dialog-volunteer').unbind('dialogclose').bind('dialogclose', function() {
        if (typeof $(this).data('result') != 'undefined')
          ajaxVolunter($(this).data('result'));
      }).html('<p>Milyen pozícióba jelentkezel?</p>'
      ).dialog( 'option', 'buttons', { 
        'Ruhatárba': function() { $(this).data('result', 'checkroom'); $(this).dialog('close'); },
        'Ültetőnek': function() { $(this).data('result', 'seating'); $(this).dialog('close'); },
        'Mégse': function() { $(this).removeData('result'); $(this).dialog('close'); }
      }).dialog('open');
    } else {
      $('#dialog-volunteer').unbind('dialogclose').bind('dialogclose', function() {
        if (typeof $(this).data('result') != 'undefined')
          ajaxVolunter($(this).data('result'));
      }).html('<p>Biztos, hogy szeretnél leiratkozni erről az előadásról?</p>'
      ).dialog( 'option', 'buttons', { 
        'Igen': function() { $(this).data('result', 'yes'); $(this).dialog('close'); },
        'Nem': function() { $(this).removeData('result'); $(this).dialog('close'); }
      }).dialog('open');
    }
    
    return false;
  });

  /*ajax lock, unlock*/
  $('a[href*="?lock"], a[href*="?unlock"]').click(function(){
    $('#loader').css('top', $('html').attr('scrollTop')).show();
    var $$ = $(this);
    $.ajax({
      url: $$.attr('href'),
      type: 'get',
      dataType: 'json',
      data: {
        ajaxaction: ''
      },
      timeout: 20000,
      cache: false, // don't cache the result
      contentType: "application/json", //tell the server we're looking for json
      success: function(json) {
        try {
          $$.attr('href', json.a.href);
          $$.find('img').attr('src', json.a.image)
          $$.find('img').attr('alt', json.a.title);
          $$.find('img').attr('title', json.a.title);
        } catch(e) {}
        $('#loader').hide();
        if (json.status == 'success') {
          $('#dialog').dialog( "option", "title", 'Információ' ).html('<p>A beállítás mentése sikeresen megtörtént.</p>');
        } else
          $('#dialog').dialog( "option", "title", 'Hiba' ).html('<p>Hiba történt a mentés során!</p>');
        $('#dialog').dialog('open');
      },
      error: function(json) {
        $('#loader').hide();
        $('#dialog').dialog( "option", "title", 'Hiba' ).html('<p>Hiba történt a mentés során!</p>');
        $('#dialog').dialog('open');
      }
    });
    return false;
  });

  $('a[href^="http"]:not([href^="http://www.hevesisandorszinhaz.hu"])').attr('target', '_blank').each(function(){
    if ($(this).attr('title') != undefined)
      $(this).attr('title', $(this).attr('href'));
  });
  
  /* datepicker */
  $('.datepicker:not(#month)').datepicker();
  var calendarCache = false;
  $('#month.datepicker').datepicker({
    onSelect: function(dateText, inst) {
      $(this).next('div:first').slideUp('normal', function(){
        var $$ = $(this);
        $$.empty();
        if (calendarCache === false || typeof calendarCache.content[dateText] == 'undefined') {
          $.ajax({
            url: '/?ajax=calendar&date=' + dateText,
            type: 'get',
            dataType: 'json',
            success: function(data) {
              calendarCache = data;
              try {
                $$.append(calendarCache.content[dateText]);
                $$.slideDown('normal');
              } catch(e) {}
            }
          });
        } else {
          try {
            $$.append(calendarCache.content[dateText]);
            $$.slideDown('normal');
          } catch(e) {}
        }
      });
    }
  });
  
  /* autocomplete */
  $('input.autocomplete').each(function(){
    var $$ = $(this);
    $$.autocomplete({
      delay: 300, 
      source: '?autocomplete&field='+$$.attr('name')
    });
  });
  
  if ($.browser.webkit) {
    $('#menu ul:first>li>a').css({padding:  '0 5px 0 6px'});
  }

  session_keepup();
  
  if ($.browser.msie && parseFloat($.browser.version) < 7) {
    $('<div/>', {
      css: {
        display: 'none',
        margin: 0,
        textAlign: 'center'
      }
    }).addClass('error'
    ).html('A Ön által használt böngésző elavult, verziója nem támogatott! (Microsoft Internet Explorer '+$.browser.version+') Kérjük frissítse: <a href="http://www.browserchoice.eu/BrowserChoice/browserchoice_hu.htm" target="_blank">támogatott böngészők</a>'
    ).prependTo($('body')).slideDown();
  } 
});
