/*
	Extensions
*/
try {
	Element.implement({

		// method disable selection of inner text
		disableTextSelection: function(){
			this.addEvents({
				'mousedown': $lambda(false),
				'selectstart': $lambda(false)
			});
			return this;
		}
	});
} catch(e){}




/*
	Font Resizer
*/
try {
	var FontResizer = new Class({

		Implements: [Options],

		options: {
			// aimed elements collection
			area: null,

			// cookie name
			cookieName: 'basefont',

			// default font size, if no cookie found
			defaultFont: 12,

			// default min font size
			minFont: 11,

			// default max font size
			maxFont: 13
		},

		// method sets base font size and write Cookie
		set: function(size){
			if(size && this.options.area) {
				this.options.area.setStyle('font-size', size+'px');
				Cookie.write(this.options.cookieName, size, {path: '/'});
				return true;
			} else {
				return false;
			}
		},

		// method gets base font size
		get: function(){
			return this.options.area.getStyle('font-size').toInt() || this.options.defaultFont;
		},

		// constructor
		initialize: function(options, navUp, navDown){
			this.setOptions(options);

			this.set(Cookie.read(this.options.cookieName) || this.options.defaultFont);

			if (navUp) {
				navUp.addEvent('click', function(){
						if(this.get() < this.options.maxFont){
							var to = this.get() + 1;
							this.set(to);
						}
						return false;
				}.bind(this));
			}

			if (navDown) {
				navDown.addEvent('click', function(){
						if(this.get() > this.options.minFont){
							var to = this.get() - 1;
							this.set(to);
						}
						return false;
				}.bind(this));
			}

			return this;
		}

	});
} catch(e){}




