$(function(){
	
	$(".btRedeSocialPrincipal").click(function(){
		$("#intervencaoSocialAux").slideToggle(400,function(){
			if($(this).css("display")=="block"){
				pageTracker._trackPageview("/menu_compartilhe_abre/");
				dataMetrics({pageName:"Compartilhe este Site - Inicio",channel:"Header"});
				//tmp DRIVE ANALYTICS SADPOR-598
				dataDrive("sadia_compartilhe");
			}else{
				pageTracker._trackPageview("/menu_compartilhe_fecha/");
			}
		});
		return false;
	});
	
	if($(".jsBtRedeSocial").size() > 0){
		postRedeSocial = new BoxRedeSocial();
		postRedeSocial.init(".jsBtRedeSocial");
		postRedeSocial.setReset = function(){
			var img = $("#jsUserPhoto").clone().attr({width:'97'});
			var name = $("#jsUserName").clone();
			$(this.id).find(".usuario").html(" ").append(img).append(name);
		};
		
		$("body").click(function(){
			postRedeSocial.close();
		});
	}
	
	var divLoad = $("<div/>").css({height:50,position:"absolute",top:0,left:"50%"}).append(Utils.loader({src:"/img/ajax-loader-redeSoc.gif"}));
	$("#intervencaoSocial").append(divLoad);

	if(Utils.cookie.get("sadiaIntervencao")){
		Utils.executeAjax({url:"/inc/intervencao_content.jsp",type:"GET",call:"intervencaoResponse"});
	}else{
		Utils.executeAjax({url:"/inc/intervencao_experimente.jsp",type:"GET",call:"intervencaoFirstTimeResponse"});
	}
	
	//$(".btRedeSocialPrincipal").unbind("click")
	
	$('ul.itensWidget li span a').click(function() {
		$('div.widget').addClass('hide');
		$('div.widgetDescription p').addClass('hide')
		
		$('div.'+$(this).attr('rel')).removeClass('hide');
		$('div.widgetDescription p.'+$(this).attr('rel')).removeClass('hide');
		
		var url = $('#url_widget').text();
		var currentWidget = $('div.widget').not('.hide').attr('class');
		classCurrentWidget = currentWidget.split(" ");
		$('#url_widget').text('');
		$('#url_widget').text(url+'/'+classCurrentWidget[1]);
		
		return false;
	})
	
	$('a.url_colocar_site').click(function() {
		$('#url_widget').show();
		return false;
	});
	
	$('.bt_copiar_url').click(function (){ 
		CopyLink('url_widget_sadia');		
		return false;
	});
	
});

function intervencaoResponse(response){
	$("._loader").parent().remove();
	$("#intervencaoSocialAux").html(response);
	initRedeSocial();
}

function intervencaoFirstTimeResponse(response){
	$("._loader").parent().remove();
	$("#intervencaoSocialAux").html(response);
	initRedeSocial();
	
	$(".jsPasso").click(function(){
		Utils.cookie.set("sadiaIntervencao","true");
		var index = $(".jsPasso").index(this);
		$(".jsIntervencao").eq(index).animate({opacity:0},250,function(){
			$(this).hide();
			$(".jsIntervencao").eq(index+1).show().animate({opacity:1},250);
		});
		
		if($(this).hasClass("btTerminei")){
			pageTracker._trackPageview("/menu_compartilhe_pronto/");
		}else if($(this).hasClass("btExperimente")){
			pageTracker._trackPageview("/menu_compartilhe_experimente/");
		}
		
		return false;
	});
	$(".jsGoPasso").click(function(){
		Utils.cookie.set("sadiaIntervencao","true");
		var index = $(this).parents(".jsIntervencao");
		var href = $(this).attr("href").split("#")[1];
		$(index).animate({opacity:0},250,function(){
			$(this).hide();
			$(".jsIntervencao").eq(href-1).show().animate({opacity:1},250);
		});
		pageTracker._trackPageview("/menu_compartilhe_nao_uso/");
		return false;
	});
	
	$(".jsCompartilhar").click(function(){
		Utils.cookie.set("sadiaIntervencao","true");
		Utils.executeAjax({url:"/inc/intervencao_content.jsp",type:"GET",call:"intervencaoResponse"});
		
		if($(this).hasClass("btComeceCompartilhar")){
			pageTracker._trackPageview("/menu_compartilhe_comece/");
		}else{
			pageTracker._trackPageview("/menu_compartilhe_ja_sei/");
		}
	});
}

