function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days*24*60*60*1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

window.addEventListener("load", function(){
	var uid;
	var token;
	var socialTranslationForm = document.getElementById("socialTranslationForm");
	socialTranslationForm.onsubmit = function(){return false;};

	FB.init({
		appId  : FOD.FB_APPID,
		status : true, // check login status
		cookie : true, // enable cookies to allow the server to access the session
		xfbml  : true  // parse XFBML
	});	
	
	function socialTranslationSubmitAction(){
		var formValid = false;
		
		if(socialTranslationForm.checkValidity){
			formValid = socialTranslationForm.checkValidity();
		}else{
			//TODO: implement custom validation
		}
		
		if(formValid){
			var ajaxIndicator = $('#socialTranslationAjaxProgress');
			ajaxIndicator.fadeIn(500);
			
			var realOriginalLanguage = document.getElementById("realOriginalLanguage");
			var ol;
			if(realOriginalLanguage){
				ol = realOriginalLanguage.value;
			}else{
				ol = $("#ol option:selected").val();	
			}
			
			var tl;
			var realTargetLanguage = document.getElementById("realTargetLanguage");
			if(realTargetLanguage){
				tl = realTargetLanguage.value;
			}else{
				tl = 'en';
			}
				
			var st_count = getSocialTranslationEntitiesCount();
			var data = {
				'uid'	: uid,
				'token'	: token,
				'sn'	: 1,
				'st_ol'	: ol,
				'st_tl'	: tl
			};
			
			data['st_count'] = st_count;
				
			var ids = ['st_ot', 'st_tt', 'st_pof'];
			
			var added = [];
			
			for(var i = 1; i <= st_count; i++){
				var tr = [];
				for(var idI in ids){
					var k = ids[idI] + i;
					var h = '#' + k;
					var val = $(h).val();
					data[k] = val;
					tr.push(val);
				}
				added.push('<b>[' + tr.join(' - ') + '</b>]');
			}
			
			$.ajax('/socialtranslate', {
				'type'		: 'post',
				'data'		: data,
				'success'	: function(data, status, xhr){					
					FB.ui(
							{								
								method		: 'feed',
								name		: 'FreeOpenDictionary Social Translations',
								link		: window.location.href,
								picture		: 'https://fbcdn-photos-a.akamaihd.net/photos-ak-snc1/v27562/149/193513424001305/app_1_193513424001305_9534.gif',
								caption		: 'I participated in Social Translations! My contribution: ' + added.join(', '),
								description	: 'Social Translations is the new cool way to share knowledge and one step towards a better world. History is made today. Share what you know and let\'s create together the first social dictionary ever!',
								message		: 'Social Translations are cool!'
						   },
						   function(response) {
							   if (response && response.post_id) {
								   //alert('Post was published.');								   
							   } else {
								   //alert('Post was not published.');
							   }
							   FB.ui(
									   {method: 'apprequests', message: 'Social Translations are cool! Check it out.'},
									   function(response) {
										   if (response && response.post_id) {
											   //alert('Post was published.');								   
										   } else {
											   //alert('Post was not published.');
										   }
		
										   window.location.reload();
									   }
							   );							   
						   }
					 );
				},
				'error'		: function(xhr, status, e){
					console.log(status, e);
				},
				'complete'	: function(xhr, status){
					ajaxIndicator.fadeOut(500);
				}
			});
		}
	};
	
	function getSocialTranslationEntitiesCount(){
		return parseInt($("#st_count").val());
	}
	
	function setSocialTranslationEntitiesCount(count){
		$("#st_count").val(parseInt(count));
	};
	
	function addSocialTranslationEtries(){
		var st_count = getSocialTranslationEntitiesCount();
		var newCount = st_count + 1;
		
		var socialTranslationEntry = document.createElement("div");
		socialTranslationEntry.setAttribute("id", "socialTranslationEntry" + newCount);
		
		var ids = ["st_ot", "st_tt", "st_pof"];
		var attributes = ["type", "placeholder", "pattern", "title", "required", "value"];
		
		for(var i in ids){			
			var htmlId = ids[i];
			var id = htmlId + newCount;
			var prevElement = document.getElementById(htmlId + st_count);
			
			var el;
			
			if(htmlId == "st_pof"){
				el = $(document.createElement("select"));				
				var prevOptions = prevElement.options;
				
				for(var i = 0; i < prevOptions.length; i++){
					po = prevOptions[i];
					
					el.append($(document.createElement("option")).
	                        attr("value", po.value).text(po.text));
				}				
				el = el[0];				
			}else{
				el = document.createElement("input");				
			}
			
			el.setAttribute("id", id);
			el.setAttribute("name", id);
			
			for(var attrI in attributes){
				var attrValue = prevElement.getAttribute(attributes[attrI]);
				if(attrValue){
					el.setAttribute(attributes[attrI], attrValue);
				}
			}			
			socialTranslationEntry.appendChild(el);
		}
		
		$("#socialTranslationEntries").append(socialTranslationEntry);
		
		setSocialTranslationEntitiesCount(newCount);
		
		return false;
	}
	
	var loginStatus = function(response){	    
		var socialTranslationSubmit 	= document.getElementById('socialTranslationSubmit');
		var socialTranslationAdd 		= document.getElementById("socialTranslationAdd");
		socialTranslationAdd.onclick 	= addSocialTranslationEtries;		
		if(response.session && response.perms){			
			/*button.setAttribute('class', 'logout');			
			button.onclick = function(){ FB.logout(); $(button).fadeOut(); };
			$(button).fadeIn();*/
			socialTranslationSubmit.onclick = socialTranslationSubmitAction;
			
			var query = FB.Data.query('select first_name from user where uid = me()');
			query.wait(function(rows){
				if(rows && rows.length > 0){
					var firstName = rows[0].first_name;
					document.getElementById("userWelcome").innerHTML = 'Hi, <span id="userName">' + firstName + "!" + '</span>';
				}
			});
			
			uid 	= response.session.uid;
			token 	= response.session.access_token;
			
			createCookie("uid", uid, 1);			
			createCookie("socialNetworkId", 1);
			createCookie("token", token, 1);
			
			$("#loginPrompt").fadeOut();
		}else {		    
			uid 	= undefined;
			token 	= undefined;
			
			eraseCookie("uid");
			eraseCookie("socialNetworkId");
			eraseCookie("token");
			
			document.getElementById("userWelcome").innerHTML = "";
			
			socialTranslationSubmit.onclick = function(){
			    FB.login(
                    function(response){                     
                        if(response.session && response.perms){
                            // user logged in and granted permissions                            
                            loginStatus(response);
                            $(socialTranslationSubmit).click();
                        }else{
                            // user either is logged or not granted permissions                         
                        }
                    }
                    ,{perms: "offline_access"}
                );
            };
            
			document.getElementById("buttonLogin").onclick = function(){
                FB.login(
                    function(response){                        
                        if(response.session && response.perms){
                            // user logged in and granted permissions
                            loginStatus(response);
                        }else{
                            // user either is logged or not granted permissions                         
                        }
                    }
                    ,{perms: "offline_access"}
                );
			};
			
			$("#loginPrompt").fadeIn();
		}
	};
	
	FB.getLoginStatus(loginStatus);
	//FB.Event.subscribe("auth.statusChange", function(response){ console.log("auth.statusChange", response); loginStatus(response); });	
	
	//<fb:comments numposts="5" width="425" publish_feed="true" xid="193513424001305"></fb:comments>
	var fbComments = document.getElementById("fb_comments");
	if(fbComments){
		fbComments.innerHTML = '<fb:comments numposts="5" width="425" publish_feed="true" xid="' + FOD.FB_APPID + '"></fb:comments>';
	}
	
	var topContributorsSize = $("#topContributors_size").html();	
	if(topContributorsSize){
		var data = {};
		var uids = [];
				
		for(var i = 0; i < topContributorsSize; i++){						
			var contributorUid = $("#uid_" + i).html();
			uids.push(contributorUid);
			var total = $("#total_" + i).html();
			data[contributorUid] = {total : total, i: i};			
		}
		
		var q = FB.Data.query('select uid, pic_square, name from user where uid in({0})', uids);
		
		q.wait(function(rows){
			for(var rowI in rows){
				var row = rows[rowI];				
				data[row.uid]['picture'] = row.pic_square;
				data[row.uid]['name'] = row.name;
			}
			
			for(var uidI in uids){
				var uid = uids[uidI];
				var entry = data[uid];
				var i = entry.i;
				$("#picture_" + i).append($(document.createElement("img")).attr({"src" : row.pic_square, 'class':'avatar'}));
				$("#name_" + i)
					.append($(document.createElement("a")).attr({
						href: document.location.protocol + '//www.facebook.com/profile.php?id=' + uid,
						target: "_blank"
					}).append($(document.createTextNode(entry.name))));
				$("#topContributor_" + i).fadeIn();
			}
		});
	}
	
}, false);

