// JavaScript Document
/* page management code */

// constants
var DEF_BAGS_INTERVALS = 1;
var DEF_BAGS_SETS = "1";
var DEF_COMP_INTERVALS = 1;
var DEF_COMP_SETS = "1";
var DEF_GOVN_INTERVALS = 1;
var DEV_BC_SETS = "2";
var DEF_AB_SETS = "1";
var DEF_SK_SETS = "2";

var wells = new Array(); /* an array of wells to store */
var companies;
var contacts;
var shipto_contacts; 

/* Page construction */
window.onload = init;


function init()
{
  var em;
  
  /* set up show hide buttons
  em = document.getElementById("hide_btn");
  em.onclick = show_hide_class;
  em.hide = true;
  em.hide_class = 'loggedinHide';
  em = document.getElementById("show_btn");
  em.onclick = show_hide_class;
  em.hide = false;
  em.hide_class = 'loggedinHide';
  */
  
  em = document.getElementById("shipto_delivery_type")
  em.onchange = shipto_company_sel_changed;
  
  em = document.getElementById("well_sel");
  em.onchange = well_select_changed;
  
  em = document.getElementById("add_well_btn");
  em.onclick = add_well;
  
  // when the well name is changed, change the select right away
  em = document.getElementById("wellname");
  em.onchange = well_name_changed;
  
  // em = document.getElementById("show_login");
  // em.onclick = login_btn_click;
  // em.show_div_id = "login_div";
  
  //em = document.getElementById("output_form");
  //em.style.display = "none"; 
  
  //em = document.getElementById("back");
  //em.onclick = back_to_order;
  
  document.forms[0].onsubmit = "form_submit";
  
  em = document.getElementById("preview_button");
  em.onclick = preview_order;
  
  em = document.getElementById("submit_button");
  em.onclick = form_submit;
  
  set_bags_view(true);
  set_checkbox_textbox_view(true, 'well_gunny', 'well_gunny_qty');
  set_checkbox_textbox_view(true, 'well_mudsample', 'well_mudsample_qty');
}

function login_btn_click()
{
    var em = document.getElementById(this.show_div_id);
    var uname = document.getElementById("login_name");
    var passwd = document.getElementById("login_password");
    
    /* If the textbox div is not shown..just show it and return. */
    if (em.style.display != "inline") {
        em.style.display = "inline";
        uname.disabled = false;
        passwd.disabled = false;
        return ;
    } else {
        // var ems = document.getElementById("temp_cover");
        // ems.style.visibility = "visible";
        
        Anthem_InvokePageMethod('Grsi_Login', [uname.value, passwd.value], return_from_login);
        uname.disabled = true;
        passwd.disabled = true;
    }
}

function login_ok()
{
    hide_show_div("loggedinHide", false);
    Anthem_InvokePageMethod('GetCompanies', null, return_from_getcompanies);
    clear_select("billto_company", "Retreiving");
    // document.getElementById("temp_cover").style.visibility = "hidden";
    // document.getElementById("login_div").style.display = "none";
}

function return_from_login(result)
{
    if (result.value == "LOGIN_OK") {
        alert("Login OK");
        document.getElementById("login_password").value = "";
        login_ok();
    } else {
        alert(result.value);
        document.getElementById("login_name").disabled = false;
        document.getElementById("login_password").disabled = false;
        document.getElementById("login_password").value = "";
        // document.getElementById("temp_cover").style.visibility = "hidden";
    }

}
        
function return_from_getcompanies(result)
{
    if (result == null || result == undefined) {
        alert ("Could not get companies from database");
        return;
    }
   
    companies = result.value;
    var count = companies.Rows.length;
    // Load both the company selects with the companies.
    var sel = document.getElementById("billto_company");
    var sel2 = document.getElementById("shipto_delivery_type");
    sel.options.length = 0;
    // Save previously selected index on sel2
    var j = sel2.selectedIndex;
    sel2.options.length = 3;
    var option;
    for (var i = 0; i < count; i ++) {
        option = new Option(companies.Rows[i].CompanyName, companies.Rows[i].CompanyName, false, false);
        sel.options[i] = option;  
        option = new Option(companies.Rows[i].CompanyName, companies.Rows[i].CompanyName, false, false);
        sel2.options[i + 3] = option;
    }

    sel.selectedIndex = 0;
    sel.onchange = company_sel_changed;
    // call company sel changed to load the values from company 0 into the form.
    company_sel_changed();
    
    // check to make sure the index is less than the default # of options.
    if (j > 2)
        j = -1;
    sel2.selectedIndex = j;
    // sel2.onchange = shipto_company_sel_changed;
}

