var bUseSmallButtons = false;
var bFollowClicked = false;

function FriendsFollowBtn(sUserId, sLoggedInId, iFollowed, sDisplayName, bSmall, bClogHome, bClogHome2, bApprovalRequired) {

	// this function will 
	//alert('entered');
	var bUseSmallButtons = false;
	if (!!bSmall) {
		//alert('got bsmall');
		bUseSmallButtons = true;
	}
	
	// 0609 - commented b/c causes issues with false 'Request Sent' labels
	
	if (typeof(bApprovalRequired) == 'undefined') {
		bApprovalRequired = !!bApprovalRequired;
	}
	
	var sHTML = '<span class="FriendsFollowBtn' + (bSmall ? ' SmallBtn' : '') + '" id="spnFriendsFollowBtn-' + sUserId + '">';
	
	
	if (!sLoggedInId) {
		//sHTML += '<a href="#" onclick="return FriendsFollowAction(' + sUserId + ', ' + sLoggedInId + ');">Follow</a>';
		// logged out, don't show button for now..
		sHTML = '<br clear="all" />';
	} else {

		if (iFollowed != 0) {
			// 1 == followed
			// 2 == pending
			// followed button + remove link
			sHTML += '<a href="#" onclick="return FriendsOpenRemove(' + sUserId + ', ' + sLoggedInId + ');" class="Following">' + (!bUseSmallButtons ? '<img src="/wp-content/themes/default/images/famfamfam/tick.png" width="16" height="16" border="0" alt="" style="padding:0px;" />' : '') + (iFollowed == 1 ? 'Following' : 'Request Sent') + '</a>';
			sHTML += '<div class="RemovePanel" id="dvRemovePanel-' + sUserId + '" style="z-index:9999;display: none;' + ((bClogHome || bClogHome2) ? 'border-width: 1px 0px 0px 0px;' : '') + '"><a href="#" onclick="return FriendsFollowActionInit(' + sUserId + ', ' + sLoggedInId + ', true, \'' + sDisplayName.replace(/\'/g, '\\\'') + '\', ' + bSmall + ',' + bClogHome + ',' + bClogHome2 + ', ' + bApprovalRequired + ');" class="Remove">Remove</a>';
			if (!bUseSmallButtons) {
				if (iFollowed == 2) {
					sHTML += '<span style="padding-right: 6px;">A request to add ' + sDisplayName + ' to your Sources has been sent.</span>';
				} else {
					sHTML += '<span style="padding-right: 6px;">' + sDisplayName + ' has been added to your Sources.</span>';
				}
				if (bFollowClicked) {
					sHTML += '<div style="margin: 8px 6px 0px 3px;"><a href="http://amplify.com/" class="SeeFeed">See your Sources Feed</a></div>';
					bFollowClicked = false;
				}
			}
			sHTML += '</div>';
		} else {
			// not followed
			sHTML += '<a href="#" onclick="return FriendsFollowActionInit(' + sUserId + ', ' + sLoggedInId + ', false, \'' + sDisplayName.replace(/\'/g, '\\\'') + '\', ' + bSmall + ',' + bClogHome + ',' + bClogHome2 + ', ' + bApprovalRequired + ');" class="Follow">Follow</a>';
		}
	
	}
	
	sHTML += '</span>';
	
	return(sHTML);
	
}


function FriendsOpenRemove(sUserId, sLoggedInId) {
	
	Effect.SlideDown('dvRemovePanel-' + sUserId, { duration: 0.3 } );
	
	return false;
}


