/**
 * @author DJ Perez <danieljordi@bab-soft.com>
 * @version 1.0
 *
 * @{inherit doc}
 *
 * Options:
 * - addElementSelectors -> array of add element selectors
 * - dataSelectors -> array of data selectors, must match with number of selectors because
 * the selectors[0] add's the dataSelectors[0]
 * - Context -> the context for find selectors
 *
 */
var MultiplePrototypeFormCollection = (function() {
    'use strict';

    function MultiplePrototypeFormCollection(options) {

        this.addElementSelectors = [];
        this.templates = [];
        this.dataSelectors = [];

        SimpleFormCollection.call(this, options);
    }

    MultiplePrototypeFormCollection.prototype = Object.create(SimpleFormCollection.prototype);

    MultiplePrototypeFormCollection.prototype.constructor = MultiplePrototypeFormCollection;

    /**
     * @returns {MultiplePrototypeFormCollection}
     * @private
     */
    MultiplePrototypeFormCollection.prototype._initCollectionEntryTemplate = function () {

        for(var i = 0; i < this.dataSelectors.length; i++) {
            this.templates.push($(this.collectionContainer).data(this.dataSelectors[i]));
            $(this.collectionContainer).removeAttr('data-'+this.dataSelectors[i]);
        }

        return this;
    };

    /**
     *
     * @returns {MultiplePrototypeFormCollection}
     * @private
     */
    MultiplePrototypeFormCollection.prototype._bindDOMEvents = function() {
        var _multiplePrototypeFormCollectionObject = this;

        $(_multiplePrototypeFormCollectionObject.addElementSelectors).each(function(index, value) {

            $(value, _multiplePrototypeFormCollectionObject.context).on('click', function(event) {
                event.preventDefault();

                _multiplePrototypeFormCollectionObject.template = _multiplePrototypeFormCollectionObject.templates[index];
                if (typeof MultiplePrototypeFormCollection.addCallback !== null && typeof _multiplePrototypeFormCollectionObject.addCallback !== 'undefined') {
                    _multiplePrototypeFormCollectionObject.addCallback();
                } else {
                    _multiplePrototypeFormCollectionObject.add();
                }
            });
        });

        return this;
    };

    return MultiplePrototypeFormCollection;
}());

$(function() {
    $.fn.MultiplePrototypeFormCollection = function(options) {

        $(this).each(function() {
            options['collectionContainer'] = $(this);

            $(this).data('multiple-collection', new MultiplePrototypeFormCollection(options));
        });

        return this;
    }
});