var irritating;
var boxRight = -835;

$(function() {
	$('#box').css({
		position: 'absolute',
		padding: '0px',
		right: boxRight + 'px',
		top: getTop() + 'px'
	})
	
	$(window).resize(function() {
		$('#box').css('top', getTop() + 'px');
		if (!irritating) {
			$('#box').css('right', (($(window).width() / 2) - 422) + 'px');
		}
	});
	
	function getTop() {
		var result = (($(window).height() / 2) - 250);
		if (result < 115) result = 115;
		return result; 
	}
	
	irritating = window.setInterval(irritate, 2000);

	var go = function() {
		if (irritating) {
			window.clearInterval(irritating);
			irritating = null;
			$('#box').stop(true);
			$('#box').animate({
				right: (($(window).width() / 2) - 422) + 'px'
			}, 800);
		};
	}
	$('#box').mouseenter(go);
	$('form').click(go);
	
	$('#box #closeme').click(function() {
		irritate();
		irritating = window.setInterval(irritate, 3000);
		return false;
	});
});

function irritate() {
	var something;
	var lots = 0;
	var silly = function(){
		something = Math.ceil(Math.random() * 100);
		$('#box').animate({
			right: (boxRight + something) + 'px'
		}, 200, function(){
			$('#box').animate({
				right: boxRight + 'px'
			}, 200, function() {
				lots += 1;
				if (lots < 0) silly();
			});
		});
	}
	silly();
}

var swooshValues = {
	swooshing: false,
	vert: null,
	tempValTo: null,
	tempValFrom: null,
	oldVal: null
}

function swoosh(direction) {
	var vert, tempValTo, tempValFrom;
	var box = $('#box');
	switch (direction) {
		case 'right':
			vert = false;
			tempValTo = ((box.width() + 100) * -1) + 'px';
			tempValFrom = ($(window).width() + 100) + 'px';
			break;
		case 'left':
			vert = false;
			tempValTo = ($(window).width() + 100) + 'px';
			tempValFrom = ((box.width() + 100) * -1) + 'px';
			break;
		default:
			vert = true;
			tempValTo = (tempValFrom = $(window).height() + 100) + 'px';
	}
	var oldVal = box.css((vert ? 'top' : 'right'));
	box.animate((vert ? {top: tempValTo} : {right: tempValTo}), 100, function() {
		box.css((vert ? 'top' : 'right'), tempValFrom);
		swooshValues.swooshing = true;
		swooshValues.vert = vert;
		swooshValues.tempValTo = tempValTo;
		swooshValues.tempValFrom = tempValFrom;
		swooshValues.oldVal = oldVal;
		window.setTimeout(finishSwoosh, 5000);
	});
}

function finishSwoosh() {
	if (swooshValues.swooshing) {
		swooshValues.swooshing = false;
		$('#box').animate((swooshValues.vert ? {top: swooshValues.oldVal} : {right: swooshValues.oldVal}), 600);
	}
}

