﻿(function($) {
    // populates form elements with data from a JSON object that acts as a cache.
    // the JSON object should be named __ECOS_CACHE.
    // __ECOS_CACHE should be an array if objects with properties:
    //  1. id: an id used as the selector to find the matching form element if use_id is set.
    //  2. type: a class used to select matching form elements if #id is not found or use_id is cleared.
    //  3. value: the value to which the matching form element(s) should be set.
    $.fn.cache = function(options) {
        var settings = {
            'cache': {},
            'use_id': true
        };

        if (options) {
            $.extend(settings, options);
        }

        for (var i = 0; i < settings.cache.length; i++) {
            var id = settings.cache[i].id;
            var type = settings.cache[i].type;
            var value = settings.cache[i].value;

            var $ctrl;
            var selector = ':input.' + type;
            if (settings.use_id) {
                $ctrl = $('#' + id, this);
                if ($ctrl.length == 0) {
                    $ctrl = $(selector, this);
                }
            }
            else {
                $ctrl = $(selector, this);
            }

            $ctrl.each(function() {
                $this = $(this);

                // Compare the values of checkboxes and radio buttons with the
                // queue entry's value in case a match wasn't made on the id.
                if ($this.attr('type') == 'checkbox' || $this.attr('type') == 'radio') {
                    if ($this.val() == value) {
                        $this.attr('checked', 'checked');
                    }
                    else {
                        $this.removeAttr('checked');
                    }
                }
                else if ($this.is('select') && $this.val() != value) {
					if ($this.attr('multiple') && !$this.data('cleared')) {
						$('option:selected', $this).removeAttr('selected');
						$this.data('cleared', 1);
					}

                    $('option', $this).each(function(index, element) {
                        var $option = $(this);
                        if ($option.html() == value) {
                            $option.attr('selected', 'selected');
                            return false;
                        }
                    });
                }
                else {
                    $this.val(value);
                }
            });
        }

		$('select[multiple]').removeData('cleared');
        return this;
    };
})(jQuery);

