// JavaScript Document

var popUpWin=0;
var invoiceRecordStart = 1;
var addressRecordStart = 1;
var doNotClear = 0;

function popUpWindow(URLStr, left, top, width, height) {
  if(popUpWin) {
    if(!popUpWin.closed) popUpWin.close();
  }
  popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=1,resizable=1,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

function forgotPassword() {
	var username = document.p_admin.username.value;
	if (username == "") {
		alert("Enter your username, then click on \"I forgot my password.\" again");
		return false;
	}
	var myURL = ("/index.cgi?rm=4&username=" + username);
	var newWindow = window.open(myURL, 'Forgot', 'height=250,width=500,resizable=yes');
}



// Address AJAX calls
function rebuildAddresslist() {
	cover();
	
	var varElemID = document.getElementById('address_lookup_box');
	document.gbsales.address_search_string.value = varElemID.value;

	if(! doNotClear) {
		addressRecordStart = 1;
		document.gbsales.starting_record.value = addressRecordStart;
	}

	submit_formdata( ['address_search_string','address_order','address_sort','starting_record'], [processAddressResults], 'post'); 
}

function processAddressSort (order, sort) {
	document.gbsales.address_order.value = order;
	document.gbsales.address_sort.value = sort;
	
	rebuildAddresslist();
}

function processAddressResults(divData) {
	var varDivID = document.getElementById('address_results');
	varDivID.innerHTML = divData;
	cover();
}

function clearAddressSearch() {
	var varElemID = document.getElementById('address_lookup_box');
	varElemID.value = "";
	document.gbsales.address_search_string.value = "";

	rebuildAddresslist();
}

function addressPageMove(pageNext, pagePrev) {
	if(pageNext) {
		addressRecordStart = addressRecordStart + 50;
	} else if(pagePrev && addressRecordStart > 1) {
		addressRecordStart = addressRecordStart - 50;
	}
	document.gbsales.starting_record.value = addressRecordStart;
	doNotClear = 1;
	rebuildAddresslist();
	doNotClear = 0;
}


// Invoice AJAX calls
function rebuildInvoiceList() {
	cover();

	var varElemID = document.getElementById('invoice_lookup_box');
	document.gbsales.invoice_search_string.value = varElemID.value;

	var varElemID = document.getElementById('unit_lookup_box');
	document.gbsales.unit_search_string.value = varElemID.value;

	var varElemID = document.getElementById('invoice_starting_lookup');
	document.gbsales.invoice_starting_date.value = varElemID.value;

	var varElemID = document.getElementById('invoice_ending_lookup');
	document.gbsales.invoice_ending_date.value = varElemID.value;

	if(! doNotClear) {
		invoiceRecordStart = 1;
		document.gbsales.starting_record.value = invoiceRecordStart;
	}
	
	submit_formdata( ['invoice_search_string','unit_search_string','invoice_order','invoice_sort', 'install_primary', 'invoice_starting_date', 'invoice_ending_date', 'starting_record'], [processInvoiceResults], 'post'); 
}

function processInvoiceSort (order, sort) {
	document.gbsales.invoice_order.value = order;
	document.gbsales.invoice_sort.value = sort;
	
	rebuildInvoiceList();
}

function processInvoiceResults(divData) {
	var varDivID = document.getElementById('invoice_results');
	varDivID.innerHTML = divData;
	cover();
}

function clearInvoiceSearch() {
	var varElemID = document.getElementById('invoice_lookup_box');
	varElemID.value = "";
	document.gbsales.invoice_search_string.value = "";

	var varElemID = document.getElementById('unit_lookup_box');
	document.gbsales.unit_search_string.value = "";
	varElemID.value = "";
	
	var varElemID = document.getElementById('invoice_starting_lookup');
	document.gbsales.invoice_starting_date.value = "";
	varElemID.value = "";
	
	var varElemID = document.getElementById('invoice_ending_lookup');
	document.gbsales.invoice_ending_date.value = "";
	varElemID.value = "";
	
	rebuildInvoiceList();
}

function invoicePageMove(pageNext, pagePrev) {
	if(pageNext) {
		invoiceRecordStart = invoiceRecordStart + 50;
	} else if(pagePrev && invoiceRecordStart > 1) {
		invoiceRecordStart = invoiceRecordStart - 50;
	}
	document.gbsales.starting_record.value = invoiceRecordStart;
	doNotClear = 1;
	rebuildInvoiceList();
	doNotClear = 0;
}

function saveApprovalInfo() {
	var approvedBy = document.getElementById('approved_by');
	var poNum = document.getElementById('po_num');
	var glNum = document.getElementById('gl_num');
	var approvalYesNo = document.getElementById('approval_yes_no');

	if(! approvedBy.value) {
		alert("You need to enter the 'Approved By' name");
		return;
	}
	if(! approvalYesNo.value) {
		alert("You need to select either 'Yes' or 'No' in the Approval box.");
		return;
	}

	cover('save');
	
	document.gbsales.approved_by_string.value = approvedBy.value;
	document.gbsales.po_num_string.value = poNum.value;
	document.gbsales.gl_num_string.value = glNum.value;
	document.gbsales.approval_yes_no_string.value = approvalYesNo.value;

	submit_formdata( ['invoice_id','approved_by_string','po_num_string','gl_num_string','approval_yes_no_string'], [processApprovalResults], 'post'); 

	hideBox('approval');
}

function processApprovalResults (divData) {
	var varDivID = document.getElementById('onscreen_invoice');
	varDivID.innerHTML = divData;
	cover('save');
}

function emailInvoice() {
	var emailAddress = document.getElementById('email_address');
	var emailMessage = document.getElementById('email_message');

	if(! emailAddress.value) {
		alert("You need to enter a valid email address");
		return;
	}

	var test = testEmail(emailAddress.value);
	if(! test) {
		alert("The email address appears to be malformed.  Please re-enter.");
		return;
	}
	
	cover('email');
	
	document.gbsales.email_address_string.value = emailAddress.value;
	document.gbsales.email_message_string.value = emailMessage.value;

	submit_formdata( ['invoice_id','email_address_string','email_message_string'], [processEmailInvoice], 'post'); 

	hideBox('email');
}

function processEmailInvoice (divData) {
	cover('email');
}

function showDepositBox() {
	hideBox('approval');
	hideBox('email');
	
	var status;
	if (document.layers) {
		status = document.layers['dep_calc'].visibility;
	} else if (document.getElementById) {
		status = document.getElementById('dep_calc').style.display;
	} else if (document.all) {
		status = document.all['dep_calc'].style.display;
	}
	if(status == "show" || status == "block") {
		return;
	}
	
	document.getElementById('created_by').value = "";
	document.getElementById('tenant_name').value = "";
	document.getElementById('deposit_start_date').value = "";
	document.getElementById('deposit_end_date').value = "";
	document.getElementById('deposit_term').value = "60";
	
	showBox('dep_calc');
	
	document.forms[0].created_by.focus();
}

function showApprovalBox() {
	hideBox('dep_calc');
	hideBox('email');
	
	var status;
	if (document.layers) {
		status = document.layers['approval'].visibility;
	} else if (document.getElementById) {
		status = document.getElementById('approval').style.display;
	} else if (document.all) {
		status = document.all['approval'].style.display;
	}
	if(status == "show" || status == "block") {
		return;
	}
		
	showBox('approval');
	
	document.forms[0].approved_by.focus();
}

function showEmailInvoiceBox() {
	hideBox('dep_calc');
	hideBox('approval');
	
	var status;
	if (document.layers) {
		status = document.layers['email'].visibility;
	} else if (document.getElementById) {
		status = document.getElementById('email').style.display;
	} else if (document.all) {
		status = document.all['email'].style.display;
	}
	if(status == "show" || status == "block") {
		return;
	}
	
	document.getElementById('email_address').value = "";
	
	showBox('email');
	
	document.forms[0].email_address.focus();
}

function depositPrintToScreen(invoiceID) {
	var createdBy = document.getElementById('created_by').value;
	var tenantName = document.getElementById('tenant_name').value;
	var startDate = document.getElementById('deposit_start_date').value;
	var endDate = document.getElementById('deposit_end_date').value;
	var term = document.getElementById('deposit_term').value;

	if(! createdBy) {
		alert("You need to enter created by name");
		return;
	}
	if(! tenantName) {
		alert("You need to enter the tenant's name");
		return;
	}
	if(! startDate) {
		alert("You need to enter the start date");
		return;
	}
	if(! endDate) {
		alert("You need to enter the end date");
		return;
	}
	if(! term) {
		alert("You need to enter the depreciation term (in months)");
		return;
	}

	var testStart = parseDate(startDate);
	var formatedStartDate;
	if(testStart == null){
		alert("Start Date is not valid.  Please use a MM/DD/YY format");
		return;
	} else {
		formatedStartDate = formatDate(testStart,'MMM dd, yyyy');
	}

	var testEnd = parseDate(endDate);
	var formatedEndDate;
	if(testEnd == null){
		alert("End Date is not valid.  Please use a MM/DD/YY format");
		return;
	} else {
		formatedEndDate = formatDate(testEnd,'MMM dd, yyyy');
	}

	var termTest = _isInteger(term);
	if(! termTest) {
		alert("Depreciation Term is not valid.  Please enter the number of months that this product depreciates over.");
		return;
	}

	var diff = compareDates(formatedStartDate, "MMM dd, yyyy", formatedEndDate, "MMM dd, yyyy");
	if(diff == 1) {
		alert("End date can not be before start date");
		return;
	}

	var popString = "/index.cgi?rm=5&invoiceid=" + invoiceID + "&created_by=" + createdBy + "&name=" + tenantName + "&startdate=" + startDate + "&enddate=" + endDate + "&term=" + term ;
	popUpWindow(popString, 200, 100, 800, 800);
}

function depositPDF(invoiceID) {
	var createdBy = document.getElementById('created_by').value;
	var tenantName = document.getElementById('tenant_name').value;
	var startDate = document.getElementById('deposit_start_date').value;
	var endDate = document.getElementById('deposit_end_date').value;
	var term = document.getElementById('deposit_term').value;

	if(! createdBy) {
		alert("You need to enter created by name");
		return;
	}
	if(! tenantName) {
		alert("You need to enter the tenant's name");
		return;
	}
	if(! startDate) {
		alert("You need to enter the start date");
		return;
	}
	if(! endDate) {
		alert("You need to enter the end date");
		return;
	}
	if(! term) {
		alert("You need to enter the depreciation term (in months)");
		return;
	}

	var testStart = parseDate(startDate);
	var formatedStartDate;
	if(testStart == null){
		alert("Start Date is not valid.  Please use a MM/DD/YY format");
		return;
	} else {
		formatedStartDate = formatDate(testStart,'MMM dd, yyyy');
	}

	var testEnd = parseDate(endDate);
	var formatedEndDate;
	if(testEnd == null){
		alert("End Date is not valid.  Please use a MM/DD/YY format");
		return;
	} else {
		formatedEndDate = formatDate(testEnd,'MMM dd, yyyy');
	}

	var termTest = _isInteger(term);
	if(! termTest) {
		alert("Depreciation Term is not valid.  Please enter the number of months that this product depreciates over.");
		return;
	}

	var diff = compareDates(formatedStartDate, "MMM dd, yyyy", formatedEndDate, "MMM dd, yyyy");
	if(diff == 1) {
		alert("End date can not be before start date");
		return;
	}
	
	var popString = "/index.cgi?rm=100&pdf_rm=5&invoiceid=" + invoiceID + "&created_by=" + createdBy + "&name=" + tenantName + "&startdate=" + startDate + "&enddate=" + endDate + "&term=" + term;
	popUpWindow(popString, 200, 100, 800, 800);
}



function showBox(index) {
	if (document.layers) {
		document.layers[index].visibility = "show";
	} else if (document.getElementById) {
		document.getElementById(index).style.display = "block";
		document.getElementById(index).style.visibility = "visible";
	} else if (document.all) {
		document.all[index].style.display = "block";
		document.all[index].style.visibility = "visible";
	}
}

function hideBox(index) {
	if (document.layers) {
		document.layers[index].visibility = "hide";
	} else if (document.getElementById) {
		document.getElementById(index).style.display = "none";
		document.getElementById(index).style.visibility = "hidden";
	} else if (document.all) {
		document.all[index].style.display = "none";
		document.all[index].style.visibility = "hidden";
	}
}


// Javascript for budgets
function processBudgetSetup(budgetType, returnDiv) {
	cover();

	document.gbsales.budget_type.value = budgetType;
	document.gbsales.return_div.value = returnDiv;

	var varDivID = document.getElementById('budget_year');
	document.gbsales.passed_budget_year.value = varDivID.value;

	var varDivID = document.getElementById('budget_month');
	document.gbsales.passed_budget_month.value = varDivID.value;

	submit_formdata( ['budget_type','passed_budget_year','passed_budget_month','search_string'], [returnBudgetSetup], 'post'); 
}

function returnBudgetSetup(divData) {
	var returnDiv = document.gbsales.return_div.value;
	var varDivID = document.getElementById(returnDiv);
	varDivID.innerHTML = divData;
	cover();
}

function updateBudgets() {
	var varDivID = document.getElementById('pre_decision');
	if(varDivID.innerHTML == "&nbsp;") {
		return;
	}

	cover();	
	
	var varDivID = document.getElementById('budget_year');
	document.gbsales.passed_budget_year.value = varDivID.value;

	var varDivID = document.getElementById('budget_month');
	document.gbsales.passed_budget_month.value = varDivID.value;

	var varDivID = document.getElementById('single_address');
	if(varDivID.value == "") {
		submit_formdata( ['budget_type','passed_budget_year','passed_budget_month','search_string'], [returnBudgetSetup], 'post'); 
	} else {
		submit_formdata( ['passed_budget_year','passed_budget_month','single_address','search_string'], [returnUpdateBudgets], 'post'); 
	}
}

function returnUpdateBudgets(returnDiv) {
	var varDivID = document.getElementById('carpet_budget_total');
	varDivID.innerHTML = arguments[0]

	var varDivID = document.getElementById('vinyl_budget_total');
	varDivID.innerHTML = arguments[1];

	var varDivID = document.getElementById('windows_budget_total');
	varDivID.innerHTML = arguments[2];

	cover();
}

function refreshBudgets() {
	cover();

	var varDivID = document.getElementById('budget_year');
	document.gbsales.passed_budget_year.value = varDivID.value;

	var varDivID = document.getElementById('returned_budget');
	varDivID.innerHTML = "";

	submit_formdata( ['passed_budget_year','search_string'], [returnRefreshedBudgets], 'post'); 
}

function returnRefreshedBudgets(divData) {
	var varDivID = document.getElementById('address_budget_label');
	varDivID.innerHTML = arguments[0]

	var varDivID = document.getElementById('address_budgets');
	varDivID.innerHTML = arguments[1];

	var varDivID = document.getElementById('account_budget_label');
	varDivID.innerHTML = arguments[2]

	var varDivID = document.getElementById('account_budgets');
	varDivID.innerHTML = arguments[3];

	if(arguments[4]) {
		var varDivID = document.getElementById('returned_budget');
		varDivID.innerHTML = arguments[4];
	}
	cover();
}

function displayBudget(selectedBudget, otherBudget, passedParam) {
	cover();

	var varDivID = document.getElementById(otherBudget);
	if(varDivID != null) {
		varDivID.value = "";
	}
	
	var budgetInfo;
	if(passedParam) {
		budgetInfo = passedParam;
	} else {
		budgetInfo = selectedBudget.value;
	}

	document.gbsales.selected_budget.value = budgetInfo;

	submit_formdata( ['selected_budget'], [returnDisplayBudget], 'post'); 
}

function returnDisplayBudget(divData) {
	var varDivID = document.getElementById('returned_budget');
	varDivID.innerHTML = divData;

	cover();
}

function returnToSearch() {
	window.location.href="http://www.gbsalesonline.com/index.cgi?rm=1";
}

function newBudget() {
	window.location.href="http://www.gbsalesonline.com/index.cgi?rm=8";
}

function showMonthlyInstall(installID) {
	var thisName = "monthly_numbers_" + installID;
	document.getElementById(thisName).value = "1";

	var annualDiv = "annual_budget_" + installID;
	var monthlyDiv = "monthly_budget_" + installID;
	hideBox(annualDiv);
	showBox(monthlyDiv);
}

function showAnnualInstall(installID) {
	var thisName = "monthly_numbers_" + installID;
	document.getElementById(thisName).value = "";

	var annualDiv = "annual_budget_" + installID;
	var monthlyDiv = "monthly_budget_" + installID;
	hideBox(monthlyDiv);
	showBox(annualDiv);
}

function updateAnnualBudget(product,installID,type) {
	var totalAmount = 0;

	var thisAmountName = "January_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "February_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "March_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "April_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "May_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "June_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "July_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "August_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "September_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "October_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "November_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var thisAmountName = "December_" + product + "_budget_" + type + "_" + installID;
	var thisAmountID = document.getElementById(thisAmountName);
	var thisAmount = thisAmountID.value;
	thisAmount = thisAmount * 1;
	totalAmount = totalAmount + thisAmount;

	var divTotalName = "monthly_" + product + "_total_" + installID;
	var divTotalID = document.getElementById(divTotalName);
	var result = Math.round(totalAmount * 100) / 100;
	if(totalAmount > 0) {
		divTotalID.innerHTML = "$" + result;
	} else {
		divTotalID.innerHTML = "";
	}

}

function addOtherExpenses() {
	var varDivID = document.getElementById('budget_year');
	var varYear = varDivID.value;
	
	var varDivID = document.getElementById('selected_budget');
	var varSelectedBudget = varDivID.value;

	var varDivID = document.getElementById('search_string');
	var varSearchString = varDivID.value;
	
	window.location.href="http://www.gbsalesonline.com/index.cgi?rm=830&passed_budget_year=" + varYear + "&selected_budget=" + varSelectedBudget + "&search_string=" + varSearchString;
}

function createBudget() {
	var varSearchString = document.gbsales.address_search_string.value;
	window.location.href="http://www.gbsalesonline.com/index.cgi?rm=8&search=" + varSearchString;
}

function viewBudget() {
	window.location.href="http://www.gbsalesonline.com/index.cgi?rm=810&rl=home";
}

function viewPrinterFriendlyBudget() {
	var varDivID = document.getElementById('selected_budget');
	var varSelectedBudget = varDivID.value;

	var link = "/index.cgi?rm=850&sel_bud=" + varDivID.value;
	popUpWindow(link, 200, 100, 800, 800);
}

function downloadExcelFile() {
	var varDivID = document.getElementById('selected_budget');
	var varSelectedBudget = varDivID.value;

	window.location.href="http://www.gbsalesonline.com/index.cgi?rm=860&sel_bud=" + varSelectedBudget;
}

function getOtherExpAddresses() {
	cover();

	var varDivID = document.getElementById('budget_year');
	document.gbsales.passed_budget_year.value = varDivID.value;

	submit_formdata( ['passed_budget_year'], [returnGetOtherExpAddresses], 'post'); 

}

function returnGetOtherExpAddresses(divData) {
	var varDivID = document.getElementById('other_expenses');
	varDivID.innerHTML = divData;

	cover();
}


function displayOtherExpenses(selectedBudget, otherBudget, passedParam) {
	cover();

	var varDivID = document.getElementById(otherBudget);
	if(varDivID != null) {
		varDivID.value = "";
	}
	
	var budgetInfo;
	if(passedParam) {
		budgetInfo = passedParam;
	} else {
		budgetInfo = selectedBudget.value;
	}

	document.gbsales.selected_budget.value = budgetInfo;
	
	submit_formdata( ['selected_budget'], [returnDisplayOtherExpenses], 'post'); 
}

function returnDisplayOtherExpenses(divData) {
	var varDivID = document.getElementById('other_exp_details');
	varDivID.innerHTML = divData;

	cover();
}

// Javascript for budget tabs
function showCarpet() {
	document.getElementById('tab1a').className="bg";
	document.getElementById('tab1b').className="bg";
	document.getElementById('tab1c').className="bg";
	document.getElementById('tab2a').className="inactive";
	document.getElementById('tab2b').className="inactive";
	document.getElementById('tab2c').className="inactive";
	document.getElementById('tab3a').className="inactive";
	document.getElementById('tab3b').className="inactive";
	document.getElementById('tab3c').className="inactive";

	hideBox('vinyl_box');
	hideBox('windows_box');
	showBox('carpet_box');
}

function showVinyl() {
	document.getElementById('tab2a').className="bg";
	document.getElementById('tab2b').className="bg";
	document.getElementById('tab2c').className="bg";
	document.getElementById('tab1a').className="inactive";
	document.getElementById('tab1b').className="inactive";
	document.getElementById('tab1c').className="inactive";
	document.getElementById('tab3a').className="inactive";
	document.getElementById('tab3b').className="inactive";
	document.getElementById('tab3c').className="inactive";

	hideBox('carpet_box');
	hideBox('windows_box');
	showBox('vinyl_box');
}

function showWindows() {
	document.getElementById('tab3a').className="bg";
	document.getElementById('tab3b').className="bg";
	document.getElementById('tab3c').className="bg";
	document.getElementById('tab1a').className="inactive";
	document.getElementById('tab1b').className="inactive";
	document.getElementById('tab1c').className="inactive";
	document.getElementById('tab2a').className="inactive";
	document.getElementById('tab2b').className="inactive";
	document.getElementById('tab2c').className="inactive";

	hideBox('carpet_box');
	hideBox('vinyl_box');
	showBox('windows_box');
}


function toggleRow(index) {
	var visible = isThisVisible(index);
	if (visible == 1) {
		hideDivBox(index);
	} else {
		showDivBox(index);
	}
}

function isThisVisible(index) {
	if (document.layers) {
		if (document.layers[index].visibility == "show") {
			return 1;
		}
	} else if (document.getElementById) {
		if (document.getElementById(index).style.visibility == "visible") {
			return 1;
		}
	} else if (document.all) {
		if (document.all[index].style.visibility == "visible") {
			return 1;
		}
	}
}

function showDivBox(index) {
	if (document.layers) {
		document.layers[index].visibility = "show";
	} else if (document.getElementById) {
		document.getElementById(index).style.display = "block";
		document.getElementById(index).style.visibility = "visible";
	} else if (document.all) {
		document.all[index].style.display = "block";
		document.all[index].style.visibility = "visible";
	}

	var varImgName = "img_" + index;
	var varImgID = document.getElementById(varImgName);
	varImgID.src = "http://www.gbsalesonline.com/images/minus.gif"
}

function hideDivBox(index) {
	if (document.layers) {
		document.layers[index].visibility = "hide";
	} else if (document.getElementById) {
		document.getElementById(index).style.display = "none";
		document.getElementById(index).style.visibility = "hidden";
	} else if (document.all) {
		document.all[index].style.display = "none";
		document.all[index].style.visibility = "hidden";
	}

	var varImgName = "img_" + index;
	var varImgID = document.getElementById(varImgName);
	varImgID.src = "http://www.gbsalesonline.com/images/plus.gif"
}


// Javascript for field validation
function testEmail(email_addr) {
	var reg = new RegExp("^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
	return reg.test(email_addr);
}

function validateNumber(item_in) {
  var item_out = "";
  var needAlert = false;

  for (var i=0; i < item_in.value.length; i++) {
	 var myChar = item_in.value.charAt(i);
	 var myCharCode = item_in.value.charCodeAt(i);
	 
	 // Only "." and [0-9] allowed
	 if (myCharCode != 46 && (myCharCode < 48 || myCharCode > 57)) {
		needAlert = true;
	 }
	 else {
		item_out += myChar;
	 }
  }
  if (needAlert) {
	 item_in.value = item_out;
	 alert ("Non-numeric characters were removed from your input.");
	 item_in.focus();
  }
}

function updateTotals(month,budgetType,accountType,accountPrimary,count) {
	var totalAmount = 0;
	for (var idx=1; idx < count; idx++) {
		var thisAmountName = budgetType + "_other_expense_amount_" + accountType + "_" + idx + "_" + month + "_" + accountPrimary;
		var thisAmountID = document.getElementById(thisAmountName);
		var thisAmount = thisAmountID.value;
		thisAmount = thisAmount * 1;
		totalAmount = totalAmount + thisAmount;
	}

	var divTotalName = budgetType + "_" + month + "_total";
	var divTotalID = document.getElementById(divTotalName);
	var result = Math.round(totalAmount * 100) / 100;
	
	var divDescName = budgetType + "_" + month + "_desc";
	var divDescID = document.getElementById(divDescName);
	if(totalAmount > 0) {
		divTotalID.innerHTML = "$" + result;
		divDescID.innerHTML = "Click to expand";
	} else {
		divTotalID.innerHTML = "";
		divDescID.innerHTML = "";
	}

}


// Javascript for loading background image
var vis=true;
function cover(option) {  

  if(option == 'save') {
  	var mycover = document.getElementById('save_cover');
  } else if (option == 'email') {
  	var mycover = document.getElementById('email_cover');
  } else {
  	var mycover = document.getElementById('cover_page');
  }
  if (vis){
	 vis=false;
	 mycover.style.display='block';      
  } else {   
	 vis=true;
	 mycover.style.display='none'; 
  }
}


// Javascript for popup help screens
function ShowHelp(obj,field,hide) {
	//Get help object
	var helpObj;
	if (document.all){
		helpObj = document.all[field+"_help"];
	} else if (document.getElementById) {
		helpObj = document.getElementById(field+"_help");
	}
	if (helpObj) {
		//if help object is shown, hide it ; if object hidden, show it
		if (hide){
		  helpObj.style.display = "none";}
		else{
		  helpObj.style.display = "";}

		//Get location of mouseover object, move help object to the left if will display off-screen
		var divWidth = 340;
		var offsetLeft = getOffsetLeft(obj);
		var screenWidth = (window.innerWidth) ? window.innerWidth - 25 : document.body.clientWidth;
		if ((offsetLeft + divWidth) > screenWidth) offsetLeft = screenWidth - divWidth;
		newX = offsetLeft;
	
		//Get location of mouseover object, move help object on top if will display off-screen
		var divHeight = helpObj.offsetHeight;
		var offsetTop = getOffsetTop(obj) + obj.offsetHeight + 2;
		var screenHeight = (window.innerHeight) ? window.innerHeight - 25 : document.body.clientHeight;
		if ((offsetTop + divHeight) > screenHeight + getScrollY()) offsetTop = getOffsetTop(obj) - divHeight;
		newY = offsetTop;	
	
		helpObj.style.top = newY;
		helpObj.style.left = newX;

		if (!hide){
		  qh_hideElement("select",helpObj);  
		  qh_hideElement("object",helpObj);  
		  qh_hideElement("embed",helpObj);  }
		else{
		  qh_showElement("select");  
		  qh_showElement("object");  
		  qh_showElement("embed");}
	}
}
function getOffsetTop (elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	while (mOffsetParent) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;}
	return mOffsetTop;
}

function getOffsetLeft (elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	while (mOffsetParent) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;}
	return mOffsetLeft;
}
function getScrollY() {
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
	//Netscape
	scrOfY = window.pageYOffset;}
  else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	//DOM
	scrOfY = document.body.scrollTop;}
  else if( document.documentElement &&
	  ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	//IE6
	scrOfY = document.documentElement.scrollTop;}
  return scrOfY;
}

