var BUBBLES;
$(document).ready(function(){
	initBubblesAnimation();
});

function initBubblesAnimation(){
	var bubbles = $('.bubble-item');
	for(var i = 0, len = bubbles.length ; i < len ; i ++ ){
		bubble = bubbles[i];
		if(i%2){
			setMovingLeft(bubble);
			setMovingTop(bubble);
		} else if(i%3){
			setMovingRight(bubble);
			setMovingTop(bubble);		
		} else {
			setMovingRight(bubble);
			setMovingBottom(bubble);		
		}
	}
	moveBubbles();
}

var containerX = 0;
var containerY = 316;

function moveBubbles(){
	var bubbles = BUBBLES = $('.bubble-item');
	var parent = $('.bubble-item').parent();
	containerX = parent.width();
	//containerY = parent.height();
	
	for(var i = 0, len = bubbles.length ; i < len ; i ++ ){
	
		var x = Math.floor(Math.random()*(containerX - 150));
		var y = Math.floor(Math.random()*(containerY - 150));
		
		bubble = BUBBLES[i];
		$(bubble).css('left', x+'px');
		$(bubble).css('top', y+'px');
	
		var interx = setInterval("doMove(" + i + ")", 75);
	}
}


function doMove(i){
		bubble = BUBBLES[i];
		new_coord =	getNewCoord(bubble);
		$(bubble).css('left', new_coord[0]+'px');
		$(bubble).css('top', new_coord[1]+'px');
}


function getNewCoord(bubble){
	var OFFSET = 1;
	var x,y;
	var coord = $(bubble).position();

	//var doc_w = $(window).width();
	//var doc_h = $(window).height();
	
	
	if ( isMovingBottom(bubble) ){
		if(coord.top > (containerY - 100)){
			setMovingTop(bubble);
		} 
	}else {
		if(coord.top < -22){
			setMovingBottom(bubble);
		}
	}
	
	
	if(isMovingTop(bubble)){
		y = coord.top - OFFSET;
	} else {
		y = coord.top + OFFSET;
	}

	if(isMovingLeft(bubble)){
		if(coord.left < 0){
			setMovingRight(bubble);
		} 
	} else {
		if(coord.left > (containerX - 136) ){
			setMovingLeft(bubble);
		} 
	}


	if(isMovingLeft(bubble)){
		x = coord.left - ( OFFSET * (Math.random() + 1));
	} else {
		x = coord.left + ( OFFSET * (Math.random() + 1));
	}
	
	return [x, y]
}

function isMovingLeft(bubble){
	return $(bubble).hasClass('bubble-moving-left');
}
function isMovingRight(bubble){
	return $(bubble).hasClass('bubble-moving-right');
}
function  isMovingTop(bubble){
	return $(bubble).hasClass('bubble-moving-top');
}
function  isMovingBottom(bubble){
	return $(bubble).hasClass('bubble-moving-bottom');
} 


function setMovingLeft(bubble){
	$(bubble).addClass('bubble-moving-left');
	return $(bubble).removeClass('bubble-moving-right');
}
function setMovingRight(bubble){
	$(bubble).removeClass('bubble-moving-left');
	return $(bubble).addClass('bubble-moving-right');
}
function setMovingTop(bubble){
	$(bubble).addClass('bubble-moving-top');
	return $(bubble).removeClass('bubble-moving-bottom');
}
function setMovingBottom(bubble){
	$(bubble).addClass('bubble-moving-bottom');
	return $(bubble).removeClass('bubble-moving-top');
}
