//<![CDATA[


var _main                 = {
    init          : function() {
        this.before();
    },
    before        : function() {
        libraries.jQvalidate.init		= true;
        libraries.jCharcounter.init    = true;
        libraries.jQmask.init          = true;
        libraries.jQfield.init         = true;
        libraries.jQform.init         = true;
        libraries.jQModal.init         = true;
        _loader.core();
    },
    after         : function() {
		category_job.init();
		validateForm.init();
		selectdeficiente.init();
		counter.init();
		mask.init();
		getAddress.init();
		captcha.init();
		field.init();
		validateresetpassword.init();
		cityAjax.init();
    }
};

var category_job = {
    init    : function() {
        if (this.check())  this.core();
    },
    check   : function() {
        return ( _exists('#category') ) ? true : false;
    },
	core	: function(){
	   //$('.categoria_especial').hide();
       $('#category').live('change',function (){
            if( ! $(this).val() ){
                $('#descricao_pessoal').fadeOut();
                $('.categoria_especial').fadeOut();
            } else if( $(this).val()=='realizadores_independentes' ){
                $('#descricao_pessoal').fadeIn();
                $('.categoria_especial').fadeOut();
            } else {
                $('#descricao_pessoal').fadeOut();
                $('.categoria_especial').fadeIn();
            }
        });
	}
}


Destino = null;

var cityAjax = {
	
    init    : function() {
        if (this.check())  this.core();
    },
    check   : function() {
        return ( _exists('#estado') ) ? true : false;
    },
	core	: function(){
			//busca cidades
		$("#estado").live('change',function(){
			Destino = $("#cidade");
			if( $(this).val() ) {
				Destino.attr('disabled','disabled');
				$.ajax({
					url: def.project.path + "accounts/users/city/" + $(this).find('option:selected').text() +"/js",
					dataType: 'json',
					success: function(j){
						var options = '<option value="">Selecione a cidade</option>';
						Cidades = j;
						for (var i in j) {
							options = options + '<option value="' + i + '">' + j[i] + '</option>';
						}
						//Destino.bind('change',liga_mostra_regiao);
						Destino.html(options).removeAttr('disabled');
					}
				});
			} else {
				Destino.html('<option value="">-- </option>').attr('disabled','disabled');
			}
		});
        if ( _exists('#institution_state') ){
            $("#institution_state").live('change',function(){
                Destino = $("#institution_city");
                if( $(this).val() ) {
                    Destino.attr('disabled','disabled');
                    $.ajax({
                        url: def.project.path + "accounts/users/city/" + $(this).find('option:selected').text() +"/js",
                        dataType: 'json',
                        success: function(j){
                            var options = '<option value="">Selecione a cidade</option>';
                            Cidades = j;
                            for (var i in j) {
                                options = options + '<option value="' + i + '">' + j[i] + '</option>';
                            }
                            //Destino.bind('change',liga_mostra_regiao);
                            Destino.html(options).removeAttr('disabled');
                        }
                    });
                } else {
                    Destino.html('<option value="">-- </option>').attr('disabled','disabled');
                }
            });
        }
	}
}


