var App = {};

App.Lightbox = function(){
	return {
		groups : {},
		initialize : function(){
			var hi_res = Config.Lang.HighRes||'I would like a Hi Res version of this image';
			var close = Config.Lang.Close||'Close';
			this.lightbox = Element.fromHTML('<div><div class="lightbox"><div class="t"><div class="tl"></div><div class="tr"></div></div><div class="image"><div class="loader"></div><img /></div><div class="controls"><a href="#" class="previous">Previous</a><a href="#" class="next">Next</a></div><div class="title"></div><div class="download"><a href="#">'+hi_res+'</a></div><div class="close"><a href="#" class="close">'+close+'</a></div><div class="b"><div class="bl"></div><div class="br"></div></div></div></div>');
			this.lightbox.id = 'lightbox';
			document.body.appendChild(this.lightbox);	
			$(this.lightbox).hide();					
			this.image = this.lightbox.getElementsByTagName('img')[0];
			$(this.image).hide();
			this.controls = this.lightbox.getElementsByClassName('controls')[0];
			this.controls.hide();
			this.download = this.lightbox.getElementsBySelector('div.download')[0];
			this.download.hide();
			this.downloadLink = this.download.getElementsByTagName('a')[0];
			this.title = this.lightbox.getElementsBySelector('div.title')[0];
			this.title.hide();
			this.close = this.lightbox.getElementsBySelector('a.close')[0];
			this.next = this.lightbox.getElementsByClassName('next')[0];
			this.prev = this.lightbox.getElementsByClassName('previous')[0];
			this.imageDiv = this.lightbox.getElementsByClassName('image')[0];
			this.loader = this.lightbox.getElementsByClassName('loader')[0];
			this.loader.hide();			
			this.overlay = new Element('div', {id: 'overlay'});
			this.overlay.hide();
			document.body.appendChild(this.overlay);
			this.addListeners();
		},
		addListeners : function(){
			$$('a.lightbox').each(function(link){
				var rel = link.rel;
				if(rel){
					if(!this.groups[rel]){
						this.groups[rel]=$A();
					}
					this.groups[rel].push(link.href);
				}
				Event.observe(link, 'click', this.show.bindAsEventListener(this));
			}.bind(this));		
			Event.observe(this.next, 'click', this.update.bindAsEventListener(this));
			Event.observe(this.prev, 'click', this.update.bindAsEventListener(this));
			Event.observe(this.close, 'click', this.hide.bindAsEventListener(this));
		},
		show : function(e){
			this.hideSelects();
			this.overlay.show();
						
			this.overlay.setStyle({
				height: document.body.offsetHeight+'px'
				
			});
			
			
			
			this.lightbox.setStyle({
				opacity : 1
			});
			this.imageDiv.setStyle({
				width: '200px',
				height: '200px'
			});
			this.image.hide();
			this.loader.show();
			this.lightbox.show();
			
			var width = Viewport.width();
			var height = Viewport.height();
			var dimensions = this.lightbox.getDimensions();
			
			
			var l = (width/2)-(dimensions.width/2)+'px';
			var t = (height/2)-(dimensions.height/2)+Client.scrollTop()+'px';
			
			this.lightbox.setStyle({
				top : t,
				left : l
			});
			this.lightbox.show();
			this.update(e);
		},
		update : function(e){
			Event.stop(e);
			this.title.innerHTML='&nbsp;';			
			new Effect.Opacity(this.image, {duration: 0.5, from: 1, to :0});
			var el = Event.element(e);
            		if(el.tagName.toLowerCase()=='img'||el.tagName.toLowerCase()=='span'){
		                el = el.parentNode;            
		        }			
			var rel = el.rel;
			var href = el.pathname;

			
			if(rel&&href){
				el = $$('a.lightbox').find(function(f){
					return f.pathname == href;
				});
			}
			
			if(href.indexOf('/')){
				href = '/'+href;
			}			
			
			var title;
			
			if(el.down().title){
				title = el.down().title;
			}
			
			if(rel){
		        	var i = this.groups[rel].indexOf(el.href);
		        	if(i!=0){
		        		var prev = {
		        			href:this.groups[rel][i-1],
		        			rel:rel
		        		};
		        	}
		        	if(i!=this.groups[rel].length-1){
		        		var next = {
		        			href:this.groups[rel][i+1],
		        			rel:rel
		        		};
		        	}
		        }else{
		        	next=null;
		        	prev=null;		        	
		        }
            		img = new Image();
            		img.onload = function(){
            			this.onload(img, prev, next, title);
            		}.bind(this);
		        img.src=href;		        
		},
		onload : function(img, prev, next, title){								
			
			var dimensions = this.lightbox.getDimensions();
			var _dimensions = this.imageDiv.getDimensions();
			
			var width = Viewport.width();
			var height = Viewport.height();
			
			var left = (width/2)-((dimensions.width-_dimensions.width+25+img.width)/2);
			var top = (height/2)-((dimensions.height-_dimensions.height+img.height)/2);
									
			top = top + Client.scrollTop();
			
			if(top<10){
				top=10;
			}
			if(left<10){
				left=10;
			}	
			
			var str = 'left : '+left+'px; top: '+top+'px;';
			var _str = 'width : '+img.width+'px; height : '+img.height+'px;';			
			
						
			new Effect.Parallel([new Effect.Morph(this.lightbox, {style : str}), new Effect.Morph(this.imageDiv, {style: _str})],
				{
					afterFinish : function(){
						if(next||prev||title){
							if(title){
								this.title.innerHTML=title;
							}else{
								this.title.innerHTML = '&nbsp;';
							}
							if(next){
								this.next.rel = next.rel;
								this.next.href = next.href;
								this.next.show();
							}else{
								this.next.hide();
							}
							if(prev){
								this.prev.rel = prev.rel;
								this.prev.href = prev.href;
								this.prev.show();
							}else{
								this.prev.hide();
							}							
							this.controls.show();
						}
						if(title){
							this.title.show();
						}else{
							this.title.hide();
						}
						if(window.media===true){
							var str = img.src.split('/');
							var s = str[str.length-1].split('_')[0];
							this.downloadLink.href = window.mediaUrl+s;
							this.download.show();
						}
						this.image.setStyle({opacity : 0});
						this.image.src= img.src;
						this.loader.hide();
						this.image.show();
						new Effect.Opacity(this.image, {duration: 0.5, from: 0, to: 1});
					}.bind(this)
				}
			);
		},
		hide : function(e){
			if(e){
				Event.stop(e);
			}
			
			new Effect.Opacity(this.lightbox, {
				duration: 0.5, 
				from: 1, 
				to: 0,
				afterFinish : function(){
					this.lightbox.hide();
					this.overlay.hide();
					this.showSelects();
				}.bind(this)
			});
		},
		hideSelects : function(){
			if(!document.all) return;
			$A(document.getElementsByTagName('select')).each(function(select){
				$(select).hide();
			});
		},
		showSelects : function(){
			if(!document.all) return;
			$A(document.getElementsByTagName('select')).each(function(select){
				$(select).show();
			});		
		}
	}
}();

