var current_orient = "";

function exto_monitor_orientation()
{
	process_start("orientation", exto_monitor_orientation_thread, 100);
}

function exto_monitor_orientation_thread()
{
	var new_orient;
	new_orient = (window.innerWidth > window.innerHeight) ? "landscape" : "portrait";
	if (new_orient != current_orient) {
		document.body.setAttribute("orient", new_orient);
		current_orient = new_orient;
	}
}

function stop_event(e)
{
    e = e || window.event;
    if (e.stopPropagation) {
            e.stopPropagation();
    } else {
            e.cancelBubble = true;
    }
}


function is_offline()
{
	return document.URL.indexOf('file:') >= 0;
}
function is_iphone()
{
	return navigator.userAgent.indexOf("iPhone") >= 0 ? true : false;
}

function csv_to_lines(x)
{
	var lines = x.split("\n");
	var cur_line = "", real_lines = [];
	for (var i = 0; i < lines.length; i++) {
		cur_line += lines[i];
		if (count_occurances(cur_line, '"') % 2 == 0) {
			if (cur_line.length > 0) {
				real_lines[real_lines.length] = cur_line;
			}
			cur_line = "";
		}
	}
	return real_lines;
}

function csv_parse_line(line) {
	var fields = line.split(",");
	var cur_field = "", real_fields = [];
	for (var i = 0; i < fields.length; i++) {
		cur_field += fields[i];
		if (count_occurances(cur_field, '"') % 2 == 0) {
			real_fields[real_fields.length] = unquote(cur_field);
			cur_field = "";
		}
	}
	return real_fields;
}

function csv_read_headers(x) {
	var h = new Object();
	var f = csv_parse_line(x);
	for (var i = 0; i < f.length; i++) {
		h[i] = f[i];
	}
	return h;
}

function csv_parse_line_headers(line, headers)
{
	var f = csv_parse_line(line);
	var obj = new Object();
	for (var i = 0; i < f.length; i++) {
		obj[headers[i]] = f[i];
	}
	return obj;
}

function assert(n)
{
	var mess = arguments[1] || "" + n;
	if (typeof n == "boolean") {
		if (!n) {
			console.log(n + ": " + mess);
			return false;
		}
		return true;
	} else if (typeof n == 'string') {
		if (!eval(n)) {
			alert("FAILED: " + mess);
			console.log(n + ": " + mess);
			return false;
		}
		return true;
	}
}

//assert(unquote('x') == 'x');
//assert(unquote('"x"') == 'x');
//assert(unquote('""') == '');
//assert(unquote('";akjshdf;lkjasdf"""') == ';akjshdf;lkjasdf""');
Array.prototype.swap = function(a, b)
{
	var tmp=this[a];
	this[a]=this[b];
	this[b]=tmp;
}
function qsort_partition(a, begin, end, pivot)
{
	var piv = a[pivot];
	a.swap(pivot, end-1);
	var store=begin;
	var ix;
	for(ix=begin; ix<end-1; ++ix) {
		if(a[ix].compare(piv) <= 0) {
			a.swap(store, ix);
			++store;
		}
	}
	a.swap(end-1, store);
	return store;
}

function qsort(a, begin, end)
{
	if (end-1 > begin) {
		var pivot=begin+Math.floor(Math.random()*(end-begin));
		pivot=qsort_partition(a, begin, end, pivot);
		qsort(a, begin, pivot);
		qsort(a, pivot+1, end);
	}
}

var processes = {};
var process_monitor_to = null;

function Process(name, func, interval, state)
{
	this.name = name;
	this.func = func;
	this.lastRun = null;
	if (typeof state == "object") {
		this.state = state;
	} else {
		this.state = new Object();
	}
	this.interval = parseInt(interval);
}

Process.prototype = {
	run: function () {
		this.func(this.state);
		this.lastRun = new Date();
	}
};

function process_start(name, func, interval, state)
{
	processes[name] = new Process(name, func, interval, state);
	process_monitor();
}

function process_stop(name)
{
	delete processes[name]
}

function process_stop_all()
{
	for (var p in processes) {
		delete processes[p];
	}
}
function process_monitor()
{
	if (process_monitor_to) {
		clearTimeout(process_monitor_to);
		process_monitor_to = setTimeout(process_monitor, 5000);
	}
	var min_interval = 1000;
	for ( var k in processes ) {
		var proc = processes[k];
		if (proc == null) continue;
		min_interval = Math.min(min_interval, proc.interval);
		if (typeof proc.lastRun != "date") {
			proc.run();
		} else {
			var now = new Date().getTime();
			if (proc.lastRun.getTime() + proc.interval < now) {
				proc.run();
			}
		}

	}
	if (process_monitor_to) {
		clearTimeout(process_monitor_to);
	}
	process_monitor_to = setTimeout(process_monitor, min_interval);
}

function highlight(text, match)
{
	if (match == null || match == "") return text;
	pat = str_replace('\\','\\\\',match);
	var pat = new RegExp('('+pat+')', 'gi');
	return text.replace(pat,"<span class=\"highlight\">$1</span>");
}

function LocalBase(data)
{
	if (typeof data != "object" && data == null) {
		data = {};
	}
	this.db = data;
	this.dbi = {};
	this.changed = false;
	this.maxID = 0;
	for (var k in data) {
		if (this.maxID = 0) this.maxID = k; else this.maxID = Math.max(k,this.maxID);
		this.dbi[data[k]] = k;
	}
}

LocalBase.unserialize = function (s) {
	s = s.split("\n");
	var data = {};
	for (var i = 0; i < s.length; i++) {
		var pair = s[i].split(":",2);
		data[pair[0]] = data[pair[1]];
	}
	return new LocalBase(data);
};

LocalBase.prototype = {
	serialize: function () {
		var s = "";
		for (var k in this.db) {
			s = s + k + ":" + str_replace("\n","\\n",this.data[k]) + "\n";
		}
		return s;
	},
	contains: function (s) {
		 return (typeof this.dbi[s] != "undefined");
	},
	insert: function (s) {
		if (this.contains(s)) return this.dbi[s];
		var id = ++this.maxID;
		this.db[id] = s;
		this.dbi[s] = id;
		this.changed = true;
	},
	remove: function (s) {
		if (!this.contains(s)) return false;
		var id = this.dbi[s];
		delete this.dbi[s];
		delete this.db[id];
		this.changed = true;
		return true;
	}
};

process_monitor();

/*
 * Page stuff
 */
var exto_page = null;
var exto_prev_page = null;
var exto_page_home = null;

function page_go(page)
{
	if (exto_page_home == null) exto_page_home = page;
	if (page == null) return;
	if (page == exto_page) return;
	if (exto_page) {
		$("#" + exto_page).slideUp("fast");
	}
	$("#" + page).slideDown("fast");
	exto_prev_page = exto_page;
	exto_page = page;
	setTimeout(scrollTo, 0, 0, 1);
}

function page_go_home()
{
	page_go(exto_page_home);
}

function page_back()
{
	if (exto_prev_page != null) {
		page_go(exto_prev_page);
	} else {
		page_go(exto_page_home);
	}
	exto_prev_page = null;
}

function page_set_home(page)
{
	exto_page_home = page;
}
