chatwnd = null;
function openChat(login, width, height){
	if(width == null)
		width = 810;
	if(height == null)
		height = 610;

	if (!isSuxx())
	{
		chatwnd = window.open('http://' + getShortDomain(document.location.host) + '/chat/#' + login, 'chatwindow', 'location=1,status=1,scrollbars=1,menubar=0,resizable=1,width=' + width + ',height=' + height);
		chatwnd.focus();
	}
	else
	{
		if (!chatwnd)
		{
			chatwnd = window.open('http://' + getShortDomain(document.location.host) + '/chat/#' + login, 'chatwindow', 'location=1,status=1,scrollbars=1,menubar=0,resizable=1,width=' + width + ',height=' + height);
			chatwnd.focus();
		}

		else
		{
			chatwnd.document.location.hash = '#' + login;
			chatwnd.focus();
		}
	}

	return false;
}

var preloaded_img = Object();
function preload_img(path)
{
	if (typeof(preloaded_img[path]) == 'undefined')
	{
		preloaded_img[path] = new Image();
		preloaded_img[path].src = path;
	}
}

function openChat2(login, width, height){
	if(width == null)
		width = 810;
	if(height == null)
		height = 610;

	if (!isSuxx())
	{
		chatwnd = window.open('http://' + getShortDomain(document.location.host) + '/chat2/#' + login, 'chat2window', 'location=1,status=1,scrollbars=1,menubar=0,resizable=1,width=' + width + ',height=' + height);
		chatwnd.focus();
	}
	else
	{
		if (!chatwnd)
		{
			chatwnd = window.open('http://' + getShortDomain(document.location.host) + '/chat2/#' + login, 'chat2window', 'location=1,status=1,scrollbars=1,menubar=0,resizable=1,width=' + width + ',height=' + height);
			chatwnd.focus();
		}

		else
		{
			chatwnd.document.location.hash = '#' + login;
			chatwnd.focus();
		}
	}

	return false;
}

function openLiteChat(login, width, height)
{
	if (!width)
		width = 890;
	if (!height)
		height = 580;

	chatwnd = window.open('/chat_lite/?chat='+login, 'litechatwindow' , 'location=1,status=1,scrollbars=1,menubar=0,resizable=1,width='+width+',height='+height);

	chatwnd.focus();

	return false;
}

function ajaxRequest(url, options)
{
	if (!options.onFailure)
		options.onFailure = function(e)
		{
			Alarm(e.responseText);
		};

	new Ajax.Request(url, options);
	return false;
}

function ajaxRequestReload(url, parameters)
{
	ajaxRequest(url, {
		method: 'post',
		parameters: parameters,
		onSuccess: function(transport)
		{
			window.location = window.location;
		}
	});
	return false;
}

function ajaxFormSend(formID, url, method){
	if(method == null)
		method = 'post';
	else
		method = 'get';

	ajaxRequest(url, {
		parameters: $(formID).serialize(true),
		onSuccess: function(t){
			window.location = window.location;
		},
		onFailure: function(t){
			Alarm(t.responseText);
		}
	});
	return false;
}

function ajaxConfirmRequest(url, parameters, method, textConfirm, textError, reloadWhenSuccess, callback){
	if(method == null)
		method = 'post';


	if ((textConfirm == null) || confirm(textConfirm))
	{
		new Ajax.Request(url,{
			parameters: parameters,
			onSuccess: function(t)
			{
				if(callback)
					callback();
				else if ((reloadWhenSuccess == undefined) || (reloadWhenSuccess))
				{
					window.location = 'http://'+window.location.host+window.location.pathname+window.location.search;
				}
			},
			onFailure: function(t){
				Alarm(t.responseText);
			}
		});
	}
	return false;
}

function chCountry(_el, sel_regions, allow_empty)
{
	var el = ((typeof _el) == 'string')? $(_el) : _el;
	var el_sel_regions = $(sel_regions);
	el_sel_regions.disabled = true;
	el_sel_regions.innerHTML = '';

	new Ajax.Updater(sel_regions, '/g/?action=g_load_regions', {
		parameters:
		{
			country_id: el.value,
			allow_empty: (allow_empty != undefined)? allow_empty : true,
			optgroups: Prototype.Browser.Opera? 'false' : 'true'
		},
		onComplete: function(t)
		{
			if (el_sel_regions.placeChanged)
				el_sel_regions.placeChanged();
		},
		onSuccess: function(t)
		{
			el_sel_regions.disabled = false;
		}
	}
	);
}

function chRegion(_el, sel_citys, allow_empty)
{
	var el = ((typeof _el) == 'string')? $(_el) : _el;
	var el_sel_citys = $(sel_citys);

	el_sel_citys.disabled = true;
	el_sel_citys.innerHTML = '';

	new Ajax.Updater(sel_citys, '/g/?action=g_load_citys', {
		parameters:
		{
			region_id: el.value,
			allow_empty: (allow_empty != undefined)? allow_empty : true,
			optgroups: Prototype.Browser.Opera? 'false' : 'true'
		},
		onComplete: function(t)
		{
			if (el_sel_citys.placeChanged)
				el_sel_citys.placeChanged();
		},
		onSuccess: function(t)
		{
			el_sel_citys.disabled = false;
		}
	}
	);
}

