var userName;
var birthday;
var fbid;
var sex;
var hometown_location;
var work_history;
var relationship_status;

function update_user_box() {
	var fb = document.getElementById('fb');
	
	//parametry z GET
	var pole = window.location.search.substr(1).split("&"); 
	var httpGetVars = new Array(); 
	for(i = 0; i < pole.length; i++){
		httpGetVars[pole[i].split("=")[0]] = unescape(pole[i].split("=")[1]); 
	}
	
	var api = new FB.ApiClient('9e89ec78c5697bbd5390a18231e0b54c', 'connect/xd_receiver.html', null);
	
	if(!!readCookie('name')) {
		fb.innerHTML = '<img src="'+readCookie('pic')+'" alt="IK" width="30" height="25" style="float:left;" /><strong style="float:left;margin-top:5px;margin-left:5px;margin-right:5px;">' + readCookie('name') + '</strong><a style="float:left;margin-top:5px;" href="" onclick="logout();">Odhlásit</a>';
	}
	else {
		if(readCookie('status') == 1 || typeof httpGetVars['session'] != 'undefined') {
			createCookie('status', 2, 14);
			api.requireLogin(function(exception) {
				//FB.Facebook.apiClient.friends_get(null, function(response){alert(response);});
				var uid = api.get_session().uid;
				var sql = "SELECT uid, name, pic, birthday, relationship_status,hometown_location, sex, work_history FROM user WHERE uid ="+uid;
				FB.Facebook.apiClient.fql_query(sql, function(result, ex) {
					hometown_location = serializeArray(result[0]['hometown_location'])
					work_history = serializeArray(result[0]['work_history'])
					relationship_status = result[0]['relationship_status'];
			        userName= result[0]['name'];
			        pic= result[0]['pic'];
			        birthday= result[0]['birthday'];
			        sex= result[0]['sex'];
			        fbid= result[0]['uid'];
					createCookie('name', result[0]['name'], 14);	
					createCookie('fbid', result[0]['uid'], 14);	
					createCookie('pic', result[0]['pic'], 14);	
					createCookie('birthday', result[0]['birthday'], 14);
					register_user(userName, fbid, birthday, sex, relationship_status, hometown_location, work_history);
					savefriends();
					fb.innerHTML = '<img src="'+readCookie('pic')+'" alt="IK" width="30" height="25" style="float:left;" /><strong style="float:left;margin-top:5px;margin-left:5px;margin-right:5px;">' + userName + '</strong><a style="float:left;margin-top:5px;" href="" onclick="logout();">Odhlásit</a>';
				});
			});
		}
		else {
 			fb.innerHTML = '<a onclick="linkclick();"><img src="/img/fbbut.gif" alt="Login with FB" border="0"/></a>';
		}
	}
	if(httpGetVars['fb'] == 'login') {
		var crop = window.location.href.length-9;
		window.location.href = window.location.href.substr(0,crop);
	}
}

function savefriends() {
	var friends;
	FB.Facebook.apiClient.friends_get(null, function(response){
		friends = response.join(",");
		
		new Ajax.Request('/users/savefriends/', {
			method: 'get',
			parameters: {uids: friends},
				onSuccess: function(transport){
					var response = transport.responseText || "no response text";
					//alert(response);
				},
				onFailure: function(){ alert('Something went wrong...'); }	
		});
	});
}
function linkclick() {
	// sem je odkaz z linku pro login
	createCookie('status', 1, 14);
	update_user_box();	
}
function logout() {
	eraseCookie('status');
	eraseCookie('name');
	eraseCookie('fbid');
	eraseCookie('birthday');
	window.location.reload();
}
function register_user(name, fbid, birthday, sex, relationship_status, hometown_location, work_history) {
	new Ajax.Request('/users/register_fb_user/', {
		method: 'get',
		parameters: {name: name, fbid: fbid, birthday: birthday, sex:sex, relationship_status:relationship_status,hometown_location:hometown_location, work_history:work_history },
			onSuccess: function(transport){
				var response = transport.responseText || "no response text";
			},
			onFailure: function(){ alert('Something went wrong...'); }	
	});
}

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 readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return false;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}

function serializeArray(a)
{
	var serializedString = '';
	var arrayLength = 0;
	for(var aKey in a)
	{
		//key definition
		if(aKey * 1 == aKey) //is_numeric?
		{
			//integer keys look like i:key
			serializedString += 'i:' + aKey + ';';	
		}
		else
		{
			//string keys look like s:key_length:key;
			serializedString += 's:' + aKey.length + ':"' + aKey + '";';
		}
		
		//value definition
		if(a[aKey] * 1 == a[aKey])
		{
			//integer value look like i:value
			serializedString += 'i:' + a[aKey] + ';';	
		}
		else if(typeof(a[aKey]) == "string")
		{
			//string value look like s:key_length:value;
			serializedString += 's:' + a[aKey].length + ':"' + a[aKey] + '";';
		}
		else if(a[aKey] instanceof Array)
		{
			serializedString += serializeArray(a[aKey]);
		}
		arrayLength++;
	}
	serializedString = 'a:' + arrayLength + ':{' + serializedString + '}';
	
	return serializedString;
}