var basePath = $('base').attr('href');
Cufon.replace('h1, h2, #calendar-time, #calendar-day, #calendar-date, #social strong, .bigbutton, #content-middle .menu li, .btn div, .btn-light div, #sidebar a.link strong, #content-bottom .green, #content-bottom .adres, #overlay-content .adres, #content-bottom .btn div');
toggleMultipleFocus('#gm-adres', '#gm-plaats');
$(document).ready(function(){
  
  /* Click overlay to close */
  $('#overlay').click(function() {
    $('a[href=#sluiten]').click();
  });
  
  /* Update time */
  if($('#calendar-time').length > 0) {
    setInterval(function() {
      var today = new Date();
      var h = today.getHours();
      if(h < 10) {
        h = '0' + h;
      }
      var m = today.getMinutes();
      if(m < 10) {
        m = '0' + m;
      }
      $('#calendar-time').html(h + ':' + m);
      Cufon.replace('#calendar-time');
    }, 10000);
  }
  
  /* Start Slideshow */
  if($('#content #content-image img').length > 1) {
    slideshowIndex = $('#content #content-image img').length - 1;
    setTimeout(startSidebarSlideshow, 5000);
  }
  
  /* Start Medewerkers slideshow */
  if($('#medewerkers .medewerker').length > 1) {
    medewerkerSlideshowIndex = $('#medewerkers .medewerker').length - 1;
    setTimeout(startMedewerkerSidebarSlideshow, 5000);
  }
  
  /* Aanleverspecificaties */
  if($('#content-middle .full').length > 0) {
    $('#content-middle h2.full').click(function(e) {
      $('#content-middle .full.txt').not($(this).next()).slideUp();
      $(this).next().slideToggle();
    });
  }
  
  /* FAQ */
  $('#faq h2').click(function(e) {
    $('#faq p').not($(this).next()).slideUp();
    $(this).next().slideToggle();
  });
  
  /* Vacatures */
  $('.vac-titel').click(function(e) {
    $('.vac-txt').not($(this).next()).slideUp();
    $(this).next().slideToggle();
  });
  
  /* Bestand uploaden */
  $('a[href=#bestanduploaden]').click(function(e) {
    e.preventDefault();
    if($('input[name="debiteurennummer"]').val() != '' && $('input[name="ordernummer"]').val() != '' && $('input[name="file"]').val() != '') {
      $(this).parent().submit();
    } else {
      alert('Vul alle velden in a.u.b.');
    }
  });
  
  /* Routeplanner */
  $('a[href=#routeplanner]').click(function(e) {
    e.preventDefault();
    var adres = $('#gm-adres').val();
    var plaats = $('#gm-plaats').val();
    if(adres != '' && plaats != '' && adres != 'adres' && plaats != 'plaats') {
      getDirections(adres + ', ' + plaats);
    } else {
      alert('Vul beide velden in a.u.b.');
    }
  });
  
  /* Vacatures */
  $('a[href=#verzenden]').click(function(e) {
    e.preventDefault();
    if($('#vacature-adres').val() == '' || $('#vacature-postcode').val() == '' || $('#vacature-plaats').val() == '' || $('#vacature-telefoon').val() == '' || $('#vacature-email').val() == '') {
      alert('Vul alle verplichte velden in a.u.b.');
    } else {
      $.ajax({
        url:'ajax.php',
        data:{vacaturedata:{titel : $('#vacature-titel').val(), aanhef : $('#vacature-aanhef').val(), naam : $('#vacature-naam').val(), adres : $('#vacature-adres').val(),
         postcode : $('#vacature-postcode').val(), plaats : $('#vacature-plaats').val(), telefoon : $('#vacature-telefoon').val(), email : $('#vacature-email').val(), functie : $('#vacature-functie').val(), motivatie : $('#vacature-motivatie').val()}},
        success:function(data) {
          if(data == 'OK') {
            alert('Uw vacature reactie is verstuurd. We nemen zo spoedig mogelijk contact met u op.');
          } else {
            alert('Er ging iets mis bij het verzenden van uw vacature reactie. Probeer het later a.u.b. nogmaals.');
          }
        }
      });
    }
  });
  
  /* Zoom */
  $('a[href=#zoom]').click(function(e) {
    e.preventDefault();
    $('#overlay-content').addClass('zoom');
    showOverlay('<img src="' + $(this).attr('rel') + '" id="zoomer" />');
  });
  
  /* Toggle info */
  $('a[href=#toonkalenderinfo]').click(function(e) {
    e.preventDefault();
    $('a[href=#toonkalenderinfo]').addClass('btn-light').removeClass('btn');
    $('a[href=#toonofferteaanvraag]').addClass('btn').removeClass('btn-light');
    $('#kalenderinfo').show();
    $('#offerteaanvraag').hide();
  });
  $('a[href=#toonofferteaanvraag]').click(function(e) {
    e.preventDefault();
    $('a[href=#toonofferteaanvraag]').addClass('btn-light').removeClass('btn');
    $('a[href=#toonkalenderinfo]').addClass('btn').removeClass('btn-light');
    $('#kalenderinfo').hide();
    $('#offerteaanvraag').show();
  });
  
  /* Zoeken */
  $('a[href=#zoeken]').click(function(e) {
    e.preventDefault();
    $(this).unbind('click');
    $(this).removeAttr('href');
    $('div', this).html('<input type="text" name="zoeken" class="zoekinput" />');
    $('div input', this).focus().keyup(function(e) {
      if(e.keyCode == 13) {
        $.ajax({
          url:'ajax.php',
          data:{zoeken:$(this).val()},
          success:function(data) {
            showOverlay(data);
          }
        });
      }
    });
  });
  
  /* Offerte aanvraag kalender */
  $('a[href=#verzendofferteaanvraag]').click(function(e) {
    e.preventDefault();
    if($('#bedrijfsnaam').val() == '' || $('#naam').val() == '' || $('#telefoon').val() == '' || $('#email').val() == '') {
      alert('Vul alle verplichte velden in a.u.b.');
    } else {
      $(this).parent().submit();
    }
  });
  
  /* Acties */
  $('a[href=#acties]').click(function(e) {
    var rel = $(this).attr('rel');
    if(rel == undefined) rel = 0;
    e.preventDefault();
    $.ajax({
      url:'ajax.php',
      data:{acties:1, selected:rel},
      success:function(data) {
        showOverlay(data);
      }
    });
  });
  if(window.location.hash == '#acties') {
    $('a[href=#acties]').click();
  }
  
  /* Nieuws */
  $('a[href=#nieuws]').click(function(e) {
    var rel = $(this).attr('rel');
    if(rel == undefined) rel = 0;
    e.preventDefault();
    $.ajax({
      url:'ajax.php',
      data:{nieuws:1, selected:rel},
      success:function(data) {
        showOverlay(data);
      }
    });
  });
  
  /* Daag ons uit */
  $('a[href=#daagonsuit]').click(function(e) {
    e.preventDefault();
    $.ajax({
      url:'ajax.php',
      data:{daagonsuit:1},
      success:function(data) {
        $('#overlay-content').addClass('daagonsuit');
        showOverlay(data);
      }
    });
  });
  
  /* Offerte aanvraag */
  $('a[href=#offerteaanvraag]').click(function(e) {
    e.preventDefault();
    $.ajax({
      url:'ajax.php',
      data:{offerteaanvraag:1},
      success:function(data) {
        showOverlay(data);
      }
    });
  });
  
  /* Contactformulier */
  $('a[href=#contactformulier]').click(function(e) {
    e.preventDefault();
    $.ajax({
      url:'ajax.php',
      data:{contactformulier:1},
      success:function(data) {
        showOverlay(data);
      }
    });
  });
  
  /* Tell-a-friend */
  $('a[href=#tellafriend]').click(function(e) {
    e.preventDefault();
    $.ajax({
      url:'ajax.php',
      data:{tellafriend:1},
      success:function(data) {
        showOverlay(data);
      }
    });
  });
  
  /* Twitter */
  if($('#twitterstream').length > 0) {
    setTimeout(checkTweets, 250);
  }
  
  /* Resize background image */
  if($('#bg-img').length > 0) {
    $(window).resize(backgroundResize);
    $('#bg-img').ready(backgroundResize);
    setTimeout(backgroundResize, 500);
  }
});
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);
    showNextTweet();
  } else {
    setTimeout(checkTweets, 250);
  }
}
var twindex = 0;
function showNextTweet() {
  $('#twitterstream ul').animate({top:'-' + ($('#twitterstream ul li:eq(' + twindex + ')').position().top + 15)}, 500);
  twindex++;
  if(twindex >= $('#twitterstream ul li').length) {
    twindex = 0;
  }
  setTimeout(showNextTweet, 5000);
}
var slideshowIndex = 0;
function startSidebarSlideshow() {
  $('#content #content-image img').eq(slideshowIndex).fadeOut(1500, function() {
    slideshowIndex--;
    if(slideshowIndex < 1) {
      setTimeout(resetSidebarSlideshow, 5000);
    } else {
      setTimeout(startSidebarSlideshow, 5000);
    }
  });
}
function resetSidebarSlideshow() {
  slideshowIndex = $('#content #content-image img').length - 1;
  $('#content #content-image img').eq(slideshowIndex).fadeIn(1500, function() {
    $('#content #content-image img').show();
    setTimeout(startSidebarSlideshow, 5000);
  });
}
var slideshowIndex2 = 0;
function startSidebarSlideshow2() {
  $('#overlay-content #content-image img').eq(slideshowIndex2).fadeOut(1500, function() {
    slideshowIndex2--;
    if(slideshowIndex2 < 1) {
      setTimeout(resetSidebarSlideshow2, 5000);
    } else {
      setTimeout(startSidebarSlideshow2, 5000);
    }
  });
}
function resetSidebarSlideshow2() {
  slideshowIndex2 = $('#overlay-content #content-image img').length - 1;
  $('#overlay-content #content-image img').eq(slideshowIndex2).fadeIn(1500, function() {
    $('#overlay-content #content-image img').show();
    setTimeout(startSidebarSlideshow2, 5000);
  });
}
var medewerkerSlideshowIndex = 0;
function startMedewerkerSidebarSlideshow() {
  $('#medewerkers .medewerker').eq(medewerkerSlideshowIndex).fadeOut(1000, function() {
    medewerkerSlideshowIndex--;
    if(medewerkerSlideshowIndex < 1) {
      setTimeout(resetMedewerkerSidebarSlideshow, 5000);
    } else {
      setTimeout(startMedewerkerSidebarSlideshow, 5000);
    }
  });
}
function resetMedewerkerSidebarSlideshow() {
  medewerkerSlideshowIndex = $('#medewerkers .medewerker').length - 1;
  $('#medewerkers .medewerker').eq(medewerkerSlideshowIndex).fadeIn(1000, function() {
    $('#medewerkers .medewerker').show();
    setTimeout(startMedewerkerSidebarSlideshow, 5000);
  });
}
var imageLoaded = 0;
var oImg = new Image();
var zImg = new Image();
function checkImagesLoaded() {
  imageLoaded++;
  if(imageLoaded > 1) {
    $('#zoomerhit').mousemove(function(e) {
      $('#zoomdiv').css({height:($('#zoomdiv').outerWidth() * zImg.height / zImg.width) + 'px'});
      var hRatio = zImg.height / oImg.height;
      var wRatio = zImg.width / oImg.width;
      var divH = Math.round($('#zoomdiv').outerHeight() / 2);
      var divW = Math.round($('#zoomdiv').outerWidth() / 2);
      var bgX = Math.floor(((e.pageX - $('#zoomerhit').offset().left) * wRatio) - divW) * -1;
      var bgY = Math.floor(((e.pageY - $('#zoomerhit').offset().top) * hRatio) - divH) * -1;
      $('#zoomdiv').css({display:'block', backgroundPosition:(bgX + 'px ' + bgY + 'px'), top: (e.pageY - divH) + 'px', left: (e.pageX - divW) + 'px'});
    }).css({left:$('#zoomer').offset().left + 'px', top:$('#zoomer').offset().top + 'px'}).mouseout(function() {
      $('#zoomdiv').hide();
    });
    setTimeout(function() { positionOverlay(true, true); }, 500);
  } 
}
function positionOverlay(show, zoomer) {
  var l = Math.round(($(window).width() - $('#overlay-content').outerWidth()) / 2);
  var t = Math.round(($(window).height() - $('#overlay-content').outerHeight()) / 2);
  $('#overlay-content').stop(true, true).animate({left:l+'px', top:t+'px'}, {duration:200, complete:function(){
    if(show != undefined) { $(this).fadeIn(400); }
    $('#zoomerhit').stop(true, true).animate({left:l+'px', top:t+'px'}, {duration:200, complete:function() {
      if(zoomer != undefined) { $(this).show(); }
    }});
  }});
}
function showOverlay(data) {
  $('#overlay').fadeTo(400, .9);
  $('#zoomerhit, #zoomdiv').hide();
  $('#overlay-content').hide().html(data);
  Cufon.refresh();
  /* Close button */
  $('a[href=#sluiten]').click(function(e) {
    e.preventDefault();
    $('#zoomer, #zoomerdub').remove();
    $('#zoomdiv, #zoomerhit').hide();
    $('#overlay-content').fadeOut(400, function() {
      $(this).html('').removeClass('daagonsuit').removeClass('zoom');
    });
    $('#overlay').fadeOut();
  });
  /* Zoom hover*/
  if($('#zoomer').length > 0) {
    oImg.src = $('#zoomer').attr('src');
    $('#zoomerhit').append($('<img src="' + $('#zoomer').attr('src') + '" id="zoomerdub" />'));
    $('#zoomerdub').css({opacity:0});
    var img = $('#zoomer').attr('src').replace('.jpg', '_zoom.jpg');
    $('#zoomdiv').css({backgroundImage:'url(\'' + img + '\')', backgroundRepeat:'no-repeat'});
    zImg.src = img;
    $(oImg).ready(checkImagesLoaded);
    $(zImg).ready(checkImagesLoaded);
  } else {
    positionOverlay(true, false);
  }
  /* Toggle acties */
  $('#overlay-content .holder .actieitem > h2').click(function(e) {
    $('#overlay-content .holder .actieitem > div').not($(this).parent().find('> div')).slideUp();
    $('#overlay-content .holder .actieitem form').slideUp();
    $(this).parent().find('> div').slideToggle(400, positionOverlay);
  });
  /* Toggle actie offerte form */
  $('a[href=#toonactieofferteaanvraag]').click(function(e) {
    e.preventDefault();
    $(this).parent().parent().find('form').slideToggle(400, positionOverlay);
  });
  /* Actie offerte aanvraag kalender */
  $('a[href=#verzendactieofferteaanvraag]').click(function(e) {
    e.preventDefault();
    if($(this).parent().find('#actie-bedrijfsnaam').val() == '' || $(this).parent().find('#actie-naam').val() == '' || $(this).parent().find('#actie-telefoon').val() == '' || $(this).parent().find('#actie-email').val() == '') {
      alert('Vul alle verplichte velden in a.u.b.');
    } else {
      $(this).parent().submit();
    }
  });
  /*$('#overlay-content .holder .actieitem > .img img').click(function() {
    $('#overlay-content').append($('<img src="' + $(this).attr('src').replace('_thumb.jpg', '.jpg') + '" id="actiezoom" style="position:absolute; left:0; top:0; z-index:4000;" /><a href="#sluitenimg" class="btn close" style="position:absolute; right:0; top:0; z-index:5000;"><div>X</div></a>'));
    $('a[href="#sluitenimg"]').click(function(e) {
      e.preventDefault();
      $('#actiezoom').remove();
      $(this).remove();
    });
  });*/
  /* Toggle nieuws */
  $('#overlay-content .holder .nieuwsitem > h2').click(function(e) {
    $('#overlay-content .holder .nieuwsitem > div').not($(this).parent().find('div')).slideUp();
    $(this).parent().find('div').slideToggle(400, positionOverlay);
  });
  /* Send daag ons uit */
  $('a[href=#verzenddaagonsuit]').click(function(e) {
    e.preventDefault();
    var bn = $('#bedrijfsnaam').val();
    var ah = $('#aanhef').val();
    var nm = $('#naam').val();
    var tl = $('#telefoon').val();
    var em = $('#email').val();
    var wg = $('#wilgraag').val();
    if(bn == '' || nm == '' || tl == '' || em == '' || wg == '') {
      alert('Vul alle verplichte velden in a.u.b.');
    } else {
      $.ajax({
        url:'ajax.php',
        data:{daagonsuitdata:{bedrijfsnaam:bn, aanhef:ah, naam:nm, telefoon:tl, email:em, wilgraag:wg}},
        success:function(data) {
          if(data == 'OK') {
            alert('Uw uitdaging is verstuurd. We nemen zo spoedig mogelijk contact met u op.');
            $('a[href=#sluiten]').click();
          } else {
            alert('Er ging iets mis bij het verzenden van uw uitdaging. Probeer het later a.u.b. nogmaals.');
          }
        }
      });
    }
  });
  /* Send offerte aanvraag */
  $('a[href=#verzendaanvraag]').click(function(e) {
    e.preventDefault();
    var bn = $('#bedrijfsnaam').val();
    var ah = $('#aanhef').val();
    var nm = $('#naam').val();
    var ad = $('#adres').val();
    var pc = $('#postcode').val();
    var pl = $('#plaats').val();
    var tl = $('#telefoon').val();
    var fx = $('#fax').val();
    var em = $('#email').val();
    var bl = $('#bellen').val();
    var wg = $('#wilgraag').val();
    var op = $('#opmerkingen').val();
    if(bn == '' || nm == '' || ad == '' || pc == '' || pl == '' || tl == '' || em == '') {
      alert('Vul alle verplichte velden in a.u.b.');
    } else {
      $.ajax({
        url:'ajax.php',
        data:{offerteaanvraagdata:{bedrijfsnaam:bn, aanhef:ah, naam:nm, adres:ad, postcode:pc, plaats:pl, telefoon:tl, fax:fx, email:em, bellen:bl, wilgraag:wg, opmerkingen:op}},
        success:function(data) {
          if(data == 'OK') {
            alert('Uw offerte aanvraag is verstuurd. We nemen zo spoedig mogelijk contact met u op.');
            $('a[href=#sluiten]').click();
          } else {
            alert('Er ging iets mis bij het verzenden van uw offerte aanvraag. Probeer het later a.u.b. nogmaals.');
          }
        }
      });
    }
  });
  /* Send contactformulier */
  $('a[href=#verzendcontactformulier]').click(function(e) {
    e.preventDefault();
    var bn = $('#bedrijfsnaam').val();
    var ah = $('#aanhef').val();
    var nm = $('#naam').val();
    var ad = $('#adres').val();
    var pc = $('#postcode').val();
    var pl = $('#plaats').val();
    var tl = $('#telefoon').val();
    var fx = $('#fax').val();
    var em = $('#email').val();
    var ho = $('#hoe').val();
    var wg = $('#wilgraag').val();
    var op = $('#opmerkingen').val();
    if(bn == '' || nm == '' || ad == '' || pc == '' || pl == '' || tl == '' || em == '') {
      alert('Vul alle verplichte velden in a.u.b.');
    } else {
      $.ajax({
        url:'ajax.php',
        data:{contactformulierdata:{bedrijfsnaam:bn, aanhef:ah, naam:nm, adres:ad, postcode:pc, plaats:pl, telefoon:tl, fax:fx, email:em, hoe:ho, wilgraag:wg, opmerkingen:op}},
        success:function(data) {
          if(data == 'OK') {
            alert('Uw contact aanvraag is verstuurd. We nemen zo spoedig mogelijk contact met u op.');
            $('a[href=#sluiten]').click();
          } else {
            alert('Er ging iets mis bij het verzenden van uw contact aanvraag. Probeer het later a.u.b. nogmaals.');
          }
        }
      });
    }
  });
  /* Send tell-a-friend */
  $('a[href=#verzendtellafriend]').click(function(e) {
    e.preventDefault();
    var nm1 = $('#naam1').val();
    var em1 = $('#email1').val();
    var nm2 = $('#naam2').val();
    var em2 = $('#email2').val();
    var br = $('#bericht').val();
    if(nm1 == '' || em1 == '' || nm2 == '' || em2 == '' || br == '') {
      alert('Vul alle velden in a.u.b.');
    } else {
      $.ajax({
        url:'ajax.php',
        data:{tellafrienddata:{naam1:nm1, email1:em1, naam2:nm2, email2:em2, bericht:br, link:window.location.href}},
        success:function(data) {
          if(data == 'OK') {
            alert('Uw bericht is verstuurd.');
            $('a[href=#sluiten]').click();
          } else {
            alert('Er ging iets mis bij het verzenden van uw bericht. Probeer het later a.u.b. nogmaals.');
          }
        }
      });
    }
  });
  if($('#overlay-content #content-image img').length > 1) {
    slideshowIndex2 = $('#overlay-content #content-image img').length - 1;
    setTimeout(startSidebarSlideshow2, 5000);
  }
}
var directionDisplay;
var map;
var startLat;
var startMarker;
function doGoogleMaps() {
  directionsDisplay = new google.maps.DirectionsRenderer({draggable:true, suppressMarkers:true});
  var geocoder = new google.maps.Geocoder();
  if(geocoder) {
    geocoder.geocode({'address':'Wethouder Sangersstraat 56, Beek'}, function(results, status) {
      if(status == google.maps.GeocoderStatus.OK) {
        var gLat = startLat = results[0].geometry.location.lat();
        var gLng = results[0].geometry.location.lng();
      }
      var latlng = new google.maps.LatLng(gLat, gLng);
      var myOptions = {zoom:16, center:latlng, 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:'Wethouder Sangersstraat 56, Beek', 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() {
  positionOverlay();
  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($(this).val() == val) {$(this).val('');}
  }).blur(function() {
    if($(this).val() == '') {$(this).val(val);}
  });
}
