

QSTimeout = null;
QSHideTools	= true;



function d(){
	if(console != undefined && console.log){
		for(i=0,l=arguments.length;i<l;i++){
			console.log(arguments[i]);
		}
	}
}
function isEmpty(ob){
	for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
	return true;
}


var showInfoMessage = function(A)
{
	
	var B = $('#sys_msg');	
	if(B.length == 0){
		B = $('<div id="sys_msg"><span class="success"></span></div>');
		$('#w_container').append(B);
	}
	B.find('span').html(A);		
	var C = function(){
         setTimeout(function(){B.slideUp()},3500);
    }
	B.slideDown("fast",C);
    
}


var processCallback = function(A,B,C,D)
{		
	$('#'+B+'Loading').hide();	
	/** THIS IS HACK FOR RIGHT_PANE * */
	if (D != 'new_stream' && $("#right_pane").is(':hidden') && favitCache.is('notify_pane_width')) {
		$("#notify").css("width", favitCache.get('notify_pane_width'));
		$("#right_pane").show();
		$('#left_content').removeClass('no-scroll').addClass('scroll-pane');
	}
	if(favitCallbacks[C]){
		favitCallbacks[C](A, D);
	}
}

var displayStream	= function(A)
{

	if (!A) return;			
	if(A.right)
	{
		$('#right_pane').html(A.html);
		return;
	}	
	$('#left_pane .title').html(A.title);	
	
	var content = $('#left_pane .content:eq(0)');
				
	var B = A.start;
	
	if(B == 30){
		content.html('');			
		if(A.header){
			content.append($(A.header));
		}
		if(A.subheader){
			$('#lsubheader').html(A.subheader);
		}
	}
	var fitem	= null;
			
	for(i in A.posts){										
		var post = A.posts[i];				
		if(!post){
			continue;
		}				
		var item = $(post.list_html);
		item.data('post_html', post.content_html);
		item.data('post_id', post.post_id);
		item.data('short_id', post.short_id);
		item.data('view_id', post.view_id);			
		item.data('vt', post.view_type);
		item.data('t',post.spread_twitter);
		item.data('f',post.spread_facebook);
		item.data('timestamp', post.time_published);
		
		var dummy = $(post.content_html);
		
		dummy.find('img').each(function(index){
			$.preLoadImages(this.src);				
		});									
		content.append(item);				
	}			
	if(A.bottom){
		content.append($(A.bottom));
	}
	var B = $('#regular_sub_header .i_actor');
	
	if(A.entity_data){
		var C = A.entity_data;
		B.show();
		var A = $('#regular_sub_header img');
		A.attr('src',C.avatar_url);
		var D = $('#regular_sub_header .dnamea');
		D.html(C.display_name);
		var E = $('.i_actor a');
		//E.unbind().bind('click',function(){fe.clickHandlers.editStream(A.title);return false;});
		E.attr('href','/#/profile/'+C.nickname);
		
	}else{
		B.hide();			
	}
	
	if(A.RT){
		var C = $('#nav [rel="'+A.title+'"]').attr('id');
		
		if(A.chanel){
			C = A.chanel;
		}
		
		var D = '';
		if(A.q){
			D = A.q;
		}						
		realtime.start(C,D);
	}
	
	
	/** REMOVELATER * */
	 var forceHeight = ($("#left_pane").height() - 104) + "px";
	 $('#left_pane .scroll-pane').css({"bottom":"auto", 'height':forceHeight})
	 	.jScrollPane({reset:B == 30, left:{contr:"#left_pane", offset: (B > 30) ? 50 : 104 } });
	 
	 // remove all but last "show more" div
	 $('#left_pane .show_more:not(:last)').remove();
	 
	 if(favitCallbacks.onlineTimeout){
		clearTimeout(favitCallbacks.onlineTimeout);
	 }
	 favitCallbacks.onlineTimeout = setTimeout('favitUI.onlineNotifier()', favit.oi);
	 
	 if(pageTracker){				 				 				 				 			
		 pageTracker._trackPageview("/stream/"+A.title); 
	}
	
}

var delegate  = function()
{
	// register click delegator
	$('body').live('change click focus blur keyup mouseover mouseout', function(event) {
		
		// loop up to the body for elements with l_
		var el = null;
		for(var node = event.target; node; node = node.parentNode) {		
			if (!node.className) {
				continue;
			}				
			// first found will be executed
			var el = node;											
			if (el && el.className != '' && el.className != 'wel_ctrl' && el.className.match(/\s*l_([\w]+)\s*/i)) {
								
				var isInput	= /^.*(input|textarea|password).*$/i.test(el.tagName);
				var nonCapture = /noncapture/.test(el.className);
				
				if(isInput && !nonCapture && !el.originalValue && el.value){
					el.originalValue = el.value;
				}
				
				var fNses = el.className.match(/\bl_([\w]+)\b/ig);								
				if(fNses){						
					for (var _i = 0, _l = fNses.length; _i < _l; _i++) {
						var fN = fNses[_i].replace(/l_/, '');
						fN = $.trim(fN); // remove whitespaces
						
						// var fN = el.className.match(/\s*l_([\w]+)\s*/i)[1];
						var pS = el.getAttribute('params') || {};
						
						// original element
						var oE = event.srcElement || event.originalTarget;
						
						var eventHandler = event.type + 'Handlers';
						var prevent = false;
						
						if (favitEvents[eventHandler] && favitEvents[eventHandler][fN]) {
							
							if (event.type == 'click' && event.button != 0) return false;
							prevent =  favitEvents[eventHandler][fN](el, pS, oE, event);
						}
					}
				}
				
				if(isInput){
					switch(event.type){
					
						case 'focusin':
							if(el.value == el.originalValue){									
								el.value = '';
							}								
							break;
						case 'focusout':								
							if(el.value == '' && el.originalValue){
								el.value = el.originalValue;
							}
							break;
					}
					
					// OK WE DO NOT NEED TO BUBBLE HERE SO CUT!
					return true;
				}
				node = false; // exit loop
				
				// IF MULTIPLE DELEGATES USED, LAST ONE WILL TAKE EFFECT ON PREVENT
				if (!prevent) {
					return false; // prevent default click behaviour
				}
				
			}
		}
		
		return true;
	});
}
var initFavit = function(){
		
	route('stream/:streamname/:filter').bind(function(A){			
		var B = {'value':A.streamname};
		$.get('/a/stream',B,displayStream,'json');		
	});

	route('feed/:feedurl').bind(function(A){				
		var B = {'value':A.feedurl};
		$.get('/a/feed',B,displayStream,'json');		
	});
		
	$(':input').each(function(index){
		if(!$(this).hasClass('noncapture') && !this.originalValue && this.value){
			this.originalValue = this.value;
		}
	});		
	
	setInterval(function () {HL._onhashchange();}, 100);
	delegate();
}

var genroute = function(A)
{
	d('Genroute:');
	d(A);
}

var HL = {}; // hash listener dispatcher

HL._hashchange_last = '';
HL._onhashchange=function(){
  if(HL._hashchange_last!=location.hash){
	  HL._hashchange_last=location.hash;	  
	  route(location.hash).run();
  }
}

var favit = f = {	
	oi: 1000 * 60,
	sparams : {},
	vn	: null,	
	init : initFavit,
	
	myNetworkIndex: {},
	buildMyNetworkIndex: function(data) {
		
		if (!data) return; // FIXME: better validation
		
		for(i in data) {
        	
        	if (i == 'counter') continue;
        	
            var c = data[i];
            var id = i;
            
            var names = c.name.split(/\s+/);
            
            for (var j=0,l=names.length;j<l;j++) {
                favit.add2MyNetworkIndex(names[j], id);
            }
            
            favit.add2MyNetworkIndex(c.nick, id);
        }
		
		favitCache.set('my_network_index', favit.myNetworkIndex);
		
		return favit.myNetworkIndex;
	},
	rebuildMyNetworkIndex: function(delay) { // delay in MS
		if (typeof delay !== typeof 1) {
			delay = 0;
		}
		
		// invalidate current my_network cache and rebuild it (FIXME: this is walkaround)
    	setTimeout(function() {
    		favitCache.remove('get_my_network');
    		favitCache.remove('my_network_index');
    		
    		$.get('/a/get_my_network', function(data) {
    			favitCache.set('get_my_network', data);
    			favit.myNetworkIndex = {};
        		favit.buildMyNetworkIndex(data);
    		}, 'json');
    	}, delay);
	},
	add2MyNetworkIndex: function(token, id) {
        var startAt = token.charAt(0).toLowerCase();
        
        if (favit.myNetworkIndex.hasOwnProperty(startAt)) {
            if (favit.myNetworkIndex[startAt][token]) {
            	favit.myNetworkIndex[startAt][token].push(id);
            } else {
                var el = favit.myNetworkIndex[startAt];
                el[token] = [id];
                favit.myNetworkIndex[startAt] = el;
            }
        } else {
            var el = {};
            el[token] = [id];
            favit.myNetworkIndex[startAt] = el;
        }
    },		
	
	keynavigation: function()
	{
		/**
		 * Start binding keys to special functions
		 */
		var doc = $(document).hotKeys({
			'j': fe.clickHandlers.post_next, // 'j' => item down in left pane
			'k': fe.clickHandlers.post_prev, // 'k' => item up in left pane
			'n': function() {}, // 'n' => scroll one page down
		    'p': function() {}, // 'p' => scroll one page up
		    'u': function() {}, // 'u' => toggle left menu
		    'i': function() {}, // 'i' => toggle image viewer
		    '/': function() {
		    	$('input.search_field').focus();
		    }, // '/' => moves cursor to the search box
		    '?': function() {
		    	$.evalHotKey('h');
		    }, // '?' => display the help menu
		    'h': function() {
		    	fPopup.show({view:'help',params:{}});
		    }, // '?' => display the help menu
		    's': function() {
		    	var like = $('a.l_pLike');
		    	
		    	if (like.length > 0) {
		    		fe.clickHandlers.pLike(like, like.attr('params'));
		    	}
		    }, // 's' => like button
		    'v': function() {
		    	var original = $('div.post_content h1 a');
		    	
		    	if (original.length > 0 && original.attr('href').length > 0) {
		    		window.open(original.attr('href'));
		            return false;
		    	}
		    }, // 'v' => opens the original source in new window
		    'r': function() {}, // reload 
		    'c': function() {
		    	fe.clickHandlers.newStream;
		    }, // 'c' => show new stream creation form
		    'shift+s': function() {
		    	var share = $('a.l_pShare');
		    	
		    	if (share.length > 0) {
		    		fe.clickHandlers.pShare(share, share.attr('params'));
		    	}
		    }, // 'shift+s' => quick share
		    'shift+d': function() {
		    	var reshare = $('a.l_pReshare');
		    	
		    	if (reshare.length > 0) {
		    		fe.clickHandlers.pReshare(reshare, reshare.attr('params'));
		    	}
		    }, // 'shift+d' => reshare
		    'shift+r': function() {
		    	var readlater = $('a.pRead_later');
		    	
		    	if (readlater.length > 0) {
		    		fe.clickHandlers.pRead_later(readlater, readlater.attr('params'));
		    	}
		    }, // 'shift+r' => read later
		    'shift+c': function() {
		    	var el = $('#commet_push');
		    	if (el.length > 0) {
		    		fe.clickHandlers.comm_activate(el);
		    	}
		    }, // 'shift+c' => add
														// comment
		    'shift+n': function() {
		    	var item = $('#t_streams li.active');
		    	var stream = item.next();
		    	if (item.length == 0) {
		    		stream = $('#t_streams li:first');
		    	}
		    	
		    	if (stream.length > 0) {	
			    	genroute({
			    		left: {
			    			params: [stream.attr('rel')]
			    		}
			    	}, true);
		    	}
		    }, // 'shift+n' => select next stream
		    'shift+p': function() {
		    	var item = $('#t_streams li.active');
		    	var stream = item.prev();
		    	if (item.length == 0) {
		    		stream = $('#t_streams li:last');
		    	}
		    	
		    	if (stream.length > 0) {	
			    	genroute({
			    		left: {
			    			params: [stream.attr('rel')]
			    		}
			    	}, true);
		    	}
		    }, // 'shift+p' => select previous stream
		    'shift+a': function() {
		    	fe.clickHandlers.navSubscribe();
		    }, // 'shift+a' => open subscribe to a feed popup
		    'space': function() {
		    	$("#right_pane div.content")[0].scrollTop += 50;
		    }, // 'space' => move page down with X
		    'shift+space': function() {
		    	$("#right_pane div.content")[0].scrollTop -= 50;
		    }, // 'shift+space' => move page up with X
		    'ctrl+enter': function() {
		    	var action = $('a[action]');
		    	if (action.length > 0 && action.attr('action') != '') {
		    		fe.clickHandlers[action.attr('action').replace('l_', '')](action, action.attr('params'));
		    	}
		    }, // 'ctrl+enter' => submit any form
		    'shift+enter': function() {
		    	$.evalHotKey('ctrl+enter');
		    }, // 'shift+enter' => submit any form
		    'home': function() {  // 'home' => go to your home (my network)
		    	$.evalHotKey('f+h');
		    },
		    'f+h': function() {
		    	genroute({
					left: {
						ctrl: 'stream',
						params: ['all']
					}
		    	}, true);
		    },
		    '@': function() {
		    	
		    	$.evalHotKey('shift+c');
		    	
		    	$('textarea.comm_field').val('@');
		    	
		    	// open a dropdown list with users to reply to
		    	var comments = $("#right_pane div.content div.p_comm");
		    	
		    	for (var i = 0, l = comments.length -1; i < l; i++) { // -1 because we do not need the FIELD COMMENT BOX
		    		// console.log(comments[i]);
		    		//$(comments[i]).find('a.l_comm_activate'));
		    	}
		    },
		    'left': function() { // previous image in image view
		    	if (favit.imageViewer) {
		    		fe.clickHandlers.prev_image();
		    	} else {
		    		$.evalHotKey('k');
		    	}
		    },
		    'right': function() { // next image in image viewer
		    	if (favit.imageViewer) {
		    		fe.clickHandlers.next_image();
		    	} else {
		    		$.evalHotKey('j');
		    	}
		    }
		});
	},
	times: { // seconds in time space
		SECOND: 1, // one seconds is equal to 1 second
		MINUTE: 60, // 1 minute == 60 seconds
		HOUR: 3600, // 1 hour == 3600 seconds
		DAY: 86400, // 1 day == 86400 seconds
		WEEK: 604800, // 1 week = 604800 seconds
		MONTH: 2592000 // 1 month == 2592000 seconds (30 days)
	},
	timeupdater: function() {
		var posts = $('#left_content div.l_post');
		favit.sysTimestamp += 60;
		
		for (var i = 0, l = posts.length; i < l; i++) {
			var post = $(posts[i]);
			var result = (favit.sysTimestamp - post.data('timestamp'));
			var timer = post.find('div.time span');
			var new_time = '';
			
			// console.log('Timestamp: ', favit.sysTimestamp, 'Result :', result, '.data(timestamp) :', post.data('timestamp'));
			
			// less then a minute (1 second is almost impossible to happen)
			if (result < favit.times.MINUTE) {
				new_time = result + ' seconds';
			}			
			// minutes till 59
			if (result >= favit.times.MINUTE && result < favit.times.HOUR) {
				var minutes = Math.floor(result / favit.times.MINUTE);
				new_time = minutes + ' minute' + (minutes > 1 ? 's' : '');
			}			
			// hours
			if (result >= favit.times.HOUR && result < favit.times.DAY) {
				var hours = Math.floor(result / favit.times.HOUR);
				new_time = hours + ' hour' + (hours > 1 ? 's' : '');
			}
			
			// days
			if (result >= favit.times.DAY && result < favit.times.WEEK) {
				var days = Math.floor(result / favit.times.DAY);
				new_time = days + ' day' + (days > 1 ? 's' : '');
			}
			
			// weeks
			if (result >= favit.times.WEEK && result < favit.times.MONTH) {
				var weeks = Math.floor(result / favit.times.WEEK); 
				new_time = weeks + ' week' + (weeks > 1 ? 's' : '');
			}
			
			// months
			if (result >= favit.times.MONTH) {
				var months = Math.floor(result / 2592000);
				new_time = months + ' month' + (months > 1 ? 's' : '');
			}
			
			// update the timer
			timer.html(new_time);
		}
	}
};
function checkField(A){
	A	= $(A);
	var B = $.trim(A.val());
	if(A[0].originalValue && A[0].originalValue == B){
		B = '';
	}
	
	if(B.length == 0){
		A.focus();
	}
	return B.length > 0;
}