GaleriaPost = function(elem){
	this.elem = elem; //jsGaleriaPostContainer
	this.elemGal = $(elem).find(".jsGaleriaPostMask"); //jsGaleriaPost
	this.elemGalAux = $(elem).find(".jsGaleriaPostMaskAux"); //jsGaleriaPost
	this.elemAux = $(elem).find(".jsGaleriaPostAux"); //jsGaleriaPostAux
	this.widthAdd = $(this.elemGal).get(0).offsetWidth;
	this.width = $(this.elemAux).get(0).offsetWidth;
	this.controle = true;
	this.total;
	this.index;
	this.callback = null;
	
	this.init = function(){
		var thisAux = this;
		
		this.verifyQuantity();
		$(this.elem).find(".btEsq").click(function(){
			thisAux.setWidth();
			thisAux.previus();
			return false;
		});
		$(this.elem).find(".btDir").click(function(){
			thisAux.setWidth();
			thisAux.next();
			return false;
		});
	}
	this.next = function(){
		if(this.width - this.widthAdd > (this.getLeft() *(-1)))
			this.anima(this.getLeft() - this.widthAdd);
	}
	this.previus = function(){
		if(this.getLeft() != 0)
			this.anima(this.getLeft() + this.widthAdd);
	}
	this.goTo = function(index){
		this.setWidth();
		this.anima(-index * this.widthAdd);
	}
	this.getLeft = function(){        
		var left = $(this.elemGalAux).css("left");
		left = parseInt(left.substring(0,left.length-2));
		return left;
	}
	this.setWidth = function(){        
		this.widthAdd = $(this.elemGal).get(0).offsetWidth;
		this.width = $(this.elemAux).get(0).offsetWidth;
	}
	this.verifyQuantity = function(){
		this.width = $(this.elemAux).get(0).offsetWidth;
		this.total = this.width/this.widthAdd;
		this.index = this.getLeft()*(-1)/this.widthAdd;
	}
	this.reset = function(){
		this.anima(0);
	}
	this.anima = function(range){
		var thisAux = this;
		if(thisAux.controle){
			thisAux.controle = false;
			$(this.elemGalAux).animate({
				left: range
				},'250',function(){
					thisAux.verifyQuantity();
			    	thisAux.controle = true;
					if(thisAux.callback != null) thisAux.callback(thisAux);
			    }
			)
		}
	}
}

function callAnima(thisGal){
	if (thisGal.total - thisGal.index < 4) {
		var id = $(thisGal.elem).find(".postsSocialItem:last input").val();
		Utils.executeAjax({url: "/social/get-updates.action?id="+id, type:"GET",call:"callAnimaResponse",args:thisGal});
	}
}
function callAnimaResponse(response,args){
	$(args.elemAux).html($(args.elemAux).html() + response);
}
function initRedeSocial(){
	
	initEsqueciSenha(); // functions.js
	
	$("#jsLoginSadia").click(function(){
		$("#jsFrmLoginSadia").show();
		$("#jsIniLoginSadia").hide();
		return false;
	});
	
	if($(".jsGaleriaPostContainer").size()!=0){
		galPost = new GaleriaPost($(".jsGaleriaPostContainer").get(0));
		galPost.callback = callAnima;
		galPost.init();
	}
	
	$("#intervencaoSocial #frmLogin").unbind("submit").submit(function(){
		$("#intervencaoSocialAux").animate({opacity:0},100,function(){
			var divLoad = $("<div/>").css({height:100,position:"absolute",top:0,left:"50%"}).append(Utils.loader({src:"/img/ajax-loader-redeSoc.gif"}));
			$(this).parent().append(divLoad);
			
			$("#intervencaoSocialAux").animate({height:50},250,function(){
				Utils.executeAjax({type: "post",url:$("#frmLogin").attr("action"),data:$("#frmLogin").serialize(),call:"loginResponse"});				
			});
		});
		return false;
	});
	
	Utils.fieldFocus($("#cmpLogin").get(0));
	
	if($("#social_message").val()!="")
		$("#status").val($("#social_message").val())
	
	redeSocial = new RedeSocial();
	
	var arForms = {};
	arForms.friends = new Array();
	arForms.communities = new Array();
	
	if ($("#frmAmigosSocial").size() != 0) {
		arForms.friends.push({form: $("#frmAmigosSocial").get(0),text: $("#status").get(0)})
		arForms.communities.push({form: $("#frmComunidadesSocial").get(0),text: $("#status").get(0)})
	}
	if ($("#frmAmigosSocial2").size() != 0) {
		arForms.friends.push({form: $("#frmAmigosSocial2").get(0),text: $("#status2").get(0)})
		arForms.communities.push({form: $("#frmComunidadesSocial2").get(0),text: $("#status2").get(0)})
	}
	redeSocial.init(arForms);
	
	if($("[for^='scTwitter']").not("[for^='scTwitter'].naoLogado").size()!=0){
		redeSocial.addCommunitiesFriends("Twitter");
	}
	if($("[for^='scFacebook']").not("[for^='scFacebook'].naoLogado").size()!=0){
		redeSocial.addCommunitiesFriends("Facebook");
	}
	redeSocial.listenerLoginLogout();
	
	$(".btScEmail").click();
}

