var webroot = '/';
var console;
var containerid;

var notFound;

var questionNum = 0;
var trueAnswers = 0;
var errorAnswers = new Array();
var rightAnswers = new Array();
var errorForMail = '';
var rightForMail = '';
var ua = navigator.userAgent;

if(!console) {
    console = { log: function() {} } 
}

var isMSIE = (navigator.appName == "Microsoft Internet Explorer");
var isMSIE6_0 = isMSIE && (ua.indexOf('MSIE 6.0') != -1);

$(document).ready( function() {
	
	if($("body").height() > 645) {
		var wrapTop = ($("html").height() / 2 - 322);

		$("#wrapp").css('margin-top', wrapTop+'px');
	}

	$("a.close").click( function () {
		//$("#blank").fadeOut();
		//$("#show-popup").hide();
		$("#show-competition").hide();
		$("#show-flash").show();

		if(isMSIE6_0) {
			$("#select-country").show();
			$("#country").show();
			$(".fake-select").hide();
		}
	});

	$("#header .submit").click( function() {
		document.location.target = '_blank';
		document.location.href = $("#select-country").val();

		if($("#select-country").val() == '#')
			ajaxpage('view/no-country-form', 'right-ajax');

		$("#select-country").val('');
	});
	
	$("a.competition").click( function() {
		//$("#show-popup").hide();
		$("#show-flash").fadeOut();
		$("#show-competition #next-question").show();

		questionNum = 0;
		trueAnswers = 0;
		errorAnswers = new Array();
		rightAnswers = new Array();
		errorForMail = '';
		rightForMail = '';

		$("#show-competition span.num").html('Question 1');
		$("#show-competition span.result").html('<font class="green-cl">' + trueAnswers + '</font> correct out of ' + questionNum);

		url = webroot + 'question/' + $(this).get(0).name + '/1';

		$("#show-competition blockquote label").html('');
		$("#show-competition blockquote ul").html('');
		$("#show-competition blockquote em").html('');

		$.getJSON(url, function(question) {
			$("#show-competition blockquote label").html(question['question']);

			var where = $("#show-competition blockquote ul").get(0);
			
			for(i = 0; i < question['answer'].length; i++) {
				var what = 
					$.LI( { }, 
						$.A( { name: i, Class: 'clickable' }, question['answer'][i])
					);

				$("a", what).click( function() {
					$("a.clickable").unbind( "click" );

					questionNum++;

					if($(this).get(0).name == question['correct']) {
						rightAnswers.unshift(question['question']);
						$(this).addClass('green');
						trueAnswers++;
					} else {
						errorAnswers.unshift(question['question']);
						$(this).addClass('red');
					}

					$("#show-competition span.result").html('<font class="green-cl">' + trueAnswers + '</font> correct out of ' + questionNum);
				});

				where.appendChild(what);
			}
		});

		$("#show-competition").fadeIn();
	});

	//$("#show-competition #next-question").click( function() {

	//});
	
	if(notFound == true)
		Common.popup('view/not-found');
});

