/*
if (!window['console']) {
	window['console'] = {
		log: function() {
			return;
		}
	};
}
*/



// ----- Fancybox stuff
var fancyStuff = function() {
	assert('body.latest, body.photos', fancyPhotos);
	assert('body.latest, body.videos', fancyVideos);
};
var fancyDefaultOptions = {
	callbackOnStart: function() {
		updateConf.paused = true;
	},
	callbackOnClose: function() {
		updateConf.paused = false;
	},
	overlayOpacity: .8
};
var fancyPhotos = function() {
	var photosSection = jQuery('body.photos').length;
	jQuery('div.thumb.photos[rel]').each(function() {
		var attr = jQuery(this).attr('rel');
		jQuery(this).wrapInner('<a href="' + attr + '" rel="group_photo" class="group_photo"></a>');
		jQuery(this).find('img').css('cursor', 'pointer');
		jQuery(this).find('a').css('cursor', 'pointer');
		if (!photosSection) {
			jQuery(this).find('a').fancybox(fancyDefaultOptions);
		}
		jQuery(this).removeAttr('rel');
	});
	jQuery('div.content.photos[rel]').each(function() {
		var attr = jQuery(this).attr('rel');
		jQuery(this).wrapInner(' <a href="' + attr + '" rel="group_photo2" class="group_photo2 preview"></a>');
		if (!photosSection) {
			jQuery(this).find('a').fancybox(fancyDefaultOptions);
		}
		jQuery(this).removeAttr('rel');
	});
	var options = fancyDefaultOptions;
	options.hideOnContentClick = false;
	jQuery('a.group_photo').fancybox(options);
	jQuery('a.group_photo2').fancybox(options);
};
var fancyVideos = function() {
	var options = fancyDefaultOptions;
	options.hideOnContentClick = false;
	options.frameWidth = 800;
	options.frameHeight = 450;
	jQuery('div.thumb.videos[rel]').each(function() {
		var attr = jQuery(this).attr('rel') + '&fs=1&rel=0&showinfo=0&disablekb=1';
		jQuery(this).wrapInner('<a href="/embed/' + attr + '"></a>');
		jQuery(this).find('img').css('cursor', 'pointer');
		jQuery(this).find('a').css('cursor', 'pointer').fancybox(options);
		jQuery(this).removeAttr('rel');
	});
	jQuery('div.content.videos[rel]').each(function() {
		var attr = jQuery(this).attr('rel');
		jQuery(this).wrapInner(' <a href="/embed/' + attr + '" class="preview"></a>');
		jQuery(this).find('a').fancybox(options);
		jQuery(this).removeAttr('rel');
	});
};
var fancyStream = function() {
	var options = fancyDefaultOptions;
	options.hideOnContentClick = false;
	options.frameWidth = 385;
	options.frameHeight = 320;
	jQuery('.nav .ustream a').removeClass('external').removeAttr('target').attr('href', '/live').fancybox(options);
};


// ----- Update stuff
var updateConf = {
	last_id: null,
	paused: false,
	interval_obj: null,
	interval_time: 30,
	type: null,
	updateCount: 0,
	is_updating: false,
	displayLoadingText: true,
	highlightClass: 'highlight',
	fadeIn: false
};
var setLoadingStatus = function(text) {
	jQuery('#content h2').text(text);
};
var updateStream = function() {
	if (updateConf.paused) {
		return;
	}
	updateConf.is_updating = true;
	if (updateConf.displayLoadingText) {
		var loadingStatus = jQuery('#content h2').text();
		var loadText = lit('Llwytho...', 'Loading...');
		setLoadingStatus(loadText);
	}
	++updateConf.updateCount;
	var type = '';
	if (updateConf.type !== null) {
		type = '&type=' + updateConf.type;
	}
	jQuery.getJSON('/updates.json?since=' + updateConf.last_id + type + '&timestamp=' + (new Date()).getTime(), function(data) {
		if (data.length == 0) {
			if (updateConf.displayLoadingText) {
				setTimeout(function() {
					setLoadingStatus(loadingStatus);
				}, 2000);
			}
			return;
		}
		updateConf.last_id = data[0].id;
		var content = '';
		jQuery.each(data, function(i, item) {
			var itemDate = Math.floor(Date.parse(item.dt_published) / 1000);
			content += '<li class="' + item.type + ' ' + updateConf.highlightClass + '" id="stream_item_' + item.id + '">';
			if (item.type === 'blogs') {
				item.thumbnail.source = '/static/img2/thumb_bloggers4plaid.png';
			}
			content += '<div class="content';
			if (item.media_content !== null) {
				content += ' ' + item.type + '" rel="' + item.media_content;
			}
			content += '">';
			if (item.type === 'twitter') {
				content += item.content.twitterUrl().twitterUsername().twitterHashTag();
			} else if (item.type === 'blogs') {
				content += '<a href="' + item.permalink + '" target="_blank">' + item.content + '</a>';
			} else {
				content += item.content;
			}
			content += '</div>';
			if (item.thumbnail.source !== null) {
				content += '<div class="thumb';
				if (item.media_content !== null) {
					content += ' ' + item.type + '" rel="' + item.media_content;
				}
				content += '"><img src="' + item.thumbnail.source + '" width="40" alt="" /></div>';
			}
			content += '<div class="meta">';
			content += '<span class="author">' + lit('gan', 'by') + ' <a href="/go/' + item.author_permalink + '" target="_blank">' + item.author + '</a></span> ';
			if (updateConf.type === null) {
				content += '<span class="type">' + lit('yn', 'in') + ' <a href="/' + item.type + '">' + item.type + '</a></span> ';
			}
			content += '<span class="datestamp" rel="' + itemDate + '">' + item.dt_published + '.</span> ';
			content += '<span class="permalink"><a href="/go/' + item.permalink + '" target="_blank" title="' + lit('Cynnwys gwreiddiol', 'Original content') + '">§</a>.</span>';
			content += '</div>';
			content += '</li>';
		});
		jQuery('#content ul').prepend(content);
		if (updateConf.fadeIn) {
			jQuery('#content li.' + updateConf.highlightClass).fadeIn(2000, function() {
				jQuery('#content li.' + updateConf.highlightClass).removeClass(updateConf.highlightClass);
			});
		} else {
			setTimeout(function() {
				jQuery('#content li.highlight').removeClass('highlight');
			}, 1000);
		}
		jQuery('#content li:gt(40)').remove();
		updateTimestamps();
		if (updateConf.displayLoadingText) {
			setLoadingStatus(loadingStatus);
		}
		fancyStuff();
		updateConf.is_updating = false;
	});
};


