
// all hail Firebug
var cl = window.console ? console.log : function(){};

var isIe6 = /MSIE 6/i.test(navigator.userAgent);

// http://www.jdempster.com/2007/07/14/jquery-disable-text-select/
(function($) {
    if ($.browser.mozilla) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).css({
                    'MozUserSelect' : 'none'
                });
            });
        };
    } else if ($.browser.msie) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('selectstart', function() {
                    return false;
                });
            });
        };
    } else {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).mousedown(function() {
                    return false;
                });
            });
        };
    }
})(jQuery);


var Preloader = function(params) {
	if(!params) params = {};
	for(var i in params) {
		this[i] = params[i];
	}
	this.init();
};
Preloader.prototype = {
	img:     null,
	loaded:  {},
	started: false,

	onStart: function() {},
	onStop: function() {},

	init: function() {
		this.img = $('<img>');
	},

	stop: function() {
		this.img.remove();
		this.init();
		this.onStop();
	},

	start: function(url, callback) {
		this.stop();
		this.started = true;
		this.onStart();
		var p = this;
		this.img.bind('load error unload abort', function() {
			if(p.img.attr('src') != url) return;
			if(!p.loaded[url]) {
				p.loaded[url] = p.img.clone().get(0); // marking a successfull load
				$('#preloaderz').append(p.loaded[url]);
			}
			if(p.started) {
				p.onStop();
				if(callback) callback();
			}
			p.started = false;
		}).attr('src', url);
	}
};


var Gallery = function(params) {
	if(!params) params = {};
	for(var i in params) {
		this[i] = params[i];
	}
	this.init();
};
Gallery.prototype = {

	img: null,
	pageSpan: null,
	imgs: [],
	page: 1,
	debug: false,

	currImg: null,

	preloader: null,
	hiddenPreloader: null,

	init: function() {
		if(this.debug) {
			// debug mode: adding crap to urls to prevent image cache
			var debugKey = '?'+Math.random();
			for(var i = 0, n = this.imgs.length; i < n; i++) {
				this.imgs[i].file += debugKey;
			}
		}
		this.currImg = this.getImg(this.page);
		// this.hiddenPreloader = new Preloader();
	},

	// public
	next: function(noAnimation, onSwitch) {
		this.switchImg(false, noAnimation, onSwitch);
	},
	prev: function(noAnimation, onSwitch) {
		this.switchImg(true, noAnimation, onSwitch);
	},
	open: function(n, noAnimation, onSwitch) {
		n = parseInt(n);
		if(this.getImg(n)) {
			this.page = n;
			this.setupImg(n, noAnimation, onSwitch);
		}
	},
	getImg: function(page) {
		if(!arguments.length) return this.currImg;
		return this.imgs[page - 1] || false;
	},

	// protected (OK to redefine)
	paintImg: function(n) {
		this.currImg = this.getImg(n);
		document.location.hash = n;
		this.img.attr('src', this.currImg.file);
		if(this.currImg.link) {
			this.img.closest('a').attr('href', this.currImg.link);
		}
	},
	paintNavigation: function(n) {
		this.pageSpan.text(n);
		// changing links to next/prev images
		this.switchPageLink($('.image-content a.next'), this.advancePageNum(n, false));
		this.switchPageLink($('.image-content a.prev'), this.advancePageNum(n, true));
	},

	// private
	switchImg: function(isPrev, noAnimation, onSwitch) {
		this.page = this.advancePageNum(this.page, isPrev);
		this.setupImg(this.page, noAnimation, onSwitch);
	},

	setupImg: function(n, noAnimation, onSwitch) {
		n = parseInt(n);

		if(noAnimation) {
			this.paintNavigation(n);
			this.paintImg(n);
			if(onSwitch) onSwitch();
			return;
		}

		var g = this;
		this.preloader.start(this.getImg(n).file, function() {
			g.img.stop(); // prevent weird animation
			g.img.fadeTo(g.fadeTime/2, 0.2, function() {
				g.paintImg(n);
				if(onSwitch) onSwitch();
				g.img.fadeTo(g.fadeTime/2, 1);
			});
			g.paintNavigation(n);
		});
	},

	switchPageLink: function(a, n) {
		var url = a.attr('href');
		var s = (n == 1) ? '' : 'image'+n+'/';
		url = url.replace(/\/image\d+\/?$/, '/')+s;
		a.attr('href', url);
	},

	advancePageNum: function(n, isPrev) {
		var len = this.imgs.length;
		n += isPrev ? -1 : 1;
		if(n < 1) n = len;
		if(n > len) n = 1;
		return n;
	}
};


var Slideshow = function(params) {
	if(!params) params = {};
	for(var i in params) {
		this[i] = params[i];
	}
	this.init();
};
Slideshow.prototype = {
	$link: null,
	delay: 3000, // msec
	gallery: null,

	isEnabled: false,
	timeout: null,

	init: function() {
		var ss = this;
		if(this.$link) {
			this.$link.click(function() {
				this.blur();
				ss.switchState();
				return false;
			});
		}
	},

	start: function() {
		this.switchState(true);
	},

	stop: function() {
		this.switchState(false);
	},

	switchState: function(state) {
		this.isEnabled = arguments.length ? state : !this.isEnabled;
		this.clear();

		// link text
		if(this.$link) {
			this.$link.text(this.isEnabled ? 'пауза' : 'слайдшоу');
		}

		// okay, do the work
		this.run(true);
	},

	clear: function() {
		clearTimeout(this.timeout);
	},

	run: function(skipDelay) {
		if(!this.isEnabled) return;
		var ss = this;
		var delay = skipDelay ? 0 : this.delay;
		this.timeout = setTimeout(function() {
			ss.gallery.next(false, function() {
				ss.run();
			});
		}, delay);
	}
};






