if(!/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
  HTMLElement.prototype.click = function() {
    var evt = this.ownerDocument.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
    this.dispatchEvent(evt);
  }
}
/******************************************************************************
* Detailseite des Ausstellers aus Flash-Geländeplan aufrufen
* 
* @param aID - Id des Ausstellers
* @param veid - VerzeichnisEintragID  
*****************************************************************************/
function openFromHallenplan(aID, veid)
{
  //console.log(aID + ' ' + veid);
  ajaxGetExhibDetails({
    id: aID,
    veid: veid
  });
}

function getFlashMovieObject(movieName)
{
  if (window.document[movieName]) {
    return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1) {
    if (document.embeds && document.embeds[movieName]) {
      return document.embeds[movieName]; 
    } else {
      return document.getElementById(movieName);
    }
  }
}

function zeigeStand(firmaId, anzeigeArt, sprechblaseGross, standId, veid, standId2)
{
  // anzeigeArt: 0 enfernen
  //1 zeigen mit Verschwinden
  //2 stehenlassen
  //3 entfernen, falls mit 1 hinzugefügt.
  
  // sprechblaseGross - 1 (liste)
  //   0 (top)
  //console.log(firmaId + ' ' + anzeigeArt + ' ' + sprechblaseGross + ' ' + standId + ' ' + veid);
  veid = typeof veid == 'undefined' ? '' : veid;
  standId2 = typeof standId2 == 'undefined' ? '' : standId2;

  var textRaus;
  var textRein;
  var textGanz;
  if(firmaId && firmaId.match(/-/)) {
    arrParam = firmaId.split("-");
    firmaId = arrParam[0];
  }
  var flashMovie = getFlashMovieObject("trans");
  if(flashMovie) {
    if(firmaId == 0) {
      flashMovie.SetVariable("/:alleLoeschen", 1);
    } else {
      //alert(firmaId);
      //alert(sprechblaseGross);
      
      textRaus = firmaId + "#" + anzeigeArt + "#" + sprechblaseGross + "#" + standId + "#" + veid + "#" + standId2 + '#';
    
      //console.log(textRaus);
     
      textRein = flashMovie.GetVariable("/:eventStackString");
      //alert(textRein + textRaus);
      textGanz = textRein + textRaus
      //textGanz = "47519#1#1#";
      flashMovie.SetVariable("/:eventStackString", textGanz);
    /*
     flashMovie.SetVariable("/:extFirmenInfo", firmaId);
      //flashMovie.SetVariable("/:dummyZeilenInhalt", firmaId);
      flashMovie.SetVariable("/:anzeigeArt", anzeigeArt);
      
      flashMovie.SetVariable("/:neueEingabe", 1);
      //MouseOver
      if(anzeigeArt==1) {
      flashMovie.SetVariable("/:extZuAktivierenderStand", firmaId);
      flashMovie.SetVariable("/:extZuSprechblaseStand", firmaId);
      }
      
      //Click
      if(anzeigeArt==2){
      flashMovie.SetVariable("/:extZuClickedStand", firmaId);
      }
      
      //MouseOut
      if(anzeigeArt==3) {
        flashMovie.SetVariable("/:extZuAktivierenderStand", -1);
        flashMovie.SetVariable("/:extZuSprechblaseStand", -1);
      }
      
     // alert(flashMovie.GetVariable("aktuelleHalle"));
     
      //flashMovie.SetVariable("/:sprechblaseGross", sprechblaseGross);
      */
    }
  } else {
    alert("flash -object not found.");
  }
  return false;
}

function zeigeZeile(firmaId, doHighlight) 
{
  // Mit der
  // firmaID     : Id des Austellers
  // doHighlight   : 1 bei spezieller Hervorhbeung
  // 0 um Hervorhebung rückgängig zu machen
  if(doHighlight) {
    $('#tab-plan tr[id='+firmaId+']').addClass('highlighted-strong');
  } else {
    $('#tab-plan tr[id='+firmaId+']').removeClass('highlighted-strong');
  }
}

function neueHalle(hallenId, exhib, sort)
{
  if(!sort) {
    sort = 'a#asc'
  }
  var textMarkierteStaende = "";
  
  $.ajax({
    type: "POST",
    async: false,
    url: "includes/ajaxRequest.php",
    data: {
      getSelectedExhibitors: hallenId
    },
    success: function(data) {
      textMarkierteStaende =  data.replace(/\-\d/g, ""); // AuftragPositionsStatus weg
      textMarkierteStaende =  textMarkierteStaende.replace(/\§/g, "#"); // Trennzeichen zwischen AusstellerID und Stand
      textMarkierteStaende =  textMarkierteStaende.replace(/\++/g, "#"); // Trennzeichen zwischen Einträgen
    //console.log('markierte: ' + textMarkierteStaende);
    }
  });
  
  this.timeout = setTimeout(function(){
    var flashMovie = getFlashMovieObject("trans");
    if(flashMovie) {
      flashMovie.SetVariable("/:markierteStaende", textMarkierteStaende);
    //console.log('markierteStaende setup');
    }
  },500);

  return ajaxGetExhibList('exhib_hall=' + hallenId +
    '&exhib=' + exhib + '&sort=' + sort , '#exhib-liste-plan');
}

function schliesseHallenPopup()
{
  $('#planDetails').hide('fast');
}

