/* 
    JSPWiki - a JSP-based WikiWiki clone.

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.  
 */

/*
 * jspwiki-commonstyles.js
 * Contains additional Dynmic Styles 
 *
 *	114 Reflection (adds reflection to images): dynamic style 
 *	132 Accordion object: dynamic style
 *	220 RoundedCorners: dynamic style
 *	260 WikiTips: dynamic style 
 *	270 WikiColumns: dynamic style
 *	300 Prettify: dynamic style
 */
 



var WikiCoolBorders = {

	render: function(page,name) {  		
		var pref = "";

		$ES('*[class^=coolborder]',page).each( function(t){
//alert("help");
			var parms = t.className.split('-');


var wi = "width:100%;";
var hi = "";
var st = "";

if (parms[1]) {
 wi = "width:"+parms[1]+"px;";
}

if (parms[2]) {
 hi = "height:"+parms[2]+"px;";
}

/*
var el = t.nextSibling;	
if (el) {		
el = el.nextSibling;	
	
if(el  && (el.nodeType == 1)) {

t.style = el.style;

}
}*/


var header =  "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"
	    + "<tr>"
	    + "<td id=\"cool\" width=\"16\" bgcolor=\"\" background=\""+pref+"/images/top_lef.gif\"></td>"
	    + "<td id=\"cool\" height=\"16\" background=\""+pref+"/images/top_mid.gif\"></td>"
	    + "<td id=\"cool\" width=\"24\" background=\""+pref+"/images/top_rig.gif\"></td>"
	    + "</tr>"
	    + "<tr>"
	    + "<td  id=\"cool\" width=\"16\" background=\""+pref+"/images/cen_lef.gif\"><img src=\""+pref+"/images/cen_lef.gif\" width=\"16\" height=\"11\"></td>"
	    + "<td align=\"\" valign=\"middle\" bgcolor=\"#FFFFFF\" style=\""+hi+" "+wi+"\">";

var content = t.innerHTML;

var footer = "<td id=\"cool\" width=\"24\" background=\""+pref+"/images/cen_rig.gif\"><img src=\""+pref+"/images/cen_rig.gif\" width=\"24\" height=\"11\"></td>"
	   + "</tr>"
	   + "<tr>"
	   + "<td id=\"cool\" width=\"16\" height=\"16\" background=\""+pref+"/images/bot_lef.gif\"></td>"
	   + "<td id=\"cool\" height=\"16\" background=\""+pref+"/images/bot_mid.gif\"></td>"
	   + "<td id=\"cool\" width=\"24\" height=\"16\" background=\""+pref+"/images/bot_rig.gif\"></td>"
	   + "</tr>"
	   + "</table>";

t.innerHTML = header + content + footer;

			//alert(header);
		});
	}


}
Wiki.addPageRender(WikiCoolBorders);









 
/*
Dynamic Style: Reflection  (114)

Inspired by Reflection.js at http://cow.neondragon.net/stuff/reflection/
Freely distributable under MIT-style license.
Adapted for JSPWiki/BrushedTemplate, D.Frederickx, Sep 06

Use:
 	%%reflection-height-opacity  [some-image.jpg] %%
 */
var WikiReflection = {

	render: function(page,name){		
		$ES('*[class^=reflection]',page).each( function(w){
			var parms = w.className.split('-');
			$ES('img',w).each(function(img){
				Reflection.add(img, parms[1], parms[2]);
			}); 
		});
	}
}
Wiki.addPageRender(WikiReflection);

/* FIXME : add delayed loading of reflection library */
var Reflection = {

	options: { height: 0.33, opacity: 0.5 },

	add: function(img, height, opacity) {
		//TODO Reflection.remove(image); --is this still needed?
		height  = (height ) ? height/100 : this.options.height;
		opacity = (opacity) ? opacity/100: this.options.opacity;

		var div = new Element('div').injectAfter(img).adopt(img),
			imgW = img.width,
			imgH = img.height,
			rH   = Math.floor(imgH * height); //reflection height

		div.className = img.className.replace(/\breflection\b/, "");
		div.style.cssText = img.backupStyle = img.style.cssText;
		//div.setStyles({'width':img.width, 'height':imgH +rH, "maxWidth": imgW });
		div.setStyles({'width':img.width, 'height':imgH +rH });
		img.style.cssText = 'vertical-align: bottom';
		//img.className = 'inline reflected';  //FIXME: is this still needed ??

		if( window.ie ){ 
			new Element('img', {'src': img.src, 'styles': {
				'width': imgW,
				'marginBottom': "-" + (imgH - rH) + 'px',
				'filter': 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+(opacity*100)+', style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+(height*100)+')'
			}}).inject(div);
		} else {
			var r = new Element('canvas', {'width':imgW, 'height':rH, 'styles': {'width':imgW, 'height': rH}}).inject(div);
			if( !r.getContext ) return;

			var ctx = r.getContext("2d");
			ctx.save();
			ctx.translate(0, imgH-1);
			ctx.scale(1, -1);
			ctx.drawImage(img, 0, 0, imgW, imgH);
			ctx.restore();
			ctx.globalCompositeOperation = "destination-out";

			var g = ctx.createLinearGradient(0, 0, 0, rH);
			g.addColorStop( 0, "rgba(255, 255, 255, " + (1 - opacity) + ")" );
			g.addColorStop( 1, "rgba(255, 255, 255, 1.0)" );
			ctx.fillStyle = g;
			ctx.rect( 0, 0, imgW, rH );
			ctx.fill(); 
		}
	}
}


