<!-- alert("Facebook conn.js installed"); -->
// JavaScript Document
var FB_API_KEY 			= '7e05a5ebc1bf46162e24c3a34d386b95';
var rel_swf_dir 		=  ""; 
var facebook_id 		= "";
var colgate_screen_name = "";
var colgate_fName		= "";
var facebook_email		= "";
var facebook_fName      = "";
var facebook_lName		= "";
var overlayContainerID 	= "overlayContainer";
var overlayContentID   	= "overlayContentSWFObj";
var profilePhotoID 		= "profilePicWrapper";
var profileLoggedInName = "profileLoggedInName";

var overlayContainer    = null;
var overlayContent		= null;
var parentAppName		= "alternateContent";
var defaultHeight		= 650;
var defaultWidth		= 650;
var contentWidth  		= 0;
var contentHeight 		= 0;
var redirectFlag = false;


//legacy carryover from old iFrame implementation
var closer              = "";
/**
* FB Connect client
**/

function requireFacebookSession()
{
	FB.Connect.requireSession(fb_sessionCallBack);	
}

function fb_sessionCallBack()
{
	//sendLinkEvent('','smile/fclogin'); 
	var myUserInfo = getCurrentUserInfo();
	//alert("fb_sessionCallBack() you just logged in to facebook");
	//showExtendedPermissionsDialog();
	return;
}

function requireColgateSession()
{
	//alert("requireFacebookSession() FB fNAme = " + facebook_fName);
	disconnect = true;
	var poststr = "alias=" + facebook_id + "&screenname=" + facebook_fName + "&email=" +facebook_email + "&type=facebook&v=true";
	makePOSTRequest('/ColgateSmile/connect.srv', poststr, onLogin);
}

function loadFBScript(xd_receiver) {
	
	// FB.Bootstrap.requireFeatures(["XFBML", "Api", "Connect"], function() { 
				// FB.Facebook.init(FB_API_KEY, xd_receiver, {
					// "ifUserConnected": onUserConnected,
					// "ifUserNotConnected":onUserNotConnected}); 
				
			// });
	FB.Bootstrap.requireFeatures(["Connect"], function() { 
		FB.Facebook.init(FB_API_KEY, xd_receiver, {
			"ifUserConnected": onUserConnected,
			"ifUserNotConnected":onUserNotConnected}); 
		
	});
}
function onUserConnected(uid) {
	
	var profilePhotoWrapper = document.getElementById(profilePhotoID);
	if(profilePhotoWrapper) profilePhotoWrapper.style.display = "block";
	if(!facebook_id ) {
		facebook_id  = waitForSession();
	}

	requireFacebookSession();
}

function getFBUserName()
{
	var fbNAme = facebook_fName + " " + facebook_lName;
	return facebook_fName + " " + facebook_lName;
}

function getFBUserEmail()
{
	return facebook_email;
}

function getFBUserID()
{
	return facebook_id;
}

function onUserNotConnected() {

	if(document.getElementById(profilePhotoID)) {
		document.getElementById(profilePhotoID).style.display = "none";
	}
}

function sendNotifications(friend_ids, notification_text) {
	FB.Facebook.apiClient.notifications_send(friend_ids, notification_text, 
									function(result, exception) {
										if(result) {
											document[parentAppName].notifcationsSent(result);
										}
										else if(exception) {
											alert("Exception: " + exception.message);
										}
									});
}

function getCurrentUserInfo() {
	var resp = {};
	FB.Facebook.apiClient.users_getInfo([facebook_id], ['first_name', 'last_name', 'pic_square', 'proxied_email'],
									function(result, exception) {
									
										if(result) {
											resp = result[0] ? result[0]:result["0"] ? result["0"]:null;
											facebook_email = resp.proxied_email;
											requireColgateSession();
											showExtendedPermissionsDialog();
											try{
												document[parentAppName].onFacebookUserInfo(resp);
											}
											catch(e) {
												
											}
										}
										else if(exception) {
											resp = exception;
										}
										
									});

	return resp;
}

