// JavaScript Document
function setTam(tam){
    var size = null;
    switch (tam){
        case "1":
            size = "P";
            font = "14px";
            break;
        case "2":
            size = "M";
            font = "16px";
            break;
        case "3":
            size = "G";
            font = "18px";
            break;
    }
	
    var src= null;
    for (i = 0; i < $('#fonts img').size(); i++){
        src = $('#fonts img:eq('+i+')').attr('src').replace('Hover','');
        $('#fonts img:eq('+i+')').attr('src',src);
    }
    $('#fonts img:eq('+(tam-1)+')').attr('src','../imagens/font'+size+'Hover.jpg');
    $('.texto').css({
        fontSize:font
    });
}

/* Mapa - polos regionais */

function pintamapa(estado){
    var estadoatual = 'http://200.245.46.107/ClaretianoBTT/imagens/mapa2_'+estado+'.png';
    $('#mapabrasil').attr('src',estadoatual);
}
/* Fim mapa - polos regionais */

$('document').ready(function(){
    viewBoxMenu('click');
});

function viewBoxMenu(act){
    $close = $('#menuSite h6.close')
    $open = $('#menuSite h6.open');
	
    if (act == 'load'){
        $close.next().hide();
        $open.next().show();
    }else{
        $close.next().slideUp();
        $open.next().slideDown();
    }
}

function controleBox(obj){
    if (obj.className == 'open')
        obj.className = 'close';
    else
        obj.className = 'open';
    viewBoxMenu('click');
}

function getCookie(name){
    var start = document.cookie.indexOf(name+"=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0,name.length)))
        return null;
    if (start == -1)
        return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1)
        end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}
 
function setCookie(name,value){
    var today = new Date();
    var zero_date = new Date(0,0,0);
    today.setTime(today.getTime() - zero_date.getTime());
    var cookie_expire_date = new Date(today.getTime() + (8 * 7 * 86400000));
    document.cookie = name+"="+escape(value)+";expires="+cookie_expire_date.toUTCString()+";path=/";
}

function setNavegacao(name,pagina){
    var cookie = getCookie(name);
	
    var paginas = new Array();
    var paginasNew = new Array();
	
    if (cookie == null) cookie = "";
    setCookie(name,pagina+"#$"+cookie);
    cookie = getCookie(name);
	
    var spl = cookie.split("#$");

    var limit = 6;
    for (i = 0; i < (limit+1); i++){
        if (spl[i] != null && spl[i] != '' && spl[i] != 'undefined'){
            paginas[i] = spl[i];
        }else
            break;
    }
	
	
    var y = 0;
    for (i = 0; i < (paginas.length); i++){
        for (x = 0; x < (paginas.length); i++){
            if (paginasNew[x] == null){
                paginasNew[y] = paginas[i];
                y++;
                break;
            }else{
                if (paginasNew[x].indexOf(paginas[i]) < 0){
                    paginasNew[y] = paginas[i];
                    y++;
                    break;
                }
            }
        }
    }

    pagina = "";
    for (i = 0; i < limit; i++){
        if (paginasNew[i] != null) pagina += paginasNew[i]+"#$";
    }
    setCookie(name,pagina);
}

function getNavegacao(name){
    var cookie = getCookie(name);
    if (cookie == null) cookie = "";

    var spl = cookie.split("#$");
    var txt = "";
    for (i = 0; i < spl.length; i++){
        txt = spl[i].split("[lk]")[0];
        if (txt.length >= 78) txt = txt.substring(0,78)+"...";
        $('#navCookie').append('<a href="'+spl[i].split("[lk]")[1]+'">'+txt+'</a>');
    }
}

