// profile-view.js [dpp]

// tooltip.js

// <@--# if expr="$tooltip!=1" -->
// <@--# set var="tooltip" value="1" -->

var Tooltip=function(el, options)
{
	this.init(el, options);
};

Tooltip.prototype =
{
	tpl:'<div class="ibc">{content}</div><div class="ibt"><b></b></div><div class="ibr"><b></b></div><div class="ibb"><b></b></div><div class="ibl"><b></b></div>',

	init:function(el, options)
	{
		this.el=$(el);
		this.initialized=false;
		this.setOptions(options);

		if(!this.el) return;

		$e.add(this.el, "mouseover", this.show, this);
		$e.add(this.el, "mouseout", this.hide, this);

		this.content=this.el.title;
		this.el.title="";

		var descendants=$q.select('*',this.el);
		for(var i=0, n=descendants.length; i<n; i++){
			if('alt' in el) el.alt='';
		}
	},

	remove:function()
	{
		$e.del(this.el, "mouseover", this.show, this);
		$e.del(this.el, "mouseout", this.hide, this);
		this.el=null;
	},

	setOptions:function(options)
	{
		this.options={
			backgroundColor:'#FFFCB5',
			borderColor:'#FFDC6E',
			textColor:'#7D660A',
			textShadowColor:'',
			maxWidth:250,
			align:"left",
			delay:0,
			mouseFollow:false,
			opacity:.75,
			appearDuration:0,
			hideDuration:.25
		};

		$config(this.options, options || {});
	},

	show:function(el)
	{
		var xy=$e.pointerXY();
		this.xCord=xy.x;
		this.yCord=xy.y;
		if(!this.initialized)
			this.timeout=setTimeout(this.appear.bind(this), this.options.delay);
	},

	hide:function(el)
	{
		if (this.initialized)
		{
			if (this.options.mouseFollow && this.el) $e.del(this.el, "mousemove", this.update, this);
			this.tooltip.parentNode.removeChild(this.tooltip);
		}

		this._clearTimeout(this.timeout);

		this.initialized=false;
	},

	update:function(e)
	{
		var xy=$e.pointerXY();
		this.xCord=xy.x;
		this.yCord=xy.y;
		this.setup();
	},

	appear:function()
	{
		this.tooltip=$u.el('div',{
			id:'clipboard_title',
			style:'display: none;',
			innerHTML:$u.tpl(this.tpl,{content:this.content})
		});

		document.body.appendChild(this.tooltip);

		this.options.width=$el.dimensions(this.tooltip).width;
		this.tooltip.style.width=this.options.width+'px';  // IE7

		this.setup();

		if (this.options.mouseFollow)
			$e.add(this.el, "mousemove", this.update, this);

		this.initialized=true;
		this.tooltip.style.display='block';
	},

	setup:function()
	{
		if(this.options.width>this.options.maxWidth){
			this.options.width=this.options.maxWidth;
			this.tooltip.style.width=this.options.width+'px';
		}

		var doc_wh=$el.dimensions(document);
		if(this.xCord+this.options.width >= doc_wh.width){
			this.options.align="right";
			this.xCord=this.xCord-this.options.width+20;
		}

		this.tooltip.style.left=this.xCord-7+"px";
		this.tooltip.style.top=this.yCord+12+"px";
	},

	_clearTimeout:function(timer)
	{
		clearTimeout(timer);
		clearInterval(timer);
		return null;
	}
};

// <@--# endif -->

// clipboard.js [vital, dpp]

var Clipboard={
	active:false,
	text:'Copied',
	timestamp:0,
	focused:false,

	init:function()
	{
		if($('this_text'))
			this.text=$('this_text').title;

		this.active=window.thisData || Flash.init(7);

		if(this.active)
			$e.on('.copy_text',this.copy_click,this);
	},

	copy_click:function(el)
	{
		if(el.tagName=='INPUT' || el.tagName=='TEXTAREA'){
			if(!el.onfocus){
				el.onfocus=this.onfocus;
				el.onfocus();
			}

			if(this.focused && this.copy(el.value)){
				this.focused=false;
				var xy=$e.pointerXY();
				this.copied(xy.x,xy.y);
			}
		}else if(el.rel){
			var ctxt=($(el.rel).tagName == 'INPUT' || $(el.rel).tagName == 'TEXTAREA') ? $(el.rel).value : $(el.rel).innerHTML;

			if(this.copy(ctxt)){
				var xy=$e.pointerXY();
				this.copied(xy.x,xy.y);
			}
		}
	},

	onfocus:function()
	{
		var el=this;

		setTimeout(function(){ el.select(); }, 0);

		Clipboard.focused=true;	//FIXME
	},

	copy:function(text2copy)
	{
		if(!this.active) return false;

		if(window.thisData){
			return window.thisData.setData("Text", text2copy);
		}else{
			var flashcopier='flashcopier';

			if(!$(flashcopier))
				document.body.appendChild($u.el('div',{id:flashcopier}));

			$(flashcopier).innerHTML='';
			var divinfo='<embed src="' + JSRoot + 'flash/_clipboard.swf" FlashVars="clipboard=' + encodeURIComponent(text2copy) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
			$(flashcopier).innerHTML=divinfo;
		}

		return true;
	},

	copied:function(x, y)
	{
		var ct=$('clipboard_title');

		if(!ct){
			ct=$u.el('div',{
				id:'clipboard_title',
				innerHTML:'<div class="ibc">' + this.text + '</div><div class="ibt"><b></b></div><div class="ibr"><b></b></div><div class="ibb"><b></b></div><div class="ibl"><b></b></div>'
			});
			document.body.appendChild(ct);
		}

		if(ct.style.display=='block')
			clearTimeout(this.timestamp);

		$config(ct.style,{
			display:'block',
			top:y+'px',
			left:x+'px'
		});

		this.timestamp=setTimeout('$("clipboard_title").style.display="none"', 1800);
	}
};

Clipboard=new ($class(dPage,Clipboard));

// dTooltip.js [dpp]

// <@--# if expr="$dtooltip!=1" -->
// <@--# set var="dtooltip" value="1" -->

var dTooltip=function(config)
{
	$config(this,config);
	this.init();
};

dTooltip.prototype=
{
	el:null,
	type:'',
	target:'',
	cel:null,
	x:0,
	y:0,
	html:'',
	images:[],
	scope:null,

	_re:null,
	_wrap:null,
	_cont:null,
	_tpl:'<div class="js_tooltip pngbox">\
		<div class="container">\
			<div class="central">\
				<div class="cont">\
					{html}\
				</div>\
				<div class="br"></div>\
			</div>\
		</div>\
		<div class="tr"></div>\
		<div class="bl"></div>\
	</div>',

	init:function()
	{

		if(!this.el)
			throw new Error('No element for dTooltip');

		this._re=new RegExp('(^|\\s)'+this.target+'(\\s|$)');

		this._wrap=$u.el('div',{
			id:'dTooltipWrap',
			className:'hidden',
			innerHTML:this._tpl
		});

		//this._cont=this._wrap.down('.cont');
		this._cont = $q.down(this._wrap, '.cont');

		document.body.appendChild(this._wrap);

		this.attachEventHandlers();

		if(this.images.length)
			$e.add(window,'load',$u.preloadImages.bind(null,this.images));

	},

	attachEventHandlers :function() {
		$e.add(this.el,'mouseover',this.test,this);
		$e.add(this.el,'mouseout',this.test,this);
		// $e.add(this._wrap,'mouseover',this.test,this);
		$e.add(this._wrap,'mouseout',this.test,this);
	},

	detachEventHandlers :function() {
		$e.del(this.el,'mouseover',this.test,this);
		$e.del(this.el,'mouseout',this.test,this);
		// $e.del(this._wrap,'mouseover',this.test,this);
		$e.del(this._wrap,'mouseout',this.test,this);
	},

	destroy:function()
	{

		this.detachEventHandlers ();

		document.body.removeChild(this._wrap);
		this._wrap=null;
		this._cont=null;
		this.el=null;

	},

	test:function(el)
	{
		var e=$e.e;

		if(e.type=='mouseout')
			el=e.relatedTarget||e.toElement;

		var p=el,
			cel=this.cel,
			w=this._wrap,
			b=document.body,
			re=this._re;

		if(el==cel) return;

		while(p && p!=cel && p!=w && !re.test(p.className) && p!=b)
			p=p.parentNode;

		if(!p || p==b) this.hide();
		else if(p!=w && p!=cel) this.show(p);
	},

	show:function(el)
	{
		this.cel=el;
		var config=this.format.call(this.scope || this,$(el));
		if(el) el.title='';

		this._cont.innerHTML=config.html;
		this._wrap.style.left=config.left+'px';
		this._wrap.style.top=config.top+'px';

		this._wrap.className=this.type;
	},

	hide:function()
	{
		this._wrap.className='hidden';
		this.cel=null;
	},

	format:function(el)
	{
		var e=$e.e;
		// var html='Test tooltip on element: <br/>'+el.nodeName+(el.id?('#'+el.id):'')+(el.className?('.'+el.className.split(' ').join('.')):'');
		var html=el.title;
		return {
			left:Event.pointerX(e),
			top:Event.pointerY(e),
			html:html
		};
	}
};

// <@--# endif -->


// show-more.js [elena]

ShowMore=
{
	name:'ShowMore',
	init : function() {
		$e.on('.js_show_more_link', this.load_more, this);
	},

	load_more : function(el)
	{
		if(!el.rev || !el.rel || el.rev == '' || el.rel == '')
			return;

		var wrappers = el.rel.split('|');
		this.block = $(wrappers[0]);
		this.global_block = wrappers[1] && $(wrappers[1]);
		this.el_loading = this.global_block ? el.up() : el;

		$u.startWaiting(this.el_loading);
		var p = el.getAttribute('rev').split('?');
		// el.rev = '';
		var myAjax = new Ajax.Request(p[0],
		{
			method : 'get',
			parameters : p[1],
			onComplete : this.onload_more.bind(this, el),
			onException: this.load_more_error.bind(this)
		});
	},

	onload_more : function(el, r)
	{
		$u.stopWaiting(this.el_loading);
		if(this.global_block) this.global_block.addClassName('unfolded');
		var link = el.up('.new_more') || el.up();
		var res = eval('(' + r.responseText + ')');

		if(!this.block || !link || !res)
			return;

		if(res.errno==0){
			this.block.innerHTML += res.html;
			if (res.more) {
				el.rev = res.more;
				if(this.global_block) {
					this.global_block.addClassName('more_exist');
					var links = this.global_block.select('.js_show_more_link');
					for(var i=0, l=links.length; i<l; i++) {
						links[i].rev = res.more;
					}
				}
			}
			else if(!res.more_hack)
				link.remove();
		}else{
			if(res.auth)
				window.location=res.auth;
		}
	},

	load_more_error:function(r, er)
	{
		$u.stopWaiting(this.el_loading);
		
	}
};

ShowMore=new ($class(dPage,ShowMore));

// contacts-menu.js

