<?php


include("zarafa_session.php");


	// We will only allow the logon when the sessionid in the GET arguments matches the
	// sessionid as send in the cookie. Otherwise the cookie was somehow modified in the
	// browser.
	$sessionid = sanitizeGetValue('sessionid', '', ID_REGEX);
/*
	if (loadNeedsSession($load) && $sessionid !== $GLOBALS["mapisession"]->getSessionID()) {
		$hresult = MAPI_E_INVALID_WORKSTATION_ACCOUNT;
	}
*/

include_once('jsconfig.php');

	$user = sanitizeGetValue('user', '', USERNAME_REGEX);
	$meetingid = sanitizeGetValue('meetingid', '', MEETINGID_REGEX);
	$email = sanitizeGetValue('email', '', ALLOWED_EMAIL_CHARS_REGEX);
	if (isset($_GET['displayname'])) {
		$displayname = htmlspecialchars($_GET['displayname']);
	} else {
		$displayname = '';
	}

	$version = trim(file_get_contents(WEBAPP_BASE_PATH . 'version'));
	$longversion = '';
	$server = DEBUG_SHOW_SERVER ? DEBUG_SERVER_ADDRESS : '';
	if (!empty($server)) {
		$longversion .= _('Server') . ': ' . $server . ' - ';
	}
	$longversion .=  _('WebApp') . ' ' . $version;
	if (DEBUG_LOADER === LOAD_SOURCE) {
		$longversion .= '-' . gitversion();
	}
	$longversion .= ' - ' . _('KC') . ' ' . phpversion('mapi');

	$url = '?logon&noredirect';
	foreach($_GET as $key => $value) {
		if(!empty($key) && !in_array($key, array('logon', 'load'))){
			$url.= '&' . $key;
			if(!empty($value)) {
				$url.= '=' . urlencode($value);
			}
		}
	}

	header("Content-type: text/html; charset=utf-8");
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta name="Generator" content="Kopano WebApp v<?=$version?>">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Kopano WebApp Auth</title>
		<link rel="stylesheet" type="text/css" href="../resources/css/login.css">
		<link rel="icon" href="../../../client/resources/images/favicon.ico" type="image/x-icon">
		<link rel="shortcut icon" href="../../../client/resources/images/favicon.ico" type="image/x-icon">
		<script src="../js/jquery-1.6.2.min.js"></script>
		<script type="text/javascript">
		    <?= PLUGIN_SPREEDWEBRTC_JS_CONFIG ?>
			window.onload = function(){
				if (document.getElementById("username").value == ""){
					document.getElementById("username").focus();
				}else if (document.getElementById("password").value == ""){
					document.getElementById("password").focus();
				} else {
					document.getElementById("submitbutton").focus();
				}
			}
		</script>
	</head>
	<body class="login">
		<table id="layout">
			<tr><td>
				<div id="login_logo">
					<img src="../../../client/resources/images/kopano-logo_220x52.png" style="background-color:white;"/>
				</div>
			</td></tr>
			<tr><td>
				<div id="login_main">
					<form action="../../../index.php<?= $url ?>" method="post" id="joinForm">
						<div id="join_data">
							<p><?=_("Please join web meetings")?></p>
							<p class="join_error"></p>
							<table id="form_fields">
								<tr>
									<td><input type="text" name="meetingid" id="meetingid" placeholder="Meeting Id" class="inputelement" value="<?= $meetingid ?>"></td>
								</tr>
								<tr>
									<td><input type="text" name="email" id="email" placeholder="E-mail" class="inputelement" value="<?= $email ?>"></td>
								</tr>
								<tr>
									<td><input type="text" name="displayname" id="displayname" placeholder="Display name" class="inputelement" value="<?= $displayname ?>"></td>
								</tr>
								<tr>
									<td class="join-button-row"><input id="joinbutton" class="button" type="submit" value=<?=_("Join meeting")?>></td>
								</tr>
							</table>
						</div>
					</form>
					<form action="../../../kopano.php?service=authenticate" method="post" id="loginForm">
						<div id="login_data">
							<p><?=_("or logon with your Kopano account")?></p>
							<p class="error"></p>
							<table id="form_fields">
								<tr>
									<td><input type="text" name="username" id="username" placeholder="Username" class="inputelement" value="<?= $user ?>"></td>
								</tr>
								<tr>
									<td><input type="password" name="password" id="password" placeholder="Password" class="inputelement"></td>
								</tr>
								<tr>
									<td class="button-row"><input id="submitbutton" class="button" type="submit" value=<?=_("Logon")?>></td>
								</tr>
							</table>
						</div>
					</form>
					<span id="version"><?= $longversion ?></span>
				</div>
			</td></tr>
		</table>
		<script>

		$("#joinForm").submit(function(event) {
			event.preventDefault();
			var $form = $(this),
				meetingid = $form.find( "input[name='meetingid']" ).val(),
				displayname = $form.find( "input[name='displayname']" ).val(),
				email = $form.find( "input[name='email']" ).val(),
				url = config.webappAuthAuthenticationUrl;
			var posting = $.post( url, { 
				meetingid: meetingid,
				displayname: displayname,
				email: email,
				client_id: 'zarafa_webmeetings',
				client_secret: ''
			});
			posting.done(function( data, textStatus, xhr ) {
				console.log( data );
				if(typeof data =='object') {
					console.log("success JSON");
				}
				var IS_JSON = true;
				var json;
				try
				{
				       json = $.parseJSON(data);
				}
				catch(err)
				{
				       IS_JSON = false;
				}                
				if(IS_JSON) {
					console.log("success JSON text");
					parent.postMessage({
						type: "loginSuccess",
						loginSuccess: {
							type: 'code',
							code: data.code
						}
					},
					config.spreedDomain);
				} else {
					// TODO json errors handling
					console.log("authenticate failed");
					console.log(jQuery(data).find('p.error').html());
					$('p.join_error').html(error);
				}
			})
			.fail(function(jqXHR, textStatus, error) {
				console.log( jqXHR.responseText );
				var IS_JSON = true;
				var json;
				try
				{
					json = $.parseJSON(jqXHR.responseText);
				}
				catch(err)
				{
					IS_JSON = false;
				}                
				if(IS_JSON) {
					// TODO json errors handling
					console.log("authenticate failed");
					console.log(json);
					$('p.join_error').html(json.message);
				}
			});
		});

		$("#loginForm").submit(function(event) {
			event.preventDefault();
			var $form = $(this),
				username = $form.find( "input[name='username']" ).val(),
				password = $form.find( "input[name='password']" ).val(),
				url = $form.attr( "action" );
			var posting = $.post( url, { username: username, password: password } );
			posting.done(function( data, textStatus, xhr ) {
				console.log( data );
				if(typeof data =='object') {
					console.log("success JSON");
					var json = data;
					if (json['authenticated']) {
						parent.postMessage({
							type: "loginSuccess",
							loginSuccess: {
								type: 'zarafa',
								zarafa: json['user']
							}
						},
						config.spreedDomain);
					} else {
						$('p.error').html(json.error.message);
					}
				} else {
					console.log("authenticate failed");
					console.log(jQuery(data).find('p.error').html());
					$('p.error').html("authentication failed");
				}
			})
			.fail(function(jqXHR, textStatus, error) {
				console.log( jqXHR.responseText );
				var IS_JSON = true;
				var json;
				try
				{
					json = $.parseJSON(jqXHR.responseText);
				}
				catch(err)
				{
					IS_JSON = false;
				}                
				if(IS_JSON) {
					console.log("authenticate failed");
					console.log(json);
					$('p.error').html(json.error.message);
				}
			});
		});
		</script>
	</body>
</html>
