<div id="primary_header">
	<h1><?php echo $this->translate('Version Update') ?></h1>
</div>
<div id="primary_content">
    <div id="primary_content_inner">
                <div id="Flash"></div>

				<table class="settings">
					<tbody>
						<tr>
							<td class="label"><?php echo $this->translate('Current Version') ?></td>
							<td id="versionCurrentDBSchema"><?php echo $this->versionCurrentDBSchema; ?></td>
						</tr>
						<tr>
							<td class="label"><?php echo $this->translate('Available Version') ?></td>
							<td><?php echo $this->availableVersion ?></td>
						</tr>
						<tr>
							<td colspan="2" style="padding:5px;" id="versionUpdateButtonArea">

<?php if( $this->versionCurrentDBSchema == $this->availableVersion ) : ?>

								<p><?php echo $this->translate('You are up to date with the latest version available.') ?></p>
<?php elseif( $this->licenseExpired == 1 ) : ?>
	<p><?php echo $this->translate('Your version is out of date, however the software license has expired. In order to use the new Atmail version you must renew your license.') ?></p>
<?php else : ?>
								<p><?php echo $this->translate('Current installation is out of date.') ?></p> 
<?php 	if( $this->isRPMEligibleAppliance ) : ?>
<?php 		if( $this->RPMUpdateFileReadyToInstall ) : ?>
								<p><?php echo $this->translate('Update file is ready for installation. Click the button to initiate update installation.') ?></p>
								<form id="updateForm" method="post">
									<input id="buttonInitiateInstallation" type="button" name="buttonInitiateInstallation" value="Initiate update installation" />
									<input id="buttonCancelUpdateInstallation" type="button" name="buttonCancelUpdateInstallation" value="Cancel update installation and delete update package." />
									
								</form>
<?php 		else : ?>
								<form id="updateForm" method="post">
									<input id="buttonDownloadFromAtmail" type="button" name="downloadFromAtmail" value="Download <?php echo $this->availableVersion ?> package from Atmail servers" />
									<input type="file" id="updateFileInput" size="10" name="updateFile" style="filter: alpha(opacity=10); -moz-opacity: 0.3; opacity: 0.3; width:20px;" />
									<input id="buttonUploadLocal" type="button" name="uploadLocal" value="Upload local update package" style="cursor: pointer; display: inline-block; overflow: hidden; position: relative; left: -20px;" />
								</form>
<?php		endif; // if( $this->RPMUpdateFileReadyToInstall ) ?>
<?php 	else : ?>
								<p><?php echo $this->translate('You can update to the latest version') ?> <?php echo ' ' . $this->availableVersion ?> <?php echo $this->translate('by clicking the button below.') ?></p>
								<form id="updateForm" method="post">
									<input id="updateButton" type="submit" value="Update to <?php echo $this->availableVersion ?>">
								</form>
<?php	endif; // if( $this->isRPMEligibleAppliance ) ?>
						
							</td>
						</tr>
<?php endif; // if( $this->versionCurrentDBSchema == $this->availableVersion ) ?>
						<tr>
							<td colspan="2" style="padding:5px;" id="updateProcessInstructions">
								<?php
									if(isset($this->cliUpdateAvailable) && $this->cliUpdateAvailable
										&& isset($this->updatePage)
									)
									{
										echo $this->render($this->updatePage);
									}
								?>
							</td>
						</tr>
					</tbody>
				</table>
				
	</div>
</div>   


<script type="text/javascript">

<?php 	if( $this->isRPMEligibleAppliance ) : ?>

var updateProgressIntervalHandle
var updateProgressLastKBDownloaded = 0
var updateProgressLastKBDownloadedCount = 0
if( !(updateProgressIntervalHandle === undefined) || updateProgressIntervalHandle === null)
	clearInterval(updateProgressIntervalHandle)

function XHRuploadFile(file) 
{

	// create a new xhr object
	var xhr = new XMLHttpRequest();
	var upload = xhr.upload;
	
	upload.fileObj = file;
	upload.fileName = file.fileName;
	upload.fileSize = file.fileSize;
	upload.uploadStartTime = new Date().getTime();
	upload.currentProgress = 0;
	upload.startData = 0;

	// add listeners
	upload.addEventListener("progress", XHRProgress, false);
	upload.addEventListener("load", XHRUploadFinished, false);
	xhr.onreadystatechange = function()
	{
		if( this.readyState == 4 && this.status == 200 )
		{
			var responseJson = JSON.parse(this.responseText);
			$("#updateProcessInstructions").html("Upload complete.\n<br />\nInitiating update.\n<br />\nUploaded file has MD5 of " + responseJson.md5 )
		}
	}
	
	// Upload to the specified directory
	xhr.open("POST", "/mail/index.php/admin/update/uploadupdate?SessionID=" + document.cookie.match(/atmail6_admin=([^;]*)/)[1]);
	xhr.setRequestHeader("Cache-Control", "no-cache");
	xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
	xhr.setRequestHeader("X-File-Name", file.fileName ||file.name);
	xhr.setRequestHeader("X-File-Size", file.fileSize || file.size);
	xhr.setRequestHeader("Content-Type", "multipart/form-data");
	xhr.send(file);

}

