jQuery(document).ready(function(){

//------------------------------------------------------------
//--> colors!!!!!!!!!!!	(and more!)
var spencer_home = (function(){
	var canvas = document.getElementById('sketch');
	if (canvas.getContext){
	var ctx = canvas.getContext("2d"),
		model = {mouse:{mode:true,x:[1],y:[1],color:["rgba(200,200,250,.1)"],ticks:0},active_objects:[],canvas:{zoom:1,rotation:0,width:0,height:0,red:60,green:250,blue:220,scale:{huge:0,big:0,middle:0,small:0}},timer:0,realtime:0};		

	function buildCanvas(){
			// check to see if height set, if so, it's a resize, update all heights
		if(model.canvas.height){
			var window_quotient = ($(window).height()-78) / model.canvas.height;
			poem.currentHeight = poem.currentHeight * window_quotient;
			poem.each(function(verse){
				verse.poem_y = verse.poem_y * window_quotient;
			});
		};
		canvas.width = model.canvas.width = $(window).width()-28; // expecting total margin of 20; border of 4
		canvas.height = model.canvas.height = $(window).height()-78; // expecting info bar 50px hight
		model.canvas.scale.huge = Math.round(model.canvas.height/2.8);
		model.canvas.scale.big = Math.round(model.canvas.height/4.5);
		model.canvas.scale.middle = Math.round(model.canvas.height/10);
		model.canvas.scale.small = Math.round(model.canvas.height/30);
		if(model.canvas.scale.small < 11){
			model.canvas.scale.small = 11;
		}
		console.log("resize: PH:"+poem.currentHeight+" s="+model.canvas.scale.small+" m="+model.canvas.scale.middle+" b="+model.canvas.scale.big+" h="+model.canvas.scale.huge);
	}
		
//------------------------------------
//--> =iterator
	var	Iterator = function(){
						this.objects = [],
						this.index = 0,
						this.length = 0;
					};
	Iterator.prototype = {
					running : true,
					add : 	function(object){
								this.objects.push(object);
								console.log("added object: "+this.objects[this.length]+" to "+this.name);
								this.length++;
							},
					remove : function(object){
								for (var i=0; i < this.length; i++){
									if (this.objects[i] === object){
										this.objects.splice(i, 1);
										break;
									}
								}
							},
					count :	function() {
								return this.length;
							},
					rewind : function() {
								this.index = 0;
							},
					hasNext:function() {
								return this.index < this.length;
							},
					next :	function() {
								var object;
								if(!this.hasNext()){
									this.running = false;
									return null;
								}
								object = this.objects[this.index];
								this.index++;
								return object;
							},
					current:function(){
								return this.objects[this.index];
							},
					each :	function (callback) {
								for (var i=0,max=this.count() ; i<max ; i++) {
									callback(this.objects[i]);
								}
							}
		};
//------------------------------------
//--> active objects iterator
	var	activeObjects = new Iterator();
	
//------------------------------------
//--> poem iterator
	var	poem = new Iterator();
	poem.add = 	function(stanza_input){
						stanza_input.length = this.length;
						this.objects.push(new Verse(stanza_input));
						console.log("added to poem: "+this.objects[this.length].verse);
						this.length++;
	};
	poem.previous  = function() {
							var object;
							this.index = this.index - 2;
							object = this.objects[this.index];
							
							return object;
						},
	poem.animate = function() {};
	poem.running = true;
	poem.currentHeight = 0; // used to position verses
	poem.mode = {
					TIMED : function() {
							poem.animate = function(){
								// next at 2 / 3 life 
								if(poem.running && poem.current().lifespan / 6 * 5 >= poem.current().lifeLeft){
									poem.next();
									poem.current().beginAnimation();
								};
							};
						},
					MOUSED : function() {
								poem.animate = function(){
									// next after 50 mouse moves 
									if(poem.running && model.mouse.ticks > 25){
										model.mouse.ticks = 0;
										poem.next();
										poem.current().beginAnimation();
									};
								};
							}
	};
						
		
//------------------------------------
// =Verse Constructor		
		var Verse = function(input) {
			this.size = (input.style) ? input.style : 'small';
			this.verse = (input.verse) ? input.verse : "";
			this.length = (input.verse.length) ? input.verse.length : 0;
			this.verseNumber = (input.length) ? input.length : 0;
			this.event = (input.event) ? input.event : NaN;
			this.lifespan = (input.lifespan) ? input.lifespan : 50;
			this.lifeLeft = (input.lifespan) ? input.lifespan : 50;
		};
		Verse.prototype = {
			onScreen:false,
			index:0,
			yPosition:0,
			beginAnimation:function(){
				// animate poemEvent given in arguments
				if(this.event){
					if(events[this.event]){
						events[this.event](this); // arguments (this) doens't work
					} else {
						console.log(this.event + " does not exist");
					}
				}
				// cut up verse into words and animate
				this.words = this.verse.split(/[ -]/);
				this.display = this.words[0];
				this.onScreen = true;
				// create position for each line
				poem.currentHeight = poem.currentHeight + model.canvas.scale[this.size];
				this.yPosition = poem.currentHeight;
//				console.log("animating: "+this.verse+" @"+model.timer+" | currentHeight: "+poem.currentHeight);
				// add animation to triggered event "animate" 
				$(window).bind('animate',this,function(event){
					if(event.data.lifeLeft > 0){
						event.data.lifeLeft --;
						event.data.display = addWords(event.data);
					}else{
						$(window).unbind('animate',event.data);
						event.data.onScreen = false;
					}
				});
				// function to animate words within animation 
				function addWords(verse){
					var max=verse.words.length-1;
					if(verse.index<max){
						verse.index++
//						console.log("added word: "+verse.words[j]+" J = "+verse.words.length);
						return verse.display.concat(" "+verse.words[verse.index]);
					} else {
						return verse.display;
					}
				}
			}
		};		
				
//------------------------------------
// events API
		var events = {
			pause : function(args){
				this.time = (args.time) ? args.time : 2000;
				poem.running = false; 
				console.log("poem stopped");
				setTimeout (function(){
					poem.running = true; 
					console.log("poem restarted");
				}, this.time);
			},
			poem_mode_moused : function() {
				model.mouse.ticks = 0;
				poem.mode.MOUSED();
			},
			world_dark : function () {
				model.mouse.mode = false;
				$('body').fadeIn( 'fast', function(){
					$(this).css('background-color','#000000');
				});
			},
			start_music : function() {
				console.log('playing music');
				soundManager.play('music');
			},
			moveCursor: function(verse) {
				console.log('moveCursor: '+ this.verse);
				verse.verse = 'Move your cursor '+model.mouse.y.length+' times.';
				return verse;
			},
			addDate: function(verse) {
				console.log('addDate: '+ this.verse);
				verse.verse = "Look around, It's "+new Date();
				return verse;
			},
			endLife: function() {
				window.location='http://www.google.com';
			}
		}
		 
//------------------------------------
// =view:
		drawScreen = function (){
			var i, j=0,max;
			ctx.clearRect(0,0,model.canvas.width,model.canvas.height);
			
			for(i=0,max=activeObjects.count();i<max;i++){
				activeObjects.objects[i]();
			}

			// --> draw out mouse history
			if(model.mouse.mode){
				for(i=0,max=model.mouse.x.length;i<max;i++){
					ctx.beginPath();
					ctx.lineWidth = 3;
					ctx.lineCap = "square";	
					ctx.strokeStyle=model.mouse.color[i];
					ctx.moveTo(model.mouse.x[i],model.mouse.y[i]-1);
					ctx.lineTo(model.mouse.x[i]+1,model.mouse.y[i]-5);
					ctx.stroke();
				}
			} else {
				ctx.fillStyle = "rgba(0, 0, 0, 1)";
				ctx.fillRect(0,0,model.canvas.width,model.canvas.height);
			}
						
			// --> draw out poetry
			poem.animate();
			poem.each(function(verse){
				if(verse.onScreen){
						// figure out verse size
					switch(verse.size){
						case 'huge':
							ctx.font  = "bold "+model.canvas.scale.huge+"px sans-serif";
							break;
						case 'big':
							ctx.font  = "normal "+model.canvas.scale.big+"px sans-serif";
							break;
						case 'middle':
							ctx.font  = "bold "+model.canvas.scale.middle+"px sans-serif";
							break;
						case 'small':
							ctx.font  = "normal "+model.canvas.scale.small+"px sans-serif";
							break;
						default:
						  	ctx.font  = "normal "+model.canvas.scale.middle+"px sans-serif";
					}
						// then position it			
					if(poem.index>14){
						// position poem verse over the last
						var poem_y = (model.canvas.height * 3 / 4) + (verse.yPosition - poem.currentHeight) + 4;
					} else {
						var poem_y = (model.canvas.height * 1 / 4) + verse.yPosition  + 4;					
					}
						// add additional styles and display
					var opacity = verse.lifeLeft/verse.lifespan;
					ctx.fillStyle = 'rgba(170,10,0,'+opacity+')';
					ctx.fillText(verse.display, 20,poem_y);
//					ctx.strokeStyle = 'rgba(190,30,0,.9)';
//					ctx.strokeText(verse.display, 20,poem_y);
				}
			});
			
			
			$('#status').html(model.mouse.x[model.mouse.x.length-1] +', '+ model.mouse.y[model.mouse.y.length-1]);
			$('#draw_count').html(model.mouse.y.length);
			$('#timer').html(model.timer);
		};

//------------------------------------
// controllers:		

		function updateModel(){
			model.timer ++; // equals 1/10 second
			
			if(model.timer % 10 === 0){
				
			}

			// change mouse colors
			if(Math.ceil((model.timer / 200)) % 2 === 0){
				model.canvas.red --;
			} else {
				model.canvas.red ++;
			}
			if((model.timer / 250 % 4) <= 1){
				model.canvas.green --;
			} else if((model.timer / 250 % 4) >= 3){
				model.canvas.green ++;
			}
		};
				// record every mousemove	 
		$(document).mousemove(function(e) {
			model.mouse.x.push(e.pageX);
			model.mouse.y.push(e.pageY);
			model.mouse.color.push('rgba('+model.canvas.red+','+model.canvas.green+','+model.canvas.blue+',0.5)');
			model.mouse.ticks++;
		});
				// on window resize recreate canvas		
		$(window).resize(buildCanvas);
				// mute / unumte music via SoundManager		
		$('#btn_mute').click(function(){
				 soundManager.toggleMute('music');
				 if($('#btn_mute').html()==="mute music"){
				 	$('#btn_mute').html('un-mute');
					$('#btn_mute').addClass('btn_engaged');
				 } else {
					$('#btn_mute').html('mute music');
					$('#btn_mute').removeClass('btn_engaged');
				 }
			
		});
		
		$(window).keydown(function(event){
			switch(event.keyCode) { 
				 case 38:				 // User pressed "up" arrow
		
				 	break;
				 case 40:				 // User pressed "down" arrow	
					var args ={time : 10000};
					events.pause(args);
//					console.log(poem.current());		 
				 	break;
				 case 37:				 // User pressed "left" arrow
					poem.previous();	 
				 	break;
				case 39:				 // User pressed "right" arrow
					poem.next();		 
				 	break;
			}
		});
//------------------------------------
// intialize:

		var reset = (function (){
						model.realtime = new Date();
						buildCanvas();
						
						$(window).bind("animate",function(){
							drawScreen();
							updateModel();
						});
						setInterval(function(){
							$(window).trigger("animate");
						}, 100);
							// create verses for poem
						$.ajax({
							url: "site/_js/homePoem.js",
							dataType: "json",
							success: function(json){
								var i,j,max = json.structure.homepage.length;
								for(i=0;i<max;i++){
									var stanza = json.structure.homepage[i];
									for(j=0;j<json.stanzas[stanza].length;j++){
										poem.add(json.stanzas[stanza][j]);
									}
								}
								poem.mode.TIMED(); // set poem mode
								poem.objects[0].beginAnimation();
							}
						});
							// include sound manager library
						$.ajax({
							url: "site/_js/soundmanager/script/soundmanager2.js",
							dataType: "script",
							cache: true,
							success: function(){
								soundManager.url = 'site/_js/soundmanager/swf/';
								soundManager.onready(function() {
									soundManager.createSound({
										id:'music',
										url:'music/site_bg_one.mp3',
										autoLoad: true,
										autoPlay: false 
									});
								});
								soundManager.beginDelayedInit(); // ensure start-up in case document.readyState and/or DOMContentLoaded are unavailable
							}
						});

		}());
		
	} //end if(canvas)
	
	
}());
   
});
