var app = {
	parentNode: window,
	widgets: {},

	ready: function(){
		window.setTimeout(function(){
			events.dispatch({
				type: "ready",
				target: app
			})
		}, 0);
	},
	destroy: function(){
		events.dispatch({
			type: "destroy",
			target: app
		});

		for (var type in app.__events)
			if (type != "ready")
				for (var handl in app.__events[type])
					delete app.__events[type][handl];
	}
};

new function(){
	app.newWidget = function(prototype) {
		return app.widgets[prototype.name] = new Widget(prototype);
	};

	function Widget(prototype) {
		if (!prototype.name)
			throw new Error("Widget Class must have name defined.");

		this.__class = extend(function(element, settings) {
			events.add(app, "destroy", bind(destroy, this));
			this.__bound = [];

			extend(this, settings, { element: element }).construct();
		}, {
			prototype: extend(
				copy(this._proto),
				prototype
			)
		});
	}

	function destroy(){
		this.destroy();
		this.removeEvent();
		this.unbind.apply(this.__bound);
		delete this.element.__widgets[this.name];
		this.element = null;
	}

	extend(Widget.prototype, {
		run: function(select, settings) {
			if(!select) return;
			select = select instanceof Array
				? select : [select];

			for (var i = 0; i < select.length; i++) {
				var widgets = select[i].__widgets;
				if (!widgets)
					widgets = select[i].__widgets = {};

				(widgets[this.name] = widgets[this.name]
					? extend(widgets[this.name], settings)
					: new this.__class(select[i], settings)
				).initilize();
			}
		},

		_proto: {
			construct: function(){},
			initilize: function(){},
			destroy: function(){},

			addEvent: function(type, method) {
				events.add(this.element, type, method = bind(method, this));
				return method;
			},
			removeEvent: function(type, method) {
				events.remove(this.element, type, method);
			},
			dispatchEvent: function(event) {
				if (typeof event == 'string')
					event = { type: event, target: this.element };
				else if (!event.target)
					event.target = this.element;
				events.dispatch(event);
			},
			bind: function() {
				for (var i = 0, a = arguments; i < a.length; i++) {
					this.element[a[i]] = bind(this[a[i]], this);
					this.__bound.push(a[i]);
				}
			},
			unbind: function() {
				for (var i = 0, a = arguments; i < a.length; i++)
					delete this.element[a[i]]
			}
		}
	});
};

app.newWidget({
	name: 'animatedHover',
	
	over: function(p) {},
	out: function(p) {},
	showbg: function(p) {},
	hidebg: function(p) {},
	
	hoverTime: null,
	overDelay: 100,
	outDelay: 100,
	overDuration: 300,
	outDuration: 300,
	target: null,
	
	position: 0,

	construct: function() {
		this.bind('_mouseover', '_mouseout', '_over', '_out');
		events.hover(this.element, this.element._mouseover, this.element._mouseout);
	},

	initilize: function() {
		if (!this.target) this.target = this.element;
	},

	_mouseover: function(e) {
		window.clearTimeline(this.hoverTimer);
		this.hoverTimer = window.setTimeout(this.element._over, this.overDelay);
		this.dispatchEvent({ type: '_mouseover', target: this.banner, relatedTarget: this.element });
	},

	_mouseout: function(e) {
		window.clearTimeline(this.hoverTimer);
		this.hoverTimer = window.setTimeout(this.element._out, this.outDelay);
		this.dispatchEvent({ type: '_mouseout', target: this.banner, relatedTarget: this.element });
	},

	_over: function() {
		window.clearTimeline(this.timelineTimer);
		var duration = this.overDuration - this.position * this.overDuration,
			_this = this, start = this.position;
		this.timelineTimer = window.setTimeline(function(p) {
			_this.position = start + (1 - start) * p;
			_this.over.call(_this.target, _this.position);
		}, duration);
	},

	_out: function() {
		window.clearTimeline(this.timelineTimer);
		var duration = this.outDuration - (1 - this.position) * this.outDuration,
			_this = this, start = this.position;
		this.timelineTimer = window.setTimeline(function(p) {
			_this.position = start - start * p;
			_this.out.call(_this.target, _this.position);
		}, duration);
	}
});

