function log(output){
	try { console.log(output); } catch(e) { 
		console = { log: function() {} } }
}
var shortversion = false;
var GAitems = new Array();

var qForm = {
	postUrl: '/form/ask-question/submit/',
	formId : 'question-form',
	start: 'step-product',
	current: null, // jquery object of the current fieldset;
	loadingIndicator : null,

	init : function(){
		if ( !$( '#'+this.formId).length == 1  ) return false;
		// Enable nav
		$('form#question-form .verstuur' ).show().bind('click', qForm.postForm);
		$('form#question-form input, select, textarea, radio' ).show().bind('blur', function () { checkRequiredFilled($(this)); } );
		$('#question-formFinished').hide();

		/********************
		 * 
		 * Extra options based on subject choice
		 * 
		 *******************/
		var opzegLi = $('#reden-opzeggen').parent('li').hide();
		// Show it when needed
		$('#betreft').change( function(){
			if( $(this).val() != 'opzegging' ){ opzegLi.hide(); }
			else{ opzegLi.show();}
		});

		// Attach event to Help icons to open helpdialogs
		$('#question-form a.form-help').bind('click', function(){ qForm.helpDialog.open( $(this) ); });

		// Captcha refresher
		$('#captcha-refresh').bind('click', function(){
			var now = new Date(); // random something to force image to be reloaded
			qForm.captchaUrl = $('#captcha').attr('src');
			$('#captcha').attr('src', qForm.captchaUrl + '?' + now.getTime() );
			return false;
		})
						
		// Also make sure it closes when clicked elsewhere in de body
		$(document.body).bind('click', function(e){  if( e.target.id != 'help-box' && $(e.target).parents('#help-box').length == 0 && !$(e.target).hasClass('form-help') ){	qForm.helpDialog.close();} });
	},
	
	postForm : function(){
		// check if all needed data is filled
		var errorStr = checkRequiredFormFilled('question-form');
		if (errorStr != '') {
			return;
		}
		// create data string
		var dataStr = '';

		var els = $('#question-form input, #question-form select, #question-form textarea, #question-form radio').each( function(){
			var el = $(this);
			if ( el.attr('type') == 'checkbox' ) {
				if (el.attr('checked')) dataStr += el.attr('name') + '=' + el.attr('value') + '&' ;
			} else if ( el.attr('type') == 'radio' ) {
				if (el.attr('checked')) dataStr += el.attr('name') + '=' + el.attr('value') + '&' ;
			} else {
				dataStr += el.attr('name') + '=' + el.attr('value') + '&' ;
			}			
		});
		
		$.ajax({
		    url: qForm.postUrl,
		    type: 'POST',
			data: dataStr,
		    dataType: 'text',
		    timeout: 10000,
		    error: function(){
		        notification.alert(regForm.connectionErrorMsg);
		    },
			
		    success: function(resp){
		        // do something with response
				if (resp == 'ok') {
					$('#question-form-explain').hide();
					$('#question-form').fadeOut('slow', function() { $('#question-formFinished').fadeIn() } );
				} else {
					notification.alert(resp);
				}
		    }
		});
	},
	helpDialog : {
		containerId : 'help-box',
		contentId : 'help-content',
		closeId : 'help-close',
		helpBox : null,

		_init : function(){
			// Create box and dialog container
			this.helpBox = $('<div></div>').attr('id', this.containerId).append( $('<div></div>').attr('id', this.contentId) )

			this.helpBox.append($('<a>x</a>').attr({ 'id' : this.closeId, 'title' : 'Sluiten' }).bind('click', function(){ qForm.helpDialog.close();}  ));
			$('body').append(this.helpBox);
		},
		// Trigger is JQ object
		open : function( trigger ){
			if(!this.helpBox){ this._init();}
			this.trigger = trigger;
			this._setPosAndWidth();
			this._setContent();
			this.helpBox.fadeIn();
			return false;
		},
		close : function(){
			if( this.helpBox ){	this.helpBox.hide();}
		},
		_setPosAndWidth : function(){
			var leftPos = this.trigger.offset().left
			this.helpBox.css('top', this.trigger.offset().top).css('left', leftPos);
			var sidebar = $('#sidecontent');
			var rightSide = sidebar.offset().left + sidebar.width();
			var width = rightSide - leftPos - 22; // Where 22 is the rightpadding of a contentbox, so that it doesn't overlap the shadow
			this.helpBox.css('width', width + 'px');
		},
		_setContent : function(){
			var childSpans = this.trigger.children('span');
			if(	childSpans.length != 1){return false;}
			this.helpBox.children('#' + this.contentId).html( childSpans.html());
		}
	}
}

