<!--<?xml version="1.0" encoding="UTF-8" ?>-->
<!DOCTYPE html>
<!-- please note that DOCTYPE is supposed to be that short for HTML5 -->
<html><!-- xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">-->
<script>
	   window.SERVER_BASE = "https://legacy.envipath.org/";

</script>
<head>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta charset="UTF-8"/>
	<title>enviPath</title>
	<link id="css-pps_white_general.css" href="https://legacy.envipath.org/css/pps_white_general.css" rel="stylesheet"
		  type="text/css"/>

    <!-- CDN VERSION -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <link
            href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@600&display=swap"
            rel="stylesheet"
        />
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<script src="https://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
	<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
	<link rel="stylesheet"
		  href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.3/css/bootstrap-select.min.css">
	<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.3/js/bootstrap-select.min.js"></script>
	<!-- CDN END -->

	<!-- LOCAL VERSION -->
<!--	<script src="https://legacy.envipath.org/js/jquery.min.js"></script>-->
<!--	<link rel="stylesheet" href="https://legacy.envipath.org/css/bootstrap.min.css">-->
<!--	<script src="https://legacy.envipath.org/js/bootstrap.min.js"></script>-->
<!--	<script src="https://legacy.envipath.org/js/jquery.tmpl.js"></script>-->
<!--	<link href="https://legacy.envipath.org/css/font-awesome.css" rel="stylesheet">-->
<!--	<link rel="stylesheet" href="https://legacy.envipath.org/css/bootstrap-select.min.css">-->
<!--	<script src="https://legacy.envipath.org/js/bootstrap-select.min.js"></script>-->
	<!-- END LOCAL -->

	<script src="https://legacy.envipath.org/js/pps.js"></script>
	<script src="https://legacy.envipath.org/js/jquery-bootstrap-modal-steps.js"></script>
	<script src="https://legacy.envipath.org/js/arrive.min.js"></script>
	<script src="https://legacy.envipath.org/js/d3.v3.min.js"></script>
	<script src="https://legacy.envipath.org/js/d3-pathway.js"></script>
	<script src="https://legacy.envipath.org/js/c3.js"></script>
	<script src="https://legacy.envipath.org/js/newSettingModal.js"></script>
	<link id="css-c3" href="https://legacy.envipath.org/css/c3.css" rel="stylesheet" type="text/css">
	<!--	<script src="https://legacy.envipath.org//js/ketcher2/script/index.js"></script>-->

	<script type="text/javascript">
        // if internet explorer(or edge) is used, deactivate caching of ajax requests
        if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )
                || (navigator.userAgent.indexOf("Edge") != -1 )) {
            $.ajaxSetup({ cache: false });
        }

	</script>

	<!-- Matomo -->
	<script>
	  var _paq = window._paq = window._paq || [];
	  /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
	  _paq.push(['trackPageView']);
	  _paq.push(['enableLinkTracking']);
	  (function() {
	      var u="//matomo.envipath.com/";
	      _paq.push(['setTrackerUrl', u+'matomo.php']);
	      _paq.push(['setSiteId', '12']);
	      var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
	      g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
	  })();
	</script>
	<!-- End Matomo Code -->

</head>
  <body>

        <!-- Brand and toggle get grouped for better mobile display -->
      <style>
          @media (max-width: 1220px) {
            .navbar-header-framework {
                float: none;
            }
            .navbar-left-framework,.navbar-right-framework {
                float: none !important;
            }
            .navbar-toggle-framework {
                display: block;
            }
            .navbar-collapse-framework {
                border-top: 1px solid transparent;
                box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
            }
            .navbar-fixed-top-framework {
                top: 0;
                border-width: 0 0 1px;
            }
            .navbar-collapse-framework.collapse {
                display: none!important;
            }
            .navbar-nav-framework {
                float: none!important;
                margin-top: 7.5px;
            }
            .navbar-nav-framework>li {
                float: none;
            }
            .navbar-nav-framework>li>a {
                padding-top: 10px;
                padding-bottom: 10px;
            }
            .collapse-framework.in{
                display:block !important;
            }
          }
      </style>


