// Load stats
var prevQs		= getCookieDefault('prevQs',	[],	'csv');
var run			= getCookieDefault('run',		0,	'int');
var highScore	= getCookieDefault('highscore',	0,	'int');
var lastAnswer	= getCookieDefault('a',			0,	'int');
var windowStart = getCookieDefault('w',			0,	'int');


var correctAnswer = -1;
var questionSize = 0;
var data = [];
var qs = [];


// Constants

var windowSize			= 50;
var windowStep			= 200;
var windowStepInc		= 10;
var windowStepBack		= 100;
var windowMoveThreshold	= 2;
var questionMemory		= 500; //about the most we can store in a cookie
var gameMemory			= 30; //days
var switcheroo			= 5; //change things around every nth question of a run

var difficultyMeterLeft = -745; //px
var difficultyMeterWidth = 718; //px (measured off screenshot
var difficultyMeterBgWidth = 800; //px

var stopWords = ' a i or by an in to of as on up no and the but his her its with when why where beside ';

var amazon = {
	defaultLocale: 'uk',
	uk: {
		url: 'http://www.amazon.co.uk/gp/product/',
		id: 'channel4comfi-21',
		title: 'Amazon.co.uk'
	},
	us: {
		url: 'http://www.amazon.com/gp/product/',
		id: 'channel4comfi-20',
		title: 'Amazon.com'
	},
	imagePrefix: 'http://ecx.images-amazon.com/images/I/',
	imageSuffix: '._SL236.jpg'
};

var result = {
	correct: {
		display: 'CORRECT',
		image: 'correct.gif'
	},
	wrong: {
		display: 'WRONG',
		image: 'wrong.gif'
	}
};


var qIDs = ['image0','image1','image2','image3'];

var answered = false;


////////////////////////////////////////////////////////////////////////////////

function randOrd() {
	return (Math.round(Math.random())-0.5); 
}

function gebi(elID) {
	if (document.getElementById) {
		return document.getElementById(elID);
	} else {
		if (document.all) {
			return document.all[elID];
		}
	}
	return null;
}

function getCookieDefault(cookieName, value, type) {
	var cv;
	
	cv = Get_Cookie(cookieName);
	if (!cv) {
		cv = value
	} else {
		switch (type) {
			case 'int':
				cv = parseInt(cv, 10);
					break;
			case 'csv':
				cv = cv.split(',');
				break;	
		}
	}
	return cv;
}

function setCookieTyped(cookieName, value, type) {
	if (type === 'csv') {
		value = value.join(',');
	}
	Set_Cookie(cookieName, value, gameMemory, '/', '', '' );
}

function stringEscape(str) {
	return str.split("'").join("\'");
}
function htmlEscape(str) {
	return str.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;");
}

function obfuscateQuote(quote, title) {
	var titleSearch = " " + title.toLowerCase().replace(/[\\\/\-+\.]+/g, ' ').replace(/[^a-z ]+/g, '') + " ";
	var quoteWords = quote.toLowerCase().replace(/[^a-z ]+/g, '').split(" ");
	var originalQuote = quote.split(" ");
	var word;
	for (var i=0; i<quoteWords.length; i++) {
		word = " " + quoteWords[i].toLowerCase().replace(/[^a-z ]+/g, '') + " ";
		if (stopWords.indexOf(word)<0 && titleSearch.indexOf(word)>=0) {
			originalQuote[i] = "****";
		}
	}
	return originalQuote.join(" ");
}

function randomInWindow(wstart, wsize, max) {
	return (wstart + Math.floor(Math.random()*wsize)) % max;
}

function randomQuestion() {
	var failedCount = 0;
	var q = randomInWindow(windowStart, windowSize, questionSize);
	
	while (data[q].used) {
		q = (q+1) % questionSize;
		failedCount++;
	}
	if (failedCount>windowMoveThreshold  || q>(windowSize+windowStart)) {
		windowStart = (windowStart + windowStep) % questionSize;
	}
	windowStart = (windowStart + windowStepInc) % questionSize;
	return q;
}

function getUnusedRandomQuestions(qCount) {
	//return array of QCount questions that haven't been recently used
	var qs = [];
	for (var i=0; i<qCount; i++) {
		qs[i] = randomQuestion();
		taintFilm(qs[i]);
	}
	return qs;
}

function taintUsedQuestions() {
	for (var i=0; i<prevQs.length; i++) {
		taintFilm(prevQs[i]);
	}
}

function taintFilm(dataIndex) {
	id = data[dataIndex].used = true;
}

function recordQuestion(q) {
	prevQs.push(q);
	if (prevQs.length > questionMemory) {
		prevQs.shift();
	}
}
function newquestion() {
	var answerList;
	
	//load questions
	makedatablob();
	questionSize = data.length;	
	taintUsedQuestions();
	
	//update with the results of the previous question
	updateScreenScore();
	putPreviousAnswerOnScreen(false);
	
	qs = getUnusedRandomQuestions(qIDs.length);
	
	correctAnswer = qs[0];
	recordQuestion(correctAnswer);
	qs.sort(randOrd);

// stick it all on screen
	setDifficultyMeter();
	putQuestionOnScreen(correctAnswer, qs);
}

// amazon url builders
function amazonLink(asin, title, locale) {
	if (!amazon[locale]) {
		locale = amazon.defaultLocale;
	}
	return '<a href="' +
				amazon[locale].url + asin + '?tag=' + amazon[locale].id +
				'" target="_blank" title="' +
				stringEscape(title) + 
				' on ' +
				amazon[locale].title +
				'">' +
				htmlEscape(title) +
				'</a>';
}

