
var ArchiveDisplay = (function () {

	var itemsPerPage = 10;

	var tabs = {
		selected: '',
		order: [ 'All', 'Videos', 'Stories' ],
		collections: {
			'All': {
				tabId: '#archive-tab-all',
				top: {
					selector: '#archive-display-top > div.archive-top:eq(0)',
					elements: []
				},
				items: {
					selector: '#archive-display-page > div.archive-item:not(:eq(0))',
					elements: []
				}
			},
			'Videos': {
				tabId: '#archive-tab-video',
				top: {
					selector: '#archive-display-top > div.archive-top.video:eq(0)',
					elements: []
				},
				items: {
					selector: '#archive-display-page > div.archive-item.video:not(:eq(0))',
					elements: []
				}
			},
			'Stories': {
				tabId: '#archive-tab-story',
				top: {
					selector: '#archive-display-top > div.archive-top.story:eq(0)',
					elements: []
				},
				items: {
					selector: '#archive-display-page > div.archive-item.story:not(:eq(0))',
					elements: []
				}
			}
		}
	};
	
	var selectTabElement = function (event) {
		var $tab = jQuery(this);  // <a>
		var $container = $tab.parent();  // <li> that contains the <a>
		
		if ( $container.hasClass('current') )
		{
			// if it's currently selected, don't bother doing anything
		}
		else
		{
			for ( var i = 0, end = tabs.order.length, tabName = '', collection = null; i < end; i++ )
			{
				tabName = tabs.order[i];
				collection = tabs.collections[ tabName ];
				
				if ( collection.tabId === '#' + this.id )  // the tab selected
				{
	
/*
					// sets BoxHeader div (curved) background off if first tab selected, and back on if not.
					if ( i === 0 ) {
						jQuery('#cnnArchiveTabActive').addClass('cnnArchiveFirstTabActive');
					} else {
						jQuery('#cnnArchiveTabActive').removeClass('cnnArchiveFirstTabActive');
					}
*/
					
					// show selected tab as current tab
					$container.siblings().removeClass( 'current' ).end().addClass( 'current' );
	
					// render archive display page area
					selectTab( tabName );
	
				}
			}
		}
		
		return false;
	};
	
	var init = function () {
				
		// collect top (T1) and items for page (think of it like caching)
		// tabs.collections['All'].top.elements and tabs.collections['All'].items.elements
		var populatedTabs = [];

		for ( var i = 0, end = tabs.order.length, tabName = '', collection = null; i < end; i++ ) {
			tabName = tabs.order[i];
			collection = tabs.collections[ tabName ];
			for ( var subcollections = [ 'top', 'items' ], j = 0, endj = subcollections.length, subcollection = null; j < endj; j++ ) {
				subcollection = collection[ subcollections[j] ];
				subcollection.elements = jQuery(subcollection.selector);
			}
			if ( collection.top.elements.length > 0 ) {
				populatedTabs.push( tabName );
				jQuery( collection.tabId ).click( selectTabElement );
			}
		}
		
		selectTab('All');

	};

	var selectTab = function ( tabName ) {
		if ( tabName !== tabs.selected ) {
			tabs.selected = tabName;
			jQuery('#archive-display-top').fadeTo( 300, 0.3, function () {
				var container = jQuery(this);
				container.find('div.archive-top:visible').hide();
				tabs.collections[ tabName ].top.elements.slice(0,1).show();
				container.fadeTo( 300, 1 );
			});
			update();
		}
		
		return false;
	};

	var selectPage = function ( pageNum ) {
		jQuery('#archive-display-page').fadeTo( 300, 0.3, function () {
			var page = jQuery(this);
			page.find('div.archive-item:visible').hide();
			tabs.collections[ tabs.selected ].items.elements
				.slice( ((pageNum)*itemsPerPage), (((pageNum+1)*itemsPerPage)) )
				.find('img[lazyload]')
					.each(function (i) {
					    var $this = jQuery(this);
					    $this.attr( 'src', $this.attr('lazyload') ).removeAttr('lazyload');
					})
				.end()
				.show()
			;
			page.fadeTo( 300, 1 );
		});
		
		return false;
	};

	var update = function () {				
		jQuery("#archive-display-pager").pagination(
			tabs.collections[ tabs.selected ].items.elements.length,
			{
				items_per_page:       itemsPerPage,
				num_display_entries:  10,
				num_edge_entries:      2,
				prev_text:     '&laquo; Previous',
				next_text:     'Next &raquo;',
				callback:      selectPage
			}
		);
	};

	return ({
		'init':       init,
		'selectTab':  selectTab,
		'selectPage': selectPage
	});
})();


