(function() {

	var parse = function(source, separator) {
		var fields = new Hash({});
		if (source.length) source.split(separator).filter($chk).each(function(val) {
			var parts = val.split('=', 2);
			fields[decodeURIComponent(parts[0])] = parts[1] ? decodeURIComponent(parts[1]) : true;
		});
		return fields;
	}
	
	window.QueryString = parse(location.search.substr(1), '&');
	window.HashString = new (new Class({
	
		Implements: Events,
		
		initialize: function() {
			this.update().listen();
		},
		
		get: function(key) {
			var val = this.values.get(key);
			return val ? decodeURIComponent(val) : null;
		},
		
		listen: function() {
			if (!this.ignore && location.hash != this.raw) this.update();
			arguments.callee.delay(250, this);
			return this;
		},
		
		save: function() {
			location.hash = this.raw = this.values.toQueryString();
			return this;
		},
		
		set: function(key, val) {
			this.values.set(key, encodeURIComponent(val));
			this.save();
			return this;
		},
		
		update: function() {
			this.values = parse((this.raw = location.hash).substring(1), '&');
			this.fireEvent('change');
			return this;
		}
		
	}));

})();

var WaveDeco = {

	place: function(container, src) {
		window.addEvent('load', function() {
			if (!Browser.Engine.trident4) {
				swfobject.embedSWF(src || '/files/cupori/swf/water_1000x320.swf', container, '100%', '320', '9.0.0', null, null, {
					scale: 'exactfit',
					wmode: 'transparent'
				});
			}
			else {
				var img = document.createElement('img');
				img.src = '/files/cupori/decoration/waves-light.jpg';
				img.height = 331;
				$(container).adopt(img);
			}
		});
	}
	
};

var HotScroller = new Class({
	
	Implements: Options,
	
	options: {
		delay: 3000
	},
	
	initialize: function(el, options) {
		this.element = $(el);
		this.setOptions(options);
		this.next();
	},
	
	next: function() {
		this.swap.delay(this.options.delay, this);
	},
	
	swap: function() {
		this.element
			.getFirst()
			.fade('out')
			.get('tween')
			.chain(function() {
				this.element
					.adopt(this.element.getFirst());
				this.element
					.getFirst()
					.fade('hide')
					.fade('in');
				this.next();
			}.bind(this));
	}
	
});

HotScroller.make = function(el) {
	return new HotScroller(el);
};

var EasyDrop = new Class({
	
	options: {
		adjustY: -3
	},
	
	initialize: function(el) {
		this.element = $(el).addEvents({
			click: function(e) {
				e.stopPropagation();
				this.toggle();
			}.bind(this),
			mouseenter: function() {
				$clear(this.hideTimer);
			}.bind(this),
			mouseleave: function() {
				$clear(this.hideTimer);
				this.hideTimer = this.hide.delay(1000, this);
			}.bind(this)
		});
		this.dropdown = this.element.getElement('dd');
		this.choices = this.dropdown.getElement('ul');
		this.hideEffect = new Fx.Tween(this.choices, {
			duration: 350,
			transition: 'expo:in',
			onComplete: function() {
				this.element.removeClass('expanded');
			}.bind(this)
		});
		this.showEffect = new Fx.Tween(this.choices, {
			duration: 1000,
			transition: 'bounce:out',
			onStart: function() {
				this.element.addClass('expanded');
			}.bind(this)
		});
		this.choices.setStyles({
			'margin-top': -this.choices.offsetHeight + this.options.adjustY
		});
		this.open = false;
	},
	
	hide: function() {
		var top = -this.choices.offsetHeight + this.options.adjustY;
		if (Browser.Engine.trident4) {
			this.choices.setStyle('margin-top', top);
			this.element.removeClass('expanded');
		}
		else {
			this.showEffect.pause();
			this.hideEffect.start('margin-top', top);
		}
		this.open = false;
	},
	
	show: function() {
		if (Browser.Engine.trident4) {
			this.element.addClass('expanded');
			this.choices.setStyle('margin-top', 0);
		}
		else {
			this.hideEffect.pause();
			this.showEffect.start('margin-top', 0);
		}
		this.open = true;
	},
	
	toggle: function() {
		if (this.open) this.hide();
		else this.show();
	}
	
});

