// remap jQuery to $

(function($){
  
  $(".playgame").fancybox({
    'type' : 'iframe',
    'width' : 830,
    'height' : 600,
    'scrolling' : 'no',
    onComplete : function() {
      //console.log(mem);
    },
    onClosed : function() {
      //console.log('fancybox closed');
      //console.log(mem);
      location = location;
    }
  });
  
  $(".view-video").fancybox({
    'type' : 'iframe',
    'autoDimensions' : true,
    'width' : 660,
    'height' : 380,
    'scrolling' : 'no'
  });
  
  $(".popup").fancybox({
    'type' : 'iframe',
    'autoDimensions' : true,
    'width' : 800,
    'scrolling' : 'auto'
  });
  
  if($('#leaderboard-select').length) {
    $('#leaderboard-select').change(function(){this.form.submit()})
  }
  
  if($('input.dob').length) {
    var dob = $('input.dob');
    if(!dob.val()) {
      dob.val('dd/mm/yyyy');
    }
    dob.click(function(e){
      if(dob.val()=='dd/mm/yyyy') {
        dob.val('');
      }
    });
    dob.blur(function(e){
      if(dob.val()=='') {
        dob.val('dd/mm/yyyy');
      }
      checkDob = Date.parse(dob.val());
      if (checkDob.addYears(16) < Date.today())
      {
          $('#UserParentEmail').parent('div').addClass('visuallyhidden');
      }
      else
      {
          $('#UserParentEmail').parent('div').removeClass('visuallyhidden');
      }
    })
  }
  
  /*
  $('#AccountVoucherForm').submit(function(e){
    e.preventDefault();
    var code = $(this).children().children('input[type="text"]').val();
    $.get(e.currentTarget.action+'?code='+code), function(ajax) {
      //console.log(ajax.response());
    })
    
  });
  */
  
  // $('#AccountVoucherForm input[type="submit"]').click(function(e){
  //   e.preventDefault();
  //   //console.log(e);
  //   $.get(e.currentTarget.baseURI+'?');
  // });
  
  $(".game-small").mouseenter(function(){
    var icon_id = $(this).attr("id");
    var panel_id = icon_id.replace(/small/i, 'big');
    $("div.game-big").addClass('visuallyhidden');
    $('#'+panel_id).removeClass('visuallyhidden');
  });
  
  if($("#GroupLicenses").length) {
    
    var group_type = $("#AccountAccountTypeId").val();
    var top_up = $("#top_up").val();
    
    if(top_up == 1) {
      var min_val = 1
      var max_val = 10000;
    }
    else {
      if(group_type == 2) {
        var min_val = 6;
        var max_val = 10000;
      }
      else if(group_type == 3) {
        var min_val = 150;
        var max_val = 10000;
      }
      else if(group_type == 4) {
        var min_val = 2;
        var max_val = 5;
      }
      else {
        var min_val = 0;
        var max_val = 0;
      }
    }
    
    $("#GroupLicenses").numeric({
      format: {format: '0.##'},
      increment: 1,
      minValue: min_val,
      maxValue: max_val
    }).change(function () {
    
      var licenses = $("#GroupLicenses").val();
      var base_price = $("#base_price").val() * licenses;
      
      if($("#discount_percent").val() > 0) {
        var discount = (base_price/100) * $("#discount_percent").val();
      }
      else if($("#discount_value").val() > 0)  {
        var discount = $("#discount_value").val();
      }
      else {
        var discount = 0;
      }
      var google_price = base_price - discount;
      var google_charges = google_price * ($("#google_charge_percent").val()/100);
      var vat_price = google_price + google_charges;
      var vat_charges = vat_price * ($("#vat_percent").val()/100);
      var total_price = vat_price + vat_charges;
    
      $("#AccountPrice").val(base_price).formatCurrency(null, {symbol:'',roundToDecimalPlace:2});
      $("#AccountDiscount").val(discount).formatCurrency(null, {symbol:'',roundToDecimalPlace:2});
      $("#AccountCharges").val(google_charges).formatCurrency(null, {symbol:'',roundToDecimalPlace:2});
      $("#AccountVat").val(vat_charges).formatCurrency(null, {symbol:'',roundToDecimalPlace:2});
      $("#AccountTotal").val(total_price).formatCurrency(null, {symbol:'',roundToDecimalPlace:2});
    
    });
  }
  
  // send details off to google...
  $("#google-frm").submit();
  
})(window.jQuery);

