var serverAppDir = '/fb/';	// Ändern für Login in GT

var serverImageUrl;
var globalAppId;
var globalServerUrl;
var globalAppLink;

//Achtung damit dies funktioniert muss auf der HTML Seite folgendes Element eingebettet sein: <div id="fb-root"></div>
function initPlatform(appId, serverUrl, platformAppLink) {
	
	serverImageUrl = serverUrl + '/res/';
	
	serverImageUrl = serverImageUrl.replace('/fb/', '/fb/');
	
    window.fbAsyncInit = function() {
    	FB.init({
 		     appId  : appId,
 		     status : true, // check login status
 		     cookie : true, // enable cookies to allow the server to access the session
 		     xfbml  : true,  // parse XFBML
 		     oauth : true,
 		     channelUrl  : serverUrl + '/html/channel.html'  // custom channel
    	});
    	platformInitialized = true;
    	globalAppId = appId;
    	globalServerUrl = serverUrl;
    	globalAppLink = platformAppLink;
    	FB.Canvas.setAutoGrow(true);
    	checkIsLoggedIn();
	};
	(function() {
	     var e = document.createElement('script');
	     e.type = 'text/javascript';
	     e.src = document.location.protocol +
	         '//connect.facebook.net/en_US/all.js';
	     e.async = true;
	     document.getElementById('fb-root').appendChild(e);
	     	     
	}());
	
//	$("#appContainer").ajaxStop(function() {
//		fixFacebookHiddenIFrameBug();
//	});
}

function reInit() {
	reInitPlatform(globalAppId, globalServerUrl);
}

function reInitPlatform(appId, serverUrl) {
    window.fbAsyncInit = function() {
    	FB.init({
 		     appId  : appId,
 		     status : true, // check login status
 		     cookie : true, // enable cookies to allow the server to access the session
 		     xfbml  : true,  // parse XFBML
 		     oauth : true,
 		     channelUrl  : serverUrl + '/html/channel.html'  // custom channel
    	});
    	
    	FB.Canvas.setAutoGrow();
    	checkIsLoggedIn();
	};
	(function() {
	     var e = document.createElement('script');
	     e.type = 'text/javascript';
	     e.src = document.location.protocol +
	         '//connect.facebook.net/en_US/all.js';
	     e.async = true;
	     document.getElementById('fb-root').appendChild(e);
	}());    
	
	
//	$("#appContainer").ajaxStop(function() {
//		fixFacebookHiddenIFrameBug();
//	});
}

function startPlatformTagParsing() {
	
	FB.XFBML.parse();
}

function publishToWall(platformAppLink, name, caption, description, postlinkWithoutBaseURL, image1WithoutBaseURL, image2WithoutBaseURL, image3WithoutBaseURL, image4WithoutBaseURL, callBackFunction, targetUser, properties) {
	scrollToTop();
	
	var completePostLink =  platformAppLink + "/" + postlinkWithoutBaseURL;
	
	
	 var completeImage1URL = '';
     if (image1WithoutBaseURL != null && image1WithoutBaseURL != '') {
         completeImage1URL = serverImageUrl + image1WithoutBaseURL;
     } 

     var completeImage2URL = ''; 
     if (image2WithoutBaseURL != null && image2WithoutBaseURL != '') { 
         completeImage2URL = serverImageUrl + image2WithoutBaseURL;                
     } 
     
     var completeImage3URL = '';
     if (image3WithoutBaseURL != null && image3WithoutBaseURL != '') { 
         completeImage3URL = serverImageUrl + image3WithoutBaseURL;                     
     } 
     
     var completeImage4URL = '';
     if (image4WithoutBaseURL != null && image4WithoutBaseURL != '') {
         completeImage4URL = serverImageUrl + image4WithoutBaseURL;                                         
     } 
	
    if(description==null || description == '') {
    	description = 'www.ghost-trappers.com';
    } 
    
    var mediaArray;
    
    if (completeImage2URL == '') {
    	mediaArray = [{ "type": "image", "src": completeImage1URL, "href": completePostLink}]; 	
    } else  if (completeImage3URL == '') {
    	mediaArray = [{ "type": "image", "src": completeImage1URL, "href": completePostLink}, 
    	              { "type": "image", "src": completeImage2URL, "href": completePostLink}]; 	
    } else if (completeImage4URL == '') {
    	mediaArray = [{ "type": "image", "src": completeImage1URL, "href": completePostLink}, 
    	              { "type": "image", "src": completeImage2URL, "href": completePostLink},
    	              { "type": "image", "src": completeImage3URL, "href": completePostLink}]; 	
    } else {
    	mediaArray = [{ "type": "image", "src": completeImage1URL, "href": completePostLink},
			          { "type": "image", "src": completeImage2URL, "href": completePostLink},
			          { "type": "image", "src": completeImage3URL, "href": completePostLink},
			          { "type": "image", "src": completeImage4URL, "href": completePostLink}];
    }
     
    if(window.platformInitialized) {
		FB.ui(
		  {
		    method: 'stream.publish',
		    attachment: {
		      name: name,
		      caption: caption,
		      description: (description),
		      href: completePostLink,
		      properties: properties,
	          'media': mediaArray
		    },
		    target_id: targetUser,
		    action_links: [
		      { text: 'Play Ghost Trappers', href: platformAppLink }
		    ]
		  },
		  callBackFunction
		);
    }
}

