var suggestRequest = null;

//add functionality (IE6 ao?)
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function (obj, fromIndex) {
		if (fromIndex == null) {
			fromIndex = 0;
		} else if (fromIndex < 0) {
			fromIndex = Math.max(0, this.length + fromIndex);
		}
		for (var i = fromIndex, j = this.length; i < j; i++) {
			if (this[i] === obj)
				return i;
		}
		return -1;
	};
}

$(document).ready(function(){
	// menu functies ////////////////////////////////////////

	//in-/uitklappen submenu
//	$('#menu > ul > li > a').click(function() {
//		// alles sluiten
//		$('#menu').find('a.open').removeClass('open').siblings('ul').slideUp();
//
//		// juiste submenu openen
//		var obj = $(this).siblings('ul');
//		if (obj.css('display')=='none')
//		{
//			obj.slideToggle();
//			$(this).addClass('open');
//		}
//		else {
//			obj.slideUp();
//			$(this).removeClass('open');
//		}
//	});
	// active menu openzetten
	$('#menu > ul > li > a.active').addClass('open').siblings('ul').css('display','block');

	// in/uitklappen subsubmenu
	$('#menu > ul > li > ul > li').each(function(){
		var link = $(this).find('a');
		if (0 < $(this).find('ul').length)
		{
			$(this).hover(function(){
				$(this).find('ul').show();
			},function(){
				$(this).find('ul').hide();
			});
		}
	});

	//in-/uitklappen form
	$('#uitklap_contact').click(function() {
		var obj = $(this).siblings('#contactform');
		if (obj.css('display')=='none')
		{
			obj.slideToggle();
			$(this).addClass('open');
		}
		else {
			obj.slideUp();
			$(this).removeClass('open');
		}
	});

	// contact form
	var checkKlanttype = function(){
		var val = $('#contactform select[name=klanttype]').val();
		var textarea = $('#contactform textarea[name=details]');

		if ('particulier' == val || 'overheid' == val)
		{
			//hide company name and kvk
			$('#js_bedrijfsnaam:visible').fadeOut();
			$('#js_kvk:visible').fadeOut(undefined, function(){
				if ('150px' != textarea.css('height'))
				{
					textarea.animate({height:'150px'});
				}
			});
		}
		else
		{
			//show
			if ('95px' != textarea.css('height'))
			{
				textarea.animate({height:'95px'}, function(){
					$('#js_bedrijfsnaam:hidden').fadeIn();
					$('#js_kvk:hidden').fadeIn();
				});
			}
		}
	}
	$('#contactform select[name=klanttype]').change(checkKlanttype);
	checkKlanttype(); //init

	var slideOpenTimeout;

	// in-/uitklappen zoek
//	$('#bomenboek_zoek').mouseover(function(e) { // mouseover, zodat het wel uitklapt als je er al op staat bij het inklappen, maar weer beweegt...
//		//don't do anything when hovering submitbutton
//		if (hoverSubmit)
//			return;
//
//		if ($('#zoek_groot').css('display')=='none')
//		{
//			if (!slideOpenTimeout)
//				slideOpenTimeout = window.setTimeout(function(){$('#zoek_groot').slideDown()}, 200);
//		}
//	});
//	$('#bomenboek_zoek').mouseleave(function(event) {// wordt helaas ook aangeroepen als je een select ingaat...
//
//		if (event.relatedTarget) // geeft null terug binnen select (omdat deze "boven" de html staat) en een object als je buiten #bomenboek_zoek komt
//		{
//			if (slideOpenTimeout)
//			{
//				window.clearTimeout(slideOpenTimeout);
//				slideOpenTimeout = null;
//			}
//			$('#zoek_groot').slideUp();
//		}
//	});

	$('.js_minderzoeken').click(function(){
		$(this).fadeOut();
		$('#zoek_groot').slideUp(function(){
			$('.js_meerzoeken').fadeIn();
		});
	})
	$('.js_meerzoeken').click(function(){
		$(this).fadeOut();
		$('#zoek_groot').slideDown(function(){
			$('.js_minderzoeken').fadeIn();
		});
	})

//	$('.submitform.zoeken').click(function(){
//		forwarding = true;
//		$(this).parents('form:first').trigger('submit');
//	})

	var hoverSubmit = false;
	$('.submitform.zoeken').hover(function(){
		hoverSubmit = true;
		if (slideOpenTimeout)
		{
			window.clearTimeout(slideOpenTimeout);
			slideOpenTimeout = null;
		}
	}, function(){
		hoverSubmit = false;
	})

	//in-/uitklappen sortiment
	$('.uitklaplink').click(function() {
		$(this).parents('#content').find('.uitklap').each(function(){
				$(this).find('.uitklap_details').slideUp();
				$(this).find('.uitklaplink').removeClass('open');
		})

		var obj = $(this).siblings('.uitklap_details');
		if (obj.css('display')=='none') //geklikt item openen
		{
			obj.slideDown();
			$(this).addClass('open');
		}
	});

	var forwarding = false;

	// suggest plant
	var searchQueryLength = 0;
	var suggestTimeout = 0;
	var searchFieldValue;

	var getSuggestion = function(){
		if (0 < suggestTimeout)
			clearTimeout(suggestTimeout);
		var field = this;
		
		suggestTimeout = setTimeout(function(){ //call binds initiator of the function to the called function
			var query = $(field).val();	
			if (query.length == searchQueryLength) //value of the field has not been changed
				return;
	
			searchQueryLength = query.length; //set global var's value
	
//			if (2 < query.length || 0 == query.length)
			if (1)
			{
				if (0 == $('#js_suggestDiv').length)
				{
					var container = $('<div id="js_suggestDiv" class="suggest"><div class="arrow"/><div id="js_suggestions" class="suggestions"/></div>').hide();
					$('#top').append(container);
					if (2 < query.length)
						$('#js_suggestDiv').slideDown();
				}
				var suggestionsDiv = $('#js_suggestions');
				if (2 < query.length)
				{
					suggestionsDiv.css('width', '260px');
					suggestionsDiv.css('height', '40px');
				}
	
				suggestionsDiv.addClass('loading');
				//display loading gif when request takes > 400 ms
				var loadingTimeout = window.setTimeout(function(){
					suggestionsDiv.addClass('loadinggif');
				}, 300);
	
				//abort currently executing request
				if (suggestRequest)
				{
					suggestRequest.abort();
					suggestRequest = null;
				}
				suggestRequest = $.ajax({
					type: 'post',
					timeout: 10000, // miliseconds
					data: $('#bomenboek_zoekform').serialize(),
					dataType: 'json',
					url: PATH + $('input[name=suggesturl]').val(),
					success: function(response){
						window.clearTimeout(loadingTimeout);
						//prevent adding of loadinggif after result are loaded
						window.setTimeout(function(){$('#js_suggestions').removeClass('loadinggif')}, 300);
	
	
						//load new:
						if (response.options && 0 < response.options.length)
						{
							//clear old
							suggestionsDiv.html('');
							suggestionsDiv.css('width', '');
							suggestionsDiv.css('height', '');
							for (var i = 0; i < response.options.length; i++)
							{
								if (0 < response.options[i]['url'].length)
								{
									var link = $('<a href="'+response.options[i]['url']+'" >'+response.options[i]['naam']+'</a>').click(function(event){
										forwarding = true;
									});
									link.hover(function(){forwarding = true}, function(){forwarding = false});
									var item = $('<div data-key="'+(i+1)+'"></div>').append(link);
								}
								else
								{
									var link = $('<a href="#" class="sortimentlink">'+response.options[i]['naam']+'</a>').click(function(event){
										forwarding = false;
										$('#bomenboek_zoekform input[name=zoekterm]').val($(this).html());
										$('#bomenboek_zoekform input[name^=soort]').removeAttr('checked');
										$('#bomenboek_zoekform').submit();
										return false;
									});
//									link.hover(function(){forwarding = true}, function(){forwarding = false});
									var item = $('<div data-key="'+(i+1)+'"></div>').append(link);
								}
								suggestionsDiv.append(item);
							}
	//						suggestDiv.css('left', '396px');
	//						suggestDiv.css('top', '180px');
	//						suggestDiv.css('z-index', '1000');
	
							var newHeight;
	
							if (response.options.length > 20)
							{
								newHeight = 440;
								if (0 == suggestionsDiv.height())
									suggestionsDiv.css('height', '440px');
								suggestionsDiv.css('overflow', 'hidden');
							}
							else
							{
								newHeight = response.options.length * 22;
	//							suggestionsDiv.css('height', (response.options.length * 22)+'px');
								suggestionsDiv.css('overflow', '');
							}
							$('#js_suggestDiv:hidden').slideDown();
	
							suggestionsDiv.animate({height:newHeight+'px'})
						}
						else
							$('#js_suggestDiv').slideUp(function(){$('#js_suggestDiv').remove();});
						$('#js_suggestions').removeClass('loading');
						suggestRequest = null;

						//set width
						suggestionsDiv.css('width', suggestionsDiv.outerWidth() + 'px');
						
						//edit filters
						filterOptions();
					},
					error: function(XMLHttpRequest, textStatus, errorThrown){
						window.clearTimeout(loadingTimeout);
						//prevent adding of loadinggif after result are loaded
						window.setTimeout(function(){$('#js_suggestions').removeClass('loadinggif')}, 300);
						$('#js_suggestions').removeClass('loading');
						$('#js_suggestDiv').slideUp(function(){$('#js_suggestDiv').remove();});
						suggestRequest = null;
					}
	
				})
			}
			else
				$('#js_suggestDiv').remove();
		}, 500); //allow typing of words before starting ajax call
	}

	$('#bomenboek_zoekform input[name=zoekterm]').attr('autocomplete', 'off');
	$('#bomenboek_zoekform input[name=zoekterm]').keyup(getSuggestion);
	
	//filter select options
	var optionsRequest = null;
	var filterOptions = function()
	{
		//can't make the request
		if (0 == $('input[name=optionsurl]').length)
			return;
		
		var data = $('#bomenboek_zoekform').serialize();

		//convert selected filters to an "unset url"
		$('#bomenboek_zoekform select').each(function(){
			if ($(this).val() && 0 == $(this).parents('p:first').find('a.js_unset').length)
			{
				$(this).parents('p:first').append('<a href="javascript:;" class="js_unset unsetfilter">' + $(this).find('option[value="'+$(this).val()+'"]').text() + '</a>');
				$(this).hide();
			}
		});
		
		//block user input sd
//		$('#bomenboek_zoekform input').attr('readonly','readonly');
		$('#bomenboek_zoekform select option').attr('disabled','disabled');	// firefox, chrome, ie8
		$('#bomenboek_zoekform select').attr('disabled','disabled');		// ie7, ie6

		optionsRequest = $.ajax({
			url: PATH + $('input[name=optionsurl]').val(),
			data: data,
			dataType: 'json',
			type: 'post',
			success: function(response){
				if (response.success)
				{
					$('#js_count').html(response.resultcount);
					
					/*
					 * rebuild select boxes from backup
					 */
					var targets = $('#bomenboek_zoekform select[name="options[]"]');
					var backups = $('#bomenboek_zoekform_backup select[name="options[]"]');
					
					for (var i = 0; i < targets.length; i++)
					{
						var target = $(targets[i]);
						var backup = $(backups[i]);
						var selected = target.val();
						target.find('option').remove();
						target.html(backup.html());
						target.val(selected);
					}
					
					/*
					 * mark all checkboxes as hidden
					 */
					$('#bomenboek_zoekform input[type="checkbox"]').addClass('disabled');

					if ('undefined' == typeof response.all || !response.all)
					{
						//winterhardheidszone
						if (0 < response.winter.length)
						{
							var winter = $('#bomenboek_zoekform select[name^=winter]');
							winter.parents('p:first').fadeIn(function(){$(this).show()});
							winter.find('option[value='+response.winter+']').prevAll().each(function(){
								if ('' != $(this).attr('value')) //don't remove hint
									$(this).remove();
							})
						}
						else
						{
							$('#bomenboek_zoekform select[name^=winter]').parents('p:first').fadeOut(function(){$(this).hide()});
						}
						for (var i = 0; i < response.winter.length; i++)
						{
							$('#bomenboek_zoekform select[name^=winter] option[value='+response.options[i]+']').each(function(){
									$(this).removeClass('disabled');
							});
						}
						
						/*
						 * remove disabled options
						 */
						$('#bomenboek_zoekform select[name="options[]"] option').each(function(){
							//don't remove the hint..
							if (0 > response.options.indexOf($(this).attr('value')) && '' !== $(this).attr('value') && $(this).parents('select:first').val () != $(this).attr('value'))
							{
								$(this).remove();
							}
						});
						
						//hide empty selectboxes
						$('#bomenboek_zoekform select[name="options[]"]').each(function(){
							if(1 >= $(this).find('option').length && $(this).val() == '') //only one option left (hint) && nothing selected
							{
								$(this).parents('p:first').fadeOut(function(){$(this).hide()});
							}
							else
							{
								$(this).parents('p:first').fadeIn(function(){$(this).show()});
							}
						})

						/*
						 * do the same for checkboxes
						 */						
						$('#bomenboek_zoekform input[type=checkbox][name="options[]"]').each(function(){
							if (0 <= response.options.indexOf($(this).attr('value')))
							{
								$(this).removeClass('disabled'); //don't hide this one
							}
						});
						
						//and excluding checkboxes
						$('#bomenboek_zoekform input[type=checkbox][name="exclude[]"]').each(function(){
							if (0 <= response.exclude.indexOf($(this).attr('value')))
							{
								$(this).removeClass('disabled'); //don't hide this one
							}
						});
						
						$('input[type=checkbox]:checked').removeClass('disabled');
					}
					else
					{
						//show everything
						$('#bomenboek_zoekform p').fadeIn();
						//keep all checkboxes
						$('#bomenboek_zoekform input[type="checkbox"]').removeClass('disabled');
					}

					$('#bomenboek_zoekform input[type="checkbox"][class!=disabled]').each(function(){
						$(this).show();
						$(this).parents('span:first').show();
					});
					$('#bomenboek_zoekform input[type="checkbox"].disabled').each(function(){
						$(this).parents('span:first').hide();
					});

					/*
					 * hide empty checkbox labels
					 */
					$('input[type=checkbox][name="exclude[]"]:first').parents('p:first').each(function(){
						if (0 == $(this).find('span input[class!=disabled]').length)
							$(this).fadeOut(function(){$(this).hide()});
						else
							$(this).show();
					});
					$('input[type=checkbox][name="options[]"]:first').parents('p:first').each(function(){
						if (0 == $(this).find('span input[class!=disabled]').length)
							$(this).fadeOut(function(){$(this).hide()});
						else
							$(this).show();
					});
					
					
					$('#bomenboek_zoekform .disabled').removeClass('disabled');
					
					//activate form
					$('#bomenboek_zoekform input').removeAttr('readonly');
					$('#bomenboek_zoekform select option').removeAttr('disabled');
					$('#bomenboek_zoekform select').removeAttr('disabled');
				}
			}
		})
	}
	
	//backup form for suggestions
	$('body').append('<form id="bomenboek_zoekform_backup" style="display:none" onsubmit="return false;">'+$('#bomenboek_zoekform').html()+'</form>');
	$('#bomenboek_zoekform_backup [id!=""]').removeAttr('id');
	$('#bomenboek_zoekform_backup [class!=""]').removeAttr('class');
	
	//set event listeners
	$('#bomenboek_zoekform select').change(filterOptions);
	$('#bomenboek_zoekform input[type=checkbox]').click(filterOptions);
	
	//call to initalize current set options
	filterOptions();

	//when a filter unset link is used
	$('a.js_unset').live('click', function(){
		$(this).parents('p:first').find('select').val('').show();
		$(this).remove();
		filterOptions(); //refresh filters
	});

	var forwarding = false;
	
	//catch return key for selecting a suggestion
	$(document).keydown(function(e){
		if (13 == e.keyCode && 0 < $('#js_suggestDiv:visible').length && 0 < $('#js_suggestDiv div.selected a').length) // return
		{
			if ($('#js_suggestDiv div.selected a').hasClass('sortimentlink')) //sortimentlijst
			{
				$('#bomenboek_zoekform input[name=zoekterm]').val($('#js_suggestDiv div.selected a').html());
				$('#bomenboek_zoekform input[name^=soort]').removeAttr('checked');
				$('#bomenboek_zoekform').submit();
			}
			else //bomenboek
			{
				document.location = $('#js_suggestDiv div.selected a').attr('href');
			}
			return false;
		}
	});

	$('#bomenboek_zoekform').submit(function(){
		if (forwarding)
			return false;
	})

	$('#bomenboek_zoekform input[name=zoekterm]').keydown(function(e){
		if (0 < $('#js_suggestDiv').length)
		{
			var select = false;
			
			var direction = false;
			if (38 == e.keyCode) // up
				direction = -1;
			if (40 == e.keyCode) // down
				direction = 1;
			if (36 == e.keyCode) // home
				select = 1;
			if (35 == e.keyCode) // end
				select = $('#js_suggestDiv div').length;
			if (34 == e.keyCode) // page down
				direction = 20;
			if (33 == e.keyCode) // page up
				direction = -20;
			if (false !== direction || false !== select)
			{
				var current	= 0;
				var suggestionsDiv = $('#js_suggestions');
				var items	= $('#js_suggestions div').length;

				// key is selected
				if (0 < $('#js_suggestions div.selected').length)
					current = $('#js_suggestions div.selected').attr('data-key');

				if (false === select)
					select = parseInt(current) + direction;

				//loop when on start or end of list
//				if (1 > select)
//					select = items;
//				if (items < select)
//					select = 1;

				if (1 > select)
					select = 1;
				if (items < select)
					select = items;

				$('#js_suggestions div.selected').removeClass('selected');
				$('#js_suggestions div[data-key='+select+']').addClass('selected');
				var offset  = $('#js_suggestions div.selected').offset().top - suggestionsDiv.offset().top + suggestionsDiv.scrollTop();
				// scroll down
				if (offset > 420 + suggestionsDiv.scrollTop())
				{
					$('#js_suggestions').scrollTop(offset - 420);
				}
				// scroll up
				if (offset < suggestionsDiv.scrollTop())
				{
					$('#js_suggestions').scrollTop(offset);
				}
				return false;
			}
		}
	});

	//remove suggestions on blur, reload filters
	$('#bomenboek_zoekform input[name=zoekterm]').blur(function(event){
		if (suggestRequest)
				suggestRequest.abort();

		if (!forwarding)
			$('#js_suggestDiv').slideUp();
	});
	$('#bomenboek_zoekform input[name=zoekterm]').focus(function(){
		$('#js_suggestDiv').slideDown();
	});

	//referentie filter
	$('#js_reffilter').change(function(){
		$(this).parents('form:first').submit();
	})	
	
	$('form').append('<input type="hidden" name="js_submit" value="oke" />');
});


/**
 * Use colorbox to display a slideshow
 */
function showPhoto(items, index)
{
	if (typeof $().colorbox != "function" || typeof items != "object")
		return;

	if (typeof index == "undefined")
		index = 0;
	index = parseInt(index);
	if (index == NaN)
		index = 0;
	if (index >= items.length)
		return;

	var container = $('<div/>').hide();
	$('body').append(container);
	var photolinks = new Array();
	var colorboxConfig = {
		previous: translations.Vorige,
		next: translations.Volgende,
		current: translations.Afbeelding + ' {current} ' + translations.van +' {total}',
		opacity:0.75,
		onClosed: function(){
			container.remove();
		}
	};

	for (var i = 0; i < items.length; i++)
	{
		photolinks[i] = $('<a rel="openalbum" href="' + items[i] + '">Afbeelding ' + (i+1) + '</a>').colorbox(colorboxConfig);
		container.append(photolinks[i]);
	}

	//open item of index
	photolinks[index].trigger('click');
}
