var basePath = $('base').attr('href');
var firstTime = true;
$(document).ready(function(){
  Cufon.replace('#menu ul li a', { hover: true })('.title')('h1');
  toggleMultipleFocus('#searchfield');
  $('.scrollmask, .medewerker-info').jScrollPane({animateScroll: true});
  
  /* Search */
  $('#searchfield').keypress(function(e){
    if(e.which == 13){
      $('#search img').click();
      $('#filtersearch img').click();
    }
  });
  $('#search img').click(function() {
    var v = $('#searchfield').val();
    if(v != 'zoekterm') {
      window.location.href = 'zoeken?search=' + escape(v);
    }
  });
  
  /* Architectuur */
  if($('#architectuur .items').length > 0) {
    $('#filtersearch img').click(function(e) {
      e.preventDefault();
      filterSearch = escape($(this).prev().val());
      if(filterSearch == 'zoekterm') {
        filterSearch = '';
      }
      loadItems();
    });
    setTimeout(loadItems, 500);
    $('#architectuur-menu ul li a').click(function(e) {
      e.preventDefault();
      if($(this).hasClass('alles')) {
        $('#architectuur-menu ul li a').not(this).parent().removeClass('active');
        $('#architectuur-menu ul li a.alles').parent().addClass('active');
        $('#architectuur-menu > ul > li > ul').hide();
        filterArray = [];
        firstTime = true;
      } else {
        $('#architectuur-menu ul li a.alles').parent().removeClass('active');
        var f = $(this).attr('href').replace('#', '');
        if(f == 'wonen') {
          if(firstTime) {
            filterArray.push('wonenprojectmatig');
            filterArray.push('wonenparticulier');
            filterArray.push('wonenverbouwing');
            $('#architectuur-menu ul li a.alles').parent().removeClass('active');
            $('#architectuur-menu ul li a.wonen').parent().addClass('active');
            $('#architectuur-menu > ul > li > ul > li').addClass('active');
            $('#architectuur-menu > ul > li > ul').show();
            firstTime = false;
          } else {
            $('#architectuur-menu ul li a.wonen').parent().removeClass('active');
            $('#architectuur-menu > ul > li > ul > li').removeClass('active');
            $('#architectuur-menu > ul > li > ul').hide();
            var idx = $.inArray('wonenprojectmatig', filterArray);
            if(idx != -1) {
              filterArray.splice(idx, 1);
            }
            idx = $.inArray('wonenparticulier', filterArray);
            if(idx != -1) {
              filterArray.splice(idx, 1);
            }
            idx = $.inArray('wonenverbouwing', filterArray);
            if(idx != -1) {
              filterArray.splice(idx, 1);
            }
            firstTime = true;
          }
        } else {
          var found = false;
          for(var i = 0; i < filterArray.length; i++) {
            if(filterArray[i] === f) {
              found = true;
              break;
            }
          }
          if(found) {
            var idx = $.inArray(f, filterArray);
            if(idx != -1) {
              filterArray.splice(idx, 1);
            }
            $(this).parent().removeClass('active');
          } else {
            filterArray.push(f);
            $(this).parent().addClass('active');
          }
        }
      }
      if(f != 'wonen') {
        if($.inArray('wonenprojectmatig', filterArray) != -1 || $.inArray('wonenparticulier', filterArray) != -1 || $.inArray('wonenverbouwing', filterArray) != -1) {
          $('#architectuur-menu ul li a.wonen').parent().addClass('active');
        } else {
          $('#architectuur-menu ul li a.wonen').parent().removeClass('active');
          $('#architectuur-menu > ul > li > ul').hide();
          firstTime = true;
        }
      }
      if(filterArray.length == 0) {
        $('#architectuur-menu ul li').removeClass('active');
        $('#architectuur-menu ul li a.alles').parent().addClass('active');
        $('#architectuur-menu > ul > li > ul > li').addClass('active');
        $('#architectuur-menu > ul > li > ul').hide();
      }
      $('.items').stop(true, true).animate({left:'0px'}, {duration:800, ease:'easeOutExpo', complete:checkArrows});
      loadItems();
    });
  }
  
  /* Home */
  if($('#portfolio-holder img').length > 1) {
    slideshowIndex = $('#portfolio-holder img').length - 1;
    $('#portfolio-next').click(nextPortfolio);
  } else {
    $('#portfolio-next').hide();
  }
  
  /* Medewerkers */
  if($('#medewerkers-holder').length > 0) {
    $('#medewerkers-holder .medewerker').hover(function() {
      $('.overlay', this).show();
      $('img', this).attr('src', $('img', this).attr('src').replace('greyscale.php?', ''));
    }, function() {
      $('.overlay', this).hide();
      if($('img', this).attr('src').indexOf('greyscale.php?') == -1) {
        $('img', this).attr('src', 'greyscale.php?' + $('img', this).attr('src'));
      }
    });
    $('#medewerkers-holder .medewerker').click(function() {
      var src = $('img', this).attr('src');
      var rel = $('img', this).attr('rel');
      if(src) {
        src = src.replace('_thumb4', '').replace('_thumb2', '').replace('_thumb', '').replace('greyscale.php?', '');
        var html = '<div id="portfolio-next"><img src="images/portfolio-next.png" /></div><img src="' + src + '" />';
        var c = 0;
        if(rel) {
          var bits = rel.split(';');
          for(var i in bits) {
            if(bits[i] != '') {
              c++;
              html += '<img src="' + src.replace('nieuws1_', 'nieuws' + bits[i] + '_') + '" style="display:none;" />';
            }
          }
        }
        $('#bigpicture').html(html);
        if(c > 0) {
          $('#portfolio-next img').click(clickNextActueelFoto);
          actueelTimeout = setInterval(nextActueelFoto, 7000);
        } else {
          $('#portfolio-next').hide();
        }
      }
      $('.medewerker-info').not('#medewerker-' + ($('#medewerkers-holder .medewerker').index($(this)) + 1)).fadeOut(200);
      $('#medewerker-' + ($('#medewerkers-holder .medewerker').index($(this)) + 1)).fadeIn(200, function() {
        $(this).jScrollPane({animateScroll: true});
      });
    });
    $('#content .medewerker-info .close-button').click(function() {
      $('#content .medewerker-info').fadeOut(200);
      $('#bigpicture').html('');
      clearInterval(actueelTimeout);
    });
  }
  
  /* Contact */
  $('#contactform #submit').click(function() {
    getDirections($('#gmStraat').val() + ' ' + $('#gmNummer').val() + ', ' + $('#gmPlaats').val());
  });
  
  checkHash();
  setInterval(checkHash, 300);
});
var actueelTimeout = 0;
function clickNextActueelFoto() {
  clearInterval(actueelTimeout);
  nextActueelFoto();
  actueelTimeout = setInterval(nextActueelFoto, 7000);
}
function nextActueelFoto() {
    var count = $('#bigpicture > img').length;
    var active = 0;
    $('#bigpicture > img').each(function(index) {
      if($(this).is(':visible')) {
        active = index;
      }
    });
    active++;
    if(active >= count) {
      active = 0;
    }
    $('#bigpicture > img').eq(active).show();
    $('#bigpicture > img').not($('#bigpicture > img').eq(active)).hide();
  }
