//////////////////////////////////////////////////////////////////////////////////////////////
/********************************************************************************************
POST SAVE TABS GUI CLASS (BUILDER AND ETC)
********************************************************************************************/
//////////////////////////////////////////////////////////////////////////////////////////////
PostSave.Tabs.GUI = {};

///////////////////////////////////////
/**************************************
STATIC
**************************************/
///////////////////////////////////////
PostSave.Tabs.GUI.isAjaxSent = false;
PostSave.Tabs.GUI.ajax = null;
PostSave.Tabs.GUI.currentTabName = '';
PostSave.Tabs.GUI.builtTabsSession = null;
PostSave.Tabs.GUI.buildTabsCurrent = null;
PostSave.Tabs.GUI.isFirstTabBuilt = false;
PostSave.Tabs.GUI.setBuiltTabsSession = function(activity)
{
	if (PostSave.Tabs.GUI.builtTabsSession === null)
		PostSave.Tabs.GUI.builtTabsSession = new Array();
	
	var l = activity.tabs.length;
	var tabName = '';
	for (i=0;i<l;++i)
	{
		tabName = activity.tabs[i];
		// initiating value //
		if (typeof(PostSave.Tabs.GUI.builtTabsSession[tabName]) === 'undefined')
			PostSave.Tabs.GUI.builtTabsSession[tabName] = false;
		// if it has already been built and needs to be built once per session //
		else if (PostSave.Tabs.GUI.builtTabsSession[tabName] && PostSave.Tabs[tabName].isBuiltOncePerSession)
			PostSave.Tabs.GUI.builtTabsSession[tabName] = true;
		// if it has already been built and item string and activity are equal and in SHARE MODE //
		else if (PostSave.Tabs.GUI.builtTabsSession[tabName] && PostSave.Items.lastItemString === PostSave.Items.currItemString && PostSave.shareMode)
			PostSave.Tabs.GUI.builtTabsSession[tabName] = true;
		else
			PostSave.Tabs.GUI.builtTabsSession[tabName] = false;
	}
}


PostSave.Tabs.GUI.setBuiltTabsCurrent = function(activity)
{
	//// cleaning array ////
	if (PostSave.Tabs.GUI.buildTabsCurrent === null)
		PostSave.Tabs.GUI.buildTabsCurrent = new Array();
	else
		PostSave.Tools.cleanArray(PostSave.Tabs.GUI.buildTabsCurrent);
	
	//// inserting values ////
	var l = activity.tabs.length;
	var tabName = '';
	for (i=0;i<l;++i)
	{
		tabName = activity.tabs[i];
		PostSave.Tabs.GUI.buildTabsCurrent[tabName] = false;
	}
	
	//// updating isFirstTabBuilt flag ////
	PostSave.Tabs.GUI.isFirstTabBuilt = false;
}

PostSave.Tabs.GUI.showByName = function(tabName)
{
	if (tabName !== 'GSMail') {
		PostSave.Tabs.GUI.GSMail.mailSentFlag = false;
	}
	
	if (typeof(PostSave.Activities.currentActivity.hashTabs[tabName]) !== 'undefined')
	{
		/// if the tab wasn't built in this session ///
		if (!PostSave.Tabs.GUI.builtTabsSession[tabName])
		{
			PostSave.Tabs[tabName].build();
			PostSave.Tabs.GUI.builtTabsSession[tabName] = true;
		}
		/// if the tab was built in this session but didn't built in this "show" ///
		else if (!PostSave.Tabs.GUI.buildTabsCurrent[tabName])
		{
			PostSave.Tabs[tabName].update();
			if (!PostSave.Tabs[tabName].isBuiltEveryTime)
				PostSave.Tabs.GUI.buildTabsCurrent[tabName] = true;
		}
		
		/// updating menu (only if items downloaded) ///
		if (PostSave.isItemsDownloaded)
			PostSave.GUI.updateMenu(PostSave.Tabs.GUI.currentTabName, tabName);
			
		/// showing tab and hiding previous tab ///
		if (PostSave.Tabs.GUI.currentTabName !== '')
			PostSave.Tabs.GUI.hideByName(PostSave.Tabs.GUI.currentTabName);
		PostSave.Tabs[tabName].pointer.style.display = "block";
		PostSave.Tabs[tabName].pointer.style.visibility = "visible";
		
		/// saving current tab ///
		PostSave.Tabs.GUI.currentTabName = tabName;
		if (tabName !== PostSave.TABS.DONE)
			PostSave.Tabs.GUI.Done.lastTab = tabName;
		
		/// running post build/update functions ///
		PostSave.Tabs[tabName].onShow();
		
		/// sending stats ///
		PostSave.Stats.send(tabName + '/view');
		
		/// PostSave.Tabs.GUI.isFirstTabBuilt flag //
		PostSave.Tabs.GUI.isFirstTabBuilt = true;
	}
}

PostSave.Tabs.GUI.showDownloadTab = function()
{
	/// sending stats ///
	PostSave.Stats.send(PostSave.Tabs.GUI.currentTabName + '/download');
	
	/// showing download tab ///
	PostSave.Tabs.GUI.showByName(PostSave.TABS.DOWNLOAD);
}

PostSave.Tabs.GUI.showDoneTabFirst = function()
{
	/// saving last tab (so done tab will show the correct links ) ///
	PostSave.Tabs.GUI.Done.lastTab = PostSave.TABS.NOTES;
	
	/// saving menu (nothing is picked) ///
	PostSave.GUI.updateMenu(PostSave.Tabs.GUI.Done.lastTab);
	
	/// showing done tab ///
	PostSave.Tabs.GUI.showByName(PostSave.TABS.DONE);	
}

PostSave.Tabs.GUI.hideByName = function(tabName)
{
	PostSave.Tabs[tabName].pointer.style.display = "none";
	PostSave.Tabs[tabName].pointer.style.visibility = "hidden";
	PostSave.Tabs[tabName].onHide();
}


PostSave.Tabs.GUI.showByIndex = function(tabIndex)
{
	tabIndex = tabIndex || 0;
	if (typeof(PostSave.Activities.currentActivity.tabs[tabIndex]) !== 'undefined')
		PostSave.Tabs.GUI.showByName(PostSave.Activities.currentActivity.tabs[tabIndex]);
}


PostSave.Tabs.GUI.insertToSkeleton = function(left, right)
{
	var htmlA = new Array();
	htmlA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
		htmlA.push("<tr>");

			///// [tab left content] /////
			htmlA.push("<td class='PostSave_TabContentLeft' valign='top'>");
				htmlA.push(left);
			htmlA.push("</td>");
			
			///// [space] /////
			htmlA.push("<td class='width30'>&nbsp;</td>");

			///// [tab right content] /////
			htmlA.push("<td class='PostSave_TabContentRight' valign='top'>");
				htmlA.push(right);
			htmlA.push("</td>");

		htmlA.push("</tr>");
	htmlA.push("</table>");
	
	return htmlA.join("");
}

PostSave.Tabs.GUI.idCheck = function(checkbox)
{
	var imgNode = checkbox.previousSibling;
	while (imgNode.tagName !== "IMG" && imgNode.tagName !== null)
	{
		imgNode = pNode.previousSibling;
	}
	
	if (imgNode.tagName === null)
		return;

		
	if (checkbox.checked)
	{
		imgNode.style.filter = "alpha(opacity=100)"; //ie
		imgNode.style.opacity = 1;  //non-ie
	}
	else
	{
		imgNode.style.filter = "alpha(opacity=33)"; //ie
		imgNode.style.opacity = 33/100;  //non-ie
	}
}

PostSave.Tabs.GUI.resetCheckBox = function(_form)
{
	var checkBoxArray = _form.item;
	var l = checkBoxArray.length;
	for (var i=0;i<l;++i)
	{
		checkBoxArray[i].checked = true;
		PostSave.Tabs.GUI.idCheck(checkBoxArray[i]);
	}
}


PostSave.Tabs.GUI.buildNoThanks = function(tabName)
{
	var buffer = new Array();
	buffer.push("<td><a href=\"javascript:PostSave.Tabs.GUI.showByName('Done')\" class='postSaveLink' onclick=\"javascript:PostSave.Stats.send("+tabName+"/no thanks');\">No Thanks</a></td>");
	buffer.push("<td width='30px'>&nbsp;</td>");
	
	return buffer.join("");
}


PostSave.Tabs.GUI.showPleaseWait = function(id)
{
	var _src = '/javascripts/postSave/images/pleasewait';
	var flashElement = GET_AC_FL_RunContent(
		'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0',
		'width', 24,
		'height', 24,
		'src', _src,
		'quality', 'best',
		'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
		'align', 'middle',
		'play', 'true',
		'loop', 'true',
		'scale', 'showall',
		'wmode', 'transparent',
		'devicefont', 'false',
		'id', 'pleaseWait',
		'bgcolor', '#fff5fa',
		'name', 'pleaseWait',
		'menu', 'true',
		'allowScriptAccess','sameDomain',
		'movie', _src,
		'salign', '',
		'swliveconnect', 'true',
		'flashvars', ''
	);
	
	document.getElementById(id).innerHTML = flashElement;
}

PostSave.Tabs.GUI.hidePleaseWait = function(id)
{
	document.getElementById(id).innerHTML = '';	
}



PostSave.Tabs.GUI.ajaxRequestFail = function(request)
{
	PostSave.Tabs.GUI.isAjaxSent = false;
	
	var splittedParams = request.params.split("&amp;");
	var action = splittedParams[0].split("=")[1];
	
	switch (action)
	{
		
		case "getFriendList":
				PostSave.Tabs.GUI.GSNote.friendsHTML = '';
				PostSave.Tabs.GUI.GSNote.friendsCount = 0;
				PostSave.Tabs.GUI.GSNote.gotFriends = true;
				PostSave.Tabs.GUI.GSNote.friendsEvent.dispatch("Friends");
			break;
		case "sendNotePostSave":
			alert('Request has failed. Please try again later.');
			PostSave.Tabs.GUI.hidePleaseWait('postSave_note_pleaseWait');
			break;		
		case "sendMailPostSave":
			alert('Request has failed. Please try again later.');
			PostSave.Tabs.GUI.hidePleaseWait('postSave_mail_pleaseWait');
			break;
		default:
			alert('Request has failed. Please try again later.');
			break;
		
	}
	
	
}

//////////////////////////////////////////////////////////////////////////////
/*****************************************************************************
TABS FUNCTIONS
*****************************************************************************/
//////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////
/**************************************
PLEASE WAIT
**************************************/
///////////////////////////////////////
PostSave.Tabs.GUI.PleaseWait = {};
PostSave.Tabs.GUI.PleaseWait.build = function()
{
	var _src = '/javascripts/postSave/images/pleasewait';
	var flashElement = GET_AC_FL_RunContent(
		'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0',
		'width', 24,
		'height', 24,
		'src', _src,
		'quality', 'best',
		'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
		'align', 'middle',
		'play', 'true',
		'loop', 'true',
		'scale', 'showall',
		'wmode', 'transparent',
		'devicefont', 'false',
		'id', 'pleaseWait',
		'bgcolor', '#fff5fa',
		'name', 'pleaseWait',
		'menu', 'true',
		'allowScriptAccess','sameDomain',
		'movie', _src,
		'salign', '',
		'swliveconnect', 'true',
		'flashvars', ''
	);
	
	
	var html = flashElement + "&nbsp;&nbsp;&nbsp;&nbsp;PLEASE WAIT...<br/><br/>";
	
	//////////// [ INSERTING TO HTML ] ////////////
	PostSave.Tabs[this.name].pointer.innerHTML = '';
	PostSave.Tabs[this.name].pointer.innerHTML = html;
	
	
}

