$(function() {

    var originalData = {
        show_editor: false,
        container: "preview"
    };

    var userData = {
        bins: [
            {
                type: "ResourceList",
                title: "Resource List",
                list: [
                    {
                        title: "IRI",
                        url: "http://www.iri.centrepompidou.fr/",
                        image: "http://www.iri.centrepompidou.fr/wp-content/themes/IRI-Theme/images/logo-iri-petit_fr_fr.png",
                        description: "Institut de Recherche et d'Innovation"
                    }
                ]
            }
        ],
        search: [
            {
                type: "Wikipedia",
                lang: "en"
            }
        ]
    };

    function getNormalizedHtml(jqsel) {
        return jqsel.html().replace(/[\r\n]/gm,' ').replace(/\s{2,}/g,' ').replace(/(^\s+|\s+$)/g,'');
    }

    var searchEngineTemplate = getNormalizedHtml($(".search-engine-list"));

    $(".search-engine-list").empty().sortable();

    var resourceTemplate = getNormalizedHtml($(".resource-list"));

    $(".resource-list").empty();

    var binTemplate = getNormalizedHtml($(".bin-list"));

    $(".bin-list").empty().sortable();

    function addSearchEngine(data, editMode) {

        $(".item").removeClass("item-editing");

        var element = $(searchEngineTemplate),
            allfields = element.find(".edit-value"),
            typefield = element.find(".search-engine-type .edit-value"),
            typedisplay = element.find(".search-engine-type .display-value"),
            langsection = element.find(".search-engine-language"),
            langfield = element.find(".search-engine-language .edit-value"),
            langdisplay = element.find(".search-engine-language .display-value");
        element.data("userdata",data);

        if (editMode) {
            element.addClass("item-editing");
        }

        var onChange = function() {

            data.type = typefield.val();
            typedisplay.text(typefield.find("[value=" + data.type + "]").text());

            if (data.type === "Wikipedia") {
                data.lang = langfield.val() || "en";
                langdisplay.text(langfield.find("[value=" + data.lang + "]").text());
                langsection.show();
            } else {
                delete data.lang;
                langsection.hide();
            }
        };

        typefield.val(data.type);

        if (data.type === "Wikipedia") {
            langfield.val(data.lang || "en");
        }

        allfields.on("keyup paste change", onChange);

        onChange();

        element.click(function() {
            $(".item").removeClass("item-editing");
            element.addClass("item-editing");
            return false;
        });
        element.find(".remove-item").click(function() {
            element.remove();
            return false;
        });

        $(".search-engine-list").append(element);
    }

    function addBin(data, editMode) {

        $(".item").removeClass("item-editing");

        var element = $(binTemplate),
            allfields = element.find(".edit-value"),
            typefield = element.find(".bin-type .edit-value"),
            typedisplay = element.find(".bin-type .display-value"),
            langsection = element.find(".bin-language"),
            langfield = langsection.find(".edit-value"),
            langdisplay = langsection.find(".display-value"),
            ldtsection = element.find(".ldt-options"),
            ldttypefield = element.find(".bin-ldt-type .edit-value"),
            ldttypedisplay = element.find(".bin-ldt-type .display-value"),
            ldtpffield = element.find(".bin-ldt-platform .edit-value"),
            ldtpfdisplay = element.find(".bin-ldt-platform .display-value"),
            ldtprojsection = element.find(".bin-ldt-project"),
            ldtprojfield = ldtprojsection.find(".edit-value"),
            ldtprojdisplay = ldtprojsection.find(".display-value"),
            kwsection = element.find(".bin-keyword"),
            kwfield = kwsection.find(".edit-value"),
            kwdisplay = kwsection.find(".display-value"),
            ressection = element.find(".bin-resources"),
            titlefield = element.find(".bin-title .edit-value"),
            titledisplay = element.find(".bin-title .display-value"),
            reslist = element.find(".resource-list");

        reslist.sortable({
            stop: updateListData
        });

        element.data("userdata",data);

        if (editMode) {
            element.addClass("item-editing");
        }

        var onChange = function() {

            data.type = typefield.val();
            typedisplay.text(typefield.find("[value=" + data.type + "]").text());

            if (data.type === "Wikipedia") {
                data.lang = langfield.val() || "en";
                langdisplay.text(langfield.find("[value=" + data.lang + "]").text());
                langsection.show();
            } else {
                delete data.lang;
                langsection.hide();
            }

            if (data.type === "Ldt") {
                ldtsection.show();
                data.ldt_type = ldttypefield.val() || "Results";
                ldttypedisplay.text(ldttypefield.find("[value=" + data.ldt_type + "]").text());

                data.ldt_platform = ldtpffield.val() || ldtpffield.val("http://ldt.iri.centrepompidou.fr/").val();
                ldtpfdisplay.text(data.ldt_platform);

                if (data.ldt_type === "Project") {
                    data.project_id = ldtprojfield.val();
                    ldtprojdisplay.text(data.ldt_project);
                    ldtprojsection.show();
                } else {
                    delete data.ldt_project;
                    ldtprojsection.hide();
                }

            } else {
                delete data.ldt_type;
                delete data.project_id;
                delete data.ldt_platform;
                ldtsection.hide();
            }

            if (data.type === "Wikipedia" || (data.type === "Ldt" && data.ldt_type === "Results")) {
                data.search = kwfield.val();
                kwdisplay.text(data.search);
                kwsection.show();
            } else {
                delete data.search;
                kwsection.hide();
            }

            if (data.type === "ResourceList") {
                data.title = titlefield.val() || titlefield.val("Untitled Resource List").val();
                titledisplay.text(data.title);
                ressection.show();
            } else {
                ressection.hide();
            }

            updateListData();

        };

        var updateListData = function() {
            if (data.type === "ResourceList") {
                data.list = Array.prototype.slice.call(
                    reslist.find(".resource").map(function(){return $(this).data("userdata");})
                );
            } else {
                delete data.list;
            }
        };

        var addResource = function(resdata, editmode) {

            var resel = $(resourceTemplate),
                all_fields = resel.find(".edit-value"),
                title_field = resel.find(".resource-title .edit-value"),
                title_text = resel.find(".resource-title .display-value"),
                url_field = resel.find(".resource-url .edit-value"),
                url_text = resel.find(".resource-url .display-value"),
                description_field = resel.find(".resource-description .edit-value"),
                description_text = resel.find(".resource-description .display-value"),
                image_field = resel.find(".resource-image .edit-value"),
                image_text = resel.find(".resource-image .display-value");

            resel.data("userdata",resdata);

            if (editmode) {
                resel.addClass("resource-editing");
            }

            var onResourceChange = function() {

                resdata.title = title_field.val();
                title_text.text(resdata.title);

                resdata.description = description_field.val();
                description_text.text(resdata.description);

                resdata.url = url_field.val();
                url_text.text(resdata.url);

                resdata.image = image_field.val();
                image_text.text(resdata.image);

                updateListData();

            };

            title_field.val( resdata.title || "" );
            url_field.val( resdata.url || "" );
            description_field.val( resdata.description || "" );
            image_field.val( resdata.image || "" );

            all_fields.on("keyup paste change", onResourceChange);

            onResourceChange();

            resel.find(".remove-item").click(function() {
                resel.remove();
                updateListData();
                return false;
            });

            resel.click(function() {
                $(".resource").removeClass("resource-editing");
                resel.addClass("resource-editing");
                return false;
            });

            reslist.append(resel);
        };

        if (data.list) {
            data.list.forEach(addResource);
        }

        typefield.val(data.type);

        if (data.type === "Wikipedia") {
            langfield.val(data.lang || "en");
        }

        if (data.type === "Ldt") {
            ldttypefield.val(data.ldt_type || "Results");
            ldtpffield.val(data.ldt_platform || "http://ldt.iri.centrepompidou.fr/");

            if (data.ldt_type === "Project") {
                ldtprojfield.val(data.ldt_project);
            }

        }

        if (data.type === "Wikipedia" || (data.type === "Ldt" && data.ldt_type === "Results")) {
            kwfield.val(data.search || "");
        }

        if (data.type === "ResourceList") {
            titlefield.val(data.title || "Untitled Resource List");
        }

        allfields.on("keyup paste change", onChange);

        onChange();

        element.click(function() {
            $(".item").removeClass("item-editing");
            element.addClass("item-editing");
            return false;
        });
        element.find(".remove-item").click(function() {
            element.remove();
            return false;
        });
        element.find(".add-resource").click(function() {
            addResource({"title": "New Resource"},true);
            return false;
        });

        $(".bin-list").append(element);

    }


    userData.search.forEach(function(data) {
        addSearchEngine(data,false);
    });
    userData.bins.forEach(function(data) {
        addBin(data,false);
    });

    $(".add-search-engine").click(function() {
        addSearchEngine({
            type: "Wikipedia",
            lang: "en"
        }, true);
        return false;
    });

    $(".add-bin").click(function() {
        addBin({
            type: "Wikipedia",
            lang: "en",
            search: ""
        }, true);
        return false;
    });

    $(".update-preview").click(function() {
        userData.search = Array.prototype.slice.call(
            $(".search-engine").map(function(){return $(this).data("userdata");})
        );
        userData.bins = Array.prototype.slice.call(
            $(".bin").map(function(){return $(this).data("userdata");})
        );
        new Rkns.Renkan(_.extend({}, originalData, userData));

    });

    new Rkns.Renkan(_.extend({}, originalData, userData));

});
