var klkExp	 = new RegExp('\\[([a-z-0-9]+)\\]');
var bronExp  = new RegExp('site-([0-9]+)');
var runHeavy = true;
var pSetup 	 = {};
var fixedEle = {};

$(document).ready( function() {
	runHeavy = !( Math.round( jQuery.browser.version ) <= 6 && jQuery.browser.msie );
	$.ajaxSetup( {
		url: "/jx.php",
		global: false,
		type: "POST",
		dataType: "json"
	} );
	
	if ( runHeavy ) {
		initItemlijst();
		initCheckboxLijst();
	}
	initMededeling();
	
	$('a[class*="]"]').filter( function() { return $(this).attr('class').match( klkExp ); } ).click( function() { return trackKlik( this ); } );
	
	// Pagina
	if ( typeof( initPagina ) != 'undefined' ) {
		initPagina();
	}
	
	if ( !runHeavy ) {
		$('.knop.klein').addClass('knopklein');
		$('.knop.wit').addClass('knopwit');
	}
	
	initInfobox();
	initDialoog();
	initFormCommentaar();
	initZoekformulier();
	
	// Fixed element meescrollen
	if ( runHeavy ) {
		initTopmenu( false );
		initKnopAccesskey();
		initFixedScroll();
	}
	
	// Valuta
	$('input.valuta').keypress( function(e) { return valutaInvoer( e ); } );
	
	// Verwijder
	$('.lijst .icoon-kruis.js').click( function() {
		return confirm('Weet u het zeker dat u dit item wilt verwijderen?');	
	} );
	
	// Pagina eind
	if ( typeof( initPaginaEind ) != 'undefined' ) { 
		initPaginaEind();
	}
} );

/**
 * Vertaling
 */
function $_t( Id, Tekst ) {
	return ( typeof tekstArray !== 'undefined' && tekstArray[ Id ] ? tekstArray[ Id ] : Tekst );
}

/**
 * Valuta
 */
function valutaInvoer( e ) {
	var code = e.which;
	if ( ( code >= 48 && code <= 57 ) || code == 0 || code == 8 || code == 9 || code == 13 ) {
		return true;
	}
	return false;
}

function trackKlik( ele, returnWaarde ) {
	if ( !ele || ( ele.nodeName != 'A' && ele.nodeName != 'IMG' ) || !$(ele).attr('class') ) {
		return true;
	}
	var expMatch = $(ele).attr('class').match( klkExp );
	
	if ( $.inArray( expMatch[1], [ 'site-4', 'site-11' ] ) >= 0 ) {
		innoTrack( 'Sites', 'Tweedehands.net', pSetup.domein );
	} else if ( expMatch[1] == 'site-16' ) {
		innoTrack( 'Sites', 'Aanbodpagina.nl', pSetup.domein );
	} else if ( expMatch[1] == 'site-3' ) {
		innoTrack( 'Sites', 'Speurders.nl', pSetup.domein );
	}
	
	$.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;
}

function innoTrack( cat1, cat2, cat3 ) {
	var pageTracker = _gat._getTracker( pSetup.gaId );
	pageTracker._initData();
	pageTracker._trackEvent( cat1, cat2, cat3 );
}

/**
 * Accesskey karakter op knop onderlijnen.
 */
function initKnopAccesskey() {
	$('button.knop[accesskey], a.knop[accesskey]').each( function() {
		var eleHtml = $(this).clone();
		eleHtml.children().remove();
		var eleText = eleHtml.text().replace(/^s+/,'').replace(/s+$/,'');
		
		var eleAccesskeyText = eleText.replace( new RegExp( $(this).attr('accesskey'), "i" ), '<u>'+$(this).attr('accesskey')+'<\/u>' );
		$(this).html( $(this).html().replace( eleText, eleAccesskeyText ) );
	} );
}

/**
 * Standaarddialoog
 */
function initDialoog() {
	$('body').append( '<div id="dialoog" title="Dialoog"></div><div id="paginadialoog" title="Dialoog"></div>' );
	$('#dialoog, #paginadialoog').dialog( {
		autoOpen: false,
		width: 600,
		minHeight: 100,
		modal: true,
		resizable: false,
		draggable: false,
		open: function() {
			$('iframe, object').filter( function() {
				if ( $(this).parents('.ui-dialog').length ) {
					return false;
				}
				
				return true;
			} ).css( { visibility: 'hidden' } );
			
			$(this).parent().find('.ui-dialog-buttonset button').addClass('knop');
		},
		close: function() {
			$('iframe, object').css( { visibility: 'visible' } );
			$(this).html('');
		}
	} );
}