///////////////////////////////////////
/**************************************
GSMAIL
**************************************/
///////////////////////////////////////
PostSave.Tabs.GUI.GSMail = {};
PostSave.Tabs.GUI.GSMail.mailSentFlag = false;
PostSave.Tabs.GUI.GSMail.build = function()
{
	var plaxoLink = "javascript:showPlaxoABChooser(\"importedEmails\", \"/javascripts/postSaveV2/plaxo_cb.html\")";
	var tabName = this.name;
	var activity = PostSave.Activities.currentActivity;

	var doItLink = '';
	var title = '';
	if (PostSave.shareActivityMode)
	{
		doItLink = activity.inviteMailLink
		title = activity.inviteMailTitle;
	}
	else
	{
		var dirName = General.getDirName(PostSave.Items.array[0].key, PostSave.Activities.currentActivity.dirNameDepth);
		doItLink = activity.mailDoItLinkTitle.replace("%item%", dirName + "/" + PostSave.Items.array[0].key) + activity.extension;
		title = activity.tabTitle + " by Email";
	}
	
	//////////// [ RIGHT ] ////////////
	var rightA = new Array();
	rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
		rightA.push("<tr>");
			//~ rightA.push("<td class='width30' valign='top'>");
				//~ rightA.push("<img src='"+PostSave.Images.array['emailIcon'].src+"' />");
			//~ rightA.push("</td>");
			//~ rightA.push("<td class='width10'>&nbsp;</td>");
			rightA.push("<td valign='top'>");
				rightA.push("<form id='postSave_form"+tabName+"' name='postSave_form"+tabName+"' action='postSave.pl' method='post' onsubmit='javascript: return false;'>");
				rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
					/// title
					rightA.push("<tr><td><h1 class='postSave_tabDiv_h1' id='postSaveTitle_mail'>"+title+"</h1></td></tr>");
					/// space
					rightA.push("<tr><td height='10px'></td></tr>");
					/// explanation
					rightA.push("<tr><td>");
						rightA.push("<h4 class='postSave_tabDiv_explanation'>myWebFace will send out e-mails for you. Click <a href='"+plaxoLink+"' title='Import your address book' id='postSave_email_"+tabName+"_importSmall' onclick=\"javascript:PostSave.Stats.send('"+tabName+"/importSmall');\">here</a> to import your address book. Separate addresses with a space. Read our <a href='http://home.mywebface.com/support/privacy.htm' title='myWebFace Privacy Policy' class='gray9 font12' target='_blank'>Privacy Policy</a></h4>");
					rightA.push("</td></tr>");
					/// space
					rightA.push("<tr><td height='30px'><div id='emailSentMsgDiv'></div></td></tr>");
					/// email
					rightA.push("<tr><td><h5 class='postSave_fieldTitle'>E-mail Addresses:</h5></td></tr>");
					rightA.push("<tr><td valign='top'>");
						rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
							rightA.push("<tr>");
								rightA.push("<td valign='top'>");
									rightA.push("<textarea name='emails' class='postSave_textbox' ></textarea>");
									rightA.push("<input type='hidden' name='importedEmails' id='importedEmails' />");
								rightA.push("</td>");
								rightA.push("<td valign='top' align='left'>");
									rightA.push("<a href='"+plaxoLink+"' title='Import your address book' id='postSave_email_"+tabName+"_importBig' onclick=\"javascript:PostSave.Stats.send('"+tabName+"/importBig');\"><img src='"+PostSave.Images.array['addressBook'].src+"' border='0' /></a>");
								rightA.push("</td>");
								rightA.push("<td width='140px'>&nbsp;</td>");
							rightA.push("</tr>");
						rightA.push("</table>");
					rightA.push("</td></tr>");
					/// space
					rightA.push("<tr><td height='10px'></td></tr>");
					/// name
					rightA.push("<tr><td><h5 class='postSave_fieldTitle'>Your name:</h5></td></tr>");
					rightA.push("<tr><td><input type='text' name='name' maxlength='30' class='postSave_textInput_short' /></td></tr>");
					/// space
					rightA.push("<tr><td height='20px'></td></tr>");
					/// send
					rightA.push("<tr><td>");
						rightA.push("<table cellspacing='0' cellpadding='0' border='0'>");
							rightA.push("<tr>");
								rightA.push("<td valign='top'><a href='javascript:PostSave.Tabs.GUI.GSMail.send()' title='Send'><img border='0' src='"+PostSave.Images.array['sendEmail'].src+"' /></a></td>");
								rightA.push("<td width='30px'>&nbsp;</td>");
								// adding NO THANKS if its the first tab and NOT in share activity mode //
								if (!PostSave.Tabs.GUI.isFirstTabBuilt && !PostSave.shareActivityMode) 
									rightA.push(PostSave.Tabs.GUI.buildNoThanks(tabName));
								rightA.push("<td id='postSave_mail_pleaseWait' width='24px'>&nbsp;</td>");
							rightA.push("</tr>");
						rightA.push("</table>");
					rightA.push("</td></tr>");
					/// space
					rightA.push("<tr><td height='35px'></td></tr>");
					/// do it your own way
					rightA.push("<tr><td><h5 class='postSave_fieldTitle'>Do it your own way:</h5></td></tr>");
					rightA.push("<tr><td><h6 class='postSave_tabDiv_explanation'>Copy the link below and send it via your own account or Instant Messaging Program</h5></td></tr>");
					rightA.push("<tr><td height='5px'></td></tr>");
					rightA.push("<tr><td height='22px' valign='top'>");
						rightA.push("<table width='250px' cellspacing='0' cellpadding='0' border='0'>");
							rightA.push("<tr>");
								rightA.push("<td><input type='text' readonly='readonly' value='"+doItLink+"' onclick='this.select()' name='url' class='postSave_textInput_long_mail'/></td>");
								rightA.push("<td width='10px'>&nbsp;</td>");
								rightA.push("<td><a href='javascript:PostSave.Tabs.GUI.GSMail.copyToClipboard()' id='postSave_email_"+tabName+"_copyToClipboard' onclick=\"javascript:PostSave.Stats.send('"+tabName+"/copy');\"><img src='"+PostSave.Images.array['copyToClipboard'].src+"' border='0' /></a></td>");
							rightA.push("</tr>");
						rightA.push("</table>");
					rightA.push("</td></tr>");
					rightA.push("<tr><td height='5px'></td></tr>");
					rightA.push("<tr><td>");
						rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
							rightA.push("<tr>");
								rightA.push("<td width='20px'><a href='http://mail.yahoo.com' target='_blank' title='Yahoo! mail' id='postSave_email_"+tabName+"_yahoo' onclick=\"javascript:PostSave.Stats.send('"+tabName+"/mailClient/yahoo');\"><img src='"+PostSave.Images.array['yahoo'].src+"' border='0' alt='Yahoo! mail'/></a></td>");
								rightA.push("<td width='5px'>&nbsp;</td>");
								rightA.push("<td width='20px'><a href='http://www.hotmail.com' target='_blank' title='Hotmail mail' id='postSave_email_"+tabName+"_hotmail' onclick=\"javascript:PostSave.Stats.send('"+tabName+"/mailClient/hotmail');\"><img src='"+PostSave.Images.array['hotmail'].src+"' border='0' alt='Hotmail'/></a></td>");
								rightA.push("<td width='5px'>&nbsp;</td>");
								rightA.push("<td width='20px'><a href='http://webmail.aol.com' target='_blank' title='Aol mail' id='postSave_email_"+tabName+"_aol' onclick=\"javascript:PostSave.Stats.send('"+tabName+"/mailClient/aol');\"><img src='"+PostSave.Images.array['aol'].src+"' border='0' alt='AOL mail'/></a></td>");
								rightA.push("<td width='5px'>&nbsp;</td>");
								rightA.push("<td width='20px'><a href='http://www.gmail.com' target='_blank' title='Gmail' id='postSave_email_"+tabName+"_gmail' onclick=\"javascript:PostSave.Stats.send('"+tabName+"/mailClient/gmail');\"><img src='"+PostSave.Images.array['gmail'].src+"' border='0' alt='Gmail'/></a></td>");
								rightA.push("<td width='5px'>&nbsp;</td>");
								rightA.push("<td width='20px'><a href='mailto:&subject="+doItLink+"' id='postSave_email_"+tabName+"_outlook' target='_blank' title='Outlook' onclick=\"javascript:PostSave.Stats.send('"+tabName+"/mailClient/outlook');\"><img src='"+PostSave.Images.array['outlook'].src+"' border='0' alt='Outlook'/></a></td>");
								rightA.push("<td>&nbsp;</td>");
							rightA.push("</tr>");
						rightA.push("</table>");
					rightA.push("</td></tr>");
				rightA.push("</table>");
				rightA.push("</form>");
			rightA.push("</td>");
		rightA.push("</tr>");
	rightA.push("</table>");
	
	//////////// [ LEFT ] ////////////
	var leftA = new Array();
	leftA.push("<form id='postSave_mailForm_right' name='postSave_formRight"+tabName+"' action='postSave.pl' method='post' onsubmit='javascript: return false;'>");
		leftA.push("<div id='postSave_mailRightContent'>");
			leftA.push(activity.getLeftPart(tabName));
		leftA.push("</div>");
	leftA.push("</form>");
	
	//////////// [ SKELETON ] ////////////
	var html = PostSave.Tabs.GUI.insertToSkeleton(leftA.join(""),rightA.join(""));
	
	//////////// [ INSERTING TO HTML ] ////////////
	PostSave.Tabs[tabName].pointer.innerHTML = '';
	PostSave.Tabs[tabName].pointer.innerHTML = html;
}


PostSave.Tabs.GUI.GSMail.copyToClipboard = function()
{
	if (General.browser === 'ie6' || General.browser === 'ie7' || General.browser === 'ie8')
	{
		var _text = document.forms['postSave_form' + PostSave.Tabs.GUI.currentTabName].url.value;
		window.clipboardData.setData('Text',_text);
	}
	else
	{
		alert("Copy to cilpboard option works only in Internet Explorer browser.\n Please copy it manualy");
	}
	
}

PostSave.Tabs.GUI.GSMail.processPlaxo = function()
{
	var plaxoRecipientsField = document.forms['postSave_form' + PostSave.Tabs.GUI.currentTabName].importedEmails.value.replace(/^\s+|\s+$/g,"");
	if (plaxoRecipientsField === '' || plaxoRecipientsField === null)
		return;
		
	var recipientsField = document.forms['postSave_form' + PostSave.Tabs.GUI.currentTabName].emails.value.replace(/^\s+|\s+$/g,"");
		
	var recipientsArr = plaxoRecipientsField.split(",");
	var emailAdd = '';
	
	for (var i=0;i<recipientsArr.length;i++)
	{
		var details_array = recipientsArr[i].split(" <");	
		emailAdd = details_array[1];
		emailAdd = emailAdd.replace(/>/gi, "");
		
		if (recipientsField !== '')
			recipientsField += " ";
		
		recipientsField += emailAdd;
	}
	document.forms['postSave_form' + PostSave.Tabs.GUI.currentTabName].emails.value = recipientsField;
}

PostSave.Tabs.GUI.GSMail.check = function(email)
{
	var emailPat = /^[\w-_\&.]+\@[\w-_]+\.+[\w-_.]+$/;
	var matchArray = email.match(emailPat);
	return (!(matchArray == null) && (email.indexOf('..') === -1));
}

PostSave.Tabs.GUI.GSMail.send = function()
{
	if (PostSave.Tabs.GUI.isAjaxSent)
		return;
	PostSave.Tabs.GUI.isAjaxSent = true;
	
	////sender
	var sender = document.forms['postSave_form' + PostSave.Tabs.GUI.currentTabName].name.value.replace(/^\s+|\s+$/g,"");
	if (sender === '')
	{
		alert('What is your name?');
		PostSave.Tabs.GUI.isAjaxSent = false;
		return;	
	}
	
	////////// PLEASE WAIT ////
	PostSave.Tabs.GUI.showPleaseWait('postSave_mail_pleaseWait');
	
	BlackFilterAjax.onResult = function(text, responseText)
	{
		if (responseText !== "OK")
		{
			if (responseText.replace(/^\s+|\s+$/g,"") !== "")
				alert('Your name is not appropriate');
				
			PostSave.Tabs.GUI.isAjaxSent = false;
			PostSave.Tabs.GUI.hidePleaseWait('postSave_mail_pleaseWait');
		}
		else
		{
			PostSave.Tabs.GUI.GSMail.sendAfterApprove();
		}
	}
	
	/// checking ///
	BlackFilterAjax.check(sender);
}
	
