function toggle_bill(id) {
	var toggle = ($('billcheckbox_' + id).checked == true) ? '1':'0';

	$('billcheckbox_' + id).checked = (toggle == '1') ? true:false;

	var params = 'toggle='+ toggle +'&id=' + id;
	
	ajax_submit(params, 'toggle_bill', 'bill_container');
}

function toggle_budget(id) {
	var disp = $('dispbgt_' + id);
	var edit = $('ebgt_' + id);
	if(disp.style.display == 'none') {
		Element.show(disp);
		Element.hide(edit);
	} else {
		Element.show(edit);
		$('bgt_' + id).select();
		$('bgt_' + id).focus();
		Element.hide(disp);
	}
}

function update_budget(id,curramt) {
	var budget = $('bgt_' + id).value;
	var params = 'budget=' + budget + '&id=' + id;
	ajax_submit(params, 'update_budget', 'catspend_' + id);
	toggle_budget(id);
	var budget = budget * 1;
	if(curramt != null) {
		if((curramt > budget) && (budget != 0)) {
			$('catspend_' + id).className = 'catspendover';
		} else {	
			$('catspend_' + id).className = 'catspend';
		}	
	}
}

function toggle_clear_transaction(id) {
	var params = '&transaction_id=' + id;

	ajax_submit(params, 'clear_transaction');

	var classnames = $('row_' + id).className;

	if (! classnames.match('large')) {
		// Show header

		$('row_' + id).className += ' large'
	} else {
		// Hide header
		classnames = classnames.replace('large', '');
		
		$('row_' + id).className = classnames;
	}
}


function add_responsetext(params, action, container) {
	params += '&action=' + action;
	
	var url = 'handler.php';
	var opt = {
		method: 'post', 
		parameters: params,
		onComplete: function (t) {
			$(container).innerHTML += t.responseText;
		}
	};
	
	new Ajax.Request(url, opt);
}


function ajax_submit(params, action, container) {
	params += '&action=' + action;
	
	var url = 'handler.php';
	var opt = {
		method: 'post', 
		parameters: params,
		onComplete: function (t) {
			ajax_complete(action, t.responseText);
		}
	};

	if (container) {
		new Ajax.Updater(container, url, opt);
	} else {
		new Ajax.Request(url, opt);
	}
}

function ajax_complete(action, t) {
	switch (action) {
		case 'set_account':
			new Ajax.Autocompleter('payee', 'payee_choices', 'handler.php?action=get_payees', {});
			break;
		case 'edit_transaction':
			var obj, i;

			eval('obj = ' + t);
			var len = obj.length;

			$('add_edit_header').innerHTML			= 'Edit the \'' + obj['payee'] + '\' Transaction';
			$('payee').value 		= obj['payee'];
			$('date').value 		= obj['date'];
			$('amount').value 		= obj['amount'].replace('-','');
			$('memo').value			= obj['memo'];

			(obj['type'] == 1) ? $('withdrawal').checked = true:$('deposit').checked = true;
//			$('cleared').checked = (obj['cleared'] == 1) ? true:false;
			
			$('check_number').value = (obj['check_number'] == 0) ? '':obj['check_number'];
			

			$('categories').value 	= obj['category_id'];
//			$('cleared').value 		= obj['cleared'];
			
			$('transaction_id').value = obj['id'];
			toggle_transaction_form();

			break;

		// ============ User is editing a bill, fill in the form:
		case 'edit_bill':
			var obj, i;
			eval('obj = ' + t);
			var len = obj.length;

			$('add_edit_bill_header').innerHTML			= 'Edit Bill';
			$('billname').value 	= obj['name'];

			$('billyear').value 	= obj['year'];
			$('billmonth').value 	= obj['month'];
			$('billday').value 		= obj['day'];

			$('billamount').value 	= obj['amount'].replace('-','');
			$('notes').value		= obj['notes'];

			(obj['billtype'] == 1) ? $('withdrawal').checked = true:$('deposit').checked = true;
			$('ongoing').checked = (obj['ongoing'] == 1) ? true:false;

			$('categories').value 	= obj['category_id'];

			$('bill_id').value = obj['id'];
			toggle_bill_form();

			break;

		case 'add_category':
			new Effect.Highlight('categories', {startcolor:'#ffff99', endcolor:'#ffffffcc'});
			break;

		case 'edit_category':
			new Effect.Highlight('categories', {startcolor:'#ffff99', endcolor:'#ffffffcc'});
			break;

		case 'delete_category':
			new Effect.Highlight('categories', {startcolor:'#ffff99', endcolor:'#ffffffcc'});
			break;
		
		case 'clear_transaction':
		case 'update_transaction':
		case 'delete_transaction':
		case 'add_transaction':
			var obj, len, i;
			eval('obj = ' + t);
			len = obj.length;
			
			for (i = 0; i < len; i++) {
				$(obj[i]['container']).innerHTML = obj[i]['content'];
			}
			
			break
		
		case 'create_user':
			if (t == 'success') {
				toggle_success();
			} else {
				$('failed').innerHTML = t;
				toggle_fail();
			}
			break;
		case 'edit_account':
			var obj, i;

			eval('obj = ' + t);
			var len = obj.length;

			$('add_edit_account_header').innerHTML			= 'Rename This Account';
			$('name').value 		= obj['name'];
			$('account_id').value = obj['id'];
			toggle_account_form();

			break;
	}
}