/**
 * Paginadialoog
 */
function showPaginadialoog( url, args ) {
	if ( typeof args !== "boolean" ) {
		pSetup.pDialoogArgs = args;
	}
	if ( typeof pSetup.pDialoogArgs.actieSucces !== "undefined" ) {
		pSetup.pDialoogArgs.actieSucces = false;
	}
	
	$.ajax( {
		url: url,
		data: $.param( $('input, select, textarea, button', $('#paginadialoog') ) ),
		success: function( data ) {
			$('#paginadialoog').dialog( 'option', 'title', data.titel ).html( data.html ).dialog('open');
			if ( typeof data.onload !== 'undefined' ) {
				$.globalEval( data.onload );
			}
			
			// Actie voltooid
			if ( pSetup.pDialoogArgs.actieSucces ) {
				if ( typeof pSetup.pDialoogArgs.onActieSucces !== 'undefined' ) {
					pSetup.pDialoogArgs.onActieSucces();
				}
				
				$('#paginadialoog a[href]').click( function() {
					$('#paginadialoog').dialog('close');
					return false;
				} );
				return;
			}
			
			$('#paginadialoog a[href]').click( function() {
				showPaginadialoog( $(this).attr('href'), true );
				return false;
			} );
			
			$('#paginadialoog form').submit( function() {
				showPaginadialoog( $(this).attr('action'), true );
				return false;
			} );
		}
	} );
}

/**
 * Items in de lijst.
 */
function initItemlijst() {
	$('.item').each( function() {
		$('.ft', $(this)).wrapInner('<a href="'+$('a', $(this)).attr('href')+'" target="_blank" class="'+$('a', $(this)).attr('class')+'"><\/a>');	
	} );
	
	jQuery('.bloklijst tbody td.item, .lijst tbody tr.item[id]').hover(
		function() {
			var itemNode = this.nodeName.toLowerCase();
			
			var itemRow = pSetup.itemArray[ jQuery(this).attr('id').replace('item-', '') ];
			if ( !itemRow ) {
				return;
			}
			
			// Provincie
			if ( itemNode == 'tr' && itemRow.prv ) {
				jQuery('td.loc', this).css( { backgroundImage: 'url(/images/provincie/'+itemRow.prv.lnd+'-'+itemRow.prv.lnk+'.png)' } );
			}			
			
			// Infobox
			jQuery('#infobox').stop().hide().height('auto').css('opacity', 1).width( ( itemNode == 'tr' ? 400 : jQuery(this).outerWidth() + 1 ) );
			jQuery('#infobox .content').html( getItemHTML( itemRow, this ) );
			jQuery('#infobox').attr('rel', '{"top": '+jQuery(this).offset().top+', "left": '+jQuery(this).offset().left+', "width": '+jQuery(this).outerWidth()+', "height": '+jQuery(this).outerHeight()+'}');
			
			// Foto eerst laden
			if ( itemRow.ft && typeof itemRow.ftload == "undefined" ) {
				itemRow.ftload = true;
				jQuery('#infobox .content .foto img').aeImageResize( { height: 140, width: jQuery(this).outerWidth() - 40 } );
				jQuery('<img rel="'+itemNode+'" />').load( function() {
					toonInfobox( ( jQuery(this).attr('rel') == 'tr' ? 'verticaal' : 'cirkel' ) );
				} ).attr('src', itemRow.ft);
			} else {
				toonInfobox( ( itemNode == 'tr' ? 'verticaal' : 'cirkel' ) );
			}
		},
		function() {
			jQuery('#infobox').attr('rel','').stop().hide();
			jQuery('td.loc', this).css( { backgroundImage: 'none' } );
		}
	).find('a').click( function() {
		$('#infobox').attr('rel','').stop().hide();
	} );
	
	// Foto verkleinen
	$('.item .ft img').aeImageResize( { height: 70, width: 70 } );
	
	// Opslaan van zoekopdracht
	$('.zoekopdrachtopslaan button[name=btnRegistreren]').click( function() {
		var eleEmail = $(this).closest('form').find('input[name=email]');
		eleEmail.trigger('clear');
		
		$.ajax( {
			data: { 'zoekopdracht': 'opslaan', 'email': eleEmail.val() },
			context: $(this).closest('form').get(0),
			success: function( data ) {
				var eleEmail = $(this).find('input[name=email]');
				
				if ( data.fout ) {
					$(this).find('.foutmelding').remove().end().prepend( '<div class="foutmelding"><div><ul><li>'+data.fout+'<\/li><\/ul><\/div><\/div>' );
					eleEmail.focus();
				} else {
					showPaginadialoog( '/'+data.actie+'.html?e='+eleEmail.val()+'&actie=zoekopslaan-'+pSetup.zoNr, {
						onActieSucces: function() {
							$('.zoekopdrachtopslaan form').remove();
						}
					} );
				}
			}
		} );
		
		return false;
	} );
}

