/****************************************************
* Build lightbox dynamically on each page           *
*                                                   *
*****************************************************/

function loadLightboxVideo(flv){
	if(flv.indexOf('/flash/video-player/') >= 0){
		try {
			var root_flv = root + flv.substring(flv.indexOf('flash/video-player/'));
			getFlashMovie('video-player-swf').changeURL(root_flv);
		} catch(er){
			loadLightboxVideo.delay(500, this, [flv]);
		}
	} else {
		alert('Flash Videos must sit in the /flash/video-player/ folder in the root directory');
	}
}

function fadeErrorMsgs(){
	var errors = $$(".fc-tbx");
	var duration = 300;
	if(browser.isIE){ duration = 0; }
	
	var fx = new Fx.Elements(errors, {
		duration: duration
	});
	
	var o = {};
	errors.each(function(error, i) {
		o[i] = {opacity: 0};
	});
	
	fx.start(o);
}

function fadeLightBox(){
	var duration = 300;
	if(browser.isIE){ duration = 0; }
	
	var oDivs = $('lightbox-content-inner').getElements('div');
	var blendFX = new Fx.Morph($('lightbox-content-inner'), {
		duration: duration,
		onComplete: function(){
			$each(oDivs, function(div,ind){
				if(div.getStyle('overflow') == 'auto'){
					div.setStyle('overflow', 'hidden');
				}
			});
		}
	});	
	
	fadeErrorMsgs();
	blendFX.start({ 'opacity':0 });
	if(browser.isIE){ $$('#lightbox-content-inner .sIFR-replaced').setStyle('opacity', 0); }		
	
}

function resizeLightBox(){
	var diff = $('lightbox-content-inner').getSize().y - $('lb-body').getSize().y;
	
	if(diff < 0){ diff = -1 * diff; }
	
	if(diff > 15){
		$('lightbox-content-inner').setStyle('height', $('lb-body').getSize().y - 2);
		if($('lightbox-overlay')){
			if($('lightbox-overlay').getStyle('height').toInt() > 0){
				$('lightbox-overlay').setStyle('height', Math.max($('wrapper').getSize().y, $('lightbox').getSize().y));
			}
		}
	}
}

function attachLbEvents(){
	if($('lightbox-content-inner')){
		var target, as = $('lightbox-content-inner').getElements('a');
		$each(as, function(a,i){
			if(a.get('target')){ target = a.get('target'); }
			else { target = '_self'; }
			
			if(!a.hasClass('no-lb') && target != '_blank' && a.get('href').indexOf('mailto:') < 0 && a.get('href') != '#'){
				a.addEvents({
					'keypress': function(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ event.stop(); fadeLightBox(); openLbPage.delay(300, this, [a]); } } },
					'click': function(event){ event.stop(); fadeLightBox(); openLbPage.delay(300, this, [a]); a.blur(); }
				});
			}
		});
	}
	
	if($('lb-body')){
		$('lb-body').addEvents({
			'keypress': function(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ resizeLightBox(); } } },
			'click': function(event){ resizeLightBox(); }
		});
	}
}