// ----- String functions for twitter by Simon Whatley - http://www.simonwhatley.co.uk/examples/twitter/prototype/
String.prototype.twitterUrl = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/gim, function(url) {
		return '<a href="'+ url +'" target="_blank">'+ url +'</a>';
		return url.link(url);
	});
};
String.prototype.twitterUsername = function() {
	return this.replace(/@[A-Za-z0-9_]{1,15}/gim, function(u) {
		var username = u.replace("@","")
		return '<a href="http://twitter.com/'+ username +'" target="_blank">'+ u +'</a>';
		return u.link("http://twitter.com/"+username);
	});
};
String.prototype.twitterHashTag = function() {
	return this.replace(/#[A-Za-z0-9-_]+/gim, function(t) {
		var tag = t.replace("#","%23")
		return '<a href="http://search.twitter.com/search?q='+ tag +'" target="_blank">'+ t +'</a>';
		return t.link("http://search.twitter.com/search?q="+tag);
	});
};


// ----- Timestamp functions
var updateTimestamps = function() {
	jQuery('#content li span.datestamp[rel]').each(function() {
		var timestamp = parseInt(jQuery(this).attr('rel'), 10);
		var now = new Date();
		now = now.getTime();
		now = Math.floor(now / 1000);
		jQuery(this).html('').html(formatTimestamp(now, timestamp));
	});
};
var formatTimestamp = function(now, timestamp) {
	var seconds = now - timestamp;
	if (seconds < 60) {
		return lit('llai na munud yn ôl', 'less than a minute ago');
	}
	var minutes = Math.floor(seconds / 60);
	if (minutes === 1) {
		return lit('tua munud yn ôl', 'about a minute ago');
	} else if (minutes < 60) {
		return lit('tua ' + minutes + ' munud yn ôl', 'about ' + minutes + ' minutes ago');
	}
	var hours = Math.floor(minutes / 60);
	if (hours === 1) {
		return lit('tua awr yn ôl', 'about an hour ago');
	} else if (hours < 24) {
		return lit('tua ' + hours + ' awr yn ôl', 'about ' + hours + ' hours ago');
	}
	var days = Math.floor(hours / 24);
	if (days === 1) {
		return lit('ddoe', 'yesterday');
	}
	return lit(days + ' diwrnod yn ôl', days + ' days ago');
};


// ----- If we pass a jQuery test (selector exists), execute callback(s)
var assert = function() {
	var selector = arguments[0];
	if (jQuery(selector).length) {
		for (var i = 1; i < arguments.length; ++i) {
			arguments[i]();
		}
		return true;
	}
	return false;
};


// ----- Execute when the DOM is ready.
var onready = function() {
	for (var i = 0; i < arguments.length; ++i) {
		jQuery(document).ready(arguments[i]);
	}
};


// ----- Returns value if not undefined, otherwise default. if default not set, returns false
var getValue = function(value, def) {
	if (typeof(value) !== 'undefined') {
		return value;
	}
	if (typeof(def) !== 'undefined') {
		return def;
	}
	return null;
};


// ----- Returns true if not undefined, otherwise false
var isset = function(value) {
	if (typeof(value) !== 'undefined') {
		return true;
	}
	return false;
};


// ----- Track Pageloads
var track = function() {
	jQuery.getScript('http://include.reinvigorate.net/re_.js', function() {
		re_("22926-rq2s85w4m4");
	});
};


// ---- External links
var externalLinks = function() {
	jQuery('a.external').attr('target', '_blank').removeClass('external');
};


// ---- Language
var lit = function() {
	var language;

	onready(function() {
		language = jQuery('html').attr('xml:lang');
	});

	return function(cy, en) {
		if (language === 'en') {
			return getValue(en, 'en');
		}
		return getValue(cy, 'cy');
	};
}();


// ----- Functions to execute each page load
onready(
	externalLinks,
	fancyStuff,
	track,
	function() {
		assert('.nav .ustream', fancyStream);
	},
	function() {
		updateConf.interval_obj = setInterval(updateStream, (updateConf.interval_time * 1000));
	}
);