app.newWidget({
	name: 'indexBanner',
	images: [],
	loading: false,
	
	overDelay: 100,
	outDelay: 300,
	
	construct: function() {
		var self = this;
		var blocks = dom.getByClass('block', this.element);
		this.initialize(blocks);
		
		this.addEvent('_mouseover', this.setBackground);
		this.addEvent('_mouseout', this.restoreBackground);
	},

	initialize: function(blocks) {
		for (var i = blocks.length - 1; i >= 0; i--) { 
			this.animateHover(blocks[i]);
		};
	},

	animateHover: function(elem) {
		var content = dom(elem, 'ul')[0];
		if(content) {
			var contentHeight = content.offsetHeight;
			content.style.height = 0;
			app.widgets.animatedHover.run(elem, {
			target: {
				content: content
			},
			banner: this.element,
			overDuration: 250,
			outDuration: 650,
			over: function(p) {
				this.content.style.height = contentHeight * ease(p) + 'px';
			},
			out: function(p) {
				this.content.style.height = contentHeight * ease(p) + 'px';
			}
			});
		}
        else {
            app.widgets.animatedHover.run(elem, {
                banner: this.element,
                overDuration: 250,
                outDuration: 650
            });
        }
	},
	
	setBackground: function(e) {
		var self = this;
		window.setTimeout(function() {
			dom.addClass(self.element, 'bg' + e.relatedTarget.id);
		}, this.overDelay);
	},
	
	restoreBackground: function(e) {
		var self = this;
		window.setTimeout(function() {
			dom.removeClass(self.element, 'bg' + e.relatedTarget.id);
		}, this.outDelay);
	}
});

app.newWidget({
	name: 'printVersion',
	sheets: {
		disabled: [],
		added: []
	},
	templates: {
		'printTrigger' : '<a id="printVersion" href="javascript:void(0);">%1</a>',
		'printButtons' : '<div id="printButtons"><button onclick="window.print();">%1</button>&nbsp;<button id="printClose">%2</button></div>' },
	translations: {
		lt: [ 'Spausdinti', 'Uždaryti' ],
		en: [ 'Print', 'Close' ]
	},
	currentLang: null,
	construct: function() {
		this.currentLang = document.body.className;
		if (!dom('banner') && !dom('broadcast')) {
			var printTrigger = dom.create(this.templates.printTrigger.format(this.translations[this.currentLang][0]));
			this.element.appendChild(printTrigger);
			events.add(dom('printVersion'), 'click', bind(this.switchToPrint, this));
		}
	},
	switchToPrint: function(e) {
		window.switchLayout = false;
		var tags = dom(dom(), 'style').concat(dom(dom(), 'link')), item, i = 0;
		for (; (item = tags[i]); i++) {
			if (item.rel == 'stylesheet' || item.type.indexOf('css') != -1) {
				if (/print/.test(item.media)) {
					var clone = item.cloneNode(false);
					clone.media = 'screen';
					this.sheets.added.push(clone);
					dom.before(clone, item);
				}
				else if (!/all/.test(item.media) && !item.disabled) {
					this.sheets.disabled.push(item);
					item.disabled = true;
				}
			}
		}
		var printButtons = dom.create(this.templates.printButtons.format(this.translations[this.currentLang][0], this.translations[this.currentLang][1]));
		dom.before(printButtons, dom().body.firstChild);
		events.add(dom('printClose'), 'click', bind(this.switchToDefault, this));
		return false;
	},
	switchToDefault: function() {
		var item, i = 0;
		dom.remove(dom('printButtons'));
		for (; (item = this.sheets.added[i]); i++) {
			dom.remove(item);
		}
		i = 0;
		for (; (item = this.sheets.disabled[i]); i++) {
			item.disabled = false;
		}
	}

});

events.add(app || window, 'ready', function() {
	app.widgets.indexBanner.run(dom('banner'));
	app.widgets.printVersion.run(dom('topmenu'), {});
});


events.add(window, 'load', function(){
	if (!window.opera) try { document.execCommand("BackgroundImageCache", false, true); } catch(e) {};
});

events.add(window, "unload", app.destroy);

function showNextPage(url){
	$.get(url, function(h){
		$('#broadcasts-list').html(h);
	});
}

$(document).ready(function(){
  $('<img src="css/images/ico.pdf.gif" class="ico-pdf" alt="PDF" />').insertAfter('#content a.link-pdf');
});