function FriendsFollowActionInit(sUserId, sLoggedInId, bRemove, sDisplayName, bSmall, bClogHome, bClogHome2, bApprovalRequired) {
	
	FriendsFollowAction(sUserId, sLoggedInId, bRemove, sDisplayName); 
	
	bFollowClicked = true;

	
	Effect.Fade('spnFriendsFollowBtn-' + sUserId, { duration: 1.0, from: 1, to: 0.1, afterFinish: function() { 
		$('spnFriendsFollowBtn-' + sUserId).innerHTML = FriendsFollowBtn(sUserId, sLoggedInId, (bRemove ? 0 : (bApprovalRequired ? 2 : 1)), sDisplayName, bSmall, bApprovalRequired);
		
		// adapt new follower number updater code here
		
		Effect.Fade('spnFriendsFollowBtn-' + sUserId, { duration: 1.0, from: 0.1, to: 1, afterFinish: function() { 
			if (!bUseSmallButtons) {
				FriendsOpenRemove(sUserId, sLoggedInId);
			}
			
			
			if (bClogHome && !bRemove) {
				Effect.Appear('dvRefreshHomefeed');
			} else if (bClogHome2 && !bRemove) {
				Effect.Appear('dvRefreshHomefeed2');
			}
			
		}  } );
		
	}  } );

	return false;

}


function FriendsFollowAction(sUserId, sLoggedInId, bRemove, sDisplayName) {
	// http://dinnerswitch.com/clog-ajax.php?ajaxaction=ajax-friend&function=friends_action_follow&user_to_follow=132
	
	//Effect.Fade('spnFriendsFollowBtn-' + sUserId, { duration: 1.0, from: 1, to: 0.1 } );

	if (bRemove) {

		new Ajax.Request('/clog-ajax.php', 
		  {
		    method: 'GET',
		    parameters: { ajaxaction: 'ajax-friend', af: 'friends_action_follow', user_to_follow: sUserId, action: 'unfollow' }, 
		    onSuccess: function(transport){
			    var sReturn = transport.responseText;
			    
			    /*
			    $('spnFriendsFollowBtn-' + sUserId).innerHTML = FriendsFollowBtn(sUserId, sLoggedInId, false, sDisplayName);
			    */
			    
			    if (!!$('spnFriendsFollowers-' + sUserId)) {
				    var iTot = ($('spnFollowersTot-' + sUserId).innerHTML == '') ? 0 : parseInt($('spnFollowersTot-' + sUserId).innerHTML);
				    if ((iTot - 1) == 0) {
					    $('spnFollowersTot-' + sUserId).innerHTML = '';
					    $('aFollowersNoun-' + sUserId).innerHTML = '';
				    } else {
					    $('spnFollowersTot-' + sUserId).innerHTML = iTot - 1;
					    $('aFollowersNoun-' + sUserId).innerHTML = ((iTot - 1 == 1) ? 'Follower' : 'Followers');
				    }
			    }
			    
		    },
		    onFailure: function(){ alert('Sorry, an error occured when attempting to remove this user. Please try again.') } 
		  });

	} else {

		  //Effect.Highlight('aFollowBtn-' + sUserId, { startcolor: '#ffff99', endcolor: '#ffffff' });

		  new Ajax.Request('/clog-ajax.php', 
		  {
		    method: 'GET',
		    parameters: { ajaxaction: 'ajax-friend', af: 'friends_action_follow', user_to_follow: sUserId  }, 
		    onSuccess: function(transport){
			    var sReturn = transport.responseText;
			    //alert(sReturn);
			
			    /*
			    $('spnFriendsFollowBtn-' + sUserId).innerHTML = FriendsFollowBtn(sUserId, sLoggedInId, true, sDisplayName);
			    */
			    
			    if (!!$('spnFriendsFollowers-' + sUserId)) {
				    var iTot = ($('spnFollowersTot-' + sUserId).innerHTML == '') ? 0 : parseInt($('spnFollowersTot-' + sUserId).innerHTML);
				    if ((iTot + 1) == 0) {
					    $('spnFollowersTot-' + sUserId).innerHTML = '';
					    $('aFollowersNoun-' + sUserId).innerHTML = '';
				    } else {
					    $('spnFollowersTot-' + sUserId).innerHTML = iTot + 1;
					    $('aFollowersNoun-' + sUserId).innerHTML = ((iTot + 1 == 1) ? 'Follower' : 'Followers');
				    }

			    }
			    
			    
			    //Effect.Fade('spnFriendsFollowBtn-' + sUserId, { duration: 1.0, from: 0.1, to: 1, afterFinish: function() { FriendsOpenRemove(sUserId, sLoggedInId); }  } );

		    },
		    onFailure: function(){ alert('Sorry, an error occured when attempting to follow user. Please try again.') } 
		  });
	
	}
	
	return false;
}


