//--------------------------------------------------------------------------------------------------------------------------	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_GETUSERFRIENDSRESULT = 'fbGetUserFriendsResult';
var CB_PUBLISHTOWALLRESULT = 'publishToWallResult';
var CB_BATCHPUBLISHTOWALLRESULT = 'batchpublishToWallResult';
var CB_STREAMPUBLISHRESULT = 'streamPublishResult';
var CB_SHARERESULT = 'shareResult';
var CB_SETSTATUS = 'setStatusResult';
//FACEBOOK APPLICATION RELATED VARS
var _apikey = "c1b2646b61807f24145ecdde3443380b";
var _perms = {perms:'publish_stream'};	//null OR fe {perms:'read_stream,publish_stream,offline_access'}
var _facebook_share_url = "http://www.standaard.be/actuaquiz";
var _auto_fetch_friends_onLogin = true;
var _auto_fetch_userinfo_onLogin = true;
//FLASH APPLICATION RELATED VARS
var _swfname = "aq_flash_contents_v1";				//DIV ID where the SWF will be placed in
var _swfURL = "preloader.swf";
var _flashwidth = 938;
var _flashheight = 760;
var _minflashversion = '10.0.0';
//var _flashvars = {regl:'reglement.html', testquizvandatum:'20100805'};
var _flashvars = {regl:'reglement.html'};
var _params = {'allowScriptAccess':'always'};
var _attributes = {};
//TWITTER RELATED VARS
var _twitter_share_status = "Speel mee met De Standaard ActuaQuiz op http://www.standaard.be/actuaquiz";
//--------------------------------------------------------------------------------------------------------------------------	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:_apikey});
}
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
		FB.api({
				method: 'fql.query',
				query: 'SELECT id, name, pic_square FROM profile WHERE id=' + FB.getSession().uid
			},
			function(response){
				if(_auto_fetch_friends_onLogin){
					FB.api('me/friends?fields=id,name,picture,first_name,last_name', function(friendsResponse) {
						//flashCallBack(CB_LOGINSUCCES, [response[0], friendsResponse]);
						if(_auto_fetch_userinfo_onLogin){
							FB.api({
								method: 'fql.query',
								query: 'SELECT first_name, last_name, sex FROM user WHERE uid=' + FB.getSession().uid
							},function(userinfoResponse){
								flashCallBack(CB_LOGINSUCCES, [response[0], friendsResponse, userinfoResponse]);
							});
						}else{
							flashCallBack(CB_LOGINSUCCES, [response[0], friendsResponse]);
						}
					});
				}else{
					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);
	});
}
//--------------------------------------	POST TO USER WALL
function testBatch(){
	//var profileids_arr = ["569281747", "569281747"];
	//var profileids_arr = ["1", "2", "3", "4", "5", "6"];
	//batchPublishToWall(profileids_arr, 'test', 'http://www.sevenedge.be/logo.jpg','http://www.sevenedge.be/test/eenurl', 'eennaam', 'eencaption', 'een description');
}
function batchPublishToWall(profileids_arr,message,picture,link,name,caption,description,source,fails){
	if(fails == undefined) fails = 0;
	//
	if(profileids_arr.length == 0){
		//all published
		var flashresponse = "ok";
		if(fails > 0) flashresponse = "error_" + fails;
		flashCallBack(CB_BATCHPUBLISHTOWALLRESULT, flashresponse);
	}else{
		//publish next
		var profileid = profileids_arr[profileids_arr.length - 1];
		profileids_arr = profileids_arr.slice(0, profileids_arr.length - 1);
		//
		publishToWall(profileid,message,picture,link,name,caption,description,source,function(response){
			if (!response || response.error) {
				fails++;
				batchPublishToWall(profileids_arr,message,picture,link,name,caption,description,source,fails);
			} else {
				batchPublishToWall(profileids_arr,message,picture,link,name,caption,description,source,fails);
			}
		});
	}
}
function publishToWall(profileid,message,picture,link,name,caption,description,source,callback){
	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;
	//
	if(callback == undefined){
		callback = function(response){
			/*if (!response || response.error) {
				 alert('Error occured');
			} else {
				 alert('Post ID: ' + response.id);
			}*/
			flashCallBack(CB_PUBLISHTOWALLRESULT, response);
		}
	}
	//
	FB.api('/' + profileid + '/feed', 'post', ptwArgs, callback);
}
//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);
}
//--------------------------------------------------------------------------------------------------------------------------	TWITTER LOGIC
function openPopup(url){
	newwindow = window.open(url,'Actuaquiz','resizable=0,height=468,width=770,scrollbars=no,toolbar=no,location=no,status=no');
	if (window.focus) newwindow.focus();
	return false;
}
//facebook simple sharing
function simpleShareFacebook(){
	newwindow = window.open('http://www.facebook.com/share.php?u=' + _facebook_share_url,'Facebook','resizable=1,height=650,width=1020,toolbar=no,scrollbars=yes,location=no,status=no');
	if(window.focus) newwindow.focus();
}
//twitter simple sharing
function simpleShareTwitter(){
	newwindow = window.open('http://twitter.com/home?status=' + _twitter_share_status,'Twitter','resizable=1,height=650,width=1020,toolbar=no,scrollbars=yes,location=no,status=no');
	if(window.focus) newwindow.focus();
}