function luz(){
    if ($('#luz img').attr('alt') == 'Apagar as luzes'){
        var bodypage 	= document.body;
        var bodyblock 	= document.createElement("div");
		
        bodyblock.setAttribute('id','bodyBlock');
        bodypage.appendChild(bodyblock);

        var ie = /msie/i.test(navigator.userAgent);
        var ieBox = ie && (document.compatMode == null || document.compatMode == "BackCompat");
        var canvasEl = ieBox ? document.body : document.documentElement;
        var h = window.innerHeight || canvasEl.clientHeight;
        if (h > document.documentElement.scrollHeight)
            bodyblock.style.height = parseInt(document.documentElement.scrollHeight + (h - document.documentElement.scrollHeight)) + "px";
        else
            bodyblock.style.height = document.documentElement.scrollHeight + 'px';

        $('#playerVideo').addClass('playerVideoS');
        $('#luz a').html('<img src="imagens/acenderLuz.png" alt="Acender as luzes" title="Acender as luzes"/> ACENDER AS LUZES');
		
        $('#ctrlSessao').removeClass('sessao');
        $('#ctrlSessao').addClass('sessaoNotLuz');
    }else{
        $('#playerVideo').removeClass('playerVideoS');
        $('#luz a').html('<img src="imagens/apagarLuz.png" alt="Apagar as luzes" title="Apagar as luzes"/> APAGAR AS LUZES');

        $('#ctrlSessao').removeClass('sessaoNotLuz');
        $('#ctrlSessao').addClass('sessao');

        $('#bodyBlock').remove();
    }
}

function luz2(acende){
    if (acende){
        var bodypage 	= document.body;
        var bodyblock 	= document.createElement("div");
		
        bodyblock.setAttribute('id','bodyBlock');
        bodypage.appendChild(bodyblock);

        var ie = /msie/i.test(navigator.userAgent);
        var ieBox = ie && (document.compatMode == null || document.compatMode == "BackCompat");
        var canvasEl = ieBox ? document.body : document.documentElement;
        var h = window.innerHeight || canvasEl.clientHeight;
        if (h > document.documentElement.scrollHeight)
            bodyblock.style.height = parseInt(document.documentElement.scrollHeight + (h - document.documentElement.scrollHeight)) + "px";
        else
            bodyblock.style.height = document.documentElement.scrollHeight + 'px';

        $('.mccv').addClass('playerVideoS2');
        //$('#luz a').html('<img src="imagens/acenderLuz.png" alt="Acender as luzes" title="Acender as luzes"/> ACENDER AS LUZES');
		
        //$('#ctrlSessao').removeClass('sessao');
        //$('#ctrlSessao').addClass('sessaoNotLuz');
    }else{
        //$('#playerVideo').removeClass('playerVideoS');
        //$('#luz a').html('<img src="imagens/apagarLuz.png" alt="Apagar as luzes" title="Apagar as luzes"/> APAGAR AS LUZES');

        //$('#ctrlSessao').removeClass('sessaoNotLuz');
        //$('#ctrlSessao').addClass('sessao');

        $('#bodyBlock').remove();
    }
}

/* filtro de cursos */
var intervaloMenu = null;
var intervaloSubMenu = null;

function showMenu(obj, sub){
    clearTimeout(intervaloMenu);
    clearTimeout(intervaloSubMenu);

    $('.subMenu').hide();
    $('.subMenu#' + sub).show();
}

function showSubMenu(obj){
    clearTimeout(intervaloMenu);
    clearTimeout(intervaloSubMenu);

    $('.subMenu').hide();
    $(obj).show();
}

function hideMenu(obj, sub){
    intervaloMenu = setTimeout(function(){
        $('.subMenu').hide();
    },100);
}

function hideSubMenu(obj){
    intervaloSubMenu = setTimeout(function(){
        $('.subMenu').hide();
    },100);
}

function findCurso(id){
	
    $.expr[':'].icontains = function(obj, index, meta, stack){
        return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
    };
	
    var str = $("#"+id+" input:text").val();
    if (str != "" && str.length > 2){
		
        $cbPresencial	= $("#"+id+' input:checkbox:eq(0)');
        $cbEAD 			= $("#"+id+' input:checkbox:eq(1)');
		
        if ($cbPresencial.attr('checked') || $cbEAD.attr('checked')){

            var spl = str.split(" ");
			
            $("#"+id+" p").hide();
            for (i = 0; i < spl.length;i++){
                if (spl[i] != ""){
					
                    if ($cbPresencial.attr('checked')) $("#"+id+" p.nivel"+$cbPresencial.val()+":icontains('"+spl[i]+"')").show();
                    if ($cbEAD.attr('checked')) $("#"+id+" p.nivel"+$cbEAD.val()+":icontains('"+spl[i]+"')").show();
					
                }
            }
        }
    }else
        viewModalidade(id);

    resultFiltro(id);
}

