/*
 * egallery_jq.js - "enhanced gallery" - gallery a (s)comparsa sulla pagina
 * versione con utilizzo di jQuery per AJAX
 *
 * richiede php:
 * photo.php o implementazione equivalente, e sue dipendenze
 *
 * richiede Javascript esterni:
 * libreria jQuery
 * dommanip.js
 * gallery.js
 *
 * richiede CSS:
 * gallery.css
 * gallery_ie.css
 *
 * UTILIZZO (dove egal e' il nome dell'oggetto):
 * egal = new EGallery(<lingua>, <id_galleria_nel_database>);
 * egal.setupEGallery(<id_link_che_apre_la_gallery>, [<restoreSkip>]);
 *
 * N.B. il link dovrebbe puntare a uno script come photo.php come fallback
 * (se la finestra non e' sufficiente a contenere la gallery a scomparsa,
 *  si ha un cambiamento di pagina verso la gallery normale)
 *
 * restoreSkip == false : alla chiusura, la gallery ricorda l'ultima immagine visitata (default)
 * restoreSkip == true  : alla chiusura, la gallery ricorda l'ultimo skipTo()
 *
 * egal.addTrigger(<id_link_addizionale>, [<offset>]);
 *
 * offset (default 0): a quanti indici piu' in la' dell'ultimo skipTo() bisogna andare
 * aprendo la gallery con il link addizionale.
 * se offset != 0 si passa automaticamente alla modalita' restoreSkip == true!
 *
 * IMPORTANTE: nell'evento window.onunload includere la chiamata
 * egal.unloadme();
 * in caso contrario si verificheranno memory leak, particolarmente in IE6
 * (N.B. non e' necessario includere anche l'unloadme() della gallery normale)
 *
 * pigi - rev. 20071130
 */

function EGallery(lang, defaultParam)
{
	this.language = lang;
	this.ajaxparam = defaultParam;

	this.galleryTitle = null;
	this.bgbak = null;
	this.galleryobj = null;
	this.maxIndex = null;
	this.currentIndex = 0;
	this.lastSkipTo = 0;
	this.restoreSkip = false;
	this.offsets = [];

	this.ajaxroot = "photo.php?output=json&p=";
	this.sLoadingId = 'egal_loading_div';
	this.sPrefix = 'gallery';

	// oggetti da ricordare per l'unload
	this.setuplink = null; // click
	this.extralinks = []; // click, array
	this.ldlink = null; // click
	this.closelink = null; // click
	this.opentimeout = null; // timeout
	this.adjtimeout = null; // timeout

	// inizializza messaggi in base alla lingua
	this.message = [];
	switch(lang) {
		case 2:
		case 'it':
			this.message[0] = 'it';
			this.message[1] = "Non e' stato possibile connettersi al server.";
			this.message[2] = "foto ";
			this.message[3] = " di ";
			this.message[4] = "Precedente";
			this.message[5] = "Successiva";
			this.message[6] = "Chiudi";
			this.message[7] = "Chiudi la galleria";
			this.message[8] = "Spiacente, la galleria non e' disponibile.";
			this.message[9] = "Caricamento gallery in corso; clicca qui per annullare";
			break;

		case 1:
		case 'en':
			this.message[0] = 'en';
			this.message[1] = "Couldn't connect to server.";
			this.message[2] = "photo ";
			this.message[3] = " of ";
			this.message[4] = "Previous";
			this.message[5] = "Next";
			this.message[6] = "Close";
			this.message[7] = "Close this gallery";
			this.message[8] = "Sorry, the gallery is not available.";
			this.message[9] = "Loading gallery; click here to cancel";
			break;

	}

	return this;
}

EGallery.prototype.unloadme = function()
{
	var i;

	if (this.setuplink) {
		this.setuplink.onclick = null;
	}
	if (this.extralinks.length > 0) {
		for (i=0; i < this.extralinks.length; i++) {
			this.extralinks[i].onclick = null;
		}
	}
	if (this.ldlink) {
		this.ldlink.onclick = null;
	}
	if (this.closelink) {
		this.closelink.onclick = null;
	}
	if (this.galleryobj && this.galleryobj.unloadme) {
		this.galleryobj.unloadme();
	}
	if (this.opentimeout) {
		clearTimeout(this.opentimeout);
		this.opentimeout = null;
	}
	if (this.adjtimeout) {
		clearTimeout(this.adjtimeout);
		this.adjtimeout = null;
	}

};

