<?
/*
Extension Name: LightBox
Extension Url: http://vanilla.baldursoft.de/LightBox
Description: LightBox is a simple script used to overlay images on the current page. Developers: Check out my site for information.
Version: 2.03.3 - c
Author: Alex Lanin
Author Url: mailto:alex@lanin.de
*/

// a little security
if (!defined('IN_VANILLA')) exit();

define('LIGHTBOX_EXTENSION', true);

// are these definitions necessary?
define('LIGHTBOX_EXTENSION_VERSION', '2.03.3 - c');
define('LIGHTBOX_VERSION', '2.03.3');


function includeLightBox() {
	if(defined('LIGHTBOX_INCLUDED')) return;

	global $Head, $Configuration;
	
	$Head->AddScript('js/prototype.js');
	$Head->AddScript('js/scriptaculous.js');
	$Head->AddScript('extensions/LightBox/LightBox.js');
	$Head->AddStylesheet('extensions/LightBox/LightBox.css');

	define('LIGHTBOX_INCLUDED', true);
}


// -----------------------------------------------------------------------------------------
// ------------------- don't bother reading anything below this line ;-) -------------------
// -----------------------------------------------------------------------------------------




// not in class, so it can be called if files are not existing
function writeFiles() {
// this is the unmodified Lightbox v2.03.3 css
// only one change: $path
$css = '#lightbox{position:absolute;left:0;width:100%;z-index:100;text-align:center;line-height:0}
#lightbox a img{border:none}
#outerImageContainer{position:relative;background-color:#fff;width:250px;height:250px;margin:0 auto}
#imageContainer{padding:10px}
#loading{position:absolute;top:40%;left:0%;height:25%;width:100%;text-align:center;line-height:0}
#hoverNav{position:absolute;top:0;left:0;height:100%;width:100%;z-index:10}
#imageContainer>#hoverNav{left:0}
#hoverNav a{outline:none}
#prevLink,#nextLink{width:49%;height:100%;background:transparent url($path/blank.gif) no-repeat;display:block}
#prevLink{left:0;float:left}
#nextLink{right:0;float:right}
#prevLink:hover,#prevLink:visited:hover{background:url($path/prevlabel.gif) left 15% no-repeat}
#nextLink:hover,#nextLink:visited:hover{background:url($path/nextlabel.gif) right 15% no-repeat}
#imageDataContainer{font:10px Verdana,Helvetica,sans-serif;background-color:#fff;margin:0 auto;line-height:1.4em;overflow:auto;width:100%}
#imageData{padding:0 10px;color:#666}
#imageData #imageDetails{width:70%;float:left;text-align:left}
#imageData #caption{font-weight:bold}
#imageData #numberDisplay{display:block;clear:left;padding-bottom:1.0em}
#imageData #bottomNavClose{width:66px;float:right;padding-bottom:0.7em}
#overlay{position:absolute;top:0;left:0;z-index:90;width:100%;height:500px;background-color:#000}';

// this is the unmodified Lightbox v2.03.3 js
// changes: $path, $trans, $animate, $speed
$js = '// Lightbox v2.03.3
// by Lokesh Dhakar - http://www.huddletogether.com
// For more information on this script, visit: http://huddletogether.com/projects/lightbox2
// This is the same script but compressed (nearly) as much as possible
// http://www.codeandcoffee.com/2006/10/02/compress-your-javascript/ with Compression Level Medium

var fileLoadingImage="$path/loading.gif";var fileBottomNavCloseImage="$path/closelabel.gif";var overlayOpacity=$trans;var animate=$animate;var resizeSpeed=$speed;var borderSize=10;var imageArray=new Array;var activeImage;if(animate==true){overlayDuration=0.2;if(resizeSpeed>10){resizeSpeed=10;}
if(resizeSpeed<1){resizeSpeed=1;}
resizeDuration=(11-resizeSpeed)*0.15;}else{overlayDuration=0;resizeDuration=0;}
Object.extend(Element,{getWidth:function(element){element=$(element);return element.offsetWidth;},setWidth:function(element,w){element=$(element);element.style.width=w+"px";},setHeight:function(element,h){element=$(element);element.style.height=h+"px";},setTop:function(element,t){element=$(element);element.style.top=t+"px";},setLeft:function(element,l){element=$(element);element.style.left=l+"px";},setSrc:function(element,src){element=$(element);element.src=src;},setHref:function(element,href){element=$(element);element.href=href;},setInnerHTML:function(element,content){element=$(element);element.innerHTML=content;}});Array.prototype.removeDuplicates=function(){for(i=0;i<this.length;i++){for(j=this.length-1;j>i;j--){if(this[i][0]==this[j][0]){this.splice(j,1);}}}}
Array.prototype.empty=function(){for(i=0;i<=this.length;i++){this.shift();}}
var Lightbox=Class.create();Lightbox.prototype={initialize:function(){this.updateImageList();var objBody=document.getElementsByTagName("body").item(0);var objOverlay=document.createElement("div");objOverlay.setAttribute("id","overlay");objOverlay.style.display="none";objOverlay.onclick=function(){myLightbox.end();}
objBody.appendChild(objOverlay);var objLightbox=document.createElement("div");objLightbox.setAttribute("id","lightbox");objLightbox.style.display="none";objLightbox.onclick=function(e){if(!e)var e=window.event;var clickObj=Event.element(e).id;if(clickObj=="lightbox"){myLightbox.end();}};objBody.appendChild(objLightbox);var objOuterImageContainer=document.createElement("div");objOuterImageContainer.setAttribute("id","outerImageContainer");objLightbox.appendChild(objOuterImageContainer);if(animate){Element.setWidth("outerImageContainer",250);Element.setHeight("outerImageContainer",250);}else{Element.setWidth("outerImageContainer",1);Element.setHeight("outerImageContainer",1);}
var objImageContainer=document.createElement("div");objImageContainer.setAttribute("id","imageContainer");objOuterImageContainer.appendChild(objImageContainer);var objLightboxImage=document.createElement("img");objLightboxImage.setAttribute("id","lightboxImage");objImageContainer.appendChild(objLightboxImage);var objHoverNav=document.createElement("div");objHoverNav.setAttribute("id","hoverNav");objImageContainer.appendChild(objHoverNav);var objPrevLink=document.createElement("a");objPrevLink.setAttribute("id","prevLink");objPrevLink.setAttribute("href","#");objHoverNav.appendChild(objPrevLink);var objNextLink=document.createElement("a");objNextLink.setAttribute("id","nextLink");objNextLink.setAttribute("href","#");objHoverNav.appendChild(objNextLink);var objLoading=document.createElement("div");objLoading.setAttribute("id","loading");objImageContainer.appendChild(objLoading);var objLoadingLink=document.createElement("a");objLoadingLink.setAttribute("id","loadingLink");objLoadingLink.setAttribute("href","#");objLoadingLink.onclick=function(){myLightbox.end();return false;}
objLoading.appendChild(objLoadingLink);var objLoadingImage=document.createElement("img");objLoadingImage.setAttribute("src",fileLoadingImage);objLoadingLink.appendChild(objLoadingImage);var objImageDataContainer=document.createElement("div");objImageDataContainer.setAttribute("id","imageDataContainer");objLightbox.appendChild(objImageDataContainer);var objImageData=document.createElement("div");objImageData.setAttribute("id","imageData");objImageDataContainer.appendChild(objImageData);var objImageDetails=document.createElement("div");objImageDetails.setAttribute("id","imageDetails");objImageData.appendChild(objImageDetails);var objCaption=document.createElement("span");objCaption.setAttribute("id","caption");objImageDetails.appendChild(objCaption);var objNumberDisplay=document.createElement("span");objNumberDisplay.setAttribute("id","numberDisplay");objImageDetails.appendChild(objNumberDisplay);var objBottomNav=document.createElement("div");objBottomNav.setAttribute("id","bottomNav");objImageData.appendChild(objBottomNav);var objBottomNavCloseLink=document.createElement("a");objBottomNavCloseLink.setAttribute("id","bottomNavClose");objBottomNavCloseLink.setAttribute("href","#");objBottomNavCloseLink.onclick=function(){myLightbox.end();return false;}
objBottomNav.appendChild(objBottomNavCloseLink);var objBottomNavCloseImage=document.createElement("img");objBottomNavCloseImage.setAttribute("src",fileBottomNavCloseImage);objBottomNavCloseLink.appendChild(objBottomNavCloseImage);},updateImageList:function(){if(!document.getElementsByTagName){return;}
var anchors=document.getElementsByTagName("a");var areas=document.getElementsByTagName("area");for(var i=0;i<anchors.length;i++){var anchor=anchors[i];var relAttribute=String(anchor.getAttribute("rel"));if(anchor.getAttribute("href")&&(relAttribute.toLowerCase().match("lightbox"))){anchor.onclick=function(){myLightbox.start(this);return false;}}}
for(var i=0;i<areas.length;i++){var area=areas[i];var relAttribute=String(area.getAttribute("rel"));if(area.getAttribute("href")&&(relAttribute.toLowerCase().match("lightbox"))){area.onclick=function(){myLightbox.start(this);return false;}}}},start:function(imageLink){hideSelectBoxes();hideFlash();var arrayPageSize=getPageSize();Element.setWidth("overlay",arrayPageSize[0]);Element.setHeight("overlay",arrayPageSize[1]);new Effect.Appear("overlay",{duration:overlayDuration,from:0.0,to:overlayOpacity});imageArray=[];imageNum=0;if(!document.getElementsByTagName){return;}
var anchors=document.getElementsByTagName(imageLink.tagName);if((imageLink.getAttribute("rel")=="lightbox")){imageArray.push(new Array(imageLink.getAttribute("href"),imageLink.getAttribute("title")));}else{for(var i=0;i<anchors.length;i++){var anchor=anchors[i];if(anchor.getAttribute("href")&&(anchor.getAttribute("rel")==imageLink.getAttribute("rel"))){imageArray.push(new Array(anchor.getAttribute("href"),anchor.getAttribute("title")));}}
imageArray.removeDuplicates();while(imageArray[imageNum][0]!=imageLink.getAttribute("href")){imageNum++;}}
var arrayPageScroll=getPageScroll();var lightboxTop=arrayPageScroll[1]+(arrayPageSize[3]/10);var lightboxLeft=arrayPageScroll[0];Element.setTop("lightbox",lightboxTop);Element.setLeft("lightbox",lightboxLeft);Element.show("lightbox");this.changeImage(imageNum);},changeImage:function(imageNum){activeImage=imageNum;if(animate){Element.show("loading");}
Element.hide("lightboxImage");Element.hide("hoverNav");Element.hide("prevLink");Element.hide("nextLink");Element.hide("imageDataContainer");Element.hide("numberDisplay");imgPreloader=new Image();imgPreloader.onload=function(){Element.setSrc("lightboxImage",imageArray[activeImage][0]);myLightbox.resizeImageContainer(imgPreloader.width,imgPreloader.height);imgPreloader.onload=function(){};}
imgPreloader.src=imageArray[activeImage][0];},resizeImageContainer:function(imgWidth,imgHeight){this.widthCurrent=Element.getWidth("outerImageContainer");this.heightCurrent=Element.getHeight("outerImageContainer");var widthNew=(imgWidth+(borderSize*2));var heightNew=(imgHeight+(borderSize*2));this.xScale=(widthNew/this.widthCurrent)*100;this.yScale=(heightNew/this.heightCurrent)*100;wDiff=this.widthCurrent-widthNew;hDiff=this.heightCurrent-heightNew;if(!(hDiff==0)){new Effect.Scale("outerImageContainer",this.yScale,{scaleX:false,duration:resizeDuration,queue:"front"});}
if(!(wDiff==0)){new Effect.Scale("outerImageContainer",this.xScale,{scaleY:false,delay:resizeDuration,duration:resizeDuration});}
if((hDiff==0)&&(wDiff==0)){if(navigator.appVersion.indexOf("MSIE")!=-1){pause(250);}else{pause(100);}}
Element.setHeight("prevLink",imgHeight);Element.setHeight("nextLink",imgHeight);Element.setWidth("imageDataContainer",widthNew);this.showImage();},showImage:function(){Element.hide("loading");new Effect.Appear("lightboxImage",{duration:resizeDuration,queue:"end",afterFinish:function(){myLightbox.updateDetails();}});this.preloadNeighborImages();},updateDetails:function(){if(imageArray[activeImage][1]){Element.show("caption");Element.setInnerHTML("caption",imageArray[activeImage][1]);}
if(imageArray.length>1){Element.show("numberDisplay");Element.setInnerHTML("numberDisplay","Image "+eval(activeImage+1)+" of "+imageArray.length);}
new Effect.Parallel([new Effect.SlideDown("imageDataContainer",{sync:true,duration:resizeDuration,from:0.0,to:1.0}),new Effect.Appear("imageDataContainer",{sync:true,duration:resizeDuration})],{duration:resizeDuration,afterFinish:function(){var arrayPageSize=getPageSize();Element.setHeight("overlay",arrayPageSize[1]);myLightbox.updateNav();}});},updateNav:function(){Element.show("hoverNav");if(activeImage!=0){Element.show("prevLink");document.getElementById("prevLink").onclick=function(){myLightbox.changeImage(activeImage-1);return false;}}
if(activeImage!=(imageArray.length-1)){Element.show("nextLink");document.getElementById("nextLink").onclick=function(){myLightbox.changeImage(activeImage+1);return false;}}
this.enableKeyboardNav();},enableKeyboardNav:function(){document.onkeydown=this.keyboardAction;},disableKeyboardNav:function(){document.onkeydown="";},keyboardAction:function(e){if(e==null){keycode=event.keyCode;escapeKey=27;}else{keycode=e.keyCode;escapeKey=e.DOM_VK_ESCAPE;}
key=String.fromCharCode(keycode).toLowerCase();if((key=="x")||(key=="o")||(key=="c")||(keycode==escapeKey)){myLightbox.end();}else if((key=="p")||(keycode==37)){if(activeImage!=0){myLightbox.disableKeyboardNav();myLightbox.changeImage(activeImage-1);}}else if((key=="n")||(keycode==39)){if(activeImage!=(imageArray.length-1)){myLightbox.disableKeyboardNav();myLightbox.changeImage(activeImage+1);}}},preloadNeighborImages:function(){if((imageArray.length-1)>activeImage){preloadNextImage=new Image();preloadNextImage.src=imageArray[activeImage+1][0];}
if(activeImage>0){preloadPrevImage=new Image();preloadPrevImage.src=imageArray[activeImage-1][0];}},end:function(){this.disableKeyboardNav();Element.hide("lightbox");new Effect.Fade("overlay",{duration:overlayDuration});showSelectBoxes();showFlash();}}
function getPageScroll(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
arrayPageScroll=new Array(xScroll,yScroll)
return arrayPageScroll;}
function getPageSize(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}
windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=xScroll;}else{pageWidth=windowWidth;}
arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight)
return arrayPageSize;}
function getKey(e){if(e==null){keycode=event.keyCode;}else{keycode=e.which;}
key=String.fromCharCode(keycode).toLowerCase();if(key=="x"){}}
function listenKey(){document.onkeypress=getKey;}
function showSelectBoxes(){var selects=document.getElementsByTagName("select");for(i=0;i!=selects.length;i++){selects[i].style.visibility="visible";}}
function hideSelectBoxes(){var selects=document.getElementsByTagName("select");for(i=0;i!=selects.length;i++){selects[i].style.visibility="hidden";}}
function showFlash(){var flashObjects=document.getElementsByTagName("object");for(i=0;i<flashObjects.length;i++){flashObjects[i].style.visibility="visible";}
var flashEmbeds=document.getElementsByTagName("embed");for(i=0;i<flashEmbeds.length;i++){flashEmbeds[i].style.visibility="visible";}}
function hideFlash(){var flashObjects=document.getElementsByTagName("object");for(i=0;i<flashObjects.length;i++){flashObjects[i].style.visibility="hidden";}
var flashEmbeds=document.getElementsByTagName("embed");for(i=0;i<flashEmbeds.length;i++){flashEmbeds[i].style.visibility="hidden";}}
function pause(ms){var date=new Date();curDate=null;do{var curDate=new Date();}
while(curDate-date<ms);}
function initLightbox(){myLightbox=new Lightbox();}
Event.observe(window,"load",initLightbox,false);';

	global $Configuration, $Context;
	
	// set file
	$SettingsFile = $Context->Configuration['EXTENSIONS_PATH'] . 'LightBox/settings.php';
	
	// create ConfigurationManager instance
	$Config = $Context->ObjectFactory->NewContextObject($Context, 'ConfigurationManager');
	
	// load settings
	$Config->GetSettingsFromFile($SettingsFile);
	

	$css = str_replace('$path', $Configuration['WEB_ROOT'] . 'extensions/LightBox', $css);
	if(file_put_contents($Configuration['EXTENSIONS_PATH'] . 'LightBox/LightBox.css', $css) == false) return false;
	
	$js = str_replace('$path', $Configuration['WEB_ROOT'] . 'extensions/LightBox', $js);
	$js = str_replace('$trans', $Config->GetSetting('trans'), $js);
	$js = str_replace('$animate', $Config->GetSetting('speed') == 11 ? 'false' : 'true', $js);
	$js = str_replace('$speed', min(10, $Config->GetSetting('speed')), $js);
	if(file_put_contents($Configuration['EXTENSIONS_PATH'] . 'LightBox/LightBox.js', $js) == false) return false;
	
	return true;
}

