jQuery(document).ready(function(){
	jQuery('#dynamicForm').hide();
	jQuery('#video_passo1').hide();
	jQuery('#loading').hide();
		
	// ////////////////////////////// VIDEOS //////////////////////////////// //
	var adicionarVideoUIToggle = false;
	jQuery('#adicionarVideo').click(function() {
        if (!adicionarVideoUIToggle) {
            jQuery('#video_passo1').slideDown(200);
            jQuery.scrollTo('#videos',500);
            adicionarVideoUIToggle = true;
        } else {
            jQuery('#video_passo1').slideUp(200);
            adicionarVideoUIToggle = false;
	    }
    });
    
    jQuery('#cancelarVideo').click(function() {
        jQuery('#dynamicForm').slideUp();
        jQuery('#adicionarVideo').show();
    });
    
	jQuery('#enviarVideo').click(function() {
	    if (jQuery('#youTubeURL').val()) {
	        jQuery('#loading').slideDown();
	        jQuery('#video_passo1').slideUp();
            dynForm = jQuery.ajax({
                    type: 'POST',
                    url: base_url + 'youtubeapi/ajax_add_video.php',
                    dataType: 'html',
                    data: {
                        videoUrl: jQuery('#youTubeURL').val()
                    },
                    complete: function() {
                       if (dynForm.responseText=='erro') {
                            alert(eletro_perfil_vars.alert_invalid_uri);
                            jQuery('#video_passo1').slideDown();
                            jQuery('#loading').slideUp();
                        } else {
                            jQuery('#loading').slideUp();
                            adicionarVideoUIToggle = false;
                            jQuery('#dynamicFormArea').html('');
                            jQuery('#dynamicFormArea').html(dynForm.responseText);
                            jQuery('#adicionarVideo').hide();
                            jQuery('#dynamicForm').slideDown();
                            jQuery('#video_passo2').show();
                            addFormChamadasEvents('insertvideo');
                        }
                    }
                });
        } else { 
            alert(eletro_perfil_vars.alert_yt_uri);
        }
    });
	
	
	// ////////////////////////////// FOTOS //////////////////////////////// //
	
	jQuery('#insertfoto').hide();
	
	var adicionarFotoUIToggle = false;
	
	jQuery('#botao_adicionarFoto').click(function() {
        if (!adicionarFotoUIToggle){
            jQuery('#insertfoto').slideDown(200);
            jQuery.scrollTo('#fotos',500);
            adicionarFotoUIToggle = true;
        } else {
            jQuery('#insertfoto').slideUp(200);
            adicionarFotoUIToggle = false;
	    }
    });
    
	jQuery('#cancelarFoto').click(function() {
        jQuery('#insertfoto').slideUp();
    });
    
    
    // ////////////////////////////// MUSICAS //////////////////////////////// //
	
	jQuery('#insertmusica').hide();
	
	var adicionarMusicaUIToggle = false;
	jQuery('#botao_adicionarMusica').click(function() {
        if (!adicionarMusicaUIToggle){
            jQuery('#insertmusica').slideDown(200);
            jQuery.scrollTo('#musicas',500);
            adicionarMusicaUIToggle = true;
        } else {
            jQuery('#insertmusica').slideUp(200);
            adicionarMusicaUIToggle = false;
	    }
    });
	
	jQuery('#cancelarMusica').click(function() {
        jQuery('#insertmusica').slideUp();
    });
    
    // ////////////////////////////// RADIO //////////////////////////////// //
	
	jQuery('#insertradio').hide();
	
	var adicionarRadioUIToggle = false;
	jQuery('#botao_adicionarRadio').click(function() {
        if (!adicionarRadioUIToggle){
            jQuery('#insertradio').slideDown(200);
            jQuery.scrollTo('#radios',500);
            adicionarRadioUIToggle = true;
        } else {
            jQuery('#insertradio').slideUp(200);
            adicionarRadioUIToggle = false;
	    }
    });
	
	jQuery('#cancelarRadio').click(function() {
        jQuery('#insertradio').slideUp();
    });
    
    // ////////////////////////////// MICROBLOG //////////////////////////////// //
	
	jQuery('#insertmicroblog').hide();
	
	var adicionarMicroblogUIToggle = false;
	jQuery('#botao_adicionarMicroblog').click(function() {
        if (!adicionarMicroblogUIToggle){
            jQuery.scrollTo('#microblog',500);
            jQuery('#insertmicroblog').slideDown(200);
            
            adicionarMicroblogUIToggle = true;
        } else {
            jQuery('#insertmicroblog').slideUp(200);
            adicionarMicroblogUIToggle = false;
	    }
    });
	
	jQuery('#cancelarMicroblog').click(function() {
        jQuery('#insertmicroblog').slideUp();
    });

    function limitChars(textid, limit, infodiv) {
        var text = jQuery('#'+textid).val(); 
        var textlength = text.length;
        if(textlength > limit) {
            //jQuery('#' + infodiv).html('You cannot write more then '+limit+' characters!');
            jQuery('#'+textid).val(text.substr(0,limit));
            return false;
        } else {
            jQuery('#' + infodiv).html((limit - textlength));
            return true;
        }
    }

    if (jQuery('#microblog_content')) {
        jQuery('#microblog_content').keyup(function() {
            limitChars('microblog_content', 150, 'microblog_info')
        })
    }
    
	// //////** Campos do perfil no formulario de chamadas **////////
	// clicar nos checkbox das chamadas exibe os campos obrigatorios se existirem
    
    function addFormChamadasEvents(escopo) {
    	var scope = '';
    	if (escopo) scope = '#' + escopo + ' ';
		jQuery(scope + '.chamadas_radio').each(function() {
			jQuery(this).click(function() {
                jQuery(scope +'.resetRadioContainer').fadeIn(1000);
				var clicked = jQuery(this);
				var show = false;
				jQuery(this).parents('form').find('.chamadas_radio').each(function() {
					if (jQuery(this).is(':checked')) {
						show = true;
					}
				});
				if (show) {
					clicked.parents('form').find('.chamada_campos_obrigatorios').slideDown();
					clicked.parents('form').find('#temCamposObrigatorios').val(1);
				} else {
					clicked.parents('form').find('.chamada_campos_obrigatorios').slideUp();
					clicked.parents('form').find('#temCamposObrigatorios').val(0);
				}
			});
		});
        jQuery(scope +'.resetRadio').click(function(){
            jQuery(scope +'.resetRadioContainer').fadeOut(1000);
            jQuery(scope + '.chamadas_radio').each(function() {
                    jQuery(this).attr("checked", false);
                    jQuery(this).parents('form').find('.chamada_campos_obrigatorios').slideUp();
                    jQuery(this).parents('form').find('#temCamposObrigatorios').val(0);
            });
            
        });
    }
    
    addFormChamadasEvents();

    /// Eventos do botão de Follow e Unfollow
    
    jQuery('#button_follow').click(function() {
    	
    	var profile_owner = jQuery('#user_id').val();
    	if (jQuery(this).hasClass('unfollow')) {
    		var action = 'unfollow';
    		var newMessage = eletro_perfil_vars.msg_folow;
    	} else {
    		var action = 'follow';
    		var newMessage = eletro_perfil_vars.msg_no_folow;
    	}
    	
    	jQuery('#button_follow span').html('');
    	jQuery('#followLoader').show();
    	follow = jQuery.ajax({
            type: 'POST',
            url: base_url + 'ajax_follow.php',
            dataType: 'html',
            data: {
                profile_owner: profile_owner,
                action: action
            },
            
            complete: function() {
                if (follow.responseText == 'ok') {
                	jQuery('#button_follow').toggleClass('follow').toggleClass('unfollow');
                	jQuery('#button_follow span').html(newMessage);
                	jQuery('#followLoader').hide();
                }
            }
        });

    });
    
    
    // ENVIAR MENSAGEM //
    
    jQuery('#sendMessage').click(function() {
    	jQuery('#sendMessageForm').toggle();
    });
    
    if (jQuery('#sendMessageContent')) {
        jQuery('#sendMessageContent').keyup(function() {
            limitChars('sendMessageContent', 500, 'sendMessageCount')
        })
    }
    
    jQuery('#sendMessageSend').click(function() {
    	
    	jQuery('#sendMessageLoader').show();
    	
    	var profile_owner = jQuery('#user_id').val();
    	var message = jQuery('#sendMessageContent').val();
    	
    	if (!message) {
    		alert(eletro_perfil_vars.alert_error_msg_text);
    		return;
    	}
    	
    	jQuery('#sendMessageLoader').show();
    	follow = jQuery.ajax({
            type: 'POST',
            url: base_url + 'ajax_sendMessage.php',
            dataType: 'html',
            data: {
                profile_owner: profile_owner,
                message: message
            },
            
            complete: function() {
                if (follow.responseText == 'ok') {
                	jQuery('#sendMessageContent').val('');
                	sendMessageFeedback('ok');
                } else {
                	sendMessageFeedback('nok');
                }
            }
        });
    	
    	jQuery('#sendMessageLoader').hide();

    });
    
    // CONVIDAR AMIGO //
    
    jQuery('#convidarAmigoLink').click(function() {
    	jQuery('#convidarAmigoContainer').toggle().toggleClass('convidarAmigoActive');
    	jQuery(this).toggleClass('convidarAmigoActive');
    });
    
    if (jQuery('#convidarAmigoContent')) {
        jQuery('#convidarAmigoContent').keyup(function() {
            limitChars('convidarAmigoContent', 500, 'convidarAmigoCount')
        })
    }
    
    jQuery('#convidarAmigoSend').click(function() {
    	
    	jQuery('#convidarAmigoLoader').show();
    	
    	var profile_owner = jQuery('#user_id').val();
    	var message = jQuery('#convidarAmigoContent').val();
    	var email = jQuery('#convidarAmigoEmail').val();
    	
    	if (!message || !email) {
    		alert(eletro_perfil_vars.alert_input_fmail_msg);
    		return;
    	}
    	
    	follow = jQuery.ajax({
            type: 'POST',
            url: base_url + 'ajax_sendInvitation.php',
            dataType: 'html',
            data: {
                profile_owner: profile_owner,
                message: message,
                email: email
            },
            
            complete: function() {
                if (follow.responseText == 'ok') {
                	jQuery('#convidarAmigoContent').val('');
                	jQuery('#convidarAmigoEmail').val('');
                	convidarAmigoFeedback('ok');
                } else {
                	convidarAmigoFeedback('nok');
                }
            }
        });
    	
    	jQuery('#convidarAmigoLoader').hide();

    });    
    
    ///////// MENSAGENS E REDE ///////////
    jQuery('#tabs span').click(function() {
    	var id = jQuery(this).attr('id').replace('tabs_', '');
    	jQuery('.tab_container').hide();
    	jQuery('.tab_container .paginationLoader').hide();
    	jQuery('#container_' + id).show();
    	jQuery('#tabs span').removeClass('active');
    	jQuery(this).addClass('active');

	// HACK ALERT
	acompanham = jQuery('.acompanham > img').attr('src');
	acompanho = jQuery('.acompanho > img').attr('src');
	if (jQuery(this).children('.acompanham').length > 0) {
	    if (!acompanham.match('selecionado')) {
                acompanham = acompanham.replace(/\w+\.\w+$/, '') + 'pessoasquemeacompanham_selecionado.gif';
	        jQuery('.acompanham > img').attr('src', acompanham);
		acompanho = acompanho.replace(/_selecionado/, '');
		jQuery('.acompanho > img').attr('src', acompanho);
	    }
	} else if (jQuery(this).children('.acompanho').length > 0) {
	    if (!acompanho.match('selecionado')) {
                acompanho = acompanho.replace(/\w+\.\w+$/, '') + 'pessoasqueeuacompanho_selecionado.gif';
	        jQuery('.acompanho > img').attr('src', acompanho);
		acompanham = acompanham.replace(/_selecionado/, '');
		jQuery('.acompanham > img').attr('src', acompanham);
	    }
	}
    });

});