function clear_select(sel_id, text)
{
    var sel = document.getElementById(sel_id);
    sel.options.length = 0;
    sel.options[0] = new Option(text, text, false, false);
    sel.selectedIndex = 0;
}

function company_sel_changed()
{
    var sel = document.getElementById("billto_company");
    var i = sel.selectedIndex;
        
    if (i < 0)
        return;
        
    if (i >= companies.Rows.length) {
        Anthem_InvokePageMethod('GetCompanies', null, return_from_getcompanies);
        alert("Need to reload companies from database");
        return;
    }
    // clear the current billto contacts and get the updated list from the db.
    clear_select("billto_contact", "Retreiving");  
    contacts = null;
    Anthem_InvokePageMethod('GetContacts', [companies.Rows[i].Index], return_from_getcontacts);
    // update the company info.
    company_name(companies.Rows[i].CompanyName);
    address(companies.Rows[i].Address);
    city(companies.Rows[i].City); 
    province(companies.Rows[i].Province); 
    postal(companies.Rows[i].PostalCode);
}

function shipto_company_sel_changed ()
{
    log_error(ENTER_EXIT, "enter shipto_company_sel_changed");
    var sel = document.getElementById("shipto_delivery_type");
    var i = sel.selectedIndex - 3;
    
    shipto_changed();
    
    if (i < 0) {
        log_error(INFO, "Index is out of range for stored companies" + i);
        return;
    }
        
    if (i >= companies.Rows.length) {
        Anthem_InvokePageMethod('GetCompanies', null, return_from_getcompanies);
        alert("Need to reload companies from database");
        return;
    }
 
    // Clear the shipto delivery contact.
    clear_select("shipto_delivery_contact", "Retreiving");
    shipto_contacts = null;    
    Anthem_InvokePageMethod('GetContacts', [companies.Rows[i].Index], shipto_return_from_getcontacts);
    // load the company info for the ship company
    ship_companyname(companies.Rows[i].CompanyName);
    ship_address(companies.Rows[i].Address);
    ship_city(companies.Rows[i].City); 
    ship_province(companies.Rows[i].Province); 
    ship_postal(companies.Rows[i].PostalCode);
}


function return_from_getcontacts(result)
{
    if (result.value == null) {
        alert ("Could not get contacts from database");
        return;
    }
    
    var sel = document.getElementById("billto_contact");
    sel.options.length = 0;
    // load the received contacts into the select.
    contacts = result.value;
    var count = contacts.Rows.length;
    if (count == 0) 
        return;
    var option 
    for (var i = 0; i < count; i ++) {
        option = new Option(contacts.Rows[i].Name, contacts.Rows[i].Name, false, false);
        sel.options[i] = option;  
    }
    
    // set the select index to 0 and load the contact into the form.
    sel.selectedIndex = 0;
    sel.onchange = contact_sel_changed;
    setTimeout(contact_sel_changed, 0);
    
}

function shipto_return_from_getcontacts(result)
{
    if (result == null) {
        alert ("Could not get contacts from database");
        return;
    }
    
    var sel = document.getElementById("shipto_delivery_contact");
    sel.options.length = 0;
    // load the received contacts into the shipto select.    
    shipto_contacts = result.value;
    var count = shipto_contacts.Rows.length;    
    if (count == 0)
        return;

    var option 
    for (var i = 0; i < count; i ++) {
        option = new Option(shipto_contacts.Rows[i].Name, shipto_contacts.Rows[i].Name, false, false);
        sel.options[i] = option;  
    }
    sel.selectedIndex = 0;
    sel.onchange = shipto_contact_sel_changed;
    setTimeout(shipto_contact_sel_changed, 0);
}

