/**
*  Sesame Street Bubble Pop Game
*
*  @author William Malone (www.williammalone.com)
*/

WM.bubbleView = function (GLOBAL, WM, ctx, unPopped, popped, highlight, popAnimation, options) {
	
	var that = WM.dispatcher(),
		bubblePopComplete = false;
	
	that.speedX = options && options.speedX;
	that.speedY = options && options.speedY;
	that.x = 0;
	that.y = 0;
	that.width = unPopped.width;
	that.height = unPopped.height;
	that.currentState = "DEFAULT";
	that.dirty = true;
	that.newX;
	that.newY;
	
	that.update = function () {

		unPopped.x = that.x;
		unPopped.y = that.y;
		unPopped.update();

		if (popped !== null) {
			popped.x = that.x;
			popped.y = that.y;
			popped.update();
		}
		
		if (that.currentState === "HIGHLIGHT") {
			highlight.x = that.x;
			highlight.y = that.y;
			highlight.update();
		}
		
		if (that.currentState === "POP") {
			popAnimation.x = that.x;
			popAnimation.y = that.y;
			popAnimation.update();
		}
		
		that.width = unPopped.width;
		that.height = unPopped.height;
	};
	
	that.render = function () {
	
		if (that.currentState === "HIGHLIGHT") {
			highlight.dirty = true;
			highlight.render();
		}
		
		if (that.currentState === "POP") {
			if (popped !== null) {
				if (that.dirty) {
					popped.dirty = true;
				}
				popped.render();
			}
			if (!bubblePopComplete) {
				popAnimation.dirty = true;
				popAnimation.render();
			}
		} else {
			if (that.dirty) {
				unPopped.x = that.x;
				unPopped.y = that.y;
				unPopped.dirty = true;
			}
			unPopped.render();
		}
	};
	
	that.setState = function (state) {

		that.currentState = state.toUpperCase();
		
		if (that.currentState === "POP") {
			popAnimation.start();
		}

		that.dirty = true;
	}
	
	that.getState = function () {

		return that.currentState;
	}
	
	that.destroy = function () {
		unPopped.destroy();
		if (popped !== null) {
			popped.destroy();
		}
		highlight.destroy();
		popAnimation.destroy();
	};
	
	popAnimation.addEventListener("ANIMATION_COMPLETE", function () {
		bubblePopComplete = true;
		that.dispatchEvent("POP_COMPLETE", that);
	});
	
	that.pointCollisionDetection = function (point) {
		var radius = 0;
		if (that.width / 2 > radius) {
			radius = that.width / 2;
		}
		if (that.height / 2 > radius) {
			radius = that.height / 2;
		}
		if (WM.math.vectors.dist(point, {
			x: that.x + radius,
			y: that.y + radius
		}) <= radius) {
			return true;
		};
		return false;
	};
	
	return that;
}