var basePath = $('base').attr('href');
var teaserInterval = 0;
$(document).ready(function(){
  Cufon.replace('#menu li a, .date .day, .date .month, .date .year', {fontFamily:'ITC Franklin Gothic Std', hover:true});
  Cufon.replace('h1, h2, #teaser-overlay p, #teaser-overlay a, .tabs');
  toggleMultipleFocus('#search', '#login-email', '#fake-password', '#login-password');
  
  if($('#youtube').length == 0) {
    $('#content h1').eq(0).addClass('dotted');
  }
  
  $('a.comments').click(function(e) {
    e.preventDefault();
    $('#commentholder').slideToggle();
  });
  $('a.pages').click(function(e) {
    e.preventDefault();
    $('a.pages').removeClass('active');
    $(this).addClass('active');
    $('#commentholder .commentpage').hide();
    $('#commentholder .commentpage').eq($(this).attr('href').replace('#', '') - 1).show();
  });
  $('.comment .black-button').click(function(e) {
    e.preventDefault();
    if($('#comment-naam').val() != '' && $('#comment-bericht').val() != '') {
      $(this).parent().submit();
    } else {
      alert('Vul alle velden in a.u.b.');
    }
  });
  
  /* Twitter */
  if($('#twitterstream').length > 0) {
    setTimeout(checkTweets, 250);
  }
  
  /* Wiki category select */
  $('#searchcat').change(function() {
    window.location = 'wiki/cat/' + $(this).val();
  });
  
  /* Wiki edit */
  $('.editwiki .edit').click(function(e) {
    e.preventDefault();
    if($('#wiki-titel').val() != '' && $('#wiki-tekst').val() != '') {
      $(this).parent().submit();
    } else {
      alert('Vul alle velden in a.u.b.');
    }
  });
  
  /* Wiki register */
  $('.editwiki .register').click(function(e) {
    e.preventDefault();
    if($('#wiki-naam').val() != '' && $('#wiki-email').val() != '' && $('#wiki-telefoon').val() != '') {
      $(this).parent().submit();
    } else {
      alert('Vul alle velden in a.u.b.');
    }
  });
  
  /* Wiki search */
  $('form .search').click(function(e) {
    e.preventDefault();
    $(this).parent().submit();
  });
  $('#search').keyup(function(e) {
    if(e.keyCode == 13) {
      $('form .search').click();
    }
  });
  
  /* Change password */
  $('form .changepw').click(function(e) {
    e.preventDefault();
    if(!$('#newpw').is(':visible')) {
      var f = $(this).parent();
      $('label, input', f).fadeIn(200);
      $(this).css({color:'#fff'});
    } else {
      if($('#newpw').val() != '' && $('#oldpw').val() != '') {
        $(this).parent().submit();
      } else {
        alert('Vul het huidige en het nieuwe wachtwoord in a.u.b.');
      }
    }
  });
  
  /* Change Wiki password */
  $('form .changewikipw').click(function(e) {
    e.preventDefault();
    if(!$('#newwikipw').is(':visible')) {
      var f = $(this).parent();
      $('label, input', f).fadeIn(200);
      $(this).css({color:'#fff'});
    } else {
      if($('#newwikipw').val() != '' && $('#oldwikipw').val() != '') {
        $(this).parent().submit();
      } else {
        alert('Vul het huidige en het nieuwe wachtwoord in a.u.b.');
      }
    }
  });
  
  /* Home stappen buttons */
  $('.stap2').click(function(e) {
    e.preventDefault();
    $('#stap1').stop(true, true).animate({width:0}, 400);
    $('#stap2').stop(true, true).animate({width:'287px'}, 400);
  });  
  $('.stap1').click(function(e) {
    e.preventDefault();
    $('#stap2').stop(true, true).animate({width:0}, 400);
    $('#stap1').stop(true, true).animate({width:'287px'}, 400);
  });
  $('#stap2 .send, #plaats-plan-right .send').click(function(e) {
    e.preventDefault();
    var vo = $('#stap-voornaam').val();
    var ac = $('#stap-achternaam').val();
    var em = $('#stap-email').val();
    var te = $('#stap-telefoon').val();
    var ti = $('#stap-titel').val();
    var om = $('#stap-omschrijving').val();
    var ma = $('#stap-maastricht').attr('checked');
    if(!ma) {
      alert('Je kunt alleen een plan of idee indienen als je in Maastricht woont, werkt of naar school gaat.');
    } else if(vo != '' && ac != '' && em != '' && te != '' && ti != '' && om != '') {
      $.ajax({
        url:'ajax.php',
        data:{what:'planindienen', vars:{voornaam:vo, achternaam:ac, email:em, telefoon:te, titel:ti, omschrijving:om}},
        success:function(data) {
          var bits = data.split('-+||+-');
          if(bits[0] == 'OK') {
            $('#stap-voornaam').val('');
            $('#stap-achternaam').val('');
            $('#stap-email').val('');
            $('#stap-telefoon').val('');
            $('#stap-titel').val('');
            $('#stap-omschrijving').val('');
            $('#stap-maastricht').attr('checked', false);
            if($('.stap1').length > 0) { $('.stap1').click(); }
          }
          alert(bits[1]);
        }
      });
    } else {
      alert('Vul alle velden in a.u.b.');
    }
  });
  
  /* Nieuwsbrief aanmelden */
 $('#content .stappen-bg .nieuwsbrief').click(function(e) {
   e.preventDefault();
   var em = $('#nieuwsbrief-email').val();
   if(em != '') {
     $.ajax({
        url:'ajax.php',
        data:{what:'nieuwsbrief', vars:{email:em}},
        success:function(data) {
          var bits = data.split('-+||+-');
          if(bits[0] == 'OK') {
            $('#nieuwsbrief-email').val('');
          }
          alert(bits[1]);
        }
      });
    } else {
      alert('Vul jouw e-mailadres in a.u.b.');
    }
 });
  
  /* Plan edit */
  $('form .edit1, form .edit3').click(function(e) {
    e.preventDefault();
    $(this).parent().submit();
  });
  $('form .edit2').click(function(e) {
    e.preventDefault();
    var start = $('#edit-start2').val()+''+$('#edit-start1').val()+''+$('#edit-start0').val();
    var end = $('#edit-end2').val()+''+$('#edit-end1').val()+''+$('#edit-end0').val();
    if(start <= end) {
      $(this).parent().submit();
    } else {
      alert('De einddatum kan niet voor de begindatum liggen!');
    }
  });
  $('#edit-file-begroting').change(function() {
    checkFileAllowed('#edit-file-begroting', ['xls', 'xlsx', 'doc', 'docx', 'pdf']);
  });
  $('#edit-file-tijdsplanning').change(function() {
    checkFileAllowed('#edit-file-tijdsplanning', ['doc', 'docx', 'pdf']);
  });
  $('#edit-file-draaiboek').change(function() {
    checkFileAllowed('#edit-file-draaiboek', ['doc', 'docx', 'pdf']);
  });
  $('#edit-file-evaluatie').change(function() {
    checkFileAllowed('#edit-file-evaluatie', ['doc', 'docx', 'pdf']);
  });
  for(var i = 1; i <= 5; i++) {
    $('#edit-file-overige' + i).change(function() {
      checkFileAllowed('#edit-file-overige' + i, ['doc', 'docx', 'pdf']);
    });
  }
  for(var i = 1; i <= 7; i++) {
    $('#edit-file-img' + i).change(function() {
      checkFileAllowed('#edit-file-img' + i, ['jpg', 'png']);
    });
  }
  $('form .voorschot').click(function(e) {
    e.preventDefault();
    var bedrag = $('#voorschotbedrag').val();
    if(bedrag.indexOf(',') != -1) {
      var bedrag = bedrag.replace(',', '.');
    }
    if(Number(bedrag) <= 0) {
      alert('Vul een bedrag in a.u.b.')
      $('#voorschotbedrag').focus();
    } else if(Number(bedrag) <=  Number($('#maxvoorschotbedrag').val())) {
      $(this).parent().submit();
    } else {
      alert('Je kunt niet meer dan 50% als voorschot ontvangen.');
    }
  });
  $('.hidden .short').blur(function() {
     $(this).filter(function() {
        if(this.value.match(/[^\d,]/)) {
          $(this).val(Number($(this).val().replace(/[^0-9\.]+/g, ''))).focus();
          alert('Je mag hier alleen cijfers invullen!');
        }
    });
  });
  $('#plaats-plan-right li input[type="checkbox"]').click(function() {
    $(this).next('div').slideToggle();
  });

  /* Home login */
  $('form .login').click(function(e) {
    e.preventDefault();
    if($('#login-email').val() != '' && $('#login-password').val() != '') {
      $(this).parent().submit();
    } else {
      alert('Vul alle velden in a.u.b.');
    }
  });
  $('#login-password').keyup(function(e) {
    if(e.keyCode == 13) {
      $('form .login').click();
    }
  });
  
  /* Header teasers */
  $('#teaser-numbers a').click(function(e) {
    e.preventDefault();
    $('#teaser-numbers a').removeClass('active');
    $(this).addClass('active');
    var i = ($(this).attr('href').split('#')[1]) - 1;
    $('#teaser-holder').stop(true, true).animate({left:'-' + (i * 715) + 'px'}, 600);
    $('#teaser-text').fadeOut(200, function() {
      $(this).html(unescape($('#teaser-holder img').eq(i).attr('rel')));
      Cufon.refresh();
      $(this).fadeIn(200);
    });
  });
  $('#teaser-overlay').fadeIn(200);
  $('#teaser').hover(function() {
    clearInterval(teaserInterval);
  }, function() {
    teaserInterval = setInterval(nextTeaser, 5000);
  });
  teaserInterval = setInterval(nextTeaser, 5000);
  
  /* Sidebar H1 */
  $('#sidebar h1.arrow:not(.plaats-oproep)').click(function() {
    $(this).next('.hidden').slideToggle(250);
  });
  $('#sidebar h1.plaats-oproep').click(function() {
    var href = window.location.href;
    if(href.indexOf('?') != -1) {
      href = href.split('?')[0];
    }
    window.location.href = href + '?plaatsen';
  });
  
  /* Plaats oproep */
  $('.oproep-plaatsen .send').click(function(e) {
    e.preventDefault();
    var na = $('#oproep-naam').val();
    var em = $('#oproep-email').val();
    var ti = $('#oproep-titel').val();
    var te = $('#oproep-tekst').val();
    if(na != '' && em != '' && ti != '' && te != '') {
      $.ajax({
        url:'ajax.php',
        data:{what:'oproepplaatsen', vars:{naam:na, email:em, titel:ti, tekst:te}},
        success:function(data) {
          var bits = data.split('-+||+-');
          alert(bits[1]);
        }
      });
    } else {
      alert('Vul alle velden in a.u.b.');
    }
  });
  
  /* Agenda / Nieuws foto/video buttons */
  $('#content .right .zoom').click(function() {
    showBigPicture($('#previewimg').attr('src').replace('_preview', ''));
  });
  $('#content .right .thumbs img').not('.video').click(function() {
    $('#previewimg').attr('src', $(this).attr('src').replace('_thumb', '_preview'));
  });
  $('#content .right .thumbs img.video, #content .middle a.video').click(function(e) {
    e.preventDefault();
    showVideo($(this).attr('rel'));
  });
  
  /* Contact route button */
  $('.berekenroute').click(function() {
    var adres = '';
    if($('#GMadres').val() != '') {
      adres += $('#GMadres').val();
    }
    if($('#GMplaats').val() != '') {
      if(adres != '') { adres += ', '; } 
      adres += $('#GMplaats').val();
    }
    if(adres != '') {
      getDirections(adres);
    } else {
      alert('Vul uw adres in a.u.b.');
    }
  });
  $('#GMplaats').keyup(function(e) {
    if(e.keyCode == 13) {
      $('.berekenroute').click();
    }
  });
  
  /* Menu active fixes */
  $('#menu > li > ul > li.active').each(function() {
    $(this).parent().parent().addClass('active');
  });
  $('#menu > li > ul').each(function() {
    $(this).parent().hover(function() {
      $(this).addClass('active2');
      $('ul', this).show();
    }, function() {
      $(this).removeClass('active2');
      $('ul', this).hide();
      Cufon.refresh();
    });
  });
  
  /* Projecten spotlight */
  $('#spotlight-arrow-left').click(function() {
    if(Number($('#projecten-spotlight-holder').css('left').replace('px', '')) < -262) {
      $('#projecten-spotlight-holder').stop(true, true).animate({left:'+=263px'}, 400);
    }
  });
  var w = $('#projecten-spotlight-holder .project').length * 263;
  $('#spotlight-arrow-right').click(function() {
    if(Number($('#projecten-spotlight-holder').css('left').replace('px', '')) > 880 - w) {
      $('#projecten-spotlight-holder').stop(true, true).animate({left:'-=263px'}, 400);
    }
  });
  
  
  /* Sidebar H1 */
  $('#plaats-plan-right .sub').click(function() {
    if($(this).hasClass('active')) {
      $(this).removeClass('active');
      $(this).next('.hidden').slideUp(250);
    } else {
      $(this).addClass('active');
      $(this).next('.hidden').slideDown(250);
    }
  });
  
  /* Resize background image */
  if($('#bg-img').length > 0) {
    $(window).resize(backgroundResize);
    $('#bg-img').ready(backgroundResize);
    setTimeout(backgroundResize, 500);
  }
});

