console.log("starting to load heartbeat.js");

function addBeatAssigned(hid, bid, fromuser, isSidebar) {
	var touser = getSelectValue('beat_assign_'+hid+'_'+bid);
	DWRRestricted.addBeatAssigned(hid, bid, fromuser, touser, function(data){
		if (data) {
			refreshBeat(hid, bid, isSidebar);
		}
	});
}

function addBeatComment(hid, bid, user, isSidebar, actionType) {
	var comment = dojo.byId('beat_addcomment_'+hid+'_'+bid).value;
	comment = dojo.trim(comment);
	if (comment.length == 0) {
		console.log('nothing added as comment');
		return;
	}
	DWRRestricted.addBeatComment(hid, bid, user, comment, actionType, function(data){
		if (data) {
			refreshBeat(hid, bid, isSidebar);
		}
	});
}

function addBeatTag(hid, bid, tag, user, isSidebar) {
	DWRRestricted.addBeatTag(hid, bid, tag, user, function(data){
		if (data) {
			refreshBeat(hid, bid, isSidebar);
		}
	});
}

function addBeatTagSelect(hid, bid, user, isSidebar) {
	addTag = getSelectValue('addtag_'+hid+"_"+bid);
	console.log('adding tag ' +addTag+' to '+hid+', '+bid);
	addBeatTag(hid, bid, addTag, user, isSidebar);
}

function addToEPowerCenter(hid, bid) {
	DWRRestricted.addToEPowerCenter(hid, bid, function(data){
		if (data) {
			alert('Successfully added to ePowerCenter');
		} else {
			alert('Failed to add to ePowerCenter');
		}
	});
}

function applyToBeats(checkboxName, beatSelectBox, user) {
	var beatSelectObj = dojo.byId(beatSelectBox);
	if (!beatSelectObj) { return;}
	var numBeats = 0;
	var action = beatSelectObj.options[beatSelectObj.selectedIndex].value;
	if (action == 'star' || action == 'unstar') {
		dojo.query("."+checkboxName).forEach(function (node) {
			var name = dojo.attr(node, 'name');
			var nameArray = name.split("_");
			var starObj = dojo.byId("beat_star_"+ nameArray[3] + "_" + nameArray[4]);
			var hid = nameArray[3];
			var bid = nameArray[4];
			if(getFormValue(node)) {				
				if (starObj) {
					numBeats++;
					if ((starObj.className == "star_off" && action == "star") || (starObj.className != "star_off" && action == "unstar")) {
						starToggleBeat(hid, bid);
					} else {
						refreshBeat(hid, bid, false);
					}
				}
			}
		});		
	} 
	else if (action == 'addTag') {
		var select = dojo.byId("tagSelectBox");
		var tag = select.options[select.selectedIndex].value;
		if (select.selectedIndex > 0){
			// for all beats
			dojo.query("."+checkboxName).forEach(function (node) {
				// if checkbox is checked
				if(getFormValue(node)) {
					numBeats++;
					// indexes 3 and 4 are hid and bid respectively
					var nameArray = (dojo.attr(node, 'name')).split("_");
					if (nameArray.length == 5) {// safety check
						
						var hid = nameArray[3]; // heartbeat id
						var bid = nameArray[4]; // beat id
						addBeatTag(hid, bid, tag, user, false);
					}
				}
			});
		} 
		select.selectedIndex = 0;
	}
	else if (action == 'removeTag'){
		var select = dojo.byId("tagSelectBox");
		var tag = select.options[select.selectedIndex].value;
		if (select.selectedIndex > 0){
			// for all beats
			dojo.query("."+checkboxName).forEach(function (node) {
				// if checkbox is checked
				if(getFormValue(node)) {
					numBeats++;
					// indexes 3 and 4 are hid and bid respectively
					var nameArray = (dojo.attr(node, 'name')).split("_");
					if (nameArray.length == 5) {// safety check
						
						var hid = nameArray[3]; // heartbeat id
						var bid = nameArray[4]; // beat id
						deleteBeatTag(hid, bid, tag, user, false)
					}
				}
			});
		} 
		select.selectedIndex = 0;
	}
	else if (action == 'delete') {
		dojo.query("."+checkboxName).forEach(function (node) {
			if(getFormValue(node)) {
				numBeats++;
				// indexes 3 and 4 are hid and bid respectively
				var nameArray = (dojo.attr(node, 'name')).split("_");
				if (nameArray.length == 5) {// safety check					
					var hid = nameArray[3]; // heartbeat id
					var bid = nameArray[4]; // beat id					
					DWRRestricted.markTrashed(hid, bid, user, function(data){
						if (data) {
							refreshBeat(hid, bid, false);
						}
					});
				}
			}
		});
	}
	else if (action == 'close') {
		dojo.query("."+checkboxName).forEach(function (node) {
			if(getFormValue(node)) {
				numBeats++;
				// indexes 3 and 4 are hid and bid respectively
				var nameArray = (dojo.attr(node, 'name')).split("_");
				if (nameArray.length == 5) {// safety check					
					var hid = nameArray[3]; // heartbeat id
					var bid = nameArray[4]; // beat id					
					DWRRestricted.closeBeat(hid, bid, user, function(data){
						if (data) {
							refreshBeat(hid, bid, false);
						}
					});
				}
			}
		});
	}
	else if (action == 'sentiment') {
		var select = dojo.byId("changeBulkSentimentSelectBox");
		var sentiment = select.options[select.selectedIndex].value;	
		dojo.query("."+checkboxName).forEach(function (node) {
			// if checkbox is checked
			if(getFormValue(node)) {
				numBeats++;
				// indexes 3 and 4 are hid and bid respectively
				var nameArray = (dojo.attr(node, 'name')).split("_");
				if (nameArray.length == 5) {// safety check					
					var hid = nameArray[3]; // heartbeat id
					var bid = nameArray[4]; // beat id
					DWRRestricted.editBeatSentiment(hid, bid, sentiment, user, function(data){
						if (data) {
							refreshBeat(hid, bid, false);
						}
					});
				}
			}
		});		
	} else if(action == 'assignTo'){
		var select = dojo.byId("changeBulkAssignToSelectBox");
		if (select.selectedIndex > 0) {
			var touser = select.options[select.selectedIndex].value;	
			dojo.query("."+checkboxName).forEach(function (node) {
				// if checkbox is checked
				if(getFormValue(node)) {
					numBeats++;
					// indexes 3 and 4 are hid and bid respectively
					var nameArray = (dojo.attr(node, 'name')).split("_");
					if (nameArray.length == 5) {// safety check					
						var hid = nameArray[3]; // heartbeat id
						var bid = nameArray[4]; // beat id
						DWRRestricted.addBeatAssigned(hid, bid, user, touser, function(data){
							if (data) {
								refreshBeat(hid, bid, false);
							}
						});
					}
				}
			});
			select.selectedIndex = 0;
		}
	} else {
		var newurl = window.location.href;
		var qstrmap = getQueryStringMap(checkboxName);
		newurl = updateUrl(newurl, qstrmap);
		newurl = updateUrlSingle(newurl, 'submitDynamicForm', 'true');
		newurl = updateUrlSingle(newurl, 'action', action);
	    console.log(newurl);
		load(newurl);
	}
	if (numBeats > 0) {
		var b = numBeats == 1 ? " beat" : " beats";
		var textMsg = "Updated: " + numBeats + b;
		var spanTag = dojo.byId("addTagConfirmMsg");
		spanTag.innerHTML = textMsg;
        dojo.style("addTagConfirmMsg", "display", "");
	} else {
        dojo.style("addTagConfirmMsg", "display", "none");
	}
}

