 /******************************
  * base.global.js             *  
  *                            *
  * comuns para todo o sistema *
  ******************************/

$(document).ready(function(){
	setupInputs();
	filterController();
	setButtonsHovers();
	
	// detalhe para o link de nova fonte pagadora...
	// diferenciação nos links do menu e submenu...
	$("ul#menu li a").each(function(i,elem){
	    var linkHref =  $(this).attr('href');
	    var linkHrefLength = linkHref.length;

	    var controllerAction = 'entidade/nova-entidade';
	    var controllerActionLength = controllerAction.length;
	    if( linkHref.substr(linkHrefLength-controllerActionLength,controllerActionLength) == controllerAction ){
	        $(this).bind('click',function(){
    	        showConfirmDialog(
    	            i18n.MN039,
                    function(){ redirect(controllerAction); },
                    function(){ return false; },
                    'Nova Fonte Pagadora?',
                    175,
                    535
                );
    	        return false;
	        });
	    }
	});
	
    // img.outros-sistemas hover...
    $('#outros_sistemas img.outros-sistemas').hover(
        function(){
            var src = $(this).attr('src');
            var novoSrc = src.substr(0,src.length-4)+'_color.gif';
            $(this).attr('src',novoSrc);
        },
        function(){
            var src = $(this).attr('src');
            var novoSrc = src.substr(0,src.length-10)+'.gif';
            $(this).attr('src',novoSrc);
        }
    );
    $('.ui-tabs li a').bind('click',function(){removeToolTip();});


//    $('form').each(function(){
//        if( $(this).attr('action') == '' ){
//            $(this).removeAttr('action').removeAttr('method').bind('submit',function(){ return false; });
//        }
//    });
});

function stopPropagation(e){
    if( $.browser.msie === true ){
        e.cancelBubble = true;
    } else {
        e.stopPropagation();
    }
}

function setPreventExit(){
    window.onbeforeunload = function(){};
//    window.onbeforeunload = function (e) {
//        if(!e) e = window.event;
//        //e.cancelBubble is supported by IE - this will kill the bubbling process.
//        e.cancelBubble = true;
//        e.returnValue = i18n.ER048; //This is displayed on the dialog
//        
//        //e.stopPropagation works in Firefox.
//        if (e.stopPropagation) {
//            e.stopPropagation();
//            e.preventDefault();
//        }
//    };
}

function unsetPreventExit(){
    window.onbeforeunload = function(){};
}

function setButtonsHovers(container){
    container = (container)?container:false;
    if( !container ){ 
        var buttons = $('button.ui-state-default');
    } else if( container.jquery ){
        var buttons = container.find('button.ui-state-default');
    } else {
        var buttons = $(container +' button.ui-state-default');
    }
    buttons.each(function(){
        $(this).hover(
            function(){
                $(this).addClass('ui-state-hover');
            },
            function(){
                $(this).removeClass('ui-state-hover');
            }
        );
    });
}
/**
 * controle dos botoes que exibem e ocultam os filtros de pesquisa
 * controle da class .combo-filter que dispara o click do botão buscar
 * quando a busca é simplificada
 */
function filterController(){
	//so aplicavel quando existir o btnShow
	/*
	var btnShow 	= $("#btn_show_filters"); 
	var btnHide 	= $("#btn_hide_filters"); 
	var filterSet	= $(".filter-set");
	var comboFilter = $('.combo-filter');
	
	if(btnShow.size() > 0){
		btnShow.click(function(){
			comboFilter.unbind("change");
			btnHide.removeClass("hide");
			btnShow.addClass("hide");
		    filterSet.show("blind");
		});
		btnHide.click(function(){
			$(".filter-set :input").each(function(){$(this).val("");});
			btnHide.addClass("hide");
			btnShow.removeClass("hide");
			filterSet.hide("blind");
		});
	}

	*/
	
	//so aplicavel quando existir o btnShow
	var btnShow 	= $(".btn_show_filters"); 
	
	if(btnShow.size() > 0){
		var gridFilter = btnShow.closest(".grid-filter");
		var btnHide 	= gridFilter.find(".btn_hide_filters"); 
		var filterSet	= gridFilter.find(".filter-set");
		var comboFilter = gridFilter.find('.combo-filter');
		
		btnShow.click(function(){
			comboFilter.unbind("change");
			btnHide.removeClass("hide");
			btnShow.addClass("hide");
			filterSet.show("blind");
		});
		btnHide.click(function(){
			$(".filter-set :input").each(function(){$(this).val("");});
			btnHide.addClass("hide");
			btnShow.removeClass("hide");
			filterSet.hide("blind");
		});
	}
}

function isset(something){
    return something!==undefined;
}

function count(object) {
    var o=0;
    for( var i in object){o++;}
    return o;
}

function isArray( value ){
    return ( typeof(value)=='object' && !isset(value.jquery) && isset(value.length) );
}

/** 
 * Encontra a posição da primeira ocorrencia de uma string dentro de outra
 *  
 * @param string haystack      //frase
 * @param string needle        //string procurada
 * @param int    offset        //deslocamento
 * @returns mixed
 */
