Ext.namespace('App');

App.init = function () {
	this.initMenu();
	var el = Ext.get('carousel');
	if (el) {
		this.initCarousel(el);
	}
}

App.initMenu = function () {
	var el = Ext.get('mainmenu');
	if (el && Ext.isIE) {
		el.setHeight(24);
	}
	var el = Ext.get('mainmenu-list');
	if (el) {
		App.menu = new Ext.ux.Menu(el, {
			transitionType: 'slide'
		});
		el.show();
		//App.menu.showMenu();
	}
};

App.initCarousel = function (el) {
	App.photoTemplate = new Ext.Template([
		'<a href="{href}" class="lightbox" title="{title}">',
			'<img src="{src}" width="100%">',
		'</a>'
	]);

	App.carousel = new Ext.ux.Carousel(el, {
		interval: 5,
		itemSelector: 'a.lightbox',
		showPlayButton: true,
		pauseOnNavigate: true,
		freezeOnHover: true,
		navigationOnHover: true,
		transitionEasing: 'easeIn'
    //transitionType: 'fade'
	});

	Ext.Ajax.request({
		url: './js/images.js',
		success: App.updatePhotos,
		scope: App
	})

	Ext.ux.Lightbox.init();
	Ext.ux.Lightbox.register('a.lightbox', true);

	Ext.ux.Lightbox.on('open', function() {
		App.carousel.pause();
	}, this);

	Ext.ux.Lightbox.on('close', function(image) {
		App.carousel.setSlide(image);
		App.carousel.play();
	}, this);

};

App.updatePhotos = function (resp) {
	var data = this.getJSONFromResponse(resp);
	if (data) {
		this.carousel.clear();
		Ext.each(data.items, function(item) {
				this.carousel.add(this.photoTemplate.append('carousel', item));
		}, this);

		this.carousel.refresh().play();
	}

};

App.getJSONFromResponse = function (response) {
	var s = null, json = null;
	try {
		json = response.responseJSON;
		if (!json) {
			s = response.responseText;
			if ((s !== undefined) && (s !== '')) {
				json = Ext.decode(s);
			} else if (response.transport) {
				s = response.transport.responseText;
				if ((s !== undefined) && (s !== '')) {
					json = Ext.decode(s);
				}
			}
		}
	} catch (e) {}
	return json;
};


Ext.onReady(App.init, App);

