var addthis_pub				= '[Site name]'; 
var addthis_logo			= '[add_this_logo]';
var addthis_logo_background	= 'ffffff';
var addthis_logo_color		= '201910';
var addthis_brand			= 'IUC';
var addthis_options			= 'favorites, email, delicious, google, digg, reddit, facebook, live, more';

CD3.Behaviors({
	'body': {
		'focus:in': {
			'input[type=text]': function(){
				if (this.getValue() == this.getAttribute('title')) this.setValue('');
			}
		},
		'focus:out': {
			'input[type=text]': function(){
				if (this.getValue().length == 0) this.setValue(this.getAttribute('title') || '');
			}
		}
	},
	'#text_size': function(){
		new CD3.FontSwitcher(this, 'content', {
			reset:	'.reset',
			plus:	'.plus',
			minus:	'.minus'
		});
	},
	'input[type=submit]':{
		mouseover: function(){
			this.style.backgroundPosition = 'left bottom';
		},		
		mouseout: function(){
			this.style.backgroundPosition = 'left top';
		}		
	},
	
	'#bookmark': {
		mouseover: function(){
			addthis_open(this, '', location.href, addthis_pub)
		},
		mouseout: addthis_close,
		click: addthis_sendto
	},
	'#custom_select select, #image_select select, .out_select select, #priemen_den select': CD3.Select,
	'#tab_menu': {
		'mouseover': {
			'#tab_menu > li': function(){
				$$('#tab_menu ul').invoke('hide');
				var ul = this.down('ul');
				if (ul){
					ul.style.display = 'block';
				}
			}	
		},
		'mouseleave': function(){
			this.select('ul').invoke('hide');
			this.select('li.selected ul').invoke('show');
		}
	},
	'ul.gal_droper,.small_droper': {
		mouseover: function(){
			this.style.overflow 			= 'visible'; 
			this.style.height				= 'auto';
			this.style.backgroundPosition	= '193px -26px';
		},
		mouseout: function(){
			this.style.overflow				= 'hidden';
			this.style.height				= '30px';
			this.style.backgroundPosition	= '193px 7px';
		}
	},
	'.big_droper': {
		mouseover: function(){
			this.style.overflow		= 'visible'; 
			this.style.height		= 'auto';
			this.style.background	= 'url(/images/cal_bg.png) no-repeat right 15px';
		},
		mouseout: function(){
			this.style.overflow		= 'hidden';
			this.style.height		= '30px';
			this.style.background	= 'url(/images/cal_bg.png) no-repeat right 15px';
		}
	},
	'#img_cont a:click': function(e){
		e.stop();
		
		$('random_image').src = this.href;
		
		$$('#img_cont a').invoke('removeClassName', 'selected');
		this.addClassName('selected');
		
		$('pos_tab').down('td.first').innerHTML = this.down('img').readAttribute('alt') ;
	},
	'select[multiple=multiple]': CD3.MultiSelect,
	'.out_sav table td.cells_send:click': function(){
		Effect.toggle(this.up('div').next('form'), 'blind');
	},
	'.toggle_close:click': function(){
		Effect.toggle(this.up('form'), 'slide');
	},
	'input[type=checkbox]': CD3.Checkbox,
	'#player_location:click': {
		'.cell_player': function(){
			swfobject.embedSWF(
				"/swf/mp3_player.swf", 
				this.identify(), 
				"288", "37", "9.0.0" , 
				"swf/expressInstall.swf",
				{soundToPlay: this.up('div').previous('a').getAttribute('href')},
				{menu:false }
			);
			this.removeClassName('audio_player');
		}
	}
});
/*
	var FlashVars = {};
		FlashVars.soundToPlay = '/files/info_pages/serebroopium2.mp3';
			var s={};
			//s.menu = false;
			//s.bgcolor = '#CCCCCC';
			//s.wmode = 'transparent';
			
			swfobject.embedSWF("/swf/mp3_player.swf", "play_music", "288", "31", "9.0.0" , "swf/expressInstall.swf" , FlashVars , s );
*/