function FriendsGetClipsByFriends(sLoggedInId, sNumPerPage, sPageNum) {
	if(sNumPerPage == ''){
		sNumPerPage = '4';
	}
	if(sPageNum == ''){
		sPageNum = '0';
	}
	new Ajax.Request('/clog-ajax.php',
		  {
		    method: 'GET',
		    parameters: { ajaxaction: 'ajax-friend', af: 'friends_get_clips_by_friends', num_per_page:sNumPerPage, page_num:sPageNum  }, 
		    onSuccess: function(transport){
		    	var clipObjects = transport.responseText.evalJSON();
		    },
		    onFailure: function(){ alert('Sorry, an error occured when attempting to display new clips. Please try again.') } 
		  });
		
}


// Direct Message functions
var iDMCharLimit = 1000;

function DMFormOpen(iPmId, iUid, sUser, sSubject, sSource) { 
	
	//alert(iPmId);
	
	if (!$('dvDMForm')) {
		DMFormRender(iPmId, iUid, sUser, sSubject, sSource);
		Event.observe('txtDMNewMessage', 'keyup', function(event) { DMFormCharCounter(); });
		Event.observe('txtDMNewMessage', 'keydown', function(event) { DMFormCharCounter(); });
	} else {
		$('dvDMSent').style.display = 'none';

		$('imgDMUser').src = 'http://content0.clipmarks.com/clog_avatar/' + iUid;
		$('spnDMUser').innerHTML = sUser;
		$('hdnDMPmId').value = iPmId;
		$('hdnDMRecipient').value = iUid;
		$('hdnDMSubject').value = sSubject;
		$('hdnDMSource').value = sSource;
		$('dvDMSubject').innerHTML = (iPmId > 0 ? 'Re: ' : '') + sSubject;
	}
	
	DMFormCharCounter();
	
	/*if ($('txtDMNewMessage')) {
		$('txtDMNewMessage').focus();
	}*/
	
	setTimeout('$(\'txtDMNewMessage\').focus();', 100);	
	
	return false;
}


function DMFormSend() {
	
	// validation
	var s = $('txtDMNewMessage').getValue();
	s = s.replace(/^\s+/, '');
	s = s.replace(/\s$/, '');
	if (s.length == 0) {
		alert('The message is blank.');
		return false;
	}
	
	$('dvDMSending').style.display = 'block';
	
	new Ajax.Request('/clog-ajax.php',
		  {
		    method: 'GET',
		    parameters: { 
			    	ajaxaction: 'ajax-friend', 
			    	af: 'post_message', 
		    		message: $('txtDMNewMessage').getValue(), 
		    		recipient: $('hdnDMRecipient').getValue(), 
		    		subject: $('hdnDMSubject').getValue(),  
		    		source: $('hdnDMSource').getValue(),
		    		inreplyto: $('hdnDMPmId').getValue()
		    }, 
		    onSuccess: function(transport){
		    	//var clipObjects = transport.responseText.evalJSON();
			DMFormSent();
		    },
		    onFailure: function(){ alert('Sorry, an error occured when attempting to display new clips. Please try again.') } 
		  });
}

function DMFormSent() {
	
	$('dvDMSending').style.display = 'none';
	$('dvDMSent').style.display = 'block';

	$('txtDMNewMessage').value = '';
	
	//document.body.removeChild($('dvDMForm'));
	
}