function qh_hideElement( elmID, overDiv ) {
  if(document.all) {
	for(i = 0; i < document.all.tags( elmID ).length; i++) {
	  obj = document.all.tags( elmID )[i];
	  if(!obj || !obj.offsetParent) continue;

	  // Find the element's offsetTop and offsetLeft relative to the BODY tag.
	  objLeft   = obj.offsetLeft;
	  objTop    = obj.offsetTop;
	  objParent = obj.offsetParent;

	  while(objParent.tagName.toUpperCase() != 'BODY') {
		objLeft  += objParent.offsetLeft;
		objTop   += objParent.offsetTop;
		objParent = objParent.offsetParent;
	  }

	  objHeight = obj.offsetHeight;
	  objWidth  = obj.offsetWidth;

	  if((overDiv.offsetLeft + overDiv.offsetWidth) <= objLeft);
	  else if((overDiv.offsetTop + overDiv.offsetHeight) <= objTop);
	  else if(overDiv.offsetTop >= (objTop + objHeight));
	  else if(overDiv.offsetLeft >= (objLeft + objWidth));
	  else {
		obj.style.visibility = 'hidden';
	  }
	}
  }
}
function qh_showElement(elmID) {
  if(document.all) {
	for(i = 0; i < document.all.tags( elmID ).length; i++) {
	  obj = document.all.tags(elmID)[i];
	  if(!obj || !obj.offsetParent) continue;
	  obj.style.visibility = '';
	}
  }
}






