<?php
//  Environment configuration
error_reporting(E_ALL);

//  *******************************************************************************************************
//  Configuration Variables
define('HEADER_CATAGORY_LIMIT_TITLE', 'View From');
define('HEADER_SORT_ORDER_TITLE', 'Sort by');

define('MOBILE',1);
define('TABLET',2);
define('COMPUTER',3);

define('NEXT_REL', 1);
define('PREVIOUS_REL', 2);
define('FIRST', 3);
define('LAST', 4);
define('NOT_AVAILABLE', 0);

define('ERROR_PRINT', TRUE);
//define('ERROR_PRINT', FALSE);

//  Decide which class file to load, based on script name
switch(basename($_SERVER['SCRIPT_NAME'])){
	case 'Test-pict.php':
		$filename='Test-PictClass.php';
		break;
	case 'pict-mobile.php':  	//  fall through
	case 'pict.php':  		//  fall through
	case 'pict2.php':  
	$filename='PictClass.php';
       	break;
	default:	
		FatalError('Cannot determine data filename to use!');
}
include_once $filename;

$FormFactor=GetBrowser();

//  Determine which Index file to use, based on script name
switch(basename($_SERVER['SCRIPT_NAME'])){
	case 'pict-mobile.php':
		$FormFactor=MOBILE;  //  Force Mobile
		$filename=DATA_FILE;
		break;
	case 'pict2.php':  //  fall through
	case 'pict.php':
		$filename=DATA_FILE;
       	break;
	case 'Test-pict.php':
		$filename=TEST_DATA_FILE;
        break;
	default:	
		FatalError('Cannot determine configuration file directory!');
}

$handle = fopen($filename,"rb");
if($handle == FALSE) FatalError('Cannot open file:  $filename');

$content = fread($handle,filesize($filename));
fclose($handle);

$Index=unserialize($content);

if(!is_object($Index)) FatalError('Improper Script Configuration Files');

//  Start work
$cookie=NULL;  //  To Do:  change $cookie to be a real cookie
$Index->SetParameters($_SERVER['QUERY_STRING'], $cookie);  
if(!$Index->CheckParameters()) $Index->SetParamatersToDefaults();

switch($Index->GetPage()){
	case MAIN:
		if($FormFactor == MOBILE){
			MobileMainWrite($Index);
		}
		else{
			MainWrite($Index);
		}
		break;
	case CATAGORY:
		if(MOBILE == true){
			MobileCatagoryWrite($Index);
		}
		else{
			FatalError("Improper Page Parameters");
		}
		break;
	case THUMBNAIL:
		AlbumWrite($Index);  //  Javascript makes things simple!
		//~ if($FormFactor == MOBILE || $FormFactor == TABLET){
			//~ MobileAlbumWrite($Index);
		//~ }
		//~ else{
			//~ AlbumWrite($Index);  //  Javascript makes things simple!
		//~ }
		break;
		
	case THUMBNAIL_LIST:
		GalleryList($Index);
		break;
		
        case THUMBNAIL_PRINT:
		ThumbnailPrintWrite($Index);
		break;
		
	case FULLSIZE:
		FullSizeWrite($Index);
		break;
	default:
		FatalError("Improper Page Parameters");
};

//  Print Errors
//ErrorDisplay();
 
//  Helper functions
function GetDirectoryRelative(&$Index, $CurrentDirectoryKey, $Direction){
	$AllDirKeys=$Index->GetDirectoriesUsingCurrentLimits();
	$CurrentDirIndex=array_search($CurrentDirectoryKey, $AllDirKeys);	
	
	switch($Direction){
		case NEXT_REL:
			$DirIndex=$CurrentDirIndex+1;
			break;
		case PREVIOUS_REL:
			$DirIndex=$CurrentDirIndex-1;
			break;
		default:
			return NOT_AVAILABLE;
	}
	
	if(array_key_exists($DirIndex, $AllDirKeys)){
		return $AllDirKeys[$DirIndex];
	}
	else return NOT_AVAILABLE;
}