function DMFormRender(iPmId, iUid, sUser, sSubject, sSource) {

	var oDiv = document.createElement('div');
	oDiv.id = 'dvDMForm';
	
	/*if (is_ie) {
		oDiv.setAttribute('cssText', 'display: none;');
	} else {
		oDiv.writeAttribute('style', 'display: none;');
	}*/
	
	var sHTML = '';
	sHTML += '<div id="dvDMFormContent" class="DMForm"><div id="dvDMSending"><span>Sending...</span></div><div id="dvDMSent"><span>Your message has been sent.</span></div>';
	sHTML += '<div class="Hd">';
	sHTML += '<img id="imgDMUser" src="http://content0.clipmarks.com/clog_avatar/' + iUid + '" /><div class="To">Send <span id="spnDMUser">' + sUser + '</span> a Direct Message';
	sHTML += '<div class="Sbj" id="dvDMSubject">' + (iPmId > 0 ? 'Re: ' : '') + sSubject + '</div></div>';
	sHTML += '</div>';
	sHTML += '<form><textarea name="txtDMNewMessage" id="txtDMNewMessage"' + (is_ie && iPmId == 0 ? ' style="width: 310px; height: 70px;"' : '') + '></textarea>';
	sHTML += '<div id="dvDMChars">' + iDMCharLimit + '</div>';
	sHTML += '<div class="Btn"><input type="button" name="btnDMSubmit" id="btnDMSubmit" value="Send" onclick="DMFormSend()" /></div>';
	sHTML += '<input type="hidden" name="hdnDMPmId" id="hdnDMPmId" value="' + iPmId + '" />';
	sHTML += '<input type="hidden" name="hdnDMRecipient" id="hdnDMRecipient" value="' + iUid + '" />';
	sHTML += '<input type="hidden" name="hdnDMSubject" id="hdnDMSubject" value="' + sSubject + '" />';
	sHTML += '<input type="hidden" name="hdnDMSource" id="hdnDMSource" value="' + sSource + '" /></form></div>';
	
	oDiv.innerHTML = sHTML;
	
	document.body.appendChild(oDiv);
}

function DMFormCharCounter(bTR) {
	var sText, iChars, obj;
	sText = (bTR ? $('txtTRMessage').getValue() : $('txtDMNewMessage').getValue());
	iChars = iDMCharLimit - sText.length;
	obj = (bTR ? $('dvTRChars') : $('dvDMChars'));
	
	if (iChars < 0) {
		obj.addClassName('CharsOver');
	} else {
		obj.removeClassName('CharsOver');
	}
	obj.update(iChars);
}

function DMFauxTb() {
	tb_show(null,'/#TB_inline?height=224&width=360&inlineId=dvDMForm',false);
	return false;
}



var iTRTot = 0;
var iTRTotSelected = 0;
var iTRTotSelectedShown = 0;
 
function TROpen(iPostId, sClipTitle, sSubject, sSource) { 
	
	if ($('dvTRForm')) {
		$('dvTRForm').remove();
		iTRTot = 0;
		iTRTotSelected = 0;
		iTRTotSelectedShown = 0;
	}
	
	//alert(iPostId);
	var oDiv = document.createElement('div');
	oDiv.id = 'dvTRForm';
	var sHTML = '<div id="dvTRFormContent" class="TRForm">';
	sHTML += '<div style="color: #aaa; font-size: 16px; margin: 20px; font-weight: bold;">Loading...</div>';
	sHTML += '</div>';
	oDiv.innerHTML = sHTML;	
	document.body.appendChild(oDiv);
	
	tb_show('Forward This Post','/#TB_inline?height=380&width=574&inlineId=dvTRForm',false);
	
	TRFormInit(iPostId, sClipTitle, sSubject, sSource);
	
	
	return false;
}


