

var tries           = 0;            						//Number of tries on current question
var mistakes        = 0;            						//Number of total mistakes
var correct         = 0;            						//Number of correct clicks
var timercount      = 0;            						//Stopwatch running timer
var chancesB4hint   = 3;            						//Number of clicks before user is given a hint
var tID             = "";           						//Target id (id of clicked object)
var qID             = "";           						//Question id (id of current question)
var timestart       = null;         						//Stopwatch started time
var gameStarted     = false;        						//Flag if game started or not
var post            = new Array();  						//Post back to server after end game
var q               = new Array();  						//Questions (clickable objects in gfx-file)
var rn		    = Math.floor(Math.random()*4294967295);//Random number used as seed in xor for cheat checking
var toatalms        = 0;									//Total used ms

$(document).ready(function() {
    init();
});

function init()
{
    //Load all clickable elements into question array
    $(".clickable").each(function() {q.push($(this).attr('id'))});

 	//Add event listeners for game
    addEventListeners();

    //Fit game to screen resolution
    adjust2screen();
	
	//Special case
	if($("#table_of_elements").length != 0)
		hideAllLabels();
		
		
	FB.getLoginStatus(function(response) {
  	if (response.status === 'connected') {
		//User is logged in and connected to app
	    var uid = response.authResponse.userID;
    	var accessToken = response.authResponse.accessToken;
		FB.api('/me', function(response) {
			$("#postNameInput").val(response.name);
			$("#postFacebookID").val(response.id);
		});
	  	} else if (response.status === 'not_authorized') {
		// the user is logged in to Facebook, 
		//but not connected to the app
	  	} else {
		// the user isn't even logged in to Facebook.
	  	}
 	});
}

function startGame()
{
	facebookPostPlay();
		
    //Set start time
    var d = new Date();
    var time = d.getTime();

    //Reset clock
    timestart = null;
    $("#stopWatchText").html("00:00");

    //Set variables to 0
    tries = 0;
    correct = 0;

    //Remove labels from map
    hideAllLabels();

    //Remove feedback colors
    resetColors();

    //switch buttons
    $("#startButton").css("display", "none");
    $("#restartButton").css("display", "block");

    //Hide question
    $("#questionWrapper").css("display", "none");

    //Show gameinfo
    $("#metaInfoWrapper").css("visibility", "visible");
    $("#stopWatchWrapper").css("visibility", "visible");
    $("#countCorrectWrapper").css("visibility", "visible");
    $("#countMistakesWrapper").css("visibility", "visible");

    //Push start time and XOR to push-array
    post.length = 0;
    post.push(new Array(time,"","",(time ^ q[0]), (time ^ rn)));

    //Shuffle questions
    q = shuffle(q);

    //Build text in the infoPanel
    buildInfoPanelText();

    //Hide not needed panels
    $("#highscoreEnterWrapper").hide("slow");
    $("#highscoreBoardWrapper").hide("slow");

	//Bind hover and click events
    $(".clickable").bind("click", clickable_onMouseClick);
    $(".clickable").bind("mouseover", clickable_onMouseOver);
    $(".clickable").bind("mouseleave", clickable_onMouseOut);

	countdown();
}

function endGame()
{
    //Get time and push to post-array
    var d = new Date();
    var ct = d.getTime();
    post.push(new Array(ct,"","",(ct ^ qID), (ct ^ rn)));

    stopTimer();
		
    // Pack post data with "," seperating values and ":" seperating game moves
    var packed = "";
    for (var i = 0; (i < post.length); i++)
    {
        for(var j = 0; j < post[i].length; j++)
        {
            packed += escape(post[i][j]);
            if(j != post[i].length-1) packed += ",";
            else if (i != post.length-1) packed += ":";
        }
    }

    //Send POST data to form
    $("#postData").val(packed);
    $("#postMistakes").val(mistakes);
    $("#postTimeMs").val(toatalms);
    $("#postRn").val(rn);

    //Build enter highscore window
    $("#playerTimeText").html(gameTime);
    $("#playerMistakesText").html(mistakes);
    $("#highscoreEnterWrapper").css("display", "block");
    $("#postNameInput").focus();

    $("#highscoreForm").bind('submit', postScore);

	document.getElementById("highscore_fb_button_text").innerHTML = "Post resultat på Facebook!";

}

