var hasTouchStartEvent = 'ontouchstart' in document.createElement( 'div' );


var $body = ga('body');
var $document = ga(document);
var _d = $document;
var $window = ga(window);
var prev_url = window.location.href;
var _winH = $window.height();
var _winW = $window.width();
var globalCont;
var g_element;
var psize;
var removeThisPanel;
var pVendor = getVendor();
var bFeature = getBwFeatures();
var crossEvent = whichTransitionEvent();
var cDialogUrl = '/template/confirmation_dialog.html';
var uploadGetFiles;
var checkedCount;
var keepScrollBar;
var sh_user_details;
var hide_feed_item;
var observe;
var jb_create_tooltip_cnt = '';
var stop_expand_post_area;
var tg_k_skip_this;
var profile_photos_wall;
var ms_container, checkFeedItemsSize;
var movementPhotosArray = [],
	fetchedUrls = [],
	update_states_arr = [],
	taggedPeopleDb = [],
	taggedPeopleSameName = [],
	jb_attach_uploads = [],
	_gifs = [],
	_maps_db = [],
	mob_popups_db = [];
	
	
	
/* From Modernizr */
function whichTransitionEvent()
{
	var t;
	var el = document.createElement('fakeelement');
	var transitions = {
		'transition': 'transitionend',
		'OTransition': 'oTransitionEnd',
		'MozTransition': 'transitionend',
		'WebkitTransition': 'webkitTransitionEnd'
	}
	for (t in transitions)
	{
		if (el.style[t] !== undefined)
		{
			return transitions[t];
		}
	}
}
 
function createCookie(name, value, days)
{
	if (!days) days = 100;
	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 base64_encode(data)
{
	//  discuss at: http://phpjs.org/functions/base64_encode/
	// original by: Tyler Akins (http://rumkin.com)
	// improved by: Bayron Guevara
	// improved by: Thunder.m
	// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// improved by: Rafa Kukawski (http://kukawski.pl)
	// bugfixed by: Pellentesque Malesuada
	//   example 1: base64_encode('Kevin van Zonneveld');
	//   returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
	//   example 2: base64_encode('a');
	//   returns 2: 'YQ=='
	var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
	var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
		ac = 0,
		enc = '',
		tmp_arr = [];
	if (!data)
	{
		return data;
	}
	do { // pack three octets into four hexets
		o1 = data.charCodeAt(i++);
		o2 = data.charCodeAt(i++);
		o3 = data.charCodeAt(i++);
		bits = o1 << 16 | o2 << 8 | o3;
		h1 = bits >> 18 & 0x3f;
		h2 = bits >> 12 & 0x3f;
		h3 = bits >> 6 & 0x3f;
		h4 = bits & 0x3f;
		// use hexets to index into b64, and append result to encoded string
		tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
	} while (i < data.length);
	enc = tmp_arr.join('');
	var r = data.length % 3;
	return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
function base64_decode(data)
{
	//  discuss at: http://phpjs.org/functions/base64_decode/
	// original by: Tyler Akins (http://rumkin.com)
	// improved by: Thunder.m
	// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	//    input by: Aman Gupta
	//    input by: Brett Zamir (http://brett-zamir.me)
	// bugfixed by: Onno Marsman
	// bugfixed by: Pellentesque Malesuada
	// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	//   example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
	//   returns 1: 'Kevin van Zonneveld'
	//   example 2: base64_decode('YQ===');
	//   returns 2: 'a'
	var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
	var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
		ac = 0,
		dec = '',
		tmp_arr = [];
	if (!data)
	{
		return data;
	}
	data += '';
	do { // unpack four hexets into three octets using index points in b64
		h1 = b64.indexOf(data.charAt(i++));
		h2 = b64.indexOf(data.charAt(i++));
		h3 = b64.indexOf(data.charAt(i++));
		h4 = b64.indexOf(data.charAt(i++));
		bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
		o1 = bits >> 16 & 0xff;
		o2 = bits >> 8 & 0xff;
		o3 = bits & 0xff;
		if (h3 == 64)
		{
			tmp_arr[ac++] = String.fromCharCode(o1);
		}
		else if (h4 == 64)
		{
			tmp_arr[ac++] = String.fromCharCode(o1, o2);
		}
		else
		{
			tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
		}
	} while (i < data.length);
	dec = tmp_arr.join('');
	return dec.replace(/\0+$/, '');
}
// get browser vendor prefix
function getVendor()
{
	var result = '';
	var div = document.createElement('div'),
		prefixes = ['Webkit', 'Moz', 'ms', 'O'];
	if ('transform' in div.style) return result;
	for (var i = 0; i < prefixes.length; i++)
	{
		if ((prefixes[i] + 'Transform') in div.style)
		{
			result = '-' + prefixes[i].toLowerCase() + '-';
			break;
		}
	}
	return result;
}

// get browser 3d support
function getBwFeatures()
{
	var result = '';
	var element = document.body || document.documentElement,
		elementStyle = element.style,
		isCSSTransitions = typeof elementStyle.transition !== 'undefined' || typeof elementStyle.WebkitTransition !== 'undefined' || typeof elementStyle.MozTransition !== 'undefined' || typeof elementStyle.OTransition !== 'undefined';
	if (isCSSTransitions === true)
	{
		var div = document.createElement('div');
		// Check if 3D transforms are supported
		if (typeof div.style.WebkitPerspective !== 'undefined' || typeof div.style.perspective !== 'undefined')
		{
			result = 'translate3d';
		}
		// Additional checks for Webkit
		if (result === 'css3D' && typeof div.styleWebkitPerspective !== 'undefined')
		{
			var style = document.createElement('style');
			style.textContent = '@media (transform-3d),(-webkit-transform-3d){#test-for-3D{left:9px;position:absolute;height:5px;margin:0;padding:0;border:0;}}';
			document.getElementsByTagName('head')[0].appendChild(style);
			div.id = 'test-for-3D';
			document.body.appendChild(div);
			if (!(div.offsetLeft === 9 && div.offsetHeight === 5))
			{
				result = null;
			}
			style.parentNode.removeChild(style);
			div.parentNode.removeChild(div);
		}
		// If CSS 3D transforms are not supported, check if 2D transforms are supported
		if (!result && (typeof div.style['-webkit-transform'] !== 'undefined' || typeof div.style.transform !== 'undefined'))
		{
			result = 'translate';
		}
	}
	else
	{
		result = 'translate';
	}
	return result;
}	

function ga(a){
	return $(a);
}

function f(a, b)
{
	return a.find(b);
}
function evstop(e)
{
	e.stopImmediatePropagation();
}

function createUrl(state, title, url)
{
	history.pushState(state, title, url)
}

function f(a, b)
{
	return a.find(b);
}

function trim(a)
{
	return $.trim(a.val());
}
function apErr(t, el, cl)
{
	return ga('<span class="new_user_reg_form_info_err ' + (typeof cl != 'undefined' ? cl : '') + '" data-textmsg="true">' + t + '</span>')
		.insertAfter(el);
}
$.fn.focusEnd = function ()
{
	$(this)
		.focus();
	var tmp = $('<span />')
		.appendTo($(this)),
		node = tmp.get(0),
		range = null,
		sel = null;
	if (document.selection)
	{
		range = document.body.createTextRange();
		range.moveToElementText(node);
		range.select();
	}
	else if (window.getSelection)
	{
		range = document.createRange();
		range.selectNode(node);
		sel = window.getSelection();
		sel.removeAllRanges();
		sel.addRange(range);
	}
	tmp.remove();
	return this;
}
$.fn.hasScrollBar = function ()
{
	return this.get(0)
		.scrollHeight > this.height();
}
function objHook(str)
{
	if (typeof str == 'undefined') return;
	else
	return validateJson(str.replace(/<!--/g, '')
		.replace(/-->/g, ''));
}

var beforeUnloadTimeout = 0 ;
function unbindRemainOnSite(namespace)
{
	

	if (namespace) ga(window)
		.off('beforeunload.' + namespace);
	else ga(window)
		.off('beforeunload');
	stop_cl = false;
	ga(window).bind('unload', function() {//alert('e')
		clearTimeout(beforeUnloadTimeout);   
	});
}

function remainOnSite(str, namespace,callback)
{
	stop_cl = str;
	ga(window)
		.on("beforeunload." + namespace, function ()
		{

		
beforeUnloadTimeout = setTimeout(function() {
if(callback) callback();
        },1000);
			
			return str;
		});
}

function auto_rsz($el)
{
	var text = $el[0];

	function resize()
	{
		text.style.height = 'auto';
		text.style.height = text.scrollHeight + 'px';
	}
	/* 0-timeout to get the already changed text */
	function delayedResize()
	{
		window.setTimeout(resize, 0);
	}
	observe(text, 'change', resize);
	observe(text, 'cut', delayedResize);
	observe(text, 'paste', delayedResize);
	observe(text, 'drop', delayedResize);
	observe(text, 'keydown', delayedResize);
	text.focus();
	text.select();
	resize();
}
if (window.attachEvent)
{
	observe = function (element, event, handler)
	{
		element.attachEvent('on' + event, handler);
	};
}
else
{
	observe = function (element, event, handler)
	{
		element.addEventListener(event, handler, false);
	};
}

function url_domain(data)
{
	var a = document.createElement('a');
	a.href = data;
	return a.hostname;
}

function insertTextAtCursor(text)
{
	var sel, range, html;
	if (window.getSelection)
	{
		sel = window.getSelection();
		if (sel.getRangeAt && sel.rangeCount)
		{
			range = sel.getRangeAt(0);
			range.deleteContents();
			range.insertNode(document.createTextNode(text));
		}
	}
	else if (document.selection && document.selection.createRange)
	{
		document.selection.createRange()
			.text = text;
	}
}
if (typeof String.prototype.startsWith != 'function')
{
	String.prototype.startsWith = function (str)
	{
		return this.indexOf(str) == 0;
	};
}
var SuggestMe = function ()
{
	"use strict";
	return {
		init: init
	};

	function init(elm, words)
	{
		if(words.length <= 2) return;
		this.$el = elm;
		this.$el.on("keypress", function (event)
		{
			if (event.keyCode === 13)
			{
				var sel = rangy.getSelection();
				if (!sel.isCollapsed)
				{
					var range = sel.getRangeAt(0);
					range.collapse(false);
					var textNode = document.createTextNode("  ");
					range.insertNode(textNode);
					sel.collapseToEnd();
					event.preventDefault();
				}
			}
		});
		this.$el.on("keyup", function (event)
		{
			var c = String.fromCharCode(event.keyCode);
			var isWordcharacter = c.match(/\w/);
			if (isWordcharacter && !event.ctrlKey)
			{
				var elm = this;
				var lastWord = getLastWord(elm);
				if (lastWord)
				{
					$.each(words, function (a)
					{
						var word = words[a];
						if (word.startsWith(lastWord))
						{
							var sel = rangy.getSelection();
							if (sel.rangeCount > 0)
							{
								var range = sel.getRangeAt(0)
									.cloneRange();
								range.collapse(false);
								var htNode = document.createElement('span');
								htNode.classList.add('opacSelection');
								var textNode = document.createTextNode(word.replace(lastWord, ""));
								htNode.appendChild(textNode);
								range.insertNode(htNode);
								range.selectNodeContents(textNode);
								rangy.getSelection()
									.setSingleRange(range);
								return false;
							}
						}
					});
				}
			}
		});
	}

	function getLastWord(elm)
	{
		var val = elm.innerText.trim();
		val = val.replace(/(\r\n|\n|\r)/gm, " ");
		var idx = val.lastIndexOf(' ');
		var lastWord = val.substring(idx + 1)
			.trim();
		return lastWord;
	}
}();


(function() {
  var hidden = "hidden";

  // Standards:
  if (hidden in document)
    document.addEventListener("visibilitychange", onchange);
  else if ((hidden = "mozHidden") in document)
    document.addEventListener("mozvisibilitychange", onchange);
  else if ((hidden = "webkitHidden") in document)
    document.addEventListener("webkitvisibilitychange", onchange);
  else if ((hidden = "msHidden") in document)
    document.addEventListener("msvisibilitychange", onchange);
  // IE 9 and lower:
  else if ("onfocusin" in document)
    document.onfocusin = document.onfocusout = onchange;
  // All others:
  else
    window.onpageshow = window.onpagehide
    = window.onfocus = window.onblur = onchange;

  function onchange (evt) {
    var v = "visible", h = "hidden",
        evtMap = {
          focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
        };

    evt = evt || window.event;
    if (evt.type in evtMap)
     ga('body').addClass(evtMap[evt.type]);
    else
      ga('body').addClass(this[hidden] ? "hidden" : "visible");
  }

  // set the initial state (but only if browser supports the Page Visibility API)
  if( document[hidden] !== undefined )
    onchange({type: document[hidden] ? "blur" : "focus"});
})();
function poll_loading(pcnt,stop){
	
	if(stop){
		pcnt.find('.poll_loader_2fa').remove();
		return;
	}
	
	if(!pcnt.find('.poll-loader').length) pcnt.find(".options").before('<div class="poll_loader_2fa"><div class="loader_ic_in_pll"></div></div>');
}


function clickOnHome()
{
	ga('.mhb_logo.al_menu')
		.trigger('click');
}
function jboxTitleTip(obj, c, stc, h)
{
	obj.jBox('Tooltip',
	{
		content: stc ? jb_create_tooltip_cnt : c,
		id: !h ? 'tagged-people-n-post' : 'tagged-people-n-post-' + h,
		closeOnMouseleave: true,
		position:
		{
			x: 'center',
			y: 'top'
		},
		///outside: 'y',
		pointer: true,
		adjustPosition: true,
		reposition: true,
		onOpen: function ()
		{
			if (stc) this.setContent(jb_create_tooltip_cnt);
		}
	});
}

function FireEvent(ElementId, EventName)
{
	if (document.getElementById(ElementId) != null)
	{
		if (document.getElementById(ElementId)
			.fireEvent)
		{
			document.getElementById(ElementId)
				.fireEvent('on' + EventName);
		}
		else
		{
			var evObj = document.createEvent('Events');
			evObj.initEvent(EventName, true, false);
			document.getElementById(ElementId)
				.dispatchEvent(evObj);
		}
	}
}
function emptyFeedText(){
	
	return '<div class="wall_no_results"><span>'+lang.empty_wall+'</span></div>';
	
	
}
function filterBoxM(){
	
	
			ga(document).off('click.searchFilterBox').on('click.searchFilterBox', '.v2_gs_filter_t', function(e){
			
			e.preventDefault();
			
			var a = ga(this).parent();
			
			if(a.hasClass('__open')){
				
				a.removeClass('__open');
				
			} else {
				
				a.addClass('__open');
			}
			
			
		});
	
}
function plusNFeed(el, ev)
{
	ev.preventDefault();
	var $el = ga(el), curr_scrollTop_pos = ga(window).scrollTop();
	var fbk_loader_markup = '<div class="_4-u2 mt8 _2iwp _4-u8"><div style="height:313px;" class="_2iwo"><div class="_2iwq"><div class="_2iwr"></div><div class="_2iws"></div><div class="_2iwt"></div><div class="_2iwu"></div><div class="_2iwv"></div><div class="_2iww"></div><div class="_2iwx"></div><div class="_2iwy"></div><div class="_2iwz"></div><div class="_2iw-"></div><div class="_2iw_"></div><div class="_2ix0"></div></div></div></div>';
	var hookWall = ga('#hook_feed_wl_pg'),
		w_inp = escape(hookWall.attr('data-feed-etp')),
		f_user = ga('[data-uprofile]').length ? '&uid='+escape(ga('[data-uprofile]').attr('data-uprofile')) : ga('#wprofileid').length ? '&uid='+escape(ga('#wprofileid').val()) : '';//hookWall.attr('data-uprofile') ? '&uid='+escape(hookWall.attr('data-uprofile')) : '';
		f_group = hookWall.attr('data-groupid') ? '&filter=groups&i='+escape(hookWall.attr('data-groupid')) : '';
		
			w_inp++;
	 
 
	//alert('cmd=wall&fp=' + escape(w_inp) + f_user + '&token='+ new Date().getTime());
	$el.addClass('_noEvt')
		.html('<span class="fetching-hor"><i class="fetching-hor_i"></i></span>'); 
	var req = jAjax('/profile', 'post', 'cmd=wall&fp=' + escape(w_inp) + f_user + f_group + '&token=' + ((new Date())
		.getTime()) + '&type=pos&view_as=json');
	req.done(function (data)
	{ 

		var jData = validateJson(data);
		var fData = jData.content;
		if (!hookWall.hasClass('profileu'))
		{
			//if(typeof ms_container != 'undefined') ms_container.masonry('destroy'); else ms_container = ga('#hook_feed_wl_pg');
			var curr_feed_height = hookWall.height();
			var $nfeed_stor = ga(fData);
			$nfeed_stor.filter('.feed')
				.addClass('_nfeed__highlight');
			hookWall.append($nfeed_stor);
				//.css('height', curr_feed_height);
				
				/*
			ms_items = ms_container.find('.feed');
			ms_container.masonry(
			{
				// options
				itemSelector: ms_items,
				isAnimated: false,
				isFitWidth: true,
				gutterWidth: 8
			});
			checkFeedItemsSize(ms_container, ms_items);
			*/
			
			hookWall.attr('data-feed-etp', w_inp);
			wallPhotosCollage(hookWall, function () {});
			//hookWall.masonry('reload');
		} else {
			var $nfeed_stor = ga(fData);
			hookWall.attr('data-feed-etp', w_inp).append($nfeed_stor);
			setTimeout(function(){wallPhotosCollage(hookWall, function () {});},500);
		}
		

			if (fData !== '[END]'){
			$el.removeClass('_noEvt')
				.empty()
				.html(lang.feed_more_stories);
				
				
				
						setTimeout(function ()
						{
							// build map
							if (ga('#hook_feed_wl_pg')
								.find('.map-box')
								.length) ga('#hook_feed_wl_pg')
								.find('.map-box')
								.each(function ()
								{
									var _t_data_ka = ga(this)
										.find('.hookMapData')
										.html();
									var d_lc_map_dt = objHook(_t_data_ka);
									postPopupBuildMap(_t_data_ka, 'feed-tip-map-loc-' + d_lc_map_dt['pl-i']);
								});
						}, 1);
						

						up_href();

						// jbox title 
						jbFeedTooltip(ga('.feed_lk_oth_fr'));
						
						
						// add css class "float:left" to the feed blocks
						setTimeout(function(){
							
							//if(hookWall.hasClass('__two_columgap')) ga('.feed').addClass('__fleft');
							
						},10);

						ga('[data-jboxmouse="1"]')
							.each(function ()
							{
								jboxMouse($(this));
							});
							
				// create vegas theme (specially for *new friend)
				generateVegasTheme(1);
						
				// create collage for user profile theme
						setTimeout(function(){
							
							feedThemeCollage();
						},10);
		}
		else
		{
			// remove "load more" button 
			$el.remove();
		}
		

							ga(window).scrollTop(curr_scrollTop_pos);
	});
}
	function venobox(){
		
		
var _venoOptions = {

    bgcolor: '#5dff5e',         // default: '#fff'
    numeratio: true,            // default: false


    // is called when opening is finished
    post_open_callback  : function(content, blocknum, blocktitle){
				$('body').attr('style','overflow:hidden!important');
	},



    // is called after finished closing. 
    post_close_callback : function(content,blocknum,blocktitle){
        $('body').removeAttr('style');
    }
}

  //$('.venobox').venobox(_venoOptions); 


	}
function wallPhotosCollage(hookWall, callback)
{ 
	//if($('.feed_image_collage').length){
	/*
	      var wall = new freewall(".media-block.media-photos")j
				wall.reset({
					selector: '.wf_three',
						animate: false,
							cellW: 320,
							cellH: 320,
							fixSize: 0,
							gutterY: 20,
							gutterX: 20,
						
					onResize: function() {
						wall.fitWidth();
					}
				});

	 			wall.fitWidth();


			
					$("aw.collage.__single").each(function() {
						var wall = new freewall(this);
						wall.reset({
							selector: '.wsize3201',

							fixSize: 0,
							gutterY: 20,
							gutterX: 20,
							onResize: function() {
								wall.fitWidth();
							}
						})
						wall.fitWidth();
					});
					$(window).trigger("resize");
			*/

			

	/*
		// for one image
		$('.feed_image_collage.__1').justifiedGallery({
		lastRow:  'nojustify',
	    rowHeight:  380,
	    maxRowHeight: '100%',imagesAnimationDuration:0,
		}).on('jg.complete', function (e) {

	});	*/
	if (ga('.feed_image_collage')
		.length)
	{ 
	// for more images
	ga('.feed_image_collage:not(.__1)')
		.justifiedGallery(
		{
			lastRow: 'justify',
			rowHeight: 120,
			imagesAnimationDuration: 0,
			//maxRowHeight: 340 ,
		})
		.on('jg.complete', function (e) {});
	}
		if ( ga('.feed_videos_collage_justified').length )
	{
		
		// 2 videos
		ga('.feed_videos_collage_justified.__2')
			.justifiedGallery(
			{
				lastRow: 'justify',
				rowHeight: 100,
				margins: 3,
				maxRowHeight: 240,
				imagesAnimationDuration: 0,
			})
			.on('jg.complete', function (e) {});
			
		// 3 videos
		ga('.feed_videos_collage_justified.__3')
			.justifiedGallery(
			{
				lastRow: 'justify',
				rowHeight: 170,
				margins: 3,
				maxRowHeight: 240,
				imagesAnimationDuration: 0,
			})
			.on('jg.complete', function (e) {});
			
		// 4 videos
		ga('.feed_videos_collage_justified.__4')
			.justifiedGallery(
			{
				lastRow: 'justify',
				rowHeight: 180,
				margins: 3,
				maxRowHeight: 240,
				imagesAnimationDuration: 0,
			})
			.on('jg.complete', function (e) {});
			
		// 5 videos
		ga('.feed_videos_collage_justified.__5')
			.justifiedGallery(
			{
				lastRow: 'justify',
				rowHeight: 180,
				margins: 3,
				maxRowHeight: 240,
				imagesAnimationDuration: 0,
			})
			.on('jg.complete', function (e) {});
			
			
		// multiple videos
		ga('.feed_videos_collage_justified.__mmm')
			.justifiedGallery(
			{
				lastRow: 'justify',
				rowHeight: 80,margins: 3,
				imagesAnimationDuration: 0
			}).on('jg.complete', function (e) { });
			
	}
	
	
	
		if(ga('.feed-product-images-collage').length){
		 
		ga('.feed-product-images-collage').each(function(){
			ga(this).justifiedGallery(
			{
				rowHeight: 90,
				maxRowHeight: 230,
				margins: 6,
				border: 0,
				rel: 'marketProductPicture',
				lastRow: 'justify',
				fixedHeight: false,
				captions: true,
				randomize: true,
				/*sizeRangeSuffixes: {
					lt100 : '_t', 
					lt240 : '_m', 
					lt320 : '_n', 
					lt500 : '', 
					lt640 : '_z', 
					lt1024 : '_b'
				}*/
			})
			.on('jg.complete', function (e) {});
			
	});

	}
	
	if (ga('.feed_photos_collage_justified')
		.length)
	{
		

		
		// multiple
		ga('.feed_photos_collage_justified.__mmm')
			.justifiedGallery(
			{
				lastRow: 'justify',
				rowHeight: 120,margins:1,
				imagesAnimationDuration: 0,
			})
			.on('jg.complete', function (e) {});
		
		// 2 photos
		ga('.feed_photos_collage_justified.__2')
			.justifiedGallery(
			{
				lastRow: 'justify',
				rowHeight: 120,
				margins: 1,
				maxRowHeight: 180,
				imagesAnimationDuration: 0,
			})
			.on('jg.complete', function (e) {});
			
			// justify for 3 photos
		ga('.feed_photos_collage_justified.__3')
			.justifiedGallery(
			{
				lastRow: 'justify',
				rowHeight: 100,
				margins: 1,
				maxRowHeight: 220,
				imagesAnimationDuration: 0,
			})
			.on('jg.complete', function (e) {});
			
			
		// justify for 4 photos
		ga('.feed_photos_collage_justified.__4')
			.justifiedGallery(
			{
				lastRow: 'justify',
				rowHeight: 100,
				margins: 1,
				imagesAnimationDuration: 0,
				//maxRowHeight: 320,
			})
			.on('jg.complete', function (e) {});
		// justify for 5 photos
		ga('.feed_photos_collage_justified.__5')
			.justifiedGallery(
			{
				lastRow: 'justify',
				rowHeight: 100,
				margins: 1,
				imagesAnimationDuration: 0,
				//maxRowHeight: 320,
			})
			.on('jg.complete', function (e) {});
		// justify for 6+ photos
		/*ga('.feed_photos_collage_justified.__mmm')
			.justifiedGallery(
			{
				lastRow: 'hide',
				rowHeight: 120,
				margins: 4,
				maxRowHeight: 190,
				imagesAnimationDuration: 0,
			})
			.on('jg.complete', function (e) {});*/
	}
	if (ga('.nb-feed-post-images')
		.length)
	{
		// slider for news feed
		var slides_arr = [];
		ga('.nb-feed-post-images')
			.each(function ()
			{
				if (typeof $(this)
					.attr('id') == 'object') return;
				var $this = $(this);
				var sid = $(this)
					.attr('id');
					
				ga('#' + sid)
					.nobleSlider(
					{
						_SLIDER_BEZIER_ENGINE: 'cubic-bezier(0.39, 0.575, 0.565, 1)',
						_SLIDE_ANIMATION_DURATION: 400, // miliseconds
						_IMAGE_SCALE_MODE: 'fit-for-bigger',
						_IMAGE_TO_CENTER: true,
						_TOUCH_SWIPE_TRESHOLD: 1,
						_TOUCH_SWIPE_SPEED_RATIO: 0.6284,
						_SLIDER_WIDTH: '60%',
						_SLIDER_HEIGHT: 308,
						_ALLOW_FULL_SCREEN: false,
						//_SLIDES_ORIENTATION: 'vertical',
						_ENABLE_PAGINATION: true,
						_ENABLE_ARROWS: true,
						_VISIBLE_DIMENSION: '100%',
						_SLIDES_SPACING: 20,
						_SLIDE_LOOP: true,
						_CLBK_IMAGE_LOADED: function ()
						{
							slides_arr.push(sid);
							ga('.nobleSlider')
								.nobleSlider('update');
						}
					});
			});
	}
	//}
	callback();
	
}




	function userFeed(){
		
		
		var _u_f_spc = ga('#hook_feed_wl_pg');
	
	if(_u_f_spc.length) {
		
		
	
			if( _u_f_spc.html() == ''|| !_u_f_spc.html().length ) {
				ga('#uprofile_load_more_btn').remove();
		
	
			}
		}
	}
function feedThemeCollage(){
	var _f_kng42 = ga('._fknga1 .uprof_ntheme_photos_collage');
	if (_f_kng42.length)
	{
		
		_f_kng42
			.justifiedGallery(
			{
				lastRow: 'hide',randomize:true,
				rowHeight: 80,
				margins: 0,
				fixedHeight:true,
				imagesAnimationDuration: 600,
			})
			.on('jg.complete', function (e) {});

	}
	
}
// forgot pass
function forgotFormSend() {
	
	var f_email = ga('#forgot_input'), _error = ga('#error');
	
	if( !validateEmail(f_email.val()) ) {
		f_email.addClass('error');
		_error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.forgot_invalid_email+'</b><br/>'+lang.forgot_invalid_email_sub+'</div></div>');
		return; 
	} else {
		
		f_email.removeClass('error');
		_error.empty();
		
		ajaxLoading();
		var send = jAjax('/cmd.php', 'post', {cmd:'forgotPass', mail:f_email.val()});
		send.done(function(data){  
			removeAjaxLoad();
			if(data == '2' || data == '0'){
				
				f_email.addClass('error');
				_error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.forgot_email_not_found+'</b><br/>'+lang.forgot_invalid_email_sub+'</div></div>');
			} else if (data == '3'){
			_error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.forgot_email_not_sent+'</b><br/>'+lang.forgot_not_sent_descr+'</div></div>');
			} else {			
				
				ga('.restore_page_section').html('<b>'+lang.forgot_mail_sent.replace('%s',f_email.val())+'</b>');
				ga('.bottom_row').empty();
			}
			
		});
		
	}
	
}

function forgotSetNewPass() {
	
	var pass_field_o = ga('#pass_field_o'), pass_field_t = ga('#pass_field_t'), hash = ga('[name="hash"]'), _error = ga('#error');
	
	if(pass_field_o.val().length < 6)
	 return _error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+lang.newPasswordIsTooShort+'</div></div>');


	if(pass_field_o.val() !== pass_field_t.val()) {
		return _error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+lang.passDontMatch+'</div></div>');
		
		
	}
	ajaxLoading();
	var send = jAjax('/cmd.php', 'post', { 'cmd' : 'forgotSetNewPass', 'email' : ga('[name="email"]').val(), 'rps' : ga('[name="rps"]').val(), 'repass' : pass_field_o.val() , 'newpass' : pass_field_t.val() , 'hash' : hash.val()});
	send.done(function(data) {
		
		removeAjaxLoad();
		if(data == '2')
			return _error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+lang.newPasswordItSame+'</div></div>');
		else if ( data == '3')
		return _error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+lang.newPasswordIsTooShort+'</div></div>');
	else if (data == '4')
		return _error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+lang.passwordDidntMatch+'</div></div>');
		else{
			kn_liveNotif(lang.forgot_pass_updated_title,'done',4000,lang.forgot_pass_updated_descr);
			setTimeout(function(){ window.location='/'; },4500);
		}

	});
	
}

/* Registration Form
------------------------- */
// validate email (check for available)
function reg_validateEmail(el, ev)
{
	ev.preventDefault();
	var $el = $(el),
		$_s_Btn = $('[name="button_continue"]');
	$el.removeAttr('onfocus')
		.off('focusout.vlmail')
		.on('focusout.vlmail', function ()
		{
			var $_this = $(this);
			if ($_this.data('currem') !== $_this.val() && $.trim($_this.val()))
			{
				var check_m = jAjax('/profile', 'post', 'type=pos&cmd=registrationValidateEmail&rm=' + $_this.val());
				check_m.done(function (d)
				{
					switch (d)
					{
					case '0':
						return false;
						break;
					case '_INVALID_TYPE':
						$_this.css('border', '1px solid red')
						$_this.parent()
							.find('.reg_em_err')
							.removeClass('__none')
							.html(lang.reg_invalid_email_type);
						$_s_Btn.addClass('__disabled')
							.off('click.reg_continue')
							.on('click.reg_continue', function (e)
							{
								e.preventDefault();
								e.stopImmediatePropagation();
								return;
							});
						break;
					case '_EMAIL_EXIST':
						$_this.css('border', '1px solid red')
						$_this.parent()
							.find('.reg_em_err')
							.removeClass('__none')
							.html(lang.reg_mail_already_in_use);
						$_s_Btn.addClass('__disabled')
							.off('click.reg_continue')
							.on('click.reg_continue', function (e)
							{
								e.preventDefault();
								e.stopImmediatePropagation();
								return;
							});
						break;
					case '_SUCCESS':
						$_this.removeAttr('style');
						$_this.parent()
							.find('.reg_em_err')
							.addClass('__none')
							.empty();
						$_s_Btn.removeClass('__disabled')
							.off('click.reg_continue');
						break;
					}
				});
			}
			if ($.trim($_this.val())) $_this.attr('data-currem', $_this.val());
		});
}

function reg_form()
{
	var rform = ga('#new_user');
	var cssBorder = {
		'border': '1px solid red'
	};
	rform.submit(function (ev)
	{
		var $his = this;
		var $this = $(this);
		var fname = f($this, '#reg_first_name'),
			sname = f($this, '#reg_last_name'),
			bday = f($this, '#day'),
			bmonth = f($this, '#month'),
			byear = f($this, '#year'),
			genre = f($this, '[name="fr.gender"]'),
			location= f($this, '#reg_country'),
			phone = f($this,'#js_phone_number'),
 
			admail = f($this, '#reg_mail'),
			pass = f($this, '#reg_password');
		var req = function (el)
		{
			$his.err = true;
			el.attr('requiredf', 'true')
				.css(cssBorder)
				.focus();
		}
		$this.find('[data-textmsg]')
			.remove();
		$this.find('[requiredf]')
			.removeAttr('style')
			.removeAttr('requiredf');
		this.err = false;
		if (!trim(fname))
		{
			apErr(lang['reg_first_name_empty'], fname);
			req(fname)
		}
		if (!trim(sname))
		{
			apErr(lang['reg_sname_empty'], sname);
			req(sname)
		}
		if (!trim(bday) || !trim(bmonth) || !trim(byear))
		{
			if (!trim(bday)) req(ga('#day-button'));//req(bday);
			if (!trim(bmonth)) req(ga('#month-button'));//req(bmonth);
			if (!trim(byear)) req(ga('#year-button'));//req(byear);
			apErr(lang['reg_bday_empty'], ga('#year-button'));
		}
		if (!genre.is(':checked'))
		{
			apErr(lang['reg_genre_empty'], genre.last(), '__ml165 __mtm5');
			req(genre)
		}
		  
		if(!validatePhoneNumber(trim(phone)) || !trim(phone)){
			apErr(lang['sg_invalid_phone'], phone);
			req(phone);
		}
		if (!trim(location))
		{
			apErr(lang['reg_country_empty'], location);
			req(location)
		} else if (!ga('#location_selected_from_list').length || !ga('#location_selected_from_list').hasClass('yes')){
			
			
			apErr(lang['reg_country_empty'], location);
			req(location)
		}
 
		if (!trim(admail))
		{
			apErr(lang['reg_mail_empty'], admail);
			req(admail)
		}
		if (!trim(pass))
		{
			apErr(lang['reg_pass_empty'], pass);
			req(pass)
		}
		else if (pass.val()
			.length < 6)
		{
			apErr(lang['reg_pass_length'], pass, '__mt3');
			req(pass)
		}
		if (this.err) ev.preventDefault();
	});
}
function inputPhone(){
	
	var p_input = ga(".phone-input");
	
	if( p_input.length ){
	 p_input.each(function(){
	
	var _this = ga(this);
	var my_country_code = $.trim(_this.data('user-country')) != '' ? _this.data('user-country') : false;
    var el_pl = _this.intlTelInput({
      // allowDropdown: false,
      // autoHideDialCode: false,
      // autoPlaceholder: "off",
      // dropdownContainer: "body",
      // excludeCountries: ["us"],
      // formatOnDisplay: false,
      // geoIpLookup: function(callback) {
      //   $.get("http://ipinfo.io", function() {}, "jsonp").always(function(resp) {
      //     var countryCode = (resp && resp.country) ? resp.country : "";
      //     callback(countryCode);
      //   });
      // },
      //  hiddenInput: "js_phone_number",
       initialCountry: my_country_code ? my_country_code : 'us',
      // nationalMode: false,
      // onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
      // placeholderNumberType: "MOBILE",
       preferredCountries: my_country_code ? [my_country_code] : ['nl','ru','us','gb'],
      // separateDialCode: true,
     // utilsScript: "build/js/utils.js"
    });
	_this.on('blur',function(){  
	
	 
	
	var getDialCode = _this.intlTelInput("getSelectedCountryData"); 
     var p_number = getDialCode.dialCode+_this.val();
	 ga('#js_phone_number').val(p_number);
	  
	if(!validatePhoneNumber(p_number)){
		
		_this.css('border-color','red');
	} else _this.removeAttr('style');
	});
		
	});
	
	}
 

}
function validatePhoneNumber(str) {
  var valid = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im.test(str);
  return valid;
}
/* LOGIN FORM 
----------------*/
function login_form()
{
	var borderErr = {};
	borderErr['border'] = '1px solid red';
	var lfrm = ga('#login_form'),
		msg = lfrm.find('#anonymLoginMsg'),
		email_field = ga('input#field_email'),
		pass_field = ga('input#field_password');
		
		msg.removeClass('_show');
	lfrm.submit(function (ev)
	{ 
		var $this = ga(this);
		var removeOvr = function ()
		{
			email_field.removeAttr('style');
			pass_field.removeAttr('style');
			$this.removeAttr('style');
			ga('.login-spinner').addClass('__none');
		}
		$this.css(
		{
			'pointer-events': 'none',
			'opacity': '0.3'
		});
		ga('.login-spinner').removeClass('__none');
		$.ajax(
		{
			type: lfrm.attr('method'),
			url: lfrm.attr('action'),
			data: lfrm.serialize(),
			success: function (data)
			{ 
				var log = data.split('|*|')[0],
					mText = data.split('|*|')[1];
				switch (log)
				{
				case 'email':
					removeOvr();
					email_field.css(borderErr)
						.focus();
					msg.addClass('_show');
					msg[0].innerHTML = mText;
					break;
				case 'pass':
					removeOvr();
					pass_field.css(borderErr)
						.focus();
					msg.addClass('_show');
					msg[0].innerHTML = mText;
					break;
				case '!INVALID_ACC':
				case '!SERVER_ERROR':
				case '!PENDING_ACC':
				case '!INCORRECT_DETAILS':
					removeOvr();
					msg.addClass('_show');
					msg[0].innerHTML = mText;
					break;
				case 'location':
					window.location = mText;
					break;
				default:
					window.location = './';
				}
			}
		});
		ev.preventDefault();
	});
}


function wSpace(s)
{
	return /\s/g.test(s);
}
$.ui.autocomplete.filter = function (a, b)
	{
		var g = new RegExp($.ui.autocomplete.escapeRegex(b), "i");
		return $.grep(a, function (c)
		{
			return g.test(c.value || c)
		})
	}
	// autocomplete countries
function countryAutoComplete(el)
{
	var $el = $(el);
	var getCountriesArr = new Array();
	var ggCountries = validateJson(__glb_countries);
	for (var a = 0; a < ggCountries.length; ++a) getCountriesArr.push(
	{
		"id": ggCountries[a].id,
		"code": ggCountries[a].code,
		"value": ggCountries[a].name,
		"label": ggCountries[a].name
	});
	$el.removeAttr('onfocus')
		.off('keypress')
		.on('keypress', function ()
		{
			$("#stfr_city,#reg_city")
				.addClass('__disabled');
		})
		.autocomplete(
		{
			minLength: 0,
			html: true,
			source: getCountriesArr,
			autoFocus: true,
			focus: function (event, ui)
			{
				//$( "#stfr_country" ).attr('country-id',ui.item.id);
				update_states_arr = new Array();
				var ggStates = validateJson(__glb_states);
				for (var b = 0; b < ggStates[ui.item.id].length; ++b) update_states_arr.push(
				{
					"id": ggStates[ui.item.id][b].id,
					"label": ggStates[ui.item.id][b].name
				});
				console.log(ggStates);
				return false;
			},
			select: function (event, ui)
			{
				var customE = $.Event("keydown",
				{
					which: 8,
					keyCode: 8
				});
				ga("#stfr_country,#reg_country")
					.val(ui.item.label);
				ga("#real_country")
					.val(ui.item.id);
				ga("#stfr_city,#reg_city")
					.removeClass('__disabled')
					.val('')
					.focus()
					.trigger(customE);
				return false;
			}
		})
		.data("ui-autocomplete")
		._renderItem = (function (ul, item)
		{
			return ga("<li></li>")
				.data("item.autocomplete", item)
				.append('<span>' + item.label + '</span><span class="autocomplete_c_code">' + item.code + '</span>')
				.appendTo(ul);
		});
}
// autocomplete states
function statesAutoComplete(el)
{
	var $el = $(el);
	$el.autocomplete(
	{
		minLength: -1,
		autoFocus: true,
		source: update_states_arr,
		select: function (event, ui)
		{
			$("#real_city")
				.val(ui.item.id);
		}
	});
}


