﻿// DEBUG
Debug = function() {

}

Debug.assert = function(expression, message) {
    if (!expression)
        throw message;
}

// NOTIFY
Notify = function() {
}

jQuery.extend(Notify.prototype, {
    notifyContainer: null,
    count: 0,
    closeNotificationUrl: null,
    init: function(closeNotificationUrl) {
        Debug.assert(closeNotificationUrl, "closeNotificationUrl cannot be null");
        this.closeNotificationUrl = closeNotificationUrl;
    },
    show: function(id, message, customCloseFunction) {
        Debug.assert(this.closeNotificationUrl, "Notifier has not been correctly initialized");
        if (!this.notifyContainer)
            this.notifyContainer = $("#notify-table");
        this.count++
        $('body').css("margin-top", this.count * 2.5 + "em");
        this.notifyContainer.append("<tr class='notify' id='notify--" + id + "' style='display:none'><td class='notify'>" + message + "</td><td class='notify-close'><a title='descartar esta notificaçao'>×</a></td></tr>");
        $("#notify--" + id).fadeIn("slow");
        var notifyCloseButton = $("#notify--" + id + " > .notify-close > a");

        var scope = this;

        notifyCloseButton.bind("click", function(e) {

            $("#notify--" + id).fadeOut("slow");
            scope.count--;

            $('body').css("margin-top", scope.count * 2.5 + "em");
            $.ajax({
                type: "POST",
                url: scope.closeNotificationUrl,
                data: "id=" + id,
                success: function(msg) {

                },
                error: function(msg) {
                    alert("algo deu errado: " + msg);
                }
            });

            if(customCloseFunction)
                customCloseFunction.call(this);
        });
    },
    showFirstTime: function() {
        var vFirstTimeNotificationCookieName = "userCanceledFirstTimeNotification";

        // primeiro eu preciso pegar se o usuário cancelou o popup
        var canceled = CookiesManager.readCookie(vFirstTimeNotificationCookieName);
        if(canceled == "true")
            return;
    
        function customButtonCloseClickHandler() {
            CookiesManager.createCookie(vFirstTimeNotificationCookieName, "true", 1);
        }

        this.show(0, "Primeira vez aqui? Conheça mais <a href='http://www.direitolivre.com.br/sobre.aspx'> sobre nós </a> e <a href='http://www.direitolivre.com.br/usuarios/login.aspx'> cadastre-se </a>", customButtonCloseClickHandler);
    }
});


// UpdateElementsAndScripts: atualiza vários elementos da página e executa scripts após um callback ajax
function UpdateElementsAndScripts(msg) {
    var data2 = msg.split("<\\>"); // separator
    var type = 0;
    var paramIdx = 0;
    var p0, p1;
    for (var idx in data2) {
        var item = data2[idx];
        if (type == 0) {
            // instrução que substitui o html de um elemento da tela, com dois argumentos: id, html
            if (item == "rep") type = 1;
            // instrução que executa um java-script, possui um parametro: script
            if (item == "js") type = 2;
        }
        if (type == 1) {
            if (paramIdx == 1) p0 = item;
            if (paramIdx == 2) p1 = item;
            paramIdx++;
            if (paramIdx == 3) {
                // agora podemos substituir um elemento pelo que veio do servidor
                $('#' + p0).replaceWith(p1);
                type = 0;
                paramIdx = 0;
            }
        }
        if (type == 2) {
            if (paramIdx == 1) p0 = item;
            paramIdx++;
            if (paramIdx == 2) {
                // agora podemos executar o script que veio junto do controle
                if (p0) eval(p0);
                type = 0;
                paramIdx = 0;
            }
        }
    }
}

function LivreAjaxPost(url, rm, cid, dataToSend) {
    if (dataToSend == undefined)
        dataToSend = {};
    dataToSend.RM = rm;
    dataToSend.CID = cid;
    $.ajax({
        type: "GET",
        url: url,
        // CID: indica que o data-source está sendo alterado, e que somente os controles afetados por ele, além dele mesmo devem ser atualizados
        // RM: indica o método de renderização, que pode ser UES = UpdateElementsAndScripts, US = UpdateScript, ou D = Default (renderiza toda a página).
        data: dataToSend,
        success: function(msg) {
            if (rm == "SU") {
                // msg deve conter instruções javascript capazes de atualizar
                // o conteúdo dos elementos da página, assim como as instâncias
                // de objetos que representam os elementos
                data = eval(msg);
            } else if (rm == "UES") {
                // msg deve conter uma lista de instruções que podem ser de
                // atualização dos elementos ou execução de scripts
                UpdateElementsAndScripts(msg);
            } else if (rm == "D") {
                // msg contém todo o html da página
                // por enquanto não será tratado!
            }
        },
        error: function(msg) {
            alert("something went wrong: " + msg);
        }
    });
}

// LivreDataSourceClient
LivreDataSourceClient = function(pgCnt, pgIdx, pgSize, prefix, id) {
    this.pgCnt = pgCnt;
    this.pgIdx = pgIdx;
    this.pgSize = pgSize;
    this.prefix = prefix;
    this.id = id;
}

jQuery.extend(LivreDataSourceClient.prototype, {
    pgCnt: 0,
    pgIdx: 0,
    pgSize: 0,
    prefix: null,
    id: null,
    rm: "UES", // método de renderização para ajax desse data-source

    init: function() {
        // este método é realmente necessário?
    },
    ajaxUpdate: function(url) {
        LivreAjaxPost(url, this.rm, this.id);
    },
    UpdateData: function(pgCnt, pgIdx, pgSize) {
        this.pgCnt = pgCnt;
        this.pgIdx = pgIdx;
        this.pgSize = pgSize;
    }
});

CookiesManager = function () {
    
}

CookiesManager.createCookie = function (name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

CookiesManager.readCookie = function (name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

CookiesManager.eraseCookie = function (name) {
    createCookie(name, "", -1);
}