//  *******************************************************************************************************
//  Function returns a URL, using the given Parameters.
function MakeURL($Param){
	return basename($_SERVER['SCRIPT_NAME']).'?'.$Param;
}
/*
function GetPictureRelative(&$Index, $Directory, $CurrentPicture, $Direction){
	
	$AllPictKey=$Index->GetAllPictureKeys($Directory);
	
	if($Direction == FIRST){
		$PictIndex=0;
	}
	elseif($Direction == LAST){
		$PictIndex=sizeof($AllPictKey)-1;
	}
	else{
		$CurrentPictIndex=array_search($CurrentPicture, $AllPictKey);
		switch($Direction){
			case NEXT_REL:
				$PictIndex=$CurrentPictIndex+1;
				break;
			case PREVIOUS_REL:
				$PictIndex=$CurrentPictIndex-1;
				break;
			default:
				return NOT_AVAILABLE;
		
		}
	
	}
	
	if(array_key_exists($PictIndex, $AllPictKey)){
		return $AllPictKey[$PictIndex];
	}
	else{ 
		return NOT_AVAILABLE;
	}
}
*/

function FullSizeWrite(&$Index){
	$Directory=$Index->GetDirectory();
	$PictureKey=$Index->GetPicture();
	$Index->GetPictureInfo($Directory , $PictureKey, $Info);
	if($Info['FullSizeFileName']==NULL){
		echo "Error.  File does not exist \n";
		return;
	}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title><?php echo $Info['Title'] ?></title>
		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<meta http-equiv="imagetoolbar" content="false">
		<meta name="description" content="">
		<meta name="keywords" content="">
		<link rel="stylesheet" type="text/css" href="/bin/css/zoom.css"></link>
		<script type="text/javascript">
		var imagePath = <?php echo '"'.$Info['FullSizeFileName'].'"'?>;
		</script>
		<script type="text/javascript" src="/bin/js/jquery-2.1.4.js"></script> 
		<script type="text/javascript" src="/bin/js/jquery.zoom.js"> </script>
		
	</head>
	<body>
	    <div class="main">
		<div id="centeredcontent">
			<p>Loading Image  </p>
			<img vspace="10px" src="/bin/images/ajax-loader-small.gif" />
			
		</div>
	    </div>
	    <div class="zoomcontrol">
		    <span>Zoom:  </span>
		    <span class="size">100%</span> |
		    <span id="zoomplus" class="button" title="Zoom in image">+</span> |
		    <span id="zoomminus" class="button" title="Zoom out image">-</span> |  
		    <span id="fitheight" class="button" title="Fit image to window height">H</span> |  
		    <span id="fitwidth" class="button" title="Fit image to window width">W</span> |  
		    <span id="close" class="button" title="Close Window">&times;</span> |
	    </div>
	</body>
</html>
<?php
}