function XHRProgress(e) 
{

	if( e.lengthComputable ) 
	{
		
		var percentage = Math.round((e.loaded * 100) / e.total);
		if( this.currentProgress != percentage ) 
		{

			if( e.loaded == e.total)
			{
			
				$("#updateProcessInstructions").html("Upload complete.\n<br />\nInitiating update.<br />\n")
				initiateUpdateInstallation()
				
			}
			else
				$("#updateProcessInstructions").html("Uploading update package " + percentage + "% complete.")
			
			this.currentProgress = percentage;
			
			/*
			var elapsed = new Date().getTime();
			var diffTime = elapsed - this.currentStart;
			if (diffTime >= opts.uploadRateRefreshTime) 
			{
				var diffData = event.loaded - this.startData;
				var speed = diffData / diffTime; // in KB/sec
				this.startData = event.loaded;
				this.currentStart = elapsed;
			}
			*/
		}
	}
}

function XHRUploadFinished(event, data) 
{ 
	
	
}

function getUpdateDownloadProgress()
{
	
	$.ajax({
		url: '<?php echo $this->moduleBaseUrl ?>/update/getupdatedownloadprogress',
		type: "POST",
		data: {'stamp' : Math.round((new Date()).getTime() / 1000)},
		dataType : "json",
		error : function(data) {  }, 
		success: function(data, text)
		{
			percentage = data.percentComplete
			//if download has stalled, then warn user
			if( updateProgressLastKBDownloadedCount++ > 10 && updateProgressLastKBDownloaded == data.downloadedKBytes )
			{
				
				$("#updateProcessInstructions").html("Download appears to have stalled on " + percentage + "% complete. Please wait, retry, or try the upload process instead.")
			
			}
			else
			{

				//download he not stalled, update milestone, reset counter and update UI
				updateProgressLastKBDownloadedCount = 0
				updateProgressLastKBDownloaded =  data.downloadedKBytes
				$("#updateProcessInstructions").html("Downloading update package " + percentage + "% complete.")

			}
			if( percentage == 100 )
			{

				clearInterval(updateProgressIntervalHandle)
				if( data.md5Pass == true)
				{
				
					$("#updateProcessInstructions").html("Downloading complete and verified as valid.\n<br />\nInitiating update process.<br />\n");
					initiateUpdateInstallation()
					
				}
				else
				{
					
					//download failed. dont change dom so user can decide on next course of action.
					$("#updateProcessInstructions").html("Downloading complete. Download verification failed. Please try again or try the Upload process instead.");

				}

			}

		}

	});

}

function cancelUpdateInstallation()
{
	
	$.ajax({
		url: '<?php echo $this->moduleBaseUrl ?>/update/cancelupdateinstallation',
		type: "POST",
		data: {},
		dataType : "json",
		error : function(data) { $("#update_screen").parent().parent().tabs('load',2); }, 
		success: function(data, text)
		{
			$("#updateProcessInstructions").html("Installation of update package canceled and update file package deleted.<br />")
			$("#update_screen").parent().parent().tabs('load',2);
			//initialize download progress interval
			
			//remove the buttons
			//$("#buttonInitiateInstallation").remove();
			//$("#buttonCancelUpdateInstallation").remove();
			
		}
	});
	
}

function initiateUpdateInstallation()
{
	
	//initialize download progress interval
	clearInterval(updateProgressIntervalHandle)
	//updateProgressIntervalHandle = setInterval( getUpdateInstallationProgress, 5000);
	//call to initiateupdateinstallation will not get result until installation is complete.
	$("#updateProcessInstructions").append("Initiating installation of update package, this will take a couple of minutes.\n<br />\n")
	$("#buttonInitiateInstallation").remove();
	$("#buttonCancelUpdateInstallation").remove();
	$.ajax({
		url: '<?php echo $this->moduleBaseUrl ?>/update/initiateupdateinstallation',
		type: "POST",
		data: {},
		dataType : "json",
		error : function(data) {  }, 
		success: function(data, text)
		{
			$("#updateProcessInstructions").append("Installation of update package complete!\n<br />\n")
			$("#updateProcessInstructions").append(data.logDeltaLines)
			
		}
	});
	
}

function getUpdateInstallationProgress()
{
	
	var ts = Math.round((new Date()).getTime() / 1000);
	$.ajax({
		url: '<?php echo $this->moduleBaseUrl ?>/update/getupdateinstallationprogress',
		type: "POST",
		data: {"stamp" : ts },
		dataType : "json",
		error : function(data) {  }, 
		success: function(data, text)
		{
			$("#updateProcessInstructions").append(data.logDeltaLines)
			$("#updateProcessInstructions").scrollTo(10000);
			//TODO: detect complecion identifief so we can clearInterval and also update UI with success
		}
	});
	
}
<?php endif //if( $this->isRPMEligibleAppliance ) ?>

