
//--------------------------------------------------------------- SCROLLER CLASS

function scrollerClass(container, buttons, options){
	this.container	= $(container);
	this.btn_left	= $(buttons[0]);
	this.bnt_right	= $(buttons[1]);

	this.content = null;
	this.listener = null;
	this.timer = null;
	
	this.container_width = 0;
	this.content_width = 0;
	this.position = 0;

	this.options = Object.extend({
		offset: 5, delay: 100
	}, options);

	this.init = function(){
		this.content = this.container.down('div.scrollContent');
		this.listener = this.action.bindAsEventListener(this);

		$A([this.btn_left, this.bnt_right]).each(function(btn){
			Event.observe(btn, 'mouseover', this.listener);
			Event.observe(btn, 'mouseout', this.listener);
		}.bind(this));

		this.reset();
	};

	this.reset = function(){
		this.container_width = this.container.getDimensions().width;
		this.content_width = this.content.firstDescendant().getDimensions().width;
		this.position = 0;
		this.move();
	};

	this.action = function(e){
		var delta = e.element() === this.btn_left ? 1 : (e.element() === this.bnt_right ? -1 : 0);
		switch(e.type){
			case "mouseover":
			case "mousedown":
				if(this.container_width < this.content_width && delta != 0){
					this.scroll(delta);
					this.timer = setInterval(this.scroll.bind(this, Math.round(delta * this.options.offset)), this.options.delay);
				}
				break;
			case "mouseout":
			case "mouseup":
				clearInterval(this.timer)
				break;
		}
	};

	this.scroll = function(offset){
		if(offset < 0){ // right button (move left)
			this.position = Math.max(this.position + offset, this.container_width - this.content_width);
		}
		if(offset > 0){ // left button (move right)
			this.position = Math.min(this.position + offset, 0);
		}                                                                    

		this.move();
	};

	this.move = function(position){
		this.content.setStyle({marginLeft: this.position + 'px'});
	}

	Event.observe(window, 'load', this.init.bindAsEventListener(this));
	Event.observe(window, 'resize', this.reset.bindAsEventListener(this));
}

//------------------------------------------------------------------ CHART CLASS

function chartClass(mid, cid){
	this.mid = mid || null;
	this.cid = cid || null;

	this.url = '/?module=chart&media=ajax&lang=' + SITE_SETTINGS.lang;
	this.id = 'ampie';
	this.btn = null;

	this.vote = function(e, vote){
		this.btn = e.element();

		if(/yes|no|hz/i.test(vote)){
			new Ajax.Request(this.url, {
				method: 'POST',
				parameters: {action: 'do_vote', mid: this.mid, cid: this.cid, vote: vote},
				onCreate: function(){
					this.btn.disable();
				}.bind(this),
				onSuccess: function(transport){
					var text = transport.responseText;
					if(text.length > 0) alert(text.isJSON() ? text.evalJSON() : text);
				},
				onComplete: function(){
					this.loadChart();
				}.bind(this),
				onException: function(a, b){
					alert('vote error: #' + b.message);
				}
			});
		}
		else{
			alert('Unknown vote value.');
		}
	};

	this.loadChart = function(){
		new Ajax.Request(this.url, {
			method: 'POST',
			parameters: {action: 'get_data', mid: this.mid, cid: this.cid},
			onSuccess: function(transport){
				var text = transport.responseText;
				if(text.length > 0 && text.isJSON()){
					var chartElement = $(this.id);
					if(typeof chartElement != 'undefined'){
						$(this.id).setData(text.evalJSON());
					}
				}
			}.bind(this),
			onComplete: function(){
				this.btn.enable();
			}.bind(this),
			onException: function(a, b){
				alert('update error: #' + b.message);
			}
		});
	};

	if($('chart_vote_true') && $('chart_vote_false') && $('chart_vote_null')){
		Event.observe('chart_vote_true', 'click', this.vote.bindAsEventListener(this, 'yes'));
		Event.observe('chart_vote_false', 'click', this.vote.bindAsEventListener(this, 'no'));
		Event.observe('chart_vote_null', 'click', this.vote.bindAsEventListener(this, 'hz'));
	}
}

