/**
 * @author jgreen
 */

var fbLoggedInDest = null;

function fbSetup(){
	FB.init({appId: fbAppId, status: true, cookie: true, xfbml: true});
	FB.Event.subscribe('auth.sessionChange', loginChangeHandler);
	FB.getLoginStatus(loginCheckHandler);
}

function loginCheckHandler(response) {
    if (response.session) {
		//alert(response.perms)
      	// A user has logged in, and a new cookie has been saved
    	fbLoggedIn(response);
    } else {
      // The user has logged out, and the cookie has been cleared
    	fbLoggedOut();
    }
}

function loginChangeHandler(response) {
    if (response.session) {
      // A user has logged in, and a new cookie has been saved
    	fbLoggedIn(response);
    } else {
      // The user has logged out, and the cookie has been cleared
    	fbLoggedOut();
		window.location="/facebook/logout?redirect="+window.location;
    }
}

function fbLogin(){
}

/*
function fbLogin(){
    FB.login(function(response){
        if (response.session) {
            if (response.perms) {
				alert('fbLogin : logged in and have permissions');
                // user is logged in and granted some permissions.
                // perms is a comma separated list of granted permissions
            	if (!document.body.className.match(/fbUser/)) {
					//Element.addClassName(document.body,'fbUser')	
				}
			}
            else {
                // user is logged in, but did not grant any permissions
            }
        }
        else {
			alert('fbLogin : logged in and do not have permissions');
			if (document.body.className.match(/fbUser/)) {
     		   //Element.removeClassName(document.body, 'fbUser');
    		}
            // user is not logged in
        }
    }, {
        perms: ''
    });
}
*/

function fbLogout(){
	//alert('fbLogout');
    FB.logout(function(response){
        // user is now logged out
		window.location = "/facebook/logout?redirect="+window.location
    });
}

function fbLoggedIn(response){
	//alert('fbLoggedIn');
    if (!document.body.className.match(/fbUser/)) {
        Element.addClassName(document.body, 'fbUser')
    }
	if(fbLoggedInDest != null){
		var url = window.location
		window.location = fbLoggedInDest + "?url=" + url
	}
	//console.log(response.session)
	fbCheckFanStatus();
	fbCheckAdminStatus();
	fbCheckAdminPages(response.session.uid);
	
	fbCheckPerms(response.perms,"read_stream","fbReadStreamUser")
	fbCheckPerms(response.perms,"publish_stream","fbPublishStreamUser")

}

