// URL to the proxy without www
var proxy_url_partial = 'http://hellofax.com/upload_services.php';
// URL to the proxy with www
var proxy_url_www = 'http://www.hellofax.com/upload_services.php';
/*
 * URL to the proxy with or without www (can be left empty, 
 * depending on whether the user visits your website using 
 * the URL without the www part, one of the two proxies 
 * above is selected upon page load
 */
var proxy_url = 'http://www.heavyjumprope.com/hellofax/upload_services.php';
// The URL into which the documents should be uploaded (the conversion server)
var uploader_url = 'http://173.203.228.146/stupidfax/index.php';
// Reference to the documents browse button component
var ajaxUpload = null;
// Flag which marks whether there is an upload and conversion running or not
var upload_done = true;
// Reference to the progressbar component
var progressbar = null;
// Progressbar value (between 0 and 1, -1 if no upload process has been started)
var current_progress = -1;
// Reference to the actual DOM object of the documents browse button
var browse_button = null;

jQuery(document).ready(function() {
	/*
	 * Detect whether the user has visited your website using www 
	 * before the domain name and pick the correct proxy to avoid
	 * cross-domain XHR request problems
	 */
	var url = Ext.util.Format.trim(parent.document.URL).toLowerCase();
	var index = url.indexOf("www");
	if(index != -1 && index < 12) proxy_url = proxy_url_www;
	else proxy_url = proxy_url_partial;
});

/*
 * Function initializes the upload button
 */

function prepare_upload_button()
{
	browse_button = $('#document_browse');
	var interval;
	
	ajaxUpload = new AjaxUpload(browse_button, {
		action: uploader_url,
		uploadId: jQuery('#upload_id').val(),
		name: 'fax_document',
		onChange : function(file, ext) {
			if(upload_done) return begin_upload(this, browse_button, ext);
			return false;
		},
		onSubmit : function(file, ext) {
			if(upload_done) return begin_upload(this, browse_button, ext);
			return true;
		},
		onComplete: function(file, response) {
			// Upon iframe load, set the progress to -1, but do not declare the uploading as ended
			current_progress = -1;
		}
	});
}

jQuery(document).ready(function() {
	jQuery('#upload_cancel_button').hide();
	
	prepare_upload_button();
	
	jQuery('#upload_cancel_button').click(function() {
		/*
		 * User decides to cancel upload
		 * 1. Progressbar is removed
		 * 2. Progress is set to -1 and upload and conversion are set to finished
		 * 3. Iframe for the upload is told to abort the loading of the document
		 * 4. Other progress elements are removed
		 */
		progressbar.destroy();
		progressbar = null;
		current_progress = -1;
		document.getElementById(jQuery('#upload_id').val()).src = '';
		upload_done = true;
		jQuery('#upload_cancel_button').hide();
		jQuery('#interactive_area').html('');
	});
});

function begin_upload(upload_cmp, browse_button, ext)
{
	// Allow only the following file extensions
	if (ext && /^(doc|docx|docm|rtf|txt|htm|html|wpd|wps|wri|xls|xlsx|ppt|pptm|pot|potm|pps|ppsm|pptx|potx|ppsx|vsd|vss|vst|vdx|vsx|vtx|pub|ps|mdi|jpg|jpeg|png|bmp|tif|tiff|gif|pdf)$/.test(ext))
	{
		browse_button.hide();
		// Post this as well together with the uploaded file
		upload_cmp.setData({ 'APC_UPLOAD_PROGRESS' : upload_cmp._settings.uploadId });
		upload_done = false;
		check_upload_progress(upload_cmp._settings.uploadId);
		return true;
	}
	else
	{
		// Do not start upload
		jQuery('#interactive_area').html('<p>The file you selected is not supported.</p>');
		setTimeout('new_upload()', 3000);
		return false;
	}
}

/*
 * This function sends regular XHR upload status requests
 * until the upload finishes and updates the page accordingly
 */