function amazonImage(amazonImgCode) {
	return amazon.imagePrefix + amazonImgCode + amazon.imageSuffix
}

function setAmazonImage(amazonImgCode, title, elID) {
	var el = gebi(elID);
	
	if (el) {
		el.src = amazonImage(amazonImgCode);
		el.alt = title;
		el.title = title;
	}
}

function getAmazonImageHTML(amazonImgCode, title, h) {
	var t =  title.replace(/\"/, '&quot;');
	if (h) {
		h = '" height="' + h;
	} else {
		h = '';
	}
	return '<img src="' + amazonImage(amazonImgCode) + h + '" alt="' + t + '" title="' + t + '">';
}

function setInnerHTML(elID, html) {
	var el = gebi(elID);
	if (el) {
		//alert(html);
		el.innerHTML = html;
	} else {
	//	alert('failed to set innerHTML of ' + elID + ' to ' + html);
	}
}


function setDifficultyMeter() {
	var dm = gebi('difficultymeter');
	var d = 0;
	var dpx = 0;
	
	if (dm) {
		d = (windowStart) / (questionSize - windowSize);
		if (d > 1) {
			d = 1;
		}
		dpx = Math.floor(difficultyMeterLeft + d * (difficultyMeterWidth - difficultyMeterBgWidth - difficultyMeterLeft));
		dm.style.backgroundPosition = dpx + 'px 0';
	}
}

function showBonusRound() {
}
function hideBonusRound() {
	var bonus = gebi('bonus');
	if (bonus) {
		bonus.className = '';
	}
}

function putQuestionOnScreen(correctAnswer, qs)
{
	var qData;
	var el;
	
	if (run == 0 || run % switcheroo) {

		setInnerHTML('questiontext', 'Which film used this tagline?');
		setInnerHTML('quotebox', '&quot;' + obfuscateQuote(data[correctAnswer].q, data[correctAnswer].n) + '&quot;');
		for (var i = 0; i<qIDs.length; i++) {
			qData = data[qs[i]];
			setAmazonImage(qData.i, qData.n, qIDs[i]);
			setInnerHTML("filmtitle"+i, qData.n);
		}
	} else {
		el = gebi('bonus');
		if (el) {
			el.className = 'shown';
			window.setTimeout(hideBonusRound, 3000);
		}
		setInnerHTML('bonus', 'You got ' + run + ' in a row<br><span style="text-decoration: blink;">BONUS ROUND</span>');
		setInnerHTML('questiontext', 'BONUS ROUND: Which tagline was used for this film?');
		setInnerHTML('quotebox', getAmazonImageHTML(data[correctAnswer].i, data[correctAnswer].n) + data[correctAnswer].n);
		for (var i = 0; i<qIDs.length; i++) {
			qData = data[qs[i]];
			setInnerHTML("filmtitle"+i, '&quot;' + obfuscateQuote(qData.q, qData.n) + '&quot;');
		}
		el = gebi('questiontable');
		if (el) {
			el.className = 'tablelist';
		}

	}
}



////////////////////////////////////////////////////////////////////////////////

function displayTickOrCross(inp, correctAnswer) {
	var el = gebi(qIDs[inp]);
	if (el) {
		el.src = (qs[inp] == correctAnswer)?result.correct.image:result.wrong.image;
	}
}

////////////////////////////////////////////////////////////////////////////////


function disableAllButtons() {
	answered = true;
}

function answer(inp) {
	var correct;
	if (!answered) {
		disableAllButtons();

		lastAnswer = qs[inp];

		if (correctAnswer == lastAnswer) {
			run += 1;
			if (run>highScore) {
				highScore = run;
			}
		} else {
			run = 0;
			//wind back the question window to make things "easier"
			windowStart -= windowStepBack;
			if (windowStart<0) {
				windowStart = 0;
			}
		}

		displayTickOrCross(inp, correctAnswer);
		updateScreenScore();


		writeCookies();
		putPreviousAnswerOnScreen(true);
		var reload = window.setTimeout(reloadpage, 1250);
	}
}

function rightWrong(q, a) {
	return (a == q)?result.correct.display:result.wrong.display;
}

function putPreviousAnswerOnScreen(justAnswered) {
	if (prevQs.length && lastAnswer>=0){
		var lastQ = prevQs[prevQs.length-1];
		var qData = data[lastQ];
		setInnerHTML('answerbox',
				'Prev: <span class="rightwrong ' + (justAnswered?'bright':'dull') + '">' + 
				rightWrong(lastQ, lastAnswer) +
				'</span><br><small>&quot;' +
				qData.q + 
				'&quot; (' +
				amazonLink(qData.u, qData.n, 'uk') +
				')</small>');
	}
}

////////////////////////////////////////////////////////////////////////////////

function writeCookies() {
	setCookieTyped('prevQs',	prevQs,			'csv');
	setCookieTyped('run',		run,			'int');
	setCookieTyped('highscore',	highScore,		'int');
	setCookieTyped('a',			lastAnswer,		'int');
	setCookieTyped('w',			windowStart,	'int');
}


function removeallcookies()
{
	Delete_Cookie('prevQs','/');
	Delete_Cookie('run','/');
	Delete_Cookie('highscore','/');
	Delete_Cookie('a','/');
	Delete_Cookie('w','/');
	reloadpage();
}

function updateScreenScore()
{
	setInnerHTML('runbox', run);
	setInnerHTML('longestrunbox', highScore);
}

function reloadpage() {
	if ((run > switcheroo && run % switcheroo === 1) || run === 0) {
		window.location.reload();
	} else {
		newquestion();
		answered = false;
	}
}



////////////////////////////////////////////////////////////////////////////////

