var calculator = {
	totaal: 0,
	optietotaal: 0,
	nieuwprijs: 0,
	items: Array(),
	init: function( nieuwprijs ) {
		calculator.items = new Array();
		calculator.nieuwprijs = nieuwprijs;
		
		// Calculatorbox
		var calcHtml = '<div id="calculator">'
		+'<ul></ul>'
		+'<span class="label">Opties &amp; accesoires:</span> <span id="optietotaal">&euro; ' +calculator.formatValuta( calculator.optietotaal ) +'</span><br />'
		+'<span class="label">Nieuwprijs auto:</span> <span id="nieuwprijs">&euro; ' +calculator.formatValuta( calculator.nieuwprijs ) +'</span><br />'
		+'<div class="lijn"></div>'
		+'<span class="label">Totaalprijs:</span> <span id="totaal">&euro; ' +calculator.formatValuta( calculator.nieuwprijs ) +'</span>'
		+'</div>';
	
		// Extra wrapper om de calculator om box.js werkend te krijgen :)
		$(".kolomrechts").append( '<br /><div id="calculator-wrap"><div class="box box-wit pad-ver"><h2 class="kop">Opties &amp; accesoires calculator</h2>'+calcHtml+'</div></div>' );
		
		box.init( $('#calculator-wrap') );
		
		this.voegKnoppenToe();
		this.maakScrollable();
		this.maakCheckboxen();
		this.maakToolTip();
	},
	
	// Knoppen voor het tonen van de calculator
	voegKnoppenToe : function( ) {
		var knopHtml = '<div class="calculator-info" style="display: none;">Gebruik de calculator om uit te rekenen wat de nieuwprijs van deze auto is inclusief de door u aangevinkte opties.</div>'
		+'<img src="/images/knop/opties-en-accessoires-calculator-blauw.png" class="knop calcknop" onclick="calculator.toggle();" />';
		
		$("#pakketten table").after( knopHtml );
		$("#opties table").after( knopHtml );
		
		initKnopHover( '.box' );
	},
	
	// Calculatorbox scrollable maken
	maakScrollable: function() {
		//$("#pakketten h2").append( $("#pakketten").offset().top );
		if ( $("#pakketten").length > 0 ) {
			var offsetBox = $("#pakketten").offset().top;
		} else {
			var offsetBox = $("#opties").offset().top;
		}
		$(window).scroll( function () { 
			offsetDoc = $( document ).scrollTop();
			if ( offsetDoc > offsetBox ) {
				$('#calculator-wrap:visible').animate( { top: offsetDoc }, { duration: 700, queue: false, easing: 'easeOutCubic' } );
			} else {
				$('#calculator-wrap:visible').animate( { top: offsetBox }, { duration: 400, queue: false } );
			}
		} );
	},
	
	// Calculator box aan of uit. En initiële positionering calculator.
	toggle: function() {
		if ( $("#pakketten").length > 0 ) {
			offsetBox = $("#pakketten"); 
		} else {
			offsetBox = $("#opties");
		}
		
		$("#calculator-wrap").css( 'top', ( offsetBox.offset().top - 113 ) );
		if ( $('#calculator-wrap').is(':visible') ) {
			$('input.calccheckbox').fadeOut();
			$('#calculator-wrap').fadeOut();
		} else {
			$('input.calccheckbox').fadeIn();
			$('#calculator-wrap').fadeIn();
		}
	},
	
	// Tooltip bij een knop
	maakToolTip: function() {
		$('.calcknop').bind( 'mouseover focus', function() {
			$(this).parent().children('.calculator-info').fadeIn(150);
			$(this).bind( 'mouseout blur', function() {
				$(this).parent().children('.calculator-info').fadeOut(150);
			} );
		} );		
	},

	// Checkboxes renderen
	maakCheckboxen: function() {
		$('.pakket b').each( function() {
			var id = $( this ).attr('id');
			var naam = $( this ).html();
			var prijs = parseInt( $(this).parent().children('span.prijs').text().replace('.','') );
			
			$(this).replaceWith( '<input type="checkbox" id="'+id+'" name="'+naam+'" rel="'+prijs+'" class="calccheckbox" style="display: none;" /><label for="'+id+'"><b>'+naam+'</b></label>' );		
		} );
		
		$('.optie').each( function() {
			var id = $( this ).attr('id');
			var naam = $( this ).text();
			var prijs = $( this ).next( 'td' ).children( '.prijs' ).text().replace( '.', '' );
			
			$(this).replaceWith( '<th><input type="checkbox" id="'+id+'" name="'+naam+'" rel="'+prijs+'" class="calccheckbox" style="display: none;" /><label for="'+id+'">'+naam+'</label></th>' );
		} );
		
		// Calculator checkboxen event toevoegen.
		$('input.calccheckbox').bind( 'click', function() {
			calculator.getTotaal();
			calculator.getOmschrijvingen();
		});
	},
   
	// Naam van optie toevoegen aan calculatorbox
	getOmschrijvingen: function(){
		$('#calculator ul').html('');
		
		calculator.items.reverse();
		$.each( calculator.items, function() {
			$('#calculator ul').append( '<li>'+this+'</li>' );
		} );
		
		$('#calculator ul li').animate( { duration: 150, color: "#000000", queue: "add"} ).animate( { color: "#666666", queue: "add" } ).hover( 
			function() {
				$(this).animate( { duration: 50, backgroundColor: "#eef6fd", color: "#000000" } );
			},
			function() {
				$(this).animate( { duration: 50, backgroundColor: "#ffffff", color: "#666666"} );
			}
		);
	},
	
	// Totaal & subtotaal berekenen
	getTotaal: function(){
		calculator.optietotaal = 0 ;
		calculator.items = new Array();
		$('input.calccheckbox:checked').each( function ( i, ele ) { 
			// Prijs van de optie er bij optellen
			calculator.optietotaal += parseInt( $( ele ).attr('rel') );
			
			// Omschrijving laten zien
			calculator.items.unshift( "<span class='label'>"+$( ele ).attr('name') +"</span> <span class=\"prijs\">&euro; "+calculator.formatValuta( $( ele ).attr('rel') ) +"</span>" );
		});
		
		// Paketten langslopen
		var optieArray = new Array();
		$('#pakketten input.calccheckbox').each( function ( i, ele ) {
			$( ele ).parent().parent().parent().find('span[id^='+$(ele).attr('id')+']').each( function () {
				var spanId = $(this).attr('id').replace( $(ele).attr('id')+'-', '' );
				if ( ele.checked ) {
					optieArray.push( spanId );
					calculator.activeerOptie( '#'+spanId, false );
				} else if ( $.inArray( spanId, optieArray ) < 0 ) {
					calculator.activeerOptie( '#'+spanId, true );
				}
			} );
		} );
		
		calculator.totaal = ( calculator.optietotaal + calculator.nieuwprijs );
		
		$('#optietotaal').html( "&euro; "+calculator.formatValuta( calculator.optietotaal ) );
		$('#totaal').html( "&euro; "+calculator.formatValuta( calculator.totaal ) );
	},
	
	// Optie (de)activeren die al in een pakket zitten
	activeerOptie: function( EleId, Activeer ) {
		if ( !Activeer ) {
			$( EleId ).attr( 'checked', false );
		}
		$( EleId ).attr( 'disabled', !Activeer );
	},
	
	// Getal omzetten naar valuta
	formatValuta: function(number) {
        var nStr = '' + Math.round(parseFloat(number) * 100) / 100;
        var x = nStr.split('.');
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '.00';
        var rgx = /(\d+)(\d{3})/;
        while ( rgx.test( x1 ) ) {
            x1 = x1.replace(rgx, '$1' + '.' + '$2');
        }
        return x1;
   }
};