// object to hold all data for the game.

var mem = {
	wpm_max: 0,
	incr_level: 0,
	lettersTyped : 0,	
	wpm_target: 0,		
	wpm_sess: 0,
	min: 0,
	user_rank: 0,
	user_stage: 0,
	user_case: 0,
	user_seconds: 0,
	userUnlocked: 0,
	user_uid: 0,
	username: '',
	highscore: 5,
	userspeed: 0,	
	highscores: []
};

// initialise all game data to 0.

for(i=0; i<=32; i++) {
  mem.highscores[i] = 0;
}

var initialised = false;
var currentTime = new Date();

/*
 on game load...
 
  updateClock()
  getUsername()
  getUserID()
  getUserScore()
  pingPage()
  getStage()
  getUnlocked()
  getWPM()
  getUserSpeed()
  getIncrementLevel()
  getTargetWPM()
  getlettersTyped()
  
  at end of the game...
  
  setlettersTyped()
  setUserScore()
  pingPage()
  setUserLevel()
  
  on back to gamegrid...
  
  closeModal()
  
*/

function getIncrementLevel () {
  //console.log('getIncrementLevel');
	//console.log(mem);
	return mem.incr_level;
}

function getWPM () {
  //console.log('getWPM');
	return mem.wpm_max;
}

function setWPM (val) {
	mem.wpm_max = val;
	document.getElementById('wpm_maximum').innerHTML = val;
	//console.log('setWPM');
	//console.log(mem);
}

function getlettersTyped () {
  //console.log('getlettersTyped');
	return mem.lettersTyped;
}

function setlettersTyped (val) {
//	mem.lettersTyped = val;
mem.lettersTyped = 0;
	//console.log('setLettersTyped');
	//console.log(mem);
}

function getTargetWPM () {
  //console.log('getTargetWPM');
	return mem.wpm_target;
}

function getWPMmax () {
  //console.log('getWPMmax');
	return mem.wpm_max;
}

function setAll(uuid,uname,uhighscore,useconds,ustage,ucase, uuserunlocked,ugs0,ugs1,ugs2,ugs3,ugs4,ugs5,ugs6,ugs7,ugs8,uwpm,uspeed,ugs9,ugs10,ugs11,ugs12,ugs13,ugs14,ugs15,ugs16,ugs17,ugs18,ugs19,ugs20,ugs21,ugs22,ugs23,ugs24,ugs25,ugs26,ugs27,ugs28,ugs29,ugs30,ugs31,ugs32,utwpm,uincr,ultype)
{
   
	mem.user_uid		= uuid;
	mem.username		= uname;
	mem.highscore		= uhighscore;
	mem.user_seconds	= useconds;
	mem.user_stage		= ustage;
	mem.user_case		= ucase;
	mem.userUnlocked	= uuserunlocked;
	mem.wpm_max			= uwpm;
	mem.wpm_target		= utwpm;
	
	mem.userspeed		= uspeed;
	mem.incr_level		= uincr;
	mem.lettersTyped	= ultype;


	mem.highscores[0] = ugs0;
	mem.highscores[1] = ugs1;
	mem.highscores[2] = ugs2;
	mem.highscores[3] = ugs3;	
	mem.highscores[4] = ugs4;
	mem.highscores[5] = ugs5;
	mem.highscores[6] = ugs6;
	mem.highscores[7] = ugs7;
	mem.highscores[8] = ugs8;	
	mem.highscores[9] = ugs9;
	mem.highscores[10] = ugs10;	

	mem.highscores[11] = ugs11;
	mem.highscores[12] = ugs12;
	mem.highscores[13] = ugs13;	
	mem.highscores[14] = ugs14;
	mem.highscores[15] = ugs15;
	mem.highscores[16] = ugs16;
	mem.highscores[17] = ugs17;
	mem.highscores[18] = ugs18;	
	mem.highscores[19] = ugs19;
	mem.highscores[20] = ugs20;	

	mem.highscores[21] = ugs21;
	mem.highscores[22] = ugs22;
	mem.highscores[23] = ugs23;	
	mem.highscores[24] = ugs24;
	mem.highscores[25] = ugs25;
	mem.highscores[26] = ugs26;
	mem.highscores[27] = ugs27;
	mem.highscores[28] = ugs28;	
	mem.highscores[29] = ugs29;
	mem.highscores[30] = ugs30;	

	mem.highscores[31] = ugs31;
	mem.highscores[32] = ugs32;
}