function contact_sel_changed()
{
    var sel = document.getElementById("billto_contact");
    var i = sel.selectedIndex;
    
    // alert(contacts + " i: " + i + " len: " + contacts.Rows.length );
    
    if (i < 0 || i == undefined) {
        contact("");
        phone("");
        email("");
        return;
    }
    
    if (contacts == null)
        return;
        
    if (i >= contacts.Rows.length) {
        Anthem_InvokePageMethod('GetContacts', [companies.Rows[i].Index], return_from_getcontacts);
        alert("Need to reload contacts from database");
        return;
    }
    // update the contact info.
    contact(contacts.Rows[i].Name);
    phone(contacts.Rows[i].Phone);
    email(contacts.Rows[i].Email); 
}

function shipto_contact_sel_changed()
{
    var sel = document.getElementById("shipto_delivery_contact");
    var i = sel.selectedIndex;
    
    if (i < 0 || i == undefined) {
        ship_phone("");
        ship_attention("");
        return;
    }
    
    if (shipto_contacts == null)
        return;
        
    if (i >= shipto_contacts.Rows.length) {
        Anthem_InvokePageMethod('GetContacts', [companies.Rows[i].Index], shipto_return_from_getcontacts);
        alert("Need to reload contacts from database");
        return;
    }
    // update the shipto contact info.
    ship_attention(shipto_contacts.Rows[i].Name);
    ship_phone(shipto_contacts.Rows[i].Phone);
}

/* set the default view state for bags */
function set_bags_view(disabled)
{
	if (disabled)
	{	
		// nosets is checked uncheck printed or blank
		e = document.getElementsByName("well_bags_type");
		for (var i = 0; i <e.length; i++)
			e[i].checked = false;
		
		//clear the number of sets 
		set_text_value("well_bags_sets", "");
		clear_intervals("well_bags_interval");
		
		// ensure that nosets is checked.
		e = document.getElementById("well_bags_nosets");
		e.checked = true;
	}
	else
	{
		// well_bags_type is selected
		e = document.getElementById("well_bags_nosets");
		e.checked = false;
		
	    var i = DEF_BAGS_INTERVALS - table_current_nrof_intervals("well_bags_interval")
	    while ( i > 0 ) {
		    add_depth_interval_to_table('well_bags_interval', 'well_bags_nosets', 'Printed or Blank Bags.')
		    i--;
		}    
		set_text_value("well_bags_sets", DEF_BAGS_SETS);
	}
	
	// enable/disable all bags controls
	en_dis_children("well_bags_sets", disabled);
	en_dis_children("well_bags_interval_from", disabled);
	en_dis_children("well_bags_interval_to", disabled);
	en_dis_children("well_bags_interval_increment", disabled);
}

function set_company_cb(disabled)
{
	var e;
	e = document.getElementById("well_vialscompany_set_type");
	e.checked = !disabled;
	e = document.getElementById("well_vialscompany_nosets");
	e.checked = disabled;
}

function set_company_view(disabled)
{
	var e;
	
	set_company_cb(disabled);
	
	if (disabled) {
		set_text_value("well_vialscompany_set_qty", "");
		clear_intervals("well_vialscompany_interval");
	} else {
	    // fill in the default sets and add some intervals 
	    var i = DEF_COMP_INTERVALS - table_current_nrof_intervals("well_vialscompany_interval")
	    while ( i > 0 ) {
		    add_depth_interval_to_table('well_vialscompany_interval', 'well_vialscompany_nosets', 'Company Vials.')
		    i--;
		}    
		set_text_value("well_vialscompany_set_qty", DEF_COMP_SETS);
	}
	
	en_dis_children("well_vialscompany_set_qty", disabled);
	en_dis_children("well_vialscompany_interval_from", disabled);
	en_dis_children("well_vialscompany_interval_to", disabled);
	en_dis_children("well_vialscompany_interval_increment", disabled);
}

function set_govenment_cb(disabled)
{
	if (disabled)
	{
		var	e = document.getElementsByName("well_vialsgovernment_set_type");
		for (var i = 0; i < e.length; i++)
		{
			e[i].checked = false;
		}
		var	e = document.getElementById("well_vialsgovernment_nosets")
		e.checked = true;
	}
	else
	{
		var	e = document.getElementById("well_vialsgovernment_nosets")
		e.checked = false;
	}
}

