function gallery_setup_buttons(){
  $('.js_gallery_scroll_right').click(function(){
    var imageWidth = 100;
    var scroll_times_max = $('#gallery').children().length / 4;
    var currentPos = parseInt($('#gallery').css('marginLeft').replace('px',''));
    if((currentPos * -1 + imageWidth*2) < scroll_times_max*imageWidth*4)
      $('#gallery').css('marginLeft',currentPos-300+'px');
    return false;
  });
  
  $('.js_gallery_scroll_left').click(function(){
    var currentPos = parseInt($('#gallery').css('marginLeft').replace('px',''));
    if(currentPos < 0)
      $('#gallery').css('marginLeft',currentPos+300+'px');
    return false;
  });
  
  // LOAD A BIG IMAGE
  $('.js_show_image').click(function(){
    $('#spleenLoading').show();
    $('#image').attr('src',$(this).attr('href'))
               .hide()
               .data('url',$(this).attr('href'));
               
    var elem = $(this);
    $("#image").load(function(data){
      $('#image').attr('src',$(this).attr('href'));
      var text = $(elem).next('div').find('input[name=title]').val();
      if(LOGGED_IN && (!text || text == ''))
        text = 'no title yet';
      $('#image_title_admin').val(text);
      $('#image_title').text(text);
      text = $(elem).next('div').find('input[name=copyright]').val();
      if(LOGGED_IN && (!text || text == ''))
        text = 'no copyright yet';
      $('#image_copyright_admin').val(text);
      $('#image_copyright').text(text);
      text = $(elem).next('div').find('input[name=description]').val();
      if(LOGGED_IN && (!text || text == ''))
        text = 'no description yet';
      $('#image_description_admin').val(text);
      $('#image_description').text(text);
      if(Dialog.origWidth < $('#image').width())
        Dialog.setWidth($('#image').width()+20);
      if(Dialog.origHeight < $('#image').height())
        Dialog.setHeight($('#image').height() + Dialog.origHeight);
      $('#spleenLoading').hide();
      $('#image').fadeIn();
    });
    
    return false;
  });
  
  $('.js_gallery_edit').click(function(){
    $(this).next('input').show()
                         .select();
    $(this).next('textarea').show().focus();
    $(this).hide();
    return false;
  });
  
  $('.ajax_save_image_details').blur(function(){
    $(this).hide();
    $(this).after("<img src=\""+ZORN_BASE_DIR+"/default/layout/img/loading.gif\" />");
    var loader = $(this).next('img');
    var elem = $(this);
    jQuery.ajax({type:'POST',
                 url: $('#image').data('url'),
                 data: {title: $('#image_title_admin').val() != 'no title yet' ? $('#image_title_admin').val() : '',
                        copyright: $('#image_copyright_admin').val() != 'no copyright yet' ? $('#image_copyright_admin').val() : '',
                        description: $('#image_description_admin').val() != 'no description yet' ? $('#image_description_admin').val() : ''
                 },
                 success: function(data){
                  $(elem).prev().text($(elem).val()).show();
                  $(loader).remove();
                 }
    });
    return false;
  });
}

function display_gallery(url){
  jQuery.ajax({type:'GET',
               url: url + '.gallery.html',
               success: function(data){
                Dialog.show("Gallery",data,{width:480,height:220});
                gallery_setup_buttons();
                $('#gallery').children(':first').click();
               },
               error: function(req){
                Dialog.show("Gallery","<p>no images found</p>");
               }
  });
}

function countdownSpleen(){
  var count = 0;
  $('.countSpleen').each(function(){
    $("#counter_"+count.toString()).countdown({until: counters[count],
                                 layout: '{hnn}h {mnn}min'});
    count++;
  });
}

