if (typeof jQuery === 'undefined'){
    throw 'Framework jQuery nÃ£o carregado. O namespace Avanz exige este framework para funcionar corretamente.';
}

/**
 * Declarando o namespace Avanz
 *
 * @type Object
 * @author joao.paulo
 */
var Avanz = Avanz || {};

/**
 * DiretÃƒÂ³rio dos javascripts
 * @type {String}
 */
Avanz.ScriptsDirectory = '../lib/js';

/**
 * Retorna a URL base
 * @namespace Avanz
 * @static
 * @returns {String}
 */
Avanz.getBaseUrl = function(){
    var basePath = '';

    if (typeof baseUrl == 'string'){
        basePath = baseUrl;
    } else if (document.getElementsByTagName){
        var elems = document.getElementsByTagName('base');
        if (elems.length){
            basePath = elems[0].href + '/';
        }
    } else{
        var url = location.href;
        basePath = url.substring(0, url.indexOf('/', 14)) + '/';
    }

    return basePath;
};
/**
 * Exibe uma caixa de diÃ¯Â¿Â½logo
 * @param {Object} message
 * @param {String} title
 * @param {Function} callback
 * @param {String} buttonValue
 * @param {String} type
 * @namespace Avanz
 * @static
 * @returns void
 */
Avanz.messageBox = function(message, title, callback, buttonValue, type){
    title = title || 'Mensagem';
    buttonValue = buttonValue || 'OK';
    type = type || 'info';
    var icon = Avanz.ScriptsDirectory + '/Avanz/resources/' + type + '.gif';

    var html = '<div id="conteudo_alerta">'
                + '<h1>' + title + '</h1>'
                    + '<div id="icone_alerta"><img src="' + icon + '" alt="Ã?cone" />'
                    + '<div id="texto_alerta">' + message + '</div>'
                    + '<div id="form_alerta">'
                        + '<input type="button" class="submits pequeno" id="fechar_alerta" value="' + buttonValue + '" />'
                    + '</div>'
                + '</div>';
    try{
        //Tentamos importar o plugin blockUI
        Avanz.Import('jquery.blockUI');
        $.blockUI({
            message : '<div style="cursor:default;">' + html + '</div>'
        });

        $('#fechar_alerta').click(function(){            
            $.unblockUI();
            if(callback){
                try{
                    callback();
                } catch(ex){
                    alert("Um erro desconhecido aconteceu: "+ex+" | Contate o suporte.");
                }
            }
        });

    } catch(e){
        alert(title + ":\n" + message);
        if(callback){
            callback();
        }
    }
};
/**
 * Exibe uma caixa de confirmaÃ§Ã£o
 * @param {Object} message
 * @param {String} title
 * @param {Function} callback
 * @namespace Avanz
 * @static
 * @returns void
 * @author italo
 */
Avanz.confirmBox = function(message, title, callback){
    title = title || 'Mensagem';
    var icon = Avanz.ScriptsDirectory + '/Avanz/resources/help.gif';

    var html = '<div id="conteudo_alerta">'
                + '<h1>' + title + '</h1>'
                + '<div id="conteudo_alerta">'
                    + '<div id="icone_alerta"><img src="' + icon + '" alt="Ã?cone" />'
                    + '<div id="texto_alerta">' + message + '</div>'
                    + '<div id="form_alerta">'
                        + '<input type="button" class="submits pequeno" id="ok_alerta" value="OK" />'
                        + '<input type="button" class="submits pequeno" id="cancel_alerta" value="Cancelar" />'
                    + '</div>'
                + '</div>';

    try {
        //Tentamos importar o plugin blockUI

        Avanz.Import('jquery.blockUI');
        $.blockUI({
            message : '<div style="cursor:default;">' + html + '</div>'
        });
        $('#ok_alerta').live('click', function(){
            $.unblockUI();
            if (callback) {
                callback(true);
            }
        });

        $("#cancel_alerta").live('click', function(){
            $.unblockUI();
            if (callback) {
                callback(false);
            }
        });
    }catch(e){
        var response = confirm(title + "\n" + message);
        if (callback) {
           callback(response);
        }
    }

}

/**
 * Exibe uma caixa de texto (prompt do javascript)
 * @param {Object} message
 * @param {String} value
 * @param {String} title
 * @param {Function} callback
 * @namespace Avanz
 * @static
 * @returns void
 * @author italo
 */

