var selectInput = new Class
(
	{
		Implements: Options,
		
    options: 
    {
    },
    
		initialize: function(className, options)
		{
			$$('select.'+className).each(function(item)
			{
				item.addEvent('change',function(event)
				{
					this.addInput(item);
				}.bind(this));
			}.bind(this));
		},
		
		addInput: function(item)
		{
			if (item.value.toLowerCase().trim()=='-input-')
			{
				if ($defined(item.getNext('input.textinput')))
				{
					item.getNext('input.textinput').setStyle('display','inline');
				}
				else
				{
					new Element('input',{type:'text',name:item.get('name')+'Text'})
						.addClass('textinput')
						.setStyle('margin-left','10px')
						.inject(item,'after')
						.focus();
				}
			}
			else
			{
				if ($defined(item.getNext('input.textinput')))
				{
					item.getNext('input.textinput').setStyle('display','none');
				}	
			}
		}
	}
);

var teaxtareaSize = new Class
(
	{
		Implements: Options,
		
    options: 
    {
    	maxLength: 10000,
    	showCount: true,
    	countClass: 'count',
    	allowedSymbols: ['backspace','up', 'down', 'left', 'right']
    },
    
		initialize: function(className, options)
		{
			this.setOptions(options);
			
			$$('.'+className).each(function(item)
			{
				this.showCounter(item,true);
				item.addEvent('keypress',this.countSymbols.bind(this))
			}.bind(this));
		},
		
		countSymbols: function(event)
		{
			if (event.target.value.length+1 > this.options.maxLength && !this.options.allowedSymbols.contains(event.key)) return false;
			if (this.options.showCount)
			{
				this.showCounter(event.target);
			}
		},
		
		showCounter: function(textarea,init)
		{
			var counter=textarea.getParent().getElement('.'+this.options.countClass);
			if ($defined(counter))
			{
				counter.set('html',textarea.value.length+($defined(init) ? 0 : 1)+' / '+this.options.maxLength);
			}
		}
	}
);

var getOptions = new Class
(
	{
		Implements: Options,
		
    options: 
    {
    	url: 'ajaxhtml/get_lands',
    	activeSubId: ''
    },
    
		initialize: function(mainId,subId,options)
		{
			this.setOptions(options);
			
			if (!$defined($(mainId)) || !$defined($(subId))) return;
			this.main=$(mainId);
			this.sub=$(subId)
				.setStyle('opacity','0.3')
				.set('disabled','disabled');
			
			this.main.addEvent('change',function(event)
			{
				this.loadOptions();
			}.bind(this));
			
			if ($chk(this.options.activeSubId)) this.main.fireEvent('change');
		},
		
		loadOptions: function()
		{
			value=this.main.value.trim();
			if ($chk(value))
			{
				new Request.HTML
				(
					{
						url: site_url(this.options.url),
						data: {'task':'getContent','id':value},
						method: 'post',
						update: this.sub,
						onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript)
						{
							if (this.sub.hasClass('withEmpty')) 
							{
								new Element('option',{'value':'','selected':'selected'})
									.set('html',MooTools.lang.get('text','select'))
									.inject(this.sub,'top');
							}
							this.sub.fade(1).removeProperty('disabled');
							
							if ($chk(this.options.activeSubId))
							{
								this.sub.getChildren().each(function(item)
								{
									if (item.get('value')==this.options.activeSubId) 
									{
										item.set('selected','selected');
										return;
									}
								}.bind(this));	 
							}
						}.bind(this),
						onRequest: function() 
						{
						}.bind(this),	
						onError: function()
						{	
							alert('error');
						}.bind(this)
					}
				).post();
			}
			else
			{
				this.sub.setStyle('opacity','0.3').set('disabled','disabled');
			}
		}
	}
);

