//Preload images
Event.observe(window, 'load', function() {
	preload('/images/screenshot-viewer/sv-loading.png');
	preload('/images/screenshot-viewer/sv-vertical.png');
	preload('/images/screenshot-viewer/sv-horizontal.png');
	preload('/images/screenshot-viewer/sv-dimmer.png');
	preload('/images/screenshot-viewer/sv-button-close.png');
	preload('/images/screenshot-viewer/sv-button-left.png');
	preload('/images/screenshot-viewer/sv-button-left-disabled.png');
	preload('/images/screenshot-viewer/sv-button-right.png');
	preload('/images/screenshot-viewer/sv-button-right-disabled.png');
	preload('/images/screenshot-viewer/sv-thumbnail-bg-vertical.png');
	preload('/images/screenshot-viewer/sv-thumbnail-bg-horizontal.png');
	preload('/images/screenshot-viewer/sv-first.png');
	preload('/images/screenshot-viewer/sv-last.png');
});
function preload(src) { var a = new Image(); a.src = src; return a; }
function track(u) { try { pageTracker._trackPageview(u); } catch(e) {} }

String.prototype.padLeft = function(s, l) { var o = this; while(o.length < l) { o = s + o; }; return o; }

screenshotRotator = Object.extend([], {
	duration: 10,
	currentIndex: 0,
	addRange: function(appName, minN, maxN) { for (var x = minN; x < maxN + 1; x++) { this.push('/images/screenshots/' + appName + '/152/' + x.toString().padLeft('0', 3) + '.jpg'); } },
	start: function() { this.rotate.bind(this).delay(this.duration); this.preloadNext(); },
	rotate: function(effect) {
		this.effect = new Effect.Opacity('screenshot', {from:1, to:0, duration:0.3, afterFinish:function(effect) {
			if (this.currentIndex === this.length - 1) { this.currentIndex = 0; } else { this.currentIndex++; }
			$('screenshot-image').src = this[this.currentIndex];
			this.effect = new Effect.Opacity('screenshot', {from:0, to:1, duration:0.3, afterFinish:function(effect) {
				this.rotate.bind(this).delay(this.duration);
				this.preloadNext();
			}.bind(this)});
		}.bind(this)});
	},
	preloadNext: function() { var a = new Image(); a.src = this[this.currentIndex === this.length - 1 ? 0 : this.currentIndex + 1]; }
});