function set_government_view(disabled)
{
	var e;
	
	en_dis_children("well_vialsgovernment_set_qty", disabled);
	en_dis_children("well_vialsgovernment_interval_from", disabled);
	en_dis_children("well_vialsgovernment_interval_to", disabled);
	en_dis_children("well_vialsgovernment_interval_increment", disabled);
	set_govenment_cb(disabled);
	
	if (disabled) {
		set_text_value("well_vialsgovernment_set_qty_ab", "");
		set_text_value("well_vialsgovernment_set_qty_sk", "");
		set_text_value("well_vialsgovernment_set_qty_bc", "");
		clear_intervals("well_vialsgovernment_interval");
    } else {
        var i = DEF_GOVN_INTERVALS - table_current_nrof_intervals("well_vialsgovernment_interval")
	    while ( i > 0 ) {
		    add_depth_interval_to_table('well_vialsgovernment_interval', 'well_vialsgovernment_nosets', 'AB, SK or BC Vials.')
		    i--;
		}    
    }
}

function enable_government_view(checked)
{
	if (checked)
	{
		return set_government_view(false);
	}
	else 
	{
		// check if the other check boxes are enabled
		var	e = document.getElementsByName("well_vialsgovernment_set_type");
		for (var i = 0; i < e.length; i++)
		{
			// if another checkbox is checked then the view should still be OK.
			// Add update to set_government_view() for the well changing case. 
			if (e[i].checked)
				return set_government_view(false);
		}
		return set_government_view(true);		
	}
}

function set_checkbox_textbox_view(disabled, checkbox_id, textbox_id)
{
    en_dis_children(textbox_id, disabled)
    if (disabled) {
        set_text_value(textbox_id, "");
        document.getElementById(checkbox_id).checked = false;
    } else
        document.getElementById(checkbox_id).checked = true;
}

function shipto_changed()
{
    log_error(ENTER_EXIT, "shipto_changed");
    var em = document.getElementById("shipto_delivery_type");    
    
	if (em.selectedIndex <= 1)
		hide_show_div("shiptoHide", true);
	else
		hide_show_div("shiptoHide", false);
		
		// TODO if logged in do stuff.
		
}

// show or hide a div. hide = true div is hidden
function hide_show_div(id, hide)
{
	var d = document.getElementsByName(id);
	var dis;
	
	if (hide)
		dis = "none";
	else
		dis = "inline";
		
	for (var i=0; i<d.length; i++)
	{
		d[i].style.display = dis;
	}
}

function show_hide_class()
{
	if (this.hide == null)
	  return log_error("show_hide_div " + id + " missing hide property");
	  
	if (this.hide_class == null)
	  return log_error("show_hide_div " + id + " missing hide_class property");
	
	 hide_show_div(this.hide_class, this.hide);
}

function copy_from_bags(name, not_required_id, error)
{
	var tbl = document.getElementById('well_bags_interval');
	var e = document.getElementById(not_required_id);
	if (e.checked == true)
	{	
		alert("You must select " + error);
		return -1;
	}
	
	var src_rows = tbl.rows.length - find_table(tbl);
	
	if (src_rows == 0)
	{
		alert("There are no depth intervals for Bags.");
		return;
	}
	tbl = document.getElementById(name);
 	
	for (var dst_rows = tbl.rows.length - find_table(tbl); src_rows > dst_rows; dst_rows++)
		add_table_row(tbl, name);
		
	var src_to = document.getElementsByName("well_bags_interval_to");
	var src_from = document.getElementsByName("well_bags_interval_from");
	var src_inc = document.getElementsByName("well_bags_interval_increment");
	var dst_to = document.getElementsByName(name + "_to");
	var dst_from = document.getElementsByName(name + "_from");
	var dst_inc = document.getElementsByName(name + "_increment");
	// need to use this to fix the copy in IE.
	//var array = tbl.getElementsByTagName("input");
	//alert("src_to " + src_to.length + " src_from " + src_from.length + " dst_to " + dst_to.length + " dst_from " + dst_from.length + " array " + array.length);
	//return false;
	for (var i = 0; i < src_rows; i++)
	{
		//if (src_to[i])
		    dst_to[i].value = src_to[i].value;
		//if (src_from[i])
		    dst_from[i].value = src_from[i].value;
		//if (src_inc[i])
		    dst_inc[i].value = src_inc[i].value;
		
	}
	return false;
}

function clear_intervals(name)
{
	var tbl = document.getElementById(name);
	var inputs = tbl.getElementsByTagName("input");
	
	for (var i = 0; i < inputs.length; i++)
	    inputs[i].value = "";
	
}


