/*
 * NOTES
 * webwidget bindings
 * 
 * IE 6/7 Bug: dojo.attr('elementId', 'value'); doesn't work in IE6/7 on form input tags, so instead of putting hidden values in an <input type="hidden"> tag, we must
 * put them inside a hidden <div> and access the data by dojo.byId('elementId').innerHTML.  Apparently this is fixed in the upcoming Dojo 1.4, so we can switch back to 
 * using the cleaner hidden form inputs to store data at that time.  See: http://trac.dojotoolkit.org/ticket/7355
 */

// bind clicks of initial orgs list
dojo.addOnLoad(function() {
	
	// do browser version check & ie warning if less than IE7
	if (dojo.isIE && dojo.isIE < 7) {
		// set browser version in warning message
		dojo.byId('browserVersion').innerHTML = dojo.isIE;
		
		// show modal dialog warning
		var dialogObj = dijit.byId('browserVersionWarning');
		dialogObj.show();
	} 
		
	bindLinksOrgList();
	bindBackButton();
	getSid();

	if (dojo.byId('directLinkDetail')) {
		// if we're on the org detail page, bind clicks on missions
		bindLinksOrgDetailMissions();
	} else if (dojo.byId('directLinkInstructions')) {
		// if we're on the mission page, bind clicks on steps
		bindLinksInstructionSteps();
		
		// set done URL to be equal to mission URL
		dojo.byId('doneUrl').innerHTML = dojo.byId('postUrl').innerHTML;
	}

});

// php session id (given global scope here)
var sid = '';

function getSid() {
	var sidString = dojo.byId('sid').innerHTML;
	if (sidString != '') {
		sid	= '?PHPSESSID=' + sidString;
	}
}

// devicetype that will be appended to all request URLs
var widgetDeviceType = 'webwidget';

// list of active connections.  use these arrays to track dojo.connect bindings so that we can insure that none are double-bound.
var connectionHandlers = { 
		bottomNavButtons: [], 
		orgList: [],
		orgDetailMissions: [],
		orgDetailUpdates: [],
		missionInstructionSteps: [],
		doneButton: [],
		completePage: []
};

// var to keep track of our click history used by the back button
var historyArray = [];

var prepareInstructionsPage = function() {
	// update the header bar
	dojo.style('widgetBranding', 'display', 'none'); 							// hide extras header
	dojo.byId('widgetHead').innerHTML = dojo.byId('orgName').innerHTML; 	// update widgetHead to contain org name
	dojo.style('widgetHead', 'display', ''); 	
};

