// Add class when JS is enabled
if(document.getElementById){
	var html = document.getElementsByTagName("html")[0];
	html.className = 'js';
}

// DOM ready
$(document).ready(function(){
	betterform();
	faq();
	//$.geekGaTrackPage('UA-19081389-1', 'taxaselandia.dk');
});

function betterform(){
	$('.form-select').find('select').css('opacity','0');
	$('.form-select').each(function(){
		selectVal = $(this).find('option:selected').text();
		$(this).append('<span>' + selectVal + '</span>');
		$(this).find('select').change(function(){
			selectVal = $(this).find('option:selected').text();
			$(this).next('span').text(selectVal);
		})
	})
	$('.form [required]').siblings('label').append(' <span>*</span>');
	
	var totalsum = 0; //parseInt($('.cashcard-new .feesum').text());
	
	$('.cashcard-new .totalsum span').text(totalsum);
	$('.cashcard-new #add').click(function(event){
		var number = $('.cashcard-new #number').val()
		var amount = $('.cashcard-new #amount option:selected').val();
		var total = number * amount;
		var i = $('.cashcard-new tbody tr').length;
		$('.cashcard-new tbody').append('<tr><td class="product">Cash Card</td><td class="number"><input type="hidden" value="' + number + '" name="products[' + i + '][number]">' + number + '</td><td class="amount"><input type="hidden" value="' + amount + '" name="products[' + i + '][amount]">' + amount + '</td><td class="total"><span>' + total + '</span><strong id="delete">X</strong></td></tr>');
		totalsum += total;
		$('.cashcard-new .totalsum span').text(totalsum);
		event.preventDefault();
		updateFeeAndTotal(totalsum);
	})
	$('.cashcard-new strong#delete').live('click',function(){
		$(this).parents('tr').remove();
		var totalsum = parseInt($('.cashcard-new .feesum').text());
		$('.cashcard-new tbody tr').each(function(i){
			$(this).find('.number :hidden').attr('name','products[' + i + '][number]');
			$(this).find('.amount :hidden').attr('name','products[' + i + '][amount]');
			totalsum += parseInt($(this).find('.total span').text());
		})
		$('.cashcard-new .totalsum span').text(totalsum);
		updateFeeAndTotal(totalsum);
	})
	if($('#shipping').is(':checked')){
		$('.cashcard-shipping').show();
	}
	$('#shipping').click(function(){
		if($(this).is(':checked')){
			$('.cashcard-shipping').slideDown();
		}else{
			$('.cashcard-shipping').slideUp();
		}
	})
	if($('#new').is(':checked')){
		$('.cashcard-new').show();
	} else if($('#refill').is(':checked')){
		$('.cashcard-new').hide();
		$('.cashcard-refill').show();
	}
	$(':radio[name=type]').click(function(){
		if($(this).attr('id') == 'new'){
			$('.cashcard-new').slideDown();
			$('.cashcard-refill').slideUp();
		}else if($(this).attr('id') == 'refill'){
			$('.cashcard-new').slideUp();
			$('.cashcard-refill').slideDown();
		}
	})
	$('#shipping').click(function(){
		if($(this).is(':checked')){
			$('.cashcard-shipping').slideDown();
		}else{
			$('.cashcard-shipping').slideUp();
		}
	})
}

function updateFeeAndTotal(newtotal) {
	var cards = 0;
	$('.cashcard-new tbody tr').each(function(i){
		cards += parseInt($(this).find('.number input').val());
	});	
	$('.cashcard-new .feesum').text((cards*25));
	$('.cashcard-new .totalsum span').text(newtotal+(cards*25));
}

