var lastFunction;
var lastFunctionParams;
var loginWindow;

//---------------------------------------------------------------
// Constants for services
//---------------------------------------------------------------
var SERVICE_FACEBOOK = 1;
var SERVICE_MYSPACE = 2;
var SERVICE_WINDOWS_LIVE = 3;
var SERVICE_BLOGGER = 4;
var SERVICE_LIVEJOURNAL = 5;
var SERVICE_BUZZNET = 6;
var SERVICE_BEBO = 7;
var SERVICE_OTHER = 8;

var FACEBOOK_APP = 'peersquared';
var BEBO_APP = 'peer2';


function getGeneric(title, swfUrl, width, height, flashVars) {
	return '<div style="border: 1px solid #999999; margin-top: 15px; margin-bottom: 15px;"> <div style="padding: 5px; padding-left: 15px; margin-bottom: 15px; font-size: larger; font-weight: bold; background-color: #e8e8e8; color: #098ae5;">'+title+'</div> <div style="width: '+width+'px; height: '+height+'px; margin-left: auto; margin-right: auto;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="swfplayer" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="false" /> <param name="movie" value="'+swfUrl + '" /><param name="flashvars" value="serverName='+webhost+'&'+flashVars+'" /><param name="quality" value="high" /><param name="bgcolor" value="#999999" />    <embed src="'+swfUrl+'" quality="high" bgcolor="#999999" width="'+width+'" height="'+height+'" name="swfplayer" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" flashvars="serverName='+webhost+'&'+flashVars+'" pluginspage="http://www.adobe.com/go/getflashplayer" /></object></div><div style="padding: 5px; padding-left: 15px; margin-top: 15px; font-size: larger; font-weight: bold; background-color: #e8e8e8; color: #788A97;">Learn more at <a style="color: #37A6EB" href="http://' + webhost + '/">' + webhost + '</div></div>';
}

function initSharing() {
	initBlogger();
}


