var pace_counter = 0;
var pace_on = true;


$(document).on('ready', function(){

    // if ( _PRIMEIRO_LOGIN ) {
    //     bootbox.remote(Router.url(["usuarios", "alterar_senha_interno"]),'dialog', {},
    //     {
    //        title: 'Alterar Senha',
    //        width: '400px',
    //        closeButton: false,
    //        onEscape: function() {return false;}
    //     });
    // }
});


if(localStorage.getItem('gonha_loading') == null)
	localStorage.setItem('gonha_loading', false);

// Pace
$(document).ajaxStart(function(a,b,c) {

});

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

$(document).ajaxSend(function(a,b,c) {

	pace_counter++;

	if(!pace_on || (typeof c.pace != "undefined" && !c.pace))
		return;

	Pace.start();
});

$(document).ajaxComplete(function(a,b,c) {

	pace_counter--;

	if(pace_counter == 0)
		$.As.killLoader('pace');
});

Pace.on('start', function() {

	$.As.showLoader('pace');
})

Pace.on('done', function() {

	if(pace_counter == 0)
		$.As.killLoader('pace');

});

$(document).keyup(function(e){

    if(e.keyCode === 27)
		Pace.trigger('done');

});

var idleTime = 0;

$(document).ready(function() {
    $(document).on('change', '#fotoUploadNavTop input[type="file"]', function(){
        $.As.submit($('#atualizarAvatarNavTop'), {
            autoClose: false,
            success: function(data) {
                if(data.success){
                    location.reload();
                }
            }
        });
    });


    if ($('.fixme').exists()) {
        var fixmeTop = $('.fixme').offset().top;
    }else{
        fixmeTop = 0;
    }


    $(window).scroll(function() {                  // assign scroll event listener

        var currentScroll = $(window).scrollTop(); // get current position

        // if (currentScroll >= fixmeTop) {           // apply position: fixed if you
            $('.fixme').css({                      // scroll to that element or below it
                position: 'relative',
                top: currentScroll,
            });
        // } else {                                   // apply position: static
        //     $('.fixme').css({                      // if you scroll above it
        //         position: 'static'
        //     });
        // }
    });

    // Incrementa o tempo de inatividade a cada 1 minuto.
    // var idleInterval = setInterval(idleIncrement, 60000); // 1 minuto

    // Zero the idle timer on mouse movement.
 //    $(this).mousemove(function (e) {
 //        idleTime = 0;
 //    });

 //    $(this).keypress(function (e) {
 //        idleTime = 0;
 //    });

	$('#bg-loading .loader').center();

	$('.btn.sys-add').each(function() {

		var _this = $(this);

		var w = _this.find('i').outerWidth() - 4;
		_this.data('data-width', _this.width());
		_this.width(w);
	});

	$('.btn.sys-add').on('mouseover', function() {
		$(this).width($(this).data('data-width'));
	});

	$('.btn.sys-add').on('mouseleave', function() {

		var _this = $(this);

		var w = _this.find('i').outerWidth() - 4;
		_this.width(w);
	});


	/**
	 * Show/Hide do botão de filtros
	 *
	 * @author Felipe Francisco
	 */
	$(document).on('click','.btn-filtros',function(){

		if(!$('.export').is(':visible'))
			$('.export').slideUp();

		if(!$('.filtros').is(':hidden'))
			return;

	    var offset = $(this).offset();
	    var filtros_width = $('.filtros').width();
	    $('.filtros').slideToggle(function() {

	    	$(this).find('.btn-dt-search').fadeIn();
	    	$(this).find('.btn-dt-clear').fadeIn();
	    });

	    if(!$('.filtros').is(':hidden')) {

	        $('.filtros').offset({
	            top:offset.top + 40,
	            left:offset.left - filtros_width + 20
	        });
	    }
	});



    /**
     * Show/Hide do botão de filtros
     *
     * @author Felipe Francisco
     */
    $(document).on('click','.btn-filtros-new',function(){

        if(!$('.export').is(':visible'))
            $('.export').slideUp();

        if(!$('.filtros').is(':hidden'))
            return;

        var offset = $(this).offset();
        var filtros_width = $('.filtros').width();
        $('.filtros').slideToggle(function() {

            $(this).find('.btn-dt-search').fadeIn();
            $(this).find('.btn-dt-clear').fadeIn();
        });

        // if(!$('.filtros').is(':hidden')) {

        //     $('.filtros').offset({
        //         top:offset.top + 40,
        //         left:offset.left - filtros_width + 20
        //     });
        // }
    });

    $(document).on('click', '.user-menu .dropdown-menu', function (e) {
        e.stopPropagation();
    });

    $('#change-perfil').change(function(){

        if($(this).val() != ""){

            Router.redirect(["usuarios", "change_group_funcionario", $(this).val()]);

        }
    });

	/**
	 * Hide de filtros.
	 *
	 * @param  {[type]} e) {                   var conteudo [description]
	 * @return {[type]}    [description]
	 */
	$(document).on('mousedown', function (e) {
        var conteudo = $('.filtros');
        var excessao = $('#ui-datepicker-div');
        var excselect2 = $('.select2');
        var excdaterangepicker = $('.daterangepicker');
        var datepicker = $('.datepicker');
        
        if (!conteudo.is(e.target)
                && conteudo.has(e.target).length === 0
                && excessao.has(e.target).length === 0
                && excselect2.has(e.target).length === 0
                && excdaterangepicker.has(e.target).length === 0
                && datepicker.has(e.target).length === 0
           )
        {
           /* if (excdaterangepicker.length > 0) {
                if (excdaterangepicker.css('display') == 'none') {
                    conteudo.slideUp();
                }
            } else { */
            	closeFiltros();
            // }
        }
    });


	/**
	 * Show/Hide do botão de exportar
	 *
	 * @author Felipe Francisco
	 */
	// $(document).on('click', '.btn-export', function() {

	// 	if(!$('.filtros').is(':visible'))
	// 		$('.filtros').slideUp();

	// 	$('.export').slideToggle(function() {

	// 		ttInstances = TableTools.fnGetMasters();
	// 		for (i in ttInstances) {
	// 			if (ttInstances[i].fnResizeRequired())
	// 				ttInstances[i].fnResizeButtons();
	// 		}
	// 	});

	// });

	/**
	 * Esconde os filtros das páginas de listagem.
	 *
	 * @author Rodrigo Sobrinho
	 */
	$('.filtros').hide();

	$(document).on('keydown', 'input.omni', function(e) {
	    if (e.which == 13) {
	        $(this).parent().find('.dt-trigger-search').trigger('click');
	        return false;
        }
	});

	$('input.omni').keypress(function(event) {
		if(event.keyCode == 13){
	        $(this).parent().find('.dt-trigger-search').trigger('click');
	        return false;
		}
	});

	$(window).on('shown.bs.modal', function() {
	   forceCenterFileUploadPreview($('.fileupload'));
	});

	$('.btn-dt-search').on('click', function() {
        closeFiltros();
    });

    // $(window).konami({
    //     cheat: function() {
    //     	if(localStorage.getItem('gonha_loading') == 'false'){

    //     		localStorage.setItem('gonha_loading', true);
    //     		$('#main-content .wrapper').prepend($('<div class="cheat-activated alert alert-warning text-center">').html('Cheat Activated'));
    //     	}else{

    //     		localStorage.setItem('gonha_loading', false);
    //     		$('#main-content .wrapper').prepend($('<div class="cheat-activated alert alert-danger text-center">').html('Cheat Deactivated'));
    //     	}
    //     	setTimeout(function(){
    //     		$('.cheat-activated').remove();
    //     	}, 1000);
    //     }
    // });

    $('.dropdown.top-profile').click(function() {

		$('.contato-ti').hide();
		$(document).one('click', function() {

			$('.contato-ti').show();
		});
	});

});