function followPopup(A)
{
	
	if(!Favit.user){
		return loginPopup();
	}
	
	var A = $(A).attr('rel');
	if(A){
		fPopup.show({view:'follow_popup',params:{'eid':A}});
		popup.hide();
	}
	
	return false;				
}

function unfollowPopup(B)
{
	if(Favit.user){
		var A = $(B).attr('rel');
		if(A){
			fPopup.show({view:'unfollow_popup',params:{'eid':A}});
			popup.hide();
		}	
		return false;
	}else{
		loginPopup();
	}
}

function browseSearch(A)
{
	var A = $(A);
	var B = A.val();	
	B 	= $.trim(B);
	
	var C = fc.params;;
	C.filter = B;
						
	$.get(fc.request ,C, function(D){				
		processCallback(D,'right','render','');
	},'json');
		
}

function loginPopup(A)
{
	alert('Please login');
}


function quickSubscribeFeed(C)
{

	var D = {'rr':true,'eid':C};			

	$.post('/a/follow',D,function(A){
		if(A.success){
			var B = $('#feed_done');
			var C = $('<p class="feeds"><img src="'+A.entity.avatar_url+'"> <a href="'+A.entity.feed_url+'" target="_blank">'+A.entity.display_name+'</a></p>');
			B.append(C);							
		}else{
			alert('Rss feed not available or invalid feed url');
		}
	},'json');
}

function sharePrivacy(A)
{
	//el = $(A);
	$("#sharing_options").hide();
	var autocmp = $('ul.token-input-list-facebook');
		var autocmp_els = autocmp.children('li');
		if (prepopulate != undefined && autocmp.length > 0 && autocmp_els.length == 1) {
			if ($('#_autocomplete_'+prepopulate.id).length == 0) {
				var tpl = '<li id="_autocomplete_'+prepopulate.id+'" class="token-input-token-facebook"><p>'+prepopulate.name+'</p> <span class="token-input-delete-token-facebook">x</span></li>';
				$(tpl).prependTo(autocmp);
			}
		}
		
	var tpx = favitCache.get('classContentTop');
	$('#share_content .content').css({'top':tpx});
	$('#share_autocomplete').addClass("is_abs").show();	
};


function isNumber(D)
{
   var A = "0123456789.";
   var B=true;
   var C;
   for (i = 0; i < D.length && B == true; i++) { 
      C = D.charAt(i); 
      if (A.indexOf(C) == -1) {
         B = false;
      }
   }
   return B;
   
}
function updatePostContent(A,B,X)
{	
	C = $('#'+A);
	if(B){
		
		var Y = $('#'+A+' .time strong');
		Y.html(B);
		Y.addClass("active").delay(250).removeClass("active", 200);
		$("#right_pane div.content span.comm_count").html(B);
		
	}
	if(!X){
		X = $('#right_pane').html();
	}
	C.data('post_html', X);

}
function slideComment(F,S,AB)
{	
	
	if ($('#c'+F.comment_id).length > 0){
		return;
	}
	
	var G = $('<div class="p_comm" id="c'+F.comment_id+'"><div class="avatar"><a href="'+F.user.profile_url+'"><img src="'+F.user.avatar_url+'"/></a><u/></div><div class="comment"><p><a class="c_author" href="'+F.user.profile_url+'">'+F.user.display_name+'</a>: '+F.comment+'</p><p class="comm_controls"><span class="info">'+F.time+'</span> '			
			+ ((!AB)?'<a href="" class="btn gray smaller l_comm_activate">Edit comment</a> <a href="" class="btn gray smaller l_comm_activate">Delete</a>':'<a href="" class="btn gray smaller l_comm_activate" rel="'+F.short_id+'" nick="'+F.user.nickname+'" irt="'+F.comment_id+'">Reply <em>@'+F.user.nickname+'</em></a>') 
			+ '</p></div></div>');

	var E = $('#right_pane .content');
	
	var C = $('#commet_push');
	
	if(C.length == 0){
		C = $('#comm_post_form');						
	}
	G.hide();
	
	if(C.length >0){
		C.before(G);
	}else{
		E.append(G);
	}
	G.slideDown("fast",S);

	E.animate({scrollTop:E.attr("scrollHeight") },500);	
	
}

