/*	usemedia.com . joes koppers . 04.2011
	thnx for reading this code */


/*	MRI pattern interference
*/

MRI.prototype.addInterference = function(sequence,settings,rsp)
{
	/*	 init the pattern interference gui
	*/
	
	//first get available patterns
	if (!rsp) 
	{
		var obj = this;
		return $.getJSON(this.srv+'get-patterns.php',function(rsp) { obj.addInterference(sequence,settings,rsp) });
	}
	if (rsp.isError) return this.error(rsp.errorMsg);
	
	//canvas mode?
	//var c = $('#interference > canvas')[settings.canvas? 'show':'hide']();
	
	this.interference = {
		app:this,
		
		refresh:settings.refresh,
		minspeed:settings.minspeed,
		maxspeed:settings.maxspeed,
		canvas:settings.canvas? $('#interference > canvas').get(0):false,
		
		path:rsp.path,
		collection:rsp.patterns,
		patterns:new Object(),
		
		sequence:sequence,
		index:0,
		uid:0,
		
		scrolltop:0,
		scrollacc:.25, 	//acceleration
		scrolldec:.01,	//deceleration
		scroll:1,		//direction

		add:function(index)
		{
			/*	add patterns by given sequence
			*/
			var s = this.sequence[this.index];
			this.index++;
			var obj = this;
			window.setTimeout(function() {
			
				//ipad, single pattern to be used in graphics
				if (obj.app.ipad) return obj.pattern();

				//pattern(s)
				for (var i=0; i<s.amount; i++) obj.pattern();
				
				if (window.location.host=='mri') return obj.pause();
				
				//next entry in sequence
				if (obj.index<obj.sequence.length) obj.add();
				
			},s.t*1000);
		},
		
		pattern:function(uid)
		{
			/*	(remove and) add new pattern
			*/
			if (uid) delete this.patterns[uid];
			this.uid++;
			this.patterns[this.uid] = new Pattern(this);
		},
		
		start:function()
		{
			/*	start sequence and interference
			*/
			if (this.canvas) 
			{
				//initialize canvas
				console.log('[interference], canvasmode')
				this.app.resize();
				if (typeof(G_vmlCanvasManager)=='object') this.canvas = G_vmlCanvasManager.initElement(this.canvas);
				this.canvas = this.canvas.getContext('2d');
			}
			
			this.add(); 
			if (!this.app.ipad) this.update();
			
			//$(window).scrollTop(10);
		},
		
		pause:function(resume)
		{
			/*	pause or resume interference
			*/
			this.paused = resume? false:true;
			console.log('[interference] ',resume? 'resume':'paused');
			if (this.interfering) window.clearTimeout(this.interfering);
			if (resume) this.update();
		},
		
		update:function()
		{
			/*	refresh display (continuously)
			*/
			if (this.canvas) this.canvas.clearRect(0,0,this.app.width,this.app.height);
			
			//monitor scrollspeed
			this.getScroll();
			
			//animate all patterns
			for (var id in this.patterns) this.patterns[id].anim(this.scroll);
			
			//loop
			var obj = this;
			this.interfering = window.setTimeout(function() {
				obj.update();
			},this.refresh);
		},
		
		getScroll:function()
		{
			/*	monitor scroll speed and direction
			*/
			var t = $(window).scrollTop();
			var d = t - this.scrolltop;
			this.scrolltop = t;

			if (d==0)
			{
				//auto normalize
				if (this.scroll>1)
				{
					this.scroll -= this.scrollacc/3;
					if (this.scroll<1) this.scroll = 1;
				}
				else if (this.scroll<1)
				{
					this.scroll += this.scrolldec;
					if (this.scroll>1) this.scroll = 1;
				}
			}
		
			if (d<0)
			{
				this.scroll += this.scrollacc;
				if (this.scroll>6) this.scroll = 6;
			}
			if (d>0)
			{
				this.scroll -= this.scroll>1? this.scrollacc:this.scrolldec;
				if (this.scroll<.25) this.scroll=.25;
			}
		},

		getPattern:function(index)
		{
			/*	return pattern from collections, by index or random
			*/
			if (index==undefined) index = Math.round(Math.random()*(this.collection.length-1));
			var p = this.path+this.collection[index];
			
			console.log('[interference] pattern used=',p);
			
			return p;
		}
	}
	
	this.interference.start();
}