var validateForm          = {

    init    : function() {
        if (this.check())  this.core();
    },

    check   : function() {
        return ( _exists('#registrationForm') &&
                typeof jQuery.fn.validate == 'function'  &&
                typeof jQuery.fn.ajaxSubmit == 'function' ) ? true : false;
    },
    
    core    : function() {
        $('input:reset').click( function() {
            $('#registrationForm').validate().resetForm();
        });

		$.validator.addMethod("alpha", function(value, element) {
			return this.optional(element) || /^([a-zà-úA-ZÀ-Ú ]+)$/i.test(value);
		});

		$.validator.addMethod("dateEmpty", function(value, element) {
			return ( this.optional(element) || (value!='__/__/____'))
		});

        $.validator.addMethod("cpfEmpty", function(value, element) {
			return ( this.optional(element) || (value!='___.___.___-__'))
		});

		$.validator.addMethod("cpfMobile", function(value, element) {
			return ( this.optional(element) || (value!='(__) ____-____'))
		});

        $.validator.addMethod("dateBR", function(value, element) {
           //contando chars
          if(value.length!=10) return false;
          // verificando data
          var data    = value;
          var dia     = data.substr(0,2);
          var barra1    = data.substr(2,1);
          var mes     = data.substr(3,2);
          var barra2    = data.substr(5,1);
          var ano     = data.substr(6,4);
          if(data.length!=10||barra1!="/"||barra2!="/"||isNaN(dia)||isNaN(mes)||mes==0||isNaN(ano)||dia>31||dia==0||mes>12)return false;
          if((mes==4||mes==6||mes==9||mes==11) && dia==31)return false;
          if(mes==2  &&  (dia>29||(dia==29 && ano%4!=0)))return false;
          if(ano < 1900 || ano > 2009)return false;
          return true;
        }, "Informe uma data válida");  // Mensagem padrão
        

		// cadastro completo
		if ( _exists('#cpf') ){
            $.validator.addMethod("cpf", function(value, element) {
                value = value.replace('.','');
                value = value.replace('.','');
                cpf = value.replace('-','');
                while(cpf.length < 11) cpf = "0"+ cpf;
                var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
                var a = [];
                var b = new Number;
                var c = 11;
                for (i=0; i<11; i++){
                  a[i] = cpf.charAt(i);
                  if (i < 9) b += (a[i] * --c);
                }
                if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
                b = 0;
                c = 11;
                for (y=0; y<10; y++) b += (a[y] * c--);
                if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
                if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) return false;
                return true;
            }, "Informe um CPF válido."); // Mensagem padrão
            
			$('#registrationForm').validate({
				rules:{
					alternate_email:{
						required	: false, email		: true
					},
					name            :{
						required	: true, alpha		: true, minlength	: 2
					},
					surname         :{
						required	: true, alpha		: true, minlength	: 2
					},
					gender          :{
						required	: true
					},
					birthday        :{
						required	: true, dateEmpty	: true, dateBR      : true
					},
					profile         :{
						required	: true
					},
					cpf				:{
						required	: true, cpfEmpty    : true, cpf			: true
					},
					category		:{
						required	: true
					},
					tipodedeficiencia:{
						required	: true
					},
					campocep        :{
						required	: true
					},
					endereco        :{
						required	: true, minlength   : 5
					},
					numero          :{
						required	: true, number      : true
					},
					bairro          :{
						required	: true, minlength   : 2
					},
					cidade          :{
						required	: true
					},
					estado          :{
						required	: true
					},
					telefone        :{
						required	: true, cpfMobile   : true
					},
					telefonecelular :{
						required	: false, cpfMobile   : false
					},
					captcha         :{
						required	: true, remote      : '/check-captcha/'
					},
					descricaopessoal:{
						required	: function () {
							if ( $("#category").val()=='realizadores_independentes' ){
								return true;
							} else { return false }
						},
						minlength	: 50, maxlength   : 600
					},
					institution_email:{
						required: false,
						email	:	true
					},
					institution_phone:{
						required	: validateForm.categoria,
						cpfMobile	:	true
					},
					institution_address:{
						required	: validateForm.categoria
					},
					institution_state:{
						required	: validateForm.categoria
					},
					institution_city:{
						required	: validateForm.categoria
					},
					institution_name:{
						required	: validateForm.categoria
					}
				},
				
				messages:{
					alternate_email :{
						email		: 'E-mail inválido.'
					},
					name            :{
						required	: 'Campo de preenchimento obrigatório.',
						minlength	: 'O campo nome deve conter no mínimo 2 caracteres.',
						alpha		: 'Apenas caracteres alpha'
					},
					surname         :{
						required	: 'Campo de preenchimento obrigatório.',
						minlength	: 'O campo sobrenome deve conter no mínimo 2 caracteres.',
						alpha		: 'Apenas caracteres alpha'
					},
					gender          :{
						required	: 'Campo de preenchimento obrigatório.'
					},
					birthday        :{
						required	: 'Campo de preenchimento obrigatório.',
						dateEmpty	: 'O campo data de nascimento é de preenchimento obrigatório.',
						dateBR      : 'O campo data de nascimento deve conter a data no formato DD/MM/AAAA.'
					},
					profile         :{
						required	: 'Campo de preenchimento obrigatório.'
					},
					captcha         :{
						required	: 'Campo de preenchimento obrigatório.',
						remote      : 'O campo de código de segurança está incorreto.'
					},
					cpf				:{
						required	: 'Campo de preenchimento obrigatório.',
						cpfEmpty    : 'Campo de preenchimento obrigatório.',
						cpf         : 'CPF inválido.'
					},
					tipodedeficiencia:{
						required	: 'Selecione o tipo de deficiência'
					},
					campocep        :{
						required	: 'Campo de preenchimento obrigatório.'
					},
					endereco        :{
						required	: 'Campo de preenchimento obrigatório.',
						milength    : 'O endereço deve conter, no minino, 5 caracteres'
					},
					numero          :{
						required	: 'Campo de preenchimento obrigatório.',
						number      : 'Digite somente numeros'
					},
					bairro          :{
						required	: 'Campo de preenchimento obrigatório.',
						minlength   : 'O bairro deve conter, no mínimo, 2 caracteres'
					},
					cidade          :{
						required	: 'Campo de preenchimento obrigatório.'
					},
					estado          :{
						required	: 'Campo de preenchimento obrigatório.'
					},
					telefone        :{
						required	: 'Campo de preenchimento obrigatório.',
						cpfMobile   : 'Por favor forneça seu celular'
					},
					telefonecelular :{
						required	: 'Campo de preenchimento obrigatório.',
						cpfMobile   : 'Por favor forneça seu celular'
					},
					descricaopessoal:{
						required	: 'Campo de preenchimento obrigatório.',
						minlength   : 'A descrição pessoal deve conter, no mínimo, 50 caracteres',
						maxlength   : 'A descrição pessoal deve conter, no máximo, 600 caracteres'
					},
					category		:{
						required	: 'Selecione uma categoria.'
					},
					institution_email:{
						email	:	'E-mail inválido.'
					},
					institution_phone:{
						required	: 'Campo de preenchimento obrigatório.',
						cpfMobile	: 'Por favor forneça telefone'
					},
					institution_address:{
						required	: 'Campo de preenchimento obrigatório.'
					},
					institution_state:{
						required	: 'Campo de preenchimento obrigatório.'
					},
					institution_city:{
						required	: 'Campo de preenchimento obrigatório.'
					},
					institution_name:{
						required	: 'Campo de preenchimento obrigatório.'
					}					
				},
				onkeyup             : false,
                event               : 'blur',
				submitHandler       : function(form) {
                    var html    = '<p class="loading"><img src="/_img/global/ajax-loader-video.gif" /><br />Aguarde enquanto seu cadastro é validado</p>';
                    $('#send-register').after(html);
                    $('#send-register').attr('disabled', 'disabled');
                    $('em.loading').fadeIn();
                    $(form).ajaxSubmit({
                        dataType        : 'json',
                        success         : validateForm.result
                    });
                }
			});
		// cadastro simples
		} else {
			$('#registrationForm').validate({
				rules:{
					email           :{
						required	: true,  email		: true, remote      : '/check-email/'
					},
					alternate_email:{
						required	: false, email		: true
					},
					password        :{
						required	: true, minlength	: 8
					},
					password_check  :{
						required	: true, minlength	: 8, equalTo     : '#password'
					},
					name            :{
						required	: true, alpha		: true, minlength	: 2
					},
					surname         :{
						required	: true, alpha		: true, minlength	: 2
					},
					gender          :{
						required	: true
					},
					birthday        :{
						required	: true, dateEmpty	: true, dateBR      : true
					},
					profile         :{
						required	: true
					},
					captcha         :{
						required	: true,  remote      : '/check-captcha/'
					},
					cidade          :{
						required	: true
					},
					estado          :{
						required	: true
					}
				},
				messages:{
					email:{
						required	: 'Campo de preenchimento obrigatório.',
						email		: 'E-mail inválido.',
						remote      : jQuery.format('E-mail {0} já cadastrado. Faça seu login.')
					},
					alternate_email :{
						email		: 'E-mail inválido.'
					},
					password        :{
						required	: 'Campo de preenchimento obrigatório.',
						minlength	: 'O campo senha deve conter no mínimo 8 caracteres.'
					},
					password_check  :{
						required	: 'Campo de preenchimento obrigatório.',
						minlength	: 'O campo senha deve conter no mínimo 8 caracteres.',
						equalTo     : 'O valor do campo confirmação de senha não confere com o valor do campo senha.'
					},
					name            :{
						required	: 'Campo de preenchimento obrigatório.',
						minlength	: 'O campo nome deve conter no mínimo 2 caracteres.',
						alpha		: 'Apenas caracteres alpha'
					},
					surname         :{
						required	: 'Campo de preenchimento obrigatório.',
						minlength	: 'O campo sobrenome deve conter no mínimo 2 caracteres.',
						alpha		: 'Apenas caracteres alpha'
					},
					gender          :{
						required	: 'Campo de preenchimento obrigatório.'
					},
					birthday        :{
						required	: 'Campo de preenchimento obrigatório.',
						dateEmpty	: 'O campo data de nascimento é de preenchimento obrigatório.',
						dateBR      : 'O campo data de nascimento deve conter a data no formato DD/MM/AAAA.'
					},
					profile         :{
						required	: 'Campo de preenchimento obrigatório.'
					},
					captcha         :{
						required	: 'Campo de preenchimento obrigatório.',
						remote      : 'O campo de código de segurança está incorreto.'
					},
					cidade          :{
						required	: 'Campo de preenchimento obrigatório.'
					},
					estado          :{
						required	: 'Campo de preenchimento obrigatório.'
					}
				},
				onkeyup             : false,
                event               : 'blur',                
				submitHandler       : function(form) {
                    var html    = '<p class="loading"><img src="/_img/global/ajax-loader-video.gif" /><br />Aguarde enquanto seu cadastro é validado</p>';
                    $('#send-register').after(html);
                    $('#send-register').attr('disabled', 'disabled');
                    $('em.loading').fadeIn();
                    $(form).ajaxSubmit({
                        dataType        : 'json',
                        success         : validateForm.result
                    });
                }
			});
		}
    },
	categoria : function() {
		if ( $("#category").val()=='ensino_medio' || $("#category").val()=='universitario' || $("#category").val()=='ongs' ){
			return true;
		} else {
			return false;
		}
	},
    result  : function(data) {

        var status  = data.claro.status;
		var tipo  = data.claro.tipo;

        var html    = '<div id="error"><ol>';

        if (status == 0) {
			$.each(data.claro.error, function(i, item) {
				html    += '<li>' + item + '</li>\n';
			});
			html += '</ol></div>';
			$('ol.submit').after(html);
        } else {
        	//alert('tipo = '+tipo);
        	if(tipo==1){
        		$.get(def.project.path + 'sucesso/', function(data) {
	                $('#conteudo').find("div.column_text_block").fadeOut( function() {
	                    $('html, body').animate({scrollTop:0}, 700, 'swing');
	                    $(this).html(data).fadeIn('slow');
	                });
	            });
        	} else if (tipo==0) {
        		window.location.href="/participe/envie-seu-video/";
        	} else {
        		$.get(def.project.path + 'sucesso-alterar-cadastro/', function(data) {
	                $('#conteudo').find("div.column_text_block").fadeOut( function() {
	                    $('html, body').animate({scrollTop:0}, 700, 'swing');
	                    $(this).html(data).fadeIn('slow');
	                });
	            });
        	}
        }
    }
};

