var workingMenu=0, menuOpen=0, mouseOnMenu=0, questionCorrect = false, answeredIncorrectly = 0, questionNum = 1, messageTimeout, right1stTime = 0, topNewsEventsBox = 0, currentTopBoxCont = 1, iPart=1,galImageNum;

var quizAnswers = new Array, quizQuestions = new Array, quizCorrect = new Array, correct1stTime = new Array, newsEventsBoxes = new Array, partnerLogo = new Array, galleryImgArr = new Array, galleryImgHeight = new Array, galleryTotalImg = new Array, currentGallery;

function setUpPartnerSwaps() {
	var int2 = setInterval ( swapPartnerImages, 3000 )
}

function swapPartnerImages () {
	cross2 = new crossfade($('partner_image'), pageURL+'images/partner_logos/'+partnerLogo[iPart][0], '1', partnerLogo[iPart][1]);
	$("partnerLink").href = partnerLogo[iPart][2];
	if (iPart<4) iPart=iPart+1; else iPart=1;
}

function alertBox (message,title) {
	if (title=='') title = 'Message'; 
	$('alertMessage').innerHTML=message;
	$('alertTitle').innerHTML=title;
	centreElement ('alertBox');
	$('alertBox').show();
	if (messageTimeout != null) clearTimeout(messageTimeout);
	messageTimeout=setTimeout(function(){ $('alertBox').hide(); },1500);
}

function centreElement (e, vert) {
	var theScrolls = document.viewport.getScrollOffsets();
	theLeft = Math.floor(((document.viewport.getWidth())-($(e).getWidth()))/2) + theScrolls[0];
	theTop = Math.floor(((document.viewport.getHeight())-($(e).getHeight()))/2) + theScrolls[1];
	if (theTop < 0) theTop = 0;
	if (vert==1)  {
		$(e).setStyle({ top: '0px' });
		$(e).setStyle({ top: theTop+'px' });
	}
	$(e).setStyle({ left: theLeft+'px' });
	
}

function setUpCancersMenu () {
	$('cancersLink').observe('mouseover', function () { displayCancersMenu(1); });
	$('cancersMenu').observe('mouseover', function () { displayCancersMenu(1); });
	$('cancersLink').observe('mouseout', function () { displayCancersMenu(0); });
	$('cancersMenu').observe('mouseout', function () { displayCancersMenu(0); });
	arr=$('cancersMenu').descendants()
	arr.each(function(node){
		$(node.id).observe('mouseover', function () { 
			$(node.id).setStyle({ backgroundColor: '#011e9c', cursor: 'pointer', color: '#ffffff' });
			displayCancersMenu(1);
			$(node.id).observe('click', function () { window.location=pageURL+node.id+'-Cancer'; });
		});
		$(node.id).observe('mouseout', function () { $(node.id).setStyle({ backgroundColor: '#ffffff', color: '#000000' }); });
   	});
}

function displayCancersMenu (num) {
	if (num>0) {
		clearTimeout(theTime);
		mouseOnMenu=1;
		if (workingMenu==0 && menuOpen==0) {
			workingMenu=1;
			new Effect.BlindDown('cancersMenu', {duration:0.3, afterFinish: function (){ 
				workingMenu=0; menuOpen=1;
				if (mouseOnMenu < 1) displayCancersMenu(0);
			}});
		}
	}
	else { 
		mouseOnMenu=0;
		if (workingMenu==0 && menuOpen==1) {
			var theTime=setTimeout("closeCancersMenu()",1000);
		}
	}
}

function closeCancersMenu () {
	if (mouseOnMenu==0 && menuOpen==1 && workingMenu==0) {
		workingMenu=1;
		new Effect.BlindUp('cancersMenu', {duration:0.3, afterFinish: function (){ workingMenu=0; menuOpen=0;}});
	}
}

function loadNewsEvents () {
	newTop = $('eventsNewsBox1').getHeight();
	if (newTop > 124) {
		Move.element('eventsNewsBox1', 'eventsAndNews', 'copy');
		$('eventsNewsBox2').setStyle({ top: newTop+'px' });
		setInterval ( "scrollNewsEvents()", 4000 );
	}
}

