var ROWS_PER_PAGE    = 6;
var PICTURES_PER_ROW = 4;

/***********************
* Allgemeine Variablen *
***********************/
var viewer;
var thumbnails = new Hash();

var WindowInfo = {
	initialize: function () {
		
	},
	getWindowSize: function () {
		var sizes = new Array(6);
		sizes[0]  = window.innerWidth;   /* Window's inner width  */
		sizes[1]  = window.innerHeight;  /* Window's inner height */
		sizes[2]  = window.outerWidth;   /* Window's outer width  */
		sizes[3]  = window.outerHeight;  /* Window's outer height */
		sizes[4]  = document.body.offsetWidth;
		sizes[5]  = document.body.offsetHeight;
		return sizes;
	}
};

/**************************************************************
* Der Viewer kümmert sich um alles, was mit dem tatsächlichen *
* Fotobetrachter zu tun hat. Also auch um die Animationen     *
**************************************************************/
var Viewer = Class.create(WindowInfo, {
	
	/**
	 * Konstruktor
	 */ 
	initialize: function () {
		var self              = this;
		this.viewer           = $("viewer");
		this.closeButton      = $("viewer_close");
		this.content          = $("viewer_content");
		this.background       = $("viewer_background");
		this.speed            = 0.2;
		this.framesPerSec     = 60;
		this.timePerFrame     = 1000.0 / this.framesPerSec;
		this.opacity          = 0.0;
		this.totalOpacity     = 1.0;
		this.totalSteps       = this.speed * this.framesPerSec;
		this.opacityStep      = this.totalOpacity / this.totalSteps;
		this.visible          = false;
		this.pictures         = new Array();
		this.width            = this.viewer.getWidth();
		this.height           = this.viewer.getHeight();
		this.observing        = false;
		this.center();
		this.closeButton.observe('click', function () {
			self.fade(null, false);
		});
	},
	
	/**
	 * Viewer zentrieren
	 */
	center: function () {
		var windowSize = this.getWindowSize();
		var left       = Math.round((windowSize[4] - this.width) / 2);
		var top        = Math.round((windowSize[1] - this.height) / 2);
		this.viewer.setStyle({'left'     : left + "px",
		                      'top'      : top + "px",
		                      'padding'  : '0',
		                      'position' : 'absolute'});
	},
	
	buildContent: function (nr) {
		/*if (this.observing) {
			$('begin').stopObserving('click', function () {});
			$('back').stopObserving('click', function () {});
			$('continue').stopObserving('click', function () {});
			$('end').stopObserving('click', function () {});
			this.observing = false;
		}*/
		var parts = pictures[nr].split(/\//);
		var album = parts[2].replace(/§§/g, '&').replace(/!!/g, ';').replace(/^\d+__/, '').replace(/_/g, ' ');
		
		var begin = "&#x21E4;";
		var back  = "&#x21E0;";
		var cont  = "&#x21E2;";
		var end   = "&#x21E5;";
		
		if (navigator.appName.match(/Explorer/i)) {
			var begin = "<span id=\"ie_arrow\">&lt;&lt;</span>";
			var back  = "<span id=\"ie_arrow\">&lt;</span>";
			var cont  = "<span id=\"ie_arrow\">&gt;</span>";
			var end   = "<span id=\"ie_arrow\">&gt;&gt;</span>";
		}
		
		this.content.innerHTML = 
			"<div id=\"viewer_picture_content\">" +
				"<h3>" + album + "</h3>" +
				"<p>" + (nr + 1) + " von " + pictures.length + "</p>" +
				"<p><img src=\"" + pictures[nr] + "\" id=\"viewer_img\" /></p>" +
				"<p id=\"controls\">" +
					"<span id=\"begin\">" + begin + "</span> <span id=\"back\">" + back + "</span>" +
			   		"<span id=\"continue\">" + cont + "</span> <span id=\"end\">" + end + "</span>" +
				"</p>" + 
			"</div>";
		
		if (nr == 0) {
			$('begin').setStyle({'color' : 'grey', 'cursor' : 'default'});
			$('back').setStyle({'color' : 'grey', 'cursor' : 'default'});
		}
		
		if (nr == pictures.length - 1) {
			$('continue').setStyle({'color' : 'grey', 'cursor' : 'default'});
			$('end').setStyle({'color' : 'grey', 'cursor' : 'default'});
		}
		
		//if (!this.observing) {
			var self = this;
			this.observing = true;
			$('begin').observe('click', function () {if ((nr) > 0) self.buildContent(0)});
			$('back').observe('click', function () {if ((nr) > 0) self.buildContent(nr - 1)});
			$('continue').observe('click', function () {if ((nr + 1) < pictures.length) self.buildContent(nr + 1)});
			$('end').observe('click', function () {if ((nr + 1) < pictures.length) self.buildContent(pictures.length - 1)});
		//}
	},
	
	/**
	 * Blendevorgang starten
	 */
	fade: function (idx, fadeIn) {
		if (fadeIn) {
			var windowSize = this.getWindowSize();
			this.buildContent(idx);
			this.background.setStyle({'width'      : windowSize[4] + 'px',
			                          'height'     : windowSize[5] + 'px',
			                          'visibility' : 'visible',
			                          'top'        : '0',
			                          'left'       : '0'});
			this.viewer.setStyle({'visibility' : 'visible'});
			this.fadeIn();
		}
		else {
			this.fadeOut();
		}
	},
	
	/**
	 * Blendet den Viewer ein
	 */
	fadeIn: function () {
		var self = this;
		this.opacity += this.opacityStep;
		if (this.opacity > 1.0) this.opacity = 1.0;
		
		this.viewer.setStyle({'opacity' : this.opacity});
		
		if (this.opacity < 1.0) setTimeout(function () {
			self.fadeIn();
		}, 
		this.timePerFrame);
	},
	
	/**
	 * Blendet den Viewer aus
	 */
	fadeOut: function () {
		var self = this;
		this.opacity -= this.opacityStep;
		if (this.opacity < 0.0) this.opacity = 0.0;
		this.viewer.setStyle({'opacity' : this.opacity});
		if (this.opacity > 0.0) setTimeout(function () {self.fadeOut()}, this.timePerFrame);
		else {
			this.viewer.setStyle({'visibility' : 'hidden'});
			this.background.setStyle({'visibility' : 'hidden'});
		}
	},
	
	/**
	 * Besorgt sich per Ajax die Bilderpfade eines Albums.
	 */
	fetchPictures: function (album) {
		new Ajax.Request('lib/request.php', {
			method: 'get',
			parameters: {get_pictures: album},
			onSuccess: function (transport) {
				var response  = transport.responseText;
				this.pictures = response.split(/:::/);
			},
			onFailure: function () {alert("nix");}
		});
	}
});


/**********************************************
* Allgemeiner Event-Handler auf das Dokument. *
*   Außerdem werden alle nötigen Objekte ini- *
* tialisiert.                                 *
**********************************************/
document.observe('dom:loaded', function () {
	var album = "";
	/* Viewer initialisieren */
	viewer = new Viewer();
	
	/************************************************
	* Zuerst werden die Bild-Links gelöscht und mit *
	* Javascript Event-Sendern überschrieben.       *
	*   Auf diese Weise bleibt die Abwärtskompati-  *
	* bilität zu Browsern ohne aktiviertem          *
	* JavaScript erhalten.                          *
	************************************************/
	$$("td.viewerElement").each(function (element) {
		var oldContent    = element.innerHTML;
		
		var imgHref       = oldContent.match(/href="[^"]+"/);
		var imgAlbum      = imgHref[0].match(/album=[^&]+/);
		album             = imgAlbum[0].replace(/album=/, '');
	});
	viewer.fetchPictures("images/galery/" + album);
	
	var cnt = 0;
	$$("td.viewerElement").each(function (element) {
		var idx           = cnt;
		var oldContent    = element.innerHTML;
		
		var imgSrc        = oldContent.match(/src="[^"]+"/);
		var src           = imgSrc[0].replace(/src=/, '').replace(/"/g, '');
		
		var imgStyle      = oldContent.match(/style="[^"]+"/);
		var imgWidth      = imgStyle[0].match(/width:\s*\d+px;?/);
		var imgHeight     = imgStyle[0].match(/height:\s*\d+px;?/);
		var width         = imgWidth[0].match(/\d+/)[0];
		var height        = imgHeight[0].match(/\d+/)[0];
		
		if (album == "") album = src.replace(/\/[^\/]+$/, '');
		
		var sizes = new Array(width, height);
		thumbnails.set(src, sizes);
		
		element.innerHTML = 
			"<span><img src=\"" + src + "\" style=\"width:" + width + "px;height:" + height + "px;\" /></span>";
		element.observe('click', function () {
			viewer.fade(idx, true);
		});
		++cnt;
	});
});