/** 132 Accordion for Tabs, Accordeons, CollapseBoxes
 **
 ** Following markup:
 ** <div class="accordion">
 **		<div class="tab-FirstTab">...<div>
 **		<div class="tab-SecondTab">...<div>
 ** </div>
 **
 **	is changed into
 **	<div class="accordion">
 **		<div class="toggle active">First Tab</div>
 **		<div class="tab-FirstTab tab active">...</div>
 **		<div class="toggle">Second Tab</div>
 **		<div class="tab-SecondTab">...</div>
 **	</div>
 **/
var WikiAccordion = {

	render: function(page,name){		
		var toggle = new Element('div',{'class':'toggle'}),
			bullet = new Element('div',{'class':'collapseBullet'});

		$ES('.accordion, .tabbedAccordion, .leftAccordion, .rightAccordion',page).each( function(tt){
			
			var toggles=[], contents=[], menu=false;
			if(tt.hasClass('tabbedAccordion')){
				menu = new Element('div',{'class':'menu top'}).injectBefore(tt);
			}
			else if(tt.hasClass('leftAccordion')){
				menu = new Element('div',{'class':'menu left'}).injectBefore(tt);
			}
			else if(tt.hasClass('rightAccordion')){
				menu = new Element('div',{'class':'menu right'}).injectBefore(tt);
			}
			
			tt.getChildren().each(function(tab) {
				if( !tab.className.test('^tab-') ) return;

				//FIXME use class to make tabs visible during printing 
				//(i==0) ? tab.removeClass('hidetab'): tab.addClass('hidetab');

				var title = tab.className.substr(4).deCamelize(),
					t = toggle.clone().appendText(title);
				menu ? t.inject(menu) : bullet.clone().injectTop(t.injectBefore(tab));

				toggles.push(t);
				contents.push(tab.addClass('tab'));
			});
			
			new Accordion(toggles, contents, {     
				height: true,
				alwaysHide: !menu,
				onComplete: function(){
					var el = $(this.elements[this.previous]);
					if (el.offsetHeight > 0) el.setStyle('height', 'auto');  
				},
				onActive: function(toggle,content){                          
					toggle.addClass('active'); 
					var b = toggle.getFirst();/*bullet*/
					if(b) b.setProperties({'title':'collapse'.localize(), 'class':'collapseOpen'}).setHTML('-'); /* &raquo; */
					content.addClass('active');//.removeClass('xhidetab'); 
				},
				onBackground: function(toggle,content){ 
					content.setStyle('height', content['offsetHeight']);
					toggle.removeClass('active'); 
					var b = toggle.getFirst();/*bullet*/
					if(b) b.setProperties({'title':'expand'.localize(), 'class':'collapseClose'}).setHTML('+'); /* &laquo; */
					content.removeClass('active');//.addClass('xhidetab');
				} 
			});
		});
		bullet=toggle=null; //avoid memory leaks
	}
}
Wiki.addPageRender(WikiAccordion);


/** 220 RoundedCorners --experimental
 ** based on Nifty corners by Allesandro Fulciniti
 ** www.pro.html.it
 ** Refactored for JSPWiki
 **
 ** JSPWiki syntax:
 **
 **  %%roundedCorners-<corners>-<color>-<borderColor>
 **  %%
 **
 **  roundedCorners-yyyy-ffc5ff-c0c0c0
 **
 **  corners: "yyyy" where first y: top-left,    2nd y: top-right,
 **                           3rd y: bottom-left; 4th y: bottom-right
 **     value can be: "y": Normal rounded corner (lowercase y)
 **                    "s": Small rounded corner (lowercase s)
 **                    "n": Normal square corner
 **
 **/