<nav class="navbar navbar-default navbar-inverse" style="border-radius:0px;" role="navigation">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header navbar-header-framework">
      <button type="button" class="navbar-toggle navbar-toggle-framework" data-toggle="collapse" data-target="#navbarCollapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a id="pictureLink" href="https://legacy.envipath.org/" class="navbar-brand">
	    <img id="image-logo-short-white.svg" src="https://legacy.envipath.org//images/logo-short-white.svg" width="100"
					 alt="enviPath">
	  </a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
  <div class="collapse navbar-collapse collapse-framework navbar-collapse-framework" id="navbarCollapse">
	  <ul class="nav navbar-nav navbar-nav-framework">
		  <li><a href="/package" id="packageLink">Package</a></li>
		  <li><a href="/pathway" id="pathwayLink">Pathway</a></li>
		  <li><a href="/rule" id="ruleLink">Rule</a></li>
		  <li><a href="/compound" id="compoundLink">Compound</a></li>
		  <li><a href="/reaction" id="reactionLink">Reaction</a></li>
		  <li><a href="/relative-reasoning" id="relative-reasoningLink">Relative
			  Reasoning</a></li>
		  <li><a href="/scenario" id="scenarioLink">Scenario</a></li>
		  <li><a href="/setting" id="settingLink">Setting</a></li>
		  <li><a href="/user" id="userLink">User</a></li>
		  <li><a href="/group" id="groupLink">Group</a></li>
		  <li class="dropdown">
			  <a data-toggle="dropdown" class="dropdown-toggle" href="#">Predict <b class="caret"></b></a>
			  <ul role="menu" class="dropdown-menu">
				  <li><a href="/batch_prediction" id="batchpredictLink">Batch Predict</a></li>
			  </ul>
		  </li>
	  </ul>

      <ul class="nav navbar-nav navbar-right navbar-nav-framework navbar-right-framework">
        <li><a href="/search" id="searchLink">Search</a></li>
	    <li class="dropdown">
          <a data-toggle="dropdown" class="dropdown-toggle" href="#">Info <b class="caret"></b></a>
          <ul role="menu" class="dropdown-menu">
            <li><a href="/contributors" id="contributorsLink">Contributors</a></li>
            <li><a href="/funding" id="fundingLink">Funding</a></li>
            <li><a href="https://community.envipath.org/t/envipath-license/109" id="licenceLink">Licences</a></li>
            <li class="divider"></li>

            <li><a target="_blank" href="https://wiki.envipath.org/" id="wikiLink">Documentation Wiki</a></li>
            <li><a target="_blank" href="https://community.envipath.org/" id="communityLink">Support Forum</a></li>
            <li>
                <a href="#"
                id="citeButton"
                data-toggle="modal"
                data-target="#citemodal">How to cite enviPath</a>
            </li>
            <li class="divider"></li>
            <li><a>Version 0.3.3</a></li>
          </ul>
        </li>
        <li>
          <a href="#signup"
           id="loginButton"
           data-toggle="modal"
           data-target="#signupmodal" style="margin-right:10px">Login</a>
        </li>

      <li class="dropdown">
        <a data-toggle="dropdown"
           id="loggedInButton"

           class="dropdown-toggle"
           id="logedInButton"
           href="#">
          <div id="username"></div>
        </a>
        <ul role="menu" class="dropdown-menu">
          <li>
			<a href="#account"
             id="accountbutton">Account</a>
			</li>
          <li class="divider"></li>
              <form class="navbar-form navbar-left navbar-left-framework"
            role="logout"
            action=""
            method="post">
        <div class="form-group">
          <input type="hidden" name="hiddenMethod" value="logout" >
        </div>
        <button type="submit" class="btn btn-default">Logout</button>
          </form>
            </ul>
          </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

    <!-- Modal -->
    <div class="modal fade bs-modal-lg" id="citemodal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h4>How to cite enviPath</h4>
          </div>
	              <div class="modal-body">
                <ol class="list-group list-group-numbered">
                    <li class="list-group-item">
                        Hafner, J., Lorsbach, T., Schmidt, S. <em>et al.</em>
                        <cite>Advancements in biotransformation pathway prediction: enhancements, datasets, and novel
                            functionalities in enviPath.</cite>
                        <a href="https://doi.org/10.1186/s13321-024-00881-6" target="_blank">J Cheminform 16, 93
                            (2024)</a>
                    </li>
                    <li class="list-group-item">
                        Wicker, J., Lorsbach, T., Gütlein, M., Schmid, E., Latino, D., Kramer, S., Fenner, K.
                        <cite>enviPath - The environmental contaminant biotransformation pathway resource</cite>
                        <a href="https://doi.org/10.1093/nar/gkv1229" target="_blank">
                            Nucleic Acids Research, Volume 44, Issue D1, 4 January 2016, Pages D502-D508
                        </a>
                    </li>
                </ol>
            </div>

          <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>


    <div class="modal fade bs-modal-sm" id="signupmodal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-sm">
	<div class="modal-content">
          <br>
          <div class="bs-example bs-example-tabs">
            <ul id="myTab" class="nav nav-tabs">
              <li class="active"><a href="#signin" data-toggle="tab">Sign In</a></li>
              <li class=""><a href="#signup" data-toggle="tab">Register</a></li>
              <li class=""><a href="#why" data-toggle="tab">Why?</a></li>
            </ul>
          </div>
	  <div class="modal-body">
            <div id="myTabContent" class="tab-content">


	      <!-- Why tab -->

              <div class="tab-pane fade in" id="why">
		<p>After you register, you have more permissions on
		this site, e.g., can create your own
		  packages, submit data for review, and set access
		  permissions to your data.</p>
		<p></p><p>
		  <br> Please
		  contact <a href="mailto:admin@envipath.org">admin@envipath.org</a>
		  if you have any questions.</p>
	      </div>
	      <div class="tab-pane fade active in" id="signin">
		<form class="form-horizontal" method="post" action="">
		  <fieldset>
		  <input type="hidden" name="hiddenMethod" id="login" value="login" />

		    <!-- Sign In Form -->
		    <!-- Text input-->
		    <div class="control-group">
		      <label class="control-label" for="userinput">Login:</label>
		      <div class="controls">
			<input required
			       id="userinput"
			       name="loginusername"
			       type="text"
			       class="form-control"
			       placeholder="User"
			       class="input-medium" >
		      </div>
		    </div>

		    <!-- Password input-->
		    <div class="control-group">
		      <label class="control-label" for="passwordinput">Password:</label>
		      <div class="controls">
			<input required
			       id="passwordinput"
			       name="loginpassword"
			       class="form-control"
			       type="password"
			       placeholder="********"
			       class="input-medium">
		      </div>
		    </div>

		    <!-- Multiple Checkboxes (inline) -->
		    <!-- <div class="control-group"> -->
		    <!--   <label class="control-label" -->
		    <!-- 	     for="rememberme"></label> -->
		    <!--   <div class="controls"> -->
		    <!-- 	<label class="checkbox inline" for="rememberme-0"> -->
		    <!-- 	  <input type="checkbox"  -->
		    <!-- 		 name="rememberme"  -->
		    <!-- 		 id="rememberme-0"  -->
		    <!-- 		 value="Remember me"> -->
		    <!-- 	  Remember me -->
		    <!-- 	</label> -->
		    <!--   </div> -->
		    <!-- </div> -->

		    <!-- Button -->
		    <div class="control-group">
		      <label class="control-label" for="signin"></label>
		      <div class="controls">
			<button id="signin"
				name="signin"
				class="btn btn-success">Sign In</button>
		      </div>
		    </div>
		  </fieldset>
		</form>
	      </div>

	      <!-- Register -->
	      <div class="tab-pane fade"
		   id="signup">
			  <div id="passwordGuideline" class="alert alert-info">
				  The password must contain 8 to 30 characters<br>
				  The following characters are allowed:
				  - Upper and lower case characters<br>
				  - Digits<br>
				  - Special characters _, -, +<br>

			  </div>

			  <form id="signup-action"
					class="form-horizontal"
		      action="/user"
		      method="post">
		  <fieldset>
		    <!-- Sign Up Form -->
		    <!-- Text input-->
		    <div class="control-group">
		      <label class="control-label"
			     for="email">Email:</label>
		      <div class="controls">
			<input id="email"
			       name="email"
			       class="form-control"
			       type="email"
			       placeholder="user@envipath.org"
			       class="input-large" required>
		      </div>
		    </div>

		    <!-- Text input-->
		    <div class="control-group">
		      <label class="control-label" for="userid">Username:</label>
		      <div class="controls">
			<input id="userid"
			       name="username"
			       class="form-control"
			       type="text"
			       placeholder="user"
			       class="input-large" required>
		      </div>
		    </div>

		    <!-- Password input-->
		    <div class="control-group">
		      <label class="control-label"
			     for="password">Password:</label>
		      <div class="controls">
			<input id="password"
			       name="password"
			       class="form-control"
			       type="password"
			       placeholder="********"
			       class="input-large"
			       required>
		      </div>
		    </div>

		    <!-- Text input-->
		    <div class="control-group">
		      <label class="control-label"
			     for="reenterpassword">Re-Enter Password:</label>
		      <div class="controls">
			<input id="reenterpassword"
			       class="form-control"
			       name="reenterpassword"
			       type="password"
			       placeholder="********"
			       class="input-large"
			       required>
		      </div>
		    </div>
		    <input id="redirectTo" type="hidden" name="redirectTo" value="">
		    <!-- Multiple Radios (inline) -->
		    <br>
		    <div class="control-group">
		      <label class="control-label" for="humancheck">Humanity Check:</label>
		      <div style="margin-left:8%" class="controls">
		    	<label class="radio inline" for="humancheck-0">
		    	  <input type="radio" name="humancheck" id="humancheck-0" value="robot" checked="checked">I'm a Robot</label>
		    	<label class="radio inline" for="humancheck-1">
		    	  <input type="radio" name="humancheck" id="humancheck-1" value="human">I'm Human</label>
		      </div>
		    </div>

		    <!-- Button -->
		    <div class="control-group">
		      <label class="control-label"
			     for="confirmsignup"></label>
		      <div class="controls">
			<button id="confirmsignup"
				name="confirmsignup"
				class="btn btn-success">Sign Up</button>
		      </div>
		    </div>
		  </fieldset>
		</form>
	      </div>
	    </div>
	  </div>
	  <div class="modal-footer">
	    <center>
	      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
	    </center>
	  </div>
	</div>
      </div>
    </div>








