window.onload = initAllQuizzes;

var initHTML = ["","","","","",""]
var containerCount = [8,5,3,20,20,8];
var containerScore = [8,5,1,8,8,8];
var correctCount = [0,0,0,0,0,0];
var attemptCount = [0,0,0,0,0,0];
var question4 = ["","","","","","","",""];
var question4_answer1 = ["T","t","t","Tt","tt","t","Tt","tt"];
var question4_answer2 = ["t","t","T","Tt","Tt","t","tt","tt"];
var question5 = ["","","","","","","",""];
var question5_answer = ["B","b","b","b","Bb","Bb","bb","bb"];
var question_scored = [false,false,false,false,false,false];
                 
function initAllQuizzes()
{
	for (var i = 0; i < containerCount.length; i++)
	{
	    initQuiz(i + 1);
	}
}

function initQuiz(containerId)
{
	// INIT SPECIFIC CONTAINER
	initHTML[(containerId - 1)] = xGetElementById("container" + containerId).innerHTML

    if( containerId == 1 || containerId == 6 || containerId == 4 || containerId == 5 ) {
	    for (var i = 0; i < containerCount[(containerId - 1)]; i++)
	    {
		    var elem;
    		
	        // Set up drag capability
	        elem = xGetElementById("c" + containerId + "-drag_" + ( i + 1));
	        xEnableDrag("c" + containerId + "-drag_" + (i + 1), fnDragStart, fnDrag, fnDragEnd);
	        elem.initX = xLeft(elem);
	        elem.initY = xTop(elem);

	        if ( containerId == 5)
	        {
		        // Remove clones from picture
		        elem = xGetElementById("c" + containerId + "-drag_" + ( i + 1) + "_clone");
		        if (elem)
			        document.body.removeChild(elem);
	        }
		   
	    }
	}
	
	// specific question for initalisation
	if( containerId == 4 )
	{
	    question4 = ["","","","","","","",""];
	}
	
	if( containerId == 5 )
	{
	    question5 = ["","","","","","","",""];
	}
	
} // end of function initQuiz

function fnDragStart(ele, mdx, mdy)
{
  var container =  ele.offsetParent;
	while (container.parentNode && (container.id.indexOf('container')==-1)) container = container.offsetParent;
	ele.offL = 0;
	ele.offR = 0;
	ele.offT = 0;
	ele.offB = 0;
	ele.bL = xPageX(container)-xPageX(ele);
	ele.bT = xPageY(container)-xPageY(ele);
	ele.bR = ele.bL+xWidth(container)-xWidth(ele);
	ele.bB = ele.bT+xHeight(container)-xHeight(ele);
	ele.style.clear = "left";
	ele.style.zIndex = 1000;
}

function fnDrag(ele, mdx, mdy)
{
  ele.offL+=mdx;
  ele.offT+=mdy;
	var x = Math.min(ele.bR,Math.max(ele.bL,ele.offL));
	var y = Math.min(ele.bB,Math.max(ele.bT,ele.offT));

	
	xMoveTo(ele, x, y);
}