//--------------------------------------------------------------- COMMENTS CLASS

function commentsClass(mid, cid){
	this.mid = mid || null;
	this.cid = cid || null;

	this.url = '/?module=comments&media=ajax&lang=' + SITE_SETTINGS.lang;
	this.block = null;

	this.add = function(parent_id){
		var parent_id = parseInt(parent_id);
		var block = parent_id > 0 ? ("comments_formplace_" + parent_id) : "comments_formplace";
		if(this.block === null || this.block !== block){
			this.cancel();
			this.block = block;
			this.loadForm(parent_id);
		}
	};

	this.loadForm = function(parent_id){
		new Ajax.Request(this.url, {
			method: 'POST',
			parameters: {action: 'get_form', mid: this.mid, cid: this.cid, parent: parent_id},
			onSuccess: function(transport){
				var text = transport.responseText;
				if(text.length > 0 && text.isJSON()) $(this.block).update(text.evalJSON());
			}.bind(this),
			onComplete: function(){
				new Effect.BlindDown(this.block, {duration: 0.25});
				Event.observe('comments_text', 'keyup', this.charCounter);
				Event.observe('comments_text', 'change', this.charCounter);
			}.bind(this),
			onException: function(a, b){
				alert('loadForm error: #' + b.message);
			}
		});
	}

	this.send = function(){
		var parent_id = $F('comments_reply');
		var text = $F('comments_text');

		$('comments_send').disable();

		if(text.blank() == false){
			new Ajax.Request(this.url, {
				method: 'POST',
				parameters: {action: 'save_comment', mid: this.mid, cid: this.cid, parent: parent_id, text: text},
				onSuccess: function(transport){
					var text = transport.responseText;
					if(text.length > 0) alert(text.isJSON() ? text.evalJSON() : text);
				},
				onComplete: function(){
					this.cancel();
					this.loadComments();
				}.bind(this),
				onException: function(a, b){
					alert('send error: #' + b.message);
				}
			});
		}
		else{
			$('comments_send').enable();
			alert('Вы не написали комментарий.');
		}
	};

	this.admin = function(id, status){
		new Ajax.Request(this.url, {
			method: 'POST',
			parameters: {action: 'admin_comment', mid: this.mid, cid: this.cid, id: id, status: status},
			onSuccess: function(transport){
				var text = transport.responseText;
				if(text.length > 0) alert(text.isJSON() ? text.evalJSON() : text);
			},
			onComplete: function(){
				this.cancel();
				this.loadComments();
			}.bind(this),
			onException: function(a, b){
				alert('send error: #' + b.message);
			}
		});
	};

	this.loadComments = function(){
		$('comments_output_container').update();
		new Ajax.Request(this.url, {
			method: 'POST',
			parameters: {action: 'load_comments', mid: this.mid, cid: this.cid},
			onSuccess: function(transport){
				if(transport.responseText.length > 0 && transport.responseText.isJSON()){
					var content = transport.responseText.evalJSON();
					$('comments_total').update(content.total);
					$('comments_output_container').update(content.all);
				}
			},
			onComplete: function(){
				$('comments_anchor').scrollTo();
			},
			onException: function(a, b){
				alert('loadComments error: #' + b.message);
			}
		});
	};

	this.cancel = function(){
		if(typeof comments_add_form == 'object'){
			Event.stopObserving('comments_text', 'keyup', this.charCounter);
			Event.stopObserving('comments_text', 'change', this.charCounter);
			$('comments_add_form').remove();
		}
		$$('div[rel="commentsformplace"]').each(function(el){
			Element.update(el);
			Element.hide(el);
		}.bind(this));
		this.block = null;
	};

	this.charCounter = function(e){
		var count = this.value.length;
		var current = 1000 - count;
		if(count >= 1000){
			this.value = this.value.substr(0, 1000);
			current = 1000 - this.value.length;
		}
		$('comments_chars').update(current);
	};
}