function strpos( haystack, needle, offset){
    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}

function roundNumber (rnum) {
   return Math.round(rnum*Math.pow(10,2))/Math.pow(10,2);
}

function moneyForView(num){
    var x = 0;
    if(num < 0) {
      num = Math.abs(num);
      x = 1;
    }
    if(isNaN(num)) num = "0";
    cents = Math.floor((num*100+0.5)%100);
    num = Math.floor((num*100+0.5)/100).toString();
    if(cents < 10) cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+'.'
       +num.substring(num.length-(4*i+3));
    ret = num + ',' + cents;
    if (x == 1) ret = ' - ' + ret;
    return ret;
}

/**
 * Função que executa um redirect com parametros por GET ou por POST
 * 
 * @param string controllerAction
 * @param mixed  params
 * @param string type
 * @param boolean hasLoading
 * @return mixed
 */
function redirect(controllerAction,params,type,hasLoading){
    unsetPreventExit();
    
    hasLoading = isset(hasLoading)?hasLoading:true;
    if( hasLoading === true ){
        ajaxLoading();
    }
    
    type = !isset(type)?'get':'post';
    var url = '';
    
    if( controllerAction === false ){
        return false;
    }
    if( !isset(controllerAction) ){
        return false;
    }
    if( controllerAction === '' ){
        return window.location = url;
    }
    
    if( type === 'get' ){
        params = !isset(params)?'':params;
        var parameters = '';
        if( typeof(params)=='object' ){
            if( isset(params.jquery)){
                parameters = '?'+params.serialize(); 
            } else {
                for( var i in params ){
                    if( isset(params.i) ){
                        parameters += '/' + i + '/' + params.i;
                    } else {
                        parameters += '/' + i + '/' + params[i];
                    }
                }
            }
        } else {
            params = (params != '')? '/' + params:'';
            parameters = params;
        }
        if( parameters != '' ){
            var arrControllerAction = new Array();
            arrControllerAction = controllerAction.split('/');
            if( !isset(arrControllerAction[1]) ){
                controllerAction += '/index';
            } else if( arrControllerAction[1] == '' ){
                controllerAction += 'index';
            }
        }
        url = baseUrl + '/' + controllerAction + parameters;
        return window.location = url;
    } else {
        url = baseUrl + '/' + controllerAction;
        var formRedirect = mountHiddenForm('formRedirect',url,params);
        return formRedirect.submit();
    }
}

/**
 * Função que monta um form com campos ocutos
 * 
 * @param string id
 * @param string action
 * @param mixed data
 * @param string container
 * @return object jQuery
 */
function mountHiddenForm(id,action,data,container){
    container = isset(container)?container:'body';
    var formXhtml  = '<form action="'+action+'" method="post" id="'+id+'">';
    $('#'+id).remove();
    if( typeof(data)=='object' ){
        if( isset(data.jquery)){
            data.each(function(i,elem){
                formXhtml += '<input type="hidden"';
                formXhtml += '       id="'+$(this).attr('id')+'"';
                formXhtml += '       name="'+$(this).attr('name')+'"';
                formXhtml += '       value="'+$(this).val()+'"';
                formXhtml += '/>';
            }); 
        } else {
            var value = '';
            for( var i in data ){
                if( isset(data.i) ){
                    value = data.i;
                } else {
                    value = (!isset(data[i]))?'':data[i];
                }
                if( isArray(value) ){
                    for( var o=0;o<value.length;o++ ){
                        formXhtml += '<input type="hidden"';
//                        formXhtml += '       id="'+i+'-'+value+'"';
                        formXhtml += '       name="'+i+'[]"';
                        formXhtml += ' value="'+value[o]+'"';
                        formXhtml += '/>';
                    }
                } else {
                    formXhtml += '<input type="hidden"';
//                    formXhtml += '       id="'+i+'"';
                    formXhtml += '       name="'+i+'"';
                    formXhtml += ' value="'+value+'"';
                    formXhtml += '/>';
                }
            }
        }
    }
    formXhtml += '</form>';
    $(container).append(formXhtml);
    return $(container+' #'+id);
}
function getBaseController(){
    return baseUrl + '/' + controller + '/';
}