var ContactsMenu =
{
	current_menu : false,
	folders : {},
	current_folder : 0,
	friends_content : '',
	m : null,

	init : function()
	{
		$e.on({
			'.cm_friend':ContactsMenu.on_friend,
			'.cm_blacklist':ContactsMenu.on_blacklist,
			'.cm_folder':ContactsMenu.on_folder,
			'.cm_remove':ContactsMenu.on_remove
		}, ContactsMenu);

		Event.observe(document, 'mouseover', ContactsMenu.over_event);

		var f = Object.keys(vars.contact_menu.folder);

		for (var i=0; i<f.length; i++) if (f[i] != '-1')
		{
			var fn = vars.contact_menu.folder[f[i]][0];
			if (fn) ContactsMenu.folders[f[i]] = fn.substr(fn.indexOf('  ') + 2);
		}
	},

	out_event : function(e)
	{
		var el = Event.element(e);

		if (!el) {
			ContactsMenu.hide_menu();
		}

		Event.stop(e);
	},

	hide_menu : function()
	{
		if (ContactsMenu.current_menu)
		{
			ContactsMenu.current_menu.setStyle({ 'display' : 'none' });
			document.body.removeChild(ContactsMenu.current_menu);
			ContactsMenu.current_menu = false;
		}
	},

	over_event : function(e)
	{
		var el = Event.element(e);

		if (el.tagName == 'A' && el.rel && el.rev && el.hasClassName('dropdown'))
		{
			var m = el.rel.split('|');  // toggle|folder|remove
			var s = el.rev.split('|');  // toggle_selected|folder_selected|user_id
			ContactsMenu.current_folder = s[1];

			if (!$('um_' + s[2])){
				ContactsMenu.create(el,m,s);
			}

			if (ContactsMenu.current_menu)
				ContactsMenu.current_menu.setStyle({ 'display' : 'none' });
			ContactsMenu.current_menu = $('um_' + s[2]);
			var mp = el.cumulativeOffset();
			var md = el.getDimensions();

			ContactsMenu.current_menu.setStyle(
			{
				'display' : 'block',
				'top'     : (mp.top - 8 - (typeof ProfileView != 'undefined') * (SafariBrowser ? 3 : 1) + SafariBrowser) + 'px',
				'left'    : (mp.left - 11) + 'px'
			});
		}
		else
		{
			var d = Event.findElement(e, 'DIV');

			if ((!d || (d && d.className != 'contacts_menu')) && ContactsMenu.current_menu) {
				ContactsMenu.hide_menu();
			}
		}
	},

	create:function(el,m,s)
	{
		var menu = $u.el('div',
		{
			'id'        : 'um_' + s[2],
			'className' : 'contacts_menu'
		});

		var ask = '';
		var menu_content = [];
		menu_content.push('<h4>' + el.innerHTML + '<span></span></h4>');

		// status
		if (m[0] != '0')
		{
			menu_content.push('<ul>');

			if (m[0] != '3')
			{
				if (s[0] == '3')
				{
					menu_content.push('<li>');
					menu_content.push('<a href="' + vars.contact_menu.toggle[1][1].replace('#user_id#', s[2]) + '">' + vars.contact_menu.toggle[1][0] + '</a></li>');
				}
				else
				{
					ask = (s[0] == '1');
					menu_content.push('<li' + (ask ? ' class="selected"><span></span>' : '>'));
					menu_content.push('<a ' + (ask ? 'class="cm_remove" ' : 'class="cm_friend" ') + 'rev="' + s[2] + ',1" href="' + vars.contact_menu.toggle[1][1].replace('#user_id#', s[2]) + '">' + vars.contact_menu.toggle[1][0] + '</a></li>');
				}
			}

			// if ((m[0] == '2' && s[0] != '1') || (m[0] == '3'))
			if (1)
			{
				ask = (s[0] == '2' || s[0] == '4');
				menu_content.push('<li' + (ask ? ' class="selected"><span></span>' : '>'));
				menu_content.push('<a ' + (ask ? 'class="cm_remove"' : '') + 'rev="' + s[2] + ',2" href="' + vars.contact_menu.toggle[2][1].replace('#user_id#', s[2]) + '">' + vars.contact_menu.toggle[2][0] + '</a></li>');
			}

			menu_content.push('</ul>');
		}

		// folders
		if (m[1] != '0')
		{
			menu_content.push('<ul' + (m[2] == '0' ? ' class="last">' : '>'));
			var f = Object.keys(vars.contact_menu.folder);

			for (var i=0; i<f.length; i++)
			{
				ask = (s[1] == f[i]);
				menu_content.push('<li' + (ask ? ' class="selected"><span></span>' : '>'));
				ask = (f[i] == '-1' ? 'class="cm_blacklist" ' : (ask ? 'rel="folder" ' : ''));
				menu_content.push('<a ' + (ask) + ' rev="' + s[2] + ',' + s[1] + '" href="' + vars.contact_menu.folder[f[i]][1].replace('#user_id#', s[2]) + '">' + vars.contact_menu.folder[f[i]][0] + '</a></li>');
			}

			menu_content.push('</ul>');
		}

		if (m[2] != '0')
		{
			ask = (m[2] != '5' ? 'class="cm_remove" rev="' + s[2] + ',' + m[2] + '" ' : '');
			menu_content.push('<ul class="last">');
			menu_content.push('<li><a ' + ask + 'href="' + vars.contact_menu.remove[m[2]][1].replace('#user_id#', s[2]) + '">' + vars.contact_menu.remove[m[2]][0] + '</a></li>');
			menu_content.push('</ul>');
		}

		menu.innerHTML = menu_content.join('');

		// Event.observe(menu, 'mouseout', ContactsMenu.out_event);
		document.body.appendChild(menu);
	},

	on_friend:function(el)
	{
		/* var url = ($u.add_href(el.href, 'ws=1', 1)).split('?');
		Friends.friends_open(url); */
		return true;
	},

	confirm:function(texts,callback)
	{
		var mp = {top:0,left:0};
		if(ContactsMenu.current_menu)
			mp=ContactsMenu.current_menu.cumulativeOffset();
		dConfirm.show({
			x:(Event.pointerX($e.e) - 250),
			y:(mp.top - (window.Messenger?(-Event.pointerY($e.e)+80+mp.top):80)),
			type:'br_tail',
			text:dConfirm.wrap(texts),
			onOk:callback
		});
	},

	on_blacklist:function(el)
	{
		var un = $('uid' + ui[0]).innerHTML.stripTags().unescapeHTML();

		var texts = [ vars.contact_delete_str['-1'][0].replace('#name#', un), vars.contact_delete_str['0'][3], vars.contact_delete_str['0'][1], vars.contact_delete_str['0'][2] ];

		ContactsMenu.confirm(texts,ContactsMenu.remove_contact.bind(ContactsMenu,el.href));
	},

	on_folder:function(el)
	{
		var ui = el.rev ? el.rev.split(',') : false;
		var un = $('uid' + ui[0]).innerHTML.stripTags().unescapeHTML();

		var opt = '<div id="confirm_text"><label><input type="radio" id="confirm_opt1" name="confirm_opt" checked="checked" value="1"> ' + vars.contact_delete_str['3'][1] + '</label><br />' + '<label><input type="radio" id="confirm_opt2" name="confirm_opt" value="2"> ' + vars.contact_delete_str['3'][2] + '</label></div>';
		var texts = [ vars.contact_delete_str['3'][0].replace('#name#', un).replace('#folder_name#', ContactsMenu.folders[ui[1]]).unescapeHTML(), vars.contact_delete_str['0'][0], vars.contact_delete_str['0'][1], vars.contact_delete_str['0'][2], opt ];

		ContactsMenu.confirm(texts,ContactsMenu.remove_confirm.bind(ContactsMenu,vars.contact_menu.remove[3][1].replace("#user_id#", ui[0]),vars.contact_menu.remove[4][1].replace("#user_id#", ui[0])));
	},

	on_remove:function(el)
	{
		var ui = el.rev ? el.rev.split(',') : false;
		var un = $('uid' + ui[0]).innerHTML.stripTags().unescapeHTML();

		// remove comletle?
		if (ui[1] == '4')
		{
			var texts = [ vars.contact_delete_str[ui[1]][0].replace('#name#', un), vars.contact_delete_str['0'][0], vars.contact_delete_str['0'][1], vars.contact_delete_str['0'][2] ];
			ContactsMenu.confirm(texts,ContactsMenu.remove_contact.bind(ContactsMenu,el.href));
		}
		else
		{
			var opt = '<div id="confirm_text"><label><input type="radio" id="confirm_opt1" name="confirm_opt" checked="checked" value="1"> ' + vars.contact_delete_str[ui[1]][1] + '</label><br />' + '<label><input type="radio" id="confirm_opt2" name="confirm_opt" value="2"> ' + vars.contact_delete_str[ui[1]][2] + '</label></div>';
			var texts = [ vars.contact_delete_str[ui[1]][0].replace('#name#', un), vars.contact_delete_str['0'][0], vars.contact_delete_str['0'][1], vars.contact_delete_str['0'][2], opt ];

			if (ui[1] == '3') {
				texts[0] = texts[0].replace('#folder_name#', ContactsMenu.folders[ContactsMenu.current_folder]);
			}

			ContactsMenu.confirm(texts,ContactsMenu.remove_confirm.bind(ContactsMenu,vars.contact_menu.remove[ui[1]][1].replace("#user_id#", ui[0]),vars.contact_menu.remove[4][1].replace("#user_id#", ui[0])));
		}
	},

	// ContactsMenu.remove_params=el.href;
	// dConfirm.show({x:(Event.pointerX(e)-20), y:(Event.pointerY(e)-80), type:'b_tail', text:dConfirm.wrap(ContactsMenu.texts), onOk:ContactsMenu.remove_folder.bind(ContactsMenu)});
	// dConfirm.show({x:(Event.pointerX(e)-20), y:(Event.pointerY(e)-80), type:'b_tail', text:dConfirm.wrap(ContactsMenu.texts), onOk:ContactsMenu.remove_folder.bind(ContactsMenu)});
	remove_contact : function(url)
	{
		document.location = url;
		dConfirm.hide();
	},

	remove_confirm : function(url1, url2)
	{
		document.location = ($('confirm_opt1').checked ? url1 : url2);
		dConfirm.hide();
	}
};

$e.onload(ContactsMenu.init,ContactsMenu);

// gifts.js [dpp]

// dTooltip.js [dpp]

// <@--# if expr="$dtooltip!=1" -->
// <@--# set var="dtooltip" value="1" -->

var dTooltip=function(config)
{
	$config(this,config);
	this.init();
};

dTooltip.prototype=
{
	el:null,
	type:'',
	target:'',
	cel:null,
	x:0,
	y:0,
	html:'',
	images:[],
	scope:null,

	_re:null,
	_wrap:null,
	_cont:null,
	_tpl:'<div class="js_tooltip pngbox">\
		<div class="container">\
			<div class="central">\
				<div class="cont">\
					{html}\
				</div>\
				<div class="br"></div>\
			</div>\
		</div>\
		<div class="tr"></div>\
		<div class="bl"></div>\
	</div>',

	init:function()
	{

		if(!this.el)
			throw new Error('No element for dTooltip');

		this._re=new RegExp('(^|\\s)'+this.target+'(\\s|$)');

		this._wrap=$u.el('div',{
			id:'dTooltipWrap',
			className:'hidden',
			innerHTML:this._tpl
		});

		//this._cont=this._wrap.down('.cont');
		this._cont = $q.down(this._wrap, '.cont');

		document.body.appendChild(this._wrap);

		this.attachEventHandlers();

		if(this.images.length)
			$e.add(window,'load',$u.preloadImages.bind(null,this.images));

	},

	attachEventHandlers :function() {
		$e.add(this.el,'mouseover',this.test,this);
		$e.add(this.el,'mouseout',this.test,this);
		// $e.add(this._wrap,'mouseover',this.test,this);
		$e.add(this._wrap,'mouseout',this.test,this);
	},

	detachEventHandlers :function() {
		$e.del(this.el,'mouseover',this.test,this);
		$e.del(this.el,'mouseout',this.test,this);
		// $e.del(this._wrap,'mouseover',this.test,this);
		$e.del(this._wrap,'mouseout',this.test,this);
	},

	destroy:function()
	{

		this.detachEventHandlers ();

		document.body.removeChild(this._wrap);
		this._wrap=null;
		this._cont=null;
		this.el=null;

	},

	test:function(el)
	{
		var e=$e.e;

		if(e.type=='mouseout')
			el=e.relatedTarget||e.toElement;

		var p=el,
			cel=this.cel,
			w=this._wrap,
			b=document.body,
			re=this._re;

		if(el==cel) return;

		while(p && p!=cel && p!=w && !re.test(p.className) && p!=b)
			p=p.parentNode;

		if(!p || p==b) this.hide();
		else if(p!=w && p!=cel) this.show(p);
	},

	show:function(el)
	{
		this.cel=el;
		var config=this.format.call(this.scope || this,$(el));
		if(el) el.title='';

		this._cont.innerHTML=config.html;
		this._wrap.style.left=config.left+'px';
		this._wrap.style.top=config.top+'px';

		this._wrap.className=this.type;
	},

	hide:function()
	{
		this._wrap.className='hidden';
		this.cel=null;
	},

	format:function(el)
	{
		var e=$e.e;
		// var html='Test tooltip on element: <br/>'+el.nodeName+(el.id?('#'+el.id):'')+(el.className?('.'+el.className.split(' ').join('.')):'');
		var html=el.title;
		return {
			left:Event.pointerX(e),
			top:Event.pointerY(e),
			html:html
		};
	}
};

// <@--# endif -->


var Gifts=
{
	name:'Gifts',
	url:'',
	gifts:{},
	disable_submit:null,

	init:function()
	{
		if($('gift_add_nosms'))
			new Tooltip($('gift_add_nosms'), { maxWidth: 350 });

		var gifts=$('gifts');
		if(gifts)
		this.gifts_tooltip=new dTooltip({
			el:gifts,
			type:'giftbox',
			target:'gift_tooltip_target',
			images:[JSRoot+'i/box-gift.png', JSRoot+'i/boxs-apts.png'],
			format:function(el)
			{
				var m=/^gift([\d_]+)$/.exec(el.id);
				var gift=this.gifts[m&&m[1]||''];

				if(!gift) return '';

				var tl=$el.cumulativeOffset(el);
				return {
					html:gift.tooltip,
					left:parseInt(tl.left+el.offsetWidth/2-14),
					top:tl.top+el.offsetHeight-16
				};
			},
			scope:this
		});

		$e.on({
			'.gift_add':this.open,
			'.gift_add_link':this.open,
			'.gift_explode':this.open,
			'* .gift_add':this.open,
			'.gift_del':this.remove_confirm,
			'.load_all_gifts':this.load_more,
			'.gift_type':this.gift_select
		}, this);
		$u.app.on('give_a_gift',this.open,this);
	},

	open:function(el)
	{
		var url=el && el.rev || this.url;
		if(!url) return;

		dOvl.open({
			url:url,
			inplace:this.opened,
			onLoad:this.loaded,
			onUnLoad:this.unload,
			scope:this
		});
	},

	loaded:function()
	{
		var ovl=$('dOvl');
		if(!ovl) return;

		var bad_els=$q.select('.giftbox a',ovl);
		for(var i=0,n=bad_els.length; i<n; i++)
			bad_els[i].removeAttribute('href');

		if($('gift_text'))
			$u.textarea_count('gift_text',50);

		var pig=$q.down(ovl,'.pop_up_in_wizard');
		if(pig){
			dOvl.onResize=(function(y)
			{
				this.style.top=20-(y<150?y:150)+'px';
			}).bind(pig);

			//pig.style.top=20-dOvl.center()+'px';
			dOvl.center();
		}

		if($('gifts_select')){
			var sel=$q.down(ovl,'.selected');
			if(!sel){
				this.disable_submit=new Tooltip($('gifts_select'), { maxWidth: 350 });
			}else{
				$el.removeClassName($('gifts_select'),'disabled');
				var m=/^gift_type_([\d_]+)$/.exec(sel.id);
				if(m) $('gifts_gift_id').value=m[1];
			}
		}
	},

	unload:function()
	{
		if($('gift_text'))
			$u.textarea_stop_count('gift_text');
	},

	gift_select:function(el)
	{
		var m=/^gift_type_(\d+)$/.exec(el.id);
		if(!m) return;

		$('gifts_gift_id').value=m[1];
		var sel=$q.down($('dOvl'),'.selected');
		sel && $el.removeClassName(sel,'selected');
		$el.addClassName(el,'selected');

		if(this.disable_submit){
			$el.removeClassName(this.disable_submit.el,'disabled');
			this.disable_submit.remove();
			this.disable_submit=null;
		}
	},

	remove_confirm:function(el)
	{
		var url=el.rev;

		var m=/gift_id=([\d_]+)/.exec(url);
		var gift_id=m&&m[1];
		if(gift_id){
			var gift=$('gift'+gift_id);
			if(gift){
				var offset=$el.cumulativeOffset(gift);

				dConfirm.show({
					x:parseInt(offset.left+gift.offsetWidth-40),
					y:(offset.top-75),
					type:'b_tail',
					text:dConfirm.wrap(vars.Gifts.str.clear_question),
					onOk:this.remove.bind(this,url)
				});

				this.gifts_tooltip.hide();
			}
		}
	},

	remove:function(url)
	{
		var m=/gift_id=([\d_]+)/.exec(url);
		var gift_id=m&&m[1];
		if(gift_id){
			// var gift=$('gift'+gift_id);
			// if(gift) gift.remove();
			this.gifts[gift_id].tooltip=this.gifts[gift_id].tooltip.substr(0,this.gifts[gift_id].tooltip.indexOf('<p>'));
		}

		new $r(url,{
			method:'post',
			params:{ws:1}
		});
	},

	load_more:function(el)
	{
		this._show_more_el=el;
		var url=el.rev;

		$u.startWaiting(el);

		new $r(url,{
			method:'get',
			params:'',
			ready: this.load_more_received,
			error: this.load_more_error
		},this);
	},

	load_more_error:function()
	{
		$u.stopWaiting(this._show_more_el);
	},

	load_more_received:function(res)
	{
		var el=this._show_more_el;

		$u.stopWaiting(el);

		if(!res.errno){
			el.up('p').remove();
			var gifts=$('gifts');
			var img_sample=$q.down(gifts,'img');

			for(var i in res.gifts){
				var gift=res.gifts[i];

				this.gifts[i]=gift;
			}
			$('gifts').innerHTML+=res.html;
		}
	}
};

Gifts=new ($class(dPage,Gifts));

// spotlight.js [ekruchinin]

// dTooltip.js [dpp]

// <@--# if expr="$dtooltip!=1" -->
// <@--# set var="dtooltip" value="1" -->

var dTooltip=function(config)
{
	$config(this,config);
	this.init();
};