var RoundedCorners =
{
	/** Definition of CORNER dimensions
	 ** Normal    Normal+Border  Small  Small+Border   Big
	 ** .....+++  .....BBB       ..+++  ..BBB          ........+++
	 ** ...+++++  ...BB+++       .++++  .B+++          .....++++++
	 ** ..++++++  ..B+++++       +++++  B++++          ...++++++++
	 ** .+++++++  .B++++++                             ..+++++++++
	 ** .+++++++  .B++++++                             .++++++++++
	 ** ++++++++  B+++++++                             .++++++++++
	 **                                                .++++++++++
	 **                                                +++++++++++
	 **
	 ** legend: . background, B border, + forground color
	 **/
	$Top: {
		'y' : /* normal */
		 [ { margin: "5px", height: "1px", borderSide: "0", borderTop: "1px" }
		 , { margin: "3px", height: "1px", borderSide: "2px" }
		 , { margin: "2px", height: "1px", borderSide: "1px" }
		 , { margin: "1px", height: "2px", borderSide: "1px" }
		 ] ,
		's' : /* small */
		 [ { margin: "2px", height: "1px", borderSide: "0", borderTop: "1px" }
		 , { margin: "1px", height: "1px", borderSide: "1px" }
		 ] ,
		'b' : /* big */ 
		 [ { margin: "8px", height: "1px", borderSide: "0", borderTop: "1px" }
		 , { margin: "6px", height: "1px", borderSide: "2px" }
		 , { margin: "4px", height: "1px", borderSide: "1px" }
		 , { margin: "3px", height: "1px", borderSide: "1px" }
		 , { margin: "2px", height: "1px", borderSide: "1px" }
		 , { margin: "1px", height: "3px", borderSide: "1px" }
		 ] 
	},

	/**
	 ** Usage:
	 ** RoundedCorners.register( "#header", ['yyyy', '00f000', '32cd32'] );
	 **/
	$registry: {},
	register: function(selector, parms){
		this.$registry[selector] = parms;
		return this;
	},

	render: function(page,name){		
		/* make reverse copies for bottom definitions */

		this.$Bottom = {};
		for(var i in this.$Top){
			this.$Bottom[i] = this.$Top[i].slice(0).reverse();
		}		
		
		for(var selector in this.$registry){  // CHECK NEEDED
			var n = $$(selector), 
				p = this.$registry[selector];
			this.exec(n, p[0], p[1], p[2], p[3]);
		}
		
		$ES('*[class^=roundedCorners]',page).each(function(el){ 
			var p = el.className.split('-');
			if(p.length >= 2) this.exec([el], p[1], p[2], p[3], p[4] );
		},this);		
	},

	exec: function(nodes, corners, color, borderColor, background){
		corners = (corners || "yyyy") + 'nnnn';
		color = new Color(color) || 'transparent';
		borderColor = new Color(borderColor);
		background  = new Color(background);

		var c = corners.split('');
		/* c[0]=top-left; c[1]=top-right; c[2]=bottom-left; c[3]=bottom-right; */

		nodes.each(function(n){
			if( n.$passed ) return;
						
			var top = this.addCorner(this.$Top, c[0], c[1], color, borderColor, n),
				bottom = this.addCorner(this.$Bottom, c[2], c[3], color, borderColor, n);

			if(top || bottom) {
				this.addBody(n, color, borderColor);

				if(top){
					var p = n.getStyle('padding-top').toInt();				
					top.setStyle('margin-top', p-top.getChildren().length);
					n.setStyle('padding-top',0);					
					top.injectTop(n);					
				}

				if(bottom){
					var p = n.getStyle('padding-bottom').toInt();
					bottom.setStyle('margin-bottom', p-bottom.getChildren().length);
					n.setStyle('padding-bottom',0);
					n.adopt(bottom);
				}
			}
			if(borderColor) n.setStyle('border','none');
			n.$passed=true;
		},this);
		// problem with ie, but do we really need it here??
		//top=null;
		//bottom=null;		
	},

	getTemplate: function(template, corners){
		var t = false;
		if(corners != 'nn') for(var item in template){
			if(corners.contains(item)){
				t = template[item];
				break;
			}
		}
		return t;
	},

	addCorner: function(corner, left, right, color, border, n){

		corner = this.getTemplate(corner, left+right);
		if(!corner) return false;

		var padl = n.getStyle('padding-left').toInt(), 
			padr = n.getStyle('padding-right').toInt();
		var node = new Element('b',{'class':'roundedCorners','styles':{
			'display':'block',
			'margin-left':-1*padl,
			'margin-right':-1*padr
		} });

		corner.each(function(line){
			var el = new Element('div', {'styles': {
				'height':line.height,
				'overflow':'hidden',
				'border-width':'0',
				'background-color':color.hex
			} });

			if(border.hex){
				el.setStyles({'border-color':border.hex,'border-style':'solid'});
				
				if(line.borderTop){ 
					el.setStyles({'border-top-width':line.borderTop,'height':'0'});				
				}
			}
			if(left != 'n') el.setStyle('margin-left', line.margin);
			if(right != 'n') el.setStyle('margin-right', line.margin);

			if(border.hex){
				el.setStyles({
					'border-left-width': (left  == 'n') ? '1px': line.borderSide,
					'border-right-width': (right == 'n') ? '1px': line.borderSide
				});
			}
			node.adopt(el);
		});
		return node;
	},

	// move all children of the node inside a DIV and set color and bordercolor
	addBody: function(n, color, border){

		var padl = n.getStyle('padding-left').toInt(),
			padr = n.getStyle('padding-right').toInt();	
			
		var container = new Element('div',{'styles':{
			'overflow':'hidden',
			'margin-left':-1*padl,
			'margin-right':-1*padr,
			'padding-left':(padl==0) ? 4 : padl,
			'padding-right':(padr==0) ? 4 : padr,
			'background-color':color.hex
		} }).wrapChildren(n);

		if(border.hex){
			//n.setStyles('border','');
			var st = "1px solid " + border.hex
			container.setStyles({'border-left':st, 'border-right': st });
		}
	}
}
Wiki.addPageRender(RoundedCorners);