function postScore() {
    $.ajax({
      type: "POST",
      url: $('#highscoreForm').attr('action'),
      data: $('#highscoreForm').serialize(),
      beforeSend: function( xhr ) {
        xhr.overrideMimeType( 'text/plain; charset=x-user-defined' );

      },
      error: function( data ) {
         alert('An error occured on the server');
      },
      success: function( data ) {
        $("#highscoreEnterWrapper").hide();
        var highscoreAjaxResponse = JSON.parse(data);
        var tableIndex = 1;
        $.each(highscoreAjaxResponse.rank, function(i, val) {
            // Show user feedback
            $("#highscoreTab" + tableIndex).prepend('<p>Tiden ' + highscoreAjaxResponse.player_time + ' med ' +
                            highscoreAjaxResponse.player_mistakes + ' feil gir deg en ' + val + '. plass ' + i + '.</p>');

            // Alter the highscore list and then show
            if (val <= 10) {
                var currentRows = $("#highscoreTab" + tableIndex + " tbody tr").length;
                var highscoreRow = "<tr class=\"player\"><td>"+val+"</td><td>"+highscoreAjaxResponse.facebook_id+"<span>"+highscoreAjaxResponse.player_name+
                        "</span></td><td>"+ highscoreAjaxResponse.player_time +"</td><td>"+highscoreAjaxResponse.player_mistakes+"</td></tr>";
                if (currentRows != 0 && currentRows >= val) {

                    $("#highscoreTab" + tableIndex + " tbody tr:nth-child(" + val + ")").before(highscoreRow);
                    $.each($("#highscoreTab" + tableIndex + " tbody tr:gt(" + parseInt(val - 1) + ") td:nth-child(1)"), function(tdIndex, td) {
                        $(td).html(parseInt($(td).html()) + 1);
                    });
                    if (currentRows == 10) {
                        $("#highscoreTab" + tableIndex + " tbody tr:last").remove();
                    }
                } else {
                    $("#highscoreTab" + tableIndex + " table").append(highscoreRow);
                }
            }
            tableIndex++;
        });
        $("#highscoreBoardWrapper").fadeToggle("fast");
      }
    });
    return false;
}

function checkAnswer(target)
{
    if(!gameStarted)
        return;

    tID = target.attr('id');
    qID = q[correct];
	
	//Special case
	if($("#table_of_elements").length != 0)
		hideAllLabels();

    //If the question has not yet been found (Valid selection)
    if(getIndex(q, tID) >= correct)
    {
        //Hide labels from previous wrong click
        hideLabels();

        //If clicked the correct answer
        if(tID == qID)
        {
            //Play sound
            document.getElementById('audio_correct').play();

            //Display label
            showLabel(tID);

            //Set color of answer
            setAnswerColor(tID, tries);

			//Special case
			if($("#table_of_elements").length != 0)
				hideAllLabels();

			
            //Build POST to server
            var d = new Date();
            var ct = Math.round(d.getTime()); //Client time
            post.push(new Array(ct, qID, tries, (ct ^ qID), (ct ^ rn)));

            //Reset tries and add 1 to correct
            correct++;
            tries = 0;

            //If last question, end game
            if(correct == q.length) endGame();

            //There are more questions
            else
            {
                //Set new question to info panel
                buildInfoPanelText();
            }

        }

        //Else if clicked the wrong answer
        else
        {
            //Play sound
            document.getElementById('audio_wrong').play();

            //Display name of clicked object
            showLabel(tID);

            //Increase tries and total mistakes
            tries++;
            mistakes++;

            //If player needs help
            if(tries >= chancesB4hint)
                show_hint(tID);
        }

        //Print new game stats
        buildInfoPanelText();
    }
}

function buildInfoPanelText()
{
    //Build infoPanel text
    $("#questionText").html(q[correct].replace(/_/g," "));
    $("#countMistakesText").html(mistakes);
    $("#countCorrectText").html((correct + 1) + " / " + q.length);
}