//bind clicks on bottom nav
var bindBottomNavLinks = function() {

	// first disconnect any existing bindings
	dojo.forEach(connectionHandlers.bottomNavButtons, dojo.disconnect);
	
	// bind Discover button
	var buttonDiscover = dojo.byId('navDiscoverButton');
	if (buttonDiscover) {
		var newConnectionDiscover = dojo.connect(buttonDiscover, 'onclick', function(event) { 	
			
			event.preventDefault(); // disable link from executing
			event.stopPropagation();
			
			// set ajax vars
			var ajaxUrl			= '/orgs/profiles/mode/summaries/tags/webwidget/format/html/devicetype/' + widgetDeviceType; //v3
			var ajaxTarget		= 'widgetWindow';
			var ajaxCallback	= 'bindLinksOrgList';
			
			//debug
			//extrasLogger('clicked: ', event.target);
			
			// make ajax request
			loadData(ajaxUrl, ajaxTarget, ajaxCallback);
		});
		
		// store new connection in tracking array
		connectionHandlers.bottomNavButtons.push(newConnectionDiscover);
	}
	
//	// bind Following button
//	var buttonFollowing = dojo.byId('navFollowingButton');
//	if (buttonFollowing) {
//		var newConnectionFollowing = dojo.connect(buttonFollowing, 'onclick', function(event) { 
//			event.preventDefault(); // disable link from executing
//			event.stopPropagation();
//			
//			// set ajax vars
//			var ajaxUrl			= '/orgs/following/format/html/devicetype/' + widgetDeviceType;
//			var ajaxTarget		= 'widgetWindow';
//			var ajaxCallback	= 'bindLinksOrgList';
//			
//			//debug
//			//extrasLogger('clicked: ', event.target);
//			
//			// make ajax request
//			loadData(ajaxUrl, ajaxTarget, ajaxCallback);
//		});
//		
//		// store new connection in tracking array
//		connectionHandlers.bottomNavButtons.push(newConnectionFollowing);
//	}
//	
//	// bind Profile button
//	var buttonProfile = dojo.byId('navProfileButton');
//	if (buttonProfile) {
//		var newConnectionProfile = dojo.connect(buttonProfile, 'onclick', function(event) { 
//			event.preventDefault(); // disable link from executing
//			event.stopPropagation();
//			
//			// set ajax vars
//			var ajaxUrl			= '/prefs/display/format/html/devicetype/' + widgetDeviceType;
//			var ajaxTarget		= 'widgetWindow';
//			var ajaxCallback	= 'bindProfileForm';
//			
//			//debug
//			//extrasLogger('clicked: ', event.target);
//			
//			// make ajax request
//			loadData(ajaxUrl, ajaxTarget, ajaxCallback);
//		});
//		
//		// store new connection in tracking array
//		connectionHandlers.bottomNavButtons.push(newConnectionProfile);
//	}
	
	// bind About button
	var buttonAbout = dojo.byId('navAboutButton');
	if (buttonAbout) {
		var newConnectionAbout = dojo.connect(buttonAbout, 'onclick', function(event) { 
			event.preventDefault(); // disable link from executing
			event.stopPropagation();
			
			// set ajax vars
			var ajaxUrl			= '/about/display/format/html/devicetype/' + widgetDeviceType + '/' + sid;
			var ajaxTarget		= 'widgetWindow';
			var ajaxCallback	= 'bindBottomNavLinks';
			
			//debug
			//extrasLogger('clicked: ', event.target);
			
			// make ajax request
			loadData(ajaxUrl, ajaxTarget, ajaxCallback);
		});
		
		// store new connection in tracking array
		connectionHandlers.bottomNavButtons.push(newConnectionAbout);
	}
	
	// bind iPhone button
	var buttonIphone = dojo.byId('navIphoneButton');
	if (buttonIphone) {
		var newConnectionIphone = dojo.connect(buttonIphone, 'onclick', function(event) { 
			event.preventDefault(); // disable link from executing
			event.stopPropagation();
			
			// set ajax vars
			var ajaxUrl			= '/about/iphoneapp/format/html/devicetype/' + widgetDeviceType + '/' + sid;
			var ajaxTarget		= 'widgetWindow';
			var ajaxCallback	= 'bindBottomNavLinks';
			
			//debug
			//extrasLogger('clicked: ', event.target);
			
			// make ajax request
			loadData(ajaxUrl, ajaxTarget, ajaxCallback);
		});
		
		// store new connection in tracking array
		connectionHandlers.bottomNavButtons.push(newConnectionIphone);
	}
};

// bind clicks on orgs discover page - load org detail on click
var bindLinksOrgList = function() {
	
	resetHeader(); // hide forward/back, show extraordinaries header
	
	// first disconnect any existing bindings
	dojo.forEach(connectionHandlers.orgList, dojo.disconnect);
	
	dojo.query('#widgetWindow li.orgRow').forEach(function(n) {
		var newConnectionOrgs = dojo.connect(n, 'onclick', function(event) { 
			var theElementId 	= dojo.attr(n, 'id');
			var orgIdArray		= theElementId.split('_');
			var orgId			= orgIdArray[1];
			
			// set ajax vars
			var ajaxUrl			= '/orgs/detail/orgid/' + orgId + '/format/html/devicetype/' + widgetDeviceType + '/' + sid;
			var ajaxTarget		= 'widgetWindow';
			var ajaxCallback	= 'bindLinksOrgDetailMissions';
			
			//debug
			//extrasLogger('org id: ', orgId);
			//extrasLogger('clicked: ', event.target);
		
			// make ajax request
			loadData(ajaxUrl, ajaxTarget, ajaxCallback);
		});
		
		// store new connection in tracking array
		connectionHandlers.orgList.push(newConnectionOrgs);
	});

	bindBottomNavLinks();
};