/**
 * TimeStamp.
 *   @param {Number}  ts  The time in milliseconds-since-epoch
 */
function TimeStamp( ts_date ) {

	var ts_time = ts_date.getTime();
	this.date = ts_date;
	this.time = ts_time;
	this.properties = {
		  date: ts_date.getDate(),
		   day: ts_date.getDay(),
		  hour: ts_date.getHours(),
		minute: ts_date.getMinutes(),
		 month: ts_date.getMonth(),
		second: ts_date.getSeconds(),
		  year: ts_date.getFullYear()
	};
	this.formattingMatch = /yy(?:yy)?|M{1,4}|dd?|EEEE?|HH?|hh?|mm?|ss?|A{1,4}|a{1,4}/g;
	this.formattingMapping = (function (self) {
		var afternoon = self.properties.hour > 11;
		return ({
			"yyyy": '' + self.properties.year,
			  "yy": self.properties.year.toString().substr(-2),
			"MMMM": self.MONTH_NAMES[ self.properties.month ],
			 "MMM": self.ABBR_MONTH_NAMES[ self.properties.month ],
			  "MM": self.properties.month < 9 ? '' + '0' + (self.properties.month + 1) : '' + (self.properties.month + 1),
			   "M": '' + (self.properties.month + 1),
			  "dd": self.properties.date < 10 ? '' + '0' + self.properties.date : '' + self.properties.date,
			   "d": '' + self.properties.date,
			"EEEE": self.WEEKDAY_NAMES[ self.properties.day ],
			 "EEE": self.ABBR_WEEKDAY_NAMES[ self.properties.day ],
			  "HH": self.properties.hour < 9 ? '' + '0' + self.properties.hour : '' + self.properties.hour,
			   "H": '' + self.properties.hour,
			  "hh": (function () {
						var twelveHour = self.properties.hour > 12 ? (self.properties.hour - 12) : self.properties.hour === 0 ? (self.properties.hour + 12) : self.properties.hour;
						return twelveHour < 10 ? '' + '0' + twelveHour : '' + twelveHour;
					})(),
			   "h": self.properties.hour > 12 ? '' + (self.properties.hour - 12) : self.properties.hour === 0 ? '' + (self.properties.hour + 12) : '' + self.properties.hour,
			  "mm": self.properties.minute < 10 ? '' + '0' + self.properties.minute : '' + self.properties.minute,
			   "m": '' + self.properties.minute,
			  "ss": self.properties.second < 10 ? '' + '0' + self.properties.second : '' + self.properties.second,
			   "s": '' + self.properties.second,
			"AAAA": afternoon ? 'P.M.' : 'A.M.',
			 "AAA": afternoon ? 'PM.' : 'AM.',
			  "AA": afternoon ? 'PM' : 'AM',
			   "A": afternoon ? 'P' : 'A',
			"aaaa": afternoon ? 'p.m.' : 'a.m.',
			 "aaa": afternoon ? 'pm.' : 'am.',
			  "aa": afternoon ? 'pm' : 'am',
			   "a": afternoon ? 'p' : 'a'
		});
	})(this);
	this.formattingReplacer = (function (self) {
		return (function (substring) {
			return self.formattingMapping[substring];
		});
	})(this);
}

TimeStamp.prototype = {
	SECOND: 1000,
	MINUTE: 60000,
	HOUR: 3600000,
	DAY: 86400000,
	MONTH_NAMES: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
	ABBR_MONTH_NAMES: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ],
	WEEKDAY_NAMES: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
	ABBR_WEEKDAY_NAMES: [ "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" ]
};

TimeStamp.prototype.format = function (formatString) {
	return formatString.replace( this.formattingMatch, this.formattingReplacer );
};


/**
 * jQuery().updateTimeStamp()
 *   @param {Object}  options  { 'attribute': name of attribute to use, 'function': logic }
 *   @requires TimeStamp
 */