/*
	PDF Creator
*/
try {
	var PdfCreator = new Class({

		// constructor
		initialize: function(){

			// Process icon
			this.divLoading = new Spinner;


			// Multilanguage variable
			this.errorCreate = _['pdfcreator-error-create'];
			this.errorClean = _['pdfcreator-error-clean'];
			this.errorRemove = _['pdfcreator-error-remove'];
			this.errorList = _['pdfcreator-error-list'];
			this.errorArchive = _['pdfcreator-error-archive'];
			this.confirmRemove = _['pdfcreator-confirm-remove'];
			this.confirmClean = _['pdfcreator-confirm-clean'];
			this.labelView = _['pdfcreator-label-view'];
			this.labelRemove = _['pdfcreator-label-remove'];
			this.labelEmpty = _['pdfcreator-label-empty'];


			// Few comfy handles
			this.divFolder = $('popup-pdffolder');
			this.divList = $('popup-pdffolder-list');
			this.aClean = $('popup-pdffolder-clean');
			this.aArchive = $('popup-pdffolder-archive');
			this.aDownload = $('pdfcreator-options-download');
			this.aAdd = $('pdfcreator-options-add');
			this.aShow = $('pdfcreator-options-show');


			var __this__ = this;


			// releases PDF options for PDF Creator
			$('pdfcreator-handle').addEvent('click', function() {
				$('pdfcreator-options').removeClass('hidden');
				return false;
			});


			// releases PDF options for PDF Creator
			$('pdfcreator').addEvent('mouseleave', function() {
				$('pdfcreator-options').addClass('hidden');
				return true;
			});


			// download pdf
			__this__.aDownload.addEvent('click', function() {
				__this__.divLoading.show(true);
				new Request({
					url: this.href,
					method: 'post',
					onSuccess: function(url) {
						__this__.divLoading.hide(true);
						window.location.href = url;
					},
					onFailure: function() {
						__this__.divLoading.hide(true);
						window.alert(__this__.errorCreate);
					}
				}).send();

				return false;
			});


			// add pdf to folder
			__this__.aAdd.addEvent('click', function() {
				__this__.divLoading.show(true);
				new Request({
					url: this.href,
					method: 'post',
					onSuccess: function(url) {
						__this__.divLoading.hide(true);
						__this__.showFolder();
					},
					onFailure: function() {
						__this__.divLoading.hide(true);
						window.alert(__this__.errorCreate);
					}
				}).send();

				return false;
			});


			// show folder
			__this__.aShow.addEvent('click', function() {
				__this__.showFolder();
				return false;
			});


			// clean folder
			__this__.aClean.addEvent('click', function() {
				if (window.confirm(__this__.confirmClean)) {
					__this__.divLoading.show(true);
					new Request({
						url: this.href,
						method: 'post',
						onSuccess: function(url) {
							__this__.divLoading.hide(true);
							__this__.showFolder();
						},
						onFailure: function() {
							__this__.divLoading.hide(true);
							window.alert(__this__.errorClean);
						}
					}).send();
				}
				return false;
			});


			// archive folder
			__this__.aArchive.addEvent('click', function() {
				__this__.divLoading.show(true);
				new Request({
					url: this.href,
					method: 'post',
					onSuccess: function(url) {
						__this__.divLoading.hide(true);
						window.location.href = url;
					},
					onFailure: function() {
						__this__.divLoading.hide(true);
						window.alert(__this__.errorArchive);
					}
				}).send();
				return false;
			});


			return this;
		},


		showFolder: function() {
			var __this__ = this;

			__this__.divLoading.show(true);
			new Request.JSON({
				url: __this__.aShow.href,
				method: 'post',
				onSuccess: function(list) {
					__this__.divLoading.hide(true);
					if (list.length>0) {
						__this__.aClean.removeClass('hidden');
						__this__.aArchive.removeClass('hidden');
						var table = new Element('table', {'class': 'noedge', 'cellspacing': 0});
						for (var i = 0; i < list.length; i++) {
							__this__.file = list[i];
							table.adopt(
								new Element('tbody').adopt(
									new Element('tr').adopt(
										new Element('td', {'class': 't-b c-black', 'width': '65%'}).appendText(i + 1 + '. ' + __this__.file.title),
										new Element('td', {'class': 'x-ar'}).adopt(
											new Element('a', {'href': __this__.file.download}).appendText(__this__.labelView)
										),
										new Element('td', {'class': 'x-ar'}).adopt(
											new Element('a', {'href': __this__.file.remove}).appendText(__this__.labelRemove).addEvent('click', function() {
												if (window.confirm(__this__.confirmRemove)) {
													__this__.divLoading.show(true);
													new Request({
														url: this.href,
														method: 'post',
														onSuccess: function(url) {
															__this__.divLoading.hide(true);
															__this__.showFolder();
														},
														onFailure: function() {
															__this__.divLoading.hide(true);
															window.alert(__this__.errorRemove);
														}
													}).send();
												}
												return false;
											})
										)
									)
								)
							);
						}
						__this__.divList.empty().adopt(table);
					} else {
						__this__.divList.empty().set('html', '<p>'+ __this__.labelEmpty +'</p>');
						__this__.aClean.addClass('hidden');
						__this__.aArchive.addClass('hidden');
					}
					__this__.divFolder.removeClass('hidden');
				},
				onFailure: function() {
					__this__.divLoading.hide(true);
					__this__.aClean.addClass('hidden');
					__this__.aArchive.addClass('hidden');
					__this__.divList.empty().set('html', '<p>'+ __this__.labelEmpty +'</p>');
					window.alert(__this__.errorList);
				}
			}).send();
		}

	});
} catch(e){}




// for AddThis
var addthis_config = {
	services_custom: {
		name: "Diary.Ru",
		url: "http://www.diary.ru/",
		icon: "http://www.diary.ru/favicon.ico"
	}
}