function chCity(_el, sel_metros, allow_empty, completeCallback)
{
	var el = ((typeof _el) == 'string')? $(_el) : _el;
	var el_sel_metros = $(sel_metros);
	
	if (!el_sel_metros)
		return;
	
	el_sel_metros.hide();
	el_sel_metros.disabled = true;
	el_sel_metros.update('');

	new Ajax.Updater(sel_metros, '/g/?action=g_load_metros',
	{
		parameters:
		{
			city_id: el.value,
			allow_empty: true,
			empty_text: 'Не важно',
			optgroups: Prototype.Browser.Opera? 'false' : 'true'
		},
		onSuccess: function(t)
		{
			el_sel_metros.disabled = false;
			if (t.responseText != '')
				el_sel_metros.show();
				
			if (!Object.isUndefined(completeCallback) && completeCallback)
				completeCallback();
		}
	});
}

function ObservePlace(id_country, id_region, id_city, id_metro, allow_empty, completeCallback, changeCallback)
{
	// native events
	Event.observe($(id_country), 'change', function()
	{
		chCountry(id_country, id_region, allow_empty);
		$(id_region).update('');
		$(id_city).update('');
		if (id_metro && $(id_metro))
			$(id_metro).update('');
			
		/*if (!Object.isUndefined(changeCallback) && changeCallback)
			changeCallback(id_country, id_region, id_city, id_metro);*/
	});
	Event.observe($(id_region), 'change', function()
	{
		chRegion(id_region, id_city, allow_empty);
		$(id_city).update('');
		if (id_metro && $(id_metro))
			$(id_metro).update('');
		
		/*if (!Object.isUndefined(changeCallback) && changeCallback)
			changeCallback(id_country, id_region, id_city, id_metro);*/
	});
	Event.observe($(id_city), 'change', function()
	{
		chCity(id_city, id_metro, allow_empty, function()
		{
			if (!Object.isUndefined(completeCallback) && completeCallback)
				completeCallback(id_country, id_region, id_city, id_metro);
		});
	});

	// мы меняем аяксом подгружая новые
	$(id_region).placeChanged = function()
	{
		chRegion(id_region, id_city, allow_empty);
		$(id_city).update('');
		if (id_metro && $(id_metro))
			$(id_metro).update('');
	};
	$(id_city).placeChanged = function()
	{
		chCity(id_city, id_metro, allow_empty, function()
		{
			if (!Object.isUndefined(completeCallback) && completeCallback)
				completeCallback(id_country, id_region, id_city, id_metro);
		});
	};
	
	if (!Object.isUndefined(completeCallback) && completeCallback)
	{
		// вызываем чтобы убрать метро там где его нет
		chCity(id_city, id_metro, allow_empty, function()
		{
			if (!Object.isUndefined(completeCallback) && completeCallback)
				completeCallback(id_country, id_region, id_city, id_metro);
		});
	}
}

function qsearch_select(allow_empty, el_city, el_region, el_country, city_id, region_id, country_id, city_name, region_name)
{
	var current_country = $F(el_country);
	var current_region  = $F(el_region);
	var current_city	= $F(el_city);

	$(el_country).value = country_id;

	if (current_country != country_id)
	{
		$(el_region).innerHTML = "<option value='" + region_id + "'>" + region_name + "</option>";
		new Ajax.Updater(el_region, '/g/?action=g_load_regions', {
			parameters:
			{
				country_id: country_id,
				allow_empty: (allow_empty != undefined) ? allow_empty : true,
				optgroups: Prototype.Browser.Opera ? 'false' : 'true'
			},
			onComplete: function(t)
			{
				$(el_region).value = region_id;
			}
		});
	}
	else
		$(el_region).value = region_id;


	if (current_region != region_id)
	{
		$(el_city).innerHTML = "<option value='"+city_id+"'>"+city_name+"</option>";
		new Ajax.Updater(el_city, '/g/?action=g_load_citys', {
			parameters:
			{
				region_id: region_id,
				allow_empty: (allow_empty != undefined)? allow_empty : true,
				optgroups: Prototype.Browser.Opera? 'false' : 'true'
			},
			onComplete: function(t)
			{
				$(el_city).value = city_id;
			}
		});
	}
	else
		$(el_city).value = city_id;

}

function qsearch_city(city_id, region_id, country_id, city_name, region_name)
{
	qsearch_select(true, 'sf_place_city', 'regions_list', 'sf_place_country', city_id, region_id, country_id, city_name, region_name);
}