Avanz.promptBox = function(message, value, title, callback){
    title = title || 'Mensagem';
    value = value || '';
    var icon = Avanz.ScriptsDirectory + '/Avanz/resources/help.gif';

    var html = '<h1>' + title + '</h1>'
                + '<div id="conteudo_alerta">'
                    + '<div id="icone_alerta"><img src="' + icon + '" alt="Ã?cone" />'
                    + '<div id="texto_alerta">' + message + '</div>'
                    + '<div id="form_alerta">'
                        + '<input type="text" id="input_alerta" value="' + value + '" />'
                        + '<input type="button" id="ok_alerta" value="OK" class="submits pequeno" />'
                        + '<input type="button" class="submits pequeno" id="cancel_alerta" value="Cancelar" />'
                    + '</div>'
                + '</div>';
    try {
        //Tentamos importar o plugin blockUI

        Avanz.Import('jquery.blockUI');
        $.blockUI({
            message : '<div style="cursor:default;">' + html + '</div>'
        });
        $("#ok_alerta").click(function(){
            $.unblockUI();
            if (callback) {
                callback($("#input_alerta").val());
            }
        });
        $("#cancel_alerta").click(function(){
            $.unblockUI();
            if (callback) {
                callback(false);
            }
        });
    }catch(e){
        var response = confirm(title + "\n" + message);
        if (callback) {
           callback(response);
        }
    }
}

/**
 * Exibe uma mensagem de erro amigÃ¯Â¿Â½vel para o usuÃ¯Â¿Â½rio
 * @param {Object} exception
 * @param {Function} callback
 * @namespace Avanz
 * @static
 * @returns {Object}
 */
Avanz.raiseError = function(exception, callback){
    var error, type;
    if (typeof exception == 'object'){
        if (exception instanceof Avanz.Exception){
            error = exception.getMessage();
            type = exception.getName();
        } else{
            if (exception.hasOwnProperty('message')){
                error = exception.message;
                type = exception.name;
            } else{
                error = exception;
                type = 'Um erro ocorreu';
            }
        }
    } else{
        error = exception;
        type = 'Um erro ocorreu';
    }

    Avanz.messageBox(error, type, callback);

    return exception;
};

/**
 * Importa um namespace
 *
 * @param {String} namespace
 * @param {String} type
 * @param {String} folder
 * @namespace Avanz
 * @static
 * @returns {Object}
 */
Avanz.Import = function(namespace, type, folder){

    /**
     * Armazena os namespaces jÃ¡ carregados
     * @private
     * @type Object
     */
    this._loadedNamespaces = this._loadedNamespaces || {};

    /**
     * Carrega uma folha de estilo
     * @param {String} url
     * @private
     */
    this._loadStylesheet = function(url){
        $('html head').append($('<link/>').attr({
            media: 'screen',
            rel: 'stylesheet',
            type: 'text/css',
            href: url
        }));
    };
    /**
     * Carrega um script. Nao foi utilizado o $.getScript pois precisamos
     * desabilitar a assicronicidade
     * @private
     * @param {String} url
     */
    this._loadScript = function(url){
        $.ajax({
            async: false,
            type: 'get',
            dataType: 'script',
            url: url,
            success: function(){
            //void
            },
            error: function(){
                throw 'Namespace ' + namespace + ' nÃ£o encontrado.';
            }
        });
    };

    var extension = type || 'js',
    pattern = namespace + '_' + extension,
    directory = folder || Avanz.ScriptsDirectory;

    if (!namespace){
        return this._loadedNamespaces;
    }

    // Para prevenir erros, carregamos o namespace somente uma vez
    if (typeof this._loadedNamespaces[pattern] !== 'undefined'){
        return this._loadedNamespaces[pattern];
    }

    var pieces = namespace.split('.'),
    // Nome da biblioteca
    library = pieces.shift(),
    url = this.getBaseUrl() + directory + '/' + library;

    for (var file in pieces){
        url += '/' + pieces[file];
    }

    url = url + '.' + extension;

    switch (extension){
        case 'css':
            this._loadStylesheet(url);
            break;
        default:
            this._loadScript(url);
    }

    this._loadedNamespaces[pattern] = {
        url: url,
        name: namespace,
        extension: extension
    };

    return this._loadedNamespaces;
};


function using(namespace, type){
    this.namesList = this.namesList || {};
    Avanz.Import(namespace, type);

    this.as = function(alias){
        if (namespace.split('.')[0].toLowerCase() == 'jquery'){
            throw new Error('NÃ£o Ã© possÃ­vel aplicar um alias em uma classe que nÃ£o pertenÃ§a ao namespace Avanz.');
        }

        var command = alias + ' = ' + namespace;

        if (this.namesList[alias] == namespace){
            return;
        }

        var exists = eval('typeof ' + alias);

        if (exists !== 'undefined'){
            throw new Error(alias + ' jÃ¡ estÃ¡ em uso (' + this.namesList[alias] + ')');
        }

        eval(command);

        this.namesList[alias] = namespace;
    };
    return this;
}