var regForm = {
	postUrl: '/form/register/',
	formId : 'subscription-form',
	start: 'step-product',
	steps: { 1 : 'step-product', 2: 'step-gegevens', 3: 'step-financieel', 4: 'step-overzicht', 5: 'step-bevestiging'},
	current: null, // jquery object of the current fieldset;
	lastzipcode: '',
	lastlicense: '',
	isValidEUDate : true,
	isValidNLDate : true,
	isExistingClient : false, 
	
	priceRangeId : 0,
	
	connectionErrorMsg: 'Er kan op dit moment geen verbinding worden gemaakt met de server. Probeert u het op een later tijdstip nog een keer.',
	noPersonCarErrorMsg: 'Bij Route Mobiel kunnen alleen personenauto&#39;s en motoren worden aangemeld. Bedrijfsauto zijn uitgesloten. Gehandicapten met een bedrijfsauto zijn wel welkom bij Route Mobiel.',
	carIsTooOld: 'Bij Route Mobiel kunnen alleen auto&#39;s en motoren jonger dan 15 jaar worden aangemeld.',
	defaultFormError: 'onbekende fout',
	defaultUserErrorMsg: 'Er is een onbekende fout opgetreden bij het controleren van uw verzoek. Controleer a.u.b de ingevoerde gegevens. Wanneer het probleem zich blijft voordoen, kunt u op maandag tot en met vrijdag tussen 8.30 uur en 17.30 uur telefonisch contact opnemen met Route Mobiel via 0800-0504 (gratis).',
	generalDateError: 'U heeft een ongeldige ingangsdatum opgegeven voor een of meerdere Pechhulp Services. Vul a.u.b. de juiste datum in voordat u verder gaat.',
	licenseTwiceError: 'U kunt niet tweemaal hetzelfde kenteken aanmelden. Controleer a.u.b. het kenteken.',
	leaseLicenseSameError : 'Het kenteken waarmee u zich aanmeldt, mag niet hetzelfde zijn als het kenteken van uw lease-auto. Vul a.u.b. het juiste kenteken in.',
	invalidNLDateError : 'Voor Pechhulp Nederland Service geldt een wachttijd van 7 dagen. De eerstvolgende datum waarop uw Pechhulp Service kan ingaan is vandaag + 7 dagen. U kunt zich tevens maximaal 1 jaar vooruit aanmelden.',
	invalidEUDateError : 'Voor Pechhulp Europa Service geldt een wachttijd van 1 dag. De eerstvolgende datum waarop uw Pechhulp Service kan ingaan is morgen. U kunt zich tevens maximaal 1 jaar vooruit aanmelden.',
	zipcodeNotFoundError : 'Deze combinatie van postcode en huisnummer is onbekend.',
	
	init : function() {

		if ( !$( '#'+this.formId).length == 1  ) return false;
		
		// do a page track for the 'first' step
		if(pageTracker != undefined ){
			var link = '/Afsluiten/Kenteken invoer?';
			link += regForm.getStartUrlForPageTracker();			
			pageTracker._trackPageview( link );
		}
		
		// Hide all steps but the one to start with and show the form
		$('#'+this.formId + ' fieldset').hide();
		this.current = $('#'+this.formId + ' #'+this.start).show();
		$('form#subscription-form').show();

		// Enable autoAdvance on form inputs, jump to next input when maxLength is reached
		$('form#subscription-form').autoAdvance();

		// Enable nav
		$('form#subscription-form .prev').show().bind('click', regForm.goToPrevious);
		if (!shortversion){
			$('form#subscription-form .next').show().bind('click', regForm.goToNext);
			regForm.checkLicense();
		}else{
			$('form#subscription-form .next').show().bind('click', function(){
				
				extraParam = (typeof(eu) != 'undefined') ? '&europa=ja' : '';
				extraParam += (typeof(fl) != 'undefined') ? '&europatype=flex' : '';
				extraParam += (typeof(referer) != 'undefined') ? '&referer=' + referer : '';
				extraParam += (typeof(ref) != 'undefined') ? '&ref=' + ref : '';
				window.location.href = '/aanmelden?kenteken=' + $('#kenteken-1').val() + extraParam;
				return false;				
			});
		}
		$('#subscription-form ol#steps li').bind('click', regForm._goBackWithTopMenu );
		

		// Attach event to Help icons to open helpdialogs (and close)
		$('#subscription-form a.form-help').bind('click', function(){ regForm.helpDialog.open( $(this) ); });
		$(document.body).bind('click', function(e){  if( e.target.id != 'help-box' && $(e.target).parents('#help-box').length == 0 && !$(e.target).hasClass('form-help') ){	regForm.helpDialog.close();} });

		// Determine amount of vehicles to display 
		var vCount = $('#post-vehicle-amount').attr('value');	
		if(vCount > 1){
			regForm._showVehicle(2);
			$('#add-vehicle-2').hide();
			$('#add-vehicle-3').show();
			if ( vCount == 3){
				regForm._showVehicle(3);
				$('#add-vehicle-3').hide();
			}
		}
		// Make sure user can add more vehicles
		$('#add-vehicle-2').bind('click', function(){ 
			regForm._showVehicle(2);
			$(this).hide();
			$('#add-vehicle-3').show();
		});
		$('#add-vehicle-3').bind('click', function(){ 
			regForm._showVehicle(3);
			$(this).hide(); 
		});
		
		// recalculate the price when option or leaseOn/Off changes
		$('#step-product select').bind('change', regForm._doTotalPriceRequest);
		$('#nederland-1, #nederland-2, #nederland-3, #europa-1, #europa-2, #europa-3,#gebruikleasenee, #gebruikleaseja').bind('click', regForm._doTotalPriceRequest);
		
		if (!shortversion){	
			// Add event for checking car-license, returns brand and model			
			$('#kenteken-1, #kenteken-2, #kenteken-3').bind('keyup', regForm.checkLicense);
		}

		// Events for checking zipcode and housenumber, returns address and city
		$('#postcode_cijfers, #postcode_letters, #huisnr').bind('blur', regForm.checkZipcode);
		
		// Attach event to auto-correct date fields
		$('#geboorte_dag').bind('blur', function(){
			var formatted = regForm._correctDateField(  $(this).attr('value'), 'day' );
			$(this).attr('value', formatted );
		});
		$('#geboorte_maand').bind('blur', function(){
			var formatted = regForm._correctDateField(  $(this).attr('value'), 'month' );
			$(this).attr('value', formatted );
		});
		$('#geboorte_jaar').bind('blur', function(){
			var formatted = regForm._correctDateField(  $(this).attr('value'), 'year' );
			$(this).attr('value', formatted );
		});
		
		$('#gezinssamenstelling').bind('change', function(){
			// onchange on 'gezinssamenstelling', only show checkboxes when value ends with 'metkind' = 'withchildren'
			var val = $('#gezinssamenstelling option:selected').attr('value');
			if (val.indexOf('metkind') > -1) {
				$('#kindcategorie').show();
			} else {
				$('#kindcategorie').hide();
			}
		});

		$('#europa_ingang_1_Day, #europa_ingang_1_Month, #europa_ingang_1_Year, #nederland_ingang_1_Day, #nederland_ingang_1_Month, #nederland_ingang_1_Year').bind('change', function(){regForm._correctDateSelects(1, $(this))});
		$('#europa_ingang_2_Day, #europa_ingang_2_Month, #europa_ingang_2_Year, #nederland_ingang_2_Day, #nederland_ingang_2_Month, #nederland_ingang_2_Year').bind('change', function(){regForm._correctDateSelects(2, $(this))});
		$('#europa_ingang_3_Day, #europa_ingang_3_Month, #europa_ingang_3_Year, #nederland_ingang_3_Day, #nederland_ingang_3_Month, #nederland_ingang_3_Year').bind('change', function(){regForm._correctDateSelects(3, $(this))});

		// Make sure that on each click we check all field and adjust displaying according to the current setting ( and run it at start as well)
		$('#step-product input').bind('click', regForm._updateProductOptionsDisplay);
		$('#step-product select').bind('change', regForm._updateProductOptionsDisplay);
		regForm._updateProductOptionsDisplay();

		// pechhulpverlener uitklappen
		$('#pechhulpverlener-li').hide();
		$('#opzegservice-li input[type=radio]').click(function(e){
			if(this.value > 0){
				$('#pechhulpverlener-li').show();
			} else {
				$('#pechhulpverlener-li').hide();
			}
			this.blur();
		});

		/************
		 * 
		 * Ben al klant en wil tweede voertuig aanmelden
		 * 
		 ***********/
		var switchlink = $('#switch-to-existing'); 
		switchlink.click(function(){
			regForm.switchType('existing-client');
			$(this).parent('p').hide();
			return false;
		});
		$('.existing-client').hide();
		
		if( $('#subscribe-second').val() == '1'){ switchlink.click();}
		
		
	},
	switchType: function( formType){
		// Set the type so that we can access it later		
		if( formType != undefined && formType == 'existing-client'){
			this.isExistingClient = true;
			$('#is-existing-client').val('1');
		}else{
			$('#is-existing-client').val('0');
			this.isExistingClient = false;
		}
		
		$('#vehiclelicense-1, #vehicle-1-header, #add-vehicle-2, #add-vehicle-3').hide();
		$('#vehiclelicense-2,#vehicle-2-header').show();
		
		// Adjust Financial page
		$('.new-client').hide();
		$('.existing-client').show();
		$('#vehiclerelated-1').hide();
		$('#kenteken-1').val('').keyup();
		$('#vehicle-1').hide();
		regForm._doTotalPriceRequest();
		regForm._updateProductOptionsDisplay();
		
	},
	confirmBrowseAway : function(){
	    return "Let op: als u deze pagina verlaat, worden de gegevens in het formulier niet opgeslagen."	
	},
	checkLicense: function( param ){
	
		if ( param != undefined ){			
			var trigger = $(this);			
		}else{			
			var trigger = $('#kenteken-1');
		}
		
		var license = trigger.attr('value').replace(/\-/g, '').replace(/\ /g, '');
		var idx = trigger.attr('id');
		idx = idx.substr(idx.length - 1, 1);	
	
		var validLicence = true;
		// dont check if license if not fully filled yet
		if (license.length < 6 || !license.match(/\w/) ) {
			$('#merk-' + idx).attr('value', '');
			$('#type-' + idx).attr('value', '');
			validLicence = false;
		}else{
			// Make sure a user cannot fill in the same license twice
			for(var v = 1; v < 10; v++ ){
				if(  v!=idx && $('#kenteken-' + v ).attr('value') != undefined && $('#kenteken-' + v ).attr('value') == license ){
					notification.alert(regForm.licenseTwiceError);
					$(this).val('');
					validLicence = false;
				}
			}
		}

		if(!validLicence){
			$('#has-valid-license-' + idx).attr('value', '0');
			regForm._updateProductOptionsDisplay();
			return false;	
		}
	
		regForm._setLoading(true);
		$('#product-' + idx + ' option').remove();

		$.ajax({
		    url: '/form/checklicense',
		    type: 'POST',
		    data: "license=" + license,
		    dataType: 'json',
		    timeout: 10000,
		    error: function(){
				regForm._setLoading(false);
		        notification.alert(regForm.connectionErrorMsg);
		    },
		    success: function(resp) {
		    	
		    	regForm._setLoading(false);

				if (resp.connectionerror) {
					captcha.alert(idx, license);
					return;
				}
				if (resp.usererror) {
					notification.alert(resp.message);
					return;
				}
		        // do something with response
				regForm.lastlicense = idx + '_' + license;
				
		
			 	 // show warning when cartype cannot be certified
				var cartype = resp.data.carType;
				if (cartype != "personenauto" && cartype != "motorfiets") {
					notification.alert(regForm.noPersonCarErrorMsg);
					$('#kenteken-' + idx).attr('value', '');
					return;
				}

				// show error if age is older then 15 years				
				if (resp.data.isOlderThan15) {
					notification.alert(regForm.carIsTooOld);
					$('#kenteken-' + idx).attr('value', '');
					return;
				}

				regForm._showRightPrice( idx, resp.data.ageRange );
				
				// do a google pagetrack for polis keuze, but only for kenteken 1
				if(pageTracker != undefined && idx == 1 ){
					var link = '/Afsluiten/Keuze polis?';
					link += regForm.getStartUrlForPageTracker();					
					pageTracker._trackPageview( link );
				}

				removeError($('#kenteken-' + idx) );

				regForm.setLicenseData(idx, resp.data);

				// call function for calculating prices
				regForm._doTotalPriceRequest();
				regForm._updateProductOptionsDisplay();

		    }
		});
	},
	
	// In html all possible prices are present. Show the correct one here.
	_showRightPrice : function( idx, range ){

		// hide all priceranges
		$('span.pricerange', $('#vehicle-' + idx )).hide();

		var range = parseInt( range ); 
		if(  range > 0 ){
			$(	'#pricerange-' + idx + '-' + range).show();	
		}
		
	},
	_updateProductOptionsDisplay : function(){
		/***********************************************************
		* Check which elements should be shown and hidden (per step)
		************************************************************/
		regForm.isValidNLDate = true;
		regForm.isValidEUDate = true;
		
		for(var idx = 1; idx < 4; idx++){
			
			if( regForm.isExistingClient && idx != 2){
				continue;
			} 
			
			var validLicense = $('#has-valid-license-' + idx).attr('value') == 1 ? true : false;
			var caravanSelect = $('#europa-caravan-' + idx);
			var selectedCaravanText = $('#europa-caravan-' + idx + ' option:selected').text();// Yes or no


			// In case of a motorcycle we don't need to ask for transmission-type
			if( $('#categorie-' + idx).val() == 'motorfiets'){
				$('#handgeschakeld-' + idx).parent('li').hide();
			}else{
				$('#handgeschakeld-' + idx).parent('li').show();	
			}	
					
			if( validLicense){
				$('#vehiclerelated-' + idx).show();
				$('#vehicle-' + idx).show();
				
				// Nederland selected?
				if ($('#nederland-' + idx).attr('checked')) {
					$('#nederland-options-' + idx).show();
					
					// Validate start date (ingangsdatum)
					if (!regForm.isValidStartDate('NL', idx)){
						regForm.isValidNLDate = false;
						/*
						if ( $(this).attr('id') != 'nederland_ingang_' + idx + '_Month' && $(this).attr('id') != 'nederland_ingang_' + idx + '_Day'){
							// If user didn't change this manually, set date to first possible
							regForm.setToFirstPossibleDate('nl', idx);
							regForm.isValidNLDate = true;
						}
						*/
					}	
				} else {
					$('#nederland-options-' + idx).hide();
				}
				
				// Europa selected?
				if ( $('#europa-'+idx).attr('checked') ) {
					
					$('#europa-options-' + idx).show();
					
					// Set all europa products right
					var euroSelect = $('#europa-product-' + idx);
					var caravanOptions = [ {value:"0", name: "Nee"} , {value:"13", name: "Ja"} ];
					
					var euroIngangMaand = $('#europa_ingang_' + idx + '_Month');
					var euroIngangDag = $('#europa_ingang_' + idx + '_Day');
					var euroIngangJaar = $('#europa_ingang_' + idx + '_Year');
					
					var now  = new Date();
					var currentMonth = parseInt(now.getMonth()+1);
					var currentYear = parseInt(now.getFullYear());
					var currentDay = parseInt(now.getDate());
					

					if ( euroSelect.val() == 4 ){
						// Europa Jaar service
						euroIngangMaand.removeAttr('disabled');
						euroIngangDag.removeAttr('disabled');
						caravanOptions = [	{value:"0", name: "Nee"} ,	{value:"5", name: "Ja"}	];
						if( euroIngangJaar.val() == currentYear - 1){
							euroIngangJaar.val( currentYear );
						}

					}else{
						// Europa 3 maanden service
						euroIngangMaand.removeAttr('disabled');
						euroIngangDag.removeAttr('disabled');
						euroIngangDag.attr('disabled', 'disabled');
						euroIngangDag.val(1);
					}

					if( euroIngangJaar.val() == currentYear - 1){
						euroIngangJaar.val( currentYear );
					}

					// Update caravan selectbox with the right product id (cause depends on which eu-product)
					var options = '';
			
					for (var i = 0; i < caravanOptions.length; i++) {
						if (selectedCaravanText == caravanOptions[i].name ){
							options += '<option value="' + caravanOptions[i].value + '" selected="selected">' + caravanOptions[i].name + '</option>';
						}else{
							options += '<option value="' + caravanOptions[i].value + '">' + caravanOptions[i].name + '</option>';
						}
					}
					caravanSelect.html(options);
					
					if (!regForm.isValidStartDate('EU', idx  )){
						regForm.isValidEUDate = false;
					}
				} else {
					$('#europa-options-' + idx).hide();
				}
				
			}else{
				// No valid license
				$('#vehiclerelated-' + idx).hide();
				$('#vehicle-' + idx).hide();
			}
		}
		
	},
	setLicenseData: function(idx, d) {

		// Once the user has entered some information,
		// make sure he doesn't leave the form without being informed about possible loss of information
		if( window.onbeforeunload == null){
			window.onbeforeunload = regForm.confirmBrowseAway;	
		}
		
		$('#has-valid-license-' + idx).attr('value', '1');
		
		// show options for car: brand, type, kmstand etc
		$('#vehiclerelated-' + idx).show();

		// show product list
		$('#vehicle-' + idx).show();

		$('#merk-' + idx).attr('value', d.brand);
		$('#type-' + idx).attr('value', d.model);
		$('#merk-text-' + idx).html( d.brand);
		$('#type-text-' + idx).html( d.model);

		$('#kleur-' + idx).attr('value', d.color);
		$('#brandstof-' + idx).attr('value', d.fuelType);
		$('#categorie-' + idx).attr('value', d.carType);
		$('#bouwjaar-' + idx).attr('value', d.buildYear);
		$('#gewicht-' + idx).attr('value', d.weight);
	},

	checkZipcode: function() {
		var zipcode = $('#postcode_cijfers').attr('value') + $('#postcode_letters').attr('value');
		var number = $('#huisnr').attr('value');

		if(regForm.lastzipcode == (zipcode + number)){
			regForm.setStreetAndCityEditable(false);
			return false;
		}
		
		if (zipcode.length < 6 || number.length < 1 ) {
			regForm.setStreetAndCityEditable(true);
			return false;
		}
		
		regForm._setLoading(true);
		
		$.ajax({
		    url: '/form/checkzipcode',
		    type: 'POST',
		    data: "zipcode=" + zipcode + "&number=" + number,
		    dataType: 'json',
		    timeout: 10000,
		    error: function(){
		        notification.alert(regForm.zipcodeNotFoundError);
		        regForm._setLoading(false);
		        regForm.setStreetAndCityEditable(true);
		    },
		    success: function(resp){
		    	if( !resp.usererror ){
					regForm.lastzipcode = zipcode + number;

			        // do something with response
			        $('#straat').attr('value', resp.data.address);
			        $('#plaats').attr('value', resp.data.city);
			        regForm.setStreetAndCityEditable(false);
		    	}else{
		    		regForm.setStreetAndCityEditable(true);		
		    	}
		    
		    	regForm._setLoading(false);
		    	return;
		    		
		    }
		});
	},
	// functio can both enable and disable the street and city fields
	setStreetAndCityEditable: function( enable ){
		if( enable == undefined || !enable ){
			$('#plaats, #straat').attr('disabled', 'disabled');	
		}else{
			$('#plaats, #straat').removeAttr('disabled');
		}
		return;
	},
	goToNext: function(){
		// Do we pass javascript validation of step?
		if (!regForm._validateStep( regForm.current )){
			return false;
		}
		// move to next part of form MOVED TO _POSTFORMSTEP
		return false;
	},
	goToPrevious: function(){
		var prev = regForm.current.prev();

		if( prev.length == 1 ){
			regForm.current.hide();
			regForm.current = prev.fadeIn();
			regForm._updateProgress();
		}
		return false;
	},
	_goBackWithTopMenu : function(){
		// This function allows for going one or more steps back

		// Find out if it's a step backward or forward
		var toOpen = 'step-' + $(this).attr('class');
		var current = regForm.current.attr('id');
		if (current == 'step-bevestiging'){ /*  can't go back */
			return false;
		}
		var nr = null;
		var currentNr = null;
		for(var stepNr in regForm.steps ){
			if (regForm.steps[stepNr] == toOpen){
				nr = stepNr;
			}else if (regForm.steps[stepNr] == current){
				currentNr = stepNr;
			}
		}
		if (!nr || !currentNr ){return false;}

		var canDo = nr < currentNr ? true : false;
		if(canDo){
			regForm.current.hide();
			regForm.current = $('#' + toOpen).fadeIn();
			regForm._updateProgress();
		}else{
			return false;
		}
	},
	_setLoading: function( loading ){

		if ( !regForm.loadingIndicator ){
			// Create loading Element and append it to body
			regForm.loadingIndicator = $('<div></div>').attr('id', 'is-loading');
			regForm.loadingIndicator.append( $('<img />').attr({'src' : '/img/loading.gif', 'id': 'loading-icon' } ));
			$('body').append( regForm.loadingIndicator );
		}

		if(loading){
			// reset height and width based on current form height
			var form = $('form#subscription-form');
			var l = form.offset().left;
			var t = form.offset().top;
			var w = form.width();
			var h = form.height();
			regForm.loadingIndicator.css( { height: h+'px', width: w+'px' , left: l, top: t });
			regForm.loadingIndicator.show();
		}else{
			regForm.loadingIndicator.hide();
		}

	},
	_doTotalPriceRequest : function(e){

		var dataStr = regForm._buildDataString();
		
		$.ajax({
		    url: '/form/calculateproducts',
		    type: 'POST',
		    data: dataStr,
		    dataType: 'json',
		    timeout: 10000,
		    error: function(){
		        notification.alert(regForm.connectionErrorMsg);
		    },
		    success: function(resp){
		        // do something with response	
		
				if (resp.connectionerror == false && resp.usererror == false && resp.data.field == 'total-price' ) {						
					regForm._setTotalPrice( resp.data.value  );
				}
		    }
		});
	},
	_hasValidProductStartDates: function(){
		if(regForm.isValidEUDate !=undefined && regForm.isValidNLDate != undefined && regForm.isValidEUDate && regForm.isValidNLDate){
			return true;
		}
		return false;
		
	},
	_showVehicle : function(idx){
		$('#vehiclelicense-' + idx).show();
		$('#vehicle-' + idx + '-header').show();
	},
	_setPrice : function(id, nr, value){
		// Update the displayed price for a field
		$('#' + id + '-price-' + nr).html( this._Float2Euro(value) );
	},
	_postFormStep : function(step, tab_id){

		// opzeg service popup
		if(step == 'contact' && $('#opzegservice-ja').attr('checked')){
			if(!phvoPopup.ready){

				var contentId = '';
				if($('#huidigepechhulpverlener').val() == 'anwb'){
					contentId = 'phvo-anwb-1';
				} else {
					contentId = 'phvo-overige-1';
				}
				phvoPopup.init();
				quitProviderPopup.show();
				phvoPopup.show(contentId);
				return false;
			}
		}

		regForm._setLoading(true);
		dataStr = regForm._buildDataString();

		$('#subscription-form input, #subscription-form select, #subscription-form radio, #subscription-form textarea .error').each ( function(){
			removeError($(this));
		} );

		if(step == 'products'){
			if( !regForm._hasValidProductStartDates()){
				var str = '<p><br />De eerst mogelijke ingangsdatum voor Nederland Service is: ' + $('#nl-range-start').val() +  '<br />' 
						  + '<br />De eerst mogelijke ingangsdatum voor Europa Service is: ' + $('#eu-range-start').val() +  '<br /></p>' ;
				notification.alert(regForm.generalDateError + str);
				
				regForm._setLoading(false);
				return;
			}
		}

		$.ajax({
		    url: regForm.postUrl + step,
		    type: 'POST',
			data: dataStr,
		    dataType: 'json',
		    timeout: 31000,
		    error: function(){
		        notification.alert(regForm.connectionErrorMsg);
		        regForm._setLoading(false);
		    },
		    success: function(resp){
		    	regForm._setLoading(false);

				if (resp.usererror == true) {
			    	regForm._handleFormErrors(resp);
					return false;

				} else if (resp.usererror == false && resp.connectionerror == false) {
					// no errors found, show next part of form (fieldset)
					var next = regForm.current.next();
					if( next.length == 1 && next.attr('tagName') == 'FIELDSET'){
						
						if(pageTracker != undefined && next.attr('id') != '' ){
							var link = '/Afsluiten/';							
							link += regForm.getStepStringForPageTracker();
							link += '?';
							link += regForm.getStartUrlForPageTracker();
							link += regForm.getProductStringForPageTracker();
							pageTracker._trackPageview( link );
						}
						regForm.current.hide();
						regForm.current = next.fadeIn();
					}

					regForm.runEyeBlasterTracker(step);
					
					if (step == "payment") {
						regForm._buildOverview();
	
					}else if (step == "save"){	
						
						// remove notification when leaving the form
						window.onbeforeunload = null;
						
						regForm.runCheckitCounter();
						regForm.makeAdwordsCall();
						regForm.makeGATransactionCall();
						if (referer == "OMG") {
							regForm.runOMGTracker();
						}else if (referer == "DC") {
							regForm.runDCTracker();						
						}	
					}			
					
					regForm._updateProgress();
				}
		    }
		});
	},
	_buildDataString : function(){

		// create data string
		var dataStr = '';
		var els = $('#subscription-form input, #subscription-form select, #subscription-form radio').each( function(){
			var el = $(this);

			if ( el.attr('type') == 'checkbox' ) {
				if (el.attr('checked')) dataStr += el.attr('name') + '=' + el.attr('value') + '&' ;
			} else if ( el.attr('type') == 'radio' ) {
				if (el.attr('checked')) dataStr += el.attr('name') + '=' + el.attr('value') + '&' ;
			} else
				dataStr += el.attr('name') + '=' + el.attr('value') + '&' ;
		});
		return dataStr;
		
	},
	/*
	*	Handle ajax form post response when an error has ocurred
	*/
	_handleFormErrors : function( resp ){

		// Highlight errors
		// Special thing built in, to show only 1 error about birthday (not 1 for each field)
		if (resp.data.length > 0) {
			var birthdayErrorAdded = false;
			var mailAdded = false;
			var errArr = new Array();
			for(var i = 0; i < resp.data.length; i++) {
				if( resp.data[i].message != undefined ){
					errArr.push(resp.data[i].message);
				}else{
					errArr.push(regForm.defaultFormError);
				}
				// always hightlight error in form
				showError($('#' + resp.data[i].field)); 
			}
			
			var more = false;
			var errList = '<ul>';
			var addedErrors = new Array(); // keep track of the messages we've already dded
			for( var e= 0; e < errArr.length; e++){
				if( e == 6){
					var more = errArr.length - e;
					break;
				}
				if (jQuery.inArray(errArr[e], addedErrors) > -1 )continue;
				
				errList += '<li>' + errArr[e] + '</li>';
				addedErrors.push(errArr[e]);
			}
			if( more ){
				errList += '<li>En ' + more + ' andere fouten</li>' ;	
			}
			errList += '</ul>';
			notification.alert( errList );
			
		}else{
			notification.alert( regForm.defaultUserErrorMsg );
			
		}
		return false;
	},
	_setTotalPrice : function(price){
		$('#total-price').html(regForm._Float2Euro( price ) );
	},
	_buildOverview: function() {
		regForm._setLoading(true);

		$('#step-gegevens .text, #step-gegevens input:checked, #step-financieel .text').each( function() {
			var val = $(this).attr('value');
			if (val.length < 1) {
				if($(this).attr('name') != 'toevoeging'){
					$('#overzicht_' + $(this).attr('name')).parent('li').hide();	
				}
			} else {
				$('#overzicht_' + $(this).attr('name')).parent('li').show();
				$('#overzicht_' + $(this).attr('name')).html(val);
			}
		});

		for (var idx = 1; idx < 4; idx++) {
			var kenteken = $("#kenteken-" + idx).attr('value').replace(/\-/g, '').replace(/\ /g, '');
			if (kenteken.length < 6) {
				$('#overzicht_vehicle-' + idx).hide();
			} else {
				$('#overzicht_vehicle-' + idx).show();

				$('#overzicht_kenteken-' + idx).html($("#kenteken-" + idx).attr('value'));
				$('#overzicht_merk-' + idx).html($("#merk-" + idx).attr('value'));
				$('#overzicht_type-' + idx).html($("#type-" + idx).attr('value'));

				if ($("#handgeschakeld-" + idx).attr('checked')) {
					$('#overzicht_transmissie-' + idx).html('handmatig');
				} else {
					$('#overzicht_transmissie-' + idx).html('automatisch');
				}

				if ($("#gebruikleaseja").attr('checked')) {
					$('#overzicht_leasekenteken').parent('li').show();
					$('#overzicht_leasemaatschappij').parent('li').show();
					$('#overzicht_leaserijder').parent('li').show();

					$('#overzicht_gebruiklease').html('Ja');
					$('#overzicht_leasekenteken').html($('#leasekenteken').attr('value'));
					$('#overzicht_leasemaatschappij').html($('#leasemaatschappij').attr('value'));
					$('#overzicht_leaserijder').html($('#leaserijder').attr('value'));
				} else {
					$('#overzicht_gebruiklease').html('Nee');
					$('#overzicht_leasekenteken').parent('li').hide();
					$('#overzicht_leasemaatschappij').parent('li').hide();
					$('#overzicht_leaserijder').parent('li').hide();
				}

				$('#overzicht_product-' + idx).html($("#product-" + idx +" option:selected").text());
				$('#overzicht_product-price-' + idx).html($('#product-price-' + idx).html());
			}
		}
		
		var dataStr = regForm._buildDataString();
		
		$.ajax({
		    url: '/form/calculateproducts2',
		    type: 'POST',
		    dataType: 'json',
		    data: dataStr,
		    timeout: 60000,
		    error: function(){
		        notification.alert(regForm.connectionErrorMsg);
		        regForm._setLoading(false);        
		    },
		    success: function(resp){
		    	regForm._setLoading(false);
				if (resp.usererror == false && resp.connectionerror == false) {
					$('#overview-pricetable').html(resp.data);
				} 
		    }
		});
		
		//regForm._updateProgress();
		regForm._validateOverview();

	},
	// convert 1 to 01 and 82 to 1982
	_correctDateField : function( value, type ){

		switch(type){
			case 'month': case 'day':
				if ( value.length ==1 ){
					value = '0' + value;
				}
				break;
			case 'year':
				if (value.length == 2){
					value = '19' + value;
				}
				break;
			default:
				break;
		}
		return value;
	
	},
	_correctDateSelects: function( idx, triggerEl){
				
		var id = triggerEl.attr('id');
		var prefix = id.indexOf('europa') > -1 ? 'europa': 'nederland';
		
		var day = $('#' + prefix + '_ingang_' + idx + '_Day');
		var month = $('#' + prefix + '_ingang_' + idx + '_Month');
		var year = $('#' + prefix + '_ingang_' + idx + '_Year');
		
		if( id.indexOf('Month') > -1 || id.indexOf('Year') > -1 ){
			// mmz could be done better, but needed quick and dirty
			var days = 0;
			var m = month.val();
			if ( m == 1 || m == 3 || m == 5 || m == 7|| m == 8 || m == 10 || m == 12){	days = 31; }
			else if (m == 2){	
				if( year.val()%4 == 0 ){
					days = 29;
				}else{	days = 28;}
			}else{ days = 30;}
			
			var curSelected = day.val();
			day.html('');
			// todo: remeber selected
			var options = '';
			for (var i=1; i<=days;i++){
				if( i != curSelected){
					options+= '<option value="' + i + '">' + i + '</option>';	
				}else{
					options+= '<option value="' + i + '" selected="selected">' + i + '</option>';
				}
			}
			day.html(options);
		}
	},
	isValidStartDate: function(type, idx ){
		
	
		if(type == 'NL'){

			var rangeStart = regForm.createDateFromDutchFormat($('#nl-range-start').val());
			var rangeEnd = regForm.createDateFromDutchFormat($('#nl-range-end').val());
			
			// get date set by user
			var day = $('#nederland_ingang_'+ idx + '_Day').val().replace(/^(\d)$/, "0$1");
			var month = $('#nederland_ingang_'+ idx + '_Month').val().replace(/^(\d)$/, "0$1");
			var year = $('#nederland_ingang_'+ idx + '_Year').val();
			var selected = regForm.createDateFromDutchFormat( day + '-' + month + '-' +  year);
			
		}else if(type=='EU'){
			return true;
		}
		
		if ( selected < rangeStart || selected > rangeEnd  ){
			return false;
		}else{
			return true;
		}
	},	
	setToFirstPossibleDate: function(type, idx){

		type = type.toLowerCase();
		if(type == 'eu'){
			var firstPossibleDate  = regForm.createDateFromDutchFormat($('#eu-range-start').val());	
			$('#europa_ingang_' + idx + '_Day').val( firstPossibleDate.getDate() );
			$('#europa_ingang_' + idx + '_Month').val( firstPossibleDate.getMonth()+1 );
			$('#europa_ingang_' + idx + '_Year').val( firstPossibleDate.getFullYear() );
		}else if( type == 'nl'){
			var firstPossibleDate  = regForm.createDateFromDutchFormat($('#nl-range-start').val());
			$('#nederland_ingang_' + idx + '_Day').val( firstPossibleDate.getDate() );
			$('#nederland_ingang_' + idx + '_Month').val( firstPossibleDate.getMonth()+1 );
			$('#nederland_ingang_' + idx + '_Year').val( firstPossibleDate.getFullYear() );
		}
	},
	// string in form 14-04-2008
	createDateFromDutchFormat: function(str){
		var date = new Date();
		date.setFullYear( str.substring(6,10) );
		var month = parseInt(str.substring(3,5) - 1); // january = 0 in JS
		date.setMonth( month );
		date.setDate( str.substring(0,2) );
		return date;
	},
	_Float2Euro : function(f){
		f = f.toString();
		if(f.indexOf('.') > -1) {
			var v = f.split('.')[0];
			var n = f.split('.')[1];
			if ( n.length == 1 )
				return v + ',' + n + '0';
			else if (n.length == 2)
				return v + ',' + n;
		 }else {
			return f + ',00';
		 }
	},
	_toggleField: function(selector, enable){ // selector can be comma-seperated to select multiple li's
		if (enable) 	$(selector).removeClass('disabled');
		else			$(selector).addClass('disabled');
	},
	_validateStep : function (step){ // checkfields and save progress to session through ajax

		var errors = new Array();
		var ajaxUrl = '';

		switch(step.attr('id')) {
			case 'step-product':
				ajaxUrl = 'products';
				break;
			case 'step-gegevens':
				ajaxUrl = 'contact';
				break;
			case 'step-financieel':
				ajaxUrl = 'payment';
				break;
			case 'step-save':
				ajaxUrl = 'save';
				break;
			case 'step-bevestiging':
				ajaxUrl = 'send';
				break;
		}
		if (errors.length == 0) {
			this._postFormStep(ajaxUrl, step.attr('id'));
			return true;
		} else {
			for (var i=0; i< errors.length; i++){
				showError(errors[i]);
			}
		}

		return false;
	},

	_validateOverview: function() {

		regForm._setLoading(true);

		$.ajax({
		    url: regForm.postUrl + 'overview',
		    type: 'POST',
		    dataType: 'json',
		    timeout: 60000,
		    error: function(){
		        notification.alert(regForm.connectionErrorMsg);
		        regForm._setLoading(false);  
		        // If there's something wrong here, user shouldn't be able to press confirm
		        
		    },
		    success: function(resp){
		    	regForm._setLoading(false);
				if (resp.usererror == false && resp.connectionerror == false) {

				} 
		    }
		});
	},
	_updateProgress: function(){
		var fieldsetId = this.current.attr('id');
		var menuClass = fieldsetId.replace('step-', '');
		$('#subscription-form ol#steps li').each( function(){
			if(!$(this).hasClass( menuClass ) ){
				$(this).removeClass('current');
			} else {
				$(this).addClass('current');
			}
		});
	},

	_getCurrentFieldset: function(){
		return $('#'+this.formId + ' #' + this.current);
	},
	runCheckitCounter: function(){
		var csetConversion = 297;
		var csetHost = 'www.routemobiel.nl';
		var csetDate = new Date();
		var csetImage = new Image();

		var csetCounterUrl = 'http://www.searchenginetracking.nl/pageview.ashx?host=' + escape(csetHost);
		if(document.location!=null && document.location.protocol!=null && document.location.protocol == "https:"){csetCounterUrl = 'https://www.searchenginetracking.nl/pageview.ashx?host=' + escape(csetHost);}
		csetCounterUrl += document.location!=null?'&url=' + escape(document.location):'';
		csetCounterUrl += document.referrer!=null?'&referrer=' + escape(document.referrer):'';
		if (typeof csetConversion != "undefined" && csetConversion != null){csetCounterUrl += '&conversion=' + csetConversion;}
		if (typeof csetCategory != "undefined" && csetCategory != null && csetCategory != ""){csetCounterUrl += '&category=' + escape(csetCategory.replace(' ', '%20'));}
		if (typeof csetQuantity != "undefined" && csetQuantity != null && csetQuantity != 0){csetCounterUrl += '&quantity=' + csetQuantity;}
		if (typeof csetAmount != "undefined" && csetAmount != null && csetAmount != 0){csetCounterUrl += '&amount=' + csetAmount;}
		csetCounterUrl += "&time=" + csetDate.getTime();
		csetImage.src = csetCounterUrl;
	},
	getStartUrlForPageTracker: function() {
		var res = '';		
		res += 'startUrl='+$('#startUrl').val();		
		return res;
	},
	// get step string for pagetracker
	getStepStringForPageTracker: function(){
		if (!regForm.current) return '';
		var next = regForm.current.next();		
		var step = next.attr('id').replace('step-', '');
		var res = '';
		if (step == 'gegevens') {
			res = 'Gegevens';
		} else if (step == 'financieel') {
			res = 'Financieel';
		} else if (step == 'save') {
			res = 'Overzicht';
		} else if (step == 'bevestiging') {
			res = 'Bevestiging';
		}
		return res;
	},
	
	// get product string for pagetracker call
	getProductStringForPageTracker: function(){
		var res = '&Polis=';
		var nrs = new Array(1,2,3); 
		var total = 0;
		var nlfound = false; // nl should only be counted once,so we keep track if it is already found
		for ( j in nrs ){
			i = nrs[j];
			if ( $('#vehicle-' + i).css('display') == 'block') {
				if ( $('#nederland-' + i).attr('checked') == true){ 
					res += 'NL' + i + '+';
					if (!nlfound) {
						nlfound = true;
						total++;
					}
				}
				if ( $('#europa-' + i).attr('checked') ){
					if ( $('#europa-product-' + i).val() == '4') { 
						res += 'EUjaar' + i + '+'
						total++; 
					}
					if ( $('#europa-product-' + i).val() == '12') { 
						res += 'EUkort' + i + '+'
						total++; 
					}
				}
			}
		}		
		res += '&Aantal=' + total;
		
		// gezinssamenstelling en nieuwsbrief checken
		if ( $('#gezinssamenstelling :selected').val() != '') {
			res += '&Gezinssamenstelling=' + escape($('#gezinssamenstelling :selected').text().replace(' ', '_'));
		}
		if ( $('#aanbiedingen').attr('checked')) {
			res += '&Nieuwsaanbiedingen=Ja';		
		}		
		return res;
	},
	
	runOMGTracker: function(){
		// Determine activityId
		var hasNL = $('#nederland-1').attr('checked');		
		var hasEU = $('#europa-1').attr('checked');		
		var yearContract = $('#europa-product-1').val() == '4' ? true : false; // False means it's a quarter contract
		var email = $('#email').attr('value');  //for ordernr 

		var codes = new Array();
		if( hasNL ){
			codes.push('8397');
		}
		if (hasEU) {
			if (yearContract) {
				codes.push('8257');
			} else {
				codes.push('8259');
			}
		}
		
		for( var code in codes) {
			var curcode = codes[code];
			var image = new Image();
			var imageUrl = 'http://www.site-id.nl/nd_servlet/___?action=action&final=http%3A%2F%2Fwww-'+curcode+'.site-id.nl%2Fnetdirect%2Fimages%2Ftrans.gif&cols=volgnr&cid='+curcode+'&volgnr=' + email;
			image.src = imageUrl;
		}
		return true;		
	},
	runDCTracker: function(){
		// Determine activityId
		var hasEU = $('#europa-1').attr('checked');		
		var yearContract = $('#europa-product-1').val() == '4' ? true : false; // False means it's a quarter contract
		var email = $('#email').attr('value');  //for ordernr 

		var links = new Array();
		
		if (hasEU) {
			if (yearContract) {
				links.push('http://ds1.nl/t/?si=1958&ti='+email+'&oa=12mnd_europa&om=12mnd_europa&ai=19814');
				links.push('http://www-8332.site-id.nl/nd_servlet/___?action=action&final=http%3A%2F%2Fwww-8332.site-id.nl%2Fnetdirect%2Fimages%2Ftrans.gif&cols=volgnr&cid=8332&volgnr='+email);
			} else {
				links.push('http://ds1.nl/t/?si=1958&ti='+email+'&oa=3mnd_europa&om=3mnd_europa&ai=19810');
				links.push('http://www-8333.site-id.nl/nd_servlet/___?action=action&final=http%3A%2F%2Fwww-8333.site-id.nl%2Fnetdirect%2Fimages%2Ftrans.gif&cols=volgnr&cid=8333&volgnr='+email);
			}
		}
		
		for( var link in links) {
			var image = new Image();
			image.src = links[link];
		}
		return true;		
	},
	runEyeBlasterTracker: function(step){

		// EDIT: removed because now NL only also had an id
		// Only continue if Europe service was chosen
		//if (!$('#europa-1').attr('checked')){
		//	return false;
		//}
		var activityId = 0;
		switch(step) {
			case 'products':
				activityId = 74339;
				break;
			case 'contact':
				activityId = 74340;
				break;
			case 'payment':
				activityId = 74341;
				break;
		}
		
		if (step == 'save') {
			// Determine activityId
			var hasNL = $('#nederland-1').attr('checked');		
			var hasEU = $('#europa-1').attr('checked');
			var yearContract = $('#europa-product-1').val() == '4' ? true : false; // False means it's a quarter contract
			var caravan = $('#europa-caravan-1').val() == '5' ? true : false;
			
			if( hasNL ){
				if (!hasEU) {
					activityId = 74205;
				} else if( yearContract ){
					// BOTH EUROPA AND NL
					activityId = caravan ? 54719 : 54722; 
				}else{
					activityId = caravan ? 54721 : 54718; 
				}
				
			}else{
				
				// EUROPA ONLY
				if( yearContract ){
					activityId = caravan ? 54717 : 54715; 
					
				}else{
					activityId = caravan ? 54716 : 54418; 
				}
			}
		
			// Pervorm tracking
			//if (activityId == 74205) {
				// on the thank you page, there is a problem with document write in the javascript file in firefox. 
				// it is loaded directly as image here to circumvent the problem 
	
			var image = new Image();
			var src0 = 'http://atemda.com/LeadTracking.ashx?tpt=5bfbb04759fd4393addd2b55c92bc96a&aId=1814&cb=' + new Date().getTime(); 
			image.src = src0;
	
			var image = new Image();
			var src1 = 'http://view.atdmt.com/action/nl_routemobiel_bedankt_14jul10';
			image.src = src1;
	
			var image = new Image();
			var src2 = 'http://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&ActivityID='+activityId+'&ns=1';
			image.src = src2;
		} else if(activityId != 0) {
			var ebRand = Math.random()+ '';
			ebRand = ebRand * 1000000;
			var trackerScriptUrl = 'http://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&ActivityID=' + activityId + '&rnd=' + ebRand + '';
			$.getScript(trackerScriptUrl);
		}
		
		return true;
	},
	loadAdwordsImage: function (conversionId, conversionLabel) {
		if ( conversionLabel != undefined && conversionId != undefined && conversionLabel != '' && conversionId != ''){
			var image = new Image();
			var googlesrc = 'http://www.googleadservices.com/pagead/conversion/' + conversionId + '/?label=' + conversionLabel + '&guid=ON&script=0&' + Math.floor(Math.random()*100);
			image.src = googlesrc;
		}	
	},
	// Pings google adwords by loading an image with parameters based on which products user has selected
	makeAdwordsCall: function(){

		var conversionId = '1034973649';	// The id for routemobiel conversion tracking
		var conversionLabelNL = '3sbSCK-AlwEQ0ePB7QM';
		var	conversionLabelEUKORT = 'Bw3jCJeHngEQ0ePB7QM';
		var conversionLabelEULANG = 'HosJCPGHngEQ0ePB7QM';

		// Check what products user has chosen, by looping through checkbox elements
		var nrs = new Array(1,2,3); 
		for ( j in nrs ){
			i = nrs[j];
			if ( $('#vehicle-' + i).css('display') == 'block') {				
				if ( $('#nederland-' + i).attr('checked') ){					
					regForm.loadAdwordsImage(conversionId, conversionLabelNL); 
				}
				if ( $('#europa-' + i).attr('checked') ){					
					if ( $('#europa-product-' + i).val() == '4') {						
						regForm.loadAdwordsImage(conversionId, conversionLabelEULANG); 
					}
					if ( $('#europa-product-' + i).val() == '12') {						
						regForm.loadAdwordsImage(conversionId, conversionLabelEUKORT);
					}
				}
			}
		}
	},	
	// Pings google for adding a transaction
	makeGATransactionCall: function(){

		if(pageTracker != undefined) {
			var cur = new Date();
			var curDateTime = cur.getFullYear() + '-' + cur.getMonth() + '-' + cur.getDate() + '-' + cur.getHours() + '-' + cur.getMinutes();
			var orderId = '';
			var reknr = $('#rekeningnummer').attr('value');
			var relnr = $('#relatienr').attr('value');
			var overnr = $('#overeenkomstnr').attr('value');
			if (reknr != '') {
				orderId = reknr + '-' + curDateTime;
			} else if (relnr != '') {
				orderId = relnr +'-' + curDateTime;				
			} else if (overnr != '') {
				orderId = overnr +'-' + curDateTime;				
			} else {
				orderId = '-' + curDateTime;			
			}
			var totalPrice = parseFloat($('#total-price').html().replace(',','.'));
			var tax = parseFloat(0.19*totalPrice);
			var city = $('#plaats').attr('value');

			pageTracker._addTrans(			
			    ""+orderId,                                     // Order ID			
			    "Online afsluiten via routemobiel.nl",                  // Affiliation			
			    ""+totalPrice,      	// Total			
			    ""+tax,  // Tax			
			    "0",                                        // Shipping			
			    ""+city,              // City			
			    "Nvt",                               	// State			
			    "Nederland"                                 // Country			
			  );
			//	alert('addtrans' + orderId + totalPrice + tax + city);
			// Check what products user has chosen
			for (i in GAitems) {			
				//alert('items: ' + GAitems[i][3] + GAitems[i][2] + GAitems[i][1] + GAitems[i][0]); 
				pageTracker._addItem(
							    ""+orderId,                    // Order ID
				    			GAitems[i][3],                                 // SKU
				    			GAitems[i][2],                            // Product Name
				    			"",                             // Category
				    			GAitems[i][0],                                    // Price
				    			GAitems[i][1]                                      // Quantity
				);				
			}
			//alert('tracktrans');
  			pageTracker._trackTrans();  			
		}		
	},	
	
	helpDialog : {
		containerId : 'help-box',
		contentId : 'help-content',
		closeId : 'help-close',
		helpBox : null,

		_init : function(){
			// Create box and dialog container
			this.helpBox = $('<div></div>').attr('id', this.containerId).append( $('<div></div>').attr('id', this.contentId) );
			this.helpBox.append($('<a>x</a>').attr({ 'id' : this.closeId, 'title' : 'Sluiten' }).bind('click', function(){ regForm.helpDialog.close();}  ));
			$('body').append(this.helpBox);
		},
		// Trigger is JQ object
		open : function( trigger ){
			if(!this.helpBox){ this._init();}
			this.trigger = trigger;
			this._setPosAndWidth();
			this._setContent();
			this.helpBox.fadeIn();
			return false;
		},
		close : function(){
			if( this.helpBox ){	this.helpBox.hide();}
		},
		_setPosAndWidth : function(){
			var leftPos = this.trigger.offset().left
			this.helpBox.css('top', this.trigger.offset().top).css('left', leftPos);
			var sidebar = $('#sidecontent');
			var rightSide = sidebar.offset().left + sidebar.width();
			var width = rightSide - leftPos - 22; // Where padding is the rightpadding of a contentbox, so that it doesn't overlap the shadow
			this.helpBox.css('width', width + 'px');
		},
		_setContent : function(){
			var childSpans = this.trigger.children('span');
			if(	childSpans.length != 1){return false;}
			this.helpBox.children('#' + this.contentId).html( childSpans.html());
		}
	}
}

