/*Easing p-in by Jamie Lemon, lemonsanver.com*/
jQuery.extend({
	easing: {
		cubicEaseInOut:function(p, n, firstNum, diff) {
            var c=firstNum+diff;
            
            if ((p/=0.5) < 1)
                return c/2*p*p*p + firstNum;
            else
                return c/2*((p-=2)*p*p + 2) + firstNum;
        }
    }
});
/*EOP-IN*/

function randim(min, max) {
	var r = min + Math.floor(Math.random() * max);
	return r;
}

var itemw;
var itemh;
var cols;
var rows;
var scenew;
var sceneh;
var homet = 0;
var homel = 0;

function set_scene() {
	var item_count = $('.post-item').length;
	
	rows = Math.ceil(Math.sqrt(item_count));
	
	cols = Math.ceil(item_count / rows);
	
	itemw = $('.post-item').width();
	itemh = $('.post-item').height();
	
	scenew = itemw * cols;
	sceneh = itemh * rows;
}

function kaydir(args) {
	$('.post-item').css('z-index', 5);
	$('.wrap').stop(false,true);
	$('.wrap').animate(args,500,'cubicEaseInOut', fokus);
}

function set_stage() {
	var bw = $(window).width();
	var bh = $(window).height();
	
	$('.main-wrap').width(bw).height(bh);
	$('.front').width(bw).height(bh);
	
	var topm = 172;
	
	$('.wrap').width(scenew).height(sceneh)
			  .css('margin-left', (5+Math.ceil((bw-itemw)/2))+'px')
			  .css('margin-top', topm+'px');
	
	var lw = (bw-820)/2;
	if(lw<0) lw=0;
	
	$('.side-wrap').css('width', lw+'px').css('height', bh+'px');
	
	var fh = bh - topm - $('.middle').height() - $('.heading').height() + 202;
	if(fh<35) fh=35;
	$('.footer').height(fh);
	
	$(document).focus();
}


function set_home() {
	homet = -1*(randim(1,rows) - 1) * itemh;
	homel = -1*(randim(1,cols) - 1) * itemw;
	kaydir({left: homel+'px', top: homet+'px'});
}

function fokus() {
	var wpos = $('.wrap').position();
	$('.post-item').each(
		function(index) {
			var pos = $(this).position();
			if(pos.left == Math.floor(Math.abs(wpos.left)) && pos.top == Math.floor(Math.abs(wpos.top))) {
				$(this).css('z-index', 15);
			}
		}
	);
}

function docload() {
	set_scene();
	set_home();
	set_stage();
}

function winresize() {
	set_scene();
	set_stage();
}

$(document).ready(docload);
$(window).resize(winresize);

$(document).keydown(
	function (e) {
		var wpos = $('.wrap').position();
		if(e.keyCode == 40 && wpos.top > -1*(rows-1)*itemh) {//alt
			kaydir({top: (wpos.top-itemh)+'px'});
		} else if (e.keyCode == 38 && wpos.top < 0){//ust
			kaydir({top: (wpos.top+itemh)+'px'});
		} else if (e.keyCode == 37 && wpos.left < 0){//sol
			kaydir({left: (wpos.left+itemw)+'px'});
		} else if (e.keyCode == 39 && wpos.left > -1*(cols-1)*itemw){//sag
			kaydir({left: (wpos.left-itemw)+'px'});
		} else if(e.keyCode == 36) {//home
			kaydir({left: homel+'px', top: homet+'px'});
		}
	}
);
