/*
 * NEWSFEED JABBER CLIENT	
 * Version: 0.1a
 * Strophe Library
 * Author : Amine MOKEDDEM
 * "May the Force be with you"
 * 
 */
/***************************************
 *                                     *   
 *          @String tools	           *
 *                                     *
 ***************************************/
String.prototype.ucFirst = function () {
	return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
};



/***************************************
 *                                     *   
 *          @Global Variables          *
 *                                     *
 ***************************************/
//81.57.50.13
var BOSH_SERVICE = 'http://'+$.url.attr('host')+'/http-bind/';
var domain = '10.3.0.1';
var connection = null;
var isAdmin = false;
var authFail = false;
var userRegistered = false;
var createApplication = false;
var applicationToCreate = '';
var createPage = false;
var pageToCreate='';
var pageToCreateOptions=null;
var subscribeToPageNodes=false;
var subscribedNode = new Array();
var commentsNode = new Array();
/***************************************
 *                                     *   
 *       @Anti Repetition              *
 *                                     *
 ***************************************/
var memberDisco = false;
var childDisco = false;
var childCreation = false;
var childNodeDisco =false;
var nodeSubscribed = false;
var newsCreation = false;
var photosCreation = false;
var videosCreation = false;
var commentsCreation = false;
var notificationsCreation = false;
var statusCreation = false;
var getSubscriptionsCalled = false;

/***************************************
 *                                     *   
 *             @Page Init              *
 *                                     *
 ***************************************/

$(document).ready(function(){
	if($.url.segment(0) == 'feeds'){
		initClips();
		bindMouseOverPublishButton();
		lastEntryBottomBorder();
		bindTimeAgo();
	}else if($.url.segment(0) == 'users'){
		//initFriendsAcceptence();
	}
	if($.url.segment(1)== 'add' || $.url.segment(1)== 'add_leg' ){
		bindSubmitButton($.url.segment(0),false);
	}else if($.url.segment(1)== 'add_simple' ){
		bindSubmitButton($.url.segment(0),true);
	}
	//bindFavoritesButtons();
	//bindUnfavoriteButtons();
	var reg= new RegExp('stadiumchat');
	if(!reg.test(window.location.href) /*&&!($.url.segment(0)=='matches' && $.url.segment(1) == 'commentaries')*/){
		connection = new Strophe.Connection(BOSH_SERVICE);
		userConnect();
	}
	$('#text').focus(function(){
		$(this).val('');
	})
});


/**************************************
 *                                    *   
 *           Authentication           *
 *                                    *
 **************************************/
function userConnect(){
	var user = getCurrentUser();
	connection.connect(user+"@"+domain+'/newsfeed','youfoot',onConnect,29);
}
function newsFeedLogin(username){
	login = jQuery.trim(username);
	userExists(login);
}

function afterExistCheck(){
	if(loginExists == "false"){
		createUser(login);
	}else{
		close_pop_login();
		$.cookie('userName-userID',loginExists,{path:"/"});
		userConnect();
	}
}

function registerNewUser(){
	$('#loading-status').text('Registering the new xmpp user');
	makeAdminRegisterUser();
}

function makeAdminRegisterUser(){
	isAdmin = true;
	connection.connect("root@"+domain,'kidon',onConnect,300);
}

function doRegistrationRequest(){
	var userName = getCurrentUser();
	var iq = $iq({type:'set',id:'reg1'});
	iq.c('query',{xmlns:"jabber:iq:register"}).c('username').t(userName).up().c('password').t("youfoot");
	//alert(iq.toString());
	connection.send(iq.tree());
}


function unregister(){
	connection.addHandler(onDereg, null, null, null, 'unreg', null);
	var userName = getCurrentUser();
	var iq = $iq({type:'set',id:'unreg'});
	iq.c('query',{xmlns:"jabber:iq:register"}).c('remove').c('username').t(userName).up().c('password').t("youfoot");
	alert(iq.toString());
	connection.send(iq.tree());
}

function onDereg(data){
	alert(Strophe.serialize(data));
}
/**************************************
 *                                    *   
 *               @Handelers           *
 *                                    *
 **************************************/

function onConnect(status){
    if (status == Strophe.Status.CONNECTING) {
		/*$('#loading-newsfeed').show();
		$('#loading-status').text('Connecting...');*/
    }else if (status == Strophe.Status.AUTHFAIL) {
		onAuthFail();
    }else if (status == Strophe.Status.DISCONNECTING) {
		
    }else if (status == Strophe.Status.ERROR) {
		
    }else if (status == Strophe.Status.DISCONNECTED) {
    	if(isAdmin){
	   		isAdmin=false;
	   		userConnect();
	   	}else if(authFail){
			authFail = false;
			registerNewUser();
		}else if(createApplication){
			makeAdminRegisterUser();
		}else if(createPage){
			makeAdminRegisterUser();
		}
    }else if (status == Strophe.Status.CONNECTED) {
		connection.send($pres().tree());
		//alert('connected');
		if(isAdmin){
			if(createApplication ){
				createApplication = false;
				createApplicationNode(applicationToCreate,1);
			}else if(createPage){
				createPage = false;
				createPageNodes(pageToCreate,1);
			}else{
				doRegistrationRequest();
			}
			
		}else{
			if(subscribeToPageNodes){
				subscribeToPageNodes=false;
				if(pageToCreateOptions.subscribe){
					putInFavorite(pageToCreate);
				}else{
					publishContribution(pageToCreateOptions);
				}
			}
			//childNodesExists();
			enablePublishForm();
		}
		$('#pending-friends').show();
		$('.accept-friend').show();
	}
	if (isAdmin) {
		connection.addHandler(onUserRegister,null,null,null,'reg1',null);
		connection.addHandler(onLastPageChildNode, null, null, null, 'lastPageChildNode', null);
	}else{
		//alert($.url.segment(0) + '/' + $.url.segment(1));
		if ($.url.segment(0) == 'feeds') {
			connection.addHandler(onDiscoPubsub, null, null, null, 'discoPubsubFeatures', null);
			connection.addHandler(onDiscoMember, null, null, null, 'discoMember', null);
			connection.addHandler(onMemberNodeCreation, null, null, null, 'createMemberCollectionNode', null);
			connection.addHandler(onDiscoChild, null, null, null, 'discoChild', null);
			connection.addHandler(onConfig, null, null, null, 'config', null);
			connection.addHandler(onInstantNodeCreation, null, null, null, 'createInstantChildNode', null);
			connection.addHandler(onNewsNodeCreation, null, null, null, 'createMemberNewsNode', null);
			connection.addHandler(onPhotosNodeCreation, null, null, null, 'createMemberPhotosNode', null);
			connection.addHandler(onVideosNodeCreation, null, null, null, 'createMemberVideosNode', null);
			connection.addHandler(onNotificationsNodeCreation, null, null, null, 'createMemberNotificationsNode', null);
			connection.addHandler(onStatusNodeCreation, null, null, null, 'createMemberStatusNode', null);
			connection.addHandler(onCommentsdNodeCreation, null, null, null, 'createMemberCommentsNode', null);
			//connection.addHandler(onChildNodesCreation,null,null,null,'createMemberChildNodeLast',null); 
			connection.addHandler(onMemberChildNodes, null, null, null, 'getMemberChildNodes', null);
			connection.addHandler(onGetSubscriptions, null, null, null, 'getMemberSubscriptions', null);
			connection.addHandler(onAffiliationsToDelete, null, null, null, 'getMemberAffiliationsToDelete', null);
			connection.addHandler(onGetItems, null, null, null, 'getItems', null);
			connection.addHandler(onMessage, null, 'message', null, null, null);
			connection.addHandler(onSubscriptions, null, null, null, 'subscribeLast', null);
			connection.addHandler(onPublish, null, null, null, 'publishItem', null);
			connection.addHandler(onretract, null, null, null, 'retract', null);
			connection.addHandler(deleteAllSubscriptions, null, null, null, 'getMemberSubscriptionsdelete', null);
			connection.addHandler(deleteFriend, null, null, null, 'getMemberSubscriptionsfriend', null);
			connection.addHandler(checkSubscriptionsToBecomeFriend, null, null, null, 'getMemberSubscriptionsToBecomeFriend', null);
			connection.addHandler(onPublishFriend, null, null, null, 'publishFriend', null);
			//connection.addHandler(onAcceptFriendship, null, null, null, 'acceptFriendship', null);
		}else{
			connection.addHandler(onAcceptFriendship, null, null, null, 'acceptFriendship', null);
			connection.addHandler(onPhotoChange, null, null, null, 'photoChange', null);
			connection.addHandler(deleteFriend, null, null, null, 'getMemberSubscriptionsfriend', null);
			connection.addHandler(onPublishFriend, null, null, null, 'publishFriend', null);
			connection.addHandler(onPublishContribution, null, null, null, 'publishContribution', null);
			connection.addHandler(onSubscribeToPageLast, null, null, null, 'subscribeToPageLast', null);
			connection.addHandler(onPublishFavorite, null, null, null, 'publishFavorite', null);
			
		}
		
	}
}

