/**
 * GalleryBox Slider version
 * @author DaVee
 * @version 0.981
 * @license under WTFPL 2.0
 */
function GalleryBoxSlide (element, option) {
	var mark = option['mark'] === undefined ? 'box' : option['mark'];
	if ($('#gallery-' + mark).length != 0) return false;
	// localization
	var clientLang = (navigator.userLanguage || navigator.language).substr(0,2).toLowerCase();
	this.text = {
		'en' : {prev: 'previous', next: 'next', close: 'close', loading: 'loading ...', error: 'Image not found.'},
		'cs' : {prev: 'p\u0159edchozí', next: 'dal\u0161í', close: 'zav\u0159ít', loading: 'na\u010dítá se ...', error: 'Obrázek nelze na\u010díst.'}
	};
	// variables
	this.ident = '#gallery-' + mark;
	this.animate = option['animate'] === undefined ? 400 : option['animate'];
	this.locale = this.text[clientLang] !== undefined ? this.text[clientLang] : this.text['en'];
	this.imgShow = -1;
	this.imgCount = 0;
	this.srcs = Array();
	this.titles = Array();

	// load links from element
	this.load = function (element) {
		$(element).each( function () {
			var oldCount = self.imgCount;
			var images = $(this).find("a");
			if (images.length != 0) {		
				$(images).each( function () {
					self.loadImage(this);
				});
			}
			else self.loadImage(element);
			self.appendAction(oldCount);
		});
	}
	
	// add image
	this.loadImage = function (link) {
		if ($(link).attr('href') !== undefined) {
			var str = $(link).attr("href");
			self.srcs.push(str);
			self.titles.push($(link).children("img").prop("title"));
			var x = this.imgCount + 0;
			$(link).click( function () {return self.show(x);});
			self.imgCount++;
		}
	}

	// show galllery
	this.show = function (num) {
		var imgNew = new Image();	
		if ($(self.ident).css("display") == "none") {
			$(self.ident +" .gallery-box-image img").toggle(self.imgShow == num);
			$(self.ident).fadeIn(500);
			$(self.ident +" .gallery-box").css("top", self.center());
			if (self.imgShow == num) return false;
		}

		self.imgShow = num;
		$(self.ident +" .gallery-box p").text(self.locale["loading"]);
		$(self.ident +" .gallery-box-image img").fadeOut(200, function () {
			$(this).remove();	
			$(imgNew).load(function () {
				var height = $(imgNew).prop('height');
				var width = $(imgNew).prop('width');
				$(self.ident +" .gallery-box").animate({width: width+"px", "top": self.center(height)}, self.animate);
				self.moveList(num, width);
				$(self.ident +" .gallery-box-image").append(this).animate({height: height+"px", width: width+"px"}, self.animate, function () {
					$(self.ident +" .gallery-box-image img").fadeIn(200);
					$(self.ident +" .gallery-box p").text(self.titles[self.imgShow]);
				});
			}).error(function () {
				$(imgNew).stop(true,true);
				$(self.ident +" .gallery-box-image").append(new Image());
				$(self.ident +" .gallery-box p").text(self.locale["error"]);
			}).hide().attr('src', self.srcs[self.imgShow]);
		});

		$(this.ident +" a.gallery-box-left").toggle(this.imgShow != 0);
		$(this.ident +" a.gallery-box-right").toggle(this.imgShow < this.imgCount-1);
		return false;
	}

	// place into center of screen
	this.center = function (newHeight) {
		if ($(self.ident +".gallery-box-all").width() < $(document).width()) $(self.ident +".gallery-box-all").width($(document).width());
		if (newHeight !== undefined) {
			$(self.ident +" .gallery-box-image").hide();
			newHeight += $(self.ident +" .gallery-box").height()
				+ parseInt($(self.ident +" .gallery-box").css('padding-top'))
				+ parseInt($(self.ident +" .gallery-box").css('padding-bottom'));
			$(self.ident +" .gallery-box-image").show();
		}
		var top = $(window).scrollTop() + Math.round(($(window).height() - (newHeight === undefined ? $(self.ident +" .gallery-box").height() : newHeight)) / 2);
		// IE 6 fix
		if ($.browser.msie && $.browser.version < 7) {
			$(self.ident +" .gallery-box-black")
				.height($(window).height() > $(document).height() ? $(window).height() : $(document).height())
				.width($(window).width() > $(document).width() ? $(window).width() : $(document).width());			
			if (($(self.ident +" .gallery-box").offset().top + $(self.ident +" .gallery-box").height()) > $(self.ident +" .gallery-box-black").height()) {
				$(self.ident +" .gallery-box-black").height($(self.ident +" .gallery-box").offset().top + $(self.ident +" .gallery-box").height());
			}
			if ($(self.ident +" .gallery-box").width() > $(self.ident +" .gallery-box-black").width()) {
				$(self.ident +" .gallery-box-black").width($(self.ident +" .gallery-box").width());
			}
		}
		return  top > 0 ? top + "px" : 0;
	}

	// listovani
	this.scroll = function (left) {
		if (left) {
			if (this.imgShow > 0) this.show(this.imgShow - 1);
		}
		else {
			if (this.imgShow < this.imgCount-1) this.show(this.imgShow + 1);
		}
		return false;
	}

	// create link on element to show gallery
	this.createLink = function (element) {
		var img = $("#"+element+" img").attr('src');
		img = img.substring( img.lastIndexOf('/') + 1 );
		for(var i = 0; i < this.srcs.length; i++) {
			if (this.srcs[i].indexOf(img) > 0) {
				$("#"+element).click( function () {self.show(i);return false;} );
				$("#"+element).css('cursor','pointer');
				break;
			}
		}
	}
	
	this.appendAction = function (old) {
		if (old != self.imgCount) {
			$(self.ident + " .gallery-box-count").text(self.imgCount);
			if (old <= 1 && self.imgCount > 1) {
				// action association
				$(self.ident +" a.gallery-box-left").click(function() {return self.scroll(true);});
				$(self.ident +" a.gallery-box-right").click(function() {return self.scroll(false);});
				$(document).keydown( function(e) {
					if ($(self.ident + ":visible").length != 0) {
						if (e.keyCode == 37) { e.preventDefault(); self.scroll(true); }
						else if (e.keyCode == 39) { e.preventDefault(); self.scroll(false); }
						else if (e.keyCode == 27) { e.preventDefault(); $(self.ident).fadeOut(500); }
					}
				});
			}
		}
	}

	this.createList = function (after) {
		var prefix = "thumb_";
		$(after).after('<div class="gallery-slider"><div class="gallery-slider-content">' +
			'</div></div><div class="gallery-box-clear"></div>');
		for (var i in this.srcs) {
			var pos = this.srcs[i].lastIndexOf('/') + 1;
			var src = this.srcs[i].substr(0, pos) + prefix + this.srcs[i].substr(pos);
			$(this.ident + " .gallery-slider-content").append('<a href="' + this.srcs[i] + '">' +
				'<img src="' + src + '" alt="' + this.titles[i] + '" title="' + this.titles[i] + '" /></a>');
			this.addLink($(this.ident + " .gallery-slider-content a:last"), i);
		}
	}

	this.addLink = function (link, i) {
		$(link).click( function () {return self.show(parseInt(i));});
	}

	this.moveList = function (show, newWidth) {
		var move = 0;
		var list = parseInt($(".gallery-slider-content a").css("margin-left")) + 
				parseInt($(".gallery-slider-content a").css("margin-right")) + 
				parseInt($(".gallery-slider-content a img").css("border-left-width")) +
				parseInt($(".gallery-slider-content a img").css("border-right-width"));
		list = list * $(".gallery-slider-content a img").length;
		$(".gallery-slider-content a img").each( function () {list += $(this).width();});

		if (list > newWidth) {
			var select = $(".gallery-slider-content a")[show];
			if (list < ($(select).position().left + (newWidth / 2))) move = -list + newWidth;
			else if ((newWidth / 2) < $(select).position().left) move = (newWidth / 2) - $(select).position().left;
		}
		$(".gallery-slider-content").animate({left: move + "px"}, self.animate);
	}

	var self = this;
	// html gallery code insetion
	$("body").append('<div id="'+this.ident.substr(1)+'" class="gallery-box-all"><div class="gallery-box-black"></div><div class="gallery-box">'+
		'<div class="gallery-box-image">'+
		'<a class="gallery-box-right" title="'+this.locale["next"]+'"><span>'+this.locale["next"]+'</span></a>'+
		'<a class="gallery-box-left" title="'+this.locale["prev"]+'"><span>'+this.locale["prev"]+'</span></a>'+
		'<img src="" /></div>'+
		'<a class="gallery-box-close" title="'+this.locale["close"]+'"><span>'+this.locale["close"]+'</span></a>'+
		'<p></p><div class="gallery-box-clear"></div></div></div>');
	$(self.ident +" a.gallery-box-close").click(function() {$(self.ident).fadeOut(500);return false;});
	$(self.ident +" .gallery-box-black").click(function() {$(self.ident).fadeOut(500);});
	this.load(element);
	this.createList(this.ident + " .gallery-box-image");
	return true;
}

