//--------------------------------------------------------------------------------------------------------------------------	CONST
//GENERAL CONST VARS
var DEBUGMODE = false;
//CALL BACK FUNCTION NAMES (register in flash to listen to response!)
var CB_LOGOUT = 'logout';
var CB_PERMISSIONSREQUIRED = 'permissionsRequired';
var CB_LOGINSUCCES = 'loginSucces';
var CB_GETUSERINFORMATION = 'fbGetUserInformation';
var CB_GETUSERFRIENDSRESULT = 'fbGetUserFriendsResult';
var CB_PUBLISHTOWALLRESULT = 'publishToWallResult';
var CB_STREAMPUBLISHRESULT = 'streamPublishResult';
var CB_GETUSERIMAGES = 'fbGetUserImages';
var CB_SHARERESULT = 'shareResult';
var CB_SETSTATUS = 'setStatusResult';
//FACEBOOK APPLICATION RELATED VARS
var _perms = {perms:'publish_stream,user_photos,user_birthday,user_relationships'};	//null OR fe {perms:'read_stream,publish_stream,offline_access'}
//FLASH APPLICATION RELATED VARS
var _swfname = "content";				//DIV ID where the SWF will be placed in
var _swfURL = "swf/Phase4_preloader.swf";
var _flashwidth = 976;
var _flashheight = 647;
var _minflashversion = '10.0.0';
var _flashvars = { load_prefix:'swf/'};
var _params = {'allowScriptAccess':'always'};
var _attributes = {};
//--------------------------------------------------------------------------------------------------------------------------	ARRAY INDEX OF FUNC
//
//		DO NOT REMOVE!!
//		
//--------------------------------------
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
//--------------------------------------
//--------------------------------------------------------------------------------------------------------------------------	INIT
window.fbAsyncInit = function(){
	fbinit();
	showswf();
}
//--------------------------------------------------------------------------------------------------------------------------	FLASH LOGIC
function showswf(){
	swfobject.embedSWF(_swfURL, _swfname, _flashwidth, _flashheight, _minflashversion, null, _flashvars, _params, _attributes);
}
function flashCallBack (func){
	log('flashCallBack:' + func + ' arguments: ' + arguments);
	//
	if(!document[_swfname]){
		//alert("SWF id '" + _swfname + "' not found! (swf not embedded / swf name not set / wrong id?)")
		return;
	}
	//
	if( arguments.length > 1 ){
		document[_swfname][func](Array.prototype.slice.call(arguments).slice(1)[0]);
	}else{
		document[_swfname][func]();
	}
}
//--------------------------------------------------------------------------------------------------------------------------	FACEBOOK LOGIC
//--------------------------------------	AUTHENTICATION
function fbinit(){
	FB.init({apiKey:'547843d596a2c916b159ec48222e71d2'});
}
function fblogin(){
	FB.getLoginStatus(getLoginStatusHandler);
}
//
function fblogout(){
	FB.logout(handleSessionResponse);
}
//
function fbdisconnect(){
	FB.api({method:'Auth.revokeAuthorization'}, handleSessionResponse);
}
//sessie response afhandelen
function handleSessionResponse(response){
	if (!response.session) {
		flashCallBack(CB_LOGOUT);
		return;
	}
	//
	var permsok = checkPermissions(response);
	if(!permsok){
		flashCallBack(CB_PERMISSIONSREQUIRED);
	}else{
		//user info
		//console.log(FB.getSession().uid);
		FB.api({
				method: 'fql.query',
				query: 'SELECT id, name, pic_square, pic_small, pic_big FROM profile WHERE id=' + FB.getSession().uid
			},
			function(response){
				flashCallBack(CB_LOGINSUCCES, response[0]);
			}
		);
	}
}
//
function getLoginStatusHandler(response){
	//check permissions
	var permsok = checkPermissions(response);
	//
	if (!response.session || !response.perms || !permsok){
		FB.login(handleSessionResponse, _perms);
	}else{
		handleSessionResponse(response);
	}
}
function checkPermissions(response){
	var permsok = true;
	if(_perms != null && response.perms != null){
		var perms_arr = _perms.perms.split(',');
		if(response.perms != ""){
			var rperms_arr = response.perms.split(',');
			for (i = 0; i < perms_arr.length; i++) {
				if(rperms_arr.indexOf(perms_arr[i]) == -1){
					permsok = false;
					break;
				}
			}
		}else{
			permsok = (perms_arr.length == 0);
		}
	}
	return permsok;
}
//--------------------------------------	GET USER FRIENDS
function fbGetUserFriends(){
	FB.api('me/friends?fields=id,name,picture', function(response) {
		flashCallBack(CB_GETUSERFRIENDSRESULT, response);
	});
}
//--------------------------------------	GET USER IMAGES
function fbgetuserimages(){
	FB.api({
		method: 'fql.query',
		//query: 'SELECT pid,src_small,src_big,src FROM photo WHERE aid IN ( SELECT aid FROM album WHERE owner = "' + FB.getSession().uid + '" ) ORDER BY created DESC LIMIT 1,10'
		query: 'SELECT pid,src_small,src_big,src FROM photo WHERE aid IN ( SELECT aid FROM album WHERE owner = "' + FB.getSession().uid + '" ) ORDER BY rand() LIMIT 10'
	},
		function(response){
			flashCallBack(CB_GETUSERIMAGES, response);
		}
	);
}
//--------------------------------------	GET USER INFORMATION
function fbgetuserinformation(){	
	FB.api('me/?fields=id,name,first_name,last_name,link,birthday,hometown,location,gender,relationship_status,significant_other', function(response) {
		flashCallBack(CB_GETUSERINFORMATION, response);
	});
}
//--------------------------------------	POST TO USER WALL
function publishToWall(profileid,message,picture,link,name,caption,description,source){
	var ptwArgs = {};
	if(message) ptwArgs.message = message;
	if(picture) ptwArgs.picture = picture;
	if(link) ptwArgs.link = link;
	if(name) ptwArgs.name = name;
	if(caption) ptwArgs.caption = caption;
	if(description) ptwArgs.description = description;
	if(source) ptwArgs.source = source;
	//
	FB.api('/' + profileid + '/feed', 'post', ptwArgs, function(response){
		/*if (!response || response.error) {
			 alert('Error occured');
		} else {
			 alert('Post ID: ' + response.id);
		}*/
		flashCallBack(CB_PUBLISHTOWALLRESULT, response);
	});
}
function fbpublish(image,description){
	FB.api('/me/feed','post',{message:'',caption:description,picture:image,link:'http://www.phase04.be',description:'Join me now before it&acute;s too late!',name:'PHASE 04'},function(response){
		flashCallBack('fbPublished', response);
	});
}
function fbpublishuid(uid,image,description){
	FB.api('/' + uid + '/feed','post',{message:'',caption:description,picture:image,link:'http://www.phase04.be',description:'Join me now before it&acute;s too late!',name:'PHASE 04'},function(response){
		flashCallBack('fbPublisheduid', response);
	});
}