var validateresetpassword = {

    init    : function() {
        if (this.check())  this.core();
    },

    check   : function() {
        return ( _exists('#reset-password')) ? true : false;
    },

    core    : function() {

		$('#reset-password').validate({
			rules:{
				new_password    :{
					required	: true,
					minlength	: 8
				},
				confirm_password:{
					required	: true,
					minlength	: 8,
					equalTo     : '#new_password'
				}
			},

			messages:{
				new_password     :{
					required	: 'Campo de preenchimento obrigatório.',
					minlength	: 'O campo senha deve conter no mínimo 8 caracteres.'
				},
				confirm_password:{
					required	: 'Campo de preenchimento obrigatório.',
					minlength	: 'O campo senha deve conter no mínimo 8 caracteres.',
                    equalTo     : 'O valor do campo confirmação de senha não confere com o valor do campo senha.'
				}
			}
		});
	}
};


var field                 = {

    init    : function() {
        if (this.check())  this.core();
    },

    check   : function() {
        return ( _exists('li.tags') ) ? true : false;
    },

    core    : function() {

        $("li.tags input:checkbox").limitSelection(3);

    }

};


var selectdeficiente      = {

    init    : function() {
        if (this.check()) this.core();
    },

    check   : function() {
        return ( _exists('#portador-de-deficiencia') ) ? true : false;
    },

    core    : function() {
    	if($('#portador-de-deficiencia').val()==1){
    		this.criaMenu();
    	}
        $('#portador-de-deficiencia').live('change',function() {
            if ($(this).val() == 1) {
                selectdeficiente.criaMenu();
            } else {
				$('#deficiencia, #tipodedeficiencia').fadeOut( function() {
                    $(this).remove();
                });
                $('#tipodedeficiencia').next('.error').fadeOut( function() {
                    $(this).remove();
                });
            }
         });
     },


    criaMenu : function(){

    var html = '<label class="label-width" id="deficiencia" for="tipodedeficiencia">*Tipo de deficiência:</label>';
    		html    += '<select class="tipodedeficiencia" id="tipodedeficiencia" name="tipodedeficiencia">';
    		html    += '    <option value="">selecione</option>';
    		//html    += '    <option value="'.item.Disability.id.'">'.item.Disability.id.'</option>';

    var Disability	=  $('#idDisability').val();

    	$.getJSON("/get_disability/",function(data){
        	$.each(data, function(i,item){
                $.each(item, function(j,item2){
                //alert(item2.description);
                if(Disability == item2.id){
                    html    += '    <option selected="selected" value="'+item2.id+'">'+item2.description+'</option>';
           		}else{
                    html    += '    <option value="'+item2.id+'">'+item2.description+'</option>';
           		}
                });
            });
			html    += '</select>';
			$('#portador-de-deficiencia').after(html);
			$('#deficiencia, #tipodedeficiencia').css('display', 'none');
			$('#deficiencia, #tipodedeficiencia').fadeIn();
        });
    }
};