//--------------------------------------------------------- FORM VALIDATOR CLASS

function formValidatorClass(form_id){
	this.form = $(form_id);
	this.isValid = true;

	this.icons = {
		loading: '/images/validator/loading.gif',
		error: '/images/validator/error.gif',
		success: '/images/validator/success.gif'
	};
	
	this.validators = {
		'required': {
			message: SITE_SETTINGS.lang == 'ua' ? 'Це поле не заповнено.' : (SITE_SETTINGS.lang == 'en' ? 'Empty field' : 'Это поле не заполнено'),
			func: function(el){ return !$F(el).blank(); }
		},
		'email': {
			message: SITE_SETTINGS.lang == 'ua' ? 'Введіть правильний e-mail.' : (SITE_SETTINGS.lang == 'en' ? 'Incorrect e-mail' : 'Введите правильный e-mail. К примеру name@youdomain.com'),
			func: function(el){ return $F(el).blank() || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test($F(el)); }
		},
		'url': {
			message: SITE_SETTINGS.lang == 'ua' ? 'Введіть правильний URL' : (SITE_SETTINGS.lang == 'en' ? 'Incorrect URL' : 'Введите правильный URL'),
			func: function(el){ return $F(el).blank() || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test($F(el)); }
		},
		'login': {
			message: SITE_SETTINGS.lang == 'ua' ? 'Невірно введено логін' : (SITE_SETTINGS.lang == 'en' ? 'Incorrect login' : 'Неверно введен логин'),
			func: function(el){ return $F(el).blank() || /^[^\s\d]{1,}[A-Z-a-zА-Я-а-я0-9_]{2,31}$/.test($F(el)); }
		},
		'password': {
			message: SITE_SETTINGS.lang == 'ua' ? 'Невірно введено пароль' : (SITE_SETTINGS.lang == 'en' ? 'Incorrect password' : 'Пароль введен неверно'),
			func: function(el){ return $F(el).blank() || /^\S{6,16}$/.test($F(el)); }
		},
		'password_confirm': {
			message: SITE_SETTINGS.lang == 'ua' ? 'Паролі не співпадають' : (SITE_SETTINGS.lang == 'en' ? 'Passwords are different' : 'Пароли не совпадают'),
			func: function(el){ return $F(el).blank() || $F(el) == $F($(el.form).select('input.password').shift()); }
		},
		'captcha': {
			message: SITE_SETTINGS.lang == 'ua' ? 'Невірний код' : (SITE_SETTINGS.lang == 'en' ? 'Incorrect code' : 'Неверный код'),
			func: function(el){ return $F(el).blank() || /^[0-9]{6}$/.test($F(el)); }
		}
	};
	
	this.submit = function(e){
		e.stop();
		this.validateAll();
		if(this.isValid == true){
			this.form.select('input[type="submit"]').invoke('disable');
			this.form.submit();
		}
	};

	this.reset = function(e){
		this.isValid = true;
		this.form.select('div.icon').invoke('update');
		this.form.select('div.message').invoke('update').invoke('hide');
		this.form.select('input[type="submit"]').invoke('enable');
	};

	this.initElement = function(el){
		if(el.hasClassName($H(this.validators).keys().join('|'))){
			Event.observe(el, 'blur', function(e){
				this.validateOne(e.element());
			}.bindAsEventListener(this));
		}
	};

	this.validateOne = function(el){
		var valid = true;

		$(el).classNames().each(function(className){
			if(valid == true){
				if(typeof (validator = $H(this.validators).get(className)) == 'object'){
					if(validator.func.bind(this)(el) == false){
						valid = false;
						this.setCheckStatus('false', el, validator.message);
					}
					else {
						this.setCheckStatus('true', el);
					}
				}
			}
		}.bind(this));
		
		this.isValid &= valid;
	};

	this.validateAll = function(){
		this.isValid = true;
		Form.getElements(this.form).each(function(el){
			if(el.hasClassName($H(this.validators).keys().join('|'))){
				this.validateOne(el);
			}
		}.bind(this));
	};

	this.setCheckStatus = function(status, el, message){
		var icon_block = $(el).up('div.fieldset').select('div.icon').shift();
		var mess_block = $(el).up('div.fieldset').select('div.message').shift();

		switch(status){
			case 'true':
				mess_block.update().hide();
				icon_block.update().insert({top: new Element('img', {src: this.icons.success, width: 16, height: 16})});
				break;
			case 'false':
				mess_block.hide().update(validator.message);
				icon_block.update().insert({top: new Element('img', {src: this.icons.error, width: 16, height: 16})});
				if(typeof Effect == 'object'){
					new Effect.Parallel([
							new Effect.BlindDown(mess_block, { sync: true }), new Effect.Appear(mess_block, { sync: true }) 
						], { 
						duration: 0.5
					});
				}
				else{
					mess_block.show();
				}
				break;
			case 'wait':
				mess_block.update().hide();
				icon_block.update().insert({top: new Element('img', {src: this.icons.loading, width: 16, height: 16})});
				break;
		}
	};

	Form.getElements(this.form).each(this.initElement.bind(this));
	Event.observe(this.form, 'submit', this.submit.bindAsEventListener(this));
	Event.observe(this.form, 'reset', this.reset.bindAsEventListener(this));

	this.reset();
}

