var piecesUsed =  [];
//var piecesAvailable =  [];  //will be dynamically generated
//var currentPuzzle = '';     //dynamically generated
//var flagSuffix = '';        //dynamicaly generated
var currentPiece = '';
//var parentURL = '' //dynamically set by server
var targets = {};
var dragStart;
var nameStart;
var nameErrors=0;

$(document).ready(function() {
	//show 7 pieces use random plugin
	$('div .bp').random(7).show();
	
	//initialize the positions from json datafile;
	
	//declare tabs
	$('div#tabContainer').tabs();
	//if puzzle is solved, reset it, else trigger ask
	$('#start').click( function() {
	})
	
	//click the ask button
    $('#ask').click( function() {
    	if ( piecesAvailable.length > 0) {
    		 //start timer on first ask
    		 if (nameStart  == undefined) {
    			 nameStart = new Date();
    		 }
	         if (currentPiece == '' ) {
	    	     var currentPos = Math.floor(Math.random() *   piecesAvailable.length );
	    	     currentPiece = piecesAvailable[currentPos];
	        	 //set currentPiece's zIndex to 3000 to put it up front
	        	 $('#n-'+currentPiece).css('zIndex',3000);
	         }
	         //dependency:  requires utf-8.js loaded
	         currentAudio = Utf8.encode(currentPiece);
	         //alert (parentURL + '/' + currentPuzzle + '/audio/' + currentPiece  + '.mp3');
	         playTrack( parentURL + '/' + currentPuzzle + '/audio/' + currentAudio  + '.mp3');
	         $('#flag2').attr("src", parentURL + "/" + currentPuzzle + "/img/flags/" + currentPiece + "-flag" + flagSuffix);
	         //$('#flag2').attr("src", parentURL + "/emblem.php?g=" + currentPuzzle + "gp=" + currentPiece);
	         //x=$('#i-'+ currentPiece).attr("longName")
			 $('#entName2').text($('#i-'+ currentPiece).attr("longName"));
		 } else {
			playTrack( parentURL + '/audio/correct.mp3');
			var nameTimeElapsed =   getPuzzleTimeDiff(new Date(),nameStart);
			checkHallOfFame(nameTimeElapsed,'Name'); 
		 }
    });
    
    //check if the currentPiece's region was clicked
    //if so give feedback and get new currentPiece
	$('.nameable').click( function() {
		if ($(this).attr('id').substr(2) == currentPiece) {
			piecesUsed.push(currentPiece);
			piecesAvailable = piecesAvailable.filter(function(el){
				return (el != currentPiece);
			});
			//set currentPiece's zIndex to a low number to put it behind
			 ;
			//a=$(this).css('zIndex');  alert(a);
			$(this).css({
				       'backgroundImage' :    $('#i-' + currentPiece).css('backgroundImage'),
				       'zIndex' : 2 
			       })
			       //.addClass('s' + $(this).attr('id').substr(1))  
			       .animate( {
				            opacity: 0.25 
				         },
				         200, 
				        'linear'
				  );

			$('#flag2').attr("src","");
		    $('#entName2').text("");
	        currentPiece='';
	        //b=$(this).css('backgroundImage'); alert(b);
			//checkWin2();
		} else {
			nameErrors++;
		}
		$('#ask').trigger('click');
	});
	 
	 // placer, on mu alert the position 
	/* 
	$('.bp').mouseup(function() {
		var $y = $(this).css('top');
		var $x = $(this).css('left');
		var $name = $(this).attr('id');
		 alert ('id= ' + $name + ':left=' +$x + " top=" + $y);
		 targets[$name] = {"left": $x, "top": $y};
		 //document.body.innerHTML='<textarea id="t"></textarea>'; 
		 f= JSON.stringify(targets);
	     //alert(f);
	     $('#t').html(f);

	});
	*/ 
	 
	 //$id = $(this).css('id');
	 
	// base the coordinates of draggers and targets on their parents  
	 $('.drag, .sensible').each( function() {
		 $parent = $(this).parent();
		 $(this).css( { 
		    //margin : '-5px',
		    top : $parent.css('top'),
		    left: $parent.css('left'), 
		    height: $parent.css('height'), //-10 + 'px',
		    width: $parent.css('width')  //-10 +'px'	
 	     });
	 });
	 
	 $('.bp').draggable( {
		 //helper  : 'clone',
		 handle  : '.drag',
		 cursor  :  'move',
	     zIndex  : 3000,
		 stop: function(e,ui) {
		    $(this).css({  'zIndex' : '3000'
		    });
		    //start timer on first drag
		    if (dragStart == undefined) {
		    	 dragStart = new Date() ; 
		    }
		 }		 
	 });
	 $('.bp').mousedown(function() { 
		 //f=parentURL + "/" + currentPuzzle + "/img/flags/" + $(this).attr('id').substring(2) + "-flag.gif"; alert(f); 
		 $('#flag').attr("src", parentURL + "/" + currentPuzzle + "/img/flags/" + $(this).attr('id').substring(2) + "-flag" + flagSuffix);
		 //dynamic graphic
		 //$('#flag').attr("src", parentURL + "/emblem.php?g=" + currentPuzzle + "&gp=" + $(this).attr('id'.substring(2)));
		 $('#entName').text($(this).attr("longName"));
	 });
	 
	 $('.bp').mouseup(function() {
	     $(this).css('zIndex', 3000);
		 $('#flag').attr("src","");
	     $('#entName').text("");
	 });
	
	 $(".droppableP > .sensible").each(function() {
			$(this).droppable( {
			   accept :    "#i" + $(this).closest('.droppableP').attr('id').substring(1), 
			   tolerance : 'intersect',
			   activeClass : 'droppable-active',
			   hoverClass : 'droppable-hover',
			   drop : function() {
				   //dependency:  requires utf-8.js loaded
		           currentAudio = Utf8.encode($(this).closest('.droppableP').attr('id').substring(2) );
				   playTrack( parentURL + '/' + currentPuzzle  + '/audio/' + currentAudio + '.mp3');
				   $(this).closest('.droppableP')
				      //.addClass($(this).closest('.droppableP').attr('id'))  //won't work anymore!!!!!
				      .addClass('encastrado')
				      .css({
				    	  'cursor' : 'auto',
				    	  'backgroundImage' :   $('#i' + $(this).closest('.droppableP').attr('id').substring(1)).css('backgroundImage')
				      }) 
				      .animate( {
				            opacity: 0.25 
				         },
				         200, 
				        'linear'
				      ) ;
				   $("#i" + $(this).closest('.droppableP').attr('id').substring(1)).addClass('used').hide();  //previously remove
				   $('div .bp').not('.used').random(1).show();  //shows a new piece to replace the old one
				   //.css('cursor','auto')
				   checkWin();
			   }
		    }); 
	 });

	function checkWin() {
		var w = $(".encastrado");
		//var a = $(".droppableP");
		// alert(w.length);
		// Congratulation message / Mensaje de felicitacion.
		if (w.length >= $('.droppableP').length) {
			//$('#canvasFinal').fadeIn();
			//$.timer(700, function(timer) {
			var dragTimeElapsed = getPuzzleTimeDiff(new Date(),dragStart);
		    //$("#win").fadeIn('slow');
		    checkHallOfFame(dragTimeElapsed,'Drag');
		}
	}
	
	function checkWin2() {
		if (piecesAvailable.length <= 0 ) {
		    $("#win").fadeIn('slow');
		}
	}

 	function playTrack(t) {
 	   $("#jquery_jplayer").jPlayer("setFile", t).jPlayer("play"); 
 	   return false;
 	};
 	
 	function setUpSubmit(etime,puzzle){
 	    $('#submitTime').val(etime);
		//show the form so the user can enter name & location
		$('#updateScoreFormContainer #puzzleType').val(puzzle);
		//move the form to inside the high scores div
		$('#hallform' + puzzle).append($('#updateScoreFormContainer'));
		$('#updateScoreFormContainer').show();	
		$('#postNewTime').css('zIndex',3050);  //put in front
 	}
 	
 	function checkHallOfFame(etime,puzzle) {
 		nScores=$('#highscores' + puzzle + ' .hiscor').size();
 		if (nScores == 0 ) {
 			setUpSubmit(etime,puzzle);
 		} else if (nScores < 10) {
 			setUpSubmit(etime,puzzle);
 		} else {
 		    $('#highscores' + puzzle + '  .hiscor').each(function() {
 			    if (etime <  (a=parseInt($(this).html())) && nameErrors == 0)  {
 	 			    setUpSubmit(etime,puzzle);   
 	 			    return(false);  //finished form
 			    }
 			});	 
 		} 
 		$('#highscores' + puzzle).show();  
 	}
 	
 	function getPuzzleTimeDiff( endDate, startDate) {
 		return (endDate.getMinutes()-startDate.getMinutes()) * 60000 + (endDate.getSeconds()-startDate.getSeconds()) * 1000 + (endDate.getMilliseconds()-startDate.getMilliseconds());
 	}
 	
 	function updateHighScoresDiv(json,which){
 	}
 	
 	 $('#postNewTime').click( function($e) {
 		$e.preventDefault();
 		var data = $('#addToHallOfFameForm :input').serialize();
 		var whichpuzz = $('#addToHallOfFameForm #puzzleType').val();
 		//alert ("wp=" + whichpuzz);
 		$.post(
 			parentURL + '/updatehighscore.php',
 			data,
 			function(json) {
 				if (json) {
 					//clear it all except the first two rows
 					$('#highscores' + whichpuzz + ' table tbody').children('tr:gt(1)').remove();
 					//console.log(whichpuzz);
 				    $.each(json, function() {
 				       d = new Date();
 					   d.setTime(this.date*1000);
 					   dateString = d.format('d mmm, yyyy');
 					   newrow = '<tr><td >' + this.name + '</td><td>' + this.geo;
					   newrow += '</td><td >' + dateString + "</td><td class=>" + this.time;
					   newrow += '</td></tr>';
					   $('#highscores' + whichpuzz + ' table tbody').append(newrow);
 					});	     
		        } else {
		    		alert('Score Not Successfully updated ');
		    	} //end if
 			}, //end callback
 			'json'
 		); //end post
 	}); //end click
   
 	
	$("#jquery_jplayer").jPlayer({
		ready: function ()
		{
			//this.element.jPlayer('setFile','http://localhost/testing1/tests/GeoP-Test/audio/correct.mp3').jPlayer("play");
		    //playTrack('http://localhost/testing1/tests/GeoP-Test/audio/correct.mp3');
		},
		swfPath: parentURL + "/js",
		oggSupport:  false
	});
	
	$("#addToHallOfFameForm").validate();
	
	//sadd safestring to validator plugin
	$.validator.addMethod("safestring", function(value, element) {
	 	     return this.optional(element) || /^[a-z0-9\_ -,.]+$/i.test(value);
		 },
		 "Field must contain only letters, numbers, space, hyphen, comma, period, or underscore."
	);
	$('.closeBox').click(function($e) {
		$e.preventDefault();
		$('#highscoresDrag, #highscoresName').hide();
	});

});