(function ($) {
	
	$.fn.updateTimeStamp = function (options) {
		
		var defaults = {
			'attribute': 'time',
			'function': function ( timestamp ) {
				var now = new Date().getTime();
				// check if global cnnCurrTime exists
				if ( typeof cnnCurrTime !== 'undefined' && typeof cnnCurrTime.getTime === 'function' ) {
					// cnnCurrTime exists
					if ( Math.abs( cnnCurrTime.getTime() - now ) < timestamp.HOUR ) {
						// cnnCurrTime seems recent, use it
						now = cnnCurrTime.getTime();
					}
				}
				var delta = now - timestamp.time;
				if ( delta < 0 ) {  // future?
					// don't change anything
				} else {
					var diff = Math.abs( delta );
					var days = Math.floor( diff / timestamp.DAY );
					var hours = Math.floor( diff % timestamp.DAY / timestamp.HOUR );
					var minutes = Math.floor( diff % timestamp.DAY % timestamp.HOUR / timestamp.MINUTE );
					var seconds = Math.floor( diff % timestamp.DAY % timestamp.HOUR % timestamp.MINUTE / timestamp.SECOND );
					var daysString = ( days === 1 ? "day" : "days" );
					var hoursString = ( hours === 1 ? "hour" : "hours" );
					var minutesString = ( minutes === 1 ? "minute" : "minutes" );
					var secondsString = ( seconds === 1 ? "second" : "seconds" );

					if ( diff < timestamp.MINUTE )
					{
						this.html( "updated " + seconds + " " + secondsString + " ago" )
							.addClass( 'cnn-ts-1m' )
						;
					}
					else if ( diff < timestamp.HOUR )
					{
						this.html( "updated " + minutes + " " + minutesString + " ago" )
							.addClass( 'cnn-ts-1h' )
						;
					}
					else if ( diff < timestamp.DAY )
					{
						this.html( "updated " + hours + " " + hoursString + ( minutes ? (", " + minutes + " " + minutesString) : '' ) + " ago" )
							.addClass( 'cnn-ts-1d' )
						;
					}
					else
					{
						var now = new Date();
						var midnight = new Date( now.getTime() - (
							((now.getHours()
								* 60 + now.getMinutes())
									* 60 + now.getSeconds())
										* 1000 + now.getMilliseconds()
						) );
						var dayDiff = midnight - timestamp.time;
						days = Math.ceil( dayDiff / timestamp.DAY );
						daysString = ( days === 1 ? "day" : "days" );
						if ( days < 3 )
						{
							this.html( "updated " + days + " " + daysString + " ago" )
								.addClass( 'cnn-ts-3d' )
							;
						}
						else
						{
							this.html( "updated " + timestamp.format( 'MMMM d, yyyy' ) )
								.addClass( 'cnn-ts-old' )
							;
						}
					}
				}

				
			}
		};
		
		var opts = $.extend( defaults, options );
		
		return this.each(function () {
			var $this = $(this);
			var attr = $this.attr( opts['attribute'] );
			var time, date, timestamp;
			if ( attr ) {
				try {
					date = new Date( parseInt( attr, 10 ) );
					time = date.getTime();
					if ( isNaN( time ) ) {
						throw "attribute '" + opts['attribute'] + "' did not parse to valid time";
					}
					opts['function'].call( $this, new TimeStamp( date ) );
				} catch (e) {
					throw "attribute '" + opts['attribute'] + "' not valid date/time";
				}
			}
		});
	};

})(jQuery);


/**
 * This jQuery plugin displays pagination links inside the selected elements.
 *
 * @author Gabriel Birke (birke *at* d-scribe *dot* de)
 * @version 1.2
 * @param {int} maxentries Number of entries to paginate
 * @param {Object} opts Several options (see README for documentation)
 * @return {Object} jQuery Object
 */