$(document).on('ifChanged', '.persist-list', function(e){
    keyname = $(this).data('keyname');
    ids = localStorageManager.getValue(keyname);
    id = $(this).val();
    index = ids.indexOf(id);

    if ($(this).is(':checked')) {
        if (index == -1) {
            ids.push(id);
        }
    }else{
        ids.splice(index, 1);
    }
    localStorageManager.setValue(keyname, ids);
});

var localStorageManager = {
    setValue: function(key, value) {
        key = CONTROLLER + '.' + VIEW + '.' + key;
        window.localStorage.setItem(key.toLowerCase(), JSON.stringify(value));
    },
    getValue: function(key, full) {
        // quando acessar direto da VIEW que faz o SET, reescreve a key.
        // mas quando acessar de outra view, passar o controller.view.key no parametro KEY
        if (full == undefined) {
            key = CONTROLLER + '.' + VIEW + '.' + key;
        }

        try {
            var list = JSON.parse(window.localStorage.getItem(key.toLowerCase()));
            if (list == undefined) {
                return [];
            }else{
                return list;
            }
        } catch (e) {
            return [];
        }
    },
    applyCheck : function () {

        $('input:checkbox.persist-list').each(function(){
            key = $(this).data('keyname');
            ids = localStorageManager.getValue(key.toLowerCase());
            value = $(this).val();
            if (ids.indexOf(value) != -1) {
                $(this).iCheck('check');
            }
        });
    }
};