//bind clicks on org detail page - load mission instructions on click
var bindLinksOrgDetailMissions = function() {

	if (dojo.byId('orgId')) {
		
		// get orgId
		var orgId = dojo.byId('orgId').innerHTML;
		
		// set orgId hidden input element so we can track it in layout/_webwidgetHeader.phtml
		dojo.byId('orgIdHeader').innerHTML = orgId;

		// update the header bar
		dojo.style('widgetBranding', 'display', 'none'); 							// hide extras header
		dojo.byId('widgetHead').innerHTML = dojo.byId('orgName').innerHTML; 	// update widgetHead to contain org name
		dojo.style('widgetHead', 'display', ''); 							// show widgetHead text
		
		// first disconnect any existing bindings
		dojo.forEach(connectionHandlers.orgDetailMissions, dojo.disconnect);
		
		// loop through each mission and bind clicks
		dojo.query('#widgetWindow li.mission').forEach(function(n) {
			var newConnectionMission = dojo.connect(n, 'onclick', function(event) { 
				
				// get missionId
				var missionElementId	= dojo.attr(n, 'id');
				var missionIdArray		= missionElementId.split('_');
				var missionId			= missionIdArray[1];
				
				// set ajax vars
				var ajaxUrl				= '/mission/instructions/missionid/' + missionId + '/orgid/' + orgId + '/format/html/devicetype/' + widgetDeviceType + '/' + sid;
				var ajaxTarget			= 'widgetWindow';
				var ajaxCallback		= 'bindLinksInstructionSteps';
				
				// set done URL to be equal to mission URL
				dojo.byId('doneUrl').innerHTML = ajaxUrl;
				
				//debug
				//extrasLogger('mission id: ', missionId);
				//extrasLogger('org id: ', orgId);
				//extrasLogger('clicked: ', event.target);
				
				// make ajax request
				loadData(ajaxUrl, ajaxTarget, ajaxCallback);
			});
			
			// store new connection in tracking array
			connectionHandlers.orgDetailMissions.push(newConnectionMission);
		});
		
		// first disconnect any existing bindings
		dojo.forEach(connectionHandlers.orgDetailUpdates, dojo.disconnect);
		
		// bind clicks to updates list
		dojo.query('#widgetWindow li.updates').forEach(function(n) {
			var newConnectionUpdates = dojo.connect(n, 'onclick', function(event) { 
				
				// set ajax vars
				var ajaxUrl				= '/orgs/updates/orgid/' + orgId + '/format/html/devicetype/' + widgetDeviceType + '/' + sid;
				var ajaxTarget			= 'detail';
				var ajaxCallback		= '';
				
				//debug
				//extrasLogger('mission id: ', missionId);
				//extrasLogger('org id: ', orgId);
				//extrasLogger('clicked: ', event.target);
				
				// make ajax request
				loadData(ajaxUrl, ajaxTarget, ajaxCallback);
			});
			
			// store new connection in tracking array
			connectionHandlers.orgDetailUpdates.push(newConnectionUpdates);
		});
	}
};