function validateJson(str, no_err)
{ console.log(str);
	try
	{
		var json = JSON.parse(str);
		return json;
	}
	catch (e)
	{
		if (!no_err) displayErr(e + '<br/>[invalid json]'); //' + lang.somethingWrong);
		return false;
	}
}
function ajaxLoading()
{
	//var markup = ga('<div class="global_ajax_loader"></div>');
	var b = ga('body');
var markup = '<div class="globalAjaxLoader">\
			<div>        \
			<div class="preloader-spin">\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
			</div></div>';
	
	if(!b.find('.globalAjaxLoader').length)
	b.prepend(markup);
}

function mob_popup_select_lang(evt){
	
	
	evt.preventDefault();
	var _a = ga(evt.target);
	var _l_markup = '';
		// open mobile popup
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.Available_languages+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();	
		ga('#m_helper').click();
		var cont = ga('.mob_popup_cnt#id_'+rand);
 
		var send = jAjax('/cmd.php', 'post', 'cmd=getSiteLanguagesList');
		send.done(function(d){  
		var _data = validateJson(d);
		
			for(var i=0; i < _data.length; ++i)
				_l_markup += '<a href="javascript:void(0);" rel="select-lang" class="mob_a_sel_lang '+ (__g_lang == _data[i].lang_a ? 'lang_selected' : '') +'" data-value="'+_data[i].lang_a+'"><i class="ic_lang_selected ic_bookmarked"></i>'+_data[i].lang_str+'</a>';
			
			cont.html('<div class="mob_popup_lang_sel">'+_l_markup+'</div>');
			
			
			
			
					ga(document).off('click.changeLanguage').on( "click.changeLanguage", '[rel="select-lang"]', function( ev ) { 
					var _this = ga(this);
					
					
					if(_this.hasClass('lang_selected')){
						
						kn_liveNotif( lang.your_currently_language_is,'warn',3000,'');
						return;
					}
					
							ajaxLoading();
							var send = jAjax('/cmd.php', 'post', { 'cmd':'updateUserLanguage', 'lang':_this.data('value') });
							send.done(function(d){
								//removeAjaxLoad();
								if(d == 1){
									if(!ga('html').hasClass('anonym_content')) {
										removeMobilePopupFromDom(rand);
										setTimeout(function(){window.location.reload();},300);
										}
											else	{ 
										setTimeout(function(){window.location=__SITEURL;},300);
									}
										
									
								}
								
								
							});
	
					});
			
			
			
			
		});
}


// change site language
function globalLangSet(evt){
	
	evt.preventDefault();
	var _a = ga(evt.target);
	var _l_markup = '';
	if (!_a.hasClass('open')){
		ajaxLoading();
		var send = jAjax('/cmd.php', 'post', 'cmd=getSiteLanguagesList');
		send.done(function(d){  
			removeAjaxLoad();
			var _data = validateJson(d);
		
			for(var i=0; i < _data.length; ++i)
				_l_markup += '<option  '+ (__g_lang == _data[i].lang_a ? 'selected' : '') +' value="'+_data[i].lang_a+'">'+_data[i].lang_str+'</option>';
				
					_a.before('<select class="lang_p_box_sel">'+_l_markup+'</select>');
					ga('.lang_p_box_sel').selectmenu();
					ga('#gl_lang_set').hide();
					
					ga(document).off('selectmenuchange.changeLanguage').on( "selectmenuchange.changeLanguage", '.lang_p_box_sel', function( ev, ui ) { 
							ajaxLoading();
							var send = jAjax('/cmd.php', 'post', { 'cmd':'updateUserLanguage', 'lang':ui.item.value });
							send.done(function(d){
								removeAjaxLoad();
								if(d == 1){
									window.location.reload();
								}
								
								
							});
	
					});
			
		});
		

		
		
	}
	
	
}
function generateVegasTheme(feed){
	 
 
	var _buildVegas = function(_conf,_images,el){   
		var ab = el ? el : ga('#u__slideshow');
    ab.vegas({
	overlay: _conf.overlay == "true" ? true : false,
	shuffle: _conf.shuffle == "true" ? true : false,
	transition:_conf.transition ? _conf.transition : 'fade',
	preloadImage: true,
	transitionDuration: _conf.trans_duration,
	timer: _conf.timer == "true" ? true : false,
	delay: _conf.delay, 
    slides:_images
    });
	ab.vegas('play');
	}
	
	
	if(feed){
		 
		// create slideshow in news feed
	if( ga('.feed_fr_slideshow').length ){
		
		ga('.feed_fr_slideshow').each(function(){
				var _this = ga(this),
					_slides_o = new Array(),
					_sl_conf = _this.find('div.hookJsData').data('jsonsliderconf'),
					_slides_conf = validateJson(_sl_conf.conf.options);

		
			for(var k = 0;k<_sl_conf.photos.length;k++)
				_slides_o.push({src:_sl_conf.photos[k].img});

			
			_buildVegas(_slides_conf,_slides_o,_this);
	});
	
	
	}

		return;
		
	} else {
	 
		
	var _slideshow_data = objHook(ga('#slideshow_data').html());
 
	// create slideshow in profile page
	if(ga('#u__slideshow').length && _slideshow_data){
 
		var _slides_o = new Array(),
     		_slides_conf = validateJson(_slideshow_data.conf.options);
			
			for(var k = 0;k<_slideshow_data.photos.length;k++)
				_slides_o.push({src:_slideshow_data.photos[k].img});

			
			_buildVegas(_slides_conf,_slides_o);
		
	}
	
	
	
	}
	
}

		function hideFromFeed(el){
			
			localStorage.setItem('feed_waiting_anim','1');
            var $this = ga(el);
            var feed_id = escape($this.data('gth'));
            var send = jAjax('/profile', 'post', 'cmd=hide_from_feed&i=' + feed_id + '&type=pos');
            send.done(function (data) { 

                if (data == '0') {
                    return displayErr(lang.error_to_hide_feed);

                } else {
                    var tf = hide_feed_item;
                    tf.slideUp(333, function () {
                        tf.remove();
						localStorage.removeItem("feed_waiting_anim");
						hide_feed_item = false;
                    });
                }


            });
			
		}
		
		
function saveMail(e, f)
{
	e.preventDefault();

	var mail_inp = f.find('#mail_update'),
		pass_m_inp = f.find('#em_curr_pass');
	if (!$.trim(mail_inp.val()) || !validateEmail(mail_inp.val())) return updInfoErr(mail_inp, lang.pleaseEnterAValidEmail);
	else if (!$.trim(pass_m_inp.val())) return updInfoErr(pass_m_inp, lang.pleaseEnterYourPassword);
	ajaxLoading();
	var sendForm = js_subForm(f);
	sendForm.done(function (data)
	{
		removeAjaxLoad();
		if (data == 2) return updInfoErr(mail_inp, lang.pleaseEnterAValidEmail);
		else if (data == 5) return updInfoErr(mail_inp, lang.thisIsYourCurrentlyEmail);
		else if (data == 3) return updInfoErr(mail_inp, lang.emailIsAlreadyInUse);
		else if (data == 4) return updInfoErr(pass_m_inp, lang.incorrectPass);
		else if (data == 1)
		{ // success
			$('#curr_email_div')
				.text(mail_inp.val());
			pass_m_inp.val('');
			updInfoErr(pass_m_inp, null, 1);
			updInfoErr(mail_inp, null, 1);
			window.location = '/?logme=passChanged';
		}
		else return displayErr(lang.err_tehnic);
	});
}

function removeAjaxLoad()
{
	ga('body')
		.find('.globalAjaxLoader')
		.remove();
}
	function validateEmail(email)
	{
		var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		return re.test(email);
	}
	
function jAjax(u, t, d, pForm)
{
	if (!pForm)
	{
		var req = jQuery.ajax(
		{
			url: u,
			type: t,
			data: d
			//  cache: true
		});
	}
	else
	{
		var req = jQuery.ajax(
		{
			url: u,
			type: t,
			data: d,
			//Options to tell jQuery not to process data or worry about content-type.
			cache: false,
			contentType: false,
			processData: false
		});
	}
	req.fail(function (a, b)
	{
		//return displayErr(b.status);
	});
	return req;
}// slide feed filter
function feedFilterSlide(el,mode){
	el = ga(el);
	switch(mode){
		
		case 'forward': el.closest('.uslider').find('.uslider_cnt').animate({scrollLeft: '+=400px'}); break;
		
		case 'back': el.closest('.uslider').find('.uslider_cnt').animate({scrollLeft: '-=400px'}); break;
		
		default:return;
		
	}
	
}
	function feedFilterSlideByArrws(){
	
		if(!ga('.uslider_cnt').hasScrollBar()) ga('.uslider_cnt').parent().find('.uslider_ctrl.__next').addClass('hidden');
	
		ga('.uslider_cnt').off('scroll.horizontal').on('scroll.horizontal', function(e){
		var _a = ga(this),
			s_newScrollLeft = _a.scrollLeft(),
			s_width=_a.outerWidth(),
			h_scrollWidth=_a.get(0).scrollWidth;
		
		
		
		if(_a.scrollLeft() >= 10){
			_a.parent().find('.uslider_ctrl.__prev').removeClass('hidden');
			
		} else {
			
			_a.parent().find('.uslider_ctrl.__prev').addClass('hidden');	
		}
		


		if (h_scrollWidth-s_newScrollLeft === s_width) {
			_a.parent().find('.uslider_ctrl.__next').addClass('hidden');
			
		} else {
			
			_a.parent().find('.uslider_ctrl.__next').removeClass('hidden');	
		}
		
	});
	
}
	function headerNavButton(){
	setTimeout(function(){
	// modify header
	var _modify_header = ga('#modifyheader');
	if(_modify_header.length){  
		var _g_header_name = _modify_header.data('headername'), _back_href = _modify_header.data('backhref');
		ga('html').addClass('appsmodifyheader');
		
		var _toolbar_back_link =   '\
									<a class="cfff toolbar_back h-mod '+ (_modify_header.hasClass('reloadwall') ? 'reloadwall' : '' )+'" href="'+_back_href+'" id="toolbar_back_id" '+ (_modify_header.hasClass('nohref') ? '' : 'hrefattr="true"' )+'>\
									'+ ( _modify_header.hasClass('noback') ? '' : '<span class="header_back_icv2"></span>')+'<span class="top_header_nav_txt">'+_g_header_name+'</span>\
									</a>\
									';
					

	if(_modify_header.hasClass('mail')){
		var mail_user_d = _modify_header.data('header-mail');
		 
		var _toolbar_back_link =   '<a class="cfff toolbar_back mail h-mod '+ (_modify_header.hasClass('reloadwall') ? 'reloadwall' : '' )+'" href="'+_back_href+'" id="toolbar_back_id" '+ (_modify_header.hasClass('nohref') ? '' : 'hrefattr="true"' )+'>\
									'+ ( _modify_header.hasClass('noback') ? '' : '<span class="header_back_icv2"></span>')+'<div class="mailHat__convoAvatar avatar avatar_1 avatar_size_s inline middle" style="background-image:url(/getPhoto?p='+mail_user_d.recipient_photo+'&sz=small);"></div><span class="top_header_nav_txt">'+_g_header_name+'</span><span class="mailHat__convoDetails"><span class="mailHat__convoDetailsText">'+mail_user_d.recipient_online+'</span></span>\
									</a>';
 
	} else if (	_modify_header.hasClass('filter_wall') ){

 
		var _toolbar_back_link =   '\
									<a class="cfff toolbar_back h-mod '+ (_modify_header.hasClass('reloadwall') ? 'reloadwall' : '' )+'" href="javascript:void(0);" id="toolbar_back_id" onclick="selectFeedFilter(event,this);">\
									<span class="top_header_nav_txt">'+_g_header_name+'</span><span class="glyphicon glyphicon-menu-down filter-wall-dropdown-ic"></span>\
									</a>\
									';
	}	
									
	ga('#header_navig_p').empty();
	ga('#header_navig_p').html(_toolbar_back_link);
	} else { 
					  ga('html').removeClass('appsmodifyheader');
					  ga('#header_navig_p').empty();
	}
	
	},200);
	
}


	function commentsInPostsPage(){

	var post_comments_sections = ga('[rel="comments-in-posts-page"]');
	
	if( post_comments_sections.length )
	{
	

	post_comments_sections.each(function(){
						var _this = ga(this);

						var $feed_id = _this.attr('id'), 
						    $itemid = _this.data('original-post-id'), 
							$shared_post_id = _this.data('shared-post-id');
							$author_id = _this.data('posts-author-id'), 
							clubid = _this.data('posts-clubid'),
							categ = _this.data('comments-categ');

				
				 
				 
						var $this = ga('[data-gth="feed-posts-'+$feed_id+'"]');
						var $after_app = ga('<div/>').addClass('feed_post_comments_widget'+(clubid ? ' incommunity' : '')).attr('id','feed_post_comments_section_'+$feed_id);
						$this.find('.feed_f').after($after_app);
						commentsWidget($shared_post_id,
												$after_app,
												categ,
												{'width':'75%','height':'auto','min-height':20,'overflow':'hidden','padding':'3px 7px'},
												'',
												'#feed_cnt_'+$feed_id,$author_id,'2',1);

					//	ga(this).remove();
						});
	
	}
	
}

function menu(){
	this.init();
}

menu.prototype = {
	init:function(){
	this.l_menu = ga('#lm_cont');
	 this.sc_wrap = ga('#sc_wrap');
	},
    toggle:function(c){ 
        ga('body').hasClass('lm_opened') ? this.closeMenu() : this.openMenu();
    },
	closeMenu:function(){
			ga('body').removeClass('lm_opened');
		
	/*	ga('#sc_wrap').addClass('lm_anim lm_anim_end').on(crossEvent, function ()
				{
					ga(this).removeClass('lm_anim lm_anim_end');
				
				});*/
	},
	openMenu:function(){
		ga('body').addClass('lm_opened');
	 /*ga('#sc_wrap').addClass('lm_anim_start').on(crossEvent, function ()
				{
					ga(this).removeClass('lm_anim_start');
					
				});
*/
		
		
	}
}
var menu = new menu();


function uprofilemenu(evt){
var el = ga(evt.target);
var s_Menu = ga('.u_profile_more_menu');

if(!el.hasClass('show')){
	el.find('#u_feed_menu_plus_minus').text('-');
	el.addClass('show');
	s_Menu.slideDown();
	
} else {
	el.find('#u_feed_menu_plus_minus').text('+');
	el.removeClass('show');
		s_Menu.slideUp();
}

}


	function appsPage(){
		
	}
	function doUploadFiles(event, files, progressBar, albID)
{  
	var photoAddTextarea = function (c)
	{
		var randomId = (new Date())
			.getTime();
		var getDescrTemp = jAjax('/modules/photoUpload/descr_tem.html', 'get', '');
		getDescrTemp.done(function (html)
		{
			c.find('img')
				.after(jprintf(html, lang.change, randomId, randomId, lang.add_descr, randomId, lang.rotate_photo));
		});
	}
	var readPhotos = function (o)
	{
		var input = event.target;
		var container = ga('#bf_upload_' + o);
		var output = container.find('img')[0]; //container.find('.img_fak')[0];
		if (container.length)
		{
			var reader = new FileReader();
			reader.onload = function ()
			{
				var dataURL = reader.result;
				if (container.length == 0) return false;
				output.src = dataURL;
				///output.style.backgroundImage = 'url('+dataURL+')';
				container.find('.__uploadingInfo')
					.addClass('__off');
				container.find('.uploading_ovr')
					.addClass('__on');
			};
			reader.readAsDataURL(files[o]);
		}
	}
	var count = 0;
	var totalFiles = files.length;
	var trigger_upForm = function ()
	{
		if (typeof files[count] === 'undefined' || count > files.length - 1)
		{
			var progressBarTimeout;
			var progressBarRemove = function ()
			{
				progressBarTimeout = setTimeout(function ()
				{
					progressBar.remove();
				}, 8000);
			}
			progressBar.hover(function ()
			{
				clearTimeout(progressBarTimeout)
			}, function ()
			{
				progressBarRemove();
			});
			edUpload();
			if (!albID) photoTabClick("#pphotosTab");
			progressBarRemove();
			return false;
		}
		var formData = new FormData();
		formData.append('files[]', files[count]);
		formData.append('albid', albID);
		$.ajax(
		{
			url: _st.uploadFile, //Server script to process data
			type: 'POST',
			xhr: function ()
			{ // Custom XMLHttpRequest
				var Xhr = $.ajaxSettings.xhr();
				if (Xhr.upload)
				{ // Check if upload property exists
					Xhr.upload.addEventListener('progress', function (e)
					{
						mainUploadProgressHandling(e, count, progressBar, count, totalFiles)
					}, false); // For handling the progress of the upload
				}
				return Xhr;
			},
			//Ajax events
			beforeSend: function ()
			{
				readPhotos(count);
			},
			success: function (data)
			{ 
				var response = validateJson(data);
				if (response['status'] === 'OK')
				{
					var container = ga('#bf_upload_' + count);
					if (container.length)
					{
						container.find('img')[0].src = '/getPhoto?p=' + response['photoid'] + '&sz=grid&v' + (new Date())
							.getTime();
						container.children(':first')
							.attr('data-photoc', response['photoid']);
						container.find('#restore_recent_upload')
							.attr('href', '/profile?pid=' + (response['photoid']) + '&q=' + (response['userid']) + '&cmd=phreturn&i=' + (response['albumid']) + '&phf=' + (response['filename']) + '&ex=' + (response['extension']) + '&fsz=' + (response['filesize']) + '&pos=0&ad=' + response['added']);
						container.find('#delete_recent_upload')
							.removeAttr('style')
							.attr('href', '/profile?q=' + (response['userid']) + '&cmd=deletephoto&ph=' + response['photoid']);
						container.find('.uploading_ovr.__on,.pup_bar_m_upload')
							.remove();
						photoAddTextarea(container);
					}
					setTimeout(function ()
					{
						count++;
						trigger_upForm();
					}, 50);
				}
				else return displayErr(data);
			},
			error: function ()
			{
				return displayErr(lang.somethingWrong)
			},
			// Form data
			data: formData,
			//Options to tell jQuery not to process data or worry about content-type.
			cache: false,
			contentType: false,
			processData: false
		});
	}
	trigger_upForm();
}

 

function deletePhoto(element, evt, photoLayer)
{
	evt.preventDefault();
	var $el = ga(element),
		hrf = $el.attr('href')
		.split('?'),
		url = hrf[0],
		data = hrf[1];
	var aj = jAjax(url, 'get', data + '&view_as=json');
	aj.done(function (data) 
	{
		 
		
		if( $el.hasClass('icommunity') ){
			
			if(data == '1'){
				
				$el.closest('[data-postshpid]').remove();
				//communityAlbumPicturesWall(1);
			} else {
				
				return displayErr(lang.somethingWrong);
				
			}
			
			
			return;
			
		}
		
		
		if (data === '1')
		{
			countPhotos('minus');
			if (!photoLayer)
			{
				$el.parent()
					.children('.ph.disabling-layer')
					.css(
					{
						'width': $el.parent()
							.width(),
						'height': $el.parent()
							.height()
					})
					.addClass('__on');
				$el.parent()
					.children('a:not([data-vphopen])')
					.hide();
				$el.closest('.ec_items')
					.addClass('notOvr');
			}
			else
			{
				var phlayer_active_slide = ga('.nb-slide.nb__active'),
					phlayer_active_image = phlayer_active_slide.find('img');
				var data_restore = validateJson(localStorage.getItem('phlayer-undophoto')); // $el.data('undophoto');
				ga('.zpv_bottom_body,.photo_viewer_right_sidebar,.header-more-pviewer')
					.hide();
				phlayer_active_slide.addClass('__removed');
				phlayer_active_slide.find('img')
					.hide();
				phlayer_active_slide.find('section.phlayer_tag.__tagged')
					.hide();
				phlayer_active_slide.find('.widget_lsco_bot_shadow')
					.hide();
				phlayer_active_slide.find('.widget_photoLayer')
					.hide();
				phlayer_active_slide.closest('#photo-viewer')
					.prepend('<div class="pl_pc_photo_stub">' + lang.photo_deleted + '.' + '<div class="photo-sc_i_utility_undo-delete"><a id="phlayer_rr_' + data_restore.pid + '" onclick="phLayerRestorePhoto(this);restorePhoto(this,event,1)" ' + 'href="/profile?pid=' + escape(data_restore.pid) + '&q=' + escape(data_restore.uid) + '&cmd=phreturn&i=' + escape(data_restore.aid) + '&phf=' + data_restore.pfl + '&ex=' + escape(data_restore.ex) + '&fsz=' + escape(data_restore.fsize) + '&pos=' + escape(data_restore.pos) + '&ad=' + escape(data_restore.ad) + '" class="il white-color">' + lang.restore_photo + '</a></div></div>');
				ga('#photo-viewer [data-vphi="' + base64_encode(data_restore.pid) + '"]')
					.children()
					.append('<div onclick="event.preventDefault();event.stopPropagation();" id="restoreforphotoviewer_' + data_restore.pid + '" class="ph disabling-layer __on"><span class="photo-sc_i_utility_delete-status">The photo has been deleted.</span>' + '<div class="photo-sc_i_utility_undo-delete"><a onclick="restoreDeleteFromPhotoViewer(this,event);restorePhoto(this,event,1)"' + ' href="/profile?pid=' + escape(data_restore.pid) + '&q=' + escape(data_restore.uid) + '&cmd=phreturn&i=' + escape(data_restore.aid) + '&phf=' + data_restore.pfl + '&ex=' + escape(data_restore.ex) + '&fsz=' + escape(data_restore.fsize) + '&pos=' + escape(data_restore.pos) + '&ad=' + escape(data_restore.ad) + '" class="il">Restore</a></div></div>');
			}
		}
		else return displayErr(lang.err_del_photo);
	});
}
function copyText(txt,el) {

      //try {
        //var successful = document.execCommand('copy')
       // var msg = successful ? 'successfully' : 'unsuccessfully'
     
		var copied = copyToClipboard(el);

	// alert(copied);
		var w = 'done';//msg == 'successfully' ? 'done' : 'warn';
		kn_liveNotif( lang.text_copied_to_clipboard.replace('%s',msg),w,1000,'');
      //} catch (err) {
	//	kn_liveNotif( lang.text_unable_to_copy_to_clipboard,'warn',1000,'');
      //}

    }
// block user
function toBlackList(obj, calbak, adt)
{
	confirm_act(lang.blacklist_confirm, function (event)
	{
		var uid = adt ? escape(adt) : escape(sh_user_details.uid);
		var send = jAjax(pm__action, 'post', 'action=uToBlackList&to=' + uid);
		send.done(function (res)
		{
			if (res === '1')
			{
				window[calbak](uid);
			}
			else if (res === '0')
			{
				displayErr(lang.blacklist_err);
			}
			else if (res !== '1' && res !== '0')
			{
				displayErr(res);
			}
		}); // ajax
	}); // confirmation
}	

// add to bookmark
function bookmarkthis(el,ev){
	
	ev.preventDefault();
	
	el = ga(el);
	var b_data = el.data('bookmark'), b_categ = b_data.categ, b_itemid = b_data.itemid;
	var send_arr = {};
	
	if(el.hasClass('bookmark_from_community')){
		
		send_arr['clubid'] = b_data.clubid;
	}
	
	send_arr['cmd'] = 'bookmarkThis';
	send_arr['categ'] = b_categ;
	send_arr['itemid'] = b_itemid;
	
	var send = jAjax('/cmd.php', 'post', send_arr );
	send.done(function(data){
		
		if(data === 'exist'){
			
			return kn_liveNotif(lang.already_bookmarked,'warn',5000,lang.the_item_is_already_in_your_bookmarks);
			
		} else if(data === '1') {
			
			switch(b_categ){
				
				case 'user':
				el.replaceWith('<div class="u_profile_bookmarked"><span class="tico"><i class="tico_img ic ic-ok"></i>'+lang.added_to_your_bookmarks+'</span></div>');
				break;
				case 'photo':
				el.find('i').replaceWith('<i class="ic tico ic_phly_bookmarked"></i>');
				break;
				case 'post':
				el.addClass('active').css('pointer-events','none');
				break;
				
			}
			
			
			kn_liveNotif(lang.bookmark_added_title,'done',4000,lang.bookmark_added_descr);
			
		} else {	
			return kn_liveNotif(lang.bookmark_add_error,'error',6000,lang.bookmark_add_error_descr);
			
		}
		
	});
	
	
}

// delete bookmark
function deleteBookmark(evt,el,f,c){
	
	evt.preventDefault();
	
	el = ga(el);
	var b_id = el.data('deletebookmark');
	
	
	var send = jAjax('/cmd.php', 'post', 'cmd=deletebookmark&id='+escape(b_id));
	send.done(function(data){
		
		if(data === '1'){
			
			kn_liveNotif(lang.bookmark_removed_title,'done',4000,lang.bookmark_removed_descr);
			if(!f) ga('[data-bookmark="'+b_id+'"]').remove();
			else {
				
				switch(f){
					
					case 'photo':
					
					el.find('i').replaceWith('<i class="ic tico ic_phly_bookmark"></i>');
					el.addClass('__disabled');
					
					break;
					
					case 'post':
					el.removeClass('active').css('pointer-events','none');
					break;
					
				}
				
				
			}
			if(c) c();
		} else {
			
			return kn_liveNotif(lang.bookmark_remove_error,'error',6000,lang.bookmark_remove_error_descr);
		}
		
		
		
	});
	
	
	
}
// delete posts
function deleteMyPost(ev, obj)
{
	ev.preventDefault();
	var $el = $(obj);
	var post_id = $el.data('post-d')
		.i;
	var send = jAjax('/cmd.php', 'post', 'cmd=deleteMyPost&i=' + post_id);
	send.done(function (data)
	{
		if (data == 0) return displayErr(lang.post_not_found);
		else
		{
			ga('#pp_post_viewer .mlr_cnts,#st_fd_i_' + x_krypt(post_id))
				.addClass('__deleted');
			ga('#hook_Block_MiddleColumnTopCard_StatusNew')
				.hide();
		}
	});
}
// restore post
function restoreMyPost(ev, obj)
{
	ev.preventDefault();
	var $el = $(obj);
	var post_data = JSON.stringify($el.data('post-d'));
	var send = jAjax('/cmd.php', 'post', 'cmd=restoreMyPost&d=' + post_data);
	send.done(function (data)
	{
		if (data == 0) return displayErr(lang.post_restore_err);
		else
		{
			$('#pp_post_viewer .mlr_cnts,#st_fd_i_' + x_krypt($el.data('post-d')
					.i))
				.removeClass('__deleted');
			$('#hook_Block_MiddleColumnTopCard_StatusNew')
				.show();
		}
	});
}
// create popups like windows 8 (full width, auto height)
function windowsPopup(cmd, dt)
{
	var send = jAjax('/profile', 'post', 'cmd=wpopups&type=pos&action=' + cmd + '&dt=' + JSON.stringify(dt));
	send.done(function (data)
	{
		var $data = ga(data);
		var $wp_b = ga('body');
		$data.find('.close_x_right_btn,.w8_cancel_form,.layer_ovr')
			.off('click.closew8p')
			.on('click.closew8p', function (e)
			{
				e.preventDefault();
				ga('#w8fullw_popup')
					.remove();
			});
		if (!$wp_b.find('#w8fullw_popup')
			.length) $wp_b.prepend($data)
			.find('.w8_popup_style')
			.css('top', (ga(window)
				.height() - $data.find('.w8_popup_style')
				.outerHeight()) / 2);
	});
}
function removeFtTpaPopup(){
	
ga('body').find('#pp_ft_markup').remove();	
	
}
function tpaPopup(el,evt){
	
	evt.preventDefault();
	var _this = ga(el);
	var _m = _this.data('mm');
	var $body = ga('body');
	var _pp_ft_markup = ga('<section/>').attr('id','pp_ft_markup'); 
	var _jb41ll = '<div onclick="removeFtTpaPopup();" class="layer_ovr _dark"></div>';
	_pp_ft_markup.html(_jb41ll+'<div id="pp_ft_cnt"><div class="ft_title"></div><div class="nano"><div class="ft_cnt nano-content"></div></div></div>');
	var _title = 'Popup';
	
		switch(_m){
			 
			case 'terms':
			_title = lang.terms_and_condition;
			break;
			
			case 'policy':
			_title = lang.privacy_policy;
			break;
			
			case 'about':
			_title = lang.About_Us;
			break;
		}
	
		// open mobile popup
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+_title+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();	
		
		var cont = ga('.mob_popup_cnt#id_'+rand);
		ga('#m_helper').click();
	
	var send = jAjax('/cmd.php', 'post', 'cmd=tpapopup&a='+_m);
	
	send.done(function(data){

		var d = validateJson(data);
		
		if(d){
			
			
			cont.html('<div class="mob_terms_p_policy">'+d.cnt+'</div>');
			//$body.find('#pp_ft_markup .ft_title').html(d.title+'<a href="javascript:;" onclick="removeFtTpaPopup();" class="ft_done_btn">'+lang.Done+'</a>');
		 
			
			ga('body').off('keyup.closeTpaPopup').on('keyup.closeTpaPopup', function(e){
				
				if(e.keyCode == 27 || e.keyCode == 13) removeMobilePopupFromDom(rand);
			});
			
		}
		
	});
	
	
}
function getSecretCode(via,mode){
	
	var _error = ga('#error');
	var $to = escape(ga('#scode_input').val());
	ajaxLoading();
	
	_error.removeClass('_show');
	var send = jAjax('/cmd.php', 'post', {'cmd':'get-secret-code','via':via,'mode':mode,'to':$to});
	send.done(function(r){  
	removeAjaxLoad();
	
		var d = validateJson(r);
		 
		if(d.status == 'success'){
			
			var _a_location = ga('<a/>').attr({'hrefattr':'true','href':'/confirmcode/'+via+'/'+$to+'/'});
		
		ga('#confirm-secret-code').html(_a_location);
		up_href();

		_a_location.trigger('click');
 
			
			
		} else if (d.status == 'error'){
			
			_error.addClass('_show').html(d.msg);
			
		} else {
			_error.addClass('_show').html(lang.err_tehnic);
		}
		
		
	});
	
	
}
function confirmSecretCode(mode) {
	ajaxLoading();
	var _error = ga('#error');
	var code = $.trim(ga('#secret-code-input').val());
	_error.removeClass('_show');
	var send = jAjax('/cmd.php', 'post', {'cmd':'confirm-secret-code','code':escape(code),'mode':mode});
	send.done(function(d){   
		removeAjaxLoad();
		var r = validateJson(d);
		
		if(r.status == 'ok' && r.msg == 'activate_account') {
			_error.empty();
			window.location='/?user='+r.login_username;
			kn_liveNotif(lang.your_account_has_been_activated_title_notif,'done',6000,lang.your_account_has_been_activated_descr_notif);
			
		}else if (r.status == 'ok' && r.msg == 'restore-password'){
			_error.addClass('_show').empty();
			window.location = '/changepass/'+r.login_username+'/'+r.new_code;
		} else {
			
		
			
			_error.addClass('_show').html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+r.msg+'</div></div>');
		}
		
		
	});
	
	
}
function forgotSetNewPass() {
	
	var pass_field_o = ga('#pass_field_o'), pass_field_t = ga('#pass_field_t'), code = ga('[name="code"]'), _error = ga('#error');
	_error.removeClass('_show');
	if(pass_field_o.val().length < 6)
	 return _error.addClass('_show').html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+lang.newPasswordIsTooShort+'</div></div>');


	if(pass_field_o.val() !== pass_field_t.val()) {
		return _error.addClass('_show').html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+lang.passDontMatch+'</div></div>');
		
		
	}
	ajaxLoading();
	var send = jAjax('/cmd.php', 'post', { 'cmd' : 'forgotSetNewPass', 'email' : ga('[name="email"]').val(), 'rps' : ga('[name="rps"]').val(), 'repass' : pass_field_o.val() , 'newpass' : pass_field_t.val() , 'code' : code.val()});
	send.done(function(data) {  
		
		removeAjaxLoad();
		if(data == '2')
			return _error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+lang.newPasswordItSame+'</div></div>');
		else if ( data == '3')
		return _error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+lang.newPasswordIsTooShort+'</div></div>');
	else if (data == '4')
		return _error.html('<div class="msg ferror"><div class="msg_text"><b>'+lang.Error+'</b><br/>'+lang.passwordDidntMatch+'</div></div>');
		else if (data == '1'){
			kn_liveNotif(lang.forgot_pass_updated_title,'done',4000,lang.forgot_pass_updated_descr);
			setTimeout(function(){ window.location='/'; },4500);
		} else return displayErr(lang.err_tehnic);

	});
	
}
function reportThis(evt){
	
	evt.preventDefault();
	
	var _this = ga(evt.target);
	var _obj = _this.data('reportobj');
	var _reason = _this.closest('#cfrmPopLayerRegisterSpam').find('#defaultreason').text();

	ajaxLoading();
	var send = jAjax('/cmd.php', 'post', {'cmd':'report_this', 'item_id' : _obj.id, 'item_type' : _obj.type, 'reason' : _reason});
	send.done(function(data){
		removeAjaxLoad();
				if(data === '1'){
					ga('#w8fullw_popup').fadeOut(function(){ga(this).remove();});
			kn_liveNotif(lang.Reported,'done',5000,lang.your_report_has_been_successfully_sent);
				}else
		   kn_liveNotif('Ooops!','warn',4000, lang.err_tehnic);
		
	});
}
	
 // generate link for item
function itemGenerateLink(){
	
	var markup = ga('<section id="item_get_direct_link"><div class="layer_ovr"></div>\
	<div class="item-direkt-link-p">\
	<span title="close" class="tico tico__n-t notifs_close close-direkt-link-popup"><i class="tico_img ic ic_close"></i></span>\
	<div class="drlk1">'+lang.direct_url+'</div>\
	<div class="drlk2"><input type="text" value="'+window.location+'"/></div>\
	<div class="drkl3 taCenter"><button id="copy_to_clipboard" class="flat_button">Copy to clipboard</button></div>\
	</div></div>');
	
	var $b = ga('body');
	
	if(!$b.find('#item_get_direct_link').length)
		$b.prepend(markup);
	///$b.find('#item_get_direct_link').on('click.closeItemDirectLink',function(e){ $b.find('#item_get_direct_link').remove();  });
	$b.find('.close-direkt-link-popup').on('click.closeItemDirectLink',function(e){
		$b.find('#item_get_direct_link').remove();
	});
	
	$b.off('keyup.closeItemDirectLink').on('keyup.closeItemDirectLink',function(e){
		
		if(e.keyCode == 27)
			$b.find('#item_get_direct_link').remove();
	});
	markup.find('#copy_to_clipboard').on('click',function(){
		copyText(markup.find('input').val(),markup.find('input'));
		$b.find('#item_get_direct_link').remove();
		
	});
	markup.find('input')[0].select();
	markup.find('input').focus();
	
}
function phLayerRestorePhoto(o)
{
	// $(o).closest('#pp_photo_viewer').find('.photo-layer').show(); 
	var phlRestore_phid = $(o)
		.attr('id')
		.match(/\d/g)
		.join('');
	var $active_slider = $('.nb-slide.nb__active');
	ga('.phlayer_deleted_photo,.pl_pc_photo_stub')
		.remove();
	ga('.zpv_bottom,.photo_viewer_right_sidebar,.header-more-pviewer')
		.show();
	$active_slider.removeClass('__removed');
	$active_slider.find('img')
		.show();
	$active_slider.find('section.phlayer_tag.__tagged')
		.show();
	$active_slider.find('.widget_lsco_bot_shadow')
		.show();
	$active_slider.find('.widget_photoLayer')
		.show();
	ga('#restoreforphotoviewer_' + phlRestore_phid)
		.remove();
}

function restoreDeleteFromPhotoViewer(obj, ev)
{
	ev.stopPropagation();
	var $obj = $(obj);
	$obj.closest('.disabling-layer')
		.remove();
}

function restorePhoto(element, evt, photoLayer,del_album)
{
	evt.preventDefault();
	var $el = ga(element),
		hrf = $el.attr('href')
		.split('?'),
		url = hrf[0],
		data = hrf[1];
		
		ajaxLoading();
		$el.addClass('__disabled');
	var aj = jAjax(url, 'get', data + '&view_as=json');
	aj.done(function (data)
	{	$el.removeClass('__disabled');
		removeAjaxLoad();
		if (data === '0')
		{
			return displayErr(lang.err_return_photo);
		}
		else
		{
			countPhotos('plus');
			if (!photoLayer)
			{
				var parentEl = $el.closest('.ph.disabling-layer.__on');
				var removeBtn = parentEl.parent()
					.find('a.x_delete_pp,a.ic_delete_min');
				/*var removeBtnHr = removeBtn.attr('href')
					.split('&');*/
				parentEl.removeClass('__on');
				$el.closest('.ec_items:not(.__uploading)')
					.removeClass('notOvr');
				removeBtn.show();
				// removeBtn.removeAttr('style');
				// removeBtn.removeAttr('href').attr('href', removeBtnHr[0] + '&' + removeBtnHr[1] + '&ph=' + data);
			}
			
			if(del_album){
				$el.closest('.ec_items.dlalb').fadeOut(1000,function(){ ga(this).remove() });
			}
		}
	});
}

// album checkboxes
function albSquareCheck()
{
	
	if(ga('#new_album_create').length) {
	var elements = $('input[album-square-ch]');
	var everyone = $('#sq1');
	var allFriends = $('#sq2');
	elements.not('#sq1,#sq2')
		.off('click')
		.on('click', function (e)
		{
			everyone.prop('checked', false);
			allFriends.prop('checked', false);
		});
	allFriends.off('click')
		.on('click', function (e)
		{
			elements.not(everyone)
				.prop('checked', true);
			everyone.prop('checked', false);
		});
	everyone.off('click')
		.on('click', function (e)
		{
			elements.prop('checked', false);
			this.checked = true;
		});
	}
}






