var _canvas = null;
$(document).ready(function() {
	/*
	 * Create the canvas object
	 *
	 * - first parameter is the id of the canvas element
	 * - second is the requested frames-per-second (0 for static, -1 for unlimited, > 0 for limited)
	 * - third is the function that is called to draw every frame (called once for static image)
	 
	_canvas = new Canvas('canvas', 0, function() {
		// Clear the canvas
		this.clear();

		// Fill a string at given xy-coordinates
		this.fillText('Hello World! This is html canvas library ' + this.getVersion(), 20, 20);
	});
	
	init();*/
	var app = new App({id:'canvas',framerate:0});
	
});


var App = Class.create({
	init:function(params){
		this.tweets= new Tweets(this.self());
		this.tweets.loadTweets();
		//$('#'+params.id).bind('click', this.onMouseClick);
		if(this.canvas==null){
			this.canvas = new Canvas(params.id, params.framerate);
			this.canvas.onMouseDown = $.proxy(this.onCanvasMouseDown,this);
			this.canvas.onMouseMove = $.proxy(this.onCanvasMouseMove, this);
		}
		//this.setDrawFrameCallback();
	}
	,onCanvasMouseDown:function(x,y,button){
		var hit = false;
		//check if mousedown event x,y within profile pic
		//loop this.tweets.tweetsList
		for(var i=0;i<this.tweets.tweetsList.length;i++){	
				
				var tweet = this.tweets.tweetsList[i];
				if(tweet.isHit(x,y) == true){
					//console.log(tweet.username +':'+ tweet.text);
					$('#tweetMessage').css({'top':y+'px','left':x+'px','display':'block'}).html('<span>'+tweet.username+'<br />'+tweet.text+'</span>');
					hit = true;
					break;
				}
		}
		if(hit == false){
			//console.log(x + ' ' + y);
		}
	}
	,drawPopupOnCanvas:function(title, message){
		this.canvas.strokeStyle("rgba(255,255,255,1)");
		this.canvas.strokeRoundedRect(10, 150, 100, 75, 2);		
		this.canvas.text(title, 15, 155);
		//this.canvas.line(10,150,100,150);
		//this.canvas.stroke();
	}
	,onCanvasMouseMove:function(x,y){
		//console.log(x + ' ' + y);
	}	
	,setCanvas:function(params){
		if(this.canvas==null){
			this.canvas = new Canvas(params.id, params.framerate, $.proxy(this.onDrawFrame,this));
		}
	}
	,setDrawFrameCallback:function(){
		if(this.canvas!=null)	{
			this.canvas.setRenderCallback($.proxy(this.onDrawFrame,this));
		}
	}
	,onDrawFrame:function(){
		
		this.canvas.clear();
		// Fill a string at given xy-coordinates
		//this.fillText('Hello World! This is html canvas library ' + this.getVersion(), 20, 20);		

		if(this.tweetsLoaded===true){
			for(var i = 0; i<this.tweets.tweetsList.length;i++){
				
				var tweet = this.tweets.tweetsList[i];

				this.canvas.loadImage(tweet.profilePic, $.proxy(this.onCanvasImageLoadComplete,this), $.proxy(this.onCanvasImageLoadError,this));	
		
			}
		}
		//this.drawPopupOnCanvas("x","y");
	}
	,onTweetsLoaded:function(){
		this.tweetsLoaded = true;
		// set x,y pos for profile pic
		for(var i=0;i<this.tweets.tweetsList.length;i++){
			this.tweets.tweetsList[i].profilePicPosX=this.destinationX;
			this.tweets.tweetsList[i].profilePicPosY=this.destinationY;
			this.destinationX+=48;
			if(this.destinationX>800){
				this.destinationX = 0;
				this.destinationY += 48;
			}	
		}
		this.destinationX = 0;
		this.destinationY = 0;
		this.onDrawFrame(); // trigger drawing the canvas
	}
	,onTweetsLoadedError:function(){
		//console.log("app->error loading tweets");
		this.canvas.fillText("Error loading tweets", 200,150);
		//this.drawPopupOnCanvas("x","y");
	}	
	,onCanvasImageLoadComplete:function(image){

		this.canvas.drawImage(image, this.destinationX, this.destinationY);

		this.destinationX+=48;
		if(this.destinationX>800){
			this.destinationX = 0;
			this.destinationY += 48;
		}
	}
	,onCanvasImageLoadError:function(){
	}

	,self:function(){
		return this;
	}
	,canvas:null // canvas el to draw on
	,tweets:null // tweet object for loading twits
	,images:new Array() // twitter profile pics
	,destinationX:0 //pos X for profile pic
	,destinationY:0 // pos Y for profile pic
	,tweetsLoaded:false // bool indicating if tweets loaded
});