function waitForSession() {
	var uid = "";
	FB.Facebook.get_sessionState().waitUntilReady(function()  {
		uid = FB.Connect.get_loggedInUser();
		var uids 	= new Array();
		var fields 	= new Array();
		uids[0] 	= uid;
		fields[0] 	= 'pic_square';
		fields[1] 	= 'proxied_email';
		fields[2] 	= 'first_name';
		fields[3] 	= 'last_name';

		FB.Facebook.apiClient.users_getInfo(uids, fields, function(result, ex) {
			var pic_url = result[0].pic_square;
			facebook_email = result[0].proxied_email;
			facebook_fName = result[0].first_name;
			facebook_lName = result[0].last_name;
			var inner = '<img src="' + pic_url + '" width="30" height="30"/>';
			document.getElementById(profileLoggedInName).innerHTML = "&nbsp;Welcome, " + facebook_fName;
			updateOverlay();
			updateParentApp();
			FB.XFBML.Host.parseDomTree();

		});
	});
	
	
	
	return uid;
}

/**
*  eCard / flex window communications via ExternalInterface
**/


function onLogout()
{
	if(FB)
	{
		FB.Connect.logout(function(){onFBLogout(true)})
	}
	else
	{
	
		if(document.LogOut)
		{
		document.LogOut.locationURL.value=location.href;
		document.LogOut.submit();
		}
	}
}

function onFBLogout(bool)
{
	var loginWrapper = document.getElementById("loginWrapper");
	var loggedInState = document.getElementById("loggedInState");
	if(loginWrapper)loginWrapper.style.display = "";
	if(loggedInState)loggedInState.style.display = "none";
	if(document.LogOut)
	{
		document.LogOut.locationURL.value=location.href;
		document.LogOut.submit();
	}
}

function onLogin()
{
	var loginWrapper = document.getElementById("loginWrapper");
	var loggedInState = document.getElementById("loggedInState");
	if(loginWrapper)loginWrapper.style.display = "none";
	if(loggedInState)loggedInState.style.display = "";
	
	//selective redirect if loggin on from the registration page
	//need to send user to hompage
	//registration.srv
	var myURL = window.location.href;
	isOnRegister = myURL.indexOf("registration.srv");
	//alert("Is on Registration page = " +isOnRegister);
	if(isOnRegister > 0) 
	{
		if(redirectFlag == true) window.location = "/ColgateSmile/home.srv";
	}
}

function updateOverlay() {
	var parentApp = document.getElementById(overlayContentID);
	if(parentApp) {
		try{
			parentApp.update();
		}
		catch(e) {
			//alert("JS updateOverlay() error :" + e.message);
		}
	}
}

function updateParentApp() {
	var parentApp = document.getElementById(overlayContentID);
	if(parentApp){
		try {
			parentApp.updateStatus();
		}
		catch(e) {
			//alert("JS updateParentApp() error : " + e.message);	
		}
	}
}

/**
* the "pop-up" / overlay related routines
**/
function createOverlay() {

	if(!overlayContainer) {
		
		var b = document.getElementById("popOverHolder");
		
		if(!b) {
			b = document.body ? document.body:document.getElementsByTagName("body")[0];	
		}
		
		overlayContainer    = document.createElement("div");
		overlayContainer.id = overlayContainerID;
		overlayContainer.style.position = "absolute";
		b.appendChild(overlayContainer);
		
		if(!overlayContent ) {
			overlayContent 	  = document.createElement("div");
			overlayContent.setAttribute("style","z-index: 2001;");
			overlayContent.id = overlayContentID;
			document.getElementById(overlayContainerID).appendChild(overlayContent);
		}
	}
}

function showPopupBox(file_url, w, h) {
	if(!w) {w = defaultWidth;}
	if(!h)  {h = defaultHeight;}
	contentWidth  = w;
	contentHeight = h;
	createOverlay();
	centerOverlay();	
	frostWindow(false);
	
	embedSWF(rel_swf_dir + file_url, w.toString(), h.toString());
	overlayContent.style.display = "block";	
	overlayContainer.style.display = "block";	
}

