<!DOCTYPE html>
<html lang="en">
<head>
	<title><?php echo ($pageTitle ?? ''); ?></title>
	<meta charset="utf-8"/>
    <?php
    if(!isset($wwwroot)){ die('Fatal error: Contact support. $wwwroot not set in header.php'); }

    //If the currently-viewed object is archived, force-unhide archived objects. Otherwise, subsequent requests may be
    //empty, e.g., projects' Plates tabs might be empty despite there being plates, because the (archived) project was suppressed.
	if(isset($data['isarchived']) && 1*$data['isarchived']){
		session::setShowArchivedProjects(1);
	}

    $backgroundImageId=-1;
    $userBackground=null;
	$defaultBackground=config::get('core_backgroundimage_default');
    if(session::isLoggedIn()){
        $userBackground=userconfig::get('backgroundImage');
    }
    if(!is_null($userBackground)){
        $backgroundImageId=$userBackground;
    } else {
        $backgroundImageId=$defaultBackground;
    }

	$shibbolethIdentityProvider=shibboleth::getIdentityProviderEntityId();

    $skinId='default';
    if(isset($userConfig)){
        if(isset($userConfig['skin'])){
            $skinId=$userConfig['skin'];
        } else if($userConfig) {
            try {
                userconfig::set('skin', 'default');
            } catch (BadRequestException|ServerException $e){
                //just eat it
            }
        }
    } else {
        $userConfig=[];
    }
    $skin=file_get_contents(config::getWwwRoot().'/client/skins/'.$skinId.'/skin.json');
    $skin=json_decode($skin, true);

    $uploadedFilesBytesLimit=0;
    if(session::get('uploadSizeLimit')){
        $uploadedFilesBytesLimit=1*session::get('uploadSizeLimit');
    } else {
		$s = [ 'g'=> 1<<30, 'm' => 1<<20, 'k' => 1<<10 ];
		$uploadMaxSize=trim(ini_get('upload_max_filesize'));
		$postMaxSize=trim(ini_get('post_max_size'));
		$postMaxSize=intval($postMaxSize) * ($s[strtolower(substr($postMaxSize,-1))] ?: 1);
		$uploadMaxSize=intval($uploadMaxSize) * ($s[strtolower(substr($uploadMaxSize,-1))] ?: 1);
        $uploadedFilesBytesLimit=min($postMaxSize, $uploadMaxSize);
        session::set('uploadSizeLimit', $uploadedFilesBytesLimit);
    }
	session::set('uploadSizeLimit', null);

    ?>
	<script type="text/javascript" src="<?php echo '/js/prototype1_7_2.js'; ?>"></script>
	<script type="text/javascript" src="<?php echo '/js/prototype1_7_2_http_fix.js'; ?>"></script>
	<script type="text/javascript" src="<?php echo '/js/ui.js?t='.@filemtime($wwwroot.'/client/js/ui.js'); ?>"></script>
    <script type="text/javascript" src="<?php echo '/js/client.js?t='.@filemtime($wwwroot.'/client/js/client.js'); ?>"></script>
    <script type="text/javascript" src="<?php echo '/js/vendor/leafletjs/leaflet.js'; ?>"></script>
    <link rel="stylesheet" type="text/css" href="<?php echo '/js/vendor/leafletjs/leaflet.css'; ?>" />
    <link rel="stylesheet" type="text/css" href="/skins/<?php echo $skin['skinId']; ?>/skin.css?t=<?php echo @filemtime($wwwroot.'/client/skins/'.$skin['skinId'].'/skin.css'); ?>" />
    <link rel="stylesheet" type="text/css" href="<?php echo '/skins/base.css?t='.@filemtime($wwwroot.'/client/skins/base.css'); ?>" />
    <link rel="stylesheet" type="text/css" href="<?php echo '/skins/client.css?t='.@filemtime($wwwroot.'/client/skins/client.css'); ?>" />
	<script type="text/javascript">
    Project.showArchivedProjects=<?php echo 1*session::get('showArchivedProjects'); ?>;
    const uploadedFilesBytesLimit=<?php echo 1*$uploadedFilesBytesLimit ?>;
    let defaultBackgroundImageId=parseInt("<?php echo $defaultBackground; ?>");
    let backgroundImageId=parseInt("<?php echo $backgroundImageId; ?>");
    const canChooseBackgrounds=<?php echo ('fixed'!==config::get('core_backgroundimage_allow')? 'true' : 'false'); ?>;
    const canUploadBackgrounds=<?php echo ('upload'===config::get('core_backgroundimage_allow')? 'true' : 'false'); ?>;
    const nullValue="<?php echo database::$nullValue; ?>";
	const currentUser=<?php echo json_encode(session::getUser()); ?>;
	const username="<?php echo session::getUsername(); ?>";
	const userId=<?php echo session::getUserId(); ?>;
    const userReadProjects=[<?php echo implode(',',session::getReadProjects());?>];
    const userUpdateProjects=[<?php echo implode(',',session::getUpdateProjects());?>];
    const shibbolethIdentityProvider=<?php echo !empty($shibbolethIdentityProvider) ? '"'.$shibbolethIdentityProvider.'"' : 'null'; ?>;
	const csrfToken="<?php echo session::get('csrfToken'); ?>";
	UserConfig.items=<?php echo json_encode($userConfig); ?>;
    const skin=<?php echo json_encode($skin);?>;

    const skinName=UserConfig.get("skin","default");
	const theme="light"; //Or dark. LATER From skin metadata. ALSO CHANGE BODY TAG BELOW!
	const helpTexts=<?php echo (isset($helpTexts)) ? json_encode($helpTexts) : 'null' ; ?>;
	const fieldValidations=<?php echo (isset($fieldValidations)) ? json_encode($fieldValidations) : 'null' ; ?>;
	const validationPatterns=<?php echo (isset($validationPatterns)) ? json_encode($validationPatterns) : 'null' ; ?>;
	let submitTimer;
	let data=<?php echo isset($data) ? json_encode($data) : 'null'; ?>;
	let pageTitle="<?php echo $pageTitle??'' ?>";
	let initialHash=document.location.hash;
	<?php if(session::isLoggedIn()){
		$isAdmin=session::isAdmin();
        $sharedProject=baseproject::getByName(baseproject::SHARED);
        if($sharedProject){
			echo 'window.sharedProject=' . json_encode($sharedProject) . ";\n";
        } else {
            echo 'alert("Could not find shared project");'."\n";
        }
        echo 'const isAdmin='.($isAdmin?'true':'false').";\n";
		if(null==session::get('isTechnician')){
			try {
				$techniciansGroup=usergroup::getByName(usergroup::TECHNICIANS);
				$isTechnician=usergroup::userisingroup($techniciansGroup['id']);
			} catch (Exception $e){
				$isTechnician=false;	
			}
			session::set('isTechnician', $isAdmin || $isTechnician);
		}
		echo 'const isTechnician='.($isAdmin || session::get('isTechnician')?'true':'false').";\n";
		if(null==session::get('isShipper')){
			try {
				$shippersGroup=usergroup::getByName(usergroup::SHIPPERS);
				$isShipper=usergroup::userisingroup($shippersGroup['id']);
			} catch (Exception $e){
				$isShipper=false;	
			}
			session::set('isShipper', $isAdmin || $isShipper);
		}
		echo 'const isShipper='.($isAdmin || session::get('isShipper')?'true':'false').";\n";
	} ?>
	<?php if(isset($canUpdate) && isset($data['projectid'])){
		echo 'let canEdit='.(($canUpdate && !in_array($data['projectid'], session::get('archivedProjectIds'))) ? 'true':'false').";\n";
	}  else if(isset($canUpdate)){
		echo 'let canEdit='.($canUpdate ? 'true':'false').";\n";
	}  else {
		echo "let canEdit=true; //Default because \$canUpdate was not set by server. Permissions will be enforced server-side.\n";
	}?>

    let groupNames={
        "ADMINISTRATORS":"<?php echo baseusergroup::ADMINISTRATORS; ?>",
        "PLATEDESTROYERS":"<?php echo usergroup::PLATEDESTROYERS; ?>",
        "SHIPPERS":"<?php echo usergroup::SHIPPERS; ?>",
        "TECHNICIANS":"<?php echo usergroup::TECHNICIANS; ?>"
    };

	</script>
