// Register Event Listeners
var IE = document.all ? true : false;
if (IE) {
	window.onclick = click;
	//window.onkeydown = keydown;
} else {
	window.addEventListener('click', click, true);
	//window.addEventListener('keydown', keydown, true);
}
// For some reason Firefox doesn't handle return false from the keydown function when using addEventListener
window.onkeydown = keydown;

/** Field ************************************************************* **/
/* 
 * The field functions assume the following conventions:
 * Div ID: type + "_" + id
 * Edit Div ID: type + "_" + id + "_edit"
 * Field ID: type + "_" + id + "_field"
 */

// Variables
var field_type;
var field_id;

// Open Field
function openField(type, id) {
	// Hide / Show
	$(type + "_" + id).hide();
	$(type + "_" + id + "_edit").show();
	
	// Focus & Select
	$(type + "_" + id + "_field").focus();
	if ($(type + "_" + id + "_field").tagName != "SELECT") {
		$(type + "_" + id + "_field").select();
	}
	
	field_type = type;
	field_id = id;
}

// Save Field
function saveField(type, id, dbTable) {
	// Get / Update Stuff
	value = $(type + "_" + id + "_field").value; 
	$(type + "_" + id).innerHTML = value;
	if (typeof(dbTable) == "undefined") {
		dbTable = DBTABLE	
	}
	new Ajax.Request('index.php?ajaxReq=saveField&dbTable=' + dbTable + '&type=' + type + '&value=' + escape(value) + '&id=' + id, { method:'get' });
	
	// Call Callback Function Of Standard Name "saveFieldCallback"
	if (window.saveFieldCallback) {
		saveFieldCallback(type, id);
	}
	
	// Hide / Show
	$(type + "_" + id + "_edit").hide();
	$(type + "_" + id).show();
	
	// This is needed or some elements may not be hidden/shown
	// Creates an issue with invoices not saving field values
	//document.getElementsByTagName("body").item(0).innerHTML += "";
	var div = document.createElement("div");
	div.style.display = "none";
	document.getElementsByTagName("body").item(0).appendChild(div);
}

/** Filter ************************************************************ **/
// Open Filter
function openFilter(filter) {
	// Hide / Show
	$(filter).hide();
	$(filter + "_filter").show();
	
	// Focus
	document.getElementsByName(filter).item(0).focus();
}

// Apply Filter
function applyFilter(filter, value) {
	// Get URL
	var l = window.location.href;
	if (!window.location.search) l += "?";
	else l += "&";
	
	// Remove Any Old Instance Of filter
	l = l.replace(new RegExp(filter + "=[^$]*"), "");
	l = l.replace("&&", "&");
	
	// Load New Page
	window.location.assign(l + filter + "=" + value);
}

// Close Filter
function closeFilter(filter) {
	$(filter + "_filter").hide();
	$(filter).show();
}

/** Overlay *********************************************************** **/
// Open Overlay
function openOverlay(overlay, width, height, id) {
	// Show Underlay
	// The top margins used in this function probably only work in Firefox, should use something from getPageSize()
	$('underlay').style.height = getPageSize()[1] + 'px';
	$('loader').style.marginTop = (window.innerHeight / 2 - 30 + window.scrollY) + 'px';	
	$('underlay').show();

	// Load Overlay
	new Ajax.Request('index.php?ajaxReq=loadOverlay&dbTable=' + DBTABLE + '&overlay=' + overlay + '&id=' + id, {
		method:'get',
		onSuccess: function(t){
			var r = t.responseText || "";
			
			// Show Overlay
			$('overlay').setStyle({
				width: width + 'px',
				height: height + 'px',
				marginTop: (window.innerHeight / 2 - (height / 2) + window.scrollY) + 'px'
			});
			$('overlay').innerHTML = r;	
			$('overlay').show();
		}
	});
}

// Close Overlay
function closeOverlay() {
	$('underlay').hide();
	$('overlay').hide();
}