//OLD WAY - POST TO WALL (with user input and comfirmation
//function streamPublish(message, name, caption, description, href, action_links, user_message_prompt){
	//var spArgs = {method:'stream.publish'};
	//if(message) spArgs.message = message;
	//if(name || caption || description || href){
		//var at = {};
		//if(name) at.name = name;
		//if(caption) at.caption = caption;
		//if(description) at.description = description;
		//if(href) at.href = href;
		//
		//spArgs.attachment = at;
	//}
	//if(action_links) spArgs.action_links = action_links;
	//if(user_message_prompt) spArgs.user_message_prompt = user_message_prompt;
	//
	//FB.ui(spArgs, function(response){flashCallBack(CB_STREAMPUBLISHRESULT, response);})
//}
//--------------------------------------	SHARE TO WALL (link)
function share(link, popup){
	var share = {
		method:'stream.share',
		u:link,
		popup:popup
	};
	//
	FB.ui(share, function(response){flashCallBack(CB_SHARERESULT, response);});
}
//--------------------------------------	SET USER STATUS
function setStatus(newstatus){
	FB.api({
		method:'status.set',
		status:newstatus
	}, function(response){flashCallBack(CB_SETSTATUS, response);});
}
//--------------------------------------	DEBUGGING - LOGGING
function log(msg){
	if(DEBUGMODE) console.log(msg);
}