function getUploadSkem(a)
{
	if (!a)
	{
		// markup for upload photos
		var mkup = '<div id="bf_upload_%s" class="ec_items __uploading notOvr">' + 
		'<div class="eg_gotph">' + '<div class="uploading_ovr"></div>' +
		'<div class="ph disabling-layer"><span class="photo-sc_i_utility_delete-status">' + lang.photo_deleted + '</span>' +
		'<div class="photo-sc_i_utility_undo-delete"><a id="restore_recent_upload" onclick="restorePhoto(this,event)" href="#" class="il">' + lang.restore_photo + '</a></div></div>' +
		'<a class="x_delete_pp" style="display:none;" id="delete_recent_upload" title="' + lang.delete_photo + '" onclick="deletePhoto(this,event)" href="#">' + lang.delete_photo + '</a>' +
			//'<div class="img_fak"></div>' +
			'<a href="/photo?q=2&show=pphotos&from=medium&a=0&o=&cmd=openPhotoViewer" data-vphopen="1" data-vphi="MzU="><img src="" class="img_fak" border="0" /></a>' + 
			'<div class="ucard-b_tx_cnt __uploadingInfo">' + lang.uploading + '<div class="bold fs-13 mw170 ellip">%s</div></div>' + 
			'<div class="pup_bar_m_upload">' + '<div class="main_progress_photo"></div>' + '</div>' + '</div></div>';
	}
	else
	{
		// markup for attachements
		var mkup = '<div id="at_upload_%s" class="ec_items __uploading notOvr">' + 
		'<div class="eg_gotph">' + '<div class="uploading_ovr"></div>' + 
		'<div class="ph disabling-layer"><span class="photo-sc_i_utility_delete-status">' + lang.photo_deleted + '</span>' + 
		'<div class="photo-sc_i_utility_undo-delete"><a id="restore_recent_upload" onclick="restorePhoto(this,event)" href="#" class="il">' + lang.restore_photo + '</a></div></div>' + 
		'<a class="x_delete_pp" style="display:none;" id="delete_recent_upload" title="' + lang.delete_photo + '" onclick="deletePhoto(this,event)" href="#"></a>' +
			// '<div class="img_fak"></div>' +
			'<img src="" class="img_fak" border="0" />' + '<span class="selectable-card_ovr"></span><span class="selectable-card_ic"></span>' + 
			'<div class="ucard-b_tx_cnt __uploadingInfo">' + lang.uploading + '<div class="bold fs-13 mw170 ellip">%s</div></div>' + 
			'<div class="pup_bar_m_upload">' + '<div class="main_progress_photo"></div>' + '</div>' + '</div></div>';
	}
	return mkup;
}
function ajaxuploadprogress(e){
	var rsp = 0;
		if (e.lengthComputable)
	{
		rsp = Math.round((e.loaded / e.total) * 100);

	}
	
	return rsp;
}
function mainUploadProgressHandling(e, i, pBar, count, ctotal)
{
	var p_id = ga('#bf_upload_' + i);
	var p_cont = ga('#bf_upload_' + i)
		.find('.main_progress_photo');
	if (e.lengthComputable)
	{
		var p_percentage = Math.round((e.loaded / e.total) * 100);
		p_cont.css('width', p_percentage + '%');
		pBar.find('#totalFiles')
			.text(ctotal);
		if (p_percentage >= 100)
		{
			pBar.find('.progress_photo')
				.css('width', (100 / ctotal) * (count + 1) + '%');
			pBar.find('#uploadedFiles')
				.text(count + 1);
			countPhotos(null, 1);
		}
	}
}

function photoTabClick(element)
{ 
	ga(element ? element : '#photosTab')
		.trigger('click');
}


function getUploadBar(a, cf)
{
	
	var markup;
	switch (a)
	{
	case 'first':
	case 'feed':
		markup = '<section class="upload_processing"><div class="site_ovr __darknest __mt3"></div><div class="pup_bar"><div class="progress_photo"></div>' + '<div aria-hidden="false" style="visibility:hidden;" class="progress_tx ellip _atcompl"><span class="tico tico__12">' + ' <i class="tico_img ic12 ic12_i_photo __upload"></i>' + ' <span id="progress_tx"></span>' + lang.uploaded + ' <a id="uploadPageLink" href="#" class="wl"><span id="uploadedFiles">%s</span> from <span id="totalFiles">%s</span> photos</a></span>' + '</div>' + '</div><div class="uploadTextCenterInf"><div class="percentage_elaps">0%</div></div></section>';
		break;
	case 'feedchange':
		markup = '<section class="upload_processing"><div class="site_ovr __darknest __mt3"></div><div class="pup_bar"><div class="progress_photo"></div>' + '<div aria-hidden="false" style="visibility:hidden;" class="progress_tx ellip _atcompl"><span class="tico tico__12">' + ' <i class="tico_img ic12 ic12_i_photo __upload"></i>' + ' <span id="progress_tx"></span>' + lang.uploaded + ' <a id="uploadPageLink" href="#" class="wl"><span id="uploadedFiles">%s</span> from <span id="totalFiles">%s</span> photos</a></span>' + '</div>' + '</div><div class="uploadTextCenterInf"><div class="percentage_elaps">0%</div></div></section>';
		break;
	case 'community':
		markup = '<section class="upload_processing"><div class="pup_bar"><div class="progress_photo"></div>' + '<div aria-hidden="false" style="visibility:hidden;" class="progress_tx ellip _atcompl"><span class="tico tico__12">' + ' <i class="tico_img ic12 ic12_i_photo __upload"></i>' + ' <span id="progress_tx"></span>' + lang.uploaded + ' <a id="uploadPageLink" href="#" class="wl"><span id="uploadedFiles">%s</span> from <span id="totalFiles">%s</span> photos</a></span>' + '</div>' + '</div></section>';
		break;
	case 'main':
		markup = '<section class="upload_processing"><div style="display:none;" class="site_ovr __darknest __mt3"></div><div class="pup_bar"><div class="progress_photo"></div>' + '<div aria-hidden="false" class="progress_tx ellip _atcompl"><span class="tico tico__12">' + ' <i class="tico_img ic12 ic12_i_photo __upload"></i>' + ' <span id="progress_tx"></span>' + lang.uploaded + ' <a id="uploadPageLink" href="#" class="wl"><span id="uploadedFiles">0</span> from <span id="totalFiles">0</span> photos</a></span>' + '</div>' + '</div></section>';
		break;
	}
	ga('body').prepend(jprintf(markup, cf, cf))
		.find('.pup_bar')
		.on('mouseover mouseenter', function ()
		{
			ga(this)
				.addClass('__addB')
		});
	return ga('section.upload_processing');
}
function assign_bfupl_img()
{   
	var intervalt = setInterval(function ()
	{
		if (typeof uploadGetFiles == 'function' && ga('.photos_content')
			.length != 0)
		{
			if (uploadGetFiles)
			{  
				clearInterval(intervalt);
				uploadGetFiles();
			}
		}
	}, 50);
}
function edUpload(c)
{
	var uploadBox = ga('.userAddPhoto,.jb_attch_uadph,.post_attch_uadph'),
		prc = ga('.upload_processing');
	if (c)
	{
		prc.remove();
		uploadBox.css(
		{
			'pointer-events': 'none',
			'opacity': 0.2
		});
	}
	else uploadBox.removeAttr('style');
}
function upload_form()
{
	jQuery('form#phform')
		.on('change drop', function (e)
		{
			//e.preventDefault();
			var $this = ga(this);
			var popup = $this.children('[name="mode"]')
				.val();
			var cf = document.all && !window.atob ? $this.find('input:file')
				.get(0)
				.files : parseInt($this.find('input:file', this)[0].files.length);
			edUpload(true);
			if (popup === 'main' && 'FileReader' in window)
			{ 
				var input = $this.children('input[type="file"]');
				var files = input[0].files;
				if (!$this.hasClass('__inAlbum')) photoTabClick("#pphotosTab");
			 
				uploadGetFiles = function (b)
				{  
					//for (var i = files.length-1; i >= 0; i--){
					for (var i = 0; i < files.length; i++)
					{
						var phContent = ga('.photos_content');
						var file_ext = files[i].name.split('.')
							.pop()
							.toLowerCase(); ///input.val().replace(/C:\\fakepath\\/i, "").split('.').pop().toLowerCase();
						if ($.inArray(file_ext, _st.photoTypes) == -1 && $.trim(file_ext))
						{
							e.preventDefault();
							e.stopImmediatePropagation();
							ga('.ec_items.__uploading')
								.remove();
							edUpload();
							return displayErr(lang.up_invalid_file_ext.replace('%s', _st.photoTypes));
						}
						if (files.length > _st.maxFilesUpload)
						{
							e.preventDefault();
							e.stopImmediatePropagation();
							edUpload();
							return displayErr(lang.up_maximumFiles.replace('%s', _st.maxFilesUpload));
						}
						//phContent.children(':first')
							//.after(jprintf(getUploadSkem(), i, files[i].name));
					 
							phContent.find('#mob_new_pictures').show().prepend( jprintf(getUploadSkem(), i, files[i].name) );
					}
					var pBar = getUploadBar(popup, cf);
					pBar.css('visibility', 'visible');
					doUploadFiles(e, files, pBar, b);
					uploadGetFiles = false;
				}
				
				
				if ($this.hasClass('__inAlbum')) uploadGetFiles($this.closest('[parent-alb="true"]').attr('id'));
				 return;
				
			}
			else popup = 'feed';
			return upload_photo($this, popup, e, cf);
		});
}
	
	
function upload_photo(t, popup, evt, cf)
{
	var files = t.children('input[type="file"]')[0].files,
		maxfiles = _st.maxFilesUpload,
		file_ext = t.find('input[type="file"]')
		.val()
		.replace(/C:\\fakepath\\/i, "")
		.split('.')
		.pop()
		.toLowerCase();
	t.attr("action", _st.uploadFile);
	if ($.inArray(file_ext, _st.photoTypes) == -1 && $.trim(file_ext))
	{
		evt.preventDefault();
		evt.stopImmediatePropagation();
		return displayErr(lang.up_invalid_file_ext.replace('%s', _st.photoTypes));
	}
	if (files > maxfiles)
	{
		evt.preventDefault();
		evt.stopImmediatePropagation();
		return displayErr(lang.up_maximumFiles.replace('%s', maxfiles));
	}
	var pBar = getUploadBar(popup, cf);
	var options = {
		beforeSend: function ()
		{
			pBar.css('visibility', 'visible');
		},
		uploadProgress: function (event, position, total, percentComplete)
		{
			if (percentComplete < 100)
			{
				pBar.find('.progress_photo')
					.css('width', percentComplete + '%')
					.closest(pBar)
					.find('.percentage_elaps')
					.text(percentComplete + '%');
			}
			else
			{
				pBar.find('._atcompl')
					.css('visibility', 'visible');
				pBar.find('.progress_photo')
					.css('width', '100%')
					.closest(pBar)
					.find('.percentage_elaps')
					.html('<div class="upload_complete _waiting ic50 tico_img"></div>');
			}
		},
		complete: function (response)
		{  
			var rsp = JSON.parse(response.responseText);
			if (rsp['status'] == 'OK')
			{
				var progressBarTimeout;
				var removeProgressBar = function ()
				{
					progressBarTimeout = setTimeout(function ()
					{
						pBar.remove();
					}, 8000);
				}
				edUpload();
				countPhotos(null, files.length);
				if (popup == 'feed') photoTabClick("#pphotosTab");
				pBar.find('.site_ovr,.uploadTextCenterInf')
					.hide();
				pBar.hover(function ()
				{
					clearTimeout(progressBarTimeout);
				}, function ()
				{
					removeProgressBar();
				});
				removeProgressBar();
			}
			else
			{
				displayErr(response.responseText);
			}
		},
		error: function ()
		{
			pBar.remove();
			if (!$.trim(file_ext)) return;
			return displayErr(lang.up_err_occur);
		}
	};
	if (cf > maxfiles)
	{
		return displayErr(lang.up_maximumFiles.replace('%s', maxfiles));
	}
	else t.ajaxForm(options)
		.trigger('submit');
}
function jprintf(format, data)
{
	var arg = arguments;
	var i = 1;
	return format.replace(/%((%)|s)/g, function (m)
	{
		return m[2] || arg[i++]
	})
}
function displayErr(str)
{  
	removeAjaxLoad();
	
	
	kn_liveNotif(lang.Error,'warn',10000,str);
	/*var errMarkup = '<section class="st_nav_error"><div class="site_ovr __light"></div><div class="site_ajax_error_msg"><div class="report_txt __info">%s</div><div class="ic close_err"></div></div></section>';
	var __err = ga('body')
		.find('section.st_nav_error');
	__err.remove();
	ga('body')
		//.find('.global_content')
		.prepend(errMarkup.replace('%s', str))
		.on('click', function (e)
		{
			clearTimeout(this.errTimeout);
			var $this = $(this);
			$this.find('.site_ajax_error_msg')
				.animate(
				{
					top: '-50px'
				}, 200, function ()
				{
					$this.find('section.st_nav_error')
						.remove();
				});
		});
	ga('.site_ajax_error_msg')
		.animate(
		{
			top: '0px'
		}, 300);
	if (_st.err_auto_hide) this.errTimeout = setTimeout(function ()
	{
		ga('.site_ajax_error_msg')
			.animate(
			{
				top: '-50px'
			}, 200, function ()
			{
				ga('body section.st_nav_error')
					.remove()
			});
	}, _st.err_HideTimeout);*/
}
function countPhotos(action, count)
{/*
	var navMenuPhCounts = ga('.navMenuCount._photos'), leftMenPhCount = ga('.lf_men._photos .lnavMenuCount');
	var userPhotoCounts = parseInt(navMenuPhCounts.text());
	var c = action ? (action == 'plus' ? ++userPhotoCounts : --userPhotoCounts) : '';
	navMenuPhCounts.text((!count ? c : parseInt(userPhotoCounts + count) ));
	leftMenPhCount.text((!count ? c : parseInt(userPhotoCounts + count) ));*/
}
function ajaxLoading()
{
	//var markup = ga('<div class="global_ajax_loader"></div>');
	var b = ga('body');
var markup = '<div class="globalAjaxLoader">\
			<div>        \
			<div class="preloader-spin">\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
            <div class="preloader-spin__petal"></div>\
			</div></div>';
	
	if(!b.find('.globalAjaxLoader').length)
	b.prepend(markup);
}
function removeAjaxLoad()
{
	ga('body')
		.find('.globalAjaxLoader')
		.remove();
}


function userPhotoWall(data, appTo)
{ 
	if (ga("#profile_wall_photos").length)
	{ 
		/*
    //setTimeout(function(){

      profile_photos_wall = new freewall("#profile_wall_photos");
			profile_photos_wall.reset({
					selector: '.ce11>img',
					animate: false,	gutterX:1, gutterY:1,		
					
					onResize: function() {
										profile_photos_wall.fitWidth();
					}
			});

 			profile_photos_wall.fitWidth();

			$('.ce11').fadeIn();
//},900);
*/
		// for more images
		ga('#profile_wall_photos')
			.justifiedGallery(
			{
				rowHeight: 120,
				//maxRowHeight: 'auto',
				margins: 6,
				border: 0,
				rel: 'profileWallPhotos',
				lastRow: 'nojustify',
				fixedHeight: false,
				captions: true,
				randomize: false,
				/*sizeRangeSuffixes: {
					lt100 : '_t', 
					lt240 : '_m', 
					lt320 : '_n', 
					lt500 : '', 
					lt640 : '_z', 
					lt1024 : '_b'
				}*/
			})
			.on('jg.complete', function (e) { });
	}
}
/* Update description and rotate of recent uploaded photos
---------------------------------------------------- */
function rotate_photo(el, id, e, rotatePhotoLayer, photolayerPicId)
{

	e.preventDefault();
	e.stopPropagation();
	var angle = parseInt(el.getAttribute('data-angle')) + parseInt(90);
	var $el = $(el);
	if (!rotatePhotoLayer)
	{
		var cont = $("#up_txt_" + id);
		var c = cont.closest('[data-parintii]');
		var rImg = c.prevAll('img');
		var iId = escape(cont.closest('[data-photoc]')
			.data('photoc'));
		var e_css = {};
		var d_css = {};
		d_css['opacity'] = 0.2;
		d_css['pointer-events'] = 'none';
		e_css['opacity'] = 1;
		e_css['pointer-events'] = 'auto';
		c.css(d_css);
	}
	else
	{
		var iId = escape(localStorage.getItem('phlayer-rotatephoto'));
		var slider_active_img = $('.nb-slides div[data-slpid="' + iId + '"]');
		var rImg = slider_active_img.find('img');
		ajaxLoading();
	}
	var request = jAjax('/profile.php', 'post', 'q=' + angle + '&ph=' + iId + '&cmd=rotate&type=pos');
	request.done(function (data)
	{ 
		if (data != '1')
		{
			///if (!photoLayer) c.css(e_css);
			return displayErr(lang.somethingWrong);
		}
		else
		{
			if (!rotatePhotoLayer)
			{
				rImg.css(
				{
					'-webkit-transform': 'rotate(' + angle + 'deg)',
					'transform': 'rotate(' + angle + 'deg)',
					//'-webkit-transition' : '-webkit-transform .1s ease',
					//'transition' : 'transform .1s ease'
				});
			}
			else
			{
				$('img [src="' + rImg.attr('src') + '"]')
					.attr('src', rImg.attr('src') + '&v=' + (new Date())
						.getTime());
				rImg.attr('src', rImg.attr('src') + '&v=' + (new Date())
						.getTime())
					.load(function ()
					{
						widget_reposition(slider_active_img.index(), 1);
					});
			}
			el.setAttribute('data-angle', (angle === 360 ? 0 : angle));
		}
		if (!rotatePhotoLayer) c.css(e_css);
		else removeAjaxLoad();
	});
}
function expand_txt_up(txt, id, e)
{
	e.preventDefault();
	e.stopPropagation();
	var _this = this,
		tx = ga("#up_txt_" + id),
		tg = tx.closest('[data-parintii="true"]')
		.find('.tag-friends');
	if (!tx.hasClass('__exp'))
	{
		tg.hide();
		tx.addClass('__exp')
			.css(
			{
				height: 80
			});
	}
	ga('body')
		.off('click.saveMediaInfo').on('click.saveMediaInfo', function (e)
		{
			var t = ga('textarea[recent-upl="true"]');
			t.css(
			{
				height: 32
			});
			t.removeClass('__exp');
			ga('.tag-friends._recu')
				.fadeIn();
			for (var i = 0; i < t.length; i++) if(tx.hasClass('icommunity')) communitySendFileDescription(t.eq(i),t.eq(i).data('fileid'),t.eq(i).data('clubid')); else upPhotoSendDescr(t.eq(i));
		});
}

function upPhotoSendDescr(d)
{
	var descr = d.val();
	var pid = escape(d.closest('.eg_gotph[data-photoc]')
		.data('photoc'));
	if (!$.trim(descr)) return false;
	var req = jAjax('/profile', 'post', 'cmd=phdescr&type=pos&q=' + descr + '&ph=' + pid);
	req.done(function (resp)
	{
		if (resp != '1') return displayErr(lang.somethingWrong);
		else
		{
			var descInput = d.closest('.descrInpCnt'),
				parintii = d.closest('[data-parintii]'),
				descCnt = parintii.find('.descrCnt'),
				change = parintii.find('.desc_change');
			descInput.hide()
				.find('textarea')
				.val('');
			descCnt.show()
				.find('.plp_descrCntText')
				.text(descr);
			change.on('click', function (e)
			{
				e.preventDefault();
				e.stopPropagation();
				descCnt.hide();
				descInput.show()
					.find('textarea')
					.val(descCnt.children(':first')
						.text())
					.css(
					{
						height: 80
					})
					.focus();
				parintii.find('.tag-friends')
					.hide();
			});
		}
	});
}
/* end update description
--------------------------  */
function js_subForm(f)
{
	var hform = $(f);
	var s = $.ajax(
	{
		url: hform.attr('action'),
		type: hform.attr('method'),
		data: hform.serialize()
	});
	s.fail(function (a, b)
	{
		return displayErr(b.status);
	});
	return s;
}
function createEmoji(){
	
var create_emoji = {
			// EMOTICONS
		       emoticons: {	
			   
			':smile:' : 'smile',
			
			':smiley:' : 'smiley',

			':grinning:' : 'grinning',
			
			':blush:' : 'blush',

			':relaxed:' : 'relaxed',
			
			':wink:' : 'wink',
			
			':heart-eyes:' : 'heart-eyes',

			':kissing_heart:' : 'kissing_heart',
			
			':kissing_closed_eyes:' : 'kissing_closed_eyes',

			':kissing:' : 'kissing',

			':kissing_smiling_eyes:' : 'kissing_smiling_eyes',
			
			':stuck_out_tongue_winking_eye:' : 'stuck_out_tongue_winking_eye',

			':stuck_out_tongue_closed_eyes:' : 'stuck_out_tongue_closed_eyes',
			
			':stuck_out_tongue:' : 'stuck_out_tongue',

			':flushed:' : 'flushed',
			
			':grin:' : 'grin',

			':pensive:' : 'pensive',

			":relieved:" : 'relieved',

			':unamused:' : 'unamused',
			
			':disappointed:' : 'disappointed',
			
			':persevere:' : 'persevere',
			
			':cry:' : 'cry',

			':joy:' : 'joy',
			
			':sob:' : 'sob',

			':sleepy:' : 'sleepy',
			
			':disappointed_relieved:' :  'disappointed_relieved',
			
			':cold_sweat:' : 'cold_sweat',
			
			':sweat_smile:' : 'sweat_smile',

			':sweat:' : 'sweat',
			
			':weary:' : 'weary',

			':tired_face:' : 'tired_face',

			':fearful:' : 'fearful',

			':scream:' : 'scream',

			':angry:' : 'angry',
			
			':rage:' : 'rage',

			':triumph:' : 'triumph',

			':confounded:' : 'confounded',

			':laughing:' : 'laughing',

			':yum:' : 'yum',

			':mask:' : 'mask',

			':sunglasses:' : 'sunglasses',

			':sleeping:' : 'sleeping',

			':dizzy_face:' : 'dizzy_face',

			':astonished:' : 'astonished',

			':worried:' : 'worried',

			':frowning:' : 'frowning',

			':anguished:' : 'anguished',

			':smiling_imp:' : 'smiling_imp',

			':imp:' : 'imp',

			':open_mouth:' : 'open_mouth',

			':grimacing:' : 'grimacing',

			':neutral_face:' : 'neutral_face',

			':confused:' : 'confused',

			':hushed:' : 'hushed',

			':no_mouth:' : 'no_mouth',

			':innocent:' : 'innocent',

			':smirk:' : 'smirk',

			':expressionless:' : 'expressionless',

			':man_with_gua_pi_mao:' : 'man_with_gua_pi_mao',

			':man_with_turban:' : 'man_with_turban',

			':cop:' : 'cop',

			':construction_worker:' : 'construction_worker',

			':guardsman:' : 'guardsman',

			':baby:' : 'baby',

			':boy:' : 'boy',

			':girl:' : 'girl',

			':man:' : 'man',

			':woman:' : 'woman',
			
			':older_man:' : 'older_man',

			':older_woman:' : 'older_woman',

			':person_with_blond_hair:' : 'person_with_blond_hair',

			':angel:' : 'angel',

			':princess:' : 'princess',

			':smiley_cat:' : 'smiley_cat',

			':smile_cat:' : 'smile_cat',

			':heart_eyes_cat:' : 'heart_eyes_cat',

			':kissing_cat:' : 'kissing_cat',

			':smirk_cat:' : 'smirk_cat',

			':scream_cat:' : 'scream_cat',

			':crying_cat_face:' : 'crying_cat_face',

			':joy_cat:' : 'joy_cat',

			':pouting_cat:' : 'pouting_cat',

			':japanese_ogre:' : 'japanese_ogre',

			':japanese_goblin:' : 'japanese_goblin',

			':see_no_evil:' : 'see_no_evil',

			':hear_no_evil:' : 'hear_no_evil',

			':speak_no_evil:' : 'speak_no_evil',

			':skull:' : 'skull',

			':alien:' : 'alien',

			':hankey:' : 'hankey',

			':fire:' : 'fire',

			':sparkles:' : 'sparkles',

			':star2:' : 'star2',

			':dizzy:' : 'dizzy',

			':boom:' : 'boom',

			':anger:' : 'anger',

			':sweat_drops:' : 'sweat_drops',

			':droplet:' : 'droplet',

			':zzz:' : 'zzz',

			':dash:' : 'dash',

			':ear:' : 'ear',

			':eyes:' : 'eyes',

			':nose:' : 'nose',

			':tongue:' : 'tongue',

			':lips:' : 'lips',

			':+1:' : 'plus1',

			':-1:' : 'minus1',

			':ok_hand:' : 'ok_hand',

			':facepunch:' : 'facepunch',

			':fist:' : 'fist',

			':v:' : 'v',

			':wave:' : 'wave',

			':hand:' : 'hand',

			':open_hands:' : 'open_hands',

			':point_up_2:' : 'point_up_2',

			':point_down:' : 'point_down',

			':point_right:' : 'point_right',

			':point_left:' : 'point_left',

			':raised_hands:' : 'raised_hands',

			':pray:' : 'pray',

			':point_up:' : 'point_up',

			':clap:' : 'clap',

			':muscle:' : 'muscle',

			':walking:' : 'walking',

			':runner:' : 'runner',

			':dancer:' : 'dancer',

			':couple:' : 'couple',

			':family:' : 'family',
			
			':two_men_holding_hands:' : 'two_men_holding_hands',

			':two_women_holding_hands:' : 'two_women_holding_hands',

			':couplekiss:' : 'couplekiss',

			':couple_with_heart:' : 'couple_with_heart',

			':dancers:' : 'dancers',

			':ok_woman:' : 'ok_woman',

			':no_good:' : 'no_good',

			':information_desk_person:' : 'information_desk_person',

			':raising_hand:' : 'raising_hand',

			':massage:' : 'massage',

			':haircut:' : 'haircut',

			':nail_care:' : 'nail_care',

			':ride_with_veil:' : 'ride_with_veil',

			':person_with_pouting_face:' : 'person_with_pouting_face',
			
			':person_frowning:' : 'person_frowning',

			':bow:' : 'bow',

			':tophat:' : 'tophat',

			':crown:' : 'crown',

			':womans_hat:' : 'womans_hat',

			':athletic_shoe:' : 'athletic_shoe',

			':mans_shoe:' : 'mans_shoe',

			':sandal:' : 'sandal',

			':high_heel:' : 'high_heel',

			':boot:' : 'boot',

			':shirt:' : 'shirt',

			':necktie:' : 'necktie',

			':womans_clothes:' : 'womans_clothes',

			':dress:' : 'dress',

			':running_shirt_with_sash:' : 'running_shirt_with_sash',

			':jeans:' : 'jeans',

			':kimono:' : 'kimono',

			':bikini:' : 'bikini',

			':briefcase:' : 'briefcase',

			':handbag:' : 'handbag',

			':pouch:' : 'pouch',

			':purse:' : 'purse',

			':eyeglasses:' : 'eyeglasses',

			':ribbon:' : 'ribbon',

			':closed_umbrella:' : 'closed_umbrella',

			':lipstick:' : 'lipstick',

			':yellow_heart:' : 'yellow_heart',

			':blue_heart:' : 'blue_heart',

			':purple_heart:' : 'purple_heart',

			':green_heart:' : 'green_heart',

			':heart:' : 'heart',

			':broken_heart:' : 'broken_heart',

			':heartpulse:' : 'heartpulse',

			':heartbeat:' : 'heartbeat',

			':two_hearts:' : 'two_hearts',

			':sparkling_heart:' : 'sparkling_heart',

			':revolving_hearts:' : 'revolving_hearts',

			':cupid:' : 'cupid',

			':love_letter:' : 'love_letter',

			':kiss:' : 'kiss',

			':ring:' : 'ring',

			':gem:' : 'gem',

			':bust_in_silhouette:' : 'bust_in_silhouette',
			
			':busts_in_silhouette:' : 'busts_in_silhouette',

			':speech_balloon:' : 'speech_balloon',

			':footprints:' : 'footprints',

		    ':thought_balloon:' : 'thought_balloon'

			
		 	},
			
			
			// MEEPs
			meep: {

			'[m-)]' : '1.png',

			'[m-L]' : '2.png',

			'[m-D]' : '3.png',

			'[m-I]' : '4.png',

			'[m-C]' : '5.png',

			'[m-LK]' : '6.png',

			'[m-S]' : '7.png',

			'[m-R]' : '8.png',

			'[m-H]' : '9.png',

			'[m-P]' : '10.png',

			'[m-B]' : '11.png',

			'[m-PK]' : '12.png',

			'[m-HH]' : '13.png',

			'[m-DN]' : '14.png',

			'[m-O]' : '15.png',

			'[m-BL]' : '16.png',

			'[m-BR]' : '17.png',

			'[m-IC]' : '18.png',

			'[m-RUS]' : '19.png',

			'[m-MBA]' : '20.png',

			'[m-IB]' : '21.png',

			'[m-IOK]' : '22.png',

			'[m-GPP]' : '23.png',

			'[m-DS]' : '24.png',

			'[m-DM]' : '25.png',

			'[m-OPN]' : '26.png',

			'[m-BIF]' : '27.png',

			'[m-KVZ]' : '28.png',

			'[m-FRK]' : '29.png',

			'[m-BFL]' : '30.png',

			'[m-RKB]' : '31.png',

			'[m-LST]' : '32.png'
			},
			
			
	y_smilies: {
				
		    // happy
			':)' : '1',
			
			//sad
			':(' : '2',
			
			//winking
			';)' : '3',
			
			
			//big grin
			':d' : '4',
			
			//batting eyelashes
			':yah5:' : '5', 
			
			// big hug
			':yah6:' : '6', 
		

			
			// confused
			':yah7:' : '7', 
			
			
			// love struck
			':yah8:' : '8', 
		
			
			// blushing
			':yah9:' : '9', 
			
			// tongue
			':p' : '10', 
			
			// kiss
			':*' : '11', 
			
			// broken heart
			':yah12:' : '12', 
			
			
			// surprise
			':o' : '13', 
			
			
			// angry
			':yah14:' : '14', 
	
			
			// smug
			':yah15:' : '15', 
			
			// cool
			':yah16:' : '16', 
	
			
			// worried
			':yah17:' : '17', 
		 
			
			
			// whew!
			':yah18:' : '18', 

			
			// devil
			':yah19:' : '19',  	
			
			// crying
			':yah20:' : '20',  

			// laughing
			':yah21:' : '21', 
			
			
			// straight face
			':|' : '22', 
			
			// raised eyebrows
			':yah23:' : '23', 
			
			// rolling on the floor
			':yah24:' : '24', 
			
			// angel
			':yah25:' : '25', 
		 
			
			// nerd
			':yah26:' : '26', 
			 
			
			// talk to the hand
			':yah27:' : '27',

			// call me
			':yah28:' : '28',

			
			// on the phone
			':yah29:' : '29',
			
			
			// at wits' end
			':yah30:' : '30',

			
			// wave
			':yah31:' : '31',


			// timeout
			':yah32:' : '32',


			// day dreaming
			':yah33:' : '33',
			
			// sleepy
			':yah34:' : '34',
			
			
			// rolling eyes
			':yah35:' : '35',
			
			// loser
			':yah36:' : '36',
			
			// sick
			':yah37:' : '37',

			// don't tell anyone
			':yah38:' : '38',		
			
			
			// not talking
			':yah39:' : '39',	
			
			
			// clown
			':yah40:' : '40',		
			
			
			// silly
			':yah41:' : '41',	
			
			// party
			':yah42:' : '42',		

			// yawn
			':yah43:' : '43',	

			// drooling
			':yah44:' : '44',		

			// thinking
			':yah45:' : '45',	

			// d'oh
			':yah45' : '46',	
			
			// applause
			':yah47:' : '47',	
			
			// nail biting
			':yah48:' : '48',	

			// hypnotized
			':yah49:' : '49',	

			// liar
			':yah50:' : '50',		
			
			// waiting
			':yah51:' : '51',		
			
			// sigh
			':yah52:' : '52',	

			// phbbbbt
			':yah53:' : '53',				
			
		    // cowboy
			':yah54:' : '54',			

		    // i don't want to see
			':yah55:' : '55',		

		    // hurry up
			':yah56:' : '56',	

		    // rock on
			':yah57:' : '57',	
			
		    // thumbs down
			':yah58:' : '58',			


		    // thumbs up
			':yah59:' : '59',	
			
		    // it wasn't me
			':yah60:' : '60',	

		    // pirate
			':yah61:' : '61'
				
	},
	
	sticker:{
		// hacker-boy
		
		'hacker-boy':{
		
		':hkboy1:' : 'hkboy1',
		':hkboy2:' : 'hkboy2',
		':hkboy3:' : 'hkboy3',
		':hkboy4:' : 'hkboy4',
		':hkboy5:' : 'hkboy5',
		':hkboy6:' : 'hkboy6',
		':hkboy7:' : 'hkboy7',
		':hkboy8:' : 'hkboy8',
		':hkboy9:' : 'hkboy9',
		':hkboy10:' : 'hkboy10',
		':hkboy11:' : 'hkboy11',
		':hkboy12:' : 'hkboy12',
		':hkboy13:' : 'hkboy13',
		':hkboy14:' : 'hkboy14',
		':hkboy15:' : 'hkboy15',
		':hkboy16:' : 'hkboy16',
		':hkboy17:' : 'hkboy17',
		':hkboy18:' : 'hkboy18',
		':hkboy19:' : 'hkboy19',
		':hkboy20:' : 'hkboy20',
		':hkboy21:' : 'hkboy21',
		':hkboy22:' : 'hkboy22',
		':hkboy23:' : 'hkboy23',
		':hkboy24:' : 'hkboy24',
		':hkboy25:' : 'hkboy25',
		':hkboy26:' : 'hkboy26',
		':hkboy27:' : 'hkboy27',
		':hkboy28:' : 'hkboy28',
		':hkboy29:' : 'hkboy29',
		':hkboy30:' : 'hkboy30',
		':hkboy31:' : 'hkboy31',
		':hkboy32:' : 'hkboy32',
		':hkboy33:' : 'hkboy33',
		':hkboy34:' : 'hkboy34',
		':hkboy35:' : 'hkboy35',
		':hkboy36:' : 'hkboy36',
		':hkboy37:' : 'hkboy37',
		':hkboy38:' : 'hkboy38',
		':hkboy39:' : 'hkboy39',
		':hkboy40:' : 'hkboy40',
		':hkboy41:' : 'hkboy41',
		':hkboy42:' : 'hkboy42',
		':hkboy43:' : 'hkboy43'
		},
		
		
		// Cute cat
		'cute-cat': {
			
						':cutecat0:' : 'cutecat0',
						':cutecat1:' : 'cutecat1',
						':cutecat2:' : 'cutecat2',
						':cutecat3:' : 'cutecat3',
						':cutecat4:' : 'cutecat4',
						':cutecat5:' : 'cutecat5',
						':cutecat6:' : 'cutecat6',
						':cutecat7:' : 'cutecat7',
						':cutecat8:' : 'cutecat8',
						':cutecat9:' : 'cutecat9',
						':cutecat10:' : 'cutecat10',
						':cutecat11:' : 'cutecat11',
						':cutecat12:' : 'cutecat12',
						':cutecat13:' : 'cutecat13',
						':cutecat14:' : 'cutecat14',
						':cutecat15:' : 'cutecat15',
						':cutecat16:' : 'cutecat16',
						':cutecat17:' : 'cutecat17',
						':cutecat18:' : 'cutecat18',
						':cutecat19:' : 'cutecat19'
			
		}
		
	}
};

return create_emoji;
	
}

function emojipath(){
	return { 

			emoticons: smilies_path,
			y_smilies: smilies_path+'/y/',
			sticker: smilies_path+'/stickers/',
			meep: meep_path

			
			 };
}

function str_smilies(str){
	
var smilies_path = emojipath().emoticons, meep_path = emojipath().meep;

	var emoticons = createEmoji().emoticons, y_smilies = createEmoji().y_smilies;
	var stickers = createEmoji().sticker;

 // emoticons	
 var re = new RegExp(Object.keys(emoticons).join("|"),"gi");
	str = str.replace(re, function(matched){
		return '<span class="emotics emoji-spritesheet-0 emoji-code-bg-kn_'+emoticons[matched]+'">&nbsp;</span>';
	});
	
 // stickers
 var re = new RegExp(Object.keys(stickers).join("|"),"gi");
	str = str.replace(re, function(matched){
		return '<img src="/css/images/b/blank.gif" class="sticker hacker-boy sticker-spritesheet-0 sticker-code-bg-kn_'+stickers[matched]+'" alt="'+stickers[matched]+'" border="0" />';
	});
	
	
  // y_Smilies
  for (var i in y_smilies) {

        var x = new RegExp(escapeRegExp(i), "g");
	
        var smiley_img = '<img style="vertical-align:middle;" src="'+smilies_path+'/y/'+y_smilies[i]+'.gif" border="0">';
	
        str = str.replace(x, smiley_img);
    }
	
	
   return str;

}

function o_krypt(str)
{
	var ret = '';
	str = str.toString();
	for (var i = 0; i < str.length; i++)
	{
		switch (str[i])
		{
		case '1':
			ret += "@11";
			break;
		case '2':
			ret += "@21";
			break;
		case '3':
			ret += "@31";
			break;
		case '4':
			ret += "@41";
			break;
		case '5':
			ret += "@51";
			break;
		case '6':
			ret += "@61";
			break;
		case '7':
			ret += "@71";
			break;
		case '8':
			ret += "@81";
			break;
		case '9':
			ret += "@91";
			break;
		case '0':
			ret += "@01";
			break;
		}
	}
	return ret;
}

function x_krypt(str)
{
	return str.replace(/@11/g, 1)
		.replace(/@21/g, 2)
		.replace(/@31/g, 3)
		.replace(/@41/g, 4)
		.replace(/@51/g, 5)
		.replace(/@61/g, 6)
		.replace(/@71/g, 7)
		.replace(/@81/g, 8)
		.replace(/@91/g, 9)
		.replace(/@01/g, 0);
}
function isInArray(value, array) {
  return array.indexOf(value) > -1;
}
function isNumeric(n)
{
	return !isNaN(parseFloat(n)) && isFinite(n);
}

function isElementInViewport(el, plusHeight, minusHeight)
{

	//special bonus for those using jQuery
	if (typeof jQuery === "function" && el instanceof jQuery)
	{
		el = el[0];
	}
	if (typeof el != 'undefined'){
	var rect = el.getBoundingClientRect();
	if (minusHeight)
	{
		return (rect.top - minusHeight >= 0 && rect.left - minusHeight >= 0 && rect.bottom - minusHeight <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */ rect.right - minusHeight <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */ );
	}
	else if (plusHeight)
	{
		return (rect.top + plusHeight >= 0 && rect.left + plusHeight >= 0 && rect.bottom + plusHeight <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */ rect.right + plusHeight <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */ );
	}
	else
	{
		return (rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */ rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */ );
	}
	
	}
}