/** Calendar Stuff **************************************************** **/
// Save Date Field
function saveDateField(date, id) {
	// Call Callback Function Of Standard Name "openNextField"
	if (window.openNextField) {
		openNextField("date", id);
	}
	
	new Ajax.Request('index.php?ajaxReq=saveDate&dbTable=' + DBTABLE + '&id=' + id + '&date=' + date, { method:'get' });
}

// Save Date Range
function saveDateRange(date, id) {
	// Get URL
	var l = window.location.href;
	if (!window.location.search) l += "?";
	else l += "&";
	
	// Remove Any Old Start & End Parameters From URL
	l = l.replace(new RegExp("start=[^&]*"), "");
	l = l.replace(new RegExp("end=[^&]*"), "");
	l = l.replace("&&", "&");
	
	// Load New Page
	window.location.assign(l + "start=" + $('date_start').innerHTML + "&end=" + $('date_end').innerHTML);
}

/** Update Net Total ************************************************** **/
function updateNetTotal() {
	var netTotal = 0;
	var totals = document.getElementsByName("totals"); 
	
	for (i = 0; i < totals.length; i++) {
		netTotal += parseFloat(totals.item(i).value);
	}
	
	$("total").innerHTML = "<b>$" + number_format(netTotal, 2, ".", ",") + "</b>";
}

/** New Line ********************************************************** **/
function newLine(id) {
	new Ajax.Request('index.php?ajaxReq=newLine&dbTable=' + DBTABLE + '&id=' + id, {
		method:'get',
		onSuccess: function(t){
			var r = t.responseText || "";
			var row = $('table').insertRow($('table').rows.length - 2);
			
			var regex = /^<id>(.+?)<\/id>/;
			var i = r.match(regex);
			var r = r.replace(regex,"");
			
			row.onmouseover = function () { back(row, "#E6EDF4"); }
			row.onmouseout = function () { back(row, ""); }
			row.innerHTML = r;
			row.id = i[1];
		}
	});
}

/** Delete Line ******************************************************* **/
function deleteLine(id) {
	new Ajax.Request('index.php?ajaxReq=deleteLine&dbTable=' + DBTABLE + '&id=' + id, {method:'get'});
	$('table').deleteRow($(id).rowIndex);
	updateNetTotal();
}

/** Save Notes ******************************************************** **/
function saveNotes(id) {
	new Ajax.Request('index.php?ajaxReq=saveNotes&dbTable=' + DBTABLE + '&id=' + id + '&notes=' + $('notes').value, {method:'get'});
	closeOverlay();
}

/** Event Callback Functions ****************************************** **/
// On Click
var pageX = 0;
var pageY = 0;
function click(e) {
	if (!e) var e = window.event;
	if (IE) {
		var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
		pageX = event.clientX + iebody.scrollLeft;
		pageY = event.clientY;
	} else { 
		pageX = e.pageX;
		pageY = e.pageY;
	}
}
	
// On Key Down
function keydown(e) {
	var key;
	var keychar;
	
	if (window.event) key = window.event.keyCode;
	else if (e) key = e.which;
	
	
	// Tab
	if (key == 9) {
		if (field_type != "date") {
			saveField(field_type, field_id);
		// Just Hide Calendar If Tab Is Pressed (Don't Save)
		} else {
			$('calendar').hide();
		}
		openNextField(field_type, field_id);
		return false;
	}
}

/** Various Support Functions ***************************************** **/
function back(obj, color) {
	obj.style.backgroundColor = color;
}

function number_format(a, b, c, d) {
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if (!f[0]) {
		f[0] = '0';
	}
	if (!f[1]) {
		f[1] = '';
	}
	if (f[1].length < b) {
		g = f[1];
		for (i=f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	neg = false;
	if (f[0].charAt(0) == "-") {
		neg = true;
		f[0] = f[0].substring(1, f[0].length);
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j+=3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	if (neg) {
		f[0] = "-" + f[0];
	}
	c = (b <= 0) ? '' : c;
	return f[0] + c + f[1];
}

function getPageSize(){
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if (yScroll < windowHeight) {
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if (xScroll < windowWidth) {	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight) ;
	return arrayPageSize;
}