var Advancr = {
	skip: 10,
	base_url: null,
	filename: null,
	number_length: 0,
	images: [],
	image: null,
	slide_timer: null,
	slider: null,
	thumb_wrapper: null,
	innerwidth: 0,
	innerheight: 0,
	
	begin_session: function (form)
	{
		if (!this.validate(form)) return;
	
		// 150 for padding and stuff
		this.innerwidth = window.innerWidth - 150;	
		this.innerheight = window.innerHeight - 50;	
		
		// URL Cleanup
		form.url.value = form.url.value.replace(/%20/gi, " ");
		
		// Break appart image URL into BASE and FILENAME
		this.base_url = form.url.value.substr(0, form.url.value.lastIndexOf('/')+1);
		this.filename = form.url.value.replace(this.base_url, "");

		// Find the image number.
		this.number = this.filename.match(/[0-9]+/g);
		
		console.log(this.filename+", "+this.number);
		// Replace the number in the FILENAME with '[[NumberHere]]' that
		// we can use later to replace again with the appropriate number
		this.filename = this.filename.replace(this.number, "[[NumberHere]]");
		
		// Determine the padding (usually in 0's) of the FILENAME
		this.number_length = this.number.toString().length;
		
		// Parse that number down to the int value. i.e '001' = 1
		this.number = parseInt(this.number);
		
		// Record the first image of the series. (user could start from say, number 005);
		this.beginning_number = this.number;
		
		// Grab the DOM image for manipulation
		this.image = document.getElementById('image');

		// Show & hide appropriate layouts.
		document.getElementById('session').style.display = '';
		document.getElementById('setup').style.display = 'none';
		
		// Setup slider (current image indicator)
		this.slider = document.getElementById('active');
		this.thumb_wrapper = document.getElementById('thumb_wrapper');
		
		// Try the new preloading first
		// this.preload_images(this.number);
		// set off the main loop for displaying images.
		this.load_images(this.number);
	},
	
	load_images: function (number)
	{
		var self = this;
		
		if (this.skip > 0 && this.images.length < 50) {
		
			var image = this.images[this.images.push(new Advancr.Image(this.base_url, this.filename, number))-1];
			
			image.load(
				// Error
				function() {
					self.skip--;
					image.destroy();
				},
			
				// Success
				function () {
					if (image.img.height < 48) {
						image.img.style.width = null;
						image.img.style.height = "48px";
					}
					
					
					setTimeout(function ()
					{
						self.load_images(number+1);
					}, 20);
					
					if (number == Advancr.beginning_number)
						image.show();
				}
			);

		}
		
//		new Ajax.Request('exists.php', {method: 'get', params: 'url='+make_url(num+1), on404: "skipper++; new_thumb("+parseInt(num+1)+", true)", on200: "new_thumb("+parseInt(num+1)+")", async: true});

	},

	validate: function (form) {
		//([a-z0-9]+\.)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}(\/[a-zA-Z0-9]+)*\/[a-zA-Z0-9]\.[a-zA-Z0-9]
		if (form.url.value.match(new RegExp("^http:\/\/")))
			return true;
		else
			return false;
	},
	
	pad_number: function (number, padding)
	{
		while (number.toString().length < padding)
			number = "0"+number;
		return number;
	},
	
	slide_frame_to: function (new_pos)
	{
		clearTimeout(this.slide_timer);
		
		cur_pos = Math.max(0, this.slider.offsetTop);
//		console.log("cur_pos: "+cur_pos);
		
		fraction = Math.ceil(Math.abs(cur_pos-new_pos) / 5);
//		console.log("fraction: "+fraction);
		
		if (new_pos < cur_pos && fraction > 1)
		{
			updated_pos = fraction-cur_pos;
			this.slider.style.top = updated_pos+"px";
		}
		else if (new_pos > cur_pos && fraction > 1)
		{
			updated_pos = fraction+cur_pos;
			this.slider.style.top = updated_pos+"px";
		} else {
			this.slider.style.top = new_pos+"px";
			return;
		}
		
		this.slide_timer = setTimeout(function ()
		{
			Advancr.slide_frame_to(new_pos);
		}, 20);
		
//		this.reposition_thumbs(cur_pos);
	},
	
	reposition_thumbs: function (offset)
	{
		thumbs = document.getElementById("thumbs");
		thumb_wrapper = document.getElementById("thumb_wrapper");
		
		if (thumb_wrapper.offsetHeight && (offset+28) > (thumb_wrapper.offsetHeight/2) && (thumb_wrapper.offsetHeight/2) + (offset+28) < thumbs.offsetHeight)
			thumbs.style.marginTop = (thumb_wrapper.offsetHeight/2) - (offset+28)+"px";
	},
	
	next: function()
	{
		this.number++;
		var image = this.images[(this.number - this.beginning_number)];
		image.show();
	},
	
	previous: function()
	{
		this.number--;
		var image = this.images[(this.number - this.beginning_number)];
		image.show();
	}
};