function add_transaction(params) {
	var action = ($('transaction_id').value == '') ? 'add_transaction':'update_transaction';
	var container = ($('transaction_id').value == '') ? 'transaction_list':'';

	if (validate_form(action, 'validate') == false) {
		ajax_submit(params, action, container);
		toggle_transaction_form();
        $('add_edit_header').innerHTML = 'Add a Transaction';
	}
}

function add_bill(params) {
	var action = ($('bill_id').value == '') ? 'add_bill':'update_bill';
	//var container = ($('bill_id').value == '') ? 'bill_list':'';
	var container = 'bill_list';

	if (validate_form(action, 'validate') == false) {
		ajax_submit(params, action, container);
		toggle_bill_form();
	}
}

function add_account(params) {
	var action = ($('account_id').value == '') ? 'add_account':'update_account';
	var container = ($('account_id').value == '') ? 'account_list':'account_list';

	ajax_submit(params, action, container);
	toggle_account_form();
}

function share_account(params) {
	var action = 'share_account';
	var container = 'confirmation_message';

	if (validate_form(action, 'validate') == false) {
		ajax_submit(params, action, container);
		toggle_share_account_form();
		Effect.Appear('confirmation_message', { duration: 1.0 });
		setTimeout("Effect.Fade('confirmation_message', { duration: 2.0, queue: 'end' })",4000);
	}
}

function submit_transfer(params) {
	var action = 'submit_transfer';
	var container = 'account_list';
	var tamt = $('transfer_amount').value;
	var faid = $('from_account_id').value;
	var taid = $('to_account_id').value;
	var error = 0;
	
	if( (tamt == '') || (isNaN(tamt)) ) {
		if(tamt == '') {
		  $('transfer_amount_error').className = 'error';
			$('transfer_amount_error').innerHTML = 'Transfer amount cannot be empty.';
			error++
		}
		if (isNaN(tamt)) {
		  $('transfer_amount_error').className = 'error';
			$('transfer_amount_error').innerHTML = 'Transfer amount must be a number.';
			error++
		}
	} else {
		$('transfer_amount_error').className = 'no_error';
		$('transfer_amount_error').innerHTML = 'Amount Ok';
	}
	if (faid == 0) {
		$('transfer_from_error').className = 'error';
		$('transfer_from_error').innerHTML = '<br />Selection must be made.';
		error++
	} else {
		$('transfer_from_error').className = 'no_error';
		$('transfer_from_error').innerHTML = '<br />Transfer from Ok';
	}
	if (taid == 0) {
		$('transfer_to_error').className = 'error';
		$('transfer_to_error').innerHTML = '<br />Selection must be made.';
		error++
	} else {
		$('transfer_to_error').className = 'no_error';
		$('transfer_to_error').innerHTML = '<br />Transfer to Ok';
	}
	
	if (error != 0) {
        Element.show('transfer_amount_error');
        Element.show('transfer_to_error');
        Element.show('transfer_from_error');
		return false;
	} else {
		toggle_transfer_form();
		ajax_submit(params, action, container);
	}
}


function add_category(id) {
	ajax_submit('newcategory=' + escape($(id).value), 'add_category', 'categories');
	Element.hide('new_cat');
	$(id).value = '';
}

function edit_category(id, existcatid) {
	if($(existcatid).value == 1) {
		Element.hide('edit_cat');
		Element.show('cannot_edit');
		return false;
	} else {	
		ajax_submit('editcategory=' + $(id).value + '&existcatid=' + $(existcatid).value, 'edit_category', existcatid);
		Element.hide('edit_cat');
		$(id).value = '';
	}
}

function delete_category(existcatid) {
	if($(existcatid).value == 1) {
		Element.hide('delete_cat');
		Element.show('cannot_delete');
		return false;
	} else {	
		ajax_submit('existcatid=' + $(existcatid).value, 'delete_category', 'categories');
		Element.hide('delete_cat');
	}
}


function exclude_category(id) {
	ajax_submit('category_id=' + id + '&tab=stats_tab', 'exclude_category', 'activity_container');
}

function exclude_budget(id) {
	ajax_submit('category_id=' + id + '&tab=trans_tab', 'exclude_budget', 'activity_container');
}

function exclude_category_accounts(id) {
	ajax_submit('category_id=' + id + '&action=accounts', 'exclude_category', 'page');
}