function deleteBeatTag(hid, bid, tag, user, isSidebar) {
	DWRRestricted.deleteBeatTag(hid, bid, tag, user, function(data){
		if (data) {
			refreshBeat(hid, bid, isSidebar);
		}
	});
}

function editBeatDemo(hid, bid, dojoPreventCache, user, isSidebar) {
	var dP = dojoPreventCache || "";
	console.log('editing beat demographics '+hid+', '+bid + ', ' + dP + ', ' + user);
	dojo.style("bid_edit_"+hid+"_"+bid + "_" + dP, "display", "block");
	var sentimentId = "edit_beat_sentiment_"+hid+"_" +bid + "_" + dP;
	var ageId = "edit_beat_age_"+hid+"_"+bid + "_" + dP;
	var genderId = "edit_beat_gender_"+hid+"_"+bid+ "_" + dP;
	var countryId = "edit_beat_country_"+hid+"_"+bid + "_" + dP;
	var authorityId = "edit_beat_authority_"+hid+"_"+bid + "_" + dP;
	var saveId = "edit_beat_save_"+hid+"_"+bid + "_" + dP;
	var sentimentVal = getSelectValue(sentimentId);	
	var ageVal = getSelectValue(ageId);
	var genderVal = getSelectValue(genderId);
	var countryVal = getSelectValue(countryId);
	var authorityVal = getSelectValue(authorityId);
	var saveVal = dojo.byId(saveId).checked;
	console.log('values for beat demographics '+sentimentVal+", "+ageVal+", "+genderVal+", "+countryVal+", "+authorityVal+", "+saveVal);
	DWRRestricted.editBeatDemographics(hid, bid, sentimentVal, ageVal, genderVal, countryVal, authorityVal, saveVal, user, function(data){
		console.log('edit beat demographics ' + data);
		if (data) {
			refreshBeat(hid, bid, isSidebar);
		}
		if (!isSidebar) {
			dojo.byId("bid_edit_msg_"+hid+"_"+bid + "_" + dP).innerHTML = "Successfully Updated";
		}
	});
}