jQuery.fn.zornTypeWriter = function() {
  $(this).each(function(){
    var text = $(this).text();
    var html = "";
    for (var i=0;i<text.length;i++){
      if ($(this).hasClass('white'))
        html += '<div class="spleenFont-white spleenFont-';
      else
        html += '<div class="spleenFont spleenFont-';
      switch(text[i]){
        case ' ':
          html += 'space';
          break;
        case '*':
          html += 'asterisk';
          break;
        case ':':
          html += 'colon';
          break;
        case 'ö':
        case '&ouml':
          html += 'oe';
          break;
        case 'ä':
        case '&auml;':
          html += 'ae';
          break;
        case 'ü':
        case '&uuml;':
          html += 'ue';
          break;
        case 'Ö':
        case 'Ouml;':
          html += 'OE';
          break;
        case 'Ä':
        case '&Auml;':
          html += 'AE';
          break;
        case 'Ü':
        case 'Uuml;':
          html += 'UE';
          break;
        case '-':
        case '–':
          html += 'dash';
          break;
        case '\'':
          html += 'single-quote';
          break;
        case ',':
          html += 'comma';
          break;
        case '(':
          html += 'bracket-left';
          break;
        case ')':
          html += 'bracket-right';
          break;
        case '!':
          html += 'exclamation-mark';
          break;
        case '?':
          html += 'question-mark';
          break;
        case '@':
          html+= 'at';
          break;
        case '+':
          html += 'plus';
          break;
        case '„':
        case '”':
        case '"':
          html += 'double-quote';
          break;
        case 'ß':
        case '&szlig;':
          html += 'scharfs';
          break;
        case '&':
          html += 'ambersand';
          break;
        case '/':
          html += 'slash';
          break;
        case '.':
          html += 'fullstop';
          break;
        default:
          html += text[i]; 
      }
      html += '" />';
    }
    $(this).html(html);
    var newwidth = 0;
    $(this).children('.spleenFont').each(function(){
      newwidth += $(this).width();
    });
    $(this).children('.spleenFont-white').each(function(){
      newwidth += $(this).width();
    });
    if(!$(this).hasClass('keepWidth'))
      $(this).css('minWidth',newwidth+5+'px');
    if($(this).hasClass('textMarkerDo')){
      $(this).removeClass('textMarkerDo');
      $(this).addClass('textMarker');
      var color = "";
      if($(this).hasClass('textMarker-red')){
        $(this).removeClass('textMarker-red');
        color = "-red";
      }
      if($(this).hasClass('textMarker-purple')){
        $(this).removeClass('textMarker-purple');
        color = "-purple";
      }
      if($(this).hasClass('textMarker-green')){
        $(this).removeClass('textMarker-green');
        color = "-green";
      }
      if($(this).hasClass('textMarker-orange')){
        $(this).removeClass('textMarker-orange');
        color = "-orange";
      }
      if($(this).hasClass('textMarker-blue'))
        color = "-blue";
      if(text.length > 35)
        $(this).addClass('textMarker'+color+'-verylong');
      if(text.length > 26)
        $(this).addClass('textMarker'+color+'-long');
      else if(text.length > 11)
        $(this).addClass('textMarker'+color+'-middle');
      else if(text.length >= 5 && color != "")
        $(this).addClass('textMarker'+color);
      else if(text.length < 5)
        $(this).addClass('textMarker'+color+'-short');
    }
  });
}

var SpleenLoading = {
  loading: false,
  show: function(){
    $('#spleenLoading').removeClass('spleenLoading-finished');
    this.loading = true;
    this.blink();
  },
  blink: function(){
    var self = this;
    if(self.loading)
      setTimeout(function(){
        self.blink();
      }, 800);
    else
      return;
    if($('#spleenLoading').css('display') == 'none')
      $('#spleenLoading').fadeIn('fast');
    else
      $('#spleenLoading').fadeOut('slow');
  },
  hide: function(){
    this.loading = false;
    $('#spleenLoading').show();
    $('#spleenLoading').addClass('spleenLoading-finished');
    $('#spleenLoading').fadeOut(1500);
  }
}