//check required input fields in the given form,maybe move to main.js if used more often.
function checkRequiredFormFilled(formname) {
	var errorStr = '';
	$('#' + formname + ' input, select, radio, textarea').each ( function(){
			if(!checkRequiredFilled($(this))) {
				errorStr += $(this).attr('name') + ' ';
			}
		} );
	if (errorStr != '') {
		notification.alert('Vul alle verplichte velden in.');
	}
	return errorStr;
}

// check if the given element is required and if so, check if it is filled with at least 1 char
function checkRequiredFilled(el) {
	if ($(el).attr('required') == '1') {
		if (Validator.isEmpty($(el).attr('value'))) {
			showError(el);
			return false;
		} else {
			removeError(el);
		}
	}
	// not required or filled
	return true;
}

var showError = function(el){
	el.parent('li').addClass('error');
}

var removeError = function(el){
	el.parent('li').removeClass('error');
}

var selectOptionByValue = function(el, value)	{
	if(el.nodeName.toLowerCase() != "select") return;
	// get number of options
	var optionsLength = el.options.length;

	for(var i = 0; i<optionsLength; i++) {
		if (el.options[i].value == value) {
			el.options[i].selected = true;
		};
	}
}

// pechhulpverlner opzeg service - popup window
var phvoPopup = function(){
	var content = [];
	var ready = false;
	var html = '';
	var inited = false;

	function init(){
		if(!inited){
			// general navigation foreward
			content = $('.phvo-popup-content');
			$('.phvo-navLink').click(onNavigationClick);

			// anwb: door naar scherm 2
			$('#pechhulpverlener-zeker-ja').click(onNavigationClick);
			$('#pechhulpverlener-zeker-nee').click(onDenyANWB);

			// anwb: door naar scherm 3
			$('#pechhulpverlener-zeker2-ja').click(onNavigationClick);
			$('#pechhulpverlener-zeker2-nee').click(onDenyANWB);
			$('#phvo-anwb-1-e-next').click(function(e){
				e.preventDefault();
				if($('#phvo-popup-end').attr('checked')){
					// end of the line
					onDenyANWB(e);
				} else if($('#phvo-popup-retry').attr('checked')){
					show('phvo-anwb-1')
				}else{
					output('U moet een keuze maken');
				}
			});

			$('#phvo-anwb-2-e-next').click(function(e){
				e.preventDefault();
				onDenyANWB(e);
			});

			// zet de juiste datums in anwb scherm 3
			var date = [stringUtils.pad($('#nederland_ingang_1_Day').val()), stringUtils.pad($('#nederland_ingang_1_Month').val()),$('#nederland_ingang_1_Year').val()].join('-');
			var newhtml = $('#phvo-anwb-3').html().replace(/%datum%/g, date);
			$('#phvo-anwb-3').html(newhtml);

			$('#phvo-anwb-3-next').click(function(e) {
				e.preventDefault();
				var myParent = $(this).parents('.phvo-popup-content:first');
				setStartDate($(':checked', myParent).val());
				phvoPopup.ready = true;
				submit();
			});

			// extra beauty check. If the first date equals the second, we will remove the second
			if(date == $('#pechhulpverlener-anwb-newyear').val()){
				$('#pechhulpverlener-anwb-newyear').hide();
				$('#pechhulpverlener-anwb-newyear-label').hide();
			} else {
				$('#pechhulpverlener-anwb-newyear').show();
				$('#pechhulpverlener-anwb-newyear-label').show();
			}
			// and since there are multiple options we check both
			if(date == $('#pechhulpverlener-anwb-newyear').val()){
				$('#pechhulpverlener-anwb-future').hide();
				$('#pechhulpverlener-anwb-future-label').hide();
			} else {
				$('#pechhulpverlener-anwb-future').show();
				$('#pechhulpverlener-anwb-future-label').show();
			}

			$('#phvo-others-next').click(function(e){
				e.preventDefault();
				phvoPopup.ready = true;
				submit();
			});

			inited = true;

			$('<div></div>').attr('id', 'phvo-overlay').appendTo('body');
		} else {
			phvoPopup.ready = false;
			$('input[type=text]', $('#phvo-dialog')).val();
			$(':checked', $('#phvo-dialog')).attr('checked', false);
		}

	}

	function onNavigationClick(e){
		if(e){
			e.preventDefault();
		}
		var contentId = $(this).parents('.phvo-popup-content:first').attr('id');
		if(checkFields(contentId)){
			var m = contentId.match(/(\d+)$/);
			contentId = contentId.replace(/(\d+)$/, Number(m[1])+1);
			if(!show(contentId)){
				phvoPopup.ready = true;
				submit();
			}
		} else {
			this.checked = false;
		}
	}

	function onDenyANWB(e){
		e.preventDefault();
		var contentId = $(this).parents('.phvo-popup-content:first').attr('id');
		contentId = contentId + '-e';
		if(!show(contentId)){
			endIt();
		}
	}

	function setStartDate(value){
		var a = value.split('-');
		for(var i = 0; i < 3; i++){
			a[i] = parseInt(a[i]);
		}

		$('#nederland_ingang_1_Day').val(a[0]);
		$('#nederland_ingang_1_Month').val(a[1]);
		$('#nederland_ingang_1_Year').val(a[2]);

		$('#nederland_ingang_2_Day').val(a[0]);
		$('#nederland_ingang_2_Month').val(a[1]);
		$('#nederland_ingang_2_Year').val(a[2]);

		$('#nederland_ingang_3_Day').val(a[0]);
		$('#nederland_ingang_3_Month').val(a[1]);
		$('#nederland_ingang_3_Year').val(a[2]);

		$('#europa_ingang_1_Day').val(a[0]);
		$('#europa_ingang_1_Month').val(a[1]);
		$('#europa_ingang_1_Year').val(a[2]);

		$('#europa_ingang_2_Day').val(a[0]);
		$('#europa_ingang_2_Month').val(a[1]);
		$('#europa_ingang_2_Year').val(a[2]);

		$('#europa_ingang_3_Day').val(a[0]);
		$('#europa_ingang_3_Month').val(a[1]);
		$('#europa_ingang_3_Year').val(a[2]);
	}

	function checkFields(id){
		switch(id){
			case 'phvo-anwb-1':
				if( $('#pechhulpverlener-overdracht-naam').val() &&
					$('#pechhulpverlener-overdracht-lidmaatschapnr').val()){
					$('#phvo-anwb-naam').val($('#pechhulpverlener-overdracht-naam').val());
					$('#phvo-anwb-lidmaatschapnr').val($('#pechhulpverlener-overdracht-lidmaatschapnr').val());
					return true;
				} else {
					output('Alle velden zijn verplicht');
					return false;
				}
			break;
			default: return true;
		}
	}

	function endIt(){
		// reset opzegservice check step 1
		$('#opzegservice-ja').attr('checked', false);
		$('#opzegservice-nee').attr('checked', true);

		$('#pechhulpverlener-li').hide();

		// submit form
		submit();
	}

	function reset(){
		phvoPopup.ready = false;
	}

	function output(s){
		$('#phvo-output').html(s);
	}

	function hidePopup(){
		quitProviderPopup.close();
	}

	function show(id){
		var success = false;
		content.each(function(){
			if(this.id == id){
				success = true;
				$(this).show();
			} else {
				$(this).hide();
			}
		});
		output('');
		return success;
	}

	function submit(){
		hidePopup();
		quitProviderPopup.close();
		$('#step2NextLink').click();
	}

	return {
		'init' : init,
		'show' : show,
		'output' : output,
		'ready' : ready,
		'reset' : reset,
		'endIt' : endIt,
		'setStartDate' : setStartDate,
		'submit' : submit
	}
}();