function findNumCheckedBeats(){
	dojo.query(":checked", ".yourBeats").length;
}

function hbAllCheckboxes(form, flag) {
	if (!form) { return; } 

    var len = form.elements.length;
    for(var i = 0; i < len; i++ ) {
        var e = form.elements[i];
        if (e.type == "checkbox") {
                e.checked = flag;
                id = e.name.split("_");
                hid = id[3];
                bid = id[4];
                highlightCheckedBeat(e, hid, bid);
        }
    }
}

function highlightCheckedBeat(checkBox, hid, bid) {
	var beat = dojo.byId("bid_" + hid + "_" + bid);
	if (checkBox.checked){
		beat.style.backgroundColor = "#ffffd9";
	} else {
		beat.style.backgroundColor = "#FFFFFF";
	}
}

function limitText(message, count, limitNum, button) {		
	limitText(message, count, limitNum, button, false);
}

function limitText(message, count, limitNum, button, newDesign) {
	var messageBox = dojo.byId(message);
	var countBox = dojo.byId(count);
	var numLeft = limitNum - messageBox.value.length;
	var button = dojo.byId(button);
	if (dojo.attr(button, "actionType") == "Re-tweet") {
		numLeft = 0;
	}
	if (numLeft < 0) {
		countBox.innerHTML = "<font color=\"red\">" + numLeft + "</font>";
		if (newDesign) {
			button.className = "b_disabled_button";
			button.disabled = true;
		} else {
			button.onclick = new Function("return false;");
			button.className = "disabled_button";
		}
	} else {
		countBox.innerHTML = numLeft;
		if (newDesign) {
			button.disabled = false;
			button.className = "bbutton";
		} else {
			button.onclick = new Function("return true;");
			button.className = "button";
		}
	}
}

function loadWithMaxSample(selectId, url){
	var select = dojo.byId(selectId);
	var s = select.options[select.selectedIndex].value;
	var list = s.split(",");
	if(list.length == 2 && list[0] > 0) {
		load(url + "&maxSample=" + list[0] + "&maxToShow="+list[1]);
	}
}

function markTrashed(hid, bid, user, isSidebar) {
	DWRRestricted.markTrashed(hid, bid, user, function(data){
		if (data) {
			refreshBeat(hid, bid, isSidebar);
		}
	});
}

function pdfFullText(id, url){
	var firstSnippet = dojo.query(".beat_content_snippet");
	var showFull = false;
	if (firstSnippet[0]){
		showFull = (dojo.style(firstSnippet[0], "display") == "none");			
	}
	var pdfElement = dojo.byId(id);	
	var newUrl = updateUrlSingle(url, "viewFullText", showFull);
	if (id == "downloadPDF"){
		dojo.attr(pdfElement, 'href', newUrl);
	} else if (id = "downloadPDFEmail") {
		window.open(newUrl, null, 'width=800,height=600,top=30,left=30,resizable=yes,scrollbars=yes,location=no,toolbar=no');
	}
}

function postFacebookComment(hid, bid, user, message, postId, dpc) {	
    if (dojo.trim(message) == "") {
            alert('No message specified.');
            return;
    }
	dojo.byId("postFbCommentStatus_msg_"+hid+"_"+bid+"_"+dpc).innerHTML = "Publishing comment...";
	dojo.style("postFbCommentStatus_"+hid+"_"+bid+"_"+dpc, "display", "block");
    DWRRestricted.postFacebookComment(hid, bid, user, message, postId, function(returnValue) {
                    if (returnValue) {
                    	if (bid > 0) {
                    		refreshBeat(hid, bid, false);
                        	dijit.byId("contents_"+hid+"_"+bid+"_"+dpc).refresh();
                    	} else {
                    		dojo.byId("postFbCommentStatus_msg_"+hid+"_"+bid+"_"+dpc).innerHTML = "Successfully published comment.";	
                    	}
                    } else {                                
            			dojo.byId("postFbCommentStatus_msg_"+hid+"_"+bid+"_"+dpc).innerHTML = "Error encountered attempting to publish comment.";
                    }
            }
    );
}