/**
 ** 260 Wiki Tips: 
 **/
var WikiTips =
{
	render: function(page,name) {  	
		var tips = [];
		$ES('*[class^=tip]',page).each( function(t){
			var parms = t.className.split('-');
			if( parms.length<=0 || parms[0] != 'tip' ) return;
			t.className = "tip";

			var body = new Element('span').wrapChildren(t).hide(),
				caption = (parms[1]) ? parms[1].deCamelize(): "tip.default.title".localize();

			tips.push( 
				new Element('span',{
					'class': 'tip-anchor',
					'title': caption + '::' + body.innerHTML
				}).setHTML(caption).inject(t)
			);
		});
		if( tips.length>0 ) new Tips( tips , {'className':'tip', 'Xfixed':true} );
	}
}
Wiki.addPageRender(WikiTips);


/**
 ** 270 Wiki Columns
 ** Dirk Frederickx, Mar 07
 **/
var WikiColumns =
{
	render: function(page,name) {  		
		var tips = [];
		$ES('*[class^=columns]',page).each( function(t){
			var parms = t.className.split('-');
			t.className='columns';
			WikiColumns.buildColumns(t, parms[1] || 'auto');
		});
	},

	buildColumns: function( el, width){		
		var breaks = $ES('hr',el);
		if(!breaks || breaks.length==0) return;

		var col_width = width.split(';');		
		
		var colCount = breaks.length+1;
		if(col_width.length == 1) {
			if(width=='auto') {
				width = 98/colCount+'%'				
			} else if(width=='fill') {
				;
			} else {
				width = width/colCount+'px';
			}
		} else {
			width = col_width[0];
		}

		var col_count = 1;
		
		var colDef;
		var col;
		var n;
		if(width != "fill") {
			colDef = new Element('div',{'class':'col','styles':{'width':width}}),
			col = colDef.clone().injectBefore(el.getFirst()),
			n;
		} else {
			colDef = new Element('div',{'class':'col'}),
			col = colDef.clone().injectBefore(el.getFirst()),
			n;
		}
		if(col_width.length > 1) {
			col.setStyle('width', col_width[0] + 'px');								
		}		
		while(n = col.nextSibling){
			if(n.tagName && n.tagName.toLowerCase() == 'hr'){
				col = colDef.clone();
				if(col_width.length > 1) {
					col.setStyle('width', col_width[col_count] + 'px');					
					col_count++;
				}
				$(n).replaceWith(col);
				continue;
			}
			col.appendChild(n);
		}
		new Element('div',{'styles':{'clear':'both'}}).inject(el);		
	}
}
Wiki.addPageRender(WikiColumns);


/* 300 Javascript Code Prettifier
 * based on http://google-code-prettify.googlecode.com/svn/trunk/README.html
 */
var WikiPrettify = {
	render: function(page,name){
		var els = $ES('.prettify pre, .prettify code',page); 
		if(!els || els.length==0) return;
		els.addClass('prettyprint');		

		//TODO: load assets .css and .js 
		//PRETTIFY: patch added to avoid processing of the same element
		prettyPrint(page);
	}
}
Wiki.addPageRender(WikiPrettify);

/* 310 Javascript Code Image Captions 
 */
