
$(function(){

	
    
    
    
    
    
    $('.bt-contato').click(function(event){
    
        var error = false;
        var errorList = [];
        
        nome = $('#con_nome').val();
        email = $('#con_email').val();
        assunto = $('#con_assunto').val();
        msg = $('#men_contato').val();
        
        
        $('.error').hide();
        $('#error-geral').hide();
        $('#sucess-geral').hide();
        
        if (nome == '' || nome == 'Nome:' || nome == 'Nome inválido') {
            
			 errorList.push('Preencha o campo Nome');
            error = true;
        }
        
        if (email == '' || email == 'E-mail:' || email == 'E-mail inválido' || !validaEmail(email)) {
       		   errorList.push('Preencha o campo com um email válido');
            error = true;
        }
        
        
        if (assunto == '' || assunto == 'Assunto:' || assunto == 'Assunto inválido') {
          	 errorList.push('Preencha o campo Assunto');
            error = true;
        }
        
        if (msg == '' || msg == 'Mensagem inválida') {
            errorList.push('Preencha o campo Mensagem');
            error = true;
        }
        
        
        if (error == false) {
        
            $.ajax({
                type: 'post',
                url: 'http://www.mercadodaaviacao.com.br/ajax.php',
                data: {
                    'acao': 'contato',
                    'nome': $('#con_nome').val(),
                    'email': $('#con_email').val(),
                    'assunto': $('#con_assunto').val(),
                    'msg': $('#men_contato').val(),
                
                
                },
                dataType: 'json',
                success: function(valor){
                
                    if (valor.mensagem == true) {
                        alert('Seu e-mail foi enviado com sucesso, Em breve entraremos em contato');
                    }
                    else {
                        alert('Não foi posivel enviar o seu e-mail. Por favor tente mais tarde');
                        
                    }
                }
            });
            
        }
        else {
        
        
            $('html, body').animate({
                scrollTop: $(".box-meio-head").offset().top
            }, 1100);
            
            errors = '';
            for (i = 0; i < errorList.length; i++) {
                errors += '<li>' + errorList[i] + '</li>';
            }
            
            if (errors) {
                $('#errojs').show();
            }
            
            $('#lista-erros').html('<ul></ul>');
            $('#lista-erros ul').html(errors);
            
            errors = '';
            errorList.length = 0;
            
            $('#lista-erros').slideDown();
            
            event.preventDefault(event);
            return false;
            
        }
        
        event.preventDefault(event);
        return false;
    });
    
    
    
    
    
    
    // bt compartilhar pagina Twitter    
    $('.bt-twitter-compartilhar').click(function(event){
        titulo = URLEncode(document.title);
        link = window.location;
		
		
		
        
        myWindow = window.open("http://twitter.com/share?text="+titulo+"&lang=pt&url=" + link, '', 'width=660,height=530,scrollbars=NO,toolbar=no,location=no,directories=no,status=no,menubar=no');
        
        
        event.preventDefault(event);
        
        return false;
    });
    
    
    
    
    // bt compartilhar pagina Facebook
    $('.bt-facebook-compartilhar').click(function(event){
        link = window.location;
        
        
        myWindow = window.open("http://www.facebook.com/sharer.php?u=" + link, '', 'width=660,height=530,scrollbars=NO,toolbar=no,location=no,directories=no,status=no,menubar=no');
        
        
        //window.open(url, 'Compartilhe no Facebook', 'width=660,height=530,scrollbars=NO,toolbar=no,location=no,directories=no,status=no,menubar=no');
        event.preventDefault(event);
        
        return false;
    });
    
    
    
    // Botão Cupom
    $('.bt-cupom').click(function(event){
    
        $(this).html('Verificando <img src="/theme/img/verificando.gif" />');
        
        
        tipo = $('#tipo-anuncio').text();
        tipo = tipo == 'servicos' ? 'servico' : tipo;
        tipo = tipo == 'aeronaves' ? 'aeronave' : tipo;
        tipo = tipo == 'partes-e-pecas' ? 'parte_peca' : tipo;
        
        $.ajax({
            type: 'post',
            url: 'http://www.mercadodaaviacao.com.br/ajax.php',
            data: {
                'acao': 'cupom',
                'cup': $('#pag_desconto').val(),
                'tipo': tipo
            },
            dataType: 'json',
            success: function(valor){
            
                if (valor.status == 'ok') {
                    $('.bt-cupom').html('Cupom válido');
                    $('#val-desconto .valor span').text(valor.valor);
                    somaPlano();
                }
                else {
                    alert(valor.msg);
                    $('.bt-cupom').html('Utilizar cupom');
                }
            }
        });
        
        
        event.preventDefault(event);
        return false;
    });
    
    $('#pag_desconto').blur(function(){
    
        if ($('#pag_desconto').val() != '') {
        
            $('.bt-cupom').html('Verificando <img src="/theme/img/verificando.gif" />');
            
            tipo = $('#tipo-anuncio').text();
            tipo = tipo == 'servicos' ? 'servico' : tipo;
            tipo = tipo == 'aeronaves' ? 'aeronave' : tipo;
            tipo = tipo == 'partes-e-pecas' ? 'parte_peca' : tipo;
            
            
            
            $.ajax({
                type: 'post',
                url: 'http://www.mercadodaaviacao.com.br/ajax.php',
                data: {
                    'acao': 'cupom',
                    'cup': $('#pag_desconto').val(),
                    'tipo': tipo
                },
                dataType: 'json',
                success: function(valor){
                
                    if (valor.status == 'ok') {
                        $('.bt-cupom').html('Cupom válido');
                        $('#val-desconto .valor span').text(valor.valor);
                        somaPlano();
                    }
                    else {
                        alert(valor.msg);
                        $('.bt-cupom').html('Utilizar cupom');
                    }
                    
                    
                }
            });
        }
    });
    
    
    
    
    
    
    
    // Botão de deletar Anúncio
    $('.bt-excluir').click(function(event){
    
        if (confirm('Você tem certeza quem deseja excluir este anúncio')) {
            return true
        }
        
        event.preventDefault(event);
        return false;
    });
    
    
    
    // Edição de Anúncios
    if ($('.field-fotos .containner').length > 0) {
        $('.field-fotos .containner').slideUp();
    }
    
    if ($('.field-detalhes .containner').length > 0) {
        $('.field-detalhes .containner').slideUp();
    }
    
    // Expandir dos anúncios
    $('.legend-edit span').mouseover(function(event){
        $(this).css('text-decoration', 'none');
    }).mouseout(function(event){
        $(this).css('text-decoration', 'underline');
    });
    
    
    $('.legend-edit span').click(function(event){
        if ($(this).html() == 'esconder') {
            $(this).html('expandir');
            $(this).parents('fieldset').children('.containner').slideUp();
            
            // Campos Textareas
            bkLib.onDomLoaded(function(){
                nicEditors.allTextAreas({
                    height: 100
                })
            });
            
        }
        else {
            $(this).html('esconder');
            $(this).parents('fieldset').children('.containner').slideDown();
        }
        
        
    })
    
    
    
    
    
    
    // Tabelas
    oTable = $('#anu-ativos').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers"
    });
    
    
    oTable2 = $('#anu-inativos').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers"
    });
    
    oTable3 = $('#anu-pendentes').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers"
    });
    
    oTable4 = $('#anu-transacoes').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers"
    });
    
    
    
    // Informações Aeronave 
    if ($('#ae_categoria').length > 0) {
    
       $('input[name="ae_definicao"]').change(function(event){
	   	
    
        $('#ae_categoria').html('<option>Carregando ..</option>');
        
        $.ajax({
            type: 'post',
            url: 'http://www.mercadodaaviacao.com.br/ajax.php',
            data: {
                'acao': 'aeronave',
                'tipo': $(this).val()
            },
            dataType: 'html',
            success: function(valor){
                $('#ae_categoria').html(valor);
              //  $('#baer_modelo').html('<option value="">Selecione Primeiro o tipo de aeronave</option>')
            }
        });
        
        
    });
        
        
        // Campo fabricante
        $('#ae_fabricante').change(function(event){
        
            $('#ae_modelo').html('<option>Carregando ..</option>');
            
            $.ajax({
                type: 'post',
                url: 'http://www.mercadodaaviacao.com.br/ajax.php',
                data: {
                    'acao': 'modelo',
                    'modelo': $(this).val()
                },
                dataType: 'html',
                success: function(valor){
                    $('#ae_modelo').html(valor);
                }
            });
        });
        
    }
    
    
    
    
    
    
    
    
    
    
    
    // Mascaras
    $("#se_cep").mask("99999-999");
    
    
    // Faz a soma do anúncio
    if ($('#soma-compra').length > 0) {
    
        // Quando carrega a Pagina  
        // Avisa para selecionar um plano 
        if ($('input:checked[name="id_plano"]').length == 0) {
            alert('Por favor selecione um plano');
        }
        else {
            // Soma o valor do anuncio	
            somaPlano();
        }
        
        
        // Quando Altera o plano 
        $('.pla-radio').change(function(){
            somaPlano();
        });
        
        
        // Quando Altera ou não o destaque
        $('.pla-destaque').change(function(){
            somaPlano();
        });
        
    }
    
    
    
    /*
     $('input:radio[name="em_finalidade"]').change(function(event){
     if ($(this).val() == '1') {
     $('.em_nome_da_empresa').hide();
     }
     else {
     $('.em_nome_da_empresa').show();
     }
     });
     */
    // Tipo de Preço (Esconder o campo de preçp)
    $('input:radio[name="pp_tipo_preco"]').change(function(event){
        if ($(this).val() == 'Consulte') {
            $('.pp_preco').hide();
        }
        else {
            $('.pp_preco').show();
        }
    });
    
    
    $('input:radio[name="ae_tipo_preco"]').change(function(event){
        if ($(this).val() == 'Consulte') {
            $('.ae_preco').hide();
        }
        else {
            $('.ae_preco').show();
        }
    });
    
    /////////////////////////////////////////////////////////////////
    // Inicializar a galeria
    if ($('#box-galeria-painel').size() > 0) {
    
        ///////////////////////////////////////////////////////////////////////			
        // Configuração Inicial 
        sessaoGaleria = $('#sessao').text();
        tipoGaleria = $('#tipo').text();
        idGaleria = $('#id').text();
        fotosTotalGaleria = $('#totalFotos').text();
        fotosTotalPermitido = $('#totalPermitido').text();
        contUpload = 0;
        formatoPermitidos = "*.jpg";
        aviso = false;
        
        
        ///////////////////////////////////////////////////////////////////////			
        // Instacia o upload
        $('#swfupload-control').swfupload({
            upload_url: "http://www.mercadodaaviacao.com.br/phps/galeria/upload_fotos.php?SESSION=" + sessaoGaleria + "&TIPO=" + tipoGaleria,
            file_size_limit: "10240",
            file_types: formatoPermitidos,
            file_types_description: "Apenas Imagens do tipo jpg",
            file_upload_limit: "0",
            flash_url: "http://www.mercadodaaviacao.com.br/theme/js/uploadswf/swfupload.swf",
            button_image_url: 'http://www.mercadodaaviacao.com.br/theme/js/uploadswf/XPButtonUploadText_94x28.png',
            button_width: 94,
            button_height: 28,
            button_placeholder: $('#button')[0],
            debug: false,
            custom_settings: {
                'SESSION': sessaoGaleria
            }
        }).bind('swfuploadLoaded', function(event){
        
            // Carrega o plugin
        }).bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
            aviso = false;
        }).bind('fileQueued', function(event, file){
            // Seleciona um arquivo
            
            if (contUpload >= fotosTotalPermitido) {
                if (aviso == false) {
                
                    titulo = "Limite de fotos ";
                    $('#msg-dialog').html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>Você atingiu o limite de imagens para este anúncio: Limite ' + fotosTotalGaleria + ' foto(s).</p>');
                    
                    $("#dialog-modal").dialog({
                        width: 340,
                        modal: true,
                        title: titulo,
                        stack: false,
                        buttons: {
                            'Ok': function(){
                                $(this).dialog("close");
                            }
                        }
                    });
                    //alert('Você atingiu o limite de imagens para este anúncio: Limite ' + fotosTotalGaleria + ' foto(s)');
                    aviso = true;
                }
                
                return false;
            }
            else {
                contUpload = contUpload + 1;
                
                $('#ordem-fotos').append('<li id="' + file.id + '" class="item"><div class="img"><img src="http://www.mercadodaaviacao.com.br/theme/img/carregando-foto.gif" /></div><div class="opcoes"><img class="bt-excluir" src="http://www.mercadodaaviacao.com.br/theme/img/bt-deletar.jpg" alt="Excluir" title="Excluir" /></div><div class="legenda">Clique para adicionar uma legenda</div><div class="edit-legenda"><input type="text" value="" class="campo-legenda" name="legenda"><img title="Salvar" alt="Ok" class="ok-legenda" src="http://www.mercadodaaviacao.com.br/theme/img/ok-legenda.png"><div class="both"></div></div></li>');
                
            }
            
            $(this).swfupload('startUpload');
        }).bind('fileQueueError', function(event, file, errorCode, message){
            // AContece algum error referente a seleção de arquivo invalido
            alert('File queue error - ' + message);
        }).bind('uploadProgress', function(event, file, bytesLoaded){
            // Progreso do arquivo        
        }).bind('uploadSuccess', function(event, file, serverData){
        
            //$('#log').append('<li>Upload success - ' + file.name + '</li>');
        }).bind('uploadComplete', function(event, file){ // upload completo
            $.get('http://www.mercadodaaviacao.com.br/phps/galeria/cadastra-foto.php', {
                'nome': file.name,
                'TIPO': tipoGaleria,
                'ID': idGaleria
            }, function(data, text, xmlhhtp){
            
                $('#' + file.id).attr('id', data.id);
                if (data.swf == 'ok') {
                    $('#' + data.id + ' .img').html('<object height="120" width="160" data="http://www.mercadodaaviacao.com.br/arquivo/' + tipoGaleria + '/' + data.nome + '" type="application/x-shockwave-flash"><param value="http://www.mercadodaaviacao.com.br/arquivo/' + tipoGaleria + '/' + data.nome + '" name="movie"><param value="transparent" name="wmode"></object>');
                }
                else {
                    $('#' + data.id + ' .img img').attr('src', 'http://www.mercadodaaviacao.com.br/arquivo/' + tipoGaleria + '/thumb160x120/' + data.nome);
                }
                
                
                $('#' + data.id).attr('id', 'foto-' + data.id);
                
                
                ordem = new Array();
                
                // Caso exista fotos
                if ($('#ordem-fotos .item').size() > 0) {
                
                    $('#ordem-fotos .item').each(function(){
                        ordem.push($(this).attr('id'));
                    });
                    
                    
                    $.get('http://www.mercadodaaviacao.com.br/phps/galeria/ordem_imgs.php', {
                        'ordem': ordem
                    }, function(data){
                    
                        if (data.error == false) {
                        
                            titulo = "Fotografias salvas com sucesso";
                            $('#msg-dialog').html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>A ordem das fotografias foram salvas com sucesso.</p>');
                            
                            $("#dialog-modal").dialog({
                                width: 340,
                                modal: true,
                                title: titulo,
                                stack: false,
                                buttons: {
                                    'Ok': function(){
                                        $(this).dialog("close");
                                    }
                                }
                            });
                            //  alert('Fotografias salvas com sucesso.');
                        }
                        else {
                        
                            titulo = "Não foi possivel salva a ordem das fotos";
                            $('#msg-dialog').html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>A ordem das fotografias não foram salvas. Por favor tente novamente ou entre em contato.</p>');
                            
                            $("#dialog-modal").dialog({
                                width: 340,
                                modal: true,
                                title: titulo,
                                stack: false,
                                buttons: {
                                    'Ok': function(){
                                        $(this).dialog("close");
                                    }
                                }
                            });
                            
                            // alert('Não foi possivel salva a ordem das fotos.');
                        }
                    }, 'json');
                }
                
                
                
            }, 'json');
            //$('#upload-atual').html((file.index + 1));
            $(this).swfupload('startUpload');
        }).bind('uploadError', function(event, file, errorCode, message){
            // Error no upload (AJAX)
            alert('Upload error - ' + message);
        });
        // Fim Instacia o upload
        ///////////////////////////////////////////////////////////////////////	
        
        
        ///////////////////////////////////////////////////////////////////////
        // Organização Fotos
        $("#ordem-fotos").sortable({
            handle: '.img',
            receive: function(event, ui){
            
            },
            stop: function(event, ui){
            
                ordem = new Array();
                
                // Caso exista fotos
                if ($('#ordem-fotos .item').size() > 0) {
                
                    $('#ordem-fotos .item').each(function(){
                        ordem.push($(this).attr('id'));
                    });
                    
                    
                    $.get('http://www.mercadodaaviacao.com.br/phps/galeria/ordem_imgs.php', {
                        'ordem': ordem
                    }, function(data){
                    
                        if (data.error == false) {
                        
                            titulo = "Fotografias salvas com sucesso";
                            $('#msg-dialog').html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>A ordem das fotografias foram salvas com sucesso.</p>');
                            
                            $("#dialog-modal").dialog({
                                width: 340,
                                modal: true,
                                title: titulo,
                                stack: false,
                                buttons: {
                                    'Ok': function(){
                                        $(this).dialog("close");
                                    }
                                }
                            });
                            //  alert('Fotografias salvas com sucesso.');
                        }
                        else {
                        
                            titulo = "Não foi possivel salva a ordem das fotos";
                            $('#msg-dialog').html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>A ordem das fotografias não foram salvas. Por favor tente novamente ou entre em contato.</p>');
                            
                            $("#dialog-modal").dialog({
                                width: 340,
                                modal: true,
                                title: titulo,
                                stack: false,
                                buttons: {
                                    'Ok': function(){
                                        $(this).dialog("close");
                                    }
                                }
                            });
                            
                            // alert('Não foi possivel salva a ordem das fotos.');
                        }
                    }, 'json');
                }
            }
        });
        
        $("#ordem-fotos").disableSelection();
    }// Fim Inicializar a galeria
    /////////////////////////////////////////////////////////////////////////////////////////
    // Botao Excluir 
    $('.bt-excluir').live('click', function(event){
    
        foto = $(this).parents('.item');
        idFoto = foto.attr('id');
        idFoto = idFoto.replace('foto-', '');
        
        
        if (confirm("Você tem certeza que deseja Excluir está foto")) {
            foto = $(this).parents('.item');
            
            idFoto = foto.attr('id');
            idFoto = idFoto.replace('foto-', '');
            
            
            
            
            
            
            
            
            $.get('http://www.mercadodaaviacao.com.br/phps/galeria/del_imgs.php', {
                'tipo': tipoGaleria,
                'id': idFoto
            }, function(data){
            
                if (data.error == false) {
                    foto.hide('slide', {
                        percent: 0
                    }, 300, function(){
                        foto.remove();
                        contUpload--;
                    });
                }
                else {
                    alert(data.msg);
                }
                
            }, 'json');
        }
        
        /*
         if (confirm("Você tem certeza que deseja Excluir está foto")) {
         foto = $(this).parents('.item');
         
         idFoto = foto.attr('id');
         idFoto = idFoto.replace('foto-', '');
         
         $.get('http://www.mercadodaaviacao.com.br/phps/galeria/del_imgs.php', {
         'tipo': tipoGaleria,
         'id': idFoto
         }, function(data){
         
         if (data.error == false) {
         foto.hide('slide', {
         percent: 0
         }, 300, function(){
         foto.remove();
         contUpload--;
         });
         }
         else {
         alert(data.msg);
         }
         }, 'json');
         } */
    });
    
    
    
    
    /////////////////////////////////////////////////////////////////////////////////////////
    // Botao capa 
    $('.bt-capa').live('click', function(event){
    
        idFotoCapa = $(this).parents('.item').attr('id');
        
        atual = $(this);
        
        $.get('http://www.mercadodaaviacao.com.br/phps/galeria/capa_imgs.php', {
            'tipo': tipoGaleria,
            'idLigacao': idGaleria,
            'id': idFotoCapa.replace('foto-', '')
        }, function(data){
        
            if (data.error == false) {
                // removo as imagens de capa
                $('.bt-capa').each(function(){
                    $(this).attr('src', 'http://www.mercadodaaviacao.com.br/theme/img/bt-capa.jpg');
                });
                
                atual.attr('src', 'http://www.mercadodaaviacao.com.br/theme//img/bt-capa-ativo.jpg');
            }
            else {
            
                titulo = data.msg;
                $('#msg-dialog').html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span> ' + data.msg + ' .</p>');
                
                $("#dialog-modal").dialog({
                    width: 340,
                    modal: true,
                    title: titulo,
                    stack: false,
                    buttons: {
                        'Ok': function(){
                            $(this).dialog("close");
                        }
                    }
                });
                
                //alert(data.msg);
            }
            
        }, 'json');
    });
    
    
    /////////////////////////////////////////////////////////////////
    // Legenda
    $('.legenda').live('mouseover', function(){
        $(this).addClass('hover');
    }).live('mouseout', function(){
        $(this).removeClass('hover');
    }).live('click', function(){
        // Pegar a leganda atual
        legendaAtual = $(this).text();
        
        // verico se o campo esta em edição
        if ($(this).data('edicao') == false || $(this).data('edicao') == null) {
        
            $(this).data('edicao', true);
            
            if (legendaAtual == 'Clique para adicionar uma legenda') {
                legendaAtual = '';
            }
            
            
            $(this).parents('.item').children('.edit-legenda').show();
            $(this).parents('.item').children('.edit-legenda').children('.campo-legenda').focus();
            $(this).hide();
            
        }
    });
    
    ///////////////////////////////////////////////////////////////////////////////////////
    // Saida do campo de legenda 
    $('.campo-legenda').live('focusout', function(event){
    
        // Salvo a legenda
        atualOriginal = $(this);
        atual = $(this).parents('.item').children('.edit-legenda').children('.campo-legenda');
        
        
        
        idFoto = $(this).parents('.item').attr('id');
        idFoto = idFoto.replace('foto-', '');
        
        $.get('http://www.mercadodaaviacao.com.br/phps/galeria/legenda_imgs.php', {
            'id': idFoto,
            'legenda': atual.attr('value')
        }, function(data){
        
        
            if (data.error == false) {
            
            
                if (atual.attr('value') == '') {
                    atual.attr('value', 'Clique para adicionar uma legenda');
                }
                
                elementoLegenda = $(atual).parent('.legenda');
                
                atualOriginal.parents('.edit-legenda').hide();
                
                atualOriginal.parents('.item').children('.legenda').html(atual.attr('value')).show().data('edicao', null);
                
                
            }
            else {
            
                titulo = data.msg;
                $('#msg-dialog').html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span> ' + data.msg + ' .</p>');
                
                $("#dialog-modal").dialog({
                    width: 340,
                    modal: true,
                    title: titulo,
                    stack: false,
                    buttons: {
                        'Ok': function(){
                            $(this).dialog("close");
                        }
                    }
                });
                
                if (atual.attr('value') == '') {
                    atual.attr('value', 'Clique para adicionar uma legenda');
                }
                elementoLegenda = $(atual).parent('.legenda');
                
                
                atualOriginal.parents('.edit-legenda').hide();
                atualOriginal.parents('.item').children('.legenda').html(atual.attr('value')).show().data('edicao', null);
                
            }
            
        }, 'json');
        
        
        event.preventDefault(event);
        return false;
    });
    
    
    /////////////////////////////////////////////////////////////////////////////////////////
    // Salvar Galeria
    $('.salvar-galeria').live('click', function(event){
    
    
    
        ordem = new Array();
        
        // Caso exista fotos
        if ($('#ordem-fotos .item').size() > 0) {
        
            $('#ordem-fotos .item').each(function(){
                ordem.push($(this).attr('id'));
            });
            
            
            $.get('http://www.mercadodaaviacao.com.br/phps/galeria/ordem_imgs.php', {
                'ordem': ordem
            }, function(data){
            
                if (data.error == false) {
                
                    titulo = "Fotografias salvas com sucesso";
                    $('#msg-dialog').html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>A ordem das fotografias foram salvas com sucesso.</p>');
                    
                    $("#dialog-modal").dialog({
                        width: 340,
                        modal: true,
                        title: titulo,
                        stack: false,
                        buttons: {
                            'Ok': function(){
                                $(this).dialog("close");
                            }
                        }
                    });
                    //  alert('Fotografias salvas com sucesso.');
                }
                else {
                
                    titulo = "Não foi possivel salva a ordem das fotos";
                    $('#msg-dialog').html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>A ordem das fotografias não foram salvas. Por favor tente novamente ou entre em contato.</p>');
                    
                    $("#dialog-modal").dialog({
                        width: 340,
                        modal: true,
                        title: titulo,
                        stack: false,
                        buttons: {
                            'Ok': function(){
                                $(this).dialog("close");
                            }
                        }
                    });
                    
                    // alert('Não foi possivel salva a ordem das fotos.');
                }
                
            }, 'json');
            
        }
        
        
        return false;
        event.preventDefault(event);
    });
    
    
    
    
    
    
    // Campo Estado
    $('#estado').change(function(event){
    
        $('#cidade').html('<option>Carregando ..</option>');
        
        $.ajax({
            type: 'post',
            url: 'http://www.mercadodaaviacao.com.br/ajax.php',
            data: {
                'acao': 'cidades',
                'estado': $(this).val()
            },
            dataType: 'html',
            success: function(valor){
                $('#cidade').html(valor);
            }
        });
        
        
    });
    
    
    /* 
     bkLib.onDomLoaded(function(){
     
     if ($('#men_contato').length > 0) {
     new nicEditor({
     height: 100
     }).panelInstance('men_contato');
     }
     
     if ($('#ae_informacoes_gerais').length > 0) {
     // Cadastro de Aeronave
     new nicEditor().panelInstance('ae_informacoes_gerais');
     new nicEditor().panelInstance('ae_status_inspencao');
     new nicEditor().panelInstance('ae_motor');
     new nicEditor().panelInstance('ae_helice');
     new nicEditor().panelInstance('ae_avionicos');
     new nicEditor().panelInstance('ae_exterior');
     new nicEditor().panelInstance('ae_interior');
     new nicEditor().panelInstance('ae_equipamentos_adicionais');
     new nicEditor().panelInstance('ae_modificacoes');
     }
     });
     */
});