function top_stats(monthsback) {
	ajax_submit('monthsback=' + monthsback + '&tab=trans_tab', 'categories_monthsback', 'statistics');
}

function toggle_transaction_form() {
	// if hiding form:
	if ($('overlay').style.display != 'none') {
		// Clear the form:
		$('transaction_form').reset();
		$('transaction_id').value = '';
		
		if ($('new_cat').style.display != 'none') {
			// Hide new category form if it's showing:
			toggle_display('new_cat');
		}
		
		toggle_display('overlay');
	}
	
	else {
		$('overlay').onclick = function () {
			toggle_transaction_form();
			return false;
		}
		resize_overlay();
	}

	// Hide or show the form:
	toggle_display('add_transaction_form', 'payee');
}

function toggle_bill_form() {
	// if hiding form:
	if ($('overlay').style.display != 'none') {
		// Clear the form:
		$('bill_form').reset();
		$('bill_id').value = '';
		
		if ($('new_cat_bill').style.display != 'none') {
			// Hide new category form if it's showing:
			toggle_display('new_cat_bill');
		}
		
		toggle_display('overlay');
	}
	
	else {
		$('overlay').onclick = function () {
			toggle_bill_form();
			return false;
		}
		resize_overlay();
	}

	// Hide or show the form:
	toggle_display('add_bill_form');
}

function toggle_account_form() {
	// if hiding form:
	if ($('overlay').style.display != 'none') {
		// Clear the form:
		Element.show('sb_container');	
		$('add_edit_account_header').innerHTML = 'Add an Account';
		$('account_form').reset();
		$('account_id').value = '';
		
		toggle_display('overlay');
	}
	
	else {
		$('overlay').onclick = function () {
			toggle_account_form();
			return false;
		}
		resize_overlay();
	}

	// Hide or show the form:
	toggle_display('add_account_form');
}

function toggle_remove_form() {
	// if hiding form:
	if ($('overlay').style.display != 'none') {
		// Clear the form:
		$('remove_account_id').value = '';
		
		toggle_display('overlay');
	}
	
	else {
		$('overlay').onclick = function () {
			toggle_remove_form();
			return false;
		}
		resize_overlay();
	}

	// Hide or show the form:
	toggle_display('remove_account_form');
}

function toggle_transfer_form() {
	// if hiding form:
	if ($('overlay').style.display != 'none') {
		// Clear the form:
		$('transfer_form').reset();		
		$('transfer_amount_error').innerHTML = '';
		$('transfer_to_error').innerHTML = '';
		$('transfer_from_error').innerHTML = '';
		toggle_display('overlay');
	}
	
	else {
		$('overlay').onclick = function () {
			toggle_transfer_form();
			return false;
		}
		resize_overlay();
	}

	// Hide or show the form:
	toggle_display('account_transfer_form');
}

function toggle_signup_form() {
	// if hiding form:
	if ($('overlay').style.display != 'none') {
		// Clear the form:
		validate_form('create_user', '');
		
		$('signupform').reset();

		toggle_display('overlay');
	}
	
	else {
		$('overlay').onclick = function () {
			toggle_signup_form();
			return false;
		}
		resize_overlay();
	}

	// Hide or show the form:
	toggle_display('signup_form');
}

function toggle_share_form() {
	// if hiding form:
	if ($('overlay').style.display != 'none') {
		// Clear the form:
		$('share').reset();
		
		toggle_display('overlay');
	}
	
	else {
		$('overlay').onclick = function () {
			toggle_share_form();
			return false;
		}
		resize_overlay();
	}

	// Hide or show the form:
	toggle_display('share_form');
}

function toggle_share_account_form() {
	// if hiding form:
	if ($('overlay').style.display != 'none') {
		// Clear the form:
		$('share_account_id').value = '';
		
		toggle_display('overlay');
	}
	
	else {
		$('overlay').onclick = function () {
			toggle_remove_form();
			return false;
		}
		resize_overlay();
	}

	// Hide or show the form:
	toggle_display('share_account_form');
}

function toggle_success() {

	if ($('success').style.display == 'none') {
		$('overlay').onclick = function () {
			toggle_success();
			return false;
		}
	} else {
		toggle_signup_form();
	}

	toggle_display('signup_form_content');
	toggle_display('success');
}

function toggle_fail() {
	if ($('failed').style.display == 'none') {
		$('overlay').onclick = function () {
			toggle_fail();
			return false;
		}
	} else {
		toggle_signup_form();
	}

	toggle_display('signup_form_content');
	toggle_display('failed');
}



function toggle_display(id, focus) {
    if ($(id).style.display == 'none') {
        //(scrOfX,scrOfY)
        var arrayPageScroll = getScrollXY();
        var vscroll = arrayPageScroll[1];
        var eltop = vscroll + 20;

        $(id).style.top = eltop + 'px';
    }
	if($(id).style.display == 'none') {
		Element.show(id);
		if(focus) {
			$(focus).focus();
		}
	} else {
		Element.hide(id);
	} 
}

