
/*
 * API key, this should be initialized before any another function in this file is called.
 */

var is_initialized = false;

var pageUrl = window.location.host;

var callback_URL = 'http://'+pageUrl+'/'; 


/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
function ensure_init(callback) {
  if(!window.application_id) {
    window.alert("application id is not set");
  }

  if(window.is_initialized) {
    callback();
  } else {
    window.fbAsyncInit = function() {
        FB.init({
          appId  : window.application_id,
          status : true, // check login status
          cookie : true, // enable cookies to allow the server to access the session
          xfbml  : true  // parse XFBML
        });

		FB.Event.subscribe('auth.logout', function(response) {
			window.location.reload();
        });
		window.is_initialized = true;
      };
	(function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
	if(callback != "donoting")
		callback();
  }
}

function checkpermissionEmail(perms){
	if(!perms){
		FB.Connect.logout(function() { logout_page(); });
	}
}


/*
 * "Session Ready" handler. This is called when the facebook
 * session becomes ready after the user clicks the "Facebook login" button.
 * In a more complex app, this could be used to do some in-page
 * replacements and avoid a full page refresh. For now, just
 * notify the server the user is logged in, and redirect to home.
 *
 * @param link_to_current_user  if the facebook session should be
 *                              linked to a currently logged in user, or used
 *                              to create a new account anyway
 */
function facebook_button_onclick() {
  
  ensure_init(function() {
			FB.login(function(response) {
			  if (response.session) {
				if (response.perms) {
				  createCookie("fb_session","1");
				  facebook_login_successfull();
				} else {
				  facebook_logout();
				}
			  } else {
				// user is not logged in
			  }
			}, {perms:'email'});

					   });
}

function fb_link_button_click(returnUrl) {
  
  ensure_init(function() {
			FB.login(function(response) {
			  if (response.session) {
				if (response.perms) {
				  createCookie("fb_session","1");
				  movetourl(returnUrl);
				} else {
				  facebook_logout();
				}
			  } else {
				// user is not logged in
			  }
			}, {perms:'email'});

					   });
}

function fan_page_permissions(){
  
  ensure_init(function() {
			FB.login(function(response) {
			  if (response.session) {
				  if (response.perms) {
				  	url = callback_URL + "/scripts/fan_page_3712.php?fanconnected=true";
				  	movetourl(url);
				  }
			  } else {
				// user is not logged in
			  }
			}, {perms:'manage_pages,publish_stream,offline_access'}/*{enable_profile_selector:true,perms:'publish_stream'}*/);

					   });
}

function church_mod_approval(church_id){
  
  ensure_init(function() {
			FB.login(function(response) {
			  if (response.session) {
				if (response.perms) {
				  createCookie("fb_session","1");
				  church_mod_approval_get(church_id);
				} else {
				  facebook_logout();
				}
			  } else {
				// user is not logged in
			  }
			}, {perms:'email'});

					   });
}

function church_mod_approval_get(church_id){
  
  url = callback_URL + "/member/invite/facebook.php?connected=true";
  url += "&c_group="+church_id;
  url += "&approval=1";
  movetourl(url);
}

function fb_invite_link_click(is_church_invite){
  
  ensure_init(function() {
			FB.login(function(response) {
			  if (response.session) {
				if (response.perms) {
				  createCookie("fb_session","1");
				  invite_redirect(is_church_invite);
				} else {
				  facebook_logout();
				}
			  } else {
				// user is not logged in
			  }
			}, {perms:'email'});

					   });
}

function invite_redirect(is_church_invite){
  
  url = callback_URL + "/member/invite/facebook.php?connected=true";
  if(is_church_invite != 0){
  	url += "&c_group="+is_church_invite;
  }
  movetourl(url);
}

function fb_invite_church_join_click(church_id){
  
  ensure_init(function() {
			FB.login(function(response) {
			  if (response.session) {
				if (response.perms) {
				  createCookie("fb_session","1");
				  invite_member_church_join_redirect(church_id);
				} else {
				  facebook_logout();
				}
			  } else {
				// user is not logged in
			  }
			}, {perms:'email'});

					   });
}

function invite_member_church_join_redirect(church_id){
  url = callback_URL + "/member/invite/facebook.php?connected=true";
  url += "&c_group="+church_id;
  url += "&join=1";
  movetourl(url);
}


function facebook_logout(){
	FB.logout(logout_page);
}


/*
 * Do a page refresh after login state changes.
 * This is the easiest but not the only way to pick up changes.
 * If you have a small amount of Facebook-specific content on a large page,
 * then you could change it in Javascript without refresh.
 */
function refresh_page() {
//  window.location = callback_URL+'member';
}
function movetourl(url){
  window.location = url;	
}

function facebook_login_successfull() {
  var current_url = window.location.href;
  if(current_url.indexOf('P=') > 0){  	 
	 current_url = decode64();
  } else{
	 current_url = 'member/myhome.php?connected=true'
  }
  current_url = callback_URL+current_url;
  movetourl(current_url);
}

function facebook_publish_stream(user_messages, attachments, actionLinks, user_message_prompts) {
	ensure_init(function() {
	  FB.ui(
	   {
		 method: 'stream.publish',
		 message: user_messages,
		 attachment: attachments,
		 action_links: actionLinks,
		 user_prompt_message: user_message_prompts
	   }
	 );
    });
}

function decode64() {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;
   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   
   var input = window.location.href;
   input = input.split('P=');
   input = input[1];

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}

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 = "";
	
	parts = pageUrl.split(".");
	domain_name = parts.length > 2 ? parts[(parts.length)-2]+'.'+parts[parts.length-1] : pageUrl;
	document.cookie = name+"="+value+expires+"; path=/;domain=."+domain_name;
}

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 null;
}