function resetVideos(param)
{
  if(typeof(param) != 'object') {
    param = eval(param);
  }
  $('#videos').empty().flash(
  {
    src: 'player/player.swf',
    width: 494,
    height: 500,
    wmode: 'opaque',
    flashvars: param
  },
  {
    version: 8
  }
  );
}



function passwordRemind()
{
  var header = t('txt_passForgot');
  var message = t('txt_mail_enter') + ":";
  message += "<input type=\"text\" name=\"remindPassword\"><br />";
  message += "<input type=\"button\" class=\"button\" value='" + t('txt_request_password') + "' name=\"remindSend\"" +
  "onClick=\"passwordRemindSend($('input[name=remindPassword]').val())\"><br />";
  alertBox(header, message);
}

function registrationMore(email)
{
  $.ajax({
    type: "POST",
    dataType: 'json',
    url: "includes/ajaxRequest.php",
    data: 'registrationMore=' + email,
    success: function(data) {
      var title = "Hinweis";
      var content = data.message;
      alertBox(title, content);
      setTimeout(function(){
        closeAlert();
      }, 2000);
      return false;
    }
  });
}

function passwordRemindSend(email)
{
  if(email == '') {
    return false;
  }
  var param = "remind=" + email;
  $.ajax({
    type: "POST",
    dataType: 'json',
    url: "includes/ajaxRequest.php",
    data: param,
    success: function(response) {
      alertBox(t('txt_hinweis'), response.message);
      return false;
    }
  });
  return true;
}

function hideShowExhib(id)
{
  if(id.match(/\:/)) {
    paramId = /([0-9]+)\:([0-9]+)/.exec(id);
    exhibitorId = paramId[1];
    directoryEntryId = paramId[2];
  }
  $detailedDiv = $('#divMyPlanner' + exhibitorId + directoryEntryId + '_2');
  $hideShowImage = $('#imgmesse' + exhibitorId + directoryEntryId);
  $textArea = $('textarea', $detailedDiv);

  if($detailedDiv.is(':visible')) {
    $detailedDiv.slideUp('slow');
    $hideShowImage.attr('src', 'images/green-plus.gif');
    if($textArea.data('changed')) {
      saveNote(id, $textArea.val());
    }
  } else {
    $detailedDiv.slideDown('slow');
    $hideShowImage.attr('src', 'images/red-minus.gif');
  }
  return false;
}

function saveNote(id, noteText) {
  $.ajax({
    type: "POST",
    url: "index.php",
    data: {
      controller: 'favorite',
      action: 'saveNote',
      ajax: 'true',
      id : id,
      note: noteText
    },
    success: function(data){
      $('body').append(data);
    }
  });
}

function updateNote(id, action) {
  if(id.match(/\:/)) {
    paramId = /([0-9]+)\:([0-9]+)/.exec(id);
    exhibitorId = paramId[1];
    directoryEntryId = paramId[2];
  }

  $mainDiv = $('#divMyPlanner' + exhibitorId + directoryEntryId + '_1');
  $imageNote = $('.imgnote', $mainDiv);
  $textArea = $('textarea', $mainDiv);

  $textArea.data('changed', false);

  if (action == 'save') {
    $imageNote.attr('src', 'images/paper-a.gif');
  } else if (action == 'delete') {
    $imageNote.attr('src', 'images/paper-p.gif');
    $textArea.attr('value', '');
  }
}

function showPrintOptions(param)
{
  $('#prnPlan').hide(); // mit Geländeplan Option
  $('#prnHallplan').hide();
  $('#prnDetails').hide();
  $('#print-options').center().fadeIn('slow');
  $('#printList, #section, #type, div#printOption').remove();
  var dataPrintList  = "";
  var $printList;

  var printOptionAll = t('txt_druck_all');
  var printOptionSelected = t('txt_druck_selected');

  var $divPrintOption = $('<div>');
  switch(param.section) {
    case 'plan':
      $.ajax({
        type: "POST",
        async: false,
        url: "includes/ajaxRequest.php",
        data: {
          getSelectedExhibitors: param.id
        },
        success: function(data) {
          dataPrintList = data;
          printOptionSelected = t('txt_druck_selected_hall') + " " + param.id;
        }
      });
      printOptionAll = t('txt_druck_all_hall') + " " + param.id;
      break; // plan
    case 'profile':
      $('#prnPlan').hide();
      dataPrintList = param.veid;
      printOptionSelected = t('txt_druck_aktuell');
      break; // profile
    case 'exhibitor':
      $('#prnPlan').show();
      $('#prnHallplan').show();
      $('#prnDetails').show();
      dataPrintList =  param.id + '§' + 'stand' + '§' + param.veid;
      break; // exhibitor

    case 'appointment':
      dataPrintList =  param.id;
      break; // appointment
    case 'jobMarket':
      dataPrintList =  param.id;
      break; //jobMarket

    default:
      $('#prnPlan').show();
      $('#prnHallplan').show();
      $('#prnDetails').show();
      dataPrintList =  param.id;
      break; // default
    
  } // switch

  if(param.section == 'plan') {
    $divPrintOption
    .attr({
      'id': 'printOption',
      'class' : 'bb pb5 pt5'
    })
    .append('<input id="printOptionAll" type="radio" name="printOption" value="all">')
    .append('<label for="printOptionAll" class="pl5">' + printOptionAll + '</label><br />');
    if(dataPrintList) {
      $divPrintOption
      .append('<input id="printOptionSelected" type="radio" name="printOption" value="selected" checked="checked">')
      .append('<label for="printOptionSelected" class="pl5">' + printOptionSelected + '</label><br />');
    }
    $('form[name=formDruckOptionen]').prepend($divPrintOption);
    if(!dataPrintList) {
      $('input[name=printOption]:first').attr('checked', true);
    }
  }

  $printList = $('<input type="hidden">').
  attr({
    'value' : dataPrintList,
    'id' : 'printList',
    'name' : 'printList'
  });
  
  var $section = $('<input type="hidden">').
  attr({
    'value' : param.section,
    'id' : 'section',
    'name': 'section'
  });
  var $type = $('<input type="hidden">').
  attr({
    'value' : param.type,
    'id' : 'type',
    'name': 'type'
  });
  $('form[name=formDruckOptionen]').
  append($section).
  append($type).
  append($printList);
  return false;
}