function resize_overlay() {
	var arrayPageSize = getPageSize();

	Element.setHeight('overlay', arrayPageSize[1]);
	new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.8 });
}


function submit_login(params) {
	Element.show('login_loader');
	ajax_submit(params, 'login', 'page');
}

function logout() {
	ajax_submit('', 'logout', 'page');
}

function edit(id) {
	var params = 'transaction_id=' + id;	

	ajax_submit(params, 'edit_transaction');
}

function rename_account(id, name) {
	toggle_account_form();
	$('add_edit_account_header').innerHTML = 'Rename this Account';
	$('name').value = name;
	$('account_id').value = id;
	Element.hide('sb_container');
}

function show_remove_account(id, name) {
	toggle_remove_form();
	$('remove_account_form').innerHTML = '<input type="hidden" name="remove_account_id" id="remove_account_id" value="' + id + '" />';
	$('remove_account_form').innerHTML += '<p>Are you sure you wish to remove <strong>\'' + name + '\'</strong> from your account list.</p><p><a href="#" onclick="remove_account(\'' + $('remove_account_id').value + '\');return false">yes</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" onclick="toggle_remove_form();return false">cancel</a><p>';
}

function show_share_account(id, name) {
	toggle_share_account_form();
	$('share_account_id').value = id;
	$('share_email').focus();
}

function remove_account(id) {
	var params = 'remove_account_id=' + id;
	var action = 'remove_account';
	var container = 'account_list';

	ajax_submit(params, action, container);
	toggle_remove_form();
}

function editbill(id) {
	var params = 'bill_id=' + id;	

	ajax_submit(params, 'edit_bill');
}

function delete_bill(id) {
	ajax_submit('bill_id=' + id, 'delete_bill', 'bill_list');
}


function delete_transaction(id) {
	ajax_submit('transaction_id=' + id, 'delete_transaction');
}

function submit_share(params) {
	ajax_submit(params + '&type=stats', 'submit_share', 'stats');
}

function submit_search(term) {
  var getfilter = readCookie("filter");
  var filter = (getfilter) ? getfilter : "all";
	window.nextset = 0;
  createCookie("search", term, 365);
	ajax_submit('nextset='+ window.nextset + '&search=' + term + '&type=searchview&filter=' + filter, 'submit_search', 'transaction_list');
	if(term != '') {
	  Element.show('clear-search');
		$('results-message').innerHTML = 'Results containing \'' + term + '\'';
	} else {
	  Element.hide('clear-search');
	}
}

function submit_filters(term, filter) {
	window.nextset = 0;
  createCookie("filter", filter, 365);
	$('display_all').className = '';
	$('display_uncleared').className = '';
	$('display_withdrawals').className = '';
	$('display_deposits').className = '';
	$('display_' + filter).className = 'active';
	ajax_submit('nextset='+ window.nextset + '&search=' + $(term).value + '&type=searchview&filter=' + filter, 'submit_search', 'transaction_list');
}

window.nextset = 0;
function more_transactions() {
  var getsearch = readCookie("search");
  var search = (getsearch) ? getsearch : "";
  var getfilter = readCookie("filter");
  var filter = (getfilter) ? getfilter : "all";
  window.nextset += 30;
  add_responsetext('nextset='+ window.nextset + '&filter=' + filter + "&search=" + search, 'submit_search', 'transaction_list');
}

function submit_category(catid) {
	
	ajax_submit('catid=' + catid + '&tab=trans_tab', 'nav_content', 'activity_container');

//	ajax_submit('catid=' + catid + '&tab=trans_tab', 'transactions_by_category', 'transaction_list');
}

function set_account(id, name) {
  createCookie("filter", 'all', 365);
  createCookie("search", '', 365);
	window.nextset = 0;
	ajax_submit('account_id=' + id + '&account_name=' + name, 'set_account', 'page');
}

function show_accounts() {
  createCookie("filter", 'all', 365);
  createCookie("search", '', 365);
	window.nextset = 0;
	ajax_submit('', 'show_accounts', 'page');
}

function loading(option) {
	var small = (option == 'small') ? ' class="small"':'';

	return '<p style="text-align: center"><img'+ small +' src="images/loading.gif" alt="loading" title="" /><br />Loading</p>'
}