screenshotViewer = {
	
	animatedTransitions: true,
	
	open: function(src, totalImages, firstImageNum) {
		track('screenshot-viewer/opened-with/' + src);
		this.path = src.replace(/(.*?\/)\d.*/, '$1') + '320/';
		this.thumbnailPath = src.replace(/(.*?\/)\d.*/, '$1') + '100/';
		this.firstImageNum = firstImageNum || 1;
		this.lastImageNum = this.firstImageNum + totalImages;
		this.images = $R(this.firstImageNum, totalImages - this.firstImageNum).collect(function(v) { return {
			path: this.path + v.toString().padLeft('0', 3) + '.jpg',
			thumbnailPath: this.thumbnailPath + v.toString().padLeft('0', 3) + '.jpg',
			image: null,
			thumbnail: null,
			imageNum: v,
			preload: function() { if (this.image) { return; } this.image = new Image(); this.image.src = this.path; },
			preloadThumbnail: function() { if (this.thumbnail) { return; } this.thumbnail = new Image(); this.thumbnail.src = this.thumbnailPath; }
		}; }.bind(this));
		$('sv').innerHTML = '<div id="sv-loading"><img src="/images/loading.gif" width="31" height="31" alt="Loading, please wait&hellip;" /><div id="sv-progress"><div id="sv-progress-value"></div></div></div>';
		$('sv').style.height = $('outer-wrap').getHeight() + 'px';
		$('sv').appear({duration: 0.2, afterFinish: function() {
			Effect.ScrollTo('sv', {duration: 0.1});
		}});
		this.updatePageWidth.bind(this)();
		this.getCurrentImages.bind(this)(parseInt(src.replace(/.*(\d){3}\..{3}$/i, '$1'), 10));
		this.preloadImages.bind(this)();
	},
	
	getCurrentImages: function(imageNum) {
		this.currentImage = this.images.find(function(v) { return v.imageNum === imageNum; }.bind(this));
		this.previousImage = this.images.find(function(v) { return v.imageNum === imageNum - 1; }.bind(this)) || null;
		this.nextImage = this.images.find(function(v) { return v.imageNum === imageNum + 1; }.bind(this)) || null;
	},
	
	preloadImages: function() {
		this.images.invoke('preloadThumbnail');
		this.images.invoke('preload');
		this.preloadCheck.bind(this)();
	},
	
	preloadCheck: function() {
		var loadingCount = this.images.findAll(function(v) { return (v.image && !v.image.width) || v.thumbnail && !v.thumbnail.width; }).length;
		if (loadingCount) {
			$('sv-progress-value').style.width = Math.max(0, Math.floor((((this.images.length * 2) - loadingCount) / (this.images.length * 2)) * $('sv-progress').getWidth()) - 2) + 'px';
			this.preloadCheck.bind(this).delay(0.05);
		} else {
			this.showImages.bind(this)();
		}
	},
	
	navigate: function(target) {
		this.getCurrentImages(this.currentImage.imageNum + target);
		if (this.animatedTransitions) {
			$$('#sv-screenshot img').invoke('fade', {duration: 0.2, afterFinish: screenshotViewer.showImages.bind(screenshotViewer)});
			$$('.sv-nav-screenshot img').invoke('fade', {duration: 0.2});
		} else {
			this.showImages.bind(this)();
		}
	},
	
	showImages: function() {
		track('screenshot-viewer/' + this.currentImage.path);
		if (this.currentImage.image.width === 320) { $('sv').addClassName('vertical'); $('sv').removeClassName('horizontal'); } else { $('sv').addClassName('horizontal'); $('sv').removeClassName('vertical'); }
		var style = this.animatedTransitions ? ' style = "display: none;"' : '';
		$('sv').innerHTML = [
			'<a id="sv-close" href="javascript:void(0);" onclick="screenshotViewer.close();" title="Close the screenshot viewer"><img src="/images/screenshot-viewer/sv-button-close.png" width="155" height="32" alt="Close the screenshot viewer" /></a>',
			'<div id="sv-content" class="sv-vertical">',
				'<div id="sv-left" class="sv-nav-panel' + (this.previousImage ? ' sv-nav-panel-active" onclick="javascript:screenshotViewer.navigate(-1);"' : '') + '">',
					'<div id="sv-left-button" class="sv-nav-button">',
						this.previousImage ? '<img src="/images/screenshot-viewer/sv-button-left.png" width="40" height="40" alt="Move to the previous screenshot" />' : '<img src="/images/screenshot-viewer/sv-button-left-disabled.png" width="40" height="40" alt="You are at the first screenshot" />',
					'</div>',
					'<div id="sv-left-screenshot" class="sv-nav-screenshot ' + (!this.previousImage || this.previousImage.thumbnail.width == 100 ? 'vertical' : 'horizontal') + '">',
						'<div class="sv-nav-screenshot-inner">',
							this.previousImage ? '<img src="' + this.previousImage.thumbnailPath + '" width="' + this.previousImage.thumbnail.width + '" height="' + this.previousImage.thumbnail.height + '" alt="Move to the previous screenshot"' + style + ' />' : '<img src="/images/screenshot-viewer/sv-first.png" width="100" height="150" alt="You are at the first screenshot"' + style + ' />',
						'</div>',
					'</div>',
				'</div>',
				'<div id="sv-screenshot">',
					this.previousImage ? '<div id="sv-screenshot-press-left" class="sv-screenshot-press" onclick="javascript:screenshotViewer.navigate(-1);"></div>' : '',
					this.nextImage ? '<div id="sv-screenshot-press-right" class="sv-screenshot-press" onclick="javascript:screenshotViewer.navigate(1);"></div>' : '',
					'<img src="' + this.currentImage.path + '" width="' + this.currentImage.image.width + '" height="' + this.currentImage.image.height + '" alt="Full size screenshot"' + style + ' />',
				'</div>',
				'<div id="sv-right" class="sv-nav-panel' + (this.nextImage ? ' sv-nav-panel-active" onclick="javascript:screenshotViewer.navigate(1);"' : '') + '">',
					'<div id="sv-right-screenshot" class="sv-nav-screenshot ' + (!this.nextImage || this.nextImage.thumbnail.width == 100 ? 'vertical' : 'horizontal') + '">',
						'<div class="sv-nav-screenshot-inner">',
							this.nextImage ? '<img src="' + this.nextImage.thumbnailPath + '" width="' + this.nextImage.thumbnail.width + '" height="' + this.nextImage.thumbnail.height + '" alt="Move to the next screenshot"' + style + ' />' : '<img src="/images/screenshot-viewer/sv-last.png" width="100" height="150" alt="You are at the last screenshot"' + style + ' />',
						'</div>',
					'</div>',
					'<div id="sv-right-button" class="sv-nav-button">',
						this.nextImage ? '<img src="/images/screenshot-viewer/sv-button-right.png" width="40" height="40" alt="Move to the next screenshot" />' : '<img src="/images/screenshot-viewer/sv-button-right-disabled.png" width="40" height="40" alt="You are at the last screenshot" />',
					'</div>',
				'</div>',
			'</div>'
		].join('');
		this.updatePageWidth.bind(this)();
		
		if (this.animatedTransitions) { $$('#sv-screenshot img, .sv-nav-screenshot img').invoke('appear', {duration: 0.2}); }
	},
	
	updatePageWidth: function() { $('outer-wrap').style.minWidth = $('sv').getStyle('min-width');; },
	
	close: function() {
		$('sv').fade({ duration: 0.2, afterFinish: function() {
			$('sv').innerHTML = '';
			$('outer-wrap').style.minWidth = '';
		}});
	}
};