dTooltip.prototype=
{
	el:null,
	type:'',
	target:'',
	cel:null,
	x:0,
	y:0,
	html:'',
	images:[],
	scope:null,

	_re:null,
	_wrap:null,
	_cont:null,
	_tpl:'<div class="js_tooltip pngbox">\
		<div class="container">\
			<div class="central">\
				<div class="cont">\
					{html}\
				</div>\
				<div class="br"></div>\
			</div>\
		</div>\
		<div class="tr"></div>\
		<div class="bl"></div>\
	</div>',

	init:function()
	{

		if(!this.el)
			throw new Error('No element for dTooltip');

		this._re=new RegExp('(^|\\s)'+this.target+'(\\s|$)');

		this._wrap=$u.el('div',{
			id:'dTooltipWrap',
			className:'hidden',
			innerHTML:this._tpl
		});

		//this._cont=this._wrap.down('.cont');
		this._cont = $q.down(this._wrap, '.cont');

		document.body.appendChild(this._wrap);

		this.attachEventHandlers();

		if(this.images.length)
			$e.add(window,'load',$u.preloadImages.bind(null,this.images));

	},

	attachEventHandlers :function() {
		$e.add(this.el,'mouseover',this.test,this);
		$e.add(this.el,'mouseout',this.test,this);
		// $e.add(this._wrap,'mouseover',this.test,this);
		$e.add(this._wrap,'mouseout',this.test,this);
	},

	detachEventHandlers :function() {
		$e.del(this.el,'mouseover',this.test,this);
		$e.del(this.el,'mouseout',this.test,this);
		// $e.del(this._wrap,'mouseover',this.test,this);
		$e.del(this._wrap,'mouseout',this.test,this);
	},

	destroy:function()
	{

		this.detachEventHandlers ();

		document.body.removeChild(this._wrap);
		this._wrap=null;
		this._cont=null;
		this.el=null;

	},

	test:function(el)
	{
		var e=$e.e;

		if(e.type=='mouseout')
			el=e.relatedTarget||e.toElement;

		var p=el,
			cel=this.cel,
			w=this._wrap,
			b=document.body,
			re=this._re;

		if(el==cel) return;

		while(p && p!=cel && p!=w && !re.test(p.className) && p!=b)
			p=p.parentNode;

		if(!p || p==b) this.hide();
		else if(p!=w && p!=cel) this.show(p);
	},

	show:function(el)
	{
		this.cel=el;
		var config=this.format.call(this.scope || this,$(el));
		if(el) el.title='';

		this._cont.innerHTML=config.html;
		this._wrap.style.left=config.left+'px';
		this._wrap.style.top=config.top+'px';

		this._wrap.className=this.type;
	},

	hide:function()
	{
		this._wrap.className='hidden';
		this.cel=null;
	},

	format:function(el)
	{
		var e=$e.e;
		// var html='Test tooltip on element: <br/>'+el.nodeName+(el.id?('#'+el.id):'')+(el.className?('.'+el.className.split(' ').join('.')):'');
		var html=el.title;
		return {
			left:Event.pointerX(e),
			top:Event.pointerY(e),
			html:html
		};
	}
};

// <@--# endif -->

// spotlight.animation.js [ekruchinin]

var SLLine = function(config) {
	$config(this, config);
	this.init();
}

SLLine.prototype = {

	spotlightMainInstance: null,
	slDOMElement: null,

	sl_img_tpl: '<a href="{profileURL}" id="slc_{sl_id}"style="margin-left:1px; margin-right:2px;" ><img src="{img_url}" width="83" height="83" alt="" title="{message}"/></a>',

	marginLeft:0,
	sims: [],
	focusedElementIndex: -1,
	maxSizeMode: false,
	tooltipShowed4SimIndex: -1,
	updateIsAvailable:true,
	profileURL: "",

	simsWMaxSum: 0,
	simsWMinSum: 0,

	items: [],

	tempUpdateLayoutParams: null,
	fullSimWidth: 86, // 83  px for img + 3 px for margins

	simsInnerContainer: null,
	positionLeft: 0,
	animationInProcess: false,
	simsTemporaryHiddenFromIndex: -1,

	init: function()
	{

		this.simsInnerContainer = $q.down (this.slDOMElement, 'div');

		this.slDOMElement.style.overflow = 'hidden';
		this.slDOMElement.style.width = '100%';

		$e.add(this.slDOMElement, 'mouseover', this.mouseOverHandler, this);
		$e.add(this.slDOMElement, 'mouseout', this.mouseOutHandler, this);

		this.handleNextZoomCommand_fn = this.handleNextZoomCommand.bind(this);
		this.zoomOutAll_fn =  this.zoomOutAll.bind(this);
		this.handleNextOffsetStep_fn = this.handleNextOffsetStep.bind(this);

		var sImDOMElements = $q.select('a', this.slDOMElement);
		this.sims = this.createSims(sImDOMElements);

	},

	destroy: function()
	{

		this.stopMouseOverStateLeavesTimeout();
		this.clearNextZoomCommandTimeout();

		$e.del(this.slDOMElement, 'mouseover', this.mouseOverHandler, this);
		$e.del(this.slDOMElement, 'mouseout', this.mouseOutHandler, this);

		this.slDOMElement = null;
		this.clearSims();

		this.handleNextZoomCommand_fn = null;
		this.zoomOutAll_fn = null;
		this.handleNextOffsetStep_fn = null;

		this.tempUpdateLayoutParams = null;
		this.simsInnerContainer = null;

		this.items = null;

		this.spotlightMainInstance = null;

	},


	clearSims: function()
	{
		for (var i=0, n=this.sims.length; i < n; i++) {
			var sim = this.sims[i];
			sim.destroy();
		}

		this.sims = [];
		this.items = [];

	},

	createSims: function(imgs)
	{
		for (var i = 0, n = imgs.length; i < n; i++) {
			imgs[i] = new sIm(imgs[i], i);
		}
		if (imgs.length > 0) {
			var sim = imgs[0];
			this.simsWMaxSum = (imgs.length - 1) * sim.min + sim.max;
			this.simsWMinSum = imgs.length * sim.min;
		}
		else {
			this.simsWMaxSum = 0;
			this.simsWMinSum = 0;
		}
		return imgs;
	},

	mouseOverHandler: function(el)
	{

		if (el == this.slDOMElement || el == this.simsInnerContainer) {
			this.stopMouseOverStateLeavesTimeout ();
			return;
		}

		if (el.nodeName == 'IMG') {
			var focusedElement = el.parentNode;
			var i = focusedElement.simIndex;
			if ( i >= 0)  {
				this.setupSimMouseOverState(i);
				return;
			}
		}
	},

	mouseOutHandler: function(el) {

		var e = $e.e;
		var el = e.relatedTarget||e.toElement;

		var slTooltip = this.spotlightMainInstance.slTooltip;

		if (!el) {
			this.mouseOverStateLeaves(0);
			this.hideTooltip();
			return;
		}

		var tooltipF = false;
		var n = el;

		while (n && n != document.body && !tooltipF) {
			if (n == slTooltip._wrap) {
				tooltipF = true;
			}
			n = n.parentNode;
		}

		if (!tooltipF) {
			//this.hideTooltip();
		}

		this.mouseOverStateLeaves();

	},

	setupSimMouseOverState: function(focusedElementIndex)
	{

		this.stopMouseOverStateLeavesTimeout ();
		var destCommandsArr = [];

		if (this.focusedElementIndex != focusedElementIndex) {

		   this.setupFocusedElementIndex(focusedElementIndex);

			for (var i = 0, n = this.sims.length; i < n; i++) {
				var sim=this.sims[i];
				if (i == this.focusedElementIndex)
					destCommandsArr.push(sim.max);
				else
					destCommandsArr.push(sim.min);
			}

			this.setupZoomValues(destCommandsArr);

		}

	},

	setupFocusedElementIndex: function(i)
	{
		this.focusedElementIndex = i;
	},

	stopMouseOverStateLeavesTimeout: function() {
		if (this.zoomOutAllTimeout)
		   clearTimeout(this.zoomOutAllTimeout);
	},

	mouseOverStateLeaves: function(delayValue)
	{
		this.stopMouseOverStateLeavesTimeout ();

		if (delayValue == 0)
			this.zoomOutAll_fn ();
		else
		if (delayValue > 0)
			this.zoomOutAllTimeout = setTimeout(this.zoomOutAll_fn, delayValue);
		else
			this.zoomOutAllTimeout = setTimeout(this.zoomOutAll_fn, 100);
	},

	setupZoomValues: function (destCommandsArr)
	{

		this.clearNextZoomCommandTimeout();

		if (destCommandsArr.length == 0)
			return;

		var numSteps = 5;

		for (var i = 0, n = destCommandsArr.length; i < n; i++) {
			var sim = this.sims[i];
			var destValue = destCommandsArr[i];
			var zoomStep = (destValue - sim.currentSize) / numSteps;
			sim.animDestValue = destValue;
			sim.animStep = zoomStep;
			sim.animCurrentSize = sim.currentSize;
		}

		if (this.needToProcessZoomStep())
			this.handleNextZoomCommand();

	},

	needToProcessZoomStep: function ()
	{
		for (var i = 0, n = this.sims.length; i < n; i++) {
			var sim = this.sims[i];
			if (sim.animStep > 0 && sim.currentSize < sim.animDestValue)
				return true;
			if (sim.animStep < 0 && sim.currentSize > sim.animDestValue)
				return true;
		}
		return false;
	},

	clearNextZoomCommandTimeout: function ()
	{
		if (this.handleNextZoomCommandTimeout != -1) {
			clearTimeout(this.handleNextZoomCommandTimeout);
			this.handleNextZoomCommandTimeout = -1;
		}
	},

	handleNextZoomCommand: function () {
		this.clearNextZoomCommandTimeout();
		this.processZoomStep();
		if (this.needToProcessZoomStep())
			this.handleNextZoomCommandTimeout = setTimeout(this.handleNextZoomCommand_fn, 20);
	},

	processZoomStep: function()
	{

	   var currentSimsSum = 0;
	   var maxSim;
	   var currentMaxSize = 0;

	   for (var i = 0, n=this.sims.length; i < n; i++) {
			var sim = this.sims[i];
			sim.setupNextZoomValue();
			currentSimsSum += sim.currentSize;
			 if (sim.currentSize > currentMaxSize) {
				maxSim = sim;
				currentMaxSize  = sim.currentSize;
			}
		}

		if (this.maxSizeMode && currentSimsSum != this.simsWMaxSum) {
			var dif = this.simsWMaxSum - currentSimsSum;
			maxSim.currentSize += dif;
			currentSimsSum += dif;
		}

		if (currentSimsSum ==  this.simsWMinSum && !this.updateIsAvailable) {
			this.animationOn(false);
		}
	   else
	   if (currentSimsSum > this.simsWMinSum && this.updateIsAvailable) {
			this.animationOn(true);
	   }

	   var currentSimsSum = 0;
	   for (var i = 0, n=this.sims.length; i < n; i++) {
			var sim = this.sims[i];
			currentSimsSum += sim.currentSize;
			sim.updateDOMElementSize();
	   }

	   if (currentSimsSum >= this.simsWMaxSum) {
			this.maxSizeMode = true;
		   if (this.focusedElementIndex != -1 &&
			  (this.tooltipShowed4SimIndex == -1 || this.focusedElementIndex != this.tooltipShowed4SimIndex)) {
				var sim = this.sims[this.focusedElementIndex];
				if (sim.currentSize >= sim.max) {
					this.showTooltip(sim, this.focusedElementIndex);
				}
		   }
	   }
	   else
		if (this.tooltipShowed4SimIndex != -1 && (this.simsWMaxSum - currentSimsSum) >= 17 ) {
			this.hideTooltip();
	   }

		var dif = Math.ceil((currentSimsSum - this.simsWMinSum) / 2);
	   this.setupMarginLeft(-dif);

	   if (currentSimsSum ==  this.simsWMinSum && !this.updateIsAvailable) 	{
			this.setupUpdateIsAvailableFlag(true);
	   }
	   else
	   if (currentSimsSum > this.simsWMinSum && this.updateIsAvailable) {
			this.setupUpdateIsAvailableFlag(false);
	   }

	},

	getFirstInvisibleSimIndex: function() {
		for (var i=0, n = this.sims.length; i < n; i++) {
			var sim = this.sims[i];
			if (parseInt(sim.domElement.offsetTop) > 50) {
				return i;
			}
		}
		return 10;
	},

	setupSimsVisibilityFromIndex: function(fromIndex, visible) {
		for (var i = fromIndex, n = this.sims.length; i < n; i++) {
			var sim = this.sims[i];
			sim.setupVisibility(visible);
		}
	},

	animationOn: function(isOn, forAnimatedOfs) {

		if ((this.animationInProcess && !isOn) || (!this.animationInProcess && isOn)) {

			if (!this.animationInProcess) {

				if (forAnimatedOfs) {
					var w = this.simsTemporaryHiddenFromIndex * this.fullSimWidth;
					this.slDOMElement.style.width = w + 'px';
				}
				else {
					this.simsTemporaryHiddenFromIndex = this.getFirstInvisibleSimIndex();
					this.setupSimsVisibilityFromIndex(this.simsTemporaryHiddenFromIndex, false);
					var w = this.simsTemporaryHiddenFromIndex * this.fullSimWidth;

					this.slDOMElement.style.width = '108%';
					this.slDOMElement.style.marginRight = '-8%';
				}

			}
			else {

				this.slDOMElement.style.width = '100%';
				this.slDOMElement.style.marginRight = '0%';

				if (this.simsTemporaryHiddenFromIndex != -1) {
					this.setupSimsVisibilityFromIndex(this.simsTemporaryHiddenFromIndex, true);
				}

				this.simsTemporaryHiddenFromIndex = -1;

			}

			this.animationInProcess = isOn;
			var w = isOn? "5000px" : "auto";
			this.simsInnerContainer.style.width = w;

		}
	},

	simsInnerContainerWidth: 'auto',

	setupSimsInnerContainerWidth: function (w) {
		if (this.simsInnerContainerWidth != w) {
			this.simsInnerContainer.style.width = w;
			this.simsInnerContainerWidth = w;
		}
	},

	setupUpdateIsAvailableFlag: function(value)
	{

		this.updateIsAvailable = value;

		if (this.tempUpdateLayoutParams && this.updateIsAvailable) {
			this.updateLayout(this.tempUpdateLayoutParams);
			this.tempUpdateLayoutParams = null;
		}


	},

	showTooltip: function(sim, simIndex)
	{

		this.tooltipShowed4SimIndex = simIndex;

		var item = this.items[simIndex];
		var userUrl = this.profileURL.replace('{login}', item.login);
		var leftOfs = simIndex * this.fullSimWidth + 45;
		this.spotlightMainInstance.tooltip(item.tooltip, leftOfs, userUrl);

	},

	hideTooltip: function()
	{
		this.tooltipShowed4SimIndex = -1;
		this.spotlightMainInstance.tooltip_hide();

	},

	setupMarginLeft: function(newValue) {
		if (this.marginLeft != newValue) {
			this.marginLeft = newValue;
			this.slDOMElement.style.marginLeft = this.marginLeft + "px";
		}
	},

	zoomOutAll: function()
	{

		this.stopMouseOverStateLeavesTimeout ();
		this.maxSizeMode = false;
		this.setupFocusedElementIndex(-1);
		var destCommandsArr = [];

		for(var i = 0, n=this.sims.length; i < n; i++){
			var sim=this.sims[i];
			destCommandsArr.push(sim.min);
		}

		this.setupZoomValues(destCommandsArr);

	},

	getItemIndexByValues: function (a, item) {
		for (var i = 0, n = a.length; i < n; i++) {
			var v = a[i];
			if (v.login == item.login && v.id == item.id && v.url == item.url && v.tooltip == item.tooltip)
				return i;
		}
		return -1;
	},

	getOffsetIndex: function (newItemsArr) {

		var a = [];

		var firstInd = -1;
		for (var i = 0, n = newItemsArr.length; i < n; i++) {
			var item = newItemsArr[i];
			item.indexInCurrentItems = this.getItemIndexByValues(this.items, item);
			if (firstInd == -1 && item.indexInCurrentItems != -1)
				firstInd = i;
		}

		if (firstInd == -1)
			return this.items.length;

		for (var i = firstInd + 1, n = newItemsArr.length; i < n; i++) {
			var item = newItemsArr[i];
			var prevItem = newItemsArr[i - 1];
			if (prevItem.indexInCurrentItems != item.indexInCurrentItems - 1)
				return this.items.length;
		}

		return firstInd;

	},

	getDestOffset: function (newItemsArr) {
		var ofs = this.getOffsetIndex(newItemsArr) * this.fullSimWidth;
	},

	getHTML: function (itemsArr)
	{
		var html = [];

		for (var i = 0, n = itemsArr.length; i < n; i++) {
			var item = itemsArr[i];
			if (!item.url)
				   item.url = JSRoot + 'i/no.gif';
			var itemHTML = $u.tpl(this.sl_img_tpl,{
				profileURL:$u.tpl(this.profileURL,{ login : item.login }),
				sl_id:item.id,
				img_url:item.url
			});
			html.push (itemHTML);
		}

		return html.join('');
	},

	updateLayout: function (sljson)
	{

		if (!this.updateIsAvailable) {
			this.tempUpdateLayoutParams = sljson;
			return;
		}

		var newItems = [];

		if (sljson instanceof Array)
			for(var i=0; i < sljson.length; i++){
				var item = sljson[i];
				newItems.push(item);
			}
		else
			for(var itemKey in sljson) {
				var item = sljson[itemKey];
				newItems.push(item);
			}

		if (!this.items || this.items.length == 0 || this.items.length != 10 || newItems.length != 10) {
			// first time, no animation...
			this.easyRedraw(newItems, 0);
		}
		else {
			// let's try to do it with an animation...
			this.removePreviousItems ();
			var ofsIndex = this.getOffsetIndex (newItems);
			if (ofsIndex >= newItems.length - 1)
				this.easyRedraw(newItems, ofsIndex);
			else
				this.redrawViaOfsAnimation (newItems, ofsIndex);
		}

	},

	removePreviousItems: function () {

		for (var i = 10, n = this.sims.length; i < n; i++) {
			var sim = this.sims[i];
			var domElement = sim.domElement;
			domElement .parentNode.removeChild(domElement);
			sim.destroy();
		}

		this.items.splice (10, this.items.length - 10);
		this.sims.splice (10, this.sims.length - 10);

	},

	redrawViaOfsAnimation: function (newItems, ofsIndex) {

		this.hideTooltip();

		var finalItemsArr = this.items.clone();

		for (var i = 0; i < ofsIndex; i++) {
			var item = newItems[i];
			finalItemsArr.unshift(item);
		}

		this.easyRedraw(finalItemsArr, ofsIndex);

		this.setupPositionLeft(- ofsIndex * this.fullSimWidth - 35);
		this.offsetTo (0);

	},

	offsetTo: function (destValue) {


		this.hideTooltip ();

		this.animationOn(true, true);

		this.destOffset = destValue;

		this.stepCounter = 0;
		this.ofsDif = this.destOffset - this.positionLeft;

		this.handleNextOffsetStep();

	},

	handleNextOffsetStep: function () {

		var positionLeft = this.positionLeft;

		if (this.stepCounter < 4)
			this.step = this.ofsDif / 10
		else
		if (this.stepCounter < 10)
			this.step = this.ofsDif / 20
		else
		if (this.stepCounter < 16)
			this.step = this.ofsDif / 30
		else
			this.step = 3;

		this.step = Math.ceil(this.step);

		if (this.step < 1)
			this.step = 1;

		this.stepCounter++;

		positionLeft += this.step;

		if (this.step > 0) {
			if (positionLeft > this.destOffset) {
				positionLeft = this.destOffset;
			}
		}
		else {
			if (positionLeft < this.destOffset) {
				positionLeft = this.destOffset;
			}
		}

		if (positionLeft  != this.destOffset)
			this.handleNextOffsetStepTimeout = setTimeout(this.handleNextOffsetStep_fn, 30);

		this.setupPositionLeft(positionLeft);

		if (positionLeft  == this.destOffset)
			this.handleOfsAnimationStop ();

	},

	setupPositionLeft: function(newValue) {
		if (this.positionLeft != newValue) {
			this.positionLeft = newValue;
			this.simsInnerContainer.style.marginLeft = this.positionLeft + "px";
		}
	},

	easyRedraw: function (newItems, ofsIndex) {

		if (ofsIndex && ofsIndex < 10) {

			this.items = newItems;

			var prevSim = this.sims[0];
			var prevDOMElement = prevSim.domElement;

			this.simsTemporaryHiddenFromIndex = this.getFirstInvisibleSimIndex();

			for (var i = ofsIndex - 1; i >= 0 ; i--) {

				var newSimDOMElement = prevDOMElement.cloneNode(true);
				this.simsInnerContainer.insertBefore(newSimDOMElement, prevDOMElement);
				var newSim = new sIm(newSimDOMElement, i);
				var item = this.items[i];

				var profileURL = this.profileURL.replace('{login}', item.login);

				newSim.update(item.url, profileURL);
				newSim.indexInCurrentItems = i;
				this.sims.unshift(newSim);

				prevDOMElement = newSimDOMElement;

			}

			for (var i = 0, n = this.sims.length; i < n; i++) {
				var sim = this.sims[i];
				sim.simIndex = i;
				sim.domElement.simIndex = i;
			}

			var sim = this.sims[0];
			this.simsWMaxSum = (this.sims.length - 1) * sim.min + sim.max;
			this.simsWMinSum = this.sims.length * sim.min;

		}
		else {

			this.clearSims();
			this.items = newItems;

			this.simsInnerContainer.innerHTML = this.getHTML(newItems);
			var sImDOMElements = $q.select('a', this.simsInnerContainer);
			this.sims = this.createSims(sImDOMElements);
		}

	},

	handleOfsAnimationStop: function () {
		this.animationOn(false);
	}

};