var Balchik = {};
Balchik.Slider = Class.create({
	initialize: function(container, options){
		var options = Object.extend({
			prev: 			null,
			next:			null,
			scrollBy:		false,
			scrollType:		'horizontal',
			event:			'click',
			beforeSlide:	false,
			afterSlide:		false,
			effectDuration: 0.8
		}, options || {});
		
		this.container	= $(container);
		this.scroll		= options.scrollType == 'vertical' ? ['top', 'offsetHeight'] : ['left', 'offsetWidth'];
		this.scrollBy	= options.scrollBy || this.container.parentNode[this.scroll[1]];
		this.prev		= $(options.prev).observe(options.event, this.slide.bind(this, -1));
		this.next		= $(options.next).observe(options.event, this.slide.bind(this, 1));
		this.sliding	= false;
		
		this.effectOptions = {
			duration:		options.effectDuration || 0.8 ,
			queue:			{scope: 'cd3:slider', limit:1}
		};
		
		if (Object.isFunction(options.beforeSlide)){
			this.effectOptions.beforeStart = options.beforeSlide.bind(this);
		}
		
		if (Object.isFunction(options.afterSlide)){
			this.effectOptions.afterFinish = options.afterSlide.bind(this);
		}

		this.checkButtons();
	},
	refreshWidth: function(tagName){
		this.container.style[this.scroll[0]] = '0px';
		this.container.style.width = this.container.select(tagName || 'li').inject(0, function(width, li){
			return width + li.offsetWidth;
		}) + 'px';
		
		this.checkButtons();
	},
	checkButtons: function(){
		var position = this.position();
	
		this.setVisibility('prev', position > 0);
		this.setVisibility('next', position < this.container[this.scroll[1]] - this.scrollBy);
	},
	position: function(){
		return - parseInt(this.container.style[this.scroll[0]]) || 0;
	},
	setVisibility: function(button, visible){
		this[button].style.visibility = visible ? 'visible' : 'hidden';
	},
	slideTo: function(position){
		var offset = this.container[this.scroll[1]]; // offsetHeight or offsetWidth
		
		position = position < 0 ? 0 : Math.min(position, offset - this.scrollBy);
		
		this.setVisibility('prev', position > 0);
		this.setVisibility('next', position < offset - this.scrollBy);		
		this.container.morph(this.scroll[0] + ":" + (-position) + "px", this.effectOptions);
	},
	slide: function(direction){
		this.slideTo(this.position() + direction * this.scrollBy);
	}
});

Balchik.Search = Class.create({
	initialize: function(form){
		this.form = $(form);
		this.input = this.form.down('input[type=text]');
		
		this.form.show();
		this.form.observe('submit', this.search.bind(this));
		
		document.observe('balchik:decision:not_found', this.notFound.bind(this));
	},
	search: function(e){
		e.stop();
		document.fire('balchik:decision:search', {value: this.input.getValue()});
	},
	notFound: function(){
		//console.log('a');
		this.input.highlight({startcolor: '#FFDBDB', endcolor: '#F1F1F1', duration: 0.5});
	}
});

Balchik.Base = Class.create({
	initialize: function(element){
		this.container = $(element);
		this.container.delegate('li a', 'click', this.onClick.bind(this));
		this.selected  = this.container.down('a.selected');
		this.slider = new Balchik.Slider(this.container.down('.solution'), {
			prev: this.container.down('.left_slide'),
			next: this.container.down('.right_slide')
		});
	},
	onClick: function(e){
		e.stop();
		this.select(e.findElement('a'));
	},
	focus: function(selected){
		if (this.selected) this.selected.removeClassName('selected');
		this.selected = selected.addClassName('selected');
		
		this.slider.slideTo(selected.up('li').offsetLeft);
	},
	fire: function(eventName, memo){
		document.fire('balchik:' + eventName, memo);
	},
	observe: function(eventName, callback){
		document.observe('balchik:' + eventName, callback);
	}
});

Balchik.Meetings = Class.create(Balchik.Base, {
	select: function(meeting){
		this.container.down('.solution_title span').innerHTML = meeting.getAttribute('data-year');
		this.focus(meeting);
		this.fire('meeting:selected', {href: meeting.href});
	}
});

