
function most_visited_article_load(a){
	var link = $(a);
	var months = link.readAttribute('rel');

	new Ajax.Request('/?module=article&media=ajax', {
		method: 'GET',
		parameters: {action: 'most_visited_article_load', offset: months},
		onSuccess: function(transport){
			if(transport.responseText.length > 0){
				$('most_visited_article_block').update(transport.responseText);
			}
		},
		onComplete: function(){
			$$('#most_visited_article_buttons a').invoke('removeClassName', 'bold');
			link.addClassName('bold');
		},
		onException: function(a, b){
			alert('most_visited_article_load error: #' + b.message);
		}
	});

	return false;
}

function zoomImageClass(){
	this.iddle = true;
	this.div = new Element('div', {id: 'zoomImageDiv'});
	this.close = new Element('img', {src: '/images/close.gif', width: 16, height: 16, title: 'закрити'}).addClassName('close');
	this.img = null
	
	this.zoom = function(src){
		if(this.iddle == false) return;
		this.iddle = false;

		this.img = new Element('img');
		this.img.observe('load', this.onload.bindAsEventListener(this));
		this.img.observe('click', this.onclose.bindAsEventListener(this));
		this.img.src = src;
	}
	
	this.onload = function(e){
		var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
		var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;

		var cTop = scrollTop + (document.viewport.getHeight() - this.img.height) / 2;
		var cLeft = scrollLeft + (document.viewport.getWidth() - this.img.width) / 2;

		this.div.setStyle({'top': cTop + 'px', 'left': cLeft + 'px', width: this.img.width + 'px', height: this.img.height + 'px'});
		this.div.insert({top: this.img}).insert({top: this.close}).hide();

		$$('body')[0].insert({top: this.div});
		
		new Effect.Appear('zoomImageDiv', {
			duration: 0.5
		});
	}
	
	this.onclose = function(e){
		new Effect.Fade('zoomImageDiv', {
			duration: 0.5,
			afterFinish: function(){
				$('zoomImageDiv').descendants().invoke('remove');
				$('zoomImageDiv').remove();
				this.img = null;
				this.iddle = true;
			}.bind(this)
		});
	}

	this.close.observe('click', this.onclose.bindAsEventListener(this));
}

function shopBasketClass(url){
	this.url = url || '/?module=shop&media=ajax';

	this.add = function(gid, count){
		new Ajax.Request(this.url, {
			method: 'GET',
			parameters: {action: 'add', gid: gid, count: count},
			onSuccess: function(transport){
				if(transport.responseText.length > 0){
					alert(transport.responseText);
				}
			},
			onComplete: function(){
				this.updateCart();
			}.bind(this),
			onException: function(a, b){
				alert('AddCart error: #' + b.message);
			}
		});
	}

	this.updateCart = function(){
		if($('shopbasket_goods') && $('shopbasket_price')){
			new Ajax.Request(this.url, {
				method: 'GET',
				parameters: {action: 'update'},
				onSuccess: function(transport){
					if(transport.responseText.length && transport.responseText.isJSON() == true){
						var result = transport.responseText.evalJSON();
						$('shopbasket_goods').update(result.total);
						$('shopbasket_price').update(result.price);
					}
					else if(transport.responseText.length){
						alert(transport.responseText);
					}
				},
				onComplete: function(){
					new Effect.Pulsate('basket', {pulses: 2, duration: .8});
				},
				onException: function(a, b){
					alert('UpdateCart error: #' + b.message);
				}
			});
		}
	}
}

function currencyCalendarChange(date){
	var effect = null;
	var url = '/?module=calendar&media=ajax';
	new Ajax.Request(url, {
		method: 'GET',
		parameters: {action: 'update', date: date},
		onSuccess: function(transport){
			if(transport.responseText.length && transport.responseText.isJSON() == true){	
				var result = transport.responseText.evalJSON();
				if(result.cale) $('currencyCalendarBlock').update(result.cale);
				if(result.data) $('currencyDataBlock').update(result.data);
			}
			else if(transport.responseText.length){
				var result = transport.responseText;
				$('currencyCalendarBlock').update(result);
			}

		},
		onComplete: function(){
			if(effect !== null) effect.cancel()
			effect = new Effect.Pulsate('currencyDataBlock', {pulses: 1, duration: .6, afterFinish: function(){
				effect = null;
			}});
		},
		onException: function(a, b){
			alert('currencyCalendarBlock error: #' + b.message);
		}
	});

	return false;
}

//------------------------------------------------------------------------------