/* Store the tables in an array with the ID and the min row we can delete to 
 * a new table is added to tables when the user trys to add or delete a row 
 * from a table that we don't know about. The base_row is the number of rows
 * the table had when the page was loaded. remove_interval will not remove
 * rows that we did not add. 
 */
var tables = new Array();

function table(table_id, base_row)
{
	this.id = table_id;     // id 
	this.row = base_row;    // # of rows when the page was loaded.
}

/* search for the table in our array and return the row i.e base_row */
function find_table(tbl)
{
	for (var i = 0; i < tables.length; i++)
	{
	    // search for this table id in our array.
		if (tbl.id == tables[i].id)
		{
			return tables[i].row;
		}
	}
	//table not found, add it
	var t = new table(tbl.id, tbl.rows.length);
	tables[tables.length] = t;
	return t.row;
}

function table_current_nrof_rows(tbl)
{
    return tbl.rows.length;
}

function table_current_nrof_intervals(table_id)
{
    var tbl = get_table(table_id);
    
	// find the table in our array.
	var min_rows = find_table(tbl);
  	var lastRow = table_current_nrof_rows(tbl);
    
    return lastRow - min_rows;
}

/* get a reference to a table with the specified table_id */
function get_table(table_id)
{
    var tbl= document.getElementById(table_id)
	
	if (tbl == null)
	{
		log_error("remove_interval table id: " + table_id + " could not get table by ID");
		return -1;
	}
	return tbl;
}

/* well intervals function */
function add_depth_interval_to_table(table_id, not_required_id, error)
{
	var tbl = document.getElementById(table_id)
	var e = document.getElementById(not_required_id);
	if (e.checked == true)
	{	
		alert("You must select " + error);
		return -1;
	}
	
	if (tbl == null)
	{
		log_error("add_interval div name: " + table_id + " could not get table by ID");
		return -1;
	}
	add_table_row(tbl, table_id);
}

function add_table_row(tbl, table_id, from, to, inc)
{
	find_table(tbl);
	
	var lastRow = tbl.rows.length;
	var iteration = lastRow;
  	var row = tbl.insertRow(lastRow);

	//add cells
  	row_add_cell_text(row, "From:");
	row_add_cell_input(row, table_id + "_from", null, from);
	row_add_cell_text(row, "To:");
	row_add_cell_input(row, table_id + "_to", null, to);
  	row_add_cell_input_text(row, table_id + "_increment", "m", inc);
  	
	return row;
}

// TODO loop through array and remove all intervals from tables.
		// TODO remove all the intervals
		// while (remove_interval("well_bags_interval") > 1) {}
/* remove a depth interval from a table. This can be
 * called even if there are not intervals added
 */ 
function remove_all_intervals(table_id)
{
    var tbl= get_table(table_id);
	
	var min_rows = find_table(tbl);
  	var lastRow = tbl.rows.length;
  	while (tbl.rows.length > min_rows) {
  	    // only remove the row if the row was previously added
  	    tbl.deleteRow(tbl.rows.length - 1);
  	}
  	log_error(INFO, "Removed rows " + lastRow +" to " + tbl.rows.length + " from table " + table_id);
}
function remove_interval(table_id)
{
    var tbl= get_table(table_id);
	
	var min_rows = find_table(tbl);
  	var lastRow = tbl.rows.length;
  	if (lastRow > min_rows) {
  	    // only remove the row if the row was previously added
  	    tbl.deleteRow(lastRow - 1);
  	    return (lastRow - min_rows);
  	}
  	return 0;
}

function show_wells()
{
	for (var i = 0; i < wells.length; i++)
		log_error(INFO, wells[i].toString());
}

function clear_well_from_page()
{
    well_name("");
    set_text_value("nameData", "");
    set_text_value("uId", "");
    set_text_value("billto_number", "");
    set_government_view(true);
    set_bags_view(true);
    set_company_view(true);
    set_checkbox_textbox_view(true, 'well_gunny', 'well_gunny_qty');
	set_checkbox_textbox_view(true, 'well_mudsample', 'well_mudsample_qty');
	clear_intervals("well_bags_interval");
	clear_intervals("well_vialscompany_interval");
	clear_intervals("well_vialsgovernment_interval");
	remove_all_intervals("well_bags_interval");
	remove_all_intervals("well_vialscompany_interval");
	remove_all_intervals("well_vialsgovernment_interval");
}