function scrollNewsEvents () {
	totalBoxes = $('eventsNewsBox1').childNodes.length -1;
	if (topNewsEventsBox < totalBoxes) {
		++topNewsEventsBox;
	}
	moveHeight = ($('eventsNewsBox'+currentTopBoxCont+'Item'+topNewsEventsBox).getHeight() + 11);
	new Effect.Move('eventsNewsBox1', { x: 0, y: -moveHeight, mode: 'relative' });
	new Effect.Move('eventsNewsBox2', { x: 0, y: -moveHeight, mode: 'relative', afterFinish: function () {
		currentTop = $('eventsNewsBox'+currentTopBoxCont).style.top;
		currentTop = currentTop.replace(/px/,"");
		currentTop = parseInt(currentTop);
		boxHeight = $('eventsNewsBox'+currentTopBoxCont).getHeight(); boxHeight = boxHeight - (boxHeight*2);
		if (currentTop <= boxHeight) {
			topNewsEventsBox = 0;
			newTop = $('eventsNewsBox'+currentTopBoxCont).getHeight();
			$('eventsNewsBox'+currentTopBoxCont).setStyle({ top: newTop+'px' });
			if (currentTopBoxCont == 1) currentTopBoxCont=2; else currentTopBoxCont=1;
			$('eventsNewsBox'+currentTopBoxCont).setStyle({ top: '0px' });
		}
	}});
}

var Move =	{

  copy	:   function(e, target)	{
	    	var eId      = $(e);
	    	var copyE    = eId.cloneNode(true);
	    	var cLength  = copyE.childNodes.length -1;
	    	//copyE.id     = e+'-copy';
			copyE.id     = 'eventsNewsBox2';
			var i2 = 1;
	    	for(var i = 0; cLength >= i;  i++)	{
	    		if(copyE.childNodes[i].id) {
	    			var cNode   = copyE.childNodes[i];
	    			var firstId = cNode.id;
	    			cNode.id    = 'eventsNewsBox2Item'+i2;
					++i2;
				}
	    	}
	    	$(target).appendChild(copyE);
	    },
  		element:  function(e, target, type)	{
	    	var eId =  $(e);
	    	if(type == 'move') {
	       		$(target).appendChild(eId);
	    	}
			else if (type == 'copy') {
	       		this.copy(e, target);
	    	}
	    }
}


// QUIZ
function loadQuiz() {
	$('startButton').observe('click', startQuiz);
	$('startButton').innerHTML='';
	$('questionNumbers').innerHTML = '';
	for (var index = 1, len = quizQuestions.length; index < len; ++index) {
		$('questionNumbers').innerHTML = $('questionNumbers').innerHTML + '<div class="quizPanelQuestionBox" id="questionNumber' + index +'">' + index +'</div>';
	}
	loadQuizQuestion (questionNum);
}

function loadQuizQuestion (num) {
	questionCorrect = false;
	questionNum=num;
	$('questionAnswers').innerHTML = '';
	$('currentQuestionNum').innerHTML = num + '.';
	$('currentQuestion').innerHTML = quizQuestions[num];
	$('questionNumber'+questionNum).setStyle({ backgroundColor: '#011e9c',color:'#ffffff'});
	for (var index = 0, len = quizAnswers[num].length; index < len; ++index) {
		$('questionAnswers').innerHTML = $('questionAnswers').innerHTML + '<div class="quizQuestionContainer3" id="questionCont2' + index +'"><div class="quizQuestionContainer" id="questionCont' + index +'" onmouseover="highlightQuizAnswer(' + index +',1)" onmouseout="highlightQuizAnswer(' + index +',0)" onclick="checkAnswer (' + (index+1) +'); return false;"><div class="quizBullet" id="bullet' + index +'"><img src="'+pageURL+'images/bullet_off.gif" alt="Bullet" /></div><div class="quizQuestionContainer2">' + quizAnswers[num][index] + '</div></div></div>';
	}
}