function onretract(data){
	//alert(Strophe.serialize(data));
}
function onAuthFail(){
	//alert('hello');
	authFail = true;
	connection.disconnect();
}
function onPublish(){
	enablePublishForm();
	return true;
}

function onPublishFriend(data){
	if(old_data != data){
		old_data = data;
		sendFriendAcceptanceNotification(sendAcceptanceOptions.one,sendAcceptanceOptions.two,sendAcceptanceOptions.three);
	}
}
function onUserRegister(data){
	var type = $(data).attr('type');
	if(type == 'result' && !userRegistered){
		userRegistered = true;
		//alert('user Registered!');
		connection.disconnect();
	}
}

function onDiscoPubsub(data){
	alert(Strophe.serialize(data));
}


function onDiscoMember(data){
	//alert(Strophe.serialize(data));
	if($(data).find('item-not-found').length == 1 && !memberDisco){
		memberDisco = true;
		createMemberCollectionNode();
	}else if(!memberDisco){
		memberDisco = true;
		childNodesNodesExists();
	};
}

function onDiscoChild(data){
	if($(data).find('item-not-found').length == 1 && !childDisco){
		childDisco = true;
		createInstantNode();
		$('#loading-status').text('Creating the nodes ...');
	}else if(!childDisco){
		childDisco = true;
		getSubscriptions();
	};
}
function onMemberNodeCreation(data){
	//alert(Strophe.serialize(data));
	childNodesExists();
}

function onConfig(data){
	//alert(Strophe.serialize(data));
}
function onInstantNodeCreation(data){
	//alert(Strophe.serialize(data));
	if(!newsCreation){
		createMemberChildNode('news');
		newsCreation = true;
	}
	return true;
}

/*function onChildNodesCreation(data){
	var user = getCurrentUser();
	if(!childCreation){
		createMemberChildNode('news');
		childCreation = true;
	}
}*/
function onNewsNodeCreation(data){
	setTimeout(function(){
		var user = getCurrentUser();
		if(!photosCreation){
			createMemberChildNode('photos');
			photosCreation = true;
			$('#loading-status').text('news node created');
		}
	},800);
	return true;
}
function onPhotosNodeCreation(data){
	setTimeout(function(){
	var user = getCurrentUser();
		if(!videosCreation){
			createMemberChildNode('videos');
			videosCreation = true;
			$('#loading-status').text('photos node created');
		}
	},800);
	return true;
}
function onVideosNodeCreation(data){
	setTimeout(function(){
		var user = getCurrentUser();
		if(!notificationsCreation){
			createMemberChildNode('notifications');
			notificationsCreation = true;
			$('#loading-status').text('videos node created');
		}
	},800);
	return true;
}
function onNotificationsNodeCreation(data){
	setTimeout(function(){
		var user = getCurrentUser();
		if(!statusCreation){
			createMemberChildNode('status');
			statusCreation = true;
			$('#loading-status').text('notifications node created');
		}
	},800);
	return true;
}
function onStatusNodeCreation(data){
	setTimeout(function(){
		var user = getCurrentUser();
		if(!commentsCreation){
			createMemberChildNode('comments');
			commentsCreation = true;
			$('#loading-status').text('status node created');
		}
	},800);
	return true;
}
function onCommentsdNodeCreation(data){
	setTimeout(function(){
		var user = getCurrentUser();
		//alert(user[0]);
		if (!nodeSubscribed) {
			$('#loading-status').text('comments node created');
			setTimeout(function(){
				subscribeToNode(user, 'news');
			},800);
			setTimeout(function(){
				subscribeToNode(user, 'photos');
			},800);
			setTimeout(function(){
				subscribeToNode(user, 'videos');
			},800);
			setTimeout(function(){
				subscribeToNode(user, 'status');
			},800);
			setTimeout(function(){
				subscribeToNode(user, 'notifications');
			},800);
			setTimeout(function(){
				subscribeToNode(user, 'comments');
			},800);
			$('#loading-status').text('Nodes Subscribed');
			nodeSubscribed = true;
		}
	},800);
	return true;
}

function onMemberChildNodes(data){
	/*if($(data).find('item').length >1 && !childNodeDisco){
		$(data).find('item').each(function(){
			alert($(this).attr('node'));
		});
		childNodeDisco = true;
	}*/
}

var requestsubscriptions = false;
function onSubscriptions(data){
	if(!requestsubscriptions){
		setTimeout(function(){
			$('#loading-status').text('Retrieving subscriptions');
			getSubscriptions();
			requestsubscriptions = true;
		},800);
	}
	
}

function onGetSubscriptions(data){
	//alert(Strophe.serialize(data));
	if(!getSubscriptionsCalled && $(data).find('subscription').length > 0){
		$(data).find('subscription').each(function(){
			var node= $(this).attr('node');
			var reg = new RegExp('comments','g');
			if (reg.test(node)) {
				if ($.inArray(node, commentsNode) == -1) {
					commentsNode.push(node);
				}
			}
			else {
				if ($.inArray(node, subscribedNode) == -1 && node != '/stadiumchat') {
					subscribedNode.push(node);
				}
			}
		});
		$('#loading-status').text('Getting Items...');
		getAllItems();
		getSubscriptionsCalled = true;
	}
	return true;
}
var old_data='';
function onMessage(data){
	var my_data = Strophe.serialize(data);
	if (old_data != my_data) {
		old_data = my_data;
		if($(data).find('headers').length!=0){
			$(data).find('item').each(function(){
				if ($(this).attr('id') != 'notify') {
					if ($(this).find('accepted').length > 0) {
						handelNotification(this);
					}
					else {
						showFeedEntry(this);
					}
				}
			});
		}
	}
	return true;
}

function onGetItems(data){
	var my_data = Strophe.serialize(data);
	if (old_data != my_data) {
		old_data = my_data;
		$(data).find('item').each(function(){
			if ($(this).find('accepted').length > 0) {
				handelNotification(this);
			}
			else {
				showFeedEntry(this);
			}
		});
		$('#newsfeed').show();
		
		enablePublishForm();
	}
	return true;
}

function onAffiliationsToDelete(data){
	deleteAllNodes(data);
	return false;
}


function onAcceptFriendship(data){
	var my_data = Strophe.serialize(data);
	if(old_data != my_data){
		old_data = my_data;
		window.location.href=friendRequest;
	}
}

function onPhotoChange(data){
	var my_data = Strophe.serialize(data);
	if (old_data != my_data) {
		if($('#UserEditForm').length>0){
			$('#UserEditForm',window.parent.document)[0].submit();
		}
	}
}

function onPublishContribution(data){
	var my_data = Strophe.serialize(data);
	if(old_data != my_data){
		old_data = my_data;
		if(contributionURL != null){
			window.location.href=contributionURL;
		}
		
	}
}

