;(function() {

	if(typeof Storify == 'function') {
		debug('Storify initializer already started',Storify.widget.stories);
		getStories();
		return;
	}

	Storify 		= function() {};
	Storify.widget 	= {stories:[]};
	Storify.ready	= false;

	DEBUG 	= (typeof DEBUG == 'undefined') ? false : DEBUG;
	ENV		= (typeof ENV == 'undefined') ? 'production' : ENV;
	
	STORIFY_BASE_URL = 'http://storify.com';
	
	function debug(msg,obj) {

		if(!DEBUG)
			return false;

		if(!obj)
			obj = '';

		if(window.console)
			console.info(msg,obj);

	}

	function setenv() {
		
		var env,permalink;
		
		jQuery('script[src*="storify.com"]').each(function() {
			if(!env && jQuery(this).attr('src').indexOf('/public/')==-1) {
				permalink = jQuery(this).attr('src');
				permalink = permalink.substr(0, permalink.lastIndexOf('.'));
				
				env = permalink.substr(7,permalink.indexOf('storify.com')-8);
			}
		});
		
		switch(env) {
			case 'dev':
				STORIFY_BASE_URL = 'http://dev.storify.com';
				break;

			case 'localhost':
				STORIFY_BASE_URL = 'http://localhost.storify.com:3000';
				break;

			case "preview":
				STORIFY_BASE_URL = 'http://preview.storify.com';
				break;

			default:
				STORIFY_BASE_URL = 'http://storify.com';
				break;
		}
		
		$ = jQuery; // We use $ and not jQuery in the elementsList.jsfi
				
		debug('hello '+STORIFY_BASE_URL);
		
	}
	
	/******** Load jQuery if not present *********/
	if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
	    var script_tag = document.createElement('script');
	    script_tag.setAttribute("type","text/javascript");
	    script_tag.setAttribute("src",
	        "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
	    script_tag.onload = scriptLoadHandler;
	    script_tag.onreadystatechange = function () { // Same thing but for IE
	        if (this.readyState == 'complete' || this.readyState == 'loaded') {
	            scriptLoadHandler();
	        }
	    };
	    // Try to find the head, otherwise default to the documentElement
	    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
	} else {
	    // The jQuery version on the window is the one we want to use
	    jQuery = window.jQuery;
	    main();
	}

	/******** Called once jQuery has loaded ******/
	function scriptLoadHandler() {
	    // Restore $ and window.jQuery to their previous values and store the
	    // new jQuery in our local jQuery variable
	    $=jQuery = window.jQuery.noConflict(true);
	    // Call our main function
	    main(); 
	}

	function require(jsfile,callback) {
		var script_tag = document.createElement('script');
		script_tag.setAttribute("type","text/javascript");
		script_tag.setAttribute("src", jsfile);
		if(typeof callback == 'function') {
			script_tag.onload = callback;
			script_tag.onreadystatechange = function () { // IE
			if (this.readyState == 'complete' || this.readyState == 'loaded') {
				callback();
				}
			};
		}
		(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
	};

	/******** Our main function ********/
	function main() { 

		setenv();

	    jQuery('head').append('<link rel="stylesheet" href="'+STORIFY_BASE_URL+'/public/css/widget.css'+'" type="text/css" />');
	    jQuery('head').append('<link rel="stylesheet" href="'+STORIFY_BASE_URL+'/public/css/jquery.fancybox-1.3.0.css'+'" type="text/css" />');
	    jQuery('head').append('<link rel="stylesheet" href="'+STORIFY_BASE_URL+'/public/css/elementsList.css'+'" type="text/css" />');
		require(STORIFY_BASE_URL+'/public/js/ElementsList.js');
		require(STORIFY_BASE_URL+'/public/js/lib/jquery.easing-1.3.pack.js');
		require(STORIFY_BASE_URL+'/public/js/lib/jquery.fancybox.js',function() {
			require(STORIFY_BASE_URL+'/public/js/utils.js', function() {
				Storify.ready = true;
				getStories();
			});
		});			
	}
	
	function getStories() {
		if(!Storify.ready)
			return;
		
		var permalink;
		
		jQuery('script[src*="storify.com"]').each(function() {
			if(jQuery(this).attr('src').indexOf('/public/')==-1) {
				permalink = jQuery(this).attr('src');
				permalink = permalink.substr(0, permalink.lastIndexOf('.'));
				
				widgetid  = permalink.substr(permalink.lastIndexOf('/')+1);
				if(typeof Storify.widget.stories[widgetid]=='undefined') {
					debug('creating story '+widgetid,Storify.widget.stories);
					Storify.widget.stories[widgetid] = new Storify.Story(permalink);
				}
			}
			});
			
	}
	
	Storify.Story = function(permalink) {
		
		this.permalink 	= permalink;
		
		this.widgetid 	= permalink.substr(permalink.lastIndexOf('/')+1);
		
		var self = this,
		 	story = {},
			elements,
			html = '<div id="'+this.widgetid+'">\n\
					<div id="sfywdgt_StorifyWidget" class="unitialized"> \n\
						<div id="sfywdgt_error"></div> \n\
						<div id="sfywdgt_header"> \n\
							<div class="sfywdgt_tools"> \n\
								<div class="sfywdgt_share sfywdgt_tool"> \n\
									<ul> \n\
										<li> \n\
											<a class="sfywdgt_twitter " target="new" rel="external" href="./">Twitter</a> \n\
										</li> \n\
										 \n\
										<li> \n\
											<a class="sfywdgt_email comingsoon" href="./">Email</a> \n\
										</li> \n\
										<li> \n\
											<a class="sfywdgt_embed iframe" href="/">Embed</a> \n\
										</li> \n\
									</ul> \n\
								</div> \n\
								';
								/*
								<div class="sfywdgt_share sfywdgt_tool"> \n\
									<p> \n\
										Share \n\
									</p> \n\
									<ul> \n\
										<li class="facebook_like"> \n\
										</li> \n\
									</ul> \n\
								</div> \n\
								';
			
			html += '\n\
								<div class="sfywdgt_embed sfywdgt_tool"> \n\
									<p> \n\
										Embed \n\
									</p> \n\
									<ul> \n\
										<li> \n\
											<a class="sfywdgt_twitter" href="./">Twitter</a> \n\
										</li> \n\
										 \n\
										<li> \n\
											<a class="sfywdgt_facebook" href="./">Facebook</a> \n\
										</li> \n\
										 \n\
										<li> \n\
											<a class="sfywdgt_email" href="./">Email</a> \n\
										</li> \n\
									</ul> \n\
								</div> \n\
								';
			*/
			html += ' \n\
							</div>\n\
								<div class="sfywdgt_image"> \n\
									<div class="sfywdgt_imgFrame"> \n\
										<img src="'+STORIFY_BASE_URL+'/public/img/dot-a.gif" alt="Dot A"> \n\
									</div> \n\
								</div> \n\
								<div class="sfywdgt_storyinfo"> \n\
									<h3 id="sfywdgt_title"> \n\
									</h3> \n\
									<div id="sfywdgt_author">by \n\
										<a href="./"></a> \n\
									</div> \n\
										 \n\
									<div id="sfywdgt_description"></div> \n\
								 </div>\n\
							</div> \n\
 						 \n\
						<div id="sfywdgt_body"> \n\
							<ul class="sfywdgt_scroll-a" id="elementsList"></ul> \n\
						</div> \n\
					</div> \n\
				</div>';
		
		this.widgetNode = jQuery(html);
		jQuery('script[src^="'+self.permalink+'"]').after(this.widgetNode);

		this.init = function() {
			this.getStory();
		};
		
		this.setBehaviour = function() {
			
			this.widgetNode.find('.sfywdgt_tools a.comingsoon').click(function(e) {
				e.preventDefault();
				alert('Coming soon');
				return false;
			})
			
			this.widgetNode.find('a.quickview').each(function() {

				if(!jQuery(this).hasClass('quickview')) 
					return false;
					
				jQuery(this).removeClass('quickview');
				jQuery(this).attr('rel','external');

				var u 					= jQuery(this).attr('href'),
					quickview_handle 	= ' <a href="'+u+'" class="quickview_handle iframe"> [quick view]</a>',
					quickview_node 		= jQuery(quickview_handle);

				quickview_node.fancybox({
					'transitionIn'	: 'elastic',
					'transitionOut'	: 'elastic',
					'title'			: '',
					'titlePosition'	: 'inside',	
					'width'			: 900,
					'height'		: 600
				});

				jQuery(this).after(quickview_node);
			});

			this.widgetNode.find('a.fancybox.youtube').hover(function() {
				debug('mouseover fancybox youtube');
				var u 		= jQuery(this).attr('href'),
					title 	= jQuery(this).attr('title');

				jQuery(this).removeClass('fancybox');
				jQuery(this).attr('rel','external');

				jQuery(this).fancybox({
					'padding'		: 0,
					'autoScale'		: false,
					'transitionIn'	: 'none',
					'transitionOut'	: 'none',
					'title'			: title,
					'width'			: 680,
					'height'		: 495,
					'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
					'type'			: 'swf',
					'swf'			: {
					   	'wmode'				: 'transparent',
						'allowfullscreen'	: 'true'
					}
				});

			});
			
			this.widgetNode.find('a.sfywdgt_embed').fancybox({
		      	'transitionIn'		: 'elastic',
		  		'transitionOut'		: 'elastic',
		  		'title'		    	: '',
		  		'titlePosition'		: 'inside',	
		  		'width'		     	: 520,
		  		'height'	    	: 800
		    });
		
			/*
			this.widgetNode.find('a.sfywdgt_facebook').click(function(e) {
				e.preventDefault();
				t=(screen.height/2)-436;
				l=(screen.width/2)-626;
				
				url = 'http://facebook.com/sharer.php?u='+encodeURIComponent(permalink)+'&t='+encodeURIComponent(story.title);
			
				window.open(url,'sharer','toolbar=0,status=0,width=626,height=436,top='+t+',left='+l);
				//instance.FBShare('Check this out!',{'name':'Test','href':url,'description':'This is the msg','media':[{'type':'image','src':'image.jpg','href':url}]},[{'text':'View the stream','href':PUBLITWEET_BASE_URL+instance.feed}]);
				return false;
			});
		    */
		}
		
		this.error = function(msg) {
			debug(msg);
			this.widgetNode.find('#sfywdgt_header').hide();
			this.widgetNode.find('#sfywdgt_body').hide();
			this.widgetNode.find('#sfywdgt_error').html(msg);
		}
		
		this.getStory = function() {
			var permalink = this.permalink;
	    	if(typeof permalink=='undefined') {
	    		this.error('undefined story permalink - please contact support@storify.com');
	    		return false;
	    	}

	    	jQuery.getJSON(permalink+'.json?callback=?',function(json) {
	    		story = json;
	    		self.setStoryHeaders();
	    	}) 
	    }
		
		this.setStoryHeaders = function () {
			
			this.widgetNode.find('#sfywdgt_StorifyWidget #sfywdgt_title').html(story.title);
			this.widgetNode.find('#sfywdgt_StorifyWidget #sfywdgt_description').html(story.description);
			
			var date = Storify.utils.displayDate(story.updated_at);
			
			this.widgetNode.find('#sfywdgt_StorifyWidget #sfywdgt_author').html('by <a href="'+STORIFY_BASE_URL+'/'+story.user.username+'">'+story.user.twitterprofile.name+'</a>, '+date);
			this.widgetNode.find('#sfywdgt_author').after('<div class="sfywdgt_facebook_like"><iframe src="http://www.facebook.com/plugins/like.php?href='+encodeURIComponent(permalink)+'&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:400px; height:80px;" allowTransparency="true"></iframe></div>');
			
			
			if(!story.image_url) {
				this.widgetNode.find('#sfywdgt_StorifyWidget div.sfywdgt_image').hide();
			}
			else {
				this.widgetNode.find('#sfywdgt_StorifyWidget div.sfywdgt_image img').attr('src',story.image_url);
			}
			
			this.widgetNode.find('a.sfywdgt_embed').attr('href',permalink+'/embed');
			
			var tweet_maxlength = 140-20-story.user.username.length-6;
			var intro = "New curated story: ";
			var tweet = story.title.substr(0,tweet_maxlength);
			if(tweet.length < (tweet_maxlength-intro.length))
				tweet = intro + tweet;
				
			this.widgetNode.find('a.sfywdgt_twitter').click(function(e) {
				e.preventDefault();
				t=(screen.height/2)-450;
				l=(screen.width/2)-550;
				windowurl = 'http://twitter.com/share?related='+story.user.username+'&via='+story.user.username+'&url='+encodeURIComponent(permalink)+'&text='+encodeURIComponent(tweet);
				window.open(windowurl,'sharer','toolbar=0,status=0,width=550,height=450,top='+t+',left='+l);
				return false;
			});
/*
			this.widgetNode.find('a.sfywdgt_twitter').click(function() {
				awesm_share('twitter',permalink, story.title, tweet);
				return false;
			});
*/			
			elements = new ElementsList('#'+this.widgetid+' #elementsList');
			var storyElement;
			var pos=0;
			elements.importElements(story.elements);
			
			
			this.setBehaviour();
			/*
			for(e in story.elements) {
				debug('adding',story.elements[e]);
				switch(story.elements[e].type) {
					case "video":
						storyElement = new VideoElement({data:story.elements[e]});
						break;
					
					case "text":
						storyElement = new TextElement({data:story.elements[e]});
						break;
				}
				elements.add(storyElement,pos++);
			}
			*/
		}

		this.init();
				
	}		
})();
