/* 	TIMELINE SOURCE DATA PROCESSOR
================================================== */

if(typeof VMM.Timeline != 'undefined' && typeof VMM.Timeline.DataObj == 'undefined') {
	
	VMM.Timeline.DataObj = {
		
		data_obj: {},
		
		model_array: [],
		
		getData: function(raw_data) {
			VMM.Timeline.DataObj.data_obj = {};
			data = VMM.Timeline.DataObj.data_obj;
			VMM.fireEvent(global, VMM.Timeline.Config.events.messege, VMM.Timeline.Config.language.messages.loading_timeline);
			
			if (type.of(raw_data) == "object") {
				trace("DATA SOURCE: JSON OBJECT");
				VMM.Timeline.DataObj.parseJSON(raw_data);
			} else if (type.of(raw_data) == "string") {
				if (raw_data.match("%23")) {
					trace("DATA SOURCE: TWITTER SEARCH");
					VMM.Timeline.DataObj.model.tweets.getData("%23medill");
				} else if (	raw_data.match("spreadsheet") ) {
					trace("DATA SOURCE: GOOGLE SPREADSHEET");
					VMM.Timeline.DataObj.model.googlespreadsheet.getData(raw_data);
				} else if (raw_data.match("storify.com")) {
					trace("DATA SOURCE: STORIFY");
					VMM.Timeline.DataObj.model.storify.getData(raw_data);
					//http://api.storify.com/v1/stories/number10gov/g8-and-nato-chicago-summit
				} else {
					trace("DATA SOURCE: JSON");
					VMM.getJSON(raw_data, VMM.Timeline.DataObj.parseJSON);
				}
			} else if (type.of(raw_data) == "html") {
				trace("DATA SOURCE: HTML");
				VMM.Timeline.DataObj.parseHTML(raw_data);
			} else {
				trace("DATA SOURCE: UNKNOWN");
			}
			
		},
		
		parseHTML: function(d) {
			trace("parseHTML");
			trace("WARNING: THIS IS STILL ALPHA AND WILL NOT WORK WITH ID's other than #timeline");
			var _data_obj = VMM.Timeline.DataObj.data_template_obj;
			
			/*	Timeline start slide
			================================================== */
			if (VMM.Lib.find("#timeline section", "time")[0]) {
				_data_obj.timeline.startDate = VMM.Lib.html(VMM.Lib.find("#timeline section", "time")[0]);
				_data_obj.timeline.headline = VMM.Lib.html(VMM.Lib.find("#timeline section", "h2"));
				_data_obj.timeline.text = VMM.Lib.html(VMM.Lib.find("#timeline section", "article"));
				
				var found_main_media = false;
				
				if (VMM.Lib.find("#timeline section", "figure img").length != 0) {
					found_main_media = true;
					_data_obj.timeline.asset.media = VMM.Lib.attr(VMM.Lib.find("#timeline section", "figure img"), "src");
				} else if (VMM.Lib.find("#timeline section", "figure a").length != 0) {
					found_main_media = true;
					_data_obj.timeline.asset.media = VMM.Lib.attr(VMM.Lib.find("#timeline section", "figure a"), "href");
				} else {
					//trace("NOT FOUND");
				}

				if (found_main_media) {
					if (VMM.Lib.find("#timeline section", "cite").length != 0) {
						_data_obj.timeline.asset.credit = VMM.Lib.html(VMM.Lib.find("#timeline section", "cite"));
					}
					if (VMM.Lib.find(this, "figcaption").length != 0) {
						_data_obj.timeline.asset.caption = VMM.Lib.html(VMM.Lib.find("#timeline section", "figcaption"));
					}
				}
			}
			
			/*	Timeline Date Slides
			================================================== */
			VMM.Lib.each("#timeline li", function(i, elem){
				
				var valid_date = false;
				
				var _date = {
					"type":"default",
					"startDate":"",
		            "headline":"",
		            "text":"",
		            "asset":
		            {
		                "media":"",
		                "credit":"",
		                "caption":""
		            },
		            "tags":"Optional"
				};
				
				if (VMM.Lib.find(this, "time") != 0) {
					
					valid_date = true;
					
					_date.startDate = VMM.Lib.html(VMM.Lib.find(this, "time")[0]);

					if (VMM.Lib.find(this, "time")[1]) {
						_date.endDate = VMM.Lib.html(VMM.Lib.find(this, "time")[1]);
					}

					_date.headline = VMM.Lib.html(VMM.Lib.find(this, "h3"));

					_date.text = VMM.Lib.html(VMM.Lib.find(this, "article"));

					var found_media = false;
					if (VMM.Lib.find(this, "figure img").length != 0) {
						found_media = true;
						_date.asset.media = VMM.Lib.attr(VMM.Lib.find(this, "figure img"), "src");
					} else if (VMM.Lib.find(this, "figure a").length != 0) {
						found_media = true;
						_date.asset.media = VMM.Lib.attr(VMM.Lib.find(this, "figure a"), "href");
					} else {
						//trace("NOT FOUND");
					}

					if (found_media) {
						if (VMM.Lib.find(this, "cite").length != 0) {
							_date.asset.credit = VMM.Lib.html(VMM.Lib.find(this, "cite"));
						}
						if (VMM.Lib.find(this, "figcaption").length != 0) {
							_date.asset.caption = VMM.Lib.html(VMM.Lib.find(this, "figcaption"));
						}
					}
					
					trace(_date);
					_data_obj.timeline.date.push(_date);
					
				}
				
			});
			
			VMM.fireEvent(global, VMM.Timeline.Config.events.data_ready, _data_obj);
			
		},
		
		parseJSON: function(d) {
			if (d.timeline.type == "default") {
				trace("DATA SOURCE: JSON STANDARD TIMELINE");
				VMM.fireEvent(global, VMM.Timeline.Config.events.data_ready, d);
			} else if (d.timeline.type == "twitter") {
				trace("DATA SOURCE: JSON TWEETS");
				VMM.Timeline.DataObj.model_Tweets.buildData(d);
				
			} else {
				trace("DATA SOURCE: UNKNOWN JSON");
				trace(type.of(d.timeline));
			};
		},
		
		/*	MODEL OBJECTS 
			New Types of Data can be formatted for the timeline here
		================================================== */
		
		model: {
			
			googlespreadsheet: {
				
				getData: function(raw) {
					var _key = VMM.Util.getUrlVars(raw)["key"];
					var _url = "https://spreadsheets.google.com/feeds/list/" + _key + "/od6/public/values?alt=json";
					VMM.getJSON(_url, VMM.Timeline.DataObj.model.googlespreadsheet.buildData);
				},
				
				buildData: function(d) {
					VMM.fireEvent(global, VMM.Timeline.Config.events.messege, "Parsing Data");
					var _data_obj = VMM.Timeline.DataObj.data_template_obj;

					for(var i = 0; i < d.feed.entry.length; i++) {
						var dd = d.feed.entry[i];
					
						if (dd.gsx$titleslide.$t.match("start")) {
							_data_obj.timeline.startDate = 			dd.gsx$startdate.$t;
							_data_obj.timeline.headline = 			dd.gsx$headline.$t;
							_data_obj.timeline.asset.media = 		dd.gsx$media.$t;
							_data_obj.timeline.asset.caption = 		dd.gsx$mediacaption.$t;
							_data_obj.timeline.asset.credit = 		dd.gsx$mediacredit.$t;
							_data_obj.timeline.text = 				dd.gsx$text.$t;
							_data_obj.timeline.type = 				"google spreadsheet";
						} else {
							var _date = {
								"type": 							"google spreadsheet",
								"startDate": 						dd.gsx$startdate.$t,
								"endDate": 							dd.gsx$enddate.$t,
					            "headline": 						dd.gsx$headline.$t,
					            "text": 							dd.gsx$text.$t,
					            "asset": {
									"media": 						dd.gsx$media.$t, 
									"credit": 						dd.gsx$mediacredit.$t, 
									"caption": 						dd.gsx$mediacaption.$t 
								},
					            "tags": 							"Optional"
							};
							if (typeof dd.gsx$tag != 'undefined') {
								_date.tag = dd.gsx$tag.$t;
							}
							_data_obj.timeline.date.push(_date);
						}
					};
				
					VMM.fireEvent(global, VMM.Timeline.Config.events.data_ready, _data_obj);
				}
				
			},
			
			storify: {
				
				getData: function(raw) {
					//http://storify.com/number10gov/g8-and-nato-chicago-summit
					//http://api.storify.com/v1/stories/number10gov/g8-and-nato-chicago-summit
					
					VMM.fireEvent(global, VMM.Timeline.Config.events.messege, "Loading Storify...");
					var _key = raw.split("storify.com\/")[1];
					var _url = "http://api.storify.com/v1/stories/" + _key + "?per_page=300&callback=?";
					
					var storify_timeout = setTimeout(function() {
						trace("STORIFY timeout");
						VMM.fireEvent(global, VMM.Timeline.Config.events.messege, "Storify is not responding");
					}, 6000);
					
					VMM.getJSON(_url, VMM.Timeline.DataObj.model.storify.buildData)
						.error(function(jqXHR, textStatus, errorThrown) {
							trace("STORIFY error");
							trace("STORIFY ERROR: " + textStatus + " " + jqXHR.responseText);
						})
						.success(function(d) {
							clearTimeout(storify_timeout);
						});
					
				},
				
				buildData: function(d) {
					VMM.fireEvent(global, VMM.Timeline.Config.events.messege, "Parsing Data");
					var _data_obj = VMM.Timeline.DataObj.data_template_obj;
					
					_data_obj.timeline.startDate	= 	new Date(d.content.date.created);;
					_data_obj.timeline.headline		= 	d.content.title;
					
					
					//d.permalink
					var tt			=	"";
					if (typeof d.content.description != 'undefined' && d.content.description != null) {
						tt			+=	d.content.description;
					}
					tt				+=	"<div class='storify'><div class='vcard author'><a class='screen-name url' href='" + d.content.author.permalink + "' target='_blank'>";
					tt				+=	"<span class='avatar'><img src='" + d.content.author.avatar + "' style='max-width: 32px; max-height: 32px;'></span>"
					tt				+=	"<span class='fn'>" + d.content.author.username + "</span>";
					tt				+=	"<span class='nickname'><div class='thumb-storify-full'></div></span>";
					tt				+=	"</a>";
					//tt				+=	"<span class='nickname'>" + d.content.author.stats.stories + " Stories</span>";
					//tt				+=	"<span class='nickname'>" + d.content.author.stats.subscribers + " Subscribers</span>";
					tt				+=	"</div></div>";
					
					_data_obj.timeline.text = tt;
					_data_obj.timeline.asset.media = d.content.thumbnail;
					
					//_data_obj.timeline.asset.media = 		dd.gsx$media.$t;
					//_data_obj.timeline.asset.caption = 		dd.gsx$mediacaption.$t;
					//_data_obj.timeline.asset.credit = 		dd.gsx$mediacredit.$t;
					_data_obj.timeline.type = 				"storify";
					
					for(var i = 0; i < d.content.elements.length; i++) {
						var dd = d.content.elements[i];
						var is_text = false;
						var d_date = new Date(dd.posted_at);
						//trace(tempdat);
						trace(dd.type);
						//trace(dd);
						var _date = {
							"type": 		"storify",
							"startDate": 	dd.posted_at,
							"endDate": 		dd.posted_at,
				            "headline": 	" ",
							"slug": 		"", 
				            "text": 		"",
				            "asset": {
								"media": 	"", 
								"credit": 	"", 
								"caption": 	"" 
							}
						};
						
						/*	MEDIA
						================================================== */
						if (dd.type == "image") {
							
							if (typeof dd.source.name != 'undefined') {
								if (dd.source.name == "flickr") {
									_date.asset.media		=	"http://flickr.com/photos/" + dd.meta.pathalias + "/" + dd.meta.id + "/";
									_date.asset.credit		=	"<a href='" + _date.asset.media + "'>" + dd.attribution.name + "</a>";
									_date.asset.credit		+=	" on <a href='" + dd.source.href + "'>" + dd.source.name + "</a>";
								} else if (dd.source.name	==	"instagram") {
									_date.asset.media		=	dd.permalink;
									_date.asset.credit		=	"<a href='" + dd.permalink + "'>" + dd.attribution.name + "</a>";
									_date.asset.credit		+=	" on <a href='" + dd.source.href + "'>" + dd.source.name + "</a>";
								} else {
									_date.asset.credit		=	"<a href='" + dd.permalink + "'>" + dd.attribution.name + "</a>";
									
									if (typeof dd.source.href != 'undefined') {
										_date.asset.credit	+=	" on <a href='" + dd.source.href + "'>" + dd.source.name + "</a>";
									}
									
									_date.asset.media		=	dd.data.image.src;
								}
							} else {
								_date.asset.credit			=	"<a href='" + dd.permalink + "'>" + dd.attribution.name + "</a>";
								_date.asset.media			=	dd.data.image.src;
							}
							
							_date.slug	 					=	dd.attribution.name;
							if (typeof dd.data.image.caption != 'undefined') {
								if (dd.data.image.caption != 'undefined') {
									_date.asset.caption				=	dd.data.image.caption;
									_date.slug	 					=	dd.data.image.caption;
								}
							}
							
						} else if (dd.type == "quote") {
							if (dd.permalink.match("twitter")) {
								_date.asset.media	=	dd.permalink; 
								_date.slug = VMM.Util.untagify(dd.data.quote.text);
							} else if (dd.permalink.match("storify")) {
								is_text = true;
								_date.asset.media	=	"<blockquote>" + dd.data.quote.text.replace(/<\s*\/?\s*b\s*.*?>/g,"") + "</blockquote>";
							}
						} else if (dd.type == "link") {
							_date.headline		=	dd.data.link.title;
							_date.text			=	dd.data.link.description;
							if (dd.data.link.thumbnail != 'undefined' && dd.data.link.thumbnail != '') {
								_date.asset.media	=	dd.data.link.thumbnail;
							} else {
								_date.asset.media	=	dd.permalink;
							}
							//_date.asset.media	=	dd.permalink;
							_date.asset.caption	=	"<a href='" + dd.permalink + "' target='_blank'>" + dd.data.link.title + "</a>"
							_date.slug			=	dd.data.link.title;
							
						} else if (dd.type == "text") {
							if (dd.permalink.match("storify")) {
								is_text = true;
								var asset_text	=	"<div class='storify'><blockquote><p>" + dd.data.text.replace(/<\s*\/?\s*b\s*.*?>/g,"") + "</p></blockquote>";
								asset_text		+=	"<div class='vcard author'><a class='screen-name url' href='" + dd.attribution.href + "' target='_blank'>";
								asset_text		+=	"<span class='avatar'><img src='" + dd.attribution.thumbnail + "' style='max-width: 32px; max-height: 32px;'></span>"
								asset_text		+=	"<span class='fn'>" + dd.attribution.username + "</span>";
								asset_text		+=	"<span class='nickname'><div class='thumb-storify-full'></div></span>";
								asset_text		+=	"</a></div></div>";
								_date.text		=	asset_text;
								
								// Try and put it before the element where it is expected on storify
								if ( (i+1) >= d.content.elements.length ) {
									_date.startDate = d.content.elements[i-1].posted_at;
									
								} else {
									if (d.content.elements[i+1].type == "text" && d.content.elements[i+1].permalink.match("storify")) {
										if ( (i+2) >= d.content.elements.length ) {
											_date.startDate = d.content.elements[i-1].posted_at;
										} else {
											if (d.content.elements[i+2].type == "text" && d.content.elements[i+2].permalink.match("storify")) {
												if ( (i+3) >= d.content.elements.length ) {
													_date.startDate = d.content.elements[i-1].posted_at;
												} else {
													if (d.content.elements[i+3].type == "text" && d.content.elements[i+3].permalink.match("storify")) {
														_date.startDate = d.content.elements[i-1].posted_at;
													} else {
														trace("LEVEL 3");
														_date.startDate = d.content.elements[i+3].posted_at;
													}
												}
											} else {
												trace("LEVEL 2");
												_date.startDate = d.content.elements[i+2].posted_at;
											}
										}
									} else {
										trace("LEVEL 1");
										_date.startDate = d.content.elements[i+1].posted_at;
									}
									
								}
								_date.endDate = _date.startDate
							}
							
							
						} else if (dd.type == "video") {
							_date.headline		=	dd.data.video.title;
							_date.asset.caption	=	dd.data.video.description;
							_date.asset.caption	=	dd.source.username;
							_date.asset.media	=	dd.data.video.src;
						} else {
							trace("NO MATCH ");
							trace(dd);
						}
						
						if (is_text) {
							_date.slug = VMM.Util.untagify(dd.data.text);
						}
						
						_data_obj.timeline.date.push(_date);
						
						
					};
				
					VMM.fireEvent(global, VMM.Timeline.Config.events.data_ready, _data_obj);
				}
				
			},
			
			tweets: {
				
				type: "twitter",
			
				buildData: function(raw_data) {
					VMM.bindEvent(global, VMM.Timeline.DataObj.model.tweets.onTwitterDataReady, "TWEETSLOADED");
					VMM.ExternalAPI.twitter.getTweets(raw_data.timeline.tweets);
				},
			
				getData: function(raw_data) {
					VMM.bindEvent(global, VMM.Timeline.DataObj.model.tweets.onTwitterDataReady, "TWEETSLOADED");
					VMM.ExternalAPI.twitter.getTweetSearch(raw_data);
				},
			
				onTwitterDataReady: function(e, d) {
					var _data_obj = VMM.Timeline.DataObj.data_template_obj;

					for(var i = 0; i < d.tweetdata.length; i++) {

						var _date = {
							"type":"tweets",
							"startDate":"",
				            "headline":"",
				            "text":"",
				            "asset":
				            {
				                "media":"",
				                "credit":"",
				                "caption":""
				            },
				            "tags":"Optional"
						};
						// pass in the 'created_at' string returned from twitter //
						// stamp arrives formatted as Tue Apr 07 22:52:51 +0000 2009 //
					
						//var twit_date = VMM.ExternalAPI.twitter.parseTwitterDate(d.tweetdata[i].raw.created_at);
						//trace(twit_date);
					
						_date.startDate = d.tweetdata[i].raw.created_at;
					
						if (type.of(d.tweetdata[i].raw.from_user_name)) {
							_date.headline = d.tweetdata[i].raw.from_user_name + " (<a href='https://twitter.com/" + d.tweetdata[i].raw.from_user + "'>" + "@" + d.tweetdata[i].raw.from_user + "</a>)" ;						
						} else {
							_date.headline = d.tweetdata[i].raw.user.name + " (<a href='https://twitter.com/" + d.tweetdata[i].raw.user.screen_name + "'>" + "@" + d.tweetdata[i].raw.user.screen_name + "</a>)" ;
						}
					
						_date.asset.media = d.tweetdata[i].content;
						_data_obj.timeline.date.push(_date);
					
					};
				
					VMM.fireEvent(global, VMM.Timeline.Config.events.data_ready, _data_obj);
				}
				
			}
		},
		
		
		/*	TEMPLATE OBJECTS
		================================================== */
		data_template_obj: {  "timeline": { "headline":"", "description":"", "asset": { "media":"", "credit":"", "caption":"" }, "date": [] } },
		date_obj: {"startDate":"2012,2,2,11,30", "headline":"", "text":"", "asset": {"media":"http://youtu.be/vjVfu8-Wp6s", "credit":"", "caption":"" }, "tags":"Optional"}
	
	};
	
}