var loading = null;
var confirm = null;
var hidden = null;

var General = {
	_confirmed : false,
	_x : 0,
	_y : 0,
	_is_ie : /MSIE/.test(navigator.userAgent) || false,
	_allowed_image_types : '.jpg.gif.png.jpeg.',
	_ajaxWorking : false,
	_blinking : false,
	_create_cookie : function( name, value, days )
    {    
	var expires;	
            if ( days )
		{
			 var date = new Date();
			 date.setTime(date.getTime() + (days*24*60*60*1000));
			 expires = "; expires=" + date.toGMTString();
		}
		else 
			expires = "" ;
		
		document.cookie = name + "=" + value + expires + "; path=/" ;
		
		if ( !document.cookie )    
			return false ;
	
   return true ;

   },
   _read_cookie : function( name )
   {
        var nameEQ = name + "=";
        var ca = document.cookie.split( ';' );
        for ( var i=0; i < ca.length; i++ )
        {
                var c = ca[i] ;
                while ( c.charAt( 0 ) == ' ' ) 
					c = c.substring( 1, c.length ) ;

                if ( c.indexOf(nameEQ) == 0 ) 
					return c.substring( nameEQ.length, c.length );
        }
        return true;
    },
	_bookmark : function(url, title) 
	{	 	
		if ( window.sidebar ) 
			window.sidebar.addPanel( title, url, '');
		else if ( window.external ) 
			window.external.AddFavorite( url, title);
		else if ( window.opera && window.print ) 
			return true;
        return false;
 	},	
	ajaxError: function(status, extraText) {
		var t = '';

		switch ( status ) {
			case 408:
				t = 'Заявката отне твърде дълго време и беше прекъсната, препоръчваме да опиташ отново. Опитай пак по-късно.';
				
				if ( extraText && extraText != '' ) {
					t += ' ' + extraText;
				}
			break;
			
			case 404:
				t = 'Възникна грешка докато се изпълнява заявката, адреса не беше намерен. Опитай пак по-късно.';
				
				if ( extraText && extraText != '' ) {
					t += ' ' + extraText;
				}
			break;
		}
		
		if ( !t ) {
			return false;
		}
		
		var el = $('ajaxError') || false;
		
		if ( el == false ) {
			var el = new Element('div', {
				'id': 'ajaxError',
				'style' : 'position: absolute; top: 180px; left: 10px; z-index: 100000; padding: 10px; width: 860px;'
			});
			
			el.addClassName('DivError');
			
			$('body').insert({
				'top': el
			});
		}
		
		el.update(t).show();
		
		var browseWidth = document.documentElement.scrollWidth;
        var browserHeight = document.documentElement.clientHeight;
		var dim = el.getDimensions();
		
		var l = (browseWidth/2) - (dim.width/2);
		var t = (browserHeight/2) - (dim.height/2) + (document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop) - 100;

        el.setStyle({top : t, left : l});
		
		window.setTimeout(function(){
			el.update('').hide();
		}, 5000);
	},
	_register_form : function(form)
	{
		var email = form.userEmail.value;		
		var pass = form.userPassword.value;
		var tos = form.tos.checked;

		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		if ( !filter.test(email) )
			this._error('Въведи валиден e-mail адрес', 'userEmail');
		else if ( pass.blank() )
			this._error('Въведи парола', 'userPassword');
		
		else if ( tos == false )
			this._error('За да продължите регистрацията трябва да отбележите, че сте съгласни с нашите условия за ползване.', 'accept_tos_container');
		else
		{
			return true;
		}
				
	return false;
	},
	_register_form_step2 : function(form)
	{		
		var userName = form.userName.value;
		var sex = form.userGender;

		if ( userName.blank() )
			this._error('Въведи име на животното', 'userName');
		else if ( sex[0].checked == false && sex[1].checked == false )
			this._error('Избери пол на животното', 'userGender');
		else
		{
			return true;
		}
				
	return false;
	},
	_change_animal : function(animal)
	{
		$$('div .bigAnimal').each(function(els){els.hide();});
		
		$('animal' + animal).show();
		$('userAnimal').value = animal;
	},
	_change_animal_confirm : function(animal) {
		//  Ще ти струва ' + gChangeAnimalPrice + ' жълтици.
		if (this._confirm('Сигурен ли си, че искаш да си смениш животното?', 'window.location="./shop/index/animals?change=' + animal + '"') == false) {
			return false;
		}
			
		return true;
	},
	_password_strength : function(pass, msg)
	{
		var length = pass.length;
		var strength = 0;
		
		if( length == 0 )
			return false;
		
		number_re = new RegExp('[0-9]');		
		if ( number_re.test(pass) )
			strength++;
		
		non_alpha_re = new RegExp('[^A-Za-z0-9]');
		if ( non_alpha_re.test(pass) )
			strength++;
		
		upper_alpha_re = new RegExp('[A-Z]');
		if ( upper_alpha_re.test(pass) )
			strength++;
		
		
		if ( length >= 8 )
			strength++;		
		
		var error = '<span style="font-weight: normal; color: #000; font-size: 11px;">';
		
		if ( strength <= 1 )		
			error += '<strong style="color: #808080;">слаба</strong>';		
		else if ( strength <= 2 )		
			error += '<strong style="color: #008FEB;">средно</strong>';		
		else		
			error += '<strong style="color: #008048;">сигурна</strong>';
			
		error += '</span>';
		if( length < 4 )		
			error = '<strong style="color: #FFA548;">Твърде кратка</strong>';
		
		this._error(error, msg, true);
		
	return false;
	},
	_check_username : function(el)
	{
		if (typeof _t != 'undefined') {
			clearTimeout(_t);
		}
			
		var username = el.value;
		
		if ( !username.blank() && username.length > 2 ) {
			_t = window.setTimeout(function(){
				if (General._ajaxWorking == true) {
					return false;
				}
			
				General._ajaxWorking = true;
				
				if ($('userNameError')) {
					$('userNameError').remove();
				}
				
				$('userNameLoading').show();
				
				new Ajax.Request('register/_check_username', {
		 		parameters : {'ajax' : 1, 'username' : escape(username.stripTags())},
				onComplete : function(res)
				{
					General._ajaxWorking = false;
					$('userNameLoading').hide();
						
					var response = res.responseText;
					var _response = response.split('|');
														
					new Insertion.Bottom('userNameText', '<span id="userNameError" style="color: #' + (_response[0] == 'success' ? '008FEB' : 'EF8D0E') + '; font-size: 11px; padding: 0 10px;">' + _response[1] + '</span>');
				},
				onFailure : function() {
					General._ajaxWorking = false;
					$('userNameLoading').hide();
				}
		 	});}, 500);
		}
	},	
	_check_email : function(el)
	{
		if (typeof _t_e != 'undefined') {
			clearTimeout(_t_e);
		}
		
		var email = el.value;
		
		if (email.blank() || email.length < 8) {
			return false;
		}
		
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if ( filter.test(email) ) {
			_t_e = window.setTimeout(function(){
				
				if (General._ajaxWorking == true) {
					return false;
				}
			
				General._ajaxWorking = true;
				
				if ($('userEmailError')) {
					$('userEmailError').remove();
				}
				
				$('emailLoading').show();
				
				new Ajax.Request('register/_check_email', {
		 		parameters : {'ajax' : 1, 'email' : email},
				onComplete : function(res)
				{
					General._ajaxWorking = false;
					$('emailLoading').hide();
					
					var response = res.responseText;									
					var _response = response.split('|');
					
					new Insertion.Bottom('userEmail', '<span id="userEmailError" style="color: #' + (_response[0] == 'success' ? '008FEB' : 'EF8D0E') + '; font-size: 11px; padding: 0 10px;">' + _response[1] + '</span>');
				},
				onFailure : function() {
					General._ajaxWorking = false;
					$('emailLoading').hide();
				}
			 	});
			 }, 500);
		}
	return false;
	},	
	_hide : function(id, time)
	{
		if ( typeof time == 'undefined' )
			time = 1000;
			
		setTimeout(function(){$(id).update('').hide();}, time);	
	},	
	_confirm : function(text, func)
	{
		if ( General._confirmed == true )
		{
			return true;
		}
		
		var b_w = document.documentElement.scrollWidth;		
		var browserHeight = document.documentElement.scrollHeight;
		var c_w = 870;

		if ( confirm.style.display == '' )
			return false;

		confirm.show();
		
		hidden.setStyle({width : b_w + 'px', height : browserHeight + 'px'}).show();
		
		$$('select').each(function(el){el.hide();});
		
		$('confirm_message').update(text);	
		$('confirm_button').onclick = function()
		{
			General._confirmed = true;
			eval(func); 
			General._hide_confirm(func);
		}		
	return false;
	},	
	_hide_confirm : function(func)
	{
		General._confirmed = false;

		$('confirm_button').onclick = function(){}
		
		confirm.setStyle({top : 0 + 'px'}).hide();
		$('confirm_message').update('');	
		$$('select').each(function(el){el.show();});
		hidden.hide();
	},	
	_error : function(text, id, stop_hide, divs, insertionTop)
	{
		var name = (typeof id == 'undefined' ? '' : id.name) || '';
		if (typeof id != 'undefined' && typeof id == 'string') {
			name = id;
			id = $(id);
		}
		
		if (typeof stop_hide == 'undefined') {
			stop_hide = false;
		}
		
		if ( typeof divs != 'undefined' ) {
			divs = 'Div';
		} else {
			divs = '';
		}
					
		if (!$('Error' + name)) {
			var div = new Element('div', {
				'id': 'Error' + name
			});
			
			div.addClassName(divs + 'Error');
			
			if (insertionTop) {
				$(id || 'header').insert({
					'top': div
				});
			} else {
				$(id || 'header').insert({
					'after': div
				});
			}
		}

		$('Error' + name).update(text).show();
			
		if (typeof _e_t != 'undefined') {
			window.clearTimeout(_e_t);
		}
			
		if (typeof _el != 'undefined' && $('Success')) {
			$('Success').setStyle({
				'left': (_el[0] - 200) + 'px',
				'top': _el[1] + 'px',
				'position': 'absolute',
				'border': '1px solid #FF9000'
			});
		}
		if (stop_hide == false) {
			_e_t = window.setTimeout(function(){
				if ( !$('Error' + name) )
					return false;
				$('Error' + name).update('').hide();
			}, 10000);
		}
	},	
	_success : function(text, id, divs, insertionTop)
	{
		var name = (typeof id == 'undefined' ? '' : id.name) || '';
		if (typeof id != 'undefined' && typeof id == 'string') {
			name = id;
			id = $(id);
		}
		
		if (typeof stop_hide == 'undefined') {
			stop_hide = false;
		}
		
		if ( typeof divs != 'undefined' ) {
			divs = 'Div';
		} else {
			divs = '';
		}
		
		if (!$('Success' + name)) {
			var div = new Element('div', {
				'id': 'Success' + name
			});
			
			div.addClassName(divs + 'Success');
			
			if (insertionTop) {
				$(id || 'header').insert({
					'top': div
				});
			} else {
				$(id || 'header').insert({
					'after': div
				});
			}
		}
		
		$('Success' + name).update(text).show();
		
		if (typeof _s_t != 'undefined') {
			window.clearTimeout(_s_t);
		}
			
		if (typeof _el != 'undefined' && $('Success')) {
			$('Success').setStyle({
				'left': (_el[0] - 200) + 'px',
				'top': _el[1] + 'px',
				'position': 'absolute',
				'border': '1px solid #008FEC'
			});
		}
		
		if (stop_hide == false) {
			_s_t = window.setTimeout(function(){
				if ( !$('Success' + name) )
					return false;
				$('Success' + name).update('').hide();
			}, 10000);
		}
	},
	_wall_pages : function(userId, p)
	{
		loading.show();
		
		new Ajax.Updater({
			success: 'wallPages'
		}, 'wall/_wall_pages', {
			parameters : {'ajax' : 1, 'userId' : userId, 'p' : p},
			onComplete : function()
			{
				loading.hide();
				General._fixIE();
			},
			onFailure : function(res) {
				General.ajaxError(res.status);
			}
		});
	},
	_wall_delete : function(wallId)
	{
		if ( typeof wallId == 'undefined' || wallId <= 0 )
			return false;

		if ( this._confirm('Сигурен ли си, че искаш да изтриеш това съобщение?', 'General._wall_delete(' + wallId + ');') == false )
			return false;

		loading.show();
		new Ajax.Request('wall/_wall_delete', {
			 parameters : {'ajax' : 1, 'wallId' : wallId},
			 onComplete : function(res)
			 {
				loading.hide();
				new Insertion.Before('wall_post_' + wallId, '<div class="clear" style="background-color: #E8F4FF; height: 30px; line-height: 30px; text-align: center; margin-top: 10px;">Съобщението е изтрито на ' + res.responseText + '</div>');
				$('wall_post_' + wallId).remove();							
			 }
		});
		return false;
	},		
	_is_enter : function(e)
	{
		  return General._get_key(e) == 13 ? true : false;
	},	
	_get_key : function(e)
	{
		var characterCode = '';
		if ( e && e.which )
		{           
			e = e;
			characterCode = e.which;
		}
		else 
		{
			e = event;
			characterCode = e.keyCode;
		}
	return characterCode;
	},
	_wall_check : function(form)
	{
		if ( ($('graffiti_text').value).blank() && (form.wall_msg.value).blank() )
		{
			General._error('Напиши текст към съобщението на стената или напиши графит.', 'wall_post_form', true);
			return false;	
		}
	return true;
	},
	_set_graffiti_font : function(name)
	{
		$('graffiti_font_input').value = name;
		$('graffiti_font_container').hide();		
		$('graffiti_set_font').update('<span>Текущ шрифт:</span> <img src="./i/graffiti/' + name + '.gif" alt="' + name + '" />');
		
	},
	_graffiti_preview : function()
	{
		var font_color = $F('graffiti_color');
		var font = $F('graffiti_font_input');
		var text = $F('graffiti_text');
		
		if ( text.empty() )
		{
			General._error('Напиши текст към графита', 'graffiti_preview');
			return false;	
		}
		
		loading.show();
		new Ajax.Updater('graffiti_preview', 'wall/_gen_graffiti_ajax', {
			 parameters : {'ajax' : 1, 'font_color' : font_color, 'font' : font, 'text' : text},
			 onComplete : function()
			 {
				 loading.hide();
			 }
		});
	return false;
	},
	_delete_profile : function()
	{
		if ( this._confirm('Сигурен ли си, че искаш да изтриеш профила?', '$(\'account_delete\').submit();') == false )
			return false;
			
		return true;
	},
	_emo_observe : function(el_c, el)
	{
		Event.observe(el_c, 'click', function(){General._show_emo_container(el);});
	},
	_hide_emo_container : function(el)
	{
		$(el).hide();
		$('smiley_container').setStyle({'width' : '100px'});
	},
	_show_emo_container : function(el)
	{
		$('smiley_container').setStyle({'width' : '100%'});
		$(el).show();
	},
	_show_emo_text : function(el, hide)
	{
		emo_id = el.id;
		if ( typeof hide != 'undefined' && hide == true )
			$(el.id + '_tooltip').hide();
		else
			$(el.id + '_tooltip').show();
	},
	_set_smiley : function(form, smile)
	{
		var f = $(form);
		f.value += smile + ' ';
		f.focus();

		$('smiley').hide();
		$('emo_text').hide();
		
		if ( typeof emo_id != 'undefined' )
			$(emo_id + '_tooltip').hide();
	},
	_scroll_to : function(last_message, form_element)
	{
		if( !last_message || !form_element )
			return false;
		
		var _begin_top = form_element.cumulativeScrollOffset()[1];
		var _duration = 600;
		var _start_time = (new Date()).getTime();
		var _last_top = null;
		var _interval_scroll = '';
		
		_interval_scroll = window.setInterval(function(){			
			var _window_height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight;
			var _last_msg_height = form_element.cumulativeOffset()[1] + form_element.offsetHeight;			
			var _form_height = last_message.cumulativeOffset()[1] - 100;
	
				if ( _last_msg_height-_form_height < _window_height )
				{
					_form_height -= (_window_height+_form_height)-_last_msg_height;
				}
				if ( _last_msg_height < _window_height+100 )
				{
					window.clearInterval(_interval_scroll);
					_interval_scroll = '';
				}
			var _time = (new Date()).getTime();
			var _scroll = null;
			var _current_top = form_element.cumulativeScrollOffset()[1];
			
			var _p = (_time-_start_time)/_duration;
			
				if ( _p > 1 )	
				{		
					_scroll = _form_height;
					window.clearInterval(_interval_scroll);
					_interval_scroll = '';
				}			
				else
				{
					if ( _p <= 0.5 )
						_fp = (_p * _p) * 2;
					else
					{
						_p -= 1; 
						_fp = (_p * _p) * - 2 + 1;
					}
					_scroll = parseInt((_form_height-_begin_top) * _fp + _begin_top);
				}
				if ( _last_top && _current_top != _last_top && _current_top != 0 )
				{
					window.clearInterval(_interval_scroll);
					_interval_scroll = '';
				}
				else
				{
					window.scrollBy(0, (_scroll-_current_top));
					_last_top = _scroll;
				}
		}, 25);
	return false;
	},
	_edit_description : function()
	{
		if ( General._ajaxWorking == true )
			return;
		
		var descr = $('description') || false;
		var descrForm = $('descrForm') || false;
		var descrText = $('userDescription') || false;
		
		if ( descr == false || descrForm == false )
			return;
		
		loading.show();
		General._ajaxWorking = true;
		
		new Ajax.Request('profile/_description', {
			parameters : {'ajax' : 1},
			onComplete : function(response)
			{
				loading.hide();
				General._ajaxWorking = false;
				
				descr.hide();
				descrForm.show();
				
				response = (response.responseText).evalJSON();
				
				descrText.value = (response[0].description).gsub("<br />", "\n");				
			}
		});
	},
	_save_description : function()
	{		
		if ( General._ajaxWorking == true )
			return;
		
		var descrText = $('userDescription') || false; // textarea
		var descr = $('descrText') || false; // visible text
		var descrForm = $('descrForm') || false;
		
		if ( descrText == false || descr == false || descrForm == false )
			return;
			
		var text = (descrText.value).stripTags();
		
		loading.show();
		General._ajaxWorking = true;
		
		new Ajax.Request('profile/_save_description', {
				parameters : {'ajax' : 1, 'text' : text},
				onComplete : function(response)
				{
					loading.hide();
					General._ajaxWorking = false;
					
					response = (response.responseText).evalJSON();
					res = response[0].description;
					descr.update(res == '' ? '<em id="tempText">Напиши кратко описание</em>' : res);							
					
					$('description').show();
					descrForm.hide();
				}
			});
	},
	_cancel_description : function()
	{
		$('description', 'descrForm').invoke('toggle');	
	},
	_feed : function(what)
	{
		if ( General._ajaxWorking == true )
			return;
		
		loading.show();				
		General._ajaxWorking = true;
		
		new Ajax.Updater({
			success: 'fridgeContent'
		}, 'profile/_fridge', {
			parameters : {'ajax' : 1, 'what' : what},
			evalScripts : true,
			onComplete : function()
			{
				General._ajaxWorking = false;
				loading.hide();
				
				if (!$('fridge').visible()) {
					Effect.SlideDown('fridge', {
						duration: 1.0
					});
				}
			},
			onFailure : function(res) {
				General.ajaxError(res.status);
			}
		});
	},
	_shop : function(type, p) {
		if (General._ajaxWorking == true) {
			return;
		}
		loading.show();		
		General._ajaxWorking = true;
		
		new Ajax.Request('shop/_shop', {
			parameters : {'ajax' : 1, 'type' : type, 'p' : p},
			onComplete : function(response)
			{
				General._ajaxWorking = false;
				loading.hide();
				response = (response.responseText).evalJSON();
					
				$('userMoney').update(response.userMoney);
				$('userCredits').update(response.userCredits);
				
				if ( response.html ) {
					$(type).update(response.html);
					General._fixIE();
				}
			}
		});
		
	},
	_buy : function(id, where, reloads, p)
	{
		if ( General._ajaxWorking == true )
			return;
		
		if ( typeof p == 'undefined' ) {
			p = 0;
		}
		
		reloads = reloads || true;
		
		error = 'resError';
		success = 'resSuccess';		
		
		$(error).update('').hide();
		$(success).update('').hide();

		loading.show();		
		General._ajaxWorking = true;
		
		new Ajax.Request('shop/_buy', {
			parameters : {'ajax' : 1, 'id' : id, 'p' : p},
			onComplete : function(response)
			{
				General._ajaxWorking = false;
				loading.hide();
				response = (response.responseText).evalJSON();
				
				if ( response[0].error ) {
					$(error).update(response[0].error).show();
				} else if ( response[0].success ) {
					$(error).update('').hide();
					$(success).update(response[0].success).show();
					$('userMoney').update(response[0].userMoney);
					$('userCredits').update(response[0].userCredits);
					
					if ( response.html ) {
						$(where).update(response.html);
						General._fixIE();
					}
				}
			}
		});
	},
	_blink_think : function()
	{
		if ( General._blinking == true )
			return;		
		
		General._blinking = true;
		
		var think = $('userThink');
		new Effect.Pulsate(think);
		
		setTimeout(function(){General._blinking = false;}, 2000);
	},
	_animal_font_set : function(id)
	{
		if ( General._ajaxWorking == true )
			return;
		
		loading.show();
		General._ajaxWorking = true;
		
		new Ajax.Request('profile/_font_set', {
			parameters : {'ajax' : 1, 'id' : id},
			onComplete : function(response)
			{
				loading.hide();
				General._ajaxWorking = false;
				response = (response.responseText).evalJSON();
				
				if ( response[0].error )
				{
					$('fontResponse').removeClassName('DivSuccess').addClassName('DivError').update(response[0].error).show();		
				}
				else if ( response[0].success )
				{				
					$$('#animalFonts div.hideShop').each(function(el){el.hide();});
					$('animalBg' + id).show();
					
					fontsPreview(id);
					
					$('fontResponse').removeClassName('DivError').addClassName('DivSuccess').update(response[0].success).show();
				}
			}
		});
	},
	_lunch : function(id, free)
	{
		if ( General._ajaxWorking == true )
			return;
		
		loading.show();
		General._ajaxWorking = true;
		
		if ( typeof free == 'undefined' )
			free = '';

		new Ajax.Request('profile/_lunch', {
			parameters : {'ajax' : 1, 'id' : id, 'free' : free},
			onComplete : function(response)
			{
				loading.hide();
				General._ajaxWorking = false;
				response = (response.responseText).evalJSON();
								
				if ( response[0].error )
				{
					$('animalTalk').removeClassName('Success').addClassName('Error').update(response[0].error).show();		
					General._blink_think();
				}
				else if ( response[0].success )
				{
					$('animalTalk').removeClassName('Error').addClassName('Success').update(response[0].success).show();
					General._blink_think();
					
					if (typeof response[0].userMoney != 'undefined') {
						$('userMoney').update(response[0].userMoney);
					}

					if ( response[0].userFood )
					{
						$('foodBar').setStyle({'width' : response[0].userFood + '%'});
						$('washBar').setStyle({'width' : response[0].userWash + '%'});
						$('walkBar').setStyle({'width' : response[0].userWalk + '%'});
					}
					
					if ( response[0].userDrink )
					{
						$('drinkBar').setStyle({'width' : response[0].userDrink + '%'});
						$('washBar').setStyle({'width' : response[0].userWash + '%'});
						$('walkBar').setStyle({'width' : response[0].userWalk + '%'});						
					}
						
					if ( free.blank() && response[0].totalFood == 0 )
						$('foodId' + id).remove();
					else
					{
						if ( free.blank() )
						{
							$('foodTotal' + id).update(response[0].totalFood + ' бр.');
						}
						else
						{
							if ( $('freeFood') )
								$('freeFood').remove();
							else if ( $('freeDrink') )
								$('freeDrink').remove();
						}
					}
					
					if ( $$('div.foods').length == 0 )
						$('fridgeContent').update('В хладилникът няма ' + (response[0].what == 'food' ? 'храна' : 'питиета') + ', <a href="./shop">нека да напазаруваме</a>');
						
					General._set_emotion(response[0].userEmotion, response[0].emotionThink);
				}
			}
		});
	},
	_walks : function()
	{
		if ( General._ajaxWorking == true )
			return;
		
		loading.show();
		General._ajaxWorking = true;
		
		new Ajax.Updater({
			success: 'walksContent'
		}, 'profile/_walks', {
			parameters : {'ajax' : 1},
			onComplete : function()
			{
				loading.hide();
				General._ajaxWorking = false;
				
				Effect.SlideDown('walks', {duration : 1.0});
			},
			onFailure : function(res) {
				General.ajaxError(res.status);
			}
		});
	},
	_walk : function(id)
	{
		if ( General._ajaxWorking == true )
			return;
			
		loading.show();
		General._ajaxWorking = true;
		
		new Ajax.Request('profile/_walk', {
			parameters : {'ajax' : 1, 'id' : id},
			onComplete : function(response)
			{
				loading.hide();
				General._ajaxWorking = false;
				response = (response.responseText).evalJSON();
				
				if ( response[0].error )
				{
					$('animalTalk').removeClassName('Success').addClassName('Error').update(response[0].error).show();
					General._blink_think();
				}
				else if ( response[0].success )
				{
					$('animalTalk').removeClassName('Error').addClassName('Success').update(response[0].success).show();
					General._blink_think();
										
					$('foodBar').setStyle({'width' : response[0].userFood + '%'});
					$('drinkBar').setStyle({'width' : response[0].userDrink + '%'});
					$('washBar').setStyle({'width' : response[0].userWash + '%'});
					$('walkBar').setStyle({'width' : response[0].userWalk + '%'});
					$('userMoney').update(response[0].userMoney);
					
					General._set_emotion(response[0].userEmotion, response[0].emotionThink);
					$('walks').hide();
				}
			}
		});
	},
	_washes : function()
	{
		if ( General._ajaxWorking == true )
			return;
		
		loading.show();
		General._ajaxWorking = true;
		
		new Ajax.Updater({
			success: 'washesContent'
		}, 'profile/_washes', {
			parameters : {'ajax' : 1},
			onComplete : function()
			{
				loading.hide();
				General._ajaxWorking = false;
				
				Effect.SlideDown('washes', {duration : 1.0});
			},
			onFailure : function(res) {
				General.ajaxError(res.status);
			}
		});
	},
	_wash : function(id)
	{
		if ( General._ajaxWorking == true )
			return;
	
		loading.show();
		General._ajaxWorking = true;
		
		new Ajax.Request('profile/_wash', {
			parameters : {'ajax' : 1, 'id' : id},
			onComplete : function(response)
			{
				loading.hide();
				General._ajaxWorking = false;
				response = (response.responseText).evalJSON();
				
				if ( response[0].error )
				{
					$('animalTalk').removeClassName('Success').addClassName('Error').update(response[0].error).show();
					General._blink_think();
				}
				else if ( response[0].success )
				{
					$('animalTalk').removeClassName('Error').addClassName('Success').update(response[0].success).show();
					General._blink_think();

					$('washBar').setStyle({'width' : response[0].userWash + '%'});
					$('userMoney').update(response[0].userMoney);
					
					General._set_emotion(response[0].userEmotion, response[0].emotionThink);
					$('washes').hide();
				}
			}
		});
	},
	_set_emotion : function(emotion, emotionThink)
	{		
		$('userEmotion').update(emotion);
	},
	_fixIE : function()
	{
		var arVersion = navigator.appVersion.split("MSIE");
		var version = parseFloat(arVersion[1]);

		if ((version >= 5.5 && version < 7) && (document.body.filters)) {	
			General._fixPng();
		}	
	},
	
	_fixPng : function() {
		for (var i = 0; i < document.images.length; i++) {
			var img = document.images[i];
			var imgName = img.src.toUpperCase();
			if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
				var imgID = (img.id) ? "id='" + img.id + "' " : "";
				var imgClass = (img.className) ? "class='" + img.className + "' " : "";
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
				var imgStyle = "display:inline-block;" + img.style.cssText;
				if (img.align == "left") {
					imgStyle = "float:left;" + imgStyle;
				}
				if (img.align == "right") {
					imgStyle = "float:right;" + imgStyle;
				}
				if (img.parentElement.href) {
					imgStyle = "cursor:hand;" + imgStyle;
				}
				var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
				
				if (img.parentNode.nodeName == "A") {
					img.parentNode.className = "fix";
				}
				img.outerHTML = strNewHTML;
				i = i - 1;
			}
		}
	},
	
	_battle : function(user, refresh)
	{
		if ( typeof refresh == 'undefined' ) {
			refresh = 0;
		}
		
		if (General._confirm('Сигурен ли си, че искаш да предизвикаш <strong>' + user + '</strong> на дуел?<br />Това ще ти струва <span class="bold orange">1</span> жълтица.', 'General._battle(\'' + user + '\', ' + refresh + ');') == false) {
			return false;
		}
		
		if ( General._ajaxWorking == true )
			return;
	
		loading.show();
		General._ajaxWorking = true;
		
		new Ajax.Request('profile/_battle', {
			parameters : {'ajax' : 1, 'user' : user, 'refresh' : refresh},
			onComplete : function(response)
			{
				loading.hide();
				General._ajaxWorking = false;
				response = (response.responseText).evalJSON();
				
				if ( typeof response.userMoney != 'undefined' ) {
					$('userMoney').update(response.userMoney);
				}
												
				if ( response.success ) {
					General._success(response.success, 'userInfo');
				}
				
				if ( response.error ) {
					General._error(response.error, 'userInfo');
				}
				
				if ( response.html && refresh == 1 ) {
					$('activeBattles').update(response.html);
				}
			}
		});
	},
	
	_setOnVacation : function(price) {
		
		if ( $('userVacation').checked ) {
			if ( this._confirm('Сигурен ли си, че искаш да излезеш във ваканция? Ще ти струва ' + price + ' жълтици.', '$(\'setOnVacationForm\').submit();') == false ) {
				return false;
			}
		}
			
		return true;
	},
	
	credits : function (siteName, userName) {
		var browseWidth = document.documentElement.scrollWidth;		
		var browserHeight = document.documentElement.scrollHeight;

		hidden.setStyle({width : browseWidth + 'px', height : browserHeight + 'px'}).show();
		$$('select').each(function(el){el.hide();});
		var credits = $('credits');
		credits.show();

        var browserHeight = document.documentElement.clientHeight;
		var dim = credits.getDimensions();
									
		var l = (browseWidth/2) - (dim.width/2);
		var t = (browserHeight/2) - (dim.height/2) + (document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop);
		
		credits.setStyle({top : t + 'px', left : l + 'px'});
		
		var creditsBuy = $('creditsBuy');
		var creditsChange = $('creditsChange');
		
		creditsChange.hide();
		creditsBuy.show();

		General.creditsSms(siteName, userName);
	},
	
	creditsClose : function() {
		hidden.hide();
		$$('select').each(function(el){el.show();});
		$('credits').hide();
	},
	
	creditsSms : function(siteName, userName) {
		var creditsFrame = $('creditsFrame');
		creditsFrame.update('<iframe src="http://payments.minifrogs.com/?payment=sms&amp;siteName=' + siteName + '&amp;userName=' + userName + '&amp;frame" allowtransparency="yes" frameborder="0" height="250" width="400" scrolling="no" id="payments"></iframe>');
	},
	
	creditsChange : function() {

		var creditsBuy = $('creditsBuy');
		var creditsChange = $('creditsChange');
		var creditsFrame = $('creditsFrame');
		
		new Ajax.Request('shop/_creditsChange', {
			 parameters : {'ajax' : 1},
			 onComplete : function(response)
			 {
				response = (response.responseText).evalJSON();
				creditsChange.update(response.html).show();
				creditsBuy.hide();
				creditsFrame.update('');
			 }
		});
	},
	
	changeCredits : function(el, money) {			
		var l = el.value.length;
		var lastV = parseInt(el.value.substring(l-1, l));
		var currentCredits = parseInt($('currentCredits').innerHTML);
		
		if ( isNaN(currentCredits) ) {
			currentCredits = 0;
		}
		
		if ( l > 0 && isNaN(lastV) ) {
			el.value = el.value.substring(0, l-1);
		}
		
		var val = parseInt(el.value);
		
		if ( l > 0 && isNaN(val) ) {
			el.value = 0;
		return false;
		}
		
		if ( val > currentCredits ) {
			el.value = el.value.substring(0, l-1);
			return false;
		}
		
		var creditsHowCoins = $('creditsHowCoins');
		var newMoney = val*money;
		
		if ( isNaN(newMoney) ) {
			newMoney = 0;
		}
		
		creditsHowCoins.update(newMoney);
	},
	
	changeCreditsSubmit : function(form) {			

		var creditsBuy = $('creditsBuy');
		var creditsChange = $('creditsChange');
		var creditsFrame = $('creditsFrame');
		
		new Ajax.Request('shop/_creditsChangeSubmit', {
			 parameters : {'ajax' : 1, 'creditsField' : form.creditsField.value},
			 onComplete : function(response)
			 {
				response = (response.responseText).evalJSON();
								
				$('userMoney').update(response.userMoney);
				$('userCredits').update(response.userCredits);
				
				creditsChange.update(response.html).show();
				creditsBuy.hide();
				creditsFrame.update('');
			 }
		});
		
	return false;
	}
}