function getUserScore (gid) 
{
  //console.log('getUserScore');
  pingPage();
	return mem.highscores[gid];
}
function setUserScore(gid,hscore)
{
  //console.log('setUserScore');
  //console.log(mem);
  pingPage();
	mem.highscores[gid] = hscore;

	var hTotalScore=0;
	hTotalScore = (isNaN(mem.highscores[0]) ? 0 : mem.highscores[0]) + (isNaN(mem.highscores[1]) ? 0 : mem.highscores[1]) + (isNaN(mem.highscores[2]) ? 0 : mem.highscores[2]) + (isNaN(mem.highscores[3]) ? 0 : mem.highscores[3])+ (isNaN(mem.highscores[4]) ? 0 : mem.highscores[4]) + (isNaN(mem.highscores[5]) ? 0 : mem.highscores[5]) + (isNaN(mem.highscores[6]) ? 0 : mem.highscores[6]) + (isNaN(mem.highscores[7]) ? 0 : mem.highscores[7]) + (isNaN(mem.highscores[8]) ? 0 : mem.highscores[8]) + (isNaN(mem.highscores[9]) ? 0 : mem.highscores[9]) + (isNaN(mem.highscores[10]) ? 0 : mem.highscores[10]) + (isNaN(mem.highscores[11]) ? 0 : mem.highscores[11]) + (isNaN(mem.highscores[12]) ? 0 : mem.highscores[12]) + (isNaN(mem.highscores[13]) ? 0 : mem.highscores[13]) + (isNaN(mem.highscores[14]) ? 0 : mem.highscores[14]) + (isNaN(mem.highscores[15]) ? 0 : mem.highscores[15]) + (isNaN(mem.highscores[16]) ? 0 : mem.highscores[16]) + (isNaN(mem.highscores[17]) ? 0 : mem.highscores[17]) + (isNaN(mem.highscores[18]) ? 0 : mem.highscores[18]) + (isNaN(mem.highscores[19]) ? 0 : mem.highscores[19]) + (isNaN(mem.highscores[20]) ? 0 : mem.highscores[20])+ (isNaN(mem.highscores[21]) ? 0 : mem.highscores[21]) + (isNaN(mem.highscores[22]) ? 0 : mem.highscores[22]) + (isNaN(mem.highscores[23]) ? 0 : mem.highscores[23])+ (isNaN(mem.highscores[24]) ? 0 : mem.highscores[24]) + (isNaN(mem.highscores[25]) ? 0 : mem.highscores[25]) + (isNaN(mem.highscores[26]) ? 0 : mem.highscores[26]) + (isNaN(mem.highscores[27]) ? 0 : mem.highscores[27]) + (isNaN(mem.highscores[28]) ? 0 : mem.highscores[28]) + (isNaN(mem.highscores[29]) ? 0 : mem.highscores[29]) + (isNaN(mem.highscores[30]) ? 0 : mem.highscores[30])+ (isNaN(mem.highscores[31]) ? 0 : mem.highscores[31])+ (isNaN(mem.highscores[32]) ? 0 : mem.highscores[32]);
	
	setUserLevel();
	document.getElementById('highscore').innerHTML = hTotalScore;
	
	
	
}
function setUserRank(val) 
{
  //console.log('setUserRank');
  //console.log(mem);
	mem.user_rank = val;
	document.getElementById('rank').innerHTML = val;
}
function setUserLevel() 
{
  //console.log('setUserLevel');
  //console.log(mem);
	var hLevel = ((isNaN(mem.user_stage) ? 0 : mem.user_stage) * 2) + ((isNaN(mem.user_case) ? 0 : mem.user_case) + 1);
	
	document.getElementById('level').innerHTML = hLevel;
}
function getStage ()
{
  //console.log('getStage');
	return mem.user_stage;
}
function setStage(val) 
{
  //console.log('setStage');
  //console.log(mem);
	mem.user_stage = val;
}
function getUserSpeed ()
{
  //console.log('getUserSpeed');
	return mem.userspeed;
}
function setUserSpeed (val)
{
  //console.log('setUserSpeed');
  //console.log(mem);
	mem.userspeed = parseInt(val);
	document.getElementById('user_speed').innerHTML = mem.userspeed;
}
function getCase () 
{
  //console.log('getCase');
	return mem.user_case;
}
function setCase (val)
{
  //console.log('setCase');
  //console.log(mem);
	mem.user_case = val;
}
function getUserSeconds () 
{
  //console.log('getUserSeconds');
	return mem.user_seconds;
}
function setUserSeconds (val)
{
  //console.log('setUserSeconds');
  //console.log(mem);
	hours = parseInt( val / 3600 ) % 24; 
	minutes = parseInt( val / 60 ) % 60; 
	seconds = val % 60; 
	document.getElementById('seconds_earned').innerHTML = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
}
function getUnlocked ()
{
  //console.log('getUnlocked');
	return mem.userUnlocked;
}
function setUnlocked (val)
{
  //console.log('setUnlocked');
  //console.log(mem);
	if(val == true)
	{
		var hLock = (isNaN(mem.userUnlocked) ? 1 : mem.userUnlocked);
		mem.userUnlocked = 1;
	}
	else
	{
		var hLock = (isNaN(mem.userUnlocked) ? 0 : mem.userUnlocked);		
		mem.userUnlocked = 0;		
	}
	document.getElementById('userUnlocked').innerHTML = hLock;
}
function viaModal ()
{
	alert('success');
}
function getUserID ()
{
  //console.log('getUserID');
	return mem.user_uid;
}
function getUsername ()
{
  //console.log('getUsername');
	return mem.username;
}
function getHighScore (game)
{
  //console.log('getHighScore');
	return mem.highscores[game];
}
function setHighScore (game,score)
{
  //console.log('setHighScore');
  //console.log(mem);
	var previousscore = mem.highscores[game];
	var increment = 0;
	if(previousscore < score) {
		mem.highscores[game] = score;
		increment = score - previousscore;
	}
	if(initialised) {
		var myscore = parseInt($("#highscore").text());
		setMyScore (myscore+increment);
	}
}
function setMyScore (score)
{
  //console.log('setMyScore');
  //console.log(mem);
	$("#highscore").text(score);
}