// F. Permadi 2005.
// Highlights table row
// Copyright (C) F. Permadi
// This code is provided "as is" and without warranty of any kind.  Use at your own risk.

// These variables are for saving the original background colors
var savedStates=new Array();
var savedStateCount=0;

/////////////////////////////////////////////////////
// This function takes an element as a parameter and 
//   returns an object which contain the saved state
//   of the element's background color.
/////////////////////////////////////////////////////
function saveBackgroundStyle(myElement)
{
  saved=new Object();
  saved.element=myElement;
  saved.className=myElement.className;
  saved.backgroundColor=myElement.style["backgroundColor"];
  return saved;   
}

/////////////////////////////////////////////////////
// This function takes an element as a parameter and 
//   returns an object which contain the saved state
//   of the element's background color.
/////////////////////////////////////////////////////
function restoreBackgroundStyle(savedState)
{
  savedState.element.style["backgroundColor"]=savedState.backgroundColor;
  if (savedState.className)
  {
    savedState.element.className=savedState.className;    
  }
}

/////////////////////////////////////////////////////
// This function is used by highlightTableRow() to find table cells (TD) node
/////////////////////////////////////////////////////
function findNode(startingNode, tagName)
{
  // on Firefox, the TD node might not be the firstChild node of the TR node
  myElement=startingNode;
  var i=0;
  while (myElement && (!myElement.tagName || (myElement.tagName && myElement.tagName!=tagName)))
  {
    myElement=startingNode.childNodes[i];
    i++;
  }  
  if (myElement && myElement.tagName && myElement.tagName==tagName)
  {
    return myElement;
  }
  // on IE, the TD node might be the firstChild node of the TR node  
  else if (startingNode.firstChild)
    return findNode(startingNode.firstChild, tagName);
  return 0;
}

