/**
 * @author jgreen
 */
Event.observe(window, 'load',
      function() { fbSetup(); }
    );


function request_param( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function fbSetup(){
//FB.XFBML.Host.parseDomTree();
//the 'initFaceBookConnect' function is embeded at the bottom of the page.
initFaceBookConnect();
}

function initFaceBookConnect(){
	FB_RequireFeatures(["XFBML"], function() {
              FB.init(fbApiKey,"xd_receiver.htm",{"ifUserConnected" : fbIsLoggedIn, "ifUserNotConnected":fbIsLoggedOut});
	});
}

function fbLogin(url) {
	// add in some XFBML. note that we set useyou=false so it doesn't display "you"
	//window.location = window.location
	if(url == null || url == ''){
		url = window.location
	}
	window.location = "/facebook/link_user_accounts?url=" + url
	//FB.XFBML.Host.parseDomTree();
}



function fbIsLoggedIn(){
	if (!document.body.className.match(/fbUser/)) {
		Element.addClassName(document.body,'fbUser')	
	}
	FB.ensureInit(function () { 
	
		var sequencer = new FB.BatchSequencer();
		var adminFql = "SELECT page_id, name from page WHERE page_id IN ( SELECT page_id FROM page_admin WHERE uid = " + FB.Connect.get_loggedInUser() + ")";
		//alert(adminFql);
		var adminResult = FB.Facebook.apiClient.pages_isAdmin(fbAppId,sequencer);
		var fanResult = FB.Facebook.apiClient.pages_isFan(fbAppId,FB.Connect.get_loggedInUser(),sequencer);
		var appPermissionResult = FB.Facebook.apiClient.users_hasAppPermission('publish_stream',sequencer);
		var appReadPermissionResult = FB.Facebook.apiClient.users_hasAppPermission('read_stream',sequencer);
		var adminPages = FB.Facebook.apiClient.fql_query(adminFql,sequencer);
		sequencer.execute(function(){
			adminCallback(adminResult.result);
			fanCallback(fanResult.result);
			publishStreamCallback(appPermissionResult.result);
			readStreamCallback(appReadPermissionResult.result);
			adminPageCallback(adminPages.result)
		});
		
	});
}


function fbIsLoggedOut(){
	if (document.body.className.match(/fbUser/)) {
		Element.removeClassName(document.body,'fbUser');
	}
	param = request_param("facebook_connect");
	//alert("param = " + param);
	if(request_param("facebook_connect")=="true" || request_param("facebook_connect")=="true/index.html"){
		FB.Connect.requireSession(fbLogin, isUserActionHint=true);
	}
}


function adminPageCallback(adminPages){
	//alert(adminPages);
	//alert("adminPages.length = " + adminPages.type);
	
	
	if(adminPages.length > 0){
		$A(adminPages).each(function(page){
			populatePageSelectors(page);
		});
		Element.addClassName(document.body,'fbOtherPageAdminUser');
	}else{
		Element.removeClassName(document.body,'fbOtherPageAdminUser');
	}
}

function populatePageSelectors(page){
	$$(".fbPageShare .fbPageSelect").each(function(select){
		option = new Element('option', {value:page["page_id"]}).update(page["name"])
		select.appendChild(option)
	});
}


function adminCallback(status){
	if(status){
		Element.addClassName(document.body,'fbAdminUser')
	}else{
		Element.removeClassName(document.body,'fbAdminUser')
	}
	
}


function publishStreamCallback(status){
	//alert("stream publish = " + status);
	if(status){
		Element.addClassName(document.body,'fbPublishStreamUser')
	}else{
		Element.removeClassName(document.body,'fbPublishStreamUser')
	}
	
}



function readStreamCallback(status){
	//alert("read_stream = " + status);
	if(status){
		//alert("addmin className");
		Element.addClassName(document.body,'fbReadStreamUser')
	}else{
		Element.removeClassName(document.body,'fbReadStreamUser')
	}
	
}

function fanCallback(status){
	//alert("fan = " + status);
	if(status){
		Element.addClassName(document.body,'fbFanUser')
	}else{
		
		Element.removeClassName(document.body,'fbFanUser')
	}
}



function reloadStream(result){
	if(result != null && result != ''){
		window.location =  "/facebook/reload_stream?url=" + window.location;
	}
}


function fbCommentFocus(commentable_id){
	form = $('comment-form_'+commentable_id);
	if (form['comments'].value == "Write a comment...") {
		form['comments'].value = ""
	}
	form.removeClassName('fbInactive');
	//alert("comment focus " + commentable_id)
}

function fbCommentBlur(commentable_id){
	setTimeout(function(){fbCommentBlurImpl(commentable_id)},2000);
	//alert("comment blur " + commentable_id)
}

function fbCommentBlurImpl(commentable_id){
	form = $('comment-form_'+commentable_id);
	comment = form["comments"].value
	if (comment == '' || comment == "Write a comment...") {
		form.addClassName('fbInactive');
		form['comments'].value = "Write a comment..."
	}
}


function writeOnFriendsWall(friendId){
	FB.Connect.streamPublish('', '', null, friendId);

}

function createSubApp(){
	FB.Connect.createApplication("test app",appCreated);
}

function appCreated(response){
	alert(response);
}


function updateStatus(){
	FB.Connect.streamPublish("",null,null,null,"Please update your status.");
}



function writeOnPageWall(){
	FB.Connect.streamPublish("",null,null,fbAppId,"Please let us know what you think.",reloadStream);
}

function buildAttachment(itemType,itemId){
	title = $(itemType + "_" + itemId + "_title").value;
	href = $(itemType + "_" + itemId + "_href").value;
	description = $(itemType + "_" + itemId + "_description").value;
	asset_url = $(itemType + "_" + itemId + "_asset_url").value; 
	comments_xid = $(itemType + "_" + itemId + "_comments_xid").value;
	media = null;
	
	attachment = {'name':title,'href':href,'description':description,'comments_xid':comments_xid}; //,'media':media
	if(asset_url != null && asset_url != ''){
		attachment['media'] = [ {'type': 'image', 'src': asset_url, 'href': href} ];
	}
	return attachment;
}


function fbPageShareItem(itemType,itemId,pageForm){
	select = pageForm['fbPageId'];
	fbPageId = select.value;
	//alert("pageForm = " + fbPageId + " : " + select);
	attachment = buildAttachment(itemType,itemId);
	var action_links =[]; // [{'text':'Do something something', 'href':href}];
	var targetId = null;
	FB.Connect.streamPublish("", attachment, action_links, targetId, "Tell your fans about this.", function(fb_id, exception){
		shareCallback(itemType,itemId, fb_id, exception,targetId,fbPageId);
	}, false, fbPageId);
	
}

function fbShareItem(itemType,itemId){
	attachment = buildAttachment(itemType,itemId);
	/*FB.Connect.streamPublish("",attachment,null,null,"",function(fb_id, exception){
		shareCallback(post_id, "post", fb_id, exception);
	}, false, null);*/
	FB.Connect.streamPublish("", attachment, null,null, "", function(fb_id, exception){
		shareCallback(itemType,itemId, fb_id, exception,null,null);
	}, false, null);
}

/*
function shareBlogPostOnAppWall(post_id){
	//alert('trying to share ' + post_id);
	title = $("post_" + post_id + "_title").value;
	href = $("post_" + post_id + "_href").value;
	description = $("post_" + post_id + "_description").value;
	asset_url = $("post_" + post_id + "_asset_url").value; 
	comments_xid = $("post_" + post_id + "_comments_xid").value;
	attachment = {'name':title,'href':href,'description':description,'comments_xid':comments_xid}
	if(asset_url != null && asset_url != ''){
		attachment['media'] = [ {'type': 'image', 'src': asset_url, 'href': href} ];
	}
	//alert('comments_xid = ' + attachment['comments_xid']);
	var action_links =[]; // [{'text':'Do something something', 'href':href}];
	var targetId = fbAppId;
	FB.ensureInit(function () { 
	FB.Connect.streamPublish("",attachment,action_links,targetId,"Tell your fans about this.",function(fb_id, exception){
		shareCallback(post_id,"post",fb_id, exception);
	},false,null);
	});
}
*/
function fbShareItemAsAppWall(itemType,itemId){
	
	attachment = buildAttachment(itemType,itemId);
	var action_links =[]; // [{'text':'Do something something', 'href':href}];
	var targetId = null;//fbAppId;

	FB.Connect.streamPublish("", attachment, action_links, targetId, "Tell your fans about this.", function(fb_id, exception){
		shareCallback(itemType,itemId, fb_id, exception,targetId,fbAppId);
	}, false, fbAppId);

	return false;

}

function shareCallback(itemType,itemId,fb_id, exception,targetId,actorId){
	//alert("fb_id = " + fb_id);
	if (fb_id != null && fb_id != '' && fb_id != 'null') {
		//alert(fb_id);
		new Ajax.Request("/facebook/save_fb_post", {
			parameters: {
				fb_post_id: fb_id,
				fb_target_id: targetId,
				fb_actor_id: actorId,
				postable_type: itemType,
				postable_id: itemId
			}
		});
	}
}




function postLink(){
	attachment = {'name':'Google','href':'http://www.google.com/','description':'Really!? You have never heard of Google?'}
	FB.Connect.streamPublish("",attachment,null,null,"Please update your status.");
}


function postPic(){
attachment = {
	'name': 'An afternoon on the mall',
	'href': 'http://www.flickr.com/photos/rhythmandcode/4327390470/',
	'caption': '{*actor*} rated this 5 stars',
	'description': 'The National Mall in Washington DC stretches from the Lincoln Memorial and on past the Washington Monument. This is the view from the top of the Old Post Office building at 12th and Pennsylvania.',
	'properties': {
		'category': { 'text': 'pics', 'href': 'http://www.flickr.com/photos/rhythmandcode/'},
		'ratings': '5 stars'
	},
	'media': [{ 'type': 'image', 'src': 'http://farm3.static.flickr.com/2801/4327390470_8cfd1238ed_o.jpg', 'href': 'http://www.flickr.com/photos/rhythmandcode/4327390470/'},
		{ 'type': 'image', 'src': 'http://farm3.static.flickr.com/2610/4186142807_a82fdc361e.jpg', 'href': 'http://www.flickr.com/photos/rhythmandcode/4186142807/'}
	]
	}; 
	
	FB.Connect.streamPublish("",attachment,null,null,"Please update your status.");
}


function addComment(commentable_id){
	//alert("adding commet for " + commentable_id);
	//.disabled = true;
	form = $('comment-form_' + commentable_id);
	if(form['comments'].value == ''){
		alert("You haven't said anything.");
		return false;
	}
	parameters = form.serialize(true); 
	toggleForm(form,true);
	Effect.toggle($('spinner_' + commentable_id));
	new Ajax.Request('/facebook/add_comment', {parameters:parameters});
	//alert("sent the comment");
	return false;	
}


function addStreamComment(commentable_id){
	//alert("adding commet for " + commentable_id);
	//.disabled = true;
	form = $('comment-form_fbPost_' + commentable_id);
	if(form['comments'].value == ''){
		alert("You haven't said anything.");
		return false;
	}
	parameters = form.serialize(true); 
	toggleForm(form,true);
	Effect.toggle($('spinner_fbPost_' + commentable_id));
	new Ajax.Request('/facebook/add_stream_comment', {parameters:parameters});
	//alert("sent the comment");
	return false;	
}


function postedCommentCallback(commentable_id,comment_id){
	FB.XFBML.Host.parseDomElement( $('comment_' + comment_id) );
	new Effect.Highlight( $('comment_' + comment_id) );
	form = $('comment-form_' + commentable_id);
	form['comments'].value = '';
	form['comments'].blur();
	toggleForm(form,false);
	Effect.toggle($('spinner_' + commentable_id));
}

function postedStreamCommentCallback(commentable_id,comment_id){
	FB.XFBML.Host.parseDomElement( $('comment_' + comment_id) );
	new Effect.Highlight( $('comment_' + comment_id) );
	form = $('comment-form_fbPost_' + commentable_id);
	form['comments'].value = '';
	form['comments'].blur();
	toggleForm(form,false);
	Effect.toggle($('spinner_fbPost_' + commentable_id));
}


function deletedCommentCallback(comment_id){
	Effect.DropOut("comment_"+comment_id);
}


function destroyComment(commentId,xid,objectId){
	if(confirm("Are you sure you want to delete this comment?  There is no udo.")){
		//document.location = "add_comment.js.rjs?comment_id=" + commentId + "&xid=" + xid + "&object_id=" + objectId + "&url=" + window.location;
		$('comment_'+commentId).addClassName('fbDeleting');
		new Ajax.Request('/facebook/remove_fb_comment', {parameters:{comment_id:commentId,xid:xid,object_id:objectId,url:window.location} });
	}
	return false;
}


function toggleForm(form,disabled) {
    var limit = form.elements.length;
    for (i=0;i<limit;i++) {
      form.elements[i].disabled = disabled;
    }
  }


function promptPublishStreamPermission(value){
	//alert('checking!')
	if (value && !document.body.className.match(/fbPublishStreamUser/g)) {
		FB.Connect.showPermissionDialog("publish_stream",publishStreamCallback);
	}
}


function promptReadStreamPermission(value){
	//alert('checking!')
	if (value && !document.body.className.match(/fbReadStreamUser/g)) {
		FB.Connect.showPermissionDialog("read_stream",readStreamCallback);
	}
}


function promptAppReadStreamPermission(value){
	//alert('checking!')
	//if (value && !document.body.className.match(/fbReadStreamUser/g)) {
		FB.Connect.showPermissionDialog("read_stream",null,true,fbAppId);
	//}
}



function fbLoadPostComments(post_id){
	//alert("getting comments for " + post_id);
	$("stream_post_comments_link_"+post_id).update("<img src='images/spinner_moz.gif'/>");
	new Ajax.Request("/facebook/update_stream_post_comments", {
			parameters: {
				fb_post_id: post_id
			}
		});
	return false;
}

function fbLoadPostCommentsCallback(post_id){
	elem = $('stream_post_comments_'+post_id);
	FB.XFBML.Host.parseDomElement(elem);
}



function getSiteFriends(){
	
	//new Ajax.Request('/facebook/site_friends');
}

function updateSiteFriends(friends){
	if(friends == null || friends == ''){return;}
	//alert("friends = " + friends);
	$$('.friendSelector').each(function(elem){
		var newDiv = document.createElement('div');
		
		//alert('doing an elem');
  		html = elem.innerHTML;
  		html = html.replace('exclude_ids=""','exclude_ids="'+friends+'"');
  		newDiv.className = elem.className;
  		newDiv.innerHTML = html;
  		elem.insert({before:newDiv});
  		elem.remove();
  		//elem.innerHTML = '';
  		//elem.childElements().each(function(e2){
  		//	elem.remove(e2);
  		//});
  		//elem.innerHTML = html;
  		FB.XFBML.Host.parseDomElement(newDiv);
  	});
  	//FB.XFBML.Host.parseDomTree();
}

function fbLogout(){
	FB.Connect.logoutAndRedirect("http://"+window.location.hostname+"/facebook/logout?redirect="+window.location);
	//fbIsLoggedOut();
	
  	//window.location="/facebook/logout?redirect="+window.location;
	//FB.XFBML.Host.parseDomTree();
}