// SPLEEN*PLAN Locations
function selectLocationMarker(elem){
    $('.spleenmapObject').removeClass('spleenmapLocation');
    $(elem).addClass('spleenmapLocation');
    var venueText = "<div class=\"bg\"></div><div class=\"fg\">";
    switch($(elem).attr('id')){
      case "location-TTZ":
        venueText += "<h1>TTZ</h1><p>Tanz & Theaterzentrum Graz</p><p>Viktor-Franzstraße 9, A - 8051 Graz</p>";
        break;
      case "location-Lend":
        venueText += "<h1>Theater am Lend</h1><p>Wienerstrasse 58a, 8020 Graz</p>";
        break;
      case "location-Orpheum":
        venueText += "<h1>Orpheum Graz</h1><p>Orpheumgasse 8, 8020 Graz</p>";
        break;
      case "location-Dom":
        venueText += "<h1>Dom im Berg</h1><p>Schloßbergplatz 1, 8010 Graz</p>";
        break;
      case "location-Next":
        venueText += "<h1>Next Liberty</h1><p>Kaiser-Josef-Platz 10, 8010 Graz</p>";
        break;
      case "location-ESC":
        venueText += "<h1>spleen*hotspot</h1><p>ESC</p><p>Jakoministraße 16, 8010 graz</p>";
        break;
      case "location-TaO":
        venueText += "<h1>TaO!</h1><p>Theater am Ortweinplatz</p><p>Ortweinplatz 1, 8010 Graz</p>";
        break;
      case "location-Frida":
        venueText += "<h1>Frida & Fred</h1><p>KIMUS Kindermuseum Graz GmbH</p><p>Friedrichgasse 34, 8010 Graz</p>";
        break;
      case "location-jakoministr":
        venueText += "<h1>spleen*trieb</h1><p>Jakoministraße</p><p>8010 Graz</p>";
        break;
    }
    venueText += "</div>";
    $('#spleenmapCaption').html(venueText);
}

function renderLocationMarkers(options){
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-TTZ\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-Lend\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-Orpheum\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-Dom\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-Next\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-ESC\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-TaO\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-Frida\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-jakoministr\"/>"));
  $('#spleenScreen').append($("<div id=\"spleenmapCaption\"/>"));
  
  if(options && options.selectLocation){
    var elem = null;
    switch(options.selectLocation){
      case "Dom im Berg":
        elem = "location-Dom";
        break;
      case "Theater am Ortweinplatz":
        elem = "location-TaO";
        break;
      case "Theater am Lend":
        elem = "location-Lend";
        break;
      case "Orpheum extra":
      case "Orpheum":
        elem = "location-Orpheum";
        break;
      case "Frida&freD":
      case "FRida&freD":
        elem = "location-Frida";
        break;
      case "spleen*hotspot":
        elem = "location-ESC";
        break;
      case "Next Liberty":
        elem = "location-Next";
        break;
      case "Tanz & Theater Zentrum Graz":
        elem = "location-TTZ";
        break;
      case "Jakoministraße":
        elem = "location-jakoministr";
        break;
    }
    if(elem)
      selectLocationMarker($('#'+elem));
  }else{
    setTimeout(function(){$('#spleenScreen > .spleenmapObject').addClass('spleenmapLocation');},800);
    setTimeout(function(){$('#spleenScreen > .spleenmapObject').removeClass('spleenmapLocation');},1800);
  }
  
  // set up event when moving mouse pointer over location
  $('#spleenScreen > .spleenmapObject').mouseenter(function(){
    selectLocationMarker(this);
  });
}

