

function closeRules(){

$('#regles').css('visibility','hidden');

}

function closeWin(){

$('#win').css('visibility','hidden');

}



function showRules(){

$('#regles').css('visibility','visible');
$('#img_rules').attr('src',"img/rules-grid.png");


}

Number.prototype.addZero  = function(){
	if (this<10){
		return '0'+this;
	}else{	
		return this;
	}
}

// Cookie functions
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
	';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
//
function Timer(conteneur) {		
    this.beginTime = null;
	this.conteneur = conteneur;   
	this.timerId = null;
	var self = this;
	
	this.update  = function(){	
		var now = new Date();		
		var diff  =  (now- self.beginTime)/1000;
		var seconds=Math.floor(diff % 60);
		diff=diff/60;
		var minutes=Math.floor(diff % 60);	  				
		self.conteneur.html(minutes.addZero() +':'+seconds.addZero());
		//alert(self.conteneur.html());
	}
	
	
	
 }


Timer.prototype.start = function(){
	 this.beginTime = new Date();	 
	  if (null!=this.timerId) clearInterval(this.timerId);
	 this.timerId = setInterval(this.update,1000);
}

Timer.prototype.stop = function(){	
	 if (null!=this.timerId) clearInterval(this.timerId);
	 this.conteneur.html("00:00");
}

Timer.prototype.pause = function(){	
	 clearInterval(this.timerId);	
}

Timer.prototype.resume = function(){	
	 this.timerId = setInterval(this.update,1000);
}

Timer.prototype.getContent = function(){	
	return this.conteneur.html();
}

// SquarO class


function SquarO(conteneur) {
	this.conteneur = conteneur;
	// pour faciliter l'int?ation dans le layout
	this.conteneur.css('position','relative');
	this.conteneur.css('height','480px');
	this.conteneur.css('width','320px');
	this.conteneur.css('background-image','url(img/app-background.png)');
	
	// fin style
	this.htmlContent = "";
	this.size = 5;
	this.nbRonds = (this.size+1)*(this.size+1);
	this.userRonds = new Array(this.nbRonds);
	this.resultat = new Array(this.size+1);
	this.chiffres = new Array(this.size);
	this.solved = false;
	this.grid = "";
	// gestion du message de retour
	this.http_request = false;
	this.timerClass = null;
	this.rondDOM = new Array(this.nbRonds);
	this.clickFunction = null;
	this.solutionFunction = null;	
	this.level = "facile";
	

}

SquarO.prototype.setChiffre = function (id,value,posX,posY){
	return '<span class="chiffre" id="'+id+'" style="position:absolute;z-index:2;font-weight:bold;font-size:18px;'
		   +'top:'+posX+'px;'
		   +'left:'+posY+'px;"'		 		 		   
		   +'>'+value+'</span>';		
}

SquarO.prototype.check = function(){

	var ok = true;
	for (var i=0;i<this.size;i++){		
		for (var j=0;j<this.size;j++){	
				if ( this.chiffres[i][j]  != (this.userRonds[(this.size+1)*i+j]+this.userRonds[(this.size+1)*(i+1)+j]+this.userRonds[(this.size+1)*i+(j+1)]+this.userRonds[(this.size+1)*(i+1)+(j+1)])){
				ok = false;					
				//break ;
				$('#ch'+i+''+j).css('color',"#b06e7c");
			}else{
				$('#ch'+i+''+j).css('color',"#9fbdcb");
			}
		}
	}
	if (ok){
		this.solved = true;
	    this.timerClass.pause();  
		//alert('Grid completed in '+this.timerClass.getContent());
		this.showWin(this.timerClass.getContent());	
	}
}


