var klkExp = new RegExp('\\[([a-z-0-9]+)\\]');
var runHeavy = true;
var siteAttr = {};
var fixedEle = {};
var voertuig = 'auto';

$(document).ready( function() {
	runHeavy = !( Math.round( jQuery.browser.version ) <= 6 && jQuery.browser.msie );
	voertuig = ( document.location.toString().indexOf( 'motorwereld' ) > 0 ? 'motor' : 'auto' );
	
	$.fn.focusDelay = function(time) { var o = this; setTimeout( function() { $(o).focus(); }, time ); return this;	}
	$.ajaxSetup( { url: '/jx.php', dataType: 'json', type: 'GET', cache: true } );
	
	$('a[class*="]"]').filter( function() { return $(this).attr('class').match( klkExp ); } ).click( function() { return trackKlik( this ); } );
	
	// Lijst hover
	$('.lijst tr, .galerij td').hover( function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); } );
	
	// Pagina
	if ( typeof initPagina != "undefined" ) { initPagina(); }
	
	if ( runHeavy ) {
		initKnopHover();
	}
	
	initLijstFilters();
	initAutocomplete();
	initFormCommentaar();
	
	// Fotolijst
	$('ul.fotolijst li.item img:not(.geen)').mouseover( function() {
		$('#fotogroot img').attr('src', $(this).attr('src').replace( '/100/', '/320/' ) );
		$('#fotogroot').attr('href', $(this).parent().attr('href') );
	} );
	
	// Verzekerbanner
	if ( $(".verzekerbox").length > 0 ){
		$("#verzeker-gebdag, #verzeker-gebmaand").bind("keyup", function() { 
			if( $(this).val().length == 2 ){
				$(this).nextAll("input:first").focus();
			}
		} );
	}
	
	// Fixed element meescrollen
	if ( runHeavy ) {
		initFixedScroll();
	}
		
	// Vergelijk checkbox
	initVergelijken();
	
	// Lijst checkbox
	$('.lijst td.checkbox input').click( function( ) {
		$.ajax( {
			data: 'occ=checklijst&nr='+this.id.replace('itemchk-', '')+'&status='+( this.checked ? 1 : 0 ),
			context: this,
			success: function() {
				this.checked = !this.checked;
			}
		} );
		return false;
	} );
	
	// Checkbox alles
	$('#itemchk-alles').click( function() {
		if ( $('.lijst').hasClass('gebruiker') ) {
			$('.lijst.gebruiker td input[type=checkbox]').prop( 'checked', $('#itemchk-alles').is(':checked') );
		} else {
			var $ele = $('.lijst td input[type=checkbox]');
			
			var data = { occ: 'checklijst' };
			if ( !$('#itemchk-alles').is( ':checked' ) ) {
				data.nr = 'legen';
			} else {
				var eleIds = new Array();
				$ele.each( function() {
					eleIds.push( $(this).attr('id').replace('itemchk-', '') );
				} );
				data.nr = eleIds.join(',');
			}
			
			$.ajax( { data: data } );		
			$ele.prop( 'checked', $('#itemchk-alles').is(':checked') );
			return true;
		}
	} );
	
	// Galerij sortering
	$('.galerij #srtr').change( function() {
		$(this).parents('form').submit();
	} );
	
	// Garantie logo's
	$(".lijst tbody tr").hover( function() { 
		$(this).find('.garantielogo').each( function( ) { 
			$(this).attr( 'src', $(this).attr('src').replace('-bw.gif','-fc.gif') );
		} );
	}, function() { 
		$(this).find('.garantielogo').each(function( ){ 
			$(this).attr( 'src', $(this).attr('src').replace('-fc.gif','-bw.gif') );
		} );
	} );
	
	// Tabframe knop zoeken
	if ( $('#tabframe .knop-zoeken').length ) {
		$('.knop-zoeken').bind('click', function() { 
			$(this).parents('form').submit();
		} );
	}
	
	// Onclick bedrijfswebsite
	$('.aanbieder a.website, .lijst.bedrijf a.website').each( function() {
		if ( $(this).attr('rel') ) {
			$(this).click( function() { 
				window.location = $(this).attr('rel');
				return false;
			} );
		}
	} );
	
	// Boxfix
	if ( runHeavy ) {
		setTimeout( initBoxfix, 100 );
	}
	
	// Dialoog
	$('body').append( '<div id="dialoog" title="Dialoog"></div>' );
	$('#dialoog').dialog( {
		autoOpen: false,
		width: 649,
		minHeight: 200,
		modal: true,
		resizable: false,
		draggable: false,
		buttons: { "Sluit scherm": function() {	$(this).dialog('close'); } },
		open: function() {
			$('iframe, object').filter( function() {
				if ( $(this).parents('#dialoog').length ) {
					return false;
				}
				
				return true;
			} ).css( { visibility: 'hidden' } );
		},
		close: function() {
			$('iframe, object').css( { visibility: 'visible' } );
		}
	} );
	
	// Print
	$('body').prepend( '<img src="/images/logo/'+voertuig+'wereld-print.gif" id="printlogo" />' );
	
	// Beste garage
	if ( $( ".bestegarage-widget" ).length ) {
		$( ".bestegarage-widget:not(.bestegarage-onbekend)" ).each( function () {
			var widgetUrl = 'http://bestegarage.nl/company/widget/id/' + $(this).attr("data-id") + "/format/" + $(this).attr("data-format") + '/';
			$(this).show().html( '<iframe id="bgframe" width="168" height="20" frameborder="0" scrolling="no" src="'+widgetUrl+'" class="noprint"></iframe>' );
		} );
	}
	
	// Beste garage - De tooltip op de widget op de overzicht pagina.
	if ( $( ".bestegarage-overzicht, .bestegarage-reviews" ).length ) {
		$( ".bestegarage-overzicht, .bestegarage-reviews" ).each( function() {
			if ( typeof( besteGarage ) != "undefined" && besteGarage.aantal > 0 ) {
				$ele = $( this );
				
				var url		= 'http://bestegarage.nl/bedrijf/'+besteGarage.link+'/'+$ele.attr("data-id");
				var titel   = "Beste Garage Reviews";
				var inhoud  = "", reviews = [];
				
				for( var i in besteGarage.reviews ){
					reviews.push( [
						'<a href="'+url+'" target="_blank" class="review-link">'+besteGarage.reviews[i].review,
						'<br /><span class="review-auteur">Door '+besteGarage.reviews[i].author+' op '+besteGarage.reviews[i].created_at+'.</span>',
						'</a>'
					].join("") );
					
					if ( i == 2 ) {
						break;
					}
				}
				
				inhoud += '<h2>'+titel+'</h2>'+reviews.join("<hr />")+'<hr />';
				inhoud += '<a href="'+url+'" target="_blank" class="pijl">Meer reviews en info, of beoordeel zelf.</a>';
				
				$ele.qtip( { 
					content: { text: inhoud },
					style: { tip: true, classes: 'ui-tooltip-bestegarage', widget: true },
					position: { adjust: { y: 5 }, my: 'top left', at: 'bottom left', target: $ele },
					hide: { event: 'mouseleave', delay: 300, fixed: true }
				} );
			}
		} );
	}
	//--
	
	initTelefoonnummer();
	initHelpTooltip();
	initMededeling();
	initNavigatieGrid();
} );