function getBaseAction(){
    return getBaseController() + '/' + action + '/';
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/**
 * Seta a function callback quando clica na tecla "ENTER" (13)
 * em todos os elementos do seletor do objQuery
 *
 * @param object objQuery
 * @param function callback
 * @return void
 */
function onKeyEnter( objQuery , callback ){
    objQuery.bind('keyup',function(e){
        if( !$(this).is('textarea') ){
            var e=e||window.event;
            var k=e.keyCode||e.which||e.charCode;
            if( k == 13 ){
                if($.isFunction(callback)){
                    setTimeout(callback, 50);
                }else{
                    setTimeout('eval('+ callback +');', 50);
                }
            }
        }
    });
}

/**
 * Função que abre o popup do relatório...
 * 
 * @param string path
 * @param object params
 * @return void
 */
function openPopup( path, params ) {
    params = $.extend({"width"   : "640"}    , params); // largura do popup
    params = $.extend({"height"  : "480"}    , params); // altura do popup
    params = $.extend({"popupId" : "JANELA"} , params); // id do popup
    params = $.extend({"scrollbars" : "no"}  , params); // popup tem scrollbar

    var jan = window.open(
        path,
        params.popupId,
        "width = "+ params.width  +", "
       +"height= "+ params.height +", "
       +"directories=no, "
       +"channelmode=no, "
       +"fullscreen=no, "
       +"location=no, "
       +"menubar=no, "
       +"resizable=yes, "
       +"scrollbars="+ params.scrollbars +", "
       +"status=no, "
       +"titlebar=no, "
       +"toolbar=no");

    if( jan != null ){
        jan.focus();
    }
}   
/**
 * Função chama o popup do relatório...
 * 
 * @param mixed  form
 * @param string action
 * @param object params
 * @return void
 */
function gerarRelatorio( form, action, params ){
    if(typeof(form)=='string'){
        form = $(form);
    }
    if(typeof(form)=='object'){
        if( !form.jquery  ){
            form = mountHiddenForm('reportForm', action, form);
        }
    }
    if( !form.length ){
        showDialog('Erro: Form não existente.','alert');
        return false;
    }
    
    if( action == '' ){
        return false;
    }

    params = $.extend({"width":"985"},params);
    params = $.extend({"height":"550"},params);
   
    if(form){
        form.attr({
            'action':action,
            'method':'post',
            'target':'new'
        });
    }
    openPopup( action, params );
    if(form){
        form.attr('target', 'JANELA');
        form.submit();
    }
}

/**
 * Faz o redirecionamento para exibir o detalhamento do registro do sisprom v2
 * 
 * @param cdRegistro
 * @param cdSituacao
 * @param telaInicial
 * @param txPerfil
 * @param siglaModulo
 * @return void
 */
function showRegistry(cdRegistro,cdSituacao,telaInicial,txPerfil,siglaModulo){
    ajaxLoading();
    var dataPost = {'cdRegistro':cdRegistro};
    var SituacaoRegistro = {
            'CANCELADO'               : 1,
            'EFETIVADO'               : 2,
            'PENDENTE_ANALISE'        : 3,
            'ANALISADO_SEM_APROVACAO' : 4,
            'ANALISADO_COM_APROVACAO' : 27,
            'DEVOLVIDO'               : 5
        };
    var urlRedirect = '';
    switch (txPerfil) {
        case 'Coordenador':
            if( (cdSituacao == SituacaoRegistro.PENDENTE_ANALISE) || (cdSituacao == SituacaoRegistro.ANALISADO_SEM_APROVACAO) || (cdSituacao == SituacaoRegistro.ANALISADO_COM_APROVACAO) ){
                urlRedirect = 'registro/analisar';
            }else{
                urlRedirect = 'registro/detalhamento';
            }
            break;
        case 'Analista':
            if( siglaModulo == 'B' || siglaModulo == 'T' ){
                urlRedirect = 'registro/detalhamento';
            } else {
                if(cdSituacao == SituacaoRegistro.PENDENTE_ANALISE ){
                    urlRedirect = 'registro/analisar';
                }else{
                    urlRedirect = 'registro/detalhamento';
                }
            }
            break;
        case 'Usuario Externo':
            if( (cdSituacao == SituacaoRegistro.DEVOLVIDO) || (cdSituacao == SituacaoRegistro.EFETIVADO) ){
                urlRedirect = 'registro/editar';
            }else{
                urlRedirect = 'registro/detalhamento';
            }
            break;
        default:

            break;
    }
    if(urlRedirect != '') {
        redirect(urlRedirect,dataPost,'post');
    }
}
/**
 * Faz o redirecionamento para exibir o detalhamento do registro do sisprom v1
 * 
 * @param sqPedidoBeneficio
 * @return void
 */
function showRegistrySisrefi(sqPedidoBeneficio){
    ajaxLoading();
    var dataPost = {'sqPedidoBeneficio':sqPedidoBeneficio};
    var urlRedirect = 'registro/detalhamento-sisrefi';
    redirect(urlRedirect,dataPost,'post');
}

/**
 * Remove os acentos do texto informado
 *
 * @param string text
 * @return string
 */
function accentStrip(text) {
  return text.replace(/[ÀÁÂÃÄÅ]/g , 'A').replace(/[àáâãäå]/g , 'a')
             .replace(/[ÈÉÊË]/g   , 'E').replace(/[èéêë]/g   , 'e')
             .replace(/[ÌÍÎÏ]/g   , 'I').replace(/[ìíîï]/g   , 'i')
             .replace(/[ÒÓÔÕÖ]/g  , 'O').replace(/[òóôõö]/g  , 'o')
             .replace(/[ÙÚÛÜ]/g   , 'U').replace(/[ùúûü]/g   , 'u')
             .replace(/[Ç]/g      , 'C').replace(/[ç]/g      , 'c')
             .replace(/[Ñ]/g      , 'N').replace(/[ñ]/g      , 'n');
}