/**
 * @author lewis
 */

if(typeof fltr === 'undefined'){
	var fltr = {};
}

function Fleet(tweet, imagesLoadFn){
	// a combination of a tweet and flickr image urls
	if (tweet === null || typeof tweet === "undefined") {
		throw 'no tweet passed in when trying to get fragment';
	}
	
	if(imagesLoadFn.constructor !== Function){
		throw 'A callback must be specified when creating a new fleet';
	}
	
	function getTweetFrag(){
		return tf;
	}
	
	this.text = tweet.text;
	this.created = tweet.text;
	this.isReply = (tweet.in_reply_to_user_id == null ? false : true);
	this.username = tweet.user.name;
	this.userId = tweet.user.id;
	this.userImg = tweet.user.profile_image_url;
	this.screenName = tweet.user.screen_name;
	
	var tempGetSearchWords = textHlpr.getSearchWords(this.text);
	
	this.searchTerms = tempGetSearchWords.words;
	this.searchMatches = tempGetSearchWords.matches;
	
	this.images = null;
	this.errors = [];
	this.imagesLoaded = imagesLoadFn;

	//populate the images
	if(this.searchTerms.length > 2)
	{
		flcrHlpr.search(this.searchTerms, this.loadImages, this);
	}
	else{
		this.errors.push('we need more than 2 words to do a search')
	}
	
}

Fleet.prototype.loadImages = function(resp){
	//resp is a flickr response
	if(resp.stat != 'ok'){
		this.errors.push('error when fetching images from flickr')
		return;
	}
	
	var imgs = [];
	var src;
	
	$.each(resp.photos.photo, function(i,p){
		 imgs.push(
		 	{
				src 	: ['http://farm',p.farm,'.static.flickr.com/',p.server,'/',p.id,'_',p.secret,'_s.jpg'].join(''),
				url		: ['http://www.flickr.com/photos/',p.owner,'/',p.id].join(''),
				title 	: p.title,	 	
				owner	: p.owner,
				id 		: p.id 	
			}
		 );
	});	
	
	this.images = imgs;
	
	// call the callback
	this.imagesLoaded(this);
}

fltr.getFleets = function(tweets, renderFn){
	
	var fleets = [];
	
	if(renderFn.constructor !== Function){
		throw 'A callback must be specified when creating a getting all fleets';
	}
	
	if(tweets === null || typeof tweets === "undefined"){
		return fleets;
	}
	
	var fleetHolder;
	for(var i = 0; i < tweets.length; i++){
		fleetHolder = new Fleet(tweets[i], renderFn);
		if(!fleetHolder.isReply && fleetHolder.searchTerms.length > 3){
			fleets.push(fleetHolder);
		}
		
	}
	
	return fleets;	
}