function check_upload_progress(upload_id)
{
	// If the upload has started and no progress bar is visible yet, make it visible
	if(progressbar == null && !upload_done)
	{
		progressbar = new Ext.ProgressBar({
			id: 'progress_bar',
			width: 350,
			renderTo: 'progress_bar'
		});
		current_progress = -1;
		// Update the upload status description accordingly
		jQuery('#interactive_area').html('<p>Starting upload...</p>');
		jQuery('#upload_cancel_button').show();
	}
	
	// Send XHR requests to the proxy server to get information about the upload and conversion
	Ext.Ajax.request({
		url: proxy_url,
		method: 'GET',
		params: { action: 'progress', id: upload_id },
		success: function(result, request) {
			// Number of pages of the submitted document (returned after conversion completes)
			var page_count = 0;
			// Status code of the conversion (OK if conversion successful)
			var status_code = '';
			// If there are conversion errors, this is set to true (initialized as true by default)
			var notifications = true;
			/*
			 * Since XHR requests are asynchronuous, another request which was sent later than this one might
			 * have set the upload and conversion status to finished. If the upload was marked as finished
			 * between the time this request was sent and the response was received, do not proceed
			 * with processing the response and updating the page 
			 */
			if(!upload_done)
			{
				var jsonData = Ext.util.JSON.decode(result.responseText);
				// If the conversion finishes, parse the status code and page count
				if(jsonData.result != undefined)
				{
					status_code = jsonData.result.status_code;
					page_count = parseInt(jsonData.result.page_count);
				}
				// If upload progress data is available, process them and update the page
				if(jsonData.status == undefined)
				{
					// Total size of the file (formatted)
					var total_size = jsonData.total_size;
					// Current upload progress (formatted)
					var current_upload = jsonData.current_upload;
					var filename = jsonData.filename;
					// Progress value for the progress bar (value between 0 and 1)
					var progress = jsonData.progress;
					// Transfer rate (formatted)
					var rate = jsonData.rate;
					/*
					 * The upload stage lasts until the transferred size smaller and 
					 * until we have a conversion result (whichever happens first)
					 */
					if(parseInt(jsonData.total) > parseInt(jsonData.current) && !(status_code != undefined && status_code != '' && status_code.length > 1))
					{
						// This check prevents the side effects of asynchronuous responses producing unstable progress status reports
						if(progress > current_progress)
						{
							current_progress = progress;
							progressbar.updateProgress(progress, parseInt(progress*100)+'%');
							jQuery('#interactive_area').html('<p>Uploading ' + filename + ': ' + current_upload + ' of ' + total_size + ' (' + rate + ')</p>');
						}
					}
					else if(jsonData.error != undefined && jsonData.error == 'bad_filesize')
					{
						// Check if the uploaded file is too big
						upload_done = true;
						progressbar.destroy();
						progressbar = null;
						current_progress = -1;
						jQuery('#upload_cancel_button').hide();
						document.getElementById(jQuery('#upload_id').val()).src = '';
						if(notifications) jQuery('#interactive_area').html('<p>The uploaded file is larger than the allowed file limit.</p>');
					}
					else
					{
						// Once upload has finished, let the user know that the conversion is taking place
						progressbar.wait();
						jQuery('#interactive_area').html('<p>Upload finished! Converting and counting pages. Please wait...</p>');
						
						// As soon as the conversion results are ready, either display error or success messages
						if(status_code != undefined && status_code != '' && status_code.length > 1)
						{
							var message = '';
							if(status_code == 'ok')
							{
								/*
								 * If no conversion errors occurred add the document to the uploaded documents table, 
								 * otherwise handle each error type separately
								 */
								if(page_count > 0)
								{
									// Add input hidden field in the DOM identifiying the successful upload and conversion
									jQuery('#senditnow').append('<input type="hidden" name="uploads[]" value="' + jQuery('#upload_id').val() + '" />');
									// Add it to the list of the uploaded documents
									jQuery('#uploader').children('tbody').append('<tr id="doc_' + jQuery('#upload_id').val() + '"><td><img src="images/ok.png" width="20" alt="" /></td>'
											+ '<td class="document">' + filename + '</td><td class="page-count">' + page_count + ' page(s)</td><td class="remove"><a onclick="removeFile(\'' + jQuery('#upload_id').val() + '\')">'
											+ '<img src="images/remove.png" width="16" align="left" style="margin-right:10px;" />Remove</a></td></tr>');
									notifications = false;
									jQuery('#interactive_area').html('');
									// Show the browse button
									if(browse_button != null) browse_button.show();
								}
								else
								{
									message = 'An unknown error has occurred';
								}
							}
							else if(status_code == 'e4')
							{
								message = 'Conversion failed';
							}
							else if(status_code == 'e0')
							{
								message = 'Conversion failed - unknown error';
							}
							else if(status_code == 'e1')
							{
								message = 'Conversion failed - wrong parameter count';
							}
							else if(status_code == 'e2')
							{
								message = 'Conversion failed - the document to convert was not found';
							}
							else if(status_code == 'e3')
							{
								message = 'Conversion failed - a document without extension was submitted';
							}
							else if(status_code == 'e5')
							{
								message = 'Conversion failed - unsupported document type';
							}
							else if(status_code == 'e6')
							{
								message = 'Upload failed';
							}
							else if(status_code == 'e7')
							{
								message = 'Invalid request';
							}
							else if(status_code == 'e8')
							{
								message = 'Configuration error';
							}
							else if(status_code == 'e9')
							{
								message = 'Error registering uploaded documents on the server';
							}
							upload_done = true;
							progressbar.destroy();
							jQuery('#upload_cancel_button').hide();
							progressbar = null;
							current_progress = -1;
							if(notifications) jQuery('#interactive_area').html('<p>' + message + '</p>');
						}
					}
				}
				else if(jsonData.status == 'bad_configuration')
				{
					// Check if the uploaded file is too big
					upload_done = true;
					progressbar.destroy();
					progressbar = null;
					current_progress = -1;
					jQuery('#interactive_area').html('<p>Progressbar cannot be displayed.</p>');
					jQuery('#upload_cancel_button').hide();
				}
			}
		},
		failure: function() {
		}
	});
	/*
	 * If upload and conversion have finished, show the browse for documents upload button, 
	 * otherwise check in 500 ms for the upload status again
	 */
	if(!upload_done) setTimeout('check_upload_progress("' + upload_id + '")', 500);
	else new_upload();
}