//bind clicks on mission instructions page - load action URL on click
var bindLinksInstructionSteps = function() {
	
	prepareInstructionsPage();
	
	// hide done button in case we are getting here from clicking the back button on the tagging page
	dojo.style('buttonDone', 'display', 'none');
	
	// get step count and current step.  if currentStep = 0, we are just starting this mission so set currentStep = 1
	if (parseInt(dojo.byId('currentStep').innerHTML, 10) === 0) { // make sure we are using radix=10 in parseInt, also === when comparing 0
		dojo.byId('currentStep').innerHTML = 1; // default currentStep to 1
	}
	var currentStep	= parseInt(dojo.byId('currentStep').innerHTML, 10);
	//extrasLogger('steps = ' + dojo.byId('numSteps').innerHTML + "\ncurrentStep = " + currentStep);
	
	// first disconnect any existing bindings
	dojo.forEach(connectionHandlers.missionInstructionSteps, dojo.disconnect);
	
	// loop through each step and bind clicks/set styles
	dojo.query('#widgetWindow li.step').forEach(function(node, index) {

		if (index+1 <= currentStep) { // if we are on a step that is less than or equal to the current step, activate it and bind clicks to it
		
			dojo.addClass(node, 'pointer'); // enable mouse pointer to emulate a clickable link
			dojo.addClass(node, 'arrow');	// add arrow icon to this row
			
			// bind clicks to this step
			var newConnectionInstructions = dojo.connect(node, 'onclick', function(event) { 
				var stepElementId	= dojo.attr(node, 'id');
				var stepIdArray		= stepElementId.split('_');
				var stepId			= stepIdArray[1];
				//extrasLogger('stepId: ', stepId);
				
				// set currentStep to be the step that was clicked
				dojo.byId('currentStep').innerHTML = stepId;
				
				// figure out some values for this step
				var actionModuleUrl		= dojo.byId('actionModuleUrl_' + stepId).innerHTML;
				var actionModuleHandler	= dojo.byId('actionModuleHandler_' + stepId).innerHTML;
				var actionModuleTitle	= dojo.byId('actionModuleTitle_' + stepId).innerHTML;
				
				// we want to use the old image tagger in the webwidget.
				actionModuleUrl = actionModuleUrl.replace('appflickr/tag/', 'appflickrcommons/displayfromcollection/');
				
				// update the widget title to be the action module title
				dojo.byId('widgetHead').innerHTML = actionModuleTitle;
				
				//debug
				//extrasLogger('step id: ', stepId);
				//extrasLogger('action_module url: ', actionModuleUrl);
				//extrasLogger('action_module handler: ', actionModuleHandler);
				//extrasLogger('action_module title: ', actionModuleTitle);
				//extrasLogger('clicked: ', event.target);
				
				// make ajax request
				var xhrArgs;
				var ajaxUrl;
				var ajaxTarget;
				var ajaxCallback;
				
				// depending on which action_module handler we've got, process it differently.  the only one getting special attention is /mission/complete (rate)
				if (actionModuleHandler == 'rate') {
					// Handle clicks to '/mission/complete'
					
					var orgId		= dojo.byId('orgId').innerHTML;
					var missionId	= dojo.byId('missionId').innerHTML;
					
					//ajaxUrl 		= actionModuleUrl + '/format/html/devicetype/' + widgetDeviceType;
					ajaxUrl 		= '/mission/complete/format/html/devicetype/' + widgetDeviceType + '/' + sid;
					ajaxTarget		= 'widgetWindow';
					ajaxCallback	= 'missionComplete';
					
					xhrArgs = {
						url: 		ajaxUrl,
						content: 	{	
										'orgid' : orgId, 
										'missionid': missionId
									},
						handleAs:	'text',
						load: 		function(response) {
							// post response to requested element
							dojo.byId(ajaxTarget).innerHTML = response;
							
							// add this URL to the history array
							prepareBackButton(ajaxUrl, ajaxTarget, ajaxCallback);
							
							// execute callback function
							if (ajaxCallback !== '') {
								window[ajaxCallback]();
							}
							
							// track AJAX call in google analytics
							gaTrackPageview(ajaxUrl);

						},
						error: function(error) {
							extrasLogger('loadData ERROR: ' + error);
						}
					};
				} else {
					// handle clicks to all other action modules
					
					ajaxUrl 		= '/actionmodules/frame/format/html/devicetype/' + widgetDeviceType + '/' + sid; // send this action module handler to the iframe
					ajaxTarget		= 'widgetWindow';
					ajaxCallback	= 'bindDoneButton';
					
					// read in optional params for the action module page
					var actionModuleDoctype 	= dojo.byId('actionModuleDoctype_' + stepId).innerHTML;
					var actionModuleRes			= dojo.byId('actionModuleRes_' + stepId).innerHTML;
					var actionModulePostvar		= dojo.byId('actionModulePostvar_' + stepId).innerHTML;
					var actionModulePhonenum	= dojo.byId('actionModulePhonenum_' + stepId).innerHTML;
					var missionId				= dojo.byId('missionId').innerHTML; // needed for uploads to S3
					
					xhrArgs = {
							url: 		ajaxUrl,
							content: 	{	
											'missionid'				: missionId,
											'actionmodulehandler' 	: actionModuleHandler,
											'actionmoduleurl' 		: actionModuleUrl,
											'actionmoduledoctype' 	: actionModuleDoctype,
											'actionmoduleres' 		: actionModuleRes,
											'actionmodulepostvar' 	: actionModulePostvar,
											'actionmodulephonenum' 	: actionModulePhonenum
										},
							handleAs:	'text',
							load: 		function(response) {
								// post response to requested element
								dojo.byId(ajaxTarget).innerHTML = response;
								
								// add this URL to the history array
								prepareBackButton(ajaxUrl, ajaxTarget, ajaxCallback);
								
								// execute callback function
								if (ajaxCallback !== '') {
									window[ajaxCallback]();
								}
								
								// track AJAX call in google analytics
								gaTrackPageview(ajaxUrl);
							},
							error: function(error) {
								extrasLogger('loadData ERROR: ' + error);
							}
					};
					
				/*
				 * MISSION TRACKING: if this is the first step, ask the server for a new mission tracking object
					TURNS OUT THAT WE NEED THE TRACKER TO BE GENERATED ALONG WITH THE INSTRUCTIONS INSTEAD OF 
					THIS STEP 1, B/C OTHERWISE WE CAN'T SEND IT TO 3RD PARTIES IN THE URLS THAT ARE SERVED AS 
					A PART OF THE INSTRUCTIONS DATA
				  
				  if (index == 0){
					  extrasLogger('webwidget.js, bindLinksInstructionSteps, requesting a mission tracker');
					  trackerUrl 		= '/mission/createtracker/format/json/';
					  xhrTrackerArgs = {
								url: 		trackerUrl,
								content: 	{	
												'missionid'	: missionId
											},
								handleAs:	'json',
								load: 		function(response) {
									extrasLogger('webwidget.js, bindLinksInstructionSteps, SUCCESS:' + response.trackerid);
								},
								error: function(error) {
									extrasLogger('webwidget.js, bindLinksInstructionSteps, ERROR:' + error);
								}
						};
				  }
				  */
				}
				
				// execute
				dojo.xhrPost(xhrArgs);
				//dojo.xhrPost(xhrTrackerArgs);
			});
			
			// store new connection in tracking array
			connectionHandlers.missionInstructionSteps.push(newConnectionInstructions);
		} else {
			
			// gray out inaccessible steps
			dojo.addClass(node, 'disabled');
			
			if (dojo.hasClass(node, 'done')) {
				dojo.removeClass(node, 'step');
				dojo.removeClass(node, 'done');
				dojo.addClass(node, 'doneDisabled');
			} else {
				dojo.removeClass(node, 'step');
				dojo.addClass(node, 'stepDisabled');
			}
		}
		
		// if this step is before current step, it is completed, so add checkmark.  this must come last so the check will override the other icons
		if (index+1 < currentStep) {
			dojo.addClass(node, 'completed');
		}
		
	});
};