PostSave.Tabs.GUI.GSMail.sendAfterApprove = function()
{
	var recipientsField = document.forms['postSave_form' + PostSave.Tabs.GUI.currentTabName].emails.value.replace(/^\s+|\s+$/g,"");
	
	if (recipientsField === '')
	{
		alert('Please send to someone');	
		return;
	}
	
	////emails string
	recipientsField = recipientsField.replace(/\n/, " ");
	var recipArr = recipientsField.split(' ');
	var emailStr = '';
	var r = new RegExp();
	var r1 = new RegExp();
	for (var i=0; i<recipArr.length;i++)
	{
		if (PostSave.Tabs.GUI.GSMail.check(recipArr[i]))
		{
			r.compile("^"+recipArr[i]+"$","i");
			r1.compile("\,"+recipArr[i]+"|" + recipArr[i] + "\,","i");
			if (r.test(emailStr) || r1.test(emailStr))
			{
				alert('Some of the e-mail addresses are identical. Please fix and try again');
				PostSave.Tabs.GUI.isAjaxSent = false;
				return;
			}
			
			if (emailStr !== '')
				emailStr += ",";
				
			emailStr += recipArr[i];	
		}
		else
		{
			alert("email address incorrect: " + recipArr[i]);
			PostSave.Tabs.GUI.isAjaxSent = false;
			return;
		}
	}
	
	var totalEmailsArr = emailStr.split(",");
	emailStr = escape(emailStr);
	
	var sender = document.forms['postSave_form' + PostSave.Tabs.GUI.currentTabName].name.value.replace(/^\s+|\s+$/g,"");
	sender = escape(sender);
	
	//// [ids] ////
	var ids = '';
	if (!PostSave.shareActivityMode)
	{
		var numOfItems = PostSave.Items.array.length;
		var key;
		var idsChecked = 0;
		var _form = document.forms['postSave_mailForm_right'];
		for (var i=0; i<numOfItems;i++)
		{
			if (numOfItems > 1)
			{
				if (_form.item[i].checked)
				{
					key = escape(PostSave.Items.array[i].key)
					ids += "&amp;id"+idsChecked+"="+key;
					idsChecked++;
				}
			}
			else
			{
				key = escape(PostSave.Items.array[i].key)
				ids += "&amp;id"+idsChecked+"="+key;
			}
		}
		
		if (ids === '')
		{
			alert('Please pick what to send');
			PostSave.Tabs.GUI.isAjaxSent = false;
			return;	
		}
	}
	
	
	///////// [ STATISTICS ] /////////
	PostSave.Stats.send(PostSave.Tabs.GUI.currentTabName + '/counts/' + (totalEmailsArr.length)); 
	
	///////////////// Ajax ////////////////
	var activityForMail = PostSave.Activities.currentActivity.name;
	// if activity share //
	if (PostSave.shareActivityMode)
		activityForMail = PostSave.Activities.currentActivity.name + "_generic";
	
	var params = "action=sendMailPostSave&amp;app="+activityForMail;
	params += "&amp;sender="+sender+"&amp;isShare="+PostSave.shareMode+"&amp;emails="+emailStr+ids;
	params += "&amp;nickname=" + PostSave.User.nicknameCreator;
		
	PostSave.Tabs.GUI.ajax.onSuccessFunction = PostSave.Tabs.GUI.GSMail.sendReply;
	PostSave.Tabs.GUI.ajax.start(params);
}


PostSave.Tabs.GUI.GSMail.sendReply = function(request)
{
	PostSave.Tabs.GUI.isAjaxSent = false;
	
	if (request.responseText === 'ok') {
		//~ PostSave.Tabs.GUI.showByName(PostSave.TABS.DONE);
		//~ alert("action done");
		PostSave.Tabs.GUI.GSMail.mailSentFlag = true;
		PostSave.Tabs.GUI.showByName(PostSave.TABS.MAIL);
	}	
	else {
		alert("Error. please try to send later");
		PostSave.Tabs.GUI.GSMail._reset();
	}
}

PostSave.Tabs.GUI.GSMail._reset = function()
{
	var _f = document.forms['postSave_form'+ PostSave.Tabs.GUI.currentTabName];
	_f.emails.value = '';
	_f.name.value = '';
	
	///// if not in share activity tab, reseting checkboxes values (if any?) /////
	if (!PostSave.shareActivityMode)
	{
		var l = PostSave.Items.array.length;
		if (l > 1)
			PostSave.Tabs.GUI.resetCheckBox(document.forms['postSave_formRight'+ PostSave.Tabs.GUI.currentTabName]);
	}
	
	////////// PLEASE WAIT ////
	PostSave.Tabs.GUI.hidePleaseWait('postSave_mail_pleaseWait');
}

PostSave.Tabs.GUI.GSMail.onHide = function()
{
	// resetting values //
	PostSave.Tabs.GUI.GSMail._reset();
}

PostSave.Tabs.GUI.GSMail.onShow = function()
{
	// enabling textboxes //
	var _f = document.forms['postSave_form' + this.name];
	_f.url.disabled = false;
	_f.emails.disabled = false;
	_f.name.disabled = false;
	
	// updating sent mail text //
	PostSave.Tabs.GUI.GSMail.updateSentMailText();
	
	try
	{
		_f.emails.focus();
	}
	catch(e){};
}

PostSave.Tabs.GUI.GSMail.update = function()
{
	var activity = PostSave.Activities.currentActivity;
	
	// updating do it link //
	var dirName = General.getDirName(PostSave.Items.array[0].key, PostSave.Activities.currentActivity.dirNameDepth);
	var doItLink = activity.mailDoItLinkTitle.replace("%item%", dirName + "/" + PostSave.Items.array[0].key);
	document.forms['postSave_form' + this.name].url.value = doItLink + activity.extension;
	
	// updating title //
	document.getElementById('postSaveTitle_mail').innerHTML = activity.tabTitle + " by Email";
	
	// updating sent mail text //
	PostSave.Tabs.GUI.GSMail.updateSentMailText();
	
	// updating outlook link + gas //
	document.getElementById('postSave_email_'+this.name+'_outlook').href = "mailto:&subject="+activity.mailDoItLinkTitle;
	
	// updating GAS //
	document.getElementById('postSave_email_'+this.name+'_outlook').onclick = "javascript:PostSave.Stats.send('"+this.name+"/mailClient/outlook');";
	document.getElementById('postSave_email_'+this.name+'_gmail').onclick = "javascript:PostSave.Stats.send('"+this.name+"/mailClient/gmail');";
	document.getElementById('postSave_email_'+this.name+'_aol').onclick = "javascript:PostSave.Stats.send('"+this.name+"/mailClient/aol');";
	document.getElementById('postSave_email_'+this.name+'_hotmail').onclick = "javascript:PostSave.Stats.send('"+this.name+"/mailClient/hotmail');";
	document.getElementById('postSave_email_'+this.name+'_yahoo').onclick = "javascript:PostSave.Stats.send('"+this.name+"/mailClient/yahoo');";
	document.getElementById('postSave_email_'+this.name+'_copyToClipboard').onclick = "javascript:PostSave.Stats.send('"+this.name+"/copy');";
	document.getElementById('postSave_email_'+this.name+'_importBig').onclick = "javascript:PostSave.Stats.send('"+this.name+"/importBig');";
	document.getElementById('postSave_email_'+this.name+'_importSmall').onclick = "javascript:PostSave.Stats.send('"+this.name+"/importSmall');";
	
	// updating right side //
	PostSave.Tabs.GUI.GSMail.updateLeft(this.name);
}

PostSave.Tabs.GUI.GSMail.updateSentMailText = function()
{
	// updating sent mail text //
	if (PostSave.Tabs.GUI.GSMail.mailSentFlag) {
		document.getElementById('emailSentMsgDiv').style.display = "block";
		document.getElementById('emailSentMsgDiv').innerHTML = "<span id='emailSentMsgText'>Your Email has been sent</span>";
	}
	else {
		document.getElementById('emailSentMsgDiv').innerHTML = "";
		document.getElementById('emailSentMsgDiv').style.display = "none";
	}

}

PostSave.Tabs.GUI.GSMail.updateLeft = function(name)
{
	name = name || this.name;
	document.getElementById('postSave_mailRightContent').innerHTML = PostSave.Activities.currentActivity.getLeftPart(name);	
}


///////////////////////////////////////
/**************************************
DOWNLOAD
**************************************/
///////////////////////////////////////
PostSave.Tabs.GUI.Download = {};
PostSave.Tabs.GUI.Download.build = function()
{
	var activity = PostSave.Activities.currentActivity;
	
	//////////// [ RIGHT ] ////////////
	var rightA = new Array();
	rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
		rightA.push("<tr>");
			//~ rightA.push("<td class='width30' valign='top'>");
				//~ rightA.push("<img src='"+PostSave.Images.array['downloadIcon'].src+"' />");
			//~ rightA.push("</td>");
			//~ rightA.push("<td class='width10'>&nbsp;</td>");
			rightA.push("<td valign='top'>");
				rightA.push("<form id='postSave_downloadForm' name='postSave_downloadForm' action='postSave.pl' method='post' onsubmit='javascript: return false;' target='_top'>");
				rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
					/// title
					rightA.push("<tr><td><h1 class='postSave_tabDiv_h1'>Download to Desktop</h1></td></tr>");
					/// space
					rightA.push("<tr><td height='5px'></td></tr>");
					/// instructions
					rightA.push("<tr><td><h4 class='postSave_tabDiv_explanation'>Save your creation as a picture on your computer.</h4></td></tr>");
					/// space
					rightA.push("<tr><td height='10px'></td></tr>");
					///items
					var numOfItems = PostSave.Items.array.length;
					if (numOfItems > 1)
					{
						rightA.push("<tr><td>");
							rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
								rightA.push("<tr>");
									var imgOpClass = '';
									for (var i=0; i<numOfItems;i++)
									{
										if (i === 0)
											imgOpClass = 'postSave_downloadImg_sel';
										else
											imgOpClass = 'postSave_downloadImg_unsel';
											
										rightA.push("<td>");
											rightA.push("<div class='postSave_id_div_small' onclick='javascript:PostSave.Tabs.GUI.Download.imagePicked("+i+")' style='cursor:pointer;'>");
												rightA.push("<img src='"+PostSave.Items.array[i].small.src+"' class='"+imgOpClass+"' id='postSave_download_image"+i+"'/>");
											rightA.push("</div>");
										rightA.push("</td>");
									}	
								rightA.push("</tr>");
							rightA.push("</table>");
						rightA.push("</td></tr>");
					}
					/// space
					rightA.push("<tr><td height='10px'></td></tr>");
					/// file name
					rightA.push("<tr><td><h5 class='postSave_fieldTitle'>File name:</h5></td></tr>");
					rightA.push("<tr><td><input type='text' name='filename' class='postSave_textInput_long2' value='' /></td></tr>");
					/// space
					rightA.push("<tr><td height='20px'></td></tr>");
					/// how to save to computer ///
					rightA.push("<tr><td><h5 class='postSave_fieldTitle'>How to save to computer:</h5></td></tr>");
					rightA.push("<tr><td height='5px'></td></tr>");
					rightA.push("<tr>");
						rightA.push("<td><ol class='facebookOL'>");
							rightA.push("<li>Click <b>\"Save to computer\"</b></li>");
							rightA.push("<li>Click <b>Save</b></li>");
							rightA.push("<li>Choose where you\'d like to save your cartoon face - <b>Desktop recommended</b> (IE browsers) </li>");
							rightA.push("<li>Click <b>Save</b> button</li>");
						rightA.push("</ol></td>");
					rightA.push("</tr>");
					/// space ///
					rightA.push("<tr><td height='10px'></td></tr>");
					/// how to change your profile pic on FB ///
					rightA.push("<tr><td><h5 class='postSave_fieldTitle'>How to change your profile picture on Facebook:</h5></td></tr>");
					rightA.push("<tr><td height='5px'></td></tr>");
					rightA.push("<tr>");
						rightA.push("<td><ol class='facebookOL'>");
							rightA.push("<li>Click Change Picture on your FB profile</li>");
							rightA.push("<li>Choose Upload a Picture</li>");
							rightA.push("<li>Click Browse to locate your myWebFace avatar on your computer</li>");
							rightA.push("<li>Search through the picture files on your computer to find your picture</li>");
							rightA.push("<li>Click Open to add picture to your profile</li>");
						rightA.push("</ol></td>");
					rightA.push("</tr>");
					/// space
					rightA.push("<tr><td height='25px'></td></tr>");
					///// SAVE TO COMPUTER ////		
					General.setRandomWWW();
					rightA.push("<tr><td><a href='javascript:PostSave.Tabs.GUI.Download.download()' title='Save To Desktop' id='postSave_download_downloadBtn' target='_self'><img src='"+PostSave.Images.array['downloadSave'].src+"' border='0' alt='download' /></a></td></tr>");
					
				rightA.push("</table>");
				rightA.push("</form>");
			rightA.push("</td>");	
		rightA.push("</tr>");
	rightA.push("</table>");
	
	//////////// [ LEFT ] ////////////
	var leftA = new Array();
	leftA.push(activity.getLeftPart(this.name));
	
	//////////// [ SKELETON ] ////////////
	var html = PostSave.Tabs.GUI.insertToSkeleton(leftA.join(""), rightA.join(""));
	
	//////////// [ INSERTING TO HTML ] ////////////
	PostSave.Tabs[this.name].pointer.innerHTML = '';
	PostSave.Tabs[this.name].pointer.innerHTML = html;
}