function openLightBox(el, url, x, y, width, height){
	
	if (TRACE) alert("START openLightBox(" + el + ", " + url + ", " + x + ", " + y + ", " + width + ", " + height + ")");
	
	if($('wrapper') && $('header')){
		var coords= {}, hCoords, flash;
		var opened = true;
		var duration = 300;
		var openWidth = 960, openLeft;
		var isImage = false, isVideo = false;
		if(browser.isIE){ duration = 0; }
		
		var href;
		if(el){
			if(el.get('href')){ href = el.get('href'); }
			else if(url){ href = url; }
		} else if(url){
			href = url;
		}
		
		if(href.endsWith('.jpg') || href.endsWith('.gif') || href.endsWith('.png') || href.indexOf('getImage.php') >= 0){
			isImage = true;
		}
		
		if(href.endsWith('.flv')){
			isVideo = true;
		}
		
		if(!$('lightbox').get('open') || $('lightbox').get('open') == 0){
			opened = false;
			$('lightbox').set('open', 1);
			if(url){
				flash = $('t1Flash') || $('flash-banner');
				coords.left = flash.getPosition($('wrapper')).x.toInt() + x.toInt();
				coords.top = flash.getPosition($('wrapper')).y.toInt() + y.toInt();
				coords.width = width.toInt();
				coords.height = height.toInt();
			} else {
				coords = el.getCoordinates($('wrapper'));
				if(coords.left < 0){
					if(9999 + coords.left > 0 && 9999 + coords.left < 960){
						coords.left = 9999 + coords.left;
					} else if(99999 + coords.left > 0 && 99999 + coords.left < 960){
						coords.left = 99999 + coords.left;
					} else if(999999 + coords.left > 0 && 999999 + coords.left < 960){
						coords.left = 999999 + coords.left;
					} else if(9999999 + coords.left > 0 && 9999999 + coords.left < 960){
						coords.left = 9999999 + coords.left;
					}
				}
			}
			
			hCoords = $('header').getCoordinates($('wrapper'));
		}
		
		var elements = [$('lightbox'), $('lightbox-content-inner'), $('lightbox-close-but')];
		var o1 = {}, o2 = {};
		var blendFX = new Fx.Elements([elements[1], elements[2]], {
			duration: duration,
			onComplete: function(){ $('lightbox').set('busy', 0); }
		});
		
		var growFX = new Fx.Elements([elements[0], elements[1]], {
			duration: 600,
			transition: Fx.Transitions.Cubic.easeOut,
			onComplete: function(){
				if(!isVideo){
					$('lightbox-content-inner').innerHTML = $('lightbox-tmp').innerHTML;
				} else {
					var video_player = new Swiff(root + 'flash/video-player/video_player.swf', {
						id: 'video-player-swf',
						width: 504,
						height: 335,
						container: $('lightbox-content-inner'),
						params: {
							play: 'true',
							loop: 'true',
							wmode: 'transparent',
							menu: 'true',
							scale: 'showall',
							salign: 'tl',
							bgcolor: '#FFFFFF',
							devicefont: 'false',
							allowfullscreen: 'true',
							allowscriptaccess: 'sameDomain',
							allownetworking: 'all'
						},
						vars: {},
						callBacks: {
							onFlashLoad: function() { }
						}
					});
					
					loadLightboxVideo(href);
				}
				
				$('lightbox-tmp').innerHTML = '';
				
				if(el){
					if(el.hasClass('upload')){
						try {
							createUploadObject();
						} catch(error){}
					}
				}
				
				if($('lightbox-overlay')){
					$('lightbox-overlay').addEvents({
						'click': function(){ /*closeLightBox();*/ }
					});
				}
				
				$('lightbox-overlay').setStyle('height', Math.max($('wrapper').getSize().y, $('lightbox').getSize().y));
				
				attachLbEvents();
				blendFX.start(o2);
			}
		});
		
		if(!opened){
			$('lightbox').setStyles({ 'left': coords.left - 8, 'top': coords.top - 8 });
			$('lightbox-content-inner').setStyles({ 'width': coords.width, 'height': coords.height });
			$('lightbox').set('oLeft', coords.left - 8);
			$('lightbox').set('oTop', coords.top - 8);
			$('lightbox').set('oWidth', coords.width);
			$('lightbox').set('oHeight', coords.height);
			
			openLeft = hCoords.left + 3;
			if(isImage){
				openLeft = hCoords.left + 3 + ((960 - $('lightbox-tmp').getElements('img')[0].width) / 2).toInt()
			}
			
			if(isVideo){
				openLeft = hCoords.left + 3 + ((960 - 504) / 2).toInt()
			}
		
			o1[0] = {left: openLeft, top: 0};
			if(el){
				if(el.hasClass('to-center')){
					o1[0] = {left: openLeft, top: Math.max(0, parseInt(getSizeY()/2,10) - parseInt($('lightbox-tmp').getSize().y/2,10) + window.getScroll().y - 8)};
				}
			}
		}
		
		if(isImage){
			openWidth = $('lightbox-tmp').getElements('img')[0].width;
		}
		
		if(isVideo){
			openWidth = 504;
		}
		o1[1] = {width: openWidth, height: $('lightbox-tmp').getSize().y};
		
		o2[0] = {opacity: 1};
		o2[1] = {opacity: 1};
		growFX.start(o1);
	}
	
	if (TRACE) alert("END openLightBox");
}

