$(function(){
	var currentLocation = "";
	
	var autoRotate = true;
	var rotationTime = 3*1000;
	var showTimer = false;
	
	var fadeTime = 350;
	var resizeTime = 400;
	
	var enforceMaxImageSizeAt = 640; // keep images from expanding excessively
	var maxImageSizePad = 200;
	
	var log = function($txt) {
		//if(true) return;
		if('console' in window) {
			window.console.log($txt);
		}
	};
	
	var $wnd = $(window);
	var $doc = $(document);
	
	var base = ''+window.location;
	var q = base.indexOf('?');
	if(q>=0) {
		base = base.substr(0,q);
	}
	log("BASE: " + base);
	
	var animateTimer = function() {
		var $imgshow = $('.bdy .imgshow');
		var $img = $imgshow.find('img:first');
		var showLine = function() {
			var w = $img.width();
			var start = function() {
				var $greenLine = $imgshow.find('.greenLine');
				$greenLine.stop().css({width:w,opacity:1,left:$img.css('marginLeft')});
				setTimeout(function(){
					$greenLine.animate({width:0,left:w/2},rotationTime-(resizeTime+fadeTime),'linear');
				},resizeTime+fadeTime);
			}
			start();
		}
		if($img.get(0).complete) {
			showLine();
		} else {
			$img.load(showLine);
		}
	}
	
	var imgRotate;
	var startRotation = function() {
		imgRotate = function() {
			if(imgRotate) {
				var $imgshow = $('.bdy .imgshow');
				var $nextLink = $imgshow.find('a+a');
				showImage($nextLink.attr('href'),function() {
					if(showTimer) animateTimer();
					setTimeout(imgRotate, rotationTime);
				});
			}
		};
		if(showTimer) animateTimer();
		if(autoRotate) setTimeout(imgRotate, rotationTime);
	};
	
	var stopRotation = function() {
		imgRotate = null;
	};
	
	var preload = function($imgshow, href) {
		var src = /.*i=([^&]*).*/.exec(href);
		if(src && src.length > 1) {
			log("PRELOAD: " + href + " to: " + src[1]);
			var url = $imgshow.find('img').attr('src').replace(/i=([^&]*)/,'i='+src[1]);
			setTimeout(function(){
				var img = new Image();
				log("PRELOADING: " + url);
				img.src = url;
				log("PRELOADING COMPLETE: " + url);
			},10);
		}
	}
	
	var replaceSection = function($data, s) {
		var $s = $(s);
		var $n = $data.find(s);
		var animate = false;
		if(animate) {
			var out = $s.css('opacity')>0?100:0;
			$s.animate({opacity:0},out,function(){
				$n.css({opacity:0})
				$s.replaceWith($n);
				$n.animate({opacity:1},125);
			});
		} else {
			$s.replaceWith($n);
		}
	}
	
	var replaceSections = function() {
		var $data = arguments[0];
		for(var i = 1; i < arguments.length; i++) {
			replaceSection($data, arguments[i]);
		}
	}

	var showImage = function(href,fn) {
		currentLocation = window.location.hash = href;
		var $currImgshow = $('.bdy .imgshow');
		var $currImg =  $currImgshow.find('img:first');
		if($currImg.size()>0) {
			$currImg.animate({opacity:0},250);
			$currImg.next().removeAttr('href')
				.next().removeAttr('href');
		}
		$.ajax({
			url: href,
			error: function(jqXHR, textStatus, errorThrown) {
				log("ERROR: " + textStatus);
			},
			success: function(data, textStatus, jqXHR) {
				var $data = $(data);
				var $imgshow = $data.find('.imgshow');
				var $img = $imgshow.find('img:first');
				var prevLink = $img.next().attr('href');
				var nextLink = $img.next().next().attr('href');
				log("SUCCESS: " + textStatus + " data: " + $img.attr('src'));
				if($currImg.size()>0) {
					var animatesize = autoRotate;
					var padh = 16;
					var padw = 16;
					if(animatesize) {
						$currImgshow.css({
							width: $currImgshow.width(),
							height: $currImgshow.height()
						});
					}
					var out = $currImg.css('opacity')>0?100:0;
					$currImg.animate({opacity:0},out,function(){
						$currImgshow.css({background:'transparent url(progress.gif) center center no-repeat'});
						$currImg.get(0).onload = function() { // only want the last onload, no jquery rebinding
							if(animatesize) {
								$currImgshow.animate({
									width: $currImg.width()+padw,
									height: $currImg.height()+padh
								},{ duration: resizeTime,
									complete:function() {
										$currImgshow.css({
											width: 'auto',
											height: 'auto'
										});
										$currImg.animate({opacity:1}, fadeTime);
										if(fn) {
											fn();
										}
									}
								});
							} else {
								$currImg.animate({opacity:1}, 350);
								if(fn) {
									fn();
								}
							}
							preload($imgshow, prevLink);
							preload($imgshow, nextLink);
							$currImgshow.css({background:'none'});
						}
						$currImg.attr('src',$img.attr('src'));
						$currImg.next().attr('href', prevLink)
							.next().attr('href', nextLink);
						$currImgshow.find('abbr').html($imgshow.find('abbr').html());
					});
				} else {
					var $bdy = $('.bdy');
					$bdy.animate({opacity:0},250,function(){
						$bdy.replaceWith($bdy = $data.find('.bdy').css({opacity:0}));
						$bdy.animate({opacity:1},125);
					});
				}
				replaceSections($(data),'.links','.footer');
			}
		});
	}
	
	var showGallery = function(href) {
		currentLocation = window.location.hash = href;
		$('.bdy').animate({opacity:0},250);
		$.ajax({
			url: href,
			error: function(jqXHR, textStatus, errorThrown) {
				log("ERROR: " + textStatus);
			},
			success: function(data) {
				replaceSections($(data),'.bdy','.links','.footer');
			}
		});
	}
	
	var showPage = function(href) {
		stopRotation(); // Any page load stops auto-rotation
		currentLocation = window.location.hash = href;
		$('.bdy').animate({opacity:0},250);
		$.ajax({
			url: href,
			error: function(jqXHR, textStatus, errorThrown) {
				log("ERROR: " + textStatus);
			},
			success: function(data) {
				log(data);
				replaceSections($(data),'.bdy','.links','.footer');
			}
		});
	}
	
	$doc.delegate('a', 'click', function(){
		var $this = $(this);
		var href = $this.attr('href');
		if(/i=/.test(href)) {
			stopRotation(); // Any click stops auto-rotation
			showImage(href);
			return false;
		}
		if(/g=/.test(href)) {
			stopRotation(); // Any click stops auto-rotation
			showGallery(href);
			return false;
		}
		if(/p=/.test(href)) {
			stopRotation(); // Any click stops auto-rotation
			showPage(href);
			return false;
		}
	});
	
	$doc.delegate('input[type=submit]', 'click', function(){
		var $this = $(this);
		var $form = $this.parents('form:first');
		$.post($form.attr('action'), $form.serialize(), function(data){
			log(data);
			replaceSections($(data),'.bdy');
			setTimeout(function(){
				$('.bdy form > i')
					.animate({opacity:0},2000);
			},3000);
		});
		return false;
	});
	
	var maxHeightElement = function(h) {
		if($wnd.height()>enforceMaxImageSizeAt) {
			return $('<style type="text/css">.imgshow img{max-height:'+h+'px !important}</style>');
		}
		return $('<style type="text/css"></style>');
	}
	
	var $sz = maxHeightElement($wnd.height()-maxImageSizePad).appendTo('head');

	$wnd.resize(function(){
		$sz.replaceWith($sz = maxHeightElement($wnd.height()-maxImageSizePad));
	});
	
	/**
	 * Returns false if changed
	 */
	var checkLocation = function() {
		var h = window.location.hash;
		if(h) {
			h = h.replace(/.*\#/,'')
			if(h != 'undefined' && h != currentLocation) {
				if(/i=/.test(h)) {
					showImage(h);
				}
				else if(/g=/.test(h)) {
					showGallery(h);
				}
				else if(/p=/.test(h)) {
					showPage(h);
				}
				currentLocation = h; // This should already be set
				return false;
			}
		}
		setTimeout(checkLocation,250);
		return true;
	};
	if(checkLocation()) {
		startRotation();
	}
});

