var osFeatureLevel = 5; // 5: TLS 1.2 - iOS 5, macOS 10.9
var dashboardWidget = false;
var usesClicks = false;
var logLevel = 0;
var hadSuccess = false;
var updateQueue;
var navigator = false;
var manualSignIn = {};
var extraInformation = {};
var xmlHTTPRequests = [];

function updateDeliveries (settings) {

	if (updateQueue == null) {
		updateQueue = new Queue();
		updateQueue.delay = 1000;
	}
	for (var x = 0; x < settings.length; x++) {
		var delivery = new Delivery(settings[x]);
		updateQueue.add(delivery);
		settings[x] = false;
	}
	updateQueue.update();
	return true;

}

function saveItems () {

	var results = {};
	results.uuid = this.id;
	results.hash = this.hash;
	results.status = this.success;
	results.interval = this.interval;
	results.url = this.url;
	if (this.mobileURL) results.mobileURL = this.mobileURL;
	if (this.tap) results.tap = this.tap;

	results.items = [];
	for (var x = 0; x < this.items.length; x++) {
		var item = this.items[x];
		var result = {};
		result.itemName = cleanText(item.title);
		result.shippedText = cleanText(item.shipText);
		result.shippedDateString = item.shipDate || '';
		result.shippedExtra = cleanText(item.shipExtra);
		result.deliveredText = cleanText(item.deliverText);
		result.deliveredDateString = item.deliverDate || '';
		result.deliveredExtra = cleanText(item.deliverExtra);
		result.statusDateString = item.statusDate || '';
		result.dateString = item.date || '';
		result.location = cleanText(item.details.mapLocation);
		result.icon = item.icon || '';
		result.shippedBold = item.shipBold;
		result.deliveredBold = item.deliverBold;
		result.url = item.url;
		if (item.details.route) {
			var route = item.details.route;
			for (var y = 0; y < route.length; y++) {
				var location = cleanText(route[y]);
				location = location.replace(/;/g,',');
				route[y] = location;	
			}
			result.route = route.join(';');
		}
		results.items[x] = result;
		logMessage(1,item.title+': '+this.from+' '+this.success+' '+this.interval+'m '+item.icon);
	}

	updateDelivery(results);

	if (this.tap == 'signin') {
		saveUserAgent(this.from,userAgentForService(this));
	}

	if (this.success > 0) hadSuccess = true;
	if (!updateQueue.busy()) {
		finalStatus(hadSuccess);
		xmlHTTPRequests = [];
	}

}

function showMessage (string) {
	var results = {};
	results.uuid = this.id;
	results.hash = this.hash;
	results.updating = true;
	results.message = string;
	updateDelivery(results);
}

function cleanText (string) {
	return (string) ? trim(removeHtmlEntities(stripHTML(string))) : '';
}

function convertDate (date) {
	var result = '';
	if (date) {
		result += date.getFullYear()+'-';
		var month = date.getMonth()+1;
		if (month < 10) month = '0'+month;
		result += month+'-';
		var day = date.getDate();
		if (day < 10) day = '0'+day;
		result += day;
	}
	return result;
}

// XMLHttpRequest

function userAgentForService (service) {
	if (service.desktopUserAgent) return 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1 Safari/605.1.15';
	if (service.mobileUserAgent) return 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1';
	return false;
}

function XMLHttpRequest () {

	this.readyState = 0;
	this.hash = null;
	this.method = null;
	this.url = null;
	this.onload = null;
	this.headers = {};

	this.open = function(method,url) {
		this.method = method; // This is currently ignored
		this.url = url;
	}

	this.setRequestHeader = function (header,value) {
		switch (header) {
			case 'Cache-Control':
			case 'Content-type':
			case 'Content-length':
			case 'Connection':
				break;
			default:
				this.headers[header] = value;
				break;
		}
	}

	this.send = function(postData) {
		var options = {};
		options.headers = this.headers;
		options.cache = (this.noCache) ? false : true;
		var service = (this.args.service) ? this.args.service : this.delivery;
		if (service) {
			var userAgent = userAgentForService(service);
			if (userAgent) options.userAgent = userAgent;
			if (service.encoding) options.encoding = service.encoding;
			if (service.postType) options.contentType = service.postType;
		}
		var requestID = xmlHTTPRequests.length;
		xmlHTTPRequests[requestID] = this;
		this.readyState = 2;
		requestURL(this.url,postData,options,requestID);
	}

	this.response = function (status,connectionDown) {
		if (this.onload == null) {
			this.readyState = 4;
			this.delivery.connectFailed(connectionDown);
		} else if (status == 0) {
			if (this.args.fallbackText) {
				logMessage(1,'Using fallback');
				this.status = this.args.fallbackStatus;
				this.responseText = this.args.fallbackText;
				this.readyState = 4;
				if (this.args) this.args.site += '-Fallback';
				(this.onload)();				
			} else {
				this.readyState = 4;
				this.delivery.connectFailed(connectionDown);
			}
		} else {
			this.status = status;
			this.readyState = 4;
			(this.onload)();
		}	
	}

}

function xmlHTTPResponse (requestID,responseText,status,connectionDown) {

	var request = xmlHTTPRequests[requestID];
	xmlHTTPRequests[requestID] = null;

	if (request) {
		request.responseText = responseText;
		request.response(status,connectionDown);
		var req = request.delivery.req;
		var index = req.indexOf(request);
		if (index >= 0) req.splice(index,1);
	}

}
