#define NO_PANEL_CODE

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using ScriptCallbacks.BusinessObjects;
using System.Globalization;
using Westwind.Tools;
using System.Threading;
using Westwind.Globlization.Data;
using System.Data.SqlClient;
using Westwind.Globalization;

public partial class CustomerList : System.Web.UI.Page
{
    protected busCustomer Customer = null;

    /// <summary>
    /// Override to force to US Dollar
    /// </summary>
    protected override void InitializeCulture()
    {
        base.InitializeCulture();
        
       Thread.CurrentThread.CurrentCulture  = CultureInfo.CurrentCulture.Clone() as CultureInfo;
       Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol = "$";
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        this.Customer = new busCustomer();
        this.BindCustomerList();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack && this.lstCustomers.Items.Count > 0)
        {
            // *** Bind the first item on first load explicitly
            this.lstCustomers.SelectedValue = this.lstCustomers.Items[0].Value;
            this.BindCustomerInfo(this.lstCustomers.Items[0].Value);
        }
    }

    #region  Handle SelectedValue with OnPreRender and LoadViewState method overloads - messy but required if you turn ViewState off on the list
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        this.ViewState["lstCustomers_SelectedValue"] = this.lstCustomers.SelectedValue;
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);

        string Val = this.ViewState["lstCustomers_SelectedValue"] as string;
        if (Val != null)
            this.lstCustomers.SelectedValue = Val;
    }
    #endregion

    protected void lstCustomers_SelectedIndexChanged(object sender, EventArgs e)
    {
        string CustomerId = this.lstCustomers.SelectedValue;
        this.BindCustomerInfo(this.lstCustomers.SelectedValue);
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        this.SaveCustomer();    

        // *** Reselect item
        int Selected = this.lstCustomers.SelectedIndex;

        // *** Reload and bind Customer List
        // *** if the Company has changed
        this.BindCustomerList();

        this.lstCustomers.SelectedIndex = Selected;
    }

    public void BindCustomerInfo(string CustomerId)
    {
        // Load the customer object and Entity member
        if (!this.Customer.Load(CustomerId))
            this.Customer.New();

        // *** Rebind only the Panel! Don't bind whole form
        // *** or there will be problems with the List selectedvalue
        this.CustomerInfoPanel.DataBind();

        this.BindInvoiceList(CustomerId);
    }


    public void BindCustomerList()
    {
        if (this.Customer.GetCustomerList() < 0)
        {
            this.txtCompany.Text = this.Customer.ErrorMessage;
            this.txtAddress.Text = Environment.UserName;
            return;
        }

        this.lstCustomers.DataSource = Customer.DataSet.Tables["TCustomerList"];
        this.lstCustomers.DataValueField = "CustomerId";
        this.lstCustomers.DataTextField = "CompanyName";
        this.lstCustomers.DataBind();
    }

    protected void BindInvoiceList(string CustomerId)
    {
        if (!this.dgOrders.Visible)
            return;
        
        busInvoice Invoice = new busInvoice();
        if (Invoice.GetInvoicesForCustomer(CustomerId) < 0)
        {
            this.ErrorDisplay.ShowError(Invoice.ErrorMessage);
            return;
        }

        this.dgOrders.DataSource = Invoice.DataSet.Tables["TCustomerInvoiceList"];

        // *** Calculate the total to display in the footer
        decimal Totals = 0.00M;
        foreach (DataRow dr in Invoice.DataSet.Tables["TCustomerInvoiceList"].Rows)
        {
            Totals += (decimal)dr["OrderTotal"];
        }

        this.dgOrders.Columns[1].FooterText = this.GetLocalResourceObject("TotalForInvoices") as string;
        this.dgOrders.Columns[2].FooterText = string.Format("{0:c}", Totals);

        this.dgOrders.DataBind();
    }

    /// <summary>
    /// Demonstrates using POSTback form vars
    /// </summary>
    /// <param name="CustomerId"></param>
    /// <returns></returns>
    public bool SaveCustomer()
    {
        string CustomerId =  this.lstCustomers.SelectedValue;

        this.Customer = new busCustomer();

        if (CustomerId == null)
            throw new ApplicationException("Invalid CustomerId");
        
        if (CustomerId == "")
        {
            if (!Customer.New())
                throw new ApplicationException("Couldn't create new customer.");
        }
        else
        {
            if (!Customer.Load(CustomerId))
                throw new ApplicationException("Couldn't load customer");
        }

        // *** Pick up values that were posted back from the
        // *** the client callback
        Customer.Entity.Contactname = this.txtContactName.Text;
        Customer.Entity.Companyname = this.txtCompany.Text;
        Customer.Entity.Address = this.txtAddress.Text;
        Customer.Entity.City = this.txtCity.Text;
        Customer.Entity.Entered = this.txtEntered.SelectedDate;

        if (!Customer.Validate())
            throw new ApplicationException(Customer.ValidationErrors.ToString());
  
        if (!Customer.Save())
            throw new Exception(Customer.ErrorMessage);

        this.ErrorDisplay.ShowMessage("Customer Saved");

        return true;
    }

    /// <summary>
    /// For the demo allow restoring the database
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lnkReloadData_Click(object sender, EventArgs e)
    {

        wwDbResourceDataManager manager = new wwDbResourceDataManager();
        if (!manager.RestoreBackupTable("Localizations_Backup") )
            this.ErrorDisplay.ShowError(manager.ErrorMessage);
        else
            this.ErrorDisplay.ShowMessage("Localization backup restored.");

    }
}