function fbCheckAdminPages(uid){
	//console.log("checking for admin pages!")
	var fql = "SELECT page_id, name from page WHERE page_id IN ( SELECT page_id FROM page_admin WHERE uid = " + uid + ")";
	//console.log("checking for admin pages!")
	FB.api({ method: 'fql.query', query: fql }, function(adminPages) {
		//console.log("length = " + adminPages.length);
		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 fbCheckAdminStatus(){
	//console.log('checking admin status');
	FB.api({ method: 'pages.isAdmin', page_id : fbAppId }, function(response){
		if(response){
			Element.addClassName(document.body,'fbAdminUser')
		}else{
			Element.removeClassName(document.body,'fbAdminUser')
		}
	});
}


function fbCheckFanStatus(){
	//console.log('checking fan status');
	FB.api({ method: 'pages.isFan', page_id : fbAppId }, function(response){
		//console.log(response)
		if(response){
			//console.log("we are a fan!");
			Element.addClassName(document.body,'fbFanUser')
		}else{
			//console.log("we are not a fan!");
			Element.removeClassName(document.body,'fbFanUser')
		}
	});
}


function fbCheckPerms(perms,target,className,negativeClassName){
	regex = /\{\"extended\":\[([^\]]*)\]/
	match = regex.exec(perms)
	if(match != null){
		perms = match[1]
	}else{
		perms = ""
	}
	//alert(perms)
	if( perms.indexOf(target) >= 0 ){
		Element.addClassName(document.body,className)
		if(negativeClassName){
			Element.removeClassName(document.body,negativeClassName)
		}
	}else{
		Element.removeClassName(document.body,className)
		if(negativeClassName){
			Element.addClassName(document.body,negativeClassName)
		}
	}
}


function fbLoggedOut(){
	//alert('fbLoggedOut');
    if (document.body.className.match(/fbUser/)) {
        Element.removeClassName(document.body, 'fbUser');
    }
}


function fbShareItemAsAppWall(itemType,itemId){
	
	attachment = buildAttachment(itemType,itemId);
	FB.ui({
        method: 'stream.publish',
        message: '',
		from: fbAppId,
        attachment: attachment,
        user_prompt_message: 'Tell your fans about this:'
    }, function(response){
        if (response && response.post_id) {
            //alert('Post was published.');
			shareCallback(itemType,itemId, response.post_id, null,fbAppId,fbAppId);
        }
        else {
            //alert('Post was not published.');
        }
    });
	

	//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 fbPageShareItem(itemType,itemId,pageForm){
	select = pageForm['fbPageId'];
	fbPageId = select.value;
	//alert("pageForm = " + fbPageId + " : " + select);
	attachment = buildAttachment(itemType,itemId);
	FB.ui({
        method: 'stream.publish',
        message: '',
		from: fbPageId,
        attachment: attachment,
        user_prompt_message: 'Tell your fans about this:'
    }, function(response){
        if (response && response.post_id) {
			shareCallback(itemType,itemId, response.post_id, null,fbPageId,fbPageId);
            //alert('Post was published.');
        }
        else {
            //alert('Post was not published.');
        }
    });
	
}


function fbShareItem(itemType, itemId){
	attachment = buildAttachment(itemType, itemId);
	FB.ui({
        method: 'stream.publish',
        message: '',
        attachment: attachment,
        user_prompt_message: 'Tell your friends about this:'
    }, function(response){
        if (response && response.post_id) {
			shareCallback(itemType,itemId, response.post_id, null,null,null);
            //alert('Post was published.');
        }
        else {
            //alert('Post was not published.');
        }
    });
}



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 fbShare(){
    var attachmentHash = {
        name: shareTitle,
        description: shareDescription,
        /*caption: 'The Facebook Connect JavaScript SDK',
         description: (
         'A small JavaScript library that allows you to harness ' +
         'the power of Facebook, bringing the user\'s identity, ' +
         'social graph and distribution power to your site.'
         <fb:login-button></fb:login-button>
         ),*/
        href: shareUrl
    }
	if (shareFlash != ""){
		attachmentHash['media'] = [{
			    "type": "flash", 
			    "swfsrc":shareFlash, 
			    "imgsrc": shareImg, 
			    "expanded_width": flashWidth, 
			    "expanded_height": flashHeight
			}]
	}else if (shareImg != "") {
        attachmentHash['media'] = [{
            'type': 'image',
            'src': shareImg,
            'href': shareUrl
        }]
    }
	
    FB.ui({
        method: 'stream.publish',
        message: '',
        attachment: attachmentHash,
        action_links: [{
            text: 'Rate it',
            href: shareUrl
        }],
        user_prompt_message: 'Share your thoughts about Connect'
    }, function(response){
        if (response && response.post_id) {
            //alert('Post was published.');
        }
        else {
            //alert('Post was not published.');
        }
    });
    /*
     var share = {
     method: 'stream.share',
     u: shareUrl
     };
     FB.ui(share, function(response) { alert(response); });
     */
    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
			}
		});
	}
}


/**************************************
 * Adapted from previous implementation
 */
function promptPublishStreamPermission(value){
	if (value && !document.body.className.match(/fbPublishStreamUser/g)) {
		FB.login(loginCheckHandler,{perms:'publish_stream'});
	}
}


function promptReadStreamPermission(value){
	if (value && !document.body.className.match(/fbReadStreamUser/g)) {
		FB.login(loginCheckHandler,{perms:'read_stream'});
	}
}


function promptReadLikesPermission(value){
	if (value && !document.body.className.match(/fbUserLikesUser/g)) {
		FB.login(loginCheckHandler,{perms:'user_likes'});
	}
}



function fbLoadPostComments(post_id){
	//alert("getting comments for " + post_id);
	if(!$("stream_post_comments_link_"+post_id)){
		return false;
	}
	$("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.parse(elem);
}



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.parse( $('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.parse( $('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;
    }
  }




/*********************************
 * Carried over directly from previous implementation
 */


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..."
	}
}


/******************************************
 * A few things that aren't directly FB related.
 * These should be refactored into a new spot
 * at some point.
 */



function addPostComment(){
		
	//alert("adding commet for " + commentable_id);
	//.disabled = true;
	form = $('comment-form');
	if($('comment_body').value == ''){
		alert("You haven't said anything.");
		return false;
	}
	
	Effect.toggle($('comment_spinner'));
	
	//If we're not logged in via FB, let the form
	//just post itself like normal.
	//This is a dirty hack.  Find a better way!
	if (!document.body.className.match(/fbUser/)) {
		return true;
	}
	
	
	parameters = form.serialize(true); 
	toggleForm(form,true);
	new Ajax.Request(document.location + "/add_comment", {parameters:parameters});
	//alert("sent the comment");
	return false;	
}



function regularCommentCallback(comment_id){
	
	form = $('comment-form');
	$('comment_body').value = '';
	toggleForm(form,false);
	Effect.toggle($('comment_spinner'));
	
	FB.XFBML.parse( $('comment_' + comment_id) );
	new Effect.Highlight( $('comment_' + comment_id) );
	
}