function refreshBeat(hid, bid, isSidebar) {
	if (isSidebar) {
		var container = dijit.byId('sidebar_beat_container');
		container.refresh();
	} else {
		console.log('will refresh hid='+hid+', bid='+bid);
		var node = dojo.byId("bid_msg_"+hid+"_"+bid);
		node.innerHTML = "<b>refreshing</b>";
		var tmpURL = globalWebroot + 'hb/ajax/beat.jsp?bid='+bid+"&hid="+hid;
		try {
			if (globalHBWebroot) {
				tmpURL = globalHBWebroot + 'ajax/beat.jsp?bid='+bid+"&hid="+hid;
			} 
		} catch (e) { }
			
		dojo.xhrGet({
			url: tmpURL,
			preventCache: true,
	        // Called when the page loaded successfully
	        load: function (data) {
				var beatNode = dojo.byId("bid_"+hid+"_"+bid);
				beatNode.innerHTML = data;
				beatNode.style.backgroundColor = "#FFFFFF";
				dojo.parser.parse("bid_"+hid+"_"+bid);
	        },
	
	        // Called if there was an error (such as a 404 response)
	        error: function (data) {
	            console.error('Error: ', data);
	            var beatNode = dojo.byId("bid_"+hid+"_"+bid);
	            beatNode.innerHTML = 'Error: ' + data;
	            beatNode.style.backgroundColor = "#FFFFFF";
	        }
		});
	}
}

function shortenTwitterContent(postName) {
	var post = dojo.byId(postName);
	DWRRestricted.shortenTwitterContent(post.value, function(shortenedText) {
		if (shortenedText != null) {
			console.log("got shortened text " + shortenedText);
			post.value = shortenedText;			
		}
	});
}

function showSelectList(main, tagSelectList, sentimentSelectList, assignToSelectList) {
	var selected = getSelectValue(main);
	if (selected == 'addTag' || selected == 'removeTag') {
		dojo.style(tagSelectList, "display", "");
		dojo.style(sentimentSelectList, "display", "none");
		dojo.style(assignToSelectList, "display", "none");
        dojo.style("addTagConfirmMsg", "display", "none");
	}
	else if (selected == 'sentiment') {
		dojo.style(tagSelectList, "display", "none");
		dojo.style(sentimentSelectList, "display", "");
		dojo.style(assignToSelectList, "display", "none");
        dojo.style("addTagConfirmMsg", "display", "none");
	}
	else if (selected == 'assignTo') {
		dojo.style(tagSelectList, "display", "none");
		dojo.style(sentimentSelectList, "display", "none");
		dojo.style(assignToSelectList, "display", "");
        dojo.style("addTagConfirmMsg", "display", "none");
	}
	else {
		dojo.style(tagSelectList, "display", "none");
		dojo.style(assignToSelectList, "display", "none");
		dojo.style(sentimentSelectList, "display", "none");
		dojo.style("addTagConfirmMsg", "display", "none");	
	}
}

function starToggleBeat(hid, bid, isSidebar) {
	DWRRestricted.starToggleBeat(hid, bid, function(data){
		if (data) {
			refreshBeat(hid, bid, isSidebar);
		}
	});
}

function subscribeHeartbeatAlert(hid, dojoPreventCache, user) {	
	console.log('subscribeHeartbeatAlert('+hid+','+dojoPreventCache+','+user+')');
	dojo.style("subscribe_alert_msg_box_"+hid+"_"+dojoPreventCache, "display", "block");
	var emailId = "subscribe_email_"+hid+"_"+dojoPreventCache;
	var typeId = "subscribe_type_"+hid+"_"+dojoPreventCache;
	var tagId = "subscribe_tags_"+hid+"_"+dojoPreventCache;
	var freqId = "subscribe_frequency_"+hid+"_"+dojoPreventCache;
	var timeId = "subscribe_time_"+hid+"_"+dojoPreventCache;
	var dayVolumeCheckId = "subscribe_day_volumebox_"+hid+"_"+dojoPreventCache;
	var dayVolumeId = "subscribe_day_volume_"+hid+"_"+dojoPreventCache;
	var hourVolumeCheckId = "subscribe_hour_volumebox_"+hid+"_"+dojoPreventCache;
	var hourVolumeId = "subscribe_hour_volume_"+hid+"_"+dojoPreventCache;
	var emailVal = dojo.byId(emailId).value;	
	var typeVal = dojo.byId(typeId).value;
	var tagVal = dojo.byId(tagId).value;
	var freqVal = getSelectValue(freqId);
	var timeVal = dijit.byId(timeId).value;
	console.log('dayVolumeCheckId is : '+dayVolumeCheckId);
	var dayVolumeCheckVal = dojo.byId(dayVolumeCheckId).checked;
	var dayVolumeVal = dojo.byId(dayVolumeId).value;
	var hourVolumeCheckVal = dojo.byId(hourVolumeCheckId).checked;
	var hourVolumeVal = dojo.byId(hourVolumeId).value;
	if (!dayVolumeCheckVal) {
		dayVolumeVal = 0;
	}
	if (!hourVolumeCheckVal) {
		hourVolumeVal = 0;
	}
	var volumeVal;
	if (freqVal == "HOURLY")
		volumeVal = hourVolumeVal;
	else //freqVal == "DAILY"
		volumeVal = dayVolumeVal;
	
	console.log('values for subscribe heartbeat alert '+hid+", "+emailVal+", "+typeVal+", "+tagVal+", "+freqVal+", "+timeVal+", "+volumeVal);
	DWRRestricted.subscribeHeartbeatAlert(hid, emailVal, typeVal, tagVal, freqVal, timeVal, volumeVal, user, function(data){
		console.log('subscribe heartbeat alert ' + data);		
		if (data) {
			dojo.byId("subscribe_alert_msg_"+hid+"_"+dojoPreventCache).innerHTML = "Successfully saved";
			dojo.style("subscribe_btn_"+hid+"_"+dojoPreventCache, "display", "none");
		} else {
			dojo.byId("subscribe_alert_msg_"+hid+"_"+dojoPreventCache).innerHTML = "Error encountered";
		}			
	});
}

