﻿function popup(text) {
	$("#alert").text(text).dialog({
		buttons: {
			"OK": function () { $(this).dialog("close"); }
		},
		draggable: false,
		modal: true,
		resizable: false,
		title: "Alert",
		open: function () {
			$("body").css("overflow", "hidden");
		},
		close: function () {
			$("body").css("overflow", "auto");
		}
	}).dialog('open')
}

function deny(text) {
	alert(text);
	return (false);
}

function json(options) {
	$.ajax({
		type: "POST",
		url: options.url,
		data: options.data,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: options.success,
		error: options.error
	});
}

function jsonClassic(options) {
	$.ajax({
		type: "POST",
		url: options.url,
		data: options.data,
		dataType: "json",
		contentType: "application/x-www-form-urlencoded",
		success: options.success,
		error: options.error
	});
}

function overlay() {
	$("#overlay").toggle();
}

function is_live() {
	return location.href.indexOf("dipintosales.co.uk") != -1;
}

function clear_primary() {
	window.open("setprimary.asp?dir=" + $("#hfDir").val() + "&folder=" + $("#hfFolder").val(), "Primary", "width=200px,height=200px");
}

//
//	Automatically opens the dispatch note when a Work Order has been created
//

function openDispatchNote(titleName, workOrderID) {
	window.open("/_print/" + titleName + "/" + workOrderID + "/Work Order " + workOrderID + ".pdf");
}

/* Uploaders */

var queued_files;

function cancelUpload() {
	window.location.href = "folderftp.asp?reset=yes";
}

/*
Process an asynchronous request with a self-updating progress bar - requires various div tags to be on the calling page:
<div id="process"></div>			Where the process is loaded into
<div id="progress">					Progress information wrapper
<div id="progress_bar"></div>		The actual progress bar
<div id="progress_pc"></div>		Textual display of percent completion
<div id="progress_output"></div>	Displays any output from the process operation
<div id="progress_continue"></div>	Displays a link to continue to the next screen, hidden to start with, shown at 100%
</div>
*/

function process(asyncProcessURL, servicesURL, guid, callback) {

	//
	//	Show the progress tags, initialise the progress bar, and start updating it
	//

	$("#progress").show();
	$("#progress_bar").progressbar({ value: 0 });
	updateProgress(servicesURL, guid, callback);

	//
	//	Hide the process div and then load the ImageCheck function into it -
	//	this is run asynchronously so we don't care what its output is
	//

	$("#process").hide().load(asyncProcessURL + "&guid=" + guid);
}

var pc = 0;
var calls = 0;

function updateProgress(servicesURL, guid, callback) {

	//
	//	Get the current progress of the image process from the CachePercent webservice
	//

	json({
		url: servicesURL + "CachePercent",
		data: "{ 'guid': '" + guid + "' }",
		success: function (msg) {

			//
			//	Set the progress bar value and output % text 
			//

			$("#progress_bar").progressbar("value", msg.d);
			$("#progress_pc").text(msg.d + "%");

			//
			//	Remember the current percent, and the number of times it has been called
			//

			if (pc == msg.d) {
				calls++;
			}
			else {
				calls = 0;
			}

			//
			//	If progress is less than 100, set a timer to recurse this function
			//

			if (msg.d < 100) {

				if (calls > 500) {
					$("#progress_output").text("This is taking too long, cancelling process bar refresh.  Please contact your system administrator.");
				}
				else {
					var t = setTimeout(function () { updateProgress(servicesURL, guid, callback); }, 350);
				}
			}

			//
			//	If progress is 100, the process is complete, so get the output text
			//	from the sister webservice, CacheOutput
			//

			else if (msg.d == 100) {
				json({
					url: servicesURL + "CacheOutput",
					data: "{ 'guid': '" + guid + "' }",
					success: function (msg) {

						//
						//	The output needs decoding because it is returned as UTF-8 encoded
						//

						$("#progress_output").html(Url.decode(msg.d));

						//
						//	Call callback function if it has been set
						//

						if (callback != null) {
							callback.call();
						}
					},
					error: function (e) { // unable to get the CacheOutput

						//
						//	Output simple error message
						//

						$("#progress_output").text("Unable to fetch completion message");
					}
				});
				$("#progress_continue").show();
			}
		},
		error: function (e) { // unable to get the CachePercent

			//
			//	Output simple error message
			//

			$("#progress_output").text("Unable to fetch progress bar percent complete");
		}
	});
}

//
//	Keep the ASP Classic session from timing out during a long process
//

function keepAlive() {
	$("#keep_alive").load("keep_alive.asp");
	var to = setTimeout(function () { keepAlive() }, 60000);
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

	// public method for url encoding
	encode: function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode: function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode: function (string) {
		string = string.replace(/\r\n/g, "\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if ((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode: function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while (i < utftext.length) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if ((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i + 1);
				c3 = utftext.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}