try {
	/* It releases Search on site */
	var Search = new Class({

		// constructor
		initialize: function(){

			var _this_ = this;


			// Few comfy handles
			this.popup = $('popup-search');
			this.popupInner = $('popup-search-inner');
			this.popupInput = $$('#search-short input')[0];
			this.spinner = $$('#search-short-spinner');
			var search_cursor = false;

			var echo = new Request({
				method: 'post',
				charset: 'utf-8',
				link: 'cancel',
				onSuccess: function(html){
					_this_.spinner.addClass('hidden');
					search_cursor = false;
					_this_.popupInner.empty().set('html', html);
					var links = _this_.popupInner.getElements('a.i');
					_this_.popupInner.getElements('a.i').addEvents({
						'mouseover': function(){
							links.removeClass('focus');
							return this.addClass('focus');
						},
						'mouseout': function(){
							links.removeClass('focus');
							return this.removeClass('focus');
						}
					});
					_this_.popup.removeClass('hidden');
					return this;
				}
			});


			this.popupInput.addEvents({
				'keyup': function(k) {
					if (k.key == 'down' || k.key == 'up') {
						var links = _this_.popupInner.getElements('a.i');

						if (k.key == 'down') {
							search_cursor = search_cursor || 0;
							if (search_cursor < links.length) search_cursor++;
						}

						if (k.key == 'up') {
							search_cursor = search_cursor || links.length+1;
							if (search_cursor > 1) search_cursor--;
						}

						links.removeClass('focus');
						links[search_cursor-1].addClass('focus');

						return false;
					} else if (k.key == 'enter') {
						echo.cancel();
						_this_.spinner.addClass('hidden');
						if (_this_.popupInner.getElements('a.focus')[0]) {
							location.href = _this_.popupInner.getElements('a.focus')[0].get('href');
						} else if (!/\*/.test(this.value)) {
              this.value += '*';
            }
					} else {
						if (this.value.length >= this.get('minlength')) {
							echo.options.url = this.getParents('form')[0].action;
							echo.options.data = 'search[phrase]=' + this.value;
							echo.send();
							_this_.spinner.removeClass('hidden');
						} else {
							_this_.popup.addClass('hidden');
						}
					}
				},
				'blur': function(){
					(function(){
						_this_.popup.addClass('hidden');
						_this_.popupInner.empty();
					}).delay(250);
				}
			});


			return this;
		}
	});
} catch(e){}