</head>
<body>
<div id="container">
<header id="header" class="<?php echo $skin['navBarIconTheme']; ?>icons">
<?php if(session::isLoggedIn()){ ?>
		<a class="control noprint" href="#" onclick="showMenu();return false" title="Menu"><img id="menubutton" src="/images/icons/<?php echo $skin['navBarIconTheme']; ?>icons/header/btn_menu.png" alt="Menu"/></a>
		<?php 
		if(isset($objectType) && file_exists($wwwroot.'/client/help/'.$objectType.'/index.php') ){ ?>
			<a class="control noprint" href="/help/<?php echo $objectType; ?>" target="_blank"><img id="helpbutton" src="/images/icons/<?php echo $skin['navBarIconTheme']; ?>icons/header/btn_help.png" title="Get help" alt="Get help"/></a>
		<?php } ?>
		<?php if(isset($hasConfig) && $hasConfig){ ?>
			<a class="control noprint nosmall" href="#"><img id="configbutton" src="/images/icons/<?php echo $skin['navBarIconTheme']; ?>icons/header/btn_config.png" title="Configure this page" alt="Configure this page"/></a>
		<?php } ?>
		<input autocomplete="off" class="noprint nosmall" type="text" name="headersearch" id="headersearch" data-classlist="project,plate,platetype,container,crystal,pdbdeposition" placeholder="Find by name..." title="Type a name or scan a barcode" />
<?php } ?>
<script type="text/javascript">
let searchBox=document.getElementById("headersearch");
if(searchBox){
    searchBox.addEventListener("focus", HeaderSearchBox.onInput);
    searchBox.addEventListener("input", HeaderSearchBox.onInput);
    searchBox.addEventListener("keyup", HeaderSearchBox.onKeyUp);
    searchBox.addEventListener("blur", HeaderSearchBox.stop);
}