Common = {
	send: function () {
		$("#send-to-friend .validate").each( function() {
			error = 0;

			if($(this).val() == '') {
					$(this).addClass('error');
					error = 1;
				} else {
					$(this).removeClass('error');
				}
			});

		if(error > 0) {
			alert('Please fill all fields');

			return false;
		}


		return $.post('/home', { 
			action: 'send_to_friend', 
			'from-name': $("#send-to-friend #from-name").val(), 
			'from-email': $("#send-to-friend #from-email").val(), 
			'to-name': $("#send-to-friend #to-name").val(), 
			'to-email': $("#send-to-friend #to-email").val(), 
			message: $("#send-to-friend #message").val()
		}, function(data) { });

		return false;
	},

	sendCountry: function () {
		$("#no-country-form .validate").each( function() {
			error = 0;

			if($(this).val() == '') {
					$(this).addClass('error');
					error = 1;
				} else {
					$(this).removeClass('error');
				}
			});

		if(error > 0) {
			alert('Please fill all fields');

			return false;
		}


		return $.post('/home', { 
			action: 'no_country', 
			name: $("#no-country-form #name").val(), 
			country: $("#no-country-form #country").val(), 
			email: $("#no-country-form #email").val(), 
			phone: $("#no-country-form #phone").val(), 
			message: $("#no-country-form #message").val()
		}, function(data) { });

		return false;
	},
	
	sendCompetition: function () {
		$("#competition-form .validate").each( function() {
			error = 0;

			if($(this).val() == '') {
					$(this).addClass('error');
					error = 1;
				} else {
					$(this).removeClass('error');
				}
			});

		if(error > 0) {
			alert('Please fill all fields');

			return false;
		}


		return $.post('/home', { 
			action: 'send_competition', 
			correct: trueAnswers, 
			wrong: (questionNum - trueAnswers), 
			total: questionNum, 
			competitionSlug: $(".competition").get(0).name, 
			'errors': errorForMail, 
			'rights': rightForMail, 
			'first-name': $("#competition-form #first-name").val(), 
			'last-name': $("#competition-form #last-name").val(), 
			address: $("#competition-form #address").val(), 
			address2: $("#competition-form #address2").val(), 
			country: $("#competition-form #country").val(), 
			city: $("#competition-form #city").val(), 
			email: $("#competition-form #email").val(), 
			telephone: $("#competition-form #telephone").val(),
			newsletter: $("#competition-form #newsletter").get(0).checked
		}, function(data) { });

		return false;
	},
	
	show: function(containerid) {
		$("#"+containerid).fadeIn();
	},
	
	popup: function(url) {
		ajaxpage(url, 'popup');

		var arrPageSizes = Common.getPageSize();

		var popupTop = (arrPageSizes[1] / 2 - 245);
		var popupLeft = (arrPageSizes[0] / 2 - 325);
	
		$("#popup").css({
			'margin-top': popupTop,
			'margin-left': popupLeft
		});

		$("#blank").css({
			opacity: 0.8,
			width: arrPageSizes[0],
			height: arrPageSizes[1]
		});

		if(isMSIE6_0) {
			$("#select-country").hide();
			$("#country").hide();
			$(".fake-select").show();
		}

		$("body").css('overflow', 'hidden');
		$("#blank").fadeIn();
		$("#popup").fadeIn();

		//$("#show-popup").show();
		//$("#show-competition").hide();
		//$("#show-flash").hide();

		$("#blank").click( function () {
			$("body").css('overflow', 'visible');
			$("#popup").fadeOut();
			$("#blank").fadeOut( function () {
				if(isMSIE6_0) {
					$("#select-country").show();
					$("#country").show();
					$(".fake-select").hide();
				}
			});
		});

		$("#popup").append('close');
	},
	
	nextQuestion: function () {
		$("#show-competition blockquote").fadeOut();
		$("#show-competition #next-question").show();

		$("#show-competition span.result").html('<font class="green-cl">' + trueAnswers + '</font> correct out of ' + questionNum);

		url = webroot + 'question/' + $(".competition").get(0).name + '/' + (questionNum + 1);

		$("#show-competition blockquote label").html('');
		$("#show-competition blockquote ul").html('');
		$("#show-competition blockquote em").html('');

		$.getJSON(url, function(question) {
			if(question['question'] == '') {
				var needListing = '';

				if(parseFloat(trueAnswers) != parseFloat(questionNum)) {
					needListing = ', the questions you got wrong are:'
					url = webroot + 'questions/' + $(".competition").get(0).name;

					$.getJSON(url, function(questions) {
						var where = $("#show-competition blockquote ul").get(0);

						for(i = 0; i < questions.length; i++) {
							for(z = 0; z < errorAnswers.length; z++) {
								if(errorAnswers[z] == questions[i]['question']) {
									var what = 
										$.LI( { Class: 'small' }, 
											'Q' + (i+1) + '. ' + questions[i]['question'] +' ',
											$.SPAN( { Class: 'green-cl' }, 'A: '+ questions[i]['answer'][questions[i]['correct']] )
										);

									where.appendChild(what);

									errorForMail += questions[i]['question']+'<br />';
								}
							}

 							for(y = 0; y < rightAnswers.length; y++) {
								if(rightAnswers[y] == questions[i]['question']) {
/* 									var what = 
										$.LI( { Class: 'small' }, 
											'Q' + (i+1) + '. ' + questions[i]['question'] +' ',
											$.SPAN( { Class: 'green' }, 'A: '+ questions[i]['answer'][questions[i]['correct']] )
										);

									where.appendChild(what); */

									rightForMail += questions[i]['question']+'<br />';
								}
							}
						}
					});
				}

				$("#show-competition span.num").html('Results.');
				$("#show-competition blockquote label").addClass('small');
				$("#show-competition blockquote label").html('You answered ' + trueAnswers + ' out of ' + questionNum + needListing);
				$("#show-competition blockquote em").html('To enter the prize draw please complete the form on the right');

				$("#show-competition #next-question").hide();
				$("#show-competition").fadeIn();

				ajaxpage('view/competition-form', 'right-ajax');

				return false;
			}

			$("#show-competition span.num").html('Question ' + (questionNum + 1));
			$("#show-competition blockquote label").html(question['question']);

			var where = $("#show-competition blockquote ul").get(0);
			
			for(i = 0; i < question['answer'].length; i++) {
				var what = 
					$.LI( { }, 
						$.A( { name: i, Class: 'clickable' }, question['answer'][i])
					);

				$("a", what).click( function() {
					$("a.clickable").unbind( "click" );

					questionNum++;

					if($(this).get(0).name == question['correct']) {
						rightAnswers.unshift(question['question']);
						$(this).addClass('green');
						trueAnswers++;
					} else {
						errorAnswers.unshift(question['question']);
						$(this).addClass('red');
					}

					$("#show-competition span.result").html('<font class="green-cl">' + trueAnswers + '</font> correct out of ' + questionNum);
				});

				where.appendChild(what);
			}

		});
		$("#show-competition blockquote").fadeIn();
	},

	getPageSize: function () {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	}
}