var counter               = {

    init    : function() {

        if (this.check())  this.core();

    },

    check   : function() {

        return ( _exists('#descricaopessoal') && typeof jQuery.fn.charCounter == 'function' ) ? true : false;

    },

    core    : function() {

		$("#descricaopessoal").charCounter(200, {
			container   : ".counter"
		});

    }

};


var captcha               = {

    init    : function() {

        if (this.check())  this.core();

    },

    check   : function() {

        return ( _exists('#registrationForm') ) ? true : false;

    },

    core    : function() {

    	$('li.captcha em a').click( function() {
    		captcha.reloadCaptcha();
    		return false;
    	});
    },

    reloadCaptcha	: function() {
		$("#security_image").attr({
          src: "/img/captcha.jpg?"+Math.random(),
          title: "Digite o código de segurança exibido na imagem",
          alt: "Digite o código de segurança exibido na imagem"
        });
        $("#captcha").val('');
    }

};


var mask = {
    init    : function() {
        if (this.check())  this.core();
    },
    check   : function() {
        return ( _exists('#registrationForm') && typeof jQuery.fn.mask == 'function' ) ? true : false;
    },
    core    : function() {
		$("#telefone").mask("(99) 9999-9999");
        $("#telefonecelular").mask("(99) 9999-9999");
		$("#institution_phone").mask("(99) 9999-9999");
		$("#campocep").mask("99999-999");
		$("#birthday").mask("99/99/9999");
		$("#cpf").mask("999.999.999-99");
    }
};