SquarO.prototype.clickDiaboliqueRond = function (e){   	
			
	var _this = e.data._this;	
	if (_this.solved) return;	
	
	var id = parseInt(this.id);	
	var obj =  _this.rondDOM[id];
	var img = e.target;
	if (_this.userRonds[id] == 0){
		img.src = 'img/grid-semicircle.png';	
		_this.userRonds[id] = 1;
	}else if (_this.userRonds[id] == 1){
		img.src = 'img/grid-circle-full.png';	
		_this.userRonds[id] = 2;
	}else{
		img.src = 'img/grid-circle-empty.png';
		_this.userRonds[id] = 0;
	}		
	_this.check();
}

SquarO.prototype.clickRond = function (e){   

	var _this = e.data._this;	
	if (_this.solved) return;	
	
	var id = parseInt(this.id);
	
	var obj =  _this.rondDOM[id];
	
	var img = e.target;

	if (_this.userRonds[id] == 1){
		 img.src = 'img/grid-circle-empty.png';
		_this.userRonds[id] = 0;
	}else{
		img.src = 'img/grid-circle-full.png';
		_this.userRonds[id] = 1;
	}	
	_this.check();
}


SquarO.prototype.showWin = function(time){
	$('#win').css('visibility','visible');
    $('#time_win').html(time);
}


SquarO.prototype.setRond = function (id,posX,posY){

	return '<span class="rond" id="rond'+id+'"'    
		   +' style="cursor:pointer;position:absolute;'
		   +'top:'+posX+'px;'
		   +'left:'+posY+'px;'
		   +'width:'+28+'px;'
		   +'height:'+28+'px;"'		  	 		   
		   +'></span>'
		   +'<img class="img_rond" id="'+id+'"'
	       +'src="img/grid-circle-empty.png" alt="rond"'
		   +'style="cursor:pointer;position:absolute;z-index:10;'
		   +'top:'+posX+'px;'
		   +'left:'+posY+'px;"'
		   +'width="'+28+'"'
		   +'height="'+28+'"'		   
		   +'/>';
}


SquarO.prototype.drawGrid = function(){
	
	var marginTop=100;
	var marginLeft=12;
    var pas=52;
	
	var currend_id_rond=0;
	for (var i=0;i<this.size+1;i++){
		for (var j=0;j<this.size+1;j++){
			this.htmlContent+= this.setRond(''+currend_id_rond,marginTop+pas*i,marginLeft+pas*j);												
		    currend_id_rond++;
		}
	}

	for (var i=0;i<this.size;i++){
		for (var j=0;j<this.size;j++){		   
			this.htmlContent+= this.setChiffre('ch'+i+''+j,0,marginTop+pas*i+pas/2+1,marginLeft+pas*j+pas/2+9);	   
		}
	}
/*	
	for (var i=0;i<(this.size+1);i++){
		for (var j=0;j<this.size;j++){	  
			this.htmlContent+=  '<span style="position:absolute;left:'+(marginLeft+27+pas*j)+'px;top:'+(marginTop+13+pas*i)+'px;background-color:black;width:28px;height:3px;"></span>';	   
		}
}

	for (var i=0;i<(this.size+1);i++){
		for (var j=0;j<this.size;j++){	  
			this.htmlContent+=  '<span style="position:absolute;left:'+(marginLeft+13+pas*i)+'px;top:'+(marginTop+27+pas*j)+'px;background-color:black;width:3px;height:28px;"></span>';	   
		}
	}

*/


  this.htmlContent+=  '<img style="position:absolute;left:'+(marginLeft+14-2)+'px;top:'+(marginTop+14-3)+'px;" src="img/grid-background.png"></img>';
}

SquarO.prototype.drawTimer = function(){
	this.htmlContent+='<div id="timer" style="text-align:center;width:80px;';
	this.htmlContent+='position: absolute;top:5px;left:65px;color:#0f445c;right:0px;z-index:200;font-size:75px;font-weight:bold;visibility:visible;">';
    this.htmlContent+='00:00';
	this.htmlContent+='</div>';
}