function pingPage() {
  //post to page ping...
  //console.log('pingPage');
  //console.log(mem);
  /*
	$.get('/ping.php', function(data) {
	  if(data == 2) {
	    window.focus();
	    closeModal();
	    location.reload(false);
	  }
	  else if (data == 3) {
	    window.focus();
	    closeModal();
	    location.reload(false);
	  }
	  else {   
	  }
	});
	*/
}

function launchModal (swf,width,height,trans) 
{
  //pingPage();
  
	var maskHeight = $(document).height();
	var maskWidth = $(document).width();
	var maskHeight = (parseInt(maskHeight));
	var maskWidth = (parseInt(maskWidth));
	
	$('#mask').css({'width':maskWidth,'height':maskHeight,'overflow':'hidden'});
	var modalTop = 5;
	var modalLeft = (parseInt(maskWidth)-parseInt(width))/2;
	$('#modal-close').css({'width':width});
	$('#modal').css({'width':width,'height':(parseInt(height)+20)});
	$('#modal').css('top', modalTop);
	$('#modal').css('left', modalLeft);
	$('#game').css({'width':width,'height':height,'overflow':'hidden'});
	$('#modal').attr('title',swf);

	$('#mask').fadeIn(1000, function() 
	{
			$('#mask').fadeTo("slow",0.8);
			var winH = $(window).height();
			var winW = $(window).width();

			var user_uid = $('#link-account span').attr('title');

			swfobject.embedSWF($('#modal').attr('title'), 'game', width, height, '9.0.0', 'js/expressInstall.swf', {}, {wmode:'window',bgcolor:'#000000',AllowScriptAccess:'always'}, {}, null);
			$('#modal').show();
			//gameFocusTimer = setTimeout("setGameToFocus()", 2100);
	});

}

function closeModal ()
{
  parent.$.fancybox.close();
	$('#mask').fadeOut('slow');
	$('#modal').fadeOut('slow');
	location.reload(false);
}