$( function()
{
    
<?php 	if( $this->isRPMEligibleAppliance ) : ?>

	$("#buttonDownloadFromAtmail").bind("click", function() 
	{ 
		$.ajax({
			url: '<?php echo $this->moduleBaseUrl ?>/update/initiateupdatedownload',
			type: "POST",
			data: {'stamp' : Math.round((new Date()).getTime() / 1000)},
			dataType : "json",
			error : function(data)
			{
					
			}, 
			success: function(data, text)
			{
				$("#updateProcessInstructions").html("Initiating download of update package.")
				//initialize download progress interval
				updateProgressLastKBDownloadedCount = 0
				updateProgressLastKBDownloaded = 0
				updateProgressIntervalHandle = setInterval( getUpdateDownloadProgress, 1000);
			}
		});
	})

	//Hitting the upload button does not submit the form but just initiates the upload proces
	$("#buttonUploadLocal").bind("click", function() { $("#updateFileInput").trigger("click"); return false; })
	
	$("#updateFileInput").bind("change", function() { XHRuploadFile(this.files[0]); return false; })
	
	$("#buttonInitiateInstallation").bind("click", function() { initiateUpdateInstallation(); return false; })
	
	$("#buttonCancelUpdateInstallation").bind("click", function() { cancelUpdateInstallation(); return false; })

<?php endif //if( $this->isRPMEligibleAppliance ) ?>
	
// bind to the form's submit event and cancel legacy submit 
    $('#updateForm').submit(function()
	{

<?php if( isset($this->config->global['demo']) &&  $this->config->global['demo'] == 1 ) 
		echo "$.php('" . $this->moduleBaseUrl . "/update/doversionupdate', $(this).serializeArray() ); return false"; ?>	

<?php 	if( $this->isRPMEligibleAppliance ) : ?>
			return false;
<?php 	elseif( $this->isAppliance && !$this->isRPMEligibleAppliance ) : ?>

		if (!confirm("The update will overwrite any customizations made to code, html templates, images etc. Please backup any modifications before proceeding. Click OK when ready to proceed with the update."))
			return false;

		$("#dialog").dialog({  
			autoOpen: false,  
			height: 250, 
			minHeight: 250,  
			minWidth: 350, 
			modal: true,  
			bgiframe: true, 
			title: "Download and upgrading Atmail",
			width: 350 
		});
		
		$('#dialog').html('<strong>Downloading Atmail version</strong><br />The server is automatically downloading and installing the latest version. The process can take between <strong>2-15</strong> minutes depending on the size of the download and available bandwidth.<br/><br /><div id="countdown"></div>');
		$('#countdown').countdown( {until: +600, layout: 'Approximate time left %M%n %l%M, %S%n %l%S.'} )
		$("#dialog").dialog('open')

		$.ajax(
			{
				url: '<?php echo $this->moduleBaseUrl ?>/update/doversionupdate',
				type: "POST",
				data: {'stamp' : Math.round((new Date()).getTime() / 1000)},
				dataType : "json",
				error : function(data) { }
			}
		);

<?php 	else : ?>
		$("#dialog").dialog({ 
			autoOpen: false,  
			height: 350, 
			minHeight: 350,  
			minWidth: 400, 
			modal: true,  
			bgiframe: true, 
			width: 400,
			title: "Update Atmail",
			close: function(event, ui) { clearInterval($('#dialog').data('intervalHandle')); $('#dialog').dialog('destroy'); },
			resize: function(event, ui) { ui.element.find('#details').css({height: (ui.element.height() - 170) + 'px' }); }
		});
		var ts = Math.round((new Date()).getTime() / 1000);
		$('#dialog').html('The server is upgrading the software and database to the new version. The process may take a long time depending on the size of your userbase.<br/><br/><div id="details" style="height: 221px; overflow:auto"></div>');
		$("#dialog").dialog('open');
		$("#dialog").data('intervalHandle', 
			setInterval(function () { $('#dialog #details').load('<?php echo $this->moduleBaseUrl ?>/update/updatestatus/stamp/' + ts); $('#dialog #details').scrollTo(10000); }, 1000)
		);

		$.ajax({
			url: '<?php echo $this->moduleBaseUrl ?>/update/doversionupdate',
			type: "POST",
			data: {'stamp' : ts},
			dataType : "json",
			success: function(data, text)
			{
				if(data.failed)
				{
					$('#dialog').dialog('close');
				}
				return php.success(data, text);
			},
			error : function(data) {  }
		})
<?php 	endif ?>
		return false
	})

});

</script>  