function testPostCB(post_id, exception){	
	if(post_id!=null && 'null'!=post_id) {
		alert("callback");
	}
}	

function checkIsLoggedIn() {
	FB.getLoginStatus(function(response) {
	  if (response.authResponse) {
	    // logged in and connected user, someone you know
		  $("#fblogin").hide();
	  } else {
	    // no user session available, someone you dont know
		  $("#fblogin").show();
	  }
	 });
}

// synchroner (blocking) check ob man eingelogt ist
// Achtung niemal zur Ladezeit ausfÃ¼hren liefert sonst undefined!
function isLoggedIn() {
	var session = FB.getSession();
	if(session != null) {
		return true;
	} else {
		return false;
	}
}

function login(uid, accessToken) {
	startAjaxQueue();
	
	$.manageAjax.add('ajaxQueue', { 
		type:'POST',
		data: "action=loginConnect&uid=" + uid + "&accessToken=" + accessToken + '&redirectParam=' + redirectParam,
		url: serverAppDir + '/social-network/facebook_direct_entry_point.php',
		success:function(json,textStatus) {
			var data = parseJson(json);
			if(data.status=='success') {
				window.location.href=serverAppDir + data.redirectUrl;
			} else {
				window.location.href=serverAppDir + "social-network/facebook_direct_entry_point.php?action=invalidAccessToken";
			}
		},
		error:function(XMLHttpRequest,textStatus,errorThrown){ 
			
			console.info('textStatus =' + textStatus);
			
		}
    });	
}

function connect() {
   	FB.login(function(response) {
   	  if (response.authResponse) {
   		login(response.authResponse.userID,  response.authResponse.accessToken);
   	  } else {
   	    // user cancelled login
   	  }
   	});
}

function logout(url) {
	
	FB.logout(function(response) {
		logoutOfApp(url);
	});
	
/*	if(isLoggedIn()) {
		FB.logout(function(response) {
			logoutOfApp(url);
		});
	} else {
		logoutOfApp(url);
	}
*/
}

function scrollToTop() {
	try {
		FB.Canvas.scrollTo(0,0);
        timer = setTimeout(function() {
        	try {
        		FB.Canvas.scrollTo(0,0);
        	} catch(e) {
        	}
        }, 200);   
	} catch(e) {
	}
}

function updateContentJsonXFBML(data) {
	processAfterUpdate();
	
	if(!isJsonDataProcessible(data)) {
		return;
	}	

	if(data.html != null) {
		var ele = document.getElementById("content");
		ele.innerHTML = data.html;
	}
	
	FB.XFBML.parse();
}

function updateContentWithXFBML(url, isScrollToTop){
		processBeforeUpdate();
	
		if(false==isLoggedIn()) {
			showMessage(msgLogin);
			return;
		}
	
    	startAjaxQueue();
    	    
    	$.manageAjax.add('ajaxQueue', { 
    		type:'GET',
    		url: url,
            dataType: "json",	    		
    		success:function(data,textStatus){updateContentJsonXFBML(data);if(isScrollToTop==true) {scrollToTop();} reInit();},
    		error:function(XMLHttpRequest,textStatus,errorThrown){}
        });
}


var callback = function(data) {
	if (data['order_id']) {
	writeback("Transaction Completed! </br></br>"
	+ "Data returned from Facebook: </br>"
	+ "<b>Order ID: </b>" + data['order_id'] + "</br>"
	+ "<b>Status: </b>" + data['status']);
	} else if (data['error_code']) {
	writeback("Transaction Failed! </br></br>"
	+ "Error message returned from Facebook:</br>"
	+ data['error_message']);
	} else {
	writeback("Transaction failed!");
	}
};
	
function writeback(str) {
	document.getElementById('output').innerHTML=str;
}

/*targetThirdPartyId wird von donate.js gesetzt*/
function placeOrder(offerId, appId, targetThirdPartyId) {

	 var order_info = { "title":'',
			 "description":'',
			 "price":'',
			 "image_url":'',
			 "product_url":'',
			 "application_id":appId,
			 "offer_id":offerId,
			 "data":targetThirdPartyId
			 };
	
	var obj = {
		method: 'pay',
		order_info: order_info,
		purchase_type: 'item'
	};
		FB.ui(obj, callback);
}


function forceCanvas(platformAppName) {

	top.location = 'http://apps.facebook.com/' + platformAppName + '/camp.php';

}

function forceConnect(globalServerUrl) {

	top.location = globalServerUrl + '/camp.php';	
}


function checkApplicationMode(appMode, platformAppName, globalServerUrl) {
	if (top.location == location && appMode == 'CANVAS') {
		// man befindet sich nicht im Facebook-Frame, aber laut Login ist es eine CANVAS anwendung
		forceCanvas(platformAppName);
	}
	if (top.location != location && appMode == 'CONNECT') {
		// man befindet sich im Facebook-Frame, aber laut Login ist man eine CONNECT ANWENDUNG
		//--> das Facebook Fenster verlassen
		forceConnect(globalServerUrl);
	}
}