var curHash = '';
function checkHash() {
  var hash = window.location.hash.replace('#', '');
  if(hash != curHash) {
    curHash = hash;
    if(hash != '') {
      getArchitectuurDetail(hash);
    } else {
      closeDetail();
    }
  }
}
var filterArray = [];
var filterSearch = '';
function loadItems() {
  $.ajax({
    url:'architectuur.php',
    data:{filters:filterArray.join(';'), search:filterSearch, who:who},
    success:function(data) {
      filterSearch = '';
      $('#architectuur .items').fadeOut(200, function() {
        $(this).html(data).fadeIn(200);
        var c = $('#architectuur .items .pair .img').length;
        if(c == 1) {
          c += ' RESULTAAT';
        } else {
          c += ' RESULTATEN';
        }
        $('#architectuur .results').html(c);
        Cufon.refresh();
        doArchitectuurMap();
        placeArchitectuurStuff();
      });
    },
    error:function() {
      alert('Er ging iets mis tijdens het opvragen van de informatie. Probeer het op een later tijdstip a.u.b. nogmaals.');
    }
  });
}
function closeDetail(e) {
  if(e) { e.preventDefault(); }
  window.location.hash = '';
  $('#architectuur-detail-holder').hide();
  $('#architectuur-menu-holder, #architectuur-holder, #info-holder').show();
  $('#architectuur-detail').html('');
}
function closeInfo(e) {
  e.preventDefault();
  $('#architectuur-detail .main a.close').unbind('click').click(closeDetail);
  $('#architectuur-detail .groot .meerinfo').fadeOut(100);
}
function getArchitectuurDetail(id) {
  $.ajax({
    url:'architectuur.php',
    data:{id:id, who:who},
    success:function(data) {
      window.location.hash = id;
      $('#architectuur-detail').html(data);
      $('#architectuur-menu-holder, #architectuur-holder, #info-holder, #tooltip').hide();
      $('#architectuur-detail-holder').show();
      
      /* Close detail */
      $('#architectuur-detail .main a.close').click(closeDetail);
      
      /* Show info */
      $('#architectuur-detail .main a:not(.close)').click(function(e) {
        e.preventDefault();
        $('#architectuur-detail .main a.close').unbind('click').click(closeInfo);
        $('#architectuur-detail .groot .meerinfo').fadeIn(100);
      });
      
      /* Thumb clicks */
      $('#architectuur-detail .thumbs .thumb').click(function() {
        var newSrc = $(' img', this).attr('src').replace('_thumb', '');
        $('#architectuur-detail .groot > img').fadeOut(200, function() {
          $('#architectuur-detail .groot > img').attr('src', newSrc);
        });
      });
      $('#architectuur-detail .groot > img').load(function() {
        $(this).fadeIn(200);
      });
      
      /* Thumbs scroll */
      var w = $('#architectuur-detail .thumbs .holder .thumb').length * 104;
      $('#architectuur-detail .arrowup').click(function() {
        if(Number($('#architectuur-detail .thumbs .holder').css('top').replace('px', '')) <= -104) {
          $('#architectuur-detail .thumbs .holder').stop(true, true).animate({top:'+=104px'}, 400);
        }
      });
      $('#architectuur-detail .arrowdown').click(function() {
        if(Number($('#architectuur-detail .thumbs .holder').css('top').replace('px', '')) > 465 - w) {
          $('#architectuur-detail .thumbs .holder').stop(true, true).animate({top:'-=104px'}, 400);
        }
      });
    },
    error:function() {
      alert('Er ging iets mis tijdens het opvragen van de detail informatie. Probeer het op een later tijdstip a.u.b. nogmaals.');
    }
  });
}
function placeArchitectuurStuff() {
  /* Click */
  $('.items .pair .img').click(function() {
    var id = $(' img', this).attr('id');
    getArchitectuurDetail(id);
  });
  
  /* Hover */
  $('.items .pair .img').hover(function() {
    $('#tooltip div').html($(' img', this).attr('alt'));
    $('#tooltipmap div').html($(' img', this).attr('alt'));
    $('#tooltip').show();
    var scale = Math.pow(2, map.getZoom())
    , nw = new google.maps.LatLng(
        map.getBounds().getNorthEast().lat(),
        map.getBounds().getSouthWest().lng()
    )
    , worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw)
    , worldCoordinate = map.getProjection().fromLatLngToPoint(glbl_markers[$(' img', this).attr('id')].getPosition())
    , pixelOffset = new google.maps.Point(
        Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
        Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
    );
    $('#tooltipmap').css({top:($('#maps').offset().top + pixelOffset['y'] - (25 + $('#tooltipmap').height())) + 'px', left:($('#maps').offset().left + pixelOffset['x'] - 5) + 'px'}).show();
    oldIcon = glbl_markers[$(' img', this).attr('id')].getIcon();
    var iconImage = new google.maps.MarkerImage(basePath + 'images/maps000000.png', null, null, new google.maps.Point(5, 5));
    glbl_markers[$(' img', this).attr('id')].setIcon(iconImage);
  }, function() {
    $('#tooltip').hide();
    $('#tooltipmap').hide();
    glbl_markers[$(' img', this).attr('id')].setIcon(oldIcon);
  });
  
  /* Mousemove */
  $('.items .pair .img').mousemove(function(e) {
    $('#tooltip').css({top:(e.pageY - (25 + $('#tooltip').height())) + 'px', left:(e.pageX - 5) + 'px'});
  });
  
  /* Browsing */
  $('.linearrow').click(nextLine);
  $('.linearrow2').click(prevLine);
  checkArrows();
}
var oldIcon = '';

