/**
 * Billboard Social
 *
 */
billboard.social = new ( function($) 
{
	var URL_CF_RATING = "rest/v1/rating/entity/create";
	var URL_CF_RATING_COMMENT_CREATE = "rest/v1/rating/comment/create";
	var URL_CF_USERGET = "rest/v1/user/get";
	var URL_CF_ENTITYGET = "rest/v1/entity/get";
	var URL_CF_ENTITYBROWSE = "rest/v1/entity/browse";
	var URL_CF_ENTITYCOUNT = "rest/v1/entity/count";
	var URL_CF_CONNECTION_CREATE = "rest/v1/connection/create";
	var URL_CF_CONNECTION_DELETE = "rest/v1/connection/delete";
	var URL_CF_CONNECTION_BROWSE = "rest/v1/connection/browse";
	var URL_CF_SEARCH = "rest/v1/search";
	var URL_CF_ADD_COMMENT = "rest/v1/comment/entity/create";
	var URL_CF_GET_COMMENT = "rest/v1/comment/entity/get";
	var URL_CF_GET_BOARD_COMMENT = "rest/v1/comment/board/get";
	var URL_CF_GET_HIGHESTRATED = "rest/v1/query/entity/highest_rated";
	var URL_CF_ACTIVITY_CREATE = "rest/v1/activityevent/create";
	var URL_CF_ACTIVITY_GET = "rest/v1/activityevent/get";
	var URL_CF_ATTR_USER_ADD = "rest/v1/attribute/user/add";
	var URL_CF_ATTR_USER_GET = "rest/v1/attribute/user/get";
	var URL_CF_ATTR_ENTITY_ADD = "rest/v1/attribute/entity/add";
	var URL_CF_USER_CREATE = "rest/v1/user/create";
	var URL_CF_ADD_BOARD = "rest/v1/board/group/add";
	var URL_CF_GROUP_GET = "rest/v1/group/get";
	var URL_CF_MESSAGEBOARD_GET = "rest/v1/board/get";
	var URL_CF_MESSAGEBOARD_COMMENT_CREATE = "rest/v1/comment/board/create";
	var URL_CF_POLL_GET = "rest/v1/poll/get";
	var URL_CF_POLL_VOTE = "rest/v1/poll/vote";
	
	var URL_CF_LOGIN = "rest/auth/login";
	var URL_CF_LOGOUT = "rest/auth/logout";
	
	var URL_CF_PROXY_LOGIN = 		 "/user/community/cf-login.json?url=";
	var URL_BB_ENTITYCREATE =        "/user/community/create-entity.json";
	var URL_BB_FOLLOWERS =           "/user/community/get-followers.json?user=";
	var URL_BB_FOLLOWING =           "/user/community/get-friends.json?user=";
	var URL_BB_MESSAGEBOARD_CREATE = "/user/create-messageboard.json";
	
	var RATING_LOVEHATE = "CustomRating0";
	
	var me = this;
	me.entityCache = [];
	
	/**
	 * start 'er up -
	 */
	me.init = function()
	{
		/**
		 * register event listeners
		 */
		billboard.broadcaster.addListener( "pageLoaded", me.onPageLoaded );	
		billboard.broadcaster.addListener( "userLoggedIn", me.onLoggedIn );
	};
	
	/**
	 * find any love hate meters, and update their information based on the
	 * entity they're associated to
	 */
	me.onPageLoaded = function()
	{
		/**
		 * love/hate dialog boxes
		 */
		$(".meter .hate").hover(
								function() {
									$(this).parents(".love-bar").find(".hate-dialog").show();
								}
								,function() {
									$(this).parents(".love-bar").find(".hate-dialog").hide();
								}
								);
		
		$(".meter .love").hover(
								function(){
			$(this).parents(".love-bar").find(".love-dialog").show();
		}
								,function(){
									$(this).parents(".love-bar").find(".love-dialog").hide();
								}
								);
		
		$(".user-comments").click( function(){
			var jump = ($("#comment-container .filter-nav").length>0) ? $("#comment-container .filter-nav").offset().top : 0;
			$('html,body').animate( {scrollTop: jump }, 1000 );
		});

		/**
		 * activate any love/hate bars
		 */
		$(".meter .hate").click( function() {
			var id = $(this).parents(".love-bar").find(".entityId").text();
			var thisptr = $(this).parents(".love-bar");
			var el = $(this);
			billboard.user.requireLogin( function() {
				me.hate( id, el, function(data) { 
					billboard.log( "onHateResult("+data+")");
					thisptr.find(".meter div").text( data.loveHateTotal + " votes" );
					thisptr.find(".love-meter-container .percentage").text( data.loveHatePercentage + "%" );
					thisptr.find(".meter .hate span").css("background-position","left bottom");
					thisptr.find(".meter .love span").css("background-position","right bottom");
					var numWidth = parseInt($(".meter").css("width"));
					var w = Math.round((numWidth - 48) * (data.loveHatePercentage/100));
					thisptr.find(".meter").css("background-position",24+w+"px");

					
				});
				//billboard.facebook.publish("hate",el);
				//googleA.trackSocialEvent("Hated", el);
			});
		});

		$(".meter .love").click( function() {
			var id = $(this).parents(".love-bar").find(".entityId").text();
			var thisptr = $(this).parents(".love-bar");
			var el = $(this);
			billboard.user.requireLogin( function() { 
				me.love(id,  el, function(data) { 
					billboard.log( "onLoveResult("+data+")");
					thisptr.find(".meter div").text( data.loveHateTotal + " votes" );
					thisptr.find(".love-meter-container .percentage").text( data.loveHatePercentage + "%" );
					thisptr.find(".meter .hate span").css("background-position","left bottom");
					thisptr.find(".meter .love span").css("background-position","right bottom");
					var numWidth = parseInt($(".meter").css("width"));
					var w = Math.round((numWidth - 48) * (data.loveHatePercentage/100));
					thisptr.find(".meter").css("background-position",24+w+"px");
				});
				
				//billboard.facebook.publish("love",el);
				//googleA.trackSocialEvent("Loved", el);
			});
		});
		
		/**
		 * this seems to be a consistent selector for the 'page' level love/hate bars of type 'news'
		 */
		me.updateLoveHateBar( "#comment-share" ); // news
		me.updateLoveHateBar( ".love-hate-box" ); // column,column feature
		
		/**
		 * many objects in this site can be social entities, which basically means
		 * they can be commented on and/or rated.  
		 * if they are properly wrapped and assigned the necessary classes
		 * this function will get the necessary info to display
		 * 
		 * The structure:
		 *   - the top level node of this specific entity's markup must have the class 'social-entity'
		 *   - under that there must be a <div> with the class 'entity-id' and text content 
		 *     of the entities billboard generated uniqueId, which is formatted as [type]-[id]
		 *     for example: article-100122 or song-16512
		 *   - if a node exists under the social-entity node with the class 'percent-like' it 
		 *     will be populated with the current rating percentage
		 *   - if a node exists under the social-entity node with the class 'total-comments' it
		 *     will be populated with the current number of comments on that entity
		 */
		$(".social-entity").each( function( i, item ) {
			me.updateItemInfo( item );
		});
		
        if(billboard.section == 'profile' && $("#profile-photo").length > 0){
        	var user;
        	if(billboard.user.isLoggedIn() && billboard.user.username == billboard.publicUser){
        		user =  billboard.publicUser
        		billboard.info("billboard.publicUser: " + user)
        	}else{
        		user = billboard.user.username
        		billboard.info("billboard.user.username: " + user)
        	}
            me.getUser(
					  user 
					   , function(data){
				if (data.user.profile_photo_url != null){
					$("#profile-photo").attr("src",data.user.profile_photo_url);
				}
			}
					   );
        }
		
        var poll = $(".poll-container");
        if (poll.length > 0){
            $.each(poll,function(i,v){
                me.execute( 
						   URL_CF_POLL_GET
						   , { name : $(v).attr("id") }
						   , function(data){
							   if(data.error_code && data.error_code > 0) {
								   $(v).html(data.error_str + " - " + data.error_detail);
							   } else {
								   var output = '<div class="poll-header">'
									   + '<h2>Poll</h2>'
									   + '<p class="poll-question">'
									   + data.poll.question
									   + '</p>'
									   + '</div>'
									   + '<div class="status-container">'
									   + '<ul class="poll-options">';
								   $.each(data.poll.answers,function(i,v){
									   output +=  '<li id="answer-' + v.id + '">'
										   + '<div class="indicator">&nbsp;</div>'
										   + '<p>' 
										   + v.answer 
										   + '</p>'
										   + '<div class="checkmark">&nbsp;</div>'
										   + '</li>';
								   });
								   output += '</ul>'
									   + '</div>';
								   $(v).html(output);
								   me.initPoll($(v));
							   }
						   }
						   );
            });
        }
		
		if (billboard.user.username != "" && billboard.user.username != null) {		
			billboard.log('Getting Followers>>');
			me.browseConnections(billboard.user.username,'following', me.sort,function(user){
				for(var i=0;i<user.connections.length;i++){
					if(billboard.publicUser==user.connections[i].to_user.external_id)
					$('.profile .header .follow').hide();
				}
			});		
		}
		if(billboard.section=='forums' && billboard.subsection=='forum-landing'){			
			me.initForumsLanding();		
		}
	};
	
	/**
	 *
	 */
   
	me.initForumsLanding=function(){
		var id,oper;
		$('#forums-table .forums-entityId').each(function(i){		
			oper=$(this);
			id=$(this).find('td').html();
			me.getForumsBoards( id, {order:"MostRecentlyCommented"},oper,me.updateForumsLanding );
		
		});
	
	};
	
	me.getForumsBoards = function( id, options,oper, callback ) 
	{
		
		var params = {};
		params.category = id.split("-")[1];
		params.offset = (options.start)?(options.start):0;
		params.max_return = (options.count)?(options.count):100;
		params.comment_period = "LastYear";
		if ( options.order ) params.order = options.order;
		
		me.browseEntity( params, function(data) { 
			var ents = data.entities;
			var boards = new Array();
			for ( var i=0;i<ents.length;i++ ) {
				try { 
					boards.push( { id:ents[i].uid,
										  title:ents[i].title.split("||")[0],
										  user:ents[i].title.split("||")[1],
										  numReplies:ents[i].comments_count,
										  modified:ents[i].last_modified } );
				} catch( ex ) { }
			}
			var result = { numBoards:boards.length, boards:boards };
			callback(result,oper);
		});
		
		
	};
	me.updateForumsLanding=function(response,oper){
	
	    var modified="No post yet";		
		oper.find('.forum-topics').html(response.numBoards);
		if(response.boards.length>0){
		modified=response.boards[0].modified 
		modified-= 1000*60*60;
		modified= formatDate( modified, true, "HH:MM:SS" );
		}
		oper.find('.forum-lastPost').html(modified);
	
	}
	
	me.getExecuteUrl = function(url, params){
		var props = billboard.properties;
		if ( typeof(props) == "undefined" ) {
			billboard.error( "Billboard Properties are NULL" );
			return;
		}
		url = props.proxyPrefix + props.cfConsumerUrl + url + "?" + props.cfQuery;
		for ( var p in params ) {
			url += "&"+p+"="+params[p];
		}
		url += "&cachebust=" + (new Date()).getTime();
        return url;
    };
	
	/**
	 * generic method to execute a crowdfactory rest api call with
	 * several params, and a callback - avoids having to construct URLs all over the place
	 */
	me.execute = function( url, params, callback ) 
	{
        url = me.getExecuteUrl(url, params);
		billboard.log("Social.execute("+url+")");
		
		$.getJSON( url, function(data) { 
				if ( data.error_code == 106 ) {
					// Fix for BBCOM-308 starts here
					if(readCookie("bbr")){
					var userInfo=readCookie("bbr").split("|");
					
					//if(userInfo[3]==1) {
					var email = userInfo[0].substring(1,userInfo[0].length);
							$("#user-login [name=email]").val(email);
							$("#user-login [name=password]").val(userInfo[2]);
							$("#user-login [name=loginRemember]").attr('checked',true);		
							billboard.user.login( function(response){
								if(response == 'success'){
									// log into crowd factory
								   billboard.social.login( function(res){ 
									  me.executeforAddComment( url, params, callback);
								   });	
									
								}
							});
							
							/* login to billboard application */
					//}	
						
					}else{
						me.login( function(response) {
							
							me.executeforAddComment( url, params, callback );
						});
					}
			}
			else { 
				if ( callback ) callback(data);
			}
		});
	};

	me.executeforAddComment = function( url, params, callback ) 
	{
       	billboard.log("executeforAddComment("+url+")");
       	
		$.getJSON( url, function(data) { 
				if ( data.error_code == 106 ) {
					billboard.error("User not authorized. Please logout and log back in.");
				}
			// Fix for BBCOM-308 ends here
			else { 
				if ( callback ) callback(data);
			}
		});
	};
	
	/**
	 *
	 */
	me.login = function( callback ) 
	{
		billboard.log("Social.login()");
		var props = billboard.properties;
		var url = URL_CF_LOGIN;
		if(props.proxyPrefix.length > 1) {
			
			url = URL_CF_PROXY_LOGIN + props.cfConsumerUrl + url + "?" +props.cfQuery + "&j_username=" + readCookie("bbr").split("|")[1] +
				"&j_password=" + readCookie("bbr").split("|")[2];
			billboard.log("Social.login()--url" + url);
		}
		else {
			url = props.cfConsumerUrl + url + "?" + 
			props.cfQuery + "&j_username=" + readCookie("bbr").split("|")[1] +
			"&j_password=" + readCookie("bbr").split("|")[2];
			
			billboard.log("Social.login()cfConsumerUrl--url" + url);
		}
		callback = callback?callback:function(){};
		url +=  "&cacher="+((new Date()).getTime());
		
		$.getJSON(url, function(result) { 
			billboard.info("Social.login() result");
			billboard.logObject( result );
			callback(result);
		});
	};
	
	me.loginCF = function( callback ) 
	{
		billboard.log("Social.login()");
		var props = billboard.properties;
		var url = "";
			
			url = "/user/community/cf-login.json?url=" + "http://bbqawl10.vnuemedia.net/community/rest/auth/login" + 
				"?" + props.cfQuery + "&j_username=" + readCookie("bbr").split("|")[1] + "&j_password=" + readCookie("bbr").split("|")[2];
			billboard.log("Social.login()--url" + url);

		callback = callback?callback:function(){};
		url +=  "&cacher="+((new Date()).getTime());
	
		$.getJSON(url, function(result) { 
			billboard.info("Social.login() result");
			billboard.logObject( result );
			callback(result);
		});
	};

	/**
	 *
	 */
	me.logout = function( callback ) 
	{
		billboard.log("Social.logout()");
		var params = {};
		callback = callback?callback:function(){};
		billboard.social.execute( URL_CF_LOGOUT, params, callback );
	};
	
	/**
	 *
	 */
	me.getEntity = function( id, mixed, callback ) 
	{
		var options = {};
		if ( typeof mixed == "function" ) {
			callback = mixed;
		}
		else {
			options = mixed;
		}
		
		var url = URL_CF_ENTITYGET;
		var params = {};
		params.entity = id;
		params.rating = RATING_LOVEHATE;
		for ( var p in options ) {
			params[p] = options[p];
		}
		
		// send the request
		me.execute( url, params, callback );
	};
	
	/**
	 *
	 */
	me.createEntity = function( id, mixed, callback ) 
	{
		var options = new Object();
		if ( typeof mixed == "function" ) {
			callback = mixed;
		}
		else if ( typeof mixed == "object" ) {
			options = mixed;
		}
		
		var url = URL_BB_ENTITYCREATE;
		if ( id ) 
		url += "?eid="+id;
		else 
		url += "?nokey=novalue";
		
		for ( var p in options ) {
			if ( options[p] ) {
				url += "&"+p+"="+options[p];
			}
		}
		
		$.getJSON( url, function(response) { 
			if ( callback ) callback(response);
		});
	};
	
	me.addEntityAttribute = function( entity, attribute, value, callback )
	{
		var url = URL_CF_ATTR_ENTITY_ADD;
		me.execute( url, {entity:entity,attribute:attribute,value:value}, callback );
	};
	
	/**
	 * message boards are used for artist 'conversations'
	 *
	 * @param name - string the entity id, and currently only adding 'message boards' to artists pages, so ex.  'artist-514241'
	 * @param user - string username
	 * @param topic - string subject of conversations
	 * @param body - string full contents of discussion
	 * @param callback - function - to handle results of request
	 */
	me.createMessageBoard = function( name, user, topic, body, callback )
	{
		billboard.info("Social.createMessageBoard("+name+","+user+"," + topic+","+body+")");
		var category = name.split("-")[1];
		// create the entity that will represent the 'message board'
		me.createEntity( null, { title:topic+"||"+user,description:user,category:category}, function(data) { 
			// add a comment to that artist entity, to track discussion counts
			billboard.log( "create entity response" );
			billboard.log( data );
			var entity = data.ExternalEntity;
			me.addComment( name, topic, body, null, function(data){
				if ( entity ) {
					var id = entity.uid;
					me.addComment( entity.uid, topic, body, null, function(data) { 
						callback(data);
					});
				}
				else {
					callback(data);
				}
			});
		});
	};
	
	me.getMessageBoardCount = function( id, callback ) 
	{
		params = {};
		params.category = id.split("-")[1];
		params.period = "All";
		me.countEntity( params, function(result) {
			var count = 0;
			if ( result ) {
				count = result.entity_count;
			}
			callback( { numBoards:count } );
		});
	};
	
	/**
	 * this is really, getting an placeholder entity that will represent a message board
	 */
	me.getMessageBoard = function( id, options, callback ) 
	{
		billboard.log("Social.getMessageBoard("+id+")");
		
		var starter;
		var response = {};
		var params = { 
			rating:"CustomRating0&rating=Recommended",
			offset:options.start,
			start:options.start,
			max_return:options.count,
			count:options.count,
			sort:options.order,
			sort_rating:options.sort_rating
		};
		
		me.getEntity( id, function(result) { 
			billboard.log( params );
			me.getComments( id, params, function( data ) {
				response.numComments = result.ExternalEntity.comments_count;
				response.comments = data.comments;
				if ( response.numComments > 6 ) { 
					me.getComments( id, {offset:data.numComments-1,max_return:1}, function(res2) { 
						if(billboard.section=='forums' && billboard.subsection=='conversations') {//Forums need comments in chronological order
							response.starter = res2.comments[response.numComments - 1];
							}
						else {
							response.starter = res2.comments[0];
							}
						callback( response );
					});
				}
				else {
					if(billboard.section=='forums' && billboard.subsection=='conversations') {//Forums need comments in chronological order
						response.starter=response.comments[0]; 
						response.comments = response.comments.slice( 1, response.numComments );
						}
					else {
						response.starter = response.comments[response.numComments-1];
						response.comments = response.comments.slice( 0, response.numComments - 1 );
						}
					
					callback( response );
				}
			});
		});
		
		
		/*
		  var params = {};
		  params.board = id;
		  params.offset = options.start;
		  params.max_return = options.count;
		  params.user = options.user;
		  params.rating = options.rating;
		  params.group = "mb_group_"+id;
		  params.most_recent_reply_comment = true;
		  me.execute( URL_CF_MESSAGEBOARD_GET, params, function(res) { 
		  res = (res&&res.board)?(res.board):(null);
		  callback( res );
		  });
		*/
	};
	
	/**
	 * @return response with two properties
	 * - board_count, 
	 * - boards, array of board data structs
	 *
	 * where boards is an array of messageboard data structs
	 * - title
	 * - user
	 * - numReplies
	 * - modified
	 */
	me.getMessageBoards = function( id, options, callback ) 
	{
		billboard.log("Social.getMessageBoards("+id+")");
		
		var params = {};
		params.category = id.split("-")[1];
		params.offset = (options.start)?(options.start):0;
		params.max_return = (options.count)?(options.count):100;
		params.comment_period = "LastYear";
		if ( options.order ) params.order = options.order;
		
		me.browseEntity( params, function(data) { 
			var ents = data.entities;
			var boards = new Array();
			for ( var i=0;i<ents.length;i++ ) {
				try { 
					boards.push( { id:ents[i].uid,
										  title:ents[i].title.split("||")[0],
										  user:ents[i].title.split("||")[1],
										  numReplies:ents[i].comments_count,
										  modified:ents[i].last_modified } );
				} catch( ex ) { }
			}
			var result = { numBoards:boards.length, boards:boards };
			callback(result);
		});
		
		/*
		  me.getComments( id, {order:"MostRecentFirst",offset:0,count:1}, function(result) { 			
		  // seems to include topic ('message boards');
		  var lastComment;
		  if ( result && result.comments ) {
		  lastComment = result.comments[0];
		  lastComment.user = lastComment.user.external_id;
		  }
		  
		  });
		*/
		
		/*
		  var params = {};
		  params.board_offset = options.start;
		  params.board_max_return = options.count;
		  params.group = "mb_group_"+id;
		  params.most_recent_reply_comment=1;
		  me.execute( URL_CF_GROUP_GET, params, function(data) {
		  var ret = { board_count:0, boards:[] };
		  if ( data.group ) {
		  ret = { board_count:data.group.board_count, boards:(data && data.group)?(data.group):({boards:[]}) };
		  }
		  callback( ret );
		  });
		*/
	};
	
	/**
	 *
	 */
	me.getUser = function( id, callback ) 
	{
		me.execute( URL_CF_USERGET, { user:id }, callback );
	};

	me.getUserProfile = function( param, callback ) 
	{
		me.execute( URL_CF_USERGET, { user:param.username }, function(data){
			callback(data,param);
		});
	};
	
	me.rate = function( entity, type, rating, value, callback ) 
	{
		var url = url=="comment"?URL_CF_RATING_COMMENT_CREATE:URL_CF_RATING;
		rating = rating?rating:"Default";
		value = (typeof value !="undefined")?value:1;
		
		var params = {};
		params.entity = entity;
		params.rating = rating;
		params.value = value;
		callback = callback?callback:function(){};
		me.execute( url, params, callback );
	};
	
	/**
	 *
	 */
	me.browseEntity = function( options, callback ) 
	{
		var url = URL_CF_ENTITYBROWSE;
		
		var params = {};
		for ( var p in options ) {
			params[p] = options[p];
		}
		
		me.execute( url, params, callback );
	};

	me.countEntity = function( options, callback ) 
	{
		var url = URL_CF_ENTITYCOUNT;
		
		var params = {};
		for ( var p in options ) {
			params[p] = options[p];
		}
		
		me.execute( url, params, callback );
	};
	
	me.search = function( query, filter, sort, start, size, callback )
	{
		var url = URL_CF_SEARCH;
		var params = {};
		params.query = query;
		params.offset = (start)?(start):(0);
		params.max_return = (size)?(size):(100);
		params.extended = true;
		params.filter = filter;
		if ( sort ) params.sort = sort;
		me.execute( url, params, callback );
	};
	
	/**
	 *
	 */
	me.addComment = function( entity, category, body, parent, callback )
	{
		billboard.log( "Social.addComment("+entity+","+category+","+body+","+parent+")");
		
		// user must be logged in...
		if ( !billboard.user.isLoggedIn() ) {
			billboard.user.showForms();
			return;
		}
		
		if ( parent ) { // adding to a message board
			var url = URL_CF_ADD_COMMENT;
			var params = {};
			params.entity = parent;
			params.subject = category;
			params.body = body;
			
			me.trackActivity( entity, 
							  "comment", 
							  " commented on  ",
							  null );
			
			// update the lastModified property of the topic entity, so that it gets properly
			// sorted against "most recent"
			me.getEntity( parent, function(response) { 
				billboard.log("response=============");
				billboard.log(response);
				
				if ( response.ExternalEntity ) { 
					// get the title and description and user...
					me.createEntity( parent, {title:response.ExternalEntity.title,description:response.ExternalEntity.description} );
				}
			});
			
			// exceute the actual add comment call
			me.execute( url, params, callback );
			
			/**
			 * execute the add, then since this is a comment on a discussion, add it to the parent
			 * to track as the "last comment"
			 */
			/*
			// exceute the actual add comment call
			me.execute( url, params, function(data) { 
			// since there is a parent, add/update it (the artist entity) with the last message and the total topic counts
			me.addComment( name, topic, body, null, callback );
			});
			*/
		}
		else { // standard comment
			me.getEntity( entity, function(response) {
				// check if entity exists, 
				if ( response.error_code == 19 ) {
					billboard.log("entity does not exists");
					// create the entity
					me.createEntity( entity, function( data ) { 
						if ( data.error_code == 0 ) { 
							me.addComment( entity, category, body, parent, callback );
						}
					});
				}
				else {
					billboard.log("entity exists");
					var url = URL_CF_ADD_COMMENT;
					//subscriber, product, topcommunity
					var params = {};
					params.entity = entity;
					params.subject = category;
					params.body = body;
					
					billboard.log( params );
					me.trackActivity( entity, 
									  "comment", 
									  " commented on  ",
									  null );
					
					me.execute( url, params, callback );
				}
			});		
		}
	};
	
	
	/**
	 *
	 */
	me.hate = function( id, el, callback )
	{
		me.loveHate( id, 0, el, callback );
	};
	
	me.love = function( id, el, callback )
	{
		me.loveHate( id, 1, el, callback );
	};
	
	/**
	 *
	 */
	me.loveHate = function( id, value, el, callback ) {
		var el = el;
		
		billboard.log( "Social.loveHate("+id+","+value+")");
		
		// user must be logged in...
		if ( !billboard.user.isLoggedIn() ) {
			billboard.user.showForms();
			return;
		}
		
		me.getEntity( id, function(response) {
			// check if entity exists, 
			if ( response.error_code == 19 ) {
				billboard.log("entity does not exists");
				
				var section = (value==0) ? "hate" : "love"; 
				var verb = (value==0) ? "Hated" : "Loved";
				billboard.facebook.publish(section,el);
				googleA.trackSocialEvent(verb, el);

				// create the entity
				me.createEntity( id, function( data ) { 
					if ( data.error_code == 0 ) { 
						me.loveHate( id, value, null, callback );
					}
				});
			}
			else {
				billboard.log("entity already exists");
				var url = URL_CF_RATING;
				var params = {};
				params.entity = id;
				params.rating = RATING_LOVEHATE;
				params.value = value;
				billboard.log( params );
				
				var allowRating = 1 ;
				
				if(response.ExternalEntity.entity_ratings[0].user_rating && 
				   ( (value == 0 && response.ExternalEntity.entity_ratings[0].user_rating == "0.0" ) ||
					 (value == 1 && response.ExternalEntity.entity_ratings[0].user_rating == "1.0" ) )){
					
					allowRating = 0;
					
				}
				
				if(allowRating == 1){
					me.execute( url, params, function(data) { 
						me.trackActivity( id, 
										  "rating", 
										  " <span class='" + (value==0?"hate":"love") + "'>rated</span>  ",
										  null );
						me.getEntityInfo( id, callback );
					});
				}
				
			}
		});
	};
	
	/**
	 * given a dom element, find the entity's id and update its comment counts and love/hate counts
	 */
	me.updateLoveHateBar = function( elem )
	{
		// pull data for the love bar...
		var entityId = $(elem).find(".love-bar .entityId").text();
		var thisptr = $(elem);
		if ( entityId ) {
			billboard.social.getEntityInfo( entityId, function(data) { 
				thisptr.find(".meter div").text( data.loveHateTotal + " votes" );
				thisptr.find(".love-meter-container .percentage").text( data.loveHatePercentage + "%" );
				
				if(billboard.section == 'artists' && billboard.subsection != 'song' && billboard.subsection != 'album' && billboard.subsection != 'review'){
					var totalComments = 0;
					var category = billboard.comments.contentId.split("-")[1];
					me.browseEntity( {category:category,order:"MostCommented",offset:0,max_return:billboard.comments.totalComments}, function(response){		
						if ( response.entities && response.entities.length > 0 ) { 
							for(var i=0;i<response.entities.length;i++){
								totalComments += response.entities[i].comments_count;
							}
							thisptr.find(".reviews .user-comments p").html( totalComments );
						}
					});
				}
				else{
					if(thisptr.find(".reviews .user-comments p").is(".withlink")) {
						thisptr.find(".reviews .user-comments p a").html( data.numComments );
					}
					else {
						thisptr.find(".reviews .user-comments p").html( data.numComments );
					}
				}
				var numWidth = parseInt($(".meter").css("width"));
				var w = Math.round((numWidth - 48) * (data.loveHatePercentage/100));
				thisptr.find(".meter").css("background-position",24+w+"px");
			});
		}
		 // Disable love hate rating if user already rated an item
		 if(billboard.user.username ){
			 me.getHighestRated('all',{ period:"LastYear",rating:"CustomRating0",start:0, count:100, user:billboard.user.username } ,function(data){
				 
				 billboard.log('Getting user rated items.');
				 billboard.log(data);
				 
				 var entities = data.entities;

				 for ( var i=0;i<entities.length;i++ ) {
					
					if(entityId==entities[i].uid) {
					thisptr.find(".meter .hate span").css("background-position","left bottom");
					thisptr.find(".meter .love span").css("background-position","right bottom");
					break;
					}
				  }
				
			} );
		}
          	 	  
	};
	
	me.updateLoveBarCommentCount = function( elem )
	{
		var thisptr = $(elem);
		
		if(thisptr.find(".reviews .user-comments p").is(".withlink")) {
			thisptr.find(".reviews .user-comments p a").html( billboard.comments.totalComments );
		}
		else {
			thisptr.find(".reviews .user-comments p").html( billboard.comments.totalComments );
		}
	};


	me.updateItemInfo = function( elem )
	{
		billboard.log("Social.updateItemInfo("+elem+")");
		elem = $(elem);
		var e = $(elem);
		var entityId = elem.find(".entity-id").text();
		if ( entityId ) {
			billboard.social.getEntityInfo( entityId, function(response){
				if ( response ) {				
					e.find(".percent-like").text( response.loveHatePercentage + "%" );
					e.find(".total-comments").text( response.numComments );
				}
			});
		}		
	};
	
	/**
	 * pulls back an entity with love/hate ratings, and comment counts
	 */
	me.getEntityInfo = function( id, callback )
	{
		var data = { id:id };
		me.getEntity( id, function( response ) { 
			billboard.log( response );
			if ( response.error_code == 19 ) {
				// entity unknown
				data.love = 0;
				data.hate = 0;
				data.loveHateTotal = 0;
				data.loveHatePercentage = 0;
				data.numComments = 0;
			}
			else {
				var count = 0;
				var average = 0;
				if ( response.ExternalEntity.entity_ratings[0].category == RATING_LOVEHATE ) {
					count = response.ExternalEntity.entity_ratings[0].count;
					average = response.ExternalEntity.entity_ratings[0].average_rating;
					data.love = count * average;
					data.hate = count - (count * average);
				}
				data.loveHateTotal = count;
				data.loveHatePercentage = (Math.round(average*100));
				data.numComments = response.ExternalEntity.comments_count;
			}
			callback( data );
		});
	};
	
	/**
	 *
	 */
	me.getComments = function( id, options, callback ) 
	{
		billboard.log( "Social.getComments("+id+")");
		var url = URL_CF_GET_COMMENT;
		
		var params = {};
		params.entity = id;
		params.order = (options.sort)?(options.sort):("MostRecentFirst");
		if ( options.rating ) params.rating = options.rating;
		//params.rating = (options.rating)?(options.rating+"&rating="+RATING_LOVEHATE):RATING_LOVEHATE;
		if ( options.sort_rating ) params.sort_rating = options.sort_rating;
		if ( options.offset_id ) params.offset_id = options.offset_id;
		if ( options.offset ) params.offset = options.offset;
		else if ( options.start ) params.offset = options.start;
		if ( options.count ) params.max_return = options.count;
		
		//billboard.log( options.rating );
		//billboard.log( params.rating );
		
		me.execute( url, params, callback );
	};
	
	me.getBoardComments = function( id, options, callback ) 
	{
		billboard.log( "Social.getBoardComments("+id+")");
		var url = URL_CF_GET_BOARD_COMMENT;
		
		var params = {};
		params.board = id;
		params.order = (options.sort)?(options.sort):("MostRecentFirst");
		if ( options.rating ) params.rating = options.rating;
		//params.rating = (options.rating)?(options.rating+"&rating="+RATING_LOVEHATE):RATING_LOVEHATE;
		if ( options.sort_rating ) params.sort_rating = options.sort_rating;
		if ( options.offset_id ) params.offset_id = options.offset_id;
		else if ( options.start ) params.offset = options.start;
		if ( options.count ) params.max_return = options.count;
		
		//billboard.log( options.rating );
		//billboard.log( params.rating );
		
		me.execute( url, params, callback );
	};
	
	me.getCommentInfo = function( id, callback )
	{
		var data = {};
		data.total = 1204;
		callback( data );
 	};
	
	/**
	 * @param username - String representing the user to be followed, the 
	 *                   logged in user is implied
	 */
	me.follow = function( users, callback )
	{
		for ( var i=0;i<users.length;i++ ) {
				var username = users[i];
				billboard.log( "Social.follow("+username+")" );
				
					if ( typeof(username)=="undefined" || username.length <= 0 ) {
						billboard.error("User cannot be null in Social.follow()");
					}
					
					if ( username == billboard.user.username ) {
						billboard.error("You cant follow yourself silly.");
						return;
					}
					
					// 
					if ( !billboard.user.isLoggedIn() ) {
						billboard.user.showForms();
						return;
					}
					
					var url = URL_CF_CONNECTION_CREATE;
					var params = {};
					params.to_user = username;
					params.category = "Friend";
					me.execute( url, params, function(response) { 
						billboard.log("Social Connection created");
						billboard.social.trackActivity( username,
														"follow", 
														" is following ",
														null );
						if ( callback ) callback(response);
					});		
		}
	};
	
	me.stopFollow = function( username, callback )
	{
		var url = URL_CF_CONNECTION_DELETE;
		var params = {};
		params.to_user = username;
		params.category = "Friend";
		me.execute( url, params, function(response) { 
			billboard.log("Social Connection deleted");
			if ( callback ) callback(response);
		});		
	};
	
	/**
	 * pulls all users that 'username' is following
	 */
	me.browseConnections = function( username, direction, sort, cb )
	{
		var url;
		var params = {};
		sort = (sort)?(sort):("date");
		if ( direction == 'followers' ) {
			url = URL_BB_FOLLOWERS;
			url = url + username;
			url += "&cachebust="+(new Date()).getTime() + "&order="+sort;
			billboard.log( "get folowers url: "+url );
			var response = {};
			$.getJSON( url, function(data) { 
				response.connections = data.response.body.list;
				billboard.log(response);
				if ( sort == "alpha" ) {
					//var sorter = function( a, b ) { return ( a.username.toLowerCase() > b.username.toLowerCase() ); }
					//response.connections = response.connections.sort( sorter );
				}
				cb(response);
			});
			
			/*
			  url = URL_CF_SEARCH;
			  params.filter = "user";
			  params.query="externaluserid:"+username+"20AND outconnectiontypes:6";
			  params.extended=1;
			  me.execute( url, params, cb );
			*/
		}
		else {
			url = URL_BB_FOLLOWING + username
			url += "&cachebust="+(new Date()).getTime() + "&order="+sort;
			billboard.log( "get folowing url: "+url );
			$.getJSON( url, function(response) { 
				//billboard.log( response );
				// sort on the to_user
				var con = new Array();
				if ( sort == "alpha" ) {
					var sorter = function( a, b ) { 
						var x = a.to_user.external_id.toLowerCase();
						var y = b.to_user.external_id.toLowerCase();
						return ( x < y ) ? ( -1 ) : ( ( x == y ) ? ( 0 ) : ( 1 ) );
					}
					response.connectioons = response.connections.sort( sorter );
				}
				
				//billboard.log( response );
				cb(response);
			});
			
			/*
			// following needs a b2b call, so we'll hit the proxy
			// TODO: remove hard coded proxy to B2B call, when connection proxy is built
			url = URL_CF_CONNECTION_BROWSE;
			var props = billboard.properties;
			url = "/proxy.json?url=http://b2b-sandbox5.crowdfactory.com/" + url + "?" + props.cfQuery;
			url += "&from_user="+username;
			$.getJSON( url, function(data) { 
			callback(data);
			});
			*/
			
			// when checking who this person is following, set from_user ONLY
			//params.from_user = username;
		}
	};

	/**
	 *
	 * @param type - the category of the entity to filter
	 * options.count = number of results
	 * 
	 */
	me.getHighestRated = function( type, options, callback ) 
	{
		billboard.info("Social.getHighestRated("+type+")");

		var types = [];
		types["song"] = 1;
		types["artist"] = 2;
		types["album"] = 3;
		types["article"] = 4;
		var cat = types[type];

		if ( type == "article" ) {
			var url = URL_CF_SEARCH;
			me.search( "category:(4 OR 6 OR 8 OR 9 OR 10 OR 11)", "entity", null, 0, 3, function(response) {
				billboard.log("search results" );
				billboard.log( response );
				var len = response.results.length;
				for ( var i=0;i<len;i++ ) {
					var uid = response.results[i].ExternalEntity.uid;
					me.getEntityInfo( uid, function(result) { 
						billboard.log("getentityresults");
						result.type = "article";
						billboard.log( result );
						callback( result );						
					});
				}
			});
		}
		else { 
			var params = {};
			if ( cat ) {
				params.entity_category = cat;
			}
			params.rating = RATING_LOVEHATE;
			params.offset = (options.start)?(options.start):(0);
			params.max_return = (options.count)?(options.count):(3);
			for ( var p in options ) {
				params[p]  = options[p];
			}
			
			var topIds = new Array();
			me.execute( URL_CF_GET_HIGHESTRATED, params, function(data){
				callback( data );
				/*
				var id;
				for ( var i=0;i<data.entities.length;i++ ) {
					id = data.entities[i].uid.split("-")[1];
					me.getEntityInfo( data.entities[i].uid, function(result) { 
						billboard.log( "getentityrinfo result" );
						billboard.log( result );
						result.type = type;
						callback( result );
					});
				}
				*/
			});
		}
	};
	
	/**
	 *
	 */
	me.getHotItems = function( type, options, callback )
	{
		//http://b2c-sandbox5.crowdfactory.com/rest/v1/entity/browse?subscriber=6119b55e-8aec-102c-b0b1-0019b9f80169&product=6119acd0-8aec-102c-b0b1-0019b9f80169&topcommunity=202&category=1&sort_rating=CustomRating0&max_return=100&order=HighestRated&pretty=1&rating=CustomRating0&
		
		//http://b2c-sandbox5.crowdfactory.com/rest/v1/query/entity/highest_rated?subscriber=6119b55e-8aec-102c-b0b1-0019b9f80169&product=6119acd0-8aec-102c-b0b1-0019b9f80169&topcommunity=202&entity_category=1&rating=CustomRating0&period=LastDay&max_return=100&order=HighestRated&pretty=1
		
		billboard.info( "Social.getHotItems("+type+")");
		// determine CF category
		var types = [];
		types["song"] = 1;
		types["artist"] = 2;
		types["album"] = 3;
		types["article"] = 4;
		
		var cat = types[type];
		if ( typeof(cat) == "undefined" ) {
			return;
		}
		
		if ( type == "article" ) {
			var url = URL_CF_SEARCH;
			me.search( "category:(4 OR 6 OR 8 OR 9 OR 10 OR 11)", "entity", "created,desc", 0, 3, function(response) {
				billboard.log("search results" );
				billboard.log( response );
				var len = response.results.length;
				for ( var i=0;i<len;i++ ) {
					var uid = response.results[i].ExternalEntity.uid;
					me.getEntityInfo( uid, function(result) { 
						billboard.log("getentityresults");
						result.type = "article";
						billboard.log( result );
						callback( result );						
					});
				}
			});
		}
		else { 
			var params = {};
			params.entity_category = cat;
			params.rating=RATING_LOVEHATE;
			params.period= (options.numDays && options.numDays==7)?("LastWeek"):("LastDay");
			params.max_return = (options.count)?(options.count):(3);
			
			var topIds = new Array();
			me.execute( URL_CF_GET_HIGHESTRATED, params, function(data){
				//billboard.log( data.entities );
				var id;
				//var item;
				for ( var i=0;i<data.entities.length;i++ ) {
					//topIds.push( {type:type,id:data.entities[i].uid.split("-")[1]} );
					//item = data.entities[i];
					id = data.entities[i].uid.split("-")[1];
					//item.type = type;
					me.getEntityInfo( data.entities[i].uid, function(result) { 
						//billboard.log( "getentityrinfo result" );
						//billboard.log( result );
						//var entity  = result;//.ExternalEntity;
						result.type = type;
						//entity.id = id;
						//entity.loveHatePercentage = result.loveHatePercentage;
						//entity.numComments = result.numComments;
						//billboard.log( entity );
						callback( result );
					});
				}
			});
		}
	};

	
	/**
	 *
	 */
	me.trackActivity = function( entityId, category, message, callback )
	{
		billboard.log( "Social.trackActivity()");
		
		var url = URL_CF_ACTIVITY_CREATE;
		
		var cats = {"rating":1,"comment":2,"follow":3,"game":4};
		var cat = cats[category];
		
		var params = {};
		params.category = cat;
		params.performerid = billboard.user.username;
		params.performertype = "user";
		
		if ( category == "follow" ) { 
			params.containerid = entityId;
			params.containertype = "user";
		}else if(category == "game") {
			
			// no container
			
		}else { 
			params.containerid = entityId;
			params.containertype = "entity";
		}
		params.message = (message&&message.length>0)?(message):("Activity Event");
		
		me.execute( url, params, function(data){
			billboard.log("trackActivity result");
			billboard.log(data);
		} );
	};
	
	/**
	 * get every activity of the user and all his friends..
	 * it will need to be combined in order of date, and paged...
	 */
	me.getActivity = function( username, filter, callback ) 
	{
		billboard.info( "Social.getActivity("+username+"," +filter+")" );
		// get *all* of current user's activity
		var url = URL_CF_ACTIVITY_GET;
		var cats = {"rating":1,"comment":2,"follow":3};
		var cat = (cats[filter])?(cats[filter]):(-1);
		
		var params = {};
		params.activityfilter = "performer";
		params.id = billboard.publicUser;
		params.idtype = "user";
		if ( cat != -1 ) { params.category = cat; }
		
		if (filter == "follow") {
			
			params = {};
			params.id = billboard.publicUser;
			params.idtype = "user";
			params.activityfilter = "performedByConnectionsOf";
			
			me.execute(url, params, function(res2){
				
				billboard.info("Social - activity results");
				var events = res2.activityevents;
				var response = {
					activityevents: events
				};
				callback(response);
			});
			
		}
		else {		
			me.execute(url, params, function(res1){
				if (filter != "user") {
					// only get the friends activities if this is not filtered by user
					// get *all* of current user's *FRIENDS* activity
					params = {};
					params.id = billboard.publicUser;
					params.idtype = "user";
					params.activityfilter = "performedByConnectionsOf";
					
					me.execute(url, params, function(res2){
						billboard.info("Social - activity results");
						var events = res1.activityevents.concat(res2.activityevents);
						
						var response = {
							activityevents: events
						};
						callback(response);
					});
				}
				else {
					callback(res1);
				}
			});
		}
	};
	
    var uploadPhotoForm = '<form id="upload-photo" class="profile" method="post" enctype="multipart/form-data">'
	+ '<div class="upload-wrapper style-input">'
	+ '<div class="upload-head">'
	+ '<h2>Upload a new photo</h2>'
	+ '</div>'
	+ '<p class="error-message" id="upload-msg" style="display:none;"></p>'
	+ '<input type="file" size="40" id="photo-file" name="profile_pic" class="textbox" />'
	+ '<p class="upload-message">The standard icon size we use is 189x189 pixels.<br/>Filesize cannot exceed 2 MB</p>'
	+ '<div class="form-button">'
	+ '<button type="submit" class="button type-four"><span>Upload</span></button>'
	+ '</div>'
	+ '</form>';
	
    var uploadingPhoto = '<div id="uploading-photo" class="profile">'
	+ '<div class="upload-wrapper">'
	+ '<div class="upload-head">'
	+ '<h2>Uploading...</h2>'
	+ '</div>'
	+ '<img src="/images/icons/ajax-progress-loader.gif" />'
	+ '</div>'
	+ '</div>';
	
    var uploadPhotoSuccess = function(imageUrl){
        var html = '<div class="profile">'
        + '<div class="upload-wrapper">'
        + '<div class="upload-head">'
        + '<h2>Success!</h2>'
        + '</div>'
        + '<p>Upload successful. Your new photo is shown below. Click "Save Changes" to confirm.</p>'
		+ '<div class="uploaded-image " ><img class="upload-error" src="' + imageUrl + '" title="image" alt="The image has been uploaded , however the preview is not available as this time due to the large image size. Save this image or upload another small sized image to see the preview."/></div>'
        + '<p>Not sure about it? Hit "Cancel" or upload a different photo.</p>'
		+ '<div class="button-group">'
		+ '<a id="upload-cancel" class="no-ajax button type-four" href="/bbcom"><span>Cancel</span></a>'
       	+ '<a id="upload-again" class="no-ajax button type-four" href="/bbcom"><span>Change Profile Photo</span></a>'
       	+ '<a id="upload-commit" class="no-ajax button type-four" href="/bbcom"><span>Save Changes</span></a>'
 		+ '</div>'
        + '</div>'
        + '</div>';
        
        return html;
    };
	
    me.uploadPhoto = function()
	{
        billboard.modal.show(uploadPhotoForm,true);
        $("#upload-photo").submit(function(){
            me.uploadPhotoSubmit();
            return false;
        });
    };
	
    me.uploadPhotoSubmit = function()
	{
        $("#upload-photo").hide();
        if ( $("#uploading-photo").length == 0 ){
            $("#modal-sub-content").append(uploadingPhoto);
        } else {
            $("#uploading-photo").show();
        }
		
        if ($("input[name=profile_pic]").val() == ''){
            $("#uploading-photo").hide();
            $("#upload-photo").show();
            $("#upload-msg").html("Please choose a photo to upload.");
            $("#upload-msg").show();
            return;
        }
		
		var props = billboard.properties;

		//var url = (props.proxyPrefix.length > 1 ? "/upload-proxy.json?url=" : "") + props.cfConsumerUrl + "cms/v1/image/create" + "?" + props.cfQuery + "&image_file=profile_pic";
		
		var url = "/bbcom" + "/upload-proxy.json?url=" + document.location.protocol+'//'+document.location.host + "/community/cms/v1/image/create" + "?" + "image_file=profile_pic&" + props.cfQuery;

        $.ajaxFileUpload ( {
            url : url
				,secureuri : false
				,fileElementId : 'photo-file'
				/*
				  ,dataType:'html'
				*/
				,success : function (response, textStatus) {
                var $res = $(response);
                var hasPre = $res.find("body pre").length;
                if ( hasPre == 1){
                    var data = eval("(" + $res.find("body pre").html() + ")");
                } else { 
                    var data = eval("(" + $res.find("body").html() + ")");
                }
                if(data.error_code && data.error_code > 0) {
                    $("#uploading-photo").hide();
                    $("#upload-photo").show();
                    $("#upload-msg").html(data.error_str + " - " + data.error_detail);
                    $("#upload-msg").show();
                } else {
                    var tempImageUrl = data.ExternalEntity.image_urls.medm_r;
                    $("#modal-sub-content").html(uploadPhotoSuccess(tempImageUrl));
                    $("#modal-content #upload-cancel").click(function(){
                        billboard.modal.hide();
                        return false;
                    });
                    $("#modal-content #upload-again").click(function(){
                        me.uploadPhoto();
                        return false;
                    });
                    $("#modal-content #upload-commit").click(function(){
                        var smallImageUrl = data.ExternalEntity.image_urls.smll_s;
                        var largeImageUrl = data.ExternalEntity.image_urls.medm_s;
                        me.execute(
								   URL_CF_ATTR_USER_ADD
								   , {
							"user" : billboard.user.username 
                                , "attribute" : "profile_photo_url_small"
                                , "value" : smallImageUrl
								}
								   , function(){
									   me.execute(
												  URL_CF_USER_CREATE
												  , {
										   "user" : billboard.user.username
											   , "profile_photo_url" : largeImageUrl
											   }
												  , function(){
													  $("#profile-photo").attr("src",largeImageUrl);
													  billboard.modal.hide();
												  }
												  );
								   }
								   );
                        return false;
                    });
                }
            }
            ,error: function (data, textStatus, e) {
				billboard.log("Photo upload error = " + textStatus + " - " + e.toString );
                $("#uploading-photo").hide();
                $("#upload-photo").show();
                $("#upload-msg").html(textStatus + " - Your photo was not uploaded");
                $("#upload-msg").show();
            }
        });
    };
    
    me.initPoll = function($item){
		$('.polls ul.poll-options li').hover(
											 function(){
												 $(this).find('div.indicator').css({backgroundPosition: '0px -25px'});
												 $(this).css({backgroundColor: '#f9f134'});
												 return false;
											 }
											 , function(){
												 $(this).find('div.indicator').css({backgroundPosition: '0px 0px'});
												 $(this).css({backgroundColor: '#ffffff'});
												 return false;
											 }
											 );		
		$('.polls ul.poll-options li').click(function(){
			$("div.checkmark").css({backgroundPosition: '0px 50px'});
			$(this).find('div.checkmark').css({backgroundPosition: '0px 2px'});
            me.submitPollAnswer($item,$(this).attr("id"));
			return false;
		});
    };
	
    me.submitPollAnswer = function($item,answerId){
        answerId = answerId.substring(answerId.indexOf("-")+1);
        me.execute( 
				   URL_CF_POLL_VOTE
				   , { answer_id : answerId }
				   , function(data){
					   if(data.error_code && data.error_code > 0) {
						   $item.find(".status-container").html(data.error_str + " - " + data.error_detail);
					   } else {
						   me.execute( 
									  URL_CF_POLL_GET
									  , { name : $item.attr("id") }
									  , function(data){
										  var $cont = $item.find(".status-container");
										  $cont = $cont.append(
															   '<h5>Results</h5>'
															   + '<ul class="poll-results">'
															   + '</ul>'
															   );
										  $.each(data.poll.answers,function(i,v){
											  var percent = ((v.number_answered/data.poll.total_answers)*100);
											  var bgPos = (percent * 288) - 288;
											  $cont.find(
														 ".poll-results"
														 ).append(
																  '<li id="answer' + v.id + '">'
																  + v.answer 
																  + '<span class="percent">'
																  +  percent + '%'
																  + '</span>'
																  + '</li>'
																  );
											  $cont.find("#answer" + v.id).css({
												  "background-position" : bgPos + "px 0"
													  });
										  });
									  }
									  );
					   }
				   }
				   );
    };
	
})(jQuery);