function fnDragEnd(ele, mx, my)
{
	var ret;
	var containerId = ele.id.substring(2, 1);
	
	ret = fnValidTarget(ele.id, mx, my);

	attemptCount[(containerId - 1)]++;

	if (ret == null)
	{
		ele.className = "quiz_drag";
		xSlideTo(ele, ele.initX, ele.initY, 250);
	}
	else
	{
		if (ret.coords)
		{
			var image = xGetElementById("eyeImage");
			var coords = ret.coords.split(",");
			xDisableDrag(ele);
			var newEle = xGetElementById(ele.id).cloneNode(true); 
			var cont = xGetElementById("container"+containerId);
			newEle.id = newEle.id + "_clone";
			
			newEle.className = "quiz_drop_correct_image";
			var x = cont.appendChild(newEle);
			//var x = document.body.appendChild(newEle);
			ele.style.visibility = "hidden";
			xMoveTo(newEle, xOffsetLeft(image) + parseInt(coords[0]), xOffsetTop(image) + parseInt(coords[1]));
			newEle.style.width = parseInt(coords[2]) - parseInt(coords[0]);
			newEle.style.height = ele.style.height;
			// Centre vertically
			newEle.style.marginTop = ((parseInt(coords[3]) - parseInt(coords[1])) - xHeight(newEle)) / 2;
		}
		else
		{
		    if( containerId == 1 ) 
		    {
		        ret.className = "quiz_drop_correct";
		    }
		    else if( containerId == 6 ) 
		    {
		        ret.className = "quiz_drop_correct_5";
		    }
		    else if( containerId == 4 ) 
		    {
		        // do nothing this option must be left here
		    }
		    else 
		    {
		        ret.className = "quiz_drop_correct_5";
		    }
		    
			ret.innerHTML = ele.innerHTML;
			xDisableDrag(ele);
			ele.style.visibility = "hidden";
		}
		correctCount[(containerId - 1)]++;
	}

	if (correctCount[(containerId - 1)] == containerScore[(containerId - 1)])
	{
		fnShowScore(containerId);
	}
}

function fnValidTarget(id, mx, my)
{
	var elem;
	var ret = null;
	var sep = id.indexOf("_");
	var num = id.substring(sep + 1);
	var dropPrefix = "c" + id.substring(2, 1) + "-";
	var dragID = 0;
	var dropID = 0;
	var target;
	var dragValue;
	
	if (id.substring(2, 1) == 1 || id.substring(2, 1) == 6 )
	{
		for (var i = 0; i < containerCount[id.substring(2, 1) - 1]; i++)
		{
			elem = xGetElementById(dropPrefix + "drop_" + ( i + 1));
			if (mx >= xPageX(elem) && mx <= (xPageX(elem) + xWidth(elem)))
			{
				if (my >= xPageY(elem) && my <= (xPageY(elem) + xHeight(elem)))
				{
					sep = elem.id.indexOf("_");
					if (elem.id.substring(sep + 1) == num)
					{
						ret = elem;
					}
				}
			}
		}
	}
	else if( id.substring(2, 1) == 5 )
	{
	    // CHECK AGAINST MAP ELEMENTS
		// CALCULATE OFFET OF AREA ELEMENT TO THE OWNING IMAGE
		var image = xGetElementById("eyeImage");
		var imageX = xPageX(image);
		var imageY = xPageY(image);
		var imageWidth = xWidth(image);
		var imageHeight = xHeight(image);

		var att = ((IsIE() && parseInt(jQuery.browser.version) < 8) ? "classname" : "class");
		var maps = document.getElementsByTagName("area"); 
		
		for (var i = 0; i < maps.length; i++)
		{ 
			var map = maps[i]; 
			if ((map.getAttribute(att) != null) && (map.getAttribute(att) != ""))
			{
				var coords = map.coords.split(",");
				
				if (mx >= (parseInt(coords[0]) + imageX) && mx <= (parseInt(coords[2]) + imageX))
				{
					if (my >= (parseInt(coords[1]) + imageY) && my <= (parseInt(coords[3]) + imageY))
					{
						sep = map.getAttribute(att).indexOf("_");
						dropID = map.getAttribute(att).substring( sep+1 );
						if( xGetElementById(id).innerHTML == question5_answer[ dropID-1 ] && question5[dropID-1] == "" )
						{
						    question5[ (dropID-1) ] = question5_answer[ (dropID-1) ];
							ret = map;
							break;
						}
					}
				}
			}
		} 
	}
	else if( id.substring(2, 1) == 4 ) 
	{
	    // this is used for question 4
	    dragID = id.substring(8,9)
	    
	    
	    target = "";
	    for (var i = 0; i < containerCount[id.substring(2, 1) - 1]; i++)
		{
			elem = xGetElementById(dropPrefix + "drop_" + ( i + 1));
			
			if (mx >= xPageX(elem) && mx <= (xPageX(elem) + xWidth(elem)))
			{
			    if (my >= xPageY(elem) && my <= (xPageY(elem) + xHeight(elem)))
				{
                    target = elem;
				}
			}
		}
		
		// we now have the target so check to see if this is valid
		if( target != "" ) 
		{
		    dragValue = xGetElementById(id).innerHTML;
		    dropID = target.id.substring(8,9)
		    
		    // determine which answer we are using 
		    if( question4[0] == "T" ) 
		    {
		        // use question_answer1
		        if( question4_answer1[dropID-1] == dragValue )
		        {
		            question4[dropID-1] = dragValue;
		            return target;
		        }
		    }
		    else if( question4[0] == "t" ) 
		    {
		        // use question_answer2
		        if( question4_answer2[dropID-1] == dragValue )
		        {
		            question4[dropID-1] = dragValue;
		             return target;
		        }
		    }
		    else {
		        if( dropID == 1 || dropID == 3 ) {
                    // as we have not determined the answer then we can use either answer type
                    // execpt for if the drop ID is 1 or 3 in which case we must check both
                    if( question4_answer1[dropID-1] == dragValue )
                    {
                        question4[dropID-1] = dragValue;
                        return target;
                    }
                    else if ( question4_answer2[dropID-1] == dragValue )
                    {
                        question4[dropID-1] = dragValue;
                        return target;
                    }
		        }
		        else 
		        {
		            // just use answer 1
		            if( question4_answer1[dropID-1] == dragValue )
	                {
	                    question4[dropID-1] = dragValue;
	                    return target;
	                }
		        }
		    }
		
		}
	}
	
	return ret;
}