//---------------------------------------------------------------- ONLOAD EVENTS

Event.observe(document, 'dom:loaded', function(e){
	$$('input[rel="clear"]').each(function(el, i){
		if(el.type.match(/text/i) && !$F(el).blank()){
			var defValue = el.value;
			el.observe('focus', function(e, defValue){
				if(this.value == defValue) this.value = "";
			}.bindAsEventListener(el, defValue));
			el.observe('blur', function(e, defValue){
				if(this.value == "") this.value = defValue;
			}.bindAsEventListener(el, defValue));
		}
	});

	$$('img[rel="hover"]').each(function(el, i){
		if (el.src.blank() == false) {   
			var defsrc = el.src;   
			var hovsrc = el.src.substring(0, el.src.length - 4) + '_a' + el.src.substring(el.src.length - 4);
			el.observe('mouseover', function(e, src){
				this.src = src;
			}.bindAsEventListener(el, hovsrc));
			el.observe('mouseout', function(e, src){
				this.src = src;
			}.bindAsEventListener(el, defsrc));
			new Element('img', {src: hovsrc});
		}   
	});

	$$('img[rel="bg"]').each(function(el, i){
		var defbg = el.up('td').style.backgroundImage;
		var hovbg = 'url(/images/menu_bg_a.gif)';
		el.observe('mouseover', function(e, bg){
			this.up('td').setStyle({backgroundImage: bg});
		}.bindAsEventListener(el, hovbg));
		el.observe('mouseout', function(e, bg){
			this.up('td').setStyle({backgroundImage: bg});
		}.bindAsEventListener(el, defbg));
	});
	
	$$('img[rel="fade"]').each(function(el, i){
		el.setOpacity(0.6);
		(function(object, start, finish, ptr){
			object.observe('mouseover', function(e){
				if(ptr !== null) ptr.cancel();
				ptr = new Effect.Appear(object, {duration: 0.3, from: start, to: finish, afterFinish: function(){
					ptr = null;
				}});
			});
			object.observe('mouseout', function(e){
				if(ptr !== null) ptr.cancel();
				ptr = new Effect.Fade(object, {duration: 0.2, from: finish, to: start, afterFinish: function(){
					ptr = null;
				}});
			});
		})(el, 0.6, 1.0, null);
	});	
});
