﻿(function ($) {

    $.fn.solapar = function (options, name, params) {

        //Devuelvo la instancia del contexto.
        return $(this).each(function () {

            //Referencias
            var _this = $(this),
            //Otras variables
            seleccionar = function (eq, evitarOnSelect) {
                _this.children().filter(":not(" + options.cancelar + ")").hide().filter(":eq(" + eq + ")").show();
                if (options.navegacion)
                    options.navegacion.children().removeClass("seleccionado").filter(":eq(" + eq + ")").addClass("seleccionado");
                if (options.onSelect && !evitarOnSelect)
                    options.onSelect(eq);
                if (options.seguimiento)
                    options.seguimiento.val(eq);
            };

            if (options == "fn") {
                options = _this.data("optionsSolapar");
                if (options == undefined) //Si se llamo a una funcion y todavia no se creo, lo creo con las opciones por defecto
                    _this.solapar();
                options = _this.data("optionsSolapar");
                if (name == "seleccionar") {
                    return seleccionar.call(_this, params);
                }
                else {
                    return null;
                }
            }
            else if (_this.data("optionsSolapar") != undefined) {
                return false; //Si se llamo para crearse y todavia ya se habia creado lo salteo
            }

            //Opciones por defecto.
            options = $.extend({
                navegacion: null, //Elementos que al clickear se deba seleccionar el corresponediente contenido
                selectedIndex: 0, //El index del contenido que debe iniciar seleccionado
                seguimiento: null, //Un input donde se quiera guardar el id del contenido seleccionado
                onSelect: null,
                cancelar: ":not(*)",
                inhabilitarNavegacion: ":not(*)"
            }, options);

            seleccionar.call(_this, options.selectedIndex, true);

            if (options.navegacion) {
                options.navegacion.children().click(function () {
                    var newIndex = options.navegacion.children().index($(this));
                    if (!$(this).is(options.inhabilitarNavegacion) && newIndex != options.navegacion.children().index(options.navegacion.children().filter(".seleccionado")))
                        seleccionar.call(_this, newIndex);
                    return false;
                });
            }

            _this.data("optionsSolapar", options);

        });

    };

})(jQuery);