function updateClock () 
{
  //console.log('updateClock');
  //console.log(mem);
	if(document.getElementById('time')) 
	{
		var year = currentTime.getFullYear();
		var month = currentTime.getMonth()+1;
		var day = currentTime.getDate();
		var hours = currentTime.getHours();
		var minutes = currentTime.getMinutes();
		var seconds = currentTime.getSeconds();
		var ampm = (hours > 11) ? "PM" : "AM";

		if (minutes < 10){
			minutes = "0" + minutes;
		}
		document.getElementById('time').innerHTML = hours + ":" + minutes + " "+ampm;
		
		if(day < 10) { day = "0"+day; }
		if(month < 10) { month = "0"+month; }
		document.getElementById('date').innerHTML = day+' '+month+' '+year;

		$.get("ping.php", function(data){
			document.getElementById('active_sessions').innerHTML = data;
		});

		setTimeout("updateClock()",10000);
	}
}
$(document).ready(function() 
{

var titledata = $('#link-account span').attr('title');
	if(titledata && titledata.length > 0) {
		mem.user_uid = titledata;
		if(document.getElementById('nickname')) {
			mem.username = document.getElementById('nickname').innerHTML;
		}
		if(document.getElementById('highscore')) {
			mem.highscore = document.getElementById('highscore').innerHTML;
		}
		if(document.getElementById('wpm_maximum')) {
			mem.wpm_max = document.getElementById('wpm_maximum').innerHTML;
		}
		if(document.getElementById('wpm_session')) {
			mem.wpm_sess = document.getElementById('wpm_session').innerHTML;
			if(mem.wpm_sess.length < 1) {
				mem.wpm_sess = 0;
			}
		}
		if(document.getElementById('minutes_earned')) {
			mem.min = document.getElementById('minutes_earned').innerHTML;
			if(mem.min.length < 1) {
				mem.min = 0;
			}
		}
	}
	var scores = $('#game-data').attr('title');
	if(scores && scores.length > 0) {
		scores = scores.split(';');
		if(scores.length > 0) {
			for(var i=0; i<scores.length; i++) {
				var scorepair = scores[i].split(':');
				setHighScore(scorepair[0],scorepair[1]);
			}
			initialised = true;
		}
	}

$("a.modal").click(function(e)
{
		e.preventDefault();
		$(this).blur();//Code
		
		var url						= $(this).attr('href');
		var rel						= $(this).attr('rel');

		var parts					= rel.split(';');

		if(parts.length == 3) {
			var width_declaration	 = parts[0].split(':');
			var height_declaration = parts[1].split(':');
			var trans_declaration	 = parts[2].split(':');
			var width	 = width_declaration[1];
			var height = height_declaration[1];
			var trans	 = trans_declaration[1];
		} else {
			var width	 = 860;
			var height = 634;
			var trans	 = 'transparent';
		}
		
		var ratio = width/height;
		
		height = $(window).height() - 20;
		width = height * ratio;

		var maskHeight = parseInt($(document).height(), 10);
		var maskWidth  = parseInt($(document).width(), 10);

		$('#mask').css({
			'width':		maskWidth,
			'height':		maskHeight,
			'overflow':		'hidden',
			'opacity':		0.8
		});
		var modalTop  = $(window).scrollTop() + 10; // scrolltop??
		var modalLeft	= (parseInt(maskWidth, 10)-parseInt(width, 10))/2;

		$('#modal-close').css({
			'width':		width
		});
		$('#modal').css({
			'width':		width,
			'height':		height,
			'top':			modalTop,
			'left':			modalLeft
		});
		$('#game').css({
			'width':		width,
			'height':		height,
			'overflow':	'hidden'
		});
		$('#modal').attr('title',url);

		//transition effect
		$('#mask').fadeIn(1000, function() {
			var winH		= $(window).height();
			var winW		= $(window).width();

			$('#modal').fadeIn(1000,function () {
				var user_uid = $('#link-account span').attr('title');
				
				//Code
				swfobject.embedSWF($('#modal').attr('title'), 'game', width, height, '10', 'js/expressInstall.swf', {}, {wmode:'window',bgcolor:'#000000', AllowScriptAccess:'always'}, {}, null);
				$('#modal').show(); 

				//Code
				gameFocusTimer = setTimeout("setGameToFocus()", 2100);
			});
		});
	});
	

	$('#modal-close').click(function () {
		$('#mask').fadeOut('slow');
		$('#modal').fadeOut('slow');
	});

	updateClock();
});

//Code
var gameFocusTimer = null;
function setGameToFocus()
{
  //console.log('setGameToFocus');
  //console.log(mem);
	$('#game').focus(); 
}

