(function($) {

	$.animations['service_thumbs'] = {
		fadeouts: null,
		loaded: false,
		thumbs: [],
		mains: {},
		total: 0,
		interval: null,
		initialize: function(thumbs)
		{
			var T = $.animations.service_thumbs;
			T.thumbs = thumbs.all_thumbs;
			T.mains = thumbs.service_thumbs;

			T.fadeouts = $('#home-services>div.section,#home-clients-others');
			if ($.browser.msie) {
				T.fadeouts.css('visibility', 'hidden');
			} else {
				T.fadeouts.css('opacity', 0);
			}

			if (thumbs.hover_anim) {
				// prepare anim divs
				$('div.section>div.image').each(function(){
					var self  = $(this);
					var inner = document.createElement('DIV');
					$(inner).css({
						height: '100%'
					});
					self.append(inner);
				});

				// attach hover event handlers
				$('#home-services>div.section:not(.first)').hover(T.do_switch, T.stop_switch);

				// preload images
				var loaded = 0;
				function _image_done() {
					loaded = loaded + 1;
					if (loaded >= T.thumbs.length / 2) {
						T.loaded = true;
					}
				}
				for (i in T.thumbs) {
					var img = document.createElement('IMG');
					img.src = T.thumbs[i];
					$(img).load(_image_done);
				}
			}
		},
		start: function()
		{
			if ($.browser.msie) {
				$.animations.service_thumbs.fadeouts.css({'visibility': 'visible'});
			} else {
				$.animations.service_thumbs.fadeouts.animate({'opacity': 1});
			}
		},
		do_switch: function()
		{
			var T = $.animations.service_thumbs;
			if (!T.loaded) {
				return;
			}
			var self = $(this);
			var first = 1;
			var cur = 0;
			var imgs = T.thumbs;
			var slide = function() {
				if (cur == imgs.length) cur = 0;
				var div = self.find('div.image');
				var inner = div.find('div');
				var nimg = '';
				if (first) {
					nimg = div.css('backgroundImage');
					first = 0;
				} else {
					var next = cur - 1;
					if (next == -1) next = imgs.length - 1;
					nimg = "url('"+imgs[next]+"')";
				}
				inner.css({
					backgroundImage: nimg,
					opacity: 1
				});
				div.css('backgroundImage', "url('"+imgs[cur]+"')");
				inner.animate({
					opacity: 0
				}, 350);
				cur++;
			}
			T.interval = window.setInterval(slide, 500);
		},
		stop_switch: function()
		{
			var T = $.animations.service_thumbs;
			if (!T.loaded) {
				return;
			}
			var self = $(this);
			var id = self.attr('id').split('-').slice(1).join('-');
			var div = self.find('div.image');
			var inner = div.find('div');
			div.css('backgroundImage', "url('"+T.mains[id]+"')");
			inner.css('backgroundImage', 'none');
			if (T.interval) {
				window.clearInterval(T.interval);
			}
		}
	};

})(jQuery);