//
//MAIN
//

$(document).ready(function() {

	// ctrl+arrows navigation in blog/etc
	$(document).bind($.browser.mozilla ? 'keypress' : 'keydown', function(e) {
		if(e.ctrlKey) {
			var a = null;
			if(e.keyCode == 39) a = $('#navigateNext'); // right arrow
			if(e.keyCode == 37) a = $('#navigatePrev'); // left arrow
			if(a && a.size()) {
				document.location.href = a.attr('href');
			}
		}
	});



	//
	// ok, now the only-for-image-pages part
	//
	if(!window.galleryImages) return;

	// we have JS: lets get rid of /image12/ crap in URLs
	var re = /\/image(\d+)\/?(#|$)/;
	if(document.location.href.match(re)) {
		var h = document.location.href;
		document.location.href = h.replace(re,
			function(url, page, hash) {
				return '/#' + (hash ? '' : page);
			}
		);
	}

	// gallery setup
	var gallery = new Gallery({
		img: $('.image-content .image img'),
		pageSpan: $('#currentPage'),

		imgs: window.galleryImages,
		page: parseInt(window.pageNum),
		fadeTime: 600,

		// debug: true,

		preloader: new Preloader({
			onStart: function() {
				$('body').addClass('loading');
			},
			onStop: function() {
				$('body').removeClass('loading');
			}
		})
	});

	$('body').append('<div id="preloaderz" style="position: absolute; top: 0; left: -9999px; width: 1px; height: 1px; overflow: hidden; zoom: 1"></div>');

	var imgBox = $('.image-content .image');
	var doAutoplay = $('div.image-content-autoplay').size();

	// navigation
	var ssLink = false;
	if(!doAutoplay) {
		// duplicating navigation links to create side-panels
		imgBox.append('<div class="panel prev-panel"></div><div class="panel next-panel"></div>');
		// preload navigation icons
		$('<img>').attr('src', '/images/next-arrow.png');
		$('<img>').attr('src', '/images/prev-arrow.png');

		$('.image-content .prev-panel')
			.bind('click', function() { $('.image-content a.prev').click(); })
			.hover(
				function() { imgBox.addClass('prev-panel-hover'); },
				function() { imgBox.removeClass('prev-panel-hover'); }
			);
		$('.image-content .next-panel')
			.bind('click', function() { $('.image-content a.next').click(); })
			.hover(
				function() { imgBox.addClass('next-panel-hover'); },
				function() { imgBox.removeClass('next-panel-hover'); }
			);


		// slideshow
		$('.image-content span.nav-pages').after('&nbsp; &nbsp; <a href="" class="slideshow">слайдшоу</a>');
		ssLink = $('.image-content a.slideshow');
	}
	var slideshow = new Slideshow({
		$link:   ssLink,
		gallery: gallery
	});

	if(doAutoplay) {
		setTimeout(function(){ slideshow.start(); }, slideshow.delay);
	}


	// prevent image selection on rapid navigation clicks
	$('.image-content .image').disableTextSelect();

	// manual gallery navigation
	$('.image-content a.next').click(function() {
		this.blur();
		slideshow.stop();
		gallery.next();
		return false;
	});
	$('.image-content a.prev').click(function() {
		this.blur();
		slideshow.stop();
		gallery.prev();
		return false;
	});

	// keyboard navigation (safari doesnt like keypress)
	if(!doAutoplay) {
		$(document).bind($.browser.mozilla ? 'keypress' : 'keydown', function(e) {
			var o = e.target || e.srcElement;
			if(!$(o).parents('form').size()) {
				if(e.keyCode == 39) {
					slideshow.stop();
					gallery.next(); // right arrow
				}
				if(e.keyCode == 37) {
					slideshow.stop();
					gallery.prev(); // left arrow
				}
			}
		});
	}

	// fixing size and position of the image
	var fixSize = function() {
		var imgInTheBox = imgBox.find('img');

		// position
		var boxH = imgBox.height();
		var imgH = imgInTheBox.height();
		var padding = 0;
		if(boxH > imgH) {
			padding = (boxH - imgH) / 2;
		}
		imgInTheBox.get(0).style.marginTop = padding+'px';

		// size
		if(!$.browser.mozilla) {
			var img = gallery.getImg();
			var boxW = imgBox.width();
			var scaleW = boxW / img.width;
			var scaleH = boxH / img.height;
			// do not stretch more than the original size
			var s = Math.min(scaleW, scaleH, 1);
			imgInTheBox.width(img.width * s).height(img.height * s);
		}
	};

	fixSize();
	$(window).resize(fixSize);
	setInterval(fixSize, 50);
	var oldPI = gallery.paintImg;
	gallery.paintImg = function() {
		oldPI.apply(gallery, arguments);
		fixSize();
	};

	// hash navigation
	var prevS = '';
	var openByHash = function() {
		var s = document.location.hash || '';
		if(s == prevS) return;
		prevS = s;
		s = s.replace(/^#/, '');
		if(s && s.match(/^\d+$/)) {
			if(gallery.page != s && gallery.getImg(s)) {
				// do not show wrong picture
				imgBox.find('img').attr('src', 'images/loading.gif');
				gallery.open(s, true);
			}
		}
	};
	// watching for hash change
	setInterval(openByHash, 250);
});