function setCookie (name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset);
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function g_open_tab(tab_name, tab_names, tab_prefix, header_prefix, class_active, class_unactive, obj)
{
	if(obj != null) {
		var o = $(obj).up('.blockp');
	}
	else {
		var o = $$('body')[0];
	}
	tab_names.each(function(i) {
		if(o.select(tab_prefix+i).length > 0){
			if ((tab_name != i) && (o.select(tab_prefix+i)[0].style['display'] != 'none'))
				o.select(tab_prefix+i)[0].hide();
			o.select(header_prefix+i)[0].removeClassName(class_active);
			o.select(header_prefix+i)[0].addClassName(class_unactive);
		}
	});


	o.select(header_prefix+tab_name)[0].removeClassName(class_unactive);
	o.select(header_prefix+tab_name)[0].addClassName(class_active);
	o.select(tab_prefix+tab_name)[0].show();

}
function open_tab(tab_name, obj)
{
	return g_open_tab(tab_name, ['sms', 'cash', 'opsos'], '.pay-via-tab-', '.pay-via-tab-header-', 'name_a', 'name', obj);
}

function alert_deleted(login)
{
	Alarm('Этот пользователь был удалён!');
}

function ctrlEnter(event){
	return (event.keyCode==10 || (event.ctrlKey && event.keyCode==13));
}

function isEnter(event)
{
	return (event.keyCode==10 || (event.keyCode==13));
}

function escKey(event)
{
	var kC  = (window.event) ?	// MSIE or Firefox?
	event.keyCode : event.keyCode;
	var Esc = (window.event) ?
	27 : event.DOM_VK_ESCAPE // MSIE : Firefox

	return (kC == Esc);
}

/**
 * Dump
 * @param {Object} d
 */
function dd(d)
{
	var s = '';
	for (k in d)
		if (d.hasOwnProperty && d.hasOwnProperty(k))
		{
			if (typeof(d[k]) == 'string')
				s += k+': "'+d[k] + '", \n';
			else if (typeof(d[k]) == 'object')
				s += k+': ' + d[k] + ' {'+dd(d[k]) + '}, \n';
			else
				s += k+': ' + d[k] + ', \n';
		}
	return s;
}