/**
 * Occasion bewaren
 */
function occBewaren( EleKnop, Nr ) {
	$.ajax( {
		data: { occ: 'bewaren', nr: Nr },
		context: EleKnop,
		success: function() {
			$(this).outerHTML( '<img src="/images/knop/'+( $('img', EleKnop).attr('src').indexOf( 'icoon' ) > 0 ? 'icoon-' : '' )+'bewaard-wit.png" alt="Bewaard" class="knop geencursor" />' );
		}
	} );
	
	return false;
}

/**
 * Occasion vergelijken
 */
function occVergelijken( EleCheck, Nr ) {
	$.ajax( {
		data: { occ: 'vergelijken', nr: Nr },
		context: EleCheck,
		success: function() {
			this.checked = !this.checked;
		}
	} );
	
	return false;
}

/**
 * Knoppen
 */
function initKnopHover( EleStr ) {
	var eleLijst = {};
	if ( typeof EleStr == 'object' ) {
		eleLijst = EleStr;
	} else {
		EleStr = ( typeof EleStr != 'string' ? '' : EleStr+' ' );
		eleLijst = $(EleStr+'input,'+EleStr+'img,'+EleStr+'a');
		
		$(EleStr+'img').parent().css( 'outline', 'none' );
	}
	
	eleLijst.filter('.knop').unbind('hover').hover(
		function() { knopHover( $(this), true ); },
		function() { knopHover( $(this), false ); }
	);
}