var sIm = function (domElement, simIndex)
{
	this.domElement = domElement;
	this.domElement.simIndex = simIndex;
	this.init();
};

sIm.prototype = {

	domElement: null,
	imgElement:null,

	min:83,
	max:100,
	currentSize: 83,
	domElementSize: 83,

	animDestValue: 83,
	animStep: 0,
	animCurrentSize: 83,
	simIndex: -1,
	visibilityValue: true,

	init: function ()
	{

		this.domElementSize = this.currentSize = this.min;

		this.imgElement = $q.down(this.domElement, "IMG");

		this.imgElement.title = "";

		this.initFilter();

	},

	initFilter: function () {
		if(/*@cc_on!@*/false) {
			var src = this.imgElement.src;
			this.imgElement.src = JSRoot + 'i/no.gif';
			this.imgElement.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
		}
	},

	setupVisibility: function (visibilityValue)
	{
		if ((this.visibilityValue && !visibilityValue) || (!this.visibilityValue && visibilityValue)) {
			this.visibilityValue = visibilityValue;
			this.domElement.style.display = visibilityValue ? "" : "none";
		}
	},

	update: function (imagePath, profileURL)
	{
		this.imgElement.src = imagePath;
		this.initFilter();
		if (profileURL)
			this.domElement.href = profileURL;
	},

	setupNextZoomValue: function ()
	{
		this.animCurrentSize += this.animStep;
		this.currentSize	= Math.ceil(this.animCurrentSize);
		if (this.currentSize < this.min)
			this.currentSize = this.min;
		else
		if (this.currentSize > this.max)
			this.currentSize = this.max;
	},

	destroy: function()
	{
		if(/*@cc_on!@*/false)
			this.domElement.firstChild.style.filter = "";
		this.domElement = null;
		this.imgElement = null;
	},

	updateDOMElementSize: function ()
	{
		if (this.domElementSize != this.currentSize) {
			this.domElementSize = this.currentSize;
			this.domElement.style.width = this.domElement.style.height = this.domElementSize + 'px';
			this.domElement.style.marginTop = ((22 - (this.domElementSize - this.min)) / 2) +  'px';
		}
	}

};

// spotlight.updater.js [ekruchinin]

var SLUpdater = function (config) {
	$config(this, config);
	this.init();
}

SLUpdater.prototype = {

	spotlightMainInstance: null,
	spotlightVars: null,
	sls: {},
	slp_id: -1,
	submit_bn:null,
	flash_params:{},
	updateTimeout: 8000,
	update_ts:0,
	profileUrl: '',
	ajaxUpdateUrl: '/sl/list-ws-json/',
	ajaxUpdateRequestUrl: '/sl/ws/',

	init: function()
	{

		if(this.spotlightVars) {
			this.sls = this.spotlightVars && this.spotlightVars.sls || {};
			this.flash_params = this.spotlightVars.flashvars;
			this.sl_json = this.spotlightVars.sljson;
			this.update_ts = this.flash_params.ts;
			this.ajax_update_params = {
				language_id: this.flash_params.lid,
				spotlight_id: this.flash_params.sid
			};
		}

		this.ajaxUpdateFirstRequest_fn = this.ajaxUpdateFirstRequest.bind(this);
		this.error_fn = this.error.bind(this);

		this.ajaxUpdateTimer = setTimeout(this.ajaxUpdateFirstRequest_fn, this.updateTimeout);

	},

	destroy: function() {

		this.ajaxUpdateFirstRequest_fn = null;
		this.ajaxFirstRequestOnCompleteHandler_fn = null;
		this.ajaxSecondRequestOnCompleteHandler_fn = null;

		clearTimeout(this.ajaxUpdateTimer);
		this.spotlightMainInstance = null;

	},

	getProfileUrl: function(r) {
		var url = 'http://' + (this.flash_params.b?('{login}.' + this.flash_params.s) : (this.flash_params.s + '/{login}'));
		return url;
	},

	ajaxUpdateFirstRequest: function()
	{
		new $r(this.ajaxUpdateRequestUrl,{
			method: 'get',
			params:this.ajax_update_params,
			readyEx: this.ajaxFirstRequestOnCompleteHandler,
			error: this.error
		}, this);
	},

	ajaxFirstRequestOnCompleteHandler : function(transport) {
		var ts = transport.transport.responseText;
		if(ts != this.update_ts) {
			this.update_ts = ts;
			this.ajaxUpdateSecondRequest(ts);
		} else {
			this.ajaxUpdateTimer = setTimeout(this.ajaxUpdateFirstRequest_fn, this.updateTimeout);
		}
	},

	ajaxUpdateSecondRequest: function(ts)
	{
		new $r (this.ajaxUpdateUrl,{
			method: 'get',
			params:this.ajax_update_params,
			ready: this.ajaxSecondRequestOnCompleteHandler,
			error: this.error
		}, this);
	},

	ajaxSecondRequestOnCompleteHandler : function(res) {
		this.sl_json = res;
		this.spotlightMainInstance.updateLayout(this.sl_json);
		this.ajaxUpdateTimer = setTimeout(this.ajaxUpdateFirstRequest_fn, this.updateTimeout);
	},

	error: function(er, r) {
		
		
	}

};


// spotlight.flash.js [ekruchinin]

var SLLineFlash = function (config) {
	$config(this, config);
	this.init();
}

SLLineFlash.prototype = {

	slDOMElement: null,
	spotlightVars: null,

	init: function()
	{

		var flash_params = this.spotlightVars.flashvars;

		flash_params.sl_json = Object.toJSON(this.spotlightVars.sljson);

		this.slDOMElement.innerHTML = Flash.draw(JSRoot + 'flash/spotlight.swf', "100%", "106", "#fff",  flash_params, true, 'swfSpotlight');

		$el.removeClassName(this.slDOMElement.parentNode, 'slline-static');

	},

	destroy: function()
	{
		this.slDOMElement = null;
	}

};

// spotlight.tooltip.js [ekruchinin]

var SLTooltip = $class(dTooltip,{

	tooltipHtmlContent: '',
	userUrl: '',
	leftOfs: 0,
	spotlightMainInstance: null,

	format: function(userUrl, html, x)
	{

		var tooltipHtmlContent = html.replace('<mask>', userUrl);
		var tl = $el.cumulativeOffset(this.el);					//FIXME reflow

		return {
			html: tooltipHtmlContent,
			left: tl.left + 0 + x - 8,
			top: tl.top + 87 + (this.is_wizard?(document.documentElement.scrollTop || document.body.scrollTop) - (document.documentElement.clientTop || 0):0)
		};

	},

	mouseOverHandler: function()
	{
		this.mouseOvered = true;
	},

	mouseOutHandler: function()
	{
		var e = $e.e;
		var el=e.relatedTarget||e.toElement;

		if (!el) {
			this.hide();
			return;
		}

		var n = el;

		while (n && n != document.body) {
			if (n == this.el) {
				this.mouseOvered = false;
				return;
			}
			if (n == this._wrap) {
				this.mouseOvered = true;
				return;
			}
			n = n.parentNode;
		}

		this.hide();

	},

	show4Spotlight: function(x, tooltip_html, user_url)
	{
		var leftOfs = parseInt(x) - 25;
		var config=this.format(user_url, tooltip_html, leftOfs);

		this._cont.innerHTML=config.html;
		this._wrap.className=this.type;
		this.fit(config);
		this._wrap.style.left=config.left+'px';
		this._wrap.style.top=config.top+'px';

		this.mouseOvered = false;

	},

	fit:function(config)			//FIXME reflow
	{
		var tl=$el.cumulativeOffset(this.el);
		var t=tl.left+this.el.offsetWidth-(config.left+this._wrap.offsetWidth);

		if(t<0)
			config.left=config.left+t-16;
	},

	hide:function()
	{
		this.mouseOvered = false;
		this._wrap.className='hidden';
		this.cel=null;
	},

	attachEventHandlers : function()
	{
		$e.add(this._wrap,'mouseout',this.mouseOutHandler,this);
		$e.add(this._wrap,'mouseover',this.mouseOverHandler,this);
	},

	detachEventHandlers :function()
	{
		$e.del(this._wrap,'mouseout',this.mouseOutHandler,this);
		$e.del(this._wrap,'mouseover',this.mouseOverHandler,this);
	}

});
// spotlight.wizard.js [ekruchinin]

// tooltip.js

// <@--# if expr="$tooltip!=1" -->
// <@--# set var="tooltip" value="1" -->

var Tooltip=function(el, options)
{
	this.init(el, options);
};

Tooltip.prototype =
{
	tpl:'<div class="ibc">{content}</div><div class="ibt"><b></b></div><div class="ibr"><b></b></div><div class="ibb"><b></b></div><div class="ibl"><b></b></div>',

	init:function(el, options)
	{
		this.el=$(el);
		this.initialized=false;
		this.setOptions(options);

		if(!this.el) return;

		$e.add(this.el, "mouseover", this.show, this);
		$e.add(this.el, "mouseout", this.hide, this);

		this.content=this.el.title;
		this.el.title="";

		var descendants=$q.select('*',this.el);
		for(var i=0, n=descendants.length; i<n; i++){
			if('alt' in el) el.alt='';
		}
	},

	remove:function()
	{
		$e.del(this.el, "mouseover", this.show, this);
		$e.del(this.el, "mouseout", this.hide, this);
		this.el=null;
	},

	setOptions:function(options)
	{
		this.options={
			backgroundColor:'#FFFCB5',
			borderColor:'#FFDC6E',
			textColor:'#7D660A',
			textShadowColor:'',
			maxWidth:250,
			align:"left",
			delay:0,
			mouseFollow:false,
			opacity:.75,
			appearDuration:0,
			hideDuration:.25
		};

		$config(this.options, options || {});
	},

	show:function(el)
	{
		var xy=$e.pointerXY();
		this.xCord=xy.x;
		this.yCord=xy.y;
		if(!this.initialized)
			this.timeout=setTimeout(this.appear.bind(this), this.options.delay);
	},

	hide:function(el)
	{
		if (this.initialized)
		{
			if (this.options.mouseFollow && this.el) $e.del(this.el, "mousemove", this.update, this);
			this.tooltip.parentNode.removeChild(this.tooltip);
		}

		this._clearTimeout(this.timeout);

		this.initialized=false;
	},

	update:function(e)
	{
		var xy=$e.pointerXY();
		this.xCord=xy.x;
		this.yCord=xy.y;
		this.setup();
	},

	appear:function()
	{
		this.tooltip=$u.el('div',{
			id:'clipboard_title',
			style:'display: none;',
			innerHTML:$u.tpl(this.tpl,{content:this.content})
		});

		document.body.appendChild(this.tooltip);

		this.options.width=$el.dimensions(this.tooltip).width;
		this.tooltip.style.width=this.options.width+'px';  // IE7

		this.setup();

		if (this.options.mouseFollow)
			$e.add(this.el, "mousemove", this.update, this);

		this.initialized=true;
		this.tooltip.style.display='block';
	},

	setup:function()
	{
		if(this.options.width>this.options.maxWidth){
			this.options.width=this.options.maxWidth;
			this.tooltip.style.width=this.options.width+'px';
		}

		var doc_wh=$el.dimensions(document);
		if(this.xCord+this.options.width >= doc_wh.width){
			this.options.align="right";
			this.xCord=this.xCord-this.options.width+20;
		}

		this.tooltip.style.left=this.xCord-7+"px";
		this.tooltip.style.top=this.yCord+12+"px";
	},

	_clearTimeout:function(timer)
	{
		clearTimeout(timer);
		clearInterval(timer);
		return null;
	}
};