var bindDoneButton = function() {
	
	dojo.style('widgetBranding', 'display', 'none'); 			// hide extras header
	dojo.style('widgetHead', 'display', ''); 			// show widgetHead text
	dojo.style('buttonDone', 'display', '');			// show done button
	
	// first disconnect any existing bindings
	dojo.forEach(connectionHandlers.doneButton, dojo.disconnect);
	
	var newConnectionDone = dojo.connect(dojo.byId('buttonDone'), 'onclick', function(event) {
		event.preventDefault(); // disable link from executing
		event.stopPropagation();
		
		var ajaxUrl			= dojo.byId('doneUrl').innerHTML; // no devicetype here, it's already specified in the doneUrl ID in the HTML
		var ajaxTarget		= 'widgetWindow';
		var ajaxCallback	= 'doneClicked';
		
		loadData(ajaxUrl, ajaxTarget, ajaxCallback);
	});
	
	// store new connection in tracking array
	connectionHandlers.doneButton.push(newConnectionDone);
};


//// submit profile form
//function bindProfileForm() {
//    
//	bindBottomNavLinks();
//	
//	// bind onclick/onblur events for form field elements
//	bindFormFieldToggle('first_name', 'First Name');
//	bindFormFieldToggle('last_name', 'Last Name');
//	bindFormFieldToggle('email', 'Email');
//	
//	var button = dojo.byId('submitButtonLink');
//
//	dojo.connect(button, 'onclick', function(event) {
//		//Stop the submit event since we want to control form submission.
//		event.preventDefault();
//		event.stopPropagation();
//
//		// set xhr args
//		var xhrArgs = {
//			form: dojo.byId('profileForm'),
//			handleAs: 'text',
//			load: function(response) {
//				dojo.byId('widgetWindowMinusNav').innerHTML = response;
//			},
//			error: function(error) {
//				extrasLogger('loadData ERROR: ' + error);
//			}
//		}
//      
//		// Hide submit button, show loading image
//		dojo.style('submitButton', 'display', 'none');
//		dojo.style('submitLoading', 'display', '');
//		
//		// execute
//		dojo.xhrPost(xhrArgs);
//	});
//}