function ValidURL(str)
{
	var pattern = /(https?\:\/\/|\s)[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})(\/+[a-z0-9_.\:\;-]*)*(\?[\&\%\|\+a-z0-9_=,\.\:\;-]*)?([\&\%\|\+&a-z0-9_=,\:\;\.-]*)([\!\#\/\&\%\|\+a-z0-9_=,\:\;\.-]*)}*/i;
	return pattern.test(str) ? urlify(str) : false;
}

function urlify(text)
{
	var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	return text.replace(urlRegex, function (url)
	{
		return url;
	});
	// or alternatively
	// return text.replace(urlRegex, '<a href="$1">$1</a>')
}

function gUrl(str)
{
	return new RegExp("(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))", "g");
}

function getDomainExt(d)
{
	
	if(!ValidURL(d)) return false; else {
	
	var AllowDomains = ["aero", "biz", "cat", "com", "coop", "edu", "gov", "info", "int", "jobs", "mil", "mobi", "museum", "name", "net", "org", "travel", "ac", "ad", "ae", "af", "ag", "ai", "al", "am", "an", "ao", "aq", "ar", "as", "at", "au", "aw", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "bj", "bm", "bn", "bo", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", "cc", "cd", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr", "cs", "cu", "cv", "cx", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "ee", "eg", "eh", "er", "es", "et", "eu", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gb", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gp", "gq", "gr", "gs", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz", "la", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "me", "mc", "md", "mg", "mh", "mk", "ml", "mm", "mn", "mo", "mp", "mq", "mr", "ms", "mt", "mu", "mv", "mw", "mx", "my", "mz", "na", "nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr", "nu", "nz", "om", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "ps", "pt", "pw", "py", "qa", "re", "ro", "ru", "rw", "sa", "sb", "sc", "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "st", "su", "sv", "sy", "sz", "tc", "td", "tf", "tg", "th", "tj", "tk", "tm", "tn", "to", "tp", "tr", "tt", "tv", "tw", "tz", "ua", "ug", "uk", "um", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "vu", "wf", "ws", "ye", "yt", "yu", "za", "zm", "zr", "zw"];
	d = new URL(d)
		.hostname;
	var domain = d.split('.')
		.pop();
	if (AllowDomains.indexOf(domain) > -1) return true;
	else return false;
	}
	
}
function ex_string_number(a){
	
	return a.match(/\d/g).join("");
}
function url_domain(data)
{
	var a = document.createElement('a');
	a.href = data;
	return a.hostname;
}
function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function kn_liveNotif(title,m,timer,descr)
{
	
	var _notif_markup = '<section id="kn_notif_ge"> <div class="kn_notif_tr '+m+'"> <div class="ic ic_notif_close ic_close" title="'+lang.close+'"></div> <div class="ic ic_kn_live_notif"></div> <div class="kn_notif_sec"> <div class="kn_notif_title">'+title+'</div> <div class="kn_notif_descr">'+descr+'</div> </div> </div> </section>';
	var _bd = ga('body'), _prev_notif = _bd.find('#kn_notif_ge');
	
	_prev_notif.remove();
	

	
	if(!_prev_notif.length){
		
		_bd.append(_notif_markup);
		
		var removeIt_ntf = function(a){
			
			var _remove_func = function(){

				_bd.find('#kn_notif_ge > div:first').removeClass('__show').on(crossEvent, function (){
					ga(this).parent().remove();
				});
				
			}
			
			if(!a){
		setTimeout(function(){
			
			_remove_func();
			
		}, (timer ? timer : 5000));
			} else {
				
				_remove_func();
			}
		
		};
		
		setTimeout(function(){	_bd.find('.kn_notif_tr').addClass('__show').off('click.hideIt').on('click.hideIt', function(evt){
			
			evt.preventDefault();
			removeIt_ntf(1);
			
		});	},100);
		

			removeIt_ntf();
	}
	
	
}
function generateUrl(element)
{
	var $element = ga(element),
		href = $element.attr('href')
		.split('?'),
		url = href[0],
		data = href[1];
	if (typeof href == 'undefined') return displayErr(lang.somethingWrong + ' [tehnical error (split href)]');
	return [url, data];
}


// send friend request
function addFriend(el, ev, uid, v)
{
	ev.preventDefault();
	ev.stopImmediatePropagation();
	var g = generateUrl(el);
	ga(el)
		.addClass('__disabled');
	var send = jAjax(g[0], 'post', g[1] + '&type=pos&view_as=json');
	send.done(function (data)
	{ 
		var dData = validateJson(data);
		ga(el)
			.removeClass('__disabled');
		if (dData)
		{
			
			var disableReqBtn = function(){
				
								ga(el)
					.addClass('__disabled')
					.removeAttr('onclick')
					.attr('href', 'javascript:return false;')
					.text(lang.friend_req_send);
			};
			if (dData.response == 'open_notif' && v == 'knownpeople')
			{
				disableReqBtn();
				return false;
			}
			
			if(dData.response === 'already_friends'){
				disableReqBtn();
				return kn_liveNotif(lang.friend_request_was_not_sent,'warn',6000,lang.this_user_already_exist_into_your_friends_list);
			} else if (dData.response === 'open_notif'){
				disableReqBtn();
				return kn_liveNotif(lang.friend_request_already_sent,'info',6000,lang.friend_request_was_sent_please_wait_while_the_user_will_accept_it);
			}
			
			if (dData['response'] == '1')
			{
				ga(el)
					.addClass('__disabled default __request_sent').text(lang.friend_request_has_been_sent);
				if (v == 'knownpeople')
				{
					ga(el)
						.removeAttr('onclick')
						.attr('href', 'javascript:return false;')
						.text(lang.friend_req_send);
					return;
				}
				else if (v == 'button'){
					ga(el)
						.removeAttr('onclick').addClass('_disabled_button').text(lang.friend_req_send);
					return;
				}
				else
				{
					ga('#action_menu_friendship_request_sent')
						.removeClass('m_hidden');
					ga('#action_menu_set_relationship')
						.removeClass('m_hidden'); //.find('a:first').trigger('click');
				}

			}
			else if (dData['response'] == 'open_notif')
			{
				return ga('.toolbar_nav_notif_i_ic')
					.parent()
					.trigger('click');
			}
			else if (dData['response'] != '1' || dData['response'] != '0') return displayErr(dData['response']);
			else return displayErr(lang.somethingWrong);
		}
	});
}

function sendRate(obj, e, dataRate)
{  
	e.preventDefault();
	var rated_markup = '<div title="' + lang.your_rate_is + '" class="phlayer_rating_stars __exist_rating __dbld" id="phlayer_rating_stars">\
    <div id="star_already_rated_0_simulator" class="star_bg" style="position: absolute; top: 0px; left: #rate_bg#px; padding: 0px; margin: 0px; width: 120px; height: 24px; z-index: 0; background-position: -#rate_bg#px 0px;background-repeat: repeat-x;"></div>\
    <div id="star_already_rated_1_simulator" class="star_bg" style="position: absolute; top: 0px; left: 0px; padding: 0px; margin: 0px; width: #rate_bg#%; height: 24px; z-index: 1; background-position: 0px -24px;background-repeat: repeat-x;"></div>\
    <div class="phly_rating_inf"><div class="ic tico ic_voted_succ"></div><span class="phly_maxrw">%rated_sum%</span>/5 (from %rated_times% ratings)</div></div>';
	var $obj = ga(obj);
	var pid = escape($obj.closest('[data-photoc-id]')
		.data('photoc-id'));
	var stele = dataRate;
	if (stele == 255)
	{
		switch ($obj.css('width')
			.replace('px', ''))
		{
		case '24':
			stele = 1;
			break;
		case '48':
			stele = 2;
			break;
		case '72':
			stele = 3;
			break;
		case '96':
			stele = 4;
			break;
		case '120':
			stele = 5;
			break;
		}
	}
	
	var is_community = $obj.closest('#phlayer_rating_stars').hasClass('is_community')? '&clubid=1' : '';
	 
	var send_rate = jAjax('/profile', 'post', 'cmd=rateit&type=pos&itemid=' + pid + '&rate=' + stele + is_community);
	send_rate.done(function (s)
	{
		var s = validateJson(s);
		if (s.success)
		{
			$('#phlayer_ratings')
				.html(rated_markup.replace('%s', stele)
					.replace(/#rate_bg#/g, s.rate_bg)
					.replace('%rated_sum%', s.rate_value)
					.replace('%rated_times%', s.rate_times));
		}
	});
}
function removeThisNotif(t, e, b)
{
	e.preventDefault();
	var rn = function (a)
	{
		a.closest('.notif')
			.slideUp(300, function ()
			{
				$(this)
					.remove()
			});
	}
	if (b) return rn($(t));
	var $t = $(t);
	var u = generateUrl(t);
	var send = jAjax(u[0], 'post', u[1]);
	send.done(function (data)
	{
		var r = validateJson(data);
		if (r['response'] == '1')
		{
			rn($t);
		}
		else
		{
			return displayErr(lang.somethingWrong + ' [ err delete notif ]');
		}
	});
}

function removeNotifbyTrigXCLOSE(a)
{
	var $t = $(a)
		.closest('[data-category]');
	$t.find('.ic12_close-g')
		.trigger('click');
}


// remove guest
function hideFromGuests(ev, el)
{
	ev.preventDefault();
	ev.stopPropagation();
	var $el = ga(el);
	confirm_act(lang.hideGuest_confirm, function (event)
	{
		var uid = escape($el.data('hideguest'));
		var send = jAjax('/cmd.php', 'post', 'cmd=removeGuest&id=' + uid);
		send.done(function (res)
		{
			if (res === '1')
			{
				//$el.closest('.u_cardsList_li')
				ga('#gu_'+uid).remove();
			}
			else
			{
				displayErr(lang.unblock_err);
			}
		}); // ajax
	}); // confirmation
}
// delete album
function delete_album(event, obj, albumId)
{
	return confirm_act(lang.confirm_delete_album, function(){
	event.preventDefault();
	ajaxLoading();
	// escape
	var id = escape(albumId);
	var aj = jAjax('/profile.php', 'post', 'type=pos&cmd=deleteAlbum&i=' + id + '&view_as=json');
	aj.done(function (resp)
	{
		var res = validateJson(resp);
		if (res['response'] != '1') return displayErr(res['message']);
		else
		{
			ga('.toolbar_back').trigger('click');
		}
		removeAjaxLoad();
	});
	});
}




// create album
function doNewAlbum(form, ev, update)
{
	ev.preventDefault();
	var redBord = function (el, color)
	{
		!color ? el.css('border', '1px solid red')
			.focus() : el.css('color', 'red');
		removeAjaxLoad();
	}
	var r_redBord = function (el)
	{
		el.removeAttr('style');
	};
	ajaxLoading();
	var sendForm = js_subForm(form);
	sendForm.done(function (data)
	{  //alert(data);
		var d = validateJson(data);
		var alN = $('#albumNam'),
			vst = $('.p_me_nm'),
			alb_grid = $('.user_albums_grid'),
			alb_grid_first = alb_grid.children(':first');
		if (d['e_checkbox'] == '1' && d['e_albumname'] == '1')
		{
			redBord(vst, 1);
			redBord(alN);
			return;
		}
		else if (d['e_albumname'] == '1')
		{
			r_redBord(vst);
			redBord(alN);
			return;
		}
		else if (d['e_checkbox'] == '1')
		{
			r_redBord(alN);
			redBord(vst, 1);
			return;
		}
		if (d['response'] > 0 && !update)
		{
			/*var albMark = jAjax('/nav/profile/albumMarkup.html', 'get', '');
			albMark.done(function (html)
			{
				alb_grid_first.after(jprintf(html, d['uid'], d['response'], d['uid'], d['response'], d['name'], d['name']));
				// update ajax href link 
				up_href();
				alb_grid.find('a#album_location')
					.trigger('click');
			});
			removePopup();*/
 
 
			var $album_href = ga('<a hrefattr="true" href="/profile?q='+d.uid+'&cmd=album&i='+d.albumid+'&nav=photos"></a>');
			
			ga('#new_album_create').html($album_href);
			$album_href.trigger('click');
		}
		else if (d['response'] > 0 && update)
		{
			var thisAlbum = alb_grid.find('#a_' + update);
			thisAlbum.find('a:last')
				.text(d['name']);
			///thisAlbum.find('[data-album-ni]').attr({'data-album-c': d['checks'], 'data-album-ni': '{"name":"'+d['name']+'","id":"'+d['response']+'"}'});
			thisAlbum.find('[data-album-ni]>span')
				.text(lang.updated)
				.parent()
				.addClass('__disabled');
			thisAlbum.find('.ic_settings')
				.addClass('__updated');
			// for controls in album details
			var albumDetailContr = $('.photo-sc_grid_controls');
			albumDetailContr.find('#album_detail_set')
				.text(lang.updated)
				.parents('a')
				.addClass('__disabled')
				.removeAttr('onclick');
			albumDetailContr.find('.ic_settings')
				.addClass('__updated');
			$('#alb_detail_title')
				.text(d['name']);
			removePopup();
		}
		else
		{
			return displayErr(lang.errCreateAlbum);
		}
		removeAjaxLoad();
	});
}

// confirmation dialog
function confirm_act(text, callback, l)
{
	window.navigator.vibrate(200); 
	if(confirm(text)){
		
		
		callback();
	}
	
}
// restore video
function restoreVideo(element, evt)
{
	evt.preventDefault();
	var $el = ga(element),
		hrf = $el.attr('href')
		.split('?'),
		url = hrf[0],
		data = hrf[1];
	var aj = jAjax(url, 'post', data);
	aj.done(function (data)
	{
		var d = validateJson(data);
		if (d.s !== 1)
		{
			return displayErr(d.s);
		}
		else
		{
			$el.closest('.ec_items.vd')
				.removeClass('__deleted')
				.find('.disabling-layer')
				.removeClass('__on');
			$el.closest('.ec_items.vd')
				.find('.vd_add_descr_field')
				.show();
			// for profile video album
			$el.closest('.u_video_gal')
				.removeClass('__deleted notOvr')
				.find('.disabling-layer')
				.removeClass('__on');
			$el.closest('.u_video_gal')
				.find('.user_video_control')
				.show();
		}
	});
}
// delete video
function deleteVideo(el, evt, clubid)
{
	evt.preventDefault();
	var $el = ga(el),
		hrf = $el.attr('href')
		.split('?'),
		url = hrf[0],
		data = hrf[1];
		var vid = $el.attr('rel-videoid');
	var aj = jAjax(url, 'post', data);
	aj.done(function (data)
	{
		
		
		var d = validateJson(data);
		
		
		if ( clubid ) {
			
			if (d.s === 1) {
				
				
				$el.closest('.ec_items.vd.icommunity').slideUp(function(){ga(this).remove()});
				$el.closest('[rel="communityWallItem"]').remove();
				$el.closest('.community_upload_video_process').slideUp(function(){ga(this).remove()});
				//communityAlbumPicturesWall(1);
			} else {
				
				return displayErr(lang.community_video_err_delete);
				
			}
			
			
			return;
		}
		
		
		
		if (d.s === 1)
		{
			$el.closest('.ec_items.vd')
				.addClass('__deleted')
				.find('.disabling-layer')
				.addClass('__on');
			$el.closest('.ec_items.vd')
				.find('.vd_add_descr_field')
				.hide();
			 
			// for profile video album
			ga('#vd_gal_'+vid)
				.addClass('__deleted notOvr')
				.find('.disabling-layer')
				.addClass('__on');
			ga('#vd_gal_'+vid)
				.find('.user_video_control')
				.hide();
		}
		else return displayErr(d.s);
	});
}

// delete photo definitive
function deleteImgDefinitive(ev){
	var el = ga(ev.target);
return confirm_act(lang.confirm_delete_img_definitive,function(evt){
	
	var data = {};
	
	data['cmd'] = 'deleteimagedefinitive';
	data['picid'] = el.attr('id').split('df_img_i|')[1];
	var send = jAjax('/cmd.php', 'post', data);
	send.done(function(data){

		if(data === '1'){
		el.closest('.pmob_item.dlalb').fadeOut(function(){ga(this).remove();});
			
		} else if (data === '404'){
			return displayErr(lang.delete_picture_definitive_not_found);
			
		} else 
			return displayErr(lang.err_tehnic);
		
	});
});
}
function X_validateUpload(elem){
	var _validFileExtensions = [];

	elem = elem instanceof jQuery ? elem.val() : ga(elem).val();
	
	for(var k=0; k < _st.photoTypes.length;k++) 
	_validFileExtensions.push('.'+_st.photoTypes[k]);


	if(!elem.hasExtension(_validFileExtensions))
		return false;//displayErr('Error at uploading these files');
	else 
		return true;
}

function validateUpload(elem){
	
		elem = elem instanceof jQuery ? elem : ga(elem);
		elem = elem
		.val()
		.replace(/C:\\fakepath\\/i, "")
		.split('.')
		.pop()
		.toLowerCase();
		
			if ( $.inArray(elem, _st.photoTypes) == -1 && $.trim(elem) )
			return false;
			else
				return true;
	
	
}
function newCommunityPage(){
 
if ( ga('#new_club_page').length ) {
	// general categories
	ga(document).off('selectmenuchange.createGroup').on( "selectmenuchange.createGroup", '#field_groups_select', function( ev, ui ) { 

    ga('[data-submenuselect="1"]').each(function(){ga(this).selectmenu( "widget" ).hide();});
	ga('[submenuselect]').each(function(){ga(this).selectmenu( "widget" ).hide();});

	ga('#comm_category,#comm_subcategory').val('');
	ga(ui.item.value).selectmenu( "widget" ).show();
	
	 ga('#comm_general_category').val(ui.item.index);
	
	
	});

	
	// categories
	ga(document).off('selectmenuchange.createGroupGetSubcateg').on( "selectmenuchange.createGroupGetSubcateg", '.comm_hidden_select_1,.comm_hidden_select_2', function( ev, ui ) { 
//community_add_location();
    ga('[submenuselect]').each(function(){ga(this).selectmenu( "widget" ).hide();});

	ga('[data-subcategb="'+ui.item.value+'"]').selectmenu( "widget" ).show();
	ga('#comm_category').val(ui.item.value);
	
	if(ga('[data-subcategb="'+ui.item.value+'"]').length)
	ga('#community_hidden_inputs').append('<input type="hidden" id="comm_subcategory" value="" />'); 
	else ga('#comm_subcategory').remove();
	
	});
	
	// subcategories
	
	ga(document).off('selectmenuchange.createGroupGetSubcategs').on( "selectmenuchange.createGroupGetSubcategs", '[name="comm_subcateg"]', function( ev, ui ) { 

	ga('#comm_subcategory').val(ui.item.value);
	
	});
	
	
	/* birthday */
	ga(document).off('selectmenuchange.createGroupBirthdayDay').on( "selectmenuchange.createGroupBirthdayDay", '[name="day"]', function( ev, ui ) { 

	ga('#community_bd_day').val(ui.item.value);
	
	});
	ga(document).off('selectmenuchange.createGroupBirthdayMonth').on( "selectmenuchange.createGroupBirthdayMonth", '[name="month"]', function( ev, ui ) { 

	ga('#community_bd_month').val(ui.item.value);
	
	});
	ga(document).off('selectmenuchange.createGroupBirthdayYear').on( "selectmenuchange.createGroupBirthdayYear", '[name="year"]', function( ev, ui ) { 

	ga('#community_bd_year').val(ui.item.value);
	
	});
	
	
	
	
ga('select').selectmenu();
ga(".comm_hidden_select_1").selectmenu( "widget" ).hide();
ga('.comm_hidden_select_2').selectmenu( "widget" ).hide();
ga('.comm_hidden_sub_select_family').selectmenu( "widget" ).hide();
ga('.comm_hidden_sub_select_music').selectmenu( "widget" ).hide();
ga('.comm_hidden_sub_select_bhealth').selectmenu( "widget" ).hide();
ga('.comm_hidden_sub_select_communication_services').selectmenu( "widget" ).hide();
ga('.comm_hidden_sub_select_celebrity').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_culture_art').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_entertainment').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_internet').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_products_stores').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_restaurants').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_sport').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_transportation_services').selectmenu('widget').hide();

 
}
	
}
// callback when a css animation end
function endAnimationEvent(){
	
			var t;
            var el = document.createElement('fakeelement');
            var animation = {
                'animation': 'animationend',
                'OAnimation': 'oAnimationEnd',
                'MSAnimation': 'MSAnimationEnd',
                'WebkitAnimation': 'webkitAnimationEnd'
            };
            for (t in animation) {
                if (el.style[t] !== undefined) {
                    return animation[t];
                }
            }
			
}
function profilePhotoWallAppendNewCont(data, appTo)
{

	if (data)
	{
		appTo.append(data.content)
			.justifiedGallery('norewind');
	}
}
function hideLeftMenu(){
	ga('body').removeClass('lm_opened');
}
function profileUpdateStatus(evt,el){
	
	var max_status_length = 190;
	var rand = randomIntFromInterval(9, 9999);
	var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.profile_leave_status_msg+'","rand":"'+rand+'"}\'></a>');
	
	ga('body').prepend(a_mob_popup);
	a_mob_popup.trigger('click');
	a_mob_popup.remove();
	
	var cur_status = ga('#user_profile_status').html() || '';
	var user_update_status = '<div class="pcont fit_box bl_cont">\
    <div class="owner_panel profile_panel">\
        <img src="/getPhoto?p='+_U.p+'&sz=small" class="op_fimg">\
        <div class="op_fcont">\
            <h2 class="op_header">'+_U.n+'</h2>\
        </div>\
        <div class="pp_edit_status">\
            <div class="pointer"><i class="i_pointer"></i></div>\
                <div class="iwrap">\
				<div class="emoji-wysiwyg-editor" contenteditable="true" id="user_new_status_text" data-input-length="190" autofocus="autofocus">'+cur_status+'</div>\
                <div class="pp_buttons_block"><div id="new_msg_Status_err"></div>\
                    <input type="submit" class="button" id="profile_add_status_btn" value="'+lang.Save+'">\
                </div>\
        </div>\
    </div>\
</div>';
	
	
	var m_popupcnt = ga('.mob_popup_cnt#id_'+rand);
	
	m_popupcnt.html(user_update_status);
	
	hideLeftMenu();
	
	
    m_popupcnt.find('#profile_add_status_btn').off('click.addStatusMsg').on('click.addStatusMsg',function(e){
		
		var new_msg_Status_err = ga('#new_msg_Status_err');
		var status_contenteditable = ga('#user_new_status_text');
		var ok = true, err_msg = '';
		
		
		// check for status length
		if(  status_contenteditable.text().length > max_status_length) {
			
			ok = false;
			err_msg = lang.profile_status_msg_too_long;
			
		}
		
		if( !ok ){
			
			
			new_msg_Status_err.css('display','block').text(err_msg);
			
		} else {
			
			new_msg_Status_err.hide().empty();
			ga('#user_add_status_msg .uasm_pd').prepend('<div class="layer_ovr" style="background:rgba(239, 239, 239, 0.48)!important"></div>');
			
			ga('#profile_add_status_btn').hide().after('<div class="div-loader"></div>');
			
			 
			var send = jAjax('/cmd.php', 'post', {cmd:'user_save_profile_status',value: status_contenteditable.text()});
			send.done(function(d){
				
				if(d == 'status_err_add') {
					
					 
					ga('#profile_add_status_msg').show();
					ga('.div-loader').hide();
					new_msg_Status_err.css('display','block').text(lang.profile_add_status_msg_err);
				} else {
					
					// success
					ga('#mobile_popup_back_btn').trigger('click');
					if(d != '') ga('.pp_no_status_link').html(d);
					else ga('.pp_no_status_link').text(lang.profile_leave_status_msg);
				}
				
				
			});
			
		}
		
	});
	
	
	
}
/*
function photoViewerGetCommentsMarkup(author, allow_edit, edited, can_be_edited, abia)
{
var phlayer_comm_markup = '<li class="comment %OPK% %REPLY% %DISPLAY%" data-aria-visible="%DISPLAY%" id="comment_%comm_id%">' + 

'<div class="comment-icon circle-icon ">' +

'<span class="kn_shortcutmenu">	<span class="hookDataShortcut" data-shortcutmenudata=\'{"uid":"%author_id%","uname":"%author_name%","uphoto":"%author_photo%","ugender":"male","ulmen":{"photo":"0","guest":"0","block":"0","unblock":"0","unfriend":"0"}}\' id="hook_ShortcutMenu_%author_id%"></span>'+
 
 '<a href="/user/%author_id%">' +
 
 '<img title="%author_name%" alt="%author_name%" src="/getPhoto?p=%author_photo%&sz=small&g=%author_gender%" width="32" height="32">' + 
 
 '</a></span>' + '</div>' 
 
 + '<div class="comment-pcont"><div class="comment-header-author"><p class="comment-author">' + 

 '<span class="kn_shortcutmenu">	'+

'<span class="hookDataShortcut" data-shortcutmenudata=\'{"uid":"%author_id%","uname":"%author_name%","uphoto":"%author_photo%","ugender":"male","ulmen":{"photo":"1","guest":"0","block":"0","unblock":"0","unfriend":"0"}}\' id="hook_ShortcutMenu_%author_id%"></span>'+

'<a title="%author_name%" class="ellip" href="/user/%author_id%" hrefattr="true"><span data-authorname>%author_name%</span>'

+'</a></span></p></div>' + 

 '<div class="comment-pi-body"><div class="comment-content">%comment%</div>'+

'<div class="comment-footer"><span class="phlayer_comm_posting_progress ' + (abia ? '' : '__none') + ' _55yn _55yo _55ym"></span>' 

+ '<span class="comment-date" title="%ADDED_TITLE%">%comment_date%</span>' 

+ '<span class="' + (edited ? '__visible __opac1' : '') + ' comm_actions_report_edit __toRight">' + (author === _U.i && allow_edit && !edited && can_be_edited ? '<a href="javascript:;" data-comments-in="%COMMENTS_IN%" onclick="return comment_edit(this,event);" class="comment-edit ic tico_img icon-comment-edit" title="Edit"></a>' : '') + (edited && !can_be_edited ? '<a href="#" onclick="event.preventDefault();return;" class=" comment-edit ic tico_img icon-comment-edit-upd" title="%EDITED_AT%"></a>' : '') + (author !== _U.i ? '<a href="javascript:;" onclick=\'var _thissobj = {"uid":' + _U.i + ',"id":"%comm_id%","type":"comment"}; return windowsPopup("report",_thissobj);\' class="comment-report mlr_top_ac_i ic12 ic12_warn ic tico_img ic-comm-report" title="Report"></a>' : '') + '</span>' 

+ '<span class="comment-actions">' 

+ '<span class="comment-likes %liked_view%">' 

+ '<span class="comm_reply_count" title="%replies_count% reply">%replies_count%</span><a href="javascript:void(0);" ' 

+ (author === _U.i ? 'curDefault' : 'onclick="return replyToComment(this,event,\'%COMMENTS_IN%\');"') 

+ ' class="' + (author === _U.i ? 'curDefault' : '') + ' comment-reply ic tico_img icon-comment-reply" title="Reply"></a>' 

+ '<span class="comm_ics_bullet">&#8226;</span>'
+'<a href="javascript:;" onclick="commentLike(this,event)" class="%cur_default% comment-like glyphicon glyphicon-heart" title="Like"></a>' 

+ '<span data-commi="%comm_id%" class="comm_likes_count">%likes_count%</span>' 

+ '</span>' 

+ '</span>' 

+ '</div>'+
'<div class="comment-footer-lk-reply"></div>'+
'</div>' 
 
 + '</div></li>';
	return phlayer_comm_markup;
}
*/

function photoViewerGetCommentsMarkup(author, allow_edit, edited, can_be_edited, abia)
{
var phlayer_comm_markup = '<li class="comment %OPK% %REPLY% %DISPLAY%" data-aria-visible="%DISPLAY%" id="comment_%comm_id%">' + '<div class="comment-icon circle-icon ">' +
'<span class="kn_shortcutmenu">	<span class="hookDataShortcut" data-shortcutmenudata=\'{"uid":"%author_id%","uname":"%author_name%","uphoto":"%author_photo%","ugender":"male","ulmen":{"photo":"0","guest":"0","block":"0","unblock":"0","unfriend":"0"}}\' id="hook_ShortcutMenu_%author_id%"></span>'+
 '<a href="/user/%author_id%">' +
 '<img title="%author_name%" alt="%author_name%" src="/getPhoto?p=%author_photo%&sz=small&g=%author_gender%" width="32" height="32">' +
 '</a></span>' + 
 '</div>' + 
 '<p class="comment-author">' + 
'<span class="kn_shortcutmenu">	<span class="hookDataShortcut" data-shortcutmenudata=\'{"uid":"%author_id%","uname":"%author_name%","uphoto":"%author_photo%","ugender":"male","ulmen":{"photo":"1","guest":"0","block":"0","unblock":"0","unfriend":"0"}}\' id="hook_ShortcutMenu_%author_id%"></span><a title="%author_name%" class="ellip" href="/user/%author_id%" hrefattr="true"><span data-authorname>%author_name%</span></a></span>' + 
'<span class="phlayer_comm_posting_progress ' + 
(abia ? '' : '__none') + ' _55yn _55yo _55ym"></span>' + 
'<span class="comment-date" title="%ADDED_TITLE%">%comment_date%</span>' + 
'<span class="' + (edited ? '__visible __opac1' : '') + 
' comm_actions_report_edit __toRight">' + 
(author === _U.i && allow_edit && !edited && can_be_edited ? '<a href="javascript:;" data-comments-in="%COMMENTS_IN%" onclick="return comment_edit(this,event);" class="comment-edit ic tico_img icon-comment-edit" title="Edit"></a>' : '') + 
(edited && !can_be_edited ? '<a href="javascript:void(0);" onclick="event.preventDefault();return;" class=" comment-edit ic tico_img icon-comment-edit-upd" title="%EDITED_AT%"></a>' : '') + 
(author !== _U.i ? '<a href="javascript:;" onclick=\'var _thissobj = {"uid":' + _U.i + ',"id":"%comm_id%","type":"comment"}; return windowsPopup("report",_thissobj);\' class="comment-report mlr_top_ac_i ic12 ic12_warn ic tico_img ic-comm-report" title="Report"></a>' : '') + 
'</span>' + 
 '</p>' +
 '<div class="comment-content">%comment%</div>' + 
 
 '<div class="comment_bottom"><div class="comment-actions">' + 
'<div class="comment-likes ">' + 

'<a href="javascript:void(0);" onclick="return replyToComment(this,event,\'%COMMENTS_IN%\');" class="comment-reply" title="'+lang.Reply+'"><i class="ic tico_img icon-comment-reply"></i>'+lang.Reply+'</a>' + 
'<span class="comm_reply_count" title="%replies_count% reply">%replies_count%</span>'+
 '<span class="comm_ics_bullet">&#8226;</span><span class="comment_likes_count_js %liked_view%"><a href="javascript:;" onclick="commentLike(this,event)" class="comment-like" title="'+lang.Like+'"><i class="ic tico_img icon-comment-like"></i>'+lang.Like+'</a>' +
 '<span data-commi="%comm_id%" class="comm_likes_count">%likes_count%</span></span>' + 
 '</div>' + 
 '</div></div>' + 
 
 
 '</li>';
	
	
	return phlayer_comm_markup;
}
function jbFeedTooltip($el)
{
	if ($el.length)
	{
		var gHTMLCont = $el.data('getjs');
		var th_tooltip_more = $el.data('tooltipmore');
		var feedId = $el.data('feedid');
		var doneHhtml = '';
		var markup_u_cn = '<div class="f_liked_tooltip"><a href="/user/%uid" hrefattr="true"><img src="/getPhoto?p=%photo&sz=small&g=%gender"><span>%name</span></a></div>';
		for (var i = 0; i < gHTMLCont.length; ++i)
		{
			var a = gHTMLCont[i];
			doneHhtml += markup_u_cn.replace(/%photo/, a.photo)
				.replace(/%uid/, a.id)
				.replace(/%name/, a.name)
				.replace(/%gender/, a.gender);
		}
		if (th_tooltip_more)
		{
			doneHhtml += '<a class="eshyo_c_friends" onclick="return feed_liked_popup(this,' + feedId + ');" href="javascript:;">' + lang.All + '&nbsp;' + th_tooltip_more + '&nbsp;' + (th_tooltip_more === 1 ? lang.friend : lang.friends) + '</a>';
		}
		$el.jBox('Tooltip',
		{
			closeOnMouseleave: true,
			animation: 'zoomIn',
			content: doneHhtml, //theme:'TooltipDark',
			trigger: 'mouseenter',
			//position: {x: 'center', y: 'bottom'},
			outside: 'y',
			pointer: true,
			adjustPosition: true,
			reposition: true
		});
	}
}
function loadAttach($cont)
{
	$cont.find('.mdialog_atch_items_container')
		.children()
		.each(function ()
		{
			var $this = ga(this);
			var $this_im = $this.find('i');
			if (isElementInViewport($this_im) && $this_im.hasClass('__default'))
			{ 
				$this_im.removeClass('__default')
					.addClass('__loaded')
					.css('background-image', 'url(' + $this_im.data('imageu') + ')');
			}
		});
}
	function PollVote(evt){
		var total;
	var width,html = "",label = "";
	var _this = ga(evt.target);
	var p_cnt = _this.closest('.poll-container')
	var _question_id = p_cnt.attr('id').split('mzv|')[1];

		var ans = p_cnt.find('.options input[type=radio]:checked').val();
		var p_opts = p_cnt.find('.options');
		if(ans){
			poll_loading(p_cnt);
			$.ajax({
				type: "POST", 
				url: "/cmd.php", 
				data : "cmd=pollvote&quid="+escape(_question_id)+"&ans="+ans,
				dataType:"json",
				success: function(response){
					poll_loading(p_cnt,'stop');
					
					html = "<div class='result' style='display:none'>";
					total = response.total; 

					if(response.success == 1){
						$.each(response.opt, function(aid,label) {
							if(response.details[aid] == undefined){
								width  = 0
								acount = 0
							}else{
								acount = response.details[aid];
								width = Math.round((parseInt(acount)/parseInt(total)) * 100); 
							}							
							html += '<div class="bar-holder">'+label+' ('+acount+' votes)<div class="perc"></div><div class="bc"><div class="bar" style="width:'+width+'%">'+width+'% &nbsp;</div></div></div>';
						});
						html += '</div>';
						html += '<p><span class="total">Total votes : <b>'+total+'</b></span>';
						
						p_opts.html(html);
						p_cnt.find('.sub').remove();
						p_cnt.find(".result").slideDown();
					}else if (response.success == 2){
						
						kn_liveNotif(lang.already_voted_in_poll,'done',6000,lang.already_voted_in_poll_descr);
					}else{
						kn_liveNotif(lang.err_vote_poll,'error',6000,lang.err_vote_poll_descr);
					}
				}
			});
			
		}
	}
	function is_gif_image(i) {
    return /^(?!data:).*\.gif/i.test(i.src);
}

function freeze_gif(i) {
    var c = document.createElement('canvas');
    var w = c.width = i.width;
    var h = c.height = i.height;
    c.getContext('2d').drawImage(i, 0, 0, w, h);
    try {
        i.src = c.toDataURL("image/gif"); // if possible, retain all css aspects
    } catch(e) { // cross-domain -- mimic original with all its tag attributes
        for (var j = 0, a; a = i.attributes[j]; j++)
            c.setAttribute(a.name, a.value);
        i.parentNode.replaceChild(c, i);
    }
}

function hideBooksPgSugg(el) {
	
	if( $.trim(ga(el).val()) == '')
	{
		
				ga('#books_list').html('');
				ga('.bookspg_search_res').removeAttr('style');
	}
	
}
function hideMoviesPgSugg(el) {
	
	if( $.trim(ga(el).val()) == '')
	{
		
				ga('#movie_list').html('');
				ga('.movies-author-search-ul-while').removeAttr('style');
	}
	
}
function profileAddBooks(result) {
	
		var r = validateJson(result); 
		var book_markup = '';
		var book_not_found = '<div style="text-align:center;">'+lang.lang_book_not_found+'</div>';
		
		
		if( r.hasOwnProperty('items') ){
		
		if( r.items.length > 0 ) {
		for( var i =0; i < r.items.length;i++){
			
			
			var book = r.items[i];
			var bookInfo = book.volumeInfo;
			var poster = bookInfo.hasOwnProperty('imageLinks') ? '/bookGetPoster?p='+encodeURIComponent(bookInfo.imageLinks.smallThumbnail) : '/bookGetPoster?p=nope'; 
			var title = bookInfo.title;
			var book_about = bookInfo.hasOwnProperty('description') ? bookInfo.description : '';
			var book_about = bookInfo.hasOwnProperty('authors') ? lang.book_authors_sugg+':&nbsp;'+bookInfo.authors : '';
			var book_id = book.id;
			
			book_markup += '<li><div class="hookData __none"><!--'+JSON.stringify(book)+'--></div><a href="javascript:void(0);" data-sug-id="'+book_id+'" data-suggest-categ="'+encodeURIComponent(title)+'" onclick="userAddBook(this,event,1);" class="sc_suggestion_movie_a"><div class="sc_suggestion_cover" style="background-image:url('+poster+')"></div><div class="sc_suggestion_str"><div class="sc_suggestion_title">'+title+'</div><div class="sc_suggestion_info">'+book_about+'</div></div></a></li>';
			
			
		} 
		
		
		
		} else book_markup = book_not_found;

		} else book_markup = book_not_found;	
			
		if(ga('html').hasClass('bookspg')){
			
			if(book_markup !== book_not_found) {
				
				ga('.bookspg_search_res').css('height','240px')
				ga('#books_list').html(book_markup);
			} else {
				ga('#books_list').html('');
				ga('.bookspg_search_res').removeAttr('style');
				
			}				
				
		
			
		} else {
		
		ga('#books_list').html(book_markup);
		}
		nanoScrollStart();
		
		
}function userAddMovieToWatched(el,event,clone){
	
	el = ga(el);
	var movie_json = objHook(el.parent().find('.hookData').html());
	
	var send = jAjax('/cmd.php', 'post', { 'cmd': 'addmovietouser', 'movie':JSON.stringify(movie_json) });
	
	send.done(function(d) { 

		if(clone){
			
			
			if(ga('#user-profile-view').length){
				
				var movies_scroll_slider = ga('.uslider_cnt._movies');
				var movie_markup = '<li class="prof_movie_item _replies__highlight"><a href="/page/movie/'+d+'/" hrefattr="true"><div class="movie_cover" style="background-image:url(/movieGetPoster?p='+encodeURIComponent(movie_json.poster_path)+')"></div><div class="movie_title">'+movie_json.original_title+'</div></a></li>';
			
			    movies_scroll_slider.scrollLeft(0);
				movies_scroll_slider.prepend(movie_markup);
			}
			
			if (ga('.movies_pg').length){
				var movies_while = ga('.movies_ul_while');
				var movie_markup = '<li class="prof_movie_item relative movie_pg_li _replies__highlight"><a href="/page/movie/'+d+'/" hrefattr="true"><div class="movie_cover" style="background-image:url(/movieGetPoster?p='+encodeURIComponent(movie_json.poster_path)+')"></div><div class="movie_title">'+movie_json.original_title+'</div></a></li>';
				ga('[rel="input_search_movies"]').val('').trigger('keyup');
				
				setTimeout(function(){
				movies_while.prepend(movie_markup);
				},500);
			}
			
			up_href();
		}

	});
}
function profileAddMovies(result){
	
		 
		
		var r = validateJson(result);
		var movies_markup = '';
		var movie_not_found = '<div style="text-align:center;">'+lang.lang_movie_not_found+'</div>';
		
		
		 
		if( r.results.length > 0 ) {
		for( var i =0; i < r.results.length;i++){
			
			
			var movie = r.results[i];
			var poster = '/movieGetPoster?p='+movie.poster_path; 
			var title = movie.original_title;
			var movie_about = movie.overview;
			var movie_id = movie.id;
			
			movies_markup += '<li><div class="hookData __none"><!--'+JSON.stringify(movie)+'--></div><a href="javascript:void(0);" data-sug-id="'+movie_id+'" data-suggest-categ="'+encodeURIComponent(title)+'" onclick="userAddMovieToWatched(this,event,1);" class="sc_suggestion_movie_a"><div class="sc_suggestion_cover" style="background-image:url('+poster+')"></div><div class="sc_suggestion_str"><div class="sc_suggestion_title">'+title+'</div><div class="sc_suggestion_info">'+movie_about+'</div></div></a></li>';
			
			
		} 
		} else movies_markup = movie_not_found;
		 
		
		
		if(ga('.movies_pg').length){
			
			if(movies_markup !== movie_not_found) {
				
				ga('.movies-author-search-ul-while').css('height','240px')
				ga('#movie_list').html(movies_markup);
			} else {
				ga('#movie_list').html('');
				ga('.movies-author-search-ul-while').removeAttr('style');
				
			}				
				
		
			
		} else {
		
		ga('#movie_list').html(movies_markup);
		}
		
		
		
		nanoScrollStart();

	
}
function bookPageSearchFor(el,evt){
	
	evt.preventDefault();
	
	var b_search = ga('#add_books_to_col_popup');
	
	if( !b_search.length) {
		
		var m = '<section id="add_books_to_col_popup"><div class="layer_ovr"></div>\
		<div class="bookspg_add_to_col_box">\
		<h3>'+lang.search_for_books+'</h3><span id="close_flying_notification_box" class="tico tico__n-t notifs_close"><i class="tico_img ic ic_close"></i></span>\
		<div class="books_pp_searc_cnt">\
		\
<div class="map_select_sugg_subcateg nano">\
				<div class="nano-content"><div class="input_serch_ic"><input type="text" class="it" rel="input_search_books" search-callback="mapBooksRes" placeholder="ex. Brothers Grimm" value="" /><i class="div-loader input-ic-loader __none"></i></div>\
				 <ul id="movie_list"></ul></div>\
	</div>\
		\
		</div>\
		</div></section>';
		
		ga('.books_pg').prepend(m);
		
	}
	
}