var BBCodePlacer = {
	save: function(doc){
		if(document.selection) {                
			doc.sel = document.selection.createRange().duplicate();
		}               
	},

	bb: function(aId, Tag, smile){
		var open = '[' + Tag + ']';
		if(smile == true)
			var close = '';
		else
			var close = '[/' + Tag + ']';
		var doc = document.getElementById(aId);

		doc.focus();

		if (window.attachEvent && navigator.userAgent.indexOf('Opera') === -1){                                        
			var s = doc.sel;
			if(s){                                  
				var l = s.text.length;
				s.text = open + s.text + close;
				s.moveEnd("character", -close.length);
				s.moveStart("character", -l);                                           
				s.select();                
			}
		}
		else{                                              
			var ss = doc.scrollTop;
			sel1 = doc.value.substr(0, doc.selectionStart);
			sel2 = doc.value.substr(doc.selectionEnd);
			sel = doc.value.substr(doc.selectionStart, doc.selectionEnd - doc.selectionStart);                                              
			doc.value = sel1 + open + sel + close + sel2;
			doc.selectionStart = sel1.length + open.length;
			doc.selectionEnd = doc.selectionStart + sel.length;
			doc.scrollTop = ss;                                             
		}

		return false;
	}
};

var subMenuObj = {
	hover: null,
	visible: null,

	expand: function(obj){
		if(!obj.readAttribute('effect')) obj.writeAttribute('effect', null);
		if(obj.readAttribute('effect') !== null) obj.readAttribute('effect').cancel();
		obj.writeAttribute('effect', new Effect.Appear(obj, {duration: 0.5, from: 0, to: 1, afterFinish: function(){
			obj.writeAttribute('effect', null);
		}}));
	},

	collapse: function(obj){
		if(obj !== null && typeof obj == 'object') obj.hide();
	},

	show: function(e, el){
		this.hover = el;
		if(this.visible == null || this.visible != el){
			if(this.visible != null) this.collapse(this.visible);
			this.visible = el;
			this.expand(this.visible);
		}
	},

	hide: function(e){
		this.hover = null;
		if(this.visible != null){
			(function(){
				if(this.hover == null || this.hover != this.visible){
					this.collapse(this.visible);
					this.visible = null;
				}
			}).bind(this).delay(0.5);
		}
	},

	init: function(){
		$$('a.dropdown').each(function(el, i){
			var block = $(el.readAttribute('rel'));
			var pos = el.down('img').positionedOffset();
			var dim = el.down('img').getDimensions();
			var table = $('smiles_container').getDimensions();

			if(typeof block == 'object' && block != null){
				block.setStyle({left: pos.left + 'px', top: (pos.top - table.height + dim.height) + 'px'});

				el.observe('click', this.show.bindAsEventListener(this, block));
				el.observe('mouseout', this.hide.bindAsEventListener(this));
				block.observe('mouseenter', this.show.bindAsEventListener(this, block));
				block.observe('mouseleave', this.hide.bindAsEventListener(this));
			}
		}.bind(this));
	}
};

//------------------------------------------------------------------------------

function ajaxSubListRedefine(url, list1, list2, loader){
	var loader = $(loader);

	new Ajax.Request(url, {
		method: 'GET',
		parameters: '/module=search&media=ajax&action=ajax_form&mid=' + list1.value,
		onCreate: function(){
			list2.disabled = true;
			loader.show();
		},
		onLoaded: function(){
			for(var i = list2.options.length - 1; i >= 0; i--)
				list2.remove(i);
				
		},
		onSuccess: function(transport){
			if(transport.responseText.length > 0){
				var result = transport.responseText.evalJSON();
				if(result.length == 0)
					list2.hide();
				else 
					list2.show();
				for(var i = 0; i < result.length; i++)
					list2.appendChild(new Element('option', {value: result[i].id}).update(result[i].title));
			}
		},
		onComplete: function(){
			loader.hide();
			list2.disabled = false;
		},
		onException: function(a, b){
			alert('error: #' + b.message);
		}
	});
}

//------------------------------------------------------------------------------

function votesClass(){
	this.url = '/?module=votes&media=ajax';

	this.send = function(form){
		new Ajax.Request(this.url, {
			method: 'POST',
			//parameters: {action: 'vote', answer: this.getCheckedValue(form.answer)},
			parameters: $(form).serialize().toString() + '&action=vote',
			onCreate: function(){
				$('votesMessageDiv').update('');
				$('votesButton').disable();
			},
			onSuccess: function(transport){
				var text = transport.responseText;
				if(text.length > 0 && text.isJSON()){
					$('votesMainContainer').update(text.evalJSON().result);
				}
				else if(!transport.responseText.blank()){
					$('votesMessageDiv').update(transport.responseText);
					$('votesButton').enable();
				}
			}.bind(this),
			onException: function(a, b){
				alert('votesClass error: #' + b.message);
			}
		});
	}

	this.getCheckedValue = function(radioObj){
		if(!radioObj) return "";
		var radioLength = radioObj.length;
		if(radioLength == undefined){
			if(radioObj.checked)
				return radioObj.value;
			else
				return "";
		}
		for(var i = 0; i < radioLength; i++) {
			if(radioObj[i].checked) {
				return radioObj[i].value;
			}
		}
		return "";
	}
}