function onPublishFavorite(data){
	var my_data = Strophe.serialize(data);
	if(old_data != my_data){
		old_data = my_data;
		if(!favoriteOptions.noRdirect || favoriteOptions.noRdirect == null){
			window.location.href=favoriteOptions.add_url;
		}
		
	}
}

function onLastPageChildNode(data){
	var my_data = Strophe.serialize(data);
	if(old_data != my_data){
		old_data = my_data;
		subscribeToPageNodes = true;
		connection.disconnect();
	}
}

function putInFavorite(page){
	setTimeout(function(){
		subscribeToPage(page+'-photos');
	},800)
	setTimeout(function(){
		subscribeToPage(page+'-videos');
	},800)
	setTimeout(function(){
		subscribeToPage(page+'-news');
	},800)
	setTimeout(function(){
		subscribeToPage(page+'-activities');
	},800)
	setTimeout(function(){
		subscribeToPage(page+'-comments',1);
	},800);
}
function onSubscribeToPageLast(data){
		var my_data = Strophe.serialize(data);
	if (old_data != my_data) {
		old_data = my_data;
		if(pageToCreate != ''){
			publishContribution(pageToCreateOptions);
		}else{
			publishFavorites(favoriteOptions);
		}
	}else{
		
	}
}
/**************************************
 *                                    *   
 *           @Display Items           *
 *                                    *
 **************************************/

function showFeedEntry(elem){
	var id = $(elem).attr('id');
	var entry = $(elem).children('entry');
	var timestamp = entry.attr('date');
	var date = entry.attr('datenews');
	var hour = entry.attr('hournews');
	var from =entry.attr('from');
	if($('#'+id).length == 0){
		renderHTML(elem);
		
	}
}

var renderTimes = 0;
function renderHTML(elem){
	
	var bAjaxOptions = {
		url : "/feeds/renderHTMLBundle",
		type : "POST",
		dataType:"json",
		success : function(data, q_len){
			for (var i = 0; i < data.length; i++) {
				var dataArray= data[i].split('>');
			 	dataArray.shift();
				elem = dataArray.join('>');
				sortMessageInFeed(elem);
			}
			renderTimes++;
			if(renderTimes>1){
				$('#loading-newsfeed').hide();
			}
		}
	};
	
	var xml = Strophe.serialize(elem);
	var text=$('<div/>').text(xml).html();
	$.bAjax(bAjaxOptions,{
		data: xml
	});
	
	/*$.ajax({
		url : "/feeds/renderHTML",
		type : "POST",
		data:"data[entry-xml]="+xml,
		success : function(data, q_len){
			var dataArray= data.split('>');
			dataArray.shift();
			elem = dataArray.join('>');
			sortMessageInFeed(elem);
		}
	})*/
}
var testago;
function sortMessageInFeed(elem){
	var id = $(elem).attr('id');
	var from = $(elem).attr('from');
	$(elem).hide();
	if ($('#' + id).length == 0) {
		var comment = false;
		if($(elem).attr('class')=='feedcomment'){
			comment = true;
		}
		if (!comment) {
			var timestamp = $(elem).attr('timestamp');
			var date = new Date();
			date.setTime(timestamp);
			var timeago = $.timeago(date);
			var title = date.toISO8601String();
			var messageDate = new Date();
			messageDate.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
			messageDate.setHours(0, 0, 0, 0);
			
			if ($('.newsfeed-day[timestamp=' + messageDate.getTime() + ']').length == 0) {
				var daydiv = "<div class='newsfeed-day' timestamp='" + messageDate.getTime() + "'>" +
				"<div class='day'>" +
				getTextDate(messageDate.getTime()) +
				"</div>" +
				"<div>  </div>"+
				"</div>";
				var previousDay = getPreviousDay(messageDate.getTime());
				if (previousDay == 0) {
					$("#newsfeed-feeds").append(daydiv);
				}
				else {
					$('.newsfeed-day[timestamp=' + previousDay + ']:first').before(daydiv);
				}
				$('.newsfeed-day[timestamp=' + messageDate.getTime() + ']:first').children(':last').append(elem);
			}
			else {
				var previousEntry = getPreviousEntry(timestamp);
				//alert(previousEntry);
				if (previousEntry == 0) {
					$('.newsfeed-day[timestamp=' + messageDate.getTime() + ']:first').children(':last').append(elem);
				}
				else {
					var dayTime = $(".feed-entry[timestamp=" + previousEntry + "]").parent().parent().attr('timestamp');
					if (dayTime == messageDate.getTime()) {
						$('.feed-entry[timestamp=' + previousEntry + ']:first').before(elem);
					}
					else {
						$('.newsfeed-day[timestamp=' + messageDate.getTime() + ']:first').children(':last').append(elem);
					}
				}
			}
			$("#"+id).find('.feed-entry-time:first').html(timeago);
			$("#"+id).find('.feed-entry-time:first').attr('title',title);
			$('#'+id).find('.feed-entry-time:first').timeago();
			lastEntryBottomBorder();
		}else{
			
				//var comment = $(elem).find('.feed-content').text();
				var feed = $(elem).attr('relateditem');
				var timestamp = $(elem).attr('timestamp');
				var from = $(elem).attr('user-id');
				var id = $(elem).attr('id');
				var commentId='this-entry-comments-' + feed;
				var prev = getPreviousComment(commentId,timestamp);
				var commentDate = new Date();
				commentDate.setTime(timestamp)
				var timeago = $.timeago(commentDate);
				elem = $(elem).clone().find('.comment-entry-time:first').html(timeago).parent().parent().parent();
				if (from != '') {
					$.Tache.Get({
						url: '/feeds/getImage/' + from,
						success: function(data){
							if ($('#' + id).length == 0) {
								if (prev == 0) {
									$('#' + commentId).prepend(elem);
								}
								else {
									//alert('ici'+prev);
									$('#' + commentId).children('.feedcomment[timestamp=' + prev + ']:first').after(elem);
								}
								$('#'+id).find('.author-photo').each(function(){
									$(this).html($(data).addClass('photo'));
								});
								var items = $('#this-entry-comments-' + feed).children('.feedcomment').length;
								$('#comments-count-' + feed).text('Comment('+items+')');
							}
						}
					});
				}else{
					if (prev == 0) {
						$('#' + commentId).prepend(elem);
					}
					else {
						//alert('ici'+prev);
						$('#' + commentId).children('.feedcomment[timestamp=' + prev + ']:first').after(elem);
					}
					//alert(timestamp+'>'+prev);
					var items = $('#this-entry-comments-' + feed).children('.feedcomment').length;
					$('#comments-count-' + feed).text(items);
				}
			
		}
		
	}
}

function lastEntryBottomBorder(){
	$('.newsfeed-day').children(':last').children().each(function(){
		$(this).css('border-bottom','2px dashed lightGray');
	});
	$('.newsfeed-day').each(function(){
		$(this).children(':last').children(':last').each(function(){
			$(this).css('border-bottom','0');
		})
	})
}
function getPreviousDay(timestamp){
	var prev = 0;
	$('.newsfeed-day').each(function(){
		if($(this).attr('timestamp') <= timestamp && $(this).attr('timestamp') > prev){
			prev = $(this).attr('timestamp');
		}
	});
	return prev;
}

function getPreviousEntry(timestamp){
	var prev = 0;
	$('.feed-entry').each(function(){
		if($(this).attr('timestamp') <= timestamp && $(this).attr('timestamp') > prev){
			prev = $(this).attr('timestamp');
		}
	});
	return prev;
}