function getPrice(tier, countryCode) {
	tiers = [
		[0,0,0,0,0,0],
		[0.99,0.99,0.79,0.59,115,1.19],
		[1.99,1.99,1.59,1.19,230,2.49],
		[2.99,2.99,2.39,1.79,350,3.99],
		[3.99,3.99,2.99,2.39,450,4.99],
		[4.99,4.99,3.99,2.99,600,5.99],
		[5.99,5.99,4.99,3.49,700,7.99],
		[6.99,6.99,5.49,3.99,800,8.99],
		[7.99,7.99,5.99,4.99,900,9.99],
		[8.99,8.99,6.99,5.49,1000,11.99],
		[9.99,9.99,7.99,5.99,1200,12.99],
		[10.99,10.99,8.99,6.49,1300,13.99],
		[11.99,11.99,9.99,6.99,1400,14.99],
		[12.99,12.99,10.49,7.49,1500,15.99],
		[13.99,13.99,10.99,7.99,1600,16.99],
		[14.99,14.99,11.99,8.99,1700,17.99]
	];
	var code = countryCode ? countryCode.toUpperCase() : google.loader.ClientLocation ? google.loader.ClientLocation.address.country_code.toUpperCase() : 'US';
	if (tier == 0) {
		return {price: 0, text: 'Free!', image: 'price-free'};
	} else if (code === 'US') {
		return {price:tiers[tier][0], text:(tiers[tier][0] >= 1 ? '$' : '') + tiers[tier][0].toString().replace(/0\./, '') + (tiers[tier][0] < 1 ? '&cent;' : '') + ' (US)', image:'price-' + tiers[tier][0] + '-us.png'};
	} else if (code === 'CA') {
		return {price:tiers[tier][1], text:(tiers[tier][1] >= 1 ? '$' : '') + tiers[tier][1].toString().replace(/0\./, '') + (tiers[tier][1] < 1 ? '&cent;' : '') + ' (CA)', image:'price-' + tiers[tier][1] + '-ca.png'};
	} else if (['AD','AL','AT','BA','BE','BG','BY','CH','CZ','DE','DK','EE','ES','FI','FO','FR','GI','GR','HR','HU','IE','IS','IT','LI','LT','LU','LV','MC','MD','MK','MT','NL','NO','PL','PT','RO','SE','SI','SJ','SK','SM','UA','VA'].include(code)) {
		return {price:tiers[tier][2], text:(tiers[tier][2] >= 1 ? '&euro;' : '') + tiers[tier][2].toString().replace(/0\./, '') + (tiers[tier][2] < 1 ? '&cent;' : '') + ' (EU)', image:'price-' + tiers[tier][2] + '-eu.png'};
	} else if (code === 'GB') {
		return {price:tiers[tier][3], text:(tiers[tier][3] >= 1 ? '&pound;' : '') + tiers[tier][3].toString().replace(/0\./, '') + (tiers[tier][3] < 1 ? 'p' : '') + ' (UK)', image:'price-' + tiers[tier][3] + '-uk.png'};
	} else if (code === 'JP') {
		return {price:tiers[tier][4], text:'&yen;' + tiers[tier][4].toString().replace(/0\./, '') + ' (JP)', image:'price-' + tiers[tier][4] + '-jp.png'};
	} else if (code === 'AU') {
		return {price:tiers[tier][5], text:(tiers[tier][5] >= 1 ? '$' : '') + tiers[tier][5].toString().replace(/0\./, '') + (tiers[tier][5] < 1 ? '&cent;' : '') + ' (AU)', image:'price-' + tiers[tier][5] + '-au.png'};
	} else {
		return {price:tiers[tier][0], text:(tiers[tier][0] >= 1 ? '$' : '') + tiers[tier][0].toString().replace(/0\./, '') + (tiers[tier][0] < 1 ? '&cent;' : '') + ' (US)', image:'price-' + tiers[tier][0] + '-us.png'};
	}
}

