var SITE = SITE || {};

SITE.fileInputs = function() {
    var $this = $(this),
    $val = $this.val(),
    valArray = $val.split('\\'),
    newVal = valArray[valArray.length-1],
    $button = $this.siblings('.button'),
    $fakeFile = $this.siblings('.file-holder');
    if(newVal !== '') {
	$button.text('Photo Chosen');
	if($fakeFile.length === 0) {
	    $button.after('<span class="file-holder">' + newVal + '</span>');
	} else {
	    $fakeFile.text(newVal);
	}
    }
};


	function onYouTubePlayerReady(playerId) {
		ytplayer = document.getElementById("myytplayer");
	}

	function play() {
		if (ytplayer) {
		ytplayer.playVideo();

		}
	}


$(document).ready(function(){
	$(".bd-page:eq(0)").css({
		top: "-30px"
	})
	$(".remove_child").live("click",function(){

		if(!confirm('Deseja remover todas as informações deste filho?')){return false;}
		var self=$(this);
		var pk_child=$(this).attr('rel');
		$.ajax({
			type: "POST",
			url: BASEURL+"/wp-content/plugins/competitions/models/__competitions_remove_child.php",
			dataType: "html",
			data: "pk_child=" + pk_child,

			success: function(response){
				$(self).parent().parent().parent('.container_child').remove();
			},

			error: function(response){
				alert('Não foi possível remover este filho, se o problema persistir contate o administrador.')
			}

		});
    });

	if($('.rlc-txt-video').length!=0){
		var keywords=$('.rlc-txt-video').attr('title').split(',');	
		$.ajax({  

		url: BASEURL+"/wp-content/themes/fisher/products.xml",  
		type: "GET",
		dataType: "xml",  
		cache: false,
		success: function(response) {  
			$('.cnt-produtos-videos-relacionados ul').empty();
			
			$(response).find("product").each(function(){  
			
			var name = $(this).find("name").text();  
			var img = $(this).find("img").text(); 
			var age = $(this).find("age").text();
			var url = $(this).find("url").text();
			var tag = $(this).find("tag").text();

			count_array=0;
			
			$(keywords).each(function(index) {

				if(keywords[index].toLowerCase()==tag.toLowerCase()){
				
				$('.cnt-produtos-videos-relacionados ul').append('<li><div class="img-prod-mf"><a target="_blank" href="'+url+'"><img title="" alt="" src="'+BASEURL+'/wp-content/themes/fisher/images/products/'+img+'"></a></div><div class="txt-prod-mf"><a target="_blank" href="'+url+'">'+name+'</a><span>'+age+'</span></div><div class="all"></div></li>')
				}
				
			});

			
			});
		},
		error: function(response){

			alert('erro');
		}
		});

	}
	
    $(".change_video").click(function(){

	$('.wrp-videos-mf').removeClass('selected');

	var url_param=$(this).attr('rel');
	var video_view=$(this).attr('alt');
	var days=$(this).attr('title');

	var keywords=$(this).parent().attr('title').split(',');	

	$('#myytplayer').empty().append('<object style="height: 382 px; width: 684px" id="flashfirebug0" name="flashfirebug0"><param value="http://www.youtube.com/v/'+url_param+'?fs=1&amp;playerapiid=myytplayer&amp;enablejsapi=1&amp;rel=0" name="movie" class="param1"><param value="true" name="allowFullScreen"><param value="always" name="allowScriptAccess"><embed width="684" height="382" allowscriptaccess="always" allowfullscreen="true" type="application/x-shockwave-flash" src="http://www.youtube.com/v/'+url_param+'?fs=1&amp;playerapiid=myytplayer&amp;enablejsapi=1&amp;rel=0" class="param2" id="flashfirebug0" name="flashfirebug0"></object>');

	$('.video_view').text(video_view);
	$('.video_days').text(days);
	$('.rlc-txt-video h2').text($(this).text());
	$('.video_by').text($(this).attr('value'));
	$('.video_description').text($(this).parent().parent().parent().children('.text-desc-video').text());


 	$(this).parent().parent().parent('.wrp-videos-mf').addClass('selected');
	$(this).parent().parent().parent().parent().parent('.wrp-videos-mf').addClass('selected');

	$.ajax({  

	    url: BASEURL+"/wp-content/themes/fisher/products.xml",  
	    type: "GET",
	    dataType: "xml",  
	    cache: false,
	    success: function(response) {  
		$('.cnt-produtos-videos-relacionados ul').empty();
		
		$(response).find("product").each(function(){  
		    
		    var name = $(this).find("name").text();  
		    var img = $(this).find("img").text(); 
		    var age = $(this).find("age").text();
		    var url = $(this).find("url").text();
		    var tag = $(this).find("tag").text();

		    count_array=0;
		    
		    $(keywords).each(function(index) {

			if(keywords[index].toLowerCase()==tag.toLowerCase()){
			    
			    $('.cnt-produtos-videos-relacionados ul').append('<li><div class="img-prod-mf"><a target="_blank" href="'+url+'"><img title="" alt="" src="'+BASEURL+'/wp-content/themes/fisher/images/products/'+img+'"></a></div><div class="txt-prod-mf"><a target="_blank" href="'+url+'">'+name+'</a><span>'+age+'</span></div><div class="all"></div></li>')
			}
			
		    });

		    
		});
	    },
	    error: function(response){

		alert('erro');
	    }
	});
    });	     
	/*---------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
	var checkbox1 = $(".check-vacina input:checkbox").is(":checked");
	var checkbox2 = $(".checked");
	
	$(".check-vacina input:checked").parent().parent().addClass("checked");
	$(".cnt-informacoes-vacina .cnt-vacina-pendente").css("display","block")
	if($(".cnt-informacoes-vacina").hasClass('checked')){
		$(".checked .cnt-check").css("display","block")
		$(".checked .cnt-vacina-pendente").css("display","none")
	}
	
	/*---------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
	//Momentos Fisher
	$(".cnt-produtos-videos-relacionados ul li:last").css("border-right","none");	

	//Video list
	var furlyt = $(".wrp-videos-mf a:first").attr('href')
	//alert(furlyt)
	$("#ytapiplayer object embed").attr({src:furlyt})
	$("#ytapiplayer object").attr({value:furlyt})
	
	$(".wrp-videos-mf a").click(function(){
		urlyt = $(this).attr("href");
		//alert(urlyt)
		$("#ytapiplayer object embed").attr({src:urlyt})
		$("#ytapiplayer object").attr({value:urlyt})
		
		return false;
	})
	
	/*---------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
		
    $(".cnt-info-vacina a").hover(
	function(){
		var txt = $(this).attr("rel");
		var p = $(this);
		var position = p.position();
		var position_balao = position.left + (-175); 
		
		//alert(position_balao);
		$(".cnt-balao-info").css("left",position_balao+"px");
	    $(this).parent().addClass("display-balao");
		$(".cnt-balao-info").html("<p>"+txt+"</p>")
	    
	},function(){
	    $(this).parent().removeClass("display-balao");
	}
    )


    $('.file-wrapper input[type=file]').bind('change focus click', SITE.fileInputs);

    $("#default-select").selectbox();
    $(".cnt-select-idade-filho select").selectbox();

    $(".focus_login").click(function(){
	$("#username").focus();
    });

    $(".user").focus(function(){
	if($(this).val()=="Usuário"){
	    $(this).val('');
	}
    });


    $(".user").focusout(function(){
	if($(this).val()==""){
	    $(this).val("Usuário");
	}
    });

/*    $(".passwd").live('focus',function(){
	if($(this).val()=="Senha"){
	    $('.passwd_wrapper').html(($('.passwd_wrapper').html().replace('text','password')));
	    $(this).remove();
	    $(".passwd").val('').focus();
	}
    });

    $(".passwd").live('focusout',function(){
	if($(this).val()==""){
	    $('.passwd_wrapper').html(($('.passwd_wrapper').html().replace('password','text')));
	    $(this).remove();
	    $(".passwd").val("Senha");
	}
    });
*/


    $('.child').change(function(){
	var total=$(this).val();
	if(total!='Selecione'){
	    var i=0;

	    $('.child_wrapper').empty();

	    for (i=0;i<total;i++) {
		$('.child_wrapper').append('<div style="height:60px!important" class="cmp-email-completo"><label>Nome*:</label><span><input type="text" class="required" name="child_name'+i+'" value=""></span></div><div style="height:60px!important" class="child_gender"><label>Sexo*:</label><select class="child_gender" name="child_gender'+i+'"><option>--</option><option value="m">Masculino</option><option value="f">Feminino</option></select></div><div style="height:60px!important" class="cmp-data-nasc"><label>Data de nascimento*:</label><span class="dd-mm"><input type="text" class="day" name="child_birthday_day'+i+'" value=""></span><span class="dd-mm"><input type="text" class="month" name="child_birthday_month'+i+'" value=""></span><span class="aa"><input type="text" name="child_birthday_year'+i+'" class="year" value=""></span></div>');
	    }
	}

    });


    $("input[name=rg]").mask('999999999');

    $("input[name=cpf]").mask('999.999.999-99');

    $("input[name=zipcode1]").mask('99999');
    $("input[name=zipcode2]").mask('999');

    $("input[name=day]").mask('99');
    $("input[name=month]").mask('99');
    $("input[name=year]").mask('9999');
    $("input[name=rddd]").mask('99');
    $("input[name=rnumber]").numeric();
    $("input[name=cddd]").mask('99');
    $("input[name=cnumber]").numeric();
    $("input[name=number]").numeric();


    var dtCh= "/";
    var minYear=1900;
    var maxYear=2100;

    function isInteger(s){
	var i;
	for (i = 0; i < s.length; i++){   
            // Check that current character is number.
            var c = s.charAt(i);
            if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
    }

    function stripCharsInBag(s, bag){
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++){   
            var c = s.charAt(i);
            if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
    }

    function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
    }
    function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
	    this[i] = 31
	    if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
	    if (i==2) {this[i] = 29}
	} 
	return this
    }

    //date validator
    function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
	    if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
	    alert("The date format should be : mm/dd/yyyy")
	    return false
	}
	if (strMonth.length<1 || month<1 || month>12){
	    alert("Please enter a valid month")
	    return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
	    alert("Please enter a valid day")
	    return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
	    alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
	    return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
	    alert("Please enter a valid date")
	    return false
	}
	return true
    }

    function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
	    dt.focus()
	    return false
	}
	return true
    }


    function cpf_validator(cpf) {
	var numeros, digitos, soma, i, resultado, digitos_iguais;
	digitos_iguais = 1;
	if (cpf.length < 11)
            return false;
	for (i = 0; i < cpf.length - 1; i++){
            if (cpf.charAt(i) != cpf.charAt(i + 1))  {
		digitos_iguais = 0;
		break;
            }
	}
	if (!digitos_iguais) {
            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--){
                soma += numeros.charAt(10 - i) * i;
	    }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0)){
                return false;
	    }
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--){
                soma += numeros.charAt(11 - i) * i;
	    }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1)){
                return false;
	    }
            return true;
        }else{
            return false;
	}
    }

    // validate signup form on keyup and submit
    $(".signup1").validate({
	rules: {
            password: {
		required: true,
		minlength: 5
	    },
	    confirm_password: {
		required: true,
		minlength: 5,
		equalTo: "#password"


	    },
	    email: {
                required: true,
                email: true
            },
	    cnumber: {
                required: true,
                maxlength: 9
            },
	    rnumber: {
                required: true,
                maxlength: 9
            }

	},
	messages: {
	    passwd: {
		minlength: "Sua senha deve ter no mínimo 5 caracteres"
	    },
	    email: "Entre com um email válido",
	}
    });

    //validate
    $(".signup2").validate({
	rules: {
            cpf: {
		required: true,
		cpf:true
	    }
	}
    });




    // validate signup form on keyup and submit
    $(".change_passwd").validate({
	rules: {
	    old_passwd: {
		required: true,
		minlength: 5
	    },
	    new_passwd: {
		required: true,
		minlength: 5
	    },
	    confirm_new_passwd: {
		required: true,
		minlength: 5,
		equalTo: "#password"
	    }		}
    });




    $('.lost_passwd').live('click', function(){
	$('<span class="passwd_wrapper remove_passwd"><input class="recovery_passwd" value=" Email" type="text" /></span><a class="send_recovery_token" href="javascript:;">ok</a>').insertAfter($('.lost_passwd'));
	$(this).remove();
	
    });

    $(".recovery_passwd").live('focus',function(){
	if($(this).val()==" Email"){
	    $(this).val('');
	}
    });

    $(".recovery_passwd").live('focusout',function(){
	if($(this).val()==""){
	    $(this).val(" Email");
	}
    });




    $(".send_recovery_token").live("click",function(){

	var email=$('.recovery_passwd').val();
	$.ajax({
	    type: "POST",
	    url: BASEURL+"/wp-content/plugins/competitions/competitions_lost_passwd.php",
	    dataType: "html",
	    data: "email=" + email,

	    success: function(response){
		$('.recovery_passwd').remove();
		$('.send_recovery_token').remove();
		$('.remove_passwd').attr('style','background:none;').append(response);
	    },

	    error: function(response){
	    }

	});
    });

    $(".send_recovery_token_2").live("click",function(){
	$('#form-esqueci-senha').submit(function(){
	    return false;
	})
	var email=$('#email').val();
	$.ajax({
	    type: "POST",
	    url: BASEURL+"/wp-content/plugins/competitions/competitions_lost_passwd.php",
	    dataType: "html",
	    data: "email=" + email,

	    success: function(response){
		$('.send_recovery_token_2').after(response);
	    },

	    error: function(){
	    }

	});
    });


    $("#subscribe").live("click",function(){
	$('#newsletter-form').submit(function(){
	    return false;
	})
	var email=$('#ne').val();
	$.ajax({
	    type: "POST",
	    url: BASEURL+"/wp-content/plugins/competitions/competitions_newsletter.php",
	    dataType: "html",
	    data: "email=" + email,

	    success: function(response){
		$('#ne').val('Seu email');
		jAlert(response, 'Alerta');

	    },

	    error: function(){
	    }

	});
    });

    $("#wrapper-cadastro .border-top-page:first").css("display","none")
    $("#wrapper-cadastro .border-bottom-page:last").css("display","none")

    
    $(".wp-socializer-jump li").removeAttr("style","display");
    
    /*Ajusta borda da Categoriaa Especialisata*/
    //$('.banner-especialista').before('<div class="borda-cnt-bottom"></div>');
	var postsbanner = $(".wrapper-cadastro").size();
	var especialista = $(".cnt-tit-post-desc-especialista").size()
	var banners = $(".banners-posts-1").html();
	var banners2 = $(".banners-posts-2").html();
	
	//alert(especialista)
	
	if(postsbanner == 0 || postsbanner == 1){
		$(".banner-1").html("<div class='banners-posts' style='padding-left:25px'>" + banners + "</div>");
		//$('.banner-1').before('<div class="borda-cnt-bottom"></div>');
		$(".banners-posts-1,.borda-cnt-bottom-blog").remove();
		
	}
	
	if(especialista == 1){
		$('.banner-1').before('<div class="borda-cnt-bottom"></div>');
	}
	
	if(postsbanner == 2){
		//$('.banner-1').before('<div class="borda-cnt-bottom"></div>');
		$(".banner-1").html("<div class='banners-posts'>" + banners2 + "</div>");
		$(".banners-posts-2").remove();
		
	}
	
	$(".banner-posts-1").before('<div class="borda-cnt-bottom"></div>');

	var tamanho = $(".wp-paginate li").width();
	var quantli = $(".wp-paginate li").size();

	var pgwidth= 51*quantli;
	//alert(pgwidth)
	$("div.pagination ").css("width",pgwidth);	
	
    $('.signup1').submit(function() {
	if($('.child2').val()==0){
	    $('.child2').after('<label class="error2">Este campo é obrigatório.</label>');
	    return false;

	}
	if($('.day').length){
	    var count_date=0;
	    if($('.day').val()=='' || $('.month').val()=='' || $('.year').val()==''){
		if(count_date==0){
		    $('.year').after('<label class="date error error2">Este campo é obrigatório.</label>');
		    count_date++;
		}
		return false;
	    }else{
		return true;
	    }
	}
    });

    $('.signup2').submit(function() {
	var a=new Array();
	var count_date=0;
	if($('.day').val()=='' || $('.month').val()=='' || $('.year').val()=='' ){
	    if(count_date==0){
		$('.year').after('<label class="date error error2">Este campo é obrigatório.</label>');
		count_date++;
	    }
	    a['date']=0;
	}else{
	    a['date']=1;
	}

	if($('.zipcode1').val()=='' || $('.zipcode2').val()==''){
	    $('.zipcode2').after('<label class="error2 error_zipcode">Este campo é obrigatório.</label>');
	    a['zipcode1']=0;
	}else{
	    a['zipcode1']=1;
	}

	if($('.state').val()=='--'){
	    $('.state').after('<label class="error2 error_zipcode state_error">Este campo é obrigatório.</label>');
	    a['state']=0;
	}else{
	    a['state']=1;
	}

	if($('.gender1').attr('checked')==false && $('.gender2').attr('checked')==false){
	    $('.gender2').after('<label class="error error_select gender_error">Este campo é obrigatório.</label>');
	    a['gender']=0;
	}else{
	    a['gender']=1;
	}
	for (var i in a){
	    if(a[i]==0) {
		return false;
	    }
	    
	}


    });

    $('.state').click(function(){
	$('.state_error').remove();
	
    });

    $('.gender1').click(function(){
	$('.gender_error').remove();
	
    });

    $('.gender2').click(function(){
	$('.gender_error').remove();
	
    });

    $('.child_gender').change(function(){
	$(this).siblings('.gender_error').remove();
    });

    $('.update_my_account').submit(function() {
	var count=0;

	$('.child_gender').each(function(index) {

	    if($(this).val()=='--'){
		$(this).siblings('.gender_error').remove();
		$(this).parent().append('<label class="error error_select gender_error">Este campo é obrigatório.</label>');
		count++;
	    }
	});

	if(count==0){
	    return true;
	}else{
	    return false;
	}

    });


    function del_error(input_error){
	setTimeout(function() {

	    if($(input_error).val()!="" && $(input_error).attr('id').substring(0,4)!='poll'){
		$(input_error).next('label').remove();
		
	    }else{

		del_error();
	    }
	    
	}, 100);
	
    }

    $('input').focus(function(){
	input_error=$(this);
	del_error(input_error);

    });

    
    $('.link-esqueci-senha').click(function(){
	$('.cmp-email-completo').show();
    });

    $('.competition_limit').limit('170','#competition_count');

	
	
	
});