function getPreviousComment(id,timestamp){
	var prev = 0;
	
	$('#'+id).children().each(function(){
		if($(this).attr('timestamp') <= timestamp && $(this).attr('timestamp') > prev){
			prev = $(this).attr('timestamp');
		}
	});
	return prev;
}
var compteur=0;
var max =6;
function addEntryMarker(id,from){
	var markers= $("."+id+"-marker").length;
	if(markers == 0 || markers < 3){
		if (markers == 0){
			var size = 'big';
		}else{
			var size = 'small';
		}
		/*if($('#'+id).find('.feed-picture').length>0){
			$.Tache.DeleteAll();
		}*/

		//if($.jCache.getItem(key))
		$.Tache.Get({
			url:'/feeds/getImage/'+from,
			success:function(data){
				var img = $(data).addClass(size+'-thumb');
				img =$('<div/>').append(img).remove().html();
				var marker="<div  class='"+id+"-marker' from='"+from+"' onclick='getUserNameFromIdPopUp(this,\""+from+"\")'>"+img+"</div>";
				$('#'+id).find('.hidden-markers').before(marker);
				/*if(compteur <=max){
					addEntryMarker(id,from);
					compteur++;
				}*/
			}
		});
		/*var img = "<img src='/img/content/player_placeholder.png' from='"+from+"' class='"+size+"-thumb' onclick='getUserNameFromIdPopUp(this,\""+from+"\")'/>";
		var marker="<div  class='"+id+"-marker' from='"+from+"'>"+img+"</div>";
		$('#'+id).find('.hidden-markers').before(marker);*/
	}else{
		if($('#'+id).find('.show-all').length == 0){
			$("."+id+"-marker:last").appendTo('#'+id+' > .markers > .hidden-markers');
			$("."+id+"-marker:last").remove();
			var showLink = "<div class='show-all' onclick=\"showAllTags('"+id+"')\"> all tags </div>"
			$('#'+id).find('.hidden-markers').before(showLink);
		}
		$.Tache.Get({
			url:'/feeds/getImage/'+from,
			success:function(data){
				var img = $(data).addClass('small-thumb');
				img =$('<div/>').append(img).remove().html();

				var marker="<div  class='"+id+"-marker' from='"+from+"' onclick='getUserNameFromIdPopUp(this,\""+from+"\")'>"+img+"</div>";
				//$(marker).append(img);
				$('#'+id).find('.hidden-markers').append(marker);
				/*if(compteur <= max){
					addEntryMarker(id,from);
					compteur++;
				}*/
			}
		});
		/*var img = "<img src='/img/content/player_placeholder.png' from='"+from+"' class='small-thumb' onclick='getUserNameFromIdPopUp(this,\""+from+"\")'/>";
		var marker="<div  class='"+id+"-marker' from='"+from+"'>"+img+"</div>";
		$('#'+id).find('.hidden-markers').append(marker);*/
	}
}

//récupere l'abscisse d'un objet
function findPosX(obj){
	var curleft = 0;
	if (obj.offsetParent)
	while (1) {
		curleft += obj.offsetLeft;
		if (!obj.offsetParent)
		break;
		obj = obj.offsetParent;
	}
	else
	if (obj.x)
	curleft += obj.x;
	return curleft;
}

//récuperer l'ordonnée d'un objet
function findPosY(obj){
	var curtop = 0;
	if (obj.offsetParent)
	while (1) {
		curtop += obj.offsetTop;
		if (!obj.offsetParent)
		break;
		obj = obj.offsetParent;
	}
	else
	if (obj.y)
	curtop += obj.y;
	return curtop;
}


function showAllTags(id){
	$('#'+id).find('.hidden-markers').toggle();
	
}

function getUserNameFromIdPopUp(elem,from){
	$.ajax({
		type:'get',
		url:'/feeds/getUserName/'+from,
		success:function(data){
			showOver(elem,data);
		}
	})
}
function showOver(elem,username){
	var from = $(elem).attr('from');
	var pos = findPos(elem);
	var hscroll = (document.documentElement.all ? document.documentElement.scrollLeft : window.pageXOffset);
	var vscroll = (document.documentElement.all ? document.documentElement.scrollTop : window.pageYOffset);
	var from = $(elem).attr('from');
	$('.custom-dialog').dialog('destroy');
	$('.closeDialog').remove();
	var closePos='z-index:1003;position:absolute;top:'+(pos.y-10) +'px;left:'+(pos.x+290)+'px';
	var closeBtn="<div onclick=\"$('.custom-dialog').dialog('destroy');$(this).remove()\" class='closeDialog' style='"+closePos+"'></div>";
	$('body').append(closeBtn);
	var dialogBox = $('#custom-dialog').clone().attr('id','this-custom-dialog').addClass('custom-dialog');
	var content = "<div>"
				+"<div><img src='/img/content/player_placeholder.png' class='thumb' /></div>"
				+"<div class='userLink'><a href='/users/profile/"+from+"'>"+username+"</a></div>"
				+"<div>unsubcribe from this user</div>"
				+"</div>";
	dialogBox.html(content);
	
	dialogBox.dialog({
		draggable:false,
		height:'48',
		minHeight:'48',
		modal:false,
		resizable:false,
		show:'normal',
		position:[(pos.x-hscroll),(pos.y-vscroll)]
	});
}
/**************************************
 *                                    *   
 *             @Publish		          *
 *                                    *
 **************************************/


function publishItem(timestamp){
	if ($.trim($('#text').val()) != '') {
		var username = nameToFront($.cookie('feed-username'));
		if (timestamp == null) {
			getTimestamp();
		}
		else {
			var id = new UUID();
			var date = new Date();
			date.setTime(timestamp);
			var now = date.getTime();
			var today = twoDigits(date.getDate()) + "-" + twoDigits(date.getMonth() + 1) + "-" + date.getFullYear();
			var hour = twoDigits(date.getHours()) + ":" + twoDigits(date.getMinutes());
			var user = getCurrentUser();
			var message = "<status>" + secureText(formatLongWords($('#text').val())) + "</status>";
			var iq = $iq({
				'type': 'set',
				'from': getJID() + '/newsfeed',
				'to': 'pubsub.' + domain,
				'id': 'publishItem'
			});
			iq.c('pubsub', {
				'xmlns': 'http://jabber.org/protocol/pubsub'
			});
			iq.c('publish', {
				'node': '/home/' + domain + '/' + user + '/status'
			});
			iq.c('item', {
				'id': id
			}).c('entry', {
				'username': username,
				'from': user,
				'date': now,
				'datenews': today,
				'hournews': hour
			}).t(message);
			//alert(iq.toString());
			connection.send(iq.tree());
		}
		disablePublishForm();
	}
}