$(document).on('click','.btn-people-allowed', function( e ){
    e.preventDefault();

    var url = $(this).attr('href');
    bootbox.remote( url , 'dialog', {},
    {
        title:'Pessoas autorizadas a retirar convites',
        width: '1000px',
        id: 'modal-pessoas-autorizadas-a-retirar'
    });
});

$(document).on('click', '.usar-autorizacao', function(){
    $(this).parent().parent().find('td').each( function(){
        var name = $(this).data('name');
        var content = $(this).html();

        $('#'+name).val( content );
    });

    $('.bootbox-close-button').click();
});

$(document).on('ifChanged', '#checkbox-terceiro', function(){
    if($(this).is(':checked')){

        $('.div-terceiros').removeClass('hide').show();
        $('.nome-terceiro').removeAttr('disabled');
        $('.rg-terceiro').removeAttr('disabled');
        $('.cpf-terceiro').removeAttr('disabled');
        $('.telefone-terceiro').removeAttr('disabled');
        $('.celular-terceiro').removeAttr('disabled');
        $('.grau-parentesco').removeAttr('disabled');

        if( typeof resizeJquerySteps === 'function' )
            resizeJquerySteps();

    }else{

        $('.div-terceiros').addClass('hide').hide();
        $('.nome-terceiro').attr('disabled', 'disabled');
        $('.rg-terceiro').attr('disabled', 'disabled');
        $('.cpf-terceiro').attr('disabled', 'disabled');
        $('.telefone-terceiro').attr('disabled', 'disabled');
        $('.celular-terceiro').attr('disabled', 'disabled');
        $('.grau-parentesco').attr('disabled', 'disabled');

        if( typeof resizeJquerySteps === 'function' )
            resizeJquerySteps();
    }
});

function printDiv(elem)
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
    mywindow.document.write('<style type="text/css"> @media print{ .noprint{ display:none;}}</style></head><body >');
    mywindow.document.write('<h1>' + document.title  + '</h1>');
    mywindow.document.write(document.getElementById(elem).innerHTML);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}

$(document).off('keydown', '.omni-trigger-search');
$(document).on('keydown', '.omni-trigger-search', function(e){

    if(e.keyCode === 13){

        $(this).closest('.panel-collapse').find('.dt-trigger-search').click();
    }
});

function closeMenu(){

    $(document).on('ready', function(){
        if($(window).width() > 700 ){
            setTimeout(function() {
                $('.close-menu-system').click();    
            }, 1500);
        }
    });
}

$(document).on('hidden.bs.modal', '.modal', function () {
    if($('.modal').length)
        $(document.body).addClass('modal-open')
});