function createCookie(name,value,days) 
{
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


var genLoading = function(A,B)
{
	
	$('#gl_2').remove();
	if(B){
		$(A).after('<img src="/static/images/loading.gif" id="gl_2" style="padding-left:3px;">');
	}
}

var unblockEntity = function(A,B)
{
	try{
		B = eval('('+B+')');
				
		genLoading(A,true);		
		$.post('/a/unblock',B,function(C){
			genLoading(A,false);
			if(C.entity_id){
				A = $('#bl'+C.entity_id);
				A.html('Block');
				A.removeClass('l_unblock');
				A.addClass('l_block');
				
			}
		},'json');
	}catch(e){
		
	}
}

var blockEntity =  function(A,B)
{
	genLoading(A,true);
	
	try{
		B = eval('('+B+')');		
	
		$.post('/a/block',B,function(C){
			genLoading(A,false);		
			if(C.entity_id){
				A = $('#bl'+C.entity_id);
				A.html('Unblock');
				A.removeClass('l_block');
				A.addClass('l_unblock');
								
			}
		},'json');
	}catch(e){}
}

var favitEvents = fe = {
		
	mouseoverHandlers :{
	
		profile : function(el,params)
		{
			popup.mouseover(el);
			
		},
		quick_share_menu : function(el)
		{				
			QSHideTools	= false;
		
			//nenko			
		},				
		new_window_tooltip: function(el, params, oel, event) {
			var val = $(el).attr('alt');
			
			if (val.length > 0) {				
				$('body').append('<span id="f_tooltip">'+val+'</span>');
				
				var tooltip = $('#f_tooltip');
				tooltip.css({
					'top': event.pageY + 'px',
					'left': event.pageX + 15 + 'px'
				}).stop(true, true).animate({opacity: "show", top: event.pageY - 20}, "slow");
			}
		},
		stats_single_count: function(el, params) {
			params = eval('('+params+')');
			el = $(el);
			
			$('#'+params.view+'_single_count').html(el.attr('rel'));
		}
	},	
	mouseoutHandlers :{
		profile : function(el,params)
		{
			popup.mouseout();
		}
		,
		quick_share_menu : function(el)
		{	
			var B = $("*:focus").attr("id");
			if(!B){
				QSHideTools	= true;
			}
			//nenko			
		},				
		new_window_tooltip: function(el, params, oel, event) {
			var tooltip = $('#f_tooltip');
			
			if (tooltip.length) {
				tooltip.animate({opacity: "hide", top: event.pageY - 20}, "fast", function() {
					tooltip.remove()
				});
			}
		},
		stats_single_count: function(el, params) {
			params = eval('('+params+')');
			el = $(el);
			
			$('#'+params.view+'_single_count').html('');
		}
	},
	clickHandlers: {			
		
		 block : blockEntity
		,unblock : unblockEntity
		,share: function(el, params) {			
			/**
			 * collect all data and send it to the server
			 */
			
			var A = $('#status_message');
			var message = A.val();
			if(A.length && A[0].originalValue){		
				if(message == A[0].originalValue){
					message	= '';
					A.focus();
					return;
				}
			}				
			var B = $('#url');
			var url = B.val();
			
			if(B.length && B[0].originalValue){				
				
				if(!B[0].hasPreview){ // detect if video
					fe.clickHandlers.preview_link(this);
					return;
				}
				if(url == B[0].originalValue){
					url	= '';
					B.focus();
					return;
				}
			}			
			var C = $('#share_comment');
			var comment = C.val();
			
			if(C.length && C[0].originalValue){				
				if(comment == C[0].originalValue){
					comment	= '';
				}
			}			
			var E = $('#title');
			var title = E.val() || E.html();			
			if(E.length && E[0].originalValue){				
				if(title == E[0].originalValue){
					title	= '';
					E.focus();
					return;
				}
			}						
			var content = $('#content').val() || $('#content').html();									
			var medias = [];
			$('div#medias img').each(function(i, el) {
				medias[i] = el.src;
			});					
			var sharewith = [];
			var streams	= [];
			$('ul.token-input-list-facebook li.token-input-token-facebook').each(function(i, el) {
				var A = $(el).attr('rel');
				if(A){
					if(A != 0){
						sharewith[i] = el.id.replace('_autocomplete_', '');
					}else{
						streams[i] = el.id.replace('_autocomplete_', '');
					}
				}else{
					sharewith[i] = el.id.replace('_autocomplete_', '');
				}
			});			
			var A = [];			
			$('input[name=es[]]').each(
					function(C){
						var B = $(this);
						if(B.attr('checked')){
							A.push(B.attr('value'));
						}
					}
			);					
			var B = $('#tiny_mce_editor').val();
			var params	= {
				'url':url,
				'comment':comment,
				'content':content,
				'title':title,
				'message':message,
				'medias':medias,				
				'sharewith':sharewith,
				'streams': streams,
				'es':A,				
				'article':B				
			};			
			$.post('/a/share',params,function(X){
				if(!X){
					return;
				}
				if(X.subheader){
					$('#lsubheader').html(X.subheader);
				}			
				realtimeAddPost(X.posts,true);				
			},'json');
		},		
		share_cancel: function(el, params) {

			$('#exs_facebook').attr('checked', false);
			$('#exs_twitter').attr('checked', false);			
			genroute({
				right: {
					params: [favit.getsegment('params', 'right')[0], new Date().getTime()]
				}
			}, true);
		},
		quickupdate : function(A)
		{			
			var B = $('#quicksupdate');
			var G = B.val();
			G = $.trim(G);
			if(QSTimeout){
				clearTimeout(QSTimeout);
			}
			if(B[0].originalValue && B[0].originalValue == G){
				G = '';
			}
			if(G.length == 0){
				$('#quicksupdate').focus();
				return false;
			}			
			var C = {'message':G};
			var F = [];
			$('input[name=es[]]').each(
				function(G){
					var B = $(this);
					if(B.attr('checked')){
						F.push(B.attr('value'));
					}
				}
			);		
			C['es[]'] = F;
			var E = $('#quick_l');
			E.show();
			$.post('/a/share',C,function(D){				
				E.hide();
				$('#quickshare_menu').slideUp(75);
				if(B[0].originalValue){
					B.val(B[0].originalValue);
				}else{
					B.val('');
				}
				realtimeAddPost(D.posts);
			},'json');			
			return false;
		},		
		show_share: function(el, params) {
	
			el = $(el);
	
			el.parent().children().removeClass('active');
			el.addClass('active');
			$("#sharing_options").remove();
			if($("#tiny_mce_editor_external").length != 0){$("#tiny_mce_editor_external").remove();}
			
			var params = $.evalJSON(params);
			
			var precache = $('#sub_header_menu').length == 0 ? 'cache' : '';
			
			var url = 'right=render/'+params.page +'/'+ precache;
			
			genroute({
				right: {
					ctrl: 'render',
					params: [params.page, precache]
				}
			}, true);
			
			// window.location.hash = url;
			
		},
		comm_replay: function(A,B){
			
			var C = $('.l_add_comment');
			C.triggerHandler('click');
			
			if(B){
				//B = eval('('+B+')');
			}					
			
			return false;
			
		},
		comm : function (A,B,C)
		{
			return true;
		},
		
		post_prev: function(el) {
			var selected = $('#left_content div.active');
			var item = (selected.length > 0) ? selected.prev() : $('#left_content div:eq(0)');
			
			if (item.hasClass('show_more')) {
				item = item.prev();
			}
			
			if (item.length && item.hasClass('l_post')) {
				$('#left_content')[0].scrollTo('#'+item.attr('id'));
				favitEvents.clickHandlers.post(item);
			}
		},
		post_next: function(el) {
			var selected = $('#left_content div.active');
			var item = (selected.length > 0) ? selected.next() : $('#left_content div:eq(0)');
			
			if (item.hasClass('show_more')) {
				item = item.next();
			}
			
			if (item.length && item.hasClass('l_post')) {
				$('#left_content')[0].scrollTo('#'+item.attr('id'));
				favitEvents.clickHandlers.post(item);
			}
		},
		
		my_network: function(el) {
			// $('#nav li').removeClass('active');
			$(el).parent().addClass('active');
			window.location.href = el.href;
		},
		select_stream: function(el) {
			$('#nav li').removeClass('active');
			$(el).parent().addClass('active');
			window.location.href = el.href;
		},
		
		show_image_viewer: function(el, p) {
			favit.imageViewer = true;
			try{
				p = eval("("+p+")");
				shortId = favit.route.right.params[0];
				fPopup.show({view:'image_viewer',params:p});
				favit.preselectedImage = $(el).index() - 1;
			}catch(e){};
		},
		close_image_view: function() {
			favit.imageViewer = false;
			favitCache.set('last_image_index', 0);
			fPopup.close();
		},
		prev_image: function() {
			var prev = $('#thumbs a.active').prev();
			
			if (prev.length == 0) {
				prev = $('#thumbs a:last');
			}
			
			fe.clickHandlers.current_image(prev);
		},
		next_image: function() {
			var next = $('#thumbs a.active').next();
			
			if (next.length == 0) {
				next = $('#thumbs a:first');
			}
			
			fe.clickHandlers.current_image(next);
		},
		current_image: function(el) {
			el = $(el);
			
			var img = null;
			var index = favitCache.get('last_image_index') || 0;
			favitCache.set('last_image_index', el.index());
			
			var offset = (index - el.index()) * 80;
			
			$('#thumbs a').removeClass('active');
			el.addClass('active');
			
			if (el[0].tagName != 'IMG') {
				img = $(el).find('img');
			} else {
				img = $(el[0]);
			}
			
			$('#thumbs').animate({
				'left': '+=' + offset + 'px'
			}, 500);
			
			$('#current_image_source').attr('href', el.attr('href')).html(el.attr('href'));
			$('#current_image').attr('src', img.attr('src'));
		},
		
		checkbox_toggle: function(A) {			
			var B = $(A).parent().children('input[type=checkbox]');
			B.attr('checked',!B.attr('checked'));
		},
		
		
		preview_video: function(el) {
			
			var A	= $('#url');
			var B 	= $.trim(A.val());
			
			if(A[0].originalValue && A[0].originalValue == B){
				B = '';				
			}			
			if(B.length == 0){
				A.focus();return;
			}
			
						
			
			$('span.share_loading').show();
			
			$.get('/a/preview_video', {'url':B}, function(X) {
				
				$('span.share_loading').hide();
				if(X.error){
					alert('Invalid video url');
					return;
				}
				if(X.unsupported){
					alert('Sorry invalid video URL or  video provider is not supported');
					return;
				}
				A[0].hasPreview = true; // publish validator check
				
				$('#video_controls').hide();
				
				$('#title').html(X.title);
				$('#player').html(X.player);
				$("#video_preview").show();
				if(A.cssclass){
					$("#video_preview").addClass(X.cssclass);
				}
				$("#comment").slideToggle('fast');
				
			}, 'json');
		},
		
		preview_link: function(el) {
			
			var A = $('#url');
			var B = $.trim(A.val());
			
			if(A[0].originalValue && A[0].originalValue == B){
				B = '';
			}			
			if(B.length == 0){
				A.focus();return false;
			}
			$('#lpreviewl').show();
			$.get('/a/preview_link', {'url':B}, function(C) {
				$('#lpreviewl').hide();
				if(!C.error){
					A[0].hasPreview = true; // publish validator check
					$('#title').html(C.title);
					$('#content').html(C.description);
					$('#sources').html(C.medias).parent().show();
					$("#link_preview").show();				
					$("#comment").slideToggle('fast');
				}else{
					alert("You have entered an invalid or unaccessable url");
				}
			}, 'json');
			return false;
		},
		link_attach_media: function(el) {
			var tpl = '<a href="" class="l_detach_media att_item"><img src="{source}" class="l_detach_media" /><strong>{title}</strong></a>';
			var img = tpl.replace('{source}', el.src).replace('{title}', el.src.substring(el.src.length - 15, 10));
			
			$('#medias').append(img);
			$(el).remove();
			
			if ($('#sources img').length == 0) {
				$('#sources').parent().hide();
			}
		},
		link_detach_media: function(el) {
			
			if (el.tagName == 'IMG') {
				var img = $(el).clone();
			} else {
				return false;
			}
			
			img.removeClass('l_detach_media').addClass('l_attach_media');
			
			if ($('#sources').parent().is(':hidden')) {
				$('#sources').parent().show();
			}
			
			$('#sources').append(img);
			
			$(el).parent().remove();
		},
		
		stats_moreinfo: function(el, params) {
			params = eval('('+params+')');
			el = $(el);
			
			if (el.hasClass('active')) { // if expanded
				$('#'+params.view+'_stat_details').hide();
			} else { // if collapsed
				$('#'+params.view+'_stat_details').show();
			}
			
			el.toggleClass('active');
		},
		stats_show_more: function(el, params) {
			params = eval('('+params+')');
			el = $(el);
			i = parseInt(el.attr('rel'), 10);
			
			$.get('/render/stats_show_more', {'ids': params.ids, 'i':i}, function(response) {
				
				$('#'+params.view+'_avatars').append(response.html);
				el.attr('rel', i+1);
			}, 'json');
		},

		photo_add: function(el) {
			
			var A = $('#photo_url');
			var B = $.trim(A.val());
			
			if(A[0].originalValue && A[0].originalValue == B){
				B = '';				
			}			
			if(B.length == 0){
				A.focus();return false;
			}
			var img = $('#medias img[src='+B+']');
			if (img.length > 0) {
            	var parent = img.parent();
            	
   				img.effect('bounce', { times:2 }, 320);
   				parent.effect("highlight", {color: '#FFEFB0'}, 500); //animate({'background-color': '#FFEFB0'}, 500).animate({'background-color': oldBackgroundColor}, 500);
   				
				return;
			}
			
			$('#lpreviewl').show();
			
			$.get('/a/preview_link', {'url':B, 'sep':true}, function(C) {
				$('#lpreviewl').hide();
				if(!C.error){					
					A[0].hasPreview = true; // publish validator check
					
					if (typeof C.medias === typeof {}) {
						for(var src in C.medias) {
							var img = $('#medias img[src='+src+']');
							if (img.length == 0) {
								$('#medias').append(C.medias[src]);
							}
						};
					} else {
						$('#medias').append(C.medias);
					}
				}else{
					alert("You have entered an invalid or unaccessable url");
				}
			}, 'json');
			//var C = '<a href="" class="l_remove_media att_item"><img src="{source}" class="l_remove_media" /><strong>{title}</strong></a>';			
			//var D = C.replace('{source}', B).replace('{title}', B.substring(B.length - 15, 10));			
			//$('#medias').append(D);			
			$('#photo_url').val('');
		},		
		remove_media: function(A) {

			if (A.tagName == 'IMG') {
				A = $(A).parent();
			}
			
			$(A).hide("explode", 500, function() { $(A).remove(); });
		},
		
		
		/** privacy * */
		share_privacy: function(A) {
			sharePrivacy(A);	
		},
		collapse: function(el){ 
			$("#left_pane .sub_header, #quick_counter").toggleClass("closed");
			if ($("#nav").hasClass('collapsed')){
				$("#flipper").unbind().remove();
				$("#left_pane").unbind();
				$("#nav").animate({left: "0px"},75, function(){$(this).removeClass('collapsed');});
				if($("#w_container").width() <= '1280' ){
					$("#left_pane").animate({left: '200px'}, 75);
				}else{
					$("#left_pane").animate({left: '250px'}, 75);
				}
			}else{
				$("#nav").animate({left: "-250px"},75, function(){$(this).addClass('collapsed');});
				$("#left_pane").animate({left: '0'}, 0, function(){
					$("#notify").append("<div id='flipper' class='l_collapse'></div>"); 
					$("#flipper").bind('mouseover',function(){
						$('#nav').css('left','0');
					});
						$("#left_pane").bind('mouseover',function(){
							$('#nav').css('left','-250px');
							$("#flipper").css("left", "0");
						});
					});				
			}
		},
		urlPreview  : function()
		{
			var B = $('#subscribe input');
			var A = B.val();
			
			var Z = $.trim(A);
			if(Z.length == 0){
				B.focus();
				return;
			}
			var C = function(){
				
				window.location.has = '/feed/'+A+'/'+Z;
								
			}
			$("#subscribe").slideUp(75,C);
			
			
		},
		subscribeKeyEscape : function(A){
			if(A && A.keyCode == 27){				
				fe.clickHandlers.navSubscribeCancel();				
			}
		},
		subscribeKeyEnter : function(A){
			if(A && A.keyCode == 13){				
				fe.clickHandlers.urlPreview();				
			}
		},		
		navSubscribe: function(){
			var A = $('#subscribe input');
			A.val('');		
			$("#subscribe").slideToggle(75,function(){A.focus();A.keyup(fe.clickHandlers.subscribeKeyEnter);$(window).bind('keyup',fe.clickHandlers.subscribeKeyEscape);});
		},
		navSubscribeCancel: function(){
			$("#subscribe").slideUp(75);
			$(window).unbind('keyup',fe.clickHandlers.subscribeKey)
		},
		newStream: function(){
			genroute({
				left: {
					ctrl: 'render:stream_editor',
					params: []
				},
				right: {
					skip: true
				}
			}, true);
		},
		
		editStream: function(sid){
			genroute({
				left: {
					ctrl: 'render:stream_editor',
					params: [sid]
				},
				right: {
					skip: true
				}
			}, true);
			
		},
		stream_follow : function(A)		
		{
			
			if(!Favit.user){
				return loginPopup();
			}
			var B = $(A).attr('rel');
			
			var C = {'sid':B};
			$.post('/a/follow_stream',C,function(D){				
				if(D.success){
					var B = $(A);					
					$(A).html('<span class="remove"></span>Unsubscribe');
					
					B.removeClass('l_stream_follow').addClass('l_stream_unfollow').addClass('gray');
					
					var C = B.parent().find('.s_round');
					
					C.html(D.count_followers);					
					var E = $('#t_streams');
					var F = '<li rel="'+D.title+'" id="'+D.stream_id+'"><u></u><a rel="tab_title" class="l_select_stream tab ui-state-default" href="#/stream/'+D.title+'"><span class="f"></span>'+D.title+'</a></li>'
					E.prepend(F);						
				}else{
					alert("Error occured. Favit team is notified")
				}
			},'json');
			return false;
		},
		
		stream_unfollow : function(A)		
		{			
			var B = $(A).attr('rel');
			var C = {'sid':B};
			
			$.post('/a/unfollow_stream',C,function(D){				
				if(D.success){
					var B = $(A);						
					B.html('<span class="add"></span> Subscribe');
					B.removeClass('gray');
					B.removeClass('l_stream_unfollow').addClass('l_stream_follow').addClass('imp');
					$('#t_streams li[rel='+D.title+']').remove();				
				}else{
					alert("Error occured. Favit team is notified")
				}
			},'json');
			return false;
		},
		
		stream_preview :  function(A,B,C)
		{
			return true;
		},
		new_stream_cancel: function(el) {
			genroute({
				left: favit.prevroute.left,
				right: favit.prevroute.right
			}, true);
		},
		new_stream_submit: function(el) {
			
			var A	  = $('#new_stream_name');			
			var title = A.val();
			if(title.length  == 0 || A[0].originalValue == title || A.css('color') == 'red'){			
				A.focus();
				return;
			}
			
			var add_filters = $('#add_filtering').is(':checked');
			var filters = [];
			if (add_filters) {
				
				$('input.l_new_stream_filter').each(function(i, el) {
					if(el.value.length >0 && el.value != el.originalValue){
						filters[i] = el.value;
					}
				});
			}
			if(add_filters && filters.length==0){
				// $('#add_filtering').attr('checked',true);
				$('.l_new_stream_filter').focus();
				return;				
			}
			
			
			var filter_area = $('#filter_area').val();
			
			var network = favitCache.get('get_my_network');
			var selected = [];
			var i = 0;
			for (var x in network) {
				if (network[x].selected) {
					selected[i] = x;
					i++;
				}
			}			
			if(selected.length == 0 && (!add_filters || (add_filters && filter_area == 6))){
				//alert('Please select at least one user or feed from your network');
				//return;
			}
			
			var share_stream = $('#make_public').is(':checked') ? 1 : 0;
			var B			= $('#new_stream_nickname');
			var nickname =  $.trim(B.val());
			
			if (share_stream) {
				
				if(nickname.length == 0 || B.css('color') == 'red'){
					$('#new_stream_nickname').focus();
					return;
				}
				var stream_desc = $('#stream_desc').val();				
				var categories = [];
				var stream_categories = $('#new_stream_category').children('option[disabled]').each(function(i, el) {
					categories[i] = el.value;
				});				
				var stream_access = $('input[name="stream_access"]:checked').val() || 'moderated';
			}
			
			var stream_order = $('input[name="stream_order"]:checked').val() || '';
			
			// share on twitter and facebook
			var share_twitter = $('#ext_acc_twitter2').is(':checked');
			var share_facebook = $('#ext_acc_facebook2').is(':checked');
			
			
			
			var B	= {
				'title': title,							
				'entities': selected ,
				'is_filtered': add_filters,
				'filters': filters || [],
				'filter_area': filter_area,
				'is_shared': share_stream,
				'nickname': nickname || '',
				'descr': stream_desc || '',
				'categories': categories || [],				
				'access': stream_access || 'moderated',
				'order': stream_order,
				'notify': {twitter:share_twitter, facebook:share_facebook}
			};
			var C = $('#stream_id');
			if(C.length>0){ // edit mode
				B.stream_id = C.val();	
			}		
			$('#stream_loading').show();
			$.post('/a/stream_editor', B, function(D) {
				try{				
				if(!D.error){
					var G 	= D.edit_mode;
					if(!G){
						var E = $('#t_streams');
						var F = $('<li rel="'+D.title+'" id="'+D.stream_id+'"><u></u><a rel="tab_title" class="l_select_stream tab ui-state-default" href="/#/stream/'+D.title+'"><span class="f"></span>'+D.title+'</a></li>');
						E.prepend(F);
					}else{
						var F = $('#t_streams li[rel='+D.title+']');					
						if(D.title != D.old_title){
							var F = $('#t_streams li[rel='+D.old_title+']');
							F.html('<li rel="'+D.title+'" id="'+D.stream_id+'"><u></u><a rel="tab_title" class="l_select_stream tab ui-state-default" href="/#/stream/'+D.title+'"><span class="f"></span>'+D.title+'</a></li>')
						}						
					}
					var G = F.find('a');
					window.location.href = G.attr('href');
				}
				}catch(e){
					//d(e);
				}
				
				$('#stream_loading').hide();
			},'json');
		},
		new_stream_add_filter: function(el) {
			var new_row = $(el).parents('tr:eq(0)');
			var cloning = new_row.clone();
			cloning.find('.tag').val('');
			cloning.insertAfter(new_row);
			$(el).remove();
		},
		new_stream_remove_filter: function(el) {
			if ($(el).parents('td:eq(0)').find('span.add').length == 0) {
				$(el).parents('tr:eq(0)').remove();
			}
		},
		new_stream_remove_category: function(el) {
			var sel = $('#new_stream_category');
			sel.children('option[value="'+el.id+'"]').attr('disabled', '');
			$(el).parent().parent().remove();
			sel.show();
		},
		table_collapse: function(el, params, oel) {
			el 	= $(el);
			oel = $(oel);
			var C = el.parents('table');
			C.toggleClass('active');			
			if (oel.is(':checkbox')) {
				var A = oel;
			}else{
				var A = el.find(':checkbox');
				A.attr('checked',C.hasClass('active'))				
			}			
			var B	= A.attr('id');		
			C.find('.tch').toggleClass('hidden');
			switch(B){
				case 'add_filtering':
					if(A.attr('checked')){
						$('#new_stream_custom_entities').hide();
					}else{
						$('#new_stream_custom_entities').show();
					}
					break;
			}			
			return true;
		},
		toggle_custom_entity: function(el) {
			var data = favitCache.get('get_my_network'); 
			if (data[el.id].selected == true) {
				data[el.id].selected = false;
				favitUI.streamAutocompleteSelectedCounter--;
			} else {
				data[el.id].selected = true;
				favitUI.streamAutocompleteSelectedCounter++;
			}
			
			$(el).toggleClass('active');
			$('#network_selected').html(favitUI.streamAutocompleteSelectedCounter);
		},
		custom_entities_switcher: function(el) {
			var value = $('#custom_entities_filter').val();
			el = $(el);
			el.parent().children().removeClass('active');
			el.addClass('active');
			favitUI.streamAutocomplete({switcher:el.attr('id'), filter:value});
		},
		stream_filter : function(el)
		{
			var B = $(el);
			var A = B.attr('rel');
			
			B.parent().children('a').removeClass('active');
			B.addClass('active');			
			
			genroute({
				left: {
					filter: A
				}
			}, true);
			
			// window.location.hash = H;
			
		},
		browse_show_more : function(el)
		{			
			var B = $(el);
			var A = B.attr('rel');
			B.hide();
			var C = fc.params;;
			C.start = A;
			var img = B.next();
			img.show();							
			$.get(fc.request ,C, function(D){				
				processCallback(D,'right','render','');
			},'json');
			
			return false;
		},
		stream_show_more : function(el)
		{
			var B = $(el);
			var A = B.attr('rel');
			B.addClass("active");
			favit.sparams = {'start':A};		
			$(window).trigger('hashchange');
			return false;
		},
		search_navswitch: function(){
			$("#search_nav").hide();
			$("#main_nav").show();
		},
		profile : function (el)
		{
			return true;
		},
		
		preview_profile: function(el) {
			el = jQuery(el);
			
			var parts = el.attr('href').replace('/#/', '').split('/'); // 0 => profile, 1 => username
			
			genroute({
				left: {
					ctrl: parts[0],
					params: [parts[1]]
				}
			}, true);
		},
		browse_stuffs: function(el) {
			el = jQuery(el);
			
			var url = el.attr('href').replace('/#/', '');
			
			genroute({
				right: {
					ctrl: url,
					params: []
				}
			}, true);
		},
		
		follow_popup : followPopup,
		unfollow_popup : unfollowPopup,
		unfollow : function(X)
		{
			var A = $('form[name=unfollow_form] :input');			
		    var B = {};
		    A.each(function() {
		    	var C  = $(this);
		    	var D = C.attr('type');
		    	var E = C.val();
		    	switch(D){
		    		case 'checkbox':
		    		case 'radio':			    			
		    			if(!C.is(':checked')){
		    				break; 
		    			}
		    		default:
		    			if(C[0].originalValue == E){
		    				E = '';
		    			}
		    			if(this.name.indexOf('[]') > -1 ){
		    				if(!B[this.name]){
		    					B[this.name] = new Array();
		    				}
		    				B[this.name].push(E);
		    			}else{
		    				B[this.name] = E;
		    			}
		    		break;
		    	}		    			    			   		        
		    });
		    var F = $('form[name=unfollow_form]');
		    
		    $.post(F.attr('action'),B,function(A){
		    	var X = B.eid;
		    	$('a[rel='+X+']')
		    		.addClass('l_follow_popup')
		    		.addClass('imp').removeClass('l_unfollow_popup').removeAttr('onclick');
		    	
		    	$('a[rel='+X+'] span').addClass('add').removeClass('remove')
		    	   .parent().contents()
		    	  .filter(function() {
		    		    return this.nodeType == Node.TEXT_NODE;
		    		  }).html('Follow me');
		    	
		    	
		    				
		    	fPopup.close();
		    },'json');
		    
			
		},
		follow : function(el)
		{
			var A = $('form[name=follow_form] :input');			
		    var B = {};
		    A.each(function() {
		    	var C  = $(this);
		    	var D = C.attr('type');
		    	var E = C.val();
		    	switch(D){
		    		case 'checkbox':
		    		case 'radio':			    			
		    			if(!C.is(':checked')){
		    				break; 
		    			}
		    		default:
		    			if(C[0].originalValue == E){
		    				E = '';
		    			}
		    			if(this.name.indexOf('[]') > -1 ){
		    				if(!B[this.name]){
		    					B[this.name] = new Array();
		    				}
		    				B[this.name].push(E);
		    			}else{
		    				B[this.name] = E;
		    			}
		    		break;
		    	}		    			    			   		        
		    });
		    
		    
		    if(!B['new_stream_chk'] && (!B['stream[]'] ||  B['stream[]'].length == 0)){
		    	//alert('Please select at least one stream to follow or create new one');
		    	//return false;
		    }
		    var F	= $('form[name=follow_form]');
		    $.post(F.attr('action'),B,function(A){
		    	var X = B.eid;
		    	
		    	$('a[rel='+X+']').addClass('l_unfollow_popup')
		    						.removeClass('l_follow_popup').removeAttr('onclick')
		    						.removeClass('imp').addClass('grey');
		    	
		    	$('a[rel='+X+'] span').addClass('remove').removeClass('add')
		    	  .parent()
		    	  .contents()
		    	  .filter(function() {
		    		    return this.nodeType == Node.TEXT_NODE;
		    		  }).html('Un-follow');		    	
		    	fPopup.close();
		    	
		    	favit.rebuildMyNetworkIndex(1000);
		    },'json');
			
		},
		popup_close : function (A)
		{
			fPopup.close();
		},

		show_comments: function(A) {
			$('#commet_push').show();
			$('.p_comm').show();
			$('#statistics').hide();
		},
		show_stats: function(A, B) {
			
			if ($('#statistics').length) {
				//$('#commet_push').hide();
				$('#statistics').remove();
				//return false;
			}
			
			B = eval('('+B+')');
			$.get('/render/stats', B, function(response) {
				$('#commet_push').hide();
				$('.p_comm').hide();
				$('#right_pane div.content').append(response.html);
			}, 'json');
		},
		likes_counter: function(A, B) { // INVALID!
//			B = eval('('+B+')');
//			$.get('/render/stats', B, function(response) {
//				$('#right_pane div.content').html(response.html);
//				$('#right_pane div.discover').html('Statistics');
//			}, 'json');
		},
		pLike: function (A,B){			
			if(Favit.user){
				$(A).toggleClass("active");	
				B 	= eval('('+B+')');
				var C = $(A).hasClass('active');
				B['like'] = C;
				$.post('/a/like',B,function(D){
					I = $('#'+D.short_id);
					I.data('post_html', $('#right_pane').html());
				},'json');
				
				// update likes counter (bottom right) FIX LATER FOR CONCURENT LIKES
				var likesCounter = jQuery('div.stream_ctrl a.likes span');
				if (likesCounter.length > 0) {
					var count = C ? 1 : -1;
					likesCounter.html(parseInt(likesCounter.html(), 10) + count);
				}
				
			}else{
				loginPopup();
			}
		},
		pShare: function (A,B){
			if(Favit.user){
				$(A).toggleClass("active");	
				B 	= eval('('+B+')');
				var C = $(A).hasClass('active');
				B['qickshare'] = C;
				$.post('/a/quickshare',B,function(D){				
					I = $('#'+D.short_id);
					I.data('post_html', $('#right_pane').html());				
				},'json');		
			}else{
				loginPopup();
			}
		},
		pReshare: function (el){
			//alert("Reshare");
			if(Favit.user){
				sharePrivacy(el);
			}else{
				loginPopup();
			}
		},		
		pRead_later: function (A,B){
			if(Favit.user){
				$(A).toggleClass("active");	
				B 	= eval('('+B+')');
				var C = $(A).hasClass('active');
				B['readlater'] = C;
				$.post('/a/readlater',B,function(D){
					var I = $('#'+D.short_id);
					I.data('post_html', $('#right_pane').html());
					var J = $('#nav li[rel=read_later] em');
					var K = parseInt(J.html());				
					if(C) K++; else K--;
					J.addClass("active", 100, function(){J.delay(250).removeClass("active", 100);});
					J.html(K);				
				},'json');		
			}else{
				loginPopup();
			}
		},
		pBundles: function (el){
			return false;
		},
		pGeo: function (el){
			//alert("Geo");
		},
		twitter_redirect : function(A)
		{

			var B = {};
			fPopup.show({view:'twitter_redirect',params:B});
			window.location.href = $(A).attr('href');
		}
		,welcome_bsubscribe: function(A)
		{
			var B = $('#burl');
			if(checkField(B)){				
				var C = B.val();
				quickSubscribeFeed(C);
				$('#burl').val('');
			}
		}
		,welcome_add: function(A)
		{
			var B = $(A).attr('rel');
			
			if(B){								
				quickSubscribeFeed(B);
				$(A).parent().fadeOut();
			}
		}
		,psettings : function (A)
		{			
			var R = ['display_name','nickname'];
			var V = true;
			var P = {};
			$('#frm_settings :input').each(function(I){
				var A = $(this);				
				var T = A.attr('type');
				
				if(T == 'checkbox' && !A.attr('checked')){
					return;
				}				
				var B = A.attr('name');				
				if(R.indexOf(B) != -1){
					V = V & checkField(A);
				}				
				P[B] = A.val();				
			});	
			
			if(V){
				$.post('/a/profile_settings',P,function(A){
					
				},'json');
			}
		}
		,add_service : function(A)
		{
			A	= $(A);
			
			var B = A.attr('rel');
			
			if(B){
				var C = {'sid':B,'mode':A.attr('mode')};
				fPopup.show({view:'service_editor',params:C});
			}
			
		},
		acc_service : function(A)
		{
			var R = ['service_value'];
			var P = {};
			var V = true;
			$('#frm_addservice :input').each(function(I){
				var A = $(this);																	
				var B = A.attr('name');				
				if(R.indexOf(B) != -1){
					V = V & checkField(A);
				}
				P[B] = A.val();				
			});	
			
			B = $(A).attr('rel');
			if(B){
				P[B] = true;
			}
			var S = A;
			if(V){
				$('#adsloading').show();
				$.post('/a/service_editor',P,function(A){
					
					$('#adsloading').hide();
					
					if(A.error && A.exists){
						alert('The profile you entered is already in your account');
						return;
					}
					if(A.service_id){	
						var B = $('a[rel='+A.service_id+']');
						if(A.del){
							B.attr('mode','add');
							B.html('<strong>Link account</strong>');
						}else if (!A.stream){
							B.attr('mode','edit');
							B.html('<strong>Edit/Unlink account</strong>');
						}else{
							var G = $('.added_services');
							var H = $('<div><a href="" title="Remove source" class="l_service_delete_feed" rel="'+A.feed_id+'"></a><img src="/static/images/serv_favs/'+A.icon+'" width="16" height="16" /> '+A.service_name+' </div>');
							H.hide();
							G.append(H);
							H.fadeIn();
							
						}
						fPopup.close();
					}else{
						alert('Invalid nickname or url');
						$(S).focus();
					}					
				},'json');
			}
		}
		,service_delete_feed :function(A)
		{
			A = $(A);
			var B = A.attr('rel');
			var C = A;
			if(B){
				var P = {'delete':true,'feed_id':B};
				$.post('/a/service_editor',P,function(A){
					C.parent().fadeOut();					
				},'json');
			}
			
		}
		,searchf : function(A)
		{
			
			A = $(A);
			var D = A.val() || '';
			var X = '#search_nav li';
			if(D.length == 0){
				X +=',div';
			}
			$(X).removeClass('active');
						
			var B = A.attr('rel') || 'all';
			
			//A.addClass('active').parent().addClass('active');
			
			var C = favit.route.left;
			C = C.params[0] || '';
			
			
			if(C.length){
				var H = '/search/'+C+'/'+B;
				if(D.length){
					H = H + '/' +D;
				}
				window.location.hash = H;
			
			}							
		},		
		search_opt : function(A){			
			$('#search_nav li,div').removeClass('active');
			$("#nav div.w_opt").removeClass('active');
			A = $(A);
			A.addClass("active");
			var B  = A.find('.l_searchf').val();
		},		
		comm_activate : function(A){
			if(Favit.user){
				A = $(A);				
				var S = A.attr('rel');
				var R = A.attr('irt');
				var T = A.attr('nick') || '';
				
				$('#comm_post_form').remove();
				
				
				if(S){					
					$('#commet_push').remove();					
					var P = $('#'+S);
					var K = P.data('post_id');
					var L = P.data('view_id');
					var M = P.data('vt');
					var N = P.data('t');
					var O = P.data('f');										
					var C = $("#right_pane .content");
					var B = function(){					
						C.animate({scrollTop:C.attr("scrollHeight")},0);
					};		
					var E = 'params="{\'post_id\':\''+K+'\',\'view_id\':\''+L+'\',\'vt\':\''+M+'\',\'t\':\''+N+'\',\'f\':\''+O+'\'';					
					if(R){E+= ',\'irt\':\''+R+'\'';}
					if(T){T = '@'+T+' ';};
					E+='}"';
					var D = '<div id="comm_post_form" class="p_comm" style="display:none;"><div class="avatar"><a href=""><img src="'+Favit.u_avatar+'" /></a><u></u></div><div class="comment"><textarea name="comment" class="comm_field" hotkeys="ctrl+enter shift+enter">'+T+'</textarea>';
					D 	+='<p><span class="info">';
					if(N || O){
						D 	+='Networks: ';
						if(N){D +='<label><input name="es[]" type="checkbox" value="6" checked="checked"/><img src="/static/images/services/tw.png" width="14" height="14" /></label> &nbsp;';}
						if(O){D +='<label><input name="es[]" type="checkbox" value="9" checked="checked"/><img src="/static/images/services/fb.png" width="14" height="14" /></label>';}				
					}
					D += '</span>';
					D += '<a href="" rel="'+S+'" class="btn gray small l_comm_publish" action="l_comm_publish" '+E+'><strong>Publish</strong> <em>[Ctrl+Enter]</em></a> <a href="" class="btn gray small l_comm_cancel" rel="'+S+'">Cancel</a></p></div>';					
					D = $(D);
					$('#right_pane .content').append(D);					
					D.slideDown(0, B);
					D.find('textarea').focus();
				}
			}else{
				loginPopup();
			}
		},
		comm_cancel : function(A){
			$("#comm_post_form").remove();			
			$("#commet_push").remove();
			if(Favit.user){
				var B = $(A).attr('rel'); 
				A= '<div class="p_comm lets l_comm_activate" id="commet_push" rel="'+B+'"><div class="avatar"><img src="'+Favit.u_avatar+'" /></div><div class="comment"> Click here to add a comment </div></div>';
				$('#right_pane .content').append($(A));				
			}
		},
		comm_publish : function(A,B){
			
			try{
				B = eval('('+B+')');
				A = $(A);
				if(A.hasClass('done')){
					return ;
				}
				A.addClass('done');
				
				var X = []; 
				$('#comm_post_form input[name=es[]]').each(function(I){
					var A = $(this);
					if(A.attr('checked')){
						X.push(A.val());
					}										
				});			
				var CT = $('#comm_post_form textarea');
				var C = CT.val();											
				Y = B.irt || ''; 				
				var C = {'post_id':B.post_id,'comment':C,'view_id':B.view_id,'vt':B.vt,'es[]':X,'irt':Y};				
				var H = this;

				var D = function(F){
					
					H.comm_cancel(A);
					var FA = function(){						
						updatePostContent(F.short_id,F.count_comments);
					}	
					
					slideComment(F,FA);	
				}
				$.post('/a/post_comment',C,D,'json');
				
			}catch(E){
				//d(E);
				
			}
			//d(B);
			//alert("publish now!");
		}
		,post : function(A,params,C){
			
			// if clicked on link in POST in left_pane follow the link
			if (C && C['tagName'] != undefined && C.tagName == 'A') {
				return true;
			}
			
			if(favit.vn){
				if(confirm('You are currenty playing video, do you want to open it in new window?')){
					newWindowVideo(favit.vn,favit.vid);				
				}				
			}
			favit.vn	= null;
			A = $(A);
			var B = $('#right_pane');
			
			var rp = B.children().remove();								
			B.html(A.data('post_html'));
			
			if(Favit.user){
				$("#commet_push").remove();
				var F = '<div class="p_comm lets l_comm_activate" id="commet_push" rel="'+A.data('short_id')+'"><div class="avatar"><img src="'+Favit.u_avatar+'" /></div><div class="comment"> Click here to add a comment </div></div>';
				$('#right_pane .content').append($(F));				
			}
			
			$('#left_content').children('div.active').removeClass('active');
			
			A.addClass('active');			
			
			var D = $('a.l_post_prev');
			var E = $('a.l_post_next');
			
			// toggle next/prev post arrows/buttons
			if (!A.prev().length) {
				D.css({'visibility':'hidden'});
				D.css({'visibility':'visible'});
			} else if (A.next().length) {
				if (A.next().hasClass('show_more')) {
					favitEvents.clickHandlers.stream_show_more(A.next().children()[0]);
				}
				E.css({'visibility':'visible'});
				D.css({'visibility':'visible'});
			}
			
			
			if(typeof pageTracker != 'undefined' && pageTracker){				 				 				 				 			
				 pageTracker._trackPageview("/post/"+A.data('short_id')); 
			}
			genroute({
				right: {
					ctrl: 'view',
					params: [A.data('short_id')]
				}
			}, true);
			
		}
		,reshare_done: function(A,D)
		{
			A 	= $(A);			
			try{
				D	= eval('('+D+')');							
				var B = [];
				var C = [];
				$('ul.token-input-list-facebook li.token-input-token-facebook').each(function(i, el) {
					var A = $(el).attr('rel');
					if(A){
						if(A != 0){
							B[i] = el.id.replace('_autocomplete_', '');
						}else{
							C[i] = el.id.replace('_autocomplete_', '');
						}
					}else{
						B[i] = el.id.replace('_autocomplete_', '');
					}
				});				
				D['qickshare'] = true;
				D['sharewith']= B;
				D['streams']= C;	
				var X = [];
				$('#share_autocomplete input[name=es[]]').each(function(I){
					if($(this).attr('checked')){
						X.push($(this).val());
					}
				});
				D['es[]'] = X;								
				$.post('/a/quickshare',D,function(D){	
					$('.pShare').addClass("active");
					I = $('#'+D.short_id);
					$('#sharing_options').show(); 
					$('#share_autocomplete').hide();
					I.data('post_html', $('#right_pane').html());					
				},'json');	
				
				
			}catch(e){
				
			}	
			
			
			
						
		},
		profile_settings: function(el, params) {
			genroute({
				right: {
					ctrl: 'profile',
					params: ['settings'],
					filter: null
				}
			}, true);
		},
		opml_popup : function(A)
		{
			this.navSubscribeCancel();
			fPopup.show({'view':'opml_popup'});
		},
		opml_import : function()
		{
			var A = $('#opml_frm');
			
			A.attr('action','/a/opml_import');
			A.submit();
		},
		opml_export : function()
		{
			var A = $('#opml_frm');
			A.attr('action','/a/opml_export');
			A.submit();
		
		}
		

		//end		
			
	},
	focusoutHandlers: {
		quickshare: function(A){			
		
			if(QSHideTools){
				QSTimeout = setTimeout(function(){
					if(QSHideTools){
						$('#quickshare_menu').slideUp(75);
					}
				},300);					
				$(A).css("color","#aaaaaa");
			}else{
				
				setTimeout(function(){
					fe.focusoutHandlers.quickshare(A);
				},300);
			}
		},
		txt_newstream : function(el)
		{
			if($(el).val() == ''){
				$('input[name=new_stream_chk]').attr('checked', false);
			}
		}
		/*custShare_input: function(){
			$("#share_autocomplete").removeClass("is_abs");
			alert("nasko");
		}*/
	},	
	focusinHandlers: {
		quickshare: function(el){
			QSHideTools	= false;
			setTimeout(function(){
				
				$('#quickshare_menu').slideDown(75);
				$(el).css("color","#000000");	
			},10);
			
		},
		status_update: function(el) {
			$(el).css("color","#333");
			$("#share_expl").fadeOut("fast");
		},
		link_url: function(el) {
			$(el).css("color","#333");
			$("#share_expl").fadeOut("fast");
		}
		
		,txt_newstream : function(el)
		{
			$('input[name=new_stream_chk]').attr('checked', true);
		}
	},

	keyupHandlers: {
		quickshare: function(el){
			var curr = el.value.length;
			$('#quick_counter').html(curr);
		},
		status_update: function(el, params) {
			var curr = el.value.length;
			$('#char_counter').html(curr);
		},
		new_stream_name: function(el, params) {
			var limit = parseInt($('#title_chars_left').attr('limit'), 10);
			var curr = el.value.length;						
			var A	= $(el).val();
			var originalName = $('#stream_original_name');
			
			// FIXME: $.trim() might cause issues with IE, so be prepared
			if (originalName.length > 0 && originalName.html() == $.trim(A)) {
				return false; // do not perform check if the original name is equal to current name
			}
						
			if (fe.keyupHandlers.stream_name_timeout != null) {
				clearTimeout(fe.keyupHandlers.stream_name_timeout);
			}			
			fe.keyupHandlers.stream_name_timeout = setTimeout(function() {
				
				var C = $('#stream_name_show_loading');
				C.show();				
				$.get('/a/stream_title_avail', {'name':A}, function(B) {
					if (B.availability == true) {
						$(el).css({'color':'green'});
					} else {
						$(el).css({'color':'red'});
					}					
					// REMOVE LATER
					setTimeout(function() {
						C.hide();
					}, 500);
				}, 'json');
			}, 150);
						
			if (limit < curr) {				
				el.value = el.value.substring(0, limit);				
				return false;
			}
			$('#title_chars_left').html(limit - curr);
			
		},
		browse_search : function (A,X,Y,Z)			
		{
			switch(Z.keyCode){
				case 13: // Enter
					browseSearch(A);
				break;
			}
					
			return true;
			
		},
		search_field : function(el,params,orEl,event)
		{
			A	= $(el).val();
			switch(event.keyCode){
				case 13: // Enter
					B	= isUrl(A) ? '/feed/' +A :'/search/'+A;					
					window.location.hash = B;
					$("#nav").hide();
					break;
			}
		},
		custom_entities_filter_timeout: null,
		custom_entities_filter: function(el)
		{
			//console.log('call me');
			
			if (fe.keyupHandlers.custom_entities_filter_timeout != null) {
				clearTimeout(fe.keyupHandlers.custom_entities_filter_timeout);
			}
			
			fe.keyupHandlers.custom_entities_filter_timeout = setTimeout(function() {
				favitEvents.clickHandlers.custom_entities_switcher($('#all'));
				// we call streamAutocomplete with custom_entities_switcher, do not call
				// it twice. :)
				// favitUI.streamAutocomplete({filter:el.value});
				//console.log('fire');
			}, 150);
		},
		stream_url_address_timeout: null,
		stream_url_address_cache: '',
		stream_url_address: function(el)
		{
			var nickname = el.value;
			if (nickname == '') return;
			
			// prevent multiple checking for the same token
			if (fe.keyupHandlers.stream_url_address_cache == nickname) return;
			fe.keyupHandlers.stream_url_address_cache = nickname;
			
			if (fe.keyupHandlers.stream_url_address_timeout != null) {
				clearTimeout(fe.keyupHandlers.stream_url_address_timeout);
			}
			
			fe.keyupHandlers.stream_url_address_timeout = setTimeout(function() {
				
				var loading = $('#stream_name_show_loading');
				loading.show();
				
				$.get('/a/stream_nickname_avail', {'stream_nickname':nickname}, function(response) {
					if (response.availability == true) {
						$(el).css({'color':'green'});
					} else {
						$(el).css({'color':'red'});
					}
					
					// REMOVE LATER
					setTimeout(function() {
						loading.hide();
					}, 500);
				}, 'json');
			}, 500);
		},
		signup_nickname: function (A,X,Y,Z){
			
			var B = $(A).val();
			B	= $.trim(B);
			if (B.length == 0) return;
			var C = Z.keyCode ? Z.keyCode:Z.whick;
			
					
			if (fe.keyupHandlers.SNT != null) {
				clearTimeout(fe.keyupHandlers.SNT);
			}			
			fe.keyupHandlers.SNT = setTimeout(function() {
				
				$.get('/a/nick_avail', {'nick':B}, function(D) {
					if (D.avail == true) {
						$(A).css({'color':'green'});
					} else {
						$(A).css({'color':'red'});
					}									
				}, 'json');
			}, 500);
		}
		
	},
	changeHandlers: {
		new_stream_entities: function(el) {
			if (el.value == 6) {
				if (!favitCache.is('new_stream_autocomplete')) {
					favitCache.set('new_stream_autocomplete', true);
					favitUI.streamAutocomplete();
				}
				$('#new_stream_custom_entities').show();
			} else {
				$('#new_stream_custom_entities').hide();
			}
		},
		new_stream_category: function(el, params, oel) {
			oel = $(oel);
			
			if (oel.val() == "null") return;
			
			var tpl = '<tr><td><span>{category}</span> <a id="{value}" class="btn small l_new_stream_remove_category"><strong>x</strong></a></td></tr>';
			var tbl = $('#stream_category');
			var limit = oel.children('option:disabled').length;
			
			if (limit < 3) {
				var sel = oel.children('option:selected');
				var new_cat = tpl.replace('{value}', oel.val()).replace('{category}', sel.text());
				tbl.append(new_cat);
				sel.attr('disabled', 'disabled');
				
				if (limit == 2) {
					oel.hide();
				}
			}
			
			oel.val('null');
		},
		change_feed: function(A) {
			var B = $(A).val();
			
			if (B != '') {
				genroute({
					left: {
						params: [B]
					}
				}, true);
			}
		}
	}
};


var fc = favitCallbacks = {
		
	stream: function(response) {

		 
	},
	discovery: function(response) {
	},
	profile: function(response) {
		
	},
	profile_settings : function(A)
	{
		if(A.html){	
			$('#right_pane').html(A.html);
		}
	},
	render: function(response, action) {
		
		
		if(response.discover){			
			$('#right_pane').html(response.html);
		}
		/**
		 * If new stream action response
		 */
		if (response.new_stream) {
			
			if (!favitCache.is('notify_pane_width')) {
				favitCache.set('notify_pane_width', $('#notify').width());
			}
			if (!favitCache.is('left_content')) {
				favitCache.set('left_content', $('#left_content').html());
			}				
			$("#right_pane").hide();
			$("#nav li").removeClass("active");
			$("#notify").css('width','100%');
			$('#regular_stream_caption').hide();
			$('#new_stream_caption').show();
			$('#regular_sub_header').hide();
			// $('#left_pane .stream_ctrl').hide();
			$('#new_stream_sub_header').show();
			$('#left_pane .content').jScrollPaneRemove();			
			$('#left_content').removeClass('scroll-pane').addClass('no-scroll').html(response.html);
			
			if(response.edit_mode){
				var A = $('.l_new_stream_submit');
				A.html('Update stream');
			}
			
			$('#lsubheader').html('');
		}
		
		
		if (response.share) {
			// favitCache.set(window.location.hash.replace('#', ''), response);
			if (response.header) {
				$('#right_pane').html(response.header + response.content);
			} else if (response.content && $('#share_content').length == 0 && window.location.hash.indexOf('/cache') === -1) {
				window.location.hash = window.location.hash.replace(/\/$/, '') + '/cache';
			}
			else {
				// little magic here
				var p = $('#share_content').parent();
				$('#share_content').remove();
				p.append(response.content);
			}
			
			// $('#right_pane
			// .stream_ctrl').children().removeClass('active');
			if ($('#right_pane .stream_ctrl').children('.active')) {
				$('#right_pane .stream_ctrl').children().removeClass('active');
				var _id = window.location.hash.replace(/#?.*render\/?/, '').replace('/cache', '').split('/')[0];
				$('#share_' + _id).addClass('active');
			}
			
			// this is stupid but
			var tpx = favitCache.get('classContentTop');
			$('#share_content .content').css({'top':tpx});
			$('#share_autocomplete').hide();
						
		}
		
		if(response.subheader){
			$('#lsubheader').html(response.subheader);
		}
		
		fc.request = favit.request;
		fc.params  = favit.params;		
	}
};



var favitCache = {
	cache: {},
	set: function(key, value) {
		this.cache[key] = value;
	},
	get: function(key) {
		if (this.cache[key]) {
			return this.cache[key];
		}
	},
	is: function(key) {
		return this.cache[key] || false;
	},
	remove: function(key) {
		if (this.cache[key]) {
			delete this.cache[key];
		}
	}
};


function isUrl(s) {
	var regexp = /^(?:http:\/\/)?(?:[\w-]+\.)+[a-z]{2,4}/i;	
	return regexp.test(s);
}


/**
 * EXTEND $ TO PROVIDE SOME FUNCTIONALITY WE WANT
 */
(function($) {
    /**
	 * $.secureEvalJSON(src) Evals JSON in a way that is *more* secure.
	 */
    $.evalJSON = function(src)
    {
    	if (typeof src == 'object') return src;
    	
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
        
        return eval("(" + filtered + ")");
    };
 
})($);

in_array = function(A,B) {
	for(var i = 0, l = A.length; i < l; i++) {
		if(A[i] == B) {
			return true;
		}
	}
	return false;
};


(function($) {
	  var cache = [];
	  $.preLoadImages = function() {
		cache = [];
	    var args_len = arguments.length;
	    for (var i = args_len; i--;) {
	      var cacheImage = document.createElement('img');
	      cacheImage.src = arguments[i];
	      cache.push(cacheImage);
	    }
	  }
})($);



/** ** OLD LIVE ENGINE JS CODE *** */
var realtime = {
		stopped : false,	
		isHome	: false,
		maxChannels: 40,
		entity	: '',		
		comments:[],
		posts:[],
		likes : [],			
		hash: Math.floor(Math.random()*1100000000),
		q: '',
		
		contentDiv		: $("#left_content"),
		scrollContainer	: $("#left_content"),
				
		start : function(){
				
			realtime.contentDiv		 = $("#left_content");
			realtime.scrollContainer =  $("#left_content");
			
			if(arguments.length > 0){
				realtime.entity = arguments[0];
			}
			if(arguments.length > 1){
				realtime.q = arguments[1];
			}			
			realtime.poll();			
			realtime.stopped = false;
		},
		
		stop : function()			
		{			
			if (realtime.xhr) {
				Favit.debug('stopping');
				// realtime.onreadystatechange = function () {};
		        realtime.xhr.abort();	
		        realtime.xhr = null;		        
		    }
			realtime.stopped = true;
			
		},
		poll : function(delay){			    
			
		     clearTimeout(realtime.polling);		     
		     if (!delay) {
		    	 delay = 500;
		     } 		     		     
		     realtime.polling = setTimeout(realtime.refresh, delay);		     		     		    
		},
		
		refresh : function(){
			realtime.hash = Math.floor(Math.random()*11000000);
			var pids = [];		
			
			if(realtime.entity){
				pids.push(realtime.entity);
			}
			
			var lc = 0;
			$(".list").each(function (s, item) {
				if(lc < realtime.maxChannels){
		            var pid = $(item).attr("id");
		            if (pid) {
		            	lc++;
		            	pids.push(pid);
		            }
				}
	        });							
			
			if(pids.length == 0 && realtime.q == ''){
				return;
			}
			
	        var r = "/live/pull/?c=" + pids.join(',');
	        r += '&l='+Favit.language;
	        
	        if(realtime.q && realtime.q.length > 0){
	        	r += '&q='+realtime.q;	        	
	        }
	        
	        
	        if(realtime.hash){
	        	r += '&h='+realtime.hash;
			}	        
	        if(realtime.xhr ){	        	
	        	realtime.xhr.abort();
	        	realtime.xhr = null;
	        }
            realtime.xhr = $.ajax({
                url: r,
                data: "",
                dataType: "",
                type: "GET",
                success: function (data,textS,xhr) {
                    realtime.success(data,textS,xhr)
                },
                error:realtime.error                	
                
            });	        
		},
		success: function (response,textS,xhr){
				
			if (xhr.readyState == 4) {		
	            try {
	                var A = eval("(" + response + ")")
	            } catch(e) {
	                realtime.error(realtime.xhr);
	                return;
	            }               
				if(A.posts){				
					realtimeAddPost(A.posts);					
				}						
				if(A.comments){											
					realtimeAddComment(A.comments);								
				}
				if(A.likes){
					realtimeAddLike(A.likes);
				}							
				realtime.poll();
			} else{
				realtime.error(realtime.xhr);
				// error
			}			
			
		},		
		error: function(xhr){
			
			if(xhr.readyState != 4){
				realtime.poll(10000);
			}
		},
		toggleState: function(l)		
		{	
			link 	= $(l);
			isOn	= link.hasClass("on");
			Favit.debug(isOn);
			var params = {'state':isOn};
			$.post('/a/realtime_state',params,function(){},'json')
			{
				link.html(isOn?'<em></em>PAUSE':'<em></em>PLAY');
				
				if(isOn){
					link.removeClass("on");
					realtime.stop();
					
					if(Favit.rtc){
						Favit.debug('staring realtine');
						realtime.start(Favit.rtc);
					}
				}else{
					Favit.realtime = false;
					link.addClass("on");
					
				}				
			}
			return false;
		}
		
};

function realtimeAddPost(A,S){	
	
	
	var aInfo = null;// getAnchorPost();
	
	for(B in A){
		
		var D = A[B].short_id;		
		if($('#'+D).length > 0){
			continue;
		}
		var C = $(A[B].list_html);		
		var D = A[B];
		C.data('post_html', D.content_html);						
		C.data('post_id', D.post_id);
		C.data('short_id', D.short_id);
		C.data('view_id', D.view_id);			
		C.data('vt', D.view_type);
		C.data('t',D.spread_twitter);
		C.data('f',D.spread_facebook);		
		C.data('timestamp', D.time_published);
		C.hide();
		// console.log(d);
		realtime.contentDiv.prepend(C);

		setTimeout(function(){					
			C.slideDown(75);
			if(S){
				fe.clickHandlers.post(C);
			}
		},300);
	}
}
function realtimeAddComment(A){
		
			
	var C = A.comment;		
	var D = A.post;	
	var E = D.short_id;	
		
	var G = $('#'+E);
	
	if(G.length > 0){ // post here
		
		var FN = function(){
			updatePostContent(E, C.count_comments,D.content_html);
		}		
		if(G.hasClass('active'))
		{
			slideComment(C,FN,true);
		}else{
			FN();
		}
		
	}else{			
		C = $(D.list_html);		
		C.data('post_html', D.content_html);
		C.data('post_id', D.post_id);
		C.data('short_id', D.short_id);
		C.data('view_id', D.view_id);			
		C.data('vt', D.view_type);
		C.data('t',D.spread_twitter);
		C.data('f',D.spread_facebook);
			
		C.hide();
		realtime.contentDiv.prepend(C);
		
		setTimeout(function(){					
			C.slideDown(75);			
		},300);
	}
	
		
}

function realtimeAddLike(A){
	
	
	var D = A.post;	
	var E = D.short_id;	
		
	var G = $('#'+E);
	
	if(G.length > 0){ // post here
		
		var FN = function(){
			updatePostContent(E,false,D.content_html);
		}	
		FN();				
	}else{			
		C = $(D.list_html);		
		C.data('post_html', D.content_html);
		C.data('post_id', D.post_id);
		C.data('short_id', D.short_id);
		C.data('view_id', D.view_id);			
		C.data('vt', D.view_type);
		C.data('t',D.spread_twitter);
		C.data('f',D.spread_facebook);
			
		C.hide();
		realtime.contentDiv.prepend(C);		
		setTimeout(function(){					
			C.slideDown(75);			
		},300);
	}
	
}

function scrollPos() {	
	var c = realtime.scrollContainer;	
    if (c.length > 0) {
        return {
            x: c[0].scrollLeft,
            y: c[0].scrollTop
        }
    }    
    var doc = document.documentElement;
    return {
        x: doc.scrollLeft,
        y: doc.scrollTop
    }
}

function setScroll(value){	
	realtime.scrollContainer.get(0).scrollTop = value;
}
function fixScrollPosition(aInfo) {
	
	// Favit.debug(aInfo);
    if (!aInfo) {
        return
    }
    var res = 0;
    if (aInfo.offset !== undefined) {
    	res = aInfo.entry.offsetTop - aInfo.offset;
    } else {
        if (aInfo.bottomOffset) {
        	res = aInfo.entry.offsetTop + aInfo.entry.offsetHeight - aInfo.bottomOffset;
        }
    }    
    if (res > 0) {
    	setScroll(scrollPos().y + res);
    }
}

function getAnchorPost(p) {
	
    var mainOffcet = realtime.contentDiv.get(0).offsetTop;
    var scrollPosY = scrollPos().y;    
    if (scrollPosY < mainOffcet) {
        return null;
    }
    var posts = $(".list");    
    for (var E = 0; E < posts.length; E++) {
        var post = posts.get(E);
        if (post.offsetTop + post.offsetHeight + mainOffcet >= scrollPosY) {
            if (!p || p.get(0).offsetTop < post.offsetTop) {
                return {
                    entry: post,
                    offset: post.offsetTop
                }
            } else {
                return null;
            }
        }
    }
    return null
}

function bubblePost(p) {	
	if(p.lenght == 0){
		return;
	}
    var nextPost = p.next(".list_links");
    var I;
    
    var kEntryReorderTime= 500;
    
    if (nextPost.length > 0) {
        I = nextPost.get(0).offsetTop - p.get(0).offsetTop
    } else {
        I = p.height()
    }
    var E = p.get(0).offsetLeft;
    var G = p.get(0).offsetTop;
    var B = p.get(0).offsetWidth;
    var D = $("<div/>");
    D.css({
        height: I
    });
    var C = $("<div/>");
    C.css({
        height: I
    });
    p.replaceWith(D);
    C.hide();
    var A = $("<div/>");
    A.css({
        position: "absolute",
        left: E,
        top: G,
        width: B
    });
    A.append(p);
    realtime.contentDiv.append(A);
    realtime.contentDiv.prepend(C);
    C.slideDown(kEntryReorderTime);
    D.slideUp(kEntryReorderTime, function () {
        D.remove()
    });
    A.animate({
        top: realtime.contentDiv.get(0).offsetTop
    },
    kEntryReorderTime, undefined, function () {
        C.replaceWith(p);
        A.remove()
    })
}





/**
 * http://jshotkeys.googlepages.com/test-static-01.html
 * http://rikrikrik.com/$/shortkeys/
 * http://plugins.$.com/project/hotkeys
 */



/** Auto complete box * */

$.fn.autoCompleteSearchBox = function (A) {
    this.autocomplete(A || [], {
        requireExplicit: true,
        selectFirst: true,
        matchContains: true,
        width: 231,
        delay: 50,
        permaResults: function (B) {
            if (B.match(searchScope)) {
                return [0]
            } else {
                return searchOrder
            }
        },
        highlight: function (D, C, E) {
            if (typeof(E[0]) == "number") {
                return D
            }
            var B = E[2];
            if (B == null) {
                B = "/static/images/nomugshot-small.png?v=ed40"
            }
            return '<img class="ac_picture picture small" src="' + B + '"/>' + $.Autocompleter.defaults.highlight(D, C)
        },
        formatItem: function (F, D, B, E, C) {
            if (typeof(F[0]) == "number") {
                return searchOptions[F[0]][0].replace("%(term)s", "<strong>" + htmlEscape(C) + "</strong>")
            }
            return (F[1] ? F[1] + " (" + F[0] + ")" : F[0])
        }
    }).result(function (C, E, D) {
        if (E.length == 1) {
            for (var B in searchOptions[E][1]) {
                $("#searchform").append('<input type="hidden" name="' + B + '" value="' + searchOptions[E][1][B] + '"/>')
            }
            $("#searchform").submit()
        } else {
            $("#searchbox").val("");
            document.location.href = "/" + E[0]
        }
    })
};

function windowSize() {
    var C = document.documentElement;
    var A = (window.innerWidth || self.innerWidth || (C && C.clientWidth) || document.body.clientWidth);
    var B = (window.innerHeight || self.innerHeight || (C && C.clientHeight) || document.body.clientHeight);
    return {
        width: A,
        height: B
    }
}
function getAbsPosition(A)
{
	var L,H = 0;
	
	while(A) {
		  L += A.offsetLeft;
		  H += A.offsetTop;
		  A = A.offsetParent;
	}
	return {'left':L,'top':H};

}
var popup = {
	    cache: {},
	    counter: 0,
	    id: null,
	    mouseover: function (A) {
	    	
	        var B = $(A).attr("eid");
	        
	        if (!B || B == 'null') {	        	
	            return;
	        }	        
	        if (B == popup.id) {
	            this.counter++;	            
	        } else {
	            this.hide();
	            this.timeout = setTimeout(function () {
	                popup.timeout = null;
	                popup.counter++;
	                popup.show(A)
	            }, 100)
	        }
	    },
	    mouseout: function () {
	    	//
	        var B = $("#ftpopup");
	        
	        
	        if (B.css("visibility") != "visible") {
	        	
	            this.hide();
	        } else {
	            var A = this.counter;
	            
	            setTimeout(function () {
	                if (popup.counter == A) {
	                    popup.hide(true)
	                }
	            }, 150)
	        }
	    },
	    show: function (A) {
	    		    	
	    	 var E = $(A);
	         var D = E.attr("eid");
	         
	         popup.id = D;	       
	         
	         if($("#ftpopup").length > 0){
	        	 return;
	         }
	         	         	         
	         this.timeout = setTimeout(function () {
	        	 
        	 	 var C = E.offset();
                 var F = windowSize();
                 var I = B;
                 var X = getAbsPosition(E.get(0));        	
                 var G = X.left;
                 var H = C.left - 10;                     
                 var F = windowSize();
                 
                 L = H;
                 T  = C.top + E.height();
                 
                 if (H + G > F.width - 25) {
                     L =  F.width - 300;
                 } 
                 if(T + 150 > F.height){
                	 T = F.height - 250; 
                 }                                      
    	         var B = $('<div id="ftpopup" class="l_profile" eid="' + popup.id + '" style="position:absolute;z-index:1000000;"><div class="bigTooltip">' + 'Loading...' + "</div></div>").css({
    		            left: L,
    		            top: T
    		        });        	         
    	         $("body").append(B);      
    	         
                 B.css("visibility", "visible");
                 popup.loadPopup(popup.id);	                 	             
	         }, 800);
	         
	        
	    },
	
	    hide: function (A) {
	        this.counter++;
	        this.id = null;
	        if (this.timeout) {
	            clearTimeout(this.timeout);
	            this.timeout = null
	        }
	        if (A && !$.browser.msie) {
	            $("#ftpopup").fadeOut(300, function () {
	                $("#ftpopup").remove()
	            })
	        } else {
	            $("#ftpopup").remove()
	        }
	    },
	    loadPopup: function (A) {
	        if (this.cache[A]) {
	            $("#ftpopup").html(this.cache[A]);
	            return
	        }
	        $.get("/render/profilepopup", {
	            eid: A
	        }, function (B) {
	            popup.cache[A] = B.html;
	            var C = $("#ftpopup");
	            if (C.length > 0 && popup.id == A) {
	                C.html(popup.cache[A]);
	            }
	        },'json')
	    }
	};


var fPopup = {
		
		show: function(params){			
			if(params.view == undefined){				
				return;
			}
			var self = this;
			var shadow = $('#darken');	
			
			if(shadow.length > 0){				
				self.close();
			}
			
			this.onClose = function() {};
			
			if(params.params == undefined){
				params.params = {};
			}

			// $('body').append('<div id="darken"></div>');
			
			if(params.nokeys == undefined){
				$(window).keyup(self.keyListener);
			}
			
			$("body").append($('<table id="overlay"><td></td></table>'));
			$.getJSON('/a/render/'+params.view,params.params,this.responce);
			
			
		},
		responce 	: function(json){
			
			$("body").append($('<div></div>').attr({'id':'darken' }));
			$('#overlay td:eq(0)').html(json.html);
		},
		
		keyListener : function(e){	

			if(e.keyCode == 27){				
				fPopup.close();				
			}
		},
		
		close : function(){
			
			var self = this;
			self.onClose();			
			$(window).unbind("keyup",self.keyListener);			
			$('#overlay').remove();
			$('#darken').remove();
			
			
		},
		
		onClose : function(){}
		
};
function small_screen (){
	$("#left_pane .sub_header, , #quick_counter").toggleClass("closed");
	$("#nav").animate({left: "0"},75, function(){$(this).addClass('collapsed');});
	$("#left_pane").animate({left: '0'}, 0, function(){
		$("#notify").append("<div id='flipper'></div>"); 
		$("#flipper").bind('mouseover',function(){
			$('#nav').css('left','0');});
			$("#left_pane").bind('mouseover',function(){
			$('#nav').css('left','-250px');
		});
	});
	setTimeout(function(){
		$('#nav').css('left','-250px');
	}, 2500);
}

function onYouTubePlayerReady(playerId)
{
	var A = document.getElementById(playerId);
	
	window['onYouTubePlayerStateChange'+playerId] = function(C){
		var B = $(A);		
		
		switch(C){
			case 1:
				favit.vn  = playerId;	
				favit.vid = B.attr('videoid');
				break;
			default:
				favit.vn = null;
		}			
	}	
	A.addEventListener("onStateChange", 'onYouTubePlayerStateChange'+playerId);
}

function newWindowVideo(A,Z)
{
	var B = document.getElementById(A);
	if(B.getCurrentTime){
		var X = B.getCurrentTime();
		B.stopVideo();	
		favit.vn	= null;		
		var C = (screen.width/2)-(B.width/2);
		var D = (screen.height/2)-(B.height/2);
		var X = '/render/video_player/?vid='+escape(Z)+'&w='+B.width + '&h='+B.height+'&s='+X;
		var E = window.open (X, A, 'width='+(B.width)+', height='+(B.height)+', top='+C+', left='+D+', toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no,resizeable=no');	
	}else{
		
	}
	return false;
}

var favitUI = {		
		// prevent multiple calls of resize event
		streamTabsUpdaterState: false,
		streamTabsUpdater: function(elementSelector)
		{
			if (favitUI.streamTabsUpdaterState) {
				return;
			}
			favitUI.streamTabsUpdaterState = true;		
			var stream_size = 24;		
			var selectors = elementSelector.split(',');
			var more_tabs = $('div.more_tabs');
			var nav = $('#nav');
			var nav_opts = $('#nav div.nav_options');
			var main_streams = $(selectors[0]);
			var more_streams = $(selectors[1]);
			var streams = main_streams.children('li').size();
			var stack_size = nav.outerHeight(true) - 180;
			// var stream_size =
			// parseInt(main_streams.children(':first').outerHeight(), 10);
			
			var total_size = streams*stream_size;
			var overflow = (streams*stream_size) - stack_size;
			
			if (overflow > 0) {
				var exceeded = Math.ceil(overflow / stream_size);
				
				for(var i = 0; i < exceeded; i++) {
					var last = main_streams.children(':last');
					var duplicate = last.clone();
					duplicate.prependTo(more_streams);
					last.remove();
				}
				
				if (exceeded > 0) {
					more_tabs.show();
				}
			}
			
			if (overflow <= 0) {
				var exceeded = Math.ceil(overflow / stream_size) * -1;
				
				for(var i = 0; i < exceeded; i++) {
					var first = more_streams.children(':first');
					var duplicate = first.clone();
					duplicate.appendTo(main_streams);
					first.remove();
				}
				
				if (more_streams.children('li').length == 0) {
					more_tabs.hide();
				}
			}
			
			favitUI.streamTabsUpdaterState = false;
		},
		
		streamTabs: function(options)
		{
			options = options || {};
			var elementSelector = options.elementSelector || '#t_streams, #sec_streams';
			var startPosition = endPosition = null;		
			
			// favitUI.streamTabsUpdater(elementSelector);
			
			$(window).resize(function() {
				// favitUI.streamTabsUpdater(elementSelector);
			});
			
			var sortableTabs = $(elementSelector);
			
			sortableTabs.sortable({
				connectWith: '.sorted',
				distance: 15,
				placeholder: 'ui-state-highlight',
				tolerance: 'pointer',
				revert: true,
				start: function(ev, ui) {
					var title = $(ui.item).children('a[rel=tab_title]').text();
					$('.ui-state-highlight').text(title);
					
					startPosition = ui.item.parent().children().index(ui.item);

					if (ui.item.parent().is('.tab_drop')) {
						startPosition += $('#t_streams li').length;
					}
				},
				drag: function(ev, ui) {
					// $('div.main_tabs').css('overflow','hidden');
				},
				stop: function(ev, ui) {
					// $('div.main_tabs').css('overflow','visible');
					// favitUI.streamTabsUpdater(elementSelector);
					endPosition = ui.item.parent().children().index(ui.item);
					eid = ui.item.attr('id');
					
					$.ajax({
						url:'/a/tabs/',
						data: {
							'old': startPosition,
							'new': endPosition,
							'eid': eid
						}
					});
				},
				receive: function(ev, ui) {
					$(ui.item).children('a[rel=tab_title]').addClass('tab ui-state-default');
				},
				over: function(ev, ui) {
					// $('div.main_tabs').css('overflow','hidden');
				}
			}).disableSelection();
		},
		onlineNotifier : function()
		{
			if(Favit.user){
				$.post('/a/notify');
				favitCallbacks.onlineTimeout = setTimeout('favitUI.onlineNotifier()', favit.oi);
			}
		},
		streamAutocompleteSelectedCounter: 0,
		streamAutocomplete: function(options)
		{
			// alert('initializing stream autocomplete');
			
			
			filtered = [];
			var types = [1, 2, 4, 8]; // all
			var selected = false;
			var all = false;
			
			if (options && options.switcher == 'people') { // only people (favit,// twitter, facebook)
				types = [1, 2, 4];
			}
			if (options && options.switcher == 'feeds') { // only feeds
				types = [8];
			}
			if (options && options.switcher == 'selected') {
				selected = true;
			}
			if (options && options.preselect){
				var preselected = options.preselect;
			}
			if (options && options.all) {
				all = options.all;
			}
			
			var initAutocomplete = function(network) {
				var custom = $('div.switch_content');
				
				favitUI.streamAutocompleteSelectedCounter = 0;
				
				// clean up but leave "class=clear"
				custom.children('div.l_toggle_custom_entity').remove();
				var show_more = 0;
				for (var property in network) {
					if (property == 'counter') continue; // skip the counter
					if (preselected && in_array(preselected, property)){network[property].selected=true;} else if (preselected && network[property].selected==true) {network[property].selected=false};
					if (filtered && filtered.counter != undefined && filtered.counter == 0) break;
					if (!in_array(types, network[property].type)) continue;
					if (filtered && filtered.counter > 0 && filtered[property] == undefined) continue;
					if (selected && (network[property].selected == undefined || network[property].selected == false)) continue;
					
					var user = network[property];
					
					if ($('#show_more_entities').length > 0) {
						$('#show_more_entities').remove();
					}
					
					if (!all && show_more > 1000) {
						// show more
						custom.append('<input type="button" id="show_more_entities" onclick="favitUI.streamAutocomplete({all:true});" style="width: 100%; height:30px;" value="Show more" />');
						// console.log('show more/all');
						break;
					}
					
					if (network.counter > 500 || user.avatar == null) {
						var tpl = '<div id="{id}" eid="{eid}" class="l_toggle_custom_entity l_profile '+ (user.selected ? 'active' : '') +'"><strong>{name}</strong>{nick}</div>';
					} else {
						var tpl = '<div id="{id}" eid="{eid}" class="l_toggle_custom_entity l_profile '+ (user.selected ? 'active' : '') +'"><img src="{avatar}" class="avatar"  /><strong>{name}</strong>{nick}</div>';
					}
					
					if (user.selected) favitUI.streamAutocompleteSelectedCounter++;
					
					user = tpl.replace('{id}', property).replace('{eid}', property).replace('{name}', user.name).replace('{nick}', user.nick).replace('{avatar}', user.avatar);
					custom.prepend(user);
					
					show_more++;
				}
				$('#network_selected').html(favitUI.streamAutocompleteSelectedCounter);
			};
		    
		    /** FILTER OPTIONS == QUICK FIND **/
			if (options && options.filter && options.filter != '') {
				var index = favitCache.get('my_network_index');
				//console.log('filtering');
				if (index == undefined) { // no index found
					return false;
				}
				
				var needle = options.filter;
				var startAt = needle.charAt(0);
				
		        if (index && index.hasOwnProperty(startAt)) {
		            var indecies = index[startAt];
					var results = {
						counter:0
					};
		            for (var x in indecies) {
						var rg = new RegExp(needle, "ig");
						if (rg.test(x)) {
							if (!results.hasOwnProperty(indecies[x][0])) {
								results[indecies[x][0]] = true;
								results.counter++;
							}
		                }
		            }
		        }
		        
		        filtered = results;
		       // console.log('3 with filter');
		        initAutocomplete(favitCache.get('get_my_network'));
				return;
			}
			
			if (favitCache.is('get_my_network')) {
				//console.log('1 with cache');
				initAutocomplete(favitCache.get('get_my_network'));
				return;
			}
			
			$.get('/a/get_my_network', function(data) {
				//console.log('2 no cache');
				favitCache.set('get_my_network', data);
				initAutocomplete(data);
			}, 'json');
		}
	};

/**
 * minWidthLeft: 200; minWidthRight: 200;
 */

/**
 * IE DOES NOT PROVIDE ENUMERATION FOR window.NODE
 */
if (window['Node'] == undefined) {
    window.Node = new Object();
    Node.ELEMENT_NODE = 1;
    Node.ATTRIBUTE_NODE = 2;
    Node.TEXT_NODE = 3;
    Node.CDATA_SECTION_NODE = 4;
    Node.ENTITY_REFERENCE_NODE = 5;
    Node.ENTITY_NODE = 6;
    Node.PROCESSING_INSTRUCTION_NODE = 7;
    Node.COMMENT_NODE = 8;
    Node.DOCUMENT_NODE = 9;
    Node.DOCUMENT_TYPE_NODE = 10;
    Node.DOCUMENT_FRAGMENT_NODE = 11;
    Node.NOTATION_NODE = 12;
}
