﻿// JavaScript Document

FB.init({apiKey: '413c3fb6ef0749099af4e3b63ec3e438',});
function perfect_match_conectarse() {
      //FB.getLoginStatus(handleSessionResponse);
	  FB.login(handleSessionResponse, {perms:'publish_stream, user_about_me, friends_about_me , user_interests, friends_interests, user_photos, user_photo_video_tags, friends_photo_video_tags, user_relationships, friends_relationships, read_friendlists, read_mailbox'});
}

// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
	// if we dont have a session, just hide the user info
	if (!response.session) {
	  return;
	}
	
	determina_estado();
}
	  
// friend list
var friendList = [];
var friendListPhotos = [];
var friendMessage = [];
var numFriends = 0;
var sexo_opuesto = "";
var significant_other_id = 0;
var nombre = "";
var nombre_completo = "";
var foto = "";
var pm_uid = null;

function determina_estado() {
FB.api(
  {
	method: 'fql.query',
	query: "SELECT significant_other_id, sex, pic_big, significant_other_id, name, first_name FROM user WHERE uid = me() "
  },
  function(response) {
	window.sexo_opuesto = response[0]['sex']=='hombre'?'mujer':'hombre';
	window.significant_other_id = response[0]["significant_other_id"];
	window.nombre_completo = response[0]["name"];
	window.nombre = response[0]["first_name"];
	window.foto = response[0]["pic_big"];
        if(response[0]['sex'] == "") {
          document.getElementById("flashcontent").select_sex();
        } else {
          lista_amigos_sexo_opuesto();
        }
  }
);
}

function select_sex(sexo) {
          window.sexo_opuesto = sexo=='hombre'?'mujer':'hombre';
          lista_amigos_sexo_opuesto();
}

function lista_amigos_sexo_opuesto() {
  FB.api(
	{
		method: 'fql.query',
		query: "SELECT uid, pic_big, name, first_name FROM user WHERE sex='" + window.sexo_opuesto + "' AND uid IN (SELECT uid2 FROM friend WHERE uid1 = me())"
	},
	function(response) {
		window.numFriends = response.length;
		var lista_img_friends = "";
		for(var friend in response) {
			window.friendList[response[friend]["uid"]] = {"name": response[friend]["name"], "pic_big": response[friend]["pic_big"], "first_name": response[friend]["first_name"]};
			lista_img_friends += response[friend]["pic_big"] + ";";
		}
		lista_img_friends = lista_img_friends.substr(0, lista_img_friends.length - 2);
		
		// Entregamos relacion de imagenes a flash
		document.getElementById("flashcontent").send_friend_image_list(lista_img_friends);
		document.getElementById("flashcontent").send_nombre_url_foto(window.nombre, window.foto);
		
		if(window.significant_other_id != null) {
			//Tiene una relacion directa
			alert("Relacion directa con: " + window.friendList[window.significant_other_id]["name"]);
		} else {
			//Busca en sus amigos quien es su perfect match
			lista_fotos_usuario();
                        //lista_mensajes();
		}
	}
  );
}
	  
function lista_fotos_usuario() {
  FB.api(
	{
		method: 'fql.query',
		query: "SELECT pid, subject FROM photo_tag WHERE subject IN ( " +
				   "SELECT uid " +
				   "FROM user " +
				   "WHERE sex='" + window.sexo_opuesto + "' " +
				   "AND uid IN ( " +
						"SELECT uid2 " +
						"FROM friend " +
						"WHERE uid1 = me() " +
				   ")" +
			   ") AND pid IN ( " +
				   "SELECT pid FROM photo_tag WHERE subject = me() " +
			   ")"
	},
	function(response) {
		for(var friend in response) {
			if( friendListPhotos[response[friend]["subject"]] == undefined ) friendListPhotos[response[friend]["subject"]] = 0;
			friendListPhotos[response[friend]["subject"]] ++;
		}
					
		var valMax = 0, uidMax = 0;
		for(var friend in friendListPhotos) {
		  if(friendListPhotos[friend] > valMax) {
			  valMax = friendListPhotos[friend];
			  uidMax = friend;
		  }
		}
		
		window.pm_uid = uidMax;
		document.getElementById("flashcontent").send_perfect_match(friendList[window.pm_uid]["name"], friendList[window.pm_uid]["first_name"], friendList[window.pm_uid]["pic_big"]);
		//publicar1();
	}
  );
}

function lista_mensajes() {
  FB.api(
	{
		method: 'fql.query',
		query: "SELECT message_count, snippet_author FROM thread WHERE folder_id = 0 OR folder_id = 1"
	},
	function(response) {
                    var max_friend_message = 0;
                    var max_friend_uid = 0;
		for(var thread in response) {
			//if( friendListPhotos[response[friend]["subject"]] == undefined ) friendListPhotos[response[friend]["subject"]] = 0;
			//friendListPhotos[response[friend]["subject"]] ++;
                        for(var friend in friendList) {
                              if(response[thread]["snippet_author"] == friend) {
                                        if(friendMessage[friend] == undefined) friendMessage[friend] = 0;
                                        friendMessage[friend] += parseInt(response[thread]["message_count"]);
                                        if(friendMessage[friend] > max_friend_message) {
                                                  max_friend_message = friendMessage[friend];
                                                  max_friend_uid = friend;
                                        }
                              }
                        }
		}
          alert("Maximo mensaje: " + max_friend_message + ", " + max_friend_uid);
					
		/*
                 var valMax = 0, uidMax = 0;
		for(var friend in friendListPhotos) {
		  if(friendListPhotos[friend] > valMax) {
			  valMax = friendListPhotos[friend];
			  uidMax = friend;
		  }
		}
                */
	}
  );
}

function publicar2() {
	FB.ui(
		{
			method: 'stream.publish',
			message: 'Perfect Match de Facebook',
			attachment: {
				name: 'Perfect Match de Facebook',
				caption: window.nombre_completo + ' ha encontrado su posible Perfect Match dentro de Facebook',
				description: (
				'Tu Perfect Match es ' + friendList[window.pm_uid]["name"] + ', que es la persona con quien mejor compartes contenido en Facebook'
			),
			href: 'http://www.lavidaeasy.com'
			},
			action_links: [
				{ text: 'Buscar Perfect Match', href: 'http://www.lavidaeasy.com' }
			],
			user_message_prompt: 'Escribe un comentario'
		},
		function(response) {
		}
	);
}

function publicar1() {
	FB.ui(
		{
			method: 'stream.publish',
			message: 'Perfect Match de Facebook',
			attachment: {
				name: 'Perfect Match de Facebook',
				caption: window.nombre_completo + ' está buscando su posible Perfect Match dentro de Facebook',
				description: (
				'Easy te invita a encontrar tu posible Perfect Match dentro de Facebook. Tu complemento perfecto si exíste!'
			),
			href: 'http://www.lavidaeasy.com'
			},
			action_links: [
				{ text: 'Buscar Perfect Match', href: 'http://www.lavidaeasy.com' }
			],
			user_message_prompt: 'Escribe un comentario'
		},
		function(response) {
			//if (response && response.post_id) {
			//	document.getElementById("flashcontent").send_perfect_match(friendList[window.pm_uid]["name"], friendList[window.pm_uid]["first_name"], friendList[window.pm_uid]["pic_big"]);
			//} else {
			//	alert('Para conocer tu Perfect Match debes publicar este feed');
			//}
		}
	);
}