EasyDrop.make = function(el) {
	return new EasyDrop(el);
};

var FontSize = new function() {

	var original, step = 0;

	function parse(value) {
		return {
			value: parseFloat(value),
			unit: String(value).match(/[a-z%]*$/)[0] || 'px'
		};	
	}
	
	function adjust(by) {
		var el = $(document.body);
		if (!original) original = parse(el.getStyle('font-size'));
		step = (step + by).limit(-2, 4);
		el.setStyle('font-size', (original.value + original.value * 0.2 * step) + original.unit);
		if (window.Cufon) Cufon.refresh();
	}

	this.larger = function(e) {
		if (e) e.preventDefault();
		adjust(1);
	},

	this.smaller = function(e) {
		if (e) e.preventDefault();
		adjust(-1);
	}
	
};

var ProductTabs = new Class({

	initialize: function(el) {
		if (window.inAdminMode) return;
		this.element = $(el);
		this.attach();
		this.persist();
	},
	
	attach: function() {
		var instance = this;
		//$('product-intro').set('html', '');
		this.element.getElement('ul').getChildren('li').getElement('a').each(function(el) {
			this.find(this.url(el), $('secondary-nav')).addEvent('click', function(e) {
				e.target.blur();
				instance.load(el.getParent('li').getElement('li a'));
			});
		}, this);
		this.element.getElements('a').addEvent('click', function(e) {
			e.target.blur();
			var el = this.getParent('li').getElement('li a') || this;
			instance.load(el);
		});
		fixTooLongProductTabs();
	},
	
	find: function(href, context) {
		if (!href) return;
		if (!context) context = this.element;
		var matches = context.getElements('a').filter(function(el) {
			return this.url(el) == href;
		}, this);
		var found = matches[0];
		if (!found) return;
		return found.getParent().getElement('ul a') || found;
	},
	
	load: function(el) {
		this.select(el);
		el.addClass('loading');
		new Request({
			url: this.url(el.getParent('ul').getPrevious('a'))
		}).addEvent('success', function(response) {
			$('product-intro').set('html', response.match(/<!--CM_PRODUCT_INTRO_BEGIN-->([\s\S]*?)<!--CM_PRODUCT_INTRO_BEGIN-->/)[1]);
			if (window.Cufon) Cufon.refresh();
		}).get({
			ts: $time()
		});
		new Request({
			url: this.url(el)
		}).addEvent('success', function(response) {
			$('product').set('html', response.match(/<!--CM_PRODUCT_DATA_BEGIN-->([\s\S]*?)<!--CM_PRODUCT_DATA_END-->/)[1]);
			fixTooLongProductTabs();
			var title = (response.match(/<title>([\s\S]*)<\/title>/) || [])[1];
			if (title) document.title = title;
			this.removeClass.delay(250, this, 'loading');
			if (window.Cufon) Cufon.refresh();
			poisonContent();
		}.bind(el)).get({
			ts: $time()
		});
	},
	
	loadByUrl: function(url) {
		var el = this.find(url);
		if (!el) return;
		this.load(el);
	},
	
	persist: function() {
		var url = location.hash.substr(1);
		var now = this.element.getElement('li li.current a');
		if (now && this.url(now) == url) return;
		if (url) this.loadByUrl(url);
		else if (!this.element.getElement('li li.current')) this.load(this.element.getElement('li.current ul a, li.current a, li li a'));
	},
	
	select: function(el) {
		el = $(el);
		this.element.getElements('li').removeClass('selected');
		var last;
		for (; el && el != this.element; el = el.getParent())
			if (el.get('tag') == 'li') last = el.addClass('selected');
		var menu = this.find(this.url(last.getElement('a')), $('secondary-nav'));
		if (!menu) return;
		$$('#secondary-nav li').removeClass('current');
		menu.getParent('li').addClass('current');
	},
	
	url: function(el) {
		return (el.hash && el.hash.substring(1)) || '';
	}

});