/*
 * This function handles the processes of generating a new
 * browse for documents button which include getting a new 
 * upload id from the conversion server and laying out the
 * button itself
 */
function new_upload()
{
	Ext.Ajax.request({
		url: proxy_url,
		method: 'GET',
		params: { action: 'new_upload_id', old_id : jQuery('#upload_id').val() },
		success: function(result, request) {
			var jsonData = Ext.util.JSON.decode(result.responseText);
			if(jsonData.status == undefined)
			{
				jQuery('#upload_id').val(jsonData.upload_id);
				jQuery('#interactive_area').html('<div id="document_browse" class="browse_button">Browse Documents</div>');
				prepare_upload_button();
			}
			else
			{
				jQuery('#interactive_area').html('<p>An unknown error has occurred.</p>');
			}
		},
		failure: function() {
			jQuery('#interactive_area').html('<p>Failed to generate new upload id. <a onclick="new_upload();>Retry here</a></p>');
		}
	});
}

/*
 * This function removes the upload from the DOM
 * and makes a XHR request to remove it from the
 * database too
 */
function removeFile(upload_id)
{	
	Ext.Ajax.request({
		url: proxy_url + '?' + Ext.urlEncode( { action: 'remove_upload', id: upload_id } ),
		method: 'GET',
		success: function(result, request) {
			jQuery('input[type="hidden"][value="' + upload_id + '"]').remove();
			Ext.get('doc_' + upload_id).remove();
		},
		failure: function() {
		}
	});
}