(dimPage = function(col,opa) {
	var col   = col || "#000";
	var opa = opa || "0.75";

	var overlay = $('<div/>').css({
		backgroundColor: col,
		position: 'absolute',
		top: '0',
		left: '0',
		width: $(window).width()+'px',
		height: $(window).height()+'px',
		zIndex: '1000',
		opacity: opa
	});

	$('body').append(overlay);
	return overlay;

});



var biebbase = {

	addConfirm: function() {
		var c = $('.confirm');
		for (var i=0; i<c.length; i++) {
			c[i].onclick = function() {
				if (confirm(this.getAttribute('title') + '. Weet je het zeker?'))
					return true;
				else
					return false;
			}
		}
	}

}



/* needs dimPage() and jQuery with color en hotkeys plugins */
var quizCards = {

/* settings & elements */
	w: 640,
	h: 400,
	canSave: false,
	random: true,

/* methods */
	reset: function() {
		this.cards = [];
		this.currentCard = 0;
		this.qcCard = null;
		this.qcSave = null;
		this.saveCheck = null;
		this.saveInput = null;
		this.isSaved = null;
		this.qcBody = $('<div/>').css({
			position: 'absolute',
			top: '0',
			left: '0',
			width: '100%',
			height: '100%',
			zIndex: '10000'
		});
		this.qcCanvas = $('<div/>').addClass('qc').css({ opacity: '0.9' });
		this.qcHeader = $('<h1/>').html('<span class="q">Quiz</span><span class="c">Cards</span>');
		this.qcMessage = $('<div/>').html('<p>Overhoor jezelf nu met dit handige overhoorprogramma. Je hoeft je ouders, broer of zus, vriend of vriendin niet meer lastig te vallen om je te laten overhoren, want met dit programma kun je het zelf, en veel effici&euml;nter!</p><p>QuizCards helpt je me met allerlei zaken die uit het hoofd geleerd moeten worden. Of het nu Engels, Duits, Frans, Latijn, Grieks, of feiten zijn die je wilt leren, het kan heel eenvoudig met Quizcards.</p><p>Het programma werkt door een lijst van vragen en bijbehorende antwoorden in te typen en vervolgens overhoort het programma jou in willekeurige volgorde.</p>').addClass('block');
		this.qcFieldset = $('<fieldset/>');
		this.qcFieldset.append($('<legend/>').text('Voeg cards toe'));
		this.qcLabel1 = $('<label/>').addClass('q1').attr({'for':'input1'}).text('Vraag');
		this.qcLabel2 = $('<label/>').addClass('q2').attr({'for':'input2'}).text('Antwoord');
		this.qcInput1 = $('<input/>').addClass('text q1')
		this.qcInput2 = $('<input/>').addClass('text q2');
		$.hotkeys.add('return', function(){
			quizCards.addCard();
		});
		this.qcAdd = $('<input type="button"/>').addClass('btn').attr({value:'Toevoegen'}).click(function() {
			quizCards.addCard();
		});
		this.qcCards = $('<dl/>').addClass('cards');
		this.qcButton = $('<input type="button"/>').addClass('btnStart').attr({value:'Start de Quiz!'}).css({ visibility: 'hidden' }).click(function() {
			quizCards.beginQuiz();
		});
		this.qcStart = $('<input type="button"/>').addClass('btnStart').attr({value:'Klaar? Start!'}).click(function() {
			if (quizCards.random)
				quizCards.cards.sort(function() {return 0.5 - Math.random()});
			quizCards.nextCard();
		});
		this.qcAgain = $('<input type="button"/>').addClass('btnStart').attr({value:'Nieuwe quiz'});
		this.qcSplash = $('<input type="button"/>').addClass('btnStart').attr({value:'Maak een Quiz!'})
		this.qcClose = $('<a/>').addClass('close').attr({title:'QuizCards afsluiten'}).text('x').click(function() {
			quizCards.exit();
		});
		this.qcProgress = $('<div/>').addClass('progress').css('display','none');
		this.qcProgressBar = $('<div/>').addClass('bar');
		this.qcProgressScore = $('<p/>').addClass('score');
		this.qcProgress.append(this.qcProgressBar);
		this.qcProgress.append(this.qcProgressScore);
	},

	init: function() {
		$('#qcLink').css('display','block');
		$('#qcLink a.qcLink').click(function() {
			quizCards.start(this.rel);
			return false;
		});
		this.reset();
	},

	start: function(opt) {
		opt = opt || null;
		if (!this.qcOverlay)
			this.qcOverlay = dimPage('#000','0.0');
		$('body').append(this.qcBody);
		this.qcOverlay.animate({ opacity:'0.75' }, 250, 'linear', function() {
			quizCards.qcBody.append(quizCards.qcCanvas);
			quizCards.qcCanvas.append(quizCards.qcClose);
			quizCards.qcCanvas.append(quizCards.qcHeader);
			quizCards.qcCanvas.append(quizCards.qcProgress);
			if (opt) { // laadt bestaande QC en speel deze
				quizCards.cards = new Array(
					Array('vraag 1', 'antwoord 1'),
					Array('vraag 2', 'antwoord 2'),
					Array('vraag 3', 'antwoord 3')
				);
				quizCards.beginQuiz(opt);
			} else { // maak nieuwe QC
				quizCards.qcCanvas.append(quizCards.qcMessage);
				quizCards.qcSplash.click(function() {
					quizCards.qcMessage.remove();
					quizCards.qcSplash.remove();
					quizCards.qcFieldset.append(quizCards.qcLabel1);
					quizCards.qcFieldset.append(quizCards.qcLabel2);
					quizCards.qcFieldset.append(quizCards.qcInput1);
					quizCards.qcFieldset.append(quizCards.qcInput2);
					quizCards.qcCanvas.append(quizCards.qcFieldset);
					quizCards.qcCanvas.append(quizCards.qcAdd);
					quizCards.qcCanvas.append(quizCards.qcCards);
					quizCards.qcCanvas.append(quizCards.qcButton);
					quizCards.qcInput1.focus();
				});
				quizCards.qcCanvas.append(quizCards.qcSplash);
			}
		});
		$.hotkeys.add('esc', function(){ 
			quizCards.exit();
		});
	},

	addCard: function() {
		if (this.qcInput1.attr('value') && this.qcInput2.attr('value')) {
			this.cards[this.cards.length] = new Array(this.qcInput1.attr('value'),this.qcInput2.attr('value'));
			if (this.cards.length == 1) {
				this.qcButton.css({ opacity:'0.0', visibility:'visible' });
				this.qcButton.animate({ opacity:'1.0' }, 3000);
			}
			this.qcCards.append($('<dt/>').text(this.cards.length + '. ' + this.qcInput1.attr('value')));
			this.qcCards.append($('<dd/>').text('- ' + this.qcInput2.attr('value')));
			this.qcInput1.attr('value','');
			this.qcInput2.attr('value','');
			this.qcInput1.focus();
			this.qcAdd.animate({ backgroundColor:'#cfc' }, 50).animate({ backgroundColor:'#ccc' }, 150);
		} else {
			if (!this.qcInput2.attr('value'))  {
				this.qcInput2.animate({ borderBottomColor:'#f00',backgroundColor:'#fcc' }, 500).animate({ borderBottomColor:'#000',backgroundColor:'#fff' }, 1500);
				this.qcInput2.focus();
			}
			if (!this.qcInput1.attr('value')) {
				this.qcInput1.animate({ borderBottomColor:'#f00',backgroundColor:'#fcc' }, 500).animate({ borderBottomColor:'#000',backgroundColor:'#fff' }, 1500);
				this.qcInput1.focus();
			}
		}
	},

	beginQuiz: function(opt) {
		opt = opt || null;
		this.qcFieldset.animate({ opacity:'0.0' }, 500, 'linear', function(){
			quizCards.qcFieldset.css('display','none');
			quizCards.qcCard = $('<div/>').addClass('block');
			quizCards.qcCard.append($('<p/>').text('Klik op de card of druk op de spatiebalk om de card om te draaien, en om door te gaan naar de volgende card!'));
			if (quizCards.canSave && !opt) {
				quizCards.saveCheck = $('<input type="checkbox"/>').attr({id:'saveQC'}).change(function() {
					if (this.checked) {
						quizCards.saveInput.attr({disabled:''});
						quizCards.qcSave.removeClass('disabled');
						quizCards.saveInput.focus();
					} else {
						quizCards.saveInput.attr({disabled:'disabled'});
						quizCards.qcSave.addClass('disabled');
					}
				});
				quizCards.saveInput = $('<input type="text"/>').attr({ id:'saveTitle', disabled:'disabled', value:'' }).addClass('text noMargin');
				quizCards.qcSave = $('<div/>').css('float','left').addClass('disabled').append(
					$('<fieldset/>').append(
						$('<legend/>').append(
							quizCards.saveCheck
						).append(
							$('<label/>').attr('for','saveQC').html('Opslaan in <em>Mijn QuizCards</em>')
						)
					).append(
						$('<label/>').attr('for','saveTitle').text('Naam:')
					).append(
						quizCards.saveInput
					)
				);
				quizCards.qcCard.append(quizCards.qcSave);
			}
			quizCards.qcCard.insertAfter(quizCards.qcHeader);
		});
		this.qcAdd.animate({ opacity:'0.0' }, 250, 'linear', function(){
			quizCards.qcAdd.css('display','none');
		});
		this.qcCards.animate({ opacity:'0.0' }, 250, 'linear', function(){
			quizCards.qcCards.css('display','none');
		});
		this.qcButton.css('display','none');
		this.qcCanvas.append(this.qcStart);
		$.hotkeys.remove('return');
	},

	// show card with question
	showCard: function(n) {
		this.setProgress();
		this.qcCard = $('<div/>').addClass('card').html('<span>'+this.cards[n][0]+'</span>').css({ height:'0', backgroundColor:'#ccc' }).click(function() {
			quizCards.flipCard(n);
		});
		this.qcCanvas.append(this.qcCard);
		$('.card span').css({ top:(150-($('.card span').height()/2))+'px' });
		this.qcCard.animate({
			height:'300px'
		}, 500);
		$.hotkeys.remove('space');
		$.hotkeys.add('space', function(){ 
			quizCards.flipCard(n);
		});
	},

	// flip card and show answer
	flipCard: function(n) {
		this.qcCard.animate({ width:'0', marginLeft:'-10px', backgroundColor:'#aaa' }, 250, 'swing', function() {
			quizCards.qcCard.html('<span>'+quizCards.cards[n][1]+'</span>');
			$('.card span').css({ top:(150-($('.card span').height()/2))+'px' });
		}).animate({ width:'480px', marginLeft:'-250px', backgroundColor:'#fff' }, 250).unbind('click').click(function() {
			quizCards.nextCard();
		});
		$.hotkeys.remove('space');
		$.hotkeys.add('space', function(){ 
			quizCards.nextCard();
		});
	},

	// fade out and remove card, then move to next
	nextCard: function() {
		// check name and save?
		if (this.canSave && !this.isSaved) {
			if (this.saveCheck && this.saveCheck.attr('checked') && (this.saveInput.attr('value') == '' || this.saveInput.attr('value') == undefined)) {
				this.saveInput.animate({ borderBottomColor:'#f00',backgroundColor:'#fcc' }, 500).animate({ borderBottomColor:'#000',backgroundColor:'#fff' }, 1500);
				this.saveInput.focus();
				return false;
			} else {
				// AJAX save action here!
				this.isSaved = true;
			}
		}
		try {
			quizCards.qcAgain.remove();
			this.qcProgress.css('cursor','default').unbind("click");
		} catch(err) {}
		if (this.cards.length > 0 && this.currentCard < this.cards.length) {
			quizCards.qcStart.css('display','none');
			quizCards.qcProgress.css('display','block');
			if (this.qcCard) {
				this.qcCard.animate({ opacity:'0' }, 250, 'linear', function() {
					quizCards.qcCard.remove();
					quizCards.showCard(quizCards.currentCard);
					quizCards.currentCard++;
				});
			} else {
				quizCards.showCard(quizCards.currentCard);
				quizCards.currentCard++;
			}
		} else {
			this.qcCard.animate({ opacity:'0' }, 250, 'linear', function() {
				quizCards.qcCard.remove();
				quizCards.endScreen();
				quizCards.currentCard = 0;
			});
		}
	},

	setProgress: function() {
		if (this.currentCard >= this.cards.length) {
			this.qcProgressScore.text('Klaar!');
			this.qcProgress.css('cursor','pointer').click(function() {
				quizCards.exit();
			});
		} else {
			this.qcProgressScore.text((this.currentCard+1) + ' / ' + this.cards.length);
		}
		this.qcProgressBar.animate({ width:((this.currentCard / this.cards.length)*100)+'%' },500);
	},

	endScreen: function(n) {
		this.setProgress();
		this.qcCard = $('<p/>').text('Dit is het einde van deze quiz. Wil je hem nog een keer afspelen, of een nieuwe quiz maken?').addClass('block');
		this.qcCanvas.append(this.qcCard);
		this.qcAgain.css({ bottom: '4em' }).click(function() {
			$.hotkeys.remove('space');
			quizCards.qcBody.remove();
			quizCards.reset();
			quizCards.start();
		});
		this.qcCanvas.append(this.qcAgain);
		this.qcStart.attr({value:'Nog een keer!'}).css({ bottom:'7em', display:'block' });
	},

	exit: function() {
		if (confirm('Weet je zeker dat je QuizCards wilt afsluiten?')) {
			this.qcOverlay.remove();
			this.qcOverlay = null;
			this.qcBody.remove();
			$.hotkeys.remove('esc');
			$.hotkeys.remove('space');
			$.hotkeys.remove('return');
			this.reset();
		} else {
			return false;
		}
	}

}

var externalLinks = function() {
	var els = document.getElementsByTagName('a');
	for (var i=0; i<els.length; i++) {
		if ((els[i].href.indexOf(document.domain) < 0 && (els[i].href.indexOf('http://') > -1 || els[i].href.indexOf('https://') > -1)) || (els[i].href.indexOf('.pdf') > -1 || els[i].href.indexOf('/r?') > -1) ) {
			els[i].target = '_blank';
			els[i].className += ' external';
			els[i].title += ' (opent in een nieuw scherm)';
		}
	}
}

$(document).ready(function() {
	biebbase.addConfirm();
	quizCards.init();
	externalLinks();
	//quizCards.start(); /* remove! */
});