function somaPlano(){
    somaTotal = 0;
    
    idPlano = $('input:checked[name="id_plano"]').val();
    
    
    valorPlano = parseFloat($('#val-plano' + idPlano).text());
    valorDestaque = parseFloat($('#val-destaque' + idPlano).text());
    destaque = $('#destaque' + idPlano).text();
    
    
    
    
    // Casas Decimais
    valorPlano = valorPlano.toFixed(2);
    valorDestaque = valorDestaque.toFixed(2);
    
    
    // Soma Total
    somaTotal = valorPlano;
    
    // Escondo o campo de destaque
    if (destaque == 1) {
        $('#destaque-plano').hide();
        $('#val-destaque').hide();
    }
    else {
        $('#destaque-plano').show();
        $('#val-destaque').show();
    }
    
    
    
    // Coloco os valor do Plano
    $('#val-plano .valor span').text(valorPlano.replace('.', ','));
    
    
    if (destaque == 2) {
        // Verifica se aumentar o destaque
        if ($('input:checked[name="pag_destaque"]').length > 0) {
            $('#val-destaque .valor span').text(valorDestaque.replace('.', ','));
            somaTotal = parseFloat(somaTotal) + parseFloat(valorDestaque);
        }
        else {
            $('#val-destaque .valor span').text('0,00');
        }
    }
    
    
    
    // Desconto
    $desconto = $('#val-desconto .valor span').text();
    $desconto = parseFloat($desconto.replace(',', '.'));
    
    
    
    
    // Soma Total
    somaTotal = parseFloat(somaTotal);
    somaTotal = somaTotal - $desconto;
    somaTotal = somaTotal.toFixed(2);
    $('#soma-total .valor span').text(somaTotal.replace('.', ','));
}


