var directionDisplay;
var directionsService;
var largemap;
var currentpenr = null;
var largeMarker;
var markers = new Array();

$(document).ready(function(){
	externalLinks();
});

initSearch = function() {
	$.get('/inc/search-penr.ajax.php', function(rsp){
		if (rsp.substring(0,3) =='err') {
			alert(rsp.substring(4));
			return false;
		} else {
			$('#search-result').html(rsp);
		}
		// show titels
		$('#search-penr .titels h3:first').html('Optie 1:');
		//$('#search-penr .titels h3').fadeIn();

		// disable text sel
		$('.search-result .content').disableTextSelect();
		

		if (currentpenr && parseInt(currentpenr.id) > 0) {
			$('[rel='+currentpenr.id+']').show();
			showPRresults($('[rel='+currentpenr.id+']'), false);
		} else {
			$('.content', '.search-result.first').show();
			showPRresults($('.search-result.first'), false);
		}

		// click bind
		$('.search-result').bind('click', function(){
			showPRresults(this);
		});
	
	});
	
	$('#vertrekpunt').focus(function(){
		if ($(this).val() == 'Plaatsnaam') $(this).val('');
	}).blur(function(){
		if ($(this).val() == '') $(this).val('Plaatsnaam');
	});

	$("#search-form").submit(function () {
		if ($('#vertrekpunt').val() == 'Plaatsnaam') {
			alert('U heeft een onjuiste plaatsnaam ingevoerd (code 0).');
			return false;
		}
		
		// close detail pane
		$('.search-result').removeClass('opened');
		$('#search-penr #detail').fadeOut(200, function(){
			$('.penr-detail, #small-map').hide();
			$('#search-penr').stop().animate({
				height: 182 
			}, 500, function() {});
		});

		// load data
		$.get('/inc/search-penr.ajax.php', {city:$('#vertrekpunt').val()}, function(rsp){
			if (rsp.substring(0,3) =='err') {
				alert(rsp.substring(4));
				return false;
			} else {
				$('#search-result').html(rsp);
			}

			// select first item
			$('.content', '.search-result.first').show();
			showPRresults($('.search-result.first'), false);
			
			// show titels
			//$('#search-penr .titels h3:first').html('Dichtsbijzijnde optie:'); // dit past niet als je optie 2 toont
			$('#search-penr .titels h3:first').html('Optie 1:');
			//$('#search-penr .titels h3').fadeIn();
			
			$('.search-result').bind('click', function(){
				showPRresults(this);	  
			});

		});
	});

	// handle clicks on result
	$('.search-result').click(function(){
		showPRresults(this);	  
	});
}

showPRresults = function(obj, opendetail) {
	if (opendetail == undefined) opendetail = true;
	var open = obj;

	
	// animate titels
	$('#search-penr .titels h3').fadeOut(200, function(){
		$('#search-penr .titels h3').addClass('option');

		sClass = false;
		if ($(open).attr('class').indexOf('first') != -1) {
			sClass = '2';
		} else if ($(open).attr('class').indexOf('second') != -1) {
			sClass = '3';
		} else if ($(open).attr('class').indexOf('third') != -1) {
			sClass = '4';
		}
		$('#search-penr .titels h3').addClass('option');
		if (sClass) $('#search-penr .titels h3:nth-child('+sClass+')').removeClass('option');

	});
	
	$('.search-result').not(obj).removeClass('active').stop().animate({
		width: '40px'
	}, 500, function(){
		//$('.content', obj).hide();
		$('#search-result .content').hide();
		$('.content', open).show();
	
		// animate clicked item
		$(open).stop().animate({
			width: '350px'
		}, 500, function(){
			$('#search-penr .titels h3').fadeIn();
			$('.search-result').not(open).removeClass('active').removeClass('opened').width('40px');
		});
		
	});

	if (!showDetail && opendetail) {
		opendetail = false;
		if ($(obj).hasClass('opened')) location.href = $('a', obj).attr('href');
	}
	
	$(obj).addClass('opened');

	// set first item active
	if ($(obj).width() > 100)
	$(obj).addClass('active');
	
	// animate more info window
	if (opendetail) {
		$('#search-penr').stop().animate({
			height: 495 
		}, 500, function() {
			$(open).addClass('active');
			_gaq.push(['_trackEvent', 'Zoeken', 'Click', $(obj).attr('rel')]);
			$('.penr-detail').hide();
			$('#penr-detail-'+parseInt($(open).attr('rel'))).show();
			$('#search-penr #detail').fadeIn(200, function(){
				showSmallMap();
			});

		});
	}

}

function showSmallMap() {
	$('#small-map').show();
    var myOptions = {
      zoom: 11,
      center: new google.maps.LatLng(52.088367,5.120659),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("small-map"),
                                  myOptions);

    for (i = 0; i < penr.length; i++) {
    	if (parseInt($('#search-penr .active').attr('rel')) != parseInt(penr[i].id)) continue;
	    var image = new google.maps.MarkerImage(
	    	'/images/maps_ico.png', // url
	    	new google.maps.Size(54, 58), //size
	      new google.maps.Point(0,0), // origin
	    	new google.maps.Point(13,55) // anchor
	    );
	    var myLatLng = new google.maps.LatLng(penr[i].Latitude, penr[i].Longitude);
	    var beachMarker = new google.maps.Marker({
	        position: myLatLng,
	        map: map,
	        icon: image
	    });
    }
}