SquarO.prototype.drawLoading = function(){
	this.htmlContent+='<div id="loading" style="background-color:red;text-align:center;width:120px;';
	this.htmlContent+='position: absolute;top:0px;left:100px;z-index:200;font-weight:bold;font-size:22px;visibility:hidden;">';
    this.htmlContent+='Loading...';
	this.htmlContent+='</div>';
}

SquarO.prototype.drawRules = function(){
	this.htmlContent+='<div id="regles" style="visibility:hidden">'
	this.htmlContent+='<div  style="position:absolute;margin-top:0px;top:0px;left:0px;width:'+this.conteneur.width()+';height:'+this.conteneur.height()+';background-repeat: no-repeat;opacity:0.5;z-index:200;">';
	this.htmlContent+='</div>'
	this.htmlContent+='<div style="background-image:url(img/app-background.png);width:320px;height:480px;position:absolute;z-index:300;opacity:1.0;color:white;font-size;14px">';
	this.htmlContent+='<p style="padding:2px;">'
	this.htmlContent+='<b>The goal of SquarO</b> is to find the circle to fill in black.<br/>';
	this.htmlContent+='In each square, you have a number between 0 and 4 which corresponds to the number of circles around that square that must be filled.<br/><br/>';
	this.htmlContent+='<center><img style="text-align:center" id="img_rules" src="" alt="rules"/></center>';
	this.htmlContent+='<br/>All the grids have a <b>unique solution</b>.<br/>';
	this.htmlContent+='For <b>evil</b> SquarO, the number can be between 0 and 8 which corresponds to the number of half-circles around that square that must be filled.'; 
	this.htmlContent+='<center><input id="close_rules_btn" type="image" src="img/button-ok.png" value="Close"/></center>';
	this.htmlContent+='</p>'
	this.htmlContent+='</div>';
	this.htmlContent+='</div>';
	
}


SquarO.prototype.drawWin = function(){
	this.htmlContent+='<div id="win" style="visibility:hidden">'
	this.htmlContent+='<div  style="position:absolute;margin-top:0px;top:0px;left:0px;width:'+this.conteneur.width()+';height:'+this.conteneur.height()+';background-repeat: no-repeat;opacity:0.5;z-index:300;">';
	this.htmlContent+='</div>'
	this.htmlContent+='<div style="background-image:url(img/app-background.png);width:320px;height:480px;position:absolute;z-index:300;opacity:1.0;color:white;font-size;14px">';
	this.htmlContent+='<p style="padding:2px;">'
	this.htmlContent+='<center><b>Congratulations !</b></center>';
	this.htmlContent+='<center><p>Your time :</p></center>';
	this.htmlContent+='<center><p id="time_win" style="margin-top:45px;margin-bottom:45px;color:#fff;right:0px;z-index:200;font-size:75px;font-weight:bold;">00:00</p></center>';
	this.htmlContent+='</p>'
	this.htmlContent+='<center><input id="share_btn"  style="margin-top:15px;margin-bottom:35px" type="image" src="img/button-share-on-facebook-en.png" value="Share"/></center>';
	this.htmlContent+='<center><input id="close_win_btn" type="image" src="img/button-ok.png" value="Close"/></center>';
	this.htmlContent+='</div>';
	this.htmlContent+='</div>';
	
}

SquarO.prototype.shareScore = function(e)
{
	var _this = e.data._this;
	var message = 'Check out this new addictive puzzle';
    var attachment = {
	'name': 'I\'ve finished a grid of SquarO in '+_this.timerClass.getContent(),
	'href': 'http://bit.ly/squaroapp',
	'caption': 'Level '+$('#level_btn :selected').text(),
	'description': 'Can you beat me ?',
	'media': [{ 'type': 'image', 'src': 'http://www.squaro.fr/app/img/apple-touch-icon.png', 'href': 'http://bit.ly/squaroapp'}]
	}; 
    var action_links = [{'text':'Play SquarO', 'href':'http://bit.ly/squaroapp'},{'text':'Play SquarO', 'href':'http://bit.ly/squaroapp'}];  
    FB.Connect.streamPublish(message, attachment, action_links);	
}