function create_user(params) {
	// Validate form before submitting ajax request:
	if (validate_form('create_user', 'validate') == false) {
		ajax_submit(params, 'create_user');
	}
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

// Form validation:
function validate_form(form, action) {
	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var email_validate = new RegExp(emailReg);

	switch (form) {
		case 'create_user':
			var fields = [
				{ field: 'firstname', req: true },
				{ field: 'lastname', req: true },
				{ field: 'email', req: true, validaddy: 'true' },
				{ field: 'password', req: true },
				{ field: 'confirmpass', req: true }
			];
			
			// Check passwords:
			if ($('password').value != $('confirmpass').value) {
				$('password_error').innerHTML = 'passwords do not match';
				$('confirmpass_error').innerHTML = 'passwords do not match';
				return 1;
			}
			
			break;
		
		case 'update_transaction':
		case 'add_transaction':
			var fields = [
				{ field: 'payee', req: true },
				{ field: 'date', req: true },
				{ field: 'amount', req: true, badchars:'[a-zA-Z]' }
			];

			break;
		
		case 'update_bill':
		case 'add_bill':
			var fields = [
				{ field: 'billname', req: true },
				{ field: 'billyear', req: true, badchars:'[a-zA-Z]' },
				{ field: 'billamount', req: true }
			];

			break;
		case 'share_account':
			var fields = [
				{ field: 'share_email', req: true, validaddy: true }
			]
	}
	
	var len = fields.length, i, error = false, error_container, item;

	for (i = 0; i < len; i++) {
		// Get value of field: 
		item = fields[i];
		
		// Set error container:
		error_container = item['field'] + '_error';

		if (action == 'validate') {

			if (item['req'] && $(item['field']).value == '') {
				$(error_container).innerHTML = 'required';
					
				error = true;
			}

			else if (item['badchars'] && $(item['field']).value.match(item['badchars'])) {
				// Check for bad chars
				$(error_container).innerHTML = 'invalid characters';

				error = true;
			}
			
			else if (item['validaddy']) {
				// Check for bad chars
				if (! $(item['field']).value.match(email_validate)) {
					$(error_container).innerHTML = 'invalid email address';

					error = true;

				} else {
					$(error_container).innerHTML = '';
				}
			}
			
			else {
				$(error_container).innerHTML = '';
			}
		}
		
		else {
			$(error_container).innerHTML = '';
		}
	}

	if (action == 'validate') {
		return error;
	}
}

//only used for when updating one value from a transation (example 'quick_info').
function save_value(input_id, type, transaction_id) {
	var params = 'type=' + type + '&value=' + $(input_id).value + '&transaction_id=' + transaction_id;
	ajax_submit(params, 'save_one', 'row_' + transaction_id);
}


// New JS handler (ADD FUNCTIONS TO THIS TO CLEAN UP JS):
function handler(action, container, options) {
	var params;

	switch (action) {
		case 'payee_quick_stats':
			params = 'payee=' + options['payee'];

			
			break;
	}
	
	ajax_submit(params, action, container)
}



// Following functions are taken from lightbox.js and are intended for resizing elements:
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});


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;
}
			
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
    
    arrayPageScroll = new Array(scrOfX,scrOfY) 
	return arrayPageScroll;
}

function setEditCat(id, sbox, sindex) {
	$(id).value = $(sbox).options[sindex].text;
}


function toggle_tab(id) {
	toggle_tab_status('trans_tab');
	toggle_tab_status('stats_tab');
	
	ajax_submit('tab=' + id, 'nav_content', 'activity_container');
}

// Toggle the status of a tab (active or not... changes the look):
function toggle_tab_status(id) {
	$(id).className = ($(id).className == 'active') ? '':'active'
}


function toggle_filters(id) {
	Element.show(id);
}

function print_view() {
    window.open("print_view.php", "print_preview", "menubar=0,resizable=1,scrollbars=1,width=550,height=650")
}


function show_account_actions(id, name) {
	var lid = 'account_actions_' + id;
	var lTop = $(lid).offsetTop;
	var lLeft = $(lid).offsetLeft;
	var aTop = lTop + 12;
	var aLeft = lLeft;

	$('account_actions').style.top = aTop + 'px';
	$('account_actions').style.left = aLeft + 'px';
	
	$('account_actions').innerHTML = '<ul class="drop_menu">'
			+ '<li><a href="#" onclick="set_account(\'' + id + '\',\'' + name + '\'); Element.hide(\'account_actions\'); return false">Manage this account</a></li>'
			+ '<li><a href="#" onclick="rename_account(\'' + id + '\',\'' + name + '\'); Element.hide(\'account_actions\'); return false">Rename this account</a></li>'
			+ '<li><a href="#" onclick="show_share_account(\'' + id + '\',\'' + name + '\'); Element.hide(\'account_actions\'); return false">Share this account</a></li>'
			+ '<li><a href="#" onclick="show_remove_account(\'' + id + '\',\'' + name + '\'); Element.hide(\'account_actions\'); return false">Remove from list</a></li>'
			+ '</ul>';
}