function closeLightBox(){
	if($('lightbox').get('busy') == 1){ return; }
	var coords = {};
	var elements = [$('lightbox'), $('lightbox-content-inner'), $('lightbox-close-but')];
	var o1 = {}, o2 = {};
	var duration = 300;
	if(browser.isIE){ duration = 0; }
	
	var growFX = new Fx.Elements([elements[0], elements[1]], {
		duration:600,
		transition: Fx.Transitions.Cubic.easeIn,
		onComplete: function(){
			$('lightbox-overlay').setStyle('height', 0);			
			$('lightbox').set('open', 0);
			$('lightbox').setStyles({
				'left': -99999,
				'top': -99999
			});
			
			$('lightbox').set('busy', 0);
		}
	});
	
	var blendFX = new Fx.Elements([elements[1], elements[2]], {
		duration: duration,
		onComplete: function(){
			$('lightbox-content-inner').innerHTML = '';
			growFX.start(o1);
		}
	});
	
	$('lightbox').set('busy', 1);
	
	$('lightbox-overlay').removeEvents('click');
	if($('lb-body')){
		$('lb-body').removeEvents('keypress');
		$('lb-body').removeEvents('click');
	}
	
	coords.left = $('lightbox').get('oLeft');
	coords.top = $('lightbox').get('oTop');
	coords.width = $('lightbox').get('oWidth');
	coords.height = $('lightbox').get('oHeight');
	
	o1[0] = {left: coords.left, top: coords.top};
	o1[1] = {width: coords.width, height: coords.height};
	o2[0] = {opacity: 0};
	o2[1] = {opacity: 0};
	
	fadeErrorMsgs();
	blendFX.start(o2);
}

function readLbHtml(el, url, x, y, width, height){
	
	if (TRACE) alert("START readLbHtml(" + el + ", " + url + ", " + x + ", " + y + ", " + width + ", " + height + ")");
	
	var href, isImage = false, isVideo = false;
	if(el){
		if(el.get('href')){ href = el.get('href'); }
		else if(url){ href = url; }
	} else if(url){
		href = url;
	}
	
	if(href.endsWith('.jpg') || href.endsWith('.gif') || href.endsWith('.png') || href.indexOf('getImage.php') >= 0){
		isImage = true;
	}
	
	if(href.endsWith('.flv')){
		isVideo = true;
	}
	
	if(isImage){
		if (DEBUG) alert("isImage");
		var aImage = new Asset.image(href, {
			onload: function(){
				if (TRACE) alert("START onload for image '" + href + "'");
				$('lightbox-tmp').innerHTML = '<img src="' + href + '" alt="" width="' + aImage.width + '" height="' + aImage.height + '" />';
				openLightBox(el, url, x, y, width, height);
				if (TRACE) alert("END onload for image '" + href + "'");
			}
		});		
		
	} else if(isVideo){
		if (DEBUG) alert("isVideo");
		$('lightbox-tmp').innerHTML = '';
		
		var lightbox_video_holder = new Element('div', {
			'id': 'lightbox-video-holder',
			'styles': {
				'width': 504,
				'height': 335
			}
		}).inject($('lightbox-tmp'));

		openLightBox(el, url, x, y, width, height);
		
	} else {
		if (DEBUG) alert("isHTML");
		var html = new Request.HTML({
			method: 'get',
			url: href,
			noCache: true,
			evalScripts: false,
			onRequest: function(){ },
			onComplete: function(){ },
			onSuccess: function(tree, elements, html, js){
				if (DEBUG) alert("Successfully loaded '" + href + "'");
				var ajaxContent = elements.filter(function(elm) {
					return elm.id.test(/^ajax-content/i);
				});
				
				if(ajaxContent.length > 0){
					$('lightbox-tmp').innerHTML = ajaxContent[0].innerHTML;
					openLightBox(el, url, x, y, width, height);
				} else {
					if (DEBUG) alert("That page contains no 'ajax-content' element");
				}
			},
			onFailure: function(xhr){
				if (DEBUG) alert("Failed to load '" + href + "'");
				$('lightbox').set('busy', 0);
				// rather than do nothing when the page fails to load, let's try to actually go there in the current window
				// at least this way, the error will be explained to the user
				window.location = href;
			}
		}).send();
	}
	
	if (TRACE) alert("END readLbHtml");
	
}

