function disableEnableUF(country) {
    country = country.replace(/\s/g,'').toLowerCase();
    if (new RegExp('^br(a[sz]il)?$').test(country)) {
        if (!document.getElementById('estado')) {
            var uf = ["AC","AL","AM","AP","BA","CE","DF","ES","GO","MA","MG","MS","MT","PA","PB","PE","PI","PR","RJ","RN","RO","RR","RS","SC","SE","SP","TO"];
            var select = jQuery('<select name="estado" id="estado" title="Selecione seu Estado">');
            select.append('<option value="" />');
            for (var i=0; i<uf.length; i++) { select.append('<option value="'+ uf[i] +'">'+ uf[i] +'</option>'); }
                    
            $('#uf_cadastrarPonto label:first').after(select);
        } 
        jQuery('#uf_cadastrarPonto').show();
    }
    else {
        jQuery('#uf_cadastrarPonto').hide();
        jQuery('select#estado').remove();
    }
}
function enableFields(enable) {
	if (enable == false) {
        jQuery("#btMarkPoint").hide();
        jQuery("#divLoad").show();
        jQuery('#mapaSugestao_pelicula').addClass('pelicula_mapa');
        jQuery('#cadastrarPonto :input').enable(false);        
	} else {
        jQuery("#cadastrarPonto p.error").hide();        
        jQuery('#cadastrarPonto :input').enable();
        jQuery('#mapaSugestao_pelicula').removeClass('pelicula_mapa');
        jQuery("#divLoad").hide();
        jQuery("#btMarkPoint").show();
	}
}
jQuery().ajaxError(function(a, b, e) {                
    alert('Operação mal sucedida:\n\n'+ 
          'status: '+ b.status +'\n'+
          'erro: '+ b.responseText );
    // throw e;
    enableFields();
});
jQuery(document).ready(function() {
    $('#cadastrarPonto').submit(function() { return false; });
    var validator = $("#cadastrarPonto").bind("invalid-form.validate", function() {
        var errors = validator.numberOfInvalids();
		if (errors) {
			var message = (errors == 1)
				? 'O formulário contém 1 erro, veja detalhe abaixo.'
				: 'O formulário contém '+ errors +' erros, veja detalhes abaixo.';
				
			$("#cadastrarPonto p.error span").html(message);
			$("#cadastrarPonto p.error").show();
		} else {
			$("#cadastrarPonto p.error").hide();
		}				
	}).validate({
        submitHandler: function(form) {
            var options = {
            	dataType:'json',
                beforeSubmit: showRequest, 
                success: showResponse,
                resetForm: true,
                contentType: 'application/x-www-form-urlencoded; charset=utf-8'
            };
            function showResponse(response, statusText)  { 
                if (statusText == 'success') {
                    if (map && imagem_n && response.codigo) {                   	
                        marker = createMarker(response, imagem_n);
                        map.addOverlay( marker );
                        map.setCenter(marker.getLatLng(), 11);                        
                        GEvent.trigger(marker,'click');
                        //
                        closePopUp();
                    }
                } else {
                	alert('Status: '+statusText+'\nErro: '+response);
                	enableFields();
                }
            }
            function showRequest(formData, jqForm, options) { enableFields(false); }
            jQuery(form).ajaxSubmit(options);            
        },       
        rules: {
			nome: { required: true, minlength: 2 },
			email: { required: true, email: true },
            latitude: "required",
            longitude: "required",
			country: "required",
			estado: "required",
			cidade: "required",
			mensagem: { required: true, minlength: 30 }
		},
		messages: {
			nome: { required: "Informe o seu nome!", minlength: "Seu nome deve ter pelo menos 2 caracteres" },
			email: { required: "Informe seu e-mail!", email: "Informe um e-mail válido!" },
            latitude: "Informe a posição do ponto no mapa para obtenção da 'latitude'!",
            longitude: "Informe a posição do ponto no mapa para obtenção da 'longitude'!",
			country: "Informe o nome do país",
			estado: "Informe o nome do estado",
			cidade: "Informe o nome da cidade",
			mensagem: { required: "Informe a sua mensagem!", minlength: "A mensagem deve ter pelo menos 30 caracteres!" }
		}
	});    
    $("input#country").blur(function() {
        var input = jQuery(this);
        input.val( input.val().replace(/\s/g,'') );
        disableEnableUF(input.val());
    });    
    $("input#country").keyup(function(){ disableEnableUF(this.value) });
    $("input#country").focus(function(){ disableEnableUF(this.value) });
    //
	// criando pela 1a vez!
	disableEnableUF('br');
});
function openPopUp() {
	enableFields();
	//
	jQuery('#popup').show("slow");
    jQuery('#pelicula').addClass('pelicula');
    //
    if (mapSugestao == null)
         inicializeMapPopUp();
    else {
        mapSugestao.clearOverlays();
        mapSugestao.setCenter(G_LAT_LNG_DEFAULT, 3);
    }
}
function closePopUp() {
    jQuery('#popup').hide("slow");
    jQuery('#pelicula').removeClass('pelicula');
    //
    enableFields();
}
function contador(elemento,tamanho,contador) {
    if(elemento.value.length <= tamanho)
        document.getElementById(contador).value = tamanho - elemento.value.length;
    else {
        alert("Por favor, preencha o campo até " + tamanho + " caracteres.");
        elemento.value = elemento.value.substring(0,tamanho);
    }
}
function checado(check) {
    var c = check.checked;
    if(check.checked) {
        $("input[type='checkbox'][name='ajudas\[\]']").each(function() { jQuery(this).attr('checked', ''); });
    }
    check.checked = c;
}
function limparUltimo() { $("input[type='checkbox'][name='ajudas\[\]']:last").attr('checked', ''); }