function hidePopupBox() {
try
{
	frostWindow(true);
 	overlayContent.style.display   = "none";
	overlayContainer.style.display = "none";
 	overlayContent.innerHTML 	   = "";
 	overlayContainer.innerHTML 	   = "";
	var ecardWindow = document.getElementById("alternateContent");
	if(ecardWindow)
	{
		ecardWindow.focus();
	}
	
cancelSWFPhotoUpload();
}catch(e){}
}

function frostWindow(className) {
	//alert("frost");
	
	try
	{
		var flashContent = document.getElementById("flashcontent");
		var elementClass = flashContent.getAttribute("class");
		//alert("flashContent " + flashContent);
		elementClass = className ? "defrost" : "frost";
		//var class_name 	= defrost ? "defrost" : "frost";
		flashContent.className = elementClass;
	}
	catch(e){}
}

function embedSWF(file_url, w, h) { 
	var so = new SWFObject(file_url, overlayContentID, w, h, "9.0.0", "#ffffff"); 
	so.addVariable("api_key", FB_API_KEY);
	/*if(colgate_id != "")so.addVariable("cid", colgate_id);*/
	so.addVariable("as_swf_name", overlayContentID);
	//these are only used in the 'why register or login pop over'
	//so.addVariable("registerPath", "http://v73.colgate.com/ColgateSmile/registration.srv?nav=true");
	so.addVariable("registerPath", "registration.srv?nav=true");
	so.addVariable("loginScriptURL", "connect/login.srv");
	so.addVariable("loginFunction", "doFlexLogin");
	so.addVariable("fbFunction", "whyLoginFBLogin");
	so.addVariable("closeFunction", "toggle_whyLoginDisplayOff");
	
	so.setAttribute("name", overlayContentID);
	so.addParam("wmode", "transparent");
	so.addParam('align', 'left');
	so.addParam('salign', 'lt');
	so.write(overlayContainerID);
}

function centerOverlay() {

	var windowWidth  = 1024;
	var windowHeight = 650;

	if(typeof( window.innerWidth ) == 'number'){
			windowWidth      = window.innerWidth;
			windowHeight     = window.innerHeight;
	}
	else if(document.documentElement && 
			(document.documentElement.clientWidth || document.documentElement.clientHeight)) {
			windowWidth      = document.documentElement.clientWidth;
			windowHeight     = document.documentElement.clientHeight;
	}
	else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
			windowWidth      = document.body.clientWidth;
			windowHeight     = document.body.clientHeight;
	}
	var x = windowWidth/2  - contentWidth/2;
	var y = windowHeight/2 - contentHeight/2;
	overlayContainer.style.left = x + "px";
	overlayContainer.style.top  = "200px";
}

function refreshSWFPhotos()
{
    closer++;
    document.getElementById("alternateContent").SetVariable("uploadComplete", closer);
	hidePopupBox()
}

function cancelSWFPhotoUpload()
{
    closer++;
    document.getElementById("alternateContent").SetVariable("uploadCancelled", closer);
}

//send to a friend functions
function addFriendsComplete($data)
{
	//alert("addFriendsComplete " + $data);
	document.getElementById("alternateContent").SetVariable("addFriendsComplete", $data);
}

function addFBFriendsComplete($data)
{
	document.getElementById("alternateContent").SetVariable("addFBFriendsComplete", $data);
	if(facebook_id != "")document.getElementById("alternateContent").SetVariable("fb_uid",facebook_id);

	//document.getElementById("alternateContent").SetVariable("addFriendsComplete", $data);
	
	//
	
}

function userLoggedInToColgate(cid, colgateFName) {
	onLogin();
	//alert("userLoggedInToColgate()  = " + colgateFName);
	if(colgateFName)
	{
		colgate_screen_name = colgateFName;
		var loggedInNameElement = document.getElementById("profileLoggedInName");
		loggedInNameElement.innerHTML = "Welcome " + colgate_screen_name;
		//alert("Colgate Screen name = " + colgate_screen_name);
	}
	
	var parentApp = document.getElementById(parentAppName);
	if(parentApp){
	
			parentApp.userLoggedInToColgate(cid);
			//parentApp.onSmilesIDUpdated(cid);
	}
	
}