function show_category_actions(id, name, accts) {
	var lid = 'category_actions_' + id;
	var lTop = $(lid).offsetTop;
	var lLeft = $(lid).offsetLeft;
	var aTop = lTop + 12;
	var aLeft = lLeft;

	$('category_actions').style.top = aTop + 'px';
	$('category_actions').style.left = aLeft + 'px';

	if(typeof(accts) == "undefined"){
    	$('category_actions').innerHTML = '<ul class="drop_menu" style="width: 200px"><li style="width: 200px"><a href="#" style="width: 180px" onclick="exclude_category(\'' + id + '\',\'' + name + '\'); Element.hide(\'category_actions\'); return false;">Exclude from this report</a></li></ul>';
	} else {
	   $('category_actions').innerHTML = '<ul class="drop_menu" style="width: 200px"><li style="width: 200px"><a href="#" style="width: 180px" onclick="exclude_category_accounts(\'' + id + '\',\'' + name + '\'); Element.hide(\'category_actions\'); return false;">Exclude from this report</a></li></ul>';
	}
}

function show_budget_actions(id, name, accts) {
	var lid = 'category_actions_' + id;
	var lTop = $(lid).offsetTop;
	var lLeft = $(lid).offsetLeft;
	var aTop = lTop + 12;
	var aLeft = lLeft;

	$('category_actions').style.top = aTop + 'px';
	$('category_actions').style.left = aLeft + 'px';

	if(typeof(accts) == "undefined"){
    	$('category_actions').innerHTML = '<ul class="drop_menu" style="width: 200px"><li style="width: 200px"><a href="#" style="width: 180px" onclick="exclude_budget(\'' + id + '\',\'' + name + '\'); Element.hide(\'category_actions\'); return false;">Exclude from budget</a></li></ul>';
	} else {
	   $('category_actions').innerHTML = '<ul class="drop_menu" style="width: 200px"><li style="width: 200px"><a href="#" style="width: 180px" onclick="exclude_category_accounts(\'' + id + '\',\'' + name + '\'); Element.hide(\'category_actions\'); return false;">Exclude from budget</a></li></ul>';
	}
}

function show_quickinfo (id) {
    var qinfo = $('quick_info_' + id);
    Element.show(qinfo);
}

function hide_quickinfo (id) {
    var qinfo = $('quick_info_' + id);
    Element.hide(qinfo);
}

function resetmouseout(id) {
    var row = $('row_' + id);
    row.onmouseout = function() {
        hide_quickinfo(id);
    }
}

function show_loading() {
  var vpDim = document.viewport.getDimensions();
  var vpw = vpDim.width;
  var lDim = $('loading').getDimensions();
  var lw = lDim.width;
  
  var lx = (vpw - lw) / 2;
  //(scrOfX,scrOfY)
  var arrayPageScroll = getScrollXY();
  var vscroll = arrayPageScroll[1];
  
  var eltop = vscroll + 20;
  
  $('loading').style.top = eltop + 'px';
  $('loading').setStyle({
	  left: lx + 'px',
	  top: eltop + 'px'
	});
  Element.show('loading');
}

function scroll_balance() {
	var arrayPageScroll = getScrollXY();
	var vscroll = arrayPageScroll[1];
	var eltop = vscroll + 10;
	if(vscroll >= 20) {
		$('pageheader_container').addClassName('drop-shadow');
	}
	if (vscroll < 20) {
		$('pageheader_container').removeClassName('drop-shadow');
	}
}

/* **************************************************************************
at times you may want to the use of the enter key to behave differently.
for instance if a user is on a page that allows for the searching of a company,
but doing so should not refresh the entire page, this script will disable the enter 
key from submitting the entire form, and click the element (eg. a button)
that will run another function.
******* e = the event
******* elem = the id of the button that will be clicked on using the '.click()' property
***************************************************************************** */
function enterKeyAct(e, elem) {
	var key = window.event ? e.keyCode : e.which;	
	var action = document.getElementById(elem);
	if(key == 13) {
		action.click();
		return false;
	}
}

function showMenu(id, eventObj, bid) {
    if(eventObj) {
		// hide any currently-visible popups
		hideCurrentMenu();
		// stop event from bubbling up any farther
		eventObj.cancelBubble = true;
		if(bid) {
			positionMenu(id, bid);
		} else {
			Element.show(id);
		}
		window.currentlyVisibleMenu = id;
	}
}

function hideCurrentMenu() {
    if(window.currentlyVisibleMenu) {
		Element.hide(window.currentlyVisibleMenu);
		window.currentlyVisibleMenu = false;
    }
}

function positionMenu(mid, bid) {
	var bttnDim = $(bid).getDimensions();
	var bttnPos = $(bid).positionedOffset();

	var bttnright = (bttnPos.left - 2) + bttnDim.width;
	var bttntop = bttnPos.top;

	var mnuw = bttnDim.width;
	var mnux = bttnright - mnuw;
	var mnuy = bttntop + bttnDim.height;

	$(mid).setStyle({
		left: mnux + 'px',
		top: mnuy + 'px',
		width: mnuw + 'px'
	});
	Element.show(mid);
}