Advancr.Image = function (base_url, filename, number)
{
	this.number = number;
	this.url = base_url+filename.replace("[[NumberHere]]", Advancr.pad_number(number, Advancr.number_length));
	this.li = document.getElementById('thumbs').appendChild(document.newElement('li', null, "thumb_"+number));
};

Advancr.Image.prototype = {

	width: null,
	height: null,
	
	build_url: function (num) {
		this.number = num;
		return base_url + filename + pad_number(parseInt(num), number_padding) + extension;
	},

	load: function (do_error, do_success) {
	
		// Self reference
		var self = this;
		
	//	document.getElementById("data").innerText = Math.ceil(loaded/images.length*100)+"%";
	
		var image = new Image();
		image.onload = function()
		{
			// Record true width/height
			self.width = image.width;
			self.height = image.height;
		}
		image.src = this.url;
		
		this.img = this.li.appendChild(document.newElement('img'));
		
		// If the image fails to load
		this.img.onerror = function () {
			do_error();
		}
		
		// When the image exists and finishes loading
		this.img.onload = function () {
			do_success();
		}
		
		// When thumbnail is clicked ...
		this.img.onclick = function(){
			self.show();
		};
		
		this.img.src = this.url;
	
	//	reposition_thumbs((55*(current_number))-56);
	},

	show: function ()
	{
		var self = this;
		Advancr.number = this.number;
		
		var top = this.img.parentNode.offsetTop;
		Advancr.slide_frame_to(top);
	
		Advancr.image.onload = function()
		{
			self.resize(Advancr.image);
		}
		
		Advancr.image.src = this.url;
	
		Advancr.reposition_thumbs(top);
	},
	
	destroy: function ()
	{
		this.li.parentNode.removeChild(this.li);
	},
	
	resize: function(image)
	{
		if (this.width/this.height < Advancr.innerwidth/Advancr.innerheight)
		{
			// shrink height to fit
			var newH = Math.min(this.height, Math.min(600, Advancr.innerheight));
			image.width = this.width * (newH/this.height);
			image.height = newH;
		} else
		{
			// shrink width to fit
			image.width = Math.min(this.width, Math.min(800, Advancr.innerwidth));
		}
		
		Advancr.thumb_wrapper.style.height = image.height+"px";
	},
};

//////////////////////////// UTILITIES ///////////////////////////////////////
String.prototype.trim = function () {
	return this.replace(/^\s+/, '').replace(/\s+$/, '');
};

document.newElement = function (type, className, id)
{
	var layer = document.createElement(type);
	if (className) {
		layer.setAttribute('class', className);
		layer.className = className;
	}
	if (id) {
		layer.setAttribute('id', id);
		layer.id = id;
	}
	return layer;
}

function init()
{
	document.body.onkeydown = function(event)
	{
		switch (event.keyCode)
		{
			case 39: Advancr.next();
				break;
			case 37: Advancr.previous();
				break;
		}	
	}
}