function onFBLinkedToSmiles()
{
	sendLinkEvent('','smile/fclink'); 
	if(document.getElementById("alternateContent"))
	{
		//alert("  >onFBLinkedToSmiles fb_uid : " + facebook_id);
		document.getElementById("alternateContent").SetVariable("fb_uid",facebook_id);
	}
}

function addFriendsCancelled()
{
	 document.getElementById("alternateContent").SetVariable("addFriendsCancelled", closer);
}

function showPhotoImportBox()
{
	sendLinkEvent('','ecard/build/uploadphoto'); 
	hidePopupBox();
	showPopupBox("/ColgateSmile/US/EN/flash/fb_ImageImporter.swf", 560, 490);
}

function showFriendsImportBox()
{
	hidePopupBox();
	showPopupBox("/ColgateSmile/US/EN/flash/fb_AddFriends.swf", 600, 620);
}

function doFlexLogin()
{
	//alert("do Flex Login");
	hidePopupBox();
	showPopupBox("/ColgateSmile/US/EN/flash/fb_LogInWindow.swf", 560, 400);
}

function toggle_whyLoginDisplay() {     
  //alert("why login display");      
  hidePopupBox();
  showPopupBox("/ColgateSmile/US/EN/flash/WhyLoginForm.swf", 612, 300);
}

function toggle_whyLoginDisplayOff() {                
  hidePopupBox();
}

function whyLoginFBLogin()
{
	
	hidePopupBox();
	requireFacebookSession()
}


function showFB_FeedDialogue()
{
	var data = {
	'images' : [{src: 'http://photos-g.ak.fbcdn.net/photos-ak-sf2p/v43/198/151019860518/app_1_151019860518_6649.gif', href:'http://www.colgate.com/ColgateSmile/ecard/intro.srv'}]
	};
	FB.Connect.showFeedDialog(151044920518, data);
}

function showExtendedPermissionsDialog()
{
	//alert("extended permissions here.");
	FB.Facebook.apiClient.users_hasAppPermission("email",
        function(result){
            if ((result == 0) || (result == null)){
                /* render the permission dialog */
            	FB.Connect.showPermissionDialog("email");
            }else{
                /* Perform action when no prompt for extended permission*/
            }
        }
	);
}

//AJAX stuff

var http_request = false;
var disconnect = false;
   
function makePOSTRequest(url, parameters, callbackFunction) {
	//alert("ajax post!" + parameters);
  http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
	 http_request = new XMLHttpRequest();
	 if (http_request.overrideMimeType) {
		// set type accordingly to anticipated content type
		//http_request.overrideMimeType('text/xml');
		http_request.overrideMimeType('text/html');
	 }
  } else if (window.ActiveXObject) { // IE
	 try {
		http_request = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
		try {
		   http_request = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {}
	 }
  }
  if (!http_request) {
	 alert('Cannot create XMLHTTP instance');
	 return false;
  }
  
  http_request.onreadystatechange = callbackFunction;
  http_request.open('POST', url, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
}

function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
          
            result = http_request.responseText;
           //alert("Disconnect response = " + http_request.responseText);   
		   if(disconnect)
		   {
			  disconnect = false;
			  onLogout();
		   }
         } else {
            alert('There was a problem with the request. Source [conn.js alertContent()]');
         }
      }
   }
   
function doDisconnect()
{
	disconnect = true;
	if(facebook_id == "" || facebook_id == null)
	{
		alert("Notice: You must be logged into Facebook from within the Colgate Smile site to disconnect!\nPlease login to continue with this operation.");
	}
	else
	{	
		var poststr = "alias=" + facebook_id + "&type=facebook";
		makePOSTRequest('/ColgateSmile/disconnect.srv', poststr, alertContents);
	}
}

function pageTop() {
	try
	{
		window.location.href="#swftop"
	}catch(e){}
}

function updateRedirectFlag(bool)
{
	redirectFlag = bool;
	//alert("redirectFlag: " + redirectFlag);
	return;
}
