GLOBAL = {};
GLOBAL.attempts=0;


(function($) {
  $.randomize = function(arr) {
     for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
     return arr;
  };
})($);


$(document).ready(function(){
		
	// Properties of each choice
	// Display choices using data from data.js
	var choices=[];
	if($.isArray(data.choices)) {
		$.each(data.choices, function(key, item) {
            choice_num = key + 1;
            choices.push("<a id=\"choice"+choice_num+"\" href=\"javascript:void(0)\" class=\"choice\" tabindex=\"-1\"><span>"+ item.text+"</span></a>");
		});
	}

    $('body').addClass(data.name); //so CSS can distinguish between different activities

	//do a quick shuffle
	if(data.randomize === "yes") {
		$.randomize(choices);
	}
	// Display choices using data from data.js
	for (var choice in choices){
		$(".choices").append(choices[choice]);
	}

	$('.choice').draggable( {
		containment: '#content',
		cursor: 'move',
		stack: '.choice',
		revert: true
	} );
	
	// Write background image from data.js at the top of targets div	
	//$(".targets").prepend(" <img src=\"" + data.backgroundimage + "\"></img>"); //no background image needed
	
	
	// Display labels and set css from data.js
	/* labels not needed
	if($.isArray(data.labels)) {

		$.each(data.labels, function(key, item) {
            label_num = key + 1;
            $(".targets").append("<div id=\"labeltext"+label_num+"\" class=\"label\"><span>"+ item.text+"</span></div>");
            $("#labeltext"+label_num).css("top",item.top);
            $("#labeltext"+label_num).css("left",item.left);
            $("#labeltext"+label_num).css("width",item.width);
            $("#labeltext"+label_num).css("text-align",item.textalign);
		});
	} */
	
	// Apply locations of droppable areas from data.js (in css)
	/*
	if($.isArray(data.droppableareas)) {
		$.each(data.droppableareas, function(key, item) {
            droppable_num = key + 1;
            $(".targets").append("<div id=\"droppable-area"+droppable_num+"\" class=\"choice"+droppable_num+" droppable\"><a href=\"javascript:void(0)\"><img src=\"clear-spot.gif\"></img></a></div>");
            $("#droppable-area"+droppable_num).css("top",item.top);
            $("#droppable-area"+droppable_num).css("left",item.left);
        });
	} */


    // Display buttons and set css from data.js
    if($.isArray(data.buttons)) {
        $.each(data.buttons, function(key, item) {
            button_num = key + 1;
            $(".buttons").append("<div id=\"button_"+button_num+"\" class=\"button\"><input type=\"button\" value=\""+ item.text+"\" tabindex=\""+ (item.tab+data.questions.length) +"\"></input></div>");
			$("#button_"+button_num).css("float",item.align);
            var thisScript=item.script;
            $(".buttons #button_"+button_num+" input").click(function(){
                eval(thisScript);
            });

        });
    }
    

    if($.isArray(data.questions)) {
        $.each(data.questions, function(key, item) {
            text_num = key + 1;
            var new_html = item.text.replace('---------','<span id=\"droppable-area'+text_num+'\" class=\"choice'+text_num+' droppable\"><a href=\"javascript:void(0);\" tabindex=\"'+text_num+'\"><img src=\"clear-spot.gif\" border=\"0\"></img></a></span>');
            $(".targets").append("<div id='text-area-"+text_num+"' class='text-area'>"+new_html+"</div>");
        });
    }


	$(".choice").css("font-size",data.choicefontsize);
	$(".choice").css("color",data.choicetextcolour);
	$(".label").css("font-size",data.labelfontsize);
	$(".label").css("color",data.labeltextcolour);
	
	
	//target	
    // if class of droppable, then make droppable
	$(".droppable").droppable({
         // Event triggered when an accepted draggable(choice) is dropped on the droppable
            drop:function(event, ui){
			ui.draggable.css({top:"0px",left:"0px"});//lock in place
			// Return choice back to choices div if in current target (droppable)
			$(".choices").append($(this).find(".choice").css({left:"",top:""}).removeClass("selected"));//chuck out any choices that were already there and put back into top list
			// Add draggable html to droppable
			$(this).html(ui.draggable);//add to target
        }
	});
	
	// If target is clicked (tapped)
	$(".targets div span").click(function(){


		if($(".choices a.selected").length){
            //if one of the choices has been selected by clicking on it
			$(".choices").append($(this).find(".choice").css({left:"",top:""}).removeClass("selected"));//chuck out
			// Add html of the 'selected' choice in the list at the top
			$(this).html($(".choices a.selected"));//append
            console.log('full');

		// otherwise we'll put in first of the choices
		} else if($(this).hasClass("selected")){
            var tabNum = $(this).parent().index()+1;

            if ($(".choices a").length === 0) {// if all targets have been filled by choices a tags
                $(".choices").append($(this).find(".choice").css({left:"",top:""}).removeClass("selected"));//chuck out
                var newString="<a href=\"javascript:void(0);\" tabindex=\""+tabNum+"\"><img src=\"clear-spot.gif\" border=\"0\"></img></a>";
                $(this).html(newString);
                console.log('goodbye');
            } else { //there are still targets to be filled
                $(".choices").append($(this).find(".choice").css({left:"",top:""}).removeClass("selected"));//chuck out (cant put before condition test so must be repeated)
                // select first of the items from the choices
                $(this).html($(".choices a").eq(0));
                $(this).find('a').attr("tabindex",tabNum);
                console.log('empty');
            }
            $(".choices a").attr("tabindex","-1"); //we dont wont these gaining a tab index

        }


		$(".targets div span").removeClass("selected");
		$(this).addClass("selected");
		$(this).find("a").focus();
	});
	// Add 'selected' to choice selected
	$(".choices a").click(function(){
		if($(this).hasClass("selected")){
			$(".choices a").removeClass("selected");
		}else{
			$(".choices a").removeClass("selected");
			$(this).addClass("selected");
			$(this).focus();
		}
	});


    $(".targets div span").focusin(function(){
      //  $(".targets div span").removeClass("selected");
        $("#content").addClass("targeting");
    });
    $(".targets div span").focusout(function(){
        $("#content").removeClass("targeting");
    });


});