function TRFormInit(iPostId, sClipTitle, sSubject, sSource) {
	
	new Ajax.Request('/clog-ajax.php', 
	  {
	    method: 'GET',
	    parameters: { ajaxaction: 'ajax-function', af: 'friends_get_friends_info', results_per_page: '1000', show_who_follows: 'true', sortby: 'alpha' }, 
	    onSuccess: function(transport){
		    TRFormRender(iPostId, sClipTitle, sSubject, sSource, transport.responseText.evalJSON());
		    //tb_show(null,'/#TB_inline?height=340&width=610&inlineId=dvTRForm',false);
		    Event.observe('txtTRMessage', 'keyup', function(event) { DMFormCharCounter(true); });
		    Event.observe('txtTRMessage', 'keydown', function(event) { DMFormCharCounter(true); });
		    DMFormCharCounter(true);
	    },
	    onFailure: function(){ alert('Sorry, a connection error occured. Please try again.'); return false; } 
	  });
	  
	  //return;
	  
}

function TRFormRender(iPostId, sClipTitle, sSubject, sSource, oFriends) {

	//alert(oFriends);

	var sHTML = '';
	sHTML += '<div id="dvTRSending"><span>One moment...</span></div><div id="dvTRSent"></div>';
	sHTML += '<form style="padding: 0px; margin: 0px;">';
	sHTML += '<div class="Hd">' + sClipTitle + '</div>';
	//sHTML += '<div class="To">Please select followers you want to forward this to. (Will be sent to their Amplify Inbox)</div>';
	sHTML += '<div class="To">Please select whose inbox you want to forward this to.</div>';
	sHTML += '<div class="Selector">';
	
	//Selector here
	iTRTot = oFriends.length;
	var sName;
	
	//for (ii = 0; ii < 3; ii++) {
	for (i = 0; i < iTRTot; i++) {
		//alert(oFriends[i].frnd_friend_user_id + ' => ' + oFriends[i].display_name);		
		sName = oFriends[i].display_name;
		sHTML += '<div class="FriendDiv" id="dvTRFriend-' + i + '"><a href="#" class="Clicker" onclick="return TRSelect(' + oFriends[i].frnd_friend_user_id + ',' + i + ', \'' + sName.replace('\'', '\\\'') + '\');"></a>';
		sHTML += '<input type="checkbox" name="chkTRFriend-' + i + '" id="chkTRFriend-' + i + '" value="' + oFriends[i].frnd_friend_user_id + '" class="CB" />';
		sHTML += '<img src="http://content0.clipmarks.com/clog_avatar/' + oFriends[i].frnd_friend_user_id + '" alt="" title="" class="Pic" />';
		sHTML += '<div class="Name">' + sName + '</div>';
		sHTML += '</div>';
	}
	//}
	sHTML += '</div>';
	
	
	sHTML += '<div class="SelectedNames"><span id="spnToSelectedLabel">Selected:</span><span id="spnToSelected"></span></div>';
	
	
	sHTML += '<div class="Message"><div class="MessageHd">Add a personal message <span style="color: #999; font-style: italic; padding-left: 10px">optional</span></div>';
	sHTML += '<textarea name="txtTRMessage" id="txtTRMessage"></textarea>';
	sHTML += '<div id="dvTRChars">' + iDMCharLimit + '</div></div>';
	
	
	sHTML += '<div class="Btn"><input type="button" name="btnTRSubmit" id="btnTRSubmit" value="Forward" onclick="TRFormSubmit()" /></div>';
	sHTML += '<input type="hidden" name="hdnTRPostId" id="hdnTRPostId" value="' + iPostId + '" />';
	sHTML += '<input type="hidden" name="hdnTRClipTitle" id="hdnTRClipTitle" value="' + sClipTitle.replace('"', '\\"') + '" />';
	sHTML += '<input type="hidden" name="hdnTRSubject" id="hdnTRSubject" value="' + sSubject.replace('"', '\\"') + '" />';
	sHTML += '<input type="hidden" name="hdnTRSource" id="hdnTRSource" value="' + sSource + '" />';
	sHTML += '<input type="hidden" name="hdnTRTo" id="hdnTRTo" value="" />';
	sHTML += '</form>';
	
	$('dvTRFormContent').innerHTML = sHTML;
	
}