function usersBooksPage() {
 
	
	if( ga('.books_pg').length) {
		 
		ga('html').scrollTop(0).addClass('bookspg');
		
		 
	
	} else {
	 
		ga('html').removeClass('bookspg');
 
	}
	
	
	
	
}

function userAddBook(el,event,clone){
	
	el = ga(el);
	var book_json = objHook(el.parent().find('.hookData').html());
	
	var send = jAjax('/cmd.php', 'post', { 'cmd': 'addbooktouser', 'book':JSON.stringify(book_json) });
	
	send.done(function(d) { 
	
	
		if(clone){
			
			
			var book = book_json;
			var bookInfo = book.volumeInfo;
			var poster = bookInfo.hasOwnProperty('imageLinks') ? '/bookGetPoster?p='+encodeURIComponent(bookInfo.imageLinks.smallThumbnail) : '/bookGetPoster?p=nope'; 
			var title = bookInfo.title;
			
			
			
			if(ga('#user-profile-view').length){
				 
				
				
				var books_scroll_slider = ga('.uslider_cnt._books');
				var book_markup = '<li class="prof_book_item _replies__highlight">\
										<a href="/page/book/'+d+'/" hrefattr="true">\
										<div class="book_cover" style="background-image:url('+poster+')"></div>\
										<div class="book_title">'+title+'</div>\
										</a>\
									</li>';
			
			    books_scroll_slider.scrollLeft(0);
				books_scroll_slider.prepend(book_markup);
			}
			
		if(ga('html').hasClass('bookspg')){
			
				var books_scroll_slider = ga('html');
				var book_markup = '<li class="prof_book_item _replies__highlight">\
										<a href="/page/book/'+d+'/" hrefattr="true">\
										<div class="book_cover" style="background-image:url('+poster+')"></div>\
										<div class="book_title">'+title+'</div>\
										</a>\
									</li>';
			ga('[rel="input_search_books"]').val('').trigger('keyup');
			 setTimeout(function(){

   			    books_scroll_slider.scrollTop(0);
				ga('.user-books-while').prepend(book_markup);
			 },1000);
			
		}
			
			
			up_href();
		}

	
	
	
	});
}
function searchMovies(key){
	

var send = jAjax('/cmd.php', 'post', { 'cmd':'search-movies', 'key' : key });

return send;
	
}
function searchTracks(key){
	

var send = jAjax('/cmd.php', 'post', { 'cmd':'postSearchMusic', 'key' : key });

return send;
	
}
function searchBooks(key){
	

var send = jAjax('/cmd.php', 'post', { 'cmd':'search-books', 'key' : key });

return send;
	
}
function jsonAddSlashes(str){
	
return (str + '')
    .replace(/[\\"']/g, '\\$&')
    .replace(/\u0000/g, '\\0')

}
(function($){
   $.fn.innerText = function(msg) {
         if (msg) {
            if (document.body.innerText) {
               for (var i in this) {
                  this[i].innerText = msg;
               }
            } else {
               for (var i in this) {
                  this[i].innerHTML.replace(/&amp;lt;br&amp;gt;/gi,"n").replace(/(&amp;lt;([^&amp;gt;]+)&amp;gt;)/gi, "");
               }
            }
            return this;
         } else {
            if (document.body.innerText) {
               return this[0].innerText;
            } else {
               return this[0].innerHTML.replace(/&amp;lt;br&amp;gt;/gi,"n").replace(/(&amp;lt;([^&amp;gt;]+)&amp;gt;)/gi, "");
            }
         }
   };
})(jQuery);
function getStoriesAjax(){
	 
	var send = jAjax('/stories.php','post',{'cmd':'getStoriesAjax'});
	send.done(function(d){
	 
		ga('#stories-wall').html(d);

	});
	
}
function getWall(obj, filt, blr)
{
	
	var fbk_loader_markup = '<div class="_4-u2 mbm _2iwp _4-u8"><div style="height:%spx;" class="_2iwo"><div class="_2iwq"><div class="_2iwr"></div><div class="_2iws"></div><div class="_2iwt"></div><div class="_2iwu"></div><div class="_2iwv"></div><div class="_2iww"></div><div class="_2iwx"></div><div class="_2iwy"></div><div class="_2iwz"></div><div class="_2iw-"></div><div class="_2iw_"></div><div class="_2ix0"></div></div></div></div>';
	var hookWall = ga('#hook_feed_wl_pg'),
		_slider_space = ga('#_slider_space');
	var fd_cont = ga('section#hook_feed_wl_pg .feed');
	var filter = filt ? '&filter=' + escape(filt) : '';
	var obj = obj ? ga(obj) : '';
	var id = '';
	var _feed_sh_mr_btn = ga('.link-show-more');
	
	// hide "show more" btn while loading the wall
	_feed_sh_mr_btn.hide();

	var sliderActiveUser = function (){
		
			ga('.nb-carousel.__active').removeClass('__active');
			obj.closest('.nb-carousel').addClass('__active');
		
		
	}
	
	if (filter)
	{
		obj.parent()
			.find('a.__active')
			.removeClass('__active');
			
		obj.addClass('__active');
		 
		
		if (filt == 'certain')
		{	var _favorite_item_id = escape(obj.data('fvid').split('_')[1]);
			id = '&i=' + _favorite_item_id;
			filter = '&filter=favorite';
			_w_sliders = 1;
			sliderActiveUser();
			hookWall.removeAttr('data-groupid').attr('data-uprofile',_favorite_item_id);
		}
		else if (filt == 'certain2')
		{	var _favorite_item_id = escape(obj.data('fvid').split('_')[1]);
			id = '&i=' + _favorite_item_id;
			filter = '&filter=friends';
			_w_sliders = 1;
			sliderActiveUser();
			 
			hookWall.removeAttr('data-groupid').attr('data-uprofile',_favorite_item_id);
		}
		else if (filt == 'certain3')
		{	var _favorite_item_id = escape(obj.data('fvid').split('_')[1]);
			id = '&i=' + _favorite_item_id;
			filter = '&filter=groups';
			_w_sliders = 1;
			sliderActiveUser();
			 
			hookWall.removeAttr('data-uprofile').attr('data-groupid',_favorite_item_id);
		}
	}
	else
	{ 
		hookWall.removeAttr('data-uprofile');
		hookWall.removeAttr('data-groupid');
		ga('.mob_feed_filter_dropdown a.__active')
			.removeClass('__active');
		ga('.mob_feed_filter_dropdown a:first')
			.addClass('__active');
	}
	
	
	
	var wall_interval = setInterval(function ()
	{
		if (hookWall.length != 0)
		{
			clearInterval(wall_interval);
			if (!blr)
			{
				if (ga('body')
					.find('#index_wall_n')
					.length)
				{
					//for(var i = 0; i < 6; i++) hookWall.addClass('__two_columgap __mt8').append(fbk_loader_markup.replace('%s',randomIntFromInterval(300,350)));//addClass('__loading_wall');
				}
				else
				{
					hookWall.addClass('__loading_wall');
				}
			}
			else
			{
				// fd_cont.addClass('__blur4');
				hookWall.empty();
				for (var i = 0; i < 4; i++) hookWall.addClass(' __mt8')
					.append(fbk_loader_markup.replace('%s', 313)); //addClass('__loading_wall');
				
			
			}
			
			setTimeout(function ()
			{
				var is_my_profile = ga('#_wall_itsme')
					.length ? '&me=1' : '';
					
				var profile_id = ga('#wprofileid').length ? '&uid='+escape(ga('#wprofileid').val()) : '';	
			 
				var req = jAjax('/profile', 'post', 'cmd=wall' + profile_id + id + filter + is_my_profile + '&token=' + ((new Date())
					.getTime()) + '&type=pos&view_as=json');
				req.done(function (data)
				{   
					var jData = validateJson(data);
					getStoriesAjax();

				
					if(jData.content === '[END]'){
						
						
						if( hookWall.hasClass('u_prof_redesign_feed') ){
							
							hookWall.removeClass('__loading_wall').html('<div class="wall_no_results"><span>'+lang.empty_feed+'</span></div>');
							
						}
						else {
						
						ga('.feed-top-nav .filter_i:not(.__active)').remove();
						var getEmptyFeed = jAjax('/cmd.php', 'post', 'cmd=emptyfeed');
						getEmptyFeed.done(function(data){
							
						
						hookWall.html(data);	
						
						
						

					//arrgFeedBlocks();		
					

						
						
						
						});
						}
						
						return;
						
					  
					}
				
				
				
					// remove sliders from DOM
					 if ( filt != 'certain' && filt != 'certain2' ) {_slider_space.empty();}
					 else if ( filt === 'certain' && ga('.w_slider._friends').length )  { _slider_space.empty();}
					 else if ( filt === 'certain2' && ga('.w_slider._favorite').length )  {_slider_space.empty();}
					

					if (jData)
					{

						if (!filter) hookWall.html(jData['content']);
						else
						{
							 hookWall.html(jData['content']);
 
							// append sliders in wall, only for [favorite && friends] categ
							if(!_slider_space.children().length) _slider_space.html(jData['page']);
						}
						hookWall.removeClass('__loading_wall __mt8');
						fd_cont.removeClass('__blur4');
						up_href();
						///onlineBlock(1);
						if(filt === 'friends') ga('.nb-carousel:first>a').trigger('click');
						
						
					
						
						// jbox title 
						jbFeedTooltip(ga('.feed_lk_oth_fr'));
						
						// show "load more" btn
						if(hookWall.find('.feed').length) setTimeout(function(){_feed_sh_mr_btn.fadeIn();},1000);
						
						// add css class "float:left" to the feed blocks
						setTimeout(function(){
							
							///if(hookWall.hasClass('__two_columgap')) ga('.feed').addClass('__fleft');
							
						if(hookWall.find('.feed').length <= 1) {ga('.feed').hide(); setTimeout(function(){ga('.feed').show();},200);}
							
						},200);
						
						
						ga('[data-jboxmouse="1"]')
							.each(function ()
							{
								jboxMouse(ga(this));
							});
							
						// create collage for user profile theme
						setTimeout(function(){
							
							feedThemeCollage();
						},10);
							
						setTimeout(function ()
						{  
							// build map
							if (ga('#hook_feed_wl_pg')
								.find('.map-box')
								.length) ga('#hook_feed_wl_pg')
								.find('.map-box')
								.each(function ()
								{
									var _t_data_ka = ga(this)
										.find('.hookMapData')
										.html();
									var d_lc_map_dt = objHook(_t_data_ka);
									postPopupBuildMap(_t_data_ka, 'feed-tip-map-loc-' + d_lc_map_dt['pl-i']);
								});
						}, 100);
						setTimeout(function ()
						{
							// build comments
							hookWall.find('.feed_cnt')
								.each(function ()
								{
									var $this = ga(this);
									var $this_feed_data = validateJson(ga(this)
											.attr('id')),
										$feed_id = $this_feed_data.fid,
										$author_id = $this_feed_data.uid;
									$this.removeAttr('id')
										.attr('id', 'feed_cnt_' + $feed_id);
									var $after_app = ga('<div/>')
										.attr('id', 'feed_post_comments_section_' + $feed_id);
									$this.closest('.feed')
										.find('.feed_f')
										.after($after_app);
									/*	commentsWidget($feed_id,
										$after_app,
										'post',
										{'width':279,'height':'auto','min-height':20,'overflow':'hidden','padding':'3px 74px 2px 7px'},
										'',
										'#feed_cnt_'+$feed_id,$author_id,'2',1);*/
								});
						}, 200);
						wallPhotosCollage(hookWall, function ()
						{
							// $("#hook_feed_wl_pg").find('.feed').css({'float':'left','display':'inli});
							// build feeeeeeeeed
							//arrgFeedBlocks();
						});
						if(ga(".__two_columgap").length){
					//	setTimeout(function(){ajaxLoading()},200);
						///setTimeout(function(){arrgFeedBlocks();removeAjaxLoad();},2000);
						}
						// pause video
						var _p_video_nvw = function (){
							
								ga('body')
									.find('.__vdplaying')
									.each(function ()
									{
										if (!isElementInViewport(ga(this))) ga(this)
											.closest('.mejs-container')
											.find('.mejs-playpause-button>button')
											.trigger('click');
									});
							
						}
						
						// vegas themes
						
						var _p_slideshow_stop_vw = function(){
							var _vegas_infeed = hookWall.find('.feed_fr_slideshow');
							if(_vegas_infeed.length){
			 
								generateVegasTheme(1);
								_vegas_infeed.each(function(){
									 
									if (!isElementInViewport(ga(this))) ga(this).vegas('pause'); else ga(this).vegas('play');
									
									
								});
							}
						}
						
						
						
						// pause video if isn't in viewport or browser tab is not active
						//ga(window).off('blur.videoPause').on('blur.videoPause',_p_video_nvw);
						ga([window, document]).off('onfocusout.videoPause').on('onfocusout.videoPause',_p_video_nvw);
						ga(window)
							.off('scroll.videoVport')
							.on('scroll.videoVport',_p_video_nvw);
							
						// pause slideshow if isn't in viewport
						ga(window)
							.off('scroll.slideshowPause')
							.on('scroll.slideshowPause', _p_slideshow_stop_vw);
							
						ga(window)
							.off('scroll.feedComments')
							.on('scroll.feedComments', function ()
							{
								var $feed_comments_widget = hookWall.find('.feed_post_comments_widget');
								$feed_comments_widget.each(function ()
								{
									if (isElementInViewport(ga(this))) ga(this)
										.show();
								});
							});
						// add pause button, if playing a track from feed
						if ($.socplusMusic)
						{
							if (typeof audio != 'undefined' && audio.playing)
							{
								var playing_id = ga('#audioTag')
									.attr('track-id');
								ga('#hook_Block_MiddleColumnTopCardUser')
									.find('.track_play#' + playing_id)
									.addClass('m_portal_track_pause');
							}
						}
						
							userFeed();
					}
				});
			}, 100);
		}
	}, 10);
}


function vFriendReq(e, t, m)
{
	e.preventDefault();
	var $t = ga(t),
		freq = $t.data('freq')
		.split('-'),
		fId = escape($t.attr('id')
			.split('_')[3]);
	if (typeof freq == 'undefined') return displayErr(lang.somethingWrong);
	ajaxLoading();
	var send = jAjax('/profile', 'post', 'q=' + escape(m) + '&cmd=vFriendReq&i=' + fId + '&ph=' + escape(freq[0]) + '&nt=' + escape(freq[1]) + '&type=pos&view_as=json');
	send.done(function (data)
	{
		var d = validateJson(data);
		var $notif = $t.closest('.notif');
		// accept request
		if (d['response'] == '1' && m)
		{
			$notif.find('.notif_ac.fade-on-hover')
				.remove();
			$notif.addClass('__accept')
				.find('.notif_tx')
				.addClass('__accept')
				.find('.become_friend_text')
				.html('&nbsp;' + lang.yarfriend);
			$t.closest('.notif_btn')
				.replaceWith('<a class="r_not" href="/profile?cmd=removeNotif&i=' + escape(d['notif_id']) + '&type=pos&view_as=json" onclick="removeThisNotif(this,event)">' + lang.close + '</a>');
			ga('#action_menu_friendship_request_confirm')
				.remove();
			// ignore request
		}
		else if (d['response'] == '1' && !m)
		{
			ga('#send_friend_req_btn_green')
				.removeClass('m_hidden');
			ga('#action_menu_friendship_request_confirm')
				.remove();
			removeThisNotif($t[0], e, 1);
		}
		else
		{
			return displayErr(lang.somethingWrong);
		}
		removeAjaxLoad();
	});
}
// filter friends by certain letter
function fr_flt_b_lt(o, event)
{
	event.preventDefault();
	var $o = ga(o);
	_gl_filter_by_letter = $o.text()
		.toUpperCase();
	checkLetterInDom();
	if (!ga('#hook_alpha .__loader')
		.length) ga('#hook_alpha')
		.append('<div class="light_modal_01"><div class="lmbd4"></div></div>');
}
// get alpha
function friendsAlphabetList(o, e)
{
	e.preventDefault();
	var $o = ga(o),
		$b = ga('body');
	var uid = $o.data('alphui')
		.split(')')[1];
		
		
		
		// open mobile popup
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.Back+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();	
		
		var cont = ga('.mob_popup_cnt#id_'+rand);
		
		
		
		
		
	var s = jAjax('/profile', 'post', 'cmd=getAlpha&i=' + escape(uid) + '&type=pos');
	s.done(function (r)
	{
		if (r == 'NODATA') cont.html(lang.no_friends);
		else
		{
			
 cont.html(r);
			setTimeout(function ()
			{
				cont.find('.drk-modal_1000')
					.addClass('__col');
					ga([document,window]).off('keyup.kAlpha click.kAlpha')
					.on('keyup.kAlpha click.kAlpha', function (e)
					{
						if (e.type == 'click' || e.keyCode == 27) removeMobilePopupFromDom(rand);
					});
				cont.find('.ulistanim')
					.addClass('__outz');
			}, 10);
		}
	});
}
function buyVotes(){
			// open mobile popup
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.Back+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();	
		
		var cont = ga('.mob_popup_cnt#id_'+rand);
   
   
   
		var send = jAjax('/cmd.php','post',{
				cmd: 'buy-votes'
			});
			
			send.done(function(data){
				cont.html(data);
				
			});
 
	
}
// keep visible header of active letter
function AlphaKeepVisible(e)
{
	e.preventDefault();
	var l = ga('.letter_header');
	var top_header = $('.toolbar');
	if (!l.length) return;
	var m = l.offset()
		.top;
	var b = 0;
	//$('[data-ltn]').removeClass('__active').css('top','auto');
	l.each(function ()
	{
		var $this = $(this);
		$this.removeClass('__active fixed_always')
			.css(
			{
				'top': 'auto'
			});
		//$this.removeClass('__active').css('transform','translate3d(0,0,0)');
		//if(top_header.offset().top+($('.toolbar').height()/2)+(l.height()/2)+10 >= $(this).offset().top && !$this.hasClass('__active'))
		if (top_header.offset()
			.top + top_header.height() >= $(this)
			.offset()
			.top) $this.addClass('__active fixed_always')
			.css(
			{
				'top': '48px'
			}); ///css('top', ($(window).scrollTop() - $this.offset().top) + $('.toolbar').height());//css('transform' , 'translate3d(0,'+($(window).scrollTop() - $this.offset().top) + $('.toolbar').height()+'px,0)');//'+='+(top_header.offset().top + l.offset().top) - ($('body').scrollTop()));
		/*
		if($this.offset().top + $this.outerHeight() >= $('[data-ltn]:eq('+($this.index()+1)+')').offset().top){
		//$this.css('top','-='+$this.offset().top + $this.outerHeight() - $('[data-ltn]:eq('+($this.index()+1)+')').offset().top);//$('[data-ltn]:eq('+($this.index()+1)+')').css('background','red');
		////alphaHeadMoveSlow($this,$('[data-ltn]:eq('+($this.index()+1)+')'),top_header);
		}*/
		//$this.addClass('__active').css('transform','translate3d(0, '+($(window).scrollTop() - $this.offset().top) + $('.toolbar').height()+'px ,0)')
		$this.removeClass('__active');
	});
}
// build months
function getMonthsDays(uday)
{
	var m = '';
	for (var i = 1; i < 32; i++) m += '<option ' + (uday == i ? 'selected="selected"' : '') + ' value="' + i + '">' + i + '</option>';
	return m;
}
// build years
function getYears(uyear)
{
	var y = '';
	for (var i = 1925; i < cur_year - 15; i++) y += '<option ' + (uyear == i ? 'selected="selected"' : '') + ' value="' + i + '">' + i + '</option>';
	return y;
}
//get 12 months
function getMonths(uMonths)
{
	return '<option ' + (uMonths == 1 ? 'selected="selected"' : '') + ' value="1">' + lang.january + '</option>\
                                <option ' + (uMonths == 2 ? 'selected="selected"' : '') + ' value="2">' + lang.february + '</option>\
                                <option ' + (uMonths == 3 ? 'selected="selected"' : '') + ' value="3">' + lang.march + '</option>\
                                <option ' + (uMonths == 4 ? 'selected="selected"' : '') + ' value="4">' + lang.april + '</option>\
                                <option ' + (uMonths == 5 ? 'selected="selected"' : '') + ' value="5">' + lang.may + '</option>\
                                <option ' + (uMonths == 6 ? 'selected="selected"' : '') + ' value="6">' + lang.june + '</option>\
                                <option ' + (uMonths == 7 ? 'selected="selected"' : '') + ' value="7">' + lang.july + '</option>\
                                <option ' + (uMonths == 8 ? 'selected="selected"' : '') + ' value="8">' + lang.august + '</option>\
                                <option ' + (uMonths == 9 ? 'selected="selected"' : '') + ' value="9">' + lang.september + '</option>\
                                <option ' + (uMonths == 10 ? 'selected="selected"' : '') + ' value="10">' + lang.october + '</option>\
                                <option ' + (uMonths == 11 ? 'selected="selected"' : '') + ' value="11">' + lang.november + '</option>\
                                <option ' + (uMonths == 12 ? 'selected="selected"' : '') + ' value="12">' + lang.december + '</option>';
}
// slide up current opened settings tab
function slideUpSettingsTab(el, ev)
{
	ev.preventDefault();
	var $el = $(el);
	var pSect = $el.closest('section');
	var aActHr = $el.closest('[data-stcateg]');
	aActHr.removeClass('__active')
		.find('.user-settings_i_lk')
		.fadeIn();
	pSect.slideUp();
}

function updateNewBirthDayInput(el, ev, a)
{
	var $el = $(el);
	switch (a)
	{
	case 'day':
		$('#hidden_fUpd_D')
			.val($(el)
				.val());
		break;
	case 'month':
		$('#hidden_fUpd_M')
			.val($(el)
				.find('option[value="' + $(el)
					.val() + '"]')
				.text());
		break;
	case 'year':
		$('#hidden_fUpd_Y')
			.val($(el)
				.val());
		break;
	}
	localStorage.setItem('pinfoUpd', 1);
}

function wSpace(s)
{
	return /\s/g.test(s);
}
function savePersonalInformationForm(e, f)
{
	e.preventDefault();
	var field_bday = ga("#field_bday"),
		field_bmonth = ga("#field_bmonth"),
		field_byear = ga("#field_byear");
	var field_location = ga("#stfr_location"),
		field_location_approved = ga("#location_selected_from_list");
	if (!$.trim(field_bday.val()) || !$.trim(field_bmonth.val()) || !$.trim(field_byear.val())) return updInfoErr('.__bd', lang.pleaseSelectYourBirthDate);
	else if ( !$.trim(field_location.val()) || !$.trim(ga('#location_id').val())) 
		return updInfoErr(field_location, lang.pleaseEnterYourCountry);
	
	ajaxLoading();
	var sendForm = js_subForm(f);
	sendForm.done(function (data)
	{  
		removeAjaxLoad();
		if (data == 2) return updInfoErr(field_location, lang.pleaseEnterACountryFromDropDownList);
		//else if (data == 3) return updInfoErr(field_location, lang.pleaseEnterACityFromDropDownList);
		else if (data == 4) return kn_liveNotif(lang.err_update_uname,'warn',6000,lang.err_update_uname_descr);
		else if (data == 5) return kn_liveNotif(lang.err_update_surname,'warn',6000,lang.err_update_surname_descr);
		else if (data == 6) return kn_liveNotif(lang.err_surname_is_same_as_name,'warn',6000,lang.err_surname_is_same_as_name_descr);
		else if (data == 1)
		{
			if (localStorage.getItem('pinfoUpd'))
			{
				ga('#update_birthday')
					.text(ga('#hidden_fUpd_M')
						.val() + ' ' + ga('#hidden_fUpd_D')
						.val() + ' ' + ga('#hidden_fUpd_Y')
						.val());
				localStorage.removeItem('pinfoUpd');
			}
			ga('#user_location')
				.text(field_location
					.val());
 
			ga('#cancel_stPI_form')
				.trigger('click');
			updInfoErr('.__bd', null, 1);
			updInfoErr(field_location, null, 1);
		}
		else return displayErr(lang.err_tehnic);
	});
}
function saveNickName(e, f)
{
	e.preventDefault();
	var nickInput = $('#nickname_update');
	var currPass = $('#stfr_must_pass');
	if (!$.trim(nickInput.val()) || wSpace(nickInput.val()) || /^\d+$/.test(nickInput.val()))
	{
		return updInfoErr(nickInput, lang.pleaseEnterAvalidNickName);
	}
	else if (!$.trim(currPass.val()))
	{
		return updInfoErr(currPass, lang.pleaseEnterYourPassword);
	}
	else if ($.trim(nickInput.val()))
	{
		updInfoErr(nickInput, null, 1);
		ajaxLoading();
		var sendForm = js_subForm(f);
		sendForm.done(function (data)
		{
			removeAjaxLoad();
			if (data == 2) return updInfoErr(currPass, lang.incorrectPass);
			if ($.trim($('#nickname_update')
					.val()) && data == 1)
			{
				$('#updated_nickname')
					.removeAttr('style')
					.text($('#nickname_update')
						.val());
				$('#block2_cancel_stPI_form')
					.trigger('click');
				currPass.val('');
				updInfoErr(currPass, null, 1);
			}
			else return displayErr(lang.err_tehnic);
		});
	}
}


function updateNewPassword(e, f)
{
	e.preventDefault();
	var old_pass_input = $('#pass_update'),
		new_pass_input = $('#newpass_update'),
		re_pass_input = $('#repass_update');
	if (!$.trim(old_pass_input.val())) return updInfoErr(old_pass_input, lang.pleaseEnterYourPassword);
	else if (!$.trim(new_pass_input.val())) return updInfoErr(new_pass_input, lang.pleaseChooseANewPassword);
	else if (!$.trim(re_pass_input.val())) return updInfoErr(re_pass_input, lang.passDontMatch);
	else if (re_pass_input.val() !== new_pass_input.val()) return updInfoErr(re_pass_input, lang.passDontMatch);
	else if (new_pass_input.val()
		.length < 6) return updInfoErr(new_pass_input, lang.newPasswordIsTooShort);
	ajaxLoading();
	var sendForm = js_subForm(f);
	sendForm.done(function (data)
	{
		removeAjaxLoad();
		if (data == 2) return updInfoErr(old_pass_input, lang.yourOldPassIsIncorrect);
		else if (data == 3) return updInfoErr(new_pass_input, lang.newPasswordIsTooShort);
		else if (data == 4) return updInfoErr(re_pass_input, lang.passDontMatch);
		else if (data == 1)
		{
			$('#pass_update,#newpass_update,#repass_update')
				.val('');
			updInfoErr(old_pass_input, null, 1);
			updInfoErr(new_pass_input, null, 1);
			updInfoErr(re_pass_input, null, 1);
			$('#block3_cancel_stPI_form')
				.trigger('click');
			setTimeout(function ()
			{
				window.location = '/?logme=passChanged';
			}, 10);
		}
		else return displayErr(lang.err_tehnic);
	});
}


// edit personal information
function editGeneralSettings(el, evt)
{
	var $el = $(el),
		$BBD_HTLM;
	var cmd = $el.data('stcateg');
	if ($el.find('section')
		.length && $el.find('section')
		.is(':visible'))
	{
		//evt.preventDefault();
		evt.stopPropagation();
		return;
	}
	ga('[data-stcateg].__active')
		.each(function ()
		{
			var block_l_a = $(this)
				.find('div:last');
			slideUpSettingsTab(block_l_a, evt);
		});
	$el.addClass('__active')
		.find('.user-settings_i_lk')
		.hide();
	switch (cmd)
	{
	case 'personalInfo':
		var exUserBirthDay = _U.b.split('-');
		var thisUserDay = exUserBirthDay[2],
			thisUserMonth = exUserBirthDay[1],
			thisUserYear = exUserBirthDay[0];
		$BBD_HTLM = '<section class="st_pifo_upd"><form method="post" id="save_personal_information_form" autocomplete="off" action="/cmd.php">\
			<input name="cmd" value="savePersonalInformation" type="hidden" />\
			<input type="hidden" id="hidden_fUpd_D" value="' + thisUserDay + '" />\
			<input type="hidden" id="hidden_fUpd_M" value="' + thisUserMonth + '" />\
		    <input type="hidden" id="hidden_fUpd_Y" value="' + thisUserYear + '" />\
			<div class="form form__gl-2-2 __settings">\
            <div class="form_i">\
			<span class="input-l"><label for="field_name">' + lang.Name + '</label></span>\
            <div class="it_w">\
            <input type="text" name="fr.name" value="' + _U.fn + '" class="it" maxlength="16">\
            </div><span class="input-e"></span></div>\
			\
			<div class="form_i">\
			<span class="input-l"><label for="field_name">' + lang.Surname + '</label></span>\
            <div class="it_w">\
            <input type="text" name="fr.surname" value="' + _U.sn + '" class="it" maxlength="16">\
            </div><span class="input-e"></span></div>\
			\
			<div class="form_i"><span class="input-l"><label for="field_bday">' + lang.Date_Of_Birth + '</label></span>\
                                <table class="input-flx-f ">\
                                    <tbody>\
                                        <tr>\
                                            <td class="input-flx-f__padding-r ">\
                                                <select onchange="updateNewBirthDayInput(this,event,\'day\');" name="fr.bday" id="field_bday" class="isl isl__day">\
                                                    <option value="">' + lang.day + '</option>\
													' + getMonthsDays(thisUserDay) + '\
                                                </select>\
                                            </td>\
                                            <td class="input-flx-f__padding-r">\
                                                <select onchange="updateNewBirthDayInput(this,event,\'month\');" name="fr.bmonth" id="field_bmonth" class="isl">\
                                                    <option value="">' + lang.month + '</option>\
													' + getMonths(thisUserMonth) + '\
                                                </select>\
                                            </td>\
                                            <td class="input-flx-f__padding-r">\
                                                <select onchange="updateNewBirthDayInput(this,event,\'year\');" name="fr.byear" id="field_byear" class="isl isl__4num">\
													<option value="">' + lang.year + '</option>\
													' + getYears(thisUserYear) + '\
                                                </select>\
                                            </td>\
                                        </tr>\
                                    </tbody>\
                                </table><span class="input-e __bd"></span></div>\
			 \
			 <div class="form_i"><span class="input-l"><label for="field_gender">' + lang.Im + '</label></span>\
             <ul class="form_ul form_ul__inline">\
             <li class="form_ul_li">\
             <input class="irc" type="radio" name="fr.gender" value="1" id="field_gender_1" ' + (_U.g == 'male' ? 'checked="checked"' : '') + '><span class="irc_l"><label for="field_gender_1">' + lang.Male + '</label></span></li>\
             <li class="form_ul_li">\
             <input class="irc" type="radio" name="fr.gender" value="2" id="field_gender_2" ' + (_U.g == 'female' ? 'checked="checked"' : '') + '><span class="irc_l"><label for="field_gender_2">' + lang.Female + '</label></span></li>\
             </ul><span class="input-e"></span></div>\
			\
			<div class="form_i">\
			<span class="input-l"><label for="field_name">' + lang.Location + '</label></span>\
            <div class="it_w">\
			<input id="stfr_location" autocomplete="off" name="location_name" placeholder="'+ lang.location_name_eg +'" class="it getuserlocation" type="text" value="'+_U.loc_name+'" />\
			<input type="hidden" name="location_id" id="location_id" value="'+_U.loc_id+'" /><input type="hidden" id="settings_approved_location" name="location_approved" value="1" class="yes" />\
            </div><span class="input-e"></span></div>\
			\
			</div>\
			<div class="notif_btn __settings">\
			<button onclick="return savePersonalInformationForm(event,$(\'form#save_personal_information_form\'));" type="submit" class="button-pro __def __small mr-8">' + lang.Save + '</button>\
			<a href="javascript:;" id="cancel_stPI_form" onclick="return slideUpSettingsTab(this,event);" class="">' + lang.Cancel + '</a>\
			</div></form>\
			</section>';
		break;
	case 'nickname':
		$BBD_HTLM = '<section class="st_pifo_upd"><form method="post" id="save_nickname_form" action="/cmd.php">\
			<input name="cmd" value="saveNickName" type="hidden" />\
			<div class="form form__gl-2-2 __settings">\
            <div class="form_i">\
			<span class="input-l"><label for="field_name">' + lang.Nickname + '</label></span>\
            <div class="it_w">\
            <input type="text" id="nickname_update" onkeypress="if(event.keyCode == 32) event.preventDefault();" name="fr.nick" value="' + _U.nick + '" class="it" maxlength="48">\
            </div><span class="input-e"></span></div>\
			\
			<div class="form_i">\
			<span class="input-l"><label for="field_name">' + lang.CurrentPassword + '</label></span>\
            <div class="it_w">\
            <input type="password" name="fr.pass" id="stfr_must_pass" class="it">\
            </div><span class="input-e"></span></div>\
			<div class="notif_btn __settings">\
			<button onclick="return saveNickName(event,$(\'form#save_nickname_form\'));" type="submit" class="button-pro __def __small mr-8">' + lang.Save + '</button>\
			<a href="javascript:;" id="block2_cancel_stPI_form" onclick="return slideUpSettingsTab(this,event);" class="">' + lang.Cancel + '</a>\
			</div></form></section>';
		break;
		
	case 'phone':
		$BBD_HTLM = '<section class="st_pifo_upd"><form method="post" id="save_phone_form" action="/cmd.php">\
			<input name="cmd" value="savePhone" type="hidden" />\
			<div class="form form__gl-2-2 __settings">\
            <div class="form_i">\
			<span class="input-l"><label for="phone_update">' + lang.reg_phone + '</label></span>\
            <div class="it_w">\
            <input type="text" autocomplete="off" data-user-country="'+_U.country_code+'" placeholder="'+lang.reg_phone_placeholder+'" id="phone_update" onkeypress="if(event.keyCode == 32) event.preventDefault();" name="fr.phone" value="" class="phone-input it" maxlength="20">\
            <input type="hidden" name="phone_number" id="js_phone_number" value="" /></div><span class="input-e"></span></div>\
			\
			<div class="form_i">\
			<span class="input-l"><label for="field_name">' + lang.CurrentPassword + '</label></span>\
            <div class="it_w">\
            <input type="password" name="fr.pass" id="p_stfr_must_pass" class="it">\
            </div><span class="input-e"></span></div>\
			<div class="notif_btn __settings">\
			<button onclick="return savePhone(event,$(\'form#save_phone_form\'));" type="submit" class="button-pro __def __small mr-8">' + lang.Save + '</button>\
			<a href="javascript:;" id="block2_cancel_stPI_form" onclick="return slideUpSettingsTab(this,event);" class="">' + lang.Cancel + '</a>\
			</div></form></section>';
			
		break;
		
	case 'password':
		$BBD_HTLM = '<section class="st_pifo_upd"><form method="post" id="updatePassword_form" action="/cmd.php">\
			<input name="cmd" value="updatePassword" type="hidden" />\
			<div class="form form__gl-2-2 __settings">\
			<div class="change_pass_descr">' + lang.changePassDescr + '</div>\
            <div class="form_i">\
			<span class="input-l"><label for="pass_update">' + lang.CurrentPassword + '</label></span>\
            <div class="it_w">\
            <input type="password" id="pass_update" onkeypress="if(event.keyCode == 32) event.preventDefault();" name="fr.oldpass" class="it">\
            </div><span class="input-e"></span></div>\
			\
			<div class="form_i">\
			<span class="input-l"><label for="newpass_update">' + lang.newPassword + '</label></span>\
            <div class="it_w">\
            <input type="password" id="newpass_update" onkeypress="if(event.keyCode == 32) event.preventDefault();" name="fr.newpass" id="stfr_must_pass" class="it">\
            </div><span class="input-e"></span></div>\
			<div class="form_i">\
			<span class="input-l"><label for="repass_update">' + lang.reTypePassword + '</label></span>\
            <div class="it_w">\
            <input type="password" id="repass_update" onkeypress="if(event.keyCode == 32) event.preventDefault();" name="fr.repass" id="stfr_must_pass" class="it">\
            </div><span class="input-e"></span></div>\
			<div class="notif_btn __settings">\
			<button onclick="return updateNewPassword(event,$(\'form#updatePassword_form\'));" type="submit" class="button-pro __def __small mr-8">' + lang.Save + '</button>\
			<a href="javascript:;" id="block3_cancel_stPI_form" onclick="return slideUpSettingsTab(this,event);" class="">' + lang.Cancel + '</a>\
			</div></form></section>';
		break;
	case 'email':
		$BBD_HTLM = '<section class="st_pifo_upd"><form method="post" autocomplete="false" id="save_mail_form" action="/cmd.php">\
			<input name="cmd" value="updateProfileEmail" type="hidden" />\
			<div class="form form__gl-2-2 __settings">\
            <div class="form_i">\
			<span class="input-l"><label for="field_name">' + lang.NewEmail + '</label></span>\
            <div class="it_w">\
            <input type="email" autocomplete="false" readonly onfocus="this.removeAttribute(\'readonly\');" id="mail_update" onkeypress="if(event.keyCode == 32) event.preventDefault();" name="fr.mail" class="it">\
            </div><span class="input-e"></span></div>\
			\
			<div class="form_i">\
			<span class="input-l"><label for="em_curr_pass">' + lang.CurrentPassword + '</label></span>\
            <div class="it_w">\
            <input type="password" autocomplete="false" readonly onfocus="this.removeAttribute(\'readonly\');" id="em_curr_pass" name="fr.pass" id="stfr_m_must_pass" class="it">\
            </div><span class="input-e"></span></div>\
			<div class="notif_btn __settings">\
			<button onclick="return saveMail(event,$(\'form#save_mail_form\'));" type="submit" class="button-pro __def __small mr-8">' + lang.Save + '</button>\
			<a href="javascript:;" id="block4_cancel_stPI_form" onclick="return slideUpSettingsTab(this,event);" class="">' + lang.Cancel + '</a>\
			</div></form></section>';
		break;
	default:
		return;
	}
	if (!$el.find('section')
		.length)
	{
		$el.append($BBD_HTLM)
			.find('section')
			.slideDown();
		 inputPhone();
	}
	else $el.find('section')
		.slideDown();
}
function updInfoErr($el, $str, a)
{
	var $EL = $el;
	var $el = typeof $el == 'string' ? $($el) : $el;
	if (typeof $EL == 'string')
	{
		$el.hide()
			.empty();
		if (!a) $el.show()
			.html($str);
		else $el.hide()
			.empty();
		return;
	}
	$el.closest('section')
		.find('.input-e')
		.hide()
		.empty();
	if (!a) $el.focus()
		.parent()
		.parent()
		.find('.input-e')
		.show()
		.html($str);
	else $el.parent()
		.parent()
		.find('.input-e')
		.hide()
		.empty();
}


// get all participants in a poll
function pollGetTotalVotes(e,optionid){
	
	e.preventDefault();
	
	var $el = ga(e.target);
	var pollId = $el.attr('id').split('pollmiv|')[1];
	
	var poll_participants = '';
	var poll_u_markup_schel = '<ul class="mob_popup_friends_list"></ul>';
		
		var p_u_markup = '<li><a class="mob_invite_friends_to_com_sel" href="/user/%uid" onclick="ga(\'#mobile_popup_back_btn\').trigger(\'click\');" hrefattr="true">\
        <div class="mob_popup_f_avatar f_left"><img src="/getPhoto?p=%pid&sz=thumb&g=%gender" alt="%uname">%online</div>\
        <div class="mob_popup_f_name ellip">%uname</div>\
    </a></li>';
	
	
		// open mobile popup
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.poll_participants+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();	
		
		var cont = ga('.mob_popup_cnt#id_'+rand);
	
	
		var send = jAjax('/cmd.php', 'post',{
			
				cmd: 'pollParticipants',
				sondageid: pollId,
				optionid:optionid ? optionid : 0,
				view_as: 'json'
			
		});
		send.done( function (data)
			{
					var d = validateJson(data);
					
					if(d.succ == 1){
						
						cont.html(poll_u_markup_schel);
						
						for(var i = 0;i< d.data.length;i++){
							var b = d.data[i];
							poll_participants += p_u_markup.replace(/%uid/g,b.uid).replace(/%pid/g,b.uphoto).replace(/%uname/g,b.uname).replace('%gender',b.ugender).replace('%online',b.online ? '<span class="ic-online"></span>' : '');
							
						}
						
						
						cont.find('ul.mob_popup_friends_list').html(poll_participants);
					} else {
						
						displayErr(d.err);
						
					}
					
			
		});

		
}


function removePostViewer(){
}

// video click play
function playVDP(e, obj)
{
	e.preventDefault();
	e.stopPropagation();
	var $this = $(obj);
	playThisVideo($this, $this.data('video-meta'));
}
	function removeMinVideoFromDOM(){
		
		ga('#min_vd_fly').remove();
		
	}
function playThisVideo(vd_el, data, flying, from)
{
	
	
	var videoViewsAdd = function (id)
	{  
		// +1 view
		var send = jAjax('/cmd.php', 'post', {cmd:"video_add_views","vid":id,"clubid": data.vd_clubid > 0 ? data.vd_clubid : 0});
		/*send.done(function(d){
	   
								alert(d);
	   
						});*/
	};
	//vd_el.flowplayer();
	if(!flying) vd_el.hide(); 
	// select the above element as player container
	var container = document.getElementById("videojw_" + data.vd_i);
	var custom_size = vd_el.data('customsize') ? vd_el.data('customsize')
		.split('|') : '';
	var is_mywall = ga('body .__wall')
		.length;
	var video_wd = is_mywall && !vd_el.closest('#video_all')
		.length ? 564 : (vd_el.closest('#video_all')
			.length ? 664 : (custom_size ? custom_size[0] : 548));
	var video_hg = is_mywall && !vd_el.closest('#video_all')
		.length ? 208 : (vd_el.closest('#video_all')
			.length ? 375 : (custom_size ? custom_size[1] : 308));

	video_wd = vd_el.closest('.mdialog_chat_conversation_cnt').length ? 343 : video_wd;	
    video_hg = vd_el.closest('.mdialog_chat_conversation_cnt').length ? 186 : video_hg;	
		
	video_wd = vd_el.width();	
		video_hg = vd_el.height();	
	
	container.style.display = 'block';
	var is_vimeo;
	
	/*
	if (data.vd_ext == 'YouTube')
	{
		var mediaElementMarkup = '<video autoplay width="' + video_wd + '" height="' + video_hg + '" id="mdel_vd_' + data.vd_i + '" preload="none">\
								<source type="video/youtube" src="' + data.vd_fn + '" />\
								</video>';

	}
	else if (data.vd_ext == 'Vimeo')
	{
		var mediaElementMarkup = '<iframe id="vm_vd_' + data.vd_i + '" src="' + data.vd_fn + '?api=1&autoplay=1" width="' + video_wd + '" height="' + video_hg + '" class="vd_vimeo_player" frameborder="0"></iframe>';
		is_vimeo = true;
		
		
		video/vimeo
	}
	else
	*/

	data.vd_ext = data.vd_ext == 'NULL' ? '' : data.vd_ext;
	var v_poster = data.vd_clubid > 0 ? '/videoCover?v=' + data.vd_i + '&clubid='+data.vd_clubid+'&_tk=' + new Date().getTime() : '/videoCover?v=' + data.vd_i + '&_tk=' + new Date().getTime();
 
	if(data.vd_s3 == 'yes'){
 
		var mediaElementMarkup = '<input type="hidden" id="curvideo_lv_time" /><video width="' + video_wd + '" height="' + video_hg + '" src="'+ data.s3_url + data.vd_s3_userid + '/' + data.vd_fn + '" type="video/' + data.vd_ext + '" \
								  id="mdel_vd_' + data.vd_i + '" poster="'+v_poster+'" \
							      controls="controls" preload="none" autoplay></video>';
		
	}else if (data.vd_ext == 'mp4'){
		var mediaElementMarkup = '<input type="hidden" id="curvideo_lv_time" /><video width="' + video_wd + '" height="' + video_hg + '" src="'+_DESKTOP+'/' + data.vd_p + data.vd_fn + '.' + data.vd_ext + '" type="video/' + data.vd_ext + '" \
								  id="mdel_vd_' + data.vd_i + '" poster="'+v_poster+'" \
							      controls="controls" preload="none" autoplay></video>';

									
	}
	else
	{ 
		var mediaElementMarkup = 	'<input type="hidden" id="curvideo_lv_time" /><video autoplay width="' + video_wd + '" height="' + video_hg + '" id="mdel_vd_' + data.vd_i + '" preload="none">\
									<source  src="' +_DESKTOP+ data.vd_fn + '" />\
									</video>';							  
	}

	//vd_el.replaceWith(mediaElementMarkup);
	container.innerHTML = mediaElementMarkup;
	var media, updateLiveVideoTime;

	var vd_player = new MediaElementPlayer('mdel_vd_' + data.vd_i, {
		
		// This is needed to make Jump Forward to work correctly
		pluginPath: _st.host+'/cmd/mediaelement/build/',setCurrentTime:9,startLanguage: __g_lang,
		features: [ 'playpause', 'current', 'progress',  'duration', 'speed', 'skipback', 'jumpforward', 'tracks',
					'markers', 'volume', 'fullscreen','chromecast', 'ads', 'vast', 'contextmenu' ],
				AndroidUseNativeControls:true,
				iPhoneUseNativeControls:true,
				iPadUseNativeControls:true,
				autoplay: true,hideVideoControlsOnPause:true,
					success: function (mediaElement, domObject) {  
            media = mediaElement; // make it available for other functions
			videoViewsAdd(data.vd_i);
			
 // add event listeners
   mediaElement.addEventListener('timeupdate', function(e) {
      ga('#curvideo_lv_time').val(media.getCurrentTime());
   }, false);
			
			
			
        } 
		 
	});
	from = from || ( ga('.startFrom').length ? ga('.startFrom').attr('id') : false);
	if(from)
	media.setCurrentTime(from); // set star
 
 
	
	
	/*
	var player = new MediaElementPlayer('#mdel_vd_' + data.vd_i,
	{
		// path to Flash and Silverlight plugins
		///pluginPath: '/cmd/mediaelement/build/',
					stretching: 'none',
			pluginPath: '/cmd/mediaelement/build/',
		// name of flash file
		//flashName: 'flashmediaelement.swf',Ã‚ plugins: ['flash','silverlight'],
		//mode:'auto_plugin',timerRate: 100
		///plugins: ['flash', 'silverlight'],
	//	autoplay: true,
		// force iPad's native controls
	//	iPadUseNativeControls: true,
		// force iPhone's native controls
	//	iPhoneUseNativeControls: true,
		// force Android's native controls
	//	AndroidUseNativeControls: true,
	//	preload: 'none',
		//silverlightName: 'silverlightmediaelement.xap',
		
					success: function (media) {
						
						player.load();
		player.play();
						
				var renderer = document.getElementById(media.id + data.vd_i);

				media.addEventListener('loadedmetadata', function () {
					var src = media.originalNode.getAttribute('src').replace('&amp;', '&');
					if (src !== null && src !== undefined) {
						renderer.querySelector('.src').innerHTML = '<a href="' + src + '" target="_blank">' + src + '</a>';
						renderer.querySelector('.renderer').innerHTML = media.rendererName;
						renderer.querySelector('.error').innerHTML = '';
					}
				});

				media.addEventListener('error', function (e) {
					renderer.querySelector('.error').innerHTML = '<strong>Error</strong>: ' + e.message;
				});
			}
		//
		success: function (media, node, player)
		{
			media.play();
			var $pl = $(node)
				.closest('.mejs-container');
			videoViewsAdd(data.vd_i);
			// add event listener
			media.addEventListener('playing', function (e)
			{
				$pl.addClass('__vdplaying');
				//alert('play')
			}, false);
			// add event listener
			media.addEventListener('canplay', function (e)
			{
				if (!this.played_o) media.play();
				this.played_o = 1;
			}, false);
			media.addEventListener('pause', function (e)
			{
				$pl.removeClass('__vdplaying');
			}, false);
			media.addEventListener('ended', function (e)
			{
				$pl.removeClass('__vdplaying');
			}, false);
		},
		error: function ()
		{
			alert('Error setting media!');
		}
	});*/

}
function alphaHeadMoveSlow(obj_o, obj_t, thead)
{
	var a = obj_o,
		b = obj_t,
		c = thead;
	obj_o.css('top', '-=1px') //+obj_o.offset().top - obj_t.offset().top);
	if (obj_o.offset()
		.top + obj_o.height() > thead.offset()
		.top) setTimeout(function ()
	{
		alphaHeadMoveSlow(a, b, c);
	}, 10);
}
function notifNav(el, evt)
{
	evt.preventDefault();
	var $el = ga(el);
	var g = generateUrl(el);
	var c_wrap = ga('.notifs_wrap');
	c_wrap.html('<div class="ajax_small_loader"></div>');
 
	var send = jAjax(g[0], 'post', g[1] + '&view_as=json');
	send.done(function (d)
	{  
		var d = validateJson(d);
		if (d)
		{
			c_wrap.html(d['content']);
			ga('#notification_nav_bar_categ')
				.text($el.data('navbartitle'));
			ga('#ntf_layer_left_menu > li > a.__active')
				.removeClass('__active');
			ga(el).addClass('__active');
			ga('.notif_space')
				.empty();
			setTimeout(up_href, 200);

			
		}
	});
}
function userSettingsPage(){
	
	if( ga('#hook_Block_User_Settings_Basic_info').length ){
	
	ga('#pedit_interests_interests').emojiarea(
	{
		wysiwyg: true,
		buttonLabel: 'Emojis',
		buttonPosition: 'after',
		button:ga('#pedit_interests_interests_emoji_btn')
	});
	ga('#pedit_interests_quotes').emojiarea(
	{
		wysiwyg: true,
		buttonLabel: 'Emojis',
		buttonPosition: 'after',
		button:ga('#pedit_interests_quotes_emoji_btn')
	});
	ga('#pedit_interests_about').emojiarea(
	{
		wysiwyg: true,
		buttonLabel: 'Emojis',
		buttonPosition: 'after',
		button:ga('#pedit_interests_about_emoji_btn')
	});
	
	ga('#pedit_interests_hobby').emojiarea(
	{
		wysiwyg: true,
		buttonLabel: 'Emojis',
		buttonPosition: 'after',
		button:ga('#pedit_interests_hobby_emoji_btn')
	});
	setTimeout(function(){
	ga('.ms_items_more_wrap').remove();},500);
	}
}
//get emojarea
function getEmojare(obj, btn, activeOn, btnpos, css)
{
	var n = '<div data-emojbtn class="disc_toolbar_w" style="margin-bottom: 0px;">' + '<div class="disc_toolbar">' + '<div class="disc_toolbar_i">' + '<a class="disc_toolbar_i_ic smiles_w __staple" href="javascript:;"></a>' + '</div>' + '<div class="disc_toolbar_i">' + '<a class="em_disc_toolbar_i_ic__sm" href="javascript:;"></a>' + '</div>' + '</div>' + '</div>';
	var n = '<div data-emojbtn class="disc_toolbar_w" style="margin-bottom: 0px;"><a class="em_disc_toolbar_i_ic__sm smiles_w" href="javascript:;"></a></div>';
	var attch = '<!--- Attach files section ---->' + '<div class="jb_attached_files __messages"></div>' + '<section data-attcjfl="1">' + '<div class="mdialog_entertm_ics">' + '<div onclick="attach_pPhoto(event)"><span class="tico"><i id="md_ics_photo" title="Photo" class="tico_img ic ic_photoattach"></i></span></div>  ' + '<div onclick="attach_pPhoto(event,1)"><span class="tico"><i id="md_ics_photo_computer" title="Photo from computer" class="tico_img ic ic_photo"></i></span></div> ' + '</div>' + '</section>';
	$obj = $(obj);
	com_emj = $obj.emojiarea(
	{
		wysiwyg: true,
		buttonLabel: 'Emojis',
		buttonPosition: btnpos ? 'before' : 'after',
		button: btn ? btn : ''
	});
	_act_emoji = activeOn;
	var btn_parent = ga(btn)
		.parent();
	if (!btn_parent.find('[data-attcjfl="1"]')
		.length) btn_parent.append(attch);
	var emoji_textarea = $obj.parent()
		.find('.emoji-wysiwyg-editor');
	if (css)
	{
		emoji_textarea.css(css);
	}
	return emoji_textarea;
}

function attach_pPhoto(a, b, c)
{ 
	setTimeout(function ()
	{
		window.trigger_attach_pPhoto(a, b, c)
	}, 100);
}
function attach_video(v){
	setTimeout(function ()
	{
		window.trigger_attach_video(v)
	}, 100);
}
function trigger_attach_video(evt){
	
	
	
}
function decodeUrlEncode(string){
	string = decodeURIComponent(string);
return string.replace(/\+/g, ' ');


}
function urlencode(str) {
  str = (str + '').toString();

  // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
  // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
  return encodeURIComponent(str)
    .replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .replace(/\)/g, '%29')
    .replace(/\*/g, '%2A')
    .replace(/%20/g, '+');
}

function removePhotoTagFromNotif(el, evt)
{
	evt.preventDefault();
	var $el = $(el);
	var __this_nid = $el.data('freq')
		.split('-');
	var send = jAjax('/cmd.php', 'post', 'cmd=removeTagFromPhoto&photoid=' + escape(__this_nid[1]) + '&notif=' + escape(__this_nid[0]));
	send.done(function (data)
	{
		if (data == 0) return displayErr(lang.err_untag);
		else
		{
			ga('#hook_FormButton_fri_' + __this_nid[0])
				.trigger('click');
		}
	});
}


// confirm tags from notification (tags request)
function confirmTaggedRequest(evt, el, notifID, photoID)
{
	evt.preventDefault();
	var $el = $(el);
	var send = jAjax('/cmd.php', 'post', 'cmd=confirmRequestedTags&photo=' + escape(photoID) + '&notID=' + escape(notifID));
	send.done(function (data)
	{
		if (data != 1) return displayErr(lang.err_tehnic);
		else ga('#hook_FormButton_fri_' + notifID)
			.trigger('click');
	});
}
function removeMobilePopupFromDom(id){
	if(ga('body').hasClass('addnoscroll')) ga('body').addClass('noscroll').removeClass('addnoscroll');
	ga('#mobile_popup_back_btn[rel="'+id+'"]').trigger('click');
}
function jb_modal_attchfiles_repositionControlBtn()
{
	/*
		var criteriu = $('.sticky-plank_hld');
		var jbx = $('.jBox-content:last'), jbc = $('.jBox-container:last'), wh = $(window).height();

		if(jbx.height() <= screen.height && $(window).scrollTop() < jbx.height()){
		jbx.css('height','+='+criteriu.height());
		criteriu.css({'bottom':screen.height-(jbx.outerHeight()+100), 'width':jbc.outerWidth(), 'position':'fixed'});
		}else criteriu.removeAttr('style').css('position','absolute');
	*/
	var control_btns = ga('<a/>')
		.addClass('jb_ready_btn __disabled')
		.text('OK');
	ga('.jBox-closeButton:last>.fixed_always')
		.prepend(control_btns);
}
function sendGiftTo(uid,gid){



		// open mobile popup
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.Gift_for+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();	
		
		var cont = ga('.mob_popup_cnt#id_'+rand);
	
		var send = jAjax('/cmd.php', 'post', {
				cmd: 'giftReadyToSend',
				//view_as: 'json',
				gid: escape(gid),
				uid: escape(uid)
			});

		send.done(function(data){
			
				cont.html(data);
				
				cont.find('.pf_message').css('width',cont.width()-170+'px');
				cont.find('#mob_popup_gifts_id').val(rand);
				cont.find('#mob_pop_gif_close').on('click',function(){
					removeMobilePopupFromDom(rand);
				});
			
		});

 
	
}
 function buyGift(evt,f) {
	
	evt.preventDefault();
	
	var t_btn = ga(evt.target);
	var s_gift = t_btn.data('gifts');
	
	
	if(s_gift == 'no') { ga('.cant_buy_gift').fadeIn('fast');  return;}

	ajaxLoading();
	var sendForm = js_subForm(f);
	sendForm.done(function (data)
	{
		removeAjaxLoad();
		
		if(data === '1'){
			var _current_balance = ga('.balance_c');
				_current_balance.text( parseInt(_current_balance.text()) - parseInt(ga('input[name="price"]').val()) );
			// close popup box
			removeMobilePopupFromDom(ga('#mob_popup_gifts_id').val());
			
				// show notification
				kn_liveNotif(lang.gift_succ_sent,'done',5000,lang.gift_send_succ_descr);

		} else {
			
				// show a error notification
				kn_liveNotif(lang.gift_not_sent,'error',5000,lang.gift_send_err);
		}
		
		
	});
	
}function uncheckOther(id){
	
	document.getElementById(id).checked=false;
	
}

// send gift
function sendGift(el,evt) {
	
	evt.preventDefault();
	
	el = ga(el);
	var gift_id = el.data('giftid');

	
			// open mobile popup
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.Gift_for_a_friend+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();	
		
		var cont = ga('.mob_popup_cnt#id_'+rand);
	
		var send = jAjax('/cmd.php', 'post', {
				cmd: 'getGiftPopup',
				view_as: 'json',
				giftid: escape(gift_id)
			});
			send.done(function(data){  
				var res = validateJson(data);
				cont.html(res.content);
				
				
					ga('#field_search_query_gift')
						.fastLiveFilter('.mob_popup_friends_list',
						{
							timeout: 200,
							callback: function (total)
							{
								/*$('#filter_search_count')
									.html(total);*/
							}
						});
			});
 
	
}
	function giftsSlider(){
	
	if(ga( ".p_giftslist" ).children().length ){
		new giftsSlideshow( "#gifts-slider>ul" );
		 
	}

		
	}
		function giftTooltip(){
		
		ga('.gift-item,.gift_item:not(.notooltip)').each(function(e){
			 
			jboxTolltip(this.id, ga(this).data('gift-tooltip'),1);
		});
		
	}
	function giftsSlideshow( element ) { 
		this.el = document.querySelector( element );
		//this.init();
		

		//giftTooltip();
	}
	
	giftsSlideshow.prototype = {
		init: function() {
			this.wrapper = this.el.querySelector( ".p_giftslist" );
			this.slides = this.el.querySelectorAll( ".gift-item" );
			this.previous = this.el.querySelector( ".slider-previous" );
			this.next = this.el.querySelector( ".slider-next" );
			this.index = 0;
			this.total = this.slides.length;
			this.timer = null;
			
			this.action();
			this.stopStart();	
		},
		_slideTo: function( slide ) {
			//if(!slide)return;
			var currentSlide = this.slides[slide];
			
			///currentSlide.style.zIndex = 2;
			currentSlide.style.display = '';
			currentSlide.style.opacity = 1;
	
			for( var i = 0; i < this.slides.length; i++ ) {
				var slide = this.slides[i];
				if( slide !== currentSlide ) {
					///slide.style.opacity = 0;
					///slide.style.zIndex = 1;
					ga(slide).css('opacity',0)
					.on(crossEvent, function ()
				{
					ga(this).hide();
				});
				
				
				}
			}
			
			
		},
		action: function() {
			var self = this;
			self.timer = setInterval(function() {
				self.index++;
				if( self.index == self.slides.length ) {
					self.index = 0;
				}
				self._slideTo( self.index );
				
			}, 3000);
		},
		stopStart: function() {
			var self = this;
			var ev_name_space = randomIntFromInterval(5, 999);
			self.el.addEventListener( "mouseover", function() {
				clearInterval( self.timer );
				self.timer = null;
				
			}, false);
			self.el.addEventListener( "mouseout", function() {
				self.action();
				
			}, false);
		}
		
		
	};
// accept gift
function acceptGift(evt,el,notif_id){
	evt.preventDefault();
	
	el = ga(el);
	var gift_q = el.data('giftq');
	
	
	ajaxLoading();
	
	
	
	var send = jAjax('/cmd.php', 'post', $.param(gift_q));
	send.done(function(data){
		removeAjaxLoad();
		if(data === '1'){
			
			// gift received successfully
				kn_liveNotif(lang.gift_succ_received,'done',5000,lang.gift_send_received_descr);
				
				// hide the gift from notifications
				ga('#hook_FormButton_fri_'+notif_id).trigger('click');
		} else {
			
			// error receive the gift
			kn_liveNotif(lang.gift_not_accept_err,'error',5000,lang.gift_not_accept_err_descr);
		}
		
	});
	
}
$.fn.hasScrollBar = function ()
{
	return this.get(0)
		.scrollHeight > this.height();
}



Array.prototype.pindexof = function (val)
{
	var i = this.length;
	while (i--)
	{
		if (this[i] == val) return i;
	}
	return -1;
}
Array.prototype.remove = function (from, to)
{
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
}
function jb_delete_attach(evt)
{
	var $obj = ga(evt.target);
	$obj.closest('obattch')
		.slideDown(400, function ()
		{
			ga(this)
				.remove();
		});
}
// attach from computer (upload)
function jb_upload_attach(files, input, evt)
{
	var readAttach = function (o)
	{
		//var input = event.target;
		var reader = new FileReader();
		reader.onload = function ()
		{
			var dataURL = reader.result;
			var container = $('#at_upload_' + o);
			var output = container.find('img')[0]; //container.find('.img_fak')[0];
			if (container.length == 0) return false;
			output.src = dataURL;
			// output.style.backgroundImage = 'url('+dataURL+')';
			container.find('.__uploadingInfo')
				.addClass('__off');
			container.find('.uploading_ovr')
				.addClass('__on');
			setTimeout(function ()
			{
				container.find('.uploading_ovr.__on,.pup_bar_m_upload')
					.remove();
			}, 1500);
		};
		reader.readAsDataURL(files[o]);
	}
	var count = 0;
	var totalFiles = files.length;
	var jb_rd_btn = ga('.attach_ready_btn'),
		jb_files_to_app = ga('.jb_attached_files');
	var trigger_attachUp = function ()
	{
		if (typeof files[count] === 'undefined' || count > totalFiles - 1)
		{
			if (jb_attach_uploads.length) jb_rd_btn.removeClass('__disabled');
			edUpload();
			return false;
		}
		var formData = new FormData();
		formData.append('files[]', files[count]);
		formData.append('to', recipientId);
		$.ajax(
		{
			url: _st.host+'/upload-inc/attach.php',
			type: 'POST',
			xhr: function ()
			{ // Custom XMLHttpRequest
				var Xhr = $.ajaxSettings.xhr();
				if (Xhr.upload)
				{ // Check if upload property exists
					Xhr.upload.addEventListener('progress', function (e)
					{
						var p_cont = $('#at_upload_' + count + ' .main_progress_photo');
						if (e.lengthComputable)
						{
							var p_percentage = Math.round((e.loaded / e.total) * 100);
							p_cont.css('width', p_percentage + '%');
						}
					}, false); // For handling the progress of the upload
				}
				return Xhr;
			},
			//Ajax events
			beforeSend: function ()
			{
				readAttach(count);
			},
			success: function (data)
			{   alert(data);
				var response = validateJson(data);
				if (response['status'] === 'OK')
				{
					var container = $('#at_upload_' + count);
					var u_image = container.find('img');
					jb_attach_uploads.push(response['photoid']);
					u_image.attr(
					{
						'src': '/getPhoto?p=' + response['photoid'] + '&attach=true&v' + (new Date())
							.getTime()
					});
					container.children(':first')
						.addClass('selectable-card __selected')
						.attr(
						{
							'data-photoc': response['photoid'],
							'onclick': 'jb_uploaded_attach_click(event,this)',
							'id': 'abidal_' + response['photoid']
						});
					container.find('#restore_recent_upload')
						.attr('href', '/profile?q=' + (response['userid']) + '&cmd=phreturn&i=' + (response['albumid']) + '&phf=' + (response['filename']) + '&ex=' + (response['extension']) + '&fsz=' + (response['filesize']) + '&pos=0&ad=' + response['added']);
					container.find('#delete_recent_upload')
						.removeAttr('style')
						.attr('href', '/profile?q=' + (response['userid']) + '&cmd=deletephoto&ph=' + response['photoid']);
					setTimeout(function ()
					{
						container.removeAttr('id');
						count++;
						trigger_attachUp();
					}, 50);
				}
				else return displayErr(data);
			},
			error: function ()
			{
				return displayErr(lang.somethingWrong)
			},
			// Form data
			data: formData,
			//Options to tell jQuery not to process data or worry about content-type.
			cache: false,
			contentType: false,
			processData: false
		});
	}
	trigger_attachUp();
}
/** Attach files to textarea ***/

function jb_uploaded_attach_click(e, obj)
{
	e.preventDefault();
	var $this = ga(obj),
		jb_rd_btn = ga('.attach_ready_btn'),
		jb_files_to_app = ga('.jb_attached_files'),
		jb_ph_id = $this.attr('id')
		.split('_')[1],
		sl_card = $this,
		s_class = '__selected';
	if (!sl_card.hasClass(s_class))
	{
		sl_card.addClass(s_class);
		jb_attach_uploads.push(jb_ph_id);
		jb_rd_btn.removeClass('__disabled');
	}
	else
	{
		sl_card.removeClass(s_class);
	
		delete jb_attach_uploads[jb_attach_uploads.pindexof(jb_ph_id)];
		//delete jb_attach_uploads[jb_attach_uploads.indexOf(jb_ph_id)];
		if (Object.keys(jb_attach_uploads)
			.length <= 0) jb_rd_btn.addClass('__disabled');
	}
}
function jb_build_upload(ev)
{
	var input = $(ev.target);
	var files = input[0].files;
	var phContent = $('.atch_cont');
	if (jb_attach_uploads.length == 21)
	{
		return displayErr(lang.jb_attach_maxim);
	}
	else if (files.length > 21)
	{
		return displayErr(lang.jb_attach_maxim_twone);
	}
	for (var i = 0; i < files.length; i++)
	{
		var file_ext = files[i].name.split('.')
			.pop()
			.toLowerCase();
		if ($.inArray(file_ext, _st.photoTypes) == -1 && $.trim(file_ext))
		{
			ev.preventDefault();
			ev.stopImmediatePropagation();
			$('.atch_cont .ec_items.__uploading')
				.remove();
			edUpload();
			return displayErr(lang.up_invalid_file_ext.replace('%s', _st.photoTypes));
		}
		if (files.length > _st.maxFilesUpload)
		{
			ev.preventDefault();
			ev.stopImmediatePropagation();
			edUpload();
			return displayErr(lang.up_maximumFiles.replace('%s', _st.maxFilesUpload));
		}
		phContent.prepend(jprintf(getUploadSkem(1), i, files[i].name));
	}
	edUpload(1);
	jb_upload_attach(files, input, ev);
}
function num(a){
	return a.match(/\d/g).join('');
}
function jb_enable_Ok_btn_upload()
{ 
	var jb_rd_btn = ga('.attach_ready_btn'),
		jb_rd_btn_id = jb_rd_btn.attr('id'),
		jb_files_to_app = jb_rd_btn_id.indexOf('messenger') > -1 ? ga('#'+jb_rd_btn_id+'.jb_attached_files') :  (jb_rd_btn_id ? ga('[data-wdcommid="'+jb_rd_btn_id+'"] .jb_attached_files') :  ga('.jb_attached_files'));
		
	jb_rd_btn.off('click')
		.on('click', function (e)
		{
			e.preventDefault();
			if (jb_attach_uploads.length <= 0)
			{
				e.stopImmediatePropagation();
				ga(this)
					.addClass('__disabled');
				return displayErr(lang.jb_attach_upload_no_files);
			}
			
			for (var i = 0; i < jb_attach_uploads.length; i++)
			{
				if (typeof jb_attach_uploads[i] != 'undefined') jb_files_to_app.prepend('<obattch><div class="attach-photo_del" data-attached="1" onclick="jb_delete_attach(event)" title="' + lang.del + '" id="attachDe_' + jb_attach_uploads[i] + '"><div class="ic10 ic10_i_close"></div></div><img src="/getPhoto?p=' + jb_attach_uploads[i] + '&attach=true&v=' + (new Date()
					.getTime()) + '" class="attach-photo_img" border="0" /></obattch>');
			}
			jb_attach_uploads = [];
			var get_popup_id = ga(this).closest('.mob_popup_cnt').attr('id').replace('id_','');
			removeMobilePopupFromDom(get_popup_id);
		});
}
function jBoxModalGetAlbumPhotos(ev, i)
{
	ev.preventDefault();
	var $obj = $(ev.target);
	var albumId = escape(i);
	var send = jAjax('/profile', 'post', 'cmd=jBoxPhotoAlbum&i=' + albumId + '&type=pos&view_as=json');
	send.done(function (data)
	{  
		data = validateJson(data);
		$('[uid="jbox_all_inclus_alb_pph"]')
			.html(data.content);
		setTimeout('jb_attachfl_enablePhotoSlct()', 500);
		//jb_modal_attchfiles_repositionControlBtn();
	});
}


function jb_attachfl_enablePhotoSlct()
{
	var $o = ga('[uid="jbx_attch_ph_sel"]');
	var jb_attach_files = [];
	$o.on('click', function (e)
	{

		e.preventDefault();
		var $this = ga(this),
			jb_rd_btn = ga('.attach_ready_btn'),
			jb_rd_btn_id = jb_rd_btn.attr('id'),
			jb_files_to_app = jb_rd_btn_id.indexOf('messenger') > -1 ? ga('#'+jb_rd_btn_id+'.jb_attached_files') : (jb_rd_btn_id ? ga('[data-wdcommid="'+jb_rd_btn_id+'"] .jb_attached_files') :  ga('.jb_attached_files')),
			jb_ph_id = $this.attr('id')
			.split('_')[1],
			sl_card = $this.find('.selectable-card'),
			s_class = '__selected';
			
			if (!sl_card.hasClass(s_class))
		{
			sl_card.addClass(s_class);
			jb_attach_files.push(jb_ph_id);
			jb_rd_btn.removeClass('__disabled')
				.off('click')
				.on('click', function (e)
				{ 
					e.preventDefault();
					if (jb_files_to_app.children()
						.length >= 21 || Object.keys(jb_attach_files)
						.length > 21 || (jb_files_to_app.children()
							.length + Object.keys(jb_attach_files)
							.length) > 21)
					{
						displayErr(lang.jb_attach_maxim);
					}
					else
					{ 
						for (var i = 0; i < jb_attach_files.length; i++)
						{
							if (typeof jb_attach_files[i] != 'undefined') jb_files_to_app.prepend('<obattch><div class="attach-photo_del" onclick="jb_delete_attach(event)" title="' + lang.del + '" id="attachDe_' + jb_attach_files[i] + '"><div class="ic10 ic10_i_close"></div></div><img src="/getPhoto?p=' + jb_attach_files[i] + '&sz=small" class="attach-photo_img" border="0" /></obattch>');
						}
						var get_popup_id = ga(this).closest('.mob_popup_cnt').attr('id').replace('id_','');
						removeMobilePopupFromDom(get_popup_id);
						 
					}
				});
		}
		else
		{
			sl_card.removeClass(s_class);
			delete jb_attach_files[jb_attach_files.pindexof(jb_ph_id)];
		//delete jb_attach_files[jb_attach_files.indexOf(jb_ph_id)];
			if (Object.keys(jb_attach_files)
				.length <= 0) jb_rd_btn.addClass('__disabled');
		}
	});
}
function tonum(str){
	
	return str.match(/\d/g).join('');
}
function getUserLocation() {

    var need_user_country = ga('[rel="getusercountry"]');


    if(need_user_country.length) {



        need_user_country.each(function() {
            var $this = ga(this);
            var user_id = ga(this).attr('id');
            user_id = tonum(user_id);

            if(saved_location.hasOwnProperty(user_id)) {

                $this.replaceWith(saved_location[user_id]);
            } else {

                need_user_country.html('<span class="div-loader"></span>');
                var send = jAjax('/cmd.php', 'post', {
                    'cmd': 'getThisUserLocationLeaflet',
                    'user_id': escape(user_id)
                });

                send.done(function(location) { 


                    saved_location[user_id] = location;


                    $this.replaceWith(location);

                });




            }

        });



    }



}
function trigger_attach_pPhoto(evt, upload, customid)
{
	
	
	evt.preventDefault();

	var rand = randomIntFromInterval(9, 9999);
	var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.j_modal_select_photos+'","rand":"'+rand+'"}\'></a>');
	
	ga('body').prepend(a_mob_popup);
	a_mob_popup.trigger('click');
	a_mob_popup.remove();	
	
	
	
	var getPhotos = jAjax('/profile.php', 'post',{
				cmd: upload ? 'gJBupload' : 'gAllPhotos',
				type: 'pos',
				view_as: 'json',
				i: recipientId ? recipientId : '' 
			});
			
			
		getPhotos.done(function(data) {  
		
				var jCont = ga('.mob_popup_cnt#id_'+rand);
				var res = validateJson(data);
				jCont.html(res.content);


				
				
					ga(window).off('scroll.getImagesSrcForAttach').on('scroll.getImagesSrcForAttach', function(){
					 
					jCont.find('[data-p-src]').each(function(){
						
					var t = ga(this);
					if(isElementInViewport(t) && !t.hasClass('_f03filt')) setTimeout(function(){t.attr('src',t.data('p-src')).addClass('_f03filt');},10);
					
					});
					
					
					});

				

				if(customid) ga('.attach_ready_btn').attr('id',customid);
				setTimeout('jb_attachfl_enablePhotoSlct();jb_enable_Ok_btn_upload();', 500);	
				
				
				ga('#attach_photos_form_btns').css('width',ga('#mobilepopup').width());

		 
				
				
		
	});

		
}
 function nobilMusicPlayOutsideTrack(el, evt, a)
{
	
}
function scrolltoanchor(hash) {
    location.hash = "#" + hash;
}
function prn_modal()
{
	ga('.modal-new,.orig-modal,.sct')
		.remove();
	ga('html').removeClass('bezovr');
}
function resizeMessenger(){
	
	if(ga('#chat_id').length){
		startChatSession();
		
		ga('body').addClass('noscroll');
		if(ga('[data-header-mail]').length) ga('html').addClass('messenger'); else ga('html').addClass('messenger');
		
		
		
	ga(window).on('resize.resizeMess', function(e){
	
	ga('.uMessenger').height( ga(window).height() - (ga('#sc_head').height() + ga('.text_panel').outerHeight() ) );
	}).trigger('resize');
	setTimeout(function(){
		ga(window).scrollTop(0);
	},3000);
		
		
	} else {
		ga('html').removeClass('messenger');
		ga('body').removeClass('noscroll');
	}

}
function delete_reply_storage()
{
	localStorage.setItem('com_reply', '');
	localStorage.setItem('com_reply_author', '');
	localStorage.setItem('com_reply_id', '');
}