var WikiImageCaptionPrettify = {
	render: function(page,name){		
		for (var id = 0; id < document.images.length; id++)
		{
			var im = document.images[id];
			var caption = im.nextSibling;			
			//var caption = im.nextSibling.nextSibling;	
			if(!caption) {
				caption = im.parentNode.nextSibling;
			}
			var class_name;
			if(caption && (caption.nodeType == 1)) {
				class_name = caption.getAttribute("class");
				if(!class_name) {
					class_name = caption.className;
				}
				if(!class_name) {
					class_name = "empty";
				}
			}
			
			if(caption && (caption.nodeType == 1) && (class_name == "image_caption")) {								
				//caption.setStyle('width', im.width + 'px');				
				caption.style.width = im.width + "px";
			}
			//caption = caption.nextSibling;
		}
	}
}
Wiki.addPageRender(WikiImageCaptionPrettify);


/* 320 Javascript Code Images 
 */
var WikiImagePrettify = {
	render: function(page,name){		
		for (var id = 0; id < document.images.length; id++)
		{
			var im = document.images[id];
			var myimage = im.parentNode;
			if (myimage.nodeName == "A") {
				//alert("muh");
				myimage = myimage.parentNode;
			}
			

			var class_name;
			if(myimage && (myimage.nodeType == 1)) {
				class_name = myimage.getAttribute("class");
				if(!class_name) {
					class_name = myimage.className;
				}
				if(!class_name) {
					class_name = "empty";
				}
			}
			
			if(myimage && (myimage.nodeType == 1) && (class_name == "image_image")) {								
								
				myimage.style.width = im.width + "px";
			}
			
		}
	}
}
Wiki.addPageRender(WikiImagePrettify);



/*

var WikiSlimbox = {

	render: function(page, name){
		var i = 0,
			lnk = new Element('a',{'class':'slimbox'}).setHTML('&raquo;');
			
		$ES('*[class^=slimbox]',page).each(function(slim){
			var group = 'lightbox'+ i++,
				parm = slim.className.split('-')[1] || 'img ajax',
				filter = [];

			if(parm.test('img')) filter.extend(['img.inline', 'a.attachment']); 
			if(parm.test('ajax')) filter.extend(['a.wikipage', 'a.external']); 

			$ES(filter.join(','),slim).each(function(el){
				var href = el.src||el.href,
					rel = (el.className.test('inline|attachment')) ? 'img' : 'ajax';

				if((rel=='img') && !href.test('(.bmp|.gif|.png|.jpg|.jpeg)(\\?.*)?$','i')) return;

				lnk.clone().setProperties({
					'href':href, 
					'rel':group+' '+rel,
					'title':el.alt||el.getText()
				}).injectBefore(el);

				if(el.src) el.replaceWith(new Element('a',{
					'class':'attachment',
					'href':el.src
				}).setHTML(el.alt||el.getText()));
			});
		});
		//if(i) Lightbox.init();
		//new Asset.javascript(Wiki.TemplateUrl+'scripts/slimbox.js');
	}
}
Wiki.addPageRender(WikiSlimbox);*/

var WikiLightBox = {
render: function(page, name){
	 Lightbox.init();
		//new Asset.javascript(Wiki.TemplateUrl+'scripts/slimbox.js');
}
	
}
Wiki.addPageRender(WikiLightBox);


/** 110 WikiSlimbox
 ** Inspired http://www.digitalia.be/software/slimbox by Christophe Bleys
 ** 	%%slimbox [...] %%
 ** 	%%slimbox-img  [some-image.jpg] %%
 ** 	%%slimbox-ajax [some-page links] %%
 **/


var WikiSlimbox = {

	render: function(page, name){
		var i = 0;
			//lnk = new Element('a',{'class':'slimbox'}).setHTML(el.innerHTML);
		$ES('*[class^=slimbox]',page).each(function(slim){
			var group = 'lightbox'+ i++,
				parm = slim.className.split('-')[1] || 'img ajax',
				filter = [];
			if(parm.test('img')) filter.extend(['img.inline', 'a.attachment', 'a.image_attach']); 
			if(parm.test('ajax')) filter.extend(['a.wikipage', 'a.external']); 

			$ES(filter.join(','),slim).each(function(el){
				var href = el.src||el.href;
					rel = (el.className.test('inline|attachment|image_attach')) ? 'img' : 'ajax';

				if((rel=='img') && !href.test('(.bmp|.gif|.png|.jpg|.jpeg)(\\?.*)?$','i')) return;

				
				

				el.setProperties({
					'href':href, 
					'rel':group+' '+rel,
					'title':el.alt||el.getText()
				});//.injectBefore(el);


				if(el.src) el.replaceWith(new Element('a',{
					'class':'attachment',
					'href':el.src
				}).setHTML(el.alt||el.getText()));
			});
		});
		if(i) Lightbox.init();
		//new Asset.javascript(Wiki.TemplateUrl+'scripts/slimbox.js');
	}
}
Wiki.addPageRender(WikiSlimbox);


