/**
 * VMF dfield module - dynamic form field population.
 * @author Tim Wong (timwong@vmware.com)
 */
(function($){

    $.fn.dfield = function(options){
        // Extend the default settings with user defined options
        var settings = $.extend({}, $.fn.dfield.defaults, options);
        // Apply the following code to each element matched by the selectors.
        return this.each(function(){
            var $this = $(this);
            // Use the inline field in the HTML code if availabe
            settings.field = $this.attr("field") || settings.field;
            // Use the inline URL in the HTML code if available
            settings.url = (settings.url + settings.field + ".js");
            // Delegate to the selectElm builder
            $.fn.dfield.selectElm.build.call(this, settings);
        });
    }
    
    // This is the constructor for the HTMLSelectElement
    $.fn.dfield.selectElm = function(){
        /**
         * Getting the Data via a JSONP getScript call.
         * @param {Object} settings The current field settings with URL and 
         */
        var getData = function(settings){
            
            $.ajax({
                cache: settings.toCacheAjax,
                dataType: 'script',
                url: settings.url,
                success: function(){
                    var data = vmf.dfield.cache[settings.field];
                    var html = [];
                    var row, lbl, val, isStr = null;
                    for (var i = 0; i < data.length; i++) {
                        row = data[i];
                        // check whether the data is string (i.e., ["value1", "value2"]
                        // or object (i.e., [{label:"lbl1",value:"val1"},{label:"lbl2"}]
                        isStr = (!row.label);
                        val = (isStr ? row : (row.value ? row.value : row.label));
                        lbl = (isStr ? row : row.label);
                        html.push("<option " + (val == settings.value ? " selected='selected'" : "") + " value='" + val + "'>" + lbl + "</option>");
                    }
                    settings.node.empty().append($(html.join("")));
                    if(settings.success){
                        settings.success();
                    }
                }
            });
        };
        
        return {
            defaults: {
                loadingContent: "loading ...",
                loadingCss: {},
                loadingAttrs: {}
            },
            build: function(settings){
                var $this = $(this);
                // First, extend the settings
                $.extend(settings, $.fn.dfield.selectElm.defaults);
                // Show the loading status 
                var $loadOpt = $('<option/>').attr(settings.loadingAttrs).css(settings.loadingCss).html(settings.loadingContent);
                $this.empty().append($loadOpt);
                
                // Save the current node for the callback function to use
                settings.node = $this;
                if (null == vmf.dfield.cache[settings.field]) {
                    getData(settings);
                }
                $this.change(function(){
                    settings.onChange.call(this, settings);
                });
            }
        };
    }();
    
    // module default setting
    $.fn.dfield.defaults = {
        url: 'http://www.vmware.com/files/include/module/dfield/data/', // The URL for fetching the data
        value: '', // The pre-selected value,
        field: '', // The Field to load,
        toCacheAjax: true,
        onChange: function(settings){
        }
    };
    
})(jQuery);

// The VMF wrapper
vmf.dfield = function($){
    return {
        build: function(id, config){
            $("#" + id).dfield(config);
        },
        cache: [],
        defaults:function(config){
            $.extend($.fn.dfield.defaults, config);
        }
    };
}(jQuery);