// check for css and js files
if(!file_exists($Configuration['EXTENSIONS_PATH'] . 'LightBox/LightBox.css') ||
   !file_exists($Configuration['EXTENSIONS_PATH'] . 'LightBox/LightBox.js')) {

	if(!writeFiles())
		$Context->WarningCollector->Add('Could not create LightBox files. Try creating a LightBox.css and LightBox.js in extensions/LightBox/ and chmod them to 777');

}



if ($Context->SelfUrl == "settings.php" && $Context->Session->User->Permission('PERMISSION_CHANGE_APPLICATION_SETTINGS')) {


	error_reporting(E_ALL);

	class LightBoxSettings extends PostBackControl
	{
		var $Config;
		
		function LightBoxSettings(&$Context) 
		{
			if (ForceIncomingString('PostBackAction', '') != 'LightBoxSettings') return;

			$this->Name = 'LightBoxSettings';
			$this->ValidActions = array('LightBoxSettings');
			$this->Constructor($Context);
			
			// set file
			$SettingsFile = $Context->Configuration['EXTENSIONS_PATH'] . 'LightBox/settings.php';
			
			// create ConfigurationManager instance
			$this->Config = $Context->ObjectFactory->NewContextObject($Context, 'ConfigurationManager');
			
			// load settings
			$this->Config->GetSettingsFromFile($SettingsFile);

			// yeah it's not clean coded using $_GET, but it's easy ;)
			// $_GET['saved'] is boolean whether saving was succuessfull
			if(isset($_POST['save'])) {
				$this->Config->DefineSetting('trans', doubleval($_POST['trans']), true);
				$this->Config->DefineSetting('speed', intval($_POST['speed']), true);
				$_GET['saved'] = $this->Config->SaveSettingsToFile($SettingsFile);

				// reload settings, since $Config doesn't contain what was just saved....
				// bug or feature? ;-)
				$this->Config->GetSettingsFromFile($SettingsFile);
			}
		}

		function Render() {
			if (ForceIncomingString('PostBackAction', '') != 'LightBoxSettings') return;

			// no idea what this does
			$this->PostBackParams->Clear();


			if (isset($_GET['saved']))
				if($_GET['saved']) {
					echo	'<div id="Success">Settings saved</div>';
					
					if(writeFiles())
						echo	'<div id="Success">LightBox js and css created</div>';
					else
						echo	'<div class="ErrorContainer">ERROR: LightBox js or css NOT created! Try creating a LightBox.css and LightBox.js in extensions/LightBox/ and chmod them to 777</div>';
				} else
					echo	'<div class="ErrorContainer">Error: Settings NOT saved</div>';


			?>
			<div id="Form">
				<fieldset>
					<legend>LightBox Settings</legend>
					<?= $this->Get_Warnings() /* no idea what this might output, never used this warning/error system */ ?>

					<form id="f" method="post" action="settings.php?PostBackAction=LightBoxSettings" enctype="multipart/form-data" >
						<table border=0 cellspacing=20>

						<tr><td nowrap="nowrap">Shadow Transparency<br>(0.0 to 1.0)
							<td><input type="text" name="trans" value="<?=$this->Config->GetSetting('trans')?>" size="5" maxlength="5" /><br />
								default: 0.8<br />
							
						<tr><td>Animation Speed<br>(1 to 11, 1 = slow, 10 = fast,<br>11 = instant = no animation):
							<td><input type="text" name="speed" value="<?=$this->Config->GetSetting('speed')?>" size="2" maxlength="2" /><br />
								default: 10<br />

						</table>
						<br />
						<input type="submit" name="save" value="save and create new LightBox css and js" />
					</form>
				</fieldset><br />
				<br />
				<div class="ErrorContainer">Warning: LightBox is licensed under <a href="http://creativecommons.org/licenses/by/2.5/" target="_blank">Creative Commons Attribution 2.5 License</a><br />
				I (Alex Lanin, Author of this Extension) am not sure what exactly "You must attribute the work in the manner specified by the author or licensor" means yet, hope the LightBox author will answer my mail</div>
			</div>
			<?
		}
	}

	$Page->AddRenderControl($Context->ObjectFactory->NewContextObject($Context, 'LightBoxSettings'),
							$Configuration["CONTROL_POSITION_BODY_ITEM"] + 1);

	$Context->SetDefinition('ExtensionOptions', 'Extension Options');
	$Panel->AddList($Context->GetDefinition('ExtensionOptions'), 10);
	
	$Panel->AddListItem($Context->GetDefinition("ExtensionOptions"),
						'LightBox',
						GetUrl($Context->Configuration, 'settings.php', '', '', '', '', 'PostBackAction=LightBoxSettings'));
}

