'use strict'

var IstexWidget = function() {};

IstexWidget.prototype = {
    injectHTML: function() {

        var searchWidget = document.getElementById('istex-widget-search');
        searchWidget.setAttribute('class', 'container');
        searchWidget.setAttribute('ng-controller', 'istexWidgetCtrl');
        var resultsWidget = document.getElementById('istex-widget-results');
        resultsWidget.setAttribute('ng-controller', 'istexWidgetCtrl');
        addHtml("istex-widget-search", "http://caron.ads.intra.inist.fr:53390/html/part_search.html");
        addHtml("istex-widget-results", "http://caron.ads.intra.inist.fr:53390/html/part_results.html");
        //addHtml("istex-widget-facets", "http://caron.ads.intra.inist.fr:53390/html/part_facets.html");

    },

    injectCSS: function() {
        addCSS("//caron.ads.intra.inist.fr:53390/css/part_search.css");
        addCSS("//caron.ads.intra.inist.fr:53390/css/part_results.css");
        addCSS("//caron.ads.intra.inist.fr:53390/css/part_facets.css");
        addCSS("//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css");
    },

    injectJS: function() {
        addJS([
            "//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js",
            "//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js",
            "//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js",
            "//caron.ads.intra.inist.fr:53390/js/app.js"
        ]);
    }
};

var addJS = function(jsLinks) {
    var body = document.body;
    var js = document.createElement("script");
    js.src = jsLinks.shift();
    js.type = "text/javascript";
    if (jsLinks.length > 0) {
        js.onload = function() {
            addJS(jsLinks);
            body.appendChild(js);
        };
    };
    body.appendChild(js);
};

var addCSS = function(cssLink) {
    var header = document.head;
    var customCss = document.createElement("link");
    customCss.href = cssLink;
    customCss.rel = "stylesheet";
    customCss.type = "text/css";
    header.appendChild(customCss);
};

var addHtml = function(id, htmlLink) {
    var searchWidget = document.getElementById(id);
    var request = new XMLHttpRequest();
    request.open("GET", htmlLink);
    request.onload = function() {
        searchWidget.innerHTML = request.responseText;
    };
    request.send();
};

var istexWidget = new IstexWidget();
istexWidget.injectHTML();
istexWidget.injectCSS();
istexWidget.injectJS();