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(){


  // licitálás
  (function(){
    var biddingsTimer = null;
    var biddingsDisplayTimer = null;
    
    function binndigs_displayTimer(seconds) {
      $('.biddings-data .biddings-timer').find('span').html(seconds);
      $('.biddings-data .biddings-timer:hidden').slideDown('slow');
      return biddingsDisplayTimer = window.setTimeout(function(){binndigs_displayTimer(seconds-1)}, 1000);
    }
    
    function biddings_timer(func, seconds) {
      seconds = parseInt(seconds);
      if (isNaN(seconds))
        seconds = 60;
      seconds = seconds % 60;
      if (seconds < 10)
        seconds += 60;
      if (biddingsTimer != null)
        window.clearTimeout(biddingsDisplayTimer);
      biddingsDisplayTimer = binndigs_displayTimer(seconds);
      if (biddingsTimer != null)
        window.clearTimeout(biddingsTimer);
      /*console.log('timeout: ' + seconds);*/
      return biddingsTimer = window.setTimeout(func, seconds * 1000);
    }
    
    function biddings_refresh(data) {
      if (typeof data.refresh != undefined) {
        biddings_timer(function(){ biddings_ajaxRefresh(); }, data.refresh);
      }
      
      $('.biddings-data:has(.biddings-id)').each(function() {
        var $this = $(this);
        var idx = 'id' + $this.find('.biddings-id').text();
        if (idx in data) {
          $.each(data[idx], function(index, value) {
            $elem = $this.find('.biddings-'+index);
            if ($elem.html() != value)
              $elem.html(value);
          });
        }
      });
    }
    
    function biddings_ajaxRefresh(){
      biddings_timer(function(){ biddings_ajaxRefresh(); }, 60)
      var ids = [];
      $('.biddings-data .biddings-id').each(function(){ ids.push($(this).text()); });
      if (ids.join(';') == '')
        return;
      $.ajax({
        url: '/?ajax=licitalas',
        type: 'GET',
        dataType: 'json',
        data: {
          'ids': ids.join(';')
        },
        timeout: 30*1000,
        cache: false,
        success: function(data, textStatus, jqXHR){
          biddings_refresh(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
        },
        complete: function(jqXHR, textStatus) {
        }
      });
    }
    biddings_timer(function(){ biddings_ajaxRefresh(); }, $('#bidding-refresh').text());

    $('form:has(input[name="biddings_bid_price"])').live('submit', function(){
      $form = $(this);
      var ids = [];
      $('.biddings-data .biddings-id').each(function(){ ids.push($(this).text()); });
      $.ajax({
        url: $form.attr('action') + '?ajax=licitalas' + '&' + 'ids=' + ids.join(';'),
        type: 'POST',
        dataType: 'json',
        data: $form.find('input[name="biddings_bid_price"]').serialize(),
        timeout: 30*1000,
        cache: false,
        success: function (data, textStatus, XMLHttpRequest) {
          biddings_refresh(data);
          if (data.result == 'success')
            alert('A licitálását rögzítettük.');
          else
            alert(data.result);
/*
          $('<div/>').attr('title', '<span class="ui-icon ui-icon-alert"></span> cím').html('Szevasz!').dialog({
            modal: true,
            dialogClass: 'check',
            buttons: {
              'Ok': function() {
                $(this).dialog('close');
              }
            }
          });
  */
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert('Hiba! A mentés nem sikerült!');
        },
        complete: function (jqXHR, textStatus) {
        }
      });
      return false;
    });  
  })();


  // form label
  $('label:has(span)>input').live('focus', function(){
    $(this).parent('label').find('span').hide();
  }).live('blur', function(){
    if ($(this).val() == '')
      $(this).parent('label').find('span').show();
  }).each(function(){
    if ($(this).val() != '')
      $(this).parent('label').find('span').hide();
  });
  
  $("div#sidebar ul.sidemenu>li:has(ul)>a").click(function(){
    var duration = 'slow';
    if ($(this).next("ul").is(":hidden")) {
      $(this).parent().nextAll("li").find("ul").animate({height: 'hide'}, duration, 'linear');
      $(this).parent().prevAll("li").find("ul").animate({height: 'hide'}, duration, 'linear');
      $(this).next("ul").animate({height: 'show'}, duration, 'linear');
    } else {
      $(this).next("ul").animate({height: 'hide'}, duration, 'linear');
    }
    return false;
  }).append(document.createTextNode("..."))/*.next("ul").hide()*/;
  var url = window.location + '';
  url = url.replace(/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/, '$10');
  if (url != '/') {
    url = url.replace(/^\/([^\/]*)(\/.*)?$/g, '$1');
    $('div#sidebar ul.sidemenu li>a[href^="/'+url+'"]:last').addClass('active');
  }
  $("div#sidebar ul.sidemenu>li:has(ul)", this).children("ul").not(":has(.active)").hide();

  $('a[rel="external"], a[href^="http"]').each(function(){
    if ($(this).attr('title') != undefined)
      $(this).attr('title', $(this).attr('href'))
  }).filter(':not(:has(img))').addClass('external');
  
  $('a[rel="external"], a[href^="http"]').live('click', function(){
    $(this).attr('target', '_blank');
    return true;
  });


  $('input.datepicker').datepicker({minDate: 0});
  $('input.time').mask("99:99:99");
  
  $('.flvplayer>span').each(function(){
    //alert($(this).attr('id'));
    $(this).html('<a href="/misc/movies/'+$(this).attr('id')+'.flv"><img src="/misc/movies/'+$(this).attr('id')+'.jpg" alt="'+$(this).attr('id')+'" width="480" /></a>');
    $(this).children('a').click(function(){
      //alert('play');
      swfobject.embedSWF("/images/flvplayer.swf", $(this).parent().attr('id'), "480", "390", "9.0.0", "expressInstall.swf",
        {
          flv: '/misc/movies/'+$(this).parent().attr('id')+'.flv',
          jpg: '/misc/movies/'+$(this).parent().attr('id')+'.jpg'
        }, {
          quality: 'high',
          align: 'middle',
          play: 'true',
          loop: 'true',
          scale: 'showall',
          wmode: 'transparent',
          devicefont: 'false',
          id: 'flvplayer',
          bgcolor: '#fff2cc',
          name: 'flvplayer',
          menu: 'false',
          allowFullScreen: 'true',
          allowScriptAccess: 'sameDomain'
        }
      );
      return false;
    });
/*
    swfobject.embedSWF("/images/flvplayer.swf", $(this).attr('id'), "480", "390", "9.0.0", "expressInstall.swf",
      {
        flv: '/misc/movies/'+$(this).attr('id')+'.flv',
        jpg: '/misc/movies/'+$(this).attr('id')+'.jpg'
      }, {
        quality: 'high',
        align: 'middle',
        play: 'true',
        loop: 'true',
        scale: 'showall',
        wmode: 'transparent',
        devicefont: 'false',
        id: 'flvplayer',
        bgcolor: '#fff2cc',
        name: 'flvplayer',
        menu: 'false',
        allowFullScreen: 'true',
        allowScriptAccess: 'sameDomain'
      }
    );
*/
  });
  
  try {
    $('.uploadify').fileUpload({
      'uploader'   : '/uploadify/uploader.swf',
      'script'     : '/uploadify/upload.php',
      'cancelImg'  : '/uploadify/cancel.png',
      'sizeLimit'  : 64000000,
      'fileExt'    : '*.pdf',
      'fileDesc'   : 'pdf dokumentumok (*.pdf)',
      //'hideButton' : true,
      'buttonImg'  : '/uploadify/browse.png',
      'width'      : 61,
      'height'     : 23,
      'wmode'      : 'transparent',
      'auto'       : true,
      'folder'     : '/temp',
      'scriptAccess' : 'martinus.hu',
      'onSelect'   : function(event, queueID, fileObj) {
        if (fileObj.type != '.pdf') {
          alert('Csak pdf fájl lehet feltölteni!');
          return false;
        } else if (fileObj.size > 64000000) {
          alert('A megadott fájl mérete túl nagy!');
          return false;
        }
      return true;
      },
      'onError'    : function(event, queueID, fileObj, errorObj) {
        //alert('Hiba!\n'+errorObj.status + errorObj.text);
      },
      'onComplete' : function(event, queueID, fileObj, response, data, id) {
        $("#" + id + queueID).after('<input type="hidden" readonly="readonly" class="form_justify" name="' + id + '" id="' + id + '" value="' + fileObj.name + '" />');
        $("#" + id + queueID + " .percentage").text('OK');
        $("#" + id + queueID + " .cancel").animate({'width': '0px'}, 'normal', 'linear', function(){$(this).hide()});
        return false;
      }
    });
    $('.uploadify').before('<small>Csak akkor kattints a mentés gombra, ha már OK van a százalék érték helyett!</small><br />');
  } catch(e) {
  }
  
   try {
    $('.uploadify_flv').fileUpload({
      'uploader'   : '/uploadify/uploader.swf',
      'script'     : '/uploadify/upload.php',
      'cancelImg'  : '/uploadify/cancel.png',
      'sizeLimit'  : 64000000,
      'fileExt'    : '*.flv',
      'fileDesc'   : 'flv videó fájlok (*.flv)',
      //'hideButton' : true,
      'buttonImg'  : '/uploadify/browse.png',
      'width'      : 61,
      'height'     : 23,
      'wmode'      : 'transparent',
      'auto'       : true,
      'folder'     : '/temp',
      'scriptAccess' : 'martinus.hu',
      'onSelect'   : function(event, queueID, fileObj) {
        if (fileObj.type != '.flv') {
          alert('Csak flv fájl lehet feltölteni!');
          return false;
        } else if (fileObj.size > 64000000) {
          alert('A megadott fájl mérete túl nagy!');
          return false;
        }
      return true;
      },
      'onError'    : function(event, queueID, fileObj, errorObj) {
        //alert('Hiba!\n'+errorObj.status + errorObj.text);
      },
      'onComplete' : function(event, queueID, fileObj, response, data, id) {
        $("#" + id + queueID).after('<input type="hidden" readonly="readonly" class="form_justify" name="' + id + '" id="' + id + '" value="' + fileObj.name + '" />');
        $("#" + id + queueID + " .percentage").text('OK');
        $("#" + id + queueID + " .cancel").animate({'width': '0px'}, 'normal', 'linear', function(){$(this).hide()});
        return false;
      }
    });
    $('.uploadify').before('<small>Csak akkor kattints a mentés gombra, ha már OK van a százalék érték helyett!</small><br />');
  } catch(e) {
  }

//  $('#napi_evangelium_rovid, #napi_evangelium, #blog_martinus, #magyarkurir, #katolikus').each(function(){
  $('#napi_evangelium_rovid:has(.ajax), #napi_evangelium:has(.ajax), #blog_martinus, #magyarkurir:has(.ajax), #katolikus:has(.ajax)').each(function(){
    var $$ = $(this);
    $.ajax({
      type: 'GET',
      url: '/ajax/' + $$.attr('id') + '.php',
      dataType: 'html',
      success: function (data, textStatus) {
        $$.slideUp('normal', function(){
          $$.html(data);
          $$.slideDown('normal');
        });
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        if ($('.error', $$).is('.error')) {
          $$.slideUp('normal', function(){
            $.html($('.error', $$).html());
            $$.slideDown('normal');
          });
        }
      }
    });
  });

  $("#main").mousemove(function(e){
    var X = e.pageX;
    var Margin = 20;
    $(this).find('div.pager').each(function(){
      var maxWidth = $(this).attr("scrollWidth") - $(this).width();
      var tX = (X - $(this).offset().left - Margin) / ($(this).width()-2.2*Margin) * maxWidth;
      $(this).scrollLeft(tX);
    });
  });

  $('img[alt^="http://www.youtube.com/"]').each(function(){
    //<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/1kCt5tVTpbs&hl=en_US&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/1kCt5tVTpbs&hl=en_US&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>
    $(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>');
  });
  
  session_keepup();

});