function twitterRequestAuthorizationError(){
	Utils.avisoRedeSocial({status:true,msg:"Erro ao tentar acessar o Twitter"});
}

function loginTwitter(userName){
	redeSocial.add("Twitter",userName);
}
function loginFacebook(userName){
	redeSocial.add("Facebook",userName);
}

function loginResponse(response) {
	$("#intervencaoSocialAux").html(response);
	$("#intervencaoSocialAux").animate({height:$("#intervencaoSocialAux > div").get(0).offsetHeight},250,function(){
		$("._loader").parent().remove();
		$("#intervencaoSocialAux").animate({opacity:1},100,function(){
			initRedeSocial();
			onScriptsLoaded();
		});
	});
	pageTracker._trackPageview("/menu_compartilhe_login_sadia/");
	dataMetrics({pageName:"Home - Login Site", channel:"Home",events:"event30"});
}

RedeSocial = function(){
	this.friends = new Array();
	this.friendsCurrent = null;
	this.communities = new Array();
	this.communitiesCurrent = null;
	
	this.init = function(opt){
		var thisAux = this;
		$(opt.friends).each(function(index){
			if (this.form != undefined) {
				$(this.form).unbind("submit").submit(function(){
					if(thisAux.friendsCurrent==null){
						alert("Selecione umas das opções");
						return false;
					}
					thisAux.friendsCurrent = thisAux.friends[index];
					if($(thisAux.friendsCurrent.form).find(":checkbox").size()!=0 && $(thisAux.friendsCurrent.form).find(":checked").size()==0 || ($(thisAux.friendsCurrent.form).find("textarea").size()!=0 && $.trim($(thisAux.friendsCurrent.form).find("textarea").val())=="")){
						alert("Selecione pelo menos um amigo(a)");
						return false;
					}
					
					if($(this).attr('id')=='frmAmigosSocial'){
						GetActionTag('qz1sad_SADIAVIDACOMSBOTAOENVIARAMIGOS_1');
					} else {
						GetActionTag('qz1sad_SADIAVIDACOMSBOTAOENVIARAMIGOSBOX_1');					
					}
					
					thisAux.friendsCurrent.postMessage();
					
					return false;
				});
				
				var friends = new RedeSocialFriends(this);
				thisAux.friends.push(friends);
			}
		});
		
		$(opt.communities).each(function(index,value){
			if (this.form != undefined) {
				$(this.form).unbind("submit").submit(function(){
					if($(this).find(":checked").size()==0){
						alert("Selecione umas das opções");
						return false;
					}
					if($(this).attr('id')=='frmComunidadesSocial'){
						GetActionTag('qz1sad_SADIAVIDACOMSBOTAOENVIARCOMUNIDADES_1');
					} else {
						GetActionTag('qz1sad_SADIAVIDACOMSBOTAOENVIARCOMUNIDADESBOX_1');					
					}
					Utils.fundoRedeSocial(true, "Enviando mensagem para suas comunidades...");
					thisAux.communitiesCurrent = thisAux.communities[index];
					thisAux.postCommunities();
					return false;
				});
				
				var communities = this;
				thisAux.communities.push(communities);
			}
		});
	}
	this.add = function(redeSoc,userName){		
		var conectado = (typeof userName!='undefined')? 'conectado como <strong>'+userName+'</strong> | ':'';
		var label = conectado +'<a href="#" title="sair" class="jsDeauthorize'+ redeSoc +'">sair</a>';
		var labelOld = $(".lstIntervencaoRedesSociais #signin" +redeSoc);
		$(labelOld).parents("li").addClass("logado");
		$(labelOld).parent().html(label);
		$(labelOld).remove();
		
		this.addCommunities(redeSoc);
		this.addFriends(redeSoc);
		this.listenerLoginLogout();
	}
	this.addCommunitiesFriends = function(redeSoc){
		this.addCommunities(redeSoc);
		this.addFriends(redeSoc);
		this.listenerLoginLogout();
	}
	this.addCommunities = function(redeSoc){
		var thisAux = this;
		
		$($(".jsFrmComunidadesSocial .btSc"+ redeSoc).parents("label")).each(function(index){
			if($(this).hasClass("naoLogado")){
				var input = $("<input/>").attr({type:"checkbox",name:"sc"+redeSoc+(index==0?'':index),id:"sc"+redeSoc+(index==0?'':index)}).val(redeSoc);
				var a = $("<a/>").attr({title:"Sair",href:"#"}).html("Sair").addClass("btSairRedeSocial").addClass("jsDeauthorize"+redeSoc);
				$(this).removeClass("naoLogado").prepend(input).append(a);
				$(this).find(".btLoginRedeSocial").remove();
			}
		});
	}
	this.addFriends = function(redeSoc){
		if(redeSoc!="Facebook"){
			var thisAux = this;
			var a = $("<a/>").addClass("btSc"+redeSoc).attr({href:"#",title:redeSoc}).html(redeSoc).unbind("click").click(function(){
				thisAux.friendsCurrent = thisAux.friends[$(".jsFrmAmigosSocial ul").index($(this).parents("ul"))];
				thisAux.friendsCurrent.selected(this,redeSoc);
				return false;
			});
			
			var li = $("<li/>").append(a);
			$(li).insertBefore($(".jsFrmAmigosSocial ul").not($(".jsFrmAmigosSocial li a.btSc"+redeSoc).parents("ul")).find("li:last"));
		}
	}
	this.remove = function(redeSoc){
		var thisAux = this;

		var span = $(".lstIntervencaoRedesSociais .jsDeauthorize" +redeSoc).parent();
		$(span).html("").append($("<a/>").attr({id:"signin"+redeSoc,title:redeSoc,href:"#"}).html("Fazer login"));
		$(span).parents("li").removeClass("logado");
		
		this.removeCommunitiesFriends(redeSoc);
		
		$(this.friends).each(function(){
			if(typeof this.selectedCurrent != "undefined" && this.selectedCurrent == redeSoc){
				$(this.form).find(".listAmigos").html("");
			}
		})
				
		Utils.avisoRedeSocial({status:true,msg:"Você foi desconectado do "+redeSoc});
			
		this.listenerLoginLogout();
	}
	this.removeCommunitiesFriends = function(redeSoc){		
		$(".jsFrmComunidadesSocial label[for^=sc"+ redeSoc +"]").each(function(index){
			if(this.length!=0 && !$(this).hasClass("naoLogado")){
				$(this).find("input").remove();
				$(this).addClass("naoLogado");
				var a = $("<a/>").attr({id:"signin"+redeSoc+(index==0?'':index),title:"Login",href:"#"}).html("Login").addClass("btLoginRedeSocial");
				$(this).append(a);
				$(this).find(".btSairRedeSocial").remove();
			}
		})
		
		$(".jsFrmAmigosSocial .btSc"+redeSoc).parents("li").remove();
	}
	this.postCommunities = function(){
		if(typeof galPost != 'undefined') Utils.executeAjax({url:"/social/updateStatus.action",data:{text:$(this.communitiesCurrent.text).val()},call:"postSadiaResponse",type:"POST"});
		var txt = $(this.communitiesCurrent.text).val();
		var arComunVal = new Array();
		var arComun = $(this.communitiesCurrent.form).find("input:checked");
		
		$(arComun).each(function(){	
			switch(this.value){
				case "Facebook":
					Facebook.statuses_update(txt);
				break;
				case "Orkut":
					if(window.console) console.log("Orkut");
				break;
				case "Twitter":
					Twitter.statuses_update(txt);
				break;
				case "Msn":
					MSN.postBlog(txt);
				break;
			};
			arComunVal.push(this.value);
		});
		
		//var box = (typeof this.communities[1]!= 'undefined' && this.communitiesCurrent.form==this.communities[1].form)?"_box":"_header";
		
		dataMetrics({prop4:arComunVal.join(","),pageName:"Compartilhe este Site - Enviar para comunidades "+arComunVal.join(","),events:getEvents()});
		pageTracker._trackPageview("/menu_compartilhe_comun_enviar"+ box +"_["+ arComunVal.join(",") +"]/?id="+ (_userSadia.id!=""?_userSadia.id:0) +"&url="+ window.location +"/");
		dataAtlas("BOTAOENVIARCOMUNIDADES"+ box.toUpperCase().replace(/(_)|(HEADER)/g,""));
	}
	this.listenerLoginLogout = function(){
		var thisAux = this;
		/* Twitter */		
		$("#signinTwitter, #jsRedSocNaoLogado .btScTwitter,.lstIntervencaoRedesSociais a.btScTwitter,label[for^=scTwitter] .btLoginRedeSocial").unbind("click").click(function(){
			Utils.pop("/social/twitter/request-authorization.action","Twitter",400,800);
			return false;
		});
		$(".jsDeauthorizeTwitter").unbind("click").click(function(){
			Utils.executeAjax({url:"/social/twitter/deauthorize.action",type:"GET",call:"Twitter.deauthorizeResponse"});
			return false;
		});
		/* END:Twitter */
		
		/* Facebook */		
		$("#signinFacebook, #signinFacebook2, label[for^=scFacebook] .btLoginRedeSocial").unbind("click").click(function(){
			Utils.pop("/social/facebook/request-authorization.action","Facebook",400,800);
			return false;
		});
		$(".jsDeauthorizeFacebook").unbind("click").click(function(){
			Utils.executeAjax({url:"/social/facebook/deauthorize.action",type:"GET",call:"Facebook.deauthorizeResponse"});
			return false;
		});
		/* END:Facebook */
		
		/* Msn */
		$("#jsRedSocNaoLogado .btScMsn,.lstIntervencaoRedesSociais a.btScMsn,label[for^=scMsn] .btLoginRedeSocial").unbind("click").click(function(){
			return false;
		});
		if($("#signinMsn,#signinMsn1").size()!=0){
			listenerMsn();
		}
		
		$(".jsDeauthorizeMsn").unbind("click").click(function(){
			$("#delegationTokenMsn").val("");
			MSN.signIn = false;
			Utils.executeAjax({url:"/social/live/deauthorize.action",type:"GET",call:"MSN.deauthorizeResponse"});
			if(_user!= null && _user.get_status()==2)_user.signOut(Microsoft.Live.Messenger.SignOutLocations.local);
			return false;
		});
		/* END:Msn */
		
		$(".btScEmail").unbind("click").click(function(){
			thisAux.friendsCurrent = thisAux.friends[$(".jsFrmAmigosSocial ul").index($(this).parents("ul"))];
			thisAux.friendsCurrent.selected(this,"Email");
			return false;
		});
		
		this.verifyButtons();
	}
	this.verifyButtons = function(){
		$(this.communities).each(function(index){
			var form = this.form;
			if (form != undefined) {
				if($(form).find(":checkbox").size()==0){
					$(form).find("[type='image']").attr("src","/img/bt_enviar_soc_inativo.png");
				}else{
					$(form).find("[type='image']").attr("src","/img/bt_enviar_soc.png");
				}
			}
		});
	}
	this.successMessage = function(){
		if ($("#intervencaoSocialAux:visible").size() != 0) {
			$("#intervencaoSocialAux").slideToggle(800,function(){
				$("#banner").append('<div class="redeSocialMessage">' +
				'<h3>Mensagem Enviada</h3>' +
				'<p><a href="#" title="Enviar outra mensagem">Enviar outra mensagem</a></p>' +
				'</div>');
				$(".redeSocialMessage a").click(function(){
					$("#intervencaoSocialAux").slideToggle(400);
				});
				$(".redeSocialMessage").fadeIn(300);
				setTimeout('$(".redeSocialMessage").fadeOut(300,function(){$(this).remove()})', 3500);
			});
		}
	}
}