App.ImageViewer = Class.create();
App.ImageViewer.prototype = {
	initialize : function(element){
		if(!element){
			return false;
		}		
		this.element = $(element);
		this.locked = false;
		this.parentNode = this.element.up();
		this.images = this.element.getElementsBySelector('a.lightbox');
		this.ul = this.element.getElementsBySelector('ul').first();
		this.ul.setStyle({
			marginTop: 0,
			marginLeft: 0
		});
		if(this.images.length>3){
			this.width = 0;
			this.height = 0;
			this.images.each(function(node){
				var image = node.getElementsBySelector('img').first();
				this.width += image.offsetWidth+10;
				this.height += image.offsetHeight;
			}.bind(this));
			this.addListeners();
		}else{
			this.element.getElementsBySelector('div.controls').first().hide();
		}		
	},
	addListeners : function(){
		Event.observe(this.element.getElementsBySelector('a.next').first(), 'click', this.scroll.bindAsEventListener(this));
		Event.observe(this.element.getElementsBySelector('a.prev').first(), 'click', this.scroll.bindAsEventListener(this));
	},
	scroll : function(e){
		var anim, property;
		Event.stop(e);
		if(this.locked===false){
			var direction = Event.element(e).className;			
			if(this.parentNode.parentNode.parentNode.parentNode.id=='content'){
				property = 'margin-left';
				if(direction=='next'){
					anim=parseInt(this.ul.style.marginLeft)-100;
					if(-anim>parseInt(this.width)-500){
						anim=-(parseInt(this.width)-500);
					}
				}else if(direction=='prev'){
					anim=parseInt(this.ul.style.marginLeft)+100;
					if(anim>0){
						anim=0;
					}
				}
			}
			var str = property+':'+anim+'px;'
			new Effect.Morph(this.ul, {style : str});
		}
	}
};