/*
	Init
*/
window.addEvent('domready', function(){


	// run markup hacks
	new Exm();


	// milkbox init
	try {
		new Milkbox({
			overlayOpacity: 0.8
		});
	} catch(e){}


	// print links
	try {
		$$('a[rel=print]').addEvent('click', function(){
			Document.print('body');
			return false;
		});
	} catch(e){}


	// IE6
	Browser.Engine.ie6 = (function(){
		if( Browser.Engine.trident && Browser.Engine.version<=4)
			return true;
		else
			return false;
	})();
	var Engine = Browser.Engine;


	// Some fixes for IE6
	if ( Engine.ie6 ) {
		// dublicate 'type' value as class name
		$each( $$('input'), function(obj){
			obj.addClass( obj.get('type') );
		});
	}


	// Add cellspacing="0" to all tables
	$$('table').setProperty('cellspacing', '0');


	// DTEK Group Enterprises
	try {
		$('groupentities').addEvent('click', function(){
			$('popup-groupentities').removeClass('hidden');
			return false;
		});
	} catch(e){}


	// release popup CLOSE button
	try {
		$$('div.sys-popup div.sys-popup-close a').addEvent('click', function(){
			this.getParent('div.sys-popup').toggleClass('hidden');
			return false;
		});
	} catch(e){}


	// init basefont for main content container
	try {
		new FontResizer({
			area: $('page'),
			cookieName: 'basefont',
			defaultFont: 11
		}, $('header-fontup'), $('header-fontdown'));
	} catch(e){}


	// release accordeons
	try {
		$$('dl.sys-accordeon').each(function(i){
			i.getElements('dt').addEvents({
				'mouseover': function(){
					this.addClass('hover');
					return false;
				},
				'mouseout': function(){
					this.removeClass('hover');
					return false;
				},
				'click': function(){
					if (this.getNext().get('tag')=='dd') {
						if (this.getNext().hasClass('open')) {
							this.getNext().removeClass('open');
						} else {
							this.getParent('dl').getElements('dd.open').removeClass('open');
							this.getNext().addClass('open');
						}
					}
					return false;
				}
			});
		});
	} catch(e){}


	// release tabs
	try {
		$$('dl.sys-tabs').each(function(i){
			i.getElements('dt').addEvents({
				'mouseover': function(){
					this.addClass('hover');
					return false;
				},
				'mouseout': function(){
					this.removeClass('hover');
					return false;
				},
				'click': function(){
					if(this.getNext().get('tag')=='dd') {
						this.getParent('dl').getElements('dt, dd').removeClass('this');

						this.addClass('this');
						this.getNext().addClass('this');
					}
					return false;
				}
			});
		});
	} catch(e){}


	// disable text selections for some elements
	try {
		var selectors = [
			'dl.sys-tabs',
			'dl.sys-accordeon dt',
			'#inlay dt'
		];

		selectors.each(function(i){
			return $$(i).disableTextSelection();
		});
	} catch(e){}


	// releases filter selects
	try {
		$$('select.filter').addEvent('change', function() {
			window.location.href = this.get('value');
		});
	} catch(e){}


	// releases inlay on home page
	try {
		if ( $('inlay') ) {
			// releases TAB for inlay
			$$('#inlay dt').addEvents({
				'mouseover': function(){
					if(!this.hasClass('this')) {
						this.addClass('hover');
					}
					return true;
				},
				'mouseout': function(){
					if(!this.hasClass('this')) {
						this.removeClass('hover');
					}
					return true;
				},
				'click': function(){
					if(!this.hasClass('this')) {
						this.getParent().getElements('dt, dd').removeClass('this').fireEvent('mouseout');
						this.addClass('this').getNext().addClass('this');
						window.location.hash = this.get('hash');
					}
					return true;
				}
			});


			window.onhashchange = function(){
				if (window.location.hash) {
					var hash = window.location.hash.substr(1);
					$$('#inlay dt[hash="'+hash+'"]')[0].fireEvent('click');
				}

				return false;
			}
			//window.onhashchange();


			if (window.location.hash) {
				var hash = window.location.hash.substr(1);
				$$('#inlay dt[hash="'+hash+'"]')[0].fireEvent('click');
			}


			// releases POST for inlay
			$('inlay-post-handle').addEvent('click', function() {
				$('inlay-post').addClass('hover');
				return false;
			});


			// releases POST for inlay
			$('inlay-post').addEvent('mouseleave', function() {
				this.removeClass('hover');
				return true;
			});
		}
	} catch(e){}


	// releases PDF Creator
	try {
		if ( $('pdfcreator') ) {
			// PDF creator
			new PdfCreator();
		}
	} catch(e){}


	// release tips (Module Dictionary)
	try {
		$$('.dfn').each(function(o) {
			o.store('tip:title', o.get('title'));
			o.store('tip:text', o.get('rel'));
		});
		var myTips = new Tips('.dfn', {
			'className': 'tip-wrap',
			'offset': {'x': 0, 'y': 20},
			'fixed': false,
			'windowPadding': {'x': 0, 'y': 0}
		});
	} catch(e){}


	// Module History
	try {
		if(_['history']) {

			var History = new Hash({
				yearFrom: 1930,
				yearTo: 2015,
				history: new Hash(_['history']),
				ruler: $('history-graph-ruler'),
				companies: $('history-graph-companies'),
				content: $('history-graph-content'),
				nav: $('history-graph-nav'),

				// method poses History to an aimed state
				goto: function(year, companyID){
					this.poseRuler(year);
					this.buildCompanies(year, companyID);
					this.buildNavigator(year);
					return this;
				},


				// method build Ruler and bind events
				buildRuler: function(){
					var _this_ = this;
					for (var i = this.yearFrom; i <= this.yearTo; i++) {
						new Element( (i%10 == 0) ? 'h4' : (i%5 == 0) ? 'h5' :'h6', {
							'class': (this.history[i]) ? 'enabled' : 'disabled',
							'title': i,
							'html': '<span>'+ i +'</span><strong>'+ i +'</strong>',
							events: {
								'click': function(){
									if (this.hasClass('enabled')) {
										var year = this.get('title').toInt();
										_this_.goto(year, null);
									}
									return this;
								}
							}
						})
						.inject(this.ruler);
					}
					return this;
				},


				// method pose Ruler's Pointer
				poseRuler: function(year){
					this.ruler.getElements('h4, h5, h6').removeClass('this');
					this.ruler.getElements('[title="'+ year +'"]').addClass('this');
					return this;
				},


				// method build Companies
				buildCompanies: function(year, companyID){
					var _this_ = this;
					var companies = new Hash(_this_.history[year]);
					companyID = (companyID) ? companyID : companies.getKeys()[0];
					var _companyID_ = companyID;

					// 1. Clear old content
					this.companies.empty();

					// 2. Create Year
					this.companies.set('html', '<h2>'+ year +'</h2>');

					// 3. For each company Create Link wrapped by DIV
					companies.each(function(companyObj, companyID){
						new Element('div', {
							'class': (_this_.history[year][companyID].image) ? 'img' : 'noimg'
						}).wraps(
							new Element('a', {
								'href': '#',
								'html': companyObj.company,
								'rel': companyID,
								'class': (companyID == _companyID_) ? 'this' : '',
								events: {
									'click': function(){
										_this_.companies.getElements('a').removeClass('this');
										this.addClass('this');
										_this_.buildContent(year, this.get('rel'));
										return false;
									}
								}
							}).inject(_this_.companies)
						);
					});

					// 4. Call buildContent
					return this.buildContent(year, companyID);
				},


				// method build Content
				buildContent: function(year, companyID){
					var _this_ = this;
					var image = this.history[year][companyID].image;
					var company = this.history[year][companyID].company;
					var content = this.history[year][companyID].content;

					// 1. Clear old content
					this.content.empty();

					// 2. Add Image
					if (image) {
						new Element('img', {
							'src': image
						}).inject(this.content);
					}

					// 3. Add Caption
					if (company) {
						new Element('h3', {
							'html': company
						}).inject(this.content);
					}

					// 4. Add Content
					if (content) {
						new Element('div', {
							'html': content
						}).inject(this.content);
					}

					return this;
				},


				// method build Navigator
				buildNavigator: function(year){
					var _this_ = this;
					var years = this.history.getKeys();
					var yearIndex = years.indexOf(year.toString());
					var yearPrevious = (yearIndex == 0) ? null : years[yearIndex-1] ;
					var yearNext = (yearIndex == years.length-1) ? null : years[yearIndex+1] ;

					// 1. Clear old content
					this.nav.empty();

					// 2. Add Previous button
					if (yearPrevious) {
						new Element('a', {
							'href': '#',
							'class': 'previous',
							'html': yearPrevious,
							events: {
								'click': function(){
									_this_.goto(yearPrevious, null);
									return false;
								}
							}
						}).inject(this.nav);
					}

					// 3. Add Next button
					if (yearNext) {
						new Element('a', {
							'href': '#',
							'class': 'next',
							'html': yearNext,
							events: {
								'click': function(){
									_this_.goto(yearNext, null);
									return false;
								}
							}
						}).inject(this.nav);
					}

					return this;
				},


				// Call function GOTO with initial parameters
				init: function() {
					var firstYear = this.history.getKeys()[0];
					var companies = new Hash(this.history[firstYear]);
					var firstYearCompany = companies.getKeys()[0];
					this.buildRuler();
					return this.goto(firstYear, firstYearCompany);
				}
			});
			History.init();

		}
	} catch(e){}


	// releases search autocomplete
	try {
		if ( $('search-short') ) {
			// Search
			new Search();
		}
	} catch(e){}


	// releases TAB for Page View
	try {
		$$('a[rel|="x-view"]').addEvent('click', function() {
			// for "A"s
			$$('a[rel|="x-view"]').removeClass('this');
			this.addClass('this');
			// for "DIV"s
			$$('div[id|="x-view"]').addClass('hidden');
			$(this.get('rel')).removeClass('hidden');
			return false;
		});
	} catch(e){}


	// releases AddThis Button
	try {
		$('addthis').addEvents({
			'mouseout': function(){
				return addthis_close();
			},
			'click': function(){
				return addthis_open(this, '', '[URL]', '[TITLE]');
			}
		});
	} catch(e){}


	// releases img change SRC
	try {
		$$('img.sys-img-swap-src').addEvents({
			'mouseover': function() {
				var path = this.get('src');
				var ext = path.split(".").pop();
				var newPath = path.replace(ext, 'hover.' + ext);
				return this.set('src', newPath);
			},
			'mouseout': function() {
				var newPath = this.get('src').replace('hover.', '');
				return this.set('src', newPath);
			}
		});
	} catch(e){}



	// subscribe form buttons fix
	try {
		var buttonElements = $$('#article_subscribe button[type="submit"]');
		buttonElements.each(function(e){
			e.addEvent('click' , function(){
				$('article_subscribe_mode').set('value', e.get('val'))
				this.getParent('form').submit();
			});
		});
	} catch(e){}

	// release BUTTON as LINKS
	try {
	$$('button.ui-link').addEvent('click', function(){
	window.location.href = this.get('name');
	return false;
	});
	} catch(e){}


	return true;
});
