function close_block(x){document.getElementById(x).style.display='none';}
function open_block(x){document.getElementById(x).style.display='block';}
function close_search_form()
{
	open_block('search_open');
	close_block('search_close');
	close_block('search_form');
}
function open_search_form()
{
	close_block('search_open');
	open_block('search_close');
	open_block('search_form');
}

function addBookmark(url, title)
{

  if (!url) url = location.href;
  if (!title) title = document.title;
  //Gecko
  if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) window.sidebar.addPanel (title, url, "");
  //IE4+
  else if (typeof window.external == "object") window.external.AddFavorite(url, title);
  //Opera7+
  else if (window.opera && document.createElement)
  {
    var a = document.createElement('A');
    if (!a) return false; //IF Opera 6
    a.setAttribute('rel','sidebar');
    a.setAttribute('href',url);
    a.setAttribute('title',title);
    a.click();
  }
  else return false;
  return true;
}

chatwnd = null;
function openChat(login, width, height){
	if(width == null) 
		width = 890;
	if(height == null) 
		height = 580;
	
	chatwnd = window.open('/chat/#'+login, 'chatwindow' , 'location=1,status=1,scrollbars=1,menubar=0,resizable=1,width='+width+',height='+height);
	
	chatwnd.focus();
	
	if (chatwnd.xchat)
		chatwnd.xchat.active(login);
	else{
	}
	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)
		{
			alert(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){alert(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)
			{
				//alert(t.responseText);
                                if(callback)
                                    callback();
				else if ((reloadWhenSuccess == undefined) || (reloadWhenSuccess))
				{
					if (window.location.toString().indexOf('?') != -1)
						window.location = window.location + '&pay=ok';
					else
					{
						window.location = window.location + '?pay=ok';
						//window.location = window.location;
					}
				}
			},
			onFailure: function(t){alert(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'
		},
		onSuccess: function(t)
		{
			el_sel_citys.disabled = false;
		}});
}

function ObservePlace(id_country, id_region, id_city, id_metro, allow_empty)
{
	// native events
	Event.observe($(id_country), 'change', function()
	{
		chCountry(id_country, id_region, allow_empty);
		$(id_region).innerHTML = '';
		$(id_city).innerHTML = '';
	});
	Event.observe($(id_region), 'change', function()
	{
		chRegion(id_region, id_city, allow_empty);
		$(id_city).innerHTML = '';
	});

	$(id_region).placeChanged = function()
	{
		chRegion(id_region, id_city, allow_empty);
		$(id_city).innerHTML = '';
	};
}

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 showLogin(idlog)
{
	var c = document.getElementById(idlog);
	c.style.display = (c.style.display == 'none')? '' : 'none';
}

function fixPNG(element)
{
  //Если браузер IE версии 5.5-6
  if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent))
  {
    var src;

    if (element.tagName=='IMG')     {
      if (/\.png$/.test(element.src))      {
        src = element.src;
        element.src = '/images/blank.gif';
      }
    }
    else
    {
      src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
      if (src)
      {
        src = src[1];
        element.runtimeStyle.backgroundImage="none";
      }
    }
    if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
  }
}

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)){
            if ((tab_name != i) && (o.select(tab_prefix+i)[0].style['display'] != 'none'))
				new Effect.BlindUp(o.select(tab_prefix+i)[0]);
			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);
	
	new Effect.BlindDown(o.select(tab_prefix+tab_name)[0]);
	
}

Event.observe(window, 'load', function()
{
	setTimeout(checkLocation, 500);
	if($('smi2adblock_7757')) {
		var smi2 = new Element('script', {'src': 'http://js.smi2.ru/data/js/7757.js', type: 'text/javascript', charset: 'windows-1251'});
		$$('body')[0].appendChild(smi2);
	}
});


function alert_deleted(login)
{
	alert('Этот пользователь был удалён!');
}

function ctrlEnter(event){
	return (event.keyCode==10 || (event.ctrlKey && 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 = (
			(currentLocation.indexOf('/my/up/') >= 0) ||
			(currentLocation.indexOf('/my/leader/') >= 0) ||
			(currentLocation.indexOf('/my/gallery/') >= 0) ||
			(currentLocation.indexOf('/my/pr/') >= 0) ||
			(currentLocation.indexOf('/my/super/') >= 0) ||
			(currentLocation.indexOf('/my/phone/') >= 0)
			);
	}
	
	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)
{
	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['rotator'])
			{
				el['rotator'].stop();
				el['rotator'] = null;
			}
		});

	if (document['photos_cache'][key])
		return;

	new Ajax.Request('/g/?action=g_user_photos', {
		parameters: {
			login: login,
			size: size
		},
		onSuccess: function (transport)
		{
			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)
		{
			//alert(transport.responseText);
		}
	});
}
function isMegaSuxx() {
    return (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
}

function isSuxx() {
    return (navigator.userAgent.toLowerCase().indexOf("msie 6") != -1);
}
function isSuxx8() {
    return (navigator.userAgent.toLowerCase().indexOf("msie 8") != -1);
}

var current_loc = location.hash;

function checkLocation ()
{
    var hash = document.location.hash;    
    if (hash != current_loc)
	{
        current_loc = hash;
        $$('body')[0].fire("location:anchor");
    }
    setTimeout(checkLocation, 500);
}

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(pay, data) {
    pay_close();
    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': '#', 'id': 'pay_close'}).observe('click', pay_close));
    _pay.insert(_pay_content);
    $$('body')[0].insert(_pay);


    if(!data) {
        var data = {};
    }
    data.pay = pay;
    new Ajax.Request('/g/?action=g_pay',{
        parameters: data,
        onSuccess: function(t)
        {
            _pay_content.update(t.responseText);
        }
    });
}

function pay_close(e) {
    if(e) { e.stop(); }
    if($('pay_bg')) {
        $('pay_bg').remove();
        $('pay').remove();
    }
}

function pay_photo_change(id) {
    $('pay_photo_'+id).up().select('.sel').each(function(i) {
        $(i).removeClassName('sel')
    });
    $('pay_photo_'+id).addClassName('sel');
    $('photo_id').setValue(id);
}


function pay_show_rules(title) {
    var div = new Element('div');
    div.update($('rules_').innerHTML);
    new window_(title, div, 'rules_win');
}