// End General Functions

var Balon = Class.create({
	initialize : function(el, _stop_disable, changePos, options)
	{
		this.options = {
			type : 'full',
			position : 'bottom'
		}
		
		Object.extend(this.options, options || { });
		
		this.el = $(el);
		if ( typeof _stop_disable != 'undefined' && _stop_disable == true )
		{
			_disable_balon = 0;
			this._stop_disable = 1;			
		}
		else
			this._stop_disable = 0;
			
		if ( typeof _disable_balon != 'undefined' && _disable_balon == 1 )
		{
			this.el.title = '';
			return false;
		}	
		
		if (typeof changePos == 'undefined') {
			this.el.setStyle({
				'position': 'relative'
			});
		}
		var div_el = 'div_' + el;
		this.div_el = $(div_el) || '';	
		
		if ( !this.div_el )
		{
			var div = new Element('div', {'id' : div_el, 'style' : 'display: none;'});
			div.addClassName('balon_container' + (this.options.type == 'short' ? ' balon_short' : '') + (this._stop_disable == 1 ? ' stop_disable' : ''));
			var div_inner = new Element('div', {'id' : div_el + '_inner'});
			div_inner.addClassName('balon_container_inner');
			var div_inner_inner = new Element('div', {'id' : div_el + '_inner_inner'});
			div_inner_inner.addClassName('balon_container_inner_inner');
			div_inner.appendChild(div_inner_inner);
			div.appendChild(div_inner);
			new Insertion.Top('siteBody', div);
			
		this.div_el = $(div_el);
		this.div_el_inner_inner = $('div_' + el + '_inner_inner');
		}		

		this.title = $(el).title;
		Event.observe(el, 'mouseover', this._show.bindAsEventListener(this));
		Event.observe(el, 'mouseout', this._hide.bindAsEventListener(this));
		
		Event.observe(div_el, 'mouseover', this._show2.bindAsEventListener(this));
		Event.observe(div_el, 'mouseout', this._hide.bindAsEventListener(this));
	return false;	
	},
	_show : function(e)
	{
		if ( typeof _disable_balon != 'undefined' && _disable_balon == 1 )
		{
			this.el.title = '';
			return false;
		}

		var element = Event.element(e);
		_el = element.cumulativeOffset();
		_h = element.getHeight();
		_w = element.getWidth();
		_x = _el[0];
		_y = _el[1];
				
		this.el.title = '';
		if ( this.options.position == 'bottom' )
		{
			var div_el = this.div_el.show().setStyle({'top' : ((_y+_h)-2) + 'px', 'left' : (_x + (_w/4)) + 'px'});
		}
		else if ( this.options.position == 'top' )
		{			
			var div_el = this.div_el.show().setStyle({'top' : (_y-30) + 'px', 'left' : (_x + (_w/8)) + 'px'});			
		}
		
		var t = '';//(this._stop_disable == 0 ? '<div style="padding-top: 10px;"><a href="settings" class="blue balonLink" onclick="General._disable_balon();event.returnValue = false;return false;">Изключи ме</a></div>' : '');
		var div_el_inner_inner = (this.div_el_inner_inner || $('div_' + element.id + '_inner_inner')).update(this.title + t);
	return false;
	},
	_show2 : function(e)
	{
		var div_el = this.div_el.show();
	},
	_hide : function(e)
	{
		this.div_el.hide();	
		this.el.title = this.title;
	}
});