function Timer (callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };

    this.resume = function() {
        start = new Date();
        timerId = window.setTimeout(callback, remaining);
    };

    this.resume();
}


function BannerChanger (banner) {
	this.period = 10000;
	this.page = ".banner-page";
	this.pageContent = ".banner-page-block";
	this.banner = banner;
	this.timer = false;
	this.pages = $(this.banner + " " + this.page).length;
	
	var changer = this;
	
	$(this.banner + " " + this.page).each( function () {
		$(this).hover(
			function () { changer.timer.pause(); },
			function () { changer.timer.resume(); }
		);
	});
	
	this.show = function (i) {
		if (i >= changer.pages) i = 0;
		var newImage = new Image();
		$(newImage).load(function () {
			$(changer.banner + " " + changer.page + ":visible").fadeOut(1000);
			$(changer.banner + " " + changer.page + ":eq(" + i + ")").fadeIn(1000);
			changer.timer = new Timer( function(){changer.show(i+1)}, changer.period);
		}).error(function () {
			changer.timer = new Timer( function(){changer.show(i+1)}, changer.period);
		}).attr("src", $(changer.banner + " " + changer.page + ":eq(" + i + ")").children("img").attr("src"));
	}
	
	this.showPage = function (i) {
		this.timer.pause();
		this.show(i);
		return false;
	}
	
	this.run = function () {
		this.timer = new Timer( function(){changer.show(1)}, this.period);
	}
	
	if (this.pages > 1) this.run();
}