var Tweets = Class.create({
	init:function(parent){
		this.parent = parent;
	}
	,loadTweets:function(){
		$.ajax({
			url:'http://search.twitter.com/search.json?q=ifeelcool&result_type=recent&rpp=100'
			,method:'get'
			,dataType:'jsonp'
			,crossDomain: true
			,success: $.proxy(this.onLoadTweetsComplete, this)
			,error:$.proxy(this.onLoadTweetsError, this)
		});	
	}
	,onLoadTweetsComplete:function(tweetData){
		var results = tweetData.results;
		for(var i=0;i< results.length;i++){
			//this.tweetsList.push(results[tweets]);
				var tweet = new Tweet();
				tweet.profilePic = results[i].profile_image_url;
				tweet.profilePicTag = "<img src="+results[i].profile_image_url+">";
				tweet.text = results[i].text;
				tweet.username = results[i].from_user;
				this.tweetsList.push(tweet);
				//console.log(tweet);
		}	
		this.doneLoading = true;
		this.parent.onTweetsLoaded();
		
	}
	,onLoadTweetsError:function(){
		this.parent.onTweetsLoadedError();
		
	}
	,toString:function(){
		return this.name + ' ' + this.version;
	}	
	,version:"0.1"
	,name:"Tweets"
	,tweetsList:new Array() // list of loaded tweets
	,parent:null // parent calling tweet class
	,doneLoading:false // bool indicating if loading tweets is done
});

var Tweet =Class.create({
	init:function(){}
	,isHit:function(x,y){
		if(x>this.profilePicPosX && x<this.profilePicPosX+this.width
			&& y>this.profilePicPosY && y<this.profilePicPosY+this.height){
			return true;
		}
		return false;
	}
	,text:""
	,username:""
	,profilePic:""
	,profilePicTag:""
	,profilePicPosX:0
	,profilePicPosY:0
	,width:48
	,height:48
});

/*
var percentage =0;
var interval = 0;
function init(){
	//_canvas.strokeRoundedRect(200,300,200,25,3,"",0);
	//_canvas.fillRoundedRect(200,300,200,25,3,"",0);
	//interval = setInterval(progress, 1000);
	
	//loadTwitterFeed();
	var tweets = new Tweets();

	console.log(tweets.ToString());
}

function progress(){
	percentage +=10;
	_canvas.fillRoundedRect(201,301,percentage,23,3,"",0);
	if(percentage>=200){
		window.clearInterval(interval);
	}
}

function loadTwitterFeed(){
	$.ajax({
		url:'http://search.twitter.com/search.json?q=Twitter%20API&result_type=mixed&count=5'
		,method:'get'
		,dataType:'json'
		,success: onTweetsLoadComplete
	});
}

function onTweetsLoadComplete(data){
	//console.log(data);
	var results = data.results;
	for(var tweets in results){
		var tweet = results[tweets];
		_canvas.loadImage(tweet.profile_image_url, onCanvasImageLoadComplete, onCanvasImageLoadError);
		
	}
}

var destinationX =0;
var destinationY =0;
var imagesLoaded = new Array();
function onCanvasImageLoadComplete(image){
	//this-> ref to canvas
	destinationX+=35;
	this.drawImage(image, destinationX, destinationY);
	imageLoaded.push(image);
}
function onCanvasImageLoadError(){
}*/
