var currentIndex = -1;
var maxIndex = 0;
var interval;
var speed = 3000;

contentMenuImages = [];

function fixlink(link) {
  if ($.browser.msie) { 
    var base = $("base").attr('href');
    if (!base.match(/\/$/)) base += "/";
    return base+link;
  }
  return link;
}

function redrawMap() {

  var map = $("#map");
  var mapPosition = map.position();
  
  $.each(locaties, function(key, data) {
    var div = $("div[data-locatie-key='"+key+"']");
    div.css({'left': mapPosition.left+data.left-7, 'top': mapPosition.top+data.top-7});
  });
}

function drawMap() {

  var map = $("#map");
  var mapPosition = map.position();
  
  var coords;
  
  map.mousemove(function(e) {
    if (e.shiftKey && e.ctrlKey) {
      if (!coords) {
        coords = $("<div />");
        map.after(coords);
      }
      pos = map.position();
      l = e.pageX - pos.left;
      t = e.pageY - pos.top;
      coords.text("X: "+l+" - Y: "+t);
    }
  });
  
  if (typeof(locaties) != "undefined") {
    $(window).resize(function() { redrawMap() });
    
    /*$("#locaties div").hover(function() {
      $(this).trigger('click', ['mouseover']);    
    }, function() {
      $(this).trigger('click', ['mouseout']);    
    });*/
        
    $.each(locaties, function(key, data) {
      var div = $("<div />").addClass('locatie').attr('data-locatie-key', key);
      div.css({'position': 'absolute', 'left': mapPosition.left+data.left-7, 'top': mapPosition.top+data.top-7});

      div.hover(function(e) {
        $("#locatie"+data.id).trigger('click', ['mouseover']);
      }, function(e) {
        $("#locatie"+data.id).trigger('click', ['mouseout']);
      });
      
      div.click(function(e) {
        $("#locatie"+data.id).trigger('click', ['click']);
      })
    
      map.append(div);    
    });
  
    $("#locaties div").click(function(e, data) {
      e.preventDefault();
    
      var active = false;
      var persist = false;
      var removeOthers = false;
    
      // actual click
      if (typeof(data) == 'undefined') {
        if ($(this).hasClass('active')) {
          window.location.href = fixlink($(this).find('a').attr('href'));
          return;
        }
        else {
          active = true;
          persist = true;  
          removeOthers = true;
        }
      }
    
      else if (!$(this).data('persist')) {
        // simulated click by hovering over map
        if (data == 'mouseover') {
          active = true;
        }
        else if (data == 'mouseout') {
          active = false;
        }
        else if (data == 'click') {
          active = false;
          persist = false;
          removeOthers = true;
          window.location.href = fixlink($(this).find('a').attr('href'));
        }
      }
      else {
        return;
      }
    
    
      if (removeOthers) {
        $("#locaties div").removeClass('active').data('persist', false);
      }
      if (active) {
        $(this).addClass('active').data('persist', persist);
      }
      else {
        $(this).removeClass('active').data('persist', persist);
      }
    });
  }
}