PostSave.Tabs.GUI.Download.currentImage = 0;
PostSave.Tabs.GUI.Download.imagePicked = function(imageNum)
{
	var numOfItems = PostSave.Items.array.length;
	var smallImg, bigImg, img;
	for (var i=0; i<numOfItems;i++)
	{
		smallImg = document.getElementById('postSave_download_image'+i) || null;		
		if (i === imageNum)
		{
			//small pic opacity
			if (numOfItems > 1)
			{
				smallImg.className = 'postSave_downloadImg_sel';
				smallImg.style.background = '#e6faff';
			}
			
			var img = new Image();
			
			img = PostSave.Items.array[i].large;
				
			document.getElementById('postSave_download_Bigimage').src = img.src;
			
			//dimension
			document.getElementById('postSave_download_dim').innerHTML = img.width + "x" + img.height;
			//file format
			var fileTypeArr = PostSave.Items.array[i].large.src.split(".")
			var fileTypeNeat = fileTypeArr[fileTypeArr.length-1].split("?");
			document.getElementById('postSave_download_format').innerHTML = fileTypeNeat[0];
			//file name
			var fnameArr = fileTypeArr[fileTypeArr.length-2].split("/");
			var fname = fnameArr[fnameArr.length-1];
			document.forms['postSave_downloadForm'].filename.value = fname;
			
			//currImage
			PostSave.Tabs.GUI.Download.currentImage = imageNum;
		}
		else
		{
			smallImg.className = 'postSave_downloadImg_unsel';
			smallImg.style.background = 'transparent';
		}
	}
}
PostSave.Tabs.GUI.Download.downloadLong = function()
{
	PostSave.Tabs.GUI.Download.currentImage = 0;
	PostSave.Tabs.GUI.Download.download(PostSave.Items.array[PostSave.Tabs.GUI.Download.currentImage].key);	
} 

PostSave.Tabs.GUI.Download.download = function(desiredName)
{
	///// [STATISTICS] /////
	PostSave.Stats.send(PostSave.Tabs.GUI.currentTabName + '/save2');
	
	/// desired name ///
	desiredName = desiredName || null;
	if (desiredName === null)
		desiredName = document.forms['postSave_downloadForm'].filename.value.replace(/^\s+|\s+$/g,"");
	desiredName = escape(desiredName.replace(/\s/g, "_"));
	
	var useThumb = 0;
	
	///// downloading image /////
	var fileId = PostSave.Items.array[PostSave.Tabs.GUI.Download.currentImage].key;
	var _link = "http://home.mywebface.com/javascripts/postSaveV2/postSave.pl?action=downloadFile&app="+PostSave.Activities.currentActivity.name+"&fileId="+fileId+"&desiredName="+desiredName+"&useThumb="+useThumb;
	window.top.location.href = _link;
	
	///// showing done tab //////
	//~ setTimeout(function(){PostSave.Tabs.GUI.showByName(PostSave.TABS.DONE);}, 1500);
	//~ setTimeout(function(){alert("action done");}, 1500);
	//~ PostSave.Tabs.GUI.showByName(PostSave.TABS.DOWNLOAD);
}

PostSave.Tabs.GUI.Download.onShow = function()
{
	// enabling text boxes //
	document.forms['postSave_downloadForm'].filename.disabled = false;
	try
	{
		document.forms['postSave_downloadForm'].filename.focus();
	}
	catch(e){};
	
	// setting picked image to be the first one //
	PostSave.Tabs.GUI.Download.imagePicked(0);
}


///////////////////////////////////////
/**************************************
TWITTER
**************************************/
///////////////////////////////////////
PostSave.Tabs.GUI.Twitter = {};
PostSave.Tabs.GUI.Twitter.build = function()
{
	var activity = PostSave.Activities.currentActivity;
	
	//////////// [ RIGHT ] ////////////
	var rightA = new Array();
	rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
		/// title 
		rightA.push("<tr><td valign='top' align='left'><h1 class='postSave_tabDiv_h1'>Post this on Twitter</h1></td></tr>");
		/// space
		rightA.push("<tr><td height='1px'></td></tr>");
		/// explanation
		rightA.push("<tr><td valign='top' align='left'>");
			rightA.push("<h4 class='postSave_tabDiv_explanation'>Share your "+activity.postActivityName+" on Twitter</h4>");
		rightA.push("</td></tr>");
		// space //
		rightA.push("<tr><td height='15px'></td></tr>");
		rightA.push("<tr>");
			rightA.push("<td valign='top' align='left'>");
				rightA.push("<div id='twitterDiv'>");
				rightA.push("<a id='twitterUpdate' href='#' onclick='PostSave.Stats.send(\""+PostSave.Tabs.GUI.currentTabName+"/Twitter/Share\")' style='position:absolute; top:0px; left:0px;'><img border=0 src='"+PostSave.Images.array['twitterShare'].src+"'></a>");
				rightA.push("<a id='twitterUpdateProfileImg' href='#' onclick='PostSave.Stats.send(\""+PostSave.Tabs.GUI.currentTabName+"/Twitter/UpdateAvatar\")' style='position:absolute; top:0px; left:152px;'><img border=0 src='"+PostSave.Images.array['twitterAvatar'].src+"'></a>");
				rightA.push("<img id='twitterImg' border=0 src='' width='24px' height='24px'>");
				rightA.push("</div>");
			rightA.push("</td>");
		rightA.push("</tr>");
	rightA.push("</table>");		

	//////////// [ LEFT ] ////////////
	var leftA = new Array();
	leftA.push("<form id='postSave_twitterForm_left' name='postSave_twitterForm_left' action='postSave.pl' method='post' onsubmit='javascript: return false;'>");
		leftA.push("<div id='postSave_twitterLeftContent'>");
			leftA.push(activity.getLeftPart(this.name));
		leftA.push("</div>");
	leftA.push("</form>");
	
	//////////// [ SKELETON ] ////////////
	var html = PostSave.Tabs.GUI.insertToSkeleton(leftA.join(""),rightA.join(""));
	
	//////////// [ INSERTING TO HTML ] ////////////
	PostSave.Tabs[this.name].pointer.innerHTML = '';
	PostSave.Tabs[this.name].pointer.innerHTML = html;
	
	//////////// [ UPDATING CONTENT ] ////////////
	PostSave.Tabs.GUI.Twitter.updateContent(this.name);
}

PostSave.Tabs.GUI.Twitter.update = function()
{
	var activity = PostSave.Activities.currentActivity;
	
	// update twitter image
	PostSave.Tabs.GUI.Twitter.updateContent(this.name);
	
	/// updating image ///
	PostSave.Tabs.GUI.Twitter.updateLeft(this.name);
}

PostSave.Tabs.GUI.Twitter.updateContent = function(tabName)
{
	///////// TWITTER IMAGE //////////
	var twitterImg = General.$('twitterImg') || null;
	if (twitterImg === null) {
		return;
	}
	else {
		General.$('twitterImg').src = PostSave.Items.array[0].small.src;
		General.$('twitterUpdate').href = "javascript:TW.go('"+PostSave.Items.array[0].small.src.split("?")[0]+"', 'update', '"+PostSave.Activities.currentActivity.name+"')";
		General.$('twitterUpdateProfileImg').href = "javascript:TW.go('"+PostSave.Items.array[0].small.src.split("?")[0]+"', 'update_profile_image', '"+PostSave.Activities.currentActivity.name+"')";
	}
}

PostSave.Tabs.GUI.Twitter.updateLeft = function(name)
{
	name = name || this.name;
	document.getElementById('postSave_twitterLeftContent').innerHTML = PostSave.Activities.currentActivity.getLeftPart(name);
}

PostSave.Tabs.GUI.Twitter.onShow = function()
{
	/// showing twitter div ///
	var twitterDiv = document.getElementById('twitterDiv');
	twitterDiv.style.visibility = 'visible';
}

PostSave.Tabs.GUI.Twitter.onHide = function()
{
	/// hiding twitter div ///
	var twitterDiv = document.getElementById('twitterDiv');
	twitterDiv.style.visibility = 'hidden';
}


///////////////////////////////////////
/**************************************
FACEBOOK
**************************************/
///////////////////////////////////////
PostSave.Tabs.GUI.Facebook = {};
PostSave.Tabs.GUI.Facebook.uid = 4719052;
PostSave.Tabs.GUI.Facebook.selectedColor = "#dce1e8";
PostSave.Tabs.GUI.Facebook.userUid = 0;
PostSave.Tabs.GUI.Facebook.isLoggedIn = false;
PostSave.Tabs.GUI.Facebook.friendArray = null;
PostSave.Tabs.GUI.Facebook.friendIdArray = null;
PostSave.Tabs.GUI.Facebook.friendsInRow = 3;
PostSave.Tabs.GUI.Facebook.loadEvent = null;
PostSave.Tabs.GUI.Facebook.friendEvent = null;
PostSave.Tabs.GUI.Facebook.isFriendListReady = false;
PostSave.Tabs.GUI.Facebook.gotFriendListResponse = false;

PostSave.Tabs.GUI.Facebook.ShowError = function(error)
{
	if (error) 
		error="\n\n("+error+")";
	else 
		error="";
	alert("Facebook Connect is not available at the moment. Please try again in a few moments."+error);
} 

PostSave.Tabs.GUI.Facebook.init = function()
{
	if (document.body === null)
	{
		setTimeout(PostSave.Tabs.GUI.Facebook.init, 500);
		return;
	}
	
	
	var containerDiv = General.$('FB_HiddenContainer')
	if (containerDiv === null)
	{
		/// adding FB div and incluing a script ///
		var _d = document.createElement('div');
		_d.setAttribute('id','FB_HiddenContainer');
		_d.style.position = 'absolute';
		_d.style.top = -10000 + "px";
		_d.style.width = "0px";
		_d.style.height = "0px";
		document.body.appendChild(_d);
		
		var _script1 = document.createElement('script');
		_script1.src = 'http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php';
		_script1.type = 'text/javascript';
		//document.getElementsByTagName('head')[0].appendChild(_script1);		
		document.body.appendChild(_script1);
	}
	
	
	if (typeof(FB) === 'undefined' || typeof(FB_RequireFeatures) === 'undefined')
	{
		setTimeout(PostSave.Tabs.GUI.Facebook.init, 500);
		return;	
	}
	
	try
	{
		//// starting connection ////
		FB_RequireFeatures(["XFBML"], PostSave.Tabs.GUI.Facebook.myWebFaceRegister);	
	}
	catch(e)
	{
		//// dispatching event ////
	  	PostSave.Tabs.GUI.Facebook.loadEvent.dispatch("Facebook");	
		PostSave.Tabs.GUI.Facebook.ShowError(e);  
	}
}