function photoChange(mediaId,timestamp){
	var username = nameToFront($.cookie('feed-username'));
		if (timestamp == null) {
			getTimestamp('photos',mediaId);
		}
		else {
			var id = new UUID();
			var date = new Date();
			date.setTime(timestamp);
			var now = date.getTime();
			var today = twoDigits(date.getDate()) + "-" + twoDigits(date.getMonth() + 1) + "-" + date.getFullYear();
			var hour = twoDigits(date.getHours()) + ":" + twoDigits(date.getMinutes());
			var user = getCurrentUser();
			var message = "<photo>" + mediaId + "</photo>";
			var iq = $iq({
				'type': 'set',
				'from': getJID() + '/newsfeed',
				'to': 'pubsub.' + domain,
				'id': 'photoChange'
			});
			iq.c('pubsub', {
				'xmlns': 'http://jabber.org/protocol/pubsub'
			});
			iq.c('publish', {
				'node': '/home/' + domain + '/' + user + '/photos'
			});
			iq.c('item', {
				'id': id
			}).c('entry', {
				'username': username,
				'from': user,
				'date': now,
				'datenews': today,
				'hournews': hour
			}).t(message);
			//alert(iq.toString());
			connection.send(iq.tree());
		}
}
var sendAcceptanceOptions = false;
function publishFriendship(friends,timestamp){
	var username = nameToFront($.cookie('feed-username'));
		if (timestamp == null) {
			getTimestamp('friend',friends);
		}
		else {
			var id = new UUID();
			if(!friends.publishID){
				sendAcceptanceOptions = {
					one:friends.second,
					two:friends.url,
					three:id
				}
				//sendFriendAcceptanceNotification(friends.second,friends.url,id);
			}else{
				id = friends.publishID;
			}
			var date = new Date();
			date.setTime(timestamp);
			var now = date.getTime();
			var today = twoDigits(date.getDate()) + "-" + twoDigits(date.getMonth() + 1) + "-" + date.getFullYear();
			var hour = twoDigits(date.getHours()) + ":" + twoDigits(date.getMinutes());
			var user = getCurrentUser();
			/*var message = "<newfriend>"
					+ "<friend1 username='"+friends.first_name+"'>" + friends.first + "</friend1>"
					+"<friend2 username='"+friends.second_name+"'>"+friends.second+"</friend2>"
					+"</newfriend>";*/
			var iq = $iq({
				'type': 'set',
				'from': getJID() + '/newsfeed',
				'to': 'pubsub.' + domain,
				'id': 'publishFriend'
			});
			iq.c('pubsub', {
				'xmlns': 'http://jabber.org/protocol/pubsub'
			});
			iq.c('publish', {
				'node': '/home/' + domain + '/' + user + '/status'
			});
			iq.c('item', {
				'id': id
			}).c('entry', {
				'username': username,
				'from': user,
				'date': now,
				'datenews': today,
				'hournews': hour
			}).c('newfriend');
			iq.c('friend1',{'username':friends.first_name}).t(friends.first).up();
			iq.c('friend2',{'username':friends.second_name}).t(friends.second);
			connection.send(iq);
		}
}
var contributionURL='/';
function publishContribution(options,timestamp){
		var username = nameToFront($.cookie('feed-username'));
		if (timestamp == null) {
			getTimestamp('contribute',options);
		}
		else {
			var id = new UUID();
			var date = new Date();
			date.setTime(timestamp);
			var now = date.getTime();
			var today = twoDigits(date.getDate()) + "-" + twoDigits(date.getMonth() + 1) + "-" + date.getFullYear();
			var hour = twoDigits(date.getHours()) + ":" + twoDigits(date.getMinutes());
			var user = getCurrentUser();
			var iq = $iq({
				'type': 'set',
				'from': getJID() + '/newsfeed',
				'to': 'pubsub.' + domain,
				'id': 'publishContribution'
			});
			iq.c('pubsub', {
				'xmlns': 'http://jabber.org/protocol/pubsub'
			});
			iq.c('publish', {
				'node': '/home/' + domain + '/' + user + '/status'
			});
			iq.c('item', {
				'id': id
			}).c('entry', {
				'username': username,
				'from': user,
				'date': now,
				'datenews': today,
				'hournews': hour
			}).c('contribution',options);
			if(options.noRedirect){
				contributionURL = null;
			}else{
				contributionURL = "/"+options.model+"/news/"+options.id;
			}
			
			connection.send(iq);
		}
}


function publishFavorites(options,timestamp){
	var username = nameToFront($.cookie('feed-username'));
		if (timestamp == null) {
			getTimestamp('favorite',options);
		}
		else {
			var id = new UUID();
			var date = new Date();
			date.setTime(timestamp);
			var now = date.getTime();
			var today = twoDigits(date.getDate()) + "-" + twoDigits(date.getMonth() + 1) + "-" + date.getFullYear();
			var hour = twoDigits(date.getHours()) + ":" + twoDigits(date.getMinutes());
			var user = getCurrentUser();
			var iq = $iq({
				'type': 'set',
				'from': getJID() + '/newsfeed',
				'to': 'pubsub.' + domain,
				'id': 'publishFavorite'
			});
			iq.c('pubsub', {
				'xmlns': 'http://jabber.org/protocol/pubsub'
			});
			iq.c('publish', {
				'node': '/home/' + domain + '/' + user + '/status'
			});
			iq.c('item', {
				'id': id
			}).c('entry', {
				'username': username,
				'from': user,
				'date': now,
				'datenews': today,
				'hournews': hour
			}).c('favorite',options);
			connection.send(iq);
		}
}
/**************************************
 *                                    *   
 *            @Subscription	          *
 *                                    *
 **************************************/

function subscribeToNode(user,nodeName,subscriber){
	if(subscriber == null){
		subscriber = getJID();
	}else{
		subscriber = subscriber+"@"+domain
	}
	last ='Last';
	var iq = $iq({'type':'set','to':'pubsub.'+domain,'id':'subscribe'+last});
	iq.c('pubsub',{
		'xmlns': 'http://jabber.org/protocol/pubsub'
	});
	iq.c('subscribe',{'node':'/home/'+domain+'/'+user+'/'+nodeName,'jid':subscriber});
	connection.send(iq.tree());
}


function subscribeToPage(nodeName,last){
	var subscriber = getJID();
	if(last == null){
		var id = 'subscribeToPage';
	}else{
		var id = 'subscribeToPageLast';
	}
	var iq = $iq({'type':'set','to':'pubsub.'+domain,'id':id});
	iq.c('pubsub',{
		'xmlns': 'http://jabber.org/protocol/pubsub'
	});
	iq.c('subscribe',{'node':nodeName,'jid':subscriber});
	connection.send(iq.tree());
}
/**************************************
 *                                    *   
 *          @Delete Items 	          *
 *                                    *
 **************************************/

function deleteItem(elem,node,subnode){
	
	if(subnode ==  null){
		subnode = 'status';
	}
	if(node == null){
		node = $(elem).parent().parent().attr('from');
	}
	var id = $(elem).parent().parent().attr('id');
	if(id == undefined){
		id = $(elem).attr('id');
	}
	
	$('#'+id).fadeOut('slow',function(){
		$(this).remove();
	});
	;
	var iq = $iq({'type':'set','from':getJID()+'/newsfeed','to':'pubsub.'+domain,'id':'retract'});
	iq.c('pubsub',{
		'xmlns': 'http://jabber.org/protocol/pubsub'
	});
	iq.c('retract',{'node':'/home/'+domain+'/'+node+'/'+subnode});
	iq.c('item',{'id':id});
	//alert(iq.toString());
	connection.send(iq.tree());
}


function deleteNotification(user, id){
	var iq = $iq({'type':'set','from':getJID()+'/newsfeed','to':'pubsub.'+domain,'id':'retract'});
	iq.c('pubsub',{
		'xmlns': 'http://jabber.org/protocol/pubsub'
	});
	iq.c('retract',{'node':'/home/'+domain+'/'+user+'/notifications'});
	iq.c('item',{'id':id});
	//alert(iq.toString());
	connection.send(iq.tree());
}
/**************************************
 *                                    *   
 *          @Items Retrieval          *
 *                                    *
 **************************************/



function getSubscriptions(del){
	var user = getCurrentUser();
	var end = '';
	if(del == 1){
		end = 'delete';
	}else if(del == 2){
		end = 'friend';
	}
	var iq = $iq({'type':'get','from':getJID()+'/newsfeed','to':'pubsub.'+domain,'id':'getMemberSubscriptions'+end});
	iq.c('pubsub',{
		'xmlns': 'http://jabber.org/protocol/pubsub'
	});
	iq.c('subscriptions');
	//alert(iq.toString());
	connection.send(iq.tree());
}

function getSubscriptionsToBecomeFriend(){
	var user = getCurrentUser();

	var iq = $iq({'type':'get','from':getJID()+'/newsfeed','to':'pubsub.'+domain,'id':'getMemberSubscriptionsToBecomeFriend'});
	iq.c('pubsub',{
		'xmlns': 'http://jabber.org/protocol/pubsub'
	});
	iq.c('subscriptions');
	connection.send(iq.tree());
}

function getAffiliations(del){
	action ='';
	if(del != null){
		action ='ToDelete'
	}
	var user = getCurrentUser();
	var iq = $iq({'type':'get','from':getJID()+'/newsfeed','to':'pubsub.'+domain,'id':'getMemberAffiliations'+action});
	iq.c('pubsub',{
		'xmlns': 'http://jabber.org/protocol/pubsub'
	});
	iq.c('affiliations');
	connection.send(iq.tree());
}