var getHtml=new Class
(
	{
		Implements: Options,
		
    options: 
    {
    	url: 'ajaxhtml/get_profile_info',
    	startPage: ''
    },
		
    initialize: function(container,tabs,options)
    {
			this.setOptions(options);
			if (!$defined($(container))) return; 
			
			this.container=$(container);
			this.tabs=$$('.'+tabs);
			
			this.currentMenu=null;
			this.ajaxInProcess=false;
			
			this.options.startPage=this.getPage(this.options.startPage);
			
			this.tabs.each(function(item)
			{
				if (this.getPage(item.get('href'))==this.options.startPage)
				{
					this.showPage(item);
				}
				
				item.addEvent('click',function(event)
				{
					this.showPage(item);
				}.bind(this));
			}.bind(this));
    },
    
    getPage: function(link)
    {
    	return link.substring(link.indexOf('#')+1);
    },
    
    showPage: function(item)
    {
    	this.highlightMenu(item);
    	
    	new Request.HTML
			(
				{
					url: site_url(this.options.url),
					method: 'post',
					data: {'page':this.getPage(item.get('href'))},
					update: this.container,
					onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript)
					{
					}.bind(this),
					onRequest: function() 
					{
						this.ajaxInProcess=true;
					}.bind(this),	
					onError: function()
					{
						this.ajaxInProcess=false;
					}.bind(this)
				}
			).send();
    },
    
    highlightMenu: function(item)
    {
    	if ($defined(this.currentMenu)) this.currentMenu.removeClass('active');
   		this.currentMenu=item;
   		this.currentMenu.addClass('active');
    }
	}
);

var submitFields=new Class
(
	{
		initialize: function(container,btn,url)
    {
			if (!$defined($(container)) || !$defined($(btn)) || !$chk(url)) return;
			
			this.container=$(container);
			this.url=url;
			
			this.btnSubmit=$(btn);
			this.btnSubmit.addEvent('click',function(event)
			{
				event.stop();
				this.redirect();
			}.bind(this));
    },
    
    redirect: function()
    {
    	var fields=[];
    	var notInArray=true;
    	this.container.getElements('input, select, textarea').each(function(item)
    	{
    		notInArray=true;
    		if ((item.get('type').toLowerCase()=='checkbox' || item.get('type').toLowerCase()=='radio') && item.checked)
    		{
    			fields.each(function(field)
    			{
    				if (field.name==item.get('name'))
    				{
    					//field.values.include(item.value.replace(/\//g,'-'));
    					field.values.include(encodeURIComponent(item.value));
    					notInArray=false;
    				}
    			});
    			
    			//if (notInArray) fields.include({name: item.get('name'),values: [item.value.replace(/\//g,'-')]});
    			if (notInArray) fields.include({name: item.get('name'),values: [encodeURIComponent(item.value)]});
    		}
    		else if (!(item.get('type').toLowerCase()=='checkbox' || item.get('type').toLowerCase()=='radio') && $chk(item.value.trim())) 
    		{
    			//fields.include({name:item.get('name'),values:[item.value.replace(/\//g,'-')]});
    			fields.include({name:item.get('name'),values:[encodeURIComponent(item.value)]});
    		}
    	}.bind(this));
    	
    	var searchurl=fields.map(function(field)
    	{
    		return field.name+'/'+field.values.join('~');
    	}).join('/');
    	
    	location.href=site_url(this.url+'/'+searchurl);
    }
	}
);