function fnResetQuestion(containerId)
{
	xGetElementById("container" + containerId).innerHTML = initHTML[(containerId - 1)];
	correctCount[(containerId - 1)] = 0;
	attemptCount[(containerId - 1)] = 0;
	question_scored[(containerId - 1)] = false;
	initQuiz(containerId);
}
/*
function fnShowScore(containerId)
{
	var popup;
	var message;
	var score;
	var attCount = attemptCount[(containerId - 1)];
	var threshold = containerScore[(containerId - 1)];
	
	question_scored[(containerId - 1)] = true;
	message = "your quiz ranking is: <br/>";
	
	if (attCount == threshold)
	{
		score = "A* - An excellent score!";
	}
	else if (attCount <= (threshold + 2))
	{
		score = "A - Very well done!";
	}
	else if (attCount <= (threshold + 4))
	{
		score = "B - Well done!";
	}
	else if (attCount > (threshold + 4))
	{
		score = "C - Try the quiz again after re-reading the section pages.";
	}

	xGetElementById("quiz_result_text").innerHTML = message;
	xGetElementById("quiz_result_score").innerHTML = score;
	xGetElementById("quiz_result_title").innerHTML = "Congratulations!";
	popup = xGetElementById("quiz_result_popup");
	popup.style.display = "block";
	var st = (document.documentElement)?document.documentElement.scrollTop:document.body.scrollTop;
	xMoveTo(popup, (xClientWidth() - xWidth(popup)) / 3, st);
}*/

function fnShowScore(containerId)
{
	var popup;
	var message;
	var score;
	var attCount = attemptCount[(containerId - 1)];
	var threshold = containerScore[(containerId - 1)];
	var wrap = xGetElementById("wrapper");
	var warp2 = xGetElementById("MainCol_inner");
	var cont = xGetElementById("container"+containerId);

	message = "your quiz ranking is: <br/>";
	
	if (attCount == threshold)
	{
		score = "A* - An excellent score!";
	}
	else if (attCount <= (threshold + 2))
	{
		score = "A - Very well done!";
	}
	else if (attCount <= (threshold + 4))
	{
		score = "B - Well done!";
	}
	else if (attCount > (threshold + 4))
	{
		score = "C - Try the quiz again after re-reading the section pages.";
	}

	xGetElementById("quiz_result_text").innerHTML = message;
	xGetElementById("quiz_result_score").innerHTML = score;
	xGetElementById("quiz_result_title").innerHTML = "Congratulations!";		
	popup = xGetElementById("quiz_result_popup");
	popup.style.display = "block";
	xMoveTo(popup, (xWidth(wrap) - xWidth(popup)) / 2, xOffsetTop(wrap)+xOffsetTop(cont)+ 100);
}