function get_well_from_page(pageWell)
{
    var b_type, b_sets;
    /* get well bags */
	
	log_error(ENTER_EXIT, "Enter get_well_from_page()");
    
    log_error(INFO, "Update well " + well_name());
    pageWell.name = well_name();
    pageWell.sidetrack = sidetrack();
    pageWell.id = id();
    pageWell.po = number();
    pageWell.potype = billto();
    pageWell.bags_type = bags_type();
    pageWell.bags.sets[0] = bags_qty();
    bags_get(pageWell.bags);
    vials_get(pageWell.company);
    gov_get(pageWell.government);
    pageWell.company.sets[0] = vials_qty();
    pageWell.government.sets[0] = vials_qty_ab();
    pageWell.government.sets[1] = vials_qty_bc();
    pageWell.government.sets[2] = vials_qty_sk();
    pageWell.gunny = gunny_qty();
    pageWell.mud = mud_qty();
    
    log_error(ENTER_EXIT, "Exit get_well_from_page()");
    return pageWell;	                  
}

/* sends pageWell to the page. overwrites everything on the page */
function send_well_to_page(pageWell)
{
    log_error(ENTER_EXIT, "Enter send_well_to_page()");
    
    log_error(INFO, "send_well_to_page " + pageWell.toString());
    well_name(pageWell.name);
    sidetrack(pageWell.sidetrack);
    id(pageWell.id);
    number(pageWell.po);
    billto(pageWell.potype);
    bags_set(pageWell.bags);
    vials_set(pageWell.company);
    bags_type(pageWell.bags_type);
    bags_qty(pageWell.bags.sets[0]);
    vials_qty(pageWell.company.sets[0]);
    vials_qty_ab(pageWell.government.sets[0]);
    vials_qty_bc(pageWell.government.sets[1]);
    vials_qty_sk(pageWell.government.sets[2]);
    // Update the view for Gov. Send false to check if ab, sk or bc is checked and update the view 
    // accordingly
    gov_set(pageWell.government);
    enable_government_view(false);
    gunny_qty(pageWell.gunny);
    mud_qty(pageWell.mud);
    
    log_error(ENTER_EXIT, "Exit send_well_to_page()");   
}

function save_well()
{
    log_error(ENTER_EXIT, "Enter save_well()");
	var i = wells.length;
	
	if (current_well_index == i) {
	    // if the current well index = length of the array then 
	    // we need to add a new well to the array.
        wells[i] = new Grswell();
    }
    get_well_from_page(wells[current_well_index]);
    
    log_error(ENTER_EXIT, "Exit save_well()");
}

function add_well()
{
    log_error(ENTER_EXIT, "Enter add_well()");
    
    save_well();
    show_wells(wells); // test code
	update_select();
	
	var option = new Option("", "", false, false);
    well_select().options[well_select().length] = option;
	well_select_index(well_select().length - 1);
	clear_well_from_page();
    
    log_error(ENTER_EXIT, "Exit add_well()");
}

function update_select()
{
    log_error(ENTER_EXIT, "Enter update_select()");
    
    var select = well_select();
    
    // store the current index
    var temp = well_select_index();
    
    log_error(INFO, "update_select() index: " + temp + " length: " + wells.length);
    select.length = 0;

    for (var i = 0; i < wells.length; i++) {
        var option = new Option(wells[i].name, wells[i].id, false, false);
        select.options[i] = option;       
    }
    well_select_index(temp);
    
    log_error(ENTER_EXIT, "Exit update_select()");
}

// the well name has been changed
// save the well and update the select right away so that the name shows.
function well_name_changed()
{
    save_well();
    update_select();
    // if the select was -1 (i.e this is the first well) change it to 0
    if (well_select_index() == -1)
        well_select_index(0);
}

function well_select_changed()
{ 
    log_error(ENTER_EXIT, "Enter well_select_changed()");
    save_well();
    update_select();
    clear_well_from_page();
    send_well_to_page(wells[current_well_index]); 
    log_error(ENTER_EXIT, "Exit well_select_changed()");
}

