if (typeof(myDeco)=="undefined") myDeco = {};

myDeco.howToArticle = {
	stories : {},
	init : function (){
		var leadStory = $('lead-story');		
			if (leadStory){
				myDeco.howToArticle.currentStory = myDeco.howToArticle.stories[leadStory.firstDescendant().id] = leadStory.firstDescendant();

				set_links = function(links){
					links._each(function(link){
						if(!link.setLeadArticle){
							var link_event = function(e){
								Event.stop(e);
								var fragmentId = link.id.replace(/fragment-/,'');
								var fragmentName = "fragment_" + fragmentId;
								new Ajax.Request("/the-magazine/~fragment/"+ fragmentId, {
								        onSuccess : function(transport){
										if (!myDeco.howToArticle.stories[fragmentName]) {
										        var temp =  $(Builder.node('div'));
										        temp.innerHTML = transport.responseText;
											myDeco.howToArticle.stories[fragmentName] = temp.firstDescendant();
											myDeco.howToArticle.stories[fragmentName].style.display = "none";
											leadStory.appendChild(myDeco.howToArticle.stories[fragmentName]);
											set_links($$('.next-prev-link'));
										}
										new Effect.Fade(myDeco.howToArticle.currentStory, {duration:0.2});
										new Effect.Appear(myDeco.howToArticle.stories[fragmentName], {duration:0.2, queue:'end'});
										myDeco.howToArticle.currentStory = myDeco.howToArticle.stories[fragmentName];
									}
								}
							)	
						}
						link.setLeadArticle = link_event;
						link.observe('click', link.setLeadArticle);
					}
				})
			}

			set_links($$('.loadFragment'));
			set_links($$('.next-prev-link'));
		}
		
		var message = $('send-to-my-friend-message');
		if (message)
			message.update("Found an article you might like on mydeco.\n\n" + document.location.href);
	}
}


addLoadEvent(myDeco.howToArticle.init);
