var cloneEntity = {
    cookieKey: 'cloneData',
    pushData: function (name, value) {
        // get data
        var data = this.getData();

        // push
        data[name] = value;

        // set data
        $.cookie(this.cookieKey, data);
    },
    getData: function () {
        var data = $.cookie(this.cookieKey);
        if (typeof data == 'undefined') {
            data = {};
        }

        return data;
    },
    isFormElement: function (item) {
        if (typeof item.attr('name') != 'undefined') {
            return true;
        }
        return false;
    },
    collectData: function () {
        // prepare data
        var self = this;
        var form = $("form");

        // for inputs
        form.find('input').each(function () {
            var item = $(this);
            if (self.isFormElement(item) && item.attr('type') != 'hidden' && item.attr('type') != 'file') {
                self.pushData(item.attr('name'), item.val());
            }
        });

        // for textarea
        form.find('textarea').each(function () {
            var item = $(this);
            if (self.isFormElement(item)) {
                self.pushData(item.attr('name'), item.text());
            }
        });

        // for select
        form.find('select').each(function () {
            var item = $(this);
            if (self.isFormElement(item)) {
                self.pushData(item.attr('name'), item.val());
            }
        });
    },
    fillForm: function () {
        // prepare data
        var self = this;
        var form = $("form");

        // fill form
        $.each(this.getData(), function (name, value) {
            // prepare item
            var item = $("[name='" + name + "']");

            if (typeof item != 'undefined') {
                item.val(value);
            }

        });
    },
    getUrlQuery: function (key)
    {
        // prepare variables
        var vars = {};
        var hash;

        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1];
        }

        return (typeof vars[key] == 'undefined') ? '' : vars[key];
    },
    cloneAction: function () {
        var self = this;
        $('#clone-entity').click(function () {
            var button = $(this);

            // collect data
            self.collectData();

            // redirect
            window.location.href = button.data('href');

            return false;
        });
    },
    init: function () {
        this.cloneAction();

        if (this.getUrlQuery('is_cloning_entity') === 'true') {
            this.fillForm();
        }
    }
};

$(document).ready(function () {
    // prepare cookie config
    $.cookie.json = true;

    cloneEntity.init();
});