var fps = 20;
var lastMove = 0;
var move = false;
var mouseevent;
var virtualmouse = {x:0,y:0};
var takeoverFactor = .6;
var takeoverThresh = 1;
var num = 2;

App = {};

App.init = function() {
	// Set the transparent pixel
	if($.ifixpng) {
		$.ifixpng('/templates/kulturka/img/s.gif');
		$('img, .bgPng').ifixpng();
	}
	$(document).bind('mousemove',App.move);
//	$('#bg3').pan({fps: fps, speed: 1, dir: 'right'});
	
	$('#sun').bind('mouseover',App.sunOver);
	$('#sun').bind('mouseout',App.sunOut);
	$('#sun').everyTime(8000,'pislant',App.sunPislant);	
//	App.fire();
}

App.now = function() {
	return (new Date).getTime();
}

App.fire = function() {
	var t = App.now();
	
	move = true; 
	var localmouse = {};
	var difference = {};
	var easing = "easeInQuad";
	var duration = 1000;
	
	localmouse.x = mouseevent ? mouseevent.clientX : 0;
	localmouse.y = mouseevent ? mouseevent.clientY : 0;
	
	// Calculate difference
    difference.x    = virtualmouse.x - localmouse.x;
    difference.y    = virtualmouse.y - localmouse.y;
    difference.sum  = Math.sqrt(difference.x*difference.x + difference.y*difference.y);

	// Reset virtualmouse
    virtualmouse.x = localmouse.x + difference.x * takeoverFactor;
    virtualmouse.y = localmouse.y + difference.y * takeoverFactor;
	
	// Move BG
	$("#bg1").css({backgroundPosition: -(virtualmouse.x/20)+"px 0"})
	$("#bg2").css({backgroundPosition: -(virtualmouse.x/60)+"px 0"})

	// If mouse is inside the takeoverThresh set ontarget to true
    if (difference.sum < takeoverThresh && difference.sum > takeoverThresh*-1) {
    	move = false;
    } else {
		setTimeout(App.fire, 1000/fps);
	}
}

App.move = function(e){
	mouseevent = e;
	if (!move && e.clientY <355) App.fire();
	lastMove = App.now();
}

App.sunOver = function(e){
	$(this).stopTime('pislant');
	this.src = "/templates/kulturka/img/sun"+num+".png";
	num = (num%2)+3; //3,4...
}

App.sunOut = function(e){
	$(this).everyTime(8000,'pislant',App.sunPislant);
	this.src = "/templates/kulturka/img/sun1.png";
}

App.sunPislant = function() {
	$('#sun')[0].src='/templates/kulturka/img/sun2.png';
	$('#sun').oneTime(200,'nyit',function(){$('#sun')[0].src='/templates/kulturka/img/sun1.png';});
}

$(document).ready(App.init);