EGallery.prototype.getAjaxURL = function(idParam)
{
	var sUrl = location.href;
	sUrl = sUrl.substring(0, sUrl.lastIndexOf("/"));
	sUrl += "/" + this.ajaxroot + idParam;
	return sUrl;
};

EGallery.prototype.reportHTTPerror = function()
{
	alert(this.message[1]);
};

EGallery.prototype.showLoading = function(flag)
{
	var lddiv;
	var ldspan;
	var id = this.sLoadingId;
	var db = document.body;
	var me = this;

	if (document.getElementById) {
		lddiv = document.getElementById(id);
		if (flag && !lddiv) {
			// aggiungi il div nel body
			lddiv = appendSimpleDiv(db, id);
			lddiv.style.display = 'none';
			this.ldlink = appendSimpleLink(lddiv, '#', id + '_a');
			this.ldlink.setAttribute('title', this.message[9]);
			ldspan = appendSimpleSpan(this.ldlink);
			appendText(ldspan, 'cancel');
			this.ldlink.onclick = function() {
				me.cancelLoading();
			};
			this.adjustDivPos(id, 200, 200, 200, 100);

		} else if (!flag && lddiv) {
			if (this.ldlink) {
				this.ldlink.onclick = null;
				this.ldlink = null;
			}

			// elimina il div
			lddiv.parentNode.removeChild(lddiv);
		}
	}
};

EGallery.prototype.cancelLoading = function()
{
	var id = this.sLoadingId;
	var lddiv = document.getElementById(id);
	if (this.ldlink) {
		this.ldlink.onclick = null;
		this.ldlink = null;
	}
	lddiv.parentNode.removeChild(lddiv);
	this.disableMain(false);
	return false;
};

EGallery.prototype.disableMain = function(flag)
{
	var db = document.body;
	var id = 'egal_filterfunc';
	var fil;
	var bodyheight;

	if (flag) {
		bodyheight = db.offsetHeight + 2;
		fil = appendSimpleDiv(db, id);
		fil.style.height = bodyheight + 'px';

	} else {
		//bstyle.background = bgbak;
		fil = document.getElementById(id);
		if (fil) {
			fil.parentNode.removeChild(fil);
		}

	}
};

EGallery.prototype.setupEGallery = function(idAnchor, setRestore)
{
	var me = this;

	if (setRestore) {
		this.restoreSkip = true;
	}

	if (document.getElementById) {
		this.setuplink = document.getElementById(idAnchor);
		if (this.setuplink) {
			this.offsets[idAnchor] = 0;
			this.setuplink.onclick = function () {
				if (me.stageIsGood()) {
					me.showLoading(true);
					if (me.galleryobj && me.galleryobj.galleryData) {
						me.galleryobj.currentIndex = me.currentIndex;
						me.popGallery();
					} else {
						me.fetchGallery();
					}
					return false;
			
				} else {
					return true;
				}
			}
		}
	}
};

EGallery.prototype.addTrigger = function(idAnchor, offset)
{
	var extralink;
	var me = this;

	if (isNaN(offset)) {
		offset = 0;
	}
	offset = Math.floor(offset);

	if (document.getElementById) {
		extralink = document.getElementById(idAnchor);
		if (extralink) {
			extralink.onclick = function() {
				if (!isNaN(me.offsets[this.id])) {
					me.currentIndex += me.offsets[this.id];
				}
			
				if (me.stageIsGood()) {
					me.showLoading(true);
					if (me.galleryobj && me.galleryobj.galleryData) {
						me.galleryobj.currentIndex = me.currentIndex;
						me.popGallery();
					} else {
						me.fetchGallery();
					}
					return false;
			
				} else {
					return true;
				}
			};
			this.extralinks.push(extralink); // per cancellare l'evento sull'unloadme
			this.offsets[idAnchor] = offset;
		}
	}

	if (offset != 0) {
		this.restoreSkip = true;
	}
};

