// Persistent form handling - pform.js

var Values_cache = new Object;
var Values;

function pvalue(name) {
    // we'll consider empty string to be the value of non-existing Value keys or any other sanity-checking condition.
    return (name && Values && Values[name]) ? Values[name] : '';
}

(function ($) {
    var defaultName = 'pform_values';

    $.getPFObj = function (name) {
        name = name || defaultName;
        //alert('got name: ' + name);

        //alert('looking for object in Values_cache');
        if (Values_cache[name]) {
            //alert('got it! short circuit!');
            return Values_cache[name];
        }

        var cookie_string = '';
        var chunks = $.cookie(name + '_chunks');
        if (chunks == undefined || !chunks.match(/^\d+$/)) {
            chunks = 0;
        }
        else {
            chunks = parseInt(chunks);
        }

        //alert('chunks: ' + chunks);

        if (chunks) {
            //alert('in chunked code path');
            for (var i = 1; i <= chunks; i++) {
                //alert ('processing chunk ' + i);
                var chunk_part = $.cookie(name + '_chunk_' + i);
                //alert ('chunk part: ' + chunk_part);
                cookie_string = cookie_string + chunk_part;
            }
        }
        else {
            cookie_string = $.cookie(name);
        }

        //alert('got cookie string: ' + cookie_string);

        var obj;
        if (cookie_string) {
            try {
                obj = $.secureEvalJSON(cookie_string);
            }
            catch (e) {
                //alert('Got exception trying to parse JSON!: ' + e);
                //alert('In FF this code worked; in Safari it returned the first two chunks as <null>; go figure...');
                //alert('raw cookie string was: ' + cookie_string);
            }
        }

        obj = obj || {};
        Values_cache[name] = obj;
        if (!Values && Values_cache[defaultName]) {
            //alert('setting up global Values namespace alias to Values_cache[' + defaultName + ']');
            Values = Values_cache[defaultName];
        }

        return obj;
    }

    $.setPFObj = function (obj, name) {
        //alert('not currently usable w/chunks');
        //$.cookie(name || defaultName, $.toJSON(obj));
    }
})(jQuery);

$(document).ready(function () {
    //alert('running document.ready!');
    $('form.persist').each(function(i,f) {
        // customize the form's cookie name by setting the form's data-pform-name attribute
        var cookie_name = $(f).data('pform-name');
        var cookie_form = $.getPFObj(cookie_name);

        //alert ($.toJSON(cookie_form));
        $(f).populate(
            cookie_form,
            { "phpNaming" : false }
        )
    })
});