SquarO.prototype.drawButtons = function(){
	var top = 415;
	this.htmlContent+='<input id="solution_btn" type="button" value="Solution" style="position:absolute;top:'+top+'px;left:70px;"/>';	
	this.htmlContent+='<input id="rules_btn" type="button" value="Rules" style="position:absolute;top:'+top+'px;left:5px;" />';
	this.htmlContent+='<input id="newGrid_btn" type="button" value="New Grid" style="position:absolute;top:'+top+'px;left:148px;"/>';
	this.htmlContent+='<select name="Level" id="level_btn"  style="position:absolute;top:'+top+'px;left:235px;">';
	this.htmlContent+='    <option value="facile">Easy</option>';
	this.htmlContent+='    <option value="moyen">Medium</option>';
	this.htmlContent+='    <option value="difficile">Hard</option>';
	this.htmlContent+='    <option value="diabolique">Evil</option>';
	this.htmlContent+='</select>';
}

SquarO.prototype.addControls = function(){

	for (var i=0;i<this.nbRonds;i++){		
			this.rondDOM[i] = $('#rond'+i);
	}	
	var btn_width = 70;
	$('#solution_btn').bind('click',{_this: this},this.displaySolution); 	
	$('#solution_btn').width(btn_width);
	$('#close_rules_btn').bind('click',closeRules);
	$('#close_rules_btn').width(btn_width);
	$('#rules_btn').bind('click',showRules);
	$('#rules_btn').width(btn_width-10);
	$('#newGrid_btn').bind('click',{_this: this},this.askForNewGrid);
	$('#newGrid_btn').width(btn_width+5);
	$('#level_btn').bind('change',{_this: this},this.askForNewGrid);
	$('#level_btn').width(btn_width+5);
	$('#close_win_btn').bind('click',closeWin);
	$('#share_btn').bind('click',{_this: this},this.shareScore);
}

SquarO.prototype.drawAppstoreLink = function(){
	
	this.htmlContent+='<center><a style="color:white;position:relative;top:450px;" href="http://getap.ps/squaro">Get SquarO for iPhone</a></center>';
}


SquarO.prototype.gridUrl = function (level)
{
	var numero = Math.floor(100*Math.random())+1;
	if (numero>100) numero = 100;
	if ("moyen"==level) {
		numero+=100;
	}else if ("difficile"==level) {
		numero+=200;
	}else if ("diabolique"==level) {
		numero+=300;
	}
	
	return 'http://www.squaro.fr/getGrid.php?size=5&grille='+numero+'&niveau='+level;
 //   return 'getGrid.php?size=5&grille='+numero+'&niveau='+level;

}


SquarO.prototype.askForNewGrid = function(e){
			 
	$('#loading').css('visibility',"visible");			
	var _this = e.data._this;		
	_this.timerClass.stop();
	var url = _this.gridUrl($('#level_btn').attr('value'));	
	$.get(url, function(data){		
		_this.newGrid(data.substring(26,62));	
		$('#loading').css('visibility',"hidden");	
	});	
}

SquarO.prototype.firstGrid = function(){
			
	$('#loading').css('visibility',"visible");	
	this.timerClass.stop();
	var url = this.gridUrl($('#level_btn').attr('value'));	
	var _this = this;
	$.get(url, function(data){		
		_this.newGrid(data.substring(26,62));	
		$('#loading').css('visibility',"hidden");	
	});	
}

