var fbPage = 'https://graph.facebook.com/posts?ids=notamedia';
var facebookLink = new Object();
var accessToken = false;


		
facebookLink.splitCount = 2;

facebookLink.addComment = function($textObj)
{
	$pageId = $textObj.attr('rel');
	$text = $textObj.val();
	$.ajax(	
	{
		url: '/facebook/post_comment/',
		type: 'POST',
		data: { 'post_id': $pageId, 'text': $text },
		success: function()
		{
			facebookLink.updatePostComments();
		}
	}
	);
}

facebookLink.addLike = function($textObj)
{
	$pageId = $textObj.attr('rel');
	$.ajax(	
	{
		url: '/facebook/like_post/',
		type: 'POST',
		data: { 'post_id': $pageId },
		success: function()
		{
			facebookLink.updatePostComments();
		}
	}
	);
}

facebookLink.doLinkPostNoMCE = function(href)
{
		$rel = $(href).attr('rel');
		$.ajax({
				url: '/editor/vacancies/fb_bind',
				data: {fb_post: $rel}
		});
		
}

facebookLink.doLinkPost = function(href)
{
	facebookLink.fbLinkPostPopup.fadeOut();
	$hrefObj = $(href);
	$html = '';
	if( tinyMCE.activeEditor )
		{
		$html =	tinyMCE.activeEditor.getContent({format : 'raw'});
	}

	$contentField = $('textarea[name=content]');

	if( $contentField.length > 0)
		{
		$html = $contentField.val();
	}	

	$rel = $hrefObj.attr('rel');

	// clear existing links
	$html = $html.replace(/<!--\s+fb-post\:.*?\s+-->/, '');
	$html += '<!-- fb-post:' + $rel + ' -->';
	//$content.html($html);

	if( tinyMCE.activeEditor )
		{
		tinyMCE.activeEditor.setContent($html, {format : 'raw'});
	}

	if( $contentField.length > 0 )
		{
		$contentField.val($html);
	}	


	//alert(href);

	//alert($rel);
}

facebookLink.linkPost = function(href,isVacancy)
{
	isVacancy = isVacancy || false;
	$hrefObj = $(href);
	$postId = $hrefObj.attr('rel');
	facebookLink.fbPostSelectList.empty();		
	facebookLink.fbLinkPostPopup.offset($hrefObj.offset());

	facebookLink.fbLinkPostPopup.slideDown();	

	$this = facebookLink.fbPostSelectList;
	
	FB.api('/notamedia/posts?'+accessToken, function(response)
	{
		for(i = 0; i < response.data.length; ++i)
			{
			post = response.data[i];
			var append_txt;
			if(isVacancy)
					append_txt = '<a href="#" onclick="javascript:facebookLink.doLinkPostNoMCE(this)" rel="' + post.id + '">' + post.name + '</a>';
			else
					append_txt = '<a href="#" onclick="javascript:facebookLink.doLinkPost(this)" rel="' + post.id + '">' + post.name + '</a>';
			$this.append(append_txt);
			// 			$this.append('<div><small>' + post.message + '</small></div>');					
			//			$this.append('<div>' + post.description + '</div>');
			$this.append('<br/>');    
		}
	});						

	return;	
	$.ajax(
	{
		url: '/facebook/link_post',
		type: 'POST',
		data: { 'post_id': $post_id },
		success: function()
		{

		}
	} );
}