function includes(arr, obj) {
  for(var i=0; i<arr.length; i++) {
    if (arr[i] == obj) return true;
  }
  return false;
}

function getIndex(arr, obj) {
    for(var i=0; i<arr.length; i++)
    {
        if (arr[i] == obj) return i;
    }

    return -1;
}

function shuffle (a)
{
    var newArray = a.slice();
    var len = newArray.length;
    var i = len;
    while (i--)
    {
        var p = parseInt(Math.random()*len);
	var t = newArray[i];
	newArray[i] = newArray[p];
  	newArray[p] = t;
    }
    return newArray;
}

function showTimer()
{
    if(timercount)
    {
        clearTimeout(timercount);
        clockID = 0;
    }
    if(!timestart)
    {
        timestart = new Date();
    }
    var timeend = new Date();
    var timedifference = timeend.getTime() - timestart.getTime();
    timeend.setTime(timedifference);
    var minutes_passed = timeend.getMinutes();
    if(minutes_passed < 10){
            minutes_passed = "0" + minutes_passed;
    }
    var seconds_passed = timeend.getSeconds();
    if(seconds_passed < 10){
            seconds_passed = "0" + seconds_passed;
    }
	var tenths_passed = timeend.getMilliseconds();
	tenths_passed = parseInt(tenths_passed / 100);

    $("#stopWatchText").html(minutes_passed + ":" + seconds_passed + "." + tenths_passed);
    timercount = setTimeout("showTimer()", 100);
}

function stopTimer()
{
    if(timercount)
    {
        clearTimeout(timercount);
        timercount  = 0;
        var timeend = new Date();
        var timedifference = timeend.getTime() - timestart.getTime();
		toatalms = timedifference;
        timeend.setTime(timedifference);
        var minutes_passed = timeend.getMinutes();
        if(minutes_passed < 10){
                minutes_passed = "0" + minutes_passed;
        }
        var seconds_passed = timeend.getSeconds();
        if(seconds_passed < 10){
                seconds_passed = "0" + seconds_passed;
        }
        var milliseconds_passed = timeend.getMilliseconds();
        if(milliseconds_passed < 10){
                milliseconds_passed = "00" + milliseconds_passed;
        }
        else if(milliseconds_passed < 100){
                milliseconds_passed = "0" + milliseconds_passed;
        }
        gameTime = minutes_passed + ":" + seconds_passed + "." + milliseconds_passed;
    }
    timestart = null;
}

function adjust2screen()
{
    //Get screen resolution
    var screen_height = $(window).height();
	var svg_height = $(".gfx svg").attr('height').replace("px","");
	var infopanel_height = $("#infoPanelWrapper").outerHeight(true);
	var padding_height = 20;
	var max_height = screen_height - (infopanel_height + padding_height);
	//If svg is too big
	//alert('Max Height: ' + max_height + "\nSvg height: " + svg_height);
	
	if(svg_height > max_height)
	{
		$(".gfx svg").height(max_height);
	}
}

function show_highscoreForm()
{
    $("#highscoreEnterWrapper").css('display', "block");
}

function close_highscoreForm()
{
    $("#highscoreEnterWrapper").css('display', "none");
}

function clickable_onMouseClick()
{
    $("#"+q[correct]).removeClass("colorHint");
    checkAnswer($(this));
}

function clickable_onMouseOver()
{
    $(this).addClass("clickable_onMouseHover");
}

function clickable_onMouseOut()
{
    $(this).removeClass("clickable_onMouseHover");
}

function showLabel(id)
{
    $("#lbl_"+id).css("display", "block");
}

function hideLabels()
{
//Hides all labels that has not yet been found
    for(var i = correct; i < q.length; i++)
    {
        $("#lbl_" + q[i]).css("display", "none");
    }
}

function hideAllLabels()
{
    for(var i = 0; i < q.length; i++)
    {
        $("#lbl_" + q[i]).css("display", "none");
    }
}

function setAnswerColor(id, tries)
{
	$("#"+id).removeClass("colorHint");
	if(tries <= 1) $("#"+id).addClass("colorTries"+tries);
	else $("#"+id).addClass("colorTries2");
	
	//Apply to children
	$("#"+q[correct]).find('polygon,path').removeClass('colorHint');
	if(tries <= 1) $("#"+id).find('polygon,path').addClass("colorTries"+tries);
	else $("#"+id).find('polygon,path').addClass("colorTries2");
}