<div id="sidebarNav" style="position:fixed;right:0;">
    <style>
        /* sidebar */
        .bs-docs-sidebar {
            padding-left: 20px;
            margin-top: 20px;
            margin-bottom: 20px;
        }

        /* all links */
        .bs-docs-sidebar .nav>li>a {
            color: #999;
            border-left: 2px solid transparent;
            padding: 4px 20px;
            font-size: 13px;
            font-weight: 400;
        }

        /* active & hover links */
        .bs-docs-sidebar .nav>.active>a,
        .bs-docs-sidebar .nav>li>a:hover,
        .bs-docs-sidebar .nav>li>a:focus {
            color: #000000;
            text-decoration: none;
            background-color: transparent;
            border-left-color: #000000;
        }
        /* all active links */
        .bs-docs-sidebar .nav>.active>a,
        .bs-docs-sidebar .nav>.active:hover>a,
        .bs-docs-sidebar .nav>.active:focus>a {
            font-weight: 700;
        }

        /* hide nav bar if screen to small*/
        @media screen and (max-width: 1550px){ /*originally at 500px*/
            .bs-docs-sidebar {
                display:none
        }
        #sidebar.floating {
            position: fixed;
            top: 0;
            right: 0;
        }
    </style>
    <script>
        // marks shown part of site as actice (doesnt seem to work TODO)
        $('docContent').scrollspy({
            target: '.bs-docs-sidebar',
            offset: 40
        });
        // keeps nav bar in the top right corner
        $(document).ready( function() {

            $(window).scroll( function() {
                if ($(window).scrollTop() > $('#sidebarNav').offset().top)
                    $('#sidebar').addClass('floating');
                else
                    $('#sidebar').removeClass('floating');
            } );

        } );
	</script>
</div>

    <div id="docContent" class="content container">
        <div id="bread"></div>
        <div id="internetExplorerWarning"></div>
        <div id="justRegistered"></div>
        <div id="activationStatus"></div>
        <div id="alreadyExisting"></div>
        <div id="noPermission"></div>
        <div id="nothingChanged"></div>
		<div id="passwordChanged"></div>
        <div id="exception"></div>
	<!-- toggle, hide, show -->

	<!-- [variable 'content'] -->

<div class="modal fade" tabindex="-1" id="newScenGenModal" role="dialog"
     aria-labelledby="newScenGenMod" aria-hidden="true">
  <div class="modal-dialog" id="addmodal">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">&times;</span> <span
						     class="sr-only">Close</span>
        </button>
	<h4 class="js-title-step"></h4>
      </div>
      <form id="base-scenario-form" accept-charset="UTF-8" action=""
	    data-remote="true" method="POST">

	<div class="modal-body hide" data-step="1" data-title="New
							       Scenario
							       - Step
							       1">
	  <div class="jumbotron">Please enter name, description,
	    and date of scenario. Date should be associated to the
	    data, not the current date. For example, this could
	    reflect the publishing date of a study. You can leave
	    all fields but the name empty and fill them in
	    later.</div>
          <label for="name">Name</label> <input id="name"
                                                name="studyname"
                                                placeholder="Name"
                                                class="form-control"/>
          <label for="name">Description</label> <input
						   id="description" name="studydescription"
						   placeholder="Description" class="form-control"/>
          <label id="dateField" for="dateYear">Date</label>
          <!--<input type="date" id="date" name="date"-->
                 <!--class="form-control" placeholder="1.1.1970">-->
					<table>
						<tr>
							<th>
								<input type="number" id="dateYear" name="dateYear"
											 class="form-control" placeholder="YYYY">
							</th>
							<th>
								<input type="number" id="dateMonth" name="dateMonth" min="1"
											 max="12"
											 class="form-control" placeholder="MM" align="">
							</th>
							<th>
								<input type="number" id="dateDay" name="dateDay" min="1"
											 max="31"
											 class="form-control" placeholder="DD">
							</th>
						</tr>

					</table>



	</div>
	<div class="modal-body hide" data-step="2" data-title="New
							       Scenario
							     - Step 2">

	  <div class="jumbotron">
	  <div id="testdiv"></div>

          Do you want to create an empty scenario and fill it
          with your own set of attributes, or fill in a
          pre-defined set of attributes for soil or sludge
          data?
	  </div>
	  <div class="radio">
	    <label><input type="radio" name="type" id="radioEmpty" onclick="clickedRadios()" checked>Empty Scenario</label>
	  </div>
	  <div class="radio">
	    <label><input type="radio" name="type" id="radioSoil"
	    onclick="clickedRadios()" value="soil" >Soil Data</label>
	  </div>
	  <div class="radio">
	    <label><input type="radio" name="type" id="radioSludge"
	    onclick="clickedRadios()" value="sludge">Sludge Data</label>
	  </div>
      <div class="radio">
		<label><input type="radio" name="type" id="radioSediment"
		onclick="clickedRadios()" value="sediment">Water-Sediment System Data</label>
      </div>
	</div>
      </form>

      <div class="modal-body hide" data-step="3" data-title="New
							     Scenario
							     - Step 3">
	<div class="jumbotron" id="finaljumbo">All done! Click
	  Submit!</div>
	<div style="float: left"><button
				    id="addColumnButton" type="button"
				    class="btn btn-default">Add
	    another Scenario
        </button></div>
	<input type="hidden" name="fullScenario" value="true"></input>
	<div id="tableDiv">
        </div>


      </div>
      <div class="modal-footer">
	<button type="button" class="btn btn-default js-btn-step pull-left" data-orientation="cancel" data-dismiss="modal"></button>
	<button type="button" class="btn btn-default js-btn-step" data-orientation="previous"></button>
	<button type="button" class="btn btn-default js-btn-step"
		data-orientation="next" id="nextbutton"></button>


      </div>
    </div>
  </div>
</div>



<p></p>
<div id="scenariocontent"></div>