EGallery.prototype.getSizes = function()
{
	var fs = [];

	if (document.documentElement && document.documentElement.scrollTop) {
		fs.sctop = document.documentElement.scrollTop;
	} else if (document.body) {
		fs.sctop = document.body.scrollTop;
	} else {
		fs.sctop = pageYOffset;
	}

	if (document.documentElement && document.documentElement.scrollLeft) {
		fs.scleft = document.documentElement.scrollLeft;
	} else if (document.body) {
		fs.scleft = document.body.scrollLeft;
	} else {
		fs.scleft = pageXOffset;
	}

	if (document.documentElement && document.documentElement.clientHeight) {
		fs.height = document.documentElement.clientHeight;
	} else if (document.body) {
		fs.height = document.body.clientHeight;
	} else {
		fs.height = innerHeight;
	}

	if (document.documentElement && document.documentElement.clientWidth) {
		fs.width = document.documentElement.clientWidth;
	} else if (document.body) {
		fs.width = document.body.clientWidth;
	} else {
		fs.width = innerWidth;
	}

	return fs;
};

EGallery.prototype.stageIsGood = function()
{
	var foursizes = this.getSizes();

	if ((foursizes.width >= 790) && (foursizes.height >= 550)) {
		return true;
	} else {
		return false;
	}
};

EGallery.prototype.fetchGallery = function()
{
	var me = this;

	// chiamata AJAX per recuperare i valori
	$.ajax({
	   type: "GET",
	   url: this.getAjaxURL(this.ajaxparam),
	   dataType: "json",
	   error: function(oRequest, sResult) {
			me.showLoading(false);
			me.reportHTTPerror();
	   },
	   success: function(oResponse) {
			if (me.processGalleryDataJson(oResponse)) {
				me.popGallery();
			} else {
				me.showLoading(false);
			}
	   }
	});

};

EGallery.prototype.processGalleryDataJson = function(oResult)
{
	if (oResult && !oResult.error) {
		if (oResult.title) {
			this.galleryTitle = oResult.title;
		}
		if (!isNaN(oResult.maxIndex)) {
			this.maxIndex = oResult.maxIndex;
			if (this.currentIndex > this.maxIndex) {
				this.currentIndex = this.maxIndex;
			}
		}
		this.galleryobj = new Gallerystatus(this.currentIndex, this.maxIndex, oResult.urlbaseImg, false);
		if (this.galleryobj && oResult.galleryData) {
			this.galleryobj.galleryData = oResult.galleryData;
		}
		return true;

	} else {
		alert(this.message[8]);
		return false;
	}
};

EGallery.prototype.skipTo = function(idx)
{
	if (isNaN(idx)) { return false; }
	idx = Math.floor(idx);
	if (idx >= 0 && (this.maxIndex === null || idx <= this.maxIndex)) {
		this.currentIndex = idx;
		this.lastSkipTo = idx;
	}

};