function checkAnswer() {
    GLOBAL.attempts++;
    var correctResponses=0;
    var numOfQuestions=0;
    if($.isArray(data.questions)) {
        $.each(data.questions, function(key, item) {
            text_num = key + 1;
            var userAttempt = $("#text-area-"+text_num+" span a").text();
            var correctAnswerArray= new Array();
            $.each(item.answers, function(i, answer) {
                //var correctAnswer = item.answers.one;
                correctAnswerArray.push(answer.text);
                console.log('test:'+text_num + '- '+ i + ', '+answer.text);
            });
            if (jQuery.inArray(userAttempt, correctAnswerArray) !== -1) correctResponses++;
            //if (correctAnswer === userAttempt) correctResponses++;
            console.dir(correctAnswerArray);
            numOfQuestions++;
        });
    }
    if (correctResponses === numOfQuestions) {
        revealAnswer();
        $(".feedback-area").text("Nice one mate, you got it all right");
    } else {
        if (GLOBAL.attempts === 1) {
            $(".feedback-area").html('Your answer is incorrect, you have scored '+correctResponses +' out of ' +  numOfQuestions +'.<br/><br/>Please try again');
            console.log('you have had '+GLOBAL.attempts);
        } else if (GLOBAL.attempts === 2) {
            $(".feedback-area").html('Your answer is still incorrect, you have scored '+correctResponses +' out of ' +  numOfQuestions +'.<br/><br/>Please try again');
            console.log('you have had '+GLOBAL.attempts);
        } else {
            revealAnswer();
            $(".feedback-area").text('Your answer was still incorrect, the correct answer is shown');
        }
    }
}

function revealAnswer() {

    if($.isArray(data.questions)) {
        $.each(data.questions, function(key, item) {
            text_num = key + 1;
            //var new_html = item.text.replace('---------','<span id=\"droppable-area'+text_num+'\" class=\"choice'+text_num+' droppable\"><a href=\"javascript:void(0);\"><img src=\"clear-spot.gif\" border=\"0\"></img></a></span>');
            $(".targets #text-area-"+text_num+" span").html("<a id=\"choice"+text_num+"\" class='answered'><span>"+ item.answers[0].text+"</span></a>");
            $(".targets #text-area-"+text_num+" span").removeClass("droppable");
        });
        $(".choices").html(" ");
    }
    $("#button_2 input").attr('disabled','disabled');
    $("#button_3 input").attr('disabled','disabled');

    $(".targets div span").removeClass("selected");
    $(".targets div span").unbind(); //unbind all handlers to disable interactivity
    $(".feedback-area").text('The correct answer is shown');
}