function niceTables(evenclass,oddclass,hiliteclass) {
    if(document.getElementsByTagName('table')) {
		var tables = document.getElementsByTagName('table');
		for (var nn = 0; nn < tables.length; nn++) {
		  var rows = tables[nn].tBodies[0].rows;
            for(var ii = 0; ii < rows.length; ii++) {
		    	var row = rows[ii];
		    	row.onmouseover = function () {
                        this.className=hiliteclass;
                    };
		    	if(ii % 2) {
		    		row.className = evenclass;
		    		row.onmouseout = function () {
		    		        this.className=evenclass;
		    		    };
		    	} else {
		    		row.className = oddclass;
		    		row.onmouseout = function () {
		    		        this.className=oddclass;
		    		    };
		    	}
		    }
		}
	}
}

window.c = -1; //change account count
window.tcount = -1; //transaction count
window.acount = -1; //accounts count
window.searchfocus = 0;
function key_commands(event) {
//console.info(event.keyCode);
	var atf = $('add_transaction_form');
	var cal = $('change_account_list');
	var accts = $('accounts');
		
		if(atf != null) {
			
			if(atf.style.display == '') {
				switch(event.keyCode) {
					case Event.KEY_ESC:
						toggle_transaction_form();
						Event.stop(event);
				}
			}
			if(atf.style.display == 'none' && window.searchfocus==0) {
				switch(event.keyCode) {
					case 78: //n key pressed
						toggle_transaction_form();
						$('payee').focus();
						var t=setTimeout("$('payee').value = ''",10);
						Event.stop(event);
						return;
					case 67: //c key pressed (choose an account from the list)
						showMenu('change_account_list', event, 'select_accounts_button');
						$('change_account_list').focus();
						$('change_account_list').scrollTo();
						window.scrollBy(0,-50);
						Event.stop(event);
						return;
					case 65: //a key pressed (go to all accounts page)
						show_accounts();
						Event.stop(event);
						return;
				}
			}
			
		}
		
		if(cal != null) {
			
			var ca = cal.getElementsByTagName('a'); //anchor tags inside change account list
			var lastitem = ca.length - 1; //number of last item in the list
			for(ii=0; ii < ca.length; ii++) {
			  ca[ii].className = '';
			}
			
			if(cal.style.display == '' && window.searchfocus==0) {
				switch(event.keyCode) {
					case Event.KEY_DOWN:
						c++;
						if(c > lastitem) c = lastitem;
				  	ca[c].className = 'hilite';
						Event.stop(event);
						return;
					case Event.KEY_UP:
						c--;
						if(c < 0) c = 0;
				  	ca[c].className = 'hilite';
						Event.stop(event);
						return;
					case Event.KEY_RETURN:
			  		ca[c].className = 'hilite';
						var id = ca[c].id;
						id = id.split("_")
						id = id[1];
						var text = ca[c].innerHTML;
						set_account(id, text);
						hideCurrentMenu();
						c=-1;
						Event.stop(event);
						return;
					case Event.KEY_ESC:
						hideCurrentMenu();
						c=-1;
						Event.stop(event);
						return;
				}
			}
				
			 if(cal.style.display == 'none' && atf.style.display == 'none' && window.searchfocus==0) {

					var tl = $('transactions');
					var it = tl.select('div.row'); //divs with a class of row (individual transaction row)
					var lastitem = it.length - 1; //number of last item in the list

					switch(event.keyCode) {
						case 74: //down = j key
							if(tcount == -1) {
								it[0].scrollTo();
								window.scrollBy(0,-250);
							}
							if(tcount > -1) it[tcount].removeClassName('active');
							tcount++;
							if(tcount > lastitem) tcount = lastitem;
							it[tcount].addClassName('active');
							var tPos = it[tcount].viewportOffset();
							var vpPos = document.viewport.getDimensions();
							if((tPos.top + 50) > vpPos.height && tcount < (lastitem -2)) {
								it[tcount].scrollTo();
								window.scrollBy(0,-50);
							}
							if(tcount > (lastitem - 2)) { //don't scroll up 50 pixels if at the bottom of the screen.
								it[tcount].scrollTo();
							}
							Event.stop(event);
							return;
						case 75: //up = k key
							if(tcount < lastitem + 1) it[tcount].removeClassName('active');
							tcount--;
							if(tcount < 0) tcount = 0;
							it[tcount].addClassName('active');
							var tPos = it[tcount].viewportOffset();
							var itPos = it[tcount].positionedOffset();
							var vpPos = document.viewport.getDimensions();
							var sby = -(vpPos.height - 150);
							if((tPos.top - 100) < 0) {
								it[tcount].scrollTo();
								window.scrollBy(0,sby);
							}
							Event.stop(event);
							return;
						case 88: //clear/unclear transaction (click checkbox) = x key
							var id = it[tcount].id;
							id = id.split("_")
							id = id[1];
							$('cleared_' + id).click();
							Event.stop(event);
							return;
						case 69: //edit transaction = e key
							var id = it[tcount].id;
							id = id.split("_")
							id = id[1];
							edit(id);
							Event.stop(event);
							return;
						case 68: //delete transaction = d key
							var id = it[tcount].id;
							id = id.split("_")
							id = id[1];							
							Element.show('delete_' + id);
							$('delete_cancel_' + id).focus();
							Event.stop(event);
							return;
						case 70: //find a transaction = f key
							$('search').focus();
							$('search').scrollTo();
							window.scrollBy(0,-250);
							Event.stop(event);
							return;
					}
					
				}
				
			}
			
			if(accts != null) {
					var al = $('account_list');
					var ia = al.getElementsByClassName('account-details'); //li tags inside accounts_list ul (individual accounts)
					
					var lastitem = ia.length - 1; //number of last item in the list

					if($('account_transfer_form').style.display == 'none' && $('add_account_form').style.display == 'none' && $('share_account_form').style.display == 'none') {
						switch(event.keyCode) {
							case 74: //down = j key
								if(acount == -1) {
									ia[0].scrollTo();
									window.scrollBy(0,-50);
								}
								if(acount > -1) ia[acount].removeClassName('active');
								acount++;
								if(acount > lastitem) acount = lastitem;
								ia[acount].addClassName('active');
								var aPos = ia[acount].viewportOffset();
								var vpPos = document.viewport.getDimensions();
								if((aPos.top + 50) > vpPos.height && acount < (lastitem -2)) {
									ia[acount].scrollTo();
									window.scrollBy(0,-50);
								}
								Event.stop(event);
								return;
							case 75: //up = k key
								if(acount < lastitem + 1) ia[acount].removeClassName('active');
								acount--;
								if(acount < 0) acount = 0;
								ia[acount].addClassName('active');
								var aPos = ia[acount].viewportOffset();
								var iaPos = ia[acount].positionedOffset();
								var vpPos = document.viewport.getDimensions();
								var sby = -(vpPos.height - 150);
								if((aPos.top - 50) < 0) {
									ia[acount].scrollTo();
									window.scrollBy(0,sby);
								}
								Event.stop(event);
								return;
							case 77: //manage account = m key
								var str = ia[acount].id;
								str = str.split("_")
								var id = str[1];	
								var name = str[2];
								set_account(id,name);
								Event.stop(event);
								return;
							case 88: //transfer funds = x key (xfer funds)
								toggle_transfer_form();
								$('transfer_amount').focus();
								Event.stop(event);
								return;
							case 78: //new account = n key
								toggle_account_form();
								$('name').focus();
								Event.stop(event);
								return;
							case 83: //detailed stats report = s key
								location.href='stats.php';
								Event.stop(event);
								return;
						}
					}
					switch(event.keyCode) {
						case Event.KEY_ESC:
							if($('account_transfer_form').style.display== '') {
								toggle_transfer_form();
							}
							if($('add_account_form').style.display== '') {
								toggle_account_form();
							}
							if($('share_account_form').style.display== '') {
								toggle_share_account_form();
							}
							Event.stop(event);
					}
				
			}

}