function afterCorrect () {
	var questions = quizQuestions.length-1;
	if (questions>questionNum) {
		loadQuizQuestion (questionNum+1);
	}
	else {
		var i=1;
		while (i <= questions) {
			if (correct1stTime[i] == 1) {
				++right1stTime;
			}
		++i;
		}
		$('currentQuestion').innerHTML = '&nbsp;';
		$('currentQuestionNum').innerHTML = '&nbsp;';
		$('questionAnswers').innerHTML = '&nbsp;';
		$('quizCompleteMessage').innerHTML = 'You\'ve answered '+right1stTime+' questions correctly 1st time. Please fill in your details below to enter our free prize draw.';
		centreElement ('quizCompleteBox');
		$('closeButton').stopObserving('click', closeQuiz);
		$('closeButton2').observe('click', closeQuiz);
		$('quizCompleteSend').observe('click', sendQuizDetails);
		$('quizPanel').setStyle({ opacity: 0.5});
		$('quizCompleteBox').show();
		questionNum=1;
	}
}

function checkAnswer (a) {
	var correct = false;
	var allCorrect = false;
	
	if (questionCorrect == false) {
	
		if (isArray(quizCorrect[questionNum])) {
			for (var index = 0, len = quizCorrect[questionNum].length; index < len; ++index) {
				if (a == quizCorrect[questionNum][index]) {
					correct = true;
					quizCorrect[questionNum][index]=0;
				}
			}
			var correctAnswers = quizCorrect[questionNum].length;
			var currentCorrectAnswers = 0;
			for (var index = 0, len = quizCorrect[questionNum].length; index < len; ++index) {
				if (quizCorrect[questionNum][index]<1) ++currentCorrectAnswers;
			}
			if (correct) {
				if (currentCorrectAnswers >= correctAnswers) {
					alertBox ('Well done, you have now found all the correct answers to this question.','');
					allCorrect=true;
					questionCorrect = true;
				}
				else {
					var answersLeft = correctAnswers - currentCorrectAnswers;
					if (answersLeft>1) {
						alertBox ('Well done, but there are still '+ answersLeft +' more correct answers to find','');
					}
					else {
						alertBox ('Well done, but there is still 1 more correct answer to find','');
					}
				}
			}
		}
		else {
			if (a == quizCorrect[questionNum]) {
				correct = true;
				allCorrect = true;
				alertBox ('Well done','');
				questionCorrect = true;
			}
		}
		if (correct == false) {
			correct1stTime[questionNum]=2;
			alertBox ('That answer was incorrect','');
			++answeredIncorrectly;
			$('questionCont2'+(a-1)).innerHTML = '<div class="quizQuestionContainer" id="questionCont' + (a-1) +'"><div class="quizBullet" id="bullet' + a +'"><img src="'+pageURL+'images/bullet_off.gif" alt="Bullet" /></div><div class="quizQuestionContainer2">' + quizAnswers[questionNum][(a-1)] + ' <img src="'+pageURL+'images/cross.gif" /></div></div>';
		}
		else {
			
			if (correct1stTime[questionNum] != 2) correct1stTime[questionNum]=1;
			
			$('questionCont2'+(a-1)).innerHTML = '<div class="quizQuestionContainer" id="questionCont' + (a-1) +'"><div class="quizBullet" id="bullet' + a +'"><img src="'+pageURL+'images/bullet_off.gif" alt="Bullet" /></div><div class="quizQuestionContainer2">' + quizAnswers[questionNum][(a-1)] + ' <img src="'+pageURL+'images/tick.gif" /></div></div>';
			$('questionNumber'+questionNum).setStyle({ backgroundColor: '#006600',color:'#ffffff'});
		}
		if (allCorrect == true) setTimeout(function(){ afterCorrect (); },1500);
	}
}

function highlightQuizAnswer (a,i) {
	var b,c;
	if (i == 1) { b = '#900'; c = 'pointer'; } else { b = '#FFF'; c = 'default'; }
	$('questionCont'+a).setStyle({ borderColor: b,cursor:c});
}

function isArray(obj) {
	return (obj.constructor.toString().indexOf("Array") != -1);
}