function knopHover( $$, Hover ) {
	var imgSrc = ( $$.attr('href') ? $( 'img', $$ ).attr('src') : $$.attr('src') ? $$.attr('src') : $$.css('backgroundImage') );
	var imgExt = imgSrc.match( RegExp('\\.([a-z]{3})("\\)|\\)|)$') );
	if ( !imgExt ) {
		return false;
	}
	imgSrc = imgSrc.replace( '-hover.'+imgExt[1], '.'+imgExt[1] );
	( Hover ? imgSrc = imgSrc.replace( '.'+imgExt[1], '-hover.'+imgExt[1] ) : false );
	( $$.attr('href') ? $( 'img', $$ ).attr('src', imgSrc) : $$.attr('src') ? $$.attr('src', imgSrc) : $$.css('backgroundImage', imgSrc ) );
}

/**
 * Merk / Model / Uitvoering laden
 */
function laadMMU( setting ) {
	if ( !setting.laad ) {
		return;
	}
	
	var jxData = {
		lijst: setting.laad,
		mrk: setting.ele.merk.val()
	};
	if ( setting.ele.model ) {
		jxData.mdl = setting.ele.model.val();
	}
	if ( setting.ele.voertuig ) {
		jxData.voertuig = setting.ele.voertuig;
	}
	if ( setting.gg ) {
		jxData.gg = 1;
	}
	
	$.ajax( {
		data: jxData,
		context: setting,
		success: function( data ) {
			var dataLijst = data;
			
			if ( this.ele.merk && $.inArray( this.laad, ['merk'] ) >= 0 ) {
				this.ele.merk.get(0).options.length = 0;
			}
			if ( this.ele.model && $.inArray( this.laad, ['merk', 'model'] ) >= 0 ) {
				this.ele.model.get(0).options.length = 0;
			}
			if ( this.ele.uitvoering && $.inArray( this.laad, ['merk', 'model', 'uitvoering'] ) >= 0 ) {
				this.ele.uitvoering.get(0).options.length = 0;
			}
			
			var n = 0;
			var targetEle = ( this.laad == 'merk' ? this.ele.merk : ( this.laad == 'model' ? this.ele.model : this.ele.uitvoering ) );
			if ( dataLijst.length == 0 ) {
				targetEle.get(0).options[0] = new Option( 'Geen '+( this.laad == 'merk' ? 'merken' : ( this.laad == 'model' ? 'modellen' : 'uitvoeringen' ) ), '' );
			} else {
				targetEle.get(0).options[0] = new Option( ( this.verplicht ? 'Selecteer...' : 'Geen voorkeur' ), '' );
				
				for ( var nr in dataLijst ) {
					var dataRow = dataLijst[ nr ];
					targetEle.get(0).options[ ++n ] = new Option( dataRow.naam, dataRow.link );
				}
			}
			targetEle.attr('disabled', ( n == 0 ) );
			
			if ( this.ele.merk.attr('disabled') || !this.ele.merk.val() ) {
				if ( this.ele.model ) {
					this.ele.model.attr('disabled', true).get(0).options[0] = new Option( ( this.verplicht ? 'Selecteer eerst een merk...' : 'Geen voorkeur' ), '' );
				}
			}
			if ( ( this.ele.merk.attr('disabled') || !this.ele.merk.val() ) || ( this.ele.model && ( !this.ele.model.val() || this.ele.model.attr('disabled') ) ) ) {
				if ( this.ele.uitvoering ) {
					this.ele.uitvoering.attr('disabled', true).get(0).options[0] = new Option( 'Selecteer eerst een '+( this.ele.model ? 'model' : 'merk' )+'...', '' );
				}
			}
		}
	} );
}