// crop photos
function upProfPh(el, evt, a)
{
	if (typeof g_element != 'undefined') g_element.show();
	var callPopup = rpopup(evt, el.getAttribute('href'), false, false, true, 'auto');
	callPopup.done(function (data)
	{
		setTimeout(function ()
		{
			g_element = ga(el);
			var mParent = ga('.cr_photo_bg');
			ga('.popup_ovr')
				.css('z-index', '-1');
			mParent.css('height', psize[1]);
			ga('.cropper_img')
				.css(
				{
					'max-width': mParent.width(),
					'max-height': mParent.height()
				});
		}, 10);
	});
}

function confirmCropPhoto(f, e)
{
	e.preventDefault();
	ajaxLoading();
	var sendForm = js_subForm(f);
	sendForm.done(function (data)
	{
		if (data === '0') return displayErr(lang.somethingWrong)
			// php return OK result
		else
		{
			var photoId = data;
			$('.op_fimg')
				.removeAttr('src')
				.attr('src', _st.getphoto.replace('%i', photoId)
					.replace('%s', 'small') + "&token=" + (new Date())
					.getTime());
///			g_element.hide();
			removeAjaxLoad();
			ga('#popup_layer_crop_photo').remove();
			ga('.js-cancelCrop').trigger('click');
			kn_liveNotif(lang.Done,'done',4000,lang.picture_done_cropped);
		}
	});
}
function searchPlaceInGroups(el,place_lt,place_ln){
	
	el = ga(el);
	
	if(!el.hasClass('club-href')){
	
	ajaxLoading();
	var send = jAjax('/cmd.php', 'post', {cmd:'searchPlaceInGroups','ln':escape(place_lt),'lt':escape(place_ln)});
	send.done(function(data) {
		removeAjaxLoad();
		if (data > 0) {
			
			
			el.removeAttr('href').removeAttr('onclick').addClass('club-href').attr({'href' : '/community/'+data,'hrefattr':'true'});
			
			up_href();
			el.trigger('click');
		} else {
			
 
         kn_liveNotif(lang.place_not_found,'info',4000,lang.place_not_found_in_communities);
			
		}
		
	});
	
	}
	
	
}



// filter friends by certain letter
function fr_flt_b_lt(o, event)
{
	event.preventDefault();
	var $o = ga(o);
	_gl_filter_by_letter = $o.text()
		.toUpperCase();
	checkLetterInDom();
	if (!ga('#hook_alpha .__loader')
		.length) ga('#hook_alpha')
		.append('<div class="light_modal_01"><div class="lmbd4"></div></div>');
}
function nanoScrollStart(){
	
}

 
function editVideo(id){
	
	var rand = randomIntFromInterval(9, 9999);
	var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.Edit_video+'","rand":"'+rand+'"}\'></a>');
	
	ga('body').prepend(a_mob_popup);
	a_mob_popup.trigger('click');
	a_mob_popup.remove();	
 
	var cnt = ga('.mob_popup_cnt#id_'+rand);
	var video_id = ga('#vd_gal_'+id);
	var video_title = video_id.find('.si_owner').text();
	var video_desc = video_id.find('.si_video_desc').text();
	var video_tags = video_id.find('.si_video_tags').text();
	var edit_video_markup = '<div class="video_editing_mob_p" id="vd_'+id+'">\
	<h4 class="subheader">Title</h4>\
	<input type="text" name="vd_title" value="'+video_title+'" class="dark it" id="group_create_title">\
	<h4 class="subheader">Description</h4>\
	<input type="hidden" name="vdTags" value="'+video_tags+'" />\
	<textarea id="group_edit_desc" name="video_descr"  class="group_edit_textarea dark" maxlength="4000" style="overflow: auto; height: fill-available; height: -webkit-fill-available;">'+video_desc+'</textarea>\
	<h4>&nbsp;</h4><button onclick="saveVdInfo(this,event,'+rand+');" class="button wide_button">'+lang.save+'</button>\
	</div>';
	
	cnt.html(edit_video_markup);
	
}