function _e()
{
	Event.observe('container', 'click', function(e){
		var element = Event.element(e);

		if ( element.tagName == 'A' || element.tagName == 'INPUT' || element.tagName == 'IMG' )
		{			
			var _el = element.cumulativeOffset();
			
			loading.setStyle({'top' : (_el[1]-30) + 'px', 'left' : (_el[0]-25) + 'px'});

			if ( _el[0] < 320 ) {
				_el[0] = (320-_el[0])+_el[0];
			}
				
			if (_el[1] < 110) {
				_el[1] = (110 - _el[1]) + _el[1];
			}		
			
			confirm.setStyle({'top' : (_el[1]-120) + 'px', 'left' : (_el[0]-170) + 'px'});
		}
	});
}

/////////////////////////////////////

function copy(inElement, id, copyText, showSuccess) 
{
	var flashcopier = 'flashcopier';
	
	if ( typeof id == 'undefined' )
		var id = inElement.id;
	
	if ( !$(flashcopier) )
	{
		var div = new Element('div', {'id' : flashcopier, 'style' : 'visibility: hidden; width: 1px; height: 1px; overflow: hidden;'});
		div.addClassName('clearDiv');
		new Insertion.After('siteBody', div);
	}
	
	if ( $('success_' + id) )
		return;
	
	$(flashcopier).update('');
	if ( window.clipboardData ) 
	{
		window.clipboardData.setData('Text', inElement.value);
	}
	else
	{
		var divinfo = '<embed src="swf/_clipboard.swf" FlashVars="clipboard=' + encodeURIComponent(inElement.value) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		$(flashcopier).update(divinfo);		
	}
	
	if ( typeof showSuccess == 'undefined' || showSuccess == true )
	{	
		new Insertion.After(id, '<div class="Success" id="success_' + id + '">' + (copyText ? copyText : 'Текста е записан в паметта.') + '</div>');
		setTimeout(function(){$('success_' + id).remove();}, 10000);
	}
}