// -------------------------------------------------------- Vegetable Nannies special use case */
function selectLocationMarkerVN(elem){
    $('.spleenmapObject').removeClass('spleenmapLocation');
    $(elem).addClass('spleenmapLocation');
    var venueText = "<div class=\"bg\"></div><div class=\"fg\">";
    switch($(elem).attr('id')){
      case "location-Frida":
        venueText += "<h1>Frida & Fred</h1><p>KIMUS Kindermuseum Graz GmbH</p><p>Friedrichgasse 34, 8010 Graz</p>";
        break;
      case "location-Lendplatz":
        venueText += "<h1>Lendplatz Markt</h1><p>Lendplatz Markt, 8020 Graz</p>";
        break;
      case "location-Mangolds":
        venueText += "<h1>Mangolds</h1><p>Griesgasse 11, 8020 Graz</p>";
        break;
      case "location-KaiserJosefMarkt":
        venueText += "<h1>Kaiser Josef Markt</h1><p>Kaiser Josef Platz 1, 8010 Graz</p>";
        break;
      case "location-EisernesTor":
        venueText += "<h1>Am Eisernen Tor</h1><p>Am Eisernen Tor 1, 8010 Graz</p>";
        break;
      case "location-Hauptplatz":
        venueText += "<h1>Hauptplatz Graz</h1><p>Hauptplatz 1, 8010 Graz</p>";
        break;
    }
    venueText += "</div>";
    $('#spleenmapCaption').html(venueText);
}

function renderLocationMarkersVN(options){
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-Frida\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-Lendplatz\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-Mangolds\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-KaiserJosefMarkt\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-EisernesTor\"/>"));
  $('#spleenScreen').append($("<div class=\"spleenmapObject\" id=\"location-Hauptplatz\"/>"));
  $('#spleenScreen').append($("<div id=\"spleenmapCaption\"/>"));
  
  if(options && options.selectLocation){
    var elem = null;
    switch(options.selectLocation){
      case "Lendplatz Markt":
        elem = "location-Lendplatz";
        break;
      case "Kaiser Josef Markt":
        elem = "location-KaiserJosefMarkt";
        break;
      case "Eisernes Tor":
        elem = "location-EisernesTor";
        break;
      case "Mangolds":
        elem = "location-Mangolds";
        break;
      case "Hauptplatz":
        elem = "location-Hauptplatz";
        break;
      case "Frida&freD":
      case "FRida&freD":
        elem = "location-Frida";
        break;
    }
    if(elem)
      selectLocationMarkerVN($('#'+elem));
  }else{
    setTimeout(function(){$('#spleenScreen > .spleenmapObject').addClass('spleenmapLocation');},800);
    setTimeout(function(){$('#spleenScreen > .spleenmapObject').removeClass('spleenmapLocation');},1800);
  }
  
  // set up event when moving mouse pointer over location
  $('#spleenScreen > .spleenmapObject').mouseenter(function(){
    selectLocationMarkerVN(this);
  });
}

/* -------------------------------------------------------- end VN special */

function loadImage(options){
  $('#spleenScreen').fadeIn();
  $('#spleenFuzzBg').show();
  SpleenLoading.show();
  var img = new Image();
  $(img).load(function(){
    if(options.imgWidth)
      $(img).width(options.imgWidth);
    if(options.imgHeight)
      $(img).height(options.imgHeight);
    $('#spleenScreen').find('img').remove();
    $('#spleenScreen').prepend(img);
    $(img).css('display', 'none');
    $(img).hide();
    setTimeout(function(){
      $('#spleenLoading').hide();
      $('#spleenScreen').width($(img).width());
      $('#spleenScreen').height($(img).height()+
                               $('#spleenScreen .bottomInfo').height());
      var marginLeft = $(img).width()/2;
      if ($(img).width() > $(window).width())
        marginLeft = $(window).width()/2;
      var marginTop = $(img).height()/2;
      if ($(img).height() > $(window).height())
        marginTop = $(window).height()/2;
      $('#spleenScreen').css('marginLeft','-'+marginLeft+'px');
      $('#spleenScreen').css('marginTop','-'+marginTop+'px');
      $('#spleenScreen .topInfo').show();
      $('#spleenScreen .bottomInfo').show();
      SpleenLoading.hide();
      $(img).fadeIn();
    }, 100);
  }).attr('src',options.src);
}