function checkPrintOptions()
{
  // Window Setup
  var winWidth  = 800;
  var winHeight = 600;
  var scrollbars = 'yes';
  if (screen.width < winWidth + 50)
  {
    winWidth = screen.width - 50;
  }
  if (screen.height < winHeight + 100)
  {
    winHeight = screen.height - 100;
  }
  var posX = Math.round((screen.width - winWidth) / 2);
  var posY = Math.round((screen.height - winHeight) / 2);
  
  var winSize = "width="+winWidth+",height="+winHeight+", ";
  var winPos = "left="+posX+",top="+posY+", ";
  var winChar = "menubar=no,resizable=yes,status=no,toolbar=no,\
    dependent=yes,titlebar=no,scrollbars="+scrollbars;
  
  $param = $('#formDruckOptionen').serialize();
  var newWin = window.open("print.php?" + $param, "", winSize + winPos + winChar);
  
  $('#print-options').fadeOut('slow');
  if(newWin) {
    newWin.focus();
  }
  return false;
}

function animateNav(param, callbackFunc)//(expand, nav, searchString, callbackFunc)
{
  var expand = param.expand;
  var nav = param.nav;
  var searchString = param.searchString;
  var navGlobal = param.nav;
  var isExact = param.isExact;
  
  if(nav && nav.match(/#/)) {
    arrNav = nav.split("#");
    nav = arrNav[0];
  }
  // Aktiven Reiter speichern für .ajaxStart()
  $('body').data('activeNav', param.nav);
  $('.wait').hide();
  $('#wait'+param.nav).show();
  $('#alert, #print-options, #outer, #details, #shadeBackground').hide();
  if(expand) {
    //Zu Anfangszustand
    $('#inside').slideUp('slow', function(){
      if($('#searchTab, #messeTab').hasClass('swapped')) {
        inhaltSuche = $('#messeTab').html();
        inhaltMesse = $('#searchTab').html();
        $('#messeTab').html(inhaltMesse);
        $('#searchTab').html(inhaltSuche);
      }
      if($('#planTab, #nomenklTab').hasClass('swapped')) {
        inhaltNomenkl = $('#planTab').html();
        inhaltPlan = $('#nomenklTab').html();
        $('#planTab').html(inhaltPlan);
        $('#nomenklTab').html(inhaltNomenkl);
      }
      $('#searchTab, #messeTab, #planTab, #nomenklTab').removeClass("swapped nav-p nav-a-selected").addClass("nav-a");
      $('#searchTab, #messeTab, #planTab, #nomenklTab').next().slideDown('slow');
      var outerDiv = $('#outer');
      $('body').prepend(outerDiv);
      $(this).empty();
      restoreNavigation();
      return false;
    });
    location.hash = "#";
  } else {
    //Zusammenklappen
    $('#searchTab, #messeTab, #planTab, #nomenklTab').removeClass("nav-a nav-a-selected").addClass("nav-p");
    $('#searchTab, #messeTab, #planTab').next().slideUp('slow');
    $('#nomenklTab').next().slideUp('slow', function(){
      if((nav == 'search' && !$('#searchTab').hasClass('swapped')) || (nav == 'messe' && $('#messeTab').hasClass('swapped'))) {
        // Inhalt von DIVs vertauschen
        swapDivs('#searchTab', '#messeTab');
      } else {
        if(((nav == 'plan' || nav == 'plan-content') && !$('#planTab').hasClass('swapped'))
          || (nav == 'nomenkl' && $('#nomenklTab').hasClass('swapped'))) {
          swapDivs('#planTab', '#nomenklTab');
        } else {
          if(nav == 'search' || nav == 'messe') {
            $('#messeTab').removeClass("nav-p").addClass("nav-a-selected");
          } else if((nav == 'plan' || nav == 'plan-content') || nav == 'nomenkl') {
            $('#nomenklTab').removeClass("nav-p").addClass("nav-a-selected");
          }
        }
      }
      restoreNavigation();
      var returnParam = {
        nav: navGlobal,
        searchString: searchString,
        isExact: isExact,
        filter: param.filter
      };
      $.extend(returnParam, param);
      return callbackFunc(returnParam);
    });
  }
}

function swapDivs(div1, div2)
{
  inhalt1 = $(div1).html();
  inhalt2 = $(div2).html();
  $(div1).html(inhalt2);
  $(div2).html(inhalt1);
  $(div1 + ', ' + div2).toggleClass("swapped");
  $(div2).removeClass("nav-p").addClass("nav-a-selected");
}

function alertBox(title, message)
{
  if(typeof(title) == 'object') {
    message = title.message;
    title = title.title;
  }
  title = title ? title : t('txt_hinweis');
  $("#alert").remove();
  $content = "<div id='alert' class='top hidden'>"
  + "<div class='dBox'>"
  + "<div class='dBox_head'>"
  + "<h2>" + title + "</h2>"
  + "<a href='#' onClick='return closeAlert();' class='close-dialog'></a>"
  + "</div>"
  + "<div class='dBox_body'>"
  + message
  + "</div></div></div>";
  $('body').prepend($content);
  
  $('#alert').center().show();
}

function closeAlert()
{
  $("#alert").fadeOut(300, function(){
    $("#alert").remove();
  });
  return false;
}

function activeForm()
{
  $form = "";
  $('form').each(function(i){
    if($(this).is(':reallyvisible') && $(this).attr('name') != 'formLogin') {
      $form = $(this);
      return false;
    }
  });
  return $form;
}

function continueAction(url)
{
  window.location = url;
}

function confirmDialog(message, callback, param)
{
  alertBox(t('txt_hinweis'), message)
  var buttonOk = $('<input type=\"button\">').attr({
    'name': 'buttonOk',
    'value': t('txt_yes')
  }).
  css('margin-right', '10px').
  click(function(){
    return callback(param);
  });
  var buttonCancel = $('<input type=\"button\">').attr({
    'name': 'buttonCancel',
    'value': t('txt_cancel')
  }).
  click(function(){
    closeAlert();
  });
  var divWrapper = $('<div>').css('padding-top', '10px').
  append(buttonOk).
  append(buttonCancel);
  $('#alert .dBox_body').append(divWrapper);
}

function warnReg()
{
  title = t('txt_hinweis');
  message = t('txt_warnReg') + 
  "<div class=\"p10 middle\"><input type=\"button\" onClick=\"closeAlert();\" value=\"OK\" /></div>";
  alertBox(title, message);
  $('.warnReg').click(function(){
    ajaxGetContent({
      nav: 'messe#2'
    });
  });
  return false;
}

function checkSearchErw()
{
  var attrCount = $('input.inAtr:checked').size();
  var hallCount = $('input.inHall:checked').size();
  var title = "Hinweis";
  var message = "";
  if(attrCount == 0) {
    message = t('txt_no_atr_selected'); //"Keine Attribute gewählt."
  }
  if(hallCount == 0) {
    message = t('txt_no_hall_selected'); // "Keine Hallen gewählt.";
  }
  if(attrCount == 0 || hallCount == 0) {
    alertBox(title, message);
    return false;
  }
  return true;
}

function loginSuccess(div, data)
{
  var text = $('<div>' + data.text + '</div>').
  addClass('p5 pt10');
  var butLogout = $('<input type="button">').
  attr('id', 'butLogout').
  attr('name', 'butLogout').
  addClass('button').
  val(t('txt_abmelden')).
  click(function(){
    logout();
  });
  var butEdit = $('<input type="button">').
  attr('id', 'butEdit').
  attr('name', 'butEdit').
  addClass('button').
  val(t('txt_userEdit')).
  click(function(){
    ajaxGetContent({
      nav: 'messe#1'
    });
  });

  var butJobmarket = "";
  if(data.user.isjobmarket) {
    butJobmarket = $('<a href="administration.php" class="b arrow" target="_blank">' + t('txt_job_market_admininstration') + '</a>');
  }
 
  var divControls = $('<div>').
  addClass('p5').
  append(butLogout).
  append('<br />').
  append(butEdit).
  append('<br />').
  append(butJobmarket);
  div.html(text);
  div.append(divControls);

  ajaxFavCount();
  
  $('#searchNav').attr('disabled', false);
  $('.buttonSearch2').click(function(){
    //searchFromNav(this.form, $('#searchNav').val());
    });
  
  $('.contentDisabled').
  removeClass('contentDisabled').
  addClass('contentEnabled').
  unbind('click').
  click(function(){
    return ajaxGetContent($(this).attr('data-content'));
  });
}

function login()
{
  if(checkForm(document.forms.formLogin)) {
    $.getJSON("includes/ajaxRequest.php",
    {
      login: $('#loginEmail').val(),
      password: $('#loginPassword').val()
    },
    function(data){
      if(data.message == 'success') {
        alertBox(t('txt_hinweis'), data.text);
        loginSuccess($('#formLogin').parent(), data);
      } else {
        alertBox(t('txt_hinweis'), data.message);
      }
    });
  }
}

function logout()
{
  $.ajax({
    type: 'POST',
    url: 'includes/ajaxRequest.php',
    data: {
      logout: 1
    },
    success: function(message){
      window.location.href = "index.php";
    }
  });
}

function getList(listName)
{
  ajaxGetList(listName);
  
  allLists = $('.genList');
  currentList = $('.genList[name=' + listName + ']');
  if(listName.match(/#/)) {
    arr = listName.split('#');
    currentList = $('.genList[name^='+arr[0]+']');
  }
  allLists.parent().removeClass('yellowBox_body').addClass('whiteBox_body');
  allLists.parent().prev().removeClass('yellowBox_head').addClass('whiteBox_head');
  allLists.parent().parent().removeClass('yellowBox').addClass('whiteBox');
  allLists.parent().parent().unbind();

  currentList.parent().removeClass('whiteBox_body').addClass('yellowBox_body');
  currentList.parent().prev().removeClass('whiteBox_head').addClass('yellowBox_head');
  currentList.parent().parent().removeClass('whiteBox').addClass('yellowBox');

  $('.genList').not(currentList).parent().parent().slideUp('slow');
  //console.log(listName + ' slided! ' + $('input.genList').not(currentList).parent().parent().attr('class'));
  $('#schalterList').addClass('schalterSucheAuf').removeClass('schalterSucheZu');

  currentList.parent().parent().
  hover(function(){
    this.timeout = setTimeout(function(){
      allLists.parent().parent().slideDown('slow');
      $('#schalterList').addClass('schalterSucheZu').removeClass('schalterSucheAuf');
    },1000);
  },function(){
    if(this.timeout) {
      clearTimeout(this.timeout);
    }
  });
  return false;
}

function favoriteDelAll()
{
  var sConfirmDelete = t('txt_confirm_delete');
  confirmDialog(sConfirmDelete, ajaxFavDel, {
    favdel: 'all',
    veid: 0
  })
}

function restoreNavigation()
{  
  $('.contentDisabled').
  unbind('click').
  click(function(){
    return warnReg();
  });
  
  $('.contentEnabled').
  unbind().
  click(function(){
    var hash = $(this).attr('data-content');
    $.historyLoad({
      nav: hash
    });
  //return ajaxGetContent($(this).attr('data-content'));
  });
    
  $(".contentEnabledx")
  .unbind('click')
  .click(function(e){
    var hash = $(this).attr('data-content');
    // hash = hash.replace(/^.*#/, '');
    // moves to a new page.
    // pageload is called at once.
    //ajaxGetContent(hash);
    //$.history.load(hash);
    return ajaxGetContent(hash);
    e.preventDefault();
  //return false;
  });

  $(".noplan").unbind('click').
  click(function(){
    title = t('txt_hinweis');
    message = t('txt_no_plan') +
    "<div class=\"p10 middle\"><input type=\"button\" onClick=\"closeAlert();\" value=\"OK\" /></div>";
    alertBox(title, message);
    return false;
  });

  $('.buttonSearch2:not(.contentDisabled)').
  unbind('click').
  click(function(){
    //searchFromNav(this.form, $('#searchNav').val());
    });
}

function bannerRefresh()
{
  $('#bannerLeft').attr('src', $('#bannerLeft').attr('src'));
  $('#bannerTop').attr('src', $('#bannerTop').attr('src'));
  $('#bannerRight').attr('src', $('#bannerRight').attr('src'));
}


// reallyvisible selector
jQuery.extend(
  jQuery.expr[ ":" ],
  {
    reallyvisible : function (a) {
      return !(jQuery(a).css('display') == 'none' || jQuery(a).parents(':hidden').length);
    }
  }
  );

function scrollText(aLink)
{
  var isInit = false;
  if(!aLink) {
    aLink = $('.scroll.up:reallyvisible');
    isInit = true;
  }

  aLink.each(function(i,e) {
    var $pagerDiv = $(this).parent();
    var $scrollDiv = $pagerDiv.next();
    if (isInit && $scrollDiv.hasClass('supplemented')) {
      return true;
    }

    var up = $(this).hasClass('up');
    var down = $(this).hasClass('down');

    // Abstand von oben
    var elScrollTop = parseInt($scrollDiv.scrollTop());

    // Zeilenhöhe
    var lineHeight = parseFloat($scrollDiv.css('line-height'));
    if(isNaN(lineHeight)) {
      lineHeight = "13"; // IE FIX
    }

    // gesamte Höhe
    var elScrollHeight = parseInt($scrollDiv.attr('scrollHeight'));

    // zu sehende Höhe
    var elHeight = $scrollDiv.height();

    if(elScrollHeight <= elHeight) {
      $pagerDiv.css('visibility', 'hidden');
      $scrollDiv.attr('scrollTop', 0);
      return true; // continue statement for jQuery .each()
    }
    // Anzahl Zeilen ausrechnen
    var countStrings = parseInt(elHeight/ lineHeight);

    // zu sehende Höhe anpassen
    elHeight = countStrings * lineHeight;

    $scrollDiv.height(elHeight);

    elHeight = $scrollDiv.height();

    if(!$scrollDiv.hasClass('supplemented')) {
      //gesamte Höhe muss vielfaches von zu sehenden Höhe sein
      // wieviel fehlt es
      var addHeight = elHeight - elScrollHeight % elHeight;
      if (elScrollHeight % elHeight < lineHeight) {
        addHeight = 0;
      }

      // Anzahl Tags <BR>, um die richtige Höhe zu bekommen
      var countBr = parseInt(addHeight / lineHeight);

      // Br Tags zum Div anhängen
      for(i = 0; i < countBr; i++) {
        $scrollDiv.append('<br />');
      }
      $scrollDiv.addClass('supplemented');
    }

    // Wenn zurückblättern und height nicht vielfaches von scrollHeight ist
    if(elScrollTop % elHeight) {
      elScrollTop = (elHeight * Math.ceil(elScrollTop / elHeight));
    }
    var val = elHeight;
    if(up) {
      val = -val;
    }

    if(aLink.size() == 1 && ((elScrollTop +  elHeight) < elScrollHeight) && down || (elScrollTop > 0) && up) {
      $scrollDiv.attr({
        scrollTop: elScrollTop + val
      });
    }

    elScrollTop = parseInt($scrollDiv.scrollTop());
    var actPage = parseInt(elScrollTop / elHeight) + 1;

    var pages = elScrollHeight / elHeight;
    var countPages = Math.ceil(elScrollHeight / elHeight);
    var delta = parseFloat(pages) - parseInt(pages);
    if (delta < 0.1) {
      countPages--;
    }

    // Falls nur eine Seite, keine Blätterfkt
    if(countPages == 1) {
      $pagerDiv.css('visibility', 'hidden');
      $scrollDiv.css({
        'height': 'auto',
        'width': 'auto'
      });
    } else {
      $pagerDiv.css('visibility', 'inherit');
    }
    // Wenn forwärtsblättern und height nicht vielfaches von scrollHeight ist
    if(elScrollTop % elHeight) {
      actPage = countPages;
    }

    $(this).parent().children('span').html(actPage + '/' + countPages);

    if(actPage == 1) {
      $scrollDiv.attr('scrollTop', 0);
      //$(this).filter('.up').hide();
      $(this).filter('.up').css('visibility', 'hidden');
      //$(this).parent().children('a.down').show();
      $(this).parent().children('a.down').css('visibility', 'inherit');
    //$(this).parent().children('a.down').css('visibility', 'visible');
    } else if(actPage == countPages) {
      //$(this).filter('.down').hide();
      $(this).filter('.down').css('visibility', 'hidden');
      //$(this).parent().children('a.up').show();
      $(this).parent().children('a.up').css('visibility', 'inherit');
    //$(this).parent().children('a.up').css('visibility', 'visible');
    } else {
      //$(this).parent().children('a').show();
      $(this).parent().children('a').css('visibility', 'visible');
    }
  });
  return false;
}



function submitAutocomplete($input) {
  $form = $input.parents('form');
  $submitButton = $('input[type=submit]', $form);
  return submitAjaxForm($submitButton, $input);
}

function showPopup(data) {
  var scrollT = $(document).scrollTop();
  $('#wait').hide();
  $('#ajaxLoaderBlack').show();
  $('#ajaxLoaderBlack').css('top', scrollT + 20 + 'px');
  $('#details, #shadeBackground').remove();
  $('body').prepend("<div id='details'>");
  $('body').prepend("<div id='shadeBackground'>");
  $('#details').css('top', scrollT + 20 + 'px');
  $('#shadeBackground').show();
  $('#details').html(data);

  $.getScript('js/details.js', function(){
    $(document).scrollTop(scrollT);
    $('#details').show('slow');
    $('#ajaxLoaderBlack').hide();
  });
  $('#details').show('slow');
  return false;
}

function hidePopup() {
  $('#meeting, #alert, #print-options').hide();
  $('#details').hide('slow', function() {
    $('#shadeBackground').hide();
  });
  $('#details, #shadeBackground').remove();
  return false;
}

function hideDetails()
{
  $('#meeting, #alert, #print-options').hide();
  $('#details').hide('slow', function() {
    $('#shadeBackground').hide();
  });
  $('#details').empty();
  return false;
}

function showDetails()
{
  $('#details').css('top', $(document).scrollTop() + 20 + 'px');
  $('#wait').hide();
  $('#shadeBackground').show();
  $('#details').show('slow');
  return false;
}



/*******************************************
* Default Texte für Input Felder
*******************************************/
jQuery.fn.inputText = function(userOptions)
{
  var options = {
    defaultText: $(this).attr('data-default')
  }
  $.extend(options, userOptions);
  $(this).val(options.defaultText);
  $(this).unbind().
  focus(function(){
    if($(this).val() == options.defaultText) {
      $(this).val('');
      $(this).removeClass('grey');
      if($(this).attr('id') == 'loginPassword') {
        var newInputPasswort = $('<input type="password">').
        attr({
          'id': 'loginPassword',
          'name': 'loginPassword'
        }).
        addClass('login not_blank').
        keyup(function(e) {
          if(e.which == 13) {
            login();
          }
        });

        $(this).after(newInputPasswort);
        $(this).remove();
        $('#loginPassword').focus();
      }
    }
  }).
  blur(function(){
    if($(this).val() == '') {
      $(this).val(options.defaultText);
      $(this).addClass('grey');
    }
  });
}



/*********************************************
* Favoriten verwalten Link
*********************************************/
jQuery.fn.favorite = function(userOptions)
{
  $(this).each(function(){
    $this = $(this);

    function Favorite($element) {
      this.$el = $element;
      this.isFavorite = $element.hasClass('favsel');
      this.id = $element.attr('data-id');
      this.veid = $element.attr('data-veid');
      // ob man sofort zu Favoriten hinzufügen kann (Benutzer registriert oder Option freigeschaltet)?
      this.warning = $element.hasClass('warnreg')
    }

    Favorite.prototype = {
      warn : function() {
        if(this.warning) {
          return warnReg();
        }
      },
      add : function() {
        this.isFavorite = true;
        this.$el.data('isFavorite', true);
        ajaxFavIns({
          favins: this.id,
          veid: this.veid
        });
      },
      remove : function() {
        // entfernen
        this.isFavorite = false;
        this.$el.data('isFavorite', false);
        ajaxFavDel({
          favdel: this.id,
          veid: this.veid
        });
      },
      highlight : function() {
        if(this.isFavorite) {
          this.$el.removeClass('favsel').addClass('favdel');
        } else {
          this.$el.removeClass('favins').addClass('favsel');
        }
      },
      dehihglight : function() {
        if(this.isFavorite) {
          this.$el.removeClass('favdel').addClass('favsel');
        } else {
          this.$el.removeClass('favsel favdel').addClass('favins');
        }
      },
      flashCounter : function() {
        //Favoritenzähler highlighten
        $(".fav-num").addClass("fav-num-h").removeClass("fav-num");
        //animiertes Pfeil zeigen
        $('.arr-counter').addClass('arr-counter-v').fadeIn('slow');
      }
    }

    var favorite = new Favorite($this);

    var options = {
      isFavorite: $this.hasClass('favsel'),
      id: $this.attr('data-id'),
      veid: $this.attr('data-veid'),
      // alle Favoritenlinks mit dieser ID
      collection: $('a.favorite[data-id=' + $this.attr('data-id') + '][data-veid=' + $this.attr('data-veid') + ']'),
      // ob man sofort zu Favoriten hinzufügen kann (Benutzer registriert oder Option freigeschaltet)?
      warning: $this.hasClass('warnreg')
    }

    $.extend(options, userOptions);

    $this.data('isFavorite', options.isFavorite);

    $this.hover(function(){
      favorite.highlight();
    }, function(){
      favorite.dehihglight();
    });


    $this.
    click(function(){
      favorite.warn();
      favorite.flashCounter()
      
      if(favorite.isFavorite) {
        favorite.remove();

        options.collection.each(function(){
          $(this).data('isFavorite', false);
          $(this).removeClass('favsel favdel').addClass('favins');

          $(this).
          tooltip({
            showURL: false,
            delay: 0,
            bodyHandler: function(){
              return '<h3>' + t('txt_favDelTooltip') + '</h3>';
            }
          });
        });
      } else {
        favorite.add();
        // Alle Links behandeln
        options.collection.each(function(){
          $(this).data('isFavorite', true);
          $(this).removeClass('favins').addClass('favsel');
          $(this).tooltip({
            showURL: false,
            delay: 0,
            bodyHandler: function(){
              return '<h3>' + t('txt_favInsTooltip') + '</h3>';
            }
          });
        });
      }
      return false;
    });
  });
}



/*********************************************
* Autocomplete für die Suche nach Ausstellern
*********************************************/
jQuery.fn.autocompleteExhibitors = function(userOptions)
{
  var options = {
    input: $(this)
  }
  $.extend(options, userOptions);

  var ENTER = 13;
  var UP = 38;
  var DOWN = 40;
  var ESC = 27;


  function lookup(inputString)
  {
    $('input[name=filter]').val('a');
    $('input[name=isExact]').val('0');
    if(inputString.length == 0) {
      $('#suggestions').hide();
      $('#outer').hide();
    } else {
      $.post("includes/ajaxRequest.php", {
        autocomplete: ""+inputString+""
      }, function(data){
        if(data.length > 0) {
          $('#suggestions').html(data);
          $('#suggestions').show();
          $('#outer').show();
          decorate();
        } else {
          $('#suggestions').hide();
          $('#outer').hide();
        }
      });
    }
  }

  function menuOver($item)
  {
    $item.addClass('iehover');
  }

  function menuOut($item)
  {
    $item.removeClass('iehover');
  }

  function decorate()
  {
    $('ul#hmenu li.acWert').
    mouseover(function(){
      menuOver($(this));
    }).
    mouseout(function(){
      menuOut($(this));
    }).
    click(function(){
      fill($(this).attr('title'), $(this).attr('name'));
      $('input[name=isExact]').val('1');
      if(options.input.attr('id') == 'searchAdvanced') {
        if(checkSearchErw()) {
          searchSubmit();
        }
      } else {
        searchSubmit();
      }
    });
  }

  function fill(thisValue, filter)
  {
    $('input[name=filter]').val(filter);
    $('#searchNav, #searchStandart, #searchAdvanced').val(thisValue);
    $('#suggestions').hide();
    $('#outer').hide();
  }

  $(this).
  unbind('keyup').
  keyup(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    switch(code) {
      case DOWN:
      case UP:
        liSelected = $('#hmenu .acWert').index($('#hmenu .acWert.iehover'));
        liCount = $('#hmenu .acWert').size();
        //alert(e.which + ' ' + liSelected + ' ' + liCount);
        if(e.which == DOWN) {
          index = liSelected + 1;
          if(index >= liCount) {
            index = liCount - 1;
          }
        //alert('key: ' + e.which + ' li: ' + liSelected + ' i: ' + index + ' count: ' + liCount);
        } else {
          index = liSelected - 1;
          if(index < 0) {
            index = 0;
          }
        //alert('key: ' + e.which + ' li: ' + liSelected + ' i: ' + index + ' count: ' + liCount);
        }
        $('#hmenu .acWert').removeClass('iehover');
        $('#hmenu .acWert').eq(index).addClass('iehover');
        //alert('li: ' + liSelected + ' title: ' + $('#hmenu .acWert').eq(index).attr('title'));
        break;
      case ENTER:
        var filter = 'a';
        if($('#hmenu .iehover').hasClass('filterF')) {
          filter = 'f';
        }
        if($('#hmenu .iehover').hasClass('filterM')) {
          filter = 'm';
        }
        if($('#hmenu .iehover').hasClass('filterN')) {
          filter = 'n';
        }
        value = $('#hmenu .iehover').attr('title');
        if(value) {
          fill(value, filter);
          $('input[name=isExact]').val('1');
        }
        if(options.input.attr('id') == 'searchAdvanced') {
          if(checkSearchErw()) {
            searchSubmit();
          }
        } else {
          searchSubmit();
        }
        break;
      case ESC:
        $('#hmenu .acWert').removeClass('iehover');
        $('#suggestions').hide();
        $('#outer').hide();
        break;
      default:
        $('#outer').remove();
        var outerDiv = $("<div id='outer'>").append($("<div id='suggestions'>"));
        var pos = $(this).position();
        var leftOffset = parseInt($(this).css('margin-left'));
        var topOffset = parseInt($(this).css('margin-top'));
        var height = $(this).height();
        outerDiv.css({
          top: pos.top + height + topOffset + 4,
          left: pos.left + leftOffset
        });
        $(this).after(outerDiv);
        lookup(this.value);
        break;
    }
  });
}



// Blättern in News / Presentations usw
$.fn.scrollElements = function(userOptions)
{
  $(this).each(function(i,e){
    var options = {
      displayedItems: 10
    }
    $.extend(options, userOptions);

    var $this = $(this);

    if($this.children().size() <= options.displayedItems){
      return;
    }

    var $list = $this.children();
    options.displayedItems = Math.min(options.displayedItems, $list.size());
    var $firstEl = $list.filter(':visible:first');
    var shift = Math.min(options.displayedItems, $list.size());
    var $lastEl = $list.eq($firstEl.index() + shift - 1);
    var countPages = Math.ceil($list.size() / options.displayedItems);

    function scrollBack() {
      $firstEl = $list.eq($firstEl.index() - options.displayedItems);
      shift = Math.min(options.displayedItems, $list.slice($firstEl.index()).size());
      $lastEl = $list.eq($firstEl.index() + shift - 1);
      update();
    }

    function scrollNext() {
      $firstEl = $lastEl.next();
      shift = Math.min(options.displayedItems, $list.slice($firstEl.index()).size());
      $lastEl = $list.eq($firstEl.index() + shift - 1);
      update();
    }

    $.fn.mask = function() {
      $(this).each(function(){
        $(this).css('visibility', 'hidden');
      });
    }

    $.fn.unmask = function() {
      $(this).each(function(){
        $(this).css('visibility', 'inherit');
      });
    }

    function update() {
      // $lastEl.index() is in IE7-8 -1, so use $list.index($lastEl)
      var firstIndex = $list.index($firstEl);
      var lastIndex = $list.index($lastEl);

      $visibleList = $list.slice(firstIndex, lastIndex + 1);
      var $scrollText = $this.prev().find('span');
      var $backLink = $this.prev().find('.scrollBack');
      var $nextLink = $this.prev().find('.scrollNext');
      var currentPage = Math.round(firstIndex / options.displayedItems) + 1;

      $backLink.unmask();
      $nextLink.unmask();

      if(currentPage == countPages) {
        $nextLink.mask();
      }

      if(currentPage == 1) {
        $backLink.mask();
      }

      $scrollText.text(currentPage + '/' + countPages);
      $list.hide();
      $visibleList.show();
    }

    var $page = $('<img height="18" width="14" src="images/page.gif" class="pages fl">');
    var $backLink = $('<a class="scrollBack"></a>')
    .click(function(){
      scrollBack();
    });

    var $scrollText = $('<span class="b black pr5 fl"></span>');

    var $nextLink = $('<a class="scrollNext"></a>')
    .click(function(){
      scrollNext();
    });

    var $scroller = $('<div class="scrollPages"></div>')
    .append($backLink)
    .append($page)
    .append($scrollText)
    .append($nextLink);

    if (!$this.prev().hasClass('scrollPages')) {
      $this.before($scroller);

      update();
      var height = $this.parent().height();
      $this.parent().css('cssText', 'height: ' + height + 'px !important');
    }
  });
}

function reloadCaptcha() {
  $('#captcha').attr('src', 'includes/captcha.php?' + Math.random());
}

function monkeyPatchAutocomplete() {
  // Don't really need to save the old fn,
  // but I could chain if I wanted to
  var oldFn = $.ui.autocomplete.prototype._renderItem;
  var oldRenderMenuFn = $.ui.autocomplete.prototype._renderMenu;

  $.ui.autocomplete.prototype._renderItem = function( ul, item) {
    var re = new RegExp("^" + this.term, "i") ;
    var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" + this.term + "</span>");
    return $( "<li></li>" )
    .data( "item.autocomplete", item )
    .append( "<a>" + t + "</a>" )
    .appendTo( ul );
  };

  $.ui.autocomplete.prototype._renderMenu = function( ul, items ) {
    var self = this;
    var appendedTitles = new Array();
    $.each( items, function( index, item ) {
      if(appendedTitles[item.type] === undefined ) {
        ul.append( "<li class='submenu'>" + item.type + "</li>" );
        appendedTitles[item.type] = true;
      }
      self._renderItem( ul, item );
    });
  }
}

function updateProfile(data, $link) {
  $div = $link.closest('div[id^=divTab]');
  $div.css('height', '');

  var parsedUrl = parseURL($link.attr('href'));
  
  if (typeof parsedUrl.params.r != 'undefined') {
    var arr = parsedUrl.params.r.split('/');
    parsedUrl.params.controller = arr[0];
    parsedUrl.params.action = arr[1];
  }

  var id = parsedUrl.params.id; // Aussteller
  var veid = parsedUrl.params.veid;
  var type = parsedUrl.params.controller;

  // Druck Button anpassen
  $('a[data-section=profile]').
  unbind('click').
  removeAttr('onclick').
  click(function(){
    showPrintOptions({
      section: 'profile',
      type: type,
      id: id,
      veid: veid
    });
  });

  $div.html(data);
  $.getScript('js/details.js');
  return false;
}