App.ReplaceImages = function(){
	return {
		url : "/img/site/headings/headings.php",
		initialize : function(){
			this.replace($$('div.graphic div.titles h1'), {size: 20, font: "Tondo_Cyr_Bold.ttf"});
			this.replace($$('div.graphic div.titles h2'), {size: 14, font: "Tondo_Cyr_Bold.ttf"});
			this.replace($$('div.titles h1'), {size: 20, font: "Tondo_Cyr_Bold.ttf"});
			this.replace($$('div.titles h2'), {size: 14, font: "Tondo_Cyr_Bold.ttf"});		
			this.replace($$('div#content div.reports h3'), {size: 12, font: "Tondo_Cyr_Bold.ttf"});
			this.replace($$('div#content div.publications h3'), {size: 12, font: "Tondo_Cyr_Bold.ttf"});
			this.replace($$('div#content div.news h3'), {size: 12, font: "Tondo_Cyr_Bold.ttf"});		
			this.replace($$('div.links h3'), {size: 12, font: "Tondo_Cyr_Bold.ttf"});
			this.replace($$('div.home div.col1 div.promo a.title span'), {size: 24, font: "Tondo_Cyr_Bold.ttf"});	
			this.replace($$('div.home div.col2 div.promo a.title span'), {size: 12, font: "Tondo_Cyr_Bold.ttf"});	
			this.replace($$('div.home div.col3 div.promo a.title span'), {size: 12, font: "Tondo_Cyr_Bold.ttf"});									
			this.replace($$('div.row2 div.promo a.title span'), {size: 12, font: "Tondo_Cyr_Bold.ttf"});			
			this.replace($$('div.row3 div.promo a.title span'), {size: 12, font: "Tondo_Cyr_Bold.ttf"});
			//this.replace($$('div.promo a.more span'), {size: 10, font: "Tondo_Cyr_Bold.ttf", width: 'auto'});
		},
		replace : function(elements, options){
			elements.each(function(element){
				if(!Element.hasClassName(element, 'replaced')){
					Element.addClassName(element, 'replaced');
					var color = element.getStyle('color').parseColor('#000000').replace('#','');
					var bgcolor = element.getStyle('background-color').parseColor('#ffffff').replace('#','');
					var size = element.getStyle('font-size');			
					
					var width = element.offsetWidth-parseInt(element.getStyle('padding-left'), 10)-parseInt(element.getStyle('padding-right'), 10);
					var text = this.getText(element);
					for(var j=0; j<element.childNodes.length; j++){
						element.removeChild(element.firstChild);
					}
					var url = this.url+"?t="+escape(text)+"&c="+color+"&b="+bgcolor+"&s="+options.size+"&f="+options.font;
					if(!options.width){
						url=url+'&w='+parseInt(width,10);
					}
					var holding = new Image();
					holding.onload = function(){	
						App.ReplaceImages.draw(holding, element, text, url);
					}
					holding.src=url;
				}
			}.bind(this));
		},
		getText : function(element){
			if(typeof element == "string"){
				return element;
			}else{
				if(typeof element == "undefined"){
				return element;
			}
	    	}
	    	var text = "";
	    	var kids = element.childNodes;
	    	for(var i=0;i<kids.length;i++) {
	    		if(kids[i].nodeType == 1){
	    			text += this.getText(kids[i]);
		    	}else{
	  	  		if(kids[i].nodeType == 3){
	    				text += kids[i].nodeValue;
	    			}
	    		}
		  }
		  return text;
		},
		draw : function(holding, element, text, url){
			var image = document.createElement('img');					
			image.setAttribute('width', holding.width);
			image.setAttribute('height', holding.height);
			image.style.width = holding.width+'px';
			image.style.height = holding.height+'px';
			image.alt = text;
			if(document.all){
				image.src="/img/site/layout/magic.png";
				image.style.filter='progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+url+'\' sizingMethod=\'crop\')';
			}else{				
				image.src = url;
			}					
			element.appendChild(image);
			var span = document.createElement("span");
			span.innerHTML = text;
			span.className = 'replacement';
			element.appendChild(span);
			$$('div.home').each(function(div){
				div.style.height='auto';
			});	
		}
	};
}();

Event.observe(window, 'load', function(){


	App.Lightbox.initialize();
	App.ReplaceImages.initialize();
	$$('div#content div.gallery').each(function(element){
		new App.ImageViewer(element);
	});
});