SquarO.prototype.newGrid = function(grid){
	

	var index=0;
	this.grid = grid;
	var size = this.size;
	for (var i=0;i<(this.size+1);i++){
		this.resultat[i] = new Array(this.size+1);
		for (var j=0;j<(this.size+1);j++){	
			this.resultat[i][j] =  parseInt(grid.substring(index,++index));		
		}
	}	
	
	for (var i=0;i<this.size;i++){
		this.chiffres[i] = new Array(this.size);
		for (var j=0;j<this.size;j++){	
			this.chiffres[i][j] = this.resultat[i][j] +this.resultat[i+1][j] +this.resultat[i][j+1] +this.resultat[i+1][j+1] ;
			var obj = $('#ch'+i+''+j);
            obj.text(this.chiffres[i][j]);			
			if (0!=this.chiffres[i][j]) {
				obj.css('color',"#b06e7c")
			}else {			
				obj.css('color',"#9fbdcb")
			}
		}
	}
	
	for (var i=0;i<this.nbRonds;i++){	
			this.userRonds[i]=0; 			
	}	
	
	var newClickFunction;
	
	if ("diabolique"==$('#level_btn').attr('value')){
			newClickFunction = this.clickDiaboliqueRond; 
	}else{
			newClickFunction = this.clickRond;
	}
	
	
	if (null!=this.clickFunction){
		$('.img_rond').unbind('click',this.clickFunction);
	}	
	
	//$('.rond').css('backgroundColor',"white");	
	$('.img_rond').attr('src',"img/grid-circle-empty.png");	
	$('.rond').css('height',"28px");	
	$('.img_rond').bind('click',{_this: this},newClickFunction);

	this.clickFunction = newClickFunction;	
	
	// solution btn
	var newSolutionFunction
	
	if (null!=this.solutionFunction){
		$('#solution_btn').unbind('click',this.solutionFunction);
	}	
	
	if ("diabolique"==$('#level_btn').attr('value')){
				newSolutionFunction = this.displayDiaboliqueSolution; 
	}else{
				newSolutionFunction = this.displaySolution; 
	}
	
	$('#solution_btn').bind('click',{_this: this},newSolutionFunction);
	
	this.solutionFunction = newSolutionFunction;	
	
	
	setCookie("squaro",this.grid+";"+$('#level_btn').attr('value'),14);
	this.solved = false;
	this.timerClass.start();
}

SquarO.prototype.displayDiaboliqueSolution = function(e){
	var _this = e.data._this;	
	_this.solved = true;	
	$('.chiffre').css('color',"#9fbdcb")
	
	for (var i=0;i<(_this.nbRonds);i++){		
		var obj = _this.rondDOM[i];	
		var res = parseInt(_this.grid.substring(i,i+1));
		var img = $('#'+i);	
		if (0==res){
			img.attr('src','img/grid-circle-empty.png');		
		}else if (1==res){
			img.attr('src','img/grid-semicircle.png');			
		}else if (2==res){
			img.attr('src','img/grid-circle-full.png');			
		}				
	}	
	
	_this.timerClass.stop();
}

SquarO.prototype.displaySolution = function(e){
	var _this = e.data._this;	
	_this.solved = true;	
	$('.chiffre').css('color',"#9fbdcb")
	
	for (var i=0;i<(_this.nbRonds);i++){		
	    var img = $('#'+i);	
		if (0==parseInt(_this.grid.substring(i,i+1))){
		    img.attr('src','img/grid-circle-empty.png');			 
		}else{
			img.attr('src','img/grid-circle-full.png');
		}			
		
	}	
	
	_this.timerClass.stop();
	
	
}

SquarO.prototype.retry = function(){
	
}

SquarO.prototype.draw = function(){
	this.drawGrid();	
	this.drawTimer();	
	this.drawButtons();
	this.drawLoading();
	this.drawRules();
	this.drawAppstoreLink();
	this.drawWin();
	
}

SquarO.prototype.setUp = function(){   
	this.draw();
	this.conteneur.html(this.htmlContent);
	this.addControls();	
	this.timerClass = new Timer($('#timer'));
	var cookie = getCookie("squaro");
	if (null==cookie){
		this.firstGrid();
	}else{
		var args = cookie.split(';');		
		$('#level_btn').attr('value',args[1]);		
		this.newGrid(args[0]);
	}
	
}