function getMemberNodeChildNodes(){
	var user = getCurrentUser();
	var iq = $iq({'type':'get','from':getJID()+'/newsfeed','to':'pubsub.'+domain,'id':'getMemberChildNodes'});
	iq.c('pubsub',{'xmlns':'http://jabber.org/protocol/disco#items','node':'/home/'+domain+'/'+user});
	connection.send(iq);
}
function getAllItems(){
	
	for(var i =0;i<subscribedNode.length;i++){
		getItemsFromNode(subscribedNode[i]);
	}
	for(var i =0;i<commentsNode.length;i++){
		getItemsFromNode(commentsNode[i]);
	}
	

}

function getItemsFromNode(nodeName){
	var user = getCurrentUser();
	var iq = $iq({'type':'get','from':getJID()+'/newsfeed','to':'pubsub.'+domain,'id':'getItems'});
	iq.c('pubsub',{
		'xmlns': 'http://jabber.org/protocol/pubsub'
	});
	iq.c('items',{'node':nodeName,'max_items':'50'});
	connection.send(iq.tree());
}


/**************************************
 *                                    *   
 *          @Nodes Creation           *
 *                                    *
 **************************************/


function createMemberCollectionNode(){
	var user = getCurrentUser();
	var iq = $iq({'type':'set',from:getJID(),to:'pubsub.'+domain,'id':'createMemberCollectionNode'});
	iq.c('pubsub',{xmlns:'http://jabber.org/protocol/pubsub'});
	iq.c('create',{'node':'/home/'+domain+'/'+user}).up();
	iq.c('configure');
	iq.c('x',{'xmlns': 'jabber:x:data',type:'submit'});
	iq.c('field',{'var':'FORM_TYPE','type':'hidden'}).c('value').t('http://jabber.org/protocol/pubsub#node_config').up().up();
	iq.c('field',{'var':'pubsub#title'}).c('value').t('member').up().up();
	iq.c('field',{'var':'pubsub#node_type'}).c('value').t('collection').up().up();
	//alert(iq.toString());
	connection.send(iq.tree());
}

function createMemberChildNode(nodeName){
	var user = getCurrentUser();
	
	var iq = $iq({'type':'set',from:getJID(),to:'pubsub.'+domain,'id':'createMember'+nodeName.ucFirst()+'Node'});
	iq.c('pubsub',{xmlns:'http://jabber.org/protocol/pubsub'});
	iq.c('create',{'node':'/home/'+domain+'/'+user+"/"+nodeName}).up();
	iq.c('configure');
	iq.c('x',{'xmlns': 'jabber:x:data','type':'submit'});
	iq.c('field',{'var':'FORM_TYPE','type':'hidden'}).c('value').t('http://jabber.org/protocol/pubsub#node_config').up().up();
	
	if(nodeName == 'comments' || nodeName == 'notifications'){
		iq.c('field',{'var':'pubsub#publish_model'}).c('value').t('open').up().up();
		iq.c('field',{'var':'pubsub#max_items'}).c('value').t('20').up().up();
	}else{
		iq.c('field',{'var':'pubsub#publish_model'}).c('value').t('open').up().up();
		iq.c('field',{'var':'pubsub#max_items'}).c('value').t('20').up().up();
	}
	iq.c('field',{'var':'pubsub#access_model'}).c('value').t('open').up().up();
	iq.c('field',{'var':'pubsub#deliver_payloads'}).c('value').t('1').up().up();
	iq.c('field',{'var':'pubsub#persist_items'}).c('value').t('1').up().up();
	iq.c('field',{'var':'pubsub#notify_config'}).c('value').t('0').up().up();
	iq.c('field',{'var':'pubsub#notify_delete'}).c('value').t('0').up().up();
	iq.c('field',{'var':'pubsub#notify_retract'}).c('value').t('0').up().up();
	
	
	/*iq.c('x',{'xmlns': 'jabber:x:data',type:'submit'});
	iq.c('field',{'var':'FORM_TYPE','type':'hidden'}).c('value').t('http://jabber.org/protocol/pubsub#node_config').up().up();
	//iq.c('field',{'var':'pubsub#collection'}).c('value').t('/home/'+domain+'/'+user[0]).up().up();
	iq.c('field',{'var':'pubsub#title'}).c('value').t(nodeName).up().up();
	iq.c('field',{'var':'pubsub#node_type'}).c('value').t('leaf').up().up();
	iq.c('field',{'var':'pubsub#deliver_notifications'}).c('value').t('1').up().up();
	iq.c('field',{'var':'pubsub#deliver_payloads'}).c('value').t('1').up().up();
	iq.c('field',{'var':'pubsub#persist_items'}).c('value').t('1').up().up();
	iq.c('field',{'var':'pubsub#access_model'}).c('value').t('open').up().up();
	if(nodeName == 'comments'){
		iq.c('field',{'var':'pubsub#publish_model'}).c('value').t('subscribers').up().up();
	}else{
		iq.c('field',{'var':'pubsub#publish_model'}).c('value').t('publishers').up().up();
	}
	iq.c('field',{'var':'pubsub#max_payload_size'}).c('value').t('100000').up().up();
	iq.c('field',{'var':'pubsub#notify_config'}).c('value').t('0').up().up();
	iq.c('field',{'var':'pubsub#notify_delete'}).c('value').t('0').up().up();
	iq.c('field',{'var':'pubsub#notify_retract'}).c('value').t('0').up().up();*/
	//alert(iq.toString());
	connection.send(iq.tree());
}

function createInstantNode(){
	var user = getCurrentUser();
	var iq = $iq({'type':'set',from:getJID(),to:'pubsub.'+domain,'id':'createInstantChildNode'});
	iq.c('pubsub',{xmlns:'http://jabber.org/protocol/pubsub'});
	iq.c('create').up();
	iq.c('configure');
	//alert(iq.toString());
	connection.send(iq.tree());
}

/**************************************
 *                                    *   
 *          @Nodes Discovery          *
 *                                    *
 **************************************/

function childNodesExists(){
	var attrs ={'type':"get",
				'from':getJID()+'/newsfeed',
				'to':'pubsub.'+domain,
				'id':'discoChild'
				};
	var queryAtrr = {
		'xmlns':'http://jabber.org/protocol/disco#info',
		'node':'/home/'+domain+'/'+getCurrentUser()+'/news'
	};
	var iq = $iq(attrs).c('query',queryAtrr);
	
	//alert(iq.toString());
	connection.send(iq);
}
function memberNodeExists(){
	var attrs ={'type':"get",
				'from':getJID()+'/newsfeed',
				'to':'pubsub.'+domain,
				'id':'discoMember'
				};
	var queryAtrr = {
		'xmlns':'http://jabber.org/protocol/disco#info',
		'node':'/home/'+domain+'/'+getCurrentUser()
	};
	var iq = $iq(attrs).c('query',queryAtrr);
	
	//alert(iq.toString());
	connection.send(iq);
}

function getNodeConfigurationForm(){
	var user = getCurrentUser();
	var iq = $iq({'type':"get",
		'from':getJID(),
		'to':'pubsub.'+domain,
		'id':'config'					
		}).c('pubsub',{'xmlns':'http://jabber.org/protocol/pubsub#owner'}).c('configure',{'node':'/home/'+domain+'/'+user+'/news'});
	connection.send(iq);
}

/**************************************
 *                                    *   
 *             @Comments              *
 *                                    *
 **************************************/
function publishComment(options,timestamp){
	//nodeId,entryId,timestamp
	if ($.trim(options.text) != '') {
		var username = nameToFront($.cookie('feed-username'));
		if (timestamp == null) {
			getTimestamp('comment', options);
		}
		else {
			var id = new UUID();
			var date = new Date();
			date.setTime(timestamp);
			var now = date.getTime();
			var today = twoDigits(date.getDate()) + "-" + twoDigits(date.getMonth() + 1) + "-" + date.getFullYear();
			var hour = twoDigits(date.getHours()) + ":" + twoDigits(date.getMinutes());
			var user = options.nodeId;
			var sender = options.sender;
			var message = "<comment relateditem='" + options.entryId + "'>" + formatLongWords(options.text) + "</comment>";
			var iq = $iq({
				'type': 'set',
				'from': getJID() + '/newsfeed',
				'to': 'pubsub.' + domain,
				'id': 'publishItem'
			});
			iq.c('pubsub', {
				'xmlns': 'http://jabber.org/protocol/pubsub'
			});
			iq.c('publish', {
				'node': '/home/' + domain + '/' + user + '/comments'
			});
			iq.c('item', {
				'id': id
			}).c('entry', {
				'from': user,
				'sender':sender,
				'username': username,
				'date': now,
				'datenews': today,
				'hournews': hour
			}).t(message);
			//alert(iq.toString());
			connection.send(iq.tree());
		}
	}
	
}