/**
 * HTML genereren voor de infobox.
 */
function getItemHTML( itemRow, ele ) {
	var html = '';
	
	// Foto
	if ( itemRow.ft ) {
		html += '<div class="foto" style="height: 140px;"><img src="'+itemRow.ft+'" height="140" style="height: 140px;" /></div>';
	}
	
	// Omschrijving
	if ( itemRow.omschr ) {
		html += '<p>'+itemRow.omschr+'</p>';
	}
	
	html += '<table><tr>';
	html += '<td><ul>';
	
	// Prijs
	if ( $('.pr', ele).length ) {
		html += '<li><div>'+$_t( 'Tekst.PRIJS', 'Prijs' )+'</div>'+( $('.pr', ele).text().length ? $('.pr', ele).text() : '&nbsp;' )+'</li>';
	}
	
	// Plaats
	if ( $('.loc', ele).length ) {
		var afstand = $('.loc span', ele).text();
		html += '<li><div>'+$_t( 'Tekst.PLAATS', 'Plaats' )+'</div>'+$('.loc', ele).html().replace('<span>'+afstand+'</span>', '')+'</li>';
		if ( afstand.length ) {
			html += '<li><div>'+$_t( 'Tekst.AFSTAND', 'Afstand' )+'</div>'+afstand+'</li>';	
		}
	}
	
	// Provincie
	if ( itemRow.prv ) {
		html += '<li><div>'+$_t( 'Tekst.PROVINCIE', 'Provincie' )+'</div>'+itemRow.prv.nm+'</li>';
	}
	
	// Datum
	if ( itemRow.dt ) {
		html += '<li><div>'+$_t( 'Tekst.GEPLAATST', 'Geplaatst' )+'</div>'+itemRow.dt+'</li>';
	}
	
	// Extra informatie
	if ( itemRow.xtra ) {
		for ( veld in itemRow.xtra ) {
			html += '<li><div>'+veld+'</div>'+itemRow.xtra[ veld ]+'</li>';
		}
	}
	
	// Bron
	if ( bronMatch = $(ele).find('h3 a').attr('class').match( bronExp ) ) {
		html += '<li><div>'+$_t( 'Tekst.BRON', 'Bron' )+'</div>'+pSetup.siteArray[ bronMatch[1] ]+'</li>';
	}
	
	html += '</ul>';
	html += '</td>';
	
	// Provincie
	if ( itemRow.prv ) {
		html += '<td class="provincie"><img src="/images/provincie/'+itemRow.prv.lnd+'-'+itemRow.prv.lnk+'.png" alt="'+itemRow.prv.naam+'" /></td>';
	}
	
	html += '</tr></table>';
	
	return html;
}

/**
 * Informatiebox tonen
 */