function getStackTrace() {
	var callstack = [];
	var isCallstackPopulated = false;
	try
	{
		i.dont.exist+=0; //does not exist - that's the point
	}
	catch(e)
	{
		if (e.stack) { //Firefox
			var lines = e.stack.split("\n");
			for (var i = 0, len = lines.length; i < len; i++) {
				if ( lines[i].match( /^\s*[A-Za-z0-9\-_\$]+\(/ ) ) {
					callstack.push(lines[i]);
				}
				else
					callstack.push(lines[i]);
			}
			//Remove call to printStackTrace()
			callstack.shift();
			isCallstackPopulated = true;
		}
		else if (window.opera && e.message) { //Opera
			var lines = e.message.split("\n");
			for (var i = 0, len = lines.length; i < len; i++) {
				if ( lines[i].match( /^\s*[A-Za-z0-9\-_\$]+\(/ ) ) {
					var entry = lines[i];
					//Append next line also since it has the file info
					if (lines[i+1]) {
						entry += " at " + lines[i+1];
						i++;
					}
					callstack.push(entry);
				}
			}
			//Remove call to printStackTrace()
			callstack.shift();
			isCallstackPopulated = true;
		}
	}
	if (!isCallstackPopulated)//IE and Safari
	{
		var currentFunction = arguments.callee.caller;
		while (currentFunction) {
			var fn = currentFunction.toString();
			//If we can't get the function name set to "anonymous"
			var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf("(")) || fn;

			var args = currentFunction.arguments.length + ' args (';
			for (var i=0; i<currentFunction.arguments.length; i++)
				args += ((i > 0)? ', ' : '') + i + '(' + typeof(currentFunction.arguments[i]) + ')' + '=' + currentFunction.arguments[i] + ' ';
			args += ')';

			callstack.push(fname + ' ' + args);

			currentFunction = currentFunction.caller;
		}
	}
	return callstack;
}

var logAnyError = false;

function handleError(err, url, line)
{
	var currentLocation = '' + document.location;
	var needLog = logAnyError;
	if (!logAnyError)
	{
		needLog = false;
	}

	if (!needLog)
		return false;

	var callstack = getStackTrace();
	if (Ajax && Ajax.Request)
	{	// Ура! У нас есть Prototype! :)
		//printStackTrace();

		new Ajax.Request('/err/?action=add',
		{
			//requestHeaders: {'Referer': document.location},
			parameters:
			{
				error: err,
				url: url,
				line: line,
				stacklines: callstack.length,
				callstack: callstack.join("\n--==##NEXT_FUNCTION##==--\n")
			},
			onSuccess: function(transport)
			{
			//var json = transport.responseText.evalJSON();
			}
		});
	}
	else
	{	// Фак! Какой-то недобраузер, там даже Prototype не работает
		var script = document.createElement('script');
		script.setAttribute('type', 'text/javascript');
		script.setAttribute('src', '/err/?line='+encodeURIComponent(line)+'&url=' + encodeURIComponent(url) + '&err=' + encodeURIComponent(err));
		document.getElementsByTagName('head')[0].appendChild(script);
	}

	return true; // error is handled
}

window.defaultOnError = window.onerror; // store default handler
window.onerror = handleError; // assign own handler
//window.onerror = window.defaultOnError; // восстановление стандартного обработчика ошибок


function check_length(obj, max)
{
	if($F(obj).length > max)
		$(obj).value = $(obj).value.truncate(max, '');
}

var prev_className = null;

function _user_rotate_photos_next(el, key)
{
	if (el['runing'])
		return;

	el['runing'] = true;
	var photos = document['photos_cache'][key];
	if (photos && photos.length > 1)
	{
		new Effect.Fade(el,
		{
			duration: 0.5,
			from: 1.0,
			to: 0.01,
			queue: {
				position: 'end',
				scope: 'rotator' + key
				},
			afterFinish: function ()
			{
				el.src = photos[el['rotator_position']]['src'];
				el.removeClassName(prev_className);
				if(photos[el['rotator_position']].addClass) {
					prev_className = photos[el['rotator_position']].addClass;
					el.addClassName(photos[el['rotator_position']].addClass);
				}
				if (el['a_el'])
				{
					var a_el = $(el['a_el']);
					if (a_el)
						a_el.href = '/' + el['login'] + '/photos/photo-' + photos[el['rotator_position']]['photo_id'];
				}


				el['rotator_position'] = (el['rotator_position'] == photos.length - 1)? 0 : el['rotator_position'] + 1;
			}
		});

		new Effect.Fade(el,
		{
			duration: 0.5,
			from: 0.01,
			to: 1.0,
			queue: {
				position: 'end',
				scope: 'rotator' + key
				}
		});
	}
	el['runing'] = false;
}

function user_rotate_photos(el, login, size, a_el, place)
{
	var key = login + '-' + size;
	if (!document['photos_cache'])
		document['photos_cache'] = {};

	if (!el['rotator_position'])
		el['rotator_position'] = 0;

	el['login'] = login;
	el['a_el'] = a_el;

	if (!el['rotator'])
	{
		_user_rotate_photos_next(el, key);
		el['rotator'] = new PeriodicalExecuter(function()
		{
			_user_rotate_photos_next(el, key);
		}, 2);
	}

	Event.observe(el, 'mouseout', function(event)
	{
		if (el['downloader'])
		{
			clearTimeout(el['downloader']);
			el['downloader'] = null;
		}
		
		if (el['rotator'])
		{
			el['rotator'].stop();
			el['rotator'] = null;
		}
	});

	if (document['photos_cache'][key])
		return;
		
	el['downloader'] = setTimeout(function()
	{
		new Ajax.Request('/g/?action=g_user_photos&place=' + place, {
			parameters: {
				login: login,
				size: size
			},
			onSuccess: function (transport)
			{
				el['downloader'] = null;
				var photos = transport.responseText.evalJSON();
				var pk_curr = null;
				for (pk in photos)
				{
					photos[pk]['sort'] = parseInt(photos[pk]['photo_id']);
	
					var src = '' + photos[pk]['src'];
					if (src.lastIndexOf('images') > 0)
						photos[pk]['sort'] -= 10000000;
	
					if (src == el.src)
						photos[pk]['sort'] -= 20000000;
				}
				photos.sort(function(a, b){
					return b['sort'] - a['sort']
					});
	
				document['photos_cache'][key] = photos;
	
				for (pk in photos)
					if (photos.hasOwnProperty && photos.hasOwnProperty(pk))
					{
						var photo = photos[pk];
						var pic = new Image();
						if(typeof(photo.src) == 'object') {
							photo.addClass = 'nophoto_' + size + '_' + photo.src.sex;
							if(photo.src.intim) {
								photo.addClass += '_intim';
							}
							photo.src = '/images/blank.gif';
						}
	
						pic.src = photo['src'];
					}
	
				// если ссылка не меняется, то можно начинать крутить сразу
				if (!a_el)
					_user_rotate_photos_next(el, key);
			},
			onFailure: function (transport)
			{
				el['downloader'] = null;
			//alert(transport.responseText);
			}
		});
	}, 100);

	
}
function isMegaSuxx() {
	return (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
}

function isSuxx() {
	return (navigator.userAgent.toLowerCase().indexOf("msie 6") != -1);
}
function isSuxx7() {
	return (navigator.userAgent.toLowerCase().indexOf("msie 7") != -1);
}
function isSuxx8() {
	return (navigator.userAgent.toLowerCase().indexOf("msie 8") != -1);
}
function isSuxx9() {
	return (navigator.userAgent.toLowerCase().indexOf("msie 9") != -1);
}

function isSuxx67()
{
	return (navigator.userAgent.toLowerCase().indexOf("msie 6") != -1) || (navigator.userAgent.toLowerCase().indexOf("msie 7") != -1);
}

var current_loc;
try{
current_loc = document.location.hash; //IE7 ACCESS DENIED
}
catch(e){
	hash = '';
}

function checkLocation()
{
	var hash;
	try{
	hash = document.location.hash;
	}
	catch(e){
		hash = '';
	}
	if (hash != current_loc)
	{
		current_loc = hash;
		$($$('body')[0]).fire("location:anchor");
	}
}

function num(value, txt0, txt1, txt2)
{
	var last_dig = value % 10;

	if ((value > 10) && (value < 20))
		return txt0;

	switch (last_dig)
	{
		case 0:
			return txt0;

		case 1:
			return txt1;

		case 2:
		case 3:
		case 4:
			return txt2;

		case 5:
		case 6:
		case 7:
		case 8:
		case 9:
			return txt0;
	}
}

function getShortDomain(domain)
{
	if (domain == undefined)
		domain = document.domain;

	if (domain.indexOf('www.') == 0)
		domain = domain.substr(4, domain.length - 4);

	return domain;
}
function pay_window(pay, html) {
	pay_close();
	if(!$('pay_bg')) {
		var bg = new Element('div', {
			'id': 'pay_bg'
		});
		$($$('body')[0]).insert(bg);
	}

	var _pay = new Element('div', {
		'id': 'pay'
	});
	_pay.addClassName('pay_'+pay);

	var _pay_content = new Element('div', {
		'id': 'pay_content'
	});
	_pay.insert(new Element('a', {
		'href': '#pay',
		'id': 'pay_close'
	}).observe('click', pay_close));
	_pay.insert(_pay_content);
	$$('body')[0].insert(_pay);
    
    var w = document.viewport.getDimensions();
    
    if(window.top != window.self) {
        var top = mouseXY.y-parseInt($('pay').getHeight()/2);
    }
    else {
        var s = document.viewport.getScrollOffsets();
        var top = s.top+parseInt((w.height-$('pay').getHeight())/2);
    }
    if(top < 10) {
        top = 10;
    }
    
    
	$('pay').setStyle({
		marginLeft: '-' + parseInt(($('pay').getWidth()+18)/2)+'px',
		//marginTop: '-' + parseInt(($('pay').getHeight()+18)/2)+'px',
        top: top+'px'
		});
    
	_pay_content.update(html);
}

function pay(pay, data, params) {
	if(executer_pay_check) {
		executer_pay_check.stop();
	}
	if(!data) {
		var data = {};
	}
	if(!$('pay')) {
		var bg = new Element('div', {
			'id': 'pay_bg'
		});
		$($$('body')[0]).insert(bg);

	}
	var pay_load = new Element('div', {'id': 'pay_load', 'class': 'radius12'});
	$($$('body')[0]).insert(pay_load);
	data.pay = pay;
	data.ref = window.location.href;

	new Ajax.Request('/pay/', {
		parameters: data,
		evalJS: true,
		onSuccess: function(t) {
			$('pay_load').remove();
			pay_window(pay, t.responseText);
		},
		onFailure: function(t) {
			if(t.status == 401) {
				window.location = '/registration/';
			}
			else {
				$('pay_load').remove();
				Alarm(t.responseText);
			}
		}
	});
}

function pay_close(e) {
	if($('pay')) {
		$('pay_bg').remove();
		$('pay').remove();
	}
}

function pay_photo_change(id, callback) {
	$('pay_photo_'+id).up().select('.sel').each(function(i) {
		$(i).removeClassName('sel')
	});
	$('pay_photo_'+id).addClassName('sel');
	$('photo_id').setValue(id);
	if(callback) {
		callback($('pay_photo_'+id).readAttribute('src'));
	}
}


function pay_show_rules(title) {
	var div = new Element('div');
	div.update($('rules_').innerHTML);
	Win(title, div, 'rules_win');
}

function change_top_region() {
	new Ajax.Request('/top/?action=region', {
		onComplete: function(t) {
			Win('Выбор региона', t.responseText);
		}
	});
}
function change_top_region_(f) {
	var data = $(f).serialize(true);
	var loc = '?country=' + data.country + '&region=' + data.region;
	if (go(loc, 'top_page'))
		window.location = loc;
	else
	{
		$('top_region_link').href = loc;
		var text = data.country_name;
		if (data.region_name != '')
			text += ', ' + data.region_name;
		$('top_region_link').update(text);
		Win.close();
	}
}

Object.extend(String.prototype, (function() {
	function toDom() {
		var n = new Element('div').insert(this);
		return $(n).childElements()[0];
	}
	return {
		toDom: toDom
	}
})());


function form_notify_(form, field, text, type) {
	if(!field) {
		return ;
	}
	if(typeof field != 'object') {
		field = $(form[field]);
	}
	try {
		var f = $(field).up('dd').select('.error')[0];
	}
	catch(e) { }

	if(!f) {
		var f = new Element('span').addClassName('error').addClassName('radius3').setStyle({
			'visibility': 'hidden'
		});
		//field.up('dd').insert(f);
		field.insert({after: f});
	}
	if(!text) {
		f.setStyle({
			visibility: 'hidden'
		});
		return ;
	}
	if(type == 'error') {
		f.removeClassName('notify');
		f.update(text);
		f.setStyle({
			visibility: 'visible'
		});
		return ;
	}

	if(type == 'notify') {
		f.addClassName('notify');
		f.update(text);
		f.setStyle({
			visibility: 'visible'
		});
		return ;
	}
}

function form_notify(form, data) {
	$(form).select('.error').each(function(i) {
		$(i).setStyle({
			visibility: 'hidden'
		});
	});
	if(data.error) {
		$H(data.error).each(function(i) {
			form_notify_(form, i.key, i.value, 'error');
		});
	}
	if(data.notify) {
		$H(data.notify).each(function(i) {
			form_notify_(form, i.key, i.value, 'notify');
		});
	}
}

var lat=new Array("jo","zh","i","ch","sh","xh","je","ju","ja","a","b","v","g","d","e","z","i","k","l","m","n","o","p","r","s","t","u","f","x","c","","y","","j","h", '-', '-', '-', '-', '-', '-', '-', '-');
var cyr=new Array("ё","ж","й","ч","ш","щ","э","ю","я","а","б","в","г","д","е","з","и","к","л","м","н","о","п","р","с","т","у","ф","х","ц","ь","ы","ъ","ж","х", ' ', ',', '(', ')', '?', ':', '.', '--');

var latcap=new Array("JO","Jo","ZH","Zh","I","Ch","CH","Sh","SH","Xh","XH","Je","JE","Ju","JU","Ja","JA","A","B","V","G","D","E","Z","I","K","L","M","N","O","P","R","S","T","U","F","X","C","Y","J","H", '-', '-', '-', '-', '-', '-', '-', '-');
var cyrcap=new Array("Ё","Ё","Ж","Ж","Й","Ч","Ч","Ш","Ш","Щ","Щ","Э","Э","Ю","Ю","Я","Я","А","Б","В","Г","Д","Е","З","И","К","Л","М","Н","О","П","Р","С","Т","У","Ф","Х","Ц","Ы","Ж","Х", ' ', ',', '(', ')', ':', '?', '.', '--');

function translate(tex)
{
	var buf=tex;
	var i;
	for (i=0;i<cyrcap.length;i++)
	{
		buf=replace(buf,cyrcap[i],latcap[i],1,0);
	}

	for (i=0;i<cyr.length;i++)
	{
		buf=replace(buf,cyr[i],lat[i],1,0);
	}

	tex=buf;
	return tex;
}

function replace(target,oldTerm,newTerm,caseSens,wordOnly) {
	var work = target;
	var ind = 0;
	var next = 0;

	if (!caseSens) {
		oldTerm = oldTerm.toLowerCase();
		work = target.toLowerCase();
	}

	while ((ind = work.indexOf(oldTerm,next)) >= 0) {
		if (wordOnly) {
			var before = ind - 1;
			var after = ind + oldTerm.length;
			if (!(space(work.charAt(before)) && space(work.charAt(after)))) {
				next = ind + oldTerm.length;
				continue;
			}
		}
		target = target.substring(0,ind) + newTerm +
		target.substring(ind+oldTerm.length,target.length);
		work = work.substring(0,ind) + newTerm +
		work.substring(ind+oldTerm.length,work.length);
		next = ind + newTerm.length;
		if (next >= work.length) {
			break;
		}
	}
	return target;
}

function photo_set_num(num, obj) {
	$($(obj).up().select('.active')[0]).removeClassName('active');
	$(obj).addClassName('active');
	$($(obj).up('form').photo_num).setValue(num);
	$$('.you_photo').each(function(i) {
		$(i).up('li').remove();
	});
	for(var i = 0; i < num; i++) {
		var li = new Element('li').update('<img src="/images/blank.gif" alt="" class="you_photo" />');
		$($($$('.current_gallery')[0]).select('li')[0]).insert({
			before: li
		});
	}
	var path = $('pay_photo_'+$F('photo_id')).readAttribute('src');
	$$('.you_photo').each(function(i) {
		$(i).writeAttribute('src', path);
	});
}

function pr_set_num(num, obj) {
	$($(obj).up().select('.active')[0]).removeClassName('active');
	$(obj).addClassName('active');
	$($(obj).up('form').pr_num).setValue(num);
}

function rate_set_num(num, obj) {
	$(obj).up().select('.active')[0].removeClassName('active');
	$(obj).addClassName('active');
	$($(obj).up('form').rate_num).setValue(num);
}
var executer_pay_check = null;
function pay_info_periodical_check(prefix, suffix, number, success, callback)
{
	var processed = false;
	var counter = 0;
	executer_pay_check = new PeriodicalExecuter(function()
	{
		++counter;
		if($$('.sms_success').length > 0) {
			return false;
		}

		if (counter > 30)
			executer.stop();

		if (processed)
			return;

		//$('pay-info-sms-wait').show();

		processed = true;
		new Ajax.Request('/g/?action=g_sms_state', {
			parameters: {
				prefix: prefix,
				suffix: suffix,
				number: number
			},
			onSuccess: function(t)
			{
				if(t.responseText == 'ok') {
					$$('.sms_code').each(function(i) {
						$(i).hide();
						var win_close = new Element('a', {'href': '#pay', 'class': 'pay_win_close'});
						win_close.observe('click', function(e) {
							pay_close();
						});
						var s = new Element('div', {'class': 'sms_success radius6'}).insert(win_close).insert(success);
						$(i).insert({'before': s});
					});

					if(callback)
						callback();
					executer_pay_check.stop();
				}
			},
			onFailed: function()
			{
			//$('')
			},
			onComplete: function()
			{
				processed = false;
			}
		});
	}, 10);
}

function show_pay_info(type, obj) {
	var pay_ = $(obj).up('.pay_info');
	pay_.select('.pay_sms, .pay_cash, .pay_opsos').each(function(i) {
		$(i).hide();
	});
	pay_.select('.pay_'+type).each(function(i) {
		$(i).show();
	});

	pay_.select('.pay_tabs a.active').each(function(i) {
		$(i).removeClassName('active');
	});
	pay_.select('.pay_tab_'+type).each(function(i) {
		$(i).addClassName('active');
	});
}

var pay_message_update_int = null;
function pay_message_update() {
	try {
		clearInterval(pay_message_update_int);
	}
	catch (e) {  }
	pay_message_update_int = setTimeout(pay_message_update_, 500);
	try {
		executer_pay_check.stop();
	}
	catch(e) { }
}

function pay_message_update_() {

	var data = $('message_').serialize(true);
	data.pay = 'message_pay';
	new Ajax.Request('/pay/', {
		parameters: data,
		onComplete: function(t) {
			//var d = t.responseText.evalJSON();
			$('message_sms').update(t.responseText);
		}
	});
}

function pay_message_limit(obj) {
	if($F(obj).length > 300) {
		$(obj).setValue($F(obj).truncate(300, ''));
	}
	$('message_limit').update(300-$F(obj).length);
}



function set_vip_style(i) {

	$('save_vip_design').show();
	$('vip_design_saved').hide();
    $('userstyle').href = '/g/?action=g_vip_style&design='+vip_designs[i].design_id;

	vip_user_design_id = vip_designs[i].design_id;
}

function user_design_save(b) {
	$('save_vip_design').hide();
	$('vip_design_save_').show();
	new Ajax.Request('/g/?action=g_design_save', {
		parameters: {design: vip_user_design_id},
		onComplete: function(t) {
			$('vip_design_save_').hide();
			$('vip_design_saved').show();
		}

	});
}

function design_preview_(i, cnt_) {

	return '<a href="#" style="background-image: url(/m/'+i.path+');" onclick="set_vip_style('+cnt_+');return false;"></a>';
}

function design_shuffle(o){
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

function more_designs() {

	$('vip_designs_').update('');

	vip_designs = design_shuffle(vip_designs);

	for(var i = 0; i < 3; i++) {
		$('vip_designs_').insert(design_preview_(vip_designs[i], i));
	}
	vip_cnt_ = i;
}

function addJSFile(url)
{
	var script = document.createElement('script');
	
	script.setAttribute('type', 'text/javascript' );
	script.setAttribute('src', url);
	
	document.getElementsByTagName('head')[0].appendChild(script);
}

function checkMuid()
{
	if (Prototype.Browser.IE)
		return;
	
	addJSFile('/js/evercookie.js');
	
	muidChecker = setInterval(function()
	{
		if (typeof evercookie == 'undefined')
			return;
			
		if (muidChecker)
		{
			clearInterval(muidChecker);
			muidChecker = null;
		}
		
		setTimeout(function()
		{
			try
			{
				realCookie = getCookie('muid');
				
				var ec = new evercookie();
				ec.get("muid", function(value)
				{
					try
					{
						if ((value == null) || (value == 'null'))
							ec.set("muid", realCookie);
						else if (realCookie != value)
						{
							new Ajax.Request('/g/?action=g_muid_wrong',
							{
								parameters: {evercookie_muid: value, realcookie_muid: realCookie}
							});
						}
					}
					catch(e)
					{
						// fucking IE
					}
				});
			}
			catch(e)
			{
				// fucking IE
			}
			
		}, 10);
		
	}, 100);
}

url_spy_add('^pay/golden/([A-Za-z0-9_-]+)$', function(e) {
	pay('golden_up', {login: e[1]});
});
url_spy_add('^pay/super-bonus$', function(e) {
	pay('super_bonus');
});
url_spy_add('^pay/([a-z0-9A-Z_]+)$', function(e) {
	pay(e[1]);
});
url_spy_add('^pay/message/([a-z0-9A-Z_-]+)$', function(e) {
	pay('message', {login: e[1]});
});
url_spy_add('^pay/confirm/([0-9]+)$', function(e) {
	pay('confirm', {amount: e[1]});
});
url_spy_add('^pay/super/([0-9]+)$', function(e) {
	pay('super', {days: e[1]});
});


url_spy_add('^pay/pr/diary/([0-9]+)$', function(e) {
	pay('pr', {'type': 'diary', 'target': e[1]});
});
url_spy_add('^pay/pr/group/([a-z0-9_-]+)$', function(e) {
	pay('pr', {'type': 'group', 'target': e[1]});
});

var loc = document.location.href;
loc = loc.replace(/#.*$/g, '');
var current_location = loc;
if (typeof(history.pushState) != 'undefined')
{
		window.onpopstate = function(event)
		{
			loc = document.location.href;
			loc = loc.replace(/#.*$/g, '');
			if (typeof(event.state) != 'undefined' && event.state != null && typeof(event.state.is_ajax) != 'undefined' && event.state.is_ajax)
			{
				var id = $(event.state.id);
				if (id != undefined)
				{
					$(event.state.id).update(event.state.data);
					current_location = loc;
				}
				else
					document.location.reload(true);
			}
			else if (current_location != loc)
				document.location.reload(true);

		};
}


function go(uri, id, callback)
{
	var el = $(id);
	var res = true;
	if (el != undefined)
	{
		$(id).insert('<div id="_'+id+'_load">Загрузка...</div>');

		if (typeof(history.pushState) != 'undefined')
		{
			uri = uri.replace('http://'+getShortDomain(document.domain),'');
			if ((((typeof(event) == 'undefined') || typeof(event.shiftKey) == 'undefined' || event.shiftKey == false)) && (((typeof(event) == 'undefined') || typeof(event.altKey) == 'undefined' || event.altKey == false)) && (((typeof(event) == 'undefined') || typeof(event.ctrlKey) == 'undefined' || event.ctrlKey == false)))
			{
				res = false;

				var result = null;
				new Ajax.Request(uri,
				{
					method: 'get',
					parameters: {action:'get-page'},
					onComplete: function(t)
					{
						if (t.responseText.isJSON())
						{
							result = t.responseText.evalJSON();

							if (result['result'] == 'Success')
							{
								if (typeof(history.pushState) != 'undefined')
								{
									history.pushState({is_ajax:true, id:id, data:result['data']}, result['title'], uri);
									$(id).update(result['data']);
									loc = document.location.href;
									loc = loc.replace(/#.*$/g, '');
									current_location = loc;
									if ((typeof(callback) != 'undefined') && (callback != null))
										callback();
								}
								else
									document.location.reload(true);
							}
							else
								document.location.reload(true);
						}
					}
				});
			}
		}
	}
	return res;
}
function getPosition(obj)
{
	if (!obj || obj == undefined) return;
	var left = 0, top = 0;
	if (obj.offsetParent)
	{
		do
		{
			left += obj.offsetLeft;
			top += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [left,top];
}
var last_scroll_effect = null;
function paginate_scroll_to_begin(id)
{
	try
	{
		if (last_scroll_effect != null)
			last_scroll_effect.cancel();
	}catch(e){}
	var scrollTo;
	try	{
		var pos = getPosition($(id));
		scrollTo = pos[1];
	}
	catch(e) {
		scrollTo = 0;
	}

	last_scroll_effect = new Effect.Tween(null, window.pageYOffset, scrollTo,
	{ duration: 0.2 },
	function(p)
	{
		window.scrollTo(0, p.round());
		if (scrollTo - p == 0)
		{
			last_scroll_effect = null;
		}
	});
}

function vk_settings_request(needRights)
{
	//var needRights = 1+4;
	
	VK.addCallback('onSettingsChanged',
		function(settings)
		{
			if (settings & needRights != needRights)
				VK.callMethod('showSettingsBox', needRights + 256);
			else
				new Ajax.Request('/g/?action=g_vk_settings', {parameters: {settings: settings}});
		});
	
	VK.callMethod('showSettingsBox', needRights + 256);
}

function vk_init(t, opts)
{
	if (opts.user_is_auth)
	{
		if (!opts.vk_is_app_user)
		{
			VK.addCallback('onApplicationAdded',
				function()
				{
					new Ajax.Request('/g/?action=g_vk_installed', {});
					vk_settings_request(opts.rights);
				});
				
			VK.callMethod('showInstallBox');
		}
		else
		{
			if (opts.needInstall)
				vk_settings_request(opts.rights);
		}
	}
}

var mouseXY = {x: 0, y: 0};

document.observe('dom:loaded', function() {
    var _mouseXY = function(e)
    {
        var x = 0, y = 0;

        if (!e) e = window.event;
        if (e.pageX || e.pageY) {
            x = e.pageX;
            y = e.pageY;
        }
        else if (e.clientX || e.clientY) {
            x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
            y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
        }
        return {"x":x, "y":y};
    }
    Event.observe(window, 'mousemove', function(e) { 
        mouseXY = _mouseXY(e);
    });
});
