var Delrio = Delrio || {
    'window': {},
    'forms' : {},
    'actions' : {}
};

Drupal.behaviors.DelrioBuild = function(){
    Delrio.window.object = $("#window-response");

    var html = '<div class="window-loading">'
    + '<div class="messages status">Carregando...</div>'
    + '</div>'
    + '<div class="window-close"><a href="javascript:void(0);">Fechar</a></div>'
    + '<div class="window-content"></div>';
    Delrio.window.object.html(html).hide();
    $('.window-close', Delrio.window.object).bind('click', function(){
        Delrio.window.hide();
    });

    Delrio.actions.changeColor();
    Delrio.actions.disableRightButton();
}

Delrio.window.show = function(message, waitingMessage){
    var content;
    var callback;

    Delrio.window.waiting('start', waitingMessage);

    if(typeof message != 'undefined'){
        message = '<div class="messages status">' + message + '</div>';
        content = $('.window-content', Delrio.window.object).html();
        callback = function(){
            $('.window-content', Delrio.window.object).html(message + content).fadeIn('slow', function(){
                Delrio.window.waiting('kill');
            });
        }
    } else {
        callback = function(){
            Delrio.window.waiting('kill');
        }
    }

    Delrio.window.object
    .show()
    .addClass('is-opened')
    .animate({
        top: ($(document).scrollTop() + 10) + 'px'
    }, 'slow', callback)
}

Delrio.window.hide = function(){
    Delrio.window.object
    .removeClass('is-opened')
    .animate({
        top: (0 - Delrio.window.object.height() - 50) + 'px'
    }, 'slow', function(){
        Delrio.window.clear();
        Delrio.window.object.hide();
    });
}

Delrio.window.waiting = function(action, message){
    message = typeof message == 'undefined' ? 'Carregando, aguarde...' : message;

    switch(action){
        case 'start':
            $('.window-loading', Delrio.window.object).html('<div class="messages status">'
                + message + '</div>').fadeIn();
            break;
        case 'kill':
        default:
            $('.window-loading', Delrio.window.object).slideUp('slow');
    }
}

Delrio.window.clear = function(){
    $('.window-content', Delrio.window.object).html("");
}

Delrio.forms.load = function(nid, params){
    params = typeof params == 'undefined' ? '' : params;
    $('.window-content', Delrio.window.object).load(
        Drupal.settings.basePath + 'node/' + nid + ' #node-' + nid,
        params,
        function(){
            Delrio.window.show();
        }
    );
}

Delrio.forms.submit = function(context, messageOnSuccess){
    var obj     = $(context);
    var action  = obj.attr('action');
    var method  = obj.attr('method').toLowerCase();
    var params  = obj.serialize();

    messageOnSuccess = typeof messageOnSuccess == 'undefined'
    ? 'Enviado com sucesso!' : messageOnSuccess;

    if( method == 'post' ){
        $.post(action, params, function(){
            Delrio.window.show(messageOnSuccess, "Submetendo formulário...");
        });
    } else {
        $.get(action, params, function(){
            Delrio.window.show(messageOnSuccess, "Submetendo formulário...");
        });
    }
}

Delrio.actions.changeColor = function(){
    $("#changeColor a").click(function(e){
        e.preventDefault();
        var color = $(this).attr('class');
        if(color == 'gray'){
            $('body').addClass('body-color-gray');
        } else {
            if($('body').hasClass('body-color-gray') ){
                $('body').removeClass('body-color-gray');
            }
        }
    });
}

Delrio.actions.changeImageInGallery = function(context, target){
    context = $(context);
    target  = $(target);

    context.bind('click', function(e){
        e.preventDefault();
        _this = $(this);
        if(target.attr('src') == _this.attr('href') ){
            return;
        } else {
            target.fadeOut('slow', function(){
                $(this).attr('src', _this.attr('href')).fadeIn('slow');
                $(this).parent().attr('href', _this.attr('href'));
            });
        }
    });
}

Delrio.actions.disableRightButton = function(){
    $(document).bind('contextmenu', function(e){
        e.preventDefault();
    });
}

Delrio.actions.addFavorite = function(url, title){
    if (window.sidebar){
        window.sidebar.addPanel(title, url, "");
    } else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    } else if(document.all){
        window.external.AddFavorite(url, title);
    }
}

Delrio.actions.preloadImages = function(){
    var args = Delrio.actions.preloadImages.arguments;
    document.imageArray = new Array(args.length);
    for(var i = 0; i < args.length; i++){
        document.imageArray[i] = new Image;
        document.imageArray[i].src = args[i];
    }
}

Delrio.actions.findZipCode = function(options){
    Delrio.window.show('Buscando pelo CEP ' + options.param);
    $.ajax({
        type : 'GET',
        url: Drupal.settings.basePath + 'cep-finder.php',
        data : {
            cep: options.param
        },
        dataType: 'xml',
        success: function(data){
            if($(data).find('resultado').text() == 'found'){
                Delrio.window.hide();
                $(options.address).val( $(data).find('tipo_logradouro').text()
                    + ' ' + $(data).find('logradouro').text() );
                $(options.district).val( $(data).find('bairro').text() );
                $(options.city).val( $(data).find('cidade').text() );
                $(options.state).val( $(data).find('uf').text() );
            } else {
                Delrio.window.show('Seu CEP não foi encontrado');
            }
        },
        error: function(){
            Delrio.window.show('Não foi possível procurar por seu CEP');
        }
    });
}

Delrio.actions.log = function(message){
    if(console){
        console.log(message);
        return true;
    }

    return false;
}

Delrio.actions.cpfIsValid = function(cpf){
    var numbers, dig, sum, i, result, eq_dig;
    eq_dig = true;
    cpf = cpf.replace(/\D/g, '');
    
    if(cpf.length < 11){
        Delrio.actions.log('Tamanho > 11');
        return false;
    }
    
    for(i = 0; i < cpf.length -1; i++){
        if(cpf.charAt(i) != cpf.charAt(i + 1) ){
            eq_dig = false;
            break;
        }
    }
    
    if(!eq_dig){
        numbers = cpf.substring(0,9);
        dig     = cpf.substring(9);
        sum     = 0;

        for(i = 10; i > 1; i--){
            sum += numbers.charAt(10 - i) * i;
        }
        result = sum % 11 < 2 ? 0 : 11 - sum % 11;
        if(result != dig.charAt(0)){
            Delrio.actions.log('Invalido|!=dig.charAt(0)');
            return false;
        }

        numbers = cpf.substring(0,10);
        sum     = 0;
        for(i = 11; i > 1; i--){
            sum += numbers.charAt(11 - i) * i;
        }
        result = sum % 11 < 2 ? 0 : 11 - sum % 11;

        if(result != dig.charAt(1)){
            Delrio.actions.log('Invalido|!=dig.charAt(1)');
            return false;
        }

        return true;
    } else {
        Delrio.actions.log('Invalido|Repeticao invalida');
        return false;
    }
    
}