var userFeed=new Class
(
	{
		Implements: Options,
		
    options: 
    {
    	containerClass: 'container',
    	feedClass: 'feed',
    	navigationClass: 'navigation',
    	btnNextClass: 'next',
    	btnPreviousClass: 'previous',
    	count: 100,
    	feedLength: 6,
    	getNextUrl: site_url('ajax/get_next_friend'),
    	userId: null,
    	newElementClass: 'userInformation',
    	shiftWidth: 110,
    	parseStatus: true,
    	addTip: false,
    	userMenuClass: null
    },
		
    initialize: function(container,options)
    {
			this.setOptions(options);
			
			if (!$defined($(container))) return;
			this.container=$(container).getElement('.'+this.options.containerClass);
			this.navigation=$(container).getElement('.'+this.options.navigationClass);
			if (!$defined(this.container) || !$defined(this.navigation)) return;
			
			if (!$defined(this.container.getFirst('.'+this.options.feedClass))) return;
			this.feed=this.container.getFirst('.'+this.options.feedClass);
			
			if (!$defined(this.navigation.getElement('.'+this.options.btnNextClass))) return;
			this.btnNext=this.navigation.getElement('.'+this.options.btnNextClass);
			
			if (!$defined(this.navigation.getElement('.'+this.options.btnPreviousClass))) return;
			this.btnPrevious=this.navigation.getElement('.'+this.options.btnPreviousClass);
			
			this.btnNext.addEvent('click',this.nextItems.bind(this));
			
			this.btnPrevious.addEvent('click',this.previousItems.bind(this));
			
			this.from=this.options.feedLength;
			this.position=0;
			this.countRight=0;
			
			this.feed.setStyle('left','0px');
			this.btnPrevious.set('disabled','disabled').getParent().setStyle('opacity','0');
			if (this.feed.getChildren().length==this.options.count) this.btnNext.set('disabled','disabled').getParent().setStyle('opacity','0');
			
			this.userMenu=null;
			if ($chk(this.options.userMenuClass))
			{
				this.userMenu=new userMenu('.'+this.options.userMenuClass);
			}
    },
    
    nextItems: function()
    {
    	if (this.feed.getStyle('width').toInt()+this.feed.getStyle('left').toInt()!=this.container.getStyle('width').toInt())
    	{
    		if ((this.feed.getStyle('width').toInt()-(this.container.getStyle('width').toInt()-this.feed.getStyle('left').toInt())==this.options.shiftWidth) && (this.from+1>=this.options.count))
	    	{
	    		this.btnNext.set('disabled','disabled').getParent().setStyle('opacity','0');	
	    	}
    		
	    	this.moveFeed('left');
	    	this.countRight--;
    	}
    	else
    	{
    		var newUser=new Element('div')
    			.addClass(this.options.newElementClass)
	    		.inject(this.feed);
	    		
	    	this.moveFeed('left',true);
	    	this.countRight++;
	    	
	    	new Request.JSON
				(
					{
						url: this.options.getNextUrl,
						method: 'post',
						data: {'act':'overLinkMenuAction','user_id': this.options.userId,'from': this.from++},
						onSuccess: function(json)
						{
							if (json.status=='OK')
							{
								newUser.set('html',json.html);
								if (this.options.parseStatus && $defined(scrollStatus))
								{
									new scrollStatus(newUser,{parseOne: true});
								}
								if ($defined(this.userMenu) && $defined(newUser.getElement('.picture')))
								{
									this.userMenu.parseItem(newUser.getElement('.picture'));
								}
								if (this.options.addTip)
								{
									var tip=newUser.getElement('.tip');
									new Tips(tip);
									var imgSrc = tip.retrieve("tip:text");
									var imgAlt = tip.retrieve("tip:title");
									tip.store("tip:text", new Element("img",{"src":imgSrc,"alt":imgAlt}));
								}
							}
							else
							{
								newUser.dispose();
								this.moveFeed('right');
								this.countRight--;
								this.from--;
							}
						}.bind(this)
					}
				).send();
				
				if (this.from>=this.options.count)
				{
					this.btnNext.set('disabled','disabled').getParent().setStyle('opacity','0');
				}
    	}
    	this.position--;
    		
    	if (this.btnPrevious.get('disabled')) 
    	{
    		this.btnPrevious.removeProperty('disabled','disabled').getParent().setStyle('opacity','1');
    	}
    },
    
    previousItems: function()
    {
    	this.moveFeed('right');
    	this.position++;
    	if (this.position==0)
    	{
    		this.btnPrevious.set('disabled','disabled').getParent().setStyle('opacity','0');
    	}
    	
    	if (this.btnNext.get('disabled')) 
    	{
    		this.btnNext.removeProperty('disabled','disabled').getParent().setStyle('opacity','1');
    	}
    },
    
    moveFeed: function(direction,changeSize)
    {
    	if ($defined(changeSize) && changeSize) this.feed.setStyle('width',this.feed.getStyle('width').toInt()+this.options.shiftWidth);
    	switch (direction)
    	{
    		case 'left':default:
    			this.feed.setStyle('left',this.feed.getStyle('left').toInt()-this.options.shiftWidth);
    			break;
    		case 'right':
    			this.feed.setStyle('left',this.feed.getStyle('left').toInt()+this.options.shiftWidth);
    			break;
    	}
    }
	}
);