ProductTabs.make = function(el) {
	return new ProductTabs(el);
};

var FeedTabs = new Class({

	initialize: function(el) {
		this.element = el;
		this.tabMap = {};
		this.element.getElements('dt.tab').each(function(el) {
			this.tabMap[this.url(el.getElement('a'))] = el;
		}, this);
		this.attach();
		this.persist();
	},
	
	activate: function(tab, url) {
		if (!tab) return;
		if (!url) url = this.url(tab.getElement('a'));
		this.element.addClass('feeds-loading');
		var content = this.relatedContent(tab);
		new Request({
			url: url
		}).addEvents({
			success: function(response) {
				content.empty();
				content.set('html', (response.match(/<!--BEGIN_ACTIVE_TAB_CONTENT-->[\s\S]*<!--END_ACTIVE_TAB_CONTENT-->/) || [])[0]);
				var title = (response.match(/<title>([\s\S]*)<\/title>/) || [])[1];
				if (title) document.title = title;
				this.element.getChildren('.active-tab').removeClass('active-tab');
				tab.addClass('active-tab');
				content.addClass('active-tab');
				this.poison(content);
				HashString.set('furl', url);
				this.element.removeClass.delay(500, this.element, 'feeds-loading');
			}.bind(this)
		}).get();
	},
	
	attach: function() {
		var instance = this;
		this.element.getChildren('dt').addEvent('click', function(e) {
			e.stop();
			instance.activate(this);
		});
	},
	
	hasContent: function(tab) {
		return !!this.relatedContent(tab).get('html').trim().length;
	},
	
	persist: function() {
		var url = HashString.get('furl');
		var tab = this.tabMap[url] || this.element.getElement('dt.active-tab');
		if (!this.hasContent(tab)) this.activate(tab, url);
	},
	
	poison: function(el) {
		var instance = this;
		el.getElements('dl.dropdown').each(EasyDrop.make);
		el.getElements('div.picture a').each(ImagePopup.make);
		el.getElements('a').addEvent('click', function(e) {
			if ((this.hostname != location.hostname) || $(e.target).getParent('.picture')) return false;
			instance.activate(instance.element.getElement('dt.active-tab'), instance.url(this));
			return false;
		});
	},
	
	relatedContent: function(tab) {
		return $(tab.className.match(/go-(\w+)/)[1]);
	},
	
	url: function(el) {
		var url = el.pathname;
		if (url.charAt(0) != '/') url = '/' + el.pathname;
		return url;
	}

});

FeedTabs.make = function(el) {
	return new FeedTabs(el);
};

ImagePopup = {
	
	make: function(el) {
		return new ReMooz($(el).adopt(new Element('span', { 'class': 'zoom' })), {
				centered: true,
				dragging: false,
				cutOut: false,
				origin: el.getElement('img')
		});
	}
	
};

var DynamicURL = (function() {

	var links = document.getElementsByTagName('a'), map = {};
	
	function replace(link) {
		if (link.hostname != location.hostname) return;
		var url = link.pathname;
		if (url.charAt(0) != '/') url = '/' + url;
		var mapped = map[url];
		if (!mapped) return;
		link.href = mapped;
	}
	
	return {
		
		process: function() {
			for (var i = 0, l = links.length; i < l; ++i) replace(links[i]);
		},
		
		register: function(template, urls) {
			for (var i = 0, l = urls.length; i < l; ++i) {
				map[urls[i]] = template.replace('@url@', urls[i]);
			}
			if (map[location.pathname]) location.href = map[location.pathname];
		}

	};

})();

function fixTooLongProductTabs() { // :(
	$$('#product div.description').each(function(desc) {
		var items = $$('#product-tabs li.selected li');
		var rows = 0;
		for (var i = 0, l = items.length; i < l; ++i) {
			if (i == 0 || items[i].offsetLeft <= items[i - 1].offsetLeft)
				++rows;
		}
		desc.addClass('at-' + rows + '-rows');
	});
}