//////////////////////////////

var Inbox = {
	_friends : [],
	_found_friends : [],
	_stop_submit : false,
	_p : 0,
	_i : 0,
	_disableSounds : 0,
	_gen_inputs : function()
	{
		$('inbox_input').show().focus();
	},
	_get_friends : function(include_me)
	{
		if ( typeof include_me == 'undefined' )
			include_me = 1;	
		else
			include_me = 0;
		
		new Ajax.Request('inbox/_get_friends', {
							parameters : {'ajax' : 1, 'me' : include_me},
							onComplete : function(response)
							{
								Inbox._friends = (response.responseText).evalJSON();
							}
			});
	},
	_suggestion : function(el, e)
	{
		var value = (el.value).stripTags();
		Inbox._found_friends = [];
		var ol = new Element('ol',{ 'id' : 'suggestions_list'});
		$('suggestions').update(ol);
		var _t = 0;

			if ( value.length >= 2 )
			{
				for ( var j = 0; j < Inbox._friends.length; j++ )
				{
					if ( ((Inbox._friends[j].username).toLowerCase()).lastIndexOf(value.toLowerCase()) != -1 )
					{
						var userName = Inbox._friends[j].username;
						
						var user = userName;						
						var userId = Inbox._friends[j].userId;
							
						if ( typeof Inbox._found_friends[0] == 'undefined' )
							Inbox._found_friends = [{'userId' : userId, 'user' : user}];												
						
						userName = userName.replace(new RegExp(value, 'gi'), function(found){return '<em style="font-size: 11px !important; background-color: #ECF2F9;">' + found + '</em>'});

						var li = new Element('li', {'id' : 'inbox_user_' + userId});
						var a_href = new Element('a', {'href' : 'javascript:void(0)', 'id' : 'inputuser_' + userId, 'class' : 'inbox_found_href'}).update(userName).observe('click', function(e){Inbox._set_user(e)});
						var input = new Element('input', {'type' : 'hidden', 'name' : 'inboxinputuser_' + userId, 'value' : user});
						
						li.appendChild(a_href);
						li.appendChild(input);
						
						_t += 1;
						
						if ( _t > 5 )
						{
							$('suggestions').setStyle({'height' : '185px', 'overflow' : 'auto'});
							$('suggestions_list').setStyle({'width' : '355px'});
						}
						else
						{
							$('suggestions').setStyle({'height' : 'auto', 'overflow' : 'hidden'});
							$('suggestions_list').setStyle({'width' : 'auto'});
						}
						
						new Insertion.Bottom('suggestions_list', li);						
						$('suggestions', 'suggestions_li').invoke('show');
					}
				}	
			}
			
		if ( Inbox._found_friends.length == 0 )
			$('suggestions', 'suggestions_li').invoke('hide');
		
		if ( General._is_enter(e) == true )
		{
			Inbox._stop_submit = true;
			if ( typeof Inbox._found_friends[0] != 'undefined' && value.length >= 2 )
				$('inbox_input').blur();
		}
	},
	_list_set_user : function(id, user, userId)
	{
		this._set_user(id, user, userId);
		
		$('inbox_user_' + userId).hide();
	},
	_set_user : function(e, id, user, userId)
	{
		if ( typeof Inbox._i == 'undefined' )
			Inbox._i = 0;

		if ( typeof userId == 'undefined' && typeof user == 'undefined' )
		{
			var el = Event.element(e).id;
			var _id = el.split('_');
			var userId = _id[1];
			
			Event.stopObserving('inbox_user_' + userId, 'click', function(e){Inbox._set_user(e)});
		}
		else
			var userId = (( typeof userId == 'undefined' && typeof Inbox._found_friends[0] != 'undefined' ) ? Inbox._found_friends[0].userId : userId);
		
		if ( typeof userId == 'undefined' )
			return;
		
		for ( var i = 0; i < Inbox._friends.length; i++ )
		{
			if ( Inbox._friends[i].userId == userId )
			{
				var username = Inbox._friends[i].username;
			}
		}
		
		if ( typeof _from_pic_tags != 'undefined' )
		{
			Inbox._found_friends = [];
			$('suggestions').update('').hide();
			$('suggestions_li').hide();

		return;
		}
		
		$('inbox_input').value = '';		
		$('suggestions').update('').hide();
		$('suggestions_li').hide();
		$('inbox_input').hide();
		
		Inbox._found_friends = [];
					
		var current_users = $$('input.inbox_inputs');
		var stop = false;

		current_users.each(function(el){
						if ( el.value == userId )
						{
							stop = true;
							return false;
						}
									});
		if ( stop == true )
			return;
		
		Inbox._i++;
		var div = new Element('div', {'id' : 'inbox_input_' + Inbox._i, 'style' : 'display: none'});
		var input = new Element('input', {'type' : 'text', 'name' : '_id[]', 'class' : 'inbox_inputs', 'value' : userId});
		div.appendChild(input);
		
		var x = new Element('a', {'href' : 'javascript:void(0)', 'class' : 'input_x', 'id' : 'close_' + Inbox._i}).update('x');
		var span = new Element('span', {'id' : 'span_' + Inbox._i, 'class' : 'inbox_users_span'}).update(username);
		
		new Insertion.Before('inbox_input', span);
		new Insertion.Bottom('span_' + Inbox._i, x);		
		new Insertion.Before('inbox_input', div);
		
		var current = Inbox._i;
			
		Event.observe($('close_' + current), 'click', function(){Inbox._remove_user(current, userId)});
	},
	_remove_user : function(id, userId)
	{
		Event.stopObserving($('close_' + id), 'click', function(){Inbox._remove_user(id, userId )});
		if ( $('span_' + id) )
			$('span_' + id).remove();
		
		if ( $('inbox_input_' + id) )
			$('inbox_input_' + id).remove();
	},
	_check_form : function(form)
	{
		if ( Inbox._stop_submit == true )
		{
			Inbox._stop_submit = false;
			return false;
		}

		if ( (form.inbox_message.value).blank() )
		{
			General._error('Напиши текст на съобщението', 'inbox_text_container');
			form.inbox_message.focus();
			return false;
		}
		
		return true;
	},
	_delete : function(inboxId, isOutbox)
	{
		if ( typeof inboxId == 'undefined' || inboxId <= 0 )
			return;
			
		if ( typeof isOutbox == 'undefined' )
			isOutbox = 0;
			
		loading.show();
		new Ajax.Updater({
			success: 'inbox_list'
		}, 'inbox/_inbox_delete', {
					parameters : {'ajax' : 1, 'inboxId' : inboxId, 'p' : Inbox._p, 'o' : isOutbox},					
					onComplete : function()
					{
						loading.hide();
						General._success('Съобщението е изтрито');						
					},
					onFailure : function(res) {
						General.ajaxError(res.status);
					}
			});
	return false;
	},
	_reply : function(form, inboxId)
	{
		if ( typeof inboxId == 'undefined' || inboxId <= 0 )
			return;
			
		if ( (form.inbox_reply.value).blank() )
		{
			General._error('Напиши текст на съобщението', 'inbox_reply_container');
			form.inbox_reply.focus();
			return false;
		}
			
		loading.show();
		form.inbox_reply.disabled = true;
		new Ajax.Updater({
			success: 'reply_container'
		}, 'inbox/_inbox_reply', {
					parameters : {'ajax' : 1, 'inboxId' : inboxId, 'message' : form.inbox_reply.value, 'attach_url' : form.attach_url.value},
					insertion: Insertion.Bottom,
					onComplete : function()
					{
						loading.hide();
						
						form.inbox_reply.value = '';
						form.attach_url.value = '';
						form.inbox_reply.disabled = false;	
						$('attach_preview').hide().update('');
						
						total_images = 0;
					},
					onFailure : function(res) {
						General.ajaxError(res.status);
					}
			});
	return false;
	},
	_change_status : function(el)
	{
		if ( typeof el == 'string' )
			el = $(el);
		
		var status = el.value;
		//var inputs = [];
		
		if ( status == "none" )
			return false;
			
		loading.show();
		
		var tr = $$('tr.inbox_tr');
		
		if ( status == "" || status == "all" )
		{
			tr.each(function(el)
				{
					el.getElementsByTagName('input')[0].checked = (status == "all") ?  true : false;
				}
			);
		}
		else
		{		
			tr.each(function(el)
					{
						el.getElementsByTagName('input')[0].checked = el.className.indexOf(status) != -1 ?  true : false;
					}
			);
		}
		Inbox._status_buttons();
		
		if ( status == "inbox_new_msg" || status == "" )
			$('inbox_select_action').selectedIndex = 0;
		
		loading.hide();
	},
	_inbox_action : function(action, el, isOutbox, p)
	{
		if ( el.indexOf('inbox_menu_disabled') != -1 )
			return false;
		
		if ( typeof isOutbox == 'undefined' )
			isOutbox = 0;
			
		if ( action == 'delete' && General._confirm('Сигурен ли си, че искаш да изтриеш съобщенията?', 'Inbox._inbox_action(\'' + action + '\', \'' + el + '\', ' + isOutbox + ', ' + p + ');') == false )
			return false;
		
		var tr = $$('tr.inbox_tr');
		var json = [];
		
		tr.each(function(el)
				{
					var input = el.getElementsByTagName('input')[0];
					if ( input.checked == true )
					{
						json.push(input.value);
						
						if ( action == 'unread' )
							el.removeClassName('inbox_readed_msg').addClassName('inbox_new_msg');
						else if ( action == 'read' )
							el.removeClassName('inbox_new_msg').addClassName('inbox_readed_msg');
						else if ( action == 'delete' )
							el.remove();
					}
				}
			);
		
		if ( json.length == 0 )
		{
			return false;
		}
		
		loading.show();
		new Ajax.Request('inbox/_inbox_action', {
		 	parameters : {'ajax' : 1, 'action' : action, '_id[]' : json, 'p' : p, 'o' : isOutbox},
			onComplete : function(response)
			{
				loading.hide();
				if ( action == 'delete' )
				{
					$('inbox_list').update(response.responseText);
					//var tr = $$('tr.inbox_tr');									
					//if ( tr.length == 0 )
						//Inbox._incoming(p);
				}
				else
				{
					inboxMails = $('inbox_new_mails');
					inboxMails.update(response.responseText).show();
					
					if ( (response.responseText).indexOf('(0 нови)') != -1 )
						inboxMails.hide();
				}
				Inbox._status_buttons();								
			}
		 });
		$('inbox_select_action').selectedIndex = 0;
		return false;
	},
	_incoming : function(p)
	{
		Inbox._p = p;
		loading.show();
		new Ajax.Updater({
			success: 'inbox_list'
		}, 'inbox/_inbox_incomin', {
						 	evalScripts : true,
						 	parameters : {'ajax' : 1, 'p' : p},
							onComplete : function()
							{
								loading.hide();
							},
			onFailure : function(res) {
				General.ajaxError(res.status);
			}
						 });
		return false;
	},
	_outcoming : function(p)
	{
		Inbox._p = p;
		loading.show();
		new Ajax.Updater({
			success: 'inbox_list'
		}, 'inbox/_inbox_outcomin', {
						 	evalScripts : true,
						 	parameters : {'ajax' : 1, 'p' : p},
							onComplete : function()
							{
								loading.hide();
							},
			onFailure : function(res) {
				General.ajaxError(res.status);
			}
						 });
		return false;
	},
	_status_buttons : function()
	{
		var tr = $$('tr.inbox_tr');
		var unread_disabled = true;
  		var read_disabled = true;

		tr.each(function(el)
				{
					var input = el.getElementsByTagName('input')[0];
					if ( input.checked == true )
					{						
						var status = (el.className.indexOf('inbox_new_msg') != -1 ? 'unread' : 'read');
						if ( status == 'unread' )
							read_disabled = false;
						else
							unread_disabled = false;						
					}
				}
			);
		
		var delete_disabled = read_disabled && unread_disabled;
		var span = $('inbox_buttons').getElementsByTagName('a');		
		var loop = [{l : span[0], d : unread_disabled}, {l : span[1], d : read_disabled}, {l : span[2], d : delete_disabled}];
		var loop_length = loop.length;
		for ( var i = 0; i < loop_length; i++ ) 
		{
			if ( loop[i].l )
			  loop[i].l.className = (loop[i].l.className.replace('inbox_menu_disabled', '') + (loop[i].d ? ' inbox_menu_disabled' : ''));			
		}
		
	},
	_attach_toggle_button : function(from, button)
	{
		if ( typeof button == 'string' )
			var button = $(button);
		
		if ( typeof from == 'string' )
			var from = $(from);
		
		if ( !(from.value).blank() )		
			button.removeClassName('inbox_menu_disabled');
		else
			button.addClassName('inbox_menu_disabled');
	},
	_attach_to_mail : function(from, to, a, folder)
	{
		var from = $(from);
		var to = $(to);
		
		if ( typeof folder == 'undefined' )
			folder = 'inbox';
		
		if ( typeof a == 'string' )
			a = $(a);
		
		if ( typeof uid == 'undefined' )
			uid = 1;
		
		if ( !(from.value).blank() )
			a.removeClassName('inbox_menu_disabled');
			
		if ( a.className.indexOf('inbox_menu_disabled') != -1 )
			return false;

			var ext = from.value.split('.');
			ext = '.' + ext[ext.length-1].toLowerCase().strip() + '.';
									
			if ( General._allowed_image_types.lastIndexOf(ext) == -1 )
				to.value += ' ' + from.value + ' ';
			else
			{
				if ( $('attach_url').value.indexOf(from.value) == -1 )
				{
					if ( typeof total_images == 'undefined' )
						total_images = 1;
					else if ( total_images < 3 )
						total_images += 1;
						
					if ( total_images == 3 )
					{
						General._error('Можеш по 2 снимки да прикачаш', 'inbox_attach_container');
						total_images = 2;
						from.value = '';
						a.addClassName('inbox_menu_disabled');
						return false;
					}
					
					var div = new Element('div', {'id' : 'container_remove_attach_' + uid, 'style' : 'text-align: center;'});
					div.addClassName('left image');
					var a_href = new Element('a', {'href' : from.value, 'target' : '_blank'});
					
					var src = from.value;
					
					if ( from.value.indexOf('d/' + folder + '/') != -1 )
					{
						var ext = from.value.substr(from.value.lastIndexOf('.')+1, from.value.length);
						src = from.value.replace('.' + ext, '_thumb.' + ext);
					}

					var img = new Element('img', {'src' : src, 'alt' : '', 'border' : 'none', 'style' : 'padding: 5px; width: 80px; height: 60px;'});
					var br = new Element('br');
										
					var a_remove = new Element('a', {'href' : 'javascript:void(0);', 'id' : 'remove_attach_' + uid}).update('премахни');
					
					a_href.appendChild(img);
					div.appendChild(a_href);
					div.appendChild(br);
					div.appendChild(a_remove);					
					
					new Insertion.Bottom('attach_preview', div);
					$('attach_url').value += ' ' + from.value + ' ';
					$('attach_preview').show();
										
					Event.observe('remove_attach_' + uid, 'click', function(e){Inbox._remove_attach(e);});
					uid += 1;
				}
			}
										
			to.focus();
			from.value = '';
			a.addClassName('inbox_menu_disabled');
		
	return false;
	},
	_remove_attach : function(e)
	{	
		var el_id = Event.element(e).id;
		var href = $('container_' + el_id).getElementsByTagName('a')[0].href;
		var base = document.getElementsByTagName('base')[0].href;
		href = href.replace(base, '');
		total_images -= 1;
		
		Event.stopObserving(el_id, 'click', function(e){Inbox._remove_attach(e); return false;});
				
		$('attach_url').value = $('attach_url').value.replace(href, '');
		$('container_' + el_id).remove();
		
	return false;
	},
	_check_for_new_mails : function()
	{
		new Ajax.Updater({
			success: 'inbox_new_mails'
		}, 'inbox/_check_for_new_mails', {
						 	parameters : {'ajax' : 1, 'check' : 1}
						 });
	},
	_synchronyze : function(inboxId, outbox)
	{
		if ( typeof inboxId == 'undefined' || inboxId <= 0 )
			return;
			
		if ( typeof outbox == 'undefined' )
			outbox = 0;
			
		new PeriodicalExecuter(function(){new Ajax.Request('inbox/_synchronyze',{
						 	parameters : {'ajax' : 1, 'inboxId' : inboxId, 'o' : outbox},
							onComplete : function(response)
							{
								if ( response.responseText != '' )
								{
									$('reply_container').update(response.responseText);
									
									if ( Inbox._disableSounds == 0 )
									{
										var so = new SWFObject("swf/plim.swf", "newmsg", "1", "1", "8");
   										so.write("new_msg");
									}
								}
								Inbox._check_for_new_mails();
							}
						 })}, 10);
	},
	_disable_inbox_sounds : function(el)
	{
		var checked = el.checked ? 1 : 0;
		
		new Ajax.Request('inbox/_disable_inbox_sounds', {
				parameters : {'ajax' : 1, 'checked' : checked},
				onComplete : function()
				{
					Inbox._disableSounds = checked;	
				}
						 });
	}
}