function mascaras(valor, id, mascara, evento){
    /////////////////////////////////////////////////////////////////////////////////
    //                             MODELO  DE MÁSCARA                              //
    //onkeyup="mascaras(this.value, this.id, '####.##.##.#######-#/#', event)"//
    /////////////////////////////////////////////////////////////////////////////////
    
    /////////////////////////////////////////////////////////////////////////////////
    //                         MODELO  DE MÁSCARA MONETÁRIA                        //
    //onkeyup="mascaraHellas(this.value, this.id, 'money', event)"                 //
    /////////////////////////////////////////////////////////////////////////////////
    
    
    //inicializa a variavel que vai conter o valor final
    var valorFinal = "";
    
    //verifica o que foi digitada para que seja verificado se é somente números ou não
    var tecla = evento.keyCode;
    
    //manetem o tamanho original do campo sem retirar a máscara
    var valorOriginal = valor;
    
    //inicializa um array com todos os caracteres que serão retirado
    var arrNaoPermitidos = new Array("-", ".", "/", "\\", "|", "(", ")", ":", " ", ",");
    
    //retira qualquer máscatra que já tenho sido colocada
    for (i1 = 0; i1 < valor.length; i1++) {
        for (i2 = 0; i2 < arrNaoPermitidos.length; i2++) {
            if (valor.charAt(i1) == arrNaoPermitidos[i2]) {
                valor = valor.toString().replace(arrNaoPermitidos[i2], "");
            }
        }
    }
    
    //merifica se a máscara é mometária ou uma máscara fixa
    if (mascara == "money") {
        //retira os zeros da frente do valor
        var temZero = true;
        while (temZero == true) {
            if (valor.substring(0, 1) == "0") {
                valor = valor.substring(1, valor.length);
            }
            else {
                temZero = false;
            }
        }
        
        //verifica se foi precionado o backspae
        if (tecla == 8) {
            valor = valor.substring(0, valor.length);
        }
        
        //faz as verificações para a formatação do valor
        if (valor.length == 1) {
            valorFinal = "0,0" + valor;
        }
        else 
            if (valor.length == 2) {
                valorFinal = "0," + valor;
            }
            else 
                if (valor.length == 4 && valor.substr(0, 2) == "00") {
                    valorFinal = "0," + valor.substr(2);
                }
                else 
                    if (valor.length == 4 && valor.substr(0, 1) == "0" && valor.substr(0, 2) != "00") {
                        valorFinal = valor.substr(1, 1) + "," + valor.substr(2);
                    }
                    else 
                        if (valor.length >= 4 || valor.length == 3) {
                            var parteInteira = valor.substr(0, (valor.length - 2));
                            var parteDecimal = valor.substr((valor.length - 2))
                            var inteiro = "";
                            var cont = 1;
                            var milhar = "";
                            
                            for (i = parteInteira.length; i > 0; i--) {
                                if (cont == 4) {
                                    milhar = ".";
                                    cont = 2;
                                }
                                else {
                                    milhar = "";
                                    cont++;
                                }
                                
                                inteiro = parteInteira.substr((i - 1), 1) + milhar + inteiro;
                            }
                            
                            valorFinal = inteiro + "," + parteDecimal;
                        }
                        else {
                            valorFinal = "0,00";
                        }
    }
    else {
        //verifica se foi precionado o backspae
        if (tecla != 8) {
            //verifica se já não ultrapassou o tamanha máximo da máscara
            if (mascara.length >= valorOriginal.length) {
                //loop em cima do valor do campo sem a máscara
                jaTemMascara = false;
                for (i = 0; i < valor.length; i++) {
                    //verifica se a string já recebeu alguma máscara ou não
                    if (jaTemMascara == false) {
                        //verifica se o tipo da entrada de dados tem que ser némerica
                        if (mascara.charAt(i) == "#") {
                            //verifica se foi digitado somente números
                            if (((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16) {
                                //0 = 96 ou 48
                                //1 = 97 ou 49
                                //2 = 98 ou 50
                                //3 = 99 ou 51
                                //4 = 100 ou 52
                                //5 = 101 ou 53
                                //6 = 102 ou 54
                                //7 = 103 ou 55
                                //8 = 104 ou 56
                                //9 = 105 ou 57
                                //tecla == 9 = tab
                                valorFinal = valorFinal + valor.charAt(i);
                            }
                            else//se não foi digitado um número é retirado o caracter da string
                            {
                                valorFinal = valorOriginal.substring(0, valorOriginal.length - 1);
                            }
                        }
                        else 
                            if (mascara.charAt(i) == "@")//verifica se o tipo da entrada é qualquer caracter
                            {
                                valorFinal = valorFinal + valor.charAt(i);
                            }
                            else//se não for quelaquer caracter é algum elemento da máscara
                            {
                                //verifica se o próxima depois da máscara é númerica 
                                if (mascara.charAt(i + 1) == "#") {
                                    //verifica se foi digitado somente números
                                    if (((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16) {
                                        //0 = 96 ou 48
                                        //1 = 97 ou 49
                                        //2 = 98 ou 50
                                        //3 = 99 ou 51
                                        //4 = 100 ou 52
                                        //5 = 101 ou 53
                                        //6 = 102 ou 54
                                        //7 = 103 ou 55
                                        //8 = 104 ou 56
                                        //9 = 105 ou 57
                                        //tecla == 9 = tab
                                        valorFinal = valorFinal + mascara.charAt(i + jaTemMascara) + valor.charAt(i);
                                        jaTemMascara = jaTemMascara + 1;
                                    }
                                    else//se não foi digitado um número é retirado o caracter da string
                                    {
                                        valorFinal = valorOriginal.substring(0, valorOriginal.length - 1);
                                    }
                                }
                                else// se não é númerico então pode ser qualuqer caracter
                                {
                                    valorFinal = valorFinal + mascara.charAt(i + jaTemMascara) + valor.charAt(i);
                                    jaTemMascara = jaTemMascara + 1;
                                }
                            }
                    }
                    else//else da verificação da máscara
                    {
                        //verifica se foi digitado somente números
                        if (mascara.charAt(i + jaTemMascara) == "#") {
                            //verifica se foi digitado somente números
                            if (((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16) {
                                //0 = 96 ou 48
                                //1 = 97 ou 49
                                //2 = 98 ou 50
                                //3 = 99 ou 51
                                //4 = 100 ou 52
                                //5 = 101 ou 53
                                //6 = 102 ou 54
                                //7 = 103 ou 55
                                //8 = 104 ou 56
                                //9 = 105 ou 57
                                //tecla == 9 = tab
                                valorFinal = valorFinal + valor.charAt(i);
                            }
                            else//se não foi digitado um número é retirado o caracter da string
                            {
                                valorFinal = valorOriginal.substring(0, valorOriginal.length - 1);
                            }
                        }
                        else 
                            if (mascara.charAt(i + jaTemMascara) == "@")//verifica se o tipo da entrada é qualquer caracter
                            {
                                valorFinal = valorFinal + valor.charAt(i);
                            }
                            else {
                                //verifica se foi digitado somente números
                                if (mascara.charAt(i + jaTemMascara + 1) == "#") {
                                    //verifica se foi digitado somente números
                                    if (((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16) {
                                        //0 = 96 ou 48
                                        //1 = 97 ou 49
                                        //2 = 98 ou 50
                                        //3 = 99 ou 51
                                        //4 = 100 ou 52
                                        //5 = 101 ou 53
                                        //6 = 102 ou 54
                                        //7 = 103 ou 55
                                        //8 = 104 ou 56
                                        //9 = 105 ou 57
                                        //tecla == 9 = tab
                                        valorFinal = valorFinal + mascara.charAt(i + jaTemMascara) + valor.charAt(i);
                                        jaTemMascara = jaTemMascara + 1;
                                    }
                                    else//se não foi digitado um número é retirado o caracter da string
                                    {
                                        valorFinal = valorOriginal.substring(0, valorOriginal.length - 1);
                                    }
                                }
                                else// se não é númerico então pode ser qualuqer caracter
                                {
                                    valorFinal = valorFinal + mascara.charAt(i + jaTemMascara) + valor.charAt(i);
                                    jaTemMascara = jaTemMascara + 1;
                                }
                            }
                    }//fim da verificação da máscara	
                }
            }
            else {
                valorFinal = valorOriginal.substring(0, mascara.length);
            }//final da verificação do tamanha máximo da string
        }
        else {
            //valorFinal = valorOriginal.substring(0, valorOriginal.length -1)
            valorFinal = valorOriginal.substring(0, valorOriginal.length);
        }//final da verificação do backspace		
    }
    document.getElementById(id).value = valorFinal;
    
    //faz as verificações para que seja feito o tab automático
    if (mascara != "money") {
    
    }
}