function setupImage(elem){
  var text = $(elem).next('div.photoHiddenData').find('input[name=title]').val();
  if(LOGGED_IN && (!text || text == ''))
    text = 'no title yet';
  $('#spleenScreen .bottomInfo #image_title_admin').val(text);
  $('#spleenScreen .bottomInfo #image_title').text(text);
  text = $(elem).next('div.photoHiddenData').find('input[name=copyright]').val();
  if(LOGGED_IN && (!text || text == ''))
    text = 'no copyright yet';
  $('#spleenScreen .bottomInfo #image_copyright_admin').val(text);
  $('#spleenScreen .bottomInfo #image_copyright').text(text);
  text = $(elem).next('div.photoHiddenData').find('input[name=description]').val();
  if(LOGGED_IN && (!text || text == ''))
    text = 'no description yet';
  $('#spleenScreen .bottomInfo #image_description_admin').val(text);
  $('#spleenScreen .bottomInfo #image_description').text(text);
  
  $('.js_gallery_edit').click(function(){
    $(this).next('input').show()
                         .select();
    $(this).next('textarea').show().focus();
    $(this).hide();
    return false;
  });
  
  $('.ajax_save_image_details').blur(function(){
    $(this).hide();
    SpleenLoading.show();
    var elem = $(this);
    var atitle = $("#spleenScreen .bottomInfo #image_title_admin").val();
    var acopy = $("#spleenScreen .bottomInfo #image_copyright_admin").val();
    var adesc = $("#spleenScreen .bottomInfo #image_description_admin").val();
    jQuery.ajax({type:'POST',
                 url: $('#spleenScreen').data('url'),
                 data: {title: atitle != 'no title yet' ? atitle : '',
                        copyright: acopy != 'no copyright yet' ? acopy : '',
                        description: adesc != 'no description yet' ? adesc : ''
                 },
                 success: function(data){
                  $(elem).prev().text($(elem).val()).show();
                  Loading.hide();
                 }
    });
    return false;
  });
}

var ACTIVE_IMG = null;