//toggle between full content and shortened snippet of a beat. 
function toggleBeatContent(snippet, full, button){
	var firstSnippet = dojo.query("."+snippet);
	if (!firstSnippet[0]) { 
		return;
	}
	var showFull = (dojo.style(firstSnippet[0], "display") == "inline");
	dojo.query("."+snippet).forEach(function (node) {
		if (showFull) {
			dojo.attr(node, 'style', {
	            display: "none"
	        });
		} else {
			dojo.attr(node, 'style', {
	            display: "inline"
	        });
		}
	});
	dojo.query("."+full).forEach(function (node) {
		if (showFull) {
			dojo.attr(node, 'style', {
	            display: "inline"
	        });
		} else {
			dojo.attr(node, 'style', {
	            display: "none"
	        });
		}
	});
	var b = dojo.query("#"+button);
	if (showFull) {
		dojo.attr(b[0], "innerHTML", "View Snippet Text");
	} else {
		dojo.attr(b[0], "innerHTML", "View Full Text");
	}
}

function toggleBeatSentiment(hid, bid, user, isSidebar) {
	// dojo.attr("sentimenticon_"+hid+"_"+bid, "onclick", "javascript:void()");
	dojo.byId("sentimenticon_"+hid+"_"+bid).innerHTML = "Changing Sentiment";
	DWRRestricted.toggleBeatSentiment(hid, bid, user, function(data){
		if (data) {
			refreshBeat(hid, bid, isSidebar);
		}
	});
}

function toggleShow(offName, onName) { 
	var offObj = dojo.byId(offName);
	var onObj = dojo.byId(onName);
	if (offObj && onObj) {
		offObj.style.display = 'none';
		onObj.style.display = '';
	}
}

function unmarkTrashed(hid, bid, user, isSidebar) {
	DWRRestricted.unmarkTrashed(hid, bid, user, function(data){
		if (data) {
			refreshBeat(hid, bid, isSidebar);
		}
	});
}

function updateTag(n, tagType, tagId) {
	var name = "";
	if (dojo.byId(n)) {
		name = dojo.byId(n).value;
	}
	updateAndLoadUrl({"tagedit": 1, "tagName": name, "tagType": tagType, "tagId": tagId, "tagAction": "editTag"});
}

function updateTimelineSelect() {
	var radioVal = getRadioValue("date_radio_stats");
	if (radioVal == 1) {
		dojo.byId("date_selects_stats").disabled = false;
		dojo.byId("date_stats_s").disabled = true;
		dojo.byId("date_stats_e").disabled = true;
	} else {
		dojo.byId("date_selects_stats").disabled = true;
		dojo.byId("date_stats_s").disabled = false;
		dojo.byId("date_stats_e").disabled = false;
	}
}

//used in twitter engage tab
function toggleTwitterErrorMsg(id, bid, msg, show) {
	var ele = dojo.byId(id+"msg_"+bid);
	if (show) {
		if (msg) {
			ele.innerHTML = msg;
		}
		dojo.attr(id + bid, 'style', {
			display: ""
		});
	} else {
		dojo.attr(id + bid, 'style', {
			display: "none"
		});
	}
}

// sets twitter action button style
//used in twitter engage tab
function setTActionButtonStyle(button, clicked) {
	button.className = clicked ? "nbbutton" : "nbutton";
}

//used in twitter engage tab
function setPostButtonStyle(bid, enabled) {
	var postButton = dojo.byId("ttooltip_post_button_" + bid);
	if (enabled) {
		postButton.disabled = false;
		postButton.className = "bbutton";
	} else {
		postButton.className = "b_disabled_button";
		postButton.disabled = true;
	}
}

// checks if given twitter account is verified
function twitterIsVerified(bid, screenName) { 
	DWRRestricted.twitterIsVerified(screenName, function(isVerified) {
		var show = dojo.byId("ttooltip_verified_"+bid);
		if (isVerified) {
			show.src = "/img/hb/twitter_verified_account.png";
			show.title = screenName + " is a verified Twitter account.\n Verified accounts can send Direct Messages to non-followers.";
			show.style.display = "";
		} else {
			show.src = "/img/tr.gif";
			show.title = "";
			show.style.display = "none";
		}
		dojo.attr(show, "verified", isVerified);
		return isVerified;
	});
}

