/*
 * Copyright (c) 2012 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*global document, window, App, console, alert*/

/**
 * This file acts as a loader for the application and its dependencies.
 *
 * First, the 'app.js' script is loaded .
 * Then, scripts defined in 'app.requires' are loaded.
 * Finally, the app is initialised - the app is instantiated ('app = new App()')
 * and 'app.init()' is called.
 */

var app = null;

(function strict() { // strict mode wrapper
    'use strict';

    ({
        /**
         * Callback for getting script events.
         * @type {{onLoad: function, onError: function}}
         */
        callbacks: {
            onLoad: null,
            onError: null
        },

        /**
         * Loads and evals scripts asynchronous to html file.
         * @param {string} url
         * @return {Object}
         */
        getScript: function getScript(url) {
            var req = new window.XMLHttpRequest(),
                async = false,
                script = null,
                callbacks = this.callbacks;

            if (url === null) {
                console.error('Url is empty, please provide correct url.');
                return;
            }

            req.addEventListener('load', function load() {
                script = document.createElement('script');

                script.text = req.responseText;
                document.head.appendChild(script)
                    .parentNode.removeChild(script);
                if (typeof callbacks.onLoad === 'function') {
                    callbacks.onLoad();
                }
            }, false);

            req.addEventListener('error', function error() {
                if (typeof callbacks.onLoad === 'function') {
                    callbacks.onError({message: url});
                }
            }, false);

            req.open('GET', url, async);
            req.send();
            return this;
        },

        /**
         * Loader init - loads the App constructor.
         */
        init: function init() {
            var self = this;

            this.callbacks.onLoad = function onAppLoaded() {
                // once the app is loaded, create the app object
                // and load the libraries
                app = new App();
                self.loadLibs();
            };
            this.callbacks.onError = this.onGetScriptError;
            this.getScript('js/app.js');
        },

        /**
         * Loads dependencies.
         */
        loadLibs: function loadLibs() {
            var req = app.requires,
                reqLen = req.length,
                self = this,
                loadedCount = 0,
                i = 0;
            function onDone() {
                loadedCount += 1;
                if (loadedCount >= reqLen) {
                    // All dependencies are loaded - initialise the app
                    app.init();
                }
            }
            if (Array.isArray(app.requires)) {
                self.callbacks.onLoad = onDone;
                self.callbacks.onError = self.onGetScriptError;
                for (i = 0; i < reqLen; i += 1) {
                    self.getScript(req[i]);
                }
            }
        },

        /**
         * Handles ajax errors.
         */
        onGetScriptError: function onGetScriptError(e) {
            alert('An error occurred: ' + e.message);
        }
    }).init(); // run the loader

}());