RedeSocialFriends = function(opt){
	this.selectedCurrent;
	this.form = opt.form;
	this.text = opt.text;
	this.loader;
	this.selected = function(bt,redeSoc){
		this.selectedCurrent = redeSoc;
		this.bt = bt;
		$(bt).parents("ul").find("li").removeClass("ativo");
		$(bt).parents("li").addClass("ativo");
		
		this.loader = Utils.loader({src:"/img/ajax-loader-marrom.gif"});
		$(this.form).find(".listAmigos").css({position:"relative",overflow:"auto"}).html("").append(this.loader);
		
		switch(redeSoc){
			case "Facebook":
				if(Facebook.friends==null)
					$.getScript("/social/facebook/followers.action?callback=Facebook.showFriends");
				else Facebook.listFriends();
			break;
			case "Orkut":
				if(window.console) console.log("Orkut");
			break;
			case "Twitter":
				if(Twitter.friends==null)
					$.getScript("/social/twitter/followers.action?callback=Twitter.showFriends");
				else Twitter.listFriends();
			break;
			case "Msn":
				if(_user!= null && _user.get_status()!=2)
					_user.signIn();
				else
	   				MSN.showFriends();
			break;
			case "Email":
				$(redeSocial.friendsCurrent.form).find(".listAmigos").css({overflow:"hidden"}).append($("<textarea/>").val("Separar os endereços de email por ponto e vírgula"));
				Utils.fieldFocus($(redeSocial.friendsCurrent.form).find(".listAmigos textarea"));
				redeSocial.friendsCurrent.removeLoader();
			break;
		}
	}
	this.removeLoader = function(){
		$(this.loader).remove();
		$(".listAmigos").css({position:""});
	}
	this.postMessage = function(){
		if(this.selectedCurrent != "Email")
			Utils.fundoRedeSocial(true, "Enviando mensagem para seus amigos...");
			
		var num = $(this.form).find(".listAmigos input:checked").size();
		
		switch(this.selectedCurrent){
			case "Facebook":
				Facebook.directMessages_new();
			break;
			case "Orkut":
				if(window.console) console.log("Orkut");
			break;
			case "Twitter":
				Twitter.directMessages_new();
			break;
			case "Msn":
				MSN.sendMessages();
			break;
			case "Email":
			var textarea = $(redeSocial.friendsCurrent.form).find(".listAmigos textarea");
				if ($(textarea).val() == $(textarea).data("valueIni")) {
					alert("Informe o emails dos seus amigos.");
					$(textarea).focus();
					return false;
				}
			
				var valueNew = $(textarea).val().replace(/,/g,";");
				var valueNew = valueNew.replace(/\s/g,"");
				$(textarea).val(valueNew);
				var values = $(textarea).val();
				var emailsInvalid = Utils.validateMultipleEmail(values);
				
				if(emailsInvalid.length!=0){
					alert("Emails inválidos: "+ emailsInvalid.join(","));
					return false;
				}
				
				if($(this.bt).attr("href")!="#"){
					modalSendEmail = new Modal();
					modalSendEmail.init({ajax:{type:"get",url:$(this.bt).attr("href"), call: "EmailSocial.catchFrom"}});
					num = values.split(";");
					return false;
				}
				EmailSocial.sendEmail();
			break;
		}
		if(this.selectedCurrent!= "Email"){
			//var box = (typeof redeSocial.friends[1]!= 'undefined' && redeSocial.friendsCurrent.form==redeSocial.friends[1].form)?"_box":"_header";
			
			dataMetrics({prop5:this.selectedCurrent,prop33:num,pageName:"Compartilhe este Site - Enviar para amigos "+this.selectedCurrent,events:getEvents()});
			pageTracker._trackPageview("/menu_compartilhe_amigos_enviar"+ box +"_["+ this.selectedCurrent +"]/?id="+ (_userSadia.id!=""?_userSadia.id:0) +"&num="+ num +"&url="+ window.location +"/");
			dataAtlas("BOTAOENVIARAMIGOS"+ box.toUpperCase().replace(/(_)|(HEADER)/g,""));
		}
	}
}