/*var WikiLightBox= {

	render: function(page, name){
		var i = 0;
			
		$ES('*[class^=lightbox]',page).each(function(light){
			i++;
			$ES(filter.join(','),slim).each(function(el){
				var href = el.src||el.href,
					rel = (el.className.test('inline|attachment')) ? 'img' : 'ajax';

				if((rel=='img') && !href.test('(.bmp|.gif|.png|.jpg|.jpeg)(\\?.*)?$','i')) return;

				
				lnk = new Element('a',{'class':'slimbox'}).setHTML(el.innerHTML);

				lnk.clone().setProperties({
					'href':href, 
					'rel':group+' '+rel,
					'title':el.alt||el.getText()
				}).injectBefore(el);

				if(el.src) el.replaceWith(new Element('a',{
					'class':'attachment',
					'href':el.src
				}).setHTML(el.alt||el.getText()));
			});
		});
		if(i) Lightbox.init();
		
	}
}
Wiki.addPageRender(WikiLightBox); */


/*
	Slimbox v1.31 - The ultimate lightweight Lightbox clone
	by Christophe Beyls (http://www.digitalia.be) - MIT-style license.
	Inspired by the original Lightbox v2 by Lokesh Dhakar.

	Updated by Dirk Frederickx to fit JSPWiki needs
	- minimum size of image canvas DONE
	- add maximum size of image w.r.t window size DONE
	- CLOSE icon -> close x text iso icon DONE
	- <<prev, next>> links added in visible part of screen DONE
	- add size of picture to info window DONE
	- spacebor, down arrow, enter : next image DONE
	- up arrow : prev image DONE
	- allow the same picture occuring several times DONE
	- add support for external page links  => slimbox_ex DONE
*/
var Lightbox = {

	init: function(options){
		this.options = $extend({
			resizeDuration: 400,
			resizeTransition: false, /*Fx.Transitions.sineInOut,*/
			initialWidth: 250,
			initialHeight: 250,
			animateCaption: true,
			errorMessage: "slimbox.error".localize()
		}, options || {});

		this.anchors=[];
		$each(document.links, function(el){
			if (el.rel && el.rel.test(/^lightbox/i)){
				el.onclick = this.click.pass(el, this);

				this.anchors.push(el);
			}
		}, this);
		//this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);

		/*	Build float panel
			<div id="lbOverlay"></div>
			<div id="lbCenter">
				<div id="lbImage">
					<!-- img or iframe element is inserted here -->
				</div>
			</div>
			<div id="lbBottomContainer">
				<div id="lbBottom">
					<div id="lbCaption">
					<div id="lbNumber">
					<a id="lbCloseLink"></a>
					<div style="clear:both;"></div>
				</div>
			</div>
		*/
		this.overlay = new Element('div', {'id': 'lbOverlay'}).inject($('wikibody'));

		this.center = new Element('div', {'id': 'lbCenter', 'styles': {'width': this.options.initialWidth, 'height': this.options.initialHeight, 'marginLeft': -(this.options.initialWidth/2), 'display': 'none'}}).inject($('wikibody'));
		new Element('a', {'id': 'lbCloseLink', 'href':'#', 'title':'slimbox.close.title'.localize()}).inject(this.center).onclick = this.overlay.onclick = this.close.bind(this);
		this.image = new Element('div', {'id': 'lbImage'}).inject(this.center);

		this.bottomContainer = new Element('div', {'id': 'lbBottomContainer', 'styles': {'display': 'none'}}).inject($('wikibody'));
		this.bottom = new Element('div', {'id': 'lbBottom'}).inject(this.bottomContainer);
		//new Element('a', {'id': 'lbCloseLink', 'href': '#', 'title':'slimbox.close.title'.localize()}).setHTML('slimbox.close'.localize()).inject(this.bottom).onclick = this.overlay.onclick = this.close.bind(this);
		this.caption = new Element('div', {'id': 'lbCaption'}).inject(this.bottom);

		var info = new Element('div').inject(this.bottom);  
		this.prevLink = new Element('a', {'id': 'lbPrevLink', 'href': '#', 'styles': {'display': 'none'}}).setHTML('slimbox.previous'.localize()).inject(info);
		this.number = new Element('span', {'id': 'lbNumber'}).inject(info);
		this.nextLink = this.prevLink.clone().setProperties({'id': 'lbNextLink' }).setHTML('slimbox.next'.localize()).inject(info);
		this.prevLink.onclick = this.previous.bind(this);
		this.nextLink.onclick = this.next.bind(this);

 		this.error = new Element('div').setProperty('id', 'lbError').setHTML(this.options.errorMessage);
		new Element('div', {'styles': {'clear': 'both'}}).inject(this.bottom);
		
		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
			resize: this.center.effects($extend({duration: this.options.resizeDuration, onComplete: nextEffect}, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),
			image: this.image.effect('opacity', {duration: 500, onComplete: nextEffect}),
			bottom: this.bottom.effect('margin-top', {duration: 400, onComplete: nextEffect})
		};

		this.fxs = new Fx.Elements([this.center, this.image], $extend({duration: this.options.resizeDuration, onComplete: nextEffect}, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {}));
		
		this.preloadPrev = new Image();
		this.preloadNext = new Image();

		

	},

	click: function(link){
		var rel = link.rel.split(' ');
		if (rel[0].length == 8) return this.open([[url, title, rel[1]]], 0);

		var imageNum=0, images = [];
		this.anchors.each(function(el){
			var elRel = el.rel.split(' ');
			if (elRel[0]!=rel[0]) return;
			if((el.href==link.href) && (el.title==link.title)) imageNum = images.length;
			images.push([el.href, el.title, elRel[1]]);
		});
		return this.open(images, imageNum);
	},

	open: function(images, imageNum){
		this.images = images;		
		this.position();
		this.setup(true);
		this.top = window.getScrollTop() + (window.getHeight() / 15);
		this.center.setStyles({top: this.top-20, display: ''});
		this.fx.overlay.start(0.7);
		return this.changeImage(imageNum);
	},

	position: function(){
		this.overlay.setStyles({top: window.getScrollTop(), height: window.getHeight()});
	},

	setup: function(open){
		/*var elements = $A(document.getElementsByTagName('object'));
		elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
		elements.each(function(el){
			if (open) el.lbBackupStyle = el.style.visibility;			
			el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
		});*/
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		//document[fn]('keydown', this.eventKeyDown);
		this.step = 0;
	},

	/*keyboardListener: function(event){
		switch (event.keyCode){
			case 27: case 88: case 67: this.close(); break;
			case 37: case 38: case 80: this.previous(); break;	
			case 13: case 32: case 39: case 40: case 78: this.next(); break;
			default: return;
		}
		new Event(event).stop();
	},*/

	previous: function(){
		return this.changeImage(this.activeImage-1);
	},

	next: function(){
		return this.changeImage(this.activeImage+1);
	},

	changeImage: function(imageNum){
		if (this.step || (imageNum < 0) || (imageNum >= this.images.length)) return false;
		this.step = 1;
		this.activeImage = imageNum;

		this.center.style.backgroundColor = '';
		this.bottomContainer.style.display = this.prevLink.style.display = this.nextLink.style.display = 'none';
		this.fx.image.hide();
		this.center.className = 'lbLoading';

		this.preload = new Image();
		this.image.empty().setStyle('overflow','hidden');
		if( this.images[imageNum][2] == 'img' ){
			this.options.showCaption = true;
		

			
			
				this.preload.onload = this.nextEffect.bind(this);
				this.preload.src =this.images[imageNum][0];
			

			

			//this.preload.inject(this.image);
			//this.nextEffect();

		} else if (this.images[imageNum][2] == "inline") {
			this.options.showCaption = false;
			this.so = new Element('div', {});

			var whh = this.images[imageNum][1].split('x');

			var tmp_w = parseInt(whh[0]);
			var tmp_h  = parseInt(whh[1]);

			
			this.preload.width = tmp_w;
			this.preload.height = tmp_h;

			this.so.innerHTML = $(this.images[imageNum][0]).innerHTML;					
			this.so.inject(this.image);
			this.nextEffect();
			

		} else {
			this.options.showCaption = false;			
			this.iframeId = "lbFrame_"+new Date().getTime();	// Safari would not update iframe content that has static id.


			var whh = this.images[imageNum][1].split('x');

			var tmp_w = parseInt(whh[0]);
			var tmp_h  = parseInt(whh[1]);

			this.preload.width = tmp_w;
			this.preload.height = tmp_h;


			this.so = new Element('iframe').setProperties({
				id: this.iframeId,
				name: this.iframeId, 
				//width: tmp_w , 
				//height: tmp_h, 
				frameBorder:0, 
				//scrolling:'auto', 
				src:this.images[imageNum][0]
			}).inject(this.image);
		
			//var iframe = document.getElementById(this.iframeId);
			if(window.ie) 
				this.nextEffect();
			else
				this.so.onload = this.nextEffect.bind(this);
			//	//asynchronous loading?

		}
		return false;
	},

	ajaxFailure: function (){
		this.ajaxFailed = true;
		this.image.setHTML('').adopt(this.error.clone());
		this.nextEffect();
	},
	
	nextEffect: function(){
		switch (this.step++){
		case 1:
			this.center.className = '';
			var capt = '' + this.images[this.activeImage][1];
			capt = capt.replace(/\\/g,', ');
			this.caption.empty().adopt(new Element('a', {
					'href':this.images[this.activeImage][0],
					'title':"slimbox.directLink".localize(),'style':"width:100%;overflow:auto;white-space:normal;word-wrap:break-word;"
				}).setHTML(capt || ''));
				
			var type = (this.images[this.activeImage][2]=='img') ? "slimbox.info" : "slimbox.remoteRequest";
			this.number.setHTML((this.images.length == 1) ? '' : type.localize(this.activeImage+1, this.images.length));
			
			var img_w = this.preload.width;
			var img_h = this.preload.height;

			var img_w_tmp = img_w;
			var img_h_tmp = img_h;

			var w = Math.max(this.options.initialWidth,this.preload.width);

			var h = Math.max(this.options.initialHeight,this.preload.height);

			var ww = Window.getWidth()-100;
			var wh = Window.getHeight()-130; 

			
			if(w > ww) { img_h = h = Math.round(h * ww/w); img_w = w = ww; }
			if(h > wh) { img_w = w = Math.round(w * wh/h); img_h = h = wh; }
			

			this.image.style.width = this.bottom.style.width = w+'px';
			this.image.style.height = h+'px';
			
			if( this.images[this.activeImage][2]=='img') {
				//if (img_w_tmp == img_w && img_h_tmp == img_h) {
				//	this.caption.empty();
				// gwurz: we want to show just the caption and not the link to the original image
				// when the original is not more than 25% bigger than the shown image
				  if (img_w_tmp < img_w*1.25 && img_h_tmp < img_h*1.25) {
				    if (capt=='[Original Size]') this.caption.empty();
				    else this.caption.empty().adopt(new Element('div',{'style':"width:100%;overflow:auto;white-space:normal;word-wrap:break-word;"}).setHTML(capt || ''));
				  }
				

			this.image.innerHTML = "<table border=\"0\"><tr><td width=\""+w+"\" height=\""+h+"\" align=\"center\" valign=\"middle\"><img width=\""+img_w+'px'+"\" height=\""+(img_h-5)+'px'+"\" src=\""+this.images[this.activeImage][0]+"\"></td></tr></table>";


				if (this.activeImage) this.preloadPrev.src = this.images[this.activeImage-1][0];
				if (this.activeImage != (this.images.length - 1)) this.preloadNext.src = this.images[this.activeImage+1][0];
			
				this.number.setHTML(this.number.innerHTML);
//this.number.setHTML(this.number.innerHTML+'&nbsp;&nbsp;['+this.preload.width+'&#215;'+this.preload.height+']');
			} 
			else {
				this.so.style.width=(w-20)+'px';
				this.so.style.height=(h-5)+'px';					
			}
			
			if (this.options.showCaption) {
				if (this.options.animateCaption) this.bottomContainer.setStyles({height: '0px', display: ''});
			}
			this.fxs.start({
				'0': { height: [this.image.offsetHeight], width: [this.image.offsetWidth], marginLeft: [-this.image.offsetWidth/2] },
				'1': { opacity: [1] }
			});	

			break;
		case 2:
			//this.center.style.backgroundColor = '#000';

			

			this.image.setStyle('overflow','auto');
			if (this.options.showCaption) {
				this.bottomContainer.setStyles({ top: (this.top-20 + this.center.clientHeight)+'px', marginLeft: this.center.style.marginLeft });
				if (this.options.animateCaption){
					this.fx.bottom.set(-this.bottom.offsetHeight);
					this.bottomContainer.style.height = '';
					this.fx.bottom.start(0);
					break;
			
				this.bottomContainer.style.height = '';
				}
			}
		case 3:
			
			if (this.activeImage) this.prevLink.style.display = '';
			if (this.activeImage != (this.images.length - 1)) this.nextLink.style.display = '';
			this.step = 0;
		}
	},

	close: function(){
		
		if (this.step < 0) return;
		this.step = -1;
		if (this.preload){
			this.preload.onload = Class.empty;
			this.preload = null;
		}
		for (var f in this.fx) this.fx[f].stop();
		this.center.style.display = this.bottomContainer.style.display = 'none';
		//this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
		this.overlay.style.visibility = "hidden";
		this.overlay.style.opacity = 0;
		this.image.empty();
		if (typeof(EditTools) != "undefined")
			EditTools.releaseLock();
		
		
		return false;
	}
};