function showComments(elem){
	var entryId = $(elem).parent().parent().attr('id');
	var nodeId = $(elem).parent().parent().attr('from');
	if($('#comments-'+entryId).length==0){
		var mycomment= $("#comment-form").clone().attr('id','comments-'+entryId);
		$(elem).parent().parent().append(mycomment.show('slow'));
		$('#comments-'+entryId+' > textarea').focus();
		$("#comments-"+entryId+" > button").bind('click',function(){
			var text=$("#comments-"+entryId+" > textarea").val();
			var options ={
				nodeId:nodeId,
				sender:getCurrentUser(),
				entryId:entryId,
				text:text
			}
			publishComment(options);
			$("#comments-"+entryId+" > textarea").val('');
		});
		$('#this-entry-comments-'+entryId).show('fast');
	}else{
		//alert($('#this-entry-comments-'+entryId).css('display') );
		if($('#this-entry-comments-'+entryId).css('display') != 'none'){
			$('#this-entry-comments-'+entryId).hide();
			$('#comments-'+entryId).hide();
		}else{
			$('#this-entry-comments-'+entryId).show();
			$('#comments-'+entryId).show();
		}
	}
	
}

function deleteComment(elem){
	var id = $(elem).parent().parent().parent().attr('id');
	var feed=$(elem).parent().parent().parent().attr('relateditem');
	var node = $(elem).parent().parent().parent().attr('from');
	$('#'+id).fadeOut('slow',function(){
		$(this).remove();
		var items = $('#this-entry-comments-' + feed).children('.feedcomment').length;
		$('#comments-count-'+feed).text('Comment('+items+')');
	});
	var iq = $iq({'type':'set','from':getJID()+'/newsfeed','to':'pubsub.'+domain,'id':'retract'});
	iq.c('pubsub',{
		'xmlns': 'http://jabber.org/protocol/pubsub'
	});
	iq.c('retract',{'node':'/home/'+domain+'/'+node+'/comments'});
	iq.c('item',{'id':id});
	//alert(iq.toString());
	connection.send(iq.tree());
}
/**************************************
 *                                    *   
 *               @Tools               *
 *                                    *
 **************************************/

function getTextDate(timestamp){
	var date = new Date();
	var compare = new Date()
	compare.setFullYear(date.getFullYear(),date.getMonth(),date.getDate());
	compare.setHours(0,0,0,0);
	var today = compare.getTime();
	var yesterday = today-86400000; // number of seconds in 24hours
	//date.setTime(timestamp);
	if(timestamp == today){
		return 'Today';
	}else if(timestamp == yesterday){
		return 'Yesterday';
	}else{
		date.setTime(timestamp);
		return date.toLocaleDateString();
	}
	
} 

function deleteNode(node){
	var user = getCurrentUser();
	var iq = $iq({'type':"set",
		'from':getJID()+'/newsfeed',
		'to':'pubsub.'+domain,
		'id':'config'					
		}).c('pubsub',{'xmlns':'http://jabber.org/protocol/pubsub#owner'}).c('delete',{'node':'/home/'+domain+'/'+user+'/'+node});
	connection.send(iq);
}

function unsubscribeNode(user,node,subid){
	var iq = $iq({'type':'set','from':getJID()+'/newsfeed','to':'pubsub.'+domain,'id':'unsubscribe'});
	iq.c('pubsub',{
		'xmlns': 'http://jabber.org/protocol/pubsub'
	});
	iq.c('unsubscribe',{'node':'/home/'+domain+'/'+user+'/'+node,'jid':getJID(),'subid':subid});
	connection.send(iq.tree());
}

function deleteAllSubscriptions(data){
	var subscriprions = $(data).find('subscription');
	
	for(var i =0; i<50 && i<subscriprions.length;i++){
		var user = $(subscriprions[i]).attr('node').split('/')[3];
		var node = $(subscriprions[i]).attr('node').split('/')[4];
		var subid = $(subscriprions[i]).attr('subid');
		unsubscribeNode(user,node,subid);
	}
	return true;
}

function test(){
	alert(favoriteOptions.id);
}

function getServerVersion(){
	var iq = $iq({type:'get',to:domain}).c('query',{xmlns:'jabber:iq:version'});
	connection.send(iq);
}

function getCurrentUser(){
	return $.cookie('userId');
}
function getCurrentUsername(){
	return nameToFront($.cookie('feed-username'));
}
function getJID(){
	return $.cookie('userId')+'@'+domain;
}

function userExists(login){
	$.ajax({
		method:'GET',
		url:'/liveFeed/feeds/userExists',
		data:'username='+login,
		success:function(data){
			loginExists = data;
		},
		complete:afterExistCheck
	})
}
 
 
function createUser(login){
	$.ajax({
		method:'GET',
		url:'/liveFeed/feeds/createUser',
		data:'username='+login,
		success:function(data){
			$.cookie('userName-userID',data,{path:"/"});
			close_pop_login();
			registerNewUser();
		}
	});
}

function twoDigits(i){
	if(i<10){
		return '0'+i;
	}else{
		return i;
	}
}
function sleep(time){
	for(i=0;i<time*10000;i++){
		
	}
	return;
}
function getTimestamp(to,options){
	$.ajax({
		type:'GET',
		url:'/feeds/getTimestamp',
		cache:false,
		success:function(data){
			if (to == 'comment') {
				publishComment(options, data);
			}else if (to == 'friend') {
				publishFriendship(options, data);
			}else if (to == 'contribute') {
				publishContribution(options, data)
			}else if (to == 'photos') {
				photoChange(options, data)
			}else if (to == 'favorite') {
				publishFavorites(options, data)
			}else {
				publishItem(data);
			}
		}
	});
}

function deleteAllNodes(elem){
	if(elem == null){
		getAffiliations('delete');
	}else{
		$(elem).find('affiliation').each(function(){
			var node = $(this).attr('node').split('/');
			if(node.length == 5){
				deleteNode(node[4]);
			}
		});
	}
	
}

function nameToServer(name){
	var reg= new RegExp(' ','g');
	var test = name.replace(reg,'_');
	return test;
	
}
function nameToFront(name){
	var reg= new RegExp('_','g');
	var test = name.replace(reg,' ');
	return test;
}

function enablePublishForm(){
	$('.publish-div').find('textarea').val(YouFoot.i18n.get('Enter your text here'));
	$(".publish-items").removeAttr('disabled');
}
function disablePublishForm(){
	$(".publish-items").attr('disabled','true');
}

function formatLongWords(text){
	var words = text.split(' ');
	var max_word_length = 50;
	for(var i = 0; i<words.length;i++){
		var word = words[i];
		if(word.length> max_word_length){
			var letters = word.split("");
			var newLetters = letters;
			var offset = max_word_length;
			while(offset<letters.length){
				newLetters.splice(offset,0,"\n");
				offset = offset + max_word_length + 1;
			}
			word = newLetters.join("");
			words.splice(i,1,word);
		}
	}
	return words.join(' ');
}