Balchik.Decisions = Class.create(Balchik.Base, {
	initialize: function($super, element){
		$super(element);
		this.decision = $('widget_decision');
		this.decisionHead = $('widget_decision_title');
		this.observe('meeting:selected', this.updateSlider.bind(this));
		this.observe('decision:search', this.search.bind(this));
	},
	select: function(decision){
		this.focus(decision);
		this.updateDecision(decision.href);
	},
	updateSlider: function(e){
		new Ajax.Updater(this.slider.container, e.memo.href, {
			method: 'get',
			onComplete: this.afterSliderUpdated.bind(this)
		});
	},
	afterSliderUpdated: function(){
		this.slider.refreshWidth();
	
		var decision = this.slider.container.down('a');

		if (decision){
			this.select(decision);
		} else {
			this.decision.innerHTML = '';
			this.decisionHead.hide();
		}
	},
	updateDecision: function(href){
		new Ajax.Updater(this.decision, href, {
			method: 'get',
			onComplete: this.afterDecisionUpdated.bind(this)
		});
	},
	afterDecisionUpdated: function(){
		var element = this.decision.down('div');
		
		this.decisionHead.show();
		this.decisionHead.down('span', 0).innerHTML = element.getAttribute('data-number');
		this.decisionHead.down('span', 1).innerHTML = element.getAttribute('data-protocol');
		this.decisionHead.down('span', 2).innerHTML = element.getAttribute('data-date');
	},
	search: function(e){
		var regexp = new RegExp(e.memo.value),
			result = this.slider.container.select('a').detect(function(link){
			return !! link.innerHTML.match(regexp);
		});
			
		if (result){
			this.select(result);
		} else {
			this.fire('decision:not_found');
		}
	}
});

CD3.Behaviors({
	'#widget_meetings':		Balchik.Meetings,
	'#widget_decisions':	Balchik.Decisions,
	'#decisions_form':		Balchik.Search
}); 


CD3.Behaviors('#gallery', function(){
	$('thumbslist').setStyle({
		width:		$$('#thumbslist li').length * 23 + 'px',
		position:	'relative',
		left:		'0px'
	});
	
	var loader		= null, 
		image		= $('mainimage').down('img'),		
		container	= $('mainimagewrapper');

	var thumbscount = $$('#thumbslist li').length, thumbslist = $('thumbslist').setStyle({
		width:		thumbscount * 23 + 'px',
		position:	'relative',
		left:		'0px'
	});
	
	function clearLoader(){
		if (loader != null){
			loader.onload	= null;
			loader			= null;
		}
	}
	
	function onLoad(){
		image.src = loader.src;
		
		container.morph('height: ' + loader.height + 'px;', {
			duration: .4,
			afterFinish: function(){
				image.appear({
				    duration: .4,
				    afterFinish: function(){
				        container.removeClassName('loading');
			        }
		        });
			}
		});
		
		clearLoader();
	}
			
	function selectImage(thumb){
		$('thumbslist').select('.selected').invoke('removeClassName', 'selected');
		thumb.addClassName('selected');
		
		clearLoader();
		
		container.up('div').addClassName('loading');
		
		image.fade({
			duration: .3,
			afterFinish: function(){		
				loader			= new Image();
				loader.onload	= onLoad;
				loader.src		= thumb.href;
			}
		});
		
		var position = parseInt(thumb.id.match(/\w+_(\d+)/)[1]);
			position = position < 2 ? 0 : (position < thumbscount - 1 ? position - 1 : thumbscount - 2);
			
		thumbslist.morph('left: ' + ( -23 * position) + 'px');
	}
	
	return {
		'div.controls:click': {
			'#thumbslist a': function(e){
				e.stop();
				selectImage(this);
			},
			'#preva': function(){
				var thumbs	 = $('thumbslist'),
					selected = thumbs.down('a.selected');
					
				selectImage(((selected && selected.up('li').previous('li')) || thumbs.select('li').last()).down('a'));
			},
			'#nexta': function(){
				var thumbs	 = $('thumbslist'),
					selected = thumbs.down('a.selected');
					
				selectImage(((selected && selected.up('li').next('li')) || thumbs.select('li').first()).down('a'));
			}
		}
	};
});


