$( document ).ready( function() {
	$('#facebookConnectButton').click( function() {
		FB.login( receivedFacebookLoginResponse, { perms:'read_friendlists,publish_stream' } );
	});
});

function receivedFacebookLoginResponse( response ) {
	if( response.session ){
		document.location.href = 'index.php';
	}
};

var useAllFriendeDebugMode = false,
totalFriendsInView = 10, // if two spots is shown in footer, set to 7
friendsWrapper = $('#footer div.friends');
function retrieveFriendsWhoUseApplication() {
	
	if(useAllFriendeDebugMode){
		FB.api('/me/friends?fields=id', function(response) {
		 				$.each(response.data, function(i,user){
		 					myFriendsArray.push(user.id);
		 				});
		 				parseAppUserFriends(myFriendsArray);
		 });
	} else {
		FB.api(
			{ method: 'friends.getAppUsers' }, 
			parseAppUserFriends
		);
	}
	
	
};

function parseAppUserFriends( users ) {
	if( users ){
		friendsWrapper.find('.holder').remove();
		$('<p/>', {id: 'moreFriends'}).html(copy.confessedFriends).appendTo(friendsWrapper);
		if( users.length > totalFriendsInView ) {
			$('<span/>').addClass('pipe').html('|').appendTo($('#moreFriends'));
			$('<a/>', {href: '#', id: 'see-all-previous'}).html(copy.loadMoreFriendsPrevious).appendTo($('#moreFriends'));
			$('<a/>', {href: '#', id: 'see-all-next'}).html(copy.loadMoreFriendsNext).appendTo($('#moreFriends'));
		}
		FB.api( '/', 'GET',{ ids: users.join(','), fields: 'name,id'}, function( response ){
			$.each(response, function(i,user){			
					$('<a/>', {
						href: 'userpage.php?userID=' + user.id,
						rel: user.name,
						mouseenter: function () {
							var thisLeft = parseInt($(this).offset().left);
							$('#fancyTitle').html('<strong>'+$(this).attr('rel')+'</strong> ' + copy.hasConfessed)
							var thisWidth = parseInt($('#fancyTitle').outerWidth()/2);
							$('#fancyTitle').css({ left: thisLeft-thisWidth+25 }).fadeIn();
    					},
    					mouseleave: function () {
        					$('#fancyTitle').hide();
    					}
					}).addClass('friend')
					  .html('<img src="http://graph.facebook.com/' + user.id + '/picture" />')
					  .appendTo(friendsWrapper);
			});
			$('#friend-slider').initSlider();			
		});
	} else {
		$('<div/>',{id: 'empty'}).html('<img src="ui/images/avatar-johnDoe.jpg" alt="avatar-johnDoe" width="50" height="50" /> <p>' + copy.noFriendsYet + '</p>').appendTo(friendsWrapper);
	}
};

function getUsername(userID){
	//console.log(userID);
	FB.api('/'+userID, {fields: 'name'}, function(response) {
  		userName = response.name;
  		$('<span/>').html(userName+copy.userConfessions + ' ').insertBefore($('#countTunes'));
	});
}

function postConfessionToFeed( tuneName, tuneURL, albumArtURL, artistName, songcode ) {
	/* POST TO FB */
	
	var message = copy.postConfessionToFBMessage;
	var propertiesObject = copy.postConfessionToFBSongKey;
	
	if( language == 'en' ) {
		propertiesObject = { 'Song' : { 'text': tuneName, 'href': tuneURL}, 'Artist': { 'text': artistName, 'href': tuneURL} };
	} else {
		propertiesObject = { 'Låt' : { 'text': tuneName, 'href': tuneURL}, 'Artist': { 'text': artistName, 'href': tuneURL} };
	}
	
	var imgURL;
	
	if( albumArtURL.indexOf( 'http://' ) != -1 ){
		imgURL = albumArtURL;
	} else {
		imgURL = 'http://bilmusikbikten.se/getdata/albumart.php?album=' + albumArtURL;
	}
	
	var attachment = { 	'name': copy.postConfessionToFBSiteLink, 
						'href': 'http://' + copy.postConfessionToFBSiteLink + '/userpage.php?userID=' + myID, 
						'description': copy.postConfessionToFBDescription,
						'properties' : propertiesObject, 
						'media': [{ 'type': 'image', 'src': imgURL, 'href': 'http://' + copy.postConfessionToFBSiteLink + '/userpage.php?userID=' + myID }] }; 
	
	FB.ui( { method: 'stream.publish', message: message, attachment: attachment },
		function( response ){
			if ( response && response.post_id && songcode != undefined ) {
				//postToDatabase( tuneName, tuneURL, albumArtURL, artistName, songcode );
			} else {
				if( !response ){
					/*$.ajax({
						type: "POST",
						url: "getdata/mail_warning.php"
					});*/
				} else {
					console.log( response );
				}
			}
		}
	);

	//console.log(myID);
	
};