//used in twitter engage tab
function twitterIsFollowing(bid, user, user2) {
 	var ele = dojo.byId("ttooltip_as_" + bid);
	var postButton = dojo.byId("ttooltip_post_button_" + bid);
	var retweetButton = dojo.byId("ttooltip_retweet_button_"+bid);
	var replyButton = dojo.byId("ttooltip_reply_button_"+bid);
	var dmButton = dojo.byId("ttooltip_dm_button_"+bid);
	var status = dojo.byId("ttooltip_follow_status_" + bid);
	var status2 = dojo.byId("ttooltip_follow_status2_" + bid);
	var followButton = dojo.byId("ttooltip_follow_button_" + bid);
	
	// clear any infobox
	toggleTwitterErrorMsg("infobox_success_", bid, "", false);
	toggleTwitterErrorMsg("infobox_failed_", bid, "", false);
	status.innerHTML = "";
	status2.innerHTML = "";
	followButton.innerHTML = "";
	setTActionButtonStyle(replyButton, (replyButton.className == 'nbbutton'));
	setTActionButtonStyle(retweetButton, (retweetButton.className == 'nbbutton'));
	setTActionButtonStyle(dmButton, (dmButton.className == 'nbbutton'));
	setPostButtonStyle(bid, true);
	
	// verifiy the twitter account
	twitterIsVerified(bid, user);

	// disable re-tweet button if user and following is the same
	// since you can't re-tweet your own tweet
	if (user == user2) {
		status.innerHTML = "Same user";
		status2.innerHTML = "";
		followButton.innerHTML = "";
		toggleTwitterErrorMsg('infobox_failed_', bid, "Can't re-tweet your own tweet.", false);
		return;
	}
	setTActionButtonStyle(retweetButton, false);
	status.innerHTML = "<img src='/img/loading.gif' style='float: left;' />";
	status2.innerHTML = "";
	followButton.innerHTML = "";
	DWRRestricted.twitterIsFollowing(user, user2, function(result){
		if (result == 3) {
			status.innerHTML = "You are following @" + user2;
			status2.innerHTML = "@" + user2 + " is following you";
			dojo.attr(status, "following", true);
			dojo.attr(status2, "follower", true);
			followButton.innerHTML = "&nbsp;(Unfollow)";
			followButton.onclick = function() { twitterFollow(bid, user, user2, false) };
		} else if (result == 2) {
			status.innerHTML = "You are not following @" + user2;
			status2.innerHTML = "@" + user2 + " is following you";
			dojo.attr(status, "following", false);
			dojo.attr(status2, "follower", true);
			followButton.innerHTML = "&nbsp;(Follow)";
			followButton.onclick = function() { twitterFollow(bid, user, user2, true) };
		} else if (result == 1) {
			status.innerHTML = "You are following @" + user2;
			status2.innerHTML = "@" + user2 + " is not following you";
			dojo.attr(status, "following", true);
			dojo.attr(status2, "follower", false);
			followButton.innerHTML = "&nbsp;(Unfollow)";
			followButton.onclick = function() { twitterFollow(bid, user, user2, false) };
		} else if (result == 0) {
			status.innerHTML = "You are not following @" + user2;
			status2.innerHTML = "@" + user2 + " is not following you";
			dojo.attr(status, "following", false);
			dojo.attr(status2, "follower", false);
			followButton.innerHTML = "&nbsp;(Follow)";
			followButton.onclick = function() { twitterFollow(bid, user, user2, true) };
		} else {
			status.innerHTML = "Failed to retrieve follow status information";
			followButton.innerHTML = "";
			followButton.onclick = "";
		}
		
		// check for dm
		var isVerified = dojo.attr("ttooltip_verified_"+bid, "verified");
		if (!isVerified && dmButton.className == "nbbutton" && (result == 1 || result == 0) && status.innerHTML != "Same user") {
			toggleTwitterErrorMsg('infobox_failed_', bid, "You cannot send messages to users who are not following you.", true);
		}
	});
}

//used in twitter engage tab
function twitterFollow(bid, user, userToFollow, follow) {
	var loadingCircle = "<img src='/img/loading.gif' style='float: left;' />";
	var followButton = dojo.byId("ttooltip_follow_button_" + bid);
	followButton.innerHTML = loadingCircle;
	followButton.disabled = true;
	DWRRestricted.twitterFollow(user, userToFollow, follow, function(result){
		var status = dojo.byId("ttooltip_follow_status_" + bid);
		if (result == 1) {
			status.innerHTML = "You are following @" + userToFollow;
			dojo.attr(status, "following", true);
			followButton.innerHTML = "&nbsp;(Unfollow)";
			followButton.onclick = function() { twitterFollow(bid, user, userToFollow, false) };
		} else if (result == 0) {
			status.innerHTML = "You are not following @" + userToFollow;
			dojo.attr(status, "following", false);
			followButton.innerHTML = "&nbsp;(Follow)";
			followButton.onclick = function() { twitterFollow(bid, user, userToFollow, true) };
		} else {
			// failed to update following status
			// TODO: inform user.
			status.innerHTML = "Failed to update following status";
			followButton.innerHTML = "";
		}
		followButton.disabled = false;
	});
}

