﻿(function ($) {

    var _views = {};
    var isInit = false;

    var methods = {
        init: function (views) {
            $.each(views, function (i, val) {
                DownloadView(val);
            });
            isInit = true;
        },
        get: function (name, data) {
            return this.each(function () {
                if (data != null) {
                    $(this).html(TemplateEngine.parse(_views[name], null, data));
                }
                else {
                    $(this).html(_views[name]);
                }
            });
        },
        contains: function (name) {
            return _views[name] != null;
        }
    };


    $.fn.viewManager = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.viewmanager');
        }
    };

    // private functions
    function DownloadView(view) {
        if (view.route != null) {
            $.get(view.route, null, function (ret) {
                _views[view.name] = ret;
                //Call completed callback;
                if (view.onLoad != null)
                    view.onLoad();
            });
        }
        if (view.content != null) {
            _views[view.name] = view.content;
        }

    };

    //  ...
    // end of closure
})(jQuery);
