/*------------------------------------------------------------------------
* Script Main.
*------------------------------------------------------------------------
* Projeto CIDEPE
*------------------------------------------------------------------------
* dEx | design digital + gráfico -  http://www.dexdesign.com.br
* @author Jackson F. de Andrade Mafra <jacksonfdam@gmail.com>
* @copyright Copyright (c) 2010, dEx | design digital + gráfico
*------------------------------------------------------------------------
*/
function retiraAcento(obj)
{
    palavra = String.fromCharCode(event.keyCode);

    var caracteresInvalidos = 'àèìòùâêîôûäëïöüáéíóúãõÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÁÉÍÓÚÃÕ';
    var caracteresValidos =   'aeiouaeiouaeiouaeiouaoAEIOUAEIOUAEIOUAEIOUAO';
    var acento = "´`^¨~";
    if(acento.indexOf(palavra)!= -1)
    {
        window.event.keyCode = 0;
    }

    if (caracteresInvalidos.indexOf(palavra) == -1)
    {
        if (caracteresValidos.indexOf(palavra) != -1) {
            window.event.keyCode = 0;
            obj = obj + palavra;
        }
    }
    else
    {
        window.event.keyCode = 0;
        nova = caracteresValidos.charAt(caracteresInvalidos.indexOf(palavra));
        obj =  obj + nova;
    }
    return obj
}