function trackKlik( ele, returnWaarde ) {
	if ( !ele || ( ele.nodeName != 'A' && ele.nodeName != 'IMG' ) || !$(ele).attr('class') ) {
		return true;
	}
	var expMatch = $(ele).attr('class').match( klkExp );
	$.ajax( { data: { trck: 'klk', id: expMatch[1] } } );
	
	if ( typeof returnWaarde != "undefined" ) {	
		return returnWaarde;
	}
	return trackReturn( ele );
}

function trackReturn( ele ) {
	if ( ele.nodeName == 'A' && ele.onclick && $(ele).attr('target') != '_blank' ) {
		if ( ele.onclick != 'undefined' && ele.onclick.toString().indexOf( 'return ' ) > 0 ) {
			return false;
		}
	}

	if ( ele.nodeName == 'IMG' || ( ele.nodeName == 'A' && ele.target == '_blank' ) ) {
		return true;
	}
	
	setTimeout( function() { document.location.href = ele.href; }, 200 );
	return false;
}

/**
 * Fixed element in een kader laten scrollen.
 */
function initFixedScroll() {
	fixedEle = $('.fixed');
	if ( fixedEle.length ) {
		// 1. Toppositie waar het element zich nu bevind.
		// 2. Toppositie waarop botsing optreed.
		fixedEle.attr('rel', fixedEle.offset().top+':'+( $('#collision').outerHeight() - fixedEle.outerHeight() ) );
		
		$(window).scroll( function() {
			scrollFixedElement();
		} );
		scrollFixedElement();
	}
}

/**
 * Fixed element scrollen.
 */
function scrollFixedElement() {
	var docScrollTop = $(window).scrollTop();
	var fixedExpl = fixedEle.attr('rel').split(':');
	
	if ( docScrollTop >= ( fixedExpl[0] - 10 ) ) {
		var fixedEleTop = ( docScrollTop - fixedExpl[0] + 10 );
		
		// Botsing
		if ( fixedEleTop >= fixedExpl[1] ) {
			fixedEle.stop().delay(200).animate( { top: fixedExpl[1]+'px' } );
		} else {
			fixedEle.stop().delay(200).animate( { top: fixedEleTop+'px' } );
		}
	} else {
		fixedEle.stop().delay(200).animate( { top: '0px' } );
	}
}

/**
 * Boxen gelijke hoogte geven.
 */
function initBoxfix() {
	$('.container.boxfix').each( function() {
		var maxHoogte = 0;
		var grootsteKolom = false;
		
		// Stap 1: grootste kolom berekenen.
		$('div[class^=grid-]', $(this) ).each( function() {
			var hoogte = $(this).outerHeight();
			if ( hoogte > maxHoogte ) {
				maxHoogte = hoogte;
				grootsteKolom = $(this);
			}
		} );
		
		// Stap 2: laatste box in de kleinere kolommen groter maken.
		$('div[class^=grid-]', $(this) ).not( grootsteKolom ).each( function() {
			var boxLaatste = $('.box:last', $(this));
			if ( boxLaatste.length ) {
				boxLaatste.css( { 'min-height': ( boxLaatste.height() + ( maxHoogte - $(this).height() ) ) } );
			} else {
				var boxLaatste = $('.boxsplit:last .inhoud', $(this));
				if ( boxLaatste.length ) {
					boxLaatste.css( { 'min-height': ( boxLaatste.height() + ( maxHoogte - $(this).height() ) ) } );
				}
			}
		} );
	} );
}