function fnHideScore()
{
	var popup;
	popup = xGetElementById("quiz_result_popup");
	popup.style.display = "none";
	return false;
}

/**
 * checks the answer of the element
 **/
function fnCheckAnswer( p_element, p_correct )
{
    var containerID;
    var questionID;
    var tickImage;
    
    containerID = p_element.id.substring(1, 2);
    questionID = p_element.id.substring(3, 4);
    tickImage = "c" + containerID + "_" + questionID + "_chk" + questionID;    

    attemptCount[(containerID - 1)] = attemptCount[(containerID - 1)] + 2;
    
    if( p_correct == 1 )
    {
        correctCount[(containerID - 1)]++;
        xGetElementById(tickImage).src = "/res/coResourceImport/modules/en-images/ans_right.gif";
    }
    else 
    {
        xGetElementById(tickImage).src = "/res/coResourceImport/modules/en-images/ans_wrong.gif";
    }
    
    // if they have answered all the questions then show their score
    if (correctCount[(containerID - 1)] == containerScore[(containerID - 1)] && !question_scored[(containerID - 1)] )
	{
		fnShowScore(containerID);
	}
    
} // end of function fnCheckAnswer

/**
 * checks the answer of the element
 **/
function fnCheckAnswer2( p_element, p_correct )
{
    var containerID;
    var questionID;
    var tickImage;
    
    containerID = p_element.id.substring(1, 2);
    questionID = p_element.id.substring(3, 4);
    tickImage = "c" + containerID + "_" + questionID + "_chk" + questionID;      
    
    attemptCount[(containerID - 1)]++;
    if( p_correct == 1 )
    {
        correctCount[(containerID - 1)]++;
        xGetElementById("c" + containerID + "_" + questionID).innerHTML = "<img src='/res/coResourceImport/modules/en-images/ans_right.gif' />";
    }
    else 
    {
        xGetElementById("c" + containerID + "_" + questionID).innerHTML = "<img src='/res/coResourceImport/modules/en-images/ans_wrong.gif' />";
    }
    
    // if they have answered all the questions then show their score
    if (attemptCount[(containerID - 1)] == containerScore[(containerID - 1)] && !question_scored[(containerID - 1)] )
	{
		fnShowScore2(containerID);
		question_scored[(containerID - 1)] = true;
	}
    
} // end of function fnCheckAnswer2

function fnShowScore2(containerId)
{
	var popup;
	var message;
	var score;
	var attCount = correctCount[(containerId - 1)];
	var threshold = containerScore[(containerId - 1)];
    
    question_scored[(containerId - 1)] = true;
	message = "your quiz ranking is: <br/>";
	
	if (attCount == threshold)
	{
		score = "A* - An excellent score!";
	}
	else if (attCount == (threshold - 1))
	{
		score = "A - Very well done!";
	}
	else if (attCount == (threshold - 2))
	{
		score = "B - Well done!";
	}
	else if (attCount <= (threshold - 3))
	{
		score = "C - Try the quiz again after re-reading the section pages.";
	}
	xGetElementById("quiz_result_text").innerHTML = message;
	xGetElementById("quiz_result_score").innerHTML = score;
	xGetElementById("quiz_result_title").innerHTML = "Congratulations!";
	popup = xGetElementById("quiz_result_popup");
	popup.style.display = "block";
	var st = (document.documentElement)?document.documentElement.scrollTop:document.body.scrollTop;
	xMoveTo(popup, (xClientWidth() - xWidth(popup)) / 3, st);
}