<!--Template index -->
<script language="javascript">


  var title = 'Scenarios';
  var desc = 'A scenario contains meta-information that can be attached to other data (compounds, rules, ..).'
      + ' <a target="_blank" href="https://wiki.envipath.org/index.php/scenarios" role="button">Learn more &gt;&gt;</a>';


  document.title = "enviPath - Scenarios";
  makeLoadingGif('#scenariocontent');
  $.ajaxSetup({
      async: false
  });
  getObjects(makeList, '#scenariocontent', 'scenario', title, desc, true, undefined, true);
  var actionsIdArray = ["#newScenGenModal"];
  var actionsNameArray = ["New Scenario"];
  var actionsGlyphiconArray =
      ["glyphicon glyphicon-plus", "glyphicon glyphicon-plus", "glyphicon glyphicon-plus"];
  makeActionsButton('#headingPanel', actionsIdArray, actionsNameArray, actionsGlyphiconArray);
  $.ajaxSetup({
      async: true
  });
  $('#modal-form-submit').on('click', function (e) {
      if (isInputGiven("name")) {
	  e.preventDefault();
	  $('#modal-form').submit();
      }
  });


  var callback1 = function (){
      checkSecondStep();
  };


  var callback2 = function (){
      if(scenCounter < 1){
	  addColumnAndResize();
      }
      if(document.getElementById('radioEmpty').checked){
	  $('#newScenGenModal').modal('hide');
	  $('#base-scenario-form').submit();
      }
  };


  function nextToText( text) {
      var next = document.getElementById('nextbutton');
      next.innerHTML = text;
  }


  function checkSecondStep(){
      if(document.getElementById('radioEmpty').checked){
	  nextToText("Submit");
      } else {
	  nextToText("Next");
      }

  }


    function clickedRadios(){
      checkSecondStep();

      var jumboelement = document.getElementById('finaljumbo');
      var finalelement = document.getElementById('finalstep');

      if(document.getElementById('radioEmpty').checked) {
	  jumboelement.innerHTML =
	      "All done! Click Complete!";
      }
      if(document.getElementById('radioSludge').checked) {
	  jumboelement.innerHTML =
	      "These are attributes particular"
	      +" for sludge data. You do not"
	      +" have to fill in all fields,"
	      +" you can update the scenario"
	      +" later. You can enter multiple"
	      +" Scenarios at the same time,"
	      +" just click the Add button. "
	      + " The scenarios will be named "
	      + " givenname-counter.";
	  fillAdInfoInputfields('sludge');
	  scenCounter = 0;

      }
      if(document.getElementById('radioSoil').checked) {
	  jumboelement.innerHTML ="These are attributes particular"
	      +" for soil data. You do not"
	      +" have to fill in all fields,"
	      +" you can update the scenario"
	      +" later. You can enter multiple"
	      +" Scenarios at the same time,"
	      +" just click the Add button.";
	      + " The scenarios will be named "
	      + " givenname-counter.";
	  fillAdInfoInputfields('soil');
	  scenCounter = 0;
      }
      if(document.getElementById('radioSediment').checked) {
	  jumboelement.innerHTML ="These are attributes particular"
	      +" for water-sediment system data. You do not"
	      +" have to fill in all fields,"
	      +" you can update the scenario"
	      +" later. You can enter multiple"
	      +" Scenarios at the same time,"
	      +" just click the Add button.";
	      + " The scenarios will be named "
	      + " givenname-counter.";
	  fillAdInfoInputfields('sediment');
	  scenCounter = 0;
      }



  }

  var startwidth = -1;

  function addColumnAndResize() {
      // Add new column
      addColumn();
      // Increase scenario counter
      scenCounter++;


      if(startwidth < 0) {
	  startwidth = $('#addmodal').width();
      }

      // increase by this size
      var increaseBy = 120;

      // Only increase size if there are too many columns to fit on
      // the modal. Plus 1 as the name column is already there.
      if((scenCounter+1) * increaseBy > startwidth) {

	  // Resize modal dialog
	  var $modal = $('.modal-dialog');
	  var w = (scenCounter+1) * increaseBy;
	  $modal.animate({width: w});
      }

  }

  /**
   * Gets an adInfo identifier and creates a hidden
   * input specifying the type
   * @param identifier adinfo type
   * @returns {string}
   */
  function addHiddenInputForType(identifier) {
      return '<input ' +
	  'id="hidden' + identifier + '"' +
	  'type="hidden" ' +
	  'name="type" ' +
	  'value="' + identifier + '"/>';
  }

  // Contains all adInfos after fillAdInfoInputfields is called
  // once
  var adInfos = [];
  var scenCounter = 0;


  /**
   * Pushes additional infos from 'infos' into the global adInfos array
   */
  function fillAdInfosArray(infos){
      for(var x in infos){
          adInfos.push(infos[x])
      }
  }

  /**
   * Initializes the scenario table with a group of additional information
   * containing their group title and a list of adInfos
   */
  function initScenarioTableFromGroup(group){
      var content = "";
      content += '<tr id="' + group.id +
              'Row" style="background-color: rgba(0, 0, 0, 0.08);">';
      content += '<td><p style="font-size:18px">' + group.title + '</p></td>';
      content += '</td>';
      content += '</tr>';

      // Fill table with input fields
      for (var x in group.infos) {
          var adInfo = group.infos[x];
          var fullName = adInfo.fullName;
          if(adInfo.unit){
              fullName += ' in ('+adInfo.unit+')';
          }
          var identifier = adInfo.identifier;
          content += '<tr id="' + identifier + 'Row">';
          content += '<td>' + fullName + '</td>';
          content += '</td>';
          content += '</tr>';
      }
      return content;
  }

  /**
   * Initializes the scenario table with the type
   */
  function fillAdInfoInputfields(type) {
      $.getJSON(getBasePath() + "/" + "addinf?allAIGrouped=" + type, function (result) {
          var specificGroup1, specificGroup2, expGroup, miscGroup;

          adInfos = [];
          if("sludge" === type){
              specificGroup1 = result.sludge;
              specificGroup2 = result.comp;
          } else if ("soil" === type){
              specificGroup1 = result.soil;
              specificGroup2 = result.spike;
          } else if ("sediment" === type){
              specificGroup1 = result.sediment;
              specificGroup2 = result.spike;
          }
          expGroup = result.exp;
          miscGroup = result.misc;

          fillAdInfosArray(specificGroup1.infos);
          fillAdInfosArray(expGroup.infos);
          fillAdInfosArray(specificGroup2.infos);
          fillAdInfosArray(miscGroup.infos);



          // Create input table
          var table = '<table class="table table-bordered table-hover">';
          table += initScenarioTableFromGroup(specificGroup1);
          table += initScenarioTableFromGroup(expGroup);
          table += initScenarioTableFromGroup(specificGroup2);
          table += initScenarioTableFromGroup(miscGroup);
          table += '</table>';

          $("#tableDiv").html("");
          $("#tableDiv").append(table);

      });
  }


  /**
   * Adds a new column with adinfos to the scenario table
   */
  function addColumn() {
	  for (var x in adInfos) {

	      var adInfo = adInfos[x];
		  if(adInfo.identifier === 'halflife'){
              // Skip halflifes since they are not allowed
              // to be created on the straight way
		      continue;
		  }
	      var inputFields = adInfo.inputfields;
		  var identifier = adInfo.identifier;
		  var content = '<td>';
		  content += '<div id="' + identifier + 'Div-' + scenCounter + '">';
		  for (var y in inputFields) {
			  content += inputFields[y];
		  }

		  // Add hidden input for the adInfo type
		  // Append input type as hidden param
		  content += addHiddenInputForType(identifier);

		  content += '</div></td>';
		  $('#' + identifier + 'Row').append(content);

		  // Append scenarioCounter to id to make input ids
		  // unique
		  $('#' + identifier + 'Div-' + scenCounter).children().each(function (index, value) {
		      var id = value.id;

		      // Check for id to skip <p>...</p> and other tags
              if(id){
                  var newId = id + '-' + scenCounter;
                  $('#' + id).attr('id', newId);
              }
		  });


	  }

	  // Fill spike compound selector
	  var temp = ["#spikeComp-" + scenCounter];
	  getCompounds(temp, attachCompounds);
  }


  // Onclick for select scenario type
  $('#adInfoTypeSelectAddFullSc').change(function () {
      var type = $(this).find(':selected').val();
      // Clear input fields
      $("#tableDiv").empty();

      // Reset scen count
      scenCounter = 0;

      // Fill with AI input fields
      fillAdInfoInputfields(type)
  });

  // Set OnClick function to add a new column
  $('#addColumnButton').on('click', function (e) {
      addColumnAndResize();
  });


  /**
   * Return the column index of a given id assuming that the index is
   * seperated by a '-' from the actual id:
   * 'spikeComp-3' -> 3
   *
   * returns -1 if column index could not be determined
   */
  function getColIndexById(id) {
      if (id.indexOf('-') <= -1) {
	  return -1;
      }
      var i = id.lastIndexOf('-');
      var ss = id.substring(i + 1);
      return parseInt(ss);
  }

  /**
   * Returns the number of scenarios to be posted
   */
  function getNumberOfScenarios() {
      // Get number of columns (equals the maximum column index)
      var idxMaxColumn = 0;
      $('#tableDiv div').each(function (index, value) {
		  var divId = value.id;
		  var divIdx = getColIndexById(divId);
		  idxMaxColumn = Math.max(idxMaxColumn, divIdx);
      });
      return idxMaxColumn;
  }

  /**
   * Fills the data array with adinfo inputs and selects, given by the user
   */
  function fillDataByDiv(divId, data, adInfoType) {
      // For each input/select of the current div
      $('#' + divId + ' > input, ' +
              '#' + divId + ' > select').each(function (index, val) {

          // Get attributes of current input/select

          var type = val.type;
          var name = val.name;
          var value = val.value;

          //Special case for halftime checkbox
          if (name == "firstOrder") {
              value = $('#firstOrder-0').prop("checked")
              if (value == false) {
                  return
              }
          }

          // Skip pmid and reference, see extra case
          if (name == 'pmid' || name == 'reference' || value ==
              'reference') {
              return;
          }

          // Check if input is given and the attribute is not hidden
          if (isInputGiven(val.id) && type != 'hidden') {


              // some extra cases
              switch (name) {
                  case 'addparametersmeasured':
                      var selectId = val.id;
                      var values = $('#' + selectId).val();
                      value = values.join(';');
                      break;
									case 'acidityType':
									    var selectId = val.id;
									    var values  = $('#' + selectId).val(),
											value = values.join(",");
              }

              // Default: simply push to data array
              data.push({name: name, value: value});
              //Getting the corresponding hidden value
							// Special cases for ranges. Only cases for start values necessary.
							// For End values default case does the job.
							switch (name) {
									case 'amionauptakerateStart':
									    adInfoType = "amionauptakerate";
									    break;
									case "oxygenuptakerateStart":
											adInfoType = "oxygenuptakerate";
											break;
									case "totalorganiccarbonStart":
									    adInfoType = "totalorganiccarbon";
									    break;
									case "dissolvedorganiccarbonStart":
									    adInfoType = "dissolvedorganiccarbon";
									    break;
									case "phosphoruscontentInfluent":
									    adInfoType = "phosphoruscontent";
									    break;
									case "oxygendemandInfluent":
									    adInfoType = "oxygendemand";
									    break;
									case "nitrogencontentInfluent":
									    adInfoType = "nitrogencontent";
									    break;
									case "temperatureMin":
									    adInfoType = "temperature";
									    break;
									case "solventforcompoundsolution1":
									    adInfoType = "solventforcompoundsolution";
									    break;
									case "ttsStart":
									    adInfoType = "tts";
									    break;
									case "volatilettsStart":
									    adInfoType = "volatiletts";
									    break;
									case "lowPh":
									    adInfoType = "acidity";
									    break;
                  case "highPh":
                      adInfoType = "acidity";
                      break;
									case 'omcontentInOM':
									    adInfoType = "omcontent";
									    break;
									case 'DissolvedoxygenconcentrationLow':
									    adInfoType = "Dissolvedoxygenconcentration";
									    break;
									case 'bioreactortype':
									    adInfoType = "bioreactor";
									    break;
									default: adInfoType = $(this).next("input:hidden").val();
							}

          }
      });
      return {adInfoType: adInfoType};
  }

  /**
   * Extra case for Reference/PubMED
   */
  function checkReferenceInput(col, adInfoTypesArray, dataArray) {
	  /*
	   Only allow the pmid OR the reference to be given
	   */

	  // Get values of pmid and refernce
	  var pmid = $('#pmid-' + col).val();
	  var reference =
			  $('#reference-' + col).val();
//	  var pmidGiven = pmid != '';
//	  var referenceGiven = reference != '';

	  if(pmid && reference) {
		  toggleInputPopup('pmid-' + col,
				  'Set PubMed ID OR Reference');
		  toggleInputPopup('reference-' + col,
				  'Set PubMed ID OR Reference');
	  	return true
	  }

	  return false;
  }

  /**
	 * Extra case for Spike compound. Only one entry should be filled
	 */
  function checkSpikeCompound(col) {

      var select = $('#spikeComp-' + col).val();
			var smile = $('#smile-' + col).val();
			var selectUndef = select != "undefined"
			if (selectUndef && smile) {
          toggleInputPopup('spikeComp-' + col ,
              'Select compound OR enter smile');
          toggleInputPopup('smile-' + col,
              'Select compound OR enter smile');
          return true;
			}
			return false;
	}

	/**
	 * Extra Case for temperature. Min has to be smaller than max.
	 */
	function checkTemperature(col) {
			var min = $('#temperatureMin-' + col).val();
			var max = $('#temperatureMax-' + col).val();
			// If both are set, check if min < max.
			if (min && max){
			    if (parseFloat(min) > parseFloat(max)) {
              toggleInputPopup('temperatureMin-' + col,
                  'Min temperature should be smaller than max temperature');
              toggleInputPopup('temperatureMax-' + col,
                  'Min temperature should be smaller than max temperature');
              return true;
					}
			}
			return false;
  }

  /**
	 * Only allowed that select and minimum start or end value is set
	 * start could be "Start", "Min" or "Influent"
	 * end could be "End", "Max" or "Effluent"
	 */
  function checkSelectWithRange(col, id, start, end){
      var select = $('#' + id + 'Type' + '-' + col).val();
			var startVal = $('#' + id + start + '-' + col).val();
			var endVal = $('#' + id + end + '-' + col).val();

			if ((select && !(startVal || endVal)) ||
					(!select && (startVal || endVal))) {
          toggleInputPopup(id + 'Type' + '-' + col, 'Type and at minimum '
							+ start + ' or ' + end + ' value has to be set');
          toggleInputPopup(id + start + '-' + col, 'Type and at minimum '
              + start + ' or ' + end + ' value has to be set');
          toggleInputPopup(id + end + '-' + col, 'Type and at minimum '
              + start + ' or ' + end + ' value has to be set');
          return true;
			}
			return false;
	}

	/**
	 * Check if only Solvent1 is selected or Solvent1, Solvent2 and proportion,
	 * or none of them.
	 */
	function checkSolventForCommpoundSolution(col) {
	    var solvent1 = $('#solventforcompoundsolution1-' + col).val();
	    var solvent2 = $('#solventforcompoundsolution2-' + col).val();
	    var solvent3 = $('#solventforcompoundsolution3-' + col).val();
	    var proportion = $('#proportion-' + col).val();
	    if (solvent2 && !solvent1) {
					toggleInputPopup('solventforcompoundsolution1-' + col,
							'Solvent2 cannot be selected without Solvent1');
					toggleInputPopup('solventforcompoundsolution2-' + col,
							'Solvent2 cannot be selected without Solvent1');
					return true;
			}
			if ((solvent2 && !proportion) || (!solvent2 && proportion)) {
					toggleInputPopup('solventforcompoundsolution2-' + col,
							'Solvent2 cannot be selected without Proportion');
					toggleInputPopup('proportion-' + col,
							'Solvent2 cannot be selected without Proportion');
					return true;
			}
      if (proportion && !solvent1) {
          toggleInputPopup('solventforcompoundsolution1-' + col,
              'Proportion cannot be selected without Solvent1');
          toggleInputPopup('proportion-' + col,
              'Proportion cannot be selected without Solvent1');
          return true;
      }
      if (solvent3 && !solvent1) {
          toggleInputPopup('solventforcompoundsolution1-' + col,
              'Solvent3 cannot be selected without Solvent1');
          toggleInputPopup('solventforcompoundsolution3-' + col,
              'Solvent3 cannot be selected without Solvent1');
          return true;
			}
      if (solvent3 && !solvent1) {
          toggleInputPopup('solventforcompoundsolution1-' + col,
              'Solvent3 cannot be selected without Solvent1');
          toggleInputPopup('solventforcompoundsolution3-' + col,
              'Solvent3 cannot be selected without Solvent1');
          return true;
      }
      if (solvent3 && !solvent2) {
          toggleInputPopup('solventforcompoundsolution2-' + col,
              'Solvent3 cannot be selected without Solvent2');
          toggleInputPopup('solventforcompoundsolution3-' + col,
              'Solvent3 cannot be selected without Solvent2');
          return true;
      }
      if (proportion) {
          // Check if proportion is of format double:double
          var propSpit = proportion.split(":");
          // There are 3 solvents
          if (solvent3) {
              if (propSpit.length == 3) {
                  // Check if both values are doubles
                  if (propSpit[0].match(/^\d+.?\d*$/) &&
                      propSpit[1].match(/^\d+.?\d*$/) &&
                      propSpit[2].match(/^\d+.?\d*$/)) {
                      return false;
                  }
              }
              toggleInputPopup('proportion-' + col,
                  'Proportion should be of format Number1:Number2:Number3');
              return true;
					}
					// There are only 2 solvents
	        if (propSpit.length == 2) {
	            // Check if both values are doubles
	            if (propSpit[0].match(/^\d+.?\d*$/) &&
									propSpit[1].match(/^\d+.?\d*$/)) {
									return false;
							}
					}
					toggleInputPopup('proportion-' + col,
              'Proportion should be of format Number1:Number2');
					return true;
			}

	    return false;
	}

	/**
	 * For sludge age check if select value and input value is set.
	 */
	function checkSludgeRetentionTime(col) {
	    var type = $('#sludgeretentiontimeType-' + col).val();
			var val = $('#sludgeretentiontime-' + col).val();
			if ((type && !val) || (!type && val)) {
          toggleInputPopup('sludgeretentiontimeType-' + col,
              'Type and value has to be set');
          toggleInputPopup('sludgeretentiontime-' + col,
              'Type and value has to be set');
          return true;
			}
			return false;
	}

	function checkSpikeConcentration(col) {
	    var val = $('#spikeConcentration-' + col).val();
	    var unit = $('#spikeconcentrationUnit-' + col).val()
			if ((!val && unit) || (val && !unit)) {
          toggleInputPopup('spikeConcentration-' + col,
              'Value and unit has to be set');
          toggleInputPopup('spikeconcentrationUnit-' + col,
              'Value and unit has to be set');
          return true;
      }
      return false;
	}

  /**
   * Post the data
   */
  function postData(data, numScenarios) {
	  $.ajax({
				  type: 'post',
				  url: '',
				  data: data,
				  success: function (data, status, jhr) {
					  /* Redirect to new scenario if one scenario was posted
					   else reload the scenario page after the last post has
					   succeeded
					   */
					  var res = JSON.parse(data);

					  // if multiple scenarios are posted: reload page on last post
					  if (numScenarios == 0) {
						  // else go to new scenario
						  window.location = res.scenarioLocation;

					  } else {
						  // Reload after all ajax calls have stopped
						  $(document).ajaxStop(function () {
							  location.reload(true);
						  });
					  }
				  }
			  }
	  );
  }

  /**
   * Searches in each div for inputs and selects and fills the dataArray with
   * its corresponding data objects (each object in the data array refers
   * to one scenario which will be posted)
   */
  function extractDataFromTable(adInfoTypesArray, dataArray) {
      // for each div get the inputs
      $('#tableDiv').find('div').each(function (index, value) {

          // Skip 'tableDiv' and 'scenarioInfo'
          // and tooltips (popping up on missing input)
          var divId = value.id;
          if (divId == '') {
              return;
          }
          // Get column number to determine the data object which shall be filled
          // with data
          var colNum = getColIndexById(divId);
          var adInfoTypes = adInfoTypesArray[colNum];
          var data = dataArray[colNum];

          // Type of current additional information
          var adInfoType = "";

          var __ret = fillDataByDiv(divId, data, adInfoType);
          adInfoType = __ret.adInfoType;

          // Store input types
          if (adInfoType != '') {
              adInfoTypes.push(adInfoType);
          }
      });
  }
  /**
   * Posts each column in the table as seperate full-scenario
   */
  var fullScenSubmit = function () {

      // Make posts synchronous to prevent double compound insertions
      $.ajaxSetup({async: false});

      // For each scenario the dataArray contains an object 'data' which will
      // be posted afterwards
      var dataArray = [];
      var adInfoTypesArray = [];

      var numScenarios = getNumberOfScenarios();

	  // Init
	  for (var i = 0; i <= numScenarios; i++) {
		  dataArray[i] = [];
		  adInfoTypesArray[i] = [];
	  }

	  var wrong = false;
	  //Check for all columns if reference is filled correctly
	  for (var col = 0; col <= numScenarios; col++) {

		  var wrongCol = checkReferenceInput(col, adInfoTypesArray, dataArray);
		  wrongCol |= checkSpikeCompound(col);
		  wrongCol |= checkSolventForCommpoundSolution(col);
		  wrongCol |= checkTemperature(col);
		  wrongCol |= checkSludgeRetentionTime(col);
		  wrongCol |= checkSpikeConcentration(col);
		  wrongCol |= checkSelectWithRange(col, "oxygendemand", "Influent",
					"Effluent");
		  wrongCol |= checkSelectWithRange(col, "nitrogencontent", "Influent",
					"Effluent");

		  wrong |= wrongCol;
		  if (wrongCol) {
			  alert("A parameter in column " + col + " contains errorneous input!");
		  }
	  }

	  if (wrong) {
        return false;
    } else {
        // Fill the dataArray with the data from the user input (in the table)
        extractDataFromTable(adInfoTypesArray, dataArray);

        // Additional stuff
        for (var col = 0; col <= numScenarios; col++) {

            // Check reference input
//          var missing = checkReferenceInput(col, adInfoTypesArray, dataArray);
//
//		  if(missing){
//		  	//TODO
//		  }

            // Get corresponding data array
            var data = dataArray[col];

            // Add all adinfo types
            data.push({name: 'adInfoTypes[]', value: adInfoTypesArray[col]});


            // Set parameter fullScenario
            data.push({name: 'fullScenario', value: 'true'});

            // Add scenario type
            if (document.getElementById('radioSoil').checked) {
                data.push({name: 'type', value: 'soil'});
            } else if (document.getElementById('radioSludge').checked) {
                data.push({name: 'type', value: 'sludge'});
            } else if (document.getElementById('radioSediment').checked) {
                data.push({name: 'type', value: 'sediment'});
            } else {
                data.push({name: 'type', value: 'not_specified'})
            }

            // Add name
            if ($('#name').val()) {
                var scenType = $('#name').val();
                data.push({name: 'studyname', value: scenType});
            }
            // Add description
            if ($('#description').val()) {
                var scenType = $('#description').val();
                data.push({name: 'studydescription', value: scenType});
            }
            // Add date
            if ($('#dateYear').val()) {
                var scenDateYear = $('#dateYear').val();
                data.push({name: 'dateYear', value: scenDateYear});
            }
						if ($('#dateMonth').val()) {
								var scenDateMonth = $('#dateMonth').val();
                data.push({name: 'dateMonth', value: scenDateMonth});
						}
						if ($('#dateDay').val()) {
								var scenDateDay = $('#dateDay').val();
                data.push({name: 'dateDay', value: scenDateDay});
						}

            // Actual post
            postData(data, numScenarios);
        }
  	}
      // Enable async posts again
      $.ajaxSetup({async: true});

//	  $('#newScenGenModal').modal({"backdrop": "static"})
  };



  $('#newScenGenModal').modalSteps({
      btnCancelHtml: 'Cancel',
      btnPreviousHtml: 'Previous',
      btnNextHtml: 'Next',
      btnLastStepHtml: 'Submit',
      disableNextButton: false,
      completeCallback: fullScenSubmit,
      callbacks: {
	  '2': callback1,
	  '3' : callback2
      }
  });

  if (!userIsWriterOnSite()) {
      document.getElementById('actionsButton').style.display = 'none';
  }


  // Add onscroll feature
  $(window).scroll(onScrollAttachObjects);