jQuery.fn.pagination = function(maxentries, opts){
	opts = jQuery.extend({
		items_per_page:10,
		num_display_entries:10,
		current_page:0,
		num_edge_entries:0,
		link_to:"#",
		prev_text:"Prev",
		next_text:"Next",
		ellipse_text:"...",
		prev_show_always:true,
		next_show_always:true,
		callback:function(){return false;}
	},opts||{});
	
	return this.each(function() {
		/**
		 * Calculate the maximum number of pages
		 */
		function numPages() {
			return Math.ceil(maxentries/opts.items_per_page);
		}
		
		/**
		 * Calculate start and end point of pagination links depending on 
		 * current_page and num_display_entries.
		 * @return {Array}
		 */
		function getInterval()  {
			var ne_half = Math.ceil(opts.num_display_entries/2);
			var np = numPages();
			var upper_limit = np-opts.num_display_entries;
			var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0;
			var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(opts.num_display_entries, np);
			return [start,end];
		}
		
		/**
		 * This is the event handling function for the pagination links. 
		 * @param {int} page_id The new page number
		 */
		function pageSelected(page_id, evt){
			current_page = page_id;
			drawLinks();
			var continuePropagation = opts.callback(page_id, panel);
			if (!continuePropagation) {
				if (evt.stopPropagation) {
					evt.stopPropagation();
				}
				else {
					evt.cancelBubble = true;
				}
			}
			return continuePropagation;
		}
		
		/**
		 * This function inserts the pagination links into the container element
		 */
		function drawLinks() {
			panel.empty();
			var interval = getInterval();
			var np = numPages();
			// This helper function returns a handler function that calls pageSelected with the right page_id
			var getClickHandler = function(page_id) {
				return function(evt){ return pageSelected(page_id,evt); };
			};
			// Helper function for generating a single link (or a span tag if it's the current page)
			var appendItem = function(page_id, appendopts){
				page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value
				appendopts = jQuery.extend({text:page_id+1, classes:""}, appendopts||{});
				if(page_id == current_page){
					var lnk = jQuery("<span class='current'>"+(appendopts.text)+"</span>");
				}
				else
				{
					var lnk = jQuery("<a>"+(appendopts.text)+"</a>")
						.bind("click", getClickHandler(page_id))
						.attr('href', opts.link_to.replace(/__id__/,page_id));
						
						
				}
				if(appendopts.classes){lnk.addClass(appendopts.classes);}
				panel.append(lnk);
			};
			// Generate "Previous"-Link
			if(opts.prev_text && (current_page > 0 || opts.prev_show_always)){
				appendItem(current_page-1,{text:opts.prev_text, classes:"prev"});
			}
			// Generate starting points
			if (interval[0] > 0 && opts.num_edge_entries > 0)
			{
				var end = Math.min(opts.num_edge_entries, interval[0]);
				for(var i=0; i<end; i++) {
					appendItem(i);
				}
				if(opts.num_edge_entries < interval[0] && opts.ellipse_text)
				{
					jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
				}
			}
			// Generate interval links
			for(var i=interval[0]; i<interval[1]; i++) {
				appendItem(i);
			}
			// Generate ending points
			if (interval[1] < np && opts.num_edge_entries > 0)
			{
				if(np-opts.num_edge_entries > interval[1]&& opts.ellipse_text)
				{
					jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
				}
				var begin = Math.max(np-opts.num_edge_entries, interval[1]);
				for(var i=begin; i<np; i++) {
					appendItem(i);
				}
				
			}
			// Generate "Next"-Link
			if(opts.next_text && (current_page < np-1 || opts.next_show_always)){
				appendItem(current_page+1,{text:opts.next_text, classes:"next"});
			}
		}
		
		// Extract current_page from options
		var current_page = opts.current_page;
		// Create a sane value for maxentries and items_per_page
		maxentries = (!maxentries || maxentries < 0)?1:maxentries;
		opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;
		// Store DOM element for easy access from all inner functions
		var panel = jQuery(this);
		// Attach control functions to the DOM element 
		this.selectPage = function(page_id){ pageSelected(page_id);};
		this.prevPage = function(){ 
			if (current_page > 0) {
				pageSelected(current_page - 1);
				return true;
			}
			else {
				return false;
			}
		};
		this.nextPage = function(){ 
			if(current_page < numPages()-1) {
				pageSelected(current_page+1);
				return true;
			}
			else {
				return false;
			}
		};
		// When all initialisation is done, draw the links
		drawLinks();
        // call callback function
        opts.callback(current_page, this);
	});
};