function validateCashCardForm() {
	var error = '';
	var emailregexp = /^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(\.){1}[a-zA-Z]{2,4})+$/;
	var cashcardregexp = /^([0-9]){19}$/;

	if(!$('#terms').is(':checked')){
		error += "Handelsbetingelser er ikke godkendt\n";
	}
	
	
	if($('#new').is(':checked')){
		var totalsum = 0;
		$('.cashcard-new tbody tr').each(function(i){
			totalsum += parseInt($(this).find('.total span').text());
		});
		
		if (totalsum == 0) {
			error += "Der er ikke valgt nogle beløb\n";
		}
		
		if ($('input[name="names"]').val().length < 2) {
			error += "Navn\n";
		}

		if ($('input[name="address"]').val().length < 4) {
			error += "Adresse\n";
		}

		if ($('input[name="zip"]').val().length < 4) {
			error += "Postnr.\n";
		}

		if ($('input[name="city"]').val().length < 2) {
			error += "By\n";
		}

		if ($('input[name="country"]').val().length < 3) {
			error += "Land\n";
		}
		
		if (!emailregexp.test($('input[name="email"]').val())) {
			error += "E-mail adresse\n";
		}	
		
		if($('#shipping').is(':checked')){	
			if ($('input[name="shipping-names"]').val().length < 2) {
				error += "Leveringsnavn\n";
			}
	
			if ($('input[name="shipping-address"]').val().length < 4) {
				error += "Leveringsadresse\n";
			}
	
			if ($('input[name="shipping-zip"]').val().length < 4) {
				error += "Leveringspostnr.\n";
			}
	
			if ($('input[name="shipping-city"]').val().length < 2) {
				error += "Leveringsby\n";
			}
	
			if ($('input[name="shipping-country"]').val().length < 3) {
				error += "Leveringsland\n";
			}
		}
	}

	if($('#refill').is(':checked')){
		if (!emailregexp.test($('#email-refill').val())) {
			error += "E-mail adresse\n";
		}		
		if (!cashcardregexp.test($('#code').val())) {
			error += "CashCard kode (19 tal)\n";
		}		
	}

	
	
	if (error != '') {
		alert("Flg. felter blev ikke korrekt udfyldt:\n" + error);
		return false;
	}
	return true;
		
}

function faq(){
	$('article.faq').find('h2').click(function(){
		if($(this).parent().hasClass('open')){
			$(this).parent().find('.entry-content').slideToggle('1000',function(){
				$(this).parent().removeClass('open');
			});
		}else{
			$('article.faq .entry-content').parent().removeClass('open').end().slideUp();
			$(this).parent().toggleClass('open').end().next('.entry-content').slideToggle('1000');
		}
	})
}