function show_hint()
{
	$("#"+q[correct]).addClass('colorHint');
			
	//Apply to children
	$("#"+q[correct]).find('polygon,path').addClass('colorHint');
}

function resetColors()
{
    for(var i = 0; i < q.length; i++)
    {
		$("#"+q[i]).removeClass("colorTries0");
		$("#"+q[i]).removeClass("colorTries1");
		$("#"+q[i]).removeClass("colorTries2");
		$("#"+q[i]).removeClass("colorHint");
		
		//Apply to children
		$("#"+q[i]).find('polygon,path').removeClass("colorTries0");
		$("#"+q[i]).find('polygon,path').removeClass("colorTries1");
		$("#"+q[i]).find('polygon,path').removeClass("colorTries2");
		$("#"+q[i]).find('polygon,path').removeClass("colorHint");
    }
}

function countdown()
{
	//Countdown and start timer
	$("#idleText").fadeOut(250, function() {
	$("#countDown3").fadeIn(250, function() {
	$("#countDown3").fadeOut(250, function() {
	$("#countDown2").fadeIn(250, function() {
	$("#countDown2").fadeOut(250, function() {
	$("#countDown1").fadeIn(250, function() {
	$("#countDown1").fadeOut(250, function() {
	$("#questionWrapper").css("display", "block", showTimer());});});});});});});});

	//Set gameStarted state
    setTimeout("gameStarted = true", 1750);
}

function restartGame()
{
	location.reload(true);
}

function addEventListeners()
{
//Add event listeners
    $("#showHighscoreButton").click(function () {
    	$("#highscoreBoardWrapper").fadeToggle("fast");
    });
	$("#statisticsButton").click(function () {
    	$("#statisticsWrapper").fadeToggle("fast");
    });
    $("#startButton").bind("click", startGame);
    $("#restartButton").bind("click", restartGame);

	$("#closeHighscores").click(function () {
        $("#highscoreBoardWrapper").fadeOut("fast");
 	});

	//Add tab control for highscores
	$(".highScoreTabMenu > li").click(function(e){
        switch(e.target.id){
            case "highscoreTabMenu1":
                //change status &amp;amp;amp; style menu
                $("#highscoreTabMenu1").addClass("HighscoreSelectedTab");
                $("#highscoreTabMenu2").removeClass("HighscoreSelectedTab");
                $("#highscoreTabMenu3").removeClass("HighscoreSelectedTab");
                //display selected division, hide others
                $("#highscoreTab1").fadeIn();
                $("#highscoreTab2").css("display", "none");
                $("#highscoreTab3").css("display", "none");
            break;
            case "highscoreTabMenu2":
                //change status &amp;amp;amp; style menu
                $("#highscoreTabMenu1").removeClass("HighscoreSelectedTab");
                $("#highscoreTabMenu2").addClass("HighscoreSelectedTab");
                $("#highscoreTabMenu3").removeClass("HighscoreSelectedTab");
                //display selected division, hide others
                $("#highscoreTab2").fadeIn();
                $("#highscoreTab1").css("display", "none");
                $("#highscoreTab3").css("display", "none");
            break;
            case "highscoreTabMenu3":
                //change status &amp;amp;amp; style menu
                $("#highscoreTabMenu1").removeClass("HighscoreSelectedTab");
                $("#highscoreTabMenu2").removeClass("HighscoreSelectedTab");
                $("#highscoreTabMenu3").addClass("HighscoreSelectedTab");
                //display selected division, hide others
                $("#highscoreTab3").fadeIn();
                $("#highscoreTab1").css("display", "none");
                $("#highscoreTab2").css("display", "none");
            break;
        }
        //alert(e.target.id);
        return false;
    });
}

function facebookSetName()
{
	FB.login(function(response) {
   if (response.authResponse) {
     FB.api('/me', function(response) {
       	$("#postNameInput").val(response.name);
		$("#postFacebookID").val(response.id);
     });
   } 
 }, {scope: 'email'});
}