EmailSocial = function(){}
EmailSocial.catchFrom = function(response){
	$("#frmEnviarEmailSocial").validate({
		errorLabelContainer: $("ul.error"),
		wrapper: 'li',
		submitHandler: function(form){
			EmailSocial.sendEmail($("#nomeEmailSocial").val(),$("#emailEmailSocial").val());
			modalSendEmail.close();
			Utils.fundoRedeSocial(true, "Enviando mensagem para seus amigos...");
		},
		rules: {
			nomeEmailSocial: {
				required: true,
				minlength: 4
			},
			emailEmailSocial: {
				required: true,
				email: true
			}
		},
		messages: {
			nomeEmailSocial: {
				required: 'Preencha o campo nome',
				minlength: 'Mínimo de 4 digitos para o campo Nome'
			},
			emailEmailSocial: {
				required: 'Preencha o campo email',
				email: 'Endereço do campo email inválido'
			}
		}
	});
}
EmailSocial.sendEmail = function(from, emailFrom){
	Utils.fundoRedeSocial(true, "Enviando mensagem para seus amigos...");
	var data = {emails: $(redeSocial.friendsCurrent.form).find(".listAmigos textarea").val(),status: $(redeSocial.friendsCurrent.text).val()};
	if(typeof from!='undefined' || typeof emailFrom!='undefined'){
		data.from =  from;
		data.emailFrom = emailFrom;
	}
	Utils.executeAjax({url:"/enviar-amigos.action",data:data,type:"POST",call:"EmailSocial.sendEmailResponse"});
	//var box = (typeof redeSocial.friends[1]!= 'undefined' && redeSocial.friendsCurrent.form==redeSocial.friends[1].form)?"_box":"_header";
			
	dataMetrics({prop5:"Email",pageName:"Compartilhe este Site - Enviar para amigos "+this.selectedCurrent,events:getEvents()});
	pageTracker._trackPageview("/menu_compartilhe_amigos_enviar"+ box +"_[Email]/?id="+ (_userSadia.id!=""?_userSadia.id:0) +"&num="+ data.emails.split(";").length +"&url="+ window.location +"/");	
	dataAtlas("BOTAOENVIARAMIGOS"+ box.toUpperCase().replace(/(_)|(HEADER)/g,""));
}
EmailSocial.sendEmailResponse = function(response){
	var response = eval("("+ response +")");
	Utils.fundoRedeSocial(false);
	if (response.success) {
		Utils.avisoRedeSocial({status: true,msg: "Mensagem enviada com sucesso!!"});
	}
}