/* upload user's profile cover
@param element "inp" - file input
@param event "evt" - window event
@param number "i_d" - square id
@param string "mth" - method
*/


function uploadProfileCovers(el,evt,i_d,mth){

		var input = ga(evt.target);
		var _form_i = input.parent();
		var form_data = new FormData(_form_i[0]);

		$.ajax(
		{
			url: _st.uploadCovers, //Server script to process data
			type: 'POST',
			xhr: function ()
			{ // Custom XMLHttpRequest
				var Xhr = $.ajaxSettings.xhr();
				if (Xhr.upload)
				{ // Check if upload property exists
					Xhr.upload.addEventListener('progress', function (e)
					{
							var upload_percentage = ajaxuploadprogress(e);
							
							if(mth === 'slideshow')ga('#photos_sort_slideshow .upload_bar_percent#pbar-'+i_d).css({'width':upload_percentage+'%','display':'inline'});
							else {
								_form_i.parent().find('.cr_theme_progress_br').css({'width':upload_percentage+'%'});
								
							}
					}, false); // For handling the progress of the upload
				}
				return Xhr;
			},
			//Ajax events
			beforeSend: function (jqXHR)
			{
				if(!validateUpload(input)){
				jqXHR.abort();
				return displayErr(lang.up_invalid_file_ext.replace('%s', _st.photoTypes));
				} else {
					
				if(mth === 'slideshow')	
				ga('#o-'+i_d+' i').hide();
			else {
				_form_i.parent().find('.cr_theme_progress_br').css({'width':'0%'});
				_form_i.find('.cr_th_txt').text(lang.uploading);
				_form_i.find('.ic_theme_from_comp').addClass('_uploading');
				//_form_i.closest('.cr_theme_btn').addClass('_uploading');
				
			}
					
				}
				
			},
			success: function (data)
			{ 
				var response = validateJson(data);
				if (response['status'] === 'OK')
				{
					
					
					if(response.method === 'cover'){

						customCoverSet(response.cover_url,response.theme_id);
						
						
					} else {
						
					var _serch_elm = ga('#o-'+i_d);
					_serch_elm.addClass('_noopac').attr('data-sid',response.photoid);
					_serch_elm.find('.attach-photo_del').attr('id','slshowim_'+response.photoid);
					readURL(evt,el,'#i-'+i_d,1);
					setTimeout(function(){_serch_elm.find('.upload_bar_percent').fadeOut(1000,function(){ga(this).removeAttr('style')});},2000);
					
					}
					
					
				}
				else return displayErr(data);
			},
			error: function ()
			{
				return displayErr(lang.somethingWrong)
			},
			// Form data
			data: form_data,
			//Options to tell jQuery not to process data or worry about content-type.
			cache: false,
			contentType: false,
			processData: false
		});
	
	
}// custom covers set 
function customCoverSet(cover_url,theme_id,pos){
	
	
	
						ga('.kn_popup_close').trigger('click');
						var _df_id_theme = ga('#up_K_theme');
						var _df_theme_ = _df_id_theme.html();
						
						_df_id_theme.html('<div class="vp_header_custom_theme"><img src="'+cover_url+'" class="kn_theme_cust_cover"></div><input type="hidden" name="kover_pos_r" id="kn_kover_pos_val"/><div class="theme_custom_cvk_sv"><div class="reposition_cover">'+lang.drag_to_reposition_cover+'</div><div class="fl_right"><button id="cancel_wrap_theme" class="flat_button _cancel mr_r12">'+lang.cancel+'</button><button class="flat_button" id="save_wrap_theme">'+lang.save+'</button></div></div>')
						.find('#cancel_wrap_theme').off('click.cancelTheme').on('click.cancelTheme', function(e){
							e.preventDefault();
							_df_id_theme.html(_df_theme_);
							
						});
						ga(document).off('click.saveTheme','#save_wrap_theme').on('click.saveTheme', '#save_wrap_theme', function(){
							
							ajaxLoading();
							var send = jAjax('/cmd.php', 'post', 'cmd=saveWrapCover&theme_pos='+escape(ga('#kn_kover_pos_val').val().replace('px',''))+'&theme_id='+escape(theme_id));
							send.done(function(data){
								
								removeAjaxLoad();
								if(data === '1') {
									var drg_img = ga(".vp_header_custom_theme img");
									drg_img.draggable('destroy');
									drg_img.addClass('curdef');
									ga('#kn_kover_pos_val,.theme_custom_cvk_sv').remove();
									kn_liveNotif(lang.theme_saved,'done',4000,lang.now_the_theme_is_visible_into_your_profile);
								}else kn_liveNotif(lang.cover_was_not_saved,'error',4000,lang.err_save_theme);
								
							});
							
							
						});
	
			setTimeout(function(){
	
				ga(".vp_header_custom_theme").imagedrag({
															input: "#kn_kover_pos_val",
															position: pos ? pos+'px' : 'middle',
															attribute: "value"
														});
									},100);
           
				
						
						
						setTimeout(function(){ga(window).scrollTop(0);},500);
	
	
	
	
}
// show my own themes
function showMyOwnThemes(evt){
	
	var $_element = ga(evt.target), $_element_id = evt.target.id;
	var _el_par = $_element.parent();
	
	
	
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.Themes_created_by_me+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();
		
		var cnt = ga('.mob_popup_cnt#id_'+rand);
	
		//if($_element_id in _target_evt) {  cnt.html(_target_evt[$_element_id]);ga("img.lazyimg_thm").lazyload();return; }
		
		
		var send = jAjax('/cmd.php', 'post', 'cmd=showMyOwnThemes');
		send.done(function(data){
			
			if(data != '0'){
				
				var b = validateJson(data), thm_markup = '', c = 0;
				
				for(var k=0;k<b.length;++k){
					
					var a = b[k];


					thm_markup += (c == 0 ? '<div class="old_own_themes">' : '') + '<div class="ec_theme"><div class="theme_hover_bg" id="ectheme_i'+a.id+'" data-cvposition="'+a.position+'" data-themeurl="'+a.src+'" onclick="return switchToThisTheme(event,'+rand+');"></div><div class="theme_oww_delete"><a href="javascript:;" id="cv_eknfviw_ajji-'+a.id+'-juicy" title="'+lang.delete_cover+'" onclick="deleteOwnTheme(event);" class="x_delete_pp"></a></div><img data-original="'+a.src+'" class="theme_s_img lazyimg_thm" /><div class="theme_added_time" title="'+lang.created+' '+a.added+'">'+a.added+'</div> <div class="theme_pp_menu"><div><a href="javascript:;" id="ectheme_i'+a.id+'" data-themeurl="'+a.src+'" onclick="return switchToThisTheme(event,'+rand+');"><i class="ic ic_set_theme"></i>Set this theme</a></div></div> </div>' + (c == 1 ? '</div>' : '');
					if(c == 1) c = 0;
					else c++;
				}
				
				// insert content
				cnt.html(thm_markup);
				cnt.find("img.lazyimg_thm").lazyload();
				//_target_evt[$_element_id] = thm_markup;

			} else {
				
				
				cnt.html('<div class="cl-alert-box notice">'+lang.you_dosent_have_your_theme+'</div>');
				
			}
			
			
		});

}
// delete cover
function deleteOwnTheme(evt){
	
	evt.preventDefault();
	var _elm = ga(evt.target);
	var _cv_id = _elm.attr('id').match(/\d/g).join('');
	return confirm_act(lang.confirm_delete_cover,function(evt){
		
		var send = jAjax('/cmd.php', 'post', 'cmd=deletemyowncover&i='+escape(_cv_id));
		send.done(function(data){
		
		if(data === '1'){
			
			_elm.closest('.ec_theme').css('width',0).on(crossEvent, function ()
				{
					ga(this).remove();
				});
			
		} else {
			
			return displayErr(lang.err_delete_cover);
		}
		
		
	});
		
	});
	
}

function slshow_remove_item(elm,evt){
	
	evt.preventDefault();
	elm = ga(elm);
	
	var _elm_i = elm.attr('id').match(/\d/g).join('');
	var _elem_orig_id = elm.parent().data('originali'); 
	var _cls_elem = elm.closest('.o_photo_slideshow');
	var send = jAjax('/cmd.php', 'post', 'cmd=removeImageFromSlideshow&img='+escape(_elm_i));
	ajaxLoading();
	send.done(function(data){
		removeAjaxLoad();
		if(data === '1'){
			_cls_elem.removeClass('_noopac __occ').find('.upload_bar_percent').removeAttr('style');
			_cls_elem.find('.slideshow-preview-uploaded-img').removeAttr('style');
			_cls_elem.find('.plus_slideshow_photo').show();
			ga('.slideshow_my_im_item.__on#'+_elem_orig_id).removeClass('__on');
		} else return displayErr(lang.somethingWrong+' -- [Err. code: '+data+']');
		
	});
	
	
}
function checkbox(el, v) {
  el = ga(el);
 // if (!el || hasClass(el, 'disabled')) return;
 if (!el || el.hasClass('disabled')) return;

 
 // toggleClass(el, 'on', v);
 $(el).toggleClass( "on" );
  return false;
}
	function readURL(evt,input,id,bg,ckbk) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            bg ? $(id).attr('style','background-image:url('+e.target.result+')') : $(id).attr('src', e.target.result);
			if(ckbk) ckbk(evt);
        }

        reader.readAsDataURL(input.files[0]);
    }
}
function updateRangeValue(el){
	var _val = el.value;
    el = ga(el);
	el.val(_val);
	el.parent().find('.slider-inp-val').text(_val+'ms');
	
}
/*
@a - array [ count, data ]
@a_id - album id (number)
*/
function slideshowPhotosFromAlbum(a,a_id){

	var _all_jeunim = '';
	var _img_app_space = $('#slshow_config_h'), _slshow_img_con = $('#slideshow_images_an_config');
	_img_app_space.hide();
	
	$('.list-albums-o').fadeOut();
	
	
	if(!_slshow_img_con.find('#images_for_alb_'+a_id).length){
		
		for(var i =0; i < a.data.length;i++){
			var _eud = a.data[i];
			_all_jeunim += '<div class="slideshow_my_im_item" id="im-'+_eud.id+'"><div class="slideshow_item_checked ic"></div><img src="/getPhoto?p='+_eud.id+'&sz=small" /></div>';
		}
		
		// hide "explore photos btn" and show back button
		var _expl_btn = $('.h_ex_your_ph');
		_expl_btn.hide();
		if(!_expl_btn.parent().find('.__return_slsh_pp').length){
			_expl_btn.after('<div class="sk43_return_btn" onclick="slideshowPopupResetToDefault(this,event);"><i class="ic ic-return-b-blue"></i>'+lang.back+'</div>');
			
		}
		
		
		_slshow_img_con.append('<div class="section_alb_all_im" id="images_for_alb_'+a_id+'"><div class="all_img_he_sec">'+a.count+' images</div><div class="nano"><div class="mob-theme-slideshow-nanooff nano-content">'+_all_jeunim+'</div></div></div>');
		ga(document).off('click.select_oP').on('click.select_oP', '.slideshow_my_im_item', function(e){ 

		e.stopPropagation();
		var $_this = $(this), c_im = 0;
		
		// before check if need to remove elements
		ga('.o_photo_slideshow').each(function(){
			
			var _this = ga(this);
			
			if(_this.hasClass('_noopac') || _this.hasClass('__occ'))
				c_im++;
			
		});

		if(c_im >= 6) {
			kn_liveNotif(lang.reached_limit_of_photos,'warn',6000,lang.remove_images_that_you_want_to_replace);
			return;}
		
		if($_this.hasClass('__on')){
			
			$_this.removeClass('__on');
			c_im = c_im-1;
		} else {
			ajaxLoading();
			
			var __add_to_slideshow_cnt = ga('#photos_sort_slideshow');
			var _slsh_photos_co = $('.o_photo_slideshow').filter(':not(.__occ):not(._noopac):first'),
			_slsh_photos_co_id = _slsh_photos_co.attr('id');
			var _this_img_src = $_this.find('img').attr('src');
			
			
			var copy_images = jAjax('/cmd.php','post', 'cmd=copyImagesToSlideshow&img_id='+escape($_this.attr('id').match(/\d/g).join('')));
			copy_images.done(function(data){  
			removeAjaxLoad();

			if(data > 0) {
				
			_slsh_photos_co.addClass('__occ').attr({'data-sop':$_this[0].id,'data-originali':$_this.attr('id')}).find('.slideshow-preview-uploaded-img').attr('style','background-image:url('+_this_img_src+')');
			_slsh_photos_co.find('[data-slideshowremoveitem="1"]').attr('id','slshowim_'+data);
			
			
				//.find('.slideshow-preview-uploaded-img').attr('style','background-image:url('+_this_img_src+')');
				//$_this.css('position','absolute').animate({'top': '-100px'},10000);
			$_this.addClass('__on');
			c_im = c_im+1;
			} else {
				
				displayErr(lang.err_slideshow_copy_photo);
				
			}
			});
		}

		});
		var _nano_scroll_simg = $('#images_for_alb_'+a_id+' .mob-theme-slideshow-nanooff'), p = 2, randId = Math.floor(Math.random() * 2);
		
		//_nano_scroll_simg.nanoScroller();
		_nano_scroll_simg.off('scroll.a'+randId).on('scroll.a'+randId, function() {
		
		
			var _get_more_photos = jAjax('/load-more-data.php','post','cmd=profilePersonalPhotosMore&album='+escape(a_id)+'&json_code=1&i='+escape(_U.i)+'&p='+(p++));
			_get_more_photos.done(function(data){

				var _b = validateJson(data);
				
				if(_b.length){
					
				for(var k =0;k< _b.length;k++)
				$('#images_for_alb_'+a_id+' .nano .nano-content').append('<div class="slideshow_my_im_item" id="im-'+_b[k].id+'"><div class="slideshow_item_checked ic"></div><img src="/getPhoto?p='+_b[k].id+'&sz=small&g='+_U.g+'"></div>');
				
				//_nano_scroll_simg.nanoScroller();
				
				} else {
					
					_nano_scroll_simg.off('scroll.a'+randId);
					
				}
				
			});
		
		});
		
		}
	
}
function slideshowPopupResetToDefault(el,ev){
	
	ev.preventDefault();
	
	
	ga(el).remove();
	ga('.section_alb_all_im').remove();
	ga('.h_ex_your_ph').show();
	ga('#slshow_config_h').show();
}
// get user's photos by respective album
function getUserSphotosFalbum(evt,alb,callf){

	evt.preventDefault();
	evt.stopImmediatePropagation();
    var _el_id = evt.target.id;

	
	alb = ga(alb);
	var alb_id = alb.attr('id').match(/\d/g).join('');
	//if(_el_id in _target_evt){ return callf(_target_evt[_el_id],alb_id);}
	ajaxLoading();

	var send = jAjax('/cmd.php', 'post', 'cmd=getphotosfromalbum&alb_id='+escape(alb_id));
	send.done(function(data){

		removeAjaxLoad();
		var __d = validateJson(data);
		callf(__d,alb_id);
		//_target_evt[_el_id] = __d;
	});
	send.fail(function(a,b,c){return displayErr(a+b+c);});
	
}
// get user's photo albums for slideshow
function slideshowGPhotoAlbums(a){
	var albums_html = '';
	var albums_explore_btn = $('.h_ex_your_ph');

		
	if(albums_explore_btn.find('.list-albums-o').length) return albums_explore_btn.find('.list-albums-o').fadeIn();
	
	for(var i =0;i< a.length;i++){
		var _xkoe = a[i];
		albums_html += '<div id="sl-i-alb-'+_xkoe.id+'" onclick="evstop(event);getUserSphotosFalbum(event,this,function(data,id){slideshowPhotosFromAlbum(data,id);});" class="col-card __no-decor _novitrina ovr-menu_soh">\
						<div><div class="photo-sc_i_cover">\
						<div class="photo-sc_i_cnt __prw">\
						<a href="javascript:void(0)" class="photo-sc_i_cnt_a">\
						<img class="photo-sc_i_cnt_a_img va_target" src="/getPhoto?p='+_xkoe.cover+'&sz=thumb">\
						<div class="col-card_ovr"></div></a></div></div>\
						<div class="photo-sc_grid_abt ellip">\
						<span class="o" title="'+_xkoe.name+'">'+_xkoe.name+'</span><span class="alb_count_pp">'+_xkoe.count+' photos</span></div></div></div>';
	}
	if(!albums_explore_btn.find('.list-albums-o').length){
		
    albums_explore_btn.append('<div class="list-albums-o" onclick="evstop(event);"><div class="up_arr_st3"></div><div class="nano albums_list-9q0" ><div class="nano-content">'+albums_html+'</div></div></div>');
	//ga(".list-albums-o .nano").nanoScroller();
	/*ga(window).off('keyup.slideshow-dropdownhide').on('keyup.slideshow-dropdownhide', function(ev){
		ev.preventDefault();
		ev.stopImmediatePropagation();
		if(ev.keyCode == 27) 
		albums_explore_btn.find('.list-albums-o').fadeOut();
	});*/
	ga('html').off('click.slideshow-dropdownhide').on('click.slideshow-dropdownhide',function(e){
		//e.preventDefault();
		albums_explore_btn.find('.list-albums-o').fadeOut();
	});
	}
}
function getUserSphotoAlbums(evt,sucfunc){
	evt.preventDefault();
	evt.stopPropagation();
    var _el_id = evt.target.id;
	if(_el_id in _target_evt){ return sucfunc(_target_evt[_el_id]);}
	ajaxLoading();
	var send = jAjax('/cmd.php', 'post', 'cmd=getmyphotoalbums');
	send.done(function(data){
		removeAjaxLoad();
		var __d = validateJson(data);
		sucfunc(__d);
		_target_evt[_el_id] = __d;
	});
	send.fail(function(a,b,c){return displayErr(a+b+c);});
	
}
function themeBuildSlideshow(el,ev){
	ev.preventDefault();
	var rand = randomIntFromInterval(9, 9999);
	var $el = ga(el);
	var _g_data = '', _g_photos = '';
	var _slideshow_transition_options = '<option value="fade">fade</option>\
										 <option value="fade2">fade2</option>\
										 <option value="slideLeft">slideLeft</option>\
										 <option value="slideLeft2">slideLeft2</option>\
										 <option value="slideRight">slideRight</option>\
										 <option value="slideRight2">slideRight2</option>\
										 <option value="slideUp">slideUp</option>\
										 <option value="slideUp2">slideUp2</option>\
										 <option value="slideDown">slideDown</option>\
										 <option value="slideDown2">slideDown2</option>\
										 <option value="zoomIn">zoomIn</option>\
										 <option value="zoomIn2">zoomIn2</option>\
										 <option value="zoomOut">zoomOut</option>\
										 <option value="zoomOut2">zoomOut2</option>\
										 <option value="swirlLeft">swirlLeft</option>\
										 <option value="swirlLeft2">swirlLeft2</option>\
										 <option value="swirlRight">swirlRight</option>\
										 <option value="swirlRight2">swirlRight2</option>\
										 <option value="burn">burn</option>\
										 <option value="burn2">burn2</option>\
										 <option value="blur">blur</option>\
										 <option value="blur2">blur2</option>\
										 <option value="flash">flash</option>\
										 <option value="flash2">flash2</option>';
										 
	var _is_slideshow_enabled = '<div class="slideshow_status_on_off"><label>Enabled<input type="checkbox" id="slideshow_enabled_cbox" class="ios-switch tinyswitch"/><div><div></div></div></label></div>';
	var _explore_your_photos = '<div class="h_ex_your_ph" id="slideshow_explore_your_photos84884" onclick="return getUserSphotoAlbums(event,function(a){slideshowGPhotoAlbums(a);});"><i class="ic ic_open_folder"></i>'+lang.explore_your_photos+'</div>';
	var _gphotos_title = '<div class="htitle_ad3rvjp">Add Photos</div>';
	var _gresort_slshow_images = '<div class="checkbox rs_slidesh_imgs" onclick="checkbox(this);$(\'._ff_slw_sorting\').toggleClass(\'off\');" name="slideshow_images_repos">Sorting images<div class="fl_r"></div></div>';
	var _separator_bullet = '<span class="rs_slidesh_bullet">&#8226;</span>';
	var _o_ph_mk_before = '<div id="photos_sort_slideshow">';
	var _o_photo_markup = '<div id="o-%s" data-sid="%s" class="o_photo_slideshow"><div class="upload_bar_percent" id="pbar-%s"></div><div class="attach-photo_del" data-slideshowremoveitem="1" onclick="slshow_remove_item(this,event);" title="'+lang.remove+'" id="slshowim_%s"><div class="ic10 ic10_i_close"></div></div><div class="slideshow-preview-uploaded-img" id="i-%s"></div><i class="plus_slideshow_photo"></i><form method="post" enctype="multipart/form-data"><input type="hidden" name="method" value="slideshow"/><input type="hidden" value="1" name="submit"/><input onchange="return uploadProfileCovers(this,event,\'%s\',\'slideshow\');" class="_ff_slw_sorting html5-link-upload _80" type="file" accept="image/*" name="file[]"></form></div>';
	var _o_ph_mk_after = '</div>';
	var _o_options_hd = '<section id="slideshow_images_an_config"><div id="slshow_config_h"><div class="htitle_ad3rvjp">Slideshow configuration</div>';
	var _o_slideshow_config = '<form class="o4sli2">\
	<div class="checkbox _w100 mt16" onclick="checkbox(this);" name="slideshow_overlay">Overlay<div class="fl_r"></div></div>\
	<div class="checkbox _w100 mt16" onclick="checkbox(this);" name="slideshow_shuffle">Shuffle<div class="fl_r"></div></div>\
	<div class="_select _w100 mt16" onclick="checkbox(this);" name="slideshow_transition">Transition<div class="fl_r"><select id="transition_options_select">'+_slideshow_transition_options+'</select></div></div>\
	<div class="_w100 mt16" name="slideshow_trans_dur">Transition Duration\
	  <div class="slider-wrp">\
            <span class="slider-inp-val"></span><input min="100" max="8000" name="trans.duration" value="500" onchange="updateRangeValue(this);" type="range" class="slide-inp" /></div></div>\
	<div class="checkbox _w100 mt16" onclick="checkbox(this);" name="slideshow_timer">Timer<div class="fl_r"></div></div>\
	<div class="_w100 mt16" onclick="checkbox(this);" name="slideshow_delay">Delay\
	<div class="slider-wrp">\
            <span class="slider-inp-val"></span><input min="1000" max="8000" value="1000" name="delay" onchange="updateRangeValue(this);" type="range" class="slide-inp" /></div>\</div>\
	</form></div></section>';
	var _o_bottom_btns = '<div class="slideshow_bottom_control_btns">'+_is_slideshow_enabled+'<button class="none" onclick="ga(\'.mhb_back[rel='+rand+']\').trigger(\'click\');" id="new-slideshow-cancel-btn"></button><button style="margin-top:50px;" class="button wide_button" onclick="return saveSlideshowConfig(event);" id="save_slideshow">Save</button></div>';
	
	for(var i=0; i < 6; ++i)
	_g_photos += jprintf(_o_photo_markup,i,i,i,i,i,i);


	_g_data += _explore_your_photos+_gphotos_title+_separator_bullet+_gresort_slshow_images+_o_ph_mk_before+_g_photos+_o_ph_mk_after+_o_options_hd+_o_slideshow_config+_o_bottom_btns;
	
 
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.New_Theme_slideshow+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();
		
		var cnt = ga('.mob_popup_cnt#id_'+rand);
	
	cnt.addClass('mob_slideshow');
	cnt.html(_g_data);
	var popup = cnt;
	
	//kn_popup(lang.New_Theme_slideshow,_g_data,592,503, function(popup){ 
	var all_square_f_imgs = popup.find('#photos_sort_slideshow');
	all_square_f_imgs.sortable({axis:   'x',

                             cursor: 'move',

    }).disableSelection();
	ga('select#transition_options_select')
		.selectmenu();
	all_square_f_imgs.on('sortupdate', function (event, photo)
		{

			var d = ga(this)
				.sortable('serialize');
				var d = all_square_f_imgs.sortable('serialize', {
                attribute: 'data-sid',//this will look up this attribute
                key: 'img[]',//this manually sets the key
                expression: /(.+)/ //expression is a RegExp allowing to determine how to split the data in key-value. In your case it's just the value

            });

			var reqSortUpdate = $.ajax(
			{
				url: '/cmd.php',
				type: 'post',
				data: d + '&' + $.param(
				{
					'cmd': 'updateSlideShowPosition'
				}),
				cache: false
			});
			reqSortUpdate.done(function (a)
			{
				if (a != '1') return displayErr(lang.err_sort_photos);
			});
			reqSortUpdate.fail(function (b, c)
			{
				return displayErr(lang.err_req + b.status);
			});
		});
	
	all_square_f_imgs.css('opacity','.3');
	ajaxLoading();
	
	setTimeout(function(){
	var send = jAjax('/cmd.php','post', 'cmd=getSlidesShowConfiguration');
	send.done(function(d){
		
		//alert(d);
		all_square_f_imgs.css('opacity','1');
		removeAjaxLoad();

		var r = validateJson(d), _s_config = r.conf;

		if(r.photos.length)
		{


			for(var b =0; b < r.photos.length;b++){
				d = r.photos[b];

				var _square_of_ph = ga('.o_photo_slideshow:not(._noopac):first');
				_square_of_ph.attr('data-sid',d.id);
				_square_of_ph.addClass('_noopac');
				_square_of_ph.find('.slideshow-preview-uploaded-img').attr('style','background-image:url('+d.img+')');
				_square_of_ph.find('i').hide();
				_square_of_ph.find('.attach-photo_del').attr('id','slshowim_'+d.id);
			}
		}
			
			
			if(_s_config.enabled === 'yes') ga('#slideshow_enabled_cbox')[0].checked=true;
			

			
			// set default options
			if(_s_config.options !== '') {
			var sl_df_opts = validateJson(_s_config.options);
			sl_df_opts.overlay != 'false' ? ga('[name="slideshow_overlay"]').addClass('on') : '';
			sl_df_opts.shuffle != 'false' ? ga('[name="slideshow_shuffle"]').addClass('on') : '';			
			sl_df_opts.timer != 'false' ? ga('[name="slideshow_timer"]').addClass('on') : '';	
			ga('[name="slideshow_trans_dur"]').find('input[name="trans.duration"]').val(sl_df_opts.trans_duration);				
			ga('[name="slideshow_delay"]').find('input[name="delay"]').val(sl_df_opts.delay);
			ga('[name="slideshow_transition"] #transition_options_select').val(sl_df_opts.transition);	
			ga("#transition_options_select").selectmenu("refresh");
			}

	});
	},200);
	

	
	
	
	
	//);

	// overlay: true,shuffle:true,transition:'fade',preloadImage: true,transitionDuration: 3000,timer:false,delay:8000,
}

// save slideshow parameters
function saveSlideshowConfig(evt){
	
	evt.preventDefault();
	
    var el = ga(evt.target);
	var _is_photos = !1, _no_succ_notif = 0;
	// check if there's photos
	ga('#photos_sort_slideshow').children().each(function(){
		
		if(ga(this).hasClass('_noopac') || ga(this).hasClass('__occ'))
			_is_photos = !0;
		
	});
	
	
	if(!_is_photos){
		
		ga('#slideshow_enabled_cbox')[0].checked=false;
		kn_liveNotif(lang.theme_not_saved,'info',2800,lang.your_slideshow_was_not_saved);
		_no_succ_notif = 1;

	}
	

	var _form_c = ga('#slideshow_images_an_config form:first');
	var _s_overlay = _form_c.find('[name="slideshow_overlay"]').hasClass('on'),
		_s_shuffle = _form_c.find('[name="slideshow_shuffle"]').hasClass('on'),
		_s_transition = _form_c.find('[name="slideshow_transition"] #transition_options_select').val(),
		_s_trans_duration = _form_c.find('[name="slideshow_trans_dur"] input:first').val(),
		_s_timer = _form_c.find('[name="slideshow_timer"]').hasClass('on'),
		_s_delay = _form_c.find('[name="slideshow_delay"] input:first').val(),
		_s_enabled = ga('#slideshow_enabled_cbox').is(':checked') ? 'yes' : 'no';
		
	var _s_post_arr = new Object();
		_s_post_arr['overlay'] = _s_overlay;
		_s_post_arr['shuffle'] = _s_shuffle;
		_s_post_arr['transition'] = _s_transition;
		_s_post_arr['trans_duration'] = _s_trans_duration;
		_s_post_arr['timer'] = _s_timer;
		_s_post_arr['delay'] = _s_delay;
		_s_post_arr['enabled'] = _s_enabled;
		_s_post_arr['cmd'] = 'saveSlideshowConfig';
		ajaxLoading();

	var send = jAjax('/cmd.php', 'post', $.param(_s_post_arr));
	send.done(function(data){

		if(data === '1') {
			setTimeout(function(){ga('#new-slideshow-cancel-btn').trigger('click');},700);
			if(!_no_succ_notif) kn_liveNotif(lang.theme_saved,'done',3200,lang.now_the_theme_is_visible_into_your_profile);
		
			setTimeout(function(){ removeAjaxLoad(); if(!_no_succ_notif) window.location.reload();  },3000);
		
		} else return displayErr(data);
		
	});
}






function createTheme(el,ev){
	
	ev.preventDefault();
	
	var $el = $(el);
	
	var _choose_btn = '<div class="cr_theme_btn"><div class="cr_theme_progress_br"></div><form method="post" enctype="multipart/form-data"><input type="hidden" name="method" value="cover"/><input type="hidden" value="1" name="submit"/><input onchange="return uploadProfileCovers(this,event,\'1\',\'cover\');" class="_ff_slw_sorting html5-link-upload cr_inputfile" type="file" accept="image/*" name="file[]"><i class="ic ic_theme_from_comp"></i><span class="cr_th_txt">'+lang.upload_from_computer+'</span></form></div><div class="cr_theme_btn" onclick="themeBuildSlideshow(this,event);"><i class="ic ic_theme_slideshow"></i><span class="cr_th_txt">'+lang.create_theme_slideshow+'</span></div>';
	//kn_popup(lang.New_theme,_choose_btn,'auto', 185);
	ga('#custom_theme_add_btns').html(_choose_btn);
	
}


function themePreview(id, object, evt)
{
	evt.preventDefault();
	evt.stopPropagation();
	var $object = $(object), $_b = $('body');
	// close preview
	var close_theme_preview = function (e)
	{
		e.preventDefault();
		ga('#hook_Modal_popLayerModalTHPRVW')
			.remove();
	}
	ajaxLoading();
	var send = jAjax($object.attr('href'), 'post', 'action=preview&i=' + escape(id));
	send.done(function (data)
	{
		removeAjaxLoad();
		var d = validateJson(data);
				
		var _theme_prf_p = ga('#up_K_theme');
		//createScrollBack();
		_theme_prf_p.html('<div class="uprf_coll_abs_kn"><div class="vp_header_kn_theme_bg"></div><div class="cover_t_c_repeat dzsparallaxer"><div id="hook_Block_ThemeTopCenterImageRB" class="hookBlock"><img class="kn_img_setted divimage dzsparallaxer--target" alt="" id="th_v_bod"></div></div></div>');
		
		
		ga('.vp_header_kn_theme_bg').removeAttr('style').attr('style','background-image:url('+d.body+')');
		ga('#th_v_bod').attr('src',d.photo);
		ga(window).scrollTop(0);//animate({'scrollTop':0},500);


		var send = jAjax($object.attr('href'), 'post', 'action=save&i=' + escape(id));
				send.done(function (data)
				{
					if (data === '0')
					{
						// error
						return displayErr(lang.err_save_theme);
					}else{
						
							kn_liveNotif(lang.theme_updated,'done',3500,lang.theme_was_successfully_updated);
					}
					
				});
/* params
 @str = text notif
 @l = offset left
 @t = offset top
 @c = color
*/
		/*
		var $d = $(data);
		$('body')
			.prepend($d);
		$d.find('.ic_close-w, #button_previewCancel, #popLayer_mo')
			.on('click', function (e)
			{
				close_theme_preview(e);
			});
		// save theme
		$d.find('#hook_FormButton_button_previewConfirm')
			.on('click', function (e)
			{
				e.preventDefault();
				var send = jAjax($object.attr('href'), 'post', 'action=save&i=' + escape(id));
				send.done(function (data)
				{
					if (data === '0')
					{
						// error
						return displayErr(lang.err_save_theme);
					}
					else
					{
						var res = validateJson(data);
						$('#t_cover_th_vw')
							.removeAttr('style')
							.find('img')
							.removeAttr('src')
							.attr('src', res.photo + '?v=' + Math.random());
						$('body #st_left_right_theme')
							.replaceWith('<style id="st_left_right_theme">.cover_t_c_repeat_l, .cover_t_c_repeat_r {   background-image: url(' + res.body + '?v=' + Math.random() + ');}body {    background-image: url(' + res.body + '?v=' + Math.random() + ');}</style>');
						// success
						close_theme_preview(e);
					}
				});
			});
			*/
	});
}

// switch to old themes
function switchToThisTheme(evt,popup_id){
	
	evt.preventDefault();
	var $el = ga(evt.target);
	var theme_id = escape($el.attr('id').match(/\d/g).join('')),
	cover_position = escape($el.data('cvposition')),
	cover_url = $el.data('themeurl');
	removeMobilePopupFromDom(popup_id);
	customCoverSet(cover_url,theme_id,cover_position);
	ga(window).scrollTop(0);
}


// Turn to standart theme
function standartTheme(evt){
	
	evt.preventDefault();
	var $el = ga(evt.target);
	
	return confirm_act(lang.switch_theme_to_default,function(event){ 
	
	
	var send = jAjax('/cmd.php', 'post', 'cmd=switchToDefaultTheme');
	send.done(function(data){
		
		if(data === '1') {
			
			kn_liveNotif(lang.theme_changed,'done',3500,lang.theme_was_successfully_switched_to_default);
			setTimeout(function(){window.location.reload();},4000);
			ajaxLoading();
		} else displayErr(lang.somethingWrong);
		
	});
	
	
	});
	
	
	
}
function scrollBackBtnTrigger(a,ev,to){
	
	ev.preventDefault();
	
	var $this = $(a);
	
	$this.remove();
	$('body').scrollTop(to);
}
function createScrollBack(){
	var $_b = $('body');
	var _last_scroll_pos = $_b.scrollTop();
		if(!$_b.find('#_theme_down_arr').length){
			
			$_b.find('#mainContent').append('<div onclick="scrollBackBtnTrigger(this,event,'+_last_scroll_pos+');" class="theme_down_ic" id="_theme_down_arr"><div class="th_down_txt">'+lang.back+'</div><div class="ic dwth_ic"></div></div>');
			
		}
		
		$(window).off('scroll.backbtn').on('scroll.backbtn', function(e){
		
			if($(this).scrollTop() >= _last_scroll_pos){
				$_b.off('scroll.backbtn');
				$('#_theme_down_arr').fadeOut(800,function(){$(this).remove()});
			}
		});
	
}
function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") {
  try {
    decimalCount = Math.abs(decimalCount);
    decimalCount = isNaN(decimalCount) ? 2 : decimalCount;

    const negativeSign = amount < 0 ? "-" : "";

    let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
    let j = (i.length > 3) ? i.length % 3 : 0;

    return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
  } catch (e) {
    console.log(e)
  }
}
 function foucsCommentInput(ev,cont){
	
	ev.preventDefault();
 
	
	var that = this;
	var _el = ga(ev.target);
 
	var is_video_popup = _el.closest('#video_all').length ? _el.closest('#video_all') : false;
	var comment_editor = is_video_popup ? is_video_popup.find('[contenteditable="true"]') : _el.closest('.feed').find('[contenteditable="true"]');
	
	if(cont)
		comment_editor = ga(cont).find('[contenteditable="true"]');
	
	comment_editor.addClass('input_highlight').focus().on(endAnimationEvent() + '.inputFocused', function(e) {
			
			ga(this).removeClass('input_highlight');
		});
 
	
}
 function priceFormat(){
	 
	 ga('.globalpriceformat').each(function(){
		 var str = ga(this).text();
		 var only_price_numb = str.match(/\d/g).join('');
		 var only_letters = str.replace(/[^a-zA-Z]+/g, '');
		 var new_price =  formatMoney( only_price_numb );
		 
 
		 ga(this).text(str.replace(only_price_numb,new_price));
		 
	 });
	 
 }
function videoControls(el,ev,id){
	ev.preventDefault();
	ev.stopImmediatePropagation();
	
	ga('.music_track_menu').remove();

	var mobmus_col_actionmenu = '<div class="music_track_menu __open" role="menu">\
								 <a onclick="deleteVideo(this,event);" rel-videoid="'+id+'" href="/cmd.php?q='+_U.i+'&cmd=deletevideo&vd='+id+'" class="fi fi-trsh menu-link" style="text-decoration:none;">\
								 <span class="mob-trash-20"></span><span class="ic_tx">Delete</span></a>\
								 <a onclick="editVideo('+id+');" class="fi fi-trsh menu-link" style="text-decoration:none;">\
								 <span class="mob-edit-20"></span><span class="ic_tx">Edit</span></a>\
								 </div>';
								 
								 
	el = ga(el);
	
	if(	!el.closest('.u_video_gal').find('.music_track_menu').length )
		el.closest('.u_video_gal').append(mobmus_col_actionmenu);
	else el.closest('.u_video_gal').find('.music_track_menu').remove();
		
}
// unblock user
function removeBlackList(ev, el, f)
{
	ev.preventDefault();
	ev.stopPropagation();
	var $el = ga(el);
	confirm_act(lang.unblock_confirm, function (event)
	{
		var uid = escape($el.data('unblockui'));
		var send = jAjax('/cmd.php', 'post', 'cmd=removeBlackList&id=' + uid);
		send.done(function (res)
		{
			if (res === '1')
			{
			/*	$el.closest('.u_cardsList_li')
					.fadeOut(function ()
					{
						ga(this)
							.remove();
					});*/
					ga('#blck_uid_'+uid).fadeOut(function ()
					{
						ga(this)
							.remove();
					});
			}
			else
			{
				displayErr(lang.unblock_err);
			}
			if(f) f();
		}); // ajax
	}); // confirmation
}
function profile_blacklist(uid)
{
	ga('#return_to_blacklist_pg')
		.trigger('click');
}
function friendControls(el,ev,id){
	ev.preventDefault();
	ev.stopImmediatePropagation();
	
	ga('.music_track_menu').remove();

	var mobmus_col_actionmenu = '<div class="music_track_menu __open" role="menu">\
								 <a onclick="deleteVideo(this,event);" rel-videoid="'+id+'" href="/cmd.php?q='+_U.i+'&cmd=deletevideo&vd='+id+'" class="fi fi-trsh menu-link" style="text-decoration:none;">\
								 <span class="mob-trash-20"></span><span class="ic_tx">Delete</span></a>\
								 <a onclick="editVideo('+id+');" class="fi fi-trsh menu-link" style="text-decoration:none;">\
								 <span class="mob-edit-20"></span><span class="ic_tx">Edit</span></a>\
								 </div>';
								 
	var friend_menu_html = '<div class="music_track_menu __open" role="menu">'+ga('#profile_friend_action').html()+'</div>';							 
	el = ga(el);
	
	if(	!el.closest('up_K_theme').find('.music_track_menu').length )
		el.closest('#up_K_theme').append(friend_menu_html);
	else el.closest('#up_K_theme').find('.music_track_menu').remove();
		
}