// <@--# endif -->


var SLWizardInstance = {

	name:'SpotlightWizard',
	url:'',
	disable_submit:null,

	slLine: null,   // : SLLine
	slLineFlash: null, // : SLLineFlash
	slTooltip: null, // : SLTooltip

	slLineDOMElement: null,

	init:function()
	{

		if(!this.url)
			this.url=$('sl_step') && $('sl_step').rev || '';

		// doing mapping beetween url's and event handlers...

		$e.on({
			'sl_step':this.open,
			'* #sl_step':this.open,
			'.slp':this.select_photo,
			'* .add_photo_sl':this.add_photo
		}, this);

		$u.app.on('spotlight', this.open.bind(this));

	},

	open:function()
	{
		dOvl.open({
			url:this.url,
			onLoad:this.loaded,
			onUnLoad:this.unload,
			onClose:this.close,
			onError:this.close,
			scope:this
		});
	},

	select_photo:function(el)
	{
		var m=/^slp_([\d_]+)$/.exec(el.id);
		if(!m) return;

		$('sl_photo_id').value=m[1];

		var ovl = $('dOvl');

		var sel=$q.down(ovl, '.selected');

		sel && $el.removeClassName(sel, 'selected');

		$el.addClassName(el, 'selected');

		if(this.disable_submit){
			$el.removeClassName(this.disable_submit.el, 'disabled');
			this.disable_submit.parentNode.removeChild (this.disable_submit);
			this.disable_submit = null;
		}
	},

	unload:function()
	{

		this.slLineDOMElement = null;
		this.disable_submit = null;

		var ovl=$('dOvl');
		if(!ovl)
			return;

		if(!$q.down(ovl, '.spotlight-line'))
			return;

		if($('sl_text'))
			$u.textarea_stop_count('sl_text');

	},

	loaded: function()
	{

		try {
			Spotlight.slTooltip.hide();
		}
		catch (e) { ; }

		var ovl = $('dOvl');

		var fvs = $q.down(ovl, 'input[name=flashvars]');
		if(fvs) {

			try {
				fvs=eval('('+fvs.value+')');
			} catch(er){
				fvs={};
			}

			this.slLineDOMElement = $q.down(ovl, '.spotlight-line');
			this.spotlightVars = vars.Spotlight;

		}

		if($('sl_text'))
			$u.textarea_count($('sl_text'),$('sl_text_count'));

		if($('sls_select')){
			var img = $q.down(ovl,'.selected');
			if(!img){
				this.disable_submit=new Tooltip($('sls_select'), { maxWidth: 350 });
			}else{
				$el.removeClassName($('sls_select'), 'disabled');
				$('sls_select').title='';

				var m=/^slp_([\d_]+)$/.exec(img.id);
				if(m) $('sl_photo_id').value=m[1];
			}
		}
	},

	add_photo:function(el)
	{
		
		if(Spotlight.jsVer || !vars.PhotoUpload || !window.PhotoUpload) return true;

		vars.PhotoUpload.onComplete_url+='#!spotlight';
		PhotoUpload.open_popup();

	}

};

SpotlightWizard = new ($class(dPage, SLWizardInstance));



var SLMainInstance = function(config) {
	$config(this, config);
	this.init();
};

SLMainInstance.prototype = {

	slLine: null,   // : SLLine
	updater: null, // : SLUpdater
	slLineFlash: null, // : SLLineFlash
	slTooltip: null, // : SLTooltip

	slLineDOMElement: null,
	spotlightVars: null,
	jsVer: false,

	init: function() {

		if (!this.slLineDOMElement)
			return;

		if(Flash.init(9) && !(window.opera && parseFloat(window.opera.version()) < 9.5))
			this.jsVer = false;
		else
			this.jsVer = true;

		this.slTooltip = new SLTooltip({
			el: this.slLineDOMElement,
		   //type: 'people_tooltip',
			type: 'spotbox',
			target: 'spotlight-line_ur_2'
		});

		if  (this.jsVer) {
			this.updater = new SLUpdater({
				spotlightVars: this.spotlightVars,
				spotlightMainInstance: this
			});
			this.slLine = new SLLine({
				slDOMElement: this.slLineDOMElement,
				profileURL: this.updater.getProfileUrl(),
				spotlightMainInstance: this,
				items: this.updater.sl_json
			});
		}
		else {
			 this.slLineFlash  = new SLLineFlash({
				slDOMElement: this.slLineDOMElement,
				spotlightVars: this.spotlightVars
			});
		};

		this.tooltipHideAfterTimeout_fn = this.tooltipHideAfterTimeout.bind(this);

		$u.preloadImages([JSRoot + 'i/box-spot.png']);

	},

	destroy: function() {
		clearTimeout(this.tooltipHideAfterTimeoutInterval);
		this.tooltipHideAfterTimeout_fn = null;
		if (this.updater) {
			this.updater.destroy ();
			this.updater = null;
		}
		if (this.slLine) {
			this.slLine.destroy ();
			this.slLine = null;
		}
		if (this.slLineFlash) {
			this.slLineFlash.destroy ();
			this.slLineFlash = null;
		}
		if (this.slTooltip) {
			this.slTooltip.destroy();
			this.slTooltip = null;
		}
		this.slLineDOMElement = null;
	},

	updateLayout: function(json) {
		if (this.slLine)
			this.slLine.updateLayout(json);
	},

	moc0: 1,
	moc1: 1,

	tooltip: function (tooltip_html, x, user_url, from_wizard, id) {

		if  (!this.jsVer)
		  clearTimeout(this.tooltipHideAfterTimeoutInterval);

		this.slTooltip.show4Spotlight(x, tooltip_html, user_url);

	},

	tooltip_hide: function ()
	{
		if  (!this.jsVer) {
			clearTimeout(this.tooltipHideAfterTimeoutInterval);
			this.tooltipHideAfterTimeoutInterval = setTimeout(this.tooltipHideAfterTimeout_fn, 2000);
		 }
		 else {
			this.tooltipHideAfterTimeout();
		 }
	},

	tooltipHideAfterTimeout: function ()
	{
		if (!this.slTooltip.mouseOvered) {
			this.slTooltip.hide();
		}
	}

};

$e.onload(function () {
	Spotlight = new SLMainInstance({
		slLineDOMElement: $('slline'),
		spotlightVars: vars.Spotlight
	});
}, SLMainInstance);



// statistics.js [dpp]

// dConfirm.js [dpp]

var dConfirm =
{
	el:null,
	_tpl:'<div class="container">\
			<div class="central">\
				<div class="cont">\
				</div>\
				<div class="br"></div>\
			</div>\
		</div>\
		<div class="tr"></div>\
		<div class="bl"></div>\
		<div class="tail"></div>',

	x:0,
	y:0,
	type:'',
	text:'',
	onOk:null,
	onCancel:null,
	scope:null,

	defaults:{
		x:0,
		y:0,
		type:'',
		text:'',
		onOk:null,
		onCancel:null,
		scope:null
	},

	init:function()
	{
		$e.on({
			'.dConfirm-ok':this.ok,
			'.dConfirm-cancel':this.cancel
		},this);
	},

	create:function()
	{
		this.el=$u.el('div',{
			className:'hidden confirm',
			innerHTML:this._tpl
		});
		this.cont=$q.down(this.el,'.cont');
		document.body.appendChild(this.el);
	},

	hide:function()
	{
		if(this.el)
			$el.addClassName(this.el,'hidden');
	},

	ok:function(el)
	{
		this.hide();
		if(this.onOk)
			this.onOk.call(this.scope);
	},
	cancel:function(el)
	{
		this.hide();
		this.onCancel && this.onCancel.call(this.scope);
	},

	show:function(config)
	{
		$config(this,config,this.defaults);
		if(!this.el) this.create();

		this.el.className='hidden confirm '+this.type;

		if(typeof(this.text)=='string'){
			this.cont.innerHTML=this.text;
		}else if(this.text.nodeType==1){
			this.cont.innerHTML='';
			this.cont.appendChild(this.text);
		}else if(text instanceof Array){
			this.cont.innerHTML=this.wrap(text);
		}else{
			
			
		}

		this.el.style.left=this.x+'px';
		this.el.style.top=this.y+'px';

		$el.removeClassName(this.el,'hidden');

		var bn=$q.down(this.el,'input, button');
		bn && bn.focus();
	},

	wrap:function(texts)
	{
		return $u.tpl('<div class="ask" id="confirm_ask">{title}</div>\
			{msg}\
			<div id="confirm_buttons">\
				<input type="button" value="{bn_text}" class="dConfirm-ok" />\
				{or} <a href="#" class="dConfirm-cancel">{cancel}</a>\
			</div>',{
				title:texts[0],
				bn_text:texts[1],
				or:texts[2],
				cancel:texts[3],
				msg:texts[4]
			});
	}
};

dConfirm=new ($class(dPage,dConfirm));

// photo-upload.js [vital]

// uploader.js

// <@--# if expr="$uploader!=1" -->
// <@--# set var="uploader" value="1" -->

var mmSWFUpload =
{
	is_ready : false,
	webcam : false,

	ready : function(a)	// from flash
	{
		this.webcam = a;
		this.is_ready = true;
		if ($('addFilesLoader'))
			$('addFilesLoader').style.display = 'none';
	},

	init : function(settings, target)
	{
		target = target || 'SWFUpload2';

		var params = '';
		for (var i in settings) {
			params += '&' + i + '=' + encodeURIComponent(settings[i]);
		}

		if (typeof(is_web_cam)!='undefined' && is_web_cam) {
			$(target).innerHTML = Flash.draw(JSRoot + 'flash/campicture.swf', '400',  // 570, 640
			'300',  // 472, 530
			'', 'ask=' + params, true, target + 'Field');
		} else {
			$(target).innerHTML = Flash.draw(JSRoot + 'flash/uploadtest.swf', '100%', '100%', '', 'ask=' + params, true, target + 'Field');
		}
	},

	// Default error handling.
	handleErrors : function(errcode, file, msg)
	{
		switch(errcode){
		case -10:  // HTTP error
			// alert(errcode + ", " + file + ", " + msg);
			break;

		case -20:  // No backend file specified
			
			break;

		case -30:  // IOError
			
			break;

		case -40:  // Security error
			
			break;

		case -50:  // Filesize too big
			
			break;
		}
	},

	callSWF : function(remain, target)
	{
		var target = target || 'SWFUpload2';
		if (this.is_ready) Flash.get(target + 'Field').uploadImage(remain);
	},

	cancelAll : function()
	{
		if (this.is_ready) Flash.get('SWFUpload2Field').cancelAll();
	},

	cancelUpload : function(id)
	{
		// if (this.webcam)
		Flash.get('SWFUpload2Field').cancelUpload(id);
	},

	createSnapshots : function(num_shots, timestep)
	{
		if (this.webcam) Flash.get('SWFWebcamField').createSnapshots(num_shots || 4, timestep || 100);
	},

	saveSnapshot : function()
	{
		if (this.webcam) Flash.get('SWFWebcamField').saveSnapshot();
	},

	webcamSound : function(click)
	{
		if (this.webcam) Flash.get('SWFWebcamField').sound(click);
	},

	webcamAgain : function()
	{
		if (this.webcam) Flash.get('SWFWebcamField').tryAgain();
	}
};

mmSWFUpload=new ($class(mmSWFUpload));

// <@--# endif -->


if (Flash.init(8)) {
	$u.add_css('#add_photos_form{display:none}');
}