function postSadiaResponse(){
	$(galPost.elemAux).load("/social/get-updates.action",function(){
		galPost.reset();
	});
}
/* Twitter */
Twitter = function(){}
Twitter.friends = null;
Twitter.showFriends = function(data){
	Twitter.friends = data;
	Twitter.listFriends();
}
Twitter.listFriends = function(){
	redeSocial.friendsCurrent.removeLoader();
	$(Twitter.friends).each(function(index){
		var formId = $(redeSocial.friendsCurrent.form).attr("id");
		var input = $("<input/>").attr({type:"checkbox",name:formId+ "amigo" +index,id:formId+ "amigo" +index}).val(this.id);
		var label = $("<label/>").attr({"for":formId+ "amigo" +index,title:this.name}).text(this.screenName).prepend(input);
		$(redeSocial.friendsCurrent.form).find(".listAmigos").append(label);
	});
}
Twitter.statuses_update = function(txt){
	Utils.executeAjax({url:"/social/twitter/updateStatus.action",type:"post",data:{status:txt},call:"Twitter.statuses_updateResponse"});
}
Twitter.statuses_updateResponse = function(response){
	var response = eval("("+ response +")");
	
	Utils.fundoRedeSocial(false);
	if(response.success){
		Utils.avisoRedeSocial({status:true,msg:"Mensagem enviada com sucesso!!"});
		redeSocial.successMessage();
	}
}
Twitter.directMessages_new = function(){
	var idsFriends = "";
	$(redeSocial.friendsCurrent.form).find(".listAmigos input:checked").each(function(index){
		idsFriends = idsFriends + $(this).val()+",";
	});
	Utils.executeAjax({url:"/social/twitter/sendDirectMessage.action",type:"post",data:{ids:idsFriends,text:$(redeSocial.friendsCurrent.text).val()},call:"Twitter.directMessages_newResponse"});
}
Twitter.directMessages_newResponse = function(response){
	var response = eval("("+ response +")");
	Utils.fundoRedeSocial(false);
	
	if(response.success){
		Utils.avisoRedeSocial({status:true,msg:"Mensagem enviada com sucesso!!"});
		redeSocial.successMessage();
	}else{
		Utils.avisoRedeSocial({status:true,msg:"Erro ao enviar mensagem!!"});
	}
}
Twitter.deauthorizeResponse = function(response){
	redeSocial.remove("Twitter");
}