//------------------------------------------------------------------------------

function maillistClass(){
	this.url = '/?module=maillist&media=ajax';

	this.subscribe = function(form){

		new Ajax.Request(this.url, {
			method: 'POST',
			parameters: {action: 'subscribe', name: $F(form.name), email: $F(form.email)},
			onCreate: function(){
				$('maillistMessDiv').update('');
				$('maillistButton').disable();
			},
			onSuccess: function(transport){
				var text = transport.responseText;
				if(text.length > 0 && text.isJSON()){
					alert(text.evalJSON());
				}
				else if(!transport.responseText.blank()){
					$('maillistMessDiv').update(transport.responseText);
				}
			}.bind(this),
			onComplete: function(){
				$('maillistButton').enable();
			},
			onException: function(a, b){
				alert('maillistClass error: #' + b.message);
			}
		});
	}
}

//------------------------------------------------------------------------------

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: 'Це поле має бути заповненим.',
			func: function(el){ return !$F(el).blank(); }
		},
		'email': {
			message: 'Некорректний email. Приклад name@youdomain.com',
			func: function(el){ return $F(el).blank() || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test($F(el)); }
		},
		'url': {
			message: 'Некорректний 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: 'Поле заповнено неправильно.',
			func: function(el){ return $F(el).blank() || /^[^\s\d]{1,}[A-Za-z0-9_-а-яА-я]{2,31}$/.test($F(el)); }
		},
		'password': {
			message: 'Парoль повинен бути вiд 6 символiв.',
			func: function(el){ return $F(el).blank() || /^\S{6,16}$/.test($F(el)); }
		},
		'password_confirm': {
			message: 'Помилка пiдтвердження паролю.',
			func: function(el){ return $F(el).blank() || $F(el) == $F($(el.form).select('input.password').shift()); }
		},
		'captcha': {
			message: 'Поле не може бути порожным.',
			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();
}

//------------------------------------------------------------------------------

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

	this.url = '/?module=comments&media=ajax';
	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(transport){
			
				new Effect.BlindDown(this.block, {duration: 0.25, afterFinish: function(){
					subMenuObj.init();
				}});
				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('Помилка вiдправки коментаря.');
		}
	};

	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 = 3000 - count;
		if(count >= 3000){
			this.value = this.value.substr(0, 3000);
			current = 3000 - this.value.length;
		}
		$('comments_chars').update(current);
	};
}

//------------------------------------------------------------------------------

function expandSpeakerBio(obj, cont){
	$(obj).up('div').hide();
	new Effect.BlindDown(cont);
	return false;
}

function showCollages(id){
	var container = id || 'collage';
	var collages = [
		'main.jpg'
/*
		'igor_berkut_1.jpg', 'igor_berkut_2.jpg', 'igor_berkut_3.jpg', 'igor_berkut_4.jpg', 'igor_berkut_5.jpg', 'igor_berkut_6.jpg', 
		'igor_berkut_7.jpg', 'igor_berkut_8.jpg', 'igor_berkut_8.jpg', 'igor_berkut_9.jpg', 'igor_berkut_10.jpg', 'igor_berkut_11.jpg', 
		'igor_berkut_12.jpg', 'igor_berkut_13.jpg', 'igor_berkut_14.jpg', 'igor_berkut_16.jpg',  
		'igor_berkut_18.jpg', 'igor_berkut_19.jpg', 'igor_berkut_20.jpg', 'igor_berkut_21.jpg',
		'calendar/01.jpg', 'calendar/02.jpg', 'calendar/03.jpg', 'calendar/04.jpg', 'calendar/05.jpg', 'calendar/06.jpg', 'calendar/07.jpg'
*/
	];
	var collage = collages[Math.round(Math.random() * (collages.length - 1))];
	var img = new Element('img', {src: '/collages/' + collage});

	try {
		$(container).insert({top: img})/*.setStyle({width: '246px', height: '728px'})*/;
	} catch(e) {};
}

//------------------------------------------------------------------------------

Event.observe(document, 'dom:loaded', function(e){
	if(typeof sub_menu_cnt == 'object'){
		var submenu = $('sub_menu_cnt');
		/*
		if(submenu.getElementsByClassName('submenu')[0].innerHTML.blank()){
			submenu.hide();
		}
		*/
	}

	$$('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);
			var hoverel = el.up('td');
			hoverel.observe('mouseover', function(e, src){
				el.src = src;
				this.addClassName('hover');
			}.bindAsEventListener(hoverel, hovsrc));
			hoverel.observe('mouseout', function(e, src){
				el.src = src;
				this.removeClassName('hover');
			}.bindAsEventListener(hoverel, defsrc));
			new Element('img', {src: hovsrc});
		}   
	});

	$$('img[rel~="hbg"]').each(function(el, i){
		var defbg = el.up('td').style.backgroundImage;
		var hovbg = 'url(/menu/bg_menu_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);
	});	

});