/**
 * Resultatenlijstfilters
 */
function initLijstFilters() {
	$('.filterlijst form[class*="]"][id]').submit( function() {
		var expMatch = $(this).prop('class').match( klkExp );
		if ( expMatch ) {
			$(this).unbind('submit');
			$.ajax( { data: { trck: 'klk', id: expMatch[1] } } );
			
			setTimeout( "$('#"+$(this).attr('id')+"').submit()", 300 );
			return false;
		}
		
		return true;
	} );


	// Filterlijst
	$('.filterlijst form:not([id=form-locatie]) select, #form-locatie #provincie').bind( 'change keyup', function() {
		$(this).parents('form').submit();
	} );
	
	// Locatie filters
	$('#form-locatie li').find('select, input:not(:radio)').bind( 'change keyup focus', function() {
		$(this).parents('li').find('input:radio').prop('checked', true);
	} );
}

/**
 * Autocomplete
 */
function initAutocomplete() {
	if ( $("#plaats").length ) {
		var acCache = {}, acLast;
		var acEmpty = '';
		$("#plaats").autocomplete( {
			source: function( request, response ) {
				var term = request.term;
				if ( term in acCache ) {
					response( acCache[ term ] );
					return;
				}
				
				if ( acEmpty.length > 0 && term.length > acEmpty.length && term.indexOf( acEmpty ) == 0 ) {
					acCache[ term ] = {};
					return;
				}
				
				$("#plaats").autocomplete( "option", "delay", 50 );
				acLast = $.getJSON( "/jx.php?lijst=plaats", request, function( data, status, xhr ) {
					if ( data.length == 0 ) {
						acEmpty = term;
					}
					
					acCache[ term ] = data;
					if ( xhr === acLast ) {
						response( data );
					}
				} );
			},
			delay: 400,
			minLength: 2,
			focus: function( event, ui ) {
				$("#plaats").val( ui.item.plaats );
				return false;
			},
			select: function(event, ui) {
				if ( !$(this).hasClass('ac-nosubmit') ) {
					$(this).val(ui.item.plaats).parents('form').submit();
				}
				return false;
			}
		} ).data("autocomplete")._renderItem = function( ul, item ) {
			return $("<li></li>").data("item.autocomplete", item).append('<a>'+item.plaats+' <span>('+item.provincie+')</span></a>').appendTo( ul );
		};
	}
}

/**
 * Formulier invoervelden met commentaar
 */
function initFormCommentaar() {
	$('form input:text[title], form textarea[title]').each( function() {
		$(this).attr('alt', $(this).attr('title')).attr('title', '');
	} ).blur( function() {
		if ( $(this).val() == '' ) {
			$(this).val( $(this).attr('alt') ).addClass('nonactief');
		}
	} ).bind('click focus', function() {
		if ( $(this).val() == $(this).attr('alt') ) {
			$(this).removeClass('nonactief').val('');
		}
	} ).trigger('blur');
	
	$('form input:text[alt], form textarea[alt]').parents('form').submit( function() {
		$('input.nonactief, textarea.nonactief', this).val('');
	} );
}

/**
 * Telefoonnummer
 */
function initTelefoonnummer() {
	$('a.telefoon').unbind('click').each( function() {
		$(this).attr('alt', $(this).attr('title')).attr('title', '');
	} ).click( function() {
		trackKlik( this, false );
		
		$(this).replaceWith( $(this).attr('alt') );
		return false;
	} );
}