function formPostNewWindow(postURL, formData) {
	if( formData !== undefined ) {
		var formElement = new Element('form', {'action': postURL, 'target': '_blank', 'method': 'POST'});
	
		formData.each(function(pair) {
			var str = pair.value.toString();
			var escapedStr = str.replace(/"/g, '\"');
			
			var inputElement = new Element('input', {'name':pair.key, 'value':escapedStr, 'type': 'hidden'});
			formElement.appendChild(inputElement);	
		});
		
		var formBody = document.getElementsByTagName('body')[0];
		formBody.appendChild(formElement);		
		formElement.submit();
	}
}

function initFacebook() {
	if( typeof(FB) == 'undefined' ) {	
		var fbScript = document.createElement('script');		
		fbScript.type = 'text/javascript';
		fbScript.src = 'http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php';
	
		document.getElementsByTagName("head")[0].appendChild(fbScript);	
	
		return;
	}
}

//--------------------------------------------------------------------
// shareFacebookCallback
// Type: Share
//
// params:	postId - the successful post ID
//			ex - An exception if there was a problem
// Return true (success), false (fail)
//--------------------------------------------------------------------

function shareFacebookCallback(postId, ex) {
	if( ex !== null ) {
		alert('Exception: ' + ex);
	}
}

//--------------------------------------------------------------------
// shareFacebook
// Type: Share
//
// Globals: fbApiKey
// params: shareUrl - the URL that will be added to the feed
// Return true (success), false (fail)
//--------------------------------------------------------------------
function shareFacebook(shareUrl) {
	
	var isSuccess = false;
	
	// When this is called, we need to dynamically load the Facebook Connect JS API so we can do useful things

	
	// Once it's loaded, init the FB API
	FB.init(fbApiKey, 'xd_receiver.htm');
	FB.ensureInit(function() {	       		
	    var client = FB.Facebook.apiClient;
	    
	    
	    FB_RequireFeatures(["XFBML", "Api", "Connect"], function() {		
	    	       	      
	    	var attachment = {
	    		name: 'Peer2 - Engage, Share and Earn Rewards',
	    		href: shareUrl
	    	};

	    	var actions = { text: 'Peer2 - Engage, Share and Earn Rewards', href: shareUrl};
   				    		
			FB.Connect.streamPublish('Check out Peer2 where you can engage, share and earn rewards', attachment, actions, null, 'Say something about Peer Squared:', shareFacebookCallback);
		});
	});	
}

//--------------------------------------------------------------------
// embedFacebook
// Type: Embed
//
// params: 
//      userId The user ID to embed as
// Return true (success), error string on error
//--------------------------------------------------------------------
function embedFacebook(userId) {
		window.open('http://apps.facebook.com/'+FACEBOOK_APP+'/?peer2uid=' + userId,'embedFacebook');

}


//--------------------------------------------------------------------
// shareMyspace
// Type: Share
//
// params: 
//		title -- the title or supercaption on the content
//		description -- the content body
//		url -- the url to share
//		location -- Where to post the content (e.g. About me, Blog, Bulletin - use constants here)
//--------------------------------------------------------------------
function shareMyspace(title, description, url, location) {
	_postMyspaceContent(title,description,url,location);
}


//--------------------------------------------------------------------
// embedMyspace
// Type: Embed
//
// params: 
//      title The text that goes at the top of the box surrounding the flash content
//      swfURL the absolute URL to the content (e.g. http://www.mysite.com/path/to/my.swf)
//      width Width of the SWF in pixels, passed to the width tag
//      width Height of the SWF in pixels, passed to the height tag
//      flashVars Flashvars to insert into the tag
//      location Where to post the content (e.g. About me, Blog, Bulletin - use constants here)
// Return true (success), error string on error
//--------------------------------------------------------------------
function embedMyspace(title, swfUrl, width, height, flashVars, location) {

	var content = '<div style="border: 1px solid #999999; margin-top: 15px; margin-bottom: 15px;"> <div style="padding: 5px; padding-left: 15px; margin-bottom: 15px; font-size: larger; font-weight: bold; background-color: #e8e8e8; color: #098ae5;">'+title+'</div> <div style="width: '+width+'px; height: '+height+'px; margin-left: auto; margin-right: auto;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="swfplayer" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="false" /> <param name="movie" value="'+swfUrl + '" /><param name="flashvars" value="serverName='+webhost+'&'+flashVars+'" /><param name="quality" value="high" /><param name="bgcolor" value="#999999" />    <embed src="'+swfUrl+'" quality="high" bgcolor="#999999" width="'+width+'" height="'+height+'" name="swfplayer" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" flashvars="serverName='+webhost+'&'+flashVars+'" pluginspage="http://www.adobe.com/go/getflashplayer" /></object></div><div style="padding: 5px; padding-left: 15px; margin-top: 15px; font-size: larger; font-weight: bold; background-color: #e8e8e8; color: #788A97;">Learn more at <a style="color: #37A6EB" href="http://' + webhost + '/">' + webhost + '</div></div>';

 	
	_postMyspaceContent(title, content, '', location);

}
 			

//--------------------------------------------------------------------
// Myspace-specific constants
//--------------------------------------------------------------------
var MYSPACE_BLOG = 1;
var MYSPACE_BULLETIN = 2;
var MYSPACE_ABOUT_ME = 3;

		
//--------------------------------------------------------------------
// _postMyspaceContent
// Type: Internal
//
// params: shareUrl - the URL that will be added to the feed
// Return true (success), error string on error
//--------------------------------------------------------------------
function _postMyspaceContent(title, content, url, location) {
	
	if( location === undefined ) {
		location = MYSPACE_BULLETIN;
	}
	
	var formData = $H();
	formData.set('t', title);
	formData.set('c', content);
	formData.set('u', url);
	formData.set('l', location);			
	
	formPostNewWindow('http://www.myspace.com/index.cfm?fuseaction=postto', formData)
}

//--------------------------------------------------------------------
// Blogger-specific variables
//--------------------------------------------------------------------
var bloggerAuthToken = null;

//--------------------------------------------------------------------
// setBloggerAuthToken
// Type: Auth
//
// params: token - the authentication token receieved from google
//--------------------------------------------------------------------
function setBloggerAuthToken(token) {
	bloggerAuthToken = token;
}


//--------------------------------------------------------------------
// shareBlogger
// Type: Share
//
// params: shareUrl - the URL that will be added to the feed
// Return true (success), error string on error
//--------------------------------------------------------------------
function shareBlogger(title, description) {
	_postBloggerContent(title,description);
}


//--------------------------------------------------------------------
// embedBlogger
// Type: Embed
//
// params: 
//      title The text that goes at the top of the box surrounding the flash content
//      swfURL the absolute URL to the content (e.g. http://www.mysite.com/path/to/my.swf)
//      width Width of the SWF in pixels, passed to the width tag
//      width Height of the SWF in pixels, passed to the height tag
//      flashVars Flashvars to insert into the tag
// Return true (success), error string on error
//--------------------------------------------------------------------
function embedBlogger(title, swfUrl, width, height, flashVars) {

	var content = '<div style="padding-bottom: 15px; margin-top: 15px; margin-bottom: 15px;"><div style="width: '+width+'px; margin-left: auto; margin-right: auto;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="swfplayer" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="false" /> <param name="movie" value="'+swfUrl + '" /><param name="flashvars" value="serverName='+webhost+'&'+flashVars+'" /><param name="quality" value="high" /><param name="bgcolor" value="#999999" />    <embed src="'+swfUrl+'" quality="high" bgcolor="#999999" width="'+width+'" height="'+height+'" name="swfplayer" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" flashvars="serverName='+webhost+'&'+flashVars+'" pluginspage="http://www.adobe.com/go/getflashplayer" /></object></div> </div>';
		 	
	_postBloggerContent(title, content);
}

/*
function _googleLoaded() {
	google.load("gdata", "1.x");
//	alert('g loaded');
}
*/


function initBlogger() {
	google.load("gdata", "1.x");	
}


//--------------------------------------------------------------------
// _postBloggerContent
// Type: Internal
//
// params: shareUrl - the URL that will be added to the feed
// Return true (success), error string on error
//--------------------------------------------------------------------
function _postBloggerContent(title, content) {

	var handleError = function(error) {
	  //alert('error: ' + error);
	};

		// The callback method invoked when getBlogFeed() returns the list of our blogs
		var blogFeedsLoaded = function(blogFeedRoot) {
		  var blogEntries = blogFeedRoot.feed.getEntries();
		  
		  if (blogEntries.length) {
		    var blogEntry = blogEntries[0]; // only get first blog
		    
		    // This is the feed uri for the blog's posts
		    var postsFeedUri = blogEntry.getEntryPostLink().getHref();
		  
		    bloggerService.getBlogPostFeed(postsFeedUri, handleBlogPostFeed, handleError);
		  }
		};
		
		// A callback invoked when getBlogPostFeed() returns the list of blog posts
		var handleBlogPostFeed = function(postsFeedRoot) {
		
	      // Constuct an new BlogPostEntry
		  var newEntry = new google.gdata.blogger.BlogPostEntry({
		    title: {
		      type: 'html',
		      text: title
		    },
		    content: {
		      type: 'html',
		      text: content
		    },
		    categories: [
		      {scheme: 'http://www.blogger.com/atom/ns#', term: 'peer2'},
		      {scheme: 'http://www.blogger.com/atom/ns#', term: 'peersquared'},		      
		    ]
		  });
		
		  // mark post as a draft?
		  // newEntry.setControl({draft: {value: google.gdata.Draft.VALUE_YES}});
		  
		  postsFeedRoot.feed.insertEntry(newEntry,
		      function() {
   		        google.accounts.user.logout();
		        window.open(postsFeedRoot.feed.getHtmlLink().getHref(), 'blogger');
		      },
		      handleError
		  );	
		}
	

  var bloggerService = new google.gdata.blogger.BloggerService('peer2-peer2-1');
  scope = "http://www.blogger.com/feeds";
  var token = google.accounts.user.login(scope);
  
  
  // First, get the list of blogs that the user has access to write to.
  bloggerService.getBlogFeed('http://www.blogger.com/feeds/default/blogs', blogFeedsLoaded, handleError)  
}

//--------------------------------------------------------------------
// shareLiveBlog
// Type: Share
//
// params: 
//		title -- the title or supercaption on the content
//		description -- the content body
//		url -- the url to share
//--------------------------------------------------------------------
function shareLiveBlog(title, description, url) {
	_postLiveBlog(title, description, url);
}

//--------------------------------------------------------------------
// embedLiveJournal
// Type: Embed
//
// params: 
//      title The text that goes at the top of the box surrounding the flash content
//      swfURL the absolute URL to the content (e.g. http://www.mysite.com/path/to/my.swf)
//      width Width of the SWF in pixels, passed to the width tag
//      width Height of the SWF in pixels, passed to the height tag
//      flashVars Flashvars to insert into the tag
// Return true (success), error string on error
//--------------------------------------------------------------------
function embedLiveBlog(title, swfUrl, width, height, flashVars) {

	var content = '<div style="padding-bottom: 15px; margin-top: 15px; margin-bottom: 15px;"><div style="width: '+width+'px; margin-left: auto; margin-right: auto;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="swfplayer" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="false" /> <param name="movie" value="'+swfUrl + '" /><param name="flashvars" value="serverName='+webhost+'&'+flashVars+'" /><param name="quality" value="high" /><param name="bgcolor" value="#999999" />    <embed src="'+swfUrl+'" quality="high" bgcolor="#999999" width="'+width+'" height="'+height+'" name="swfplayer" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" flashvars="serverName='+webhost+'&'+flashVars+'" pluginspage="http://www.adobe.com/go/getflashplayer" /></object></div><div style="padding: 5px; padding-left: 15px; margin-top: 15px; font-size: larger; font-weight: bold; background-color: #e8e8e8; color: #788A97;">Learn more at <a style="color: #37A6EB" href="http://' + webhost + '/">' + webhost + '</div></div>';
		 	
	_postLiveBlog(title, content, 'http://peer2.com/');
}

//--------------------------------------------------------------------
// _postLiveBlog
// Type: Internal
//
// params: 
//		title -- the title or supercaption on the content
//		description -- the content body
//		url -- the url to share
//--------------------------------------------------------------------

function _postLiveBlog(title, content, url) {
	var formData = $H();
	formData.set('Title', title);
	formData.set('description', content);
	formData.set('SourceURL', url);
	
	formPostNewWindow('http://spaces.live.com/BlogIt.aspx', formData)
}


//--------------------------------------------------------------------
// LiveJournal-specific variables
//--------------------------------------------------------------------
var liveJournalAuthToken = null;

//--------------------------------------------------------------------
// setLiveJournalAuthToken
// Type: Auth
//
// params: token - the authentication token receieved from google
//--------------------------------------------------------------------
function setLiveJournalAuthToken(token) {
	liveJournalAuthToken = token;
}


//--------------------------------------------------------------------
// shareLiveJournal
// Type: Share
//
// params: shareUrl - the URL that will be added to the feed
// Return true (success), error string on error
//--------------------------------------------------------------------
function shareLiveJournal(title, description) {
	showLoginBox('LiveJournal', '/share/livejournal.php', escape(title), escape(content));
//	_postLiveJournalContent(title,description);
}


//--------------------------------------------------------------------
// embedLiveJournal
// Type: Embed
//
// params: 
//      title The text that goes at the top of the box surrounding the flash content
//      swfURL the absolute URL to the content (e.g. http://www.mysite.com/path/to/my.swf)
//      width Width of the SWF in pixels, passed to the width tag
//      width Height of the SWF in pixels, passed to the height tag
//      flashVars Flashvars to insert into the tag
// Return true (success), error string on error
//--------------------------------------------------------------------
function embedLiveJournal(title, swfUrl, width, height, flashVars) {
	var content = '<div style="padding-bottom: 15px; margin-top: 15px; margin-bottom: 15px;"><div style="width: '+width+'px; margin-left: auto; margin-right: auto;"><lj-embed id=""><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="swfplayer" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="false" /> <param name="movie" value="'+swfUrl + '" /><param name="flashvars" value="serverName='+webhost+'&'+flashVars+'" /><param name="quality" value="high" /><param name="bgcolor" value="#999999" />    <embed src="'+swfUrl+'" quality="high" bgcolor="#999999" width="'+width+'" height="'+height+'" name="swfplayer" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" flashvars="serverName='+webhost+'&'+flashVars+'" pluginspage="http://www.adobe.com/go/getflashplayer" /></lj-embed></div> </div>';
		 	
		 	

//	_postLiveJournalContent(title, content);
	showLoginBox('LiveJournal', '/share/livejournal.php', escape(title), escape(content));
}


//--------------------------------------------------------------------
// shareBuzznet
// Type: Share
//
// params: shareUrl - the URL that will be added to the feed
// Return true (success), error string on error
//--------------------------------------------------------------------
function shareBuzznet(title, description) {
//	_postBuzznetContent(title,description);
	showLoginBox('Buzznet', '/share/buzznet.php', escape(title), escape(content));
}


//--------------------------------------------------------------------
// embedBuzznet
// Type: Embed
//
// params: 
//      title The text that goes at the top of the box surrounding the flash content
//      swfURL the absolute URL to the content (e.g. http://www.mysite.com/path/to/my.swf)
//      width Width of the SWF in pixels, passed to the width tag
//      width Height of the SWF in pixels, passed to the height tag
//      flashVars Flashvars to insert into the tag
// Return true (success), error string on error
//--------------------------------------------------------------------
function embedBuzznet(title, swfUrl, width, height, flashVars) {

	var content = '<div style="padding-bottom: 15px; margin-top: 15px; margin-bottom: 15px;"><div style="width: '+width+'px; margin-left: auto; margin-right: auto;"><lj-embed id=""><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="swfplayer" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="false" /> <param name="movie" value="'+swfUrl + '" /><param name="flashvars" value="serverName='+webhost+'&'+flashVars+'" /><param name="quality" value="high" /><param name="bgcolor" value="#999999" />    <embed src="'+swfUrl+'" quality="high" bgcolor="#999999" width="'+width+'" height="'+height+'" name="swfplayer" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" flashvars="serverName='+webhost+'&'+flashVars+'" pluginspage="http://www.adobe.com/go/getflashplayer" /></lj-embed></div> </div>';
		 	
	//_postBuzznetContent(title, content);
	showLoginBox('Buzznet', '/share/buzznet.php', escape(title), escape(content));
}

//--------------------------------------------------------------------
// embedBebo
// Type: Embed
//
// params: 
//      userId The user ID to embed as
// Return true (success), error string on error
//--------------------------------------------------------------------
function embedBebo(userId) {
	window.open('http://apps.bebo.com/'+BEBO_APP+'?peer2uid=' + userId,'embedBebo');
}

//--------------------------------------------------------------------

function showSuccessBox(postURL) {
	var postStatusDiv = new Element('div', {'id': 'postStatusBox', 'class': 'overlayContainer', 'style': 'width: 400px; height: 180px;'});

	postStatusDiv.appendChild(new Element('div', {'class': 'overlayHeader'}).update('Success!'));
	postStatusDiv.appendChild(new Element('div', {'class': 'overlaySubhead'}).update('The player has been posted'));

	var linkDiv = new Element('div', {'style': 'text-align: center; margin: 15px;'});				
	linkDiv.appendChild(new Element('a', {'href': postURL, 'style': 'font-size: larger; font-weight: bold', 'target': '_blank'}).update('Click Here to View Post'));
	postStatusDiv.appendChild(linkDiv);
	
	var btnDiv = new Element('div', {'style': 'text-align: center; margin-top: 25px;'});
	var closeLink = new Element('a', {'href': '#'});
		closeLink.onclick = function() { closeLogin(); return false;}				
	var closeImg = new Element('img', {'src': '/images/btn_close.png', 'alt': 'Close'});
	closeLink.appendChild(closeImg);
	btnDiv.appendChild(closeLink);

	postStatusDiv.appendChild(btnDiv);
	$('lightbox').innerHTML = '';
	$('lightbox').appendChild(postStatusDiv);	
	Effect.Grow('lightbox', {duration: 0.5, direction: 'top-left', delay: 0.6});			

}

//--------------------------------------------------------------------

function closeLogin() {

	var hideTint = function() {
		Effect.Fade('lightboxTint', {duration: 0.75, from: 0.2, to: 0});	
		$('lightbox').update('');
	};
	
	Effect.Shrink('lightbox', {duration: 0.5, direction: 'top-left', afterFinish: hideOverlay});
	Effect.Fade('lightboxTint', {duration: 0.75, from: 0.2, to: 0});	
}

//--------------------------------------------------------------------

function hideOverlay() {
	$('lightboxOverlay').setStyle({display: 'none'});
	$('lightbox').innerHTML = '';
}


//--------------------------------------------------------------------
// showLogin
// Type: Common
//
// params: 
//      service - Label name for service, will identify the service
//				  to the user using this string
//		action -  url to post the form
//
//		title -	title of the content
//		content - body of the content
//
//--------------------------------------------------------------------

function showLoginBox(service, action, title, content) { 
//	$('serviceLogin').remove();
	
	var loginDiv = new Element('div', {'id': 'serviceLogin', 'class': 'overlayContainer', 'style': 'width: 400px; height: 240px;'});
	loginDiv.appendChild(new Element('div', {'class': 'overlayHeader'}).update('Log In'));
	loginDiv.appendChild(new Element('div', {'class': 'overlaySubhead'}).update('To post this content, please provide your '+service+' credentials. We won\'t keep them (or even look)'));
	var loginForm = new Element('form', {'id': 'loginForm', 'action': action, 'method': 'post', 'onsubmit': 'event.returnValue = false; return false;'});
	loginForm.observe('submit', submitLogin);
	
	// Create the form div
	var formDiv = new Element('div', {'style': 'width: 255px; margin-left: auto; margin-right: auto;'});
	
	
	formDiv.appendChild(new Element('input', {'type': 'hidden', 'id': 'loginAction', 'value': action}));
	formDiv.appendChild(new Element('input', {'type': 'hidden', 'class': 'loginSubmittable','id': 'title', 'value': title}));
	formDiv.appendChild(new Element('input', {'type': 'hidden', 'class': 'loginSubmittable','id': 'content', 'value': content}));	
	
	// Create the username input div
	var userDiv = new Element('div', {'class': 'input text', 'style': 'text-align: right'});
	userDiv.appendChild(new Element('label', {'for': 'email'}).update('Username'));
	userDiv.appendChild(new Element('input', {'type': 'text', 'class': 'loginSubmittable', 'id': 'username','style': 'margin-left: 5px; margin-bottom: 5px'}));
	
	// Append it to the form
	formDiv.appendChild(userDiv);
	
	// Create the password input div
	var passDiv = new Element('div', {'class': 'input password', 'style': 'text-align: right'});
	passDiv.appendChild(new Element('label', {'for': 'password'}).update('Password'));
	passDiv.appendChild(new Element('input', {'type': 'password', 'class': 'loginSubmittable', 'id': 'password', 'style': 'margin-left: 8px;'}));
	
	// Append it to the form
	formDiv.appendChild(passDiv);
	
	loginForm.appendChild(formDiv);
	
	// Add the progress spinner
	var progressDiv = new Element('div', {'id': 'progressSpinner', 'style': 'display: none;'});
	
	progressDiv.appendChild(new Element('img', {'src': '/images/loading.gif', 'width': 32, 'height': 32, 'alt': 'Posting content spinner'}));
	progressDiv.appendChild(new Element('span').update('Posting content to '+service+'...'));
	
	loginForm.appendChild(progressDiv);
	
	loginForm.appendChild(new Element('div', {'id': 'loginStatus', 'style': 'display: none; font-weight: bold; color: #bb0000; text-align: center; margin-top: 15px;'}));
	
	// Add the buttons
	var btnDiv = new Element('div', {'style': 'text-align: center; margin-top: 25px;'});
	var closeLink = new Element('a', {'href': '#'});
	closeLink.onclick = function() { closeLogin(); return false;}
	var closeImg = new Element('img', {'src': '/images/btn_cancel.png', 'alt': 'Close, do not post to ' + service});
	closeLink.appendChild(closeImg);
	btnDiv.appendChild(closeLink);

	var continueLink = new Element('input', {'type': 'image', 'src': '/images/btn_continue.png'});
	btnDiv.appendChild(continueLink);
	
	loginForm.appendChild(btnDiv);
	loginDiv.appendChild(loginForm);
	
	$('lightbox').appendChild(loginDiv);
	$('lightbox').setStyle({display: 'none'});
	$('lightboxOverlay').setStyle({display: 'block'});
	
	var showLogin = function() {
		Effect.Grow('lightbox', {duration: 0.5, direction: 'top-left', afterFinish: function() {$('username').activate();}});	
	};
	
    var arrayPageSize = this.getPageSize();
    $('lightboxOverlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
    $('lightboxTint').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });	
	
	Effect.Appear('lightboxTint', {duration: 0.25, from: 0, to: 0.2, afterFinish: showLogin});
}