function startQuiz () {
	pageWidth = document.viewport.getWidth(); pageHeight = document.viewport.getHeight(); quizLeft = Math.floor((pageWidth-488)/2);
	$('quizPanel').setStyle({ left: quizLeft+'px' });
	$('quizPanelOverlay').setStyle({ opacity: '0.6', display: 'block', width:pageWidth+'px', height:pageHeight+'px' });
	new Effect.Appear('quizPanel', {duration:0.3, afterFinish: function (){ new Effect.BlindDown('quizPanelContent', {duration:0.8});}});;
	$('closeButton').observe('click', closeQuiz);
}

function closeQuiz () {
	$('quizCompleteBox').hide();
	new Effect.BlindUp('quizPanelContent', {duration:0.8});
    new Effect.Fade('quizPanel', {duration:0.3, delay:0.8, afterFinish: function (){ $('quizPanel').setStyle({ opacity: 1.0}); $('quizPanelOverlay').hide();}});
}

function sendQuizDetails () {
	var allNodes = Form.serialize("quizUserForm");
	var aj1 = new Ajax.Request(pageURL+'ajaxStuff.php', {method: 'post', parameters: 'quizDetails=1'+'&right1stTime='+right1stTime+'&'+allNodes,onComplete: function(response) {
		var response = response.responseText;
		if (response == 'Thank you. Your details have been entered.') {
				$('quizUserForm').reset();
				questionNum = 1;
				$('closeButton2').stopObserving('click', closeQuiz);
				setTimeout(function(){ closeQuiz(); },800);
		}
		alertBox (response,'');
		if (messageTimeout != null) clearTimeout(messageTimeout);
		messageTimeout=setTimeout(function(){ $('alertBox').hide(); },3000);
	}});
}

/* QUIZ QUESTIONS */
quizQuestions[1] = 'What percentage of UK smokers say that they want to quit?';
quizQuestions[2] = 'The level of carbon monoxide is completely removed from the body after how many hours of stopping smoking?';
quizQuestions[3] = 'How many chemicals are there in tar?';
quizQuestions[4] = 'What are the chances of a lifelong male smoker living until he is 73 years old?';
quizQuestions[5] = 'What is the most common cause of death for males?';
quizQuestions[6] = 'How many people in the UK get cancer of the bowel in their lifetime?';
quizQuestions[7] = 'What is the most common symptom of testicular cancer?';
quizQuestions[8] = 'What is the standard treatment for testicular cancer?';
quizQuestions[9] = 'Where is the prostate gland?';
quizQuestions[10] = 'What is the most common symptom of prostate cancer?';
quizQuestions[11] = 'What is the standard treatment for prostate cancer?';
quizQuestions[12] = 'At birth, females in the western world have a longer life expectancy than males. By about how many years on average?';
quizQuestions[13] = 'A man should consider losing weight if his Body Mass Index (BMI) exceeds:-';
quizQuestions[14] = 'Ideally, what proportion of a man’s body should be made up of fat?';
quizQuestions[15] = 'Which sex is more likely to be overweight?';
quizQuestions[16] = 'The recommended sensible weekly drinking limit for men is (one unit = 1/2 pint of beer):';
quizQuestions[17] = 'Which of the following could be symptoms of depression in men?';

quizAnswers[1] = new Array('49%','69%','79%','89%');
quizAnswers[2] = new Array('8 hours','12 hours','24 hours','48 hours');
quizAnswers[3] = new Array('1000','4000','8000');
quizAnswers[4] = new Array('42%','52%','62%','72%');
quizAnswers[5] = new Array('Prostate Cancer','Heart disease','Lung cancer','Road accidents');
quizAnswers[6] = new Array('1 in 1000','1 in 100','1 in 50','1 in 20');
quizAnswers[7] = new Array('Generally feeling tire and run down','Traces of blood in urine or semen','A painless lump in the scrotum','Severe back pain');
quizAnswers[8] = new Array('Wait and see how big it gets before removing the tumour','Completely removing the scrotum','Taking drugs (eg. Chemotherapy)','Removing the affected testicle');
quizAnswers[9] = new Array('In the brain','In the neck','Beside the liver','Beneath the bladder');
quizAnswers[10] = new Array('Frequent urination','Blood in urine or semen','Swelling in the groin','An aching penis');
quizAnswers[11] = new Array('Watch and wait to see how it develops before taking any action','Radiotherapy','Completely removing the prostate gland','Removing the testicles');
quizAnswers[12] = new Array('1-2','3-4','6-7','10-11');
quizAnswers[13] = new Array('20','25','30','35');
quizAnswers[14] = new Array('5-10%','15-20%','25-30%','35-40%');
quizAnswers[15] = new Array('Males','Females','Both are equally likely');
quizAnswers[16] = new Array('12 units','21 units','35 units','50 units');
quizAnswers[17] = new Array('Anxiety and irritability','Feelings of emptiness and dissatisfaction','Fatigue','Indecisiveness','Disturbed sleep','Aggressive behaviour','Taking on more and more work');