PostSave.Tabs.GUI.Facebook.myWebFaceRegister = function()
{
    try
	{
		//// initiating facebook connect ////
		FB.Facebook.init("37e54fe3133fe5f770e8282047a81d7e", "/javascripts/postSaveV2/xd_receiver.htm");
		
		//// dispatching event ////
	    PostSave.Tabs.GUI.Facebook.loadEvent.dispatch("Facebook");
	    
		//// what will happen when the user is connected //// 
	    FB.Facebook.get_sessionState().waitUntilReady(PostSave.Tabs.GUI.Facebook.sessionIsReadyHandler);
    }
    catch(e)
    {
		//// dispatching event ////
	    PostSave.Tabs.GUI.Facebook.loadEvent.dispatch("Facebook");
		PostSave.Tabs.GUI.Facebook.ShowError(e);  
    }
}

PostSave.Tabs.GUI.Facebook.sessionIsReadyHandler = function()
{
	if (typeof(fbInvoker) !== 'undefined' && fbInvoker !== 'postSave' && fbInvoker !== '')
		return;
		
	//// processing friend list ////
	try {
		FB.Connect.ifUserConnected(PostSave.Tabs.GUI.Facebook.userIsConnected);
	} catch(e) {
		PostSave.Tabs.GUI.Facebook.ShowError(e);
	}
}                 

PostSave.Tabs.GUI.Facebook.userIsConnected = function()
{
	try {
		if (typeof(fbInvoker) !== 'undefined' && fbInvoker !== 'postSave')
			return;
			
		//// [saving uid] ////
		PostSave.Tabs.GUI.Facebook.userUid = FB.Facebook.apiClient.get_session().uid;
		
		//// [setting connect flag] ////
		PostSave.Tabs.GUI.Facebook.isLoggedIn = true;
		
		//// [setting friends load event] ////
		PostSave.Tabs.GUI.Facebook.friendEvent = new EVENTS.Event("facebookFriendLoaded");
		EVENTS.addEventListener(PostSave.Tabs.GUI.Facebook.friendEvent, PostSave.Tabs.GUI.Facebook.friendsLoaded);
		
		//// [getting friends] ////
		FB.Facebook.apiClient.friends_get(null, PostSave.Tabs.GUI.Facebook.getFriendListHandler);
		
		//// updating content (if viewing facebook tab) ////
		if (PostSave.Tabs.GUI.currentTabName === PostSave.TABS.FACEBOOK)
			PostSave.Tabs.GUI.Facebook.updateContent();
	} catch(e) {
		PostSave.Tabs.GUI.Facebook.ShowError(e);
	}
}

PostSave.Tabs.GUI.Facebook.getFriendListHandler = function(result, ex)
{
	// ex = exception 
	if (ex == null) 
	{
		if (PostSave.Tabs.GUI.Facebook.gotFriendListResponse)
			return;
		PostSave.Tabs.GUI.Facebook.gotFriendListResponse = true;
		
		// initiating arrays //
		if (PostSave.Tabs.GUI.Facebook.friendArray === null)
			PostSave.Tabs.GUI.Facebook.friendArray = new Array();
		else
			PostSave.Tools.cleanArray(PostSave.Tabs.GUI.Facebook.friendArray);
			
		if (PostSave.Tabs.GUI.Facebook.friendIdArray === null)
			PostSave.Tabs.GUI.Facebook.friendIdArray = new Array();
		else
			PostSave.Tools.cleanArray(PostSave.Tabs.GUI.Facebook.friendIdArray);	
		
		// getting friends info //
	   	FB.Facebook.apiClient.users_getInfo(result,['uid','first_name','last_name','name', 'pic_square_with_logo'], PostSave.Tabs.GUI.Facebook.getFriendsInfoResultHandler);
	}
	else
	{
		//alert("getFriendList Exception: " + ex);
		PostSave.Tabs.GUI.Facebook.logout();
	}
}

PostSave.Tabs.GUI.Facebook.getFriendsInfoResultHandler = function(res, ex)
{
    if (ex == null) 
    {
	    var n = res.length;
		var isOK = true; 
	    for (var i=0; i<n && isOK;++i)
	    {
	    	try
	    	{
			    PostSave.Tabs.GUI.Facebook.friendArray.push(new PostSave.Tabs.GUI.Facebook.friend(res[i]['uid'],res[i]['first_name'],res[i]['last_name'],res[i]['name'],res[i]['pic_square_with_logo']));
		    	PostSave.Tabs.GUI.Facebook.friendIdArray.push(res[i]['uid']);
	    	}
	    	catch(e)
	    	{
		    	isOK = false;
		    	ex = e;
	    	}
	    }
	    if (isOK)
	    {
	    	PostSave.Tabs.GUI.Facebook.friendArray.sort(PostSave.Tabs.GUI.Facebook.sortByLastName);
		    PostSave.Tabs.GUI.Facebook.friendEvent.dispatch();
    	}
	   	else
	   	{
	   		//alert("getFriendsInfoResultHandler error: " + ex);
	   		
		   	//// logging out ////
		   	PostSave.Tabs.GUI.Facebook.logout();
	   		
	   		//// updating content (if viewing facebook tab) ////
			if (PostSave.Tabs.GUI.currentTabName === PostSave.TABS.FACEBOOK)
				PostSave.Tabs.GUI.Facebook.updateContent();
   		}
    }
    //~ else
    //~ {
		//~ //alert("getFriendsInfoResultHandler Exception: " + ex);
	    //~ PostSave.Tabs.GUI.Facebook.logout();
    //~ }
}