var PhotoUpload =
{
	strings:[ 'Internal Error', 'Upload error or unsupported format', 'File too large, max size: 100Mb', 'Loading...;', 'No rated yet', 'Images', 'Video Files', 'Images and Video', 'All files', 'Done', 'Upload in progress. Would you like to leave this page unsaved?' ],

	types :
	{
		'images':'*.jpg; *.jpeg; *.jpe; *.jfif; *.jfi; *.gif; *.jp2, *.jpc; *.wdp; *.hdp; *.png; *.bmp; *.tiff; *.tif',
		'video' :'*.flv; *.avi; *.mpg; *.mov; *.3gp; *.mpeg; *.mp4; *.wmv'
	},

	cache:{},
	progress:false,
	serv:[],
	sess:'',
	to_remove:{},
	timers:{},

	counters :
	{
		now  :0,
		total:0
	},

	last_percent:0,

	loading :
	{
		file:'',
		time:0
	},

	fom:false,
	inited:false,
	started:false,

	tpl :
	{
		'process' :'<tr id="l#id#"><th class="thumb"><div class="nothumb"></div></th><th class="name"><div>#filename#</div></th><td class="icon"><a href="#" id="fid#fid#" class="cancel"></a></td><td class="status"><div class="upload_bar"><span></span></div></td></tr>',
		'error'   :'<tr><th class="thumb"><div class="nothumb"></div></th><th class="name"><div>#filename#</div></th><td class="icon"><span class="note"></span></td><td class="status">#status#</td></tr>',
		'done'    :'<tr id="l#id#"><th class="thumb"><div class="thumb"><img src="#url#" alt="" width="#w#" height="#h#" /></div></th><th class="description"><div><a href="#" class="description emptydesc">#add_str#</a></div></th><td class="icon"><span class="ok"></span></td><td class="status uploaded">#uploaded_str#</td></tr>',
		'descview':'<tr id="l#id#"><th class="thumb"><div class="thumb"><img src="#url#" alt="" width="#w#" height="#h#" /></div></th><th class="description"><div><a href="#" class="description" title="#edit_str#">#description#</a></div></th><td class="icon"><span class="ok"></span></td><td class="status uploaded">#uploaded_str#</td></tr>',
		'descedit':'<tr id="l#id#"><th class="thumb"><div class="thumb"><img src="#url#" alt="" width="#w#" height="#h#" /></div></th><th colspan="3" class="description"><form action="" class="photodescr" id="frm#id#"><button type="button" class="escape_action cancel_descr">#descr_cancel#</button><button type="button" class="approve">#descr_save#</button><div class="photodescr_input"><div><input id="lin#id#" type="text" size="50" value="#description#" /></div></div></form></th></tr>'
	},

	init:function()
	{
		if (!Flash.init(8)) return false;
		PhotoUpload.clear_timers();

		if(!$('js_str')) return;

		PhotoUpload.strings=$('js_str').title.split('|');
		//PhotoUpload.popup='<div id="p_upload">' + $('p_upload_content').innerHTML + '</div>';
		PhotoUpload.tpl.done=PhotoUpload.replacer('done', [ 'add_str', 'uploaded_str' ], [ vars.upload_str.click_str[0], vars.upload_str.uploaded_str ]);
		PhotoUpload.tpl.descview=PhotoUpload.replacer('descview', [ 'edit_str', 'uploaded_str' ], [ vars.upload_str.click_str[1], vars.upload_str.uploaded_str ]);
		PhotoUpload.tpl.descedit=PhotoUpload.replacer('descedit', [ 'descr_cancel', 'descr_save' ], vars.upload_str.descr_str);
		vars.upload_str.delete_str[4]=$u.tpl('<div>{html}</div>', { html:vars.upload_str.delete_str[4] });

		PhotoUpload.serv=vars.photo_service;
		PhotoUpload.sess='?' + $('session_name').name + '=' + $('session_name').value;
		PhotoUpload.fom=($('photoset') && $('photoset').className == 'is_fom');

		// PhotoUpload.init_flash();

		window.onbeforeunload=PhotoUpload.check_progress;
		$e.on({
			'.add_more_photos':PhotoUpload.open_popup,
			'.add_photo':PhotoUpload.open_popup,
			'.take_webcam':PhotoUpload.open_webcam,
			'* .add_photo':PhotoUpload.open_popup
		}, PhotoUpload);
		$e.onclick(PhotoUpload.click_event);
		$u.app.on('upload_photo',PhotoUpload.open_popup,PhotoUpload);
		$u.app.on('webcam_link',PhotoUpload.open_webcam,PhotoUpload);
	},

	once:false,
	init_flash:function(webcam)
	{
		is_web_cam=webcam||false;

		$('SWFUpload').innerHTML='';

		if(!webcam){
			var w=$('SWFUpload2');
			var bn1=$('addFilesDialog');

			if(w && bn1)
				w.clonePosition(bn1);
		}

		mmSWFUpload.init(
		{
			uploadBackend              :(($('upload_ws_url')?$('upload_ws_url').value:$('upload_form').action).replace('/upload/', '/upload-ws/') + '?slot=' + Math.random() + '&' + $('session_name').name + '=' + $('session_name').value),
			allowedFilesize            :'100',
			imageTypesDescription      :PhotoUpload.strings[5],
			imageTypesExtension        :PhotoUpload.types.images,
			videoTypesDescription      :PhotoUpload.strings[6],
			videoTypesExtension        :PhotoUpload.types.video,
			mediaTypesDescription      :PhotoUpload.strings[7],
			allTypesDescription        :PhotoUpload.strings[8],
			uploadStartCallback        :'PhotoUpload.start',
			uploadProgressCallback     :'PhotoUpload.loaded',
			uploadCompleteCallback     :'PhotoUpload.complete',
			uploadErrorCallback        :'PhotoUpload.error',
			uploadCancelCallback       :'PhotoUpload.cancel',
			uploadQueueCompleteCallback:'PhotoUpload.queue_complete',
			webcamReady                :'PhotoUpload.webcam_ready',
			webcamSnapshotsReady       :'PhotoUpload.webcam_snapshots_ready',
			txt1                       :vars.upload_str.webcam_str[0],
			txt2                       :vars.upload_str.webcam_str[1],
			txt3                       :vars.upload_str.webcam_str[2],
			txt4                       :vars.upload_str.webcam_str[3],
			txt5                       :vars.upload_str.webcam_str[4]
		},
		webcam?'SWFWebcam':'SWFUpload2');

	},

	webcam_ready:function()
	{
		$('takeShot').disabled=false;
		mmSWFUpload.webcam=true;
	},

	webcam_snapshots_ready:function()
	{
		// remove white screen
		PhotoUpload.white_screen(0);
		$('save_shot').removeClassName('hidden');
	},

	clear_timers:function(now)
	{
		PhotoUpload.timers =
		{
			file_name   :'',
			file_time   :0,
			queue_time  :(now?new Date().getTime():0),
			queue_size  :0,
			queue_loaded:0
		};
	},

	switch_progress:function(s)
	{
		if (PhotoUpload.progress == s) return;
		if (!s) PhotoUpload.started=false;

		// if ($('simpleHint')) $('simpleHint').hide();
		PhotoUpload.clear_timers(s);

		var disable_buttons=[ 'save', 'finishUpload' ];

		for (var i=0; i<disable_buttons.length; i++)
		{
			var b=$(disable_buttons[i]);
			if (b) b.disabled=s;
		}

		PhotoUpload.uploading_hint(s);
		PhotoUpload.progress=s;
	},

	check_progress:function()
	{
		if (PhotoUpload.progress) return PhotoUpload.strings[11];
	},

	click_event:function(e)
	{
		var el=Event.element(e);
		if (el.tagName == 'B' && el.up('a')) el=el.up('a');

		if (el.tagName == 'A' && el.hasClassName('description') && el.up('th'))
		{
			Event.stop(e);

			var lid=el.up('tr');
			var id=lid.id.substr(1);
			var a=lid.down('a');
			var desc='';

			if (!a.hasClassName('emptydesc')) {
				desc=a.innerHTML.replace('"', '&quot;');
			}

			new Insertion.After(lid, PhotoUpload.replacer('descedit', [ 'url', 'w', 'h', 'id', 'description' ], PhotoUpload.cache[id].slice(0, 4).concat([ desc ])));
			lid.remove();
			$('lin'+id).focus();

			var frm=$('frm' + id);
			Event.observe(frm, 'submit', PhotoUpload.input);
		}
		else if (el.id)
		{
			switch(el.id)
			{
				case 'try_classic':
					Event.stop(e);
					PhotoUpload.close(e);
					$('add_photos_form').show();
					break;

				/* case 'addFiles':
					Event.stop(e);

					// if (!mmSWFUpload.is_ready) return;
					PhotoUpload.open_popup();
					break; */

				case 'addFilesDialog':
				case 'addMoreFilesDialog':
					Event.stop(e);
					if (!mmSWFUpload.is_ready) return;
					mmSWFUpload.callSWF(vars.photos_limit[1]);
					break;

				case 'simpleForm':
					Event.stop(e);
					$u.add_css('#add_photos_form{display:block}');

					if ($('submit_to'))
					{
						$('submit_to').value=$('upload_form').old_action;
						$('upload_form').action=$('upload_form').old_action;
					}

					PhotoUpload.close(e);
					break;

				case 'finishUpload':
					PhotoUpload.close(e);
					$u.app.set(vars.PhotoUpload && vars.PhotoUpload.onComplete_url || '');
					break;

				case 'tryShot':
					mmSWFUpload.webcamAgain();
					$('take_shot').removeClassName('hidden');
					$('progress_shot').addClassName('hidden');
					$('save_shot').addClassName('hidden');
					break;

				case 'takeShot':
					PhotoUpload.progress_shot();
					break;

				case 'saveShot':
					$('save_shot').addClassName('hidden');
					$('uploading_shot').removeClassName('hidden');
					mmSWFUpload.saveSnapshot();
					break;

				default:
					if (el.tagName == 'A' && el.id.substr(0, 3) == 'fid')
					{
						Event.stop(e);
						el.up('tr').remove();
						mmSWFUpload.cancelUpload(el.id.substr(3));
					}

					break;
			}
		}
		else if (el.className)
		{
			switch(el.className)
			{
				case 'webcam_link':
				case 'webcam':
					Event.stop(e);
					PhotoUpload.open_webcam();
					break;

				case 'email':
					Event.stop(e);
					$('upload-start').addClassName('hidden');
					$('webcam-shooter').addClassName('hidden');
					$('email-uploader').removeClassName('hidden');

					$('take_shot').addClassName('hidden');
					$('progress_shot').addClassName('hidden');
					$('save_shot').addClassName('hidden');

					dOvl.center();
					break;

				case 'files':
					Event.stop(e);
					PhotoUpload.open_files();
					break;

				case 'tClose':
					Event.stop(e);
					PhotoUpload.close(e);
					break;

				case 'approve':
					var tr=el.up('tr');

					if (tr) {
						PhotoUpload.description_save(tr.id.substr(1));
					}

					break;
			}

			if (el.hasClassName('cancel_descr'))
			{
				var tr=el.up('tr');

				if (tr)
				{
					var id=tr.id.substr(1);
					var lid=$('l' + id);
					new Insertion.After(lid, PhotoUpload.replacer((PhotoUpload.cache[id][4] == ''?'done':'descview'), [ 'url', 'w', 'h', 'id', 'description' ], PhotoUpload.cache[id]));
					lid.remove();
				}
			}
		}
	},

	open_webcam:function()
	{
		if(!PhotoUpload._opened) PhotoUpload.open_popup();
		$('upload-start').addClassName('hidden');
		$('email-uploader').addClassName('hidden');
		$('webcam-shooter').removeClassName('hidden');

		$('take_shot').removeClassName('hidden');
		$('progress_shot').addClassName('hidden');
		$('save_shot').addClassName('hidden');

		PhotoUpload.init_flash(true);
		dOvl.center();
	},

	progress_shot:function(num)
	{
		if($('takeShot').disabled) return;

		if (typeof num == 'undefined')
		{
			$('take_shot').addClassName('hidden');
			$('progress_shot').removeClassName('hidden');
			$('save_shot').addClassName('hidden');
			mmSWFUpload.webcamSound(1);
			window.setTimeout('PhotoUpload.progress_shot(2)', 1000);
		}
		else
		{
			if (num < 1)
			{
				$('progress_shot').addClassName('hidden');
				$('progress_shot').down().className='cipher1';
				PhotoUpload.white_screen(1);
				mmSWFUpload.webcamSound(0);
				mmSWFUpload.createSnapshots();
			}
			else
			{
				$('progress_shot').down().className='cipher' + (4 - num);
				mmSWFUpload.webcamSound(num == 1?2:1);
				window.setTimeout('PhotoUpload.progress_shot(' + (num - 1) + ')', 1000);
			}
		}
	},

	white_screen:function(on)
	{
		if (on && !$('white_screen'))
		{
			var w=$u.el('div',{id:'white_screen'});
			document.body.appendChild(w);
		}
		else if (!on && $('white_screen'))
		{
			var o=new Fx.Opacity('white_screen',
			{
				duration:500,
				transition:Fx.Transitions.linear,

				onComplete:function() {
					this.element.remove();
				}
			});  // opacity: true

			o.toggle();
		}
	},

	open_popup:function()
	{
		PhotoUpload._opened=true;
		if(!PhotoUpload.once){
		    PhotoUpload.popup='<div id="p_upload">' + $('p_upload_content').innerHTML + '</div>';
		    PhotoUpload.once=true;
		}
		if($('slideshow'))
			$('slideshow').addClassName('noflash');

		dOvl.open({
			html:PhotoUpload.popup,
			hide_close:true,
			onClose:function()
			{
				PhotoUpload._opened=false;
				if ($('slideshow')) $('slideshow').removeClassName('noflash');
			},
			onLoad:function()
			{
				PhotoUpload.init_flash();
			}
		});
	},

	open_files:function()
	{
		is_web_cam=false;
		$('upload-start').removeClassName('hidden');
		$('webcam-shooter').addClassName('hidden');
		$('email-uploader').addClassName('hidden');

		dOvl.center();
	},

	close:function(e, close)
	{
		if (close)
		{
			mmSWFUpload.cancelAll();
			PhotoUpload.queue_complete();
			dOvl.close();

			PhotoUpload.counters =
			{
				now  :0,
				total:0
			};

			return false;
		}

		if (PhotoUpload.progress) {
			dConfirm.show({
				x:(Event.pointerX(e) - 241),
				y:(Event.pointerY(e) - 100),
				type:'br_tail zindex7001',
				text:dConfirm.wrap(vars.upload_str.delete_str),
				onOk:PhotoUpload.close.bind(PhotoUpload,0,1)
			});
		}
		else
		{
			dOvl.close();

			PhotoUpload.counters =
			{
				now  :0,
				total:0
			};
		}

		return false;
	},

	input:function(e)
	{
		Event.stop(e);
		var el=Event.element(e);
		PhotoUpload.description_save(el.id.substr(3));
	},

	description_cancel:function(id) {},

	description_save:function(id)
	{
		var myAjax=new Ajax.Request(PhotoUpload.serv[1] + id + '/description-ws/',
		{
			method:'post',
			parameters:'description=' + encodeURIComponent($('lin' + id).value.strip()),

			onComplete:function(r)
			{
				var res=eval('(' + r.responseText + ')');

				if (res.errno == 0)
				{
					$('p' + res.data.photo_id).childNodes[0].childNodes[0].lastChild.childNodes[1].nodeValue=res.data.description.unescapeHTML();

					var lid=$('l' + res.data.photo_id);
					var id=lid.id.substr(1);
					PhotoUpload.cache[id][4]=res.data.description;
					new Insertion.After(lid, PhotoUpload.replacer((res.data.description == ''?'done':'descview'), [ 'url', 'w', 'h', 'id', 'description' ], PhotoUpload.cache[id]));
					lid.remove();
				}
				else if (res.auth)
				{
					window.location.href=res.auth;
				}
			}
		});
	},

	check_photo_counter:function(count)
	{
		vars.photos_limit[1] += count;

		if ($('addMore')) if (vars.photos_limit[1] < 1) {
			$('addMore').addClassName('hidden');
		} else {
			$('addMore').removeClassName('hidden');
		}

		PhotoUpload.uploading_hint(1);
	},

	idify:function(name)
	{
		if (!name) return;
		var ret="i";

		for (var i=0; i<name.length; i++) {
			ret += name.charCodeAt(i).toString(16);
		}

		return ret;
	},

	// Default upload start function.
	start:function(fileObj)
	{
		PhotoUpload.switch_progress(true);
		if (is_web_cam) return;
		if ($('upload-start')) $('upload-start').addClassName('hidden');
		if ($('upload-process')) $('upload-process').removeClassName('hidden');

		if (!PhotoUpload.started) {
			dOvl.center();
		}

		var w=$('SWFUpload2');
		var bn2=$('addMoreFilesDialog');

		if(w && bn2)
			w.clonePosition(bn2);

		PhotoUpload.started=true;

		PhotoUpload.create_loader(fileObj);
		PhotoUpload.counters.total++;
		if ($('files_toupload_num')) $('files_toupload_num').innerHTML=PhotoUpload.counters.total;
		PhotoUpload.timers.queue_size += fileObj.size;
	},

	loaded:function(fileObj, bytesLoaded)
	{
		if (is_web_cam) return;
		var now=new Date().getTime();
		if ((PhotoUpload.loading.file == fileObj.name) && (bytesLoaded != fileObj.size) && ((now - PhotoUpload.loading.time) < 1000)) return;
		PhotoUpload.loading.file=fileObj.name;
		PhotoUpload.loading.time=now;

		PhotoUpload.create_loader(fileObj);
		var percent=Math.ceil((bytesLoaded / fileObj.size) * 100);
		var queue_percent='';
		if(PhotoUpload.timers.queue_size)
			queue_percent=Math.ceil(((PhotoUpload.timers.queue_loaded + bytesLoaded) / PhotoUpload.timers.queue_size) * 100);

		// count total progress
		var elapsed=now - PhotoUpload.timers.queue_time;

		var t='';

		/*
		  if (elapsed>5000)
		  {
			 t=Math.round((PhotoUpload.timers.queue_time+Math.round((elapsed*100)/queue_percent)-now)/1000);

			 h=Math.floor(t/3600);
			 m=Math.floor((t-h*3600)/60);
			 s=Math.floor(t-h*3600-m*60);
			 t=' (remain: '+(h<10?'0':'') +h + ':' + (m<10?'0':'')+m  + ':' + (s<10?'0':'') + s+')';
		  }
		  */

		if ($('loaded_percent')) $('loaded_percent').innerHTML=queue_percent?(queue_percent + '%'):'...' + t;

		if (PhotoUpload.last_percent == percent) return;
		PhotoUpload.last_percent=percent;

		// count file progress
		var t='';

		if (percent != 100)
		{
			if (PhotoUpload.timers.file_name != fileObj.name)
			{
				PhotoUpload.timers.file_name=fileObj.name;
				PhotoUpload.timers.file_time=new Date().getTime();
			}
		}

		var tr=$('l' + PhotoUpload.idify(fileObj.name));
		var sp=tr.getElementsByTagName('span')[0];
		sp.style.width=Math.round((189 * percent) / 100) + 'px';
	},

	create_loader:function(fileObj, file_name)
	{
		if (is_web_cam) return;
		var fname=file_name || fileObj.name || false;
		var id=PhotoUpload.idify(fname);

		if (!$('l' + id) && fname && $('upload-filelist')) {
			new Insertion.Bottom($('upload-filelist'), PhotoUpload.replacer('process', [ 'id', 'filename', 'fid' ], [ PhotoUpload.idify(fname), fname.escapeHTML(), fileObj.id || false ]));
		}
	},

	replacer:function(str, tpl, values)
	{
		var str=PhotoUpload.tpl[str];
		var reg=false;

		for (var i=0; i<tpl.length; i++)
		{
			reg=new RegExp('#' + tpl[i] + '#', 'gi');
			str=str.replace(reg, values[i]);
		}

		return str;
	},

	complete:function(fileObj)
	{
		if (!fileObj.result) return;
		PhotoUpload.counters.now++;
		if ($('files_uploaded_num')) $('files_uploaded_num').innerHTML=PhotoUpload.counters.now;
		PhotoUpload.timers.queue_loaded += fileObj.size;

		if (fileObj.result.indexOf('|') != -1)
		{
			var res=fileObj.result.split('|');
			var s=res[4].split('x');
			var v=res[3].split('x');
			var is_video=(v.length > 2);

			PhotoUpload.file_info(fileObj.name, '', 0, [ s[0], s[1], res[1], res[0] ]);

			if(typeof(EntryEdit)!='undefined')
				EntryEdit.draw_uploaded_photo(res,s,is_video)
		}
		else
		{
			PhotoUpload.file_info(fileObj.name, fileObj.result, 1);
		}

		if(typeof(PhotoEdit)!='undefined')
			PhotoEdit.updateLinks();
	},

	remove:function(id)
	{
		var el=$('p' + id);
		el.remove();
		EntryEdit.init_sortable();
	},

	uploading_hint:function(first)
	{
		first=first?1:0;
		var upl=$('upload-process');
		if(!upl) return;

		var pclose=upl.select('p.close').toArray();
		var l=pclose[first].addClassName('hidden');
		PhotoUpload.recount_string(l);

		var l=pclose[1-first].removeClassName('hidden');
		PhotoUpload.recount_string(l);
	},

	recount_string:function(el)
	{
		var l1=el.down();

		if (l1.down('i')) l1.down('i').update(vars.photos_limit[1]);

		l1[vars.photos_limit[1] > 1?'removeClassName':'addClassName']('hidden');
		l1.next()[vars.photos_limit[1] == 1?'removeClassName':'addClassName']('hidden');
		l1.next(1)[vars.photos_limit[1] < 1?'removeClassName':'addClassName']('hidden');
	},

	queue_complete:function(fileObj)
	{
		if ($('loaded_percent')) $('loaded_percent').innerHTML='100%';

		PhotoUpload.switch_progress(false);

		if ($('share') && (EntryView.ph.length > 0)) {
			$('share').removeClassName('hidden');
		}

		if (is_web_cam) {
			window.setTimeout('PhotoUpload.open_files();PhotoUpload.close();', 300);
		}
	},

	error:function(errcode, file, msg)
	{
		// alert(errcode+':'+ file + ':'+ msg);
		switch(errcode)
		{
			case -10:  // HTTP error
				if (msg == 500) {
					PhotoUpload.file_info(file.name, PhotoUpload.strings[1], 1);
				} else {
					PhotoUpload.file_info(file.name, PhotoUpload.strings[0], 1);
				}

				break;

			case -20:  // No backend file specified
				PhotoUpload.file_info(file.name, PhotoUpload.strings[0], 1);
				break;

			case -30:  // IOError
				PhotoUpload.file_info(file.name, PhotoUpload.strings[0], 1);
				break;

			case -40:  // Security error
				PhotoUpload.file_info(file.name, PhotoUpload.strings[0], 1);
				break;

			case -50:  // Filesize too big
				PhotoUpload.file_info(file.name, PhotoUpload.strings[2], 1);
				break;

			case -60:  // Too much files
				PhotoUpload.file_info(file.name, PhotoUpload.strings[0], 1);
				break;
		}

		return true;
	},

	file_info:function(filename, info, err, photo)
	{
		if (is_web_cam) return;
		PhotoUpload.create_loader(false, filename);

		var id=PhotoUpload.idify(filename);
		var lid=$('l' + id);

		if (lid)
		{
			var id=PhotoUpload.idify(filename);

			if (err) {
				new Insertion.After(lid, PhotoUpload.replacer('error', [ 'status', 'filename' ], [ info, filename ]));
			}
			else
			{
				var rw=photo[0] / 34;
				var rh=photo[1] / 24;

				var ratio=(rh > rw?rh:rw);

				rw=Math.ceil(photo[0] / ratio);
				rh=Math.ceil(photo[1] / ratio);

				PhotoUpload.cache[photo[3]]=[ photo[2], rw, rh, photo[3], '' ];
				new Insertion.After(lid, PhotoUpload.replacer('done', [ 'url', 'w', 'h', 'id' ], [ photo[2], rw, rh, photo[3] ]));
			}

			lid.remove();
		}
	},

	cancel:function() {
		PhotoUpload.switch_progress(false);
	},

	get_limit:function()
	{
		return parseInt(vars.photos_limit[1]);
	}
};