let path=document.location.pathname.substring(1).replace(/\/$/, "");
let breadcrumbs='';
let crumbParts=<?php echo (isset($breadcrumbs)) ? json_encode($breadcrumbs) : 'null' ?>;

if(!!userId){
    //if !userId, no breadcrumbs needed - login page.
    if(crumbParts){
        breadcrumbs+='<a class="breadcrumb noprint" href="/"><img id="breadcrumb0" src="/images/icons/<?php echo $skin['navBarIconTheme']; ?>icons/header/bc_home.png" title="Home" alt="Home"/></a>';
        let bcCount=1;
        crumbParts.forEach(function(part){
            breadcrumbs+='<a class="breadcrumb noprint" href="'+part.url+'"><img id="breadcrumb'+bcCount+'" src="/images/icons/<?php echo $skin['navBarIconTheme']; ?>icons/header/bc_'+part["icon"]+'.png" title="'+part["help"]+'" alt="'+part["icon"]+'"/></a>';
            bcCount++;
        });
    } else if(''!==path){
        breadcrumbs+='<a class="breadcrumb noprint" href="/"><img id="breadcrumb0" src="/images/icons/<?php echo $skin['navBarIconTheme']; ?>icons/header/bc_home.png" title="Home" alt="Home"/></a>';
        path=path.split("/");
        const objType=path[0];
        if(2<=path.length && ''!==path[1]){
            breadcrumbs+='<a class="breadcrumb noprint" href="/'+objType+'/"><img id="breadcrumb1" src="/images/icons/<?php echo $skin['navBarIconTheme']; ?>icons/header/bc_'+objType+'.png" title="'+objType+'s" alt="'+objType+'s"/></a>';
        } else {
            <?php if(isset($showCreateLink) && $showCreateLink){ ?>
            pageTitle+='&nbsp;&nbsp;&nbsp;&nbsp;<a style="font-size:80%;float:none;" href="/'+objType+'/create">Create new...</a>';
            <?php }?>
        }
    }
}

document.write(breadcrumbs+'&nbsp;'+'<h1 id="pagetitle">'+pageTitle+'</h1>');

if(document.getElementById("headersearch")){ 
	document.getElementById("headersearch").focus();
}

window.addEventListener("load",function(){
	ui.checkForSmallScreen();
	initialHash=initialHash.replace("#","");
	if(initialHash){
		let elem=document.getElementById(initialHash);
		if(elem && elem.classList.contains("tab")){
			elem.click();
		}
	}
	window.setTimeout(ui.smallScreenInit,100);
    <?php if(-1!==$backgroundImageId){
    	echo 'document.body.style.backgroundImage="url(/api/backgroundimage/'.$backgroundImageId.')";';
    } ?>
});

</script>
</header>
<div id="content">