// keep visible header of active letter
function AlphaKeepVisible(e)
{
	e.preventDefault();
	var l = ga('.letter_header');
	var top_header = $('.toolbar');
	if (!l.length) return;
	var m = l.offset()
		.top;
	var b = 0;
	//$('[data-ltn]').removeClass('__active').css('top','auto');
	l.each(function ()
	{
		var $this = $(this);
		$this.removeClass('__active fixed_always')
			.css(
			{
				'top': 'auto'
			});
		//$this.removeClass('__active').css('transform','translate3d(0,0,0)');
		//if(top_header.offset().top+($('.toolbar').height()/2)+(l.height()/2)+10 >= $(this).offset().top && !$this.hasClass('__active'))
		if (top_header.offset()
			.top + top_header.height() >= $(this)
			.offset()
			.top) $this.addClass('__active fixed_always')
			.css(
			{
				'top': '48px'
			}); ///css('top', ($(window).scrollTop() - $this.offset().top) + $('.toolbar').height());//css('transform' , 'translate3d(0,'+($(window).scrollTop() - $this.offset().top) + $('.toolbar').height()+'px,0)');//'+='+(top_header.offset().top + l.offset().top) - ($('body').scrollTop()));
		/*
		if($this.offset().top + $this.outerHeight() >= $('[data-ltn]:eq('+($this.index()+1)+')').offset().top){
		//$this.css('top','-='+$this.offset().top + $this.outerHeight() - $('[data-ltn]:eq('+($this.index()+1)+')').offset().top);//$('[data-ltn]:eq('+($this.index()+1)+')').css('background','red');
		////alphaHeadMoveSlow($this,$('[data-ltn]:eq('+($this.index()+1)+')'),top_header);
		}*/
		//$this.addClass('__active').css('transform','translate3d(0, '+($(window).scrollTop() - $this.offset().top) + $('.toolbar').height()+'px ,0)')
		$this.removeClass('__active');
	});
}

function alphaHeadMoveSlow(obj_o, obj_t, thead)
{
	var a = obj_o,
		b = obj_t,
		c = thead;
	obj_o.css('top', '-=1px') //+obj_o.offset().top - obj_t.offset().top);
	if (obj_o.offset()
		.top + obj_o.height() > thead.offset()
		.top) setTimeout(function ()
	{
		alphaHeadMoveSlow(a, b, c);
	}, 10);
}



function translate_str(evt,el) {
	
	evt.preventDefault();
	el = ga(el);
	var str_txt = el.find('[rel="str_text"]').text();
	var send = jAjax('/cmd.php', 'post', { 'cmd':'translate_str', 'str_text':str_txt});
	
	send.done(function(data){
		 
		if(data){
			var tr_txt_container = el.closest('.div_str_translate');
			tr_txt_container.addClass('_translated');
			tr_txt_container.find('.tr_output').removeClass('__none').text(data).addClass('_replies__highlight');
			tr_txt_container.find('a.a_str_translate').removeAttr('onclick').addClass('curDefault').css('color','#919798');
		} else {
			
			displayErr(lang.somethingWrong);
		}
	
	});
	
}
function cropPicture(el){
	el = ga(el);
	if (typeof g_element != 'undefined') g_element.show();
	var send = jAjax('/cmd.php','post', {cmd:'crop-photo','pictureid': escape(el.data('pictureid'))} );
	
	send.done(function (data)
	{
		 
		 
		ga('body').prepend(data);
		 
		
		setTimeout(function ()
		{	//resizePopup(true, 'auto', 'auto', false);
		ga('.photo-layer_cnt_main').css({'width' : ga(window).width()+'px', 'height' : ga(window).height()+'px','margin':'auto','overflow':'hidden'});
		
		ga('.pcrop_close_btn,.js-cancelCrop').on('click',function(){ ga('#popup_layer_crop_photo').remove(); });
			/*g_element = ga(el);
			var mParent = ga('.cr_photo_bg');
			ga('.popup_ovr')
				.css('z-index', '-1');
		    mParent.css('height', psize[1]);*/
			ga('.cropper_img')
				.css(
				{
					'max-width': ga(window).width()-50 +'px',
					'max-height': ga(window).height() -50 +'px'
				});
		}, 10);
	});
	
}


function resizePopup(mt, h, w, p, pd)
{
	var c = ga('#hook_Block');
	var t = p ? ga('table.mw_tbl') : '';
	var style = {};
	// if p have value, mean is the light popup called
	if (t) t.css('width', w);
	if (p == 'right' || p == 'left') return rsSidPopup(p, w, pd);
	var mxH = mt ? parseInt(_winH - 40) : (_winH / 2) - (c.height() / 2);
	style['marginTop'] = p == 'sub_header' ? '50' : (_winH - mxH) / 2;
	style['marginLeft'] = p == 'sub_header' ? '' : (_winW - (w === 'auto' || !w ? c.width() : w)) / 2;
	style['visibility'] = 'visible';
	style['overflow'] = 'hidden';
	style['height'] = h == 'auto' ? mxH : (!h ? '' : h);
	style['width'] = w == 'auto' ? _winW - 100 : (!w ? '' : w);
	c.css(style);
	return [c.width(), c.height()];
}
// update profile's photo
function cropPhoto(p)
{  
	var cropper;
	var showCoords = function (c, img, oimgW, oimgH)
	{
		var fackW = img.width(),
			fackH = img.height();
		ga('#js_crop_x')
			.val(c.x);
		ga('#js_crop_y')
			.val(c.y);
		ga('#js_crop_x2')
			.val(c.x2);
		ga('#js_crop_y2')
			.val(c.y2);
		ga('#js_crop_w')
			.val(c.w);
		ga('#js_crop_h')
			.val(c.h);
		ga('#js_crop_w2')
			.val(fackW);
		ga('#js_crop_h2')
			.val(fackH);
		ga('#js_crop_w3')
			.val(oimgW);
		ga('#js_crop_h3')
			.val(oimgH);
	};
	var img = new Image();
	img.src = p;
	var alloWstart = false;
	img.onload = function ()
	{
		var imgW, imgH;
		if (typeof this.naturalWidth != 'undefined' || this.naturalWidth)
		{
			imgW = this.naturalWidth;
			imgH = this.naturalHeight;
		}
		else
		{
			imgW = this.width;
			imgH = this.height;
		}
		if (imgW <= _st.min_crop_w || imgH <= _st.min_crop_h)
		{
			removePopup();
			return displayErr(lang.err_small_img.replace('%x', _st.min_crop_w)
				.replace('%y', _st.min_crop_h));
		}
		else
		{
			$.getScript(_THEME+"/plugins/jcrop/jquery.Jcrop.js?v=12")
				.done(function (s, Status)
				{
					cropper = ga('#jcrop_img')
						.Jcrop(
						{
							setSelect: [0, imgH, 0, 0],
							createHandles: ['nw', 'ne', 'se', 'sw'],
							aspectRatio: 1,
							handleOpacity: 1,
							trueSize: [imgW, imgH],
							minSize: [224, 224],
							fadeTime: 500,
							bgFade: true,
							borderOpacity: 1,
							touchSupport: 1,
							onChange: function (c)
							{
								showCoords(c, ga('.cropper_img'), imgW, imgH);
								if (alloWstart) ga('#__plpcte_buttons')
									.addClass('__hidden');
								setTimeout(function ()
								{
									alloWstart = true;
								}, 1500)
							},
							onSelect: function ()
							{
								ga('#__plpcte_buttons')
									.removeClass('__hidden');
							},
						});
				})
				.fail(function (jqxhr, settings, exception)
				{
					displayErr("Something went wrong" + exception);
				});
		}
	}
}
// open photoviewer
function openPhotoViewer(e, obj)
{
	e.preventDefault();
	e.stopPropagation();
	var $this = ga(obj);
	var p_id = $this.data('vphi');
	var g = generateUrl($this[0]);
	var bd_prg_ic = ga('body #load_ic_pop_rd');
	if (ga('#pp_photo_viewer')
		.length) return false;
	var call_pv = jAjax(g[0], 'post', g[1] + '&cur_pid=' + escape(p_id) + '&type=pos');
	call_pv.done(function (data)
	
	{ //document.write('<pre>'+data);
	 
		var $d = ga(data);
		ga('body')
			.addClass(_nscroll)
			.append($d);
			
	if(hasTouchStartEvent){
		ga('html').addClass('touchstopprop');
	}
		
		$d.find('.photo-layer,#photo-viewer')
 
			.off('click.stopProp')
			.on('click.stopProp', function (e)
			{
				//e.preventDefault();
				//e.stopPropagation();
			});
		$d.find('.pviewer_close_btn')
			.off('click.mdcl')
			.on('click.mdcl', function ()
			{  
				ga('body')
					.removeClass(_nscroll);
				ga("#pp_photo_viewer")
					.remove();
				localStorage.removeItem('attch_checkUser');
				createUrl('', '', prev_url);
				ga('html').removeClass('touchstopprop');
			});
 
		var ppl_cur_img = $d.find('img#__plpcte_target');
		var ppl_img = new Image();
		ppl_img.src = ppl_cur_img.data('ppvwlg');
		ppl_img.onload = function ()
		{
			ppl_cur_img[0].src = this.src;
			ppl_cur_img.removeAttr('style');
			ga(".st_nv_popup_content_processing")
				.hide();
		};
	});
}
 




function showLikesToPosts(){
	
	 ga('[data-photolikesdropdown]').each(function(){
	
		var __forpid = escape(ga(this).data('photolikesdropdown'));
		var __container_atPeLK = ga('[data-lkdrp="hook_Block_LikesInPh_'+__forpid+'"]');
		var __tooltip_appendto = ga(this).data('appendtooltipto');
		var _is_community = ga(this).closest('[data-community="true"]').length ? '&community=1' : '';
		var _hasCateg = ga(this).data('itemcateg');
		var _is_dark = ga(this).hasClass('_lightp') ? false : true;
		
		var __dark_tooltip_markup = '<section id="ph_likes_for_'+__forpid+'"><div class="phlikes_tooltip __dark"></div></section>';
		
		var __dark_tooltip_markup = '<div data-lkdrp="hook_Block_LikesInPh_'+__forpid+'" id="hook_Block_LikesInPh_'+__forpid+'" class="posR">\
									<div class="sc-menu sc-menu__top '+ (_is_dark ? '__dark' : '__light') +' __lktooltip">\
									<div id="hook_Block_LikedUsersBlock_'+__forpid+'">\
									<ul class="u-menu">\
									<li сlass="u-menu_li">\
									<ul class="ucard-mini-list __ppeachpeople">\
									</ul>\
									</li>\
									<li style="display:none" class="mb-2x _all_pins"><a href="javascript:void(0);" data-pplikt="ppo_'+__forpid+'" data-popup-people-likedphoto="1" class="al">All %all_pins</a></li>\
									</ul>\
									</div>\
									</div>\
									</div>';
		var __lk_each_people_markup = '<li class="ucard-mini-list_li" %likedbyme>\
									<a href="/user/%profileid" class="ucard-mini o" hrefattr="true"><img src="/getPhoto?p=%photo&sz=small&g=%gender" class="ucard-mini_img">\
									<div class="ucard-mini_cnt">\
                                    <div class="ucard-mini_cnt_i __dc ellip">%uname</div>\
									</div>\
									</a>\
									</li>';
		
		if(typeof _clog_timeouts.likesPhDrw != undefined) { ga('.visb_lkdropdown:not(#hook_Block_LikesInPh_'+__forpid+')').fadeOut(); clearTimeout(_clog_timeouts.likesPhDrw);}
 
	    if(!ga(this).closest('li').find('[data-lkdrp="hook_Block_LikesInPh_'+__forpid+'"]').length){
		   ga(this).closest(__tooltip_appendto).append(__dark_tooltip_markup);
		   __container_atPeLK = ga('[data-lkdrp="hook_Block_LikesInPh_'+__forpid+'"]');
	}else{
		__container_atPeLK.addClass('visb_lkdropdown').fadeIn();
	}
	
	var repositionDropDownP = function (){
		if( !isElementInViewport(__container_atPeLK.find('div:first')) )__container_atPeLK.find('div:first').removeClass('sc-menu__top'); else __container_atPeLK.find('div:first').addClass('sc-menu__top');
	}

	
		if(!__container_atPeLK.find('.__ppeachpeople').length) return repositionDropDownP();
		
		var send = jAjax('/cmd.php', 'post', 'cmd=dropDownPhotoLikesPeople'+_is_community + (_hasCateg ? '&item='+_hasCateg : '') +'&photo='+__forpid);
		send.done(function(d){
			var _cntToAp = __container_atPeLK.find('ul.__ppeachpeople');
			if(d != 0){

				d = validateJson(d);
				var u = d.users;
				
				__container_atPeLK.find('li._all_pins').css('display',(d.total > 5 ? '' : 'none')).children().text(lang.All+' '+d.total);
				for(var j =0; j< u.length;++j){
					d = u[j];
					_cntToAp.append(__lk_each_people_markup.replace(/%likedbyme/g,d.id === _U.i ? 'likedbyme="1"' : '').replace(/%photo/g,d.photo).replace(/%gender/g,d.gender).replace(/%profileid/g,d.id).replace(/%uname/g,d.name));
					
				}

			} else _cntToAp.html(lang.err_comm_no_people_liked);
			
			 _cntToAp.removeClass('__ppeachpeople');
			 repositionDropDownP();
		});
	});
	
	
}
function randomIntFromInterval(min, max)
{
	return Math.floor(Math.random() * (max - min + 1) + min);
}
function link_photo_viewer(){
	
	if(ga('#link-photo-viewer').length){
		ajaxLoading();
		$.getScript(_THEME+'/plugins/photo-viewer/link-pviewer.js?v='+ randomIntFromInterval(9, 9999),function(){
			
			removeAjaxLoad();
		});
		
		
		
	}
	

	
}function selectThisLocation(evt){
	
	//evt.preventDefault();
	
	var el = ga(evt.target);
	var location_val = el.parent().data('location-name');
	var location_id = el.parent().attr('id');
	ga('.getuserlocation').val(location_val);
	ga('#location_id').val(location_id);
	el.closest('ul').slideUp();
 
	if(ga('#location_selected_from_list').length) 
		el.closest('section#google_found_locations').find('#location_selected_from_list').val(1).addClass('yes').removeClass('no');
	
}
function checkJson(text){
	
if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

  return true;

}else{

  return false;

}
	
}
function isBodyRestive(){
	var b = ga('body');
	
if(
b.hasClass('css-640') || 
b.hasClass('css-400') || 
b.hasClass('css-960') || 
b.hasClass('css-480') ||
b.hasClass('css-1024') ||
b.hasClass('css-1200') ||
b.hasClass('css-320')
) return true; else return false;
	
}
function gShortcutMenu(){
	
}
function scrollToAnchor(hash) {
    location.hash = "#" + hash;
}

function CommunityEditPage(){
	
	if(ga('#community-edit').length){
		
		
	ga('#pedit_status').emojiarea(
	{
		wysiwyg: true,
		buttonLabel: 'Emojis',
		buttonPosition: 'after',
		button:ga('#pedit_status_emoji_btn')
	});
	setTimeout(function(){
	ga('.ms_items_more_wrap').remove();},500);
	
	
	var comm_status_txt = ga('#pedit_status'), comm_up_status = ga('.pedit_labeled');
var limit = 100;
comm_up_status.find('div:first').keypress(function() {
	var l = this.innerHTML.length;
	
	ga('.comm_status_update_maxlength').html(  (limit - l) < 0 ? 0 : limit - l  );
	
  return  l < limit;
}).on({
  'paste': function(e) {
    var len = this.innerHTML.length,
      cp = e.originalEvent.clipboardData.getData('text');
    if (len < limit)
      this.innerHTML += cp.substring(0, limit - len);	
    return false;
  },
  'drop': function(e) {
    e.preventDefault();
    e.stopPropagation();
  }
});
	
	// general categories
	ga(document).off('selectmenuchange.createGroup').on( "selectmenuchange.createGroup", '#field_groups_select', function( ev, ui ) { 

    ga('[data-submenuselect="1"]').each(function(){ga(this).selectmenu( "widget" ).hide();});
	ga('[submenuselect]').each(function(){ga(this).selectmenu( "widget" ).hide();});

	//ga('#comm_category,#comm_subcategory').val('');

	ga(ui.item.value).selectmenu( "widget" ).show();
	
	 ga('#comm_general_category').val(ui.item.index);
	
	
	});

	
	// categories
	ga(document).off('selectmenuchange.createGroupGetSubcateg').on( "selectmenuchange.createGroupGetSubcateg", '.comm_hidden_select_1,.comm_hidden_select_2', function( ev, ui ) { 

    ga('[submenuselect]').each(function(){ga(this).selectmenu( "widget" ).hide();});

	ga('[data-subcategb="'+ui.item.value+'"]').selectmenu( "widget" ).show();
	ga('#comm_category').val(ui.item.value);
	
	if(ga('[data-subcategb="'+ui.item.value+'"]').length)
	ga('#community_hidden_inputs').append('<input type="hidden" id="comm_subcategory" value="" />'); 
	else ga('#comm_subcategory').remove();
	
	});
	
	// subcategories
	ga(document).off('selectmenuchange.createGroupGetSubcategs').on( "selectmenuchange.createGroupGetSubcategs", '[name="comm_subcateg"]', function( ev, ui ) { 

	ga('#comm_subcategory').val(ui.item.value);
	
	});
	
	
	/* birthday */
	ga(document).off('selectmenuchange.createGroupBirthdayDay').on( "selectmenuchange.createGroupBirthdayDay", '[name="day"]', function( ev, ui ) { 

	ga('#community_bd_day').val(ui.item.value);
	
	});
	ga(document).off('selectmenuchange.createGroupBirthdayMonth').on( "selectmenuchange.createGroupBirthdayMonth", '[name="month"]', function( ev, ui ) { 

	ga('#community_bd_month').val(ui.item.value);
	
	});
	ga(document).off('selectmenuchange.createGroupBirthdayYear').on( "selectmenuchange.createGroupBirthdayYear", '[name="year"]', function( ev, ui ) { 

	ga('#community_bd_year').val(ui.item.value);
	
	});
	
	// allow to post
	ga(document).off('selectmenuchange.AllowToAddPost').on( "selectmenuchange.AllowToAddPost", '#select_allow_to_post', function( ev, ui ) { 

	ga('#allow_to_post_input').val(ui.item.value);
	});
	
	
ga('select').selectmenu();
if(ga('#comm_general_category').val() != '1') ga(".comm_hidden_select_1").selectmenu( "widget" ).hide();
if(ga('#comm_general_category').val() != '2') ga('.comm_hidden_select_2').selectmenu( "widget" ).hide();
ga('.comm_hidden_sub_select_family').selectmenu( "widget" ).hide();
ga('.comm_hidden_sub_select_music').selectmenu( "widget" ).hide();
ga('.comm_hidden_sub_select_bhealth').selectmenu( "widget" ).hide();
ga('.comm_hidden_sub_select_communication_services').selectmenu( "widget" ).hide();
ga('.comm_hidden_sub_select_celebrity').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_culture_art').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_entertainment').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_internet').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_products_stores').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_restaurants').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_sport').selectmenu('widget').hide();
ga('.comm_hidden_sub_select_transportation_services').selectmenu('widget').hide();

auto_rsz(ga('#group_edit_desc'));
//data-subcategb="Music"
ga('[data-subcategb="'+ga('#comm_category').val()+'"]').selectmenu( "widget" ).show();
//ga('#field_groups_select').trigger('selectmenuchange.createGroupGetSubcateg');
///setTimeout(function(){ga('#field_groups_select').selectmenu("refresh").trigger("selectmenuchange.createGroup");},500);

communityGetLocation('_e');
		
		
	}
	
}
function communityGetLocation(e){
	e = e || '';

	// create community location on map
	if( ga('#club_map_cnt'+e).length ){ 
	var _comm_loc_data = ga('#community_location_hook_data'+e).html();
	  var d_lc_map_dt = objHook(_comm_loc_data);
	  var club_map_design = '<div class="feed-tip-map-loc media-map" id="community-tip-map-loc'+e+'-' + d_lc_map_dt['pl-i']+'"><div class="map_loading"><div class="map_load_ic tico_img"></div></div></div>';
		var club_map_address = '<div class="club_map_address">'+d_lc_map_dt['road']+'<span class="communities_row_info_bullet">&#8226;</span>'+d_lc_map_dt['city']+',&nbsp;'+d_lc_map_dt['country']+'.</div>';
		ga('#club_map_cnt').html(club_map_address+club_map_design);				
									
									postPopupBuildMap(_comm_loc_data, 'community-tip-map-loc'+e+'-' + d_lc_map_dt['pl-i']);
	
	}
}
function postPopupBuildMap(data, customid)
{  
	var m_id = !customid ? 'post-tip-map-loc' : customid;
	var mp_data = objHook(data);
	var latlng = [mp_data['pl-lt'], mp_data['pl-ln']];

 
	if(  ! ga('#'+m_id).length ) return;
	
	
	var pmap = new L.Map(m_id)
		.setView(latlng, 17)
		.whenReady(function ()
		{
			ga('.map_loading')
				.remove()
		});
	pmap.addLayer(new L.TileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw',
		{
		maxZoom: 18,

		id: 'mapbox.streets'	
		}
	
	)); //base layer
	var newMarker = new L.marker(latlng)
		.addTo(pmap);
	newMarker.bindPopup(mp_data['display_name']); //.openPopup();
	L.Util.requestAnimFrame(pmap.invalidateSize, pmap, !1, pmap._container);
	ga('.leaflet-control-attribution.leaflet-control')
		.remove();
}
function communityPage(){
	
	if( typeof communityFeed == 'function' )
	communityFeed();

	communityGetLocation();
	
	if(ga('#group_pg_details,#page_contain_cover').length){
		ga('html').addClass('cover_in_page');
	}else{
		ga('html').removeClass('cover_in_page');
	}

}
function getExtension(filename) {
    var parts = filename.split('.');
    return parts[parts.length - 1];
}

function isImage(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
    case 'jpg':
    case 'gif':
    case 'bmp':
    case 'png':
        //etc
        return true;
    }
    return false;
}

function isVideo(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
    case 'm4v':
    case 'avi':
    case 'mpg':
    case 'mp4':
	//case 'wmw':
        // etc
        return true;
    }
    return false;
}
function feedEmpty(a,b){
	var x = '<div class="feed_loaded_complete"></div>';
	b ? a.after(x) : a.append(x);
	
}
function communityAlbumPicturesWall(n,is_video){
 
	var pictures_obj = ga('#community_pictures_wall');
	var pictures_count = n ? 2 : pictures_obj.data('pictures-count');


	
	if(pictures_obj.length && pictures_count > 0) { 
	
		var _all_items = pictures_obj.find('img');

 

            ajaxLoading();	

	

			
			pictures_obj
			.justifiedGallery(
			{
				rowHeight:80,
				//maxRowHeight: 'auto',
				margins: 4,
				border: 0,
				rel: 'communityWallItem',
				lastRow: 'nojustify',
				fixedHeight: false,
				captions: true,
				randomize: false,
				/*sizeRangeSuffixes: {
					lt100 : '_t', 
					lt240 : '_m', 
					lt320 : '_n', 
					lt500 : '', 
					lt640 : '_z', 
					lt1024 : '_b'
				}*/
			})
			.on('jg.complete', function (e) {
				removeAjaxLoad();

			});
			
			
	}

}
function runAjax(element, evt, type)
{
	evt.preventDefault();
	var $el = $(element),
		href = $el.attr('href')
		.split('?'),
		url = href[0],
		data = href[1];
	var query = jAjax(url, type, data + '&view_as=json');
	return query;
}

function checkforMobile(){
	
	
	if(hasTouchStartEvent)
	ga('body').addClass('_touch');
	else
	ga('body').addClass('_hover');
	
}

function checkForTransparentMHEAD(){
	
	

		var l_opac;
	if(ga('html').hasClass('cover_in_page')){	
	ga(window).off('scroll.communityCoverOvr').on('scroll.communityCoverOvr', function(e){
 
		 
		var _nav_m = ga('.groupCover'), toolbar_menu = ga('#mhead');
/*	if(toolbar_menu.offset().top >= (_nav_m.offset().top + _nav_m.height()) ) {
	
	if(!this.a_start_position)
	this.a_start_position = ga(this).scrollTop();

	//ga('html').removeClass('cover_in_page');
	this.a = true;
	} 
	else 
		if ((toolbar_menu.offset().top - toolbar_menu.height())  <= _nav_m.offset().top ) {
		 
		//ga('html').addClass('cover_in_page');
		console.log('achia');
		this.a = false;
		//alert('o');
		
             var getOpac = function() {
                 var _viewportSize = toolbar_menu.height();
                 var yOffset = toolbar_menu.offset().top - toolbar_menu.height()//lY - iY; // difference between initial and current position
                 var result = Math.abs(yOffset / (_viewportSize / 1.2));
                 return (1 - result);
             }
			 console.log(getOpac());
			 
			toolbar_menu.css('background-color','rgba(93, 120, 148, '+getOpac()+')');
			 
	}		
		
		*/
		  

             var getOpac = function() {
                 var _viewportSize = toolbar_menu.height();
                 var yOffset = toolbar_menu.offset().top - toolbar_menu.height()//lY - iY; // difference between initial and current position
                 var result =yOffset / _viewportSize; //.abs(yOffset / _viewportSize);
                 return result > 1 ? 1 : (result < 0 ? 0 : result); 
             }
			 console.log(getOpac());
			 
			 
			 
			 if(getOpac() <= 0){
			ga('body').find('#mhead_before').remove();
			ga('body').prepend('<style id="mhead_before">.cover_in_page #mhead:before{background-color:transparent;opacity:1;background-image: -webkit-linear-gradient(rgba(0,0,0,.5) 0%,transparent);background-image: linear-gradient(rgba(0,0,0,.5) 0%,transparent);}</style>');
				 
			 }
			 
			 
			 
			 
			 if(l_opac != getOpac()){
			//toolbar_menu.css('background-color','rgba(93, 120, 148, '+getOpac()+')'); 
			ga('body').find('#mhead_before').remove();
			ga('body').prepend('<style id="mhead_before">.cover_in_page #mhead:before{opacity:'+getOpac()+';}</style>');
			 }
		l_opac = getOpac();
	});
		
	} else {
		ga('#mhead_before').remove();
		
	}
	
}


	function LikesByPeoplePopup(el,evt){
		var $this = ga(el);
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.back+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();
		
		var cnt = ga('.mob_popup_cnt#id_'+rand);

		
		
	var people = '';
	var people_u_markup_schel = '<ul class="mob_popup_friends_list"></ul>';
		
		var people_u_markup = '<li><a class="mob_invite_friends_to_com_sel" href="/user/%uid" onclick="ga(\'#mobile_popup_back_btn\').trigger(\'click\');" hrefattr="true">\
        <div class="mob_popup_f_avatar f_left"><img src="/getPhoto?p=%pid&sz=thumb&g=%gender" alt="%uname"></div>\
        <div class="mob_popup_f_name ellip">%uname</div>\
    </a></li>';
		
		
		
		
		
		
		var send = jAjax('/cmd.php', 'post', {'cmd':'popup_liked_by_people','id':$this.data('postid'),'type':$this.data('posttype'),'clubid':$this.data('clubid')});
		
		send.done(function(data){
			
			var d = validateJson(data);
			
				cnt.html(people_u_markup_schel);
				
				
				
						for(var i = 0;i< d.length;i++){
							var b = d[i];
							people += people_u_markup.replace(/%uid/g,b.id).replace(/%pid/g,b.photo).replace(/%uname/g,b.name).replace('%gender',b.gender);
							
						}
						
						
						cnt.find('ul.mob_popup_friends_list').html(people);
			
		});
		
	}
function sLoadImages() {
	
	var o_images = ga('img[data-original]');
	
	if( o_images.length ){
		
		
		ga(window).on('scroll.LoadOiriginalImages', function() {
			
			o_images.each(function(){
				
				if( isElementInViewport(ga(this)) ){
					
					
					ga(this).attr('src',ga(this).data('original'));
					
					
				}
				
			});
			
		});
		
		
	}
	
	
	
	
}

function constructPostsPage(){
	
var status_pg_feed = ga('.media_feed.status_pg');
wallPhotosCollage(status_pg_feed,function(){});

			// build map
			if(status_pg_feed.find('.map-box').length)
				status_pg_feed.find('.map-box').each(function(){ 
					var _t_data_ka = ga(this).find('.hookMapData').html();
					var d_lc_map_dt = objHook(_t_data_ka);
					postPopupBuildMap(_t_data_ka,'feed-tip-map-loc-'+d_lc_map_dt['pl-i']);
				});
	
	
}
// play gif images
function playGifImages() {
	
	ga(window).off('scroll.playGif').on('scroll.playGif', function(e){
		

 

	});
	
	
	// SCROLLING
	ga(window).on('scroll.gifAutoPlay',$.debounce( 250, true, function(){

	
	ga('.gifplayer:not(.gifed)').each(function(){
		
		var _this = ga(this);
		
		if(!_this.hasClass('gifed')){
			
		_this.gifplayer();
		_this.addClass('gifed');
		_gifs.push(_this.data('gif-id'));
 
		}
		
		
	});
	
	
				if(_gifs.length){
					for(var i=0;i<_gifs.length;i++){
						var _i_gif = ga('[data-gif-id="'+_gifs[i]+'"]'), _gif_element =  _i_gif.parent().find('.gp-gif-element:last');
						if ( _gif_element.length && !isElementInViewport( _gif_element ) ){
						_i_gif.gifplayer('stop');
						}  
					}
				}
	
	
	} ) );
	
	// STOP SCROLLING
	ga(window).on('scroll.gifAutoPlay',$.debounce( 250, function(){

	
	
				if(_gifs.length){ 
					for(var i=0;i<_gifs.length;i++){
						var _i_gif = ga('[data-gif-id="'+_gifs[i]+'"]'), _gif_element =  _i_gif.parent().find('.gp-gif-element:last').length ? _i_gif.parent().find('.gp-gif-element:last') : _i_gif.parent().find('.play-gif');
						if ( _gif_element.length && isElementInViewport( _gif_element ) ){  
						 _i_gif.trigger('mouseover');
						}  
					}
				}
	
	
	
	
	} ) );
	
	
	
	
	
 
}

function selectProfilePhoto(ev,el) {
	ev.preventDefault();
	ev.stopPropagation();
	 
	 
	 
		// open mobile popup
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+lang.change_profile_picture+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();	
		
		var cont = ga('.mob_popup_cnt#id_'+rand);
	 
	 
	 
	 
	 
	var g = generateUrl(el);
	var send = jAjax(g[0], 'post', g[1]+'&type=pos');  
	send.done(function (data)
	{  

			cont.html(data);
		
	});
	
}
// mutual friends popup
function popupMutualFriends(el, ev)
{
	ev.preventDefault();
	ev.stopImmediatePropagation();
	var $this = ga(el);
	var $this_data = $this.data('mtforui');
	var uid = escape($this_data.uid.match(/\d/g)
		.join(''));
	var _title = lang.mob_popup_mutual_friends;
		
		
		// open mobile popup
		var rand = randomIntFromInterval(9, 9999);
		var a_mob_popup = ga('<a href="javascript:void(0);" data-mobilepopup=\'{"header_title":"'+_title+'","rand":"'+rand+'"}\'></a>');
		
		ga('body').prepend(a_mob_popup);
		a_mob_popup.trigger('click');
		a_mob_popup.remove();	
		
		var jCont = ga('.mob_popup_cnt#id_'+rand);
		var u_li = '';

		
	var dcont = '<div id="modal_main" style="height:'+(ga(window).height()-180)+'px" class="modal_main ">\
    <div id="modal_cnt" class="modal_cnt ppymknw nano">\
        <ul class="photoPeopleLike nano-content">\
        </ul>\
    </div>\
</div>';
		
		
		
	var __plkphotouserMarkup = '<li class="cardListUsLk">\
                <a href="/user/%uid" onclick="ga(\'#mobile_popup_back_btn\').trigger(\'click\');" hrefattr="true"><div class="userCard">\
					<div class="ucard_ph_lk432">\
                                <span class="photoWrapper"><img src="/getPhoto?p=%photo&sz=thumb&g=%gender" alt="" width="128" height="128"></span>\
                            </div>\
                    <div class="card_add">\
                        <div class="ellip"><span class="o p_mutualfriendsa">%uname</span></div>\
						<div class="_2uju6 ellip">%nickname</div>\
                    </div>\
				<div class="_72gdz _73dsgg"><span class="_e616g"><span class="_e425">%yearsold</span><span class="_e425">%cityCountry</span></span></div>\
				 </div></a>\
            </li>';
			
		
		
		
		
var send = jAjax('/cmd.php', 'post', { cmd: 'mutualfriendsfor', u: uid});

 send.done(function(data){
	 
 
				if (data == '0') return jCont.html(lang.err_tehnic);
				else if (data == '1') return jCont.html(lang.not_found);
				else
				{
					var knw_d = validateJson(data);
					var a = knw_d.users;
					var count_m = knw_d.count;
					if (!count_m)
					{
						return jCont.html(lang.popup_not_found_mutual_friends);
					}
					jCont.html(dcont);
 
					for (var b = 0; b < a.length; b++)
					{
						var res = a[b];
						u_li += __plkphotouserMarkup.replace(/%uid/g, res.id)
								.replace(/%photo/g, res.photo)
								.replace(/%uname/g, res.name)
								.replace(/%nickname/g, res.nick)
								.replace(/%yearsold/g, res.yearsold +'&nbsp;'+lang.yearsold)//res.fr_status === 'confirmed' ? '<button class="_aj7mu isfriend _2hpcs _95tat _o0442">'+lang.friends+'</button>' : ( res.fr_status === 'pending' ? '<button class="_aj7mu __disabled _2hpcs _95tat _o0442">'+lang.friend_request_has_been_sent+'</button>' : '<button href="/profile?q='+_U.i+'&cmd=addFriend&i='+res.id+'" onclick="addFriend(this,event,\''+o_krypt('+res.id+')+'\',\'button\')" class="_aj7mu _2hpcs _95tat _o0442">'+lang.friend_request+'</button>' ) )
								.replace(/%cityCountry/g, lang.from + '&nbsp;' +res.cityCountry)
								.replace(/%gender/, res.gender);
					}
					jCont.find('ul.photoPeopleLike').html(u_li);
					 
					 
				}
	 
 });
		
		


			
			
 
 
}
function communitySendFileDescription(d,fileid,_id)
{
	var descr = d.val();

	if (!$.trim(descr)) return false;
	ajaxLoading();
	var req = jAjax('/communities.php', 'post',{cmd:'save-file-info',info:descr,file_id:escape(fileid),id:escape(_id)});
	req.done(function (resp)
	{
	removeAjaxLoad();
		if (resp != '1') return displayErr(lang.somethingWrong);
		else
		{
			
			d.removeAttr('style');
			
		}
	});
}
function copyToClipboard(el) {

    // resolve the element
    el = ga(el)[0];//(typeof el === 'string') ? document.querySelector(el) : el;

    // handle iOS as a special case
    if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {

        // save current contentEditable/readOnly status
        var editable = el.contentEditable;
        var readOnly = el.readOnly;

        // convert to editable with readonly to stop iOS keyboard opening
        el.contentEditable = true;
        el.readOnly = true;

        // create a selectable range
        var range = document.createRange();
        range.selectNodeContents(el);

        // select the range
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        el.setSelectionRange(0, 999999);

        // restore contentEditable/readOnly to original state
        el.contentEditable = editable;
        el.readOnly = readOnly;
    }
    else {
        el.select();
    }

    // execute copy command
    document.execCommand('copy');
}// allow only numbers and dot .
function inputPrice(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
 
	
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
function st(){
	var style_css = ga('[scomm="common-global-style"]');
	style_css.attr('href', style_css.attr('href')+(new Date().getTime()));
	return true;
}
function marketViewProductInDom(){
	
	if( ga('.market_view_product').length){
 
		market.viewProductInDOM();
	} else {
		
		market.viewProductInDOM_QUIT();
	}
	
}
 function marketPage(){
   if(ga('#marketplace').length){
 
			market.searchFilter();
		}  

	 
 }
 function notifications(){
	 
	 if(ga('.notifs_menu').length){
		 
		 
		 ga('.notifs_menu_btn.all').click();
	 }
	 
 }
var clear_interval_gif;
function domStart() {
 
login_form();
reg_form();
headerNavButton();
upload_form();
userPhotoWall();
albSquareCheck();
resizeMessenger();
userSettingsPage();
link_photo_viewer();
inputPhone();
playMusicInBackground();
newCommunityPage();
CommunityEditPage();
communityPage();
communityAlbumPicturesWall();
getUserLocation();
filterBoxM();
sLoadImages();
 usersBooksPage();
	commentsInPostsPage();
	generateVegasTheme();
checkforMobile();
playGifImages();
marketViewProductInDom();marketPage();
usersOnMapPage();
checkForTransparentMHEAD();
constructPostsPage();
giftsSlider();
notifications();
if(typeof searchRightFilter === 'function') searchRightFilter();
setTimeout(function(){
//showLikesToPosts();
},4000);

/*
clearInterval(clear_interval_gif);
clear_interval_gif = setInterval(function(){
	
[].slice.apply(document.images).filter(is_gif_image).map(freeze_gif);

	
},2000);
*/

 	
	// custom [select]
	ga('select')
		.selectmenu({
			
			  create: function( event, ui ) {
				  
				//  var t_id = ga(event.target).attr('id')+'-menu';
				  
				 // ga('#'+t_id).parent().addClass('nano');
				 // ga('#'+t_id).addClass('nano-content');
				  
				  
				 // ga(this).addClass('nano');
				  //ga(this).find('ul').addClass('nano-content');
				  
				//  setTimeout(function(){ga('#'+t_id).parent().nanoScroller();},400);
				  
			  }

			
			
		});

	ga(window)
		.off('scroll.pointOvr')
		.on('scroll.pointOvr', function (e)
		{
			var scroll_top = ga(window)
				.scrollTop();
			clearTimeout($.data(this, 'scrollTimer'));
			$.data(this, 'scrollTimer', setTimeout(function ()
			{
				ga('#pointerOverlay')
					.removeClass('__auto');
			}, 250));
			ga('#pointerOverlay')
				.addClass('__auto');
					var _topoffset = _st.scrollTopPosition;
			        if (scroll_top > _topoffset) {
				    ga('#scrollToTop').addClass('__active');
			          //  el.css('top', scroll_top - _topoffset);
			        } else {
				    ga('#scrollToTop').removeClass('__active');
			          //  el.css('top', '');
			        }

		});


ga(document).on('click.coseLeftMenu', '#m_helper', function(e){
	
	ga('body').removeClass('lm_opened');
	
});



	if( ga('#hook_feed_wl_pg').length )
	getWall();

/*
document.body.addEventListener("touchmove", function(event) {
    event.preventDefault();
    event.stopPropagation();
}, false);
*/
 
}
/*
window.onerror = function (message, url, lineNo){
    alert('Error: ' + message + '\n' + 'Line Number: ' + lineNo);
    return true;
}*/


ga(document).ready(domStart);