var memoryGamesClass = {
	tplURL : '/global/contents/games/memory.html',
    tplReference : '#memory',
    datasource : 'memory_html',
	femalePercentage    : 2, 
    gridSize            : 72,
    titlesCount			: undefined,
    cols				: 6,
    rows				: 4,
    width				: 432,
    height				: 341,
    mtop				: 170.5,
    mleft				: 216,
    tiles2Fill          : new Array(),
    count				: 0,
    atempts				: 0,
    pic1				: undefined,
    pic2				: undefined,
    picId1				: undefined,
    picId2				: undefined,
    arrMemory			:[],
    coupleFind			:0,
    abilityClick		: true,
	init:function(){
		var self = this;
		$(this.tplReference).css({'width':this.width,'height':this.height,'margin-top':- this.mtop,'margin-left':-this.mleft});
		
		// Seleziona il livello
		$(this.tplReference+' input[name="level"]').change(function () {
    		self._level({ timeout: 3000 });
    	});
		this._calculateRowsColsAndCenter();
		this._generateGrid();
		
		if($.client.os=="Mac") { $(this.tplReference+" .close").css({'right': '','left': -'22'}); }
        
    	$(document).keypress(function(e) {
    		if (e.keyCode == 27) { self._close(); }   // esc
    	});
    	
		$(this.tplReference+" .close").click(function() {
			memoryGamesClass._close();
        });
		$("#maskId").click(function(){
        	self._close();
        });
    },
	_level:function(){
		var level = $(this.tplReference+' input[name=level]:checked' ).val();
		
		switch (level){
			case "easy":
				this.cols = 6;
				this.rows = 4;
			break;
			case "medium":
				this.cols = 8;
				this.rows = 6;
			break;
			
			case "hard":
				this.cols = 12;
				this.rows = 6;
			break;
		}
		this.atempts = 0;
		this.coupleFind =0;
		$(this.tplReference + " #memorygrid").empty();
		this.width = this.cols * this.gridSize;
        this.height = this.rows * this.gridSize + $(this.tplReference+ " #level .title").height();
        this.mtop  = this.height/2;
        this.mleft = this.width/2;
		$(this.tplReference).css({'width':this.width,'height':this.height,'margin-top':-this.mtop,'margin-left':-this.mleft});
		// Calcola quanti elementi ci stanno in una griglia
		this._calculateRowsColsAndCenter();
		this._generateGrid();
		
	},
	_calculateRowsColsAndCenter : function() { // ex boxesCenter
        // Dimenzione della griglia
		this.width = this.cols * this.gridSize;
        this.height = this.rows * this.gridSize;
		$(this.tplReference + " #memorygrid").css({'width':this.width,'height':this.height});

		// aggiorno in numero di celle solo se mi servono + tessere      
		var tilesNeeded = this.cols * this.rows; 
        this.tilesCount = Math.round(tilesNeeded/2);
        
        $(this.tplReference+ " #memorytotal").html(this.tilesCount);
        $(this.tplReference+ " #memorycount").html(this.coupleFind);
    },
    _generateGrid:function(){
    	var self = this;
    	for( var n=0 ; n < this.tilesCount*2; n++){
            $(this.tplReference+' #memorygrid').append('<li id="tile_'+n+'" tilenum="'+n+'" class="tile tile-size"></li>');
            this.tiles2Fill.push(n.toString());
    	}
    	    	
    	$.post('/json/get/'+this.tilesCount+'/'+me.settings.navigation.filter.sex+'/'+me.settings.navigation.filter.filter+'/', function(data){
    		var b = data.concat(data);
    		var shuffledusers = shuffle(b);
    		self._renderTiles(shuffledusers);
    	});
    },
    _renderTiles : function (_usersLoaded) {
        $.each(_usersLoaded,function(index,value){
            // prendo uno a caso dall'array dei tiles da riempire
            var randomEmptyTile = Math.floor(Math.random()*memoryGamesClass.tiles2Fill.length);
            // ne recupero il valore
            var tileSelector = memoryGamesClass.tiles2Fill[randomEmptyTile];
            // lo seleziono e lo inizializzo come tile passandogli i dati utente caricati
            $(memoryGamesClass.tplReference+' #memorygrid [tilenum="'+tileSelector+'"]').click(function(){
            	if(memoryGamesClass.abilityClick == true){
            		$(this).tile(value);
            		$(memoryGamesClass.tplReference+' .status').remove();
            		$(memoryGamesClass.tplReference+' .filter').remove();
                	memoryGamesClass.count++;
                	memoryGamesClass._memoryRules($(this).attr('id'), tileSelector,memoryGamesClass.count);
            	}
            	
            });
            // rimuovo questo indice dall'array dei tiles da riempire
            memoryGamesClass.tiles2Fill.splice(randomEmptyTile, 1);
        });
    },
    _memoryRules:function(elementId,tileSelector,count){
    	
    	if(count==1){
    		this.pic1 = tileSelector;
    		this.picId1 = elementId;
    		this.arrMemory = [{
				'id': elementId,
				'tileSelector' : tileSelector
    		}];
    	}else{
    		
    		if(this.pic1!=tileSelector){
    			this.abilityClick = false;
    			this.pic2 = tileSelector;
    			this.picId2 = elementId;
    			if(this.picId2!=this.picId1){
    				memoryGamesClass.atempts ++;
    				this.arrMemory.push({'id':elementId,'tileSelector' :tileSelector});
        			tempoMem = setTimeout("memoryGamesClass._removeTile(memoryGamesClass.arrMemory);", 1200);
    			}else{
    				this.pic2 = undefined;
    				this.pic1 = undefined;
    				this.picId2 = undefined;
    				this.picId1 = undefined;
    				this.arrMemory = [];
    				this.abilityClick = true;
    				this.coupleFind ++;
    				$(this.tplReference+ " #memorycount").html(this.coupleFind);

    				if(this.coupleFind==this.tilesCount){
    					this.coupleFind=this.tilesCount;
    					alert("Complimenti ci sei riuscito con "+this.atempts+ " errori");
    				}
    			}
    			this.count=0;
    		}else{
    			this.count=1;
    			count = 1;
    		}
    	}
    	
    },
    _removeTile:function(arrMemory){

    	$.each(arrMemory,function(key,value){
        	$(memoryGamesClass.tplReference+ " #"+value.id).removeAttr('style').removeAttr('initialized').removeAttr('sex').removeAttr('category').attr('id','tile_'+value.tileSelector);
    	});
		this.pic2 = undefined;
		this.pic1 = undefined;
		this.picId2 = undefined;
		this.picId1 = undefined;
    	this.abilityClick = true;
    	this.picCache = undefined;
    	
    },
    _close:function(){
    	$.unmask();
    	$(this.tplReference).remove();
    }
};