function showLargeMap(id){
	var myOptions = {
    zoom: 11,
    center: new google.maps.LatLng(52.088367,5.120659),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  largemap = new google.maps.Map(document.getElementById("large-map"), myOptions);
	
	directionsService = new google.maps.DirectionsService()	
	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsDisplay.setMap(largemap);
	directionsDisplay.setPanel(document.getElementById("route"));
											
  for (i = 0; i < penr.length; i++) {
		if(parseInt(penr[i].id) == parseInt(id)){
			currentpenr = penr[i];

			var image = new google.maps.MarkerImage(
					'/images/maps_ico_'+id+'.png', // url
					new google.maps.Size(217, 66), //size
					new google.maps.Point(0,0), // origin
					new google.maps.Point(13,55) // anchor
			);
		} else {
			if(!parseInt(id)){
		    var image = new google.maps.MarkerImage(
		    		'/images/maps_ico.png', // url
		    		new google.maps.Size(54, 58), //size
		    		new google.maps.Point(0,0), // origin
		    		new google.maps.Point(13,55) // anchor
		    );
			} else {
				continue;
			}
		}
    var myLatLng = new google.maps.LatLng(penr[i].Latitude, penr[i].Longitude);
    largeMarker = new google.maps.Marker({
        position: myLatLng,
        map: largemap,
        icon: image,
		zIndex: (parseInt(penr[i].id) == parseInt(id) ? 20 : 10),
		clickurl: penr[i].url,
		penrid: penr[i].id
    });
    
    // add click even handler to marker
    google.maps.event.addListener(largeMarker, 'click', function() {
        location.href=this.clickurl;
      });
    if(!parseInt(id)){
	    google.maps.event.addListener(largeMarker, 'mouseover', function() {
	    	var image = new google.maps.MarkerImage(
					'/images/maps_ico_'+this.penrid+'.png', // url
					new google.maps.Size(217, 66), //size
					new google.maps.Point(0,0), // origin
					new google.maps.Point(13,55) // anchor
			);
	    	this.setZIndex(20);
	        this.setIcon(image);
	      });
	    google.maps.event.addListener(largeMarker, 'mouseout', function() {
	    	var image = new google.maps.MarkerImage(
					'/images/maps_ico.png', // url
		    		new google.maps.Size(54, 58), //size
		    		new google.maps.Point(0,0), // origin
		    		new google.maps.Point(13,55) // anchor
	
			);
	    	this.setZIndex(10);
	        this.setIcon(image);
	      });   
    }
    markers.push(largeMarker);
  }
}

function hoverMarker(num, event) {
	for(var i=0; i<markers.length;i++)
	if (markers[i].penrid == num) new google.maps.event.trigger(markers[i], event);
}

function calcRoute() {
	var start = document.getElementById("input-route").value;
	var end = currentpenr.Latitude+','+currentpenr.Longitude;

	var request = {
		origin:start, 
		destination:end,
		travelMode: google.maps.DirectionsTravelMode.DRIVING,
		unitSystem: google.maps.DirectionsUnitSystem.METRIC,
		region: 'NL'
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
			largeMarker.setMap(null);
			
			
			$('#route').prepend('<br><a href="javascript:void(0);" onclick="window.open(\'http://maps.google.nl/maps?f=d&hl=nl&source=s_d&geocode=&saddr='+start+'&daddr='+currentpenr.adres+'@'+end+'&pw=2\', \'route\', \'scrollbars=1, width=780, height=600\'); return false;">print route</a>');
			$('#route').after('<br><a href="javascript:void(0);" onclick="window.open(\'http://maps.google.nl/maps?f=d&hl=nl&source=s_d&geocode=&saddr='+start+'&daddr='+currentpenr.adres+'@'+end+'&pw=2\', \'route\', \'scrollbars=1, width=780, height=600\'); return false;">print route</a>');
		}
	});
}


function toggleFaq(id){
	$('#farticles li').removeClass('open');
	$('#farticles #'+id).addClass('open');
}

validate = function( id ) {
	var err = false;

	$('#'+id+' :input').each(function(){
		$(this).removeClass('ferr');
		if ($(this).attr('type') != 'hidden' && $(this).attr('rel') == 'req') {
			if ($(this).attr('name').indexOf('E-mailadres') >= 0) {
				var reg = new RegExp("^[0-9a-zA-Z\-\_\.]+@[0-9a-zA-Z\-]+[\.]{1}[0-9a-zA-Z\-]+[\.]?[0-9a-zA-Z]+$");
				if(!reg.test($(this).val())) {
					$(this).addClass('ferr');
					err = true;
				}
			} else if ($(this).val().length == 0) {
				$(this).addClass('ferr');
				err = true;
			}
		}
	});
	$('#'+id+' :input.ferr:first').focus();

	if (err) window.alert('Niet alle velden zijn correct ingevoerd. Deze zijn rood gemarkeerd.');
	
	return !err;
}