// update bindings after 'done' button is clicked
function doneClicked() {

	// increment currentStep
	var currentStep = parseInt(dojo.byId('currentStep').innerHTML, 10); // make sure we use radix paramater here in parseInt
	dojo.byId('currentStep').innerHTML = currentStep + 1;
	
	// re-bind instructions page
	bindLinksInstructionSteps();
}

// handle completion of mission
function missionComplete() {
	
	// show header and bind bottom nav links
	resetHeader();
	bindBottomNavLinks();
	
	// reset currentStep to 0
	dojo.byId('currentStep').innerHTML = 0;
	
	// handle clicks of 'done' button on complete page (different from 'done' button in header)
	// first disconnect any existing bindings
	dojo.forEach(connectionHandlers.completePage, dojo.disconnect);
	
	var newConnectionCompletePageDone = dojo.connect(dojo.byId('completePageDoneButton'), 'onclick', function(event) {
		//Stop the submit event since we want to control form submission.
		event.preventDefault();
		event.stopPropagation();

		// set ajax vars
		var ajaxUrl			= '/orgs/profiles/mode/summaries/tags/webwidget/format/html/devicetype/' + widgetDeviceType + '/' + sid; //v3
		var ajaxTarget		= 'widgetWindow';
		var ajaxCallback	= 'bindLinksOrgList';
		
		//debug
		//extrasLogger('clicked: ', event.target);
		
		// make ajax request
		loadData(ajaxUrl, ajaxTarget, ajaxCallback);
	});
	
	// store new connection in tracking array
	connectionHandlers.completePage.push(newConnectionCompletePageDone);
}








// UTILITY FUNCTIONS #####################################################################################################################

//handle cleanup of header after user clicks 'Done' button
function resetHeader() {
	// update the header bar
	dojo.style('buttonDone', 'display', 'none');	// hide done button
	dojo.style('widgetHead', 'display', 'none'); 	// hide widgetHead text
	dojo.style('widgetBranding', 'display', ''); 			// show extras header
}

// load a page into the specified elementId
function loadData(postUrl, elementId, callbackFunction) {
	
	dojo.xhrGet ({
		// The page that parses the POST request
        url: postUrl,
        	
    	// we don't need to send parameters with our request because it's being passed in the URL
        //content: {'field_name' : field_name, 'field_contents': field_contents},
    		
        // Loads this function if everything went ok
        load: function(response) {
			
			// post response to requested element
			dojo.byId(elementId).innerHTML = response;
			
			// add this URL to the history array
			prepareBackButton(postUrl, elementId, callbackFunction);
			
			// execute callback function
			if (callbackFunction !== '') {
				window[callbackFunction]();
			}
			
			// track AJAX call in google analytics
			gaTrackPageview(postUrl);
			
			//debug
			//extrasLogger("loadData successful: " + response);
        },
            
        // Call this function if an error happened
        error: function(error) {
        	extrasLogger("loadData ERROR:\npostURL = " + postUrl + "\nelementId = " + elementId + "\ncallbackFunction = " + callbackFunction + "\n" + error);
        }
	});
}









