if (Object.isUndefined(TakTakTak)) { var TakTakTak = { } };
if (Object.isUndefined(TakTakTak.Controls)) { TakTakTak.Controls = { } };

/**
 * Flash message
 */

function hideFlash() {
	if ($('flashMessage')) {
		Effect.Fade('flashMessage');
	}
	if ($('errorMessage')) {
		Effect.Fade('errorMessage');
	}
}
document.observe('click', function() {
	hideFlash();
});


document.observe('dom:loaded', function() {
	
	$$(".error-message").each(function(el) {
		$(el).up(".item").addClassName("error");
	});
	
	setTimeout('hideFlash()', 5000);
});

TakTakTak.Controls.Flash = Class.create({
	initialize: function(message) {
		
		this.message = $('flashMessage') || null;
		
		if (!this.message) {
			this.message = new Element('div', { 'id': 'flashMessage', 'class': 'message' } );
			document.body.insert(this.message);
		}
		
		this.message.update(message);
		Effect.Appear(this.message);
		
		// setTimeout('hideFlash()', 5000);
	}
});


/**
 * Постраничный скроллинг с CTRL
 */

function NavigateThrough(evt) 
{
	if (!evt && window.event) evt = window.event;
	if (evt.ctrlKey) 
	{
		var eLink = null;
		var iKeyCode = (evt.keyCode)? evt.keyCode : (evt.which)? evt.which : null;
		if (iKeyCode) switch (iKeyCode) 
		{
			case 0x25: 
				eLink = $('PrevLink');
				break;
			case 0x27:
				eLink = $('NextLink');
				break;
		}
		if (eLink && eLink.href) 
		{
			if (evt.preventDefault) evt.preventDefault();
			document.location.href = eLink.href;
		}
	}
}

document.onkeydown = NavigateThrough;



/**
 * Всплывающий слой
 */
TakTakTak.Controls.Popup = Class.create({
	
	initialize: function(popup) {
		var e = Prototype.emptyFunction;
		this.config = Object.extend({
			afterLoad: e
		}, arguments[1] || { });
		
	    this.popup = $(popup);
		this.active = false;
		this.opener = null;
		
		this.popup.addClassName('_TakTakTakPopup');
		document.body.appendChild(this.popup.remove());
		this.closer = this.popup.down('.closer');
		
		this.initMouseEvents();
	},
	
	initMouseEvents: function() {
		Event.observe(document, 'click', this.onDocumentClick.bind(this));
		if (this.closer) {
			this.closer.observe('click', this.hide.bind(this));
		}
	},
	
	onDocumentClick: function(event) {
		if (!this.active) return;
		var el = Event.element(event);
		if (this.opener && (el == this.opener || el.up() == this.opener)) return;
		if (el == this.popup || el.up('._TakTakTakPopup') == this.popup) return;
		this.hide();
	},
	
	show: function(position) {
		if (Object.isElement(position)) {
			this.opener = position;
		}
		if (position) {
			this.move(position);
		}
		this.active = true;
		this.popup.show();
		//this.popup.appear({ duration: 0.2 });
	},
	
	hide: function() {
		this.active = false;
		this.popup.fade({ duration: 0.2 });
	},
	
	move: function(position) {
		if (Object.isArray(position)) {
			position = { left: position[0], top: position[1] };
		} else if (Object.isElement(position) || Object.isString(position)) {
			position = $(position).cumulativeOffset();
		}
		
		this.popup.setStyle({
			'left': position.left + 'px',
			'top': position.top + 'px'
		});
	}
});

/**
 * Всплывающий слой с загрузкой контента
 */
TakTakTak.Controls.AjaxPopup = Class.create(TakTakTak.Controls.Popup, {
	
	initialize: function(url) {
		var e = Prototype.emptyFunction;
		this.config = Object.extend({
			method: "get",
			parameters: { },
			afterLoad: e
		}, arguments[1] || { });
		
		this.url = url;
		this.popup = null;
		this.active = false;
		this.opener = null;
		this.loading = false;
	},
	
	load: function(position, bShow) {
		if (this.loading) return;
		this.loading = true;
		new Ajax.Request(this.url, {
			method: this.config.method || "get", 
			parameters: this.config.parameters || { },
			onSuccess: function(response) {
				this.build(response.responseText);
				this.initMouseEvents();
				this.config.afterLoad.call(this);
			 	if (bShow) this.show(position);
			 	this.loading = false;
			 }.bind(this)
		});
	},
	
	build: function(content) {
		this.popup.update(content);
		document.body.appendChild(this.popup.remove());
		this.closer = this.popup.down('.closer');
	},
	
	show: function(position) {
		if (Object.isElement(position)) {
			this.opener = position; 
		}
		if (!this.popup) {
			this.load(position, true);
			return;
		}
		if (position) {
			this.move(position);
		}
		this.active = true;
		this.popup.appear({ duration: 0.2 });
	}
});