function twitterCallback2(o) {
	$('recent-tweet-list').innerHTML = o.collect(function(v) {
		return ['<li>',
			'<span>' + v.text.replace(/\bwww\.\w.\w/ig, 'http://$&').replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, '<a href="$1">$1</a>').replace(/\B@([_a-z0-9]+)/ig, '@<a href="http://twitter.com/$1">$1</a>') + '</span>',
			'<a href="http://twitter.com/' + v.user.screen_name + '/statuses/' + v.id + '" title="Tweet Permalink" class="tweet-date">' + relativeTime(v.created_at) + '</a>',
		'</li>'].join('');
	}).join('');
}

function relativeTime(t) {
	var v = t.split(' ');
	t = v[1] + ' ' + v[2] + ', ' + v[5] + ' ' + v[3];
	var p = Date.parse(v);
	var r = (arguments.length > 1) ? arguments[1] : new Date();
	var d = parseInt((r.getTime() - p) / 1000, 10);
	d = d + (r.getTimezoneOffset() * 60);
	if (d < 60) { return 'less than a minute ago'; }
	else if (d < 120) { return 'about a minute ago'; }
	else if (d < (60 * 60)) { return (parseInt(d / 60, 10)).toString() + ' minutes ago'; }
	else if (d < (120 * 60)) { return 'about an hour ago'; }
	else if (d < (24 * 60 * 60)) { return 'about ' + (parseInt(d / 3600, 10)).toString() + ' hours ago'; }
	else if (d < (48 * 60 * 60)) { return '1 day ago'; }
	else { return (parseInt(d / 86400, 10)).toString() + ' days ago'; }
}