function checkFileAllowed(id, allowed) {
  var ok = true;
  var val = $(id).val();
  if(val != '') {
    var bits = val.split('.');
    var ext = bits[bits.length - 1].toLowerCase();
    if($.inArray(ext, allowed) == -1) {
      alert('Je mag alleen bestanden uploaden met de volgende extensies: .' + allowed.join('/ .'));
      $(id).val('');
      ok = false;
    }
  }
  return ok;
}
var teaserIndex = 0;
function nextTeaser() {
  teaserIndex++;
  if(teaserIndex >= $('#teaser-holder img').length) {
    teaserIndex = 0;
  }
  $('#teaser-numbers a').removeClass('active');
  $('#teaser-numbers a').eq(teaserIndex).addClass('active');
  $('#teaser-holder').stop(true, true).animate({left:'-' + (teaserIndex * 715) + 'px'}, 600);
  $('#teaser-text').fadeOut(200, function() {
    $(this).html(unescape($('#teaser-holder img').eq(teaserIndex).attr('rel')));
    Cufon.refresh();
    $(this).fadeIn(200);
  });
}

var maxHeight = 0;
function checkTweets() {
  if($('#twitterstream ul li').length > 0) {
    $('#twitterstream ul li').each(function() {
      maxHeight = ($(this).outerHeight() > maxHeight) ? $(this).outerHeight() : maxHeight;    
    });
    $('#twitterstream ul li').each(function() {
      if($(this).outerHeight() < maxHeight) {
        $(this).css({height:maxHeight});
      }
    });
    //$('#twitterstream').animate({height:maxHeight}, 500);
    $('#twitterstream').animate({height:'100px'}, 500);
    showNextTweet();
  } else {
    setTimeout(checkTweets, 250);
  }
}
var twindex = 0;
function showNextTweet() {
  $('#twitterstream ul').animate({top:'-' + ($('#twitterstream ul li:eq(' + twindex + ')').position().top + 5)}, 500);
  twindex++;
  if(twindex >= $('#twitterstream ul li').length) {
    twindex = 0;
  }
  setTimeout(showNextTweet, 5000);
}
function showVideo(src) {
  var b = $('<div id="blocker" title="Klik om te sluiten"></div>').css({height:$(window).height(), width:$(window).width()}).click(function() {
    $(this).fadeOut(400, function() {
      $(this).remove();
    });
  });
  b.append('<div>' + unescape(src) + '</div>');
  $('body').append(b);
  var emb = $('#blocker > div').find('*[width]');
  $('#blocker > div').css({left:(($(window).width() - emb.attr('width')) / 2), top:(($(window).height() - emb.attr('height')) / 2)});
  $('#blocker').fadeIn();
}
function showBigPicture(src) {
  var b = $('<div id="blocker" title="Klik om te sluiten"></div>').css({height:$(window).height(), width:$(window).width()}).click(function() {
    $(this).fadeOut(400, function() {
      $(this).remove();
    });
  });
  var i = $('<img src="' + src + '" title="Klik om te sluiten" alt="Klik om te sluiten" />;');
  $(i).load(function() {
    $('#blocker img').css({left:(($(window).width() - $('#blocker img')[0].width) / 2), top:(($(window).height() - $('#blocker img')[0].height) / 2)});
    $('#blocker').fadeIn();
  });
  $(b).append(i);
  $('body').append(b);
}

