(function($,$tartup){
	
	// $tartup
   // docs: http://wiki.nyc.foxnews.com/display/DEV/Fox+News+Javascript+Framework
   var FOX_Live = window.FOX_Live = $tartup;
   var Add = FOX_Live.site.Add,
      DOC_Ready = FOX_Live.site.OnDocReady,
      PAGE_Ready = FOX_Live.site.OnPageReady;
	
	// General document.ready
	DOC_Ready(function(){
		$.ad.init(); // initialize ads
	});
	
	// General page ready
	PAGE_Ready(function(){
		$.ad.pre(); // preload ads
		 
		// special case closing
		$("#section-video > p:last a").click(function(){
			$(this).parent().hide();
			return false;
		});
	});
	
	// FOX_Live.site.StrategyRoomSchedule
	PAGE_Ready("StrategyRoomSchedule",{
		init: function() {
			var self = this;
			$("#strategy-room-on").each(function(){
				self.set($(this));
			});
		},
		set: function(elm) {
			var self = this;
			
			var ajax = new AjaxContext({
				url: "/schedule/fox-news-live/today", 
				data: {},
				cacheFreq: 1, // cache bust every 1 minute 
				dataType: "json",
				callback: {
					success: function(data) {
						elm.parent().find(".loading").remove();
						if (data && data.length>0) {
							self.render(elm,data);
						}
					}
				}
			});
		},
		render: function(elm,data) {
			var self, parent = elm.parent(), htmlArr = [], dataArr = [], hasLive = false;
			
			// set title
			parent.prepend('<h2>Today\'s Show</h2>');
			
			var setItem = function(item) {
				var item = data[x],
					title = (typeof item.episode_title==="string" && item.episode_title.length>0) ? item.episode_title : item.show_title,
					desc = (item.episode_short_description) ? item.episode_short_description : item.show_short_description,
					months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
				
				desc = $("<span>"+desc+"</span>").text(); // text only!
				
				// isLive
				var now = new Date(item.now),
					start = new Date(item.episode_start_time),
					end = new Date(item.episode_end_time),
					isLive = (now >= start && now <= end) ? true : false;
				
				if (isLive && !hasLive) { // ONLY 1 LIVE SHOW -> First one
					hasLive = true;
				} else if (hasLive) {
					isLive = false;
				}
				
				var prefix = (parseInt(item.show_start_time,10) < 10) ?  "0" : "",
					timeStr = prefix + item.show_start_time + ":" +item.show_startminute + item.show_time_meridiem.toLowerCase(),
					css = (isLive) ? ' class="active curr-live-show"' : "";
				
				timeStr += (isLive) ? '<br/><span class="live">Live</span>' : "";

				htmlArr.push('<li'+css+'><h3>'+timeStr+'</h3>');
				htmlArr.push('<p>'+desc+'</p>');
				htmlArr.push('</li>');
				// store data
				dataArr.push(item);
			};
			
			// date
			var getDate = function(val) {
				var d = new Date(val),
					mm = parseInt(d.getMonth()+1,10),
					dd = d.getDate().toString(),
					yr = d.getFullYear().toString(),
					ret = new Date(((mm < 10) ? "0" : "") + mm.toString() + "/" + dd + "/" + yr + " 23:59");
				return ret;
			};
			
			// replay jump
			var getReplayJump = function(info) {
				var first = new Date(dataArr[0].episode_start_time), now = new Date(info.episode_start_time);
				first = first.getTime();
				now = now.getTime();
				var diff = (now - first) / 1000; // seconds
				log(diff + " second/s or " + (diff / 60) + " minute/s or " + (diff / (60*60)) + " hour/s");
				
				var player = $(".video-player-wrapper > object").get(0);
				try {
					log("[videoPlayer.jumpToTime] Executing: player.jumpToTime("+diff+")");
					player.jumpToTime(diff);
				} catch(err) {
					log("[videoPlayer.jumpToTime] Error: " + err);
				}
				
			};
			
			htmlArr.push('<div class="show-items"><ul id="show-item-mod">');
			for (var x = 0; x < data.length; x++) {
				var item = data[x], itemDate = getDate(item.episode_start_time), nowDate = getDate(item.now);
				// only items from today's date onwards
				if (itemDate >= nowDate) { setItem(item); }
			}
			htmlArr.push('</ul></div>');
			elm.html(htmlArr.join(""));
			
			var highlightSummary = function(id,isAfterLive) {
				var info = (dataArr[id]) ? dataArr[id] : false;
				
				var summary = elm.find("> #summary-hldr-mod");
				if (summary.size()===0) {
					var summaryArr = [];
					summaryArr.push('<div id="summary-hldr-mod" style="display:none;"><h3>Summary</h3>');
					summaryArr.push('<a style="display:none;" href="http://live.foxnews.com/" class="btn-smll">Watch Replay</a>');
					summaryArr.push('<span class="desc">&nbsp;</span>');
					summaryArr.push('</div>');
					elm.append(summaryArr.join(""));
					summary = elm.find("> #summary-hldr-mod");
				}
				
				var desc = (info) ? (info.episode_long_description) ? info.episode_long_description : info.show_long_description : "&nbsp;";
				desc = ($('<span>'+desc+'</span>').find("p").size() > 0) ? desc : '<p>' + desc + '</p>';
				
				summary.find("> .desc").html(desc);
				
				// replay button for non-live items
				var replay = summary.find("> .btn-smll");
				replay.unbind("click");
				replay.css("display",(isAfterLive) ? "none" : "block");
				// replay event
				if (!isAfterLive) {
					replay.click(function(){
						var secs = getReplayJump(info);
						$(window).scrollTop(0);
						return false;
					});
				}
				
				summary.show();
				
				// store original holder height
				var list = elm.find("#show-item-mod"), lastLI = list.find("> li:last");
				
				// if summary is too long, set up styles
				if (list.outerHeight() < summary.outerHeight()) {
					lastLI.addClass("ext-height");
				} else {
					lastLI.removeClass("ext-height");
				}
			};
			
			var afterLive = false, opened = false, listItems = elm.find("#show-item-mod > li");
			
			listItems.each(function(i){
				var el = $(this);
				// "live" will automatically be highlighted
				if (el.hasClass("curr-live-show")) {
					afterLive = true;
					opened = true;
					highlightSummary(i,true);
				}
				
				el.data("_isAfterLive",(afterLive) ? true : false);
				el.click(function(){
					highlightSummary(i,el.data("_isAfterLive"));
					listItems.removeClass("active");
					el.addClass("active");
					if (dataArr[i]) { log(dataArr[i]); }
					return false;
				});
			});
			
			if (!opened) { listItems.eq(0).click(); }
		}
	});
	
	// FOX_Live.site.ComingUp
	PAGE_Ready("ComingUp",{
		init: function() {
			var self = this;
			$('#strategy-room-also-on').each(function(){
				self.set($(this));
			});
		},
		set: function(elm) {
			var self = this;
			
			var ajax = new AjaxContext({
				url: "/schedule/fox-news-live/?days=5", 
				data: {},
				cacheFreq: 1, // cache bust every 1 minute 
				dataType: "json",
				callback: {
					success: function(data) {
						elm.parent().find(".loading").remove();
						if (data && data.length>0) {
							self.render(elm,data);
						} else {
							elm.css("visibility","hidden");
						}
					}
				}
			});
		},
		render: function(elm,data) {
			var self = this, htmlArr = [], limit = (data.length > 2) ? 2 : data.length, count = 0;

			htmlArr.push('<div class="encap module-3"><ul>');
			for (var x = 0; x < data.length; x++) {
				if (count >= 2) { break; } // only 2 items
				var item = data[x],
					title = (typeof item.episode_title==="string" && item.episode_title.length>0) ? item.episode_title : item.show_title,
					desc = (item.episode_short_description) ? item.episode_short_description : item.show_short_description,
					months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
				
				desc = $("<span>"+desc+"</span>").text(); // text only!
				
				// isLive
				var now = new Date(item.now),
					start = new Date(item.episode_start_time),
					end = new Date(item.episode_end_time),
					isAfterLive = (start > now && end > now) ? true : false; 

				if (isAfterLive) {
					// date
					var dateStr = (function(){
						var d = new Date(item.episode_start_time),
							ret = months[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
						return ret;
					}());

					// time
					var timeStr = item.show_start_time + ":" + item.show_startminute + " " + item.show_time_meridiem.toUpperCase() + " ET";

					htmlArr.push('<li>');
					htmlArr.push('<div class="img"><img src="'+item.show_image_filepath+'" style="width:60px; height:60px;" alt=""/></div>');
					htmlArr.push('<p class="date">'+dateStr+' <span>'+timeStr+'</span></p>');
					htmlArr.push('<h3>'+title+'</h3>');
					htmlArr.push('<p>'+desc+'</p>');
					htmlArr.push('</li>');
					
					count++;
				}
			}
			htmlArr.push('</ul></div>');
			elm.append(htmlArr.join(""));
		}
	});
	
	// FOX_Live.site.AlsoStreaming
	PAGE_Ready("AlsoStreaming",{
		init: function() {
			var self = this;
			$("#also-streaming").each(function(){
				self.set($(this));
			});
		},
		set: function(elm) {
			var self = this;
			
			var ajax = new AjaxContext({
				url: "/schedule/live-web-shows/?days=5&limit=2", 
				data: {},
				cacheFreq: 1, // cache bust every 1 minute 
				dataType: "json",
				callback: {
					success: function(data) {
						elm.parent().find(".loading").remove();
						if (data && data.length>0) {
							self.render(elm,data);
						}
					}
				}
			});
		},
		render: function(elm,data) {
			var self = this, htmlArr = [], limit = (data.length > 2) ? 2 : data.length;
			
			htmlArr.push('<div class="encap module-3"><ul>');
			for (var x = 0; x < limit; x++) {
				var item = data[x],
					title = (typeof item.episode_title==="string" && item.episode_title.length>0) ? item.episode_title : item.show_title,
					desc = (item.episode_short_description) ? item.episode_short_description : item.show_short_description,
					months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

				desc = $("<span>"+desc+"</span>").text(); // text only!
				
				// date
				var dateStr = (function(){
					var d = new Date(item.episode_start_time),
						ret = months[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
					return ret;
				}());
				
				// time
				var timeStr = item.show_start_time + " " + item.show_time_meridiem.toUpperCase() + " ET";
				
				htmlArr.push('<li>')
				htmlArr.push('<div class="img"><img src="'+item.show_image_filepath+'" style="width:60px; height:60px;" alt=""/></div>');
				htmlArr.push('<p class="date">'+dateStr+' <span>'+timeStr+'</span></p>');
				htmlArr.push('<h3><a href="'+item.show_channel_link+'">'+title+'</a></h3>');
				htmlArr.push('<p>'+desc+'</p>');
				htmlArr.push('</li>');
			}
			htmlArr.push('</ul></div>');
			elm.append(htmlArr.join(""));
		}
	});
	
	// FOX_Live.site.tweetLatest
	PAGE_Ready("tweetLatest",{
		init: function() {
			var self = this;
			$(".tweet-latest").each(function(){
				self.set($(this));
			});
		},
		set: function(elm) {
			var self = this, user = "foxnewslive";
			
			window.FOX_Live_Latest_Tweet = new AjaxContext({
				namespace: "FOX_Live_Latest_Tweet",
				url: "http://search.twitter.com/search.json",
				data: { q:encodeURI("from:foxnewslive"), rpp:"1" },
				cacheFreq: 1, // cache bust every 1 minute 
				dataType: "jsonp",
				callback: {
					success: function(data) {
						if (!data) { return false; }
						if (data && data.results && data.results.length > 0) {
							self.render(elm,data.results[0]);
						}
					}
				}
			});
			
			elm.find("> .encap.module-4 > a[rel='external']").each(function(){
				var a = $(this), href = a.attr("href");
				a.unbind("click").click(function(){ window.open(href,"_blank"); return false; });
			});
		},
		render: function(elm,data) {
			var self = this, desc = self.setMessage(data.text);
			elm.find("> .encap.module-4 > p").html(desc);
		},
		setMessage: function(text) {
			var x, i, TW = this;
			var matches = {
				links: text.match(/\http:\/\/\S+/gi),
				users: text.match(/@[a-zA-Z0-9\-\_]+/gi),
				terms: text.match(/#[a-zA-Z0-9\-\_]+/gi)
			};

			var replace = {
				links: '<a target="_blank" href="${item}" target="_blank" class="hyper-word">${item}</a>',
				users: '<a target="_blank" href="http://twitter.com/${link}">${item}</a>',
				terms: '<a target="_blank" href="http://twitter.com/${link}">${item}</a>'
			};

			for (i in matches) {
				var match = matches[i];
				if (match) {
					var len = match.length;
					for (x = 0; x < len; x++) {
						var item = match[x];
						if (i==="users") {
							text = text.replace(item,replace[i].replace(/(\$\{item\})/g,item).replace(/(\$\{link\})/g,item.slice(1)));
						} else if (i==="terms") {
							text = text.replace(item,replace[i].replace(/(\$\{item\})/g,item).replace(/(\$\{link\})/g,"search?q="+item.slice(1)));
						}
						else {
							text = text.replace(item,replace[i].replace(/(\$\{item\})/g,item));
						}
					}
				}
			}

			return text;
		}
	});
	
	function log(str) {
		if (window.console && console.log) { console.log(str); }
	}
	
}(jQuery,$tartup));
