/**
 * 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(scriptResponse){
                    // evaluate the script if the field is not in the cache
                    if (!vmf.dfield.cache[settings.field]) { eval(scriptResponse); }
                    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 !== undefined && row.value !== null) ? 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);
                });
            }
        };
    }();
    // set path to load files from
    /* TODO: this code can be removed AFTER the SAT module has been released to production */
    if (vmf != undefined && vmf !== null && (vmf.hostname == undefined || vmf.hostname === null)) {
        vmf.hostname = window.location.protocol+"//www.vmware.com";
        switch (window.location.hostname) {
            case 'www.vmware.com':
            case 'downloads.vmware.com':
                vmf.hostname = window.location.protocol+"//www.vmware.com";
                break;
            case 'phnx-portal-stage.vmware.com':
            case 'downloads-stage.vmware.com':
                vmf.hostname = window.location.protocol+"//phnx-portal-stage.vmware.com";
                break;
            case 'portal-vmwperf.vmware.com':
            case 'downloads-qa.vmware.com':
                vmf.hostname = window.location.protocol+"//portal-vmwperf.vmware.com";
                break;
            case 'newcastle.vmware.com':
            case 'wwwa-dev-sso-1.vmware.com':
                /* lmpimage2 does not support https */
                vmf.hostname = "http://lmpimage2.vmware.com";
                break;
            case 'serafina.vmware.com':
                vmf.hostname = window.location.protocol+"//serafina-home.vmware.com";
                break;
            default:
                vmf.hostname = window.location.protocol+"//www.vmware.com";
                break;
        }
    }
    // module default setting
    $.fn.dfield.defaults = {
        url: vmf.hostname+"/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);

