if(typeof tms === 'undefined') var tms = {};

tms.flickr = {};

var global_reference_to_this;
function jsonFlickrFeed(obj){
	global_reference_to_this.onLoad(obj);
}

/*
 * Create a flickr display
 * @param  {Object} contains parameters
 * @constructor
 */
tms.flickr = function(o) {
	
	this._self = this;
	
	//Check for dom
	this._dom = new newsi.HTML.DOM();
	if(!this._dom.isW3C()) return false;
		
	// Data source options
	this._feedURL	= o.feedURL;
	this._data		= null;
	this._self		= this;
		
	// Dataloader options
	this._callback		= o.callback;
	this._callbackName 	= o.callbackName;
	this._dataloader	= null;

	var _self = this;
	this._dataListener 	= {};	
	this._dataListener.parent = this;
	this._dataListener.onOperationError = function(managerError) {
	}
	this._dataListener.onData = function(manager) {	
		if(manager.data.success) {
			_self.success(manager.data.content);
		} else {
			_self.error(manager, {});
		}
	}
	this._dataListener.onComplete = function(manager) {
		this.parent._dataloader.cancelTimer();
		this.parent._dataloader.removeListener(this);
	}
	
	// For display
	this._elementId	= o.elementId;
	this._numImages	= o.numImages || null;
	this._photoSize = o.photoSize || "s";
	this._showLinks = o.showLinks || false;
	this._randomise = o.randomise || false;
	
	this._helpLinkId = o.helpLink || "flickr-help"	
	this._fallbackState = "";
}

/*
 * Call this when DOM is loaded to begin
 * the image loading
 */
tms.flickr.prototype.init = function() {
	var _self = this;
	
	// Get initial state of container for fallback
	this._fallbackState = newsi.gebid(this._elementId).innerHTML;
	
	// Show loading spinner
	this._showLoader();
	
	// Get data from flickr
	this._dataloader = new newsi.JsodLoadManager(
								[{	url: this._feedURL,
									name: this._callback,
									callback: this._callbackName }],5, 10, false, false);
	this._dataloader.addListener(this._dataListener);	
	this._dataloader.init();
}

/*
 * This method is called by the data loader when 
 * it has successfully got the data from flickr
 */
tms.flickr.prototype.success = function(data) {
	this._data = data;

	var photos = this._data.items;
	
	if(this._randomise) photos = this._randomiseArray(photos);
	
	var _photoLimit = this._data.items.length;
	if(this._numImages) _photoLimit = this._numImages;
	
	var imageList = this._createImageList({containerTag: "ol", imageWrapperTag:"li", limit:_photoLimit, photos:photos})	

	this._updateContainer(imageList);
	//this._dom.showHide(this._helpLinkId);
}

/*
 * Called by data loader when error condition occures
 */
tms.flickr.prototype.error = function(data, errorHandler) {
	this._updateContainer(this._fallbackState);
}

tms.flickr.prototype._showLoader = function() {
	var loader = "<span id='flickr_loader'>" + this._imgTag({src:"http://newsimg.bbc.co.uk/nol/shared/spl/hi/in_depth/web_reporter/inside_turkey/img/loading.gif", alt:"Loading photos..."}) + "</span>";
	this._updateContainer(loader);
}

/*
 * Replaces the innerHTML of the container with the parameter
 * passed
 */
tms.flickr.prototype._updateContainer = function(content) {
	this._dom.gebid(this._elementId).innerHTML = content;
}

/*
 * This creates the list of images
 * 
 */
tms.flickr.prototype._createImageList = function(o) {
	
	var container = "";
	container += "<" + o.containerTag + ">";
	
	var lastPhoto = o.limit - 1;
	
	for(var i=0; i < o.limit; i++) {
		var photoSrc = o.photos[i].media.m.replace(/_m\.jpg/g,'_'+this._photoSize+'.jpg');
		var photoName = o.photos[i].title;
		var photoLink = o.photos[i].link;
		
		var tag = "";
		
		if(i == lastPhoto) {
			tag +=  "<" + o.imageWrapperTag + " class=\"last\"" + ">";
		} else {
			tag += "<" + o.imageWrapperTag + ">";
		}
		
		if(this._showLinks) tag += "<a href=\"" + photoLink + "\">";
		tag += this._imgTag({alt:"", title:photoName, src:photoSrc});
		tag += "</" + o.imageWrapperTag + ">";
		if(this._showLinks) tag += "</a>";
		
		container += tag;
	}	
	
	container += "</" + o.containerTag + ">";
	
	return container;
}

/*
 * Creates a single image tag
 */
tms.flickr.prototype._imgTag = function(o) {
	var _tag = "<img ";
	for(attr in o) {
		_tag += " " + attr + "=" + "\"" + o[attr] + "\"" + " ";
 	}
	_tag += " />";
	
	return _tag;
}

/*
 * Return a randomised copy of an array
 */
tms.flickr.prototype._randomiseArray = function(arr) {
	var random = [];
	
	for(var i=0;i<arr.length;i++) {
		random[i] = arr[i];
	}
	
	var shuffler = function(a, b) {
		var num = Math.round(Math.random()*2)-1;
		return num;
	}
	
	random.sort(shuffler);	
	return random;
}