$(document).ready(function() {
  drawMap();
  
  $(".werkgebied input[name='overig-chk']").change(function() {
    if ($(this).attr('checked')) {
      $("#werkgebied_overig").show().focus();
    }
    else {
      $("#werkgebied_overig").hide().focus();
    }    
  }).change().closest('form').submit(function(e) {
    var form = $(this);
    if ($("input[name='overig-chk']", form).attr('checked') && !$("#werkgebied_overig").val().length) {
      alert('U heeft "overig" aangevinkt, maar geen tekst ingevuld.');
      e.preventDefault();
      return;
    }
    count = 0;
    $('input[type="checkbox"]', form).each(function() {
      if ($(this).attr('checked') && $(this).attr('name') != 'overig-chk') {
        count++;
      }
    });
    if ($('input[name="overig-chk"]').attr("checked") && $('#werkgebied_overig').val().length) {
      count++;
    }
    if (!count) {
      alert('Geef aan wat uw werkgebied is.');
      e.preventDefault();
    }
  });
  
  var popupElements = [{
    'trigger': '.nieuwscontainer a',
    'parent': '.nieuwscontainer'
  }, {
    'trigger': '.vacatures .meer',
    'parent': '.vacatures tbody',
    'className': 'vacatures'
  }, {
    'trigger': '.educa .meer, .educa img',
    'parent': '.educa tbody',
    'className': 'educa'
  }];
  
  $.each(popupElements, function(key, data) {
    $(data.trigger).click(function(e) {
      e.preventDefault(); 
      if ($(".overlay").length) return;
      
      // create overlay
      var position = $("#pagecontent").offset();
      var overlay = $("<div />").addClass('overlay').css({'background-color': 'white', 'position':'absolute', 'left': position.left, 'top': position.top}).fadeTo(0, 0);
      overlay.height($("#pagecontent").height());
      overlay.width($("#pagecontent").width());
  
      // create nieuwsItem
      var container = $("<div />").addClass('popup').fadeTo(0, 0);
      
      var item = $(this).closest(".item").clone();
      container.css('minHeight', $(this).closest(".item").height());
      
      if (item[0].tagName == 'TR') {
        item = $("<div />").append( $("<table />").attr('cellspacing', 0).attr('cellpadding', 0).addClass(data.className).append(item) );
        container.css('padding', 0);
      }
      
      container.append(item);
      
      var position = $(this).closest(".item").position();
      position.left -= $(this).closest(".item").offset().left - $(this).closest(data.parent).offset().left;
      position.top -= $(this).closest(".item").siblings(".item").andSelf().eq(0).offset().top - $(this).closest(data.parent).offset().top;
      
      container.css({'position': 'absolute', 'top': position.top, 'left': position.left});
      container.width($(this).closest(data.parent).width());

      // append
      $("body").append(overlay);
      $("body").append(container);

      var oldCss = {'left': container.position().left, 'width': container.width(), 'paddingLeft': container.css('paddingLeft')};
      // add close handler
      container.find('a').click(function(e) {
        e.stopPropagation();        
      });
      container.click(function(e) {
        e.preventDefault();
        overlay.stop(true, false);
        container.find(':animated').stop(true, false);
        // quickly hide the image to prevent disturbing the rest of the animation
        container.find('.image').fadeOut('fast');
        container.find('.fotoGroot').fadeOut(500);
        container.find('.programma').hide();
        
        // animate back to the values we had before we started animating
        container.find('.content').slideUp('slow', function() {
        
          container.find('.fotoKlein').fadeIn(500);
          container.animate(oldCss);
          $('html, body').animate({'scrollTop': oldScrollTop}, 'slow');
          
          $(this).hide();
          container.find('.caption').show();
          
          // clean up
          container.fadeTo(1000, 0, function() { $(this).remove(); });
          overlay.fadeTo(1000, 0, function() { $(this).remove(); });
        });
      });
      
      var oldScrollTop = $(window).scrollTop();
      $('html, body').animate({'scrollTop': position.top - 50}, 'slow');
      
      // animate
      overlay.fadeTo(1000, .7);

      // fix width so it won't animate together with the container when it gets bigger (also, clear some more space for the image)
      container.find('.content').width(container.find('.caption').width() - 50);
      
      container.find('.fotoKlein').fadeTo(500, 0.01);
            
      // animate to make the box span the whole page
      var newLeft = $("#container").position().left + parseInt($("#container").css('borderLeftWidth'));
      var newPadding = parseInt(container.css('paddingLeft')) + container.position().left - newLeft;
      container.animate({
        'left': newLeft,
        'opacity': 1,
        'paddingLeft': newPadding,
        'width': $("#container").innerWidth() - (container.innerWidth() - container.width()) - (newPadding - parseInt(oldCss['paddingLeft']))
      }, 1000, function() {
        // when animation finishes, hide the caption and show content and image
        container.find('.caption').hide();
        container.find('.programma').slideDown();
        container.find('.fotoGroot').fadeIn(500);
        container.find('.content').slideDown(function() {
          $(this).prev('.image').fadeIn('slow');
        });
      });
    });
  });
  
  $(window).resize(function() {
    var left = $("#container").position().left + 2;
    $(".popup").css({'left': left});
    $(".overlay").css({'left': left});
  });
  
  // add hover effect to contact image
  $("#contact").hover(
    function() {
      $(this).find('img').attr('src', 'fileadmin/excent_template/images/contact-hover.png');
    },
    function() {
      $(this).find('img').attr('src', 'fileadmin/excent_template/images/contact.png');
    }
  )  
  
  $(".content-menu li > span").hover(
    function(e, auto) {
      if ($(this).closest('td').hasClass('right')) {
        if (!auto) {
          clearInterval(interval);
        }
        $(".content-menu .right li").removeClass('hover');
        var index = $(this).closest('li').prevAll().length;
        $(this).closest('table').css('background-image', 'url('+ contentMenuImgPath+'/'+contentMenuImages[index]+')');
      }
      else {
        $(".content-menu .left li").removeClass('hover');
      }
      $(this).closest('li').addClass('hover');
    },
    function(e, auto) {
      $(this).closest('li').removeClass('hover');
      if ($(this).closest('td').hasClass('right') && !auto) {
        highlightNext();
        interval = setInterval('highlightNext()', speed);      
      }
    }
  );
  
  maxIndex = $(".content-menu .right li > span").length;
  
  highlightNext();
  interval = setInterval('highlightNext()', speed);
  
  
  var matches = window.location.href.match(/tx_ttnews(?:\[|%5B)tt_news(?:\]|%5D)=(\d+)/);
  if (matches) {
    $("a[href*='tx_ttnews[tt_news]="+matches[1]+"']").click();
    $("a[href*='tx_ttnews%5Btt_news%5D="+matches[1]+"']").click();
  }
  
  
  
  $(".productbuttons #voornafotografie, .productbuttons #instructievideo").each(function() {
    if ($(this).children().length > 0) {
      var text = '';
      switch($(this).attr('id')) {
        case 'voornafotografie':
          text = 'Voor-/nafotografie';
          break;
        case 'instructievideo':
          text = 'Instructievideo';
          break;
      }
      var className = $(this).attr('id');
      var title = text + ' ' + $("#content h2:first").text();
      var button = $('<a />').addClass(className).attr('href', '#').text(text);

      var content = $(this);
      
      button.click(function(e) {
        e.preventDefault();
        var overlay = $("<div />").css('width', $(document).width()).css('height', $(document).height());
        overlay.fadeTo(0, 0);
        $('body').append(overlay);
        overlay.css({'position': 'absolute', left: 0, top: 0, 'background-color': 'black'});
        overlay.fadeTo(500, .7);
        
        var popup = $("<div />").addClass('popup2').addClass(className);
        var header = $("<div />").addClass('header').text(title);
        popup.append(header);
        popup.append($("<div />").addClass('content').append(content.get(0).innerHTML));
        popup.css({ position: 'absolute' });
        $('body').append(popup);
        popup.css({ position: 'absolute', top: $(window).scrollTop() + (($(window).height() - popup.height()) / 2), left: ($(window).width() - popup.width()) / 2 });

        var click = function(e) {
          popup.remove();
          overlay.fadeTo(500, 0, function() {
            overlay.remove();
          })
        };
        overlay.click(click);
        popup.click(click);
      });
      
      var div = $("<div />").addClass('right');
      div.append(button);
      var lastRight = $('.productbuttons .right:last');
      if (lastRight.length) { $('.productbuttons .right:last').after(div); }
      else { $('.productbuttons').prepend(div); }
    }
  });
  
  $("#cursussen select").live('change', function() {
    var cursus = $(this);
    var row = cursus.closest('tr');
    var table = row.closest('table');
    var personen = row.find('input');
    
    if (!cursus.val()) {
      if (!table.find('tbody tr:last').equals(row)) {
        row.remove();
      }
    }
    else {
      if (table.find('tbody tr:last').equals(row)) {
        var newRow = row.clone();
        row.removeClass('error');
        newRow.find('input').val('');
        newRow.find('select option').attr('selected', false);
        table.find('tbody').append(newRow);
      }
    }
  });
  $("#cursussen").closest('form').submit(function(e) {
    var error = '';
    var found = 0;
    var selected = [];
    $("#cursussen tbody tr").removeClass('error');

    $("#cursussen tbody tr").each(function() {
      if ($(this).find('select').val()) {
        found++;
        if (!$(this).find('input').val()) {
          error = error ? error : 'Vul het aantal personen in bij de geselecteerde cursus(sen)';
          $(this).addClass('error');
        }
        else if ($.inArray($(this).find('select').val(), selected) >= 0) {
          $(this).addClass('error');
          error = error ? error : 'U heeft de gemarkeerde cursussen dubbel geselecteerd';          
        }
        else {
          selected.push($(this).find('select').val());
        }
      }
    });
    if (found == 0) {
      error = error ? error : 'Geef aan voor welke cursus(sen) u zich wilt inschrijven';
      $("#cursussen").find('tr').addClass('error');
    }
    if (error) {
      alert(error);
      $('html, body').animate({'scrollTop': 0}, 500);
      e.preventDefault();
    }
  });
});

function highlightNext() {
  currentIndex++;
  if (currentIndex == maxIndex) {
    currentIndex = 0;
  }
  
  $(".content-menu .right li:eq("+currentIndex+") > span").trigger('mouseenter', [true]);  
}

$.fn.equals = function(compareTo) {
    if (!compareTo || !compareTo.length || this.length!=compareTo.length) {
        return false;
    }
    for (var i=0; i<this.length; i++) {
        if (this[i]!==compareTo[i]) {
            return false;
        }
    }
    return true;

} 
