// create a new object for each feed

// console.log("Setting up Feed object");

var Feed = function(source) {

	// import feed data from JSON
	jQuery.extend(true, this, source);
	this.element = $("#"+this.id); // DOM element

	// the image to show for the feed
	this.icon = new Image();
	this.icon.src = this.i;
	this.icon.parent = this;
	// attach data loader and run it (if it exists)
	if (FeedLoader.APIs.hasOwnProperty(this.name)) {
//		console.log('Found '+this.name+' in FeedLoader.APIs');
		this.loader = FeedLoader.APIs[this.name];
		this.loader.parent = this;
		this.loader.getData();
	}
	
	// attach to parent object for easy iteration
	Feed.children.push(this);

	Feed.attemptLoadIn(); // start the interval that attempts load-in

}

// gracefully fade in icon when the time is right
Feed.prototype.show = function() {
//console.log('fading in '+this.name);
	var feedname = this.name;
	this.element.fadeTo(300, 0.4)
		.hover(
			function() {
				$('#link-desc').text(feedname);
				$(this).fadeTo(150, 0.9);
			},
			function() {
				$('#link-desc').text(' ');
				$(this).fadeTo(150, 0.4);
			}
		);
}

// children array holds feed objects for easy iteration
Feed.children = [];

// articles array will hold feed data
Feed.articles = [];

// get feed info from JSON and instantiate Feed objects
Feed.loadFeeds = function(url) {
	jQuery.getJSON(url)
		.success(function(data) {
//			console.log('feedlist JSON loaded, parsing elements');
			Feed.count = data.length; // tell Feed how many children it should have
			// console.log('Feed count is '+Feed.count);
			data.forEach( function(item, key) {
				var newfeed = new Feed(item); // the Feed will attach itself where necessary
			});
		})
		.error(function() {
			// console.log('error loading feedlist');
		}
	);
}

// test if all icon images are loaded before fading them in
Feed.allIconsLoaded = function() {
	if(Feed.children.length != Feed.count) return false;
	var loaded = true;
	Feed.children.forEach( function(item, key) {
		loaded = item.icon.complete && loaded;
		// if (!loaded) {
		// 	console.log(item.icon.parent.name+" not loaded");
		// }
	});
	// if(loaded) {
	//   console.log("all images are loaded");
	// }
	return loaded; 
}

Feed.attemptLoadIn = function() {
	// IE is bad at img.onload, so we have to set an interval to
	//  test for loaded images and then fade them in
	if(Feed.iconLoader === undefined) {
		Feed.iconLoader = setInterval(Feed.showWhenLoaded, 300);
	}
}

// if all objects are loaded, initiate fade-in
Feed.showWhenLoaded = function() {
	if(Feed.allIconsLoaded()) {
		clearInterval(Feed.iconLoader);
		var timeout = 0;
		var step = 200;
		$('#seealso').fadeIn(300);
		Feed.children.forEach( function(child, key) {
			// only load in icons that don't have feed data
			if(!FeedLoader.APIs.hasOwnProperty(child.name)) {
				timeout+=step;
				setTimeout("Feed.children["+key+"].show()", timeout);
			}
		});
	} 
}