/* Facebook */
Facebook = function(){}
Facebook.friends = null;
Facebook.showFriends = function(data){
	Facebook.friends = data;
	Facebook.listFriends();
}
Facebook.listFriends = function(){
	redeSocial.friendsCurrent.removeLoader();
	$(Facebook.friends).each(function(index){
		var formId = $(redeSocial.friendsCurrent.form).attr("id");
		var input = $("<input/>").attr({type:"checkbox",name:formId+ "amigo" +index,id:formId+ "amigo" +index}).val(this.id);
		var label = $("<label/>").attr({"for":formId+ "amigo" +index,title:this.name}).text(this.screenName).prepend(input);
		$(redeSocial.friendsCurrent.form).find(".listAmigos").append(label);
	});
}
Facebook.statuses_update = function(txt){
	Utils.executeAjax({url:"/social/facebook/updateStatus.action",type:"post",data:{status:txt},call:"Facebook.statuses_updateResponse"});
}
Facebook.statuses_updateResponse = function(response){
	var response = eval("("+ response +")");
	
	Utils.fundoRedeSocial(false);
	if(response.success){
		Utils.avisoRedeSocial({status:true,msg:"Mensagem enviada com sucesso!!"});
		redeSocial.successMessage();
	}
}
Facebook.directMessages_new = function(){
	var idsFriends = "";
	$(redeSocial.friendsCurrent.form).find(".listAmigos input:checked").each(function(index){
		idsFriends = idsFriends + $(this).val()+",";
	});
	Utils.executeAjax({url:"/social/facebook/sendDirectMessage.action",type:"post",data:{ids:idsFriends,text:$(redeSocial.friendsCurrent.text).val()},call:"Facebook.directMessages_newResponse"});
}
Facebook.directMessages_newResponse = function(response){
	var response = eval("("+ response +")");
	Utils.fundoRedeSocial(false);
	
	if(response.success){
		Utils.avisoRedeSocial({status:true,msg:"Mensagem enviada com sucesso!!"});
		redeSocial.successMessage();
	}else{
		Utils.avisoRedeSocial({status:true,msg:"Erro ao enviar mensagem!!"});
	}
}
Facebook.deauthorizeResponse = function(response){
	redeSocial.remove("Facebook");
}