function Pattern(interference)
{
	/*	pattern constructor, 
		add pattern at random side of screen */
	
	var i = this.interference = interference;
	this.uid = interference.uid;
	var app = interference.app;
	
	//settings
	this.ds = 1; //acceleration
	this.s = i.minspeed + (Math.random()*(i.maxspeed-i.minspeed)); //random base speed;

	this.w = 1000; //fixed dimensions, must match HIP gallery
	this.h = 707;
	
	/*	pick start and target positions, target is always in opposite quadrant
	*/
	var m = { x:200, y:100 }; 				//edge margins, the minimum amount of pixels that is shown at start position
	var s = Math.round(Math.random()*3);	//random screen side, 0-3, order is [top,right,bottom,left]
	var c = { 								//center of screen
		x:Math.round(app.width/2), 
		y:Math.round(app.height/2)
	}; 
	
	var x = m.x - this.w + Math.round((Math.random() * (app.width - (2*m.x) + this.w)));
	var y = m.y - this.h + Math.round((Math.random() * (app.height - (2*m.y) + this.h)));

	switch (s)
	{
		case 0: //top
		case 2: //bottom
			this.x = x;
			this.tx = Math.round(Math.random()*c.x);
			if (x<c.x) this.tx += c.x;
			
			this.y = s==0? -this.h:app.height;
			this.ty = s==0? app.height:-this.h;
			
			//speeds
			this.ys = s==0? this.s:-this.s; //vertical speed is leading
			this.xs = ((this.tx-this.x) / Math.abs(this.ty-this.y)) * this.s;
			break;
		
		case 3: //left
		case 1: //right
			this.y = y;
			this.ty = Math.random(Math.round()*c.y);
			if (y<c.y) this.ty += c.y;

			this.x = s==3? -this.w:app.width;
			this.tx = s==3? app.width:-this.w;

			//speeds			
			this.xs = s==3? this.s:-this.s; //horizontal speed is leading
			this.ys = ((this.ty-this.y) / Math.abs(this.tx-this.x)) * this.s;
			break;
	}

	this.create();
}

Pattern.prototype.create = function()
{
	/*	load and append pattern image
	*/
	var obj = this;

	//select random pattern from list
	this.elm = $('<img/>')
		.addClass('pattern loading')
		.css({
			left:this.x,
			top:this.y
		})
		.load(function() {

			/*	 start animating
			*/
			console.log('[pattern',obj.uid,'], loaded');
			
			if (obj.uid==1) obj.interference.app.scroll();
			
			//obj.interference.app.scroll();

			$(this).removeClass('loading')
			
			obj.anim();
		})
		.attr('src',this.interference.getPattern())
		
	if (!this.interference.canvas) this.elm.prependTo('#interference');
}

Pattern.prototype.anim = function(ds)
{
	/*	 move pattern on screen
	*/
	if (ds) this.ds = ds;
	
	if (!this.elm || this.elm.hasClass('loading')) return;
	
	this.y += this.ds * this.ys;
	this.x += this.ds * this.xs;
	
	if (this.interference.canvas) this.interference.canvas.drawImage(this.elm.get(0),this.x,this.y,this.w,this.h);
	else this.elm.css({ left:this.x, top:this.y });

// 	if (!this.onscreen)
// 	{	
// 		//half visible?
// 		this.onscreen = this.s>0? this.y>-(.5*this.h):this.y<wh-(.5*this.h);
// 	}
	
	if (this.x<-this.w || this.x>this.interference.app.width || this.y<-this.h || this.y>this.interference.app.height)
	{
		//self destruct when offscreen
		this.dispose();
	}
}

Pattern.prototype.dispose = function()
{
	/*	remove pattern, which will create a new pattern.
		(patterns have everlasting lifes..) */
	
	console.log('[pattern',this.uid,'], disposed');
	
	this.elm.remove();
	this.interference.pattern(this.uid);
}

Pattern.prototype.changeSpeed = function(s)
{
	this.ds = s;
}

// Pattern.prototype.setSpeed = function(y)
// {
// 	if (!this.onscreen) return; //patterns must be onscreen completely before control is allowed..
// 	
// 	y = y - (wh/2);
// 	if (y>-100 && y<100) y = 0;
// 	
// 	if (y==0) return; //idle
// 	
// 	this.ys = y / (wh/2);
// 		
// 	if (this.ys!=0)
// 	{
// 		var dy = Math.floor(Math.pow(1.7,Math.abs(this.ys)*3));
// 		if (this.ys>0) dy = -dy;
// 	}
// 	
// 	//console.log('dy=',dy);
// 	
// 	if (dy!=0) this.s = dy;
// }