$( function(){ 

	$.ajax({url: '/facebook/get_access_token/',
					success: function(data){accessToken = data;}
	});
				 
		
	window.fbAsyncInit = function(){
//debugger;
		FB.init({ appId: '6f3d009df4472bdef30e498108a9fd68', status: true, cookie: true, xfbml: true });

		facebookLink.postHolder = $('._fb_posts');
		facebookLink.fbRootHolder = $('#fb-root');
		//$('body').append('<div class="facebookLinkPost" id="facebookLinkPost"><a href="#" onclick="$(this).parent().slideUp()">Закрыть</a><div id="fbPostSelectList"></div></div>');
		facebookLink.fbLinkPostPopup = $('#facebookLinkPost');
		facebookLink.fbPostSelectList = $('#fbPostSelectList');                            

		facebookLink.postHolder.each( function(_obj)
		{
			$this = $(this);

			$pageId = $this.attr('rel');
			$reqUrl = '/' + $pageId + '/posts';

			FB.api($reqUrl, function(response)
			{
				for(i = 0; i < response.data.length; ++i)
					{
					post = response.data[i];
					$this.append('<h3>' + post.name + '</h3>');
					$this.append('<div><small>' + post.message + '</small></div>');					
					$this.append('<div>' + post.description + '</div>');

					if( post.comments && post.comments.data.length )
						{
						for(j = 0; j < post.comments.data.length; ++j)
							{					
							comment = post.comments.data[j];
							$this.append('<div style="padding-left:3em"><small>' + comment.from.name + ': </small>' + comment.message + '</div>');
						}
					}

					$this.append('<br/>');    
				}
			});			
		});

		facebookLink.postCommentHolder = $('._fb_post_comments');
		facebookLink.commentCountHolder = $('._fb_comment_count');           		
		facebookLink.likeCountHolder = $('._fb_like_count');           		
		facebookLink.firstLikeNames = $('._fb_like_first_names');
		facebookLink.otherLikeCount = $('._fb_other_like_count');		
		facebookLink.likeHolder = $('._fb_likes');           		
		facebookLink.otherLikeHolder = $('._fb_other');           		
		facebookLink.likeButton = $('._fb_like_button');           
		facebookLink.totalLikeCount = $('._fb_total_like_count');		
		

	
		facebookLink.updatePostComments = function()
		{
                                                var hasComments=false;
			facebookLink.postCommentHolder.each( function(_obj)
			{
        hasComments = true;
				$this = $(this);
				$this.empty();
				$postId = $this.attr('rel');
				$reqUrl = '/' + $postId + '/comments';
				$this.hide();

				FB.api($reqUrl, function(response)
				{

					$ul = $('<ul class="commentsList"></ul>');

					for(i = 0; i < response.data.length; ++i)
						{
						comment = response.data[i];
						time = comment.created_time;
						time = time.replace(/T/, ' ');
						time = time.replace(/\+\d+/, '');
						$ul.append('<li><div class="descr">'+ comment.message +'</div><div class="name"><img src="/facebook/get_avatar/' + comment.from.id + '"/><br/><a href="http://www.facebook.com/profile.php?id=' + comment.from.id + '">' +
						comment.from.name + '</a><span class="date">' + time + '</span></li>');
					}
					$this.append('<h2>Комментарии <span>(' + response.data.length + ')</span></h2>');
					$this.append($ul);
					$this.slideDown();

					facebookLink.firstLikeNames.empty();

					$reqUrl = '/' + $postId + '/likes';
					FB.api($reqUrl, function(response)
					{
						if(response.data.length > 0)
							{
							likeCount = response.data.length;
              facebookLink.totalLikeCount.text(likeCount);
							firstLikeCount = Math.min( facebookLink.splitCount, likeCount );
							otherLikeCount = likeCount - firstLikeCount;
							if(otherLikeCount % 10 < 5)
							{
							 	firstLikeCount += otherLikeCount % 10;
							 	otherLikeCount -= otherLikeCount % 10;
							}

							for(i = response.data.length - 1; i >= otherLikeCount; --i)
								{
								like = response.data[i];
								if(i < response.data.length - 1) facebookLink.firstLikeNames.append(', ');
								facebookLink.firstLikeNames.append("<a href='http://www.facebook.com/profile.php?id=" + like.id + "'>" + like.name + "</a>");
							}
							facebookLink.otherLikeCount.text(otherLikeCount);
							facebookLink.likeHolder.show();
							if(otherLikeCount > 0) facebookLink.otherLikeHolder.show();
						}
					});						
				});
			});
      
      if(!hasComments)
      {
      	$postId = facebookLink.likeButton.attr('rel');
        $reqUrl = '/' + $postId + '/likes';
        FB.api($reqUrl, function(response)
        {
        	if(response.data.length > 0)
          {
          	likeCount = response.data.length;
            facebookLink.totalLikeCount.text(likeCount);
          }
        });
      }
      
		}

		facebookLink.updateCommentCount = function()
		{
			facebookLink.commentCountHolder.each( function(_i, _obj)
			{
				$this = $(_obj);
				$this.hide();          								
				$postId = $this.attr('rel');
				$reqUrl = '/' + $postId + '/comments';

				FB.api($reqUrl, function(response)
				{
					$(_obj).text(response.data.length);					
					if(response.data.length > 0) $(_obj).fadeIn();
				});

			});

		}

		facebookLink.updatePostComments();
		facebookLink.updateCommentCount();        


		if( window.location.search.indexOf('session') != -1 )
		{
			window.location = location.pathname;
		}

	};

	(function(){
		var e = document.createElement('script');
		
		e.async=true;
		e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';

		document.getElementById('fb-root').appendChild(e);
	}());
});