/////////////////////////////////////////////////////
// Highlight table row.
// newElement could be any element nested inside the table
// highlightColor is the color of the highlight
/////////////////////////////////////////////////////
function highlightTableRow(myElement, highlightColor)
{
  var i=0;
  // Restore color of the previously highlighted row
  for (i; i<savedStateCount; i++)
  {
    restoreBackgroundStyle(savedStates[i]);          
  }
  savedStateCount=0;

  // To get the node to the row (ie: the <TR> element), 
  // we need to traverse the parent nodes until we get a row element (TR)
  // Netscape has a weird node (if the mouse is over a text object, then there's no tagName
  while (myElement && ((myElement.tagName && myElement.tagName!="TR") || !myElement.tagName))
  {
    myElement=myElement.parentNode;
  }

  // If you don't want a particular row to be highlighted, set it's id to "header"
  // If you don't want a particular row to be highlighted, set it's id to "header"
  if (!myElement || (myElement && myElement.id && myElement.id=="header") )
    return;
		  
  // Highlight every cell on the row
  if (myElement)
  {
    var tableRow=myElement;
    
    // Save the backgroundColor style OR the style class of the row (if defined)
    if (tableRow)
    {
	  savedStates[savedStateCount]=saveBackgroundStyle(tableRow);
      savedStateCount++;
    }

    // myElement is a <TR>, then find the first TD
    var tableCell=findNode(myElement, "TD");    

    var i=0;
    // Loop through every sibling (a sibling of a cell should be a cell)
    // We then highlight every siblings
    while (tableCell)
    {
      // Make sure it's actually a cell (a TD)
      if (tableCell.tagName=="TD")
      {
        // If no style has been assigned, assign it, otherwise Netscape will 
        // behave weird.
        if (!tableCell.style)
        {
          tableCell.style={};
        }
        else
        {
          savedStates[savedStateCount]=saveBackgroundStyle(tableCell);        
          savedStateCount++;
        }
        // Assign the highlight color
        tableCell.style["backgroundColor"]=highlightColor;

        // Optional: alter cursor
        tableCell.style.cursor='default';
        i++;
      }
      // Go to the next cell in the row
      tableCell=tableCell.nextSibling;
    }
  }
}