function submitLogin() {
	var postVars = $H();
	$('loginStatus').hide();
	
	 $$('.loginSubmittable').each(function(submittable) {	 	
	 	postVars.set(submittable.id, submittable.value);
	 });
	 	
	new Ajax.Request($F('loginAction'), {
		method: 'post',
		parameters: postVars,
		requestHeaders: {Accept: 'application/json'},		
		onCreate: function() { $('progressSpinner').show()},
		evalJS: false,
		evalJSON: true,
		onSuccess: function(transport) {
			$('progressSpinner').hide();			
			var json = transport.responseText.evalJSON(true);		 
			if(json.postok) {
				Effect.Shrink('lightbox', {duration: 0.5, direction: 'top-left'});
				showSuccessBox(json.url);				
			} else {
				$('loginStatus').update(json.reason);
				$('loginStatus').show();				
			}
		}	
	});
	
	// Hopefully these convince the browser not to submit the form 
	// via normal means.
	event.returnValue = false;	
	return false;
}


//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/* These APIs we have not finished yet */
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

//--------------------------------------------------------------------
// shareFriendfeed
// Type: Share
//
// params: shareUrl - the URL that will be added to the feed
// 			title  - Title of the 'feed'
// Return true (success), false (fail)
//--------------------------------------------------------------------
function shareFriendfeed(url, title, target) {

	var postParams = new Hash();
	postParams.set('title', title);
	postParams.set('link', url);
	postParams.set('image0_url', 'http://www.peer2.com/images/logo.png');


	// Need HTTP Basic auth to make this work. Coming back to
	new Ajax.Request('http://friendfeed.com/api/share', {
		method: 'post',
		evalJSON: false,
		parameters: postParams
	});	
}


//--------------------------------------------------------------------
// shareTwitter
// Type: Share
//
// params: shareUrl - the URL that will be added to the feed
// Return true (success), error string on error
//--------------------------------------------------------------------
function shareTwitter(shareUrl) {	
	var updateString = 'Check out the latest on peer2.com: ' + shareUrl;
	var postParams = new Hash();
	postParams.set('status', updateString);
	
	new Ajax.Request('http://twitter.com/statuses/update.json', {
		method: 'post',
		parameters: postParams,
		onSuccess: function(transport) {
			alert('Success! ' + transport.responseText);
		}
	});	
}

//--------------------------------------------------------------------------------
// Borrowed from Lightbox
// http://www.huddletogether.com/projects/lightbox2/#download
//--------------------------------------------------------------------------------
function getPageSize() {
	        
    var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}




