var maingridClass = {
	tiles2Fill: new Array(),
	init : function(_containerRef,_sex,_gridSize)
    {
    	var self = this;
    	this.containerRef = _containerRef ? _containerRef : this.containerRef;
        this.gridSize = _gridSize ? _gridSize : this.gridSize;
        this.sex = _sex ? _sex : me.settings.navigation.filter.sex;
        this.category = me.settings.navigation.filter.filter;
        $(this.containerRef).append('<ul id="maingrid"></ul>');
        $(this.containerRef).append('<div id="reloader" class="tile-size"><div id="reload_button" class="tile-size"></div></div>');
        $(this.containerRef).append('<div id="highlighter" class="tile-size"></div>');
        
        $(this.containerRef+" .tile").live('mouseenter',function(){
            var uid = $(this).attr('id').split('tile_')[1];
            var ucategory = $(this).attr('category');
            var left = $(this).position().left;
            var top = $(this).position().top;
            if(uid) {
            	$('#highlighter').css({
            		left: left,
            		top: top
            	}).attr('userId', uid).removeClass().addClass("tile-size category_"+ucategory).show();
            }
        });
        
        $('#reload_button').live('click',function(){
        	$('#reload_button').hide();
            maingridClass.reloadTiles();
        });
        
        $('#highlighter').click(function(){
            $.trace('show profile:'+$(this).attr('userId'));
            var userId = $(this).attr('userId');
            if($('#profileContainer').length==0){
            	$('body').append('<div id="profileContainer"></div>');
            }
            
            $('#profileContainer').load('global/contents/profile/profile.html', function() {
            	profileClass.init(userId);
            });
            
            $(this).hide();
        }).mouseleave(function(){
            $(this).hide();
        });
    },
    reloadTiles : function(_sex,_category, _online){
    	if(_sex!=undefined){
    		this.sex = _sex;
    	}
    	if(_category!=undefined){
    		this.category = _category;
    	}
    	if(_online!=undefined){
    		this.online = _online;
    	}
    	$('#maingrid li').remove();
        this.tiles2Fill = [];
        this.resize();
        $('#maingrid').trigger('reload');
        
    },
    resize : function(){
    	$("#reload_button").hide();
    	this._calculateRowsColsAndCenter();
    	this._addTiles(this.tilesNeeded);    
    }, 
    _addTiles : function(tiles2Add){
    	// calcolo lo startIndex nel caso debba aggiungere delle tessere e non rigenerarle tutte
        var startIndex = $('#maingrid li').length;
        var endIndex = startIndex+tiles2Add;
        for( var n=startIndex ; n < endIndex; n++){
            $('#maingrid').append('<li id="emptyTile'+n+'" tilenum="'+n+'" class="tile tile-size bg-g'+ (1+Math.floor(Math.random()* 10))+'"></li>');
            maingridClass.tiles2Fill.push(n.toString());
        }        
        this._loadTilesData(this.tilesNeeded);
    },
    _calculateRowsColsAndCenter : function() {
        this.cols = Math.ceil($(this.containerRef).width() / this.gridSize);
        this.rows = Math.ceil($(this.containerRef).height() / this.gridSize);
        // la larghezza del maingrid sarà quindi più grande del suo container
        this.width = this.cols * this.gridSize;
        this.height = this.rows * this.gridSize;
        $('#maingrid').css({width : this.width,height : this.height});
        // aggiorno in numero di celle solo se mi servono + tessere
        this.tilesNeeded = this.cols * this.rows; 
        this.tilesCount = this.tilesNeeded;

        // posiziono il bottone per il reload dei tiles
        this.rowsCenter = Math.floor(this.rows / 2);
        this.colsCenter = Math.floor(this.cols / 2);
        var x = this.colsCenter * this.gridSize;
        var y = this.rowsCenter * this.gridSize;
        $('#reloader').css({top: y,left: x});
    },
    _loadTilesData : function(_tiles2Load)
    {        
		$.post('/json/get/'+_tiles2Load+'/'+this.sex+'/'+this.category+'/', function(data){
	    	var shuffledusers = shuffle(data);
	        maingridClass._renderTiles(shuffledusers);
		});
		
		// dopo 10 secondi se ajax non ha finito per qualche errore faccio ricomparire il reloader
		this.tilesLoadTimeout = setTimeout('maingridClass._showReloader()', 5000); 
    },
    _renderTiles : function (_usersLoaded) {
    	
    	$.each(_usersLoaded,function(index,value){
    		var randomEmptyTile = Math.floor(Math.random()*maingridClass.tiles2Fill.length);
            var tileSelector = maingridClass.tiles2Fill[randomEmptyTile];
            $('#maingrid [tilenum="'+tileSelector+'"]').tile(value);
            maingridClass.tiles2Fill.splice(randomEmptyTile, 1);
            if(maingridClass.tiles2Fill.length == 0){
            	$("#reload_button").show();
            }
        });
    	
        
        if(this.online==false){
        	$('#maingrid .status').css('display','none');
        }else{
        	$('#maingrid .status').css('display','inline-block');
        }
    },
    _showReloader:function(){
    	$("#reload_button").show();
    }
};