function viewModalidade(id){
	
    $cbPresencial	= $("#"+id+' input:checkbox:eq(0)');
    $cbEAD 			= $("#"+id+' input:checkbox:eq(1)');
	
    if ($cbPresencial.attr('checked'))
        $("#"+id+" p.nivel"+$cbPresencial.val()).show();
    else
        $("#"+id+" p.nivel"+$cbPresencial.val()).hide();
		
    if ($cbEAD.attr('checked'))
        $("#"+id+" p.nivel"+$cbEAD.val()).show();
    else
        $("#"+id+" p.nivel"+$cbEAD.val()).hide();

    var str = $("#"+id+" input:text").val().replace("Buscar ...","");
	
    if (str != "" && str.length > 2)
        findCurso(id);
    else
        resultFiltro(id);
}

function resultFiltro(id){
    $("#"+id+" .content h3").remove();
    if ($("#"+id+" p:visible").size() == 0) $("#"+id+' .content').prepend("<h3>Nenhum curso encontrado com esse termo</h3>");
}

/* fim filtro de cursos */

function playMovie(path,file,widthV,heightV) {
    var FO = {
        movie:path+"/swf/player.swf",
        width:(widthV)+"px",
        height:(heightV)+"px",
        majorversion:"7",
        build:"0",
        flashvars:"file="+file+"&showdigits=false&allowfullscreen=false"
    };
    UFO.create(FO, 'player');
}


/* Limpar os campos do formulÃ¡rio */
function formReset(frm){
    $(':input',frm).not(':button, :submit, :reset, :hidden')
    .val('')
    .removeAttr('checked')
    .removeAttr('selected');
}

/* Efeito do menu */
function controleMenu(obj){
    $('.menu ul').each(function(index) {
        if ($(obj).children("li:eq(0)").html() == $(this).children("li:eq(0)").html()){
            $(this).children('li:eq(1)').slideDown();
            $(this).children('li:eq(1)').removeClass('hide').addClass('show');
        }else{
            $(this).children('li:eq(1)').slideUp();
            $(this).children('li:eq(1)').removeClass('show').addClass('hide');
        }
    });
}

/* CriaÃ§Ã£o de selects */
function createSelect(path, parentName, targetName, parentClass, childClass, selectedId){
    parent = $(parentName);
    target = $(targetName);

    if (parent != null && parent != undefined && target != null && target != undefined &&
        parentClass != null && parentClass != undefined && childClass != null && childClass != undefined) {
        if (parent.val() != '' && parent.val() != '0' && parent.val() != 0 && parent.val() != '-1' && parent.val() != -1) {
            url = path + "/ajax/" + parentClass + "/" + childClass + "/" + parent.val();
            target.empty().html('<option value="">Carregando ...</option>');

            doJsonPost(url, null, function(json) {
                if (json != null && json.lstItem.length != null && json.lstItem.length > 0){
                    target.attr('disabled', false);
                    target.html('<option value="">-- Selecione --</option>');
                    $(json.lstItem).each(function(i){
                        selected = "";

                        if (selectedId != undefined && $.trim(selectedId) != '' && selectedId == json.lstItem[i][0])
                            selected = "selected=\"selected\"";

                        target.append("<option value=\"" + json.lstItem[i][0] + "\" " + selected + ">" + json.lstItem[i][1] + "</option>");
                    });
                }
                else{
                    target.attr('disabled', true);
                    target.html('<option value="">Nenhum registro encontrado</option>');
                    setTimeout(function(){
                        target.html('<option value="">-- Selecione --</option>');
                    }, 1200);
                }
            });
        }
        else {
            target.attr('disabled', true);
            target.html('<option value="">-- Selecione --</option>');
        }
    }
    return false;
}

/* Envio AJAX */
function doPost(url, target, parameters, successFunction){
    $.post(url, parameters,
        function(data){
            $(target).unbind('ajaxStart');
            $(target).unbind('error');
            $(target).unbind('success');
            if ($.trim(data) != '')
            {
                $(target).empty().html(data);
            }
            if (successFunction != null)
            {
                successFunction(data);
            }
        }
        );
}

function doJsonPost(url, parameters, successFunction){
    $.post(url, parameters,
        function(json){
            if (successFunction != null)
            {
                successFunction(json);
            }
        },
        'json');
}