?>.getAttribute("href")&&(relAttribute.toLowerCase().match("lightbox"))){area.onclick=function(){myLightbox.start(this);return false;}}}},start:function(imageLink){hideSelectBoxes();hideFlash();var arrayPageSize=getPageSize();Element.setWidth("overlay",arrayPageSize[0]);Element.setHeight("overlay",arrayPageSize[1]);new Effect.Appear("overlay",{duration:overlayDuration,from:0.0,to:overlayOpacity});imageArray=[];imageNum=0;if(!document.getElementsByTagName){return;}
var anchors=document.getElementsByTagName(imageLink.tagName);if((imageLink.getAttribute("rel")=="lightbox")){imageArray.push(new Array(imageLink.getAttribute("href"),imageLink.getAttribute("title")));}else{for(var i=0;i<anchors.length;i++){var anchor=anchors[i];if(anchor.getAttribute("href")&&(anchor.getAttribute("rel")==imageLink.getAttribute("rel"))){imageArray.push(new Array(anchor.getAttribute("href"),anchor.getAttribute("title")));}}
imageArray.removeDuplicates();while(imageArray[imageNum][0]!=imageLink.getAttribute("href")){imageNum++;}}
var arrayPageScroll=getPageScroll();var lightboxTop=arrayPageScroll[1]+(arrayPageSize[3]/10);var lightboxLeft=arrayPageScroll[0];Element.setTop("lightbox",lightboxTop);Element.setLeft("lightbox",lightboxLeft);Element.show("lightbox");this.changeImage(imageNum);},changeImage:function(imageNum){activeImage=imageNum;if(animate){Element.show("loading");}
Element.hide("lightboxImage");Element.hide("hoverNav");Element.hide("prevLink");Element.hide("nextLink");Element.hide("imageDataContainer");Element.hide("numberDisplay");imgPreloader=new Image();imgPreloader.onload=function(){Element.setSrc("lightboxImage",imageArray[activeImage][0]);myLightbox.resizeImageContainer(imgPreloader.width,imgPreloader.height);imgPreloader.onload=function(){};}
imgPreloader.src=imageArray[activeImage][0];},resizeImageContainer:function(imgWidth,imgHeight){this.widthCurrent=Element.getWidth("outerImageContainer");this.heightCurrent=Element.getHeight("outerImageContainer");var widthNew=(imgWidth+(borderSize*2));var heightNew=(imgHeight+(borderSize*2));this.xScale=(widthNew/this.widthCurrent)*100;this.yScale=(heightNew/this.heightCurrent)*100;wDiff=this.widthCurrent-widthNew;hDiff=this.heightCurrent-heightNew;if(!(hDiff==0)){new Effect.Scale("outerImageContainer",this.yScale,{scaleX:false,duration:resizeDuration,queue:"front"});}
if(!(wDiff==0)){new Effect.Scale("outerImageContainer",this.xScale,{scaleY:false,delay:resizeDuration,duration:resizeDuration});}
if((hDiff==0)&&(wDiff==0)){if(navigator.appVersion.indexOf("MSIE")!=-1){pause(250);}else{pause(100);}}
Element.setHeight("prevLink",imgHeight);Element.setHeight("nextLink",imgHeight);Element.setWidth("imageDataContainer",widthNew);this.showImage();},showImage:function(){Element.hide("loading");new Effect.Appear("lightboxImage",{duration:resizeDuration,queue:"end",afterFinish:function(){myLightbox.updateDetails();}});this.preloadNeighborImages();},updateDetails:function(){if(imageArray[activeImage][1]){Element.show("caption");Element.setInnerHTML("caption",imageArray[activeImage][1]);}
if(imageArray.length>1){Element.show("numberDisplay");Element.setInnerHTML("numberDisplay","Image "+eval(activeImage+1)+" of "+imageArray.length);}
new Effect.Parallel([new Effect.SlideDown("imageDataContainer",{sync:true,duration:resizeDuration,from:0.0,to:1.0}),new Effect.Appear("imageDataContainer",{sync:true,duration:resizeDuration})],{duration:resizeDuration,afterFinish:function(){var arrayPageSize=getPageSize();Element.setHeight("overlay",arrayPageSize[1]);myLightbox.updateNav();}});},updateNav:function(){Element.show("hoverNav");if(activeImage!=0){Element.show("prevLink");document.getElementById("prevLink").onclick=function(){myLightbox.changeImage(activeImage-1);return false;}}
if(activeImage!=(imageArray.length-1)){Element.show("nextLink");document.getElementById("nextLink").onclick=function(){myLightbox.changeImage(activeImage+1);return false;}}
this.enableKeyboardNav();},enableKeyboardNav:function(){document.onkeydown=this.keyboardAction;},disableKeyboardNav:function(){document.onkeydown="";},keyboardAction:function(e){if(e==null){keycode=event.keyCode;escapeKey=27;}else{keycode=e.keyCode;escapeKey=e.DOM_VK_ESCAPE;}
key=String.fromCharCode(keycode).toLowerCase();if((key=="x")||(key=="o")||(key=="c")||(keycode==escapeKey)){myLightbox.end();}else if((key=="p")||(keycode==37)){if(activeImage!=0){myLightbox.disableKeyboardNav();myLightbox.changeImage(activeImage-1);}}else if((key=="n")||(keycode==39)){if(activeImage!=(imageArray.length-1)){myLightbox.disableKeyboardNav();myLightbox.changeImage(activeImage+1);}}},preloadNeighborImages:function(){if((imageArray.length-1)>activeImage){preloadNextImage=new Image();preloadNextImage.src=imageArray[activeImage+1][0];}
if(activeImage>0){preloadPrevImage=new Image();preloadPrevImage.src=imageArray[activeImage-1][0];}},end:function(){this.disableKeyboardNav();Element.hide("lightbox");new Effect.Fade("overlay",{duration:overlayDuration});showSelectBoxes();showFlash();}}
function getPageScroll(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
arrayPageScroll=new Array(xScroll,yScroll)
return arrayPageScroll;}
function getPageSize(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}
windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=xScroll;}else{pageWidth=windowWidth;}
arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight)
return arrayPageSize;}
function getKey(e){if(e==null){keycode=event.keyCode;}else{keycode=e.which;}
key=String.fromCharCode(keycode).toLowerCase();if(key=="x"){}}
function listenKey(){document.onkeypress=getKey;}
function showSelectBoxes(){var selects=document.getElementsByTagName("select");for(i=0;i!=selects.length;i++){selects[i].style.visibility="visible";}}
function hideSelectBoxes(){var selects=document.getElementsByTagName("select");for(i=0;i!=selects.length;i++){selects[i].style.visibility="hidden";}}
function showFlash(){var flashObjects=document.getElementsByTagName("object");for(i=0;i<flashObjects.length;i++){flashObjects[i].style.visibility="visible";}
var flashEmbeds=document.getElementsByTagName("embed");for(i=0;i<flashEmbeds.length;i++){flashEmbeds[i].style.visibility="visible";}}
function hideFlash(){var flashObjects=document.getElementsByTagName("object");for(i=0;i<flashObjects.length;i++){flashObjects[i].style.visibility="hidden";}
var flashEmbeds=document.getElementsByTagName("embed");for(i=0;i<flashEmbeds.length;i++){flashEmbeds[i].style.visibility="hidden";}}
function pause(ms){var date=new Date();curDate=null;do{var curDate=new Date();}
while(curDate-date<ms);}
function initLightbox(){myLightbox=new Lightbox();}
Event.observe(window,"load",initLightbox,false);';

	global $Configuration, $Context;
	
	// set file
	$SettingsFile = $Context->Configuration['EXTENSIONS_PATH'] . 'LightBox/settings.php';
	
	// create ConfigurationManager instance
	$Config = $Context->ObjectFactory->NewContextObject($Context, 'ConfigurationManager');
	
	// load settings
	$Config->GetSettingsFromFile($SettingsFile);
	

	$css = str_replace('$path', $Configuration['WEB_ROOT'] . 'extensions/LightBox', $css);
	if(file_put_contents($Configuration['EXTENSIONS_PATH'] . 'LightBox/LightBox.css', $css) == false) return false;
	
	$js = str_replace('$path', $Configuration['WEB_ROOT'] . 'extensions/LightBox', $js);
	$js = str_replace('$trans', $Config->GetSetting('trans'), $js);
	$js = str_replace('$animate', $Config->GetSetting('speed') == 11 ? 'false' : 'true', $js);
	$js = str_replace('$speed', min(10, $Config->GetSetting('speed')), $js);
	if(file_put_contents($Configuration['EXTENSIONS_PATH'] . 'LightBox/LightBox.js', $js) == false) return false;
	
	return true;
}