$(document).ready(function(){
  if ($.browser.msie && $.browser.version.substr(0,1)<7) {
    location = "http://spleengraz.at/index.ie-error.html";
  }
  
  $('#spleenFuzzBg').height($(document).height());

  $('#search_text').focus(function(){
    $(this).select();
    return false;
  });
  
  // SEARCH RESULTS 
  if (location.search && location.search.indexOf('search_text=') >= 0 &&
      location.search.length > location.search.indexOf('search_text=')+13){
    terms = location.search.replace('?search_text=','').split('+');
    for (var i in terms){
      $('li').highlight(terms[i]);
      $('.highlight').addClass('term_'+i)
                     .addClass('highlighted')
                     .removeClass('highlight');
    }
    $('.result_p').each(function(){
      var t = $(this).html();
      var start = t.indexOf('highlighted')-100;
      if (start < 0)
        start = 0;
      var end = t.lastIndexOf('highlighted')+100;
      if (end > t.length)
        end = t.length;
      $(this).html(t.substring(start,end));
    });
  }
    
  $('a.js_display_gallery').click(function(){
    if($(this).attr('href') == '#' || $(this).attr('href') == ''){
      alert('a.href must be set');
      return false;
    }
    display_gallery($(this).attr('href'));
    return false;
  });
  
  
  if(location.href.indexOf('/index.html') > 0 ||
     location.href.lastIndexOf('/') == location.href.length-1)
    countdownSpleen();
  
  
  $('.spleenTypeWriter').zornTypeWriter();
  
  $('#spleenPlan').click(function(){
    loadImage({'src':$(this).find('a').attr('href')});
    renderLocationMarkers();
    return false;
  });
  
  $('#spleenScreenClose').click(function(){
    $('#spleenScreen').fadeOut();
    $('#spleenFuzzBg').hide();
    $('#spleenScreen .spleenmapObject').remove();
    $('#spleenScreen #spleenmapCaption').remove();
    $('#spleenScreen .bottomInfo').html('');
    $('#spleenScreenFW').hide();
    $('#spleenScreenBW').hide();
    return false;
  });
  
  $('#spleenScreenFW').click(function(){
    var nextImg = $(ACTIVE_IMG).closest('li').next().find('a.jsOpenImage');
    if (nextImg.length <= 0)
      nextImg = $(document).find('a.jsOpenImage:first');
    ACTIVE_IMG = nextImg;
    loadImage({'src':$(nextImg).attr('href'),
               'imgWidth':500});
    $('#spleenScreen .bottomInfo').html($('#photoDetails').html());
    return false;
  });  
  
  $('#spleenScreenBW').click(function(){
    var nextImg = $(ACTIVE_IMG).closest('li').prev('li').find('a.jsOpenImage');
    if (nextImg.length <= 0)
      nextImg = $(document).find('a.jsOpenImage:last');
    ACTIVE_IMG = nextImg;
    loadImage({'src':$(nextImg).attr('href'),
               'imgWidth':500});
    $('#spleenScreen .bottomInfo').html($('#photoDetails').html());
    return false;
  });  
  
  $('.jsOpenImage').click(function(){
    if($(this).attr('href') == '#')
      nextImg = "/spleengraz_at/layout/img/defaultPhoto.jpg";
    else{
      ACTIVE_IMG = this;
      nextImg = $(this).attr('href');
    }
    loadImage({'src':nextImg,
               'imgWidth':500});
    $('#spleenScreen .bottomInfo').html($('#photoDetails').html());
    $('#spleenScreen').data('url',$(this).attr('href'));
    if(ACTIVE_IMG){
      $('#spleenScreenFW').show();
      $('#spleenScreenBW').show();
    }
    setupImage(this);
    return false;
  });
  
  $('.jsOpenVenue').click(function(){
    loadImage({'src':$('#spleenPlan').find('a').attr('href')});
    if($(this).text()=="Im öffentlichen Raum, verschiedene Ausgangspunkte")
      renderLocationMarkersVN();
    else
      renderLocationMarkers({selectLocation: $(this).text()});
    return false;
  });
  
  $('.jsOpenVenueVN').click(function(){
    loadImage({'src':$('#spleenPlan').find('a').attr('href')});
    renderLocationMarkersVN({selectLocation: $(this).text()});
    return false;
  });
  
  $('#jsShowFBHints').click(function(e){
    e.preventDefault();
    $('#spleenScreen').find('img').remove();
    $('#spleenLoading').hide();
    var text = "<h1>Hinweise zur Verwendung der Facebook Integration auf der spleen*graz website</h1>" +
               "<ul><li>Der Anwendung &raquo;spleen website&laquo; muss der Zugriff gestattet werden, damit" +
               " Freunde und Bekannte angezeigt und erweiterte Kommunikationsm&ouml;glichkeiten aktiviert werden k&ouml;nnen" +
               " aktiviert werden.</li><li>Mit diesen Zugriffsrechten kann die Anwendung z.B. gepostete " + 
               " Kommentare mit dem bei facebook registrierten Benutzer verkn&uuml;pfen. "+
               " Diese &raquo;Verbindung&laquo; kann man sich &auml;hnlich einer " +   
               " Freundschaft zweier Personen auf Facebook vorstellen. " +
               " Die Kommunikation passiert &uuml;ber eine Schnittstelle von facebook.com.</li></ul>" +
               "<h4>Bekannte Probleme</h4><ul>" +
               "<li>Beim Laden der Website kommt es vor, dass die Facebookeinstellungen" +
               " nicht sofort ausgelesen werden. Hier hilft es, wenn man die Seite nochmal neu l&auml;dt.</li>" +
               "</ul>"; 
    $('#spleenScreen .bottomInfo').html(text);
    $('#spleenScreen').fadeIn();
  });
  
  $('#spleenLogoClick').click(function(){
    location = '/';
  });
  
  $('.day li:first-child').click(function(){
    location = location.href.replace('list.html','day.html?date='+
                $(this).closest('ul').attr('id'));
  });
  
});