//used in twitter engage tab
function updateTwitterButton(bid, actionType, screenName, content) {
	var postButton = dojo.byId("ttooltip_post_button_"+bid);
	var replyButton = dojo.byId("ttooltip_reply_button_"+bid);
	var dmButton = dojo.byId("ttooltip_dm_button_"+bid);
	var retweetButton = dojo.byId("ttooltip_retweet_button_"+bid);
	var msgField = dojo.byId("ttooltip_msg_"+bid);
	toggleTwitterErrorMsg('infobox_success_', bid, "", false);
	toggleTwitterErrorMsg('infobox_failed_', bid, "", false);
	msgField.readOnly = "";
	postButton.innerHTML = "<b>Post " + actionType + "</b>";
	dojo.attr(postButton, 'actionType', actionType);
	if (dojo.attr(replyButton, 'actionType') == actionType) {
		replyButton.className = "nbbutton";
		dmButton.className = "nbutton";
		retweetButton.className = "nbutton";
		msgField.value = "@" + screenName;
	} else if (dojo.attr(dmButton, 'actionType') == actionType) {
		replyButton.className = "nbutton";
		dmButton.className = "nbbutton";
		retweetButton.className = "nbutton";
		msgField.value = "";
		// check if this user if being followed by the user
		var isVerified = dojo.attr("ttooltip_verified_"+bid, "verified");
		var follower = dojo.attr("ttooltip_follow_status2_"+bid, "follower");
		var status = dojo.byId("ttooltip_follow_status_" + bid);
		if (!isVerified && !follower && status.innerHTML != "Same user") {
			toggleTwitterErrorMsg('infobox_failed_', bid, "You cannot send messages to users who are not following you.", true);
		}
	} else if (dojo.attr(retweetButton, 'actionType') == actionType) {
		replyButton.className = "nbutton";
		dmButton.className = "nbutton";
		retweetButton.className = "nbbutton";
		msgField.value = "RT: " + content;
		msgField.readOnly = "true";
	}
}

//used in twitter engage tab
function updateTwitterApiLimit(bid) {
	var userSelect = dojo.byId('ttooltip_as_'+bid);
	var toScreenName = userSelect.options[userSelect.selectedIndex].value;
	var div = dojo.byId('ttooltip_api_limit_'+bid);
	DWRRestricted.twitterApiLimit(toScreenName, function(limit){
		// limit is a string in the following format
		// limit left;total limit;seconds until next reset
		var arr = limit.split(";", 3);
		var left = arr[0];
		var total = arr[1];
		var untilRest = arr[2]; // in seconds
		div.innerHTML = left + " requests left";
		div.title = Math.floor(untilRest/60) + " mins " + untilRest%60 + " seconds left until reset to " + total + " requests";
	});
}

// twitter function to send reply, direct message and retweet
// used in twitter engage tab
function postTwitterMsg(hid, bid, hbUser, tweetItemId, toScreenName, commentToBeat){
	var postButton = dojo.byId("ttooltip_post_button_"+bid);
	if(postButton.disabled) {
		return;
	}
	toggleTwitterErrorMsg('infobox_success_', bid, "", false);
	toggleTwitterErrorMsg('infobox_failed_', bid, "", false);
	setPostButtonStyle(bid, false);
	var userSelect = dojo.byId("ttooltip_as_" + bid);
	var tUser = userSelect.options[userSelect.selectedIndex].value;
	var actionType = dojo.attr(postButton, 'actionType');
	var msg = dojo.byId("ttooltip_msg_"+bid).value; 
	var postStatus = dojo.byId("ttooltip_post_status_"+bid);
	if (msg) {
		postStatus.innerHTML = "Sending...<img src='/img/loading.gif' style='float: left;' />"
		if (actionType == "Reply" || actionType == "Direct Message" || actionType == "Re-tweet") {
			var cBid = -1;
			if (commentToBeat) {
				cBid = bid;
			}
			DWRRestricted.postTwitterMsg(hbUser, tUser, toScreenName, hid, cBid, msg, tweetItemId, actionType, function(result){
				postStatus.innerHTML = "";
				if (result == "") {
					toggleTwitterErrorMsg('infobox_success_', bid, actionType + " successful.", true);
				} else {
					toggleTwitterErrorMsg('infobox_failed_', bid, result, true);
				}
				setPostButtonStyle(bid, true);
			});
		} else {
			console.log("[sendTwitterMsg] unknown actionType - " + actionType + ", hid: " + hid + ", bid: " + bid);
		}
	}
}