function secureText(text){
	var reg=new RegExp("(#@\/)", "g");
	return text.replace(reg,'');
}
function createApplicationNode(nodeName,go){
	applicationToCreate = nodeName;
	if (go == null) {
		createApplication = true;
		connection.disconnect();
	}
	else {
		var user = getCurrentUser();
		var iq = $iq({
			'type': 'set',
			to: 'pubsub.' + domain,
			'id': 'createApplication' + nodeName.ucFirst() + 'Node'
		});
		iq.c('pubsub', {xmlns: 'http://jabber.org/protocol/pubsub'});
		iq.c('create', {'node': "" + nodeName,'type':'flat'}).up();
		iq.c('configure');
		iq.c('x', {'xmlns': 'jabber:x:data','type': 'submit'});
		iq.c('field', {'var': 'FORM_TYPE','type': 'hidden'}).c('value').t('http://jabber.org/protocol/pubsub#node_config').up().up();
		iq.c('field', {'var': 'pubsub#publish_model'}).c('value').t('open').up().up();
		iq.c('field', {'var': 'pubsub#max_items'}).c('value').t('20').up().up();
		iq.c('field', {'var': 'pubsub#access_model'}).c('value').t('open').up().up();
		iq.c('field', {'var': 'pubsub#deliver_payloads'}).c('value').t('1').up().up();
		iq.c('field', {'var': 'pubsub#persist_items'}).c('value').t('0').up().up();		
		iq.c('field', {'var': 'pubsub#notify_config'}).c('value').t('0').up().up();
		iq.c('field', {'var': 'pubsub#notify_delete'}).c('value').t('0').up().up();
		iq.c('field', {'var': 'pubsub#notify_retract'}).c('value').t('0').up().up();
		//alert(iq.toString());
		connection.send(iq.tree());
	}
}
function createPageChildNode(nodeName,last){
	if(last != null){
		var id = 'lastPageChildNode';
	}else{
		var id = 'createPage' + nodeName.ucFirst() + 'Node';
	}
	var iq = $iq({
			'type': 'set',
			to: 'pubsub.' + domain,
			'id': id
		});
		iq.c('pubsub', {xmlns: 'http://jabber.org/protocol/pubsub'});
		iq.c('create', {'node': "" + nodeName,'type':'flat'}).up();
		iq.c('configure');
		iq.c('x', {'xmlns': 'jabber:x:data','type': 'submit'});
		iq.c('field', {'var': 'FORM_TYPE','type': 'hidden'}).c('value').t('http://jabber.org/protocol/pubsub#node_config').up().up();
		iq.c('field', {'var': 'pubsub#publish_model'}).c('value').t('open').up().up();
		iq.c('field', {'var': 'pubsub#max_items'}).c('value').t('20').up().up();
		iq.c('field', {'var': 'pubsub#access_model'}).c('value').t('open').up().up();
		iq.c('field', {'var': 'pubsub#deliver_payloads'}).c('value').t('1').up().up();
		iq.c('field', {'var': 'pubsub#persist_items'}).c('value').t('0').up().up();		
		iq.c('field', {'var': 'pubsub#notify_config'}).c('value').t('0').up().up();
		iq.c('field', {'var': 'pubsub#notify_delete'}).c('value').t('0').up().up();
		iq.c('field', {'var': 'pubsub#notify_retract'}).c('value').t('0').up().up();
		//alert(iq.toString());
		connection.send(iq.tree());
}

function createPageNodes(page,go,options){
	if(go == null){
		pageToCreate=page;
		createPage=true;
		connection.disconnect();
		if(options != null){
			pageToCreateOptions = options;
		}
	}else{
		setTimeout(function(){
			createPageChildNode(pageToCreate+"-photos");
		},800);
		setTimeout(function(){
			createPageChildNode(pageToCreate+"-videos");
		},800);
		setTimeout(function(){
			createPageChildNode(pageToCreate+"-news");
		},800);
		setTimeout(function(){
			createPageChildNode(pageToCreate+"-activities");
		},800);
		setTimeout(function(){
			createPageChildNode(pageToCreate+"-comments",1);
		},800);
	}
	
}

var friendRequest='';
function sendFriendAcceptanceNotification(user,requestURL,id){
	var username = nameToFront($.cookie('feed-username'));
	var userID = $.cookie('userId');
	var iq = $iq({
				'type': 'set',
				'from': getJID() + '/newsfeed',
				'to': 'pubsub.' + domain,
				'id': 'acceptFriendship'
			});
			iq.c('pubsub', {
				'xmlns': 'http://jabber.org/protocol/pubsub'
			});
			iq.c('publish', {
				'node': '/home/' + domain + '/' + user + '/notifications'
			});
	iq.c('item',{'id':id}).c('entry', {
				'username': username,
				'from': userID
			}).c('accepted');
	connection.send(iq.tree());
	friendRequest=requestURL;
}


function becomeFriendWith(elem, notice,requestURL,name){
	if (notice == null){
		var userId = $(elem).find('entry:first').attr('from');
		var userName = $(elem).find('entry:first').attr('username');
		var uuid = $(elem).attr('id');
	}else{
		var userId = elem;
		var userName = name;
		var uuid = false;
	}
	setTimeout(function(){
	subscribeToNode(userId,'news');
	},800);
	setTimeout(function(){
	subscribeToNode(userId,'status');
	},800);
	setTimeout(function(){
	subscribeToNode(userId,'videos');
	},800);
	setTimeout(function(){
	subscribeToNode(userId,'photos');
	},800);
	setTimeout(function(){
		subscribeToNode(userId,'activities');
	},800);
	setTimeout(function(){
	subscribeToNode(userId,'comments');
	},800);

	setTimeout(function(){
		var options = {
			first:getCurrentUser(),
			first_name:getCurrentUsername(),
			second:userId,
			second_name:userName,
			url:requestURL,
			publishID:uuid
		}
		publishFriendship(options);
	}, 1000);
	/*setTimeout(function(){
		//getSubscriptionsCalled = false;
		//getSubscriptions();
	},800);*/
}
function checkSubscriptionsToBecomeFriend(data){
	var my_data = Strophe.serialize(data);
	if (old_data != my_data) {
		old_data = my_data;
		handelNotification(friend,data);
	}
	return true;
}


var friend;
function handelNotification(elem,data){
	if(data == null){
		friend = elem;
		getSubscriptionsToBecomeFriend(1);
	}else{
		//alert(Strophe.serialize(data));
		var friends=new Array();
		 $(data).find('subscription').each(function(){
		 	var user = $(this).attr('node').split('/')[3];
			if($.inArray(user,friends) == -1){
				friends.push(user);
			}
		});
		var userId = $(elem).find('entry:first').attr('from');
		if($.inArray(userId,friends) == -1){
			becomeFriendWith(elem);
		}
	}
}


function purgeNode(node){
	var user = getCurrentUser();
	var iq = $iq({'type':"set",
		'from':getJID()+'/newsfeed',
		'to':'pubsub.'+domain,
		'id':'purge'					
		}).c('pubsub',{'xmlns':'http://jabber.org/protocol/pubsub#owner'}).c('purge',{'node':'/home/'+domain+'/'+user+'/'+node});
	connection.send(iq);
}

function unsubscribeFromAll(){
	getSubscriptions(1);
}


var friendToDelete;
function unfriend(userid){
	getSubscriptions(2);
	friendToDelete = userid;
}
function deleteFriend(data){
	if (old_data != data) {
		old_data = data;
		$(data).find('subscription').each(function(){
			if ($(this).attr('node').split('/')[3] == friendToDelete) {
			 	unsubscribeNode(friendToDelete,$(this).attr('node').split('/')[4],$(this).attr('subid'));
			}
		});
		//friendToDelete = null;
	}
}

function empty(varibale){
	if(typeOf(variable)=='undefined' || !variable){
		return true;
	}else{
		return false;
	}
}

function bindTimeAgo(){
	$('.feed-entry-time').each(function(){
		var timestamp = $(this).attr('timestamp');
		var date = new Date();
		date.setTime(timestamp);
		var title = date.toISO8601String();
		var day = new Date();
		day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
		day.setHours(0, 0, 0, 0);
		if(getTextDate(day.getTime()) == 'Today'){
			$(this).attr('title',title);
			$(this).timeago();
		}
	});	
}
