//<![CDATA[


var _main                 = {

    init          : function() {
        this.before();
    },

    before        : function() {
        libraries.jCharcounter.init    = true;
        libraries.jQmask.init          = true;
        libraries.jQscrollTo.init      = true;
        libraries.jQfield.init         = true;
        libraries.fileStyle.init       = true;
        _loader.core();
    },

    after         : function() {
         validateForm.init();
         selectdeficiente.init();
         counter.init();
         mask.init();
         getAddress.init();
         captcha.init();
         validateCurta.init();
         field.init();
         validateresetpassword.init();
    }
};


var validateForm          = {

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

    check   : function() {
        return ( _exists('#registrationForm') &&
                typeof jQuery.fn.validate == 'function'  &&
                typeof jQuery.fn.ajaxSubmit == 'function'  &&
                typeof jQuery.fn.scrollTo == '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!='(__) ____-____'))
		});

		$('#registrationForm').validate({
			rules:{
				email           :{
					required	: true,
					email		: true,
					//minlength	: 8,
                    remote      : '/check-email/'
				},
				alternate_email:{
					required	: false,
					email		: true,
					minlength	: 8
				},
				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
				},
				optin           :{
					required	: true
				},
				captcha         :{
					required	: true,
                    remote      : '/check-captcha/'
				},
				cpf				:{
                    required	: true,
                    cpfEmpty    : true,
					cpf			: true
				},
				descricaopessoal:{
					required	: true,
                    minlength	: 50,
                    maxlength   : 600
				},
				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	: true,
                    cpfMobile   : true
				},
				operadora       :{
					required	: true
				}

			},
			messages:{
				email:{
					required	: 'Campo de preenchimento obrigatório.',
					email		: 'E-mail inválido.',
                    remote      : jQuery.format('O e-mail {0} já está em uso, utilize outro.')
				},
				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.'
				},
                optin           :{
					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.'
				},
                descricaopessoal:{
					required	: 'Campo de preenchimento obrigatório.',
                    minlength   : 'A descrição pessoal deve conter, no mínimo, 50 caracteres'
				},
                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'
				},
                operadora       :{
					required	: 'Campo de preenchimento obrigatório.'
				}
			},
            onkeyup             : false,
            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
                });
            }
		});
    },

    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) {

	                $('#content').fadeOut( function() {
	                    $.scrollTo( '#header', 1000, {easing:'BounceEaseOut'} );
	                    $(this).html(data).fadeIn('slow');
	                });

	            });

        	}else if(tipo==0){
        		window.location.href="/envie-seu-curta/";
        	}else{


        		$.get(def.project.path + 'sucesso-aletrar-cadastro/', function(data) {

	                $('#content').fadeOut( function() {
	                    $.scrollTo( '#header', 1000, {easing:'BounceEaseOut'} );
	                    $(this).html(data).fadeIn('slow');
	                });

	            });


        	}


        }
    }
};


var validateCurta         = {

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

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

    core    : function() {

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

		$('#upload').validate({
			rules:{
				tit_video       :{
					required	: true,
					minlength	: 5,
                    maxlength   : 100,
                    alpha		: true
				},
				genero          :{
					required	: true
				},
                sinopse         :{
					required	: true,
                    minlength	: 50,
                    maxlength   : 600
				},
                datafile        :{
					required	: true,
                    accept      : true //avi|mpeg|mov|wma|3gp'
                },
                regulation      :{
					required	: true
				}
			},

			messages:{
				tit_video       :{
					required	: 'Campo de preenchimento obrigatório.',
					minlength	: 'O titulo deve conter, no minino, 5 caracteres.',
                    maxlength   : 'O titulo deve conter, no maximo, 100 caracteres.',
                    alpha		: 'Apenas caracteres alpha'
				},
				genero          :{
					required	: 'Selecione o gênero.'
				},
                sinopse         :{
					required	: 'Campo de preenchimento obrigatório.',
					minlength	: 'A sinopse deve conter, no minino, 50 caracteres.',
                    maxlength   : 'A sinopse deve conter, no maximo, 600 caracteres.'
				},
                datafile        :{
					required	: 'Selecione o arquivo.'
                },
                regulation      :{
					required	: 'Por favor leia e selecione o nosso regulamento.'
                }
			}
		});

        // style do botão de upload
        $("input[type=file]").filestyle({
            image: "/_img/participe/bt-upload-video.png",
            imageheight : 26,
            imagewidth : 112,
            width : 250
        });
    }
};


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 ($('#portador-de-deficiencia').length > 0) ? true : false;

     },

    core    : function() {


    	if($('#portador-de-deficiencia').val()==1){
    		this.criaMenu();
    	}

        $('#portador-de-deficiencia').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");
		$("#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();


//]]>