/**
 * Добавляет в инпуты примеры значения
 */
TakTakTak.Controls.PlaceHolder = Class.create({
	
	initialize: function(element, msg, restore) {
		this.element = $(element);
		this.msg = msg;
		this.restore = restore || false;
		
		this.element.observe('focus', this.clearMsg.bind(this));

		if (this.element.form) {
			$(this.element.form).observe('submit', this.clearMsg.bind(this));
		}

		if (this.restore) {
			this.element.observe('blur', this.setMsg.bind(this));
		}

		this.setMsg();
	},
	
	setMsg: function() {
		if (!this.element.value || this.element.value == this.msg) {
			this.element.addClassName('placeholder');
			this.element.value = this.msg;
		} else {
			this.element.removeClassName('placeholder');
		}
	},
	
	clearMsg: function() {
		this.element.value = (this.element.value == this.msg) ? '' : this.element.value;
		this.element.removeClassName('placeholder');
	}
});

/**
 * Открывалка-закрывался тегов и регионов
 */
TakTakTak.Controls.FiltersExpander = Class.create({
	initialize: function() {
		
		this.tags = $('filters-content').down('.tags');
		this.regions = $('filters-content').down('.regions');
		this.tagsButton = $('show-tags-button');
		this.regionsButton = $('show-regions-button');
		
		this.duration = 0.5;
		
		this.tagsButton.observe('click', function(event) {
			if (this.tags.style.display == 'none') {
				this.hideRegions();
				this.showTags();
			} else {
				this.hideRegions();
				this.hideTags(true);
			}
			Event.stop(event);
		}.bind(this));
		
		if (this.regionsButton) {
			this.regionsButton.observe('click', function(event) {
				if (this.regions.style.display == 'none') {
					this.hideTags();
					this.showRegions();
				} else {
					this.hideTags();
					this.hideRegions(true);
				}
				Event.stop(event);
			}.bind(this));
		}
	},
	
	showTags: function() {
		this.tags.show();
		//Effect.SlideDown(this.tags, {duration: this.duration});
		this.tagsButton.removeClassName('l');
		this.tagsButton.addClassName('l-active');
	},
	hideTags: function() {
		this.tags.hide();
		//Effect.SlideUp(this.tags, {duration: this.duration});
		this.tagsButton.removeClassName('l-active');
		this.tagsButton.addClassName('l');
	},
	showRegions: function() {
		this.regions.show();
		//Effect.SlideDown(this.regions, {duration: this.duration});
		if (this.regionsButton) {
			this.regionsButton.removeClassName('r');
			this.regionsButton.addClassName('r-active');
		}
	},
	hideRegions: function(bSlide) {
		this.regions.hide();
		//Effect.SlideUp(this.regions, {duration: this.duration});
		if (this.regionsButton) {
			this.regionsButton.removeClassName('r-active');
			this.regionsButton.addClassName('r');
		}
	}
});


/**
 * Селектор тегов
 */
TakTakTak.Controls.TagSelector = Class.create({
	initialize: function(container, options) {
		
		this.container = $(container);
		
		this.options = options || {};
		this.options.onSelect = this.options.onSelect || Prototype.emptyFunction;
		
		this.options.tag = this.options.tag || 'li';
		this.options.field = this.options.field || 'tags[]';
		this.options.url = options.url || null;
		
		this.container.select(this.options.tag).each(function(item) {
			if (!item.hasClassName('disabled')) {
				new TakTakTak.Controls.TagSelectorItem(this, item);
			}
		}.bind(this));
	},
	
	updateContent: function() {
		if (!this.options.url) {
			return false;
		}
		var items = [];
		this.container.select(this.options.tag + '.active').each(function(item) {
			items.push(item.getAttribute('item_id'));
		}.bind(this));
		
		var params = {};
		if (items.length > 0) {
			params[this.options.field + '[]'] = items;
		} else {
			params[this.options.field] = '';
		}
		
		new Ajax.Updater('content', this.options.url, {
			method: 'get',
			evalScripts: true,
			parameters: params
		});
	}
});

/**
 * Селектор тегов (элемент тега)
 */
TakTakTak.Controls.TagSelectorItem = Class.create({
	initialize: function(manager, element) {
		
		this.manager = manager;
		this.element = $(element);
		
		var _manager = this.manager;
		
		this.element.observe('click', function(event) {
			this.toggleClassName('active');
			_manager.updateContent();
			_manager.options.onSelect.call(this);
			if (_manager.options.tag == 'a') {
				Event.stop(event);
			}
		});
	}
});


/**
 * Менеджер табов
 */
TakTakTak.Controls.TabsManager = Class.create({
	initialize: function(tabs, container, options) {
		
		this.tabs = $(tabs);
		this.container = $(container);
		this.options = options || {};
		
		this.items = [];
		this.current_item = null;
		
		this.tabs.select('li.tab').each(function(li) {
			this.items.push (new TakTakTak.Controls.TabItem(this, li));
		}.bind(this));
	},
	
	set: function (item) {
		if (this.current_item && this.current_item != item) {
			this.current_item.hide();
		}
		this.current_item = item;
	}
});