function toonInfobox( kompas ) {
	if ( !$('#infobox').length || !$('#infobox').attr('rel').length ) {
		return;
	}
	
	var itemSet = $.parseJSON( $('#infobox').attr('rel') );
	var docSet  = { top: $(document).scrollTop(), left: $(document).scrollLeft(), width: $(window).width(), height: $(window).height() };
	var boxSet  = { width: $('#infobox').width(), height: $('#infobox').height() };
	var docOverflow = { noord: false, oost: false, west: false, zuid: false };
	var cssClassV = cssClassH = '';
	
	// Overflow: verticaal
	if ( kompas == 'verticaal' ) {
		// Noord
		if ( itemSet.top - boxSet.height < docSet.top ) {
			docOverflow.noord = true;
		}
		
		// Zuid
		if ( itemSet.top + itemSet.height + boxSet.height > docSet.top + docSet.height ) {
			docOverflow.zuid = true;
		}
	}
	
	// Overflow: cirkel
	else {
		// Noord
		if ( itemSet.top + ( itemSet.height / 2 ) - ( boxSet.height / 2 ) < docSet.top ) {
			docOverflow.noord = true;
		}
		
		// Oost
		if ( itemSet.left + itemSet.width + boxSet.width > docSet.left + docSet.width ) {
			docOverflow.oost = true;
		}
		
		// Zuid
		if ( itemSet.top + ( itemSet.height / 2 ) + ( boxSet.height / 2 ) > docSet.top + docSet.height ) {
			docOverflow.zuid = true;
		}
		
		// West
		if ( itemSet.left - boxSet.width < docSet.left ) {
			docOverflow.west = true;
		}
	}
	
	// CSS: verticaal
	if ( kompas == 'verticaal' ) {
		if ( docOverflow.noord ) {
			cssClassV = 'n';
			$('#infobox').css( { top: ( itemSet.top + itemSet.height - 6 )+'px' } );
		} else {
			cssClassV = 'z';
			$('#infobox').css( { top: ( itemSet.top - boxSet.height + 5 )+'px' } );
		}
		$('#infobox').css( { left: ( itemSet.left + ( itemSet.width / 2 ) - ( boxSet.width / 2 ) )+'px' } );
	}
	
	// CSS: cirkel
	else {
		if ( docOverflow.noord ) {
			cssClassV = 'n';
			$('#infobox').css( { top: ( itemSet.top + ( itemSet.height / 2 ) + 4 )+'px' } );
		} else if ( docOverflow.zuid ) {
			cssClassV = 'z';
			$('#infobox').css( { top: ( itemSet.top + ( itemSet.height / 2 ) - boxSet.height )+'px' } );
		} else {
			$('#infobox').css( { top: ( itemSet.top + ( itemSet.height / 2 ) - ( boxSet.height / 2 ) + 4 )+'px' } );
		}
		
		if ( !docOverflow.oost ) {
			cssClassH = 'w';
			$('#infobox').css( { left: ( itemSet.left + itemSet.width - 11 )+'px' } );
		} else {
			cssClassH = 'o';
			$('#infobox').css( { left: ( itemSet.left - boxSet.width )+'px' } );
		}
	}
	
	$('#infobox').attr('class', cssClassV+cssClassH ).delay( 400 ).fadeIn( 'fast' );
}

/**
 * Topmenu
 */
function initTopmenu( email ) {
	if ( email ) {
		var emailSplit = email.split('@');
		$('.topmenu li:eq(0)').html( '<a href="/user/" class="persoon"><strong>'+emailSplit[0]+'<\/strong>@'+emailSplit[1]+'<\/a>' );
		$('.topmenu li:eq(1)').html( '<a href="/logout.html">'+$_t( 'Tekst.UITLOGGEN', 'Uitloggen' )+'<\/a>' );
	} else {
		if ( typeof pSetup.zoNr !== "undefined" ) {
			$( 'a[href*=login], a[href*=register]', $('.topmenu') ).click( function() {
				if ( document.location.href.indexOf( $(this).attr('href') ) < 0 ) {
					showPaginadialoog( $(this).attr('href'), {} );
					return false;
				}
			} );
		}
	}
}

/**
 * Infobox
 */
function initInfobox() {
	$('body').append( '<div id="infobox"><div class="content"></div></div>' );
	$('#infobox').hide();
}

/**
 * Checkbox lijst.
 */
function initCheckboxLijst() {
	$('.lijst').each( function() {
		if ( !$('input:checkbox', $(this) ).length ) {
			return true;
		}
		
		$('thead th.check', $(this) ).html( '<input type="checkbox" />' );
		$('thead th.check input:checkbox', $(this) ).click( function() {
			$('.item input:checkbox', $(this).parents('.lijst') ).prop( 'checked', $(this).prop('checked') ).trigger('change');
		} );
	} );
}

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

/**
 * Fixed element scrollen.
 */
function scrollFixedElement() {
	var docScrollTop = $(window).scrollTop();
	var fixedExpl = fixedEle.attr('rel').split(':');
	
	if ( fixedExpl[1] > 0 && 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' } );
	}
}