$e.onload(PhotoUpload.init,PhotoUpload);

// riseup.js [dpp]

var Riseup={
	name:'Riseup',
	url:'/ws/riseup-ws.phtml',

	init:function()
	{
		$e.on({
			'.riseup_open':this.open
		}, this);
	},

	open:function()
	{
		dOvl.open({
			url:this.url
		});
	}
};

Riseup=new ($class(dPage,Riseup));


var Statistics=
{
	name:'Statistics',
	data:{},
	data_list:{},
	data_list2:{},

	init:function()
	{
		$e.on('.stats_info', this.showTooltip, this);

		this.data=this.data||{};
		$config(this.data,this.data_list);
		$config(this.data,this.data_list2);
	},

	showTooltip:function(el)
	{
		var e=$e.e;
		var div=$q.up(el,'div.stats_info_wrap, div.user_contact');
		if(!div) return;

		var data=this.data[div.id] || '';
		if(!data){
			
			return true;
		}
		var offset=$el.cumulativeOffset(el);

		dConfirm.show({
			x:parseInt(offset.left+el.offsetWidth+6),
			y:(offset.top-10),
			type:'',
			text:data
		});
	}
};

Statistics=new ($class(dPage,Statistics));

// chatting-inset.js [elena]

var ChattingInset=
{
	name:'ChattingInset',
	inset:null,
	text:null,
	activated:false,
	autoshow:false,

	init:function()
	{
		this.inset=$('js_chatting_button') && $('js_chatting_button').down('span');
		this.block=$('js_chatting_block');

		if(!this.inset || !this.block)
			return;

		this.form=this.block.down('form');
		this.block.style.left='-240px';

		this.activated=this.block.hasClassName('search_interlocutor')?true:false;

		if(this.autoshow)
			this.show(this.inset);

		if(!this.activated){
			$e.add(this.inset, 'mouseover', this.show, this);
		}else{
			$e.add(this.inset, 'mouseover', this.over, this);
			$e.on(this.inset, this.show, this);
		}
		$e.add(this.inset, 'mouseout', this.hide, this);
		$e.add(this.block, 'mouseover', this.over, this);
		$e.add(this.block, 'mouseout', this.hide, this);

		$e.add(this.form, 'submit', this.activate, this);
	},

	activate:function(el)
	{
		this.form.request();
		this.block.replaceClassName('wish_to_chat', 'search_interlocutor');
	},

	show:function(el)
	{
		clearTimeout(this.collapse_timeout);
		this.move(this.block, 10, 15, 0);
	},

	over:function(el)
	{
		clearTimeout(this.collapse_timeout);
	},

	hide:function(el)
	{
		var e=$e.e;
		var reltg=e.relatedTarget || e.toElement;
		reltg=$(reltg);
		if(!reltg || reltg && !reltg.up('#js_chatting_block'))
			this.collapse_timeout=setTimeout(this.move.bind(this, this.block, -10, 15, -240), 200);
	},

	move:function(obj, step, time, to, b)
	{
		obj=$(obj);
		if(!obj || obj._process || obj._done == to) return;

		obj._process=true;
		step=step || 10;
		time=time || 10;

		this.make_step(obj, step, time, to);
	},

	make_step:function(obj, step, time, to)
	{
		if((step > 0 && parseInt(obj.style.left) < 0) || (step < 0 && parseInt(obj.style.left) >= (to - step))){
			obj.style.left=parseInt(obj.style.left) + step + 'px';
			this._toggle_position_timer=setTimeout(this.make_step.bind(this, obj, step, time, to), time);
		} else{
			obj._process=false;
			obj._done=to;
		}
	}
};

ChattingInset=new ($class(dPage,ChattingInset));

// tiw.js [dpp]

// dSuggest.js [dpp]

/**
 * @dependences dEvtMan, dClass, dUtils, Prototype [ Event, Element, Selector, Ajax, Function.bind ]
 * @param {} config
 */

// <@--# if expr="$dsuggest!=1" -->
// <@--# set var="dsuggest" value="1" -->

/**
* @class dSuggest	- suggest as you type
* @contructor
*/
var dSuggest=function(config)
{
	$config(this,config);
	this.init();
}

dSuggest.prototype=
{
	target:null,
	timeout: 500,
	url:'',
	url_params:{},
	msgs:{
		note:'Start typing and select your city from the list',
		loading:'Loading...',
		nothing_found:'Nothing found'
	},
	validate:false,
	initial_data:null,
	del:true,
	autocomplete_onblur:true,

	_focused:false,
	_timer:null,
	_form:null,
	_list:null,
	_value:'',
	_sel_length:0,
	_sel_item:0,
	_items:null,
	_show_loading:true,
	_load_progress:false,
	_store:{},

	init:function()
	{
		var target=this.target=$(this.target);
		if(!this.target) return;

		this.url_params={};

		target.setAttribute("autocomplete", "off");

		this._value=target.value;

		this._list=$u.el('ul',{className:'hidden'});
		target.parentNode.appendChild(this._list);

		if(this.del){
			this._del=$u.el('div');
			target.parentNode.appendChild(this._del);
		}

		this._form=this._form||$q.up(target,'form');

		if(!this._hid){
			var hid=$q.down(this._form,'input[name='+target.name+'_id'+']');
			if(!hid){
				hid=$u.el('input',{
					name:(target.name+'_id'),
					type:'hidden'
				});
				target.parentNode.insertBefore(hid,target);
			}
			this._hid=hid;
		}

		this._suggest_fn=this.suggest.bind(this);

		$e.add(target,'keyup',this.suggest_delayed,this);
		$e.add(target,'keydown',this.highlight_kbd,this);
		$e.add(this._list,'mouseover',this.highlight_mouse,this);
		$e.add(target,'blur',this.blur,this);
		// $e.add(target,'click',this.focus,this);
		$e.add(target,'focus',this.focus,this);
		if(this.del) $e.add(this._del,'click',this.clear,this);
		if(!this.autocomplete_onblur)
			$e.add(this._list,'click',this.select,this);

		$e.add(this._form,'submit',this.onSubmit,this);

		if(this.initial_data)
			this.parse_results(this.initial_data);
	},

	focus:function()
	{
		if(this._focused)
			return true;

		this.target.select();
		this._focused=true;
		this.layout();
		return true;
	},

	blur:function()
	{
		this._focused=false;

		// if(this._items && !this._timer){
		if(this.autocomplete_onblur)
			this.select();
		// }

		this.onError(!this._hid.value);

		this.layout();
		return true;
	},

	clear:function()
	{
		this._value=this.target.value="";
		this._hid.value='';
		if(this._transport){
			this._transport.abort();
			this._transport=null;
		}
		this.target.focus();
		// this.layout();
	},

	highlight:function(i,renew)
	{
		if(!this._items) return;

		if(!renew)
			$el.removeClassName(this._list.childNodes[this._sel_item],'selected');

		if(i<0) i=this._sel_length+i;
		this._sel_item=i%this._sel_length;

		var list=this._list;
		var item=list.childNodes[this._sel_item];

		$el.addClassName(item,'selected');

		if(this._list.className)	// invisible list causes hard reflow in opera
			return;

		if(item.offsetTop<list.scrollTop){
			list.scrollTop=item.offsetTop;
		}else if(item.offsetTop+item.offsetHeight>list.scrollTop+list.offsetHeight){
			list.scrollTop=item.offsetTop-list.offsetHeight+item.offsetHeight;
		}
	},

	highlight_mouse:function(el)
	{
		if(!this._items || !el) return;

		if(el.nodeName!='LI'){
			el=el.parentNode;
			if(el.nodeName!='LI'){
				return;
			}
		}

		$el.removeClassName(this._list.childNodes[this._sel_item],'selected');
		this._sel_item=0;
		var i=el;
		while(i.previousSibling){
			i=i.previousSibling;
			if(i.nodeName=='LI')
				this._sel_item++;
		}
		$el.addClassName(this._list.childNodes[this._sel_item],'selected');
	},

	highlight_kbd:function()
	{
		var e=$e.e;
		var code=e.charCode||e.keyCode||e.which||0;

		switch(code){
		case 40:	// down
			this.highlight(this._sel_item+1);
			return;
		case 38:	// up
			this.highlight(this._sel_item-1);
			return;
		case 13:	// enter
			this.select();
			return;
		}
		return true;
	},

	select:function()
	{
		if(this._items){
			var id=/^dsi_([\d_]+)$/.exec(this._list.childNodes[this._sel_item].id)[1];
			var v=this._items[id].split(', ');
			if((this._items[id].unique) && v.length==3)
				v.splice(1,1);
			v=v.join(', ');
			this._value=this.target.value=v;
			if(this.url) this._items=null;
			this._hid.value=id;
		}

		if(this._hid.value)
			this.onError(false);

		this.layout();
	},

	suggest_delayed:function()
	{
		if(this._value==this.target.value)
			return;

		this._hid.value='';

		clearTimeout(this._timer);
		this._timer=null;

		// if(!this._timer){
			if(this.target.value.length<2){
				if(this.url) this._items=null;
				this._value='';
			}else{
				if(this.url)
					this._timer=setTimeout(this._suggest_fn,this.timeout);
			}
		// }

		// if(this.target.value.length>1 && this._value!=this.target.value && !this._items)
			// this._load_progress=true;

		this.layout();
	},

	suggest:function()
	{
		this._timer=null;

		if(this._value==this.target.value){
			this.layout();
			return;
		}

		this._value=this.target.value;
		if(this._transport){
			this._transport.abort();
			this._transport=null;
		}

		if(this.target.value){
			this._load_progress=true;

			var q=this.target.value.replace(/(^[\s,]+|[\s,]+$)/g,'');

			if(q in this._store){
				setTimeout(this.parse_results.bind(this,this._store[q]),0);
			}else{
				this.url_params.q=q;
				//! [dpp] try to re-use object - dont create new one every time
				this._transport=new $r(this.url,{
					method:'get',
					params:this.url_params,
					ready:this.suggest_ready,
					error:this.response_error
				},this);
			}
		}

		this.layout();
	},

	suggest_ready:function(res)
	{
		this.parse_results(res);

		this._transport=null;
	},

	response_error:function()
	{
		this._load_progress=false;
		this.layout();
	},

	parse_results:function(res)
	{
		if(!res) return;

		this._store[res.q]=res;

		this._load_progress=false;

		var locations=res.locations;

		if('length' in locations){
			this._items=null;
			this._sel_item=null;
			this._sel_length=0;
		}else{
			var q=res.q;
			var html=[];

			var filter_data=res.filter && this.filters[res.filter];
			if(filter_data)
				locations=filter_data(locations);

			this._items=locations;
			var j=false;
			var re=new RegExp('('+q+')','i');
			for(var i in locations){
				html[html.length]='<li id="dsi_'+i+'"'+(j?'class="bg"':'')+'>'+(q?locations[i].replace(re,'<span>$1</span>'):locations[i])+'</li>';
				j=!j;
			}
			this._sel_length=html.length;

			this._list.innerHTML=html.join('');
			this.highlight(0,1);

			if(!this._focused && html.length==1){
				this.select();
			}
		}


		this.layout();
	},

	filters:{
		rm_region:function(data)
		{
			var res={};
			var idx={};

			for(var i in data){
				var v=data[i].split(', ');
				v[3]=v[0]+v[2];
				res[i]=v;

				idx[v[3]]=(idx[v[3]]||0)+1;
			}

			for(var i in res){
				var v=res[i];

				if(idx[v[3]]==1){
					res[i]=v[0]+', '+v[2];
					res[i].unique=true;
				}else{
					res[i]=v[0]+', '+v[1]+', '+v[2];
				}
			}

			return res;
		}
	},

	external_set:function(id,text)
	{
		var v=text.split(', ');
		if(v.length==3){
			v.splice(1,1);
			text=v.join(', ');
		}

		this._value=this.target.value=text;
		this._hid.value=id;
		if(this.url) this._items=null;

		this.onError(!this._hid.value);
		this.layout();
	},

	onError:function(error)
	{
		if(error) $el.addClassName(this.target,'error_location');
		else $el.removeClassName(this.target,'error_location');
	},

	onSubmit:function()
	{
		if(window.opera && this._focused){
			return;
		}

		if(!this.validate || this.onValidate())
			return true;

		if(this.target.offsetHeight)	//FIXME (reflow)
			this.target.focus();
	},

	onValidate:function()
	{
		if(this._hid.value){
			this.onError(false);
			return true;
		}else{
			this.onError(true);
			return false;
		}
	},

	layout:function()
	{
		clearTimeout(this._del_timer);

		if(!this._focused){
			this._del_timer=setTimeout((function(){
				this._list.className='hidden';
				if(this.del) this._del.className='hidden';
			}).bind(this),200);

			if(this._load_progress){
				$el.addClassName(this.target.parentNode,'dSuggest-loading');
			}else{
				$el.removeClassName(this.target.parentNode,'dSuggest-loading');
			}

			if(this._hid.value)
				$el.addClassName(this.target,'selected');

			return;
		}

		$el.removeClassName(this.target,'selected');

		if(this._hid.value)
			this._list.className='hidden';
		else
			this._list.className='';

		var msg='';
		if(this.target.value.length<2 || this._value.length<2){
			msg=('<li class="info_li">'+this.msgs.note+'</li>');
			if(this.del) this._del.className='hidden';
			this._show_loading=true;
		}else if(this._load_progress && this._show_loading){
			msg=('<li class="info_li">'+this.msgs.loading+'</li>');
			this._show_loading=false;
		}else if(!this._hid.value && !this._items){
			msg=('<li class="info_li">'+this.msgs.nothing_found+'</li>');
			this._show_loading=true;
		}
		if(msg) this._list.innerHTML=msg;

		if(this._load_progress){
			if(this.del) this._del.className='hidden';
			$el.addClassName(this.target.parentNode,'dSuggest-loading');
		}else{
			if(this.target.value)
				if(this.del) this._del.className='';
			$el.removeClassName(this.target.parentNode,'dSuggest-loading');
		}
	}
};