EGallery.prototype.popGallery = function()
{
	if (!this.galleryobj.galleryData) { return false; }

	var prefix = this.sPrefix;
	var db = document.body;
	var gal = [];

	// fermati se e' stato annullato il caricamento
	var test = document.getElementById(this.sLoadingId);
	if (!test) { return false; }

	// fermati se e' gia' caricata la gallery
	test = document.getElementById(prefix + '_container');
	if (test) { return false; }

	var me = this;

	this.disableMain(true);

	// schema generale della galleria
	gal.container = appendSimpleDiv(db, prefix + '_container');
	gal.container.style.display = 'none';
	gal.content = appendSimpleDiv(gal.container, prefix + '_content');
	gal.photo = appendSimpleDiv(gal.content, prefix + '_photo');
	gal.text = appendSimpleDiv(gal.content, prefix + '_text');
	gal.links = appendSimpleDiv(gal.content, prefix + '_links');
	gal.close = appendSimpleDiv(gal.content, prefix + '_close');

	// triplo div contenitore per la foto (centra h+v)
	gal.photoV = appendSimpleDiv(gal.photo);
	gal.photoH = appendSimpleDiv(gal.photoV);
	gal.image = appendElement(gal.photoH, 'img', prefix + '_image');
	gal.image.setAttribute('alt', '');
	
	// testi
	gal.title = appendSimpleDiv(gal.text, prefix + '_title');
	appendText(gal.title, this.galleryTitle);
	gal.dida = appendSimpleDiv(gal.text, prefix + '_dida');

	// numero foto
	gal.which = appendSimpleDiv(gal.links, prefix + '_which');
	appendText(gal.which, this.message[2]);
	gal.whichIdx = appendSimpleSpan(gal.which, prefix + '_idx');
	//appendText(gal.whichIdx, (1 + currentIndex));
	appendText(gal.which, this.message[3]);
	gal.whichMax = appendSimpleSpan(gal.which, prefix + '_maxidx');
	appendText(gal.whichMax, (1 + this.maxIndex));

	// link precedente e successiva
	gal.prevDiv = appendSimpleDiv(gal.links, prefix + '_prev');
	gal.prevLink = appendSimpleLink(gal.prevDiv, '#', prefix + '_prev_link');
	//gal.prevLink.className = (currentIndex > minIndex)? 'show' : 'hide';
	gal.prevLink.setAttribute('title', this.message[4]);
/*
	gal.prevLink.onclick = doFalse;
	gal.prevLink.onmouseup = prevPhoto;
*/
	gal.prevLinkSpan = appendSimpleSpan(gal.prevLink);
	appendText(gal.prevLinkSpan, this.message[4]);

	gal.nextDiv = appendSimpleDiv(gal.links, prefix + '_next');
	gal.nextLink = appendSimpleLink(gal.nextDiv, '#', prefix + '_next_link');
	//gal.nextLink.className = (currentIndex < maxIndex)? 'show' : 'hide';
	gal.nextLink.setAttribute('title', this.message[5]);
	gal.nextLinkSpan = appendSimpleSpan(gal.nextLink);
	appendText(gal.nextLinkSpan, this.message[5]);

	// link chiudi
	this.closelink = appendSimpleLink(gal.close, '#');
	this.closelink.setAttribute('title', this.message[7]);
	this.closelink.onclick = function() {
		me.destroyGallery();
		return false;
	};
	gal.closeLinkSpan = appendSimpleSpan(this.closelink);
	appendText(gal.closeLinkSpan, this.message[6]);

	this.galleryobj.setupGallery(prefix + '_prev_link', prefix + '_next_link');
	this.galleryobj.updatePhoto(this.galleryobj.currentIndex);
	this.adjustDivPos(prefix + '_container', 806, 550, 550);
	this.opentimeout = setTimeout(function() { me.showLoading(false); }, 100);
};

EGallery.prototype.destroyGallery = function()
{
	var gallery = document.getElementById(this.sPrefix + '_container');
	this.disableMain(false);
	if (gallery) {
		if (this.adjtimeout) {
			clearTimeout(this.adjtimeout);
		}
		this.closelink.onclick = null;
		gallery.parentNode.removeChild(gallery);
	}

	if (this.restoreSkip) {
		this.currentIndex = this.lastSkipTo;
	} else {
		this.currentIndex = this.galleryobj.currentIndex;
	}
	return false;
};

EGallery.prototype.adjustDivPos = function(id, pwidth, pheight, phthreshold, popera)
{
	var me = this;
	var foursizes = this.getSizes();
	var flt = document.getElementById(id);
	var nx;
	var ny;

	if (!popera) { popera = 10; }

	if (flt && flt.style) {
		nx = Math.floor((foursizes.width - parseInt(pwidth, 10)) / 2);
		if (window.opera) {
			// Opera non computa bene .height, ancoro in alto invece che al centro
			ny = parseInt(popera, 10);
			if (ny < 0) {
				ny = 0;
			}

		} else if (foursizes.height <= parseInt(phthreshold, 10)) {
			ny = 0;

		} else {
			ny = Math.floor(foursizes.height - parseInt(pheight, 10)) / 2;
		}

		ny += foursizes.sctop;
		flt.style.left = nx+'px';
		flt.style.top = ny+'px';
		flt.style.display = 'block';
		this.adjtimeout = setTimeout(function() { me.adjustDivPos(id,pwidth,pheight,phthreshold,popera); } , 100);
	}
};