function openLbPage(el, url, x, y, width, height){
	
	if (TRACE) alert("START openLbPage(" + el + ", " + url + ", " + x + ", " + y + ", " + width + ", " + height + ")");
	
	if($('lightbox').get('busy') == 1){
		if (TRACE) { alert("busy"); alert("END openLbPage"); }
		return;
	}
	var duration = 0;
	
	if(window.getScroll().y > 0){
		duration = parseInt(300 + window.getScroll().y/4, 10);
	}
	
	if($('lightbox-overlay')){
		$('lightbox-overlay').setStyle('height', $('wrapper').getSize().y);
	}
	
	if(el){
		if(!el.get('href')){
			if (TRACE) { alert("no href"); alert("END openLbPage"); }
			return;
		}
	} else {
		if(!url){
			if (TRACE) { alert("no url"); alert("END openLbPage"); }
			return;
		}
	}
	
	var bodyFx = new Fx.Scroll(window, {
		duration: duration,
		wheelStops: false,
		onComplete: function(){
			readLbHtml(el, url, x, y, width, height);
		}
	});
	
	$('lightbox').set('busy', 1);
	
	if(el){
		if(el.hasClass('to-center')){
			readLbHtml(el, url, x, y, width, height);
		} else {
			bodyFx.start(0, 0);
		}
	} else {
		bodyFx.start(0, 0);
	}
	
	if (TRACE) alert("END openLbPage");
	
}

function initLightbox(){
	
	if (TRACE) alert("START initLightBox");
	
	if($('wrapper')){
		
		var lightbox = new Element('div', { 'id': 'lightbox' }).inject($('wrapper'), 'top');
		lightbox.innerHTML = '<div id="lb-br"><div id="lb-tr"><div id="lb-tl"><div id="lb-top"><div id="lb-base"><div id="lb-right"><div id="lb-left"><div id="lightbox-content"><div id="lightbox-content-inner"></div></div></div></div></div></div></div></div></div>';
		lightbox.set('busy',0);
		
		var lightbox_tmp = new Element('div', { 'id': 'lightbox-tmp' }).inject($('wrapper'), 'bottom');
		var lightbox_overlay = new Element('div', {
			'id': 'lightbox-overlay'
		}).inject($('wrapper'), 'bottom');
		
		var lightbox_close = new Element('div', {
			'id': 'lightbox-close-but',
			'class': 'lightbox-close',
			'styles': {'opacity': 0},
			'events': {
				'click': function(){ closeLightBox(); },
				'mouseenter': function(){ this.addClass('lightbox-close-over'); },
				'mouseleave': function(){ this.removeClass('lightbox-close-over'); }
			}
		}).inject($('lightbox-content'));
		
		$('lightbox-content-inner').setStyle('opacity', 0);
		
		var as = $(document.body).getElements('a.lb');
		$each(as, function(a,i){
			if (DEBUG) alert(a.href + " will be converted to a lightbox");
			a.addEvents({
				'keypress': function(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ event.stop(); openLbPage(a); } } },
				'click': function(event){ event.stop(); openLbPage(a); a.blur(); }
			});
		});
		
		window.addEvents({
			'keypress': function(event){ if(event.key){ if(event.key == 'esc'){ closeLightBox(); } } },
			'resize': function(event){ }
		});
		
	}
	
	if (TRACE) alert("END initLightBox");
	
}