// function used in Message Central
function postTwitterDM(hid, hbUser, tUser, toId, msgId){
	var to = dojo.byId(toId).value;
	var msg = dojo.byId(msgId);
	var loadingCircle = "<img src='/img/loading.gif' style='float: left;' />";
	var status = dojo.byId("mc_post_status");
	if (msg.value.length > 140 || msg.value.length <= 0){
		return;
	}
	status.innerHTML = "Sending..." + loadingCircle;
	DWRRestricted.postTwitterMsg(hbUser, tUser, to, hid, -1, msg.value, "", "Direct Message", function(result){
		status.innerHTML = "";
		if (result == "") {
			toggleTwitterErrorMsg('infobox_success_', "", "Direct Message sent successfully.", true);
			msg.value = "";
		} else {
			toggleTwitterErrorMsg('infobox_failed_', "", result, true);
		}
	});
}

// used in twitter Message Central and Tweets
// both fetch and updates the ui in twitter engage centre
function fetchTwitterProfile(user, linkedUser) {
	var loadingCircle = "/img/loading.gif";
	// get all dom elements
	var uiDisplay = dojo.byId("mc_profile_display");
	var uiLink = dojo.byId("mc_profile_link"); // href
	var uiLink2 = dojo.byId("mc_profile_link2"); // href, innerHTML
	var uiImg = dojo.byId("mc_profile_img"); // src
	var uiLoading = dojo.byId("mc_profile_loading"); // src
	var uiName = dojo.byId("mc_profile_name"); // innerHTML
	var uiFollowing = dojo.byId("mc_profile_following"); // innerHTML
	var uiFollower = dojo.byId("mc_profile_follower"); // innerHTML
	var uiTweets = dojo.byId("mc_profile_tweets"); // innerHTML
	var uiSummary = dojo.byId("mc_profile_summary"); // innerHTML
	var uiAuthority = dojo.byId("mc_profile_authority"); // src, alt, title
	var uiLocationFlag = dojo.byId("mc_profile_location_flag"); // src
	var uiLocation = dojo.byId("mc_profile_location"); // innerHTML

	if (dojo.attr(uiDisplay, "lastuser") != user) {
		if (user != "") {
			// show loading
			uiLoading.src = loadingCircle;
			// get profile
			DWRRestricted.twitterFetchProfile(user, function(result){
				// stop loading
				uiLoading.src = "/img/transparent_pixel.png";
				if (result != null) {
					uiLink2.innerHTML = "@" + user;
					uiName.innerHTML = result['name'];
					uiImg.src = result["img"];
					if (result["summary"] == null){
						uiSummary.innerHTML = "<i>No profile summary</i>"
					} else {
						uiSummary.innerHTML = result["summary"];
					}
					uiFollower.innerHTML = result["follower"];
					uiFollowing.innerHTML = result["following"];
					uiTweets.innerHTML = result["tweets"];
					uiLink.href = result["link"];
					uiLink2.href = result["link"];
					uiAuthority.src = result["authority_src"];
					uiAuthority.title = "Authority " + result["authority"];
					uiAuthority.alt = "Authority " + result["authority"];
					uiLocationFlag.src = result["countryflag"];
					uiLocation.innerHTML = result["location"];
					// display the profile
					dojo.attr(uiDisplay, 'style', {
						display: ""
					});
				}
				// update the last user checked
				dojo.attr(uiDisplay, "lastuser", user);
			});
			// get messages
			var uiMsgs = dijit.byId("mc_msgs");
			var origHref = uiMsgs.get("href");
			var origHrefArray = origHref.split("?");
			dojo.attr("mc_msgs", 'style', {
				display: ""
			});
			uiMsgs.set("href", origHrefArray[0] + "?linkedUser=" + encodeURIComponent(linkedUser) + "&user=" + encodeURIComponent(user));
		}
		// hide the profile
		dojo.attr(uiDisplay, 'style', {
			display: "none"
		});
	}
}

//used in twitter Message Central
function clickedDM(screenName, linkedScreenName) {
	var to = dojo.byId("mc_to");
	to.value = screenName;
	fetchTwitterProfile(screenName, linkedScreenName);
	mcClickSubTab("mc_sendDM", false);
}

function prepareLocalTimeZone() {
	dojo.query(".time_stamp").forEach(function (node) {
		var time = parseInt(dojo.attr(node, 'time_ms')); // time in ms
		var newDate = new Date();
		newDate.setTime(time);
		var dateStr = dojo.date.locale.format(newDate, {datePattern: "d MMM y", timePattern: "h:mma (z)"});
		dojo.attr(node, 'title', dateStr);
	});
}

dojo.addOnLoad(
   function() {
	  prepareLocalTimeZone();
   }
);

console.log("finishing to load heartbeat.js");