function postToDatabase( tuneName, tuneURL, albumArtURL, artistName, songcode ) {
	var facebookid = myID;
	var outdata = '{"action":"confess","songcode":"'+songcode+'","facebookid":"'+facebookid+'","tuneName":"'+tuneName+'","artistName":"'+artistName+'","albumArtURL":"'+albumArtURL+'"}';
	$.ajax({
		type: "POST",
		url: "getdata/back.php",
		data: $.parseJSON( outdata ),
		dataType: 'json',
		success: function(msg){
			if(msg.error.length > 0) {
				console.log(msg.error);
				return;
			}else {
				var messageString = tuneName + ',' + tuneURL + ',' + albumArtURL + ',' + artistName + ',' + songcode;
				$('<form/>',{ action:'thanks.php', method: 'POST'}).append($('<input/>',{type:'hidden',name: 'message', value: messageString})).appendTo('body').submit(); }
			}
	});
}

function postLinkToFacebook( linkType, userID, userName, albumArtURL, tuneName, artistName, tuneURL ) {
	var message;
	var imgSrc = 'http://www.actionvillain.se/clients/ddb/bilmusikbikten/ui/images/VW_logga_Das_Auto.gif';
	var propertiesObject = {};
	
	switch( linkType ){
		case 'userPage':
			message = copy.postConfessionToFBUserMessageStart + userName + copy.postConfessionToFBUserMessageEnd;
			break;
		case 'spotifySong':
			if( userName != 'undefined' ){
				message = copy.postConfessionToFBSongMessageUserStart + userName + copy.postConfessionToFBSongMessageUserEnd;
			} else {
				message = copy.postConfessionToFBSongMessage;
			}
			imgSrc = albumArtURL;
			if( language == 'en' ) {
				propertiesObject = { 'Song' : { 'text': tuneName, 'href': tuneURL}, 'Artist': { 'text': artistName, 'href': tuneURL} };
			} else {
				propertiesObject = { 'Låt' : { 'text': tuneName, 'href': tuneURL}, 'Artist': { 'text': artistName, 'href': tuneURL} };
			}
			break;
		case 'siteLink':
			message = '';
			break;
		case 'myPage':
			message = copy.postConfessionToFBMyMessage;
			break;
	}
	
	var linkURL = language == 'en' ? 'http://www.drivingtrackconfessions.com' : 'http://www.bilmusikbikten.se';
	if( linkType != 'spotifySong' && linkType != 'siteLink' ){
		linkURL += '/userpage.php?userID=' + userID;
	}
	
	var attachment = { 	'name': copy.postConfessionToFBSiteLink, 
						'href': linkURL,
						'description': copy.postConfessionToFBDescription,
						'properties': propertiesObject, 
						'media': [{ 'type': 'image', 'src': imgSrc, 'href': linkURL}] }; 
		
	FB.ui( { method: 'stream.publish', message: message, attachment: attachment },
		function( response ) {
		if (response && response.post_id) {
		       
			} else {
		       // TODO Fixa ett felmeddelande i den lilla bubblan. Typ "Ett fel uppstod. Försök igen".
		     }
		}
	);
};