</script><!-- [/variable 'content'] -->
    </div>



    <div class="container text-center">
      <hr />

      <div class="row">
	<div class="col-lg-12">
	  <ul class="nav nav-pills
		     nav-justified">
	    <li>
	      <a href="http://eawag.ch" target="_blank">
		<img id="image-ealogo"
                     height="60"
		   src="https://legacy.envipath.org//images/ealogo.gif"
		   alt="Eawag" />
	      </a>
	    </li>
	    <!-- <li> -->

	    <!--   <a href="http://www.uni-mainz.de/eng/" target="_blank"> -->
	    <!-- 	<img id="image-jgu-print" -->
            <!--          height="60" -->
	    <!-- 	   src="https://legacy.envipath.org//images/jgu-print.png" -->
	    <!-- 	   alt="Johannes Gutenberg-Universitaet Mainz" /> -->
	    <!--   </a> -->
	    <!-- </li> -->
	    <li>
	      <a href="http://ml.auckland.ac.nz" target="_blank">
		<img id="image-uoalogo"
                     height="60"
		   src="https://legacy.envipath.org//images/uoa.png"
		   alt="The Univserity of Auckland" />
	      </a>
	    </li>
	  </ul>
	</div>
      </div>
    </div>

    <div class="row">
      <div class="col-lg-12">
	<ul class="nav nav-pills nav-justified">
	  <li><a href="https://envipath.com/imprint/"
		 target="_blank">Impressum/Imprint</a></li>
	  <li><a href="mailto:admin@envipath.org"
		 target="_blank">Contact</a></li>

	  <li><a href="http://envipath.com" target="_blank">
	      enviPath UG (haftungsbeschr&auml;nkt) &amp; Co. KG &copy;
	      <script type="text/javascript">
                document.write(new Date().getFullYear());
              </script></a></li>
	  <!-- <li><a href="http://www.informatik.uni-mainz.de/secondnavigation/legal-notice" -->
	  <!-- target="_blank">Legal Notice</a></li> -->
	</ul>
	</div>
    </div>


    <script type="text/javascript">
    if((navigator.userAgent.indexOf("MSIE") != -1 )
            || (!!document.documentMode == true )) {
        var theDiv = document.getElementById("internetExplorerWarning");
        var content = '<div class="alert '
                + 'alert-danger"> Please note: We are experiencing problems '
                + 'displaying pathways with Microsoft Internet Explorer and it is unlikely that there will '
                + 'be a solution any time soon! We suggest using Mozilla Firefox or Google Chrome instead.'
				+ '</div>';
        theDiv.innerHTML += content;
    }
    </script>

    <input type="hidden" id="refreshed" value="no">
				<script type="text/javascript">

	// TODO This needs a refactoring!!!

	$.getJSON("?getname=true",function(result){
	    if(result.name !== "" && result.name !== undefined) {
    	    document.title = document.title + " - " + result.name;
        }
	 });

				  // to refresh page after hitting back button
            addLoadEvent(function(){
                var e=document.getElementById("refreshed");
                if(e.value=="no")e.value="yes";
                else{e.value="no";location.reload();}
            });
        //fill breadcrumbs
        var url = window.location.href + "";
        var content = "<ol class='breadcrumb'>";
        var theDiv = document.getElementById("bread");


        if (appPath!="") {

//            Update href of links
            document.getElementById("packageLink").href = getBasePath() +
                "/package";
            document.getElementById("pathwayLink").href = getBasePath() +
                "/pathway";
            document.getElementById("ruleLink").href = getBasePath() + "/rule";
            document.getElementById("compoundLink").href = getBasePath() +
                "/compound";
            document.getElementById("reactionLink").href = getBasePath() +
                "/reaction";
            document.getElementById("relative-reasoningLink").href =
                getBasePath() +
                "/relative-reasoning";
            document.getElementById("scenarioLink").href = getBasePath() +
                "/scenario";
            document.getElementById("settingLink").href = getBasePath() +
								"/setting";
            document.getElementById("userLink").href = getBasePath() + "/user";
            document.getElementById("groupLink").href = getBasePath() + "/group";
            document.getElementById("searchLink").href = getBasePath() + "/search";
            document.getElementById("contributorsLink").href = getBasePath() +
								"/contributors";
            document.getElementById("fundingLink").href = getBasePath() +
								"/funding";
            document.getElementById("licenceLink").href = getBasePath() +
								"/licence";
            document.getElementById("wikiLink").href = "https://wiki.envipath.org/";
            //Update signup
            document.getElementById("signup-action").action = getBasePath() + "/" +
                "user";
        }


        // Get Pathname by taking the difference between full url and basePath
        var currentPathname = window.location.href.replace(getBasePath(),"");
        var active = "Active";
        var locationName = "Location";
        if (currentPathname){
            var pathArray = currentPathname.split( '/' );
            content += "<li><a href='" + getBasePath() + "'>Home</a></li>";
            for (j = 0; j < pathArray.length; j++) {
                if (pathArray[j] === "") continue;
                if (pathArray[j] === "index") continue;
                var newPathname = getBasePath();

                for (i = 1; i < j+1; i++) {
                    newPathname += "/";
                    newPathname += pathArray[i];
                }

                if (i === pathArray.length) {
                    active = pathArray[j];
                    // if active is an ID get name from json
                    if ((active.length === 36)
                        && (active.indexOf("-") === 8)
                        && (active.indexOf("-",9) === 13)
                        && (active.indexOf("-",14) === 18)
                        && (active.indexOf("-",19) === 23)){

                        $.ajaxSetup({
                            async: false
                        });
                        $.getJSON("?getname=true", function(result) {
                            active = result.name;
                        })
                            .fail( function(d) {
                                handleError(JSON.parse(d.responseText));
                            });
                    } else {
											/* if ((active != "funding") && (active != "documentation")
											 && (active != "contributors") && (active != "lhs")
											 && (active != "rhs")){
											 active = active.concat("s");
											 }*/
											// Capitalize active
												// active = active.capitalize();
                        active = active.charAt(0).toUpperCase() +
														active.slice(1);
                    }

                    content += "<li class='active'>" + active + "</a></li>";
                    $.ajaxSetup({
                        async: true
                    });
                } else {
                    locationName = pathArray[j];
                    if ((locationName.length === 36)
                        && (locationName.indexOf("-") === 8)
                        && (locationName.indexOf("-",9) === 13)
                        && (locationName.indexOf("-",14) === 18)
                        && (locationName.indexOf("-",19) === 23)){

                        $.ajaxSetup({
                            async: false
                        });

                        $.getJSON(newPathname + "?getname=true", function(result) {
                            locationName = result.name;
                        })
                            .fail( function(d) {
                                handleError(JSON.parse(d.responseText));
                            });
                    } else {
                        if((locationName != "rhs") && (locationName != "lhs"))
                        //locationName = locationName.concat("s");
                        // simple-rule / parallel-rule / composite-rule are all shown under rule
                            if (locationName.indexOf("-rule") > -1) {
                                newPathname = newPathname.substring(0,newPathname.lastIndexOf("/")+1)+"rule";
                                locationName = locationName.replace(/^.*-/,"");
                            }
												// Capitalize
												//locationName = locationName.capitalize();
                        locationName = locationName.charAt(0).toUpperCase() +
                            locationName.slice(1);
                    }

                    content += "<li><a href='" + newPathname + "'>"
                        + locationName + "</a></li>";
                    $.ajaxSetup({
                        async: true
                    });
                }
            }
            content += "</ol>";
        } else {
            content += "<li><a href='"+ url +"'>Home</a></li></ol>"
        }
        // don't show breadcrumbs on start page
        if(window.location.href == getBasePath() || pathArray[1] == "") {
            content = "";
        }
        theDiv.innerHTML += content;
		</script>
				<script>
				whoAmI();
      //enables popovers on all elements of the ppsPopover class
      var url = window.location.href + "";
      if(url.indexOf("justRegistered=true") > -1){
          var theDiv = document.getElementById("justRegistered");
          var content = '<div class="alert '
                  + 'alert-warning"> <button type="button" class="close" '
                  + 'data-dismiss="alert" aria-label="Close"><span aria-hidden="true"'
                  + '>&times;</span></button> Received registration request!'
	          + ' To complete your'
	          + ' registration, click the confirmation'
                  + ' link in the E-Mail we just send you, to complete'
                  + ' your registration! Make sure to do this before trying to log in.</div>';
          theDiv.innerHTML += content;
      }

      if(url.indexOf("activationSuccessful") > -1){
          var theDiv = document.getElementById("activationStatus");
          var content = '<div class="alert '
                  + 'alert-success"> <button type="button" class="close" '
                  + 'data-dismiss="alert" aria-label="Close"><span aria-hidden="true"'
                  + '>&times;</span></button> Your activation was successful!</div>';
          theDiv.innerHTML += content;
      }

      if(url.indexOf("alreadyExisting") > -1){
    	  var obj = "object";

    	  if(url.indexOf("compound") > -1){
    		  obj = "compound";
    	  }
    	  if(url.indexOf("reaction")){
    		  obj = "reaction";
    	  }

    	  var theDiv = document.getElementById("alreadyExisting");
          var content = '<div class="alert '
                  + 'alert-success"> <button type="button" class="close" '
                  + 'data-dismiss="alert" aria-label="Close"><span aria-hidden="true"'
                  + '>&times;</span></button>You are redirected to an equal '+obj+'! But you can modify it.</div>';
          theDiv.innerHTML += content;

      }

      if(url.indexOf("activationFailed") > -1){
          var theDiv = document.getElementById("activationStatus");
          var content = '<div class="alert '
                  + 'alert-danger"> Your activation was not successful! '
                  + 'Please check the activation link. '
                  + 'If your activation link is broken please contact: admin@envipath.org'
                  + '</div>';
          theDiv.innerHTML += content;
      }

      if(url.indexOf("alreadyActivated") > -1){
          var theDiv = document.getElementById("activationStatus");
          var content = '<div class="alert '
                  + 'alert-warning"> The account is already activated and can be used to log in.'
                  + '</div>';
          theDiv.innerHTML += content;
      }

      if(url.indexOf("nothingChanged") > -1){
          var theDiv = document.getElementById("nothingChanged");
          var content = '<div class="alert '
                  + 'alert-danger"> <button type="button" class="close" '
                  + 'data-dismiss="alert" aria-label="Close"><span aria-hidden="true"'
                  + '>&times;</span></button> You have not entered any input, nothing was changed! '
                  + '</div>';
          theDiv.innerHTML += content;
      }

	  // Give feedback whether the password was changed
      if(url.indexOf("passwordChanged") > -1) {
      	  var theDiv = document.getElementById("passwordChanged");
          var content = '<div class="alert '
                  + 'alert-success"> <button type="button" class="close" '
                  + 'data-dismiss="alert" aria-label="Close"><span aria-hidden="true"'
                  + '>&times;</span></button> Password successfully changed! '
                  + '</div>';
          theDiv.innerHTML += content;
      }

      //alert if user wants to change group owner without being the current user
      if(url.indexOf("permissionToChangeOwner=false") > -1){
          var theDiv = document.getElementById("noPermission");
          var content = '<div class="alert '
                  + 'alert-danger"> <button type="button" class="close" '
                  + 'data-dismiss="alert" aria-label="Close"><span aria-hidden="true"'
                  + '>&times;</span></button> You must be the current owner of the group '
                  + 'to change the ownership of the group!</div>';
          theDiv.innerHTML += content;
      }
      document.getElementById('redirectTo').value = url;
      $('.ppsPopover').popover();
    </script>


  </body>
</html>