/* Abertura de popup */
function popup(url, title, width, height){
    var left =  (screen.width / 2) - (width / 2);
    var top =   (screen.height / 2) - (height / 2);

    var targetWin;

    if(document.all){
        targetWin = window.open(
            url,
            '_blank',
            'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
    }
    else{
        targetWin = window.open(
            url,
            title,
            'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
    }

    return targetWin;
}

/* CÃ³digo da tecla */
function getKeyCode(evt){
    var code;
    //IE
    if(document.all) {
        code = evt.keyCode;
    }
    //NETSCAPE
    else if (document.layers && navigator.appName.indexOf("Mozilla") == -1) {
        code = evt.which;
    }
    // Mozilla / FireFox / Opera
    else {
        code = evt.which;
    }

    return code;
}

/* Verifica se o enter foi pressionado */
function isEnterDown(evt){
    return (getKeyCode(evt) == 13);
}

/* limpa todos os inputs */
function clearAllInput()
{
    $('input[type=text]').val("");
    $('input[type=hidden]').val("");
    $('input[type=password]').val("");
    $('textarea').val("");

    $('option[value=-1]').attr('selected','selected');
}

/* Verifica se uma string contÃ©m outra */
function contains(str, val)
{
    return str.indexOf(val) != -1;
}

/* Adiciona parametros a uma url */
function addParam(url, param, value)
{
    if (contains(url, '?') == true)
    {
        url = url + "&" + param + "=" + value;
    }
    else
    {
        url = url + "?" + param + "=" + value;
    }

    return url;
}

/* Codifica uma string */
function encode(text)
{
    var str = "";

    var rand = new Array();

    rand.push("a");
    rand.push("d");
    rand.push("x");
    rand.push("l");
    rand.push("t");
    rand.push("v");
    rand.push("e");
    rand.push("h");
    rand.push("r");
    rand.push("s");

    var sum = 0;

    switch (Math.round(Math.random() * 4)) {
        case 0: {
            str += rand[0];
            sum = 220;
        }
        break;
        case 1: {
            str += rand[1];
            sum = 13;
        }
        break;
        case 2: {
            str += rand[2];
            sum = 47;
        }
        break;
        case 3: {
            str += rand[3];
            sum = 212;
        }
        break;
        case 4: {
            str += rand[4];
            sum = 1025;
        }
        break;
    }

    for (i = 0; i < text.length; i++) {
        alpha = ((text.charCodeAt(i) * 1) + sum);

        if (alpha == '')
            stop = 1;

        beta = rand[Math.round(Math.random() * (rand.length - 1))];
        gama = (Math.round(Math.random() * 9));

        str += '' + alpha + beta + gama;
    }

    return str;
}

/* Decodifica uma string */
function decode(code) {
    var result = "";

    if (code != null) {
        var sumChar = code.charAt(0);

        var sum = 0;

        switch (sumChar) {
            case 'a': {
                sum = 220;
            }
            break;
            case 'd': {
                sum = 13;
            }
            break;
            case 'x': {
                sum = 47;
            }
            break;
            case 'l': {
                sum = 212;
            }
            break;
            case 't': {
                sum = 1025;
            }
            break;
        }

        code = code.substring(1);

        code = code.replace(/[a|d|x|l|t|v|e|h|r|s][0|1|2|3|4|5|6|7|8|9]/g, ";");

        codeSplit = code.split(';');

        for (i = 0; i < codeSplit.length - 1; i++) {
            var asciiCode = (codeSplit[i] * 1) - sum;

            var ch = String.fromCharCode(asciiCode);

            result += ch;
        }
    }
    return result;
}


function okp(e){
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if(e)
		keycode = e.which;
	else
		return true;
	if (keycode == 13) {
		$('#cse-search-box #q').val(removerAcentos($('#cse-search-box #qshow').val()));
		$('#cse-search-box').submit();
    	return false;
	}
	return true;
}

function removerAcentos(texto) {
	   var normal =   "áàãââÁÀÃÂéêÉÊíÍóõôÓÔÕúüÚÜçÇ";
	   var semacento ="aaaaaAAAAeeEEiIoooOOOuuUUcC";

	   var texto2 = "";

	   for (var x = 0; x < texto.length; x++) {
	       if (normal.indexOf(texto.charAt(x)) != -1) {
	            texto2 += semacento.charAt(normal.indexOf(texto.charAt(x)));
	       }
	       else {
	            texto2 += texto.charAt(x);
	       }
	   }

	   return texto2;
	}