quizCorrect[1] = 2;
quizCorrect[2] = 3;
quizCorrect[3] = 2;
quizCorrect[4] = 1;
quizCorrect[5] = 2;
quizCorrect[6] = 4;
quizCorrect[7] = 3;
quizCorrect[8] = 4;
quizCorrect[9] = 4;
quizCorrect[10] = 1;
quizCorrect[11] = new Array(1,2,3);
quizCorrect[12] = 3;
quizCorrect[13] = 2;
quizCorrect[14] = 2;
quizCorrect[15] = 1;
quizCorrect[16] = 2;
quizCorrect[17] = new Array(1,2,3,4,5,6,7);


Event.observe(window, 'load', loadQuiz);
Event.observe(window, 'load', setUpPartnerSwaps);
Event.observe(window, 'load', setUpCancersMenu);
Event.observe(window, 'load', loadNewsEvents);


function nxtPrevGalIm (dir) {
	if (dir == 'l') {
		if (currentGalImg==1) {
			galImageNum = galleryTotalImg[currentGallery];
		}
		else {
			galImageNum = currentGalImg - 1;
		}
	}
	else {
		if (currentGalImg<galleryTotalImg[currentGallery]) {
			galImageNum = currentGalImg + 1;	
		}
		else {
			galImageNum = 1;
		}
	}
	currentGalImg =galImageNum;
	$('galleryMainImageCont').innerHTML='<img src="images/gallery/' + galleryImgArr[currentGallery][galImageNum] +'" />';
	$('galleryMainImageCont').setStyle({ height: galleryImgHeight[currentGallery][galImageNum]+'px' });
	centreElement ('galleryContainer', 1);
}

function loadGallery (galleryID) {
	currentGallery=galleryID;
	currentGalImg=1;
	$('galleryContainer').show();
	pageWidth = document.viewport.getWidth(); pageHeight = document.viewport.getHeight(); quizLeft = Math.floor((pageWidth-488)/2);
	$('quizPanel').setStyle({ left: quizLeft+'px' });
	$('quizPanelOverlay').setStyle({ opacity: '0.6', display: 'block', width:pageWidth+'px', height:pageHeight+'px' });
	$('galleryMainImageCont').setStyle({ height: galleryImgHeight[currentGallery][galImageNum]+'px' });
	$('galleryMainImageCont').innerHTML='<img src="images/gallery/' + galleryImgArr[currentGallery][currentGalImg] + '" />';
	centreElement ('galleryContainer', 1);
}

function closeGallery () {
	currentGallery=null;
	currentGalImg=null;
	$('galleryMainImageCont').innerHTML='';
	$('galleryContainer').hide();
	$('quizPanelOverlay').hide();
}

function pageOverlay(overlayID) {
	var theScrolls = document.viewport.getScrollOffsets();
	pageWidth = document.viewport.getWidth() + theScrolls[0]; pageHeight = document.viewport.getHeight() + theScrolls[1];
	if (pageWidth < $('container').getWidth()) pageWidth = $('container').getWidth();
	if (pageHeight < $('container').getHeight()) pageHeight = $('container').getHeight();
	$(overlayID).setStyle({ opacity: '0.6', display: 'block', width:pageWidth+'px', height:pageHeight+'px' });
	$(overlayID).show();
}