// check for css and js files
if(!file_exists($Configuration['EXTENSIONS_PATH'] . 'LightBox/LightBox.css') ||
   !file_exists($Configuration['EXTENSIONS_PATH'] . 'LightBox/LightBox.js')) {

	if(!writeFiles())
		$Context->WarningCollector->Add('Could not create LightBox files. Try creating a LightBox.css and LightBox.js in extensions/LightBox/ and chmod them to 777');

}



if ($Context->SelfUrl == "settings.php" && $Context->Session->User->Permission('PERMISSION_CHANGE_APPLICATION_SETTINGS')) {


	error_reporting(E_ALL);

	class LightBoxSettings extends PostBackControl
	{
		var $Config;
		
		function LightBoxSettings(&$Context) 
		{
			if (ForceIncomingString('PostBackAction', '') != 'LightBoxSettings') return;

			$this->Name = 'LightBoxSettings';
			$this->ValidActions = array('LightBoxSettings');
			$this->Constructor($Context);
			
			// set file
			$SettingsFile = $Context->Configuration['EXTENSIONS_PATH'] . 'LightBox/settings.php';
			
			// create ConfigurationManager instance
			$this->Config = $Context->ObjectFactory->NewContextObject($Context, 'ConfigurationManager');
			
			// load settings
			$this->Config->GetSettingsFromFile($SettingsFile);

			// yeah it's not clean coded using $_GET, but it's easy ;)
			// $_GET['saved'] is boolean whether saving was succuessfull
			if(isset($_POST['save'])) {
				$this->Config->DefineSetting('trans', doubleval($_POST['trans']), true);
				$this->Config->DefineSetting('speed', intval($_POST['speed']), true);
				$_GET['saved'] = $this->Config->SaveSettingsToFile($SettingsFile);

				// reload settings, since $Config doesn't contain what was just saved....
				// bug or feature? ;-)
				$this->Config->GetSettingsFromFile($SettingsFile);
			}
		}

		function Render() {
			if (ForceIncomingString('PostBackAction', '') != 'LightBoxSettings') return;

			// no idea what this does
			$this->PostBackParams->Clear();


			if (isset($_GET['saved']))
				if($_GET['saved']) {
					echo	'<div id="Success">Settings saved</div>';
					
					if(writeFiles())
						echo	'<div id="Success">LightBox js and css created</div>';
					else
						echo	'<div class="ErrorContainer">ERROR: LightBox js or css NOT created! Try creating a LightBox.css and LightBox.js in extensions/LightBox/ and chmod them to 777</div>';
				} else
					echo	'<div class="ErrorContainer">Error: Settings NOT saved</div>';


			?>
			<div id="Form">
				<fieldset>
					<legend>LightBox Settings</legend>
					<?= $this->Get_Warnings() /* no idea what this might output, never used this warning/error system */ ?>

					<form id="f" method="post" action="settings.php?PostBackAction=LightBoxSettings" enctype="multipart/form-data" >
						<table border=0 cellspacing=20>

						<tr><td nowrap="nowrap">Shadow Transparency<br>(0.0 to 1.0)
							<td><input type="text" name="trans" value="<?=$this->Config->GetSetting('trans')?>" size="5" maxlength="5" /><br />
								default: 0.8<br />
							
						<tr><td>Animation Speed<br>(1 to 11, 1 = slow, 10 = fast,<br>11 = instant = no animation):
							<td><input type="text" name="speed" value="<?=$this->Config->GetSetting('speed')?>" size="2" maxlength="2" /><br />
								default: 10<br />

						</table>
						<br />
						<input type="submit" name="save" value="save and create new LightBox css and js" />
					</form>
				</fieldset><br />
				<br />
				<div class="ErrorContainer">Warning: LightBox is licensed under <a href="http://creativecommons.org/licenses/by/2.5/" target="_blank">Creative Commons Attribution 2.5 License</a><br />
				I (Alex Lanin, Author of this Extension) am not sure what exactly "You must attribute the work in the manner specified by the author or licensor" means yet, hope the LightBox author will answer my mail</div>
			</div>
			<?
		}
	}

	$Page->AddRenderControl($Context->ObjectFactory->NewContextObject($Context, 'LightBoxSettings'),
							$Configuration["CONTROL_POSITION_BODY_ITEM"] + 1);

	$Context->SetDefinition('ExtensionOptions', 'Extension Options');
	$Panel->AddList($Context->GetDefinition('ExtensionOptions'), 10);
	
	$Panel->AddListItem($Context->GetDefinition("ExtensionOptions"),
						'LightBox',
						GetUrl($Context->Configuration, 'settings.php', '', '', '', '', 'PostBackAction=LightBoxSettings'));
}

?>