TakTakTak.Controls.TabItem = Class.create({
	initialize: function(manager, tab, content) {
		
		this.manager = manager;
		this.tab = tab;
		this.content = content || null;
		
		if (this.tab.down('a')) {
			this.url = this.tab.down('a').getAttribute('href');
		}
		
		this.is_active = this.tab.hasClassName('active');
		if (this.is_active) {
			this.content = this.manager.container.down('div');
			this.show();
		}
		
		this.tab.observe('click', function(e) {
			this.show();
			Event.stop(e);
		}.bind(this));
	},
	
	hide: function() {
		this.is_active = false;
		this.tab.removeClassName('active');
		if (this.content) {
			this.content.hide();
		}
	},
	
	show: function() {
		if (!this.content) {
			this.load(true);
		} else {
			this.is_active = true;
			this.tab.addClassName('active');
			this.manager.set(this);
			this.content.show();
		}
	},
	
	load: function(bShow) {
		new Ajax.Request(this.url, {
			method: 'get',
			onSuccess: function(transport) {
				this.content = new Element('div').update(transport.responseText);
				this.manager.container.insert(this.content);
				if (bShow) {
					this.show();
				}
			}.bind(this)
		});
	}
});



/**
 * Моталка туда-сюда
 */

TakTakTak.Controls.Scroll = Class.create({
	initialize: function(container, content) {
		
		this.container = $(container);
		this.content = $(content);
		
		this.speed = 0;
		this.max_speed = 5;
		
		this.init();
		
		this.container.observe('mouseover', this.onMouseOver.bindAsEventListener(this));
		this.container.observe('mouseout', this.onMouseOut.bindAsEventListener(this));
		this.container.observe('mousemove', this.onMouseMove.bindAsEventListener(this));
	},
	
	init: function() {
		this.content_width = this.content.getWidth();
		this.container_width = this.container.getWidth();
		this.container_pos = this.container.cumulativeOffset()[0];
		this.container_offset = Math.round(this.container_width / 2);
	},
	
	onMouseOver: function(event) {
		this.start();
	},
	
	onMouseOut: function(event) {
		this.stop();
	},
	
	start: function() {
		if (!this.interval) {
			this.interval = setInterval(this.scroll.bind(this), 10);
		}		
	},
	
	stop: function() {
		clearInterval(this.interval);
		this.interval = null;
		this.speed = 0;
	},
	
	onMouseMove: function(event) {
		if (!this.interval) {
			return false;
		}
		this.calcSpeed(Event.pointerX(event));
	},
	
	calcSpeed: function (mouse_pos) {
		var mouse_offset = mouse_pos - this.container_pos - this.container_offset;
		return this.speed = Math.round(mouse_offset * this.max_speed / this.container_offset);
	},
	
	scroll: function() {
		
		var pos = this.content.offsetLeft - 10 - this.speed;
		
		if (pos > 0) {
			pos = 0;
			this.stop();
		};
		
		if (pos + this.content_width < this.container_width) {
			pos = this.container_width - this.content_width;
			this.stop();
		}
		
		this.content.setStyle({
			'left': pos + 'px'
		});
	}
});

TakTakTak.Controls.AttachmentManager = Class.create({
	initialize: function(container, link, options) {
		this.container = $(container);
		this.link = $(link);
		
		this.options = options || {};
		this.options.fieldName = this.options.fieldName || 'files[]';
		
		this.container.select('li').each(function(item) {
			new TakTakTak.Controls.Attachment(this, item);
		}.bind(this));
		
		this.link.observe('click', function(e){
			if (this.container.select('li').size() > 2) {
				alert('Вы не можете прикрепить больше 3-х файлов к одному документу');
				return false;
			} else {
				new TakTakTak.Controls.Attachment(this);
				e.stop();				
			}
		}.bind(this));
		
	}
});
TakTakTak.Controls.Attachment = Class.create({
	initialize: function(manager, element) {
		this.manager = manager;
		
		this.element = element ? $(element) :
			new Element('li')
				.insert(
					new Element('div', { 'class': 'cross click'})
						.update(new Element('span'))
				)
				.insert(
					new Element('input', { 'type': 'file', 'name': this.manager.options.fieldName})
				);
		
		this.element.down('.cross').observe('click', function(e) {
			this.element.remove();
			if (this.manager.container.select('li').size() > 0) {
				this.manager.link.update('Прикрепить ещё документ');
			} else {
				this.manager.link.update('Прикрепить документ');
			}
			e.stop();
		}.bind(this));
		
		this.manager.container.insert(this.element);
		this.manager.link.update('Прикрепить ещё документ');		
	}
});