var busyMoving = false;
function nextLine() {
  var la = $('#architectuur .line.active');
  if($('.items .pair').length && !busyMoving) {
    $('#architectuur .block.active').removeClass('active')
    la.nextAll('.block').eq(0).addClass('active');
    la.nextAll('.block').eq(1).addClass('active');
    la.nextAll('.line').eq(0).addClass('active');
    la.removeClass('active');
    busyMoving = true;
    $('.items').stop(true, true).animate({left:'-=966px'}, {duration:800, ease:'easeOutExpo', complete:checkArrows});
  }
}
function prevLine() {
  var la = $('#architectuur .line.active');
  if(la.prevAll('.line').eq(0).length > 0 && !busyMoving) {
    $('#architectuur .block.active').removeClass('active')
    la.prevAll('.block').eq(0).addClass('active');
    la.prevAll('.block').eq(1).addClass('active');
    la.prevAll('.line').eq(0).addClass('active');
    la.removeClass('active');
    busyMoving = true;
    $('.items').stop(true, true).animate({left:'+=966px'}, {duration:800, ease:'easeOutExpo', complete:checkArrows});
  }
}
function checkArrows() {
  if($('#architectuur .line.active').prevAll('.line').length > 0) {
    $('#architectuur .block').first().css('visibility','hidden');
    $('.linearrow2').show();
  } else {
    $('#architectuur .block').first().css('visibility','visible');
    $('.linearrow2').hide();
  }
  if(0 - ((Math.ceil($('.items .pair').length / 7) - 1) * 966) < Number($('.items').css('left').replace('px', ''))) {
    $('#architectuur .block').last().css('visibility','hidden');
    $('.linearrow').show();
  } else {
    $('#architectuur .block').last().css('visibility','visible');
    $('.linearrow').hide();
  }
  busyMoving = false;
}