CD3.Behaviors({
	'#thumbslist_2 li a:click': function(e){
		e.stop();
		$$('#thumbslist_2 a').invoke('removeClassName', 'selected');
	
		this.addClassName('selected');
	
		$('change_info').innerHTML				= this.down('span').innerHTML; 
		$('change_link').href					= this.href; 
		$('change_link_2').href					= this.href;
		$('change_link_2').innerHTML			= this.down('p').innerHTML;
		$('change_image').style.backgroundImage = 'url('+ this.getAttribute('data-src') +')';
	},
	'#thumbslist_2': function(){
		new CD3.Slider(this, 'preva_2', 'nexta_2',{ 
			scroll_by:	138,
			event:		'click'
		});
		this.style.width = (this.select('li').length * 23) + 'px';
	},
	'#transport_poll .last:click': function(){
		this.next('input[type="hidden"]').value = 'yes';
	}
});


Balchik.ContinuesSlider = Class.create({
	initialize: function(container, options){
		var options = Object.extend({
			prev: 			null,
			next:			null,
			scrollBy:		4,
			scrollType:		'horizontal',
			beforeSlide:	false,
			afterSlide:		false
		}, options || {});

		this.container		= $(container);
		this.scroll			= options.scrollType == 'vertical' ? ['top', 'getHeight', 'y'] : ['left', 'getWidth', 'x'];
		this.beforeSlide	= options.beforeSlide || Prototype.emptyFunction;
		this.afterSlide		= options.afterSlide || Prototype.emptyFunction;
		this.prev			= $(options.prev);
		this.next			= $(options.next);

		this.prev.observe('mouseover', this.startSliding.bind(this, options.scrollBy));
		this.prev.observe('mouseout',  this.stopSliding.bind(this));
		
		this.next.observe('mouseover', this.startSliding.bind(this, -options.scrollBy));
		this.next.observe('mouseout',  this.stopSliding.bind(this));
		
		var pos = parseInt(this.container.style[this.scroll[0]]) || 0;

		this.setVisibility('prev', pos != 0);
		this.setVisibility('next', this.container[this.scroll[1]]() + pos + options.scrollBy * 2 > 900)
	},
	setVisibility: function(button, visible){
		this[button].style.visibility = visible ? 'visible' : 'hidden';
	},
	startSliding: function(moveBy){
		if (this.interval){
			clearInterval(this.interval);
		}
		this.beforeSlide.call(this);
		this.interval = setInterval(this.slide.bind(this, moveBy), 1);
	},
	stopSliding: function(){
		if (this.interval){
			clearInterval(this.interval);
			this.interval = null;
			this.afterSlide.call(this);
		}
	},
	slide: function(value){
		var property	= parseInt(this.container.style[this.scroll[0]]) || 0,	// top or left
			offset		= this.container[this.scroll[1]](); // offsetHeight or offsetWidth

		if ((value > 0 && property > 0) || (value < 0 && property + offset + value < 0)) return;

		this.setVisibility('prev', property + value < 0);
		this.setVisibility('next', offset + property + value * 2 > 900);
		this.sliding = true;

		value = value < 0 ? Math.max(value, - (offset + property + value)) : Math.min(value, -property);
		
		this.container.style[this.scroll[0]] = value + property + 'px';
	}
});

CD3.Behaviors('#main_menu', function(){
	var active,
		maxLeft = this.getWidth() - 182,
		slider  = $('menu_slider');
	
	slider.style.width = slider.select('li').inject(0, function(w, li){ return w += li.getWidth(); }) + 'px';
	
	new Balchik.ContinuesSlider(slider, {
		prev:	'backer',
		next:	'nexter'
	});
	
	//new CD3.Slider(slider, 'backer', 'nexter', { scroll_by: 915,  event: 'mouseover' });
	
	function getPosition(left){
		left += parseInt(slider.style.left) || 0;
		
		return Math.max(0, Math.min(left, maxLeft));
	}

	return {
		'#backer,#nexter:mouseover': function(e){
			if (active){
				active.hide();
				active = null;
			}
		},
		'span.invisible:mouseleave': function(e){
			this.hide();
			if (active == this){
				active = null;
			}
		 },
		'#menu_slider:mouseover': {
			li: function(){
				if (active){
					active.hide();
				}
				
				if($('item_' + this.getAttribute('name'))){
					active = $('item_' + this.getAttribute('name')).show().setStyle({
						left: getPosition(this.positionedOffset().left) + 22 + 'px'
					});
				}
				
			}
		}
	};
});
