﻿//-------------------- livePanel.js

function LivePanel(panelName, formName, url, options) {
    this.serializeSelector  = "form[name='" + formName + "'], :input[name^='" + formName + "_']";
    this.panel              = document.getElementById(panelName);
    this.options            = options;
    this.url = url;
    if (jQuery("form[name = '" + formName + "']").length == 1) {

        this.serialize = function () {
            return jQuery("form[name = '" + formName + "']").serialize();
        }

    } else {

        var prefix;
        if (jQuery("form :input[name*='_" + formName + "_']").length > 0) {
            var name = jQuery("form :input[name*='_" + formName + "_']")[0].name;
            prefix = name.substring(0, name.indexOf('_' + formName + '_')) + '_' + formName + '_';
        } else {
            prefix = formName + '_';
        }

        this.serialize = function () {
            var params = jQuery("form input[name='instance'], form :input[name^='" + prefix + "']").serializeArray();
            params = jQuery.map(params, function (kv) { return { name: kv.name.replace(prefix, ""), value: kv.value} });
            return jQuery.param(params);
        }

    }
}

LivePanel.prototype = {

    update: function(query, callback) {

        // call LivePanel_onUpdate "event" in calling page
        if (typeof (window.LivePanel_onUpdate) == 'function') {
            window.LivePanel_onUpdate(this);
        }

        query = (!this.options.requestParameters ? '' : this.options.requestParameters.join('&') + '&') +
                (!query || query == '' ? '' : query + '&') +
                this.serialize();

        var thisObj = this;
        if (typeof (callback) == 'function') {
            fn = function(data, textStatus) { thisObj.ajaxUpdate(data, textStatus); callback(this, data, textStatus); };
        } else {
            fn = function(data, textStatus) { thisObj.ajaxUpdate(data, textStatus); };
        }

        jQuery.post(this.url, query, fn, "html");

    },

    ajaxUpdate: function(data, textStatus) {
        this.panel.innerHTML = data;
        var x = this.panel.getElementsByTagName("script");
        for (var i = 0; i < x.length; i++) {
            eval(x[i].text);
        }

        // call LivePanel_onUpdate "event" in calling page
        if (typeof (window.LivePanel_onUpdateComplete) == 'function') {
            window.LivePanel_onUpdateComplete(this, data);
        }
    }

};