function initHelpTooltip() {
	// Als tooltip
	if ( runHeavy && $.fn.qtip ) {
		$('#cntnrPage img.tticoon[class*="]"]').each( function() {
			var expMatch = $(this).attr('class').match( klkExp );
			
			$(this).qtip( {
				content: {
					text: '&nbsp;',
					ajax: {
						cache: true,
						url: '/jx.php?tooltip=help&get='+expMatch[1],
						success: function( data, status ) {
							if ( data ) {
								this.set('content.title.text', data.titel);
								this.set('content.text', '<div class="tt-help">'+data.tekst+'<\/div>');
							} else {
								this.set('content.title.text', 'Geen informatie');
								this.set('content.text', '<div class="tt-help">Er is geen informatie beschikbaar.<\/div>');
							}
						}
					}
				},
				position: {
					viewport: $(window)
				},
				show: {
					event: 'mouseover',
					solo: true
				},
				hide: 'mouseout',
				style: {
					classes: 'ui-tooltip-schaduw'
				}
			} );
		} );
	}
	
	// Als dialoog
	else {
		$('#cntnrPage img.tticoon[class*="]"]').click( function() {
			var expMatch = $(this).attr('class').match( klkExp );
			
			$.ajax( {
				data: { tooltip: 'help', get: expMatch[1] },
				success: function( data, status ) {
					var titel = ( data && data.titel ? data.titel : 'Geen informatie' );
					var tekst = ( data && data.tekst ? data.tekst : 'Er is geen informatie beschikbaar.' );
					$('#dialoog').dialog( { title: titel } ).html( '<div class="tt-help">'+tekst+'<\/div>' ).dialog('open');
				}
			} );
		} );
	}
}

/**
 * Occasion vergelijken
 */
function initVergelijken() {
	$('.lijst a.vergelijk').click( function( ) {
		if ( !$(this).hasClass('actief') ) {
			$(this).find('input:checkbox').each( function() {
				checkVergelijk( this, 1 );
			} );
			return false;
		}
	} );
	
	$('.lijst .vergelijk input:checkbox').unbind('click').click( function() {
		checkVergelijk( this, ( $(this).prop('checked') ? 1 : 0 ) );	
		return false;
	} );
}

/**
 * Vergelijk checkbox vink
 */
function checkVergelijk( Ele, Waarde ) {
	$.ajax( {
		data: 'occ=checklijst&nr='+$(Ele).attr('id').replace('itemchk-', '')+'&status='+Waarde,
		context: Ele,
		success: function() {
			$(this).prop('checked', !$(this).prop('checked'));
			if ( $(this).prop('checked') ) {
				$(this).parent().addClass("actief");
				$(this).parent().parent().addClass("actief");
			} else {
				$(this).parent().removeClass('actief');
				$(this).parent().parent().removeClass("actief");
			}
		}
	} );
}

/**
 * Navigatiegrid
 */
function initNavigatieGrid() {
	$('.navigatiegrid li a').click( function() {
		$('.navigatiegrid li').not(this).removeClass('actief');
		$(this).parent().addClass('actief');
	} );
	
	var docHash = ( typeof document.location.hash != "undefined" ? document.location.hash : false );
	if ( docHash ) {
		$('.navigatiegrid li a').each( function() {
			if ( $(this).attr('href').indexOf( docHash ) > 0 ) {
				$(this).parent().addClass('actief');
			} else {
				$(this).parent().removeClass('actief');
			}
		} );
	}
}

/**
 * Mededeling
 */
function initMededeling() {
	$('#mededeling').hide().slideDown('normal', function() {
		$(this).delay( 3500 ).fadeOut();
	} );
}
function toonMededeling( tekst, vast ) {
	$('#mededeling').remove();
	
	$('#cntnrPage').append('<div id="mededeling" style="display: none;"><div class="container">'+tekst+'<\/div><\/div>');
	if ( typeof vast != "undefined" && vast === true ) {
		$('#mededeling').slideDown('normal');
	} else {
		initMededeling();
	}
}
function setMededeling( tekst ) {
	if ( $('#mededeling').length == 0 ) {
		toonMededeling( tekst, true );
	} else {
		$('#mededeling .container').html( tekst );
	}
}