var questionnaire = function() {
	return {
		countdownTimer : false,
		currentQuestion : 1,
		totalQuestions : 15,
		secondsLeft : 900,
		a: [],
		participant_save : function() {
			var participant = {	
				name:$('#participant input[name="name"]').val(),
				address:$('#participant input[name="address"]').val(),
				zip:$('#participant input[name="zip"]').val(),
				city:$('#participant input[name="city"]').val(),
				phone:$('#participant input[name="phone"]').val(),
				email:$('#participant input[name="email"]').val()
			} 
		
			var error = '';
			var emailRegEx = /^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(\.){1}[a-zA-Z]{2,4})+$/
		
			if (participant.name.length < 2) {
				error += "Dit navn\n";
			}

			if (participant.phone.length < 8) {
				error += "Dit telefonnummer\n";
			}
		
			if (participant.email.length > 0 && !emailRegEx.test(participant.email)) {
				error += "Gyldig email adresse\n"
			}
			
			if (error != '') {
				alert("Flg. felter blev ikke korrekt udfyldt:\n" + error);
				return false;
			}
			
			$('div#participant').hide();
			$('div#question-1').show();
			questionnaire.setCountDown();
			$(window).bind('beforeunload', function() { return 'Er du sikker på at du vil forlade siden? Dine svar vil blive slettet.' });
		},
		question_save : function() {
			var checked = $('div#question-'+questionnaire.currentQuestion+' input[type="radio"]:checked');
			if (checked.length < 1) {
				alert('Der skal svares på spørgsmålet');
				return false;
			}
			$('div#question-' + questionnaire.currentQuestion).hide();
			questionnaire.currentQuestion++;
			if (questionnaire.currentQuestion > questionnaire.totalQuestions) {
				clearTimeout(questionnaire.countdownTimer);
				questionnaire.showResult();
			} else {
				$('div#question-' + questionnaire.currentQuestion).show();
			} 
		},
		setCountDown : function() {
			var minutes = Math.floor(questionnaire.secondsLeft/60);
			var seconds = questionnaire.secondsLeft-(minutes*60);
			
			var minutesStr = String(minutes);
			var secondsStr = String(seconds);
			
			$('#countdown-minutes').children('span').get(0).innerHTML = (minutes > 9) ? minutesStr.substr(0,1) : 0;	
			$('#countdown-minutes').children('span').get(1).innerHTML = (minutes > 9) ? minutesStr.substr(1,1) : minutes;	

			$('#countdown-seconds').children('span').get(0).innerHTML = (seconds > 9) ? secondsStr.substr(0,1) : 0;	
			$('#countdown-seconds').children('span').get(1).innerHTML = (seconds > 9) ? secondsStr.substr(1,1) : seconds;	

			questionnaire.secondsLeft--;

			if (questionnaire.secondsLeft > -1) {
				questionnaire.countdownTimer = setTimeout('questionnaire.setCountDown();', 1000);
			} else {
				alert('Tiden er gået');
				$('div#question-' + questionnaire.currentQuestion).hide();
				questionnaire.showResult();
			}
		},
		showResult : function() {
			var result = questionnaire.getResult();
			
			$('#correct-answers').html(result.correct);
			$('#total-questions').html(questionnaire.totalQuestions);
			
			$('div#result').show();
			questionnaire.sendMail();
			$(window).unbind('beforeunload');
		},
		sendMail : function() {
			var i;
			var questions = [];
			var question;
			
			for (i = 1; i <= questionnaire.totalQuestions; i++) {
				question = {question:$('div#question-' + i + ' h2').html(), answer: $('label[for="' + $('div#question-' + i + ' input:checked').attr('id') + '"]').html(), correct: ($('div#question-' + i + ' input:checked').val() == questionnaire.a[i])}
				questions.push(question);
			}
			console.log(questions);
			var participant = {	
								name:$('#participant input[name="name"]').val(),
								address:$('#participant input[name="address"]').val(),
								zip:$('#participant input[name="zip"]').val(),
								city:$('#participant input[name="city"]').val(),
								phone:$('#participant input[name="phone"]').val(),
								email:$('#participant input[name="email"]').val()
							}
			
			$.post('/wp-content/themes/taxaselandia/questionnaire.send.php', {questions:questions,participant:participant});
		},
		getResult : function() {
			var status = {correct:0,wrong:0,missed:0};
			var i, answer;
			
			for (i = 1; i <= questionnaire.totalQuestions; i++) {
				answer = $('div#question-' + i + ' input:checked');
				if (answer.length == 0) {
					status.missed++;
				} else {
					if (answer.val() == questionnaire.a[i]) {
						status.correct++;
					} else {
						status.wrong++;
					}
				}
			}
			
			return status;
		}
	}
}(); 

// geekGa.js v1.2
(function($){var pageTracker;$.geekGaTrackPage=function(account_id,domain_name){var host=(("https:"==document.location.protocol)?"https://ssl.":"http://www.");var src=host+'google-analytics.com/ga.js';$.ajax({type:'GET',url:src,success:function(){pageTracker=_gat._getTracker(account_id);domain_name=domain_name||'';if(domain_name!='')
{pageTracker._setDomainName(domain_name);}
pageTracker._trackPageview();},error:function(){throw"Unable to load ga.js; _gat has not been defined.";},dataType:'script',cache:true});};$.geekGaTrackEvent=function(category,action,label,value){if(typeof pageTracker!=undefined){pageTracker._trackEvent(category,action,label,value);}else{throw"Unable to track event; pageTracker has not been defined";}};})(jQuery);