/**
 * 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 clear', 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('');
	} );
}

/**
 * Zoekformulier
 */
function initZoekformulier() {
	$('#zoek .eenvoudig a').click( function() {
		if ( $('#zoek .uitgebreid').is(':visible') ) {
			$('#q').focus();
			$('#zoek #uz').val(0);
			$('#zoek .uitgebreid').slideUp('normal', function() { $('#zoek .eenvoudig').removeClass('uitgeklapt'); } );
		} else {
			$('#zoek .eenvoudig').addClass('uitgeklapt');
			$('#zoek .uitgebreid').slideDown('normal', function() { $('#zoek #uz').val(1); $('#rbr').focus(); });
		}
		return false;
	} );
	
	// Provincie of postcode
	$('#prv').focus( function() {
		$('#pc').attr( 'rel', $('#pc').val() ).val('');
	} );
	$('#pc').focus( function() {
		if ( !$(this).val().length ) {
			$(this).val( $(this).attr('rel') );
		}
		$('#prv option:eq(0)').attr('selected', 'selected');
	} ).blur( function() {
		$('#pc').attr( 'rel', $('#pc').val() );
	} );
	
	$('#pagina a[href*=uitgebreid-zoeken]').click( function() {
		$('#zoek .eenvoudig a').trigger('click');
		return false;
	} );
	
	// Rubrieken bij hoofdrubriek
	/*$('#hrbr').bind( 'change keyup', function() {
		$('#rbr').get(0).options.length = $('#srbr').get(0).options.length = 0;
		$('#rbr').get(0).options[0] = new Option( String.fromCharCode( 160 ), '' );
		$('#srbr').get(0).options[0] = new Option( String.fromCharCode( 160 ), '' );
			
		if ( $(this).val() ) {
			$.ajax( {
				data: 'lijst=rubriek&hrbr='+$(this).val(),
				success: function( data ) {
					if ( data.length > 0 ) {
						for ( var n in data ) {
							var row = data[ n ];
							$('#rbr').get(0).options[ ++n ] = new Option( row.naam, row.nr );
						}
					}
				}
			} );
		}
	} );
	
	// Subrubrieken bij rubriek
	$('#rbr').bind( 'change keyup', function() {
		$('#srbr').get(0).options.length = 0;
		$('#srbr').get(0).options[0] = new Option( String.fromCharCode( 160 ), '' );
			
		if ( $(this).val() ) {
			$.ajax( {
				data: 'lijst=subrubriek&rbr='+$(this).val(),
				success: function( data ) {
					if ( data.length > 0 ) {
						for ( var n in data ) {
							var row = data[ n ];
							$('#srbr').get(0).options[ ++n ] = new Option( row.naam, row.nr );
						}
					}
				}
			} );
		}
	} );*/
}

/**
 * Snelmenu
 */
function initSnelmenu() {
	$('#footer').hide();
	
	var snelmenuArray = $('*[id^=snelmenu-]');
	if ( snelmenuArray.length ) {
		$('body').append( '<div id="snelmenu"><ul></ul></div>' );
		
		snelmenuArray.each( function() {
			var titel = ( $(this).attr('title') ? $(this).attr('title') : $(this).text() );
			
			var liEle = $('<li>'+titel+'</li>');
			liEle.attr('id', $(this).attr('id')+'-li' ).hover(
				function() { $('#'+$(this).attr('id').replace('-li', '')).addClass('highlight'); },
				function() { $('#'+$(this).attr('id').replace('-li', '')).removeClass('highlight'); }
			).click( function() {
				$(document).stop().scrollTo( $('#'+$(this).attr('id').replace('-li', '')), 800 );
			} );
			
			$('#snelmenu ul').append( liEle );
		} );
	}
}

/**
 * CSS 'eerste'-klasse
 */
function setLijstEerste( eleLijst ) {
	$('tr', eleLijst).removeClass('eerste');
	$('tr:visible:eq(0)', eleLijst).addClass('eerste');
}

/**
 * Mededeling
 */
function initMededeling() {
	$('#mededeling').hide().slideDown('normal', function() {
		$(this).delay( 3500 ).fadeOut();
	} );
}
function toonMededeling( tekst, vast ) {
	$('#mededeling').remove();
	
	$('#pagina').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 );
	}
}