function TRSelect(iUid, iOrd, sName) {
	var bChecked = !($('chkTRFriend-' + iOrd).checked);
	
	$('chkTRFriend-' + iOrd).checked = bChecked;
	
	if (bChecked) {
		$('dvTRFriend-' + iOrd).addClassName('Act');
			
		iTRTotSelected++;
		
		//if (iTRTotSelected <= 7) {
		// insert node
			var sHTML = '<span class="Inner">' + sName + ' <a href="#" onclick="return TRSelect(' + iUid + ',' + iOrd + ', \'' + sName.replace('\'', '\\\'') + '\');">x</a></span> ';
			var oToName = new Element('span', { 'class': 'ToName', 'id': 'spnToName-' + iUid }).update(sHTML);
			$('spnToSelected').insert(oToName, 'bottom');
			iTRTotSelectedShown++;
		//}
		
	} else {
		$('dvTRFriend-' + iOrd).removeClassName('Act');
		
		iTRTotSelected--;

		// remove node
		if ($('spnToName-' + iUid)) {
			$('spnToName-' + iUid).remove();
			iTRTotSelectedShown--;
		}
	}

	/*
	if ($('spnToOver')) {
		$('spnToOver').remove();
	}
	*/
	
	/*
	if (iTRTotSelected > 7) {
		// insert node
		var iOver = parseInt(iTRTotSelected - 7);
		var sHTML = ' + ' + iOver + ' more';
		var oToOver = new Element('span', { 'class': 'ToOver', 'id': 'spnToOver' }).update(sHTML);
		$('spnToSelected').insert(oToOver, 'bottom');
	}
	*/
	
	//$('spnToEmpty').style.display = (iTRTotSelected > 0 ? 'none' : 'block');
	$('spnToSelectedLabel').style.display = (iTRTotSelected > 0 ? 'inline' : 'none');
		
	return false;
}



function TRFormSubmit() {

	var sRecIds = '';
	var iTRTotSent = 0;
	
	for (i = 0; i < iTRTot; i++) {
		if ($('chkTRFriend-' + i).checked) {
			sRecIds += $('chkTRFriend-' + i).getValue() + ',';
			iTRTotSent++;
		}
	}

	sRecIds = sRecIds.replace(/\,$/, '');
	
	if (sRecIds == '') {
		alert('Please select at least one person to recommend this post to...');
		return false;
	}
	
	//alert(sRecIds);

	if (is_ie) {
		$('dvTRSending').style.height = '382px';
		$('dvTRSent').style.height = '382px';
	}
	
	$('dvTRSending').style.display = 'block';
	
	new Ajax.Request('/clog-ajax.php',
	  {
	    method:'get',
	    //parameters: { ajaxaction: 'ajax-recommend-post', id: $('hdnTRPostId').getValue(), target: sRecIds }, 
	    parameters: {		    	
				ajaxaction: 'ajax-friend', 
			    	af: 'post_message', 
		    		message: $('txtTRMessage').getValue(), 
		    		recipient: sRecIds, 
				sourcetype: 'forward',
				sourcetitle: $('hdnTRClipTitle').getValue(),
				subject: $('hdnTRSubject').getValue(),  
		    		source: $('hdnTRSource').getValue(),
		    		inreplyto: 0
            },
	    onSuccess: function(transport){
		    
		    //transport.responseText.evalJSON()
		    
		    $('dvTRSending').style.display = 'none';
		    $('dvTRSent').innerHTML = '<span><div style="font-size: 15px; font-weight: bold; margin-bottom: 24px;">This has been forwarded to ' + iTRTotSent + ' of your followers.</div><div style="color: #778;">It has been sent to their Amplify inbox.</div></span>';
		    $('dvTRSent').style.display = 'block';
		    
		    
	    },
	    onFailure: function(){ alert('Something went wrong recommending...'); }
	  });
	  
	  return false;

}