function ThumbnailPrintWrite(&$Index){
    define('BIG_THUMBNAIL_WIDTH', 300);
    
    
	$Directory=$Index->GetDirectory();
	if(!$Index->GetThumbnailLink($Directory, $UrlParam, $ShortTitle, $LongTitle, $Date, $DateEntered, $CatagoryName)){
			ErrorPrint("Invalid directory: $Index->GetDirectory()");
			return;
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
	<title>Photo Gallery - Thumbnail Print</title>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    </head>
    <body>
<?php
    
    echo '<H2>'.$LongTitle.'</H1>'."\n";
    echo '<p>'."\n";
        echo '<b>Short Title</b>:  '.$ShortTitle.'<br/>'."\n";
        echo '<b>Catagory</b>:  '.$CatagoryName.'<br/>'."\n";
        echo '<b>Date</b>:  '.date ("F dS, Y h:i:s A", $Date).'<br/>'."\n";
        echo '<b>Directory</b>:  '.$Directory."\n";
	echo '</p>'."\n";	
    
	//$Index->GetPictMaxSize($Directory, $PictMaxWidth, $PictMaxHeight, $ThumbMaxWidth, $ThumbMaxHeight);
	$PictKey=$Index->GetAllPictureKeys($Directory);
	$RowNum=(int) ceil((sizeof($PictKey)/2));
    
    echo '<table width="100%">'."\n";
    
	for($i=0; $i< sizeof($PictKey); $i++){
		echo '<tr>'."\n";
        
        $Index->GetPictureInfo($Directory , $PictKey[$i], $Info);
        
        //  Determine Picture File Name
        $UrlInfo=parse_url($Info['FileName']);
        $FileInfo=pathinfo($UrlInfo['path']);        


        //  Picture Cell
        echo '	<td align="center" width="'.(BIG_THUMBNAIL_WIDTH+10).'">'."\n";
        echo '		<img width="'.BIG_THUMBNAIL_WIDTH.'"  src="'.$Info['FileName'].'">'."\n";
        echo '	</td>'."\n";
        
        //  Information Cell
        echo '  <td>'."\n";
        echo '		<b>'.($i+1).'</b>.<br />'."\n";
        echo '		<b>Title:  '.$Info['Title'].'</b><br />'."\n";
        echo '      <b>Code</b>:  '.$PictKey[$i].'<br />'."\n";
        echo '      <b>Filename</b>:  '.$FileInfo['basename'].'<br />'."\n";
       // echo '      <b>Picture Size</b>:  '.$PictWidth.' x '.$PictHeight.'<br />'."\n";
       // echo '      <b>Thumbnail Size</b>:  '.$ThumbWidth.' x '.$ThumbHeight."\n";
        echo '	</td>'."\n";
        
        echo '</tr>'."\n";
	}
	echo '</table>'."\n";
	
	?>
	</body>
</html>
<?php
}

function MobileMainWrite(&$Index){
?>
<!DOCTYPE html> 
<html> 
	<head> 
		<title>Photo Gallery - Main List</title> 
		<?php MobileHeader(); ?>
	</head> 
	<body> 
		<div data-role="page">
			<div data-role="header" data-theme="b">
				<h1 >Photo Gallery</h1>
			</div><!-- /header -->
			<div data-role="header" data-theme="c">
				<h1 >Select Catagory</h1>
			</div><!-- /header -->
			<div data-role="content">
				<ul data-role="listview" data-inset="false" data-theme="a" >
<?php			foreach($Index->GetAllCatagories() as $key){  //Catagory options
					$Index->GetCatagoryPageLinks($key, $UrlParam, $LinkTooltip, $LinkText, $fSelected);
					
					$DirNewest=$Index->GetDirectoriesSortedDate(SORT_DATE_ENTERED, $key);
					if(!$Index->GetThumbnailLink($DirNewest[0], $UrlParamIgnore, $ShortTitle, $LongTitle, $Date, $DateEntered, $CatagoryName)){
						ErrorPrint("Invalid directory: $Directory");
						next;
					}
					$Details=' <p class="inl">  (Last Update: '.date ("F j, Y", $DateEntered).')</p>';
					
					if($key ==CAT_ALL){
						$AllURL=MakeURL($UrlParam);
						$AllText=$LinkText;
					}
					else{
						echo '					';
						echo '<li><a href="'.MakeURL($UrlParam).'" >'.$LinkText.$Details.'</a></li>'."\n";
					}
				}
?>	
					<li data-role="list-divider"></li>
					<li><a href="<?php echo $AllURL;?>" ><?php echo $AllText;?></a></li>
				</ul>
			</div>
		</div><!-- /page -->
	</body>
</html>


<?php
}

function MainWrite(&$Index){
?>
<!DOCTYPE html> 
<html>
    <head>
	<title>Photo Gallery - Main List</title>
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<meta http-equiv="imagetoolbar" content="false">
	<meta name="description" content="">
	<meta name="keywords" content="">
	<link href='https://fonts.googleapis.com/css?family=Merriweather+Sans:400,700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" type="text/css" href="/bin/css/main.css" media="screen">
	<link rel="stylesheet" type="text/css" href="/bin/css/maincarousel.css">
	<link rel="stylesheet" type="text/css" href="/bin/css/jquery.popup.css">
	<script src="/bin/js/jquery-2.1.4.js"></script> 
	<script src="/bin/js/jquery.popup.js"></script> 
	<script src="/bin/js/jquery.jcarousel.modernizr.custom.js"></script> 
	<script src="/bin/js/jquery.jcarousel.js"></script>
	<script src="/bin/js/jquery.main.js"></script>
    </head>
    <body>
         <div id="header">
		<div class="headerBar titleBar" id="titleBar" >
			<span id="titleBarSpacer" class="headerBarSpacer" ></span>
			<h1  id="mainTitle">Photo Gallery</h1>
			<a id="titleBarNav" href="/"  >Home Page</a>
		</div>
		<div class="thumbnails" id="thumbnails">
			<div class="jcarousel">
				<div class="loading">Loading thumbnails...</div>
			</div>
			<a href="#" class="jcarousel-control-prev">&lsaquo;</a>
			<a href="#" class="jcarousel-control-next">&rsaquo;</a>
		</div>	
		<div class="headerBar galleryBar" id="galleryBar">
			<span id="galleryBarSpacer" class="headerBarSpacer"></span>
			<h2 id="thumbTitle"></h2>
			<span id="galleryOptions">
				<a id="linkGal">View</a> |
				<a id="linkPrev" class="thumbUpdate" rel="#">Previous</a> |
				<a id="linkNext" class="thumbUpdate" rel="#">Next</a>
			</span>
		</div>
	</div>
	 <?php
	//~ <div id="up" class="btn"><a href="/"  >Home Page</a></div>

	 ?>
	 

	
	<div class="options" id="leftBar">
		<h1><?php echo HEADER_CATAGORY_LIMIT_TITLE ?></h1>
		<ul>
<?php	foreach($Index->GetAllCatagories() as $key){  //Catagory options
			echo '			';
			$Index->GetCatagoryLimitLinks($key, $UrlParam, $LinkTooltip, $LinkText, $fSelected);
			if($fSelected){
				echo "<li>$LinkText</li>\n";
			}
			else{
				echo '<li><a href="'.MakeURL($UrlParam).'" title="'.$LinkTooltip.'">'.$LinkText.'</a></li>'."\n";
			}
		}
?>	
		</ul>
		<h1><?php echo HEADER_SORT_ORDER_TITLE ?></h1>
		<ul>
<?php	foreach($Index->GetAllSortOrders() as $key){  //Sort options
			echo '			';
			$Index->GetSortOrderLimitLinks($key, $UrlParam, $LinkTooltip, $LinkText, $fSelected);
			if($fSelected){
				echo "<li>$LinkText</li>\n";
			}
			else{
				echo '<li><a href="'.MakeURL($UrlParam).'" title="'.$LinkTooltip.'">'.$LinkText.'</a></li>'."\n";
			}
		}
?>	
		</ul>
		<h1>Other</h1>
		<ul>
			<li><a id="linkPrint">Print</a> </li>
		</ul>
	</div>
	<div class="body" id="mainPage">
<?php	
	MainListsWrite($Index);
?>
    	</div>
	</body>
</html>
<?php
}

function MainListsWrite(&$Index){
	
	$SortOrder=$Index->GetSortOrder();
	if($SortOrder == SORT_BY_CATAGORY){
		//  Get a list of catagories we are displaying.  This list can be limited to only one catagory depending on the current parameters
		$CatLimit=$Index->GetCatagoryLimit();
		if($CatLimit == CAT_ALL){
			//  Get an array of Catagories.  This array might include CAT_ALL, which we don't want
			$Catagories=$Index->GetAllCatagories();
			$key=array_search(CAT_ALL, $Catagories);
			if(($key!==NULL) && ($key !== FALSE)){	 //  Old version return NULL, new versions return FALSE.  The value 0 can be an array index, so we must be precise
				array_splice($Catagories, $key, 1);
			}
		}
		else{
			$Catagories[]=$CatLimit;
		}
		
		$i=0;
		foreach($Catagories as $key){
			$Data[$i]['CatKey']=$key;
			$Data[$i]['DirList']=$Index->GetDirectoriesInCatagory($key);
			$i++;
		}
	}
	else{
			$Data[0]['CatKey']=$Index->GetCatagoryLimit();
			$Data[0]['DirList']=$Index->GetDirectoriesSortedDate($SortOrder, $Index->GetCatagoryLimit());
	}
	
	//$CatagoryCount=count($Catagories);
	//  Find newest addition;
	$ListNewest=$Index->GetDirectoriesSortedDate(SORT_DATE_ENTERED, $Index->GetCatagoryLimit());


	for($i=0; array_key_exists($i, $Data) ; $i++){
		echo '		<div class="column">'."\n";
		if(!$Index->GetCatagoryLimitLinks($Data[$i]['CatKey'], $UrlParam, $LinkTooltip, $Name, $fSelected)){
			ErrorPrint("Invalid catagory: $key");
		}
		echo '			<h1>' .$Name.'</h1>'."\n";	
		
		$CurrentYear='';
		$space='					';
		
		foreach($Data[$i]['DirList'] as $Directory){
			if(!$Index->GetThumbnailLink($Directory, $UrlParam, $ShortTitle, $LongTitle, $Date, $DateEntered, $CatagoryName)){
				ErrorPrint("Invalid directory: $Directory");
				next;
			}
			
			$Class="thumbUpdate smallButton";
			if($Directory==$ListNewest[0]){
				$Class = $Class.' activealbum';
			}
			
			$Year=date ("Y", $Date);
			if($CurrentYear != $Year){
				if($CurrentYear !=''){
					echo '					</ul>'."\n";	
				}
				$CurrentYear = $Year;
				echo '				<h2>' .$CurrentYear.'</h2>'."\n";	
				echo '					<ul>'."\n";	
			}
			$MonthOption=' ('.date ("F", $Date).')';
			echo $space.'<li>'."\n";
			echo $space.'	<a class="'.$Class.'" rel="'. MakeURL($Index->GetThumbnailListLink($Directory)) .'">&#3664;</a>'."\n";
			echo $space.'	<a class="albumlink" href="'. MakeURL($UrlParam) .'" title="'.$LongTitle .'" >'. $ShortTitle.$MonthOption .' </a> '."\n";
			echo $space.'</li>'."\n";
		}
		echo '		</div>'."\n";
	}
	
}

function MobileCatagoryWrite(&$Index){
	$CatLimit=$Index->GetCatagoryLimit();
	$CurrentYear='';
	$space= '					';

	$CatLimit=$Index->GetCatagoryLimit();
	if($CatLimit == CAT_ALL){
		$Directories=$Index->GetDirectoriesSortedDate($Index->GetSortOrder(), $Index->GetCatagoryLimit());
		$title="All Catagories";
	}
	else{
		$Directories=$Index->GetDirectoriesInCatagory($CatLimit);
		if(!$Index->GetCatagoryLimitLinks($CatLimit, $UrlParam, $LinkTooltip, $Name, $fSelected)){
			ErrorPrint("Invalid catagory: $key");
		}
		$title=$Name;
	}
?>	
<!DOCTYPE html> 
<html> 
	<head> 
		<title>Photo Gallery - Select Album</title> 
		<?php MobileHeader(); ?>
	</head> 
	<body> 
		<div data-role="page" >
			<div class="parent" data-role="header" data-add-back-btn="true" data-theme="b">
				<h1><?php echo $title; ?></h1>
			</div><!-- /header -->
			<div class="parent" data-role="header" data-theme="c">
				<h1>Select Album</h1>
			</div><!-- /header -->
			<div class="parent" data-role="content">
				<ul data-role="listview" data-inset="false" data-theme="a">
<?php	
	foreach($Directories as $Directory){
		if(!$Index->GetThumbnailLink($Directory, $UrlParam, $ShortTitle, $LongTitle, $Date, $DateEntered, $CatagoryName)){
			ErrorPrint("Invalid directory: $Directory");
			next;
		}
		$PictKeys=$Index->GetAllPictureKeys($Directory);	
		$Index->GetPictureInfo($Directory , $PictKeys[0], $Info);  //  Details for first Picture in album
		
		$Year=date ("Y", $Date);
		if($CurrentYear != $Year){
			$CurrentYear = $Year;
			echo$space.'<li data-role="list-divider" >' .$CurrentYear.'</li>'."\n";	
		}
		
		if($CatLimit == CAT_ALL){
			$Details=' <p class="inl">('.$CatagoryName.' - '.date ("F", $Date).')</p>';
		}
		else{
			$Details=' <p class="inl"> ('.date ("F", $Date).')</p>';
		}
		echo  $space.'<li><a class="picturelink" href="'.MakeURL($UrlParam).
			'" data-tnlist="'.MakeURL($Index->GetThumbnailListLink($Directory)).'">'.
			'<img src="'. $Info['ThumbnailFileName'] .'" style="width:80px;height:80px;object-fit: cover"> '.
			$ShortTitle.$Details.'<span class="ui-li-count">'.count($PictKeys).'</span></a></li>'."\n";
	}
?>	
				</ul>
			</div>
		
			<!-- Root element of PhotoSwipe. Must have class pswp. -->
			<div class="pswp" tabindex="-1" data-enhance="false" role="dialog" aria-hidden="true">

				<!-- Background of PhotoSwipe. 
				    It's a separate element as animating opacity is faster than rgba(). -->
				<div class="pswp__bg"></div>

				<!-- Slides wrapper with overflow:hidden. -->
				<div class="pswp__scroll-wrap">

					<!-- Container that holds slides. 
					    PhotoSwipe keeps only 3 of them in the DOM to save memory.
					    Don't modify these 3 pswp__item elements, data is added later on. -->
					<div class="pswp__container">
						<div class="pswp__item"></div>
						<div class="pswp__item"></div>
						<div class="pswp__item"></div>
					</div>

					<!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
					<div class="pswp__ui pswp__ui--hidden">
						<div class="pswp__top-bar">
							<!--  Controls are self-explanatory. Order can be changed. -->
							<div class="pswp__counter"></div>
							<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
							<button class="pswp__button pswp__button--share" title="Share"></button>
							<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
							<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
							<!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
							<!-- element will get class pswp__preloader--active when preloader is running -->
							<div class="pswp__preloader">
								<div class="pswp__preloader__icn">
									<div class="pswp__preloader__cut">
										<div class="pswp__preloader__donut"></div>
									</div>
								</div>
							</div>
						</div>
						<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
							<div class="pswp__share-tooltip"></div> 
						</div>
						<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
						</button>
						<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
						</button>
						<div class="pswp__caption">
							<div class="pswp__caption__center"></div>
						</div>
					</div>
				</div>
			</div>
			<!-- /photoswipe -->
		</div><!-- /page -->
	</body>
</html>


<?php
}




function AlbumWrite(&$Index){
	$Directory=$Index->GetDirectory();
	if(!$Index->GetThumbnailLink($Directory, $UrlParam, $ShortTitle, $LongTitle, $Date, $DateEntered, $CatagoryName)){
		ErrorPrint("Invalid directory: $Index->GetDirectory()");
		return;
	}
	
	//  Get data we need for filling in the page
	$ImageJson=MakeURL($Index->GetThumbnailListLink($Directory));

	$LinkMainPage=MakeURL($Index->GetLinkHome(USE_CURRENT_PARAMS));
	
?>
<!DOCTYPE html> 
<html>
    <head>
	<title><?php echo $LongTitle;?></title>
	<meta name="viewport" content="width = device-width, initial-scale = 1.0"> 
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" href="/bin/css/pict.css"></link>
	<link rel="stylesheet" href="/bin/css/photoswipe.css"></link>
	<link rel="stylesheet" href="/bin/css/photoswipe/default-skin.css"></link>
	<script src="/bin/js/photoswipe.js"></script> 
	<script src="/bin/js/photoswipe-ui-default.js"></script> 
	<script src="/bin/js/pict.js"> </script>
    </head>
    <body id='body' data-back="<?php echo $LinkMainPage;?>" data-list="<?php echo $ImageJson;?>">
   	<!-- Root element of PhotoSwipe. Must have class pswp. -->
        <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

		<!-- Background of PhotoSwipe. 
		    It's a separate element as animating opacity is faster than rgba(). -->
		<div class="pswp__bg"></div>

		<!-- Slides wrapper with overflow:hidden. -->
		<div class="pswp__scroll-wrap">

			<!-- Container that holds slides. 
			    PhotoSwipe keeps only 3 of them in the DOM to save memory.
			    Don't modify these 3 pswp__item elements, data is added later on. -->
			<div class="pswp__container">
				<div class="pswp__item"></div>
				<div class="pswp__item"></div>
				<div class="pswp__item"></div>
			</div>

			<!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
			<div class="pswp__ui pswp__ui--hidden">
				<div class="pswp__top-bar">
					<!--  Controls are self-explanatory. Order can be changed. -->
					<div class="pswp__counter"></div>
					<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
					<button class="pswp__button pswp__button--share" title="Share"></button>
					<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
					<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
					<!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
					<!-- element will get class pswp__preloader--active when preloader is running -->
					<div class="pswp__preloader">
						<div class="pswp__preloader__icn">
							<div class="pswp__preloader__cut">
								<div class="pswp__preloader__donut"></div>
							</div>
						</div>
					</div>
				</div>
				<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
					<div class="pswp__share-tooltip"></div> 
				</div>
				<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
				</button>
				<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
				</button>
				<div class="pswp__caption">
					<div class="pswp__caption__center"></div>
				</div>
			</div>
		</div>
	</div>
    </body>
</html>

<?php
}
?>
<?php
function MobileAlbumWrite(&$Index){
	$Directory=$Index->GetDirectory();
	if(!$Index->GetThumbnailLink($Directory, $UrlParam, $ShortTitle, $LongTitle, $Date, $DateEntered, $CatagoryName)){
		ErrorPrint("Invalid directory: $Index->GetDirectory()");
		return;
	}
	
	//  Get data we need for filling in the page
	$LinkMainPage=MakeURL($Index->GetLinkHome(USE_CURRENT_PARAMS))
	
?>

<!DOCTYPE html> 
<html> 
	<head> 
	<title><?php echo $LongTitle;?></title> 
	<?php MobileHeader(); ?>
</head> 
	<body> 
		<div data-role="page" data-fullscreen="true" class="ui-page-fullscreen" id="a1"  >
			<div data-role="header" data-position="fixed"> 
				<a href="#" data-rel="back" data-icon="arrow-l">Back</a>
				<h1></h1> 
				<div id="btnGroup" class="ui-btn-right" data-role="controlgroup" data-type="horizontal"  data-theme="a">
					<a id="prev" data-role="button" data-icon="arrow-l"  data-theme="a">Prev</a>
					<a id="thumblist"   data-inline="true" data-transition="fade" data-role="button" data-icon="arrow-d"  data-iconpos="right" data-theme="a">1</a>
					<a id="next" data-role="button" data-icon="arrow-r" data-iconpos="right" data-theme="a">Next</a>
				</div>
			</div> 
			<div data-role="content" >
				<div id="slider">
<?php
	$fFirstPict=true;
	$PictKeys=$Index->GetAllPictureKeys($Directory);	
	foreach($PictKeys as $Key){
		if(!$Index->GetPictureInfo($Directory , $Key, $Info)){
			ErrorPrint("Invalid Picture key: $Key");
			return;
		}
		echo '					';
		echo '<img src="'.$Info['FileName'].'" alt="'.$Info['ThumbnailFileName'].'" title="'.$Info['Title'].'"></img>'."\n";
		//if($Info['FullSizeFileName']) {  //  Only add link for fullsize if this picture is present
		//	$Index->GetFullSizeLink($Directory , $Key, $UrlParams);
		//	echo 'alt="'.MakeURL($UrlParams).'"' ;
		//}
	}
?>
				</div>
			</div><!-- /content -->

			<div  id="thumbdialogue" style="display:none" >
				<div ><h2>Goto Picture</h2></div> 
				<div id="thumbcontent" ></div>
			</div>

		</div><!-- /page -->
	</body>
</html>
<?php
}


function MobileHeader(){
?>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1"> 
	<meta name="apple-mobile-web-app-capable" content="yes" />
-	<meta name="apple-mobile-web-app-status-bar-style" content="black" />
	<link rel="stylesheet" href="/bin/mobile/css/theme.min.css" />
	<link rel="stylesheet" href="/bin/mobile/css/jquery.mobile.icons.min.css" />
	<link rel="stylesheet" href="/bin/mobile/css/jquery.mobile.structure-1.4.5.css" /> 
	<link rel="stylesheet" href="/bin/css/photoswipe.css"/>
	<link rel="stylesheet" href="/bin/css/photoswipe/default-skin.css"/>
	<script src="/bin/js/photoswipe.js"></script> 
	<script src="/bin/js/photoswipe-ui-default.js"></script> 
	<script src="/bin/js/jquery-2.1.4.js"></script> 
	<script src="/bin/js/pict.js"> </script>
	<script src="/bin/mobile/js/jquery.mobile-1.4.5.js"></script>
<?php
}


function GalleryList(&$Index){
	$Directory=$Index->GetDirectory();
	if(!$Index->GetThumbnailLink($Directory, $UrlParam, $ShortTitle, $LongTitle, $Date, $DateEntered, $CatagoryName)){
			ErrorPrint("Invalid directory: $Index->GetDirectory()");
			return;
	}
	$PictKey=$Index->GetAllPictureKeys($Directory);
	
	//  Figure out some of the entries
	$linkPrev='';
	$PrevIndexKey=GetDirectoryRelative($Index, $Directory, PREVIOUS_REL);
	if(strcmp($PrevIndexKey, NOT_AVAILABLE) != 0){
		$linkPrev=MakeURL($Index->GetThumbnailListLink($PrevIndexKey));
	}
	$linkNext='';
	$NextIndexKey=GetDirectoryRelative($Index, $Directory, NEXT_REL);
	if(strcmp($NextIndexKey, NOT_AVAILABLE) != 0){
		$linkNext=MakeURL($Index->GetThumbnailListLink($NextIndexKey));
	}
	
	//  Get the list of images
	$images = array();
	for($i=0; $i< sizeof($PictKey) ; $i++){
		$Index->GetPictureInfo($Directory , $PictKey[$i], $Info);
		
		$images[]=array(
			'thumbnail' => $Info['ThumbnailFileName'],
			'large' => $Info['FileName'],
			'caption' => htmlspecialchars($Info['Title'], ENT_QUOTES, "UTF-8"),  //  Need to handle xml special characters better
			'x'=>$Info['x'],
			'y'=>$Info['y'],
			'xThumb'=>$Info['xThumb'],
			'yThumb'=>$Info['yThumb']
		);
	}
	
	$data= array(
		'title' => $LongTitle,
		'catagory' => $CatagoryName,
		'date' => date ("F Y", $Date),
		'linkPrint' => MakeURL($Index->GetThumbnailPrintLink($Directory)),
		'linkGal' => MakeURL($UrlParam),
		'linkPrev' => $linkPrev,
		'linkNext' => $linkNext,
		'total' => sizeof($PictKey),
		'images' => $images
	);
	
	header("Access-Control-Allow-Origin: *");
	header("Content-Type: application/json; charset=UTF-8");
	echo stripslashes(json_encode($data)); 	
}


function GetBrowser(){
	$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
	
	if(	stripos($ua, 'ipad') 		|| 
		stripos($ua, 'playbook') 	|| 
		(stripos($ua, 'android') == true &&  stripos($ua,'mobile') == false)
	)
	{return TABLET;}
	
	if(	stripos($ua,'android') == true 		||
		stripos($ua,'iphone') == true		||
		stripos($ua,'ipod') == true		||
		stripos($ua,'blackberry') == true 	||
		stripos($ua,'phone') == true 			//  windows phone
		
	)
	{return MOBILE;}
	
	
	
	return COMPUTER;

}

function ErrorPrint($message){
	global $ErrorList;
	$ErrorList[]=$message;
}

function ErrorDisplay(){
	global $ErrorList;
	if(count($ErrorList) > 0){
		echo "<H4>The following errors occured when this page was generated:</H4>\n";
		foreach($ErrorList as $line){
			echo "<p>$line</p>";
		}
	}

}

//  *******************************************************************************************************
function FatalError($ErrorText){
	echo ' <?xml version="1.0" encoding="UTF-8"?>';echo"\n"; 
	?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
		<head>
			<title>Error</title>
		</head>
		<body>
			<h3>Error:</h3>
			<p><?php echo $ErrorText ?></p>
		</body>
	</html>
<?php
	exit();
}
?>