function toggle_keyboard_help () {
	if($('keyboard_change_accounts').style.display == 'none' && $('keyboard_new_transaction').style.display == 'none') {
		var bttnDim = $('new_trans_bttn').getDimensions();
		var bttnPos = $('new_trans_bttn').positionedOffset();
		
		var bttnright = (bttnPos.left - 2) + bttnDim.width;
		var bttntop = bttnPos.top;
		
		var mnuw = bttnDim.width;
		var mnux = bttnright - mnuw;
		var mnuy = bttntop + bttnDim.height;
		
		$('keyboard_new_transaction').setStyle({
			left: mnux + 'px',
			top: mnuy + 'px'
		});
		
		
		Effect.Appear('keyboard_choose_transaction',{ duration: 1.0, from: 0, to: .9 });
		Effect.Appear('keyboard_change_accounts',{ duration: 1.0, from: 0, to: .9 });
		Effect.Appear('keyboard_new_transaction',{ duration: 1.0, from: 0, to: .9 });
		$('keyboard_help_link').innerHTML = 'Hide shortcuts';
	} else {
		Effect.Fade('keyboard_choose_transaction',{ duration: 1.0, from: .9, to: 0 });
		Effect.Fade('keyboard_change_accounts',{ duration: 1.0, from: .9, to: 0 });
		Effect.Fade('keyboard_new_transaction',{ duration: 1.0, from: .9, to: 0 });
		$('keyboard_help_link').innerHTML = 'Keyboard shortcuts';
	}
}


document.onclick = hideCurrentMenu;

if (window.attachEvent) window.attachEvent("onscroll", scroll_balance);
if (window.addEventListener) window.addEventListener("scroll", scroll_balance, false);

var myGlobalHandlers = {
	onCreate: function(){
		show_loading();
	},
	onComplete: function() {
		if(Ajax.activeRequestCount == 0){
			Element.hide('loading');
		}
	}
};

Ajax.Responders.register(myGlobalHandlers);