PostSave.Tabs.GUI.Facebook.sortByLastName = function(a, b)
{
		var x = a.lastName.toLowerCase();
		var y = b.lastName.toLowerCase();
		return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

PostSave.Tabs.GUI.Facebook.friendsLoaded = function()
{
	PostSave.Tabs.GUI.Facebook.isFriendListReady = true;
	PostSave.Tabs.GUI.Facebook.friendEvent.dispose();
	if (PostSave.Tabs.GUI.currentTabName === PostSave.TABS.FACEBOOK)
		PostSave.Tabs.GUI.Facebook.updateContent();
	
}

PostSave.Tabs.GUI.Facebook.logout = function()
{
	if (typeof(FB)!='undefined' && typeof(FB.Connect)!='undefined') {
		PostSave.Tabs.GUI.Facebook.isLoggedIn = false;
		setTimeout(FB.Connect.logout, 400);
		PostSave.Tabs.GUI.Facebook.gotFriendListResponse = false;
	} else {
		//PostSave.Tabs.GUI.Facebook.ShowError('FB.Connect is undefined - cannot log out');
	}
}

PostSave.Tabs.GUI.Facebook.login = function()
{
	try {
		if (typeof(fbInvoker) !== 'undefined')
			 fbInvoker = 'postSave';
			 
		FB_RequireFeatures(["XFBML"], PostSave.Tabs.GUI.Facebook.myWebFaceRegister);
		FB.Connect.requireSession();
	} catch(e) {
		PostSave.Tabs.GUI.Facebook.ShowError(e);
	}
 	return false;	
}

/*
PostSave.Tabs.GUI.Facebook.inviteFriends = function()
{
		var box_fbml =	"\
			<fb:fbml>\
				<fb:request-form \
				action='http://home.mywebface.com/'\
				method='POST' \
				invite='true' \
				type='myWebFace' \
				content=\"Create, inspire, enjoy  - all at one place - myWebFace!  <fb:req-choice url='http://www.myWebFace.com' label='Take me there' />\" >\
					<fb:multi-friend-selector showborder='false' actiontext='Invite your friends to visit myWebFace.' cols='4' rows='4' bypass='cancel' max='35'>\
				</fb:request-form>	 \
			</fb:fbml>\
		";

		var inviteDialog = new FB.UI.FBMLPopupDialog("Invite friends to visit myWebFace", box_fbml);
		inviteDialog.setContentWidth(650);
		inviteDialog.showLoading = true;
		inviteDialog.setContentHeight(650);
		inviteDialog.show();
}
*/

PostSave.Tabs.GUI.Facebook.build = function()
{
	var activity = PostSave.Activities.currentActivity;
	
	//////////// [ RIGHT ] ////////////
	var rightA = new Array();
	rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
		// user info //
		rightA.push("<tr>");
			rightA.push("<td valign='top' align='left'>");
				rightA.push("<div id='FB_userInfoDiv'></div>");
			rightA.push("</td>");
		rightA.push("</tr>");
		// space //
		rightA.push("<tr><td height='15px'></td></tr>");
		// actions //
		rightA.push("<tr>");
			rightA.push("<td valign='top' align='left'>");
				rightA.push("<div id='FB_actionsDiv'></div>");
			rightA.push("</td>");
		rightA.push("</tr>");
		
		//~ // space //
		//~ rightA.push("<tr><td height='30px'></td></tr>");
		//~ // E-card //
		//~ rightA.push("<tr>");
			//~ rightA.push("<td valign='top' align='left'>");
				//~ rightA.push("<a href='#' onclick='javascript:PostSave.Tabs.GUI.showByName(PostSave.TABS.MAIL);PostSave.Stats.send(\""+PostSave.Tabs.GUI.currentTabName+"/Ecard\")' ><div id='ecardDiv'><img id='ecardImg' border=0 src='' width='40px' height='40px'></div></a>");
			//~ rightA.push("</td>");
		//~ rightA.push("</tr>");


		// POST (gigya or addtoall)
		//~ if (registered === '1')
		//~ {
			//~ // space //
			//~ rightA.push("<tr><td height='30px'></td></tr>");
			//~ // NEW post: addToAny button //
			//~ rightA.push("<tr>");
				//~ rightA.push("<td valign='top' align='left'>");
					//~ rightA.push("<div id='addToAllDiv'></div>");
				//~ rightA.push("</td>");
			//~ rightA.push("</tr>");
		//~ }
		//~ else
		//~ {
			//~ // space //
			//~ rightA.push("<tr><td height='30px'></td></tr>");
			//~ // post //
			//~ rightA.push("<tr>");
				//~ rightA.push("<td valign='top' align='left'>");
					//~ rightA.push("<div id='divWildfire'></div>");
				//~ rightA.push("</td>");
			//~ rightA.push("</tr>");
		//~ }
		
	rightA.push("</table>");
	rightA.push("<div id='FB_friendsDiv'></div>");
	rightA.push("<div id='postToAlbumDiv'></div>");
	
	
	//////////// [ LEFT ] ////////////
	var leftA = new Array();
	leftA.push("<form id='postSave_facebookForm_right' name='postSave_facebookForm_right' action='postSave.pl' method='post' onsubmit='javascript: return false;'>");
		leftA.push("<div id='postSave_facebookLeftContent'>");
			leftA.push(activity.getLeftPart(this.name));
		leftA.push("</div>");
	leftA.push("</form>");


	//////////// [ SKELETON ] ////////////
	var html = PostSave.Tabs.GUI.insertToSkeleton(leftA.join(""),rightA.join(""));
	
	//////////// [ INSERTING TO HTML ] ////////////
	PostSave.Tabs[this.name].pointer.innerHTML = '';
	PostSave.Tabs[this.name].pointer.innerHTML = html;
	
	
	//////////// [ UPDATING CONTENT ] ////////////
	PostSave.Tabs.GUI.Facebook.updateContent(this.name);
	/// updating gigya/add2all & twitter ///
	PostSave.Tabs.GUI.Facebook.updatePosts();
	//~ General.$('ecardImg').src = PostSave.Items.array[0].small.src;
}

PostSave.Tabs.GUI.Facebook.updateContent = function(tabName)
{
	var activity = PostSave.Activities.currentActivity;
	
	tabName = tabName || PostSave.Tabs.GUI.currentTabName;
	
	var userInfo = document.getElementById("FB_userInfoDiv") || null;
	if (userInfo === null)
		return;
		
	var actionDiv = document.getElementById("FB_actionsDiv");
   	if (actionDiv === null)
		return;
	
	// NEW_CODE added at April 28 2010
	//~ if (registered === '1') {
		//~ if (MWF.Account.User.uidType === 'FB') {
			//~ //PostSave.Tabs.GUI.Facebook.isLoggedIn = true;
			//~ //PostSave.Tabs.GUI.Facebook.isFriendListReady = true;
			
			
			//~ //// processing friend list ////
			//~ try {
				//~ //FB.Connect.ifUserConnected(PostSave.Tabs.GUI.Facebook.userIsConnected);
				//~ PostSave.Tabs.GUI.Facebook.userIsConnected();
			//~ }
			//~ catch(e) {
				//~ PostSave.Tabs.GUI.Facebook.ShowError(e);
			//~ }
		//~ }
	//~ }
	// END_NEWCODE

	//// [not connected] ////
	if (!PostSave.Tabs.GUI.Facebook.isLoggedIn)
	{
		var html = new Array();
		html.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
			/// title
			html.push("<tr><td valign='top' align='left'><h1 class='postSave_tabDiv_h1_FB'>Post this on Facebook</h1></td></tr>");
			/// space
			html.push("<tr><td height='1px'></td></tr>");
			/// explanation
			html.push("<tr><td valign='top' align='left'>");
				html.push("<h4 class='postSave_tabDiv_explanation'>Share your "+activity.postActivityName+" on Facebook</h4>");
			html.push("</td></tr>");
			/// space
			html.push("<tr><td height='15px'></td></tr>");
			/// Connect
			html.push("<tr><td valign='top' align='left'>");
				html.push("<a href='#' onclick='javascript:return PostSave.Tabs.GUI.Facebook.login();PostSave.Stats.send(\""+tabName+"/connect\")' >");
					html.push('<img id="fb_login_image" border="0" src="http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_light_large_long.gif" alt="Connect"/>');
				html.push('</a>');
			html.push("</td></tr>");
		html.push("</table>");		
		userInfo.innerHTML = html.join("");
		actionDiv.innerHTML = '';
	}
	//// [connected] ////
	else
	{
		///////// USER INFO //////////
		var html = new Array();
		html.push("<table border='0' cellpadding='0' cellspacing='0'>");
		// picture and name // 
		html.push("<tr>");
			html.push("<td align='left' valign='top'>");
				html.push("<fb:profile-pic uid='"+PostSave.Tabs.GUI.Facebook.userUid+"' facebook-logo='true' linked='false' width='30'></fb:profile-pic>");
			html.push("</td>");
			
			html.push("<td width='10px'>&nbsp;</td>");
			
			html.push("<td align='left' valign='top'>");
				html.push("<h1 class='facebookName'>Welcome, <fb:name class='facebookName' uid='"+PostSave.Tabs.GUI.Facebook.userUid+"' useyou='false' linked='false' firstnameonly='true'></fb:name></h1>");
				html.push("<h2 class='facebookInfo'>You are logged in with your Facebook account.</h2>");
			html.push("</td>");
		html.push("</tr>");
		html.push("</table>");
		
		userInfo.innerHTML = html.join("");

		FB.XFBML.Host.parseDomElement(userInfo);
		
		///////// ACTION DIV //////////
		
	    	var html = new Array();
		html.push("<table border='0' cellpadding='0' cellspacing='0'>");
		html.push("<tr>");
			
			// 1. post to album //
			html.push("<td id='FB_albums'>");
				html.push("<a href='javascript:PostSave.Tabs.GUI.Facebook.showAlbums()' onclick=\"PostSave.Stats.send('"+tabName+"/postClick/postToMyAlbum')\"><img src='"+PostSave.Images.array['postToAlbumBtn'].src+"' border='0'/></a>");
			html.push("</td>");

			// space //
			html.push("<td width='2px' rowspan='3'>&nbsp;</td>");

			// 2. post to my wall //
			html.push("<td id='FB_sendToMe'>");
				html.push("<a href='javascript:PostSave.Tabs.GUI.Facebook.showSendDialog(\""+activity.facebookActivity+"\", \""+PostSave.Items.array[0].key+"\", \"me\")' onclick=\"PostSave.Stats.send('"+tabName+"/postClick/postToOwn')\"><img src='"+PostSave.Images.array['fbOwnWall'].src+"' border='0'/></a>");
			html.push("</td>");
			
			// space //
			html.push("<td width='2px' rowspan='3'>&nbsp;</td>");
			
			// 3. send to friend's wall
			//// [friend list is not ready] ////
			if (!PostSave.Tabs.GUI.Facebook.isFriendListReady) {
				html.push("<td id='FB_sendToFriends'>");
					html.push("Loading your friend list...");
				html.push("</td>");
			}
			//// [friend list is ready] ////
			else {
				html.push("<td id='FB_sendToFriends'>");
					html.push("<a href='javascript:PostSave.Tabs.GUI.Facebook.showSendDialog(\""+activity.facebookActivity+"\", "+PostSave.Items.array[0].key+", \"friends\")' onclick=\"PostSave.Stats.send('"+tabName+"/postClick/postToFriends')\"><img src='"+PostSave.Images.array['fbFriendWall'].src+"' border='0'/></a>");
				html.push("</td>");
			}
			
		html.push("</tr>");
	    html.push("</table>");

	    actionDiv.innerHTML = html.join("");
	}
}

///////// POST TO ALBUM _start //////////

PostSave.Tabs.GUI.Facebook.isPostToAlbumObjectBuilt = false;

PostSave.Tabs.GUI.Facebook.showAlbums = function() {
	if (!PostSave.Tabs.GUI.Facebook.isPostToAlbumObjectBuilt) {
		PostSave.Tabs.GUI.Facebook.createPostToAlbumObject();
	}
	PostSave.Tabs.GUI.Facebook.viewAlbumsDiv();
}

PostSave.Tabs.GUI.Facebook.createPostToAlbumObject = function() {
	var _div = General.$('postToAlbumDiv') || null;
	if (_div) {
		// post to album flash object
		var swfId = "postToAlbumObject";
		var swfSrc = "http://home.mywebface.com/javascripts/postSaveV3_amit/images/FacebookPostToAlbum";
		var params = "imageLink="+PostSave.Items.array[0].large.src.split("?")[0]+"&caption=http://home.mywebface.com/";
		var postToAlbumObjectStr = '';
		postToAlbumObjectStr = GET_AC_FL_RunContent(
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
			'width', '450',
			'height', '270',
			'src', swfSrc,
			'quality', 'high',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
			'align', 'middle',
			'play', 'true',
			'loop', 'true',
			'scale', 'noscale',
			'wmode', 'transparent',
			'devicefont', 'false',
			'id', swfId,
			'bgcolor', '#ffffff',
			'name', swfId,
			'menu', 'true',
			'allowFullScreen', 'false',
			'allowScriptAccess','sameDomain',
			'movie', swfSrc,
			'salign', 'TL',
			'flashvars',  params
		); //end AC code

		var html = new Array();
		html.push("<table cellpadding='0' cellspacing='0' border='0' width='100%'>");
			// top layer //
			html.push("<tr>");
				html.push("<td valign='middle' align='left' style='background:#6d84b4;border:1px solid #3b5998;border-bottom:none;height:30px;width:100%' height='30px' >");
					html.push("<table cellpadding='0' cellspacing='0' border='0' width='100%'>");
						html.push("<tr>");
							html.push("<td width='10px' height='30px'></td>");
							html.push("<td valign='middle' align='left' height='30px'><img src='"+PostSave.Images.array['fbFriends'].src+"' /></td>");
							html.push("<td width='5px' height='30px'></td>");
							html.push("<td valign='middle' align='left' height='30px'>");
								html.push("<h1 style='font-size:14px;color:#ffffff;font-family:Tahoma;font-weight:bold;'>Post to my Album</h1>");
							html.push("</td>");
						html.push("</tr>");
					html.push("</table>");
				html.push("</td>");
			html.push("</tr>");
			
			// the flash object
			html.push("<tr>");
				html.push("<td valign='middle' align='center'>");
					html.push(postToAlbumObjectStr);
				html.push("</td>");
			html.push("</tr>");
		
		html.push("</table>");

		_div.innerHTML = html.join("");
	}
}

PostSave.Tabs.GUI.Facebook.postToAlbumIsReady = function() {
	var _e = General.getFlashMovieObject('postToAlbumObject');
	if (_e) {
		_e.userLoggedIn(PostSave.Tabs.GUI.Facebook.getSessionInfo());
		PostSave.Tabs.GUI.Facebook.isPostToAlbumObjectBuilt = true;
	}
} 

PostSave.Tabs.GUI.Facebook.getSessionInfo = function() {
	var sessionData = FB.Facebook.apiClient.get_session();
	var fbdata = {};
	if (sessionData) {
		fbdata.fb_sig_session_key = sessionData.session_key;
		fbdata.fb_sig_ss = sessionData.secret;
		fbdata.fb_sig_user = sessionData.uid;
		fbdata.fb_sig = sessionData.sig;
		fbdata.fb_sig_api_key = "37e54fe3133fe5f770e8282047a81d7e";
	} 
	return fbdata;
}

PostSave.Tabs.GUI.Facebook.closeAlbumsDiv = function() {
	var _div = General.$('postToAlbumDiv') || null;
	if (_div) {
		_div.style.visibility = "hidden";
	}
}

PostSave.Tabs.GUI.Facebook.viewAlbumsDiv = function() {
	var _div = General.$('postToAlbumDiv') || null;
	if (_div) {
		_div.style.visibility = "visible";
	}
}

///////// POST TO ALBUM _end //////////

PostSave.Tabs.GUI.Facebook.showSendDialog = function(activity, id, toWhom)
{
	// to do
	//PostSave.Tabs.facebook.hideActions();
	
	if (!activity || !id || !toWhom) return;
	
	if (toWhom === 'friends')
		PostSave.Tabs.GUI.Facebook.showFriendSelector();
	else if (toWhom === 'me')
		PostSave.Tabs.GUI.Facebook.sendToWall(null);
}

PostSave.Tabs.GUI.Facebook.showFriendSelector = function()
{
	/// buliding content ///
	PostSave.Tabs.GUI.Facebook.buildFriendsDiv(null);
	
	/// showing friend div ///
	var friendDiv = document.getElementById('FB_friendsDiv');
	friendDiv.style.display = 'block';
	friendDiv.style.visibility = 'visible';
	
	/// trying to do focus and clearing value ///
	try
	{
		var _fsearchBox = document.forms['FB_friendForm'].FB_searchBox || null;
		if (_fsearchBox !== null)
		{ 
			_fsearchBox.disabled = false;
			_fsearchBox.value = '';
			_fsearchBox.focus();
		}
	}
	catch(e)
	{
		PostSave.Tabs.GUI.Facebook.ShowError(e);
	}
	
}

PostSave.Tabs.GUI.Facebook.hideFriendSelector = function()
{
	/// hiding friend div ///
	var friendDiv = document.getElementById('FB_friendsDiv');
	friendDiv.style.display = 'none';
	friendDiv.style.visibility = 'hidden';
}

PostSave.Tabs.GUI.Facebook.isFriendsDivBuilt = false;
PostSave.Tabs.GUI.Facebook.buildFriendsDiv = function(searchValue)
{
	searchValue = searchValue || '';
	
	
	
	//////// [BUILDING THE SKELETON] ////////
	if (!PostSave.Tabs.GUI.Facebook.isFriendsDivBuilt)
	{
		var friendsListContentDiv = document.getElementById('FB_friendsDiv');
		if (friendsListContentDiv === null)
			return;
			
		var formString = new Array();
		formString.push("<table cellpadding='0' cellspacing='0' border='0' width='100%'>");
			// top layer //
			formString.push("<tr>");
				formString.push("<td valign='middle' align='left' style='background:#6d84b4;border:1px solid #3b5998;border-bottom:none;height:30px;width:100%' height='30px' >");
					formString.push("<table cellpadding='0' cellspacing='0' border='0' width='100%'>");
						formString.push("<tr>");
							formString.push("<td width='10px' height='30px'></td>");
							formString.push("<td valign='middle' align='left' height='30px'><img src='"+PostSave.Images.array['fbFriends'].src+"' /></td>");
							formString.push("<td width='5px' height='30px'></td>");
							formString.push("<td valign='middle' align='left' height='30px'>");
								formString.push("<h1 style='font-size:14px;color:#ffffff;font-family:Tahoma;font-weight:bold;'>Send to Friends wall</h1>");
							formString.push("</td>");
							formString.push("<td width='20px' height='30px'></td>");
							formString.push("<td valign='middle' align='right' height='30px'>");
								formString.push("<form id='FB_friendForm' name='FB_friendForm' style='margin:0px;' onsubmit='javascript:return false;'>");
								formString.push("<input type='text' value='' style='margin:0px;width:100px;font-family:tahoma;font-size:11px;color#666666;vertical-align:middle' name='FB_searchBox' id='FB_searchBox' onkeyup='javascript:PostSave.Tabs.GUI.Facebook.doSearch()'/>");
								formString.push("</form>");
							formString.push("</td>");
							formString.push("<td width='5px' height='30px'></td>");
						formString.push("</tr>");
					formString.push("</table>");
				formString.push("</td>");
			formString.push("</tr>");
			
			formString.push("<tr>");
				formString.push("<td valign='top' align='left'>");
					formString.push("<div id='FB_friendList'></div>");
				formString.push("</td>");
			formString.push("</tr>");
				
			// cancel row //
			formString.push("<tr>");
				formString.push("<td valign='middle' align='left' height='40px' style='background:#f2f2f2;'>");
					formString.push("<table cellpadding='0' cellspacing='0' border='0' width='100%'>");
						formString.push("<tr>");
							formString.push("<td valign='middle' align='right'>");
								formString.push("<a href='javascript:PostSave.Tabs.GUI.Facebook.hideFriendSelector();'><img src='"+PostSave.Images.array['fbCancel'].src+"' border='0' /></a>");
							formString.push("</td>");
							formString.push("<td width='10px'>&nbsp;</td>");
						formString.push("</tr>");
					formString.push("</table>");
				formString.push("</td>");
			formString.push("</tr>");
		formString.push("</table>");
		friendsListContentDiv.innerHTML = formString.join("");
		
		PostSave.Tabs.GUI.Facebook.isFriendsDivBuilt = true;		
	}
	
	
	//////// [FRIENDS] ////////
	var tabName = PostSave.Tabs.GUI.currentTabName;
	var counter = 0;
	var picNameSpace = 2;
	var userSpace = 5;
	var heightSpace = 10;
	
	var friends = new Array();
	friends.push("<table cellpadding='0' cellspacing='0' border='0' width='100%'>");
		friends.push("<tr><td height='7px'></td></tr>");
		
		// friends loop //
		friends.push("<tr>");
		
		var l = PostSave.Tabs.GUI.Facebook.friendArray.length;
		for (var i=0; i<l; ++i)
		{
			var friend = PostSave.Tabs.GUI.Facebook.friendArray[i];
			if (friend.uid !== 0)
			{
				var toPut = false;
				var theName = friend.name;
				if(searchValue === '')
				{
					toPut = true;
				}
				else
				{
					searchValue = searchValue.toLowerCase();
					var found = theName.toLowerCase().indexOf(searchValue);
					if(found !== -1)
					{
						var tmp = theName.substr(theName.toLowerCase().indexOf(searchValue), searchValue.length);
						theName = theName.replace(new RegExp(searchValue, 'gi'),("<font style='color:#6D84B4;'><b>" + tmp + "</b></font>"));
						toPut = true;
					}
				}
				
				if (toPut)
				{
					if (counter !== 0 && counter % PostSave.Tabs.GUI.Facebook.friendsInRow === 0)
					{
						friends.push("</tr><tr><td height='"+heightSpace+"px'></td></tr><tr>");
					}
					if (counter % PostSave.Tabs.GUI.Facebook.friendsInRow === 0)
					{
						friends.push("<td width='7px'>&nbsp;</td>");
					}
					
					friends.push("<td onmouseover='this.style.backgroundColor=\""+PostSave.Tabs.GUI.Facebook.selectedColor+"\"' onmouseout='this.style.backgroundColor=\"#ffffff\"' onclick='PostSave.Tabs.GUI.Facebook.sendToWall("+friend.uid+");PostSave.Stats.send(\""+tabName+"/userClick\")' class='friendTd'>");
						friends.push("<table cellpadding='0' cellspacing='0' border='0'>");
								friends.push("<tr><td height='2px' colspan='4'></td></tr>");
								friends.push("<tr>");
									// left space //
									friends.push("<td width='2px' style='font-size:1px;'></td>");
									// pic //
									friends.push("<td valign='middle' align='center' width='54px' height='54px' style='border:1px solid #dddddd;'>");
										//friends.push("<div class='FB_faceDiv'>");
											friends.push("<img class='FB_faceImg' src='"+friend.pic+"' />");		
										//friends.push("</div>");
									friends.push("</td>");
									// space //
									friends.push("<td width='"+picNameSpace+"px'></td>");
									// name //
									friends.push("<td valign='top' align='left' width='76px'>");
										friends.push("<h3 class='FB_name'>"+theName+"</h3>");
									friends.push("</td>");
								friends.push("</tr>");
						friends.push("</table>");
					friends.push("</td>");
					
					// if not the last col in the row //
					if (counter % PostSave.Tabs.GUI.Facebook.friendsInRow !== (PostSave.Tabs.GUI.Facebook.friendsInRow-1))
						friends.push("<td width='"+userSpace+"px'></td>");
					else
						friends.push("<td width='15px'>&nbsp;</td>");
						
					++counter;	
				}
			}
		}
		
		while (counter % PostSave.Tabs.GUI.Facebook.friendsInRow !== 0)
		{
			friends.push("<td>&nbsp;</td>");
			if (counter % PostSave.Tabs.GUI.Facebook.friendsInRow !== (PostSave.Tabs.GUI.Facebook.friendsInRow-1))
				friends.push("<td width='"+userSpace+"px'>&nbsp;</td>");
			
			++counter;
		}
		friends.push("</tr>");	
	friends.push("</table>");
				
	
	document.getElementById('FB_friendList').innerHTML = friends.join("");
}

PostSave.Tabs.GUI.Facebook.lastValue = '';
PostSave.Tabs.GUI.Facebook.doSearch = function()
{
	try {
		var sb = document.forms['FB_friendForm'].FB_searchBox;
		if (sb === null)
			return;
			
		var _value = sb.value;
		if (_value === PostSave.Tabs.GUI.Facebook.lastValue)
			return;
		else
		{
			PostSave.Tabs.GUI.Facebook.lastValue = _value;
			PostSave.Tabs.GUI.Facebook.buildFriendsDiv(_value);
			try
			{
				sb.focus();
			}
			catch(e){}
		}
	} catch(e) {
		PostSave.Tabs.GUI.Facebook.ShowError(e);
	}
}


PostSave.Tabs.GUI.Facebook.sendToWall = function(selectedId)
{
	try {
		/*
			FB.Connect.streamPublish: http://developers.facebook.com/docs/?u=facebook.jslib.FB.Connect.streamPublish
			
			streamPublish(
				String user_message, // The main user-entered message for the post. This field should typically be blank- only fill this field with content the user has actually entered themselves.  
				Object attachment,  // A dictionary object containing the text of the post, relevant links, and optionally a media type. You can also include other key/value pairs which will be stored as metadata. See Stream Attachments for details.
				Object action_links,  // A dictionary of Action links objects, containing the link text and a hyperlink.
				String target_id,  // The ID of the user or the Page where you are publishing the content. If you specify a target_id, the post appears on the wall of the target user, not the user that published the post. This mimics the action of posting on a friend's Wall.
				String user_message_prompt,  // The sentence that appears before the user message field (e.g. "What's on your mind?")
				Function callback,  // A function that takes two parameters: post_id and exception. post_id returns the id of the published post (which can be null if the user cancels). exception returns error description if an error occurred.
				Boolean auto_publish,  // If the user has granted the publish_stream extended permission AND this parameter is true, then the post will be published without user approval. If the user has not set the extended permission, then the method will fail. (Default value is false)
				String actor_id // Allows the logged in user to publish on a Facebook Page's behalf if the user is an admin of the Page. If specified, actor_id indicates the ID of the Page that will publish the post. The post will appear on the Page's Wall as if the Page had posted it. (Default value is null)
			)
		*/
		
		var activity = PostSave.Activities.currentActivity;
		selectedId = selectedId || null;
		
		var attachment;
		//~ if (registered === '1') {
		
			var saved_img = PostSave.Items.array[0].large;
		
			var hostURL = activity.facebookLink;
			var imageId = saved_img.src.split('.jpg')[0].split('/')[saved_img.src.split('.jpg')[0].split('/').length-1]; //42574;
			var dir = saved_img.src.split('.com/')[1].split('/')[0];

			var imgSize = PostSave.Tabs.GUI.Facebook.getImgWallSize(saved_img.width, saved_img.height);
			var w = imgSize.width;
			var h = imgSize.height;
			var thumbURL = PostSave.Items.array[0].small.src;
			var browser = (navigator.appVersion.indexOf("MSIE") !== -1)? "ie" : "other";
			var swfURL = "http://home.mywebface.com/javascripts/postSaveV2/images/FBImage.swf?uid="+imageId+"&app="+dir+"&w="+w+"&h="+h+"&browser="+browser;
			var txt = 'Check out my ' + activity.facebookActivity + '! Visit MyWebFace to create your own.';
			
			attachment = {
				'name': txt,
				'href': hostURL,
				'media': [
					{'type':'flash', 'swfsrc':swfURL, 'imgsrc':thumbURL, 'width':'80', 'height':'80', 'expanded_width':w, 'expanded_height':h}
				]
			}; 
		//~ }
		//~ else {
			//~ /// new version ///
			//~ attachment = {
				//~ 'name': 'Check out my ' + activity.facebookActivity + '! Visit MyWebFace to create your own.',
				//~ 'href': activity.facebookLink,
				//~ 'media': [
					//~ {'type':'image','src':PostSave.Items.array[0].small.src,'href':activity.facebookLink}
				//~ ]
			//~ };
		//~ }
			
		var action_links = 
		{	
			'text':'Visit MyWebFace to create your own', 
			'href':activity.facebookLink
		}; 
		
		FB.Facebook.apiClient.users_hasAppPermission('publish_stream', 
			function(result)
			{ 
				// if there are no permissions //
				if (result == 0)
				{
					// openning permission dialog //
					FB.Connect.showPermissionDialog('publish_stream',
						function(granted)
						{
						   	// if the permission was granted //
							if(granted != "")
							{
							    // the MOST important line
							    if(FB.Connect._singleton._userInfo!=null) {
							    	FB.Connect._singleton._userInfo.shortStorySetting = FB.FeedStorySetting.autoaccept;
							    }
							    // publishing the stream //
							    //~ FB.Connect.streamPublish('', attachment, null, selectedId, '', PostSave.Tabs.GUI.Facebook.sendNotifications2, true);
							    FB.Connect.streamPublish('', attachment, null, selectedId, '', PostSave.Tabs.GUI.Facebook.sendNotifications2, false);
						   	}
						   	// permission wasn't granted //
						   	else
						   	{
			   					// publishing the stream //
							   	FB.Connect.streamPublish('', attachment, null, selectedId, '', PostSave.Tabs.GUI.Facebook.sendNotifications2, false);
		   					}
						}
					);
					
					
				}
				// there are permissions //
				else
				{
					// the MOST important line
					if(FB.Connect._singleton._userInfo!=null) {
						FB.Connect._singleton._userInfo.shortStorySetting = FB.FeedStorySetting.autoaccept;
					}	

					// publishing the stream //
					//~ FB.Connect.streamPublish('', attachment, null, selectedId, '', PostSave.Tabs.GUI.Facebook.sendNotifications2, true);
					FB.Connect.streamPublish('', attachment, null, selectedId, '', PostSave.Tabs.GUI.Facebook.sendNotifications2, false);
				}
			}
		);
	} catch(e) {
		PostSave.Tabs.GUI.Facebook.ShowError(e);
	}
}

PostSave.Tabs.GUI.Facebook.getImgWallSize = function (img_width, img_height) {
	
	var max_dimension = 460;
	
	var imgSize = {};
	imgSize.width = img_width;
	imgSize.height = img_height;
	
	if (imgSize.width > max_dimension || imgSize.height > max_dimension) {
		if (imgSize.width === imgSize.height) {
			imgSize.width = imgSize.height = max_dimension;
		}
		else if (imgSize.width > imgSize.height) {
			var ratio = imgSize.height / imgSize.width;
			imgSize.width = max_dimension;
			imgSize.height = parseInt(ratio * imgSize.width);
		}
		else if (imgSize.height > imgSize.width) {
			var ratio = imgSize.width / imgSize.height;
			imgSize.height = max_dimension;
			imgSize.width = parseInt(ratio * imgSize.height);
		}
	}
	
	return imgSize;
}

PostSave.Tabs.GUI.Facebook.sendNotifications2 = function(post_id, exception)
{
	try {
		var notificationMsg = " is displaying their creations on friends' walls. You can too, <a href='"+PostSave.Activities.currentActivity.facebookLink+"' target='_blank' title='myWebFace.com'>click here!</a>";
		FB.Facebook.apiClient.notifications_send(PostSave.Tabs.GUI.Facebook.friendIdArray, notificationMsg, function() {});
		// showing DONE tab //
		//~ PostSave.Tabs.GUI.showByName(PostSave.TABS.DONE);
		//~ alert("action done");
		PostSave.Tabs.GUI.showByName(PostSave.TABS.FACEBOOK);
	} catch(e) {
		PostSave.Tabs.GUI.Facebook.ShowError(e);
	}
}

PostSave.Tabs.GUI.Facebook.sendNotifications = function()
{
	try {
		var notificationMsg = " is displaying their creations on friends' walls. You can too, <a href='"+PostSave.Activities.currentActivity.facebookLink+"' target='_blank' title='myWebFace.com'>click here!</a>";	
		FB.Facebook.apiClient.notifications_send(PostSave.Tabs.GUI.Facebook.friendIdArray, notificationMsg, function() {});
	} catch(e) {
		PostSave.Tabs.GUI.Facebook.ShowError(e);
	}
}

PostSave.Tabs.GUI.Facebook.isAddToAllRemoved = false;
PostSave.Tabs.GUI.Facebook.updatePosts = function()
{
	///////// Add2ALL post API //////////
	//~ if (registered === '1')
	//~ {	
		//~ if (!PostSave.Tabs.GUI.Facebook.isAddToAllRemoved)
		//~ {
			//~ try
			//~ {
				//~ PostSave.Tabs.GUI.Facebook.isAddToAllRemoved = true;
				//~ var _a2aDiv = General.$('addToAllDiv');
				//~ var _a2aA = General.$('a2aA');
			
				//~ _a2aA.parentNode.removeChild(_a2aA);
				//~ _a2aDiv.appendChild(_a2aA);
			//~ }
			//~ catch(e)
			//~ {
				//~ //alert(e);
			//~ }
		//~ }
	//~ }
	
}

PostSave.Tabs.GUI.Facebook.update = function()
{
	var activity = PostSave.Activities.currentActivity;
	
	/// updating links ///
	PostSave.Tabs.GUI.Facebook.updateContent();
	
	/// updating gigya/add2all & twitter ///
	PostSave.Tabs.GUI.Facebook.updatePosts();
	
	/// updating image ///
	PostSave.Tabs.GUI.Facebook.updateLeft(this.name);
	
	/// E-card ///
	//~ General.$('ecardImg').src = PostSave.Items.array[0].small.src;
}

PostSave.Tabs.GUI.Facebook.updateLeft = function(name)
{
	name = name || this.name;
	document.getElementById('postSave_facebookLeftContent').innerHTML = PostSave.Activities.currentActivity.getLeftPart(name);
}

PostSave.Tabs.GUI.Facebook.onShow = function()
{
	return;
	
	if (registered === '1'){
		return;
	}
	
	//// setting gigya's div ////
	var _divWidth = 450;
	var _divHeight = 100;
	
	//// getting the buffer ////
	var buffer = PostSave.Activities.currentActivity.getPostBuffer();
	
	//// config ////
	var conf = 
	{
		UIConfig: "<config><display showEmail='false' showBookmark='true' showContent='true'/></config>",
		bookmarkURL: "http://home.mywebface.com/",
		defaultContent: buffer,
		partnerData: "postSave" + PostSave.Activities.currentActivity.name,
		networksToShow: "myspace, friendster, blogger, bebo, myyearbook, wordpress, hi5, vox"
	}
	Wildfire.initPost('6391', 'divWildfire', _divWidth, _divHeight, conf);
}

PostSave.Tabs.GUI.Facebook.onHide = function()
{
	PostSave.Tabs.GUI.Facebook.hideFriendSelector();	
}


/****** FACEBOOK FRIEND OBJECT ******/
PostSave.Tabs.GUI.Facebook.friend = function(uid, first, last, name, pic)
{
	this.uid = uid;
	this.firstName = first;
	this.lastName = last;
	this.name = name;
	if(pic == '')
		pic = "http://static.ak.fbcdn.net/pics/q_default.gif";
	this.pic = pic;
}
PostSave.Tabs.GUI.Facebook.friend.prototype.uid = 0;
PostSave.Tabs.GUI.Facebook.friend.prototype.firstName = '';
PostSave.Tabs.GUI.Facebook.friend.prototype.lastName = '';
PostSave.Tabs.GUI.Facebook.friend.prototype.name = '';
PostSave.Tabs.GUI.Facebook.friend.prototype.pic = '';


///////////////////////////////////////
/**************************************
DONE
**************************************/
///////////////////////////////////////
PostSave.Tabs.GUI.Done = {};
PostSave.Tabs.GUI.Done.lastTab = '';
PostSave.Tabs.GUI.Done.build = function()
{
	var activity = PostSave.Activities.currentActivity;
	
	//////////// [ RIGHT ] ////////////
	var rightA = new Array();
	rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
		rightA.push("<tr>");
			rightA.push("<td class='width30' valign='top'>");
				rightA.push("<img src='"+PostSave.Images.array['doneIcon'].src+"' />");
			rightA.push("</td>");
			rightA.push("<td class='width10'>&nbsp;</td>");
			rightA.push("<td valign='top'>");
				rightA.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
					/// title
					rightA.push("<tr><td><h1 class='postSave_tabDiv_h1'>DONE!</h1></td></tr>");
					/// space
					rightA.push("<tr><td height='5px'></td></tr>");
					/// instructions
					rightA.push("<tr><td><h4 class='postSave_tabDiv_explanation'>Choose from one of the other options above or go to one<br/> of these fun activities:</h4></td></tr>");
					/// space
					rightA.push("<tr><td height='40px'></td></tr>");
					/// links
					rightA.push("<tr><td>");
						rightA.push("<div id='postSave_doneDiv'></div>");
					rightA.push("</td></tr>");
				rightA.push("</table>");
			rightA.push("</td>");	
		rightA.push("</tr>");
	rightA.push("</table>");
	
	//////////// [ LEFT ] ////////////
	var leftA = new Array();
	leftA.push("<form id='postSave_doneForm_right' name='postSave_doneForm_right' action='postSave.pl' method='post' onsubmit='javascript: return false;'>");
		leftA.push("<div id='postSave_doneRightContent'>");
			leftA.push(activity.getLeftPart(this.name));
		leftA.push("</div>");
	leftA.push("</form>");
	
	//////////// [ SKELETON ] ////////////
	var html = PostSave.Tabs.GUI.insertToSkeleton(leftA.join(""),rightA.join(""));
	
	//////////// [ INSERTING TO HTML ] ////////////
	PostSave.Tabs[this.name].pointer.innerHTML = '';
	PostSave.Tabs[this.name].pointer.innerHTML = html;
	
	//////////// [ RUNNING UPDATE ] ////////////
	PostSave.Tabs.GUI.Done.update(this.name);
}

PostSave.Tabs.GUI.Done.update = function(thisName)
{
	thisName = thisName || this.name;
	
	var activity = PostSave.Activities.currentActivity;
	
	var linksArray = activity.getDoneLinks(PostSave.Tabs.GUI.Done.lastTab);
	if (linksArray === null)
		return;
	
	var html = new Array();
	html.push("<table width='100%' cellspacing='0' cellpadding='0' border='0'>");
	var l = linksArray.length;
	for (var i=0;i<l;i++)
	{
		var _link = linksArray[i].link;
		var _txt = linksArray[i].text;
		
		var _class = '';
		var spaceHeight = '';
		if (i === 0)
		{
			_class = 'postSave_done_option1';
			spaceHeight = '15px';
		}
		else
		{
			_class = 'postSave_done_options';
			spaceHeight = '5px';
		}
		
		var _target = '_top';
		
		if (i === 0)
		{
			html.push("<tr>");
				html.push("<td>");
					html.push("<table cellpadding='0' cellspacing='0'>");
						html.push("<tr>");
							html.push("<td class='bigBtnLeft'>&nbsp;</td>");
							html.push("<td class='bigBtnCenter'>");
								html.push("<a href='"+_link+"' class='"+_class+"' onclick=\"javascript:PostSave.Stats.send('"+this.name+"/"+linksArray[i].gas+"');\" target='"+_target+"'>"+_txt+"</a>");
								html.push("&nbsp;&nbsp;");
							html.push("</td>");
							html.push("<td class='bigBtnRight'>&nbsp;</td>");
						html.push("</tr>");
					html.push("</table>");
				html.push("</td>");
			html.push("</tr>");
		}
		else
		{
			html.push("<tr>");
				html.push("<td>");
					html.push("<table width='75%' cellpadding='0' cellspacing='0'>");
						html.push("<tr>");
							html.push("<td width='5px'></td>");
							html.push("<td width='10px'><img src='"+PostSave.Images.array['doneArrow'].src+"' /></td>");
							html.push("<td width='5px'></td>");
							html.push("<td><a href='"+_link+"' class='"+_class+"' onclick=\"javascript:PostSave.Stats.send('"+this.name+"/"+linksArray[i].gas+"');\" target='"+_target+"'>"+_txt+"</a></td>");
						html.push("</tr>");
					html.push("</table>");
				html.push("</td>");
			html.push("</tr>");
		}
		
		/// space
		html.push("<tr><td height='"+spaceHeight+"' colspan='3'></td></tr>");
	}
	html.push("</table>");
	
	///// updating html /////
	document.getElementById('postSave_doneDiv').innerHTML = html.join("");
	
	///// updating right side /////
	PostSave.Tabs.GUI.Done.updateLeft(this.name);
}

PostSave.Tabs.GUI.Done.updateLeft = function(name)
{
	name = name || this.name;
	document.getElementById('postSave_doneRightContent').innerHTML = PostSave.Activities.currentActivity.getLeftPart(name);	
}



/****** LINK OBJECT ******/
PostSave.Tabs.GUI.Done.doneLink = function(text, link, gas)
{
	if (!text || !link || !gas)
		return;
		
	this.text = text;	
	this.link = link;
	this.gas = gas;
}
PostSave.Tabs.GUI.Done.doneLink.prototype.text = '';
PostSave.Tabs.GUI.Done.doneLink.prototype.link = '';
PostSave.Tabs.GUI.Done.doneLink.prototype.gas = '';


//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////// PLAXO FUNCTION /////////////
function onABCommComplete()
{
	PostSave.Tabs.GUI.GSMail.processPlaxo();
}