function send_preview_to_output_form()
{   
    var text = "";
    // set the layout of the table
    text += "<table width='700px' cellpadding='2' bgcolor='#f7f7f7'font-family:'arial'>";
    text += "<tr><td width='100px'></td><td width='250px'></td><td width='100px'></td><td width='250px'></td></tr>";
    text += "<tr><td colspan='4'><b>Order Preview</b></td></tr>";
    var sel = document.getElementById("shipto_delivery_type");
    var show_ship = true;
    
    if (sel.selectedIndex <= 1)
        show_ship = false;
        
    text += "<tr><td colspan='2'><b>Bill To:</b></td><td colspan='2'><b>Ship To Attn: " + ship_attention() + "</b></td></tr>";
    
    
    if (show_ship) {
        text += "<tr><td><b>Company:</b> </td><td>" + company_name() + "</td><td></td><td>" + ship_companyname() + "</td></tr>";
        text += "<tr><td><b>Address:</b> </td><td>" + address() + "</td><td></td><td>" + ship_address() + "</td></tr>";
        text += "<tr><td><b>City:</b> </td><td>" + city() + "</td><td></td><td>" + ship_city() + "</td></tr>";
        text += "<tr><td><b>Province:</b> </td><td>" + province() + "</td><td></td><td>" + ship_province() + "</td></tr>";
        text += "<tr><td><b>Postal:</b> </td><td>" + postal() + "</td><td></td><td>" + ship_postal() + "</td></tr>";
        text += "<tr><td><b>Contact:</b> </td><td>" + contact() + "</td><td></td><td>" + ship_contact() + "</td></tr>";
        text += "<tr><td><b>Phone:</b> </td><td>" + phone() + "</td><td></td><td>" + ship_phone() + "</td></tr>";
    } else {
        sel = document.getElementById("shipto_delivery_type");    
        text += "<tr><td><b>Company:</b> </td><td>" + company_name() + "</td><td></td><td>" + sel.value + "</td></tr>";
        text += "<tr><td><b>Address:</b> </td><td>" + address() + "</td><td colspan='2'></td></tr>";
        text += "<tr><td><b>City:</b> </td><td>" + city() + "</td><td colspan='2'></td></tr>";
        text += "<tr><td><b>Province:</b> </td><td>" + province() + "</td><td colspan='2'></td></tr>";
        text += "<tr><td><b>Postal:</b> </td><td>" + postal() + "</td><td colspan='2'></td></tr>";
        text += "<tr><td><b>Contact:</b> </td><td>" + contact() + "</td><td colspan='2'></td></tr>";
        text += "<tr><td><b>Phone:</b> </td><td>" + phone() + "</td><td></td><td>" + ship_phone() + "</td></tr>";
    }    
    text += "<tr><td><b>Email:</b></td><td>" + email()+ "</td><td colspan='2'></td></tr>";
    //text += "<tr><td>number: " + number()+ "</td><td colspan='2'></td></tr>";
   
     for (var i = 0; i < wells.length; i++) {
       text += "<tr><td colspan='4'><hr><font size='4'><b>************Well " + (i + 1) + "************</b></font></td></tr>";
       text += "<tr><td colspan='4'>" + wells[i].toString() + "</td></tr>";
   }
    
	text += "<tr><td colspan='4'><hr></td></tr>";
    text += "<tr><td valign='top'><b>Instructions:</b> </td><td colspan='3'>" + instructions()+ "</td></tr>";
    text += "<tr><td><b>Date:</b> </td><td colspan='3'> " +  date() + "</td></tr>";
    text += "<tr><td><b>Invoice:</b> </td><td colspan='3'>" + document.getElementById(getRadioCheckedId("invoice")).value + "</td></tr>";
    text += "<tr><td><b>cc Email:</b> </td><td colspan='3'> " +  ccEmail() + "</td></tr>";

    return text;
}

function preview_order()
{
    save_well();
    window.open("order_show.aspx", "ORDER", "", false);  
}

function back_to_order()
{
    var em = document.getElementById("output_form");
    em.style.display = "none";    
    var em = document.getElementById("input_form");
    em.style.display = "inline";
}

function form_submit()
{
    save_well();
    
    if (company_name() == "") {
        alert("Company Name must be supplied.");
        return;
    } else if (phone() == "") {
        alert("Phone number must be supplied.");
        return;
    }
    document.getElementById("order_text").value = send_preview_to_output_form();
    document.forms[0].submit();
    clear_well_from_page();
    wells = null;
    clearRadioCheckedId("invoice");
}

function return_from_submit(result)
{
    alert(result.value);
}