/////////////////////////////////////////////////////
// This function is to be assigned to a <table> mouse event handler.
// If the element that fired the event is within a table row,
//   this function will highlight the row.
/////////////////////////////////////////////////////
function trackTableHighlight(mEvent, highlightColor)
{
  if (!mEvent)
    mEvent=window.event;
		
  // Internet Explorer
  if (mEvent.srcElement)
  {
    highlightTableRow( mEvent.srcElement, highlightColor);
  }
  // Netscape and Firefox
  else if (mEvent.target)
  {
    highlightTableRow( mEvent.target, highlightColor);		
  }
}

/////////////////////////////////////////////////////
// Highlight table row.
// newElement could be any element nested inside the table
// highlightColor is the color of the highlight
/////////////////////////////////////////////////////
function highlightTableRowVersionA(myElement, highlightColor)
{
  var i=0;
  // Restore color of the previously highlighted row
  for (i; i<savedStateCount; i++)
  {
    restoreBackgroundStyle(savedStates[i]);          
  }
  savedStateCount=0;

  // If you don't want a particular row to be highlighted, set it's id to "header"
  if (!myElement || (myElement && myElement.id && myElement.id=="header") )
    return;
		  
  // Highlight every cell on the row
  if (myElement)
  {
    var tableRow=myElement;
    
    // Save the backgroundColor style OR the style class of the row (if defined)
    if (tableRow)
    {
	  savedStates[savedStateCount]=saveBackgroundStyle(tableRow);
      savedStateCount++;
    }

    // myElement is a <TR>, then find the first TD
    var tableCell=findNode(myElement, "TD");    

    var i=0;
    // Loop through every sibling (a sibling of a cell should be a cell)
    // We then highlight every siblings
    while (tableCell)
    {
      // Make sure it's actually a cell (a TD)
      if (tableCell.tagName=="TD")
      {
        // If no style has been assigned, assign it, otherwise Netscape will 
        // behave weird.
        if (!tableCell.style)
        {
          tableCell.style={};
        }
        else
        {
          savedStates[savedStateCount]=saveBackgroundStyle(tableCell);        
          savedStateCount++;
        }
        // Assign the highlight color
        tableCell.style["backgroundColor"]=highlightColor;

        // Optional: alter cursor
        tableCell.style.cursor='default';
        i++;
      }
      // Go to the next cell in the row
      tableCell=tableCell.nextSibling;
    }
  }
}








// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

// HISTORY
// ------------------------------------------------------------------
// May 17, 2003: Fixed bug in parseDate() for dates <1970
// March 11, 2003: Added parseDate() function
// March 11, 2003: Added "NNN" formatting option. Doesn't match up
//                 perfectly with SimpleDateFormat formats, but 
//                 backwards-compatability was required.

// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
//              | NNN (abbr.)        |
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Day of Week  | EE (name)          | E (abbr)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
		}
	else if (d1 > d2) {
		return 1;
		}
	return 0;
	}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getFullYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
	
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getFullYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"||token=="NNN"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
	}

// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d   MMM d, y   MMM d,y   y-MMM-d   d-MMM-y  MMM d
// M/d/y   M-d-y      M.d.y     MMM-d     M/d      M-d
// d/M/y   d-M-y      d.M.y     d-MMM     d/M      d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------
function parseDate(val) {
	var preferEuro=(arguments.length==2)?arguments[1]:false;
	generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
	monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
	dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
	var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
	var d=null;
	for (var i=0; i<checkList.length; i++) {
		var l=window[checkList[i]];
		for (var j=0; j<l.length; j++) {
			d=getDateFromFormat(val,l[j]);
			if (d!=0) { return new Date(d); }
			}
		}
	return null;
	}