function initContentActions() {

	$$('a.share').removeEvents('click').addEvent('click', function() {
		location.href =  this.href + '?' + Hash.toQueryString({
			link: location.href,
			about: document.title
		});
		return false;
	});
	
	$$('a.print').removeEvents('click').addEvent('click', function() {
		window.print();
		return false;
	});
	
}

function poisonContent() {
	$$('table tbody tr:nth-child(odd)').addClass('odd');
	$$('table tbody tr:last-child').addClass('last');
	$$('table td:last-child').addClass('last');
	$$('table').each(function(table) {
		new Element('div', { 'class': 'table-cover' }).wraps(table);
	});
	// fixes tinymce "fun"
	$$('h2 img:only-child').each(function(img) {
		img.replaces(img.getParent());
	});
	// fixes wrongly entered content
	$$('div.infobox h3 ~ h3').addClass('not-first-of-type');
	if (Browser.Engine.trident4) {
		$$('table td:first-child').addClass('first');
		$$('li:first-child').addClass('first');
		$$('table + p em, div.table-cover + p em').addClass('table-description');
		$$('button').addEvents({
			mouseenter: function() {
				this.addClass('hover');
			},
			mouseleave: function() {
				this.removeClass('hover');
			}
		});
	}
	initContentActions();
}

window.init = function() {

	if (window.Cufon) {
	
		Cufon.replace('#content h1, #showcase .title', {
			fontFamily: 'NB 55'
		});
	
		if (!$(document.body).hasClass('ru_RU')) {
		
			Cufon.replace('#intro h2, #intro p, #content h2, .apply-font-1', {
				fontFamily: 'Avenir Next LT Pro'
			});
			
			Cufon.replace('dl.feeds dt.tab', {
				fontFamily: 'Avenir Next LT Pro',
				textShadow: '1px 1px rgba(0, 0, 0, 0.2)'
			});
	
		}
	
		Cufon.DOM.ready();
		
	}
	
	DynamicURL.process();
	
	$$('#content h1 + p').addClass('p-after-h1');
	
	// this fixes erronous content
	$$('div.infobox h3 ~ h3').addClass('not-first-of-type');
	
	$$('div.box-2-ss').each(function(el, i) {
		if (i % 2 == 0) el.addClass('box-first-in-row');
	});
	
	$$('div.box-3-ss').each(function(el, i) {
		if (i % 3 == 0) el.addClass('box-first-in-row');
	});
	
	$$('div.hibox li a').each(function(el) {
		new Element('span', { text: '>', 'class': 'after' }).inject(el, 'bottom');
	});
	
	$$('dl.tabbed dt').reverse().each(function(el) {
		el.inject(el.getParent(), 'top');
	});
	
};

window.addEvent('domready', function() {

	$$('#lang dl, dl.dropdown').each(EasyDrop.make);
	$$('#hot ul').each(HotScroller.make);
	$$('#product-tabs').each(ProductTabs.make);
	$$('dl.feeds').each(FeedTabs.make);
	$$('ul.feed-items div.picture a').each(ImagePopup.make);
	
	$$('.larger-text').addEvent('click', FontSize.larger);
	$$('.smaller-text').addEvent('click', FontSize.smaller);
	
	poisonContent();
	fixTooLongProductTabs();
	
	$$('ul.purposes span.cover').set({
		tween: { duration: 'short' },
		styles: { opacity: 0, visibility: 'visible' }
	}).getParent('a').addEvents({
		mouseenter: function() {
			this.getElement('.cover').tween('opacity', 0.5);
		},
		mouseleave: function() {
			this.getElement('.cover').tween('opacity', 0);
		}
	});
	
	$$('#product-tabs > ul > li > a, div.easytabs a').each(function(link) {
		link.adopt(new Element('span', { 'class': 'l1-hilite' }));
	});

});