function sendMessageFeedback(q) {
    if (jQuery('#sendMessageFeedback_'+q).is(':visible')) {
        jQuery('#sendMessageFeedback_'+q).fadeOut();
    } else {
        jQuery('#sendMessageFeedback_'+q).fadeIn('fast');
        setTimeout(function(){sendMessageFeedback(q);}, 4000);
    }
}

function convidarAmigoFeedback(q) {
    if (jQuery('#convidarAmigoFeedback_'+q).is(':visible')) {
        jQuery('#convidarAmigoFeedback_'+q).fadeOut();
    } else {
        jQuery('#convidarAmigoFeedback_'+q).fadeIn('fast');
        setTimeout(function(){convidarAmigoFeedback(q);}, 4000);
    }
}

function feedbackUpload() {
    jQuery('#postFeedback').hide();
	jQuery.scrollTo('body',500);
	setTimeout("jQuery('#perfil_media').hide()", 1000);
	setTimeout("jQuery('#updates').hide()", 1000);
	setTimeout("jQuery('#uploadFeedback').show()", 1000);
}

function validateForm(type) {
    
	var erros = '';
	if (jQuery('#insert' + type + ' #temCamposObrigatorios').val() == 1) {
		var errosCampos = false;
		jQuery('#insert' + type).find('.chamadas_obrigatorio').each(function() {
			if (jQuery(this).val() == "") {
				if (!errosCampos) 
					erros +=  eletro_perfil_vars.msg_error_fill_form + '\n\n';
				errosCampos = true;
			}
			if (this.id == 'rg') {
				if (!ValRG(jQuery(this).val(), true))
					erros += eletro_perfil_vars.msg_error_RG + '\n\n';
			}
			if (this.id == 'cpf') {
				if (!verificaCPF(jQuery(this).val()))
					erros += eletro_perfil_vars.msg_error_CPF + '\n\n';
			}
			if (this.id == 'cep') {
				if (!IsCEP(jQuery(this).val(), false))
					erros += eletro_perfil_vars.msg_error_CEP + '\n\n';
			}
		});
	}
	
	if(!jQuery("#"+type+"licenseok").is(":checked")) {
        erros += eletro_perfil_vars.msg_error_TOS + '\n\n';
    }

	if (erros) {
		alert(erros);
		return false;
	} else {
		switch(type) {
	        case "radio": case "musica": case "foto":
	            feedbackUpload();
	            break;
	        default: 
	            break;
	    }
		return true;
	}

}