$(document).ready( function() {
	// Filterlijst
	$('.filterlijst select').bind( 'change keyup', function() {
		$( '#form-'+this.id.replace( new RegExp( 'min|max' ), 'minmax' ) ).submit();
	} );
	
	// Carrosserie tabel
	$('table.crs img').css('opacity', 0.5).hover(
		function() {
			$( this ).css('opacity', 1);
		},
		function() {
			if ( $( this ).parent().children('input:checked').val() == undefined ) {
				$( this ).css('opacity', 0.5);
			}
		}
	);
	
	$('table.crs img').click( function() { 
		$( this ).parent().children('input').attr('checked', 'checked' ) ;
		getAantalResultaten();
		
		$('table.crs img').css('opacity', 0.5 );
		$('table.crs label').css('font-weight', 'normal' );
		
		$( this ).parent().children('img').css('opacity', 1 );
		$( this ).parent().children('label' ).css('font-weight', 'bolder');
	});
	
	$('table.crs input').bind('change keyup', function() { 
		$('table.crs img').css('opacity', 0.5);
		$( this ).parent().children('img').css('opacity',1);
	} );
	
	
	// Energie-label
	$('img[class=energie-label]').css('opacity',0.5).hover(
		function() {
			$( this ).css('opacity', 1);
		},
		function() {
			if ( $( this ).next('input[type=radio]:checked').val() == undefined ) {
				$( this ).css('opacity', 0.5);
			}
		}
	);
	$('img[class=energie-label]').bind( 'click',function() { 
		$('img[class=energie-label]').css('opacity', 0.5);
		$( this ).css('opacity', 1);
		
		$( this ).next('input[type=radio]').attr( 'checked' ,'checked' );
		getAantalResultaten();
	});
	
	$('input[type=radio]').hide();
	$('input[id$=geen-voorkeur]').show();
	
	// Aantal resultaten weergeven 
	function getAantalResultaten(){
		
		$.ajax({
			data : $('#form-voorpagina').serializeArray( ),
			success: function(html){
		   	 $("#zoeken-ok").val(html +((html ==1)? ' resultaat gevonden': ' resultaten gevonden' ));
		 	 }
		});
	}
	
	$('#zoeken-ok').hover(
		function(){
			$( this ).addClass('hover'); 
		},
		function(){
			$( this ).removeClass('hover');
		}
	);

	$('#form-voorpagina, #form-voorpagina select').change( function() { getAantalResultaten() } )  ;
	
	// Merk selecteren
	$('#form-voorpagina #merk').bind( 'change keyup', function() {
		$.ajax( {
			data: 'lijst=autoinfo-model&merk='+this.value,
			success: function(lijst) {
				var eleLijst = $('#model')[0];
				eleLijst.options.length = 0;
				if ( lijst.length == 0 ) {
					eleLijst.options[0] = new Option('Geen modellen');
				} else {
					eleLijst.options[0] = new Option( 'Alle modellen', '');
					for ( var n in lijst ) {
						var modelRow = lijst[ n ];
						eleLijst.options[ ++n ] = new Option( modelRow.naam, modelRow.link );
					}
				}
			}
		} )
	} );
} );