var City = {
	_showCityBalloon : function() {
		var city = $('city');
		var cityBalloon = $('cityBalloon');
		cityBalloon.show();
		var _c = city.getDimensions();		
		
		var box = cityBalloon.select('.box');
		var _bx = box[0].getDimensions();
		
		var l = (_c.width - _bx.width)/2;
		var t = (_c.height - _bx.height)/2;
		
		cityBalloon.setStyle({
			left : l + 'px',
			top : t + 'px',
			width : _bx.width + 'px'
		});
	},
	_closeCityBalloon : function() {
		var cityBalloon = $('cityBalloon');
		cityBalloon.update('');
		cityBalloon.hide();
	},
	_school : function(){
		if ( General._ajaxWorking == true )
			return;
		
		General._ajaxWorking = true;		
		loading.show();		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_school', {
				parameters : {'ajax' : 1},					
				onComplete : function()
				{
					General._ajaxWorking = false;
					loading.hide();
					City._showCityBalloon();
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});			
	},
	
	_sendToSchool : function(fastSchool){
		if ( General._ajaxWorking == true )
			return;
		
		var fs = fastSchool.getValue();
		
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Request('profile/_sendToSchool', {
				parameters : {'ajax' : 1, 'fastSchool' : (fs == null ? 0 : 1)},					
				onComplete : function(response)
				{						
					General._ajaxWorking = false;
					loading.hide();
					var json = (response.responseText).evalJSON();
					
					if (json.userClever) {
						$('userClever').update(json.userClever);
					}
					
					if (json.lastDate) {
						$('lastDate').update(json.lastDate);
					}
					
					if ( typeof json.userCredits != 'undefined' ) {
						$('userCredits').update(json.userCredits);
					}
					
					if (json.Success) {
						General._success(json.Success, 'actionButton');
					}
					else if (json.Error) {
						General._error(json.Error, 'actionButton');
					}
				}
		});			
	},
	
	_ticket: function(){
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_ticket', {
				parameters : {'ajax' : 1},	
				evalScripts : true,				
				onComplete : function()
				{		
					General._ajaxWorking = false;									
					loading.hide();										
					City._showCityBalloon();
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});	
	},
	
	_ticketWinners: function(p){
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_ticketWinners', {
				parameters : {'ajax' : 1, 'p' : p},	
				evalScripts : true,				
				onComplete : function()
				{		
					General._ajaxWorking = false;									
					loading.hide();
					City._showCityBalloon();
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});	
	},
	
	_bank: function(success) {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
		
		loading.show();
		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_bank', {
				parameters : {'ajax' : 1},	
				evalScripts : true,				
				onComplete : function()
				{						
					General._ajaxWorking = false;					
					loading.hide();
					City._showCityBalloon();
					
					if (success) {
						General._success(success, 'actionButton');
					}
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});	
	},
	
	_bank_loan: function(form) {
		
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
		
		var money = form.loanMoney.value;
		var period = form.loanPeriod.value;
		
		loading.show();		
		new Ajax.Request('profile/_bankLoan', {
				parameters : {'ajax' : 1, 'money' : money, 'period' : period},					
				onComplete : function(response)
				{						
					General._ajaxWorking = false;					
					loading.hide();
					var json = (response.responseText).evalJSON();
									
					if ( typeof json.userMoney != 'undefined' ){
						$('userMoney').update(json.userMoney);
					}
					
					if (json.Success) {												
						City._bank(json.Success);
					}
					else if (json.Error) {
						General._error(json.Error, 'actionButton');
					}
				}
		});	
		
		return false;
	},
	
	_bank_loan_pay: function(form) {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
		
		var money = form.payMoney.value;
				
		loading.show();		
		new Ajax.Request('profile/_bankLoanPay', {
				parameters : {'ajax' : 1, 'money' : money},					
				onComplete : function(response)
				{						
					General._ajaxWorking = false;
					
					loading.hide();
					var json = (response.responseText).evalJSON();
									
					if ( typeof json.userMoney != 'undefined' ){
						$('userMoney').update(json.userMoney);
					}
					
					if (json.Success) {												
						City._bank(json.Success);
					}
					else if (json.Error) {
						General._error(json.Error, 'actionButton');
					}
				}
		});	
		
		return false;
	},
	
	_bank_deposit: function(form) {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
		
		var money = form.depositMoney.value;
				
		loading.show();		
		new Ajax.Request('profile/_bankDeposit', {
			parameters : {'ajax' : 1, 'money' : money},					
			onComplete : function(response)
			{						
				General._ajaxWorking = false;
				
				loading.hide();
				var json = (response.responseText).evalJSON();
								
				if ( typeof json.userMoney != 'undefined' ){
					$('userMoney').update(json.userMoney);
				}
				
				if (json.Success) {												
					City._bank(json.Success);
				}
				else if (json.Error) {
					General._error(json.Error, 'actionButton');
				}
			}
		});	
		
		return false;
	},
	
	_factory: function(){
		if ( General._ajaxWorking == true )
			return;
		
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_factory', {
				parameters : {'ajax' : 1},	
				evalScripts : true,				
				onComplete : function()
				{						
					General._ajaxWorking = false;					
					loading.hide();
					City._showCityBalloon();
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});	
	},
	
	_sendToFactory: function(){
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
		
		loading.show();		
		new Ajax.Request('profile/_sendToFactory', {
				parameters : {'ajax' : 1},					
				onComplete : function(response)
				{						
					General._ajaxWorking = false;
					
					loading.hide();
					var json = (response.responseText).evalJSON();
														
					if (json.lastDate) {
						$('lastDate').update(json.lastDate);
					}
					
					if (json.nextDate) {
						$('nextDate').update(json.nextDate);
					}
					
					if ( typeof json.userMoney != 'undefined' ){
						$('userMoney').update(json.userMoney);
					}
					
					if (json.Success) {
						General._success(json.Success, 'actionButton');
					}
					else if (json.Error) {
						General._error(json.Error, 'actionButton');
					}
				}
		});			
	},
	
	_hospital: function(cure){
		if ( General._ajaxWorking == true )
			return;
		
		General._ajaxWorking = true;			
		loading.show();	
		
		if ( typeof cure == 'undefined' ) {
			cure = 0;
		}
			
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_hospital', {
				parameters : {'ajax' : 1, 'cure' : cure},	
				evalScripts : true,				
				onComplete : function()
				{		
					General._ajaxWorking = false;									
					loading.hide();
					City._showCityBalloon();
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});
	},
		
	_place: function(p, section){
		if ( General._ajaxWorking == true )
			return;
		
		General._ajaxWorking = true;
		
		var url = 'profile/_place';
		var params = {'ajax' : 1, 'p' : p};
		
		if ( typeof section != 'undefined' ) {
			url = section.url + '/_place';
			
			if ( section.p ) {
				Object.extend(params, section.p);
			}
		}
			
		loading.show();		
		new Ajax.Updater({
			success: 'placePostContainer'
		}, url, {
				parameters : params,	
				evalScripts : true,				
				onComplete : function()
				{		
					General._ajaxWorking = false;
									
					loading.hide();
					$('placeBody').scrollTo();
					General._fixIE();
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});
	},
	
	_limitText: function(limitField, limitCount, limitNum) {
		if (limitField.value.length > limitNum) {
			limitField.value = limitField.value.substring(0, limitNum);
		} else {
			limitCount.value = limitNum - limitField.value.length;
		}
	},
	_check_post : function(form, p, section)
	{
		if ( (form.placeText.value).blank() )
		{
			General._error('Напиши текст към съобщението', 'placeForm');
			form.placeText.focus();
			return false;
		}
		
		form.submitContent.disabled = true;
		
		var url = 'profile/_placePost';
		var params = {'ajax' : 1, 'placeText' : (form.placeText.value).escapeHTML()};
		
		if ( typeof section != 'undefined' ) {
			url = section.url + '/_placePost';
			
			if ( section.p ) {
				Object.extend(params, section.p);
			}
		}
		
		loading.show();
		new Ajax.Request(url, {
				parameters : params,
				evalScripts : true,
				onComplete : function(response)
				{										
					loading.hide();
					
					form.submitContent.disabled = false;
					form.placeText.value = '';					
					form.countdown.value = 140;					
										
					if ( !(response.responseText).blank() )
					{					
						$('placePostContainer').update(response.responseText);
						General._success('Съобщението е публикувано', 'placeForm');
						General._fixIE();
					}					
				}
		});
		
	return false;
	},
	
	_post_delete: function(contentId, section){
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
		
		var url = 'profile/_placePostDelete';
		var params = {'ajax' : 1, 'contentId' : contentId};
		
		if ( typeof section != 'undefined' ) {
			url = section.url + '/_placePostDelete';
			
			if ( section.p ) {
				Object.extend(params, section.p);
			}
		}
			
		loading.show();
		new Ajax.Request(url, {
				parameters : params,
				evalScripts : true,
				onComplete : function(response)
				{
					General._ajaxWorking = false;
					
					loading.hide();
										
					$('placePostContainer').update(response.responseText);
					General._success('Съобщението е изтрито', 'placeForm');		
					General._fixIE();								
				}
		});
	},
	
	_post_edit : function(contentId)
	{
		if ( !$('contentForm' + contentId) )
			return false;
			
		$('contentForm' + contentId).toggle();
		$('contentText' + contentId).toggle();
		
		if ($('contentForm' + contentId).visible()) {
			$('limitedtextarea2').focus();
		}
	},
	
	_post_edit_proccess : function(text, contentId, section)
	{		
		if ( text.blank() )
		{			
			$('limitedtextarea2').focus();
			return false;
		}
		
		if ( General._ajaxWorking == true )
			return;
		
		General._ajaxWorking = true;
		
		var url = 'profile/_placePostEdit';
		var params = {'ajax' : 1, 'placeText' : text.escapeHTML(), 'contentId' : contentId};
		
		if ( typeof section != 'undefined' ) {
			url = section.url + '/_placePostEdit';
			
			if ( section.p ) {
				Object.extend(params, section.p);
			}
		}
		
		loading.show();
		new Ajax.Request(url, {
				parameters : params,
				evalScripts : true,
				onComplete : function(response)
				{
					General._ajaxWorking = false;
					
					loading.hide();										
					$('placePostContainer').update(response.responseText);
					General._fixIE();
				}
		});
	},
	
	_comments : function(id, p, section)
	{
		
		if ( typeof p == 'undefined' )
			p = 0;			
		
		var ajaxComId = $('ajax_comments_' + id) || false;
		
		if ( ajaxComId )
		{				
			ajaxComId.remove();
		}
		
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
		
		var url = 'profile/_placeComments';
		var params = {'ajax' : 1, 'contentId' : id, 'p' : p};
		
		if ( typeof section != 'undefined' ) {
			url = section.url + '/_placeComments';
			
			if ( section.p ) {
				Object.extend(params, section.p);
			}
		}
	
		loading.show();
		new Ajax.Updater({
			success: 'placePostContainer'
		}, url, {
					parameters : params,
					insertion : Insertion.After,
					evalScripts : true,
					onComplete : function()
					{	
						General._ajaxWorking = false;
						
						loading.hide();
							
						var textareaComId = $('textarea_comment_' + id) || '';
												
						if (textareaComId && textareaComId.visible()) {
							$(textareaComId).focus();
						}	
						General._fixIE();				
					},
					onFailure : function(res) {
						General.ajaxError(res.status);
					}
		});
	},
	_comments_submit : function(form, section)
	{			
		var id = parseInt(form.contentId.value);
		
		if ( (form.comment.value).blank() )
			General._error('Напиши текст към коментара.', 'submitComment_' + id);
		else
		{
			if ( General._ajaxWorking == true )
				return false;
			
			General._ajaxWorking = true;
		
			form.submitComment.disabled = true;
			
			var url = 'profile/_placeCommentsSubmit';
			var params = {'ajax' : 1, 'text' : (form.comment.value), 'contentId' : id};
			
			if ( typeof section != 'undefined' ) {
				url = section.url + '/_placeCommentsSubmit';
				
				if ( section.p ) {
					Object.extend(params, section.p);
				}
			}
			
			loading.show();
			new Ajax.Request(url, {
					parameters : params,
					evalScripts : true,
					onComplete : function()
					{
						General._ajaxWorking = false;
						loading.hide();
						
						form.submitComment.disabled = false;
						City._comments(id, 0, section);
					}
			});
		}
	return false;
	},
	_comments_edit_submit : function(form, section)
	{
		var id = parseInt(form.contentIdEdit.value);
		var comId = parseInt(form.commentIdEdit.value);
		
		if ( (form.comment_edit.value).blank() )
			General._error('Напиши текст към коментара.', 'submitCommentEdit_' + id);
		else
		{
			if ( General._ajaxWorking == true )
				return;
			
			General._ajaxWorking = true;
		
			form.submitCommentEdit.disabled = true;
			
			var url = 'profile/_placeCommentsEdit';
			var params = {'ajax' : 1, 'text' : (form.comment_edit.value), 'contentId' : id, 'comId' : comId};
			
			if ( typeof section != 'undefined' ) {
				url = section.url + '/_placeCommentsEdit';
				
				if ( section.p ) {
					Object.extend(params, section.p);
				}
			}
			
			loading.show();
			new Ajax.Updater({
				success: 'contentText' + comId
			}, url, {
					parameters : params,
					evalScripts : true,
					onComplete : function()
					{
						General._ajaxWorking = false;
						loading.hide();
						
						form.submitCommentEdit.disabled = false;
						City._comments_edit(comId, id);
						
						General._fixIE();
					},
					onFailure : function(res) {
						General.ajaxError(res.status);
					}
			});
		}
	return false;
	},
	_comments_delete : function(comId, id, p, section)
	{
		if ( General._ajaxWorking == true )
			return;
		
		General._ajaxWorking = true;
		
		if ( typeof p == 'undefined' )
			p = 0;
		
		var url = 'profile/_placeCommentsDelete';
		var params = {'ajax' : 1, 'id' : comId};
		
		if ( typeof section != 'undefined' ) {
			url = section.url + '/_placeCommentsDelete';
			
			if ( section.p ) {
				Object.extend(params, section.p);
			}
		}
		
		loading.show();
		new Ajax.Request(url, {
					parameters : params,
					evalScripts : true,
					onComplete : function()
					{
						General._ajaxWorking = false;
						loading.hide();
						General._comments(id, p);
					}
		});
	},
	_comments_edit : function(comId, id)
	{
		$('edit_comment_' + comId).toggle();
		$('contentText' + comId).toggle();
		
		if ( $('edit_comment_' + comId).visible() )
			$('comment_edit_' + comId).focus();
	},
	
	_market: function(){
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_market', {
				parameters : {'ajax' : 1},	
				evalScripts : true,				
				onComplete : function()
				{	
					General._ajaxWorking = false;
							
					loading.hide();
					City._showCityBalloon();					
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});
	},
	
	_marketList : function(type, p, section){
		if ( General._ajaxWorking == true )
			return;
		
		General._ajaxWorking = true;
		
		var url = 'profile/_marketList';
		var params = {'ajax' : 1, 'type' : type, 'p' : p};
		
		if ( typeof section != 'undefined' ) {
			url = section.url + '/_marketList';
			
			if ( section.p ) {
				Object.extend(params, section.p);
			}
		}
		
		loading.show();		
		new Ajax.Updater({
			success: 'marketList'
		}, url, {
				parameters : params,	
				evalScripts : true,
				onComplete : function()
				{			
					General._ajaxWorking = false;								
					loading.hide();				
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});
	},
	
	_marketMy: function() {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_marketMy', {
				parameters : {'ajax' : 1},	
				evalScripts : true,				
				onComplete : function()
				{			
					General._ajaxWorking = false;
								
					loading.hide();
					City._showCityBalloon();
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});
	},
	
	_wIds : [],
	_ids : [],
	els : 1,
	
	_confirmSell : function(id, p, p2)
	{
		$('pricingId').value = id;
		$('p').value = p;
		$('p2').value = p2;
		$('pricing').show();
		$('pricingInput').focus();
	},
	
	_cancelSell : function()
	{
		$('pricingId').value = 0;
		$('p').value = 0;
		$('p2').value = 0;
		$('pricing').hide();
	},
	_marketListDraggables : [],
		
	removeDraggables : function()
	{
		var l = City._marketListDraggables.length;
		for ( var i = 0; i < l; i++ )
		{
			City._marketListDraggables[i].destroy();			
		}
		City._marketListDraggables = [];
	},
	
	_setForSell : function(id, price, p, p2)
	{		
		var price = parseInt(price);
		
		if ( isNaN(price) ) {
			price = 0;
		}
		
		if ( price <= 0 ) {
			General._error('Сложи цена на стоката по-голяма от нула.', 'pricingMsgs');
		return false;
		}

		if (General._ajaxWorking == true) {
			return;
		}
		
		City.removeDraggables();
		
		General._ajaxWorking = true;
		loading.show();
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_marketSetForSell', {
					parameters : {'ajax' : 1, 'id' : parseInt(id), 'price' : price, 'p' : parseInt(p), 'p2' : parseInt(p2)},
					evalScripts : true,
					onComplete : function()
					{
						General._ajaxWorking = false;						
						loading.hide();
					},
					onFailure : function(res) {
						General.ajaxError(res.status);
					}
		});
	},
	
	_removeFromSell : function(id, p, p2)
	{
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
		
		City.removeDraggables();
				
		loading.show();
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_marketRemoveFromSell', {
					parameters : {'ajax' : 1, 'id' : parseInt(id), 'p' : parseInt(p), 'p2' : parseInt(p2)},
					evalScripts : true,
					onComplete : function()
					{
						General._ajaxWorking = false;						
						loading.hide();
					},
					onFailure : function(res) {
						General.ajaxError(res.status);
					}
		});
	},
	
	_marketBuy : function(mId, type, section)
	{
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
		
		var p = $('marketPage').value;
		var url = 'profile/_marketBuy';
		var params = {'ajax' : 1, 'mId' : parseInt(mId), 'type' : type, 'p' : parseInt(p)};
		
		if ( typeof section != 'undefined' ) {
			url = section.url + '/_marketBuy';
			
			if ( section.p ) {
				Object.extend(params, section.p);
			}
		}
			
		loading.show();
		
		new Ajax.Request(url, {
					parameters : params,
					evalScripts : true,
					onComplete : function(response)
					{
						General._ajaxWorking = false;
						
						loading.hide();
						
						var json = (response.responseText).evalJSON();
												
						if ( typeof json[0].html != 'undefined' )
						{							
							$('marketList').update(json[0].html);							
						}
						
						if ( json[0].error )
						{
							General._error(json[0].error, 'marketList', false, true, true);
						}
						
						if ( typeof json[0].userMoney != 'undefined' )
						{
							$('userMoney').update(json[0].userMoney);
						}
												
						if ( json[0].success )
						{
							General._success(json[0].success, 'marketList', true, true);
						}
					}
		});
	},
	
	_stage : function()
	{
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_stage', {
				parameters : {'ajax' : 1},	
				evalScripts : true,				
				onComplete : function()
				{	
					General._ajaxWorking = false;
							
					loading.hide();
					City._showCityBalloon();					
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});
	},
	
	_married : function(p)
	{
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'profile/_married', {
				parameters : {'ajax' : 1, 'p' : p},	
				evalScripts : true,				
				onComplete : function()
				{	
					General._ajaxWorking = false;
							
					loading.hide();
					City._showCityBalloon();					
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});
	},
	
	_parseMemberData : function(data) {
		
		if ( data.companyMembersTotal ) {
			$('companyMembersTotal').update(data.companyMembersTotal);
		}
		
		if ( data.companyMembersList ) {
			$('companyMembersList').update(data.companyMembersList);
		}
		
		if ( data.companyMembersNewList ) {
			$('companyMembersNewList').update(data.companyMembersNewList);
		}
		
		if ( data.error )
		{
			General._error(data.error, 'companiesContainer', false, true, true);
			$('companiesContainer').scrollTo();
		}
		
		if ( data.success )
		{
			General._success(data.success, 'companiesContainer', true, true);
			$('companiesContainer').scrollTo();
		}
		
		if ( typeof data.userMoney != 'undefined' ) {
			$('userMoney').update(data.userMoney);
		}
		
		if ( typeof data.userCredits != 'undefined' ) {
			$('userCredits').update(data.userCredits);
		}
	},
	
	_companies : function() {
		if ( General._ajaxWorking == true )
			return;
		
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'companies/_index', {
				parameters : {'ajax' : 1},	
				evalScripts : true,				
				onComplete : function()
				{						
					General._ajaxWorking = false;					
					loading.hide();
					City._showCityBalloon();
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});
	},
	
	_companiesAcceptAllNewMembers : function(url) {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Request('companies/_acceptAllNewMembers', {
				parameters : {'ajax' : 1, 'url' : url},	
				evalScripts : true,				
				onComplete : function(response)
				{	
					General._ajaxWorking = false;
					loading.hide();
					
					var json = (response.responseText).evalJSON();
					
					City._parseMemberData(json);
				}
		});
	},
	
	_companiesDenyAllNewMembers : function(url) {
		if ( General._ajaxWorking == true )
			return;
			
		if (General._confirm('Сигурен ли си, че искаш да отхвърлиш всички нови членове?', 'City._companiesDenyAllNewMembers(\'' + url + '\')') == false) {
			return false;
		}
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Request('companies/_denyAllNewMembers', {
				parameters : {'ajax' : 1, 'url' : url},	
				evalScripts : true,				
				onComplete : function(response)
				{	
					General._ajaxWorking = false;
					loading.hide();
					
					var json = (response.responseText).evalJSON();
					
					City._parseMemberData(json);
				}
		});
	},
	
	_companiesAcceptNewMember : function(url, user) {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Request('companies/_acceptMember', {
				parameters : {'ajax' : 1, 'url' : url, 'user' : user},	
				evalScripts : true,				
				onComplete : function(response)
				{	
					General._ajaxWorking = false;
					loading.hide();
					
					var json = (response.responseText).evalJSON();
					
					City._parseMemberData(json);
				}
		});
	},
	
	_companiesDenyNewMember : function(url, user) {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Request('companies/_denyMember', {
				parameters : {'ajax' : 1, 'url' : url, 'user' : user},	
				evalScripts : true,				
				onComplete : function(response)
				{	
					General._ajaxWorking = false;
					loading.hide();
					
					var json = (response.responseText).evalJSON();
					
					City._parseMemberData(json);
				}
		});
	},
	
	_companiesMakeViceOwner : function(url, user) {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Request('companies/_changeViceOwner', {
				parameters : {'ajax' : 1, 'url' : url, 'user' : user},	
				evalScripts : true,				
				onComplete : function(response)
				{	
					General._ajaxWorking = false;
					loading.hide();
					
					var json = (response.responseText).evalJSON();
					
					City._parseMemberData(json);
				}
		});
	},
	
	_companiesRemoveViceOwner : function(url, user) {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
			
		loading.show();		
		new Ajax.Request('companies/_fireViceOwner', {
				parameters : {'ajax' : 1, 'url' : url, 'user' : user},	
				evalScripts : true,				
				onComplete : function(response)
				{	
					General._ajaxWorking = false;
					loading.hide();
					
					var json = (response.responseText).evalJSON();
					
					City._parseMemberData(json);
				}
		});
	},
	
	_companiesSendMoney : function(url, user, money, toOwner) {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
		
		if ( typeof toOwner == 'undefined' ) {
			toOwner = false;
		}
			
		loading.show();		
		new Ajax.Request('companies/_sendMoney', {
				parameters : {'ajax' : 1, 'url' : url, 'user' : user, 'money' : parseInt(money.value), 'toOwner' : toOwner},	
				evalScripts : true,				
				onComplete : function(response)
				{	
					General._ajaxWorking = false;
					loading.hide();
					
					var json = (response.responseText).evalJSON();
					
					money.value = '';
					$('companySendMoneyTo' + user).hide();
					
					City._parseMemberData(json);
				}
		});
	},
	
	_companiesList : function(p) {
		if ( General._ajaxWorking == true )
			return;
			
		General._ajaxWorking = true;
					
		loading.show();		
		new Ajax.Updater({
			success: 'cityBalloon'
		}, 'companies/_companiesList', {
				parameters : {'ajax' : 1, 'p' : p},	
				evalScripts : true,				
				onComplete : function(response)
				{	
					General._ajaxWorking = false;
					loading.hide();
					City._showCityBalloon();
				},
				onFailure : function(res) {
					General.ajaxError(res.status);
				}
		});
	}
}