var slideshowIndex = 0;
var busy = false;
function nextPortfolio() {
  if(!busy) {
    busy = true;
    if(slideshowIndex < 1) {
      resetPortfolio();
    } else {
      $('#portfolio-holder img').eq(slideshowIndex).fadeOut(1500, function() { busy = false; });
      slideshowIndex--;
    }
  }
}
function resetPortfolio() {
  slideshowIndex = $('#portfolio-holder img').length - 1;
  $('#portfolio-holder img').eq(slideshowIndex).fadeIn(1500, function() {
    $('#portfolio-holder img').show();
    busy = false;
  });
}

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':'Koningsplein 16, Maastricht'}, 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, disableDefaultUI:true, 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, icon:basePath + 'images/googlemapsicon.png'});
      directionsDisplay.setMap(map);
      directionsDisplay.setPanel(document.getElementById("directions"));
    });
  }
}

function getDirections(address) {
  var directionsService = new google.maps.DirectionsService();
  var altImage = new google.maps.MarkerImage(basePath + 'images/googlemapsicon-alt.png', null, null, new google.maps.Point(18, 0));
  directionsService.route({origin:address, destination:'Koningsplein 16, 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();
          }
  	      $('#address').slideUp();
          var useAlt = '';
          if(startLat > gLng) {
            useAlt = '-alt';
            var latlng2 = new google.maps.LatLng(gLat, gLng);
            new google.maps.Marker({position:latlng2, map:map, icon:altImage});
          } else {
            startMarker.setIcon(altImage);
            var latlng2 = new google.maps.LatLng(gLat, gLng);
            new google.maps.Marker({position:latlng2, map:map, icon:basePath + 'images/googlemapsicon.png'});
          }
          $('#directions').slideDown();
        });
      }
    } else {
      alert('Het adres "' + address + '" kan niet worden gevonden. Controleer het door u opgegeven adres op mogelijke typfouten.');
    }
  });
}
var bounds;
var infowindow;
function doArchitectuurMap() {
  bounds = new google.maps.LatLngBounds();
  var myOptions = {zoom:15, disableDefaultUI:true, center:new google.maps.LatLng(0,0), mapTypeControlOptions: { mapTypeId:[google.maps.MapTypeId.ROADMAP, 'narch'] }};
  map = new google.maps.Map(document.getElementById("maps"), myOptions);
  var mapStyle = [
    {
      featureType: "poi",
      elementType: "geometry",
      stylers: [
        { visibility: "off" }
      ]
    },{
      featureType: "road",
      elementType: "geometry",
      stylers: [
        { visibility: "off" }
      ]
    },{
      featureType: "transit",
      elementType: "geometry",
      stylers: [
        { visibility: "off" }
      ]
    },{
      featureType: "landscape.man_made",
      elementType: "geometry",
      stylers: [
        { visibility: "off" }
      ]
    },{
      featureType: "landscape.natural",
      elementType: "geometry",
      stylers: [
        { visibility: "on" },
        { saturation: -100 }
      ]
    },{
      featureType: "road.highway",
      elementType: "geometry",
      stylers: [
        { visibility: "off" }
      ]
    },{
      featureType: "road.arterial",
      elementType: "all",
      stylers: [
        { visibility: "off" }
      ]
    },{
      featureType: "road",
      elementType: "labels",
      stylers: [
        { visibility: "off" }
      ]
    },{
      featureType: "administrative",
      elementType: "labels",
      stylers: [
        { visibility: "off" }
      ]
    }
  ]
  var styledMapOptions = {
      name: "N-Architecten"
  }
  var NMapStyle = new google.maps.StyledMapType(
      mapStyle, styledMapOptions);
  map.mapTypes.set('narch', NMapStyle);
  map.setMapTypeId('narch');
  infowindow = new google.maps.InfoWindow();
  for(var i = 0; i < projecten.length; i++) {
    if(projecten[i][1] > 0 && projecten[i][2] > 0) {
      addMarker(projecten[i]);
    }
  }
}
var glbl_markers = {};
function addMarker(p) {
  var iconImage = new google.maps.MarkerImage(basePath + 'images/maps' + p[0] + '.png', null, null, new google.maps.Point(4, 4));
  var latlng = new google.maps.LatLng(Number(p[1]), Number(p[2]));
  bounds.extend(latlng);
  map.fitBounds(bounds);
  var marker = new google.maps.Marker({position:latlng, map:map, title:p[3], icon:iconImage});
  google.maps.event.addListener(marker,'mouseover',function(){
    $('#tooltipmap div').html(p[3]);
    var scale = Math.pow(2, map.getZoom())
    , nw = new google.maps.LatLng(
        map.getBounds().getNorthEast().lat(),
        map.getBounds().getSouthWest().lng()
    )
    , worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw)
    , worldCoordinate = map.getProjection().fromLatLngToPoint(this.getPosition())
    , pixelOffset = new google.maps.Point(
        Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
        Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
    );
    $('#tooltipmap').css({top:($('#maps').offset().top + pixelOffset['y'] - (25 + $('#tooltipmap').height())) + 'px', left:($('#maps').offset().left + pixelOffset['x'] - 5) + 'px'}).show();
  });
  google.maps.event.addListener(marker,'mouseout',function(){
    $('#tooltipmap').hide();
  });
  google.maps.event.addListener(marker,'click',function(){
    window.location.hash = p[4];
  });
  glbl_markers[p[4]] = marker;
}
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);}
  });
}