var getAddress            = {

    init    : function() {

        if (this.check())  this.core();

    },

    check   : function() {

        return ( _exists('#registrationForm') ) ? true : false;

    },

    core    : function() {

		$('.status').click(function(){
			var cep = $('#campocep').attr('value')

			if(cep != '') {

				var html =  '<img src="/_img/global/ajax-loader.gif" class="loader"/>';
                html    +=  '<em class="loader">Carregando informação!</em>';
                    $('.status').after(html);
                    $('.status').hide();


				$.getScript('http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep=' + cep, function(data){
                    $('.status').show()
					$('.loader').hide()
					$('#endereco').val('')
					$('#bairro').val('')
					$('#cidade').val('')
					$('#estado').val('Selecione')

					if(resultadoCEP.resultado == 0)
						alert('Não foi encontrado nenhum endereço para este CEP!\nCaso ele realmente exista, preencha o endereço manualmente!')
					else if(resultadoCEP.resultado == 1) {
						$('#endereco').val(unescape(resultadoCEP.tipo_logradouro + ' ' + resultadoCEP.logradouro))
						$('#bairro').val(unescape(resultadoCEP.bairro))
						$('#cidade').val(unescape(resultadoCEP.cidade))
						$('#estado').val(unescape(resultadoCEP.uf))
					}
					else {
						$('#estado').val(resultadoCEP.uf)
						$('#cidade').val(unescape(resultadoCEP.cidade))
						$('#endereco').focus()
					}
				})
			}

			else
				alert('Para que o endereço seja completado automaticamente você deve preencher o campo CEP!')
			return false
		})

    }

};


_main.init();


//]]>

