var feedbackOldOnload = window.onload;

window.onload = function()
{
    if (typeof feedbackOldOnload == 'function')
    {
         feedbackOldOnload();
    }

    window.feedbackInstance = new feedback();
    feedbackInstance.init();
}

feedback = function ()
{
    this.box = null;
    this.form = null;
    this.submitButton = null;
    this.fields = {};
}

feedback.prototype.init = function()
{

    this.box = document.getElementById('feedbackBox');
    if (!this.box)
    {
        return;
    }
    this.form = document.getElementById('feedbackForm');
    if (!this.form)
    {
        return;
    }
    this.submitButton = document.getElementById('feedbackSubmit');
    if (!this.submitButton)
    {
        return;
    }
    this.loadFields();
    this.setupBlockSubmit();
}


feedback.prototype.loadFields = function()
{
    var tags = ['input', 'textarea'];
    for (var i = 0; i < tags.length; i++)
    {
        var elements = this.form.getElementsByTagName( tags[i] );
        for (var j = 0; j < elements.length; j++)
        {
            var name = elements[j].name;
            this.fields[name] = elements[j];

        }
    }

}



feedback.prototype.setupBlockSubmit = function()
{
    // the block submit must come after validation,
    // so wait in loop till the validation script attaches itself
    // (the form's onsubmit handler gets set)

    this.form.currentOnSubmit =  this.form.onsubmit;

    if (typeof this.form.currentOnSubmit != 'function')
    {
        window.setTimeout( 'feedbackInstance.setupBlockSubmit();', 200 );
        return;
    }

    var script = this;
    this.form.onsubmit = function()
    {
        if (typeof this.currentOnSubmit == 'function')
        {
            var response = this.currentOnSubmit();
            if (response == false)
            {
                pasakasInstance.showLabelValues(this);
                return false;
            }
        }
        return script.submitFormAsBlock();
    }
}

feedback.prototype.submitFormAsBlock = function()
{
    this.submitButton.disabled = true; // prevent double posts
    Blocks.submitFormAsBlock(this.form, 'send', this.processFormResponse, this);
    return false; // prevent full page form submit
}

feedback.prototype.processFormResponse = function(xmlhttp, script)
{
    if (xmlhttp.readyState != 4)
    {
        return;
    }
    script.box.innerHTML = xmlhttp.responseText;
}