Scroll = Class.create({
	initialize : function(options)
	{					
		this.options = {
			leftButton : 'leftScrollButton',
			rightButton : 'rightScrollButton',
			elements : ((City._wIds.length)/2),
			elementsLength : City._wIds.length,
			scrollContent : 'scrollContent',
			pageContainer : 'smallPageContainer',
			width : 310,					
			currentPosition : 1,
			elementsToShow : 3,
			moving : false
		};
		
		Object.extend(this.options, options || { });	
																					
		this.options.elements = Math.round(this.options.elements);
		
		if ( this.options.elements < this.options.elementsToShow )
		{
			return false;
		}

		this.lBtn = $(this.options.leftButton);
		this.rBtn = $(this.options.rightButton);

		if ( this.options.elements >= this.options.elementsToShow )
		{
			$(this.lBtn.parentNode.id).show();
			$(this.rBtn.parentNode.id).show();
		}
		
		this.showPages();
		
		Event.observe(this.lBtn, 'click', this.clk.bindAsEventListener(this));
		Event.observe(this.rBtn, 'click', this.clk.bindAsEventListener(this));
	},
	showPages : function()
	{
		var div = new Element('div');
		
		for ( var i = 1; i < this.options.elements; i++ )
		{
			var subDiv = new Element('div', {'id' : 'smallPageId' + this.options.pageContainer + i});
			subDiv.addClassName('smallPageBtn' + (i == 1 ? ' smallPageBtnSelected' : ''));
			//Event.observe(subDiv, 'click', this.listenPages.bindAsEventListener(this, i));
			div.appendChild(subDiv);
		}
		
		$(this.options.pageContainer).update(div);												
	},
	listenPages : function(e, i){
		this.goToPage(i, true);
	},
	changePages : function()
	{
		$$('#' + this.options.pageContainer + ' .smallPageBtn').each(function(el){							
			el.removeClassName('smallPageBtnSelected');
		});
		
		if ($('smallPageId' + this.options.pageContainer + this.options.currentPosition)) {
			$('smallPageId' + this.options.pageContainer + this.options.currentPosition).addClassName('smallPageBtnSelected');
		}
	},
	goToPage : function(p, animate)
	{
		this.options.currentPosition = Math.round(p);
		
		if ( this.options.currentPosition > this.options.elements )
		{
			this.options.currentPosition = this.options.elements - this.options.currentPosition;
		}
		
		if ( animate == false )
		{
			$(this.options.scrollContent).setStyle({'left' : -this.options.width*(this.options.currentPosition-1) + 'px'});
		}
		else
		{
			this.options.moving = true;
			$(this.options.scrollContent).setStyle({'left' : 0});
			
			new Effect.Move(this.options.scrollContent, {x : -this.options.width*(this.options.currentPosition-1), y : 0, afterFinish : this.stopMoving.bind(this)});
		}
		this.changePages();
		this.buttons();
	},
	stopMoving : function()
	{
		this.options.moving = false;
	},					
	clk : function(e)
	{	
	var el = Event.element(e);	
	var where = (el.id).indexOf('left') != -1 ? 'left' : 'right';
	
		if ( where == 'left' )
		{
			if ( this.options.currentPosition == 1 || this.options.moving == true )
			{
				return false;
			}
			
			this.options.moving = true;
			new Effect.Move(this.options.scrollContent, {x : this.options.width, y : 0, afterFinish : this.stopMoving.bind(this)});
			this.options.currentPosition--;
		}
		else
		{
			if ( this.options.currentPosition == (this.options.elements-1) || this.options.moving == true )
			{
				return false;
			}
			
			this.options.moving = true;
			new Effect.Move(this.options.scrollContent, {x : -this.options.width, y : 0, afterFinish : this.stopMoving.bind(this)});
			this.options.currentPosition++;
		}
			
		this.changePages();
		this.buttons();
	},
	buttons: function(){
		if ( this.options.currentPosition == 1 )
		{
			this.lBtn.addClassName('wdbDisabled');
		}
		else
		{
			this.lBtn.removeClassName('wdbDisabled');
		}
		
		if ( this.options.currentPosition == (this.options.elements-1) )
		{
			this.rBtn.addClassName('wdbDisabled');
		}
		else
		{
			this.rBtn.removeClassName('wdbDisabled');
		}
	}
});

document.observe("dom:loaded", function() {
	loading = $('loading');
	confirm = $('confirm');
	hidden = $('hidden');
	_e();
});