/* MSN */
MSN = function(){}
MSN.signIn = null;
MSN.flagUpdateFriends = false;
MSN.showFriends = function(){
	redeSocial.friendsCurrent.removeLoader();
	
	$(redeSocial.friendsCurrent.form).find(".listAmigos").html("");
	for (var i = 0; i < _user.get_onlineContacts().get_count(); i++) {
		var c = _user.get_onlineContacts().get_item(i);
		var input = $("<input/>").attr({type: "checkbox",name:"amigo" +i,id:$(redeSocial.friendsCurrent.form).attr("id")+"-amigo" +i}).val(c.get_cid()).data("contato",c);
		var label = $("<label/>").attr({"for":$(redeSocial.friendsCurrent.form).attr("id")+"-amigo"+i, title:c.get_currentAddress().get_address()}).text(c.get_displayName()).prepend(input);
		
		$(redeSocial.friendsCurrent.form).find(".listAmigos").append(label);
	}
}
MSN.updateFriends = function(){
	if (!MSN.flagUpdateFriends) {
		setTimeout('MSN.appendUpdateFriends()', 10000);
		MSN.flagUpdateFriends = true;
	}
}
MSN.appendUpdateFriends = function(){
	$(redeSocial.friends).each(function(){
		if(this.selectedCurrent == "Msn"){
			Utils.avisoRedeSocial({status: true,msg: "Atualizando amigos do MSN..."});
			
			$(this.form).find(".listAmigos").each(function(){
				var thisAux = this;
				var friendsChecked = $(this).find("input:checked");
				MSN.showFriends();
				$(friendsChecked).each(function(){
					$(thisAux).find("input[value=" + this.value + "]").attr("checked", "checked");
				});
			});	
		}
	});
	MSN.flagUpdateFriends = false;
}
MSN.sendMessages = function(){
	var arFriendMsn = $(redeSocial.friendsCurrent.form).find("input:checked");
	$(arFriendMsn).each(function(){
		var contato = $(this).data("contato");
		var _conv = _user.get_conversations().create(contato.get_currentAddress());
		var message = new Microsoft.Live.Messenger.TextMessage($(redeSocial.friendsCurrent.text).val(), null);
		_conv.sendMessage(message,null);
	});
	Utils.fundoRedeSocial(false);
	redeSocial.successMessage();
}
MSN.postBlog = function(txt){
	Utils.pop("http://spaces.live.com/BlogIt.aspx?Title=" + encodeURI(txt) + "&SourceURL=" + encodeURI(window.location.href) + "&description=" + encodeURI(txt),"MSN",400,800);
	Utils.fundoRedeSocial(false);
}
MSN.deauthorizeResponse = function(response){
	redeSocial.remove("Msn");
}