// ABOUT PAGE #####################################################################################################################

function showMe(myId) {
	dojo.style(myId, 'display', '');
}

function hideMe(myId) {
	dojo.style(myId, 'display', 'none'); 
}

function getTweets() {
    dojo.xhrGet ({
        //GET request
        url: '/twitter/search/search_term/extraordinaries/format/json/',
		handleAs: 'json',
        // Loads this function if everything went ok
        load: function (data) {
        	displayTweets(data);
        },
        // Call this function if an error happened
        error: function (error) {
        	extrasError ('Error: ', error);
        }
	});
}
function displayTweets(data) {
	var tweetText = ''; 
	for (var i in data) {
		//console.debug(data[i]);
		//extrasLogger(data[i].date);
		//extrasLogger(data[i].body);
		//extrasLogger(data[i].who);
		tweetText += '<li> <p><em>'+data[i].date+'</em> @' +data[i].who+ ' ' +data[i].body+'</p> </li>';
	}
	hideMe('tweetsLoading');
	dojo.byId('tweets').innerHTML = tweetText;
}





// BACK BUTTON #####################################################################################################################

//adds url to AJAX history.  if history is empty, hide back button, otherwise show it
function prepareBackButton(postUrl, elementId, callbackFunction) {
	
	var historyState 				= [];
	historyState.postUrl 			= postUrl;
	historyState.elementId			= elementId;
	historyState.callbackFunction	= callbackFunction;
	historyArray.push(historyState);
	
	if (dojo.byId('showBackButton')) {
		var showBackButton = dojo.byId('showBackButton').innerHTML;
	}
	
	if (historyArray.length > 1 && showBackButton == 'true') {
		dojo.style('buttonBack', 'display', ''); // show back
	} else {
		dojo.style('buttonBack', 'display', 'none'); // hide back button
	}
	
	// debug
	//extrasLogger('length = ' + historyArray.length);
	//extrasDir(historyArray);
}

function bindBackButton() {
	
	//extrasLogger('bindBackButton() called.');
	
	// initialize historyArray with orgs/discover as the default
	var historyState 				= [];
	historyState.postUrl 			= dojo.byId('postUrl').innerHTML;
	historyState.elementId 			= dojo.byId('elementId').innerHTML;
	historyState.callbackFunction	= dojo.byId('callbackFunction').innerHTML;
	historyArray.push(historyState);
	
	// bind back button
	var backElement = dojo.byId('buttonBack');
	dojo.connect(backElement, 'onclick', function(event) {
		event.preventDefault(); // disable link from executing
		event.stopPropagation();
		
		var historyCurrent;
		var historyPrevious;
		if (historyArray.length >= 2) {
			// pop top two elements from array.  1st element is current URL, 2nd element is previous URL
			// we want to go to previous so we need to pop two off the array
			historyCurrent 	= historyArray.pop();
			historyPrevious = historyArray.pop();
			//extrasLogger('two states');
		} else {
			// pop the last element from array.
			historyPrevious = historyArray.pop();
			//extrasLogger('one state');
		}
		
		// debug
		//extrasLogger('current = ');
		//extrasDir(historyCurrent);
		//extrasLogger('previous = ');
		//extrasDir(historyPrevious);
		
		var ajaxUrl			= historyPrevious.postUrl;
		var ajaxTarget		= historyPrevious.elementId;
		var ajaxCallback	= historyPrevious.callbackFunction;
		
		if (ajaxUrl !== '' && ajaxTarget !== '') {
			loadData(ajaxUrl, ajaxTarget, ajaxCallback);
		}
	});
}