function removeAcentos(palavra) {

    var com_acento = 'áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ';
    var sem_acento = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';
    var nova='';
    for(var i=0;i<palavra.length;i++) {
        if (com_acento.search(palavra.substr(i,1))>=0) {
            nova+=sem_acento.substr(com_acento.search(palavra.substr(i,1)),1);
        }
        else {
            nova+=palavra.substr(i,1);
        }
        nova = nova.replace(/[´`^¨~]/, '');
    }
    return nova;

}
J(document).ready(function(){	

	J('a.nyroModal').nyroModal({
		windowResize: true,
		resizable: true, // Indicate if the content is resizable. Will be set to false for swf
		autoSizable: true
	});

	
	
    var x = '';
    var _busca_url = (idioma == 'pt') ? 'busca' : ( (idioma == 'en') ? 'search' : 'busca');
    
    J(document).click(function(){
        J('#autocomplete_choices').hide();
    });
	
    J('#send_search').click(function(e){
        e.preventDefault();
        J('#search').submit();
    });
    J('#autocomplete_choices').click(function(){
        J('#autocomplete_choices').show();
    });
    J('#search').submit(function(e){
        e.preventDefault();
        if( ( J('input[name="function_name"]', this).val() != J('input[name="function_name"]', this).attr('title') ) && J('input[name="function_name"]', this).val().length > 1){
            window.location.href= siteUrl + idioma + '/' +  _busca_url + '/' + removeAcentos(J('input[name="function_name"]', this).val().toLowerCase());
        }else{
            return false;
        }
    });
    J('#function_name').keyup(function(){			
        J('#autocomplete_choices').html('');
        J('#autocomplete_choices').hide();
        if(x != ''){
            x.abort();
        }
        if(J(this).val().length > 3){
            x = J.ajax({
                type: "post",
                url: siteUrl + idioma + "/busca/ajaxsearch/",
                dataType:'html',
                cache:false,
                data: {
                    'termo': J(this).val(),
                    'idioma':idioma
                },
                beforeSend: function(){
                    J('#autocomplete_choices').css('position','relative');
                    J('#autocomplete_choices').css('top','20px');
                    J('#autocomplete_choices').css('width','229px');
                    J('#autocomplete_choices').html('Aguarde...').slideDown();
                },
                success: function(data) {
                    J('#autocomplete_choices').html('');
                    J('#autocomplete_choices').html(data).slideDown();
                },
                error:function (xhr, ajaxOptions, thrownError){
                //console.error(thrownError);
                }
            });
        }
    });
    /*J('input.qty').blur(function(){
        J.ajax({
            type: "post",
            url: siteUrl + "orcamentos/updateCart/",
            dataType:'html',
            cache:false,
            data: {
                'qty': J(this).val(),
                'rowId': J(this).attr('rel'),
            },
            beforeSend: function(){

            },
            success: function(data) {

            },
            error:function (xhr, ajaxOptions, thrownError){
            //console.error(thrownError);
            }
        });
    });
	*/
	J('input.qty').blur(function(){
		J.post(siteUrl + "orcamentos/updateCart/", { qty: J(this).val(), rowId: J(this).attr('rel') },
			function(data){
			//alert("Data Loaded: " + data);
		});						 
	});
			
    J('#subcategories img').mouseover(function(){
        return false;
    }).each(function(){
        J(this).qtip({
            content: J(this).attr('title').replace(/^([^-]+)/, '<b>$1</b>'),
            style: {
                name: 'light',
                fontFamily: 'Trebuchet MS, Arial, Helvetica, sans-serif',
                fontSize: '11px',
                color: '#000000',
                background: '#FFFFFF',
                width: 260,
                tip: 'bottomLeft',
                border: {
                    radius: 5
                }
            },
            position: {
                corner: {
                    target: 'topRight'
                },
                target: 'mouse',
                adjust: {
                    mouse: true,
                    y: -70
                }
            },
            show: {
                delay:0,
                effect: {
                    length:50
                }
            },
            hide: {
                delay:0,
                effect: {
                    length:50
                }
            }
        })
    }).attr('title','');

		
    J("#map h3").mouseover(function(){
        J(this).next().fadeIn('fast');
    }).mouseout(function(){
        J(this).next().fadeOut('fast');
    });
	
    J("#map li > a").mouseover(function(){
        J(this).prev().fadeIn('fast');
    }).mouseout(function(){
        J(this).prev().fadeOut('fast');
    });
	
	var size = J("#slideview li").size();
	
	//VERIFICA SE É MULTIPLO DE 3 OU DE 2
	//var scroll = 3;
	
	//if((size%3) == 0){
	//	scroll = 3;
	//}else if((size%2) == 0){
	//	scroll = 2;
	//}

    J("#slideview").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".previous",
        mouseWheel: false,
		visible: 3,
		scroll: 3,
		circular: true
		
    });
	//HOME SLIDESHOW

	J('#slide').before('<div id="nav" class="nav">').cycle({
        fx:     'scrollLeft',
        speed:  'fast',
        timeout: 4000,
        pager:  '#nav'
    });	

    J("a[href*='http://']").click(function(){
        //J(this).attr("target", "_blank");
    });
	
    J(".ParibusForm input, .ParibusForm textarea").each(function(){
        if(J(this).attr('value') != '')
            J(this).prev().hide();
    });
	
    J(".ParibusForm input, .ParibusForm textarea").keydown(function(){
        J(this).prev().fadeOut("fast");
    });
	
    J(".ParibusForm input, .ParibusForm textarea").keyup(function(e){
        if(J(this).attr("value") == ""){
            J(this).prev().fadeIn("fast");
        }
    });
	
    J(".ParibusForm input, .ParibusForm textarea").blur(function(e){
        if(J(this).attr("value") == ""){
            J(this).prev().fadeIn("fast");
        }
    });
	
    J("#box-info .Tabs a").click(function(e){
        e.preventDefault();
		
        J('#box-info .Tabs a').removeClass('Active');
        J('#box-info .Box').slideUp('fast');
		
        J(this).addClass('Active');
        var boxId = J(this).attr('href');
		
        J(boxId).slideDown('slow');
    });
	
    // Crio uma variável chamada Jforms que pega o valor da tag form
    Jforms = J('form');

    // hide(): esconde a div cadastro enquanto carrega o ready()
    J('#cadastro').hide();

    /**
     bind(): é manipulador de evento exemplo submit, click e/ou double click
     a: é a tag <a href>
    */

    J('a').bind('click', function(){
        switch(this.id){
            case 'c':
                J('#cadastro').show(); // show(): mostra div que está oculta (hide()).
                return false;
                break;
        }
    });
    //validação de cadastro para newsletter
    J("#register-news").validate({
        // Define as regras
        rules:{
            nome:{
                required: true
            },
            email:{
                required: true,
                email: true
            }
        },
        // Define as mensagens de erro para cada regra
        messages:{
            nome:{
				required: "Digite seu nome"
            },
            email:{
                required: "Digite seu e-mail",
                email: "Digite um email válido"
            }
        },
		
        errorPlacement: function(error, element) {
            error.insertBefore(element);
        },
		submitHandler: function(form) {
			J.post('header/create' , J('#register-news').serialize() , function(retorno) {
				if(retorno == true){
					form.reset();
					alert('Cadastro efetuado com sucesso!');
				}else{
					alert('Erro ao efetuar cadastro, tente novamente mais tarde!');
				}
			});
		},	
        errorClass:"Error",
        errorElement:"strong"
    });
    J('form').attr("autocomplete", 'off');
    
    Jforms.bind('#register-news', function(){

        /**
        Crio a variável Jbutton
        attr(): set a propriedade de um atributo, nesse exemplo foi desativado o botão com a tag button
        */
        var Jbutton = J('button',this).attr('disabled',true);

        /**
       Criada a variável params
        serialize(): pega os dados inseridos no formulário
        */
        var params = J(this.elements).serialize();

        var self = this;
        J.ajax({

            // Usando metodo Post
            type: 'POST',

            // this.action pega o script para onde vai ser enviado os dados
            url: this.action,

            // os dados que pegamos com a função serialize()
            data: params,

            // Antes de enviar
            beforeSend: function(){
                // mostro a div loading
                J('#loading').show();

                // html(): equivalente ao innerHTML
                J('#loading').html("Carregando...");
            },
            success: function(txt){
                // Ativo o botão usando a função attr()
                Jbutton.attr('disabled',false);

                // Escrevo a mensagem
                J('#loading').html(txt);

                // Limpo o formulário
                self.reset();
            },

            // Se acontecer algum erro é executada essa função
            error: function(txt){
                J('#loading').html(txt);
            }
        })
        return false;
    });
});    
