﻿mTimer=0;
function FB_init() { 
// Create an ApiClient object, passing app's API key and site relative URL to xd_receiver.htm
	FB.Facebook.init(my_api_key, channel_path); 
	api = FB.Facebook.apiClient; 
	// require user to login 
//	api.FB.Connect.requireSession(function(exception) { 
//	});   //END [api.FB.Connect.requireSession]
}  //END [init]

//Function for initializating the page.
function startChat(sDisplayDIV) {
	chat_div = document.getElementById(sDisplayDIV);
	sendReq = getXmlHttpRequestObject();
	receiveReq = getXmlHttpRequestObject();
	lastMessageID = 0;
	chatNum=7;
	
//Initialize FB
	var my_api_key = '0ddab72503ac1e380c0ed0def2732820';  //'MY API KEY'; 
	var channel_path = "xd_receiver.htm";
	FB.init(my_api_key, channel_path);  //"64f423ffcaf0268344a9edaa59aeef8a"
	FB.Bootstrap.requireFeatures(["Connect","XFBML"], function() {
		FB.Facebook.init(my_api_key, channel_path); 
	//	FB.Connect.showPermissionDialog("email"); 
	});  //END [FB.Bootstrap.requireFeatures]

	getChatText();	//Start Recieving Tweets
}  //ENDFUNCTION

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.  Consider upgrading your browser.';
	}
}  //ENDFUNCTION

//Gets the current messages from the server
function getChatText() {
	if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
		receiveReq.open("GET", 'Functions/getChat.php?chat='+chatNum+'&lastMsgID=' + lastMessageID, true);
		receiveReq.onreadystatechange = handleReceiveChat; 
		receiveReq.send(null);
	}			
}  //ENDFUNCTION

//Add a message to the chat server.  This is called from the Index page once user submits a Tweet.  
function sendChatText(UserID, chatNum) {
	if(document.getElementById('txt_message').value == '') {
		alert("You have not entered a message");
		return;
	}
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", 'Functions/getChat.php?chat='+chatNum+'&lastMsgID=' + lastMessageID, true);  //GET params included in URL
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = handleSendChat; 
		var AJAXParams = 'message=' + document.getElementById('txt_message').value;
		AJAXParams += '&name='+UserID;
		AJAXParams += '&chat='+chatNum;
		sendReq.send(AJAXParams);  //POST params included in AJAXParams
		document.getElementById('txt_message').value = '';
	}							
}  //ENDFUNCTION

//When our message has been sent, update our page.
function handleSendChat() {
	//Clear out the existing timer so we don't have 
	//multiple timer instances running.
	clearInterval(mTimer);
	getChatText();
} //ENDFUNCTION

function handleReceiveChat() {
	if (receiveReq.readyState == 4) {  //IF [AJAX Response Received == YES]
		//Get the AJAX response and eval it to turn it into usable object. 
		//(Since JSON value is passed as a string it must be wrapped in parens).
		var response = eval("(" + receiveReq.responseText + ")");
		OTweet='';

		rtnMsg = response.messages.message;  //array in case of multiple Tweets
		for( var i=0; i < rtnMsg.length; i++ ) {  //FOR [loop through all messages]
			if ( rtnMsg[i].PostToOH == 'Y' ) {  //IF [Post to www.oheller.net only if requested]
				chat_div.innerHTML += '<span style="color:'+rtnMsg[i].userStyle+';font-family: Verdana;font-size: x-small"><b><em>'+rtnMsg[i].user+ ':</em></b>&nbsp;';
				chat_div.innerHTML += OTweet='<span style="color:'+rtnMsg[i].userStyle+';font-family: Verdana;font-size: x-small">'+rtnMsg[i].text + '&nbsp;</span>';
				chat_div.innerHTML += '<span style="color:#606060;font-family: Verdana; font-size:6pt">' + rtnMsg[i].date + '</span><br/>';
				chat_div.scrollTop = chat_div.scrollHeight;
				lastMessageID = rtnMsg[i].id;
				OTweet=rtnMsg[i].text;
				pronoun=rtnMsg[i].pronoun;
				source=rtnMsg[i].source;
				finalUID = rtnMsg[i].UID; 
			}  //ENDIF [Post to www.oheller.net only if requested]
		}  //ENDFOR [loop through all messages]
		mTimer = setTimeout('getChatText();',2000); //Refresh our chat in 2 seconds
		
//Post Tweet to FB only if this is the final Tweet
// (Still need to add logic to get connected to FB)
// User must be logged in to see Tweets
		var UID=getCookieValue('UID');
//Determine whether to post the Tweet from OH to FB or not
//alert('UID='+UID+', finalUID='+finalUID); //debug
		if (lastMessageID>initialFinalTweet && OTweet != '' && source != 'FB' && UID==finalUID) {  //IF [New Tweet from OH & Tweeter is the logged in user]

			FB_RequireFeatures(["Connect","XFBML"], function() {
				var my_api_key = '0ddab72503ac1e380c0ed0def2732820';  //'MY API KEY'; 
				var channel_path = "xd_receiver.htm";
				FB.Facebook.init(my_api_key, channel_path); 
				FB.Facebook.get_sessionState().waitUntilReady(function() {
					var fbUIDs = {'Pete':503072158, 'Tigger':1411732284, 'Greg':1093953733, 'Barb':682052802, 'Kami':1075445757};
					var tweetBundle='65195328397'; // //pronoun in heading, bold body //replaces '60063323397'
					var template_data = {"OTweet": OTweet, "pronoun": pronoun};
					facebook_publish_feed_story(tweetBundle, template_data);					
				});  //END [FB.Facebook.get_sessionState().waitUntilReady] 
			});  //END [FB_RequireFeatures]

		}  // ENDIF [New Tweet from OH and Tweeter is the logged in user]
	}  //ENDIF [AJAX Response Received == YES]
}  //ENDFUNCTION [handleReceiveChat]

//This functions handles when the user presses enter.  Instead of submitting the form, 
//send a new message to the server and return false.
function blockSubmit() {
	sendChatText();
	return false;
}

//This cleans out the database so we can start a new chat session.
function resetChat() {
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", 'Functions/getChat.php?chat='+chatNum+'&lastMsgID=' + lastMessageID, true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = handleResetChat;
		var AJAXParams = 'action=reset';
		sendReq.send(AJAXParams);
		document.getElementById('txt_message').value = '';
	}							
}  //ENDFUNCTION

//This function handles the response after the page has been refreshed.
function handleResetChat() {
	document.getElementById('OTwitterBox').innerHTML = '';
	getChatText();
}  //ENDFUNCTION