var debug = true;
//var debug = false;
var options = ["Rocket Mortgage", "Hyundai", "Dark Gummies", "Specsavers", "Snickers"];
var selections = [0,0,0,0,0];
var num_voters = 0;
var totals = [0,0,0,0,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='"+(11+choice_num)+"'><span>"+ item.text+"</span></a>");	
      choices.push("<div id='choice"+choice_num+"' class='choice'>"+item.text+"</div>");	
		});
	}
	
	
	//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,
		start: function(event, ui) {
			that = this;
		 },
		stop: function(event, ui) {
			//$('div.mark:empty').each(function() {
      //  if($.trim($(this).html()).length == 0) {
      //    $(this).append("<a href=\"javascript:void(0)\"><img src=\"clear.gif\" border=\"0\"></img></a>");
      //    $(".targets div.selected").css("border","none");			
      //  }
      //});			
		}
	});
	
	// 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 mark\"></div>");
	//	$("#droppable-area"+droppable_num).css("top",item.top);
	//	$("#droppable-area"+droppable_num).css("left",item.left);		
  //      });
		
	//}
	
	$(".choice").css("font-size",data.choicefontsize);
	$(".choice").css("color",data.choicetextcolour);
	$(".label").css("font-size",data.labelfontsize);
	$(".label").css("color",data.labeltextcolour);
	
	// Make choices div droppable so can drop choices back
	$(".choices").droppable ({
		drop:function(event, ui){
			ui.draggable.css({top:"0px",left:"0px"});
			$(this).append(ui.draggable);		 
			console.log(".choices droppable()");
			checkTargets();
		}
	})
	
	//target	
	// 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 - overwrites what's in the target
			$(this).html(ui.draggable);//add to target
			// ui.choice.css({top:"0px",left:"0px"});
			checkTargets();
		},
    over: function(){ 
      $(this).addClass("bg-hover");
    },
    out: function() {
      $(this).removeClass("bg-hover");
    }
	}); 
	

  $(".targets div.mark").on("keydown click", function(e) {
    if (e.type == "keydown") {
      if ((e.keyCode != 13) && (e.keyCode != 32)) return;
    }
    handleClick($(this));
    checkTargets();
  });

  function handleClick($this) {
		// Is a choice selected from the choices at the top
		if($(".choices a.selected").length){
			// Is there already a choice in the target?
			$(".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 div.selected"));//append
		// If target is selected
		}
		else {
			$(".choices").append($this.find(".choice").css({left:"",top:""}).removeClass("selected"));//chuck out
			// select first of the items from the choices
			// mjt
			// $(".choice1").css({top:"14px",left:"290px"});
			$this.html($(".choices div").eq(0));//append
		}
		$(".targets div.mark").removeClass("selected");
		$this.addClass("selected");		
		//$this.find("a").focus();
  }
  
	// If target is clicked (tapped)
	$(".xtargets div.mark").click(function(){
		// Is a choice selected from the choices at the top
		if($(".choices a.selected").length){
			// Is there already a choice in the target?
			$(".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
		// If target is selected
		}
		else {
			$(".choices").append($(this).find(".choice").css({left:"",top:""}).removeClass("selected"));//chuck out
			// select first of the items from the choices
			// mjt
			// $(".choice1").css({top:"14px",left:"290px"});
			$(this).html($(".choices a").eq(0));//append
		}
		$(".targets div.mark").removeClass("selected");
		$(this).addClass("selected");		
		$(this).find("a").focus();
	});

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

  $('#btnReset').click(function() {
    window.location.reload();
  });

  $('#btnSubmit').click(function() {
    selections = [];
    if (debug) {
      selections = [5,4,3,2,1];
    } else {
      for (var i=1; i<=5; i++) {
        selections.push(Number($("#droppable-area"+i).find("div").attr("id").slice(-1)));
      }
    }
    //console.log(selections);
    saveUserVote();
  });

  // submit is disabled until all targets are filled
  function checkTargets() {
    if (!debug) {
      for (var i=1; i<=5; i++) {
        //console.log($("#droppable-area"+i).find("div")[0]);
        if ($("#droppable-area"+i).find("div")[0] === undefined) {
          //console.log("Targets not filled yet");
          $("#btnSubmit").prop("disabled", true);
          return;
        }
      }
    }
    //console.log("All targets filled!");
    $("#btnSubmit").prop("disabled", false);
  }
   
  function populateOptions() {
    var elOptions = document.querySelectorAll(".option");
    for (var i=0; i<elOptions.length; i++) {
      elOptions[i].innerHTML = options[i];
    }
  }

  function populateResults() {
    var positions = ["1st", "2nd", "3rd", "4th", "5th"];
    var out = [], obj = {};
    var pos = 0, largest, occ;
   
    if (debug) {
      num_voters = 3; //from VLE
      totals = [12,14,9,5,5]; //from VLE
    }
    
    // calculate ranking positions (including joint positions!)    
    for (j=0; j<5; j++) { //max number of iterations
      largest = Math.max.apply(null, totals); //find largest value in totals array
      if (largest == 0) break; //all done
      occ = totals.filter(function(v) {return (v == largest)}).length; //count # of occurences
      //console.log("largest:"+largest+", occ:"+occ);
      for (var i=0; i<5; i++) {
        if (totals[i] == largest) {
            obj = {};
            obj.idx = i;
            obj.pos = positions[pos] + ((occ > 1) ? "=": ""); //may be joint equal
            obj.pc = (100*totals[i]/(15*num_voters)).toFixed(0);
            obj.orig = selections[i];
            totals[i] = 0;
            out.push(obj);
        }
      }
      pos += occ;
    }
    //console.log(out);
    
    if (pos == 0) {
      $("#fb_msg").html("<b>No votes have been submitted yet</b>");
      return;
    }
    
    // populate results page
    for (var i=0; i<5; i++) {
      $("#rank"+(i+1)+"_pos").html(out[i].pos);
      $("#rank"+(i+1)+"_advert").html(options[out[i].idx]+" <span style='font-size:11px'>("+out[i].orig+")</span>");
      $("#rank"+(i+1)+"_bar").css("width",out[i].pc+"%");
      $("#rank"+(i+1)+"_pc").html(out[i].pc+"%");
    }
    
    $("#fb_msg").html("<b>You have voted.</b><br/>The total number of participants so far is "+num_voters+".");
  }
  
  function getUserVote() {
    console.log("getUserVote()");
    VLE.get_server_data(
      true, //user
      ['vote'],
      function ok(values){
        if (values.vote != '') {
          selections = JSON.parse(values.vote);
          getGlobalVote(viewVotes);
        } else { //not voted
          setPollEnabled();        
        }
      },
      function err() {
        setPollEnabled();
      }
    );
  }

  function getGlobalVote(callback) {
    console.log("getGlobalVote()");
    VLE.get_server_data(
      false, //global
      ['num_voters', 'totals'],
      function ok(values){        
        if (values.num_voters != '') {
          num_voters = Number(values.num_voters);
          totals = JSON.parse(values.totals);
        } else { //no Global data yet initialise
          num_voters = 0;
          totals = [0,0,0,0,0];          
        }
        callback();
      },
      function err(msg){
        console.log("Error reading global data: ",msg)
        alert("Unable to read data from the VLE");
      },
      activityid,
      itemid
    );
  }

  function saveUserVote() {
    console.log("saveUserVote()");
    VLE.set_server_data(
      true, //user
      {'vote':JSON.stringify(selections)},
      function ok() {
        getGlobalVote(updateGlobalVotes);
      },
      function err(msg) {
        console.log("Error writing user data: ",msg);
        alert("Failed to write data to the VLE");
        if (debug) viewVotes();
      }
    );
  }

  function updateGlobalVotes() {
    console.log("updateGlobalVotes()");
    num_voters++; //one more participant
    for (var i=0; i<5; i++) {
      totals[i] = totals[i] + (6-selections[i]); //add weighted rank values 1st=5,2nd=4...5th=1
    }
    saveGlobalVote();
  }

  function saveGlobalVote() {
    console.log("saveGlobalVote()");
    VLE.set_server_data(
      false, //global
      {'num_voters':num_voters,'totals':JSON.stringify(totals)},
      function ok() {
        viewVotes()
      },
      function err(msg) {
        console.log("Error writing global data: ",msg)
      }
    );
  }

  function setPollEnabled() {
    var el = document.querySelector("#input");
    el.style.display = "block";
    resize_iframe();
  }

  function viewVotes() {
    console.log("viewVotes()");
    var el = document.querySelector("#input");
    el.style.display = "none";
    populateResults();
    var el = document.querySelector("#results");
    el.style.display = "block";
    resize_iframe();
  }  

  function resize_iframe() {
    // Find iframe in parent window.
    var iframe = window.frameElement;
    // If we can't find it, put a message in the console and abort.
    if (!iframe) {
        if (window.console) {
            console.log('VLE.resize_iframe: Unable to find parent iframe');
        }
        return;
    }
    // Get current window scroll.
    var currentScroll = window.top.pageYOffset;

    // Set the iframe too small so that it scrolls, then set it to the
    // required scroll height. (You can't get scroll height when not
    // scrolling as it returns the current height.)
    iframe.height = 1;
    iframe.height = document.documentElement.scrollHeight;

    // Put scroll position back (it may have moved due to removing the iframe there).
    if (currentScroll !== undefined) {
        window.top.scrollTo(window.top.pageXOffset, currentScroll);
    }
  }

  var itemid = VLE.get_param("itemId") || VLE.get_param("_i");
  var activityid = VLE.get_param("activityId") || VLE.get_param("_a");
console.log("itemid:",itemid);
console.log("activityid:",activityid);
  if (VLE.get_param("admin")) {
    getGlobalVote(viewVotes);
  } else {
    populateOptions();
    getUserVote();
  }
});