// <@--# endif -->

// dLabel.js [dpp]

// <@--# if expr="$dlabel!=1" -->
// <@--# set var="dlabel" value="1" -->

var dLabel=function(config)
{
	$config(this,config);
	this.init();
};

dLabel.prototype={
	el:null,
	input:null,

	init:function()
	{
		this.input=$(this.el && this.el.htmlFor);

		if(!this.el || !this.input){
			//
			return;
		}

		this.show();

		$e.add(this.el,'click',this.hide,this);
		$e.add(this.input,'focus',this.hide,this);
		$e.add(this.input,'blur',this.show,this);
	},

	destroy:function()
	{
		$e.del(this.el,'click',this.hide,this);
		$e.del(this.input,'focus',this.hide,this);
		$e.del(this.input,'blur',this.show,this);

		this.input=null;
		this.el=null;
	},

	hide:function(el)
	{
		this.el.style.display='none';
		if($e.e.type!='focus' && !this.input.disabled)
			this.input.focus();
	},

	show:function(el)
	{
		this.el.style.display=this.input.value?'none':'block';
	}
};


$e.onload(function()
{
	var els=$q.select('.dLabel');	// 'label.dLabel'
	for(var i=0, n=els.length; i<n; i++){
		
			new dLabel({el:els[i]});
	}
},dLabel);

// <@--# endif -->


var dSuggestTiw=$class(dSuggest,{
	editable:true,
	del:false,
	autocomplete_onblur:false,
	_list_shown:false,
	init:function()
	{
		//debugger;
		// this.show_list=this.toggle_list;
		// this.hide_list=this.toggle_list;

		$super(this,arguments);

		var arrow=$q.down(this.target.parentNode,'.arrow_open');
		if(arrow)
			$e.on(arrow,this.toggle_list,this);

		if(this.editable){
			$e.on(this.target,this.show_list_editable,this);
			$e.add(this.target,'focus',this.show_list_editable,this);
		}else
			$e.on(this.target,this.toggle_list,this);
	},
	suggest_delayed:function(e){},
	onError:function(error){},
	filter_data:function(data){ return data; },
	layout:function()
	{
		clearTimeout(this._del_timer);

		if(!this._focused){
			this._del_timer=setTimeout((function(){
				this.hide_list();
			}).bind(this),200);
			return;
		}
	},
	highlight_kbd:function()
	{
		var e=$e.e;
		var code = e.charCode||e.keyCode||e.which||0;

		switch(code){
		case 40:	// down
			this.highlight(this._sel_item+1);
			this.show_list();
			return;
		case 38:	// up
			this.highlight(this._sel_item-1);
			this.show_list();
			return;
		case 13:	// enter
			if(this._list.className)
				return true;
			this.select();
			return;
		}

		this.hide_list();
		return true;
	},
	show_list:function()
	{
		if(this._skipp_once){
			this._skipp_once=false;
			return;
		}
		this._list_shown=true;
		$el.addClassName(this.target.parentNode,'arrow_opened');
		this._list.className='';
		this.target.focus();
	},
	select:function()
	{
		/* var res= */$super(this,arguments);
		this.hide_list();
	},
	hide_list:function()
	{
		this._list_shown=false;
		$el.removeClassName(this.target.parentNode,'arrow_opened');
		this._list.className='hidden';
	},
	toggle_list:function()
	{
		if(this._list_shown){
			$el.removeClassName(this.target.parentNode,'arrow_opened');
			this._list.className='hidden';
		}else{
			$el.addClassName(this.target.parentNode,'arrow_opened');
			this._list.className='';
			this.target.focus();
		}
		this._list_shown=!this._list_shown;
	},
	show_list_editable:function()
	{
		this.toggle_list();
	}
});


var TiwClass={
	//name:'Tiw',
	el:null,
	data:{},
	_wrap:null,
	_form:null,
	_to:null,
	_with:null,
	_submit_bn:null,
	_wrap:null,
	_field_to_label:null,

	init:function(wrap)
	{
		$config(this,vars.Tiw);

		this._wrap=wrap;
		if(!this.el)
			this.el=$q.down(wrap||document.body,'.tiw');

		if(!this.el) return;

		if(!wrap){
			$e.on({
				'.tiw-action-edit':this.edit,
				'.tiw-action-edit-a':this.edit,
				'.tiw-action-cancel':this.cancel_edit,
				'.tiw-riseup-skip':this.skip_riseup,
				'.tiw-riseup-open':this.riseup_open,
				'* .tiw-toggle-curtailed':this.toggle_curtailed,
				'.tiw-the-same':this.the_same
			},this);
		}

		var label=$q.down(this.el,'.field_to_label')
		if(label) this._field_to_label=new dLabel({el:label});

		if($el.hasClassName(this.el,'tiw-edit'))
			this.init_edit();
	},

	init_edit_done:false,
	init_edit:function()
	{
		if(this._field_to_label)	// touch dLabel
			this._field_to_label.show();

		if(this.init_edit_done) return;
		this.init_edit_done=true;

		this._form=$q.down(this.el,'form');

		this.data['tiw-to'].locations['0']=this.data['tiw-to'].own;
		this._to=new dSuggestTiw({
			target:$q.down(this.el,'.tiw-to .dSelect-input'),
			_form:this._form,
			initial_data:this.data['tiw-to'],
			Tiw:this,
			suggest_delayed:function()
			{
				this.Tiw.manage_clear();

				// $super(this,arguments);
			},
			select:function()
			{
				var res=$super(this,arguments);
				if(this._hid.value=='0'){
					this._skipp_once=true;
					this.target.value=$('to_default').value;
				}

				this.Tiw.manage_clear();

				this.hide_list();
				this.target.focus();
			},
			show_list_editable:function()
			{
				if(this.target.value==$('to_default').value)		//FIXME
					this.show_list();
			}
		});

		this._with=new dSuggestTiw({
			target:$q.down(this.el,'.tiw-with .dSelect-input'),
			_form:this._form,
			initial_data:this.data['tiw-with'],
			editable:false
		});

		$e.add(this._form,'submit',this.submit,this);
	},

	state:function(state)
	{
		this.el.className='tiw '+state;
	},
	edit:function(el)
	{
		this.init_edit();

		this.manage_clear();

		this.state('tiw-edit');
	},
	cancel_edit:function(el)
	{
		this._form.reset();
		this.state('tiw-edited');
	},
	skip_riseup:function(el)
	{
		this.state('tiw-edited');
	},
	riseup_open:function(el)
	{
		Riseup.open();
		this.state('tiw-edited');
	},

	toggle_curtailed:function()
	{
		if($el.hasClassName(this.el,'tiw-curtailed')){
			this.state('tiw-edit tiw-edit-not-cancelable');
			this.init_edit();
		}else{
			this.state('tiw-curtailed');
		}
	},
	the_same:function(el)
	{
		el.parentNode.className+=' s';

		if($el.hasClassName(this.el,'tiw-edited-not-mine')){
			new $r(el.rel,{
				params:{ws:1}
			});
		}else{
			this.init_edit();
			this._submit_bn=$q.down(this._form,'.tiw-riseup-show');	//HACK for using common this.loaded()

			new $r(el.rel,{
				params:{ws:1},
				ready:this.loaded,
				error:this.error
			},this);
		}
	},

	submit:function()
	{
		var clear=$el.hasClassName(this._form,'tiw-clear');
		this._submit_bn=$q.down(this._form,clear?'.file_action_clear':'.tiw-riseup-show');

		if(!this.allow_submit())
			return;

		$el.addClassName(this._submit_bn,'disabled');
		$u.startWaiting(this._submit_bn);
		if(this._wrap) return true;

		var url=this._form.action;
		var params=$r.serialize(this._form);
		params.ws=1;

		new $r(url,{
			params:params,
			ready:this.loaded,
			error:this.error
		},this);
	},

	loaded:function(res)
	{
		$u.stopWaiting(this._submit_bn);
		$el.removeClassName(this._submit_bn,'disabled');
		var clear=$el.hasClassName(this._form,'tiw-clear') || !res.edited;

		if(!res.errno){
			if(!this._edited_text)
				this._edited_text=$q.down(this.el,'.tiw-edited-text');

			this._edited_text.innerHTML=res.edited||'';

			if('edited_to' in res)
				this._to.target.value=res.edited_to;
			if('edited_with' in res)
				this._with.external_set(res.edited_with,this.data['tiw-with'].locations[res.edited_with]);

			if(res.riseup){
				if(!this._riseup_text)
					this._riseup_text=$q.down(this.el,'.tiw-riseup-text');
				this._riseup_text.innerHTML=res.riseup;
				this.state('tiw-riseup');
			}else if(clear){
				this.state('tiw-edit tiw-edit-not-cancelable');
			}else{
				this.state('tiw-edited');
			}
		}

		if(clear){
			this._to.target.defaultValue=$('to_default').value;
			this._to._hid.defaultValue='';
			this._with.target.defaultValue=this.data['tiw-with'].locations['1'];
			this._with._hid.defaultValue='1';
			this._form.reset();
			this.manage_clear();
		}else{
			this._to.target.defaultValue=this._to.target.value;
			this._to._hid.defaultValue=this._to._hid.value;
			this._with.target.defaultValue=this._with.target.value;
			this._with._hid.defaultValue=this._with._hid.value;
		}
	},

	error:function()
	{
		$u.stopWaiting(this._submit_bn);
		$el.removeClassName(this._submit_bn,'disabled');
	},

	manage_clear:function()
	{
		var input=this._to.target;
		var def=$('to_default').value;
		var form=this._form;

		if(!input.defaultValue || input.defaultValue==def){
			$el.removeClassName(this._form,'tiw-clear');
		}else{
			if(!input.value){
				$el.addClassName(form,'tiw-clear');
			}else{
				$el.removeClassName(form,'tiw-clear');
			}
		}
	},

	allow_submit:function()
	{
		var to=this._to.target;
		var _with=this._with.target;
		var def=$('to_default').value;
		if($el.hasClassName(this._submit_bn,'disabled')) return false;
		if(_with.value==_with.defaultValue){
			if(to.value==to.defaultValue) return false;
			if(def && to.value.replace(/(^\s+|\s+$)/g,'')==def.replace(/(^\s+|\s+$)/g,'')) return false;
		}
		return true;
	}
};

var Tiw=new ($class(dPage,TiwClass));


/*ShowMore.insert_more=function(more)
{
	if(ShowMore.to_remove) Element.remove(ShowMore.to_remove);

	new Insertion.Bottom($('entries'), more);
	ShowMore.preload_more();
};*/

ProfileView={
	name:'ProfileView',
	profile:null,
	init:function() {
		this.profile=$('profile_section');

		new Tooltip($('write_disabled'), { maxWidth: 350 });

		var more_people=$('container_more_people');
		if(more_people)
		this.more_people=new dTooltip({
			el:more_people,
			type:'people_tooltip',
			target:'tooltip_target',
			format:function(el)
			{
				var html=$u.tpl('<a href="{url}" class="name {online}"><i>{name}</i><b class="{riseup}"></b></a>\
					<small>{info}</small><span>{msg}</span>',{
					name:el.rel,
					url:el.href,
					online:el.className.split(' ')[1],
					riseup:el.className.split(' ')[2],
					info:el.rev
					});

				var tl=el.cumulativeOffset();
				return {
					html:html,
					left:tl.left+8,
					top:tl.top+el.offsetHeight-18
				};
			}
		});

		$e.on({
			'show_info_profile':this.toggle_info,
			'hide_info_profile':this.toggle_info
		},this);
	},

	toggle_info:function()
	{
		this.profile && this.profile.toggleClassName('enabled');
	}
};

ProfileView=new ($class(dPage,ProfileView));