var stringUtils = function(){
	function pad(targetStr, maxLength, padChr){
		maxLength = maxLength || 2;
		padChr = padChr || '0';
		while(targetStr.toString().length < maxLength){
			targetStr = padChr.toString() + targetStr;
		}
		return targetStr;
	}
	return {
		'pad' : pad
	}
}();


// custom function to show alerts
var quitProviderPopup = {
	active : false,
	overlay : null,
	dialog : null, // The actual dialog
	content: null,
	ie6 : navigator.userAgent.indexOf("MSIE 6")>=0 ,

	show : function (){
		if( !this.dialog ){	this._createDialog();}
		this._setContent();
		this._open();
	},
	_toggleAllSelects : function ( show ){
		if(show){
			$('select').css('visibility', 'visible');
		}else{
			$('select').css('visibility', 'hidden');
		}
	},
	_setContent : function( content, title ){
		$('#phvo-dialog').show().appendTo(this.content);
	},
	_open : function(){
		if (quitProviderPopup.ie6){
			quitProviderPopup._toggleAllSelects(false);
		}
		quitProviderPopup.overlay.show();
		quitProviderPopup.dialog.show();
		quitProviderPopup.active = true;

	},
	close : function(){
		if (quitProviderPopup.ie6){
			quitProviderPopup._toggleAllSelects(true);
		}
		quitProviderPopup.overlay.hide();
		quitProviderPopup.dialog.hide();
		quitProviderPopup.active = false;

	},

	_createDialog : function(){
		this.overlay = 	$('<div></div>').attr('id', 'alert-overlay').appendTo('body');
		this.content = $('<div></div>').attr('id', 'dialog-content');

		// Put it all together and append to body
		this.dialog = $('<div></div>').attr('id', 'alert-dialog').append( this.content ).appendTo('body');
	}
}
