var productsOldOnload = window.onload;
window.onload = function()
{

    if (typeof productsOldOnload == 'function')
    {
         productsOldOnload();
    }

    window.productsInstance = new products();
    productsInstance.init();

}

function products ()
{
    this.container = null;
    this.foodForm = null;
    this.catTypeSelect = null;
    this.foodTypeSelect = null;

    this.foodFormValues = null;
}

products.prototype.init = function()
{

    this.container = document.getElementById('foodFormBox');
    if (!this.container)
    {
        return;
    }

    // remove button
    var noScriptButton = document.getElementById('foodFormSubmit');
    if (noScriptButton)
    {
        noScriptButton.parentNode.removeChild(noScriptButton);
    }

    this.assignFormBehaviour();

}


products.prototype.assignFormBehaviour = function()
{
    this.foodForm = document.getElementById('foodForm');
    if (!this.foodForm)
    {
        return;
    }

    this.catTypeSelect = document.getElementById('cat_type');
    if (!this.catTypeSelect)
    {
        return;
    }

    this.foodTypeSelect = document.getElementById('food_type');
    if (!this.foodTypeSelect)
    {
        return;
    }


    this.catTypeSelect.onchange  = this.catTypeChanged;
    this.foodTypeSelect.onchange = this.foodTypeChanged;
}

products.prototype.catTypeChanged = function()
{
    // reset food type
    var inst = window.productsInstance;
    inst.foodTypeSelect.selectedIndex = 0;
    inst.submitForm(  inst  );
}

products.prototype.foodTypeChanged = function()
{
    var inst = window.productsInstance;
    inst.submitForm( inst );
}

products.prototype.submitForm = function( inst )
{
    inst.storeFormValues();
    Blocks.submitFormAsBlock(inst.foodForm, 'food_form', inst.handleResponse, inst);

}

products.prototype.handleResponse = function (xmlhttp, main)
{
    if (xmlhttp.readyState != 4)
    {
        return;
    }
    main.container.innerHTML = xmlhttp.responseText;
    main.assignFormBehaviour();
    main.restoreFormValues();
}

products.prototype.storeFormValues = function()
{
    this.foodFormValues = Forms.collectFormValues( this.foodForm );
}

products.prototype.restoreFormValues = function()
{
    Forms.restoreFormValues( this.foodForm, this.foodFormValues );
}