var statusMessage = new Class
(
	{
		Implements: Options,
		
    options: 
    {
    	conatiner: 'pageLayout',
    	className: 'statusMessage',
    	delay: 10000
    },
    
		initialize: function(options)
		{
			this.setOptions(options);
			
			$(this.options.conatiner).getElements('.'+this.options.className).each(function(item)
			{
				var delayFunction=function(){this.closeMessage(item)};
				delayFunction.delay(this.options.delay,this);
				
				var btnClose=item.getElement('.close');
				if ($defined(btnClose))
				{
					btnClose.addEvent('click',function(event)
					{
						this.closeMessage(item);
					}.bind(this));
				}
			}.bind(this));
		},
		
		closeMessage: function(item)
		{
			var closeFx = new Fx.Tween
			(
				item,
				{
					onComplete: function()
					{
						item.dispose();
					}
				}
			).start('opacity','1','0');
		}
	}
);

function remindPassword()
{
	var value=$('txtEmail').value.trim();
	if (!$chk(value) || !value.test(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) return;
	
	new Request.JSON
	(
		{
			url: site_url('ajax/remind_password'),
			method: 'post',
			data: {'act':'remindPassword','email': value},
			onSuccess: function(json)
			{
				new Element('div')
					.addClass('validationMsg')
					.setStyles
					(
						{
							position: 'relative',
							top: 'auto',
							left: 'auto',
							margin: '10px auto'
						}
					)
					.set('html',MooTools.lang.get('msg','remindPasswordOk'))
					.inject($('txtEmail').getParent());
			}.bind(this)
		}
	).send();	
}

var wysiwygEditorOptions=
{
	actions: 'bold italic underline strikethrough | insertunorderedlist insertorderedlist indent outdent | undo redo | smiley | forecolor',
	paragraphise: false,
	semantics: false,
	cleanup: true,
	rootElement: false
};

var wysiwygEditor=new Class
(
	{
		Implements: Options,
		
    options: 
    {
			elements: 'textarea'
    },
		
    initialize: function(options)
    {
			this.setOptions(options);
			
			this.editors=[];
			
			new Asset.javascript
			(
				_config_live_site+'js/mooeditable.js',
				{
					onload: this.initEditor.bind(this)
				}
			);
			new Asset.css(_config_live_site+'css/default/mooeditable.css');
    },
    
    initEditor: function()
    {
    	if (!$defined(this.editors.getLast()))
    	{
	    	$$(this.options.elements).each(function(item)
	    	{
	    		this.editors.include
	    		(
	    			new MooEditable
		    		(
		    			item,
		    			wysiwygEditorOptions
		    		)
	    		);
	    		
	    	}.bind(this));
    	}
    }
	}
);

function blinkWindowTitle(count)
{
	if (count>0)
	{
		var period=500;
		var msg1=MooTools.lang.get('msg','newMessageTitle1');
		var msg2=MooTools.lang.get('msg','newMessageTitle2');
		var fun=function()
		{
			document.title=document.title==msg1 ? msg2 : msg1;
		};
		fun.periodical(period);
	}
}

function markCounter(elId,count)
{
	var el=$(elId);
	if ($defined(el))
	{
		var newCount=el.get('html').toInt()-count;
		el.set('html',newCount<=0 ? 0 : newCount);
		if (newCount<=0) el.getParent().removeClass('rb');
	}
}

function checkAll(el,className)
{
	state=$defined($(el).checked) ? $(el).checked : true;
	$$('input[type=checkbox].'+className).each(function(item)
	{
		item.checked=state;
	});
}

var fastMenu = new Class
({
	Implements: Options,
	
  options: 
  {
		menuItemId: 'fastMenuIcon',
		menuContainer: 'fastMenuContainer',
		getMenuUrl: 'ajax/get_fast_menu'
  },
  
	initialize: function(options)
	{
  	this.setOptions(options);
  	this.control=$(this.options.menuItemId);
  	this.container=$(this.options.menuContainer);
  	
  	if (!$defined(this.control) || !$defined(this.container))
  	{
  		return;
  	}
  	
  	this.control.addEvent('click',this.showHideMenu.bind(this));
  	
  	this.getMenu();
	},
	
	showHideMenu: function(event)
	{
		event.stop();
		this.container.toggle();
	},
	
	getMenu: function()
	{
		new Request.JSON
		(
			{
				url: site_url(this.options.getMenuUrl),
				method: 'post',
				data: {'act':'getMenu'},
				onSuccess: function(json)
				{
					if (json.status=='OK')
					{
						this.container.empty();
						this.container.set('html',json.html);
						
						if (json.open)
						{
							this.container.show();
							this.control.addClass('active');
							this.container.addClass('active');
						}
					}
				}.bind(this)
			}
		).send();	
	}
});