var directionDisplay;
var map;
var startLat;
var startMarker;
function doGoogleMaps() {
  directionsDisplay = new google.maps.DirectionsRenderer({draggable:true, suppressMarkers:true});
  var latlng = new google.maps.LatLng(50.8507852 , 5.681255100000044);
  var myOptions = {zoom:16, center:latlng, mapTypeControl:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
  map = new google.maps.Map(document.getElementById("googlemaps"), myOptions);
  startMarker = new google.maps.Marker({position:latlng, map:map});
  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById("directions"));
}

function getDirections(address) {
  var directionsService = new google.maps.DirectionsService();
  directionsService.route({origin:address, destination:'Herbenusstraat 89, Maastricht', provideRouteAlternatives:false, travelMode:google.maps.DirectionsTravelMode.DRIVING, unitSystem:google.maps.DirectionsUnitSystem.METRIC}, function(result, status) {
    if(status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
      var geocoder = new google.maps.Geocoder();
      if(geocoder) {
        geocoder.geocode({'address':address}, function(results, status) {
          if(status == google.maps.GeocoderStatus.OK) {
            var gLat = results[0].geometry.location.lat();
            var gLng = results[0].geometry.location.lng();
          }
          var latlng2 = new google.maps.LatLng(gLat, gLng);
          new google.maps.Marker({position:latlng2, map:map});
        });
      }
    } else {
      alert('Het adres "' + address + '" kan niet worden gevonden. Controleer het door u opgegeven adres op mogelijke typfouten.');
    }
  });
}
function backgroundResize() {
  if($('#blocker').length > 0) {
    $('#blocker').css({height:$(window).height(), width:$(window).width()});
    if($('#blocker img').length > 0) {
      $('#blocker img').css({left:(($(window).width() - $('#blocker img')[0].width) / 2), top:(($(window).height() - $('#blocker img')[0].height) / 2)});
    }
    if($('#blocker > div').length > 0) {
      $('#blocker > div').css({left:(($(window).width() - $('#blocker > div').outerWidth()) / 2), top:(($(window).height() - $('#blocker > div').outerHeight()) / 2)});
    }
  }
  if($('#bg-img').length > 0) {
    var oImg = new Image();
    oImg.src = $('#bg-img').attr('src');
    $('#bg-img').ready(function (e) {
      var orgW = oImg.width;
      var orgH = oImg.height;
      if(orgW != 0 && orgH != 0) {
        var h = $(window).height();
        var w = $(window).width();
        var ratioW = w / orgW;
        var ratioH = h / orgH;
        if(ratioW > ratioH) {
          $('#bg-img').css({'height':(w * orgH / orgW), 'width':w});
        } else {
          $('#bg-img').css({'height':h, 'width':(h * orgW / orgH)});
        }
        $('#bg-holder').css({'display':'block'});
      }
    });
    setTimeout(function() {
      $('#bg-holder').css({'display':'block'});
    }, 3000);
  }
}
function preloadImages() {
  for(var i = 0; i < arguments.length; i++) {
    var oImg = new Image();
    oImg.src = arguments[i];
  }
}
function toggleMultipleFocus() {
  for(var i = 0; i < arguments.length; i++) {
    toggleFocus(arguments[i]);
  }
}
function toggleFocus(id) {
  var val = $(id).val();
  $(id).focus(function() {
    if(id == '#fake-password') {
      $(id).hide();
      $('#login-password').show().focus();
    } else {
      if($(this).val() == val) {$(this).val('');}
    }
  }).blur(function() {
    if(id == '#login-password') {
      $(id).hide();
      $('#fake-password').show();
    } else {
      if($(this).val() == '') {$(this).val(val);}
    }
  });
}
