//videoStreamErrorHandler is defined in embed.js

function onMediaPlaybackError(playerId, code, message, detail)
{
	var videoRequest = videoStreamErrorHandler.request;
	
	if(videoStreamErrorHandler.retryCount < 3)
		retryTimeout = setTimeout("videoStreamErrorHandler.container.setMediaResourceURL(\""+videoRequest.url+"\",\""+videoRequest.poster+"\")",150);

	videoStreamErrorHandler.retryCount++;
}

$(function() {
	
	$('html').addClass('js');
	var cookie = { 'path': '/' }
	
	if (typeof(VideoJS) !== 'undefined') {
		VideoJS.setupAllWhenReady();
	}
	
	$('.gallery').m2gallery();
	if(!$('#content').hasClass('hemnet')) {
		if(typeof $.prettyPhoto == 'object') {
			$('a[rel=pop],a.pop').prettyPhoto({ theme: 'newsletter', allow_resize: false, opacity: 0, animation_speed: 'fast', show_title: false, modal: true });
			$('a.pop_london').prettyPhoto({ theme: 'london', allow_resize: false, opacity: 0, animation_speed: 'fast', show_title: false, modal: true });
			$('a.pop_christmas').prettyPhoto({ theme: 'christmas', allow_resize: false, opacity: 0, animation_speed: 'fast', show_title: false, modal: true });
			$('a.pop_white_orange').prettyPhoto({ theme: 'white_orange', allow_resize: false, opacity: 0, animation_speed: 'fast', show_title: false, modal: true });
		}
	}

	if ($('#register_form').length > 0) {
		
		$("#register_form input:text").each(function() {
			if ($(this).val() == 'obligatoriskt') {
				$(this).css({'color': '#a2a3a5', 'font-style': 'italic'});
			} else {
				$(this).css({'color': '#000', 'font-style': 'normal'});
			}
		});
		
		$("#register_form input:text").bind({
			focus: function() {
				if ($(this).val() == 'obligatoriskt') {
					$(this).css({'color': '#000', 
							'font-style': 'normal'}).val('');
				}
			},
			blur: function() {
				if ($(this).val() == '') {
					$(this).css({'color': '#a2a3a5', 
							'font-style': 'italic'}).val('obligatoriskt');					
				}
			}
		});
		
		$('#register_form input.submit').click(function() {
			$('#register_form input:text').each(function() {
				if ($(this).val() == 'obligatoriskt') {
					$(this).val('');
				}
			});
			return true;
		});
	}

	/**
	 * Startpage
	 */
	$('#startpage-video').disableSelection().each(function() {
		
		var $left = $("a[rel='left']", '#video-pager-nav'),
			$right = $("a[rel='right']", '#video-pager-nav'),
			$pageinfo = $('em', '#page-information'),
			item_height = 50;
			
		var $items, $page, items, pages, page;
		
		$('a', '#startpage-video-tabs').click(function() {
			$('a', '#startpage-video-tabs').removeClass('active');
			$(this).addClass('active');
			$('.video-type', '#startpage-video').hide();
			$('#'+this.id.replace('show-', '')).show();
			
			$items = $('.video-type:visible a', '#startpage-video');
			
			items = $items.size();
			pages = Math.ceil(items / 5);
			page = 1;

			$pageinfo.html('1/'+pages);
			
			$left.addClass('disabled');
			$right.addClass('disabled');

			if(pages > 1) {
				$right.removeClass('disabled');
			}
			
			_gaq.push(['_trackEvent', 'StartPageVideo', 'Tab', $(this).attr('href').replace('#', '')]);
			return false;
		}).eq(0).trigger('click');

		$('a', '#video-pager-nav').click(function() {
			var $button = $(this),
				direction = $button.attr('rel'),
				disabled = $button.hasClass('disabled'),
				$page = $('.video-pages', '.video-type:visible');
				
			if(!disabled) {
				if(direction == 'right') {
					$pageinfo.html(++page+'/'+pages);
					if(page == pages) {
						$button.addClass('disabled');						
					}
					if (page > 1) {
						$left.removeClass('disabled');						
					}
					_gaq.push(['_trackEvent', 'StartPageVideo', 'Page', $page.attr('id') + '-right']);
				} else {
					$pageinfo.html(--page+'/'+pages);
					if(page == 1) {
						$button.addClass('disabled');
					}
					if (page < pages) {
						$right.removeClass('disabled');						
					}
					_gaq.push(['_trackEvent', 'StartPageVideo', 'Page', $page.attr('id') + '-left']);
				}
				$page.stop().animate({ 'scrollTop': (((page-1) * 5) * item_height) }, 400);
			}
			return false;
		});
		
		$('a', '.video-type').click(function(ev) {
			var id = this.id.replace('video-', ''),
				video = videos[id] || null,
				$link = $(this),
				$placeholder = $('#video-placeholder'),
				$video = $('video', $placeholder),
				$flash = ($.browser.msie) ? window['video-placeholder'] : document['video-placeholder'],
				$desc = $('span.description', '#startpage-video-details');
			
			videoStreamErrorHandler.container = $flash;	
			
			if(!$link.hasClass('active') && video) {
				$('a', '.video-type').removeClass('active');
				$(this).addClass('active');
				
				if($video.size()) { // html5

					var video_html = "";
					video_html += '<video width="100%" height="100%" controls>';
					video_html += '<source type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />';
					video_html += '</video>';
					
					$placeholder.empty().html(video_html);					
					$placeholder.find('video').attr('src', video.m3u8);
					$placeholder.find('video').attr('poster', video.poster);
					VideoJS.setup($placeholder.find('video').get(0));

				} else { // flash
         			//$flash.setMediaResourceURL(video.smil);
					videoStreamErrorHandler.retryCount = 0;
					videoStreamErrorHandler.request = {url: video.large, poster: video.poster};
         			$flash.setMediaResourceURL(video.large, video.poster);
				}
				
				$('#startpage-video-details').find('a.button').remove();
				if(video.link) {
					$('#startpage-video-details').append($('<a />', { 'className': 'button button-inactive', href: video.link }).html('<span>'+video.linktitle+'</span>'));
				}
				
				$desc.html(video.desc);
				$desc.css('bottom', ($desc.height() < 30) ? 10 : 0);
				_gaq.push(['_trackEvent', 'StartPageVideo', 'ChangeVideo', video.desc]);
			}
			return false;
		}).eq(0).addClass('active');
	});
	
	$('#startpage-splash').disableSelection().each(function(n, item) {
		var $splash = $('#startpage-splash');
		var $container = $('#startpage-splash-container');
		var $slides = $container.find('.splash');
		var $thumbs = $('#startpage-splash-thumbnails');
		
		var stage_width = $('#startpage-splash').width(),
			thumb_width = 58,
			slide_speed = 2000,
			slide_interval = 8000,
			item = 0,
			items = $slides.size(),
			autoslide;
		
		if(items <= 1) return
		$slides.each(function(n, item) {
			$(item).attr('rel', n);
		});
		
		$thumbs.css({ 'left': (stage_width / 2) - (((thumb_width+10) * items / 2)) - 10}).css('height', 0);
		$thumbs.find('a').css('opacity', 0.7).eq(0).css('opacity', 1);
		$thumbs.find('a').click(function() {
			$thumbs.find('a').css('opacity', 0.7);
			$(this).css('opacity', 1);
			item = this.rel;
			var splash_index = $('.splash[rel='+item+']', $container).index();
			$container.stop(false, false).animate({ left: -(splash_index * stage_width)}, { duration: 1000, complete: function() {
				$container.append($container.find('.splash:lt('+splash_index+')'));
				$container.css({ 'left': 0 });
			}});
			return false;
		});
		
		$splash.hover(function() {
			clearInterval(autoslide); 
			$thumbs.animate({ 'height': 50}, 120);
		}, function() {
			$thumbs.animate({ 'height': 0}, 60);
			autoslide = setTimeout(function() {
				auto_slide();
				autoslide = setInterval(auto_slide, slide_interval);
			}, slide_speed);
		})
		
		$container.css('width', items * stage_width);
		
		autoslide = setInterval(auto_slide, slide_interval);
		function auto_slide() {
			++item;
			if(item + 1 > items) {
				item = 0;
			}
			$thumbs.find('a').css('opacity', 0.7).eq(item).css('opacity', 1);
			$container.animate({ 'left':  -stage_width }, { duration: slide_speed, complete: function() {
				$container.append($container.find('.splash').eq(0));
				$container.css({ 'left': 0 });
			}});
		}
		
	});
	
	/**
	 * Brokers
	 */
	$('#brokers').delegate('#broker-area-dropdown', 'change', function() {
		var $brokers = $('#brokers');
		var val = $(this).val();
		if(val.length) {
			$.ajax({
				'type': 'post',
				'url': m2.baseUrl + 'brokers/get_broker_by_area/',
				'data': 'name='+val,
				'success': function(response) {
					$brokers.find('.broker-list').html("").html(response);
				}
			})
		}
	});
	
	$('#wrapper').delegate("a.video-link,a.video-button", 'click', function() {
		$('#video-popup').remove();
		var url = $(this).attr('href');
		var $iframe = $('<iframe />', { src: url, frameborder: 0 });
		var $close = $('<a />', { id: 'video-close' }).click(function() { $('#video-popup').remove(); });
		var $video = $('<div />', { id: 'video-popup' }).append($close).append($iframe)
				.css('top', $(window).scrollTop() + ($(window).height() - 469) / 2);
		if($.browser.msie) {
			$video.css('border', '1px solid #ddd');
		}
		$('#wrapper').append($video);
		_gaq.push(['_trackEvent', 'VideoPopup', 'Open', url]);
		return false;
	});
	
	$(window).scroll(function() {
		$('#video-popup').stop().animate({ top: $(window).scrollTop() + ($(window).height() - 469) / 2 }, 500);
	});
	
	/**
	 * Object
	 */
	/*
	$('#object-list').each(function() {
		var $objects = $('.object', '#object-list');
		$(window).keydown(function(e) {
			var $object;
			switch(e.which) {
			case 75: // k
			case 38: // up
				if($('.object', '#object-list').is('.active')) {
					$object = $objects.filter('.active');
					if($object.index() == 0) {
						$object.removeClass('active');
						$object = $objects.eq(-1);
						$object.addClass('active');
					} else {
						$object.removeClass('active').prev().addClass('active');
					}
				} else { 
					$object = $objects.eq(-1)
					$object.addClass('active');
				}
				$('body').animate({ 'scrollTop': $object.prev().offset().top-50 }, 0);
				e.preventDefault();
				break;
			case 74: // j
			case 40: // down
				if($('.object', '#object-list').is('.active')) {
					$object = $objects.filter('.active');
					if($object.index() == $objects.eq(-1).index()) {
						$object.removeClass('active');
						$object = $objects.eq(0);
						$object.addClass('active');
					} else {
						$object.removeClass('active').next().addClass('active');
					}
				} else { 
					$object = $objects.eq(0)
					$object.addClass('active');
				}
				$('body').animate({ 'scrollTop': $object.offset().top-50 }, 0);
				e.preventDefault();
				break;
			case 79: // o
				location.href = $('.object.active .buttons a', '#object-list').attr('href');
				break;
			case 39: // right
				$('.active .gallery-next', '#object-list').trigger('click');
				break;
			case 37: // left
				$('.active .gallery-prev', '#object-list').trigger('click');
				break;
			}
		});
	});
	*/
	
	$('a.button_print').click(function() {
		$(this).parents('li.print-settings').addClass('print-open');
		var hide;
		$('div.print-settings').hover(function() {
			clearTimeout(hide);
		},function() {
			hide = setTimeout(function() {
				$('li.print-settings').removeClass('print-open');
			}, 400);
		});
		return false;
	});
	
	$('a#button-floorplan').click(function() {
		var win = window.open(this.href, 'images', "width=800,height=650,toolbars=0,scrollbars=1");
		return false;
	});
	
	$('a#button-furnish').click(function() {
		var win = window.open(this.href, 'images', "width=100,height=100,toolbars=0,scrollbars=1");
		return false;
	});
	
	$('#print-object').click(function() {
		var options = [];
		$('.print-settings input').each(function(n, item) {
			if(item.checked) options.push(item.value);
		});
		if(!options.length) options.push(1);
		var print = window.open(this.href + '/print:'+options, 'print', 'width=960,height=700,toolbar=0,scrollbars=1');
		
		return false;
	});
	
	$('#object-budgivning a').click(function() {
		var budgivning = window.open($(this).attr('href'), 'budgivning', 'width=900,height=710,toolbar=0,scrollbars=1')
		return false;
	});
	
	$('#object-kalkyl a').click(function() {
		var kalkyl = window.open($(this).attr('href'), 'kalkyl', 'width=900,height=710,toolbar=0,scrollbars=1')
		return false;
	});
	
	$('a.show-on-map', '#object-nearby').click(function() {
		var map = window.open($(this).attr('href'), 'map', 'width='+($(window).width()*0.9)+',height='+($(window).height()*0.9+100)+',toolbar=0,scrollbars=1');
		return false;
	});
	
	$('a.show-more', '#object-nearby').click(function() {
		$(this).hide();
		$('div.more', '#object-nearby').slideDown(200);
		return false;
	});
	
	$('a.show-description', '#object-nearby').click(function() {
		$('div.description', '#object-nearby').slideDown(200);
		return false;
	});
	
	$('#area-objects').delegate('a.next', 'click', area_object_paginator);
	$('#area-objects').delegate('a.prev', 'click', area_object_paginator);
	
	function area_object_paginator(that) {
		var direction = this.className;
		$('#area-objects').load(this.href + ' #area-objects', function() {
			$('.gallery', '#area-objects').m2gallery();
			var script = 'http://s7.addthis.com/js/250/addthis_widget.js#username=hw2k&domready=1';
			if (window.addthis){
			    window.addthis = null;
			}
			$.getScript( script );
		})
		return false;
	}
	
	$('a', '#object-controls .left').click(function() {
		
		// Override streetview, IE9 bug, open new window
		if($(this).attr('class') == 'streetview' && jQuery.browser.msie && jQuery.browser.version == '9.0')
		{
			var $item = $('#object-'+$(this).attr('id').substr(5));
			var $iframe = $('iframe', $item);
			if($iframe.attr('tmp') != '') {
				window.open($iframe.attr('tmp'),"streetview","width=960,height=680,resizable=1");
			}
			return false;
		}
		
		$('.item', '#object-top-container').hide().removeClass('active');
		var $item = $('#object-'+$(this).attr('id').substr(5)).addClass('active');
		
		var $video = $('video', '#object-video');
		if($video.size()) {
			$video.get(0).pause();	
		}
		
		$('#object-controls a').removeClass('active');
		
		switch($(this).attr('class')) {
			case 'map':
			case 'streetview':
				var $iframe = $('iframe', $item);
				if($iframe.attr('tmp') != '') {
					$iframe.css('height', $('#object-top-container').height()).attr('src', $iframe.attr('tmp')).attr('tmp', '');
				}
				$item.show();
				break;
			default:
				$item.show();
				break;
		}

		$(this).addClass('active');
		
		return false;
	});
	
	/**
	 * Search
	 */
	$('#quicksearch a').click(function() {
		var $link = $(this);
		$.cookie('search', 'types[]='+$link.attr('rel'), cookie);
		$.cookie('search_url', 'sok/types:'+$link.attr('rel')+'/areas:/rooms:/size:/price:', cookie);
		$.cookie('filter_string', $link.find('span').html(), cookie);
		$.cookie('search_count', null, cookie);
	});
	
	$('#search').each(function() {
		
		var $search = $(this);
		var $box = $('#search-box')
		var $bar = $('#search-bar');
		var $types = $('#search-types');
		var $areas = $('#search-areas');
		var $rooms = $('#slider-rooms');
		var $size = $('#slider-size');
		var $price = $('#slider-price');
		var $counter = $('#search-counter');
		var $filter_string = $('#filter-string');
		var $areas_string = $('#areas-string');
		var $search_button = $('#search-button');
		var $reset_button = $('#reset-button');
		
		var search_query = $.cookie('search') || null;
		var search_url = $.cookie('search_url') || null;
		var filter_string = $.cookie('filter_string') || '';
		var areas_string = $.cookie('areas_string') || '';
		var search_count = $.cookie('search_count') || 0;
		var search_default = { types: [], rooms: [1,8], size: [0,300], price: [0,8000000], areas: [] };
		var search = $.extend(true, {}, search_default);
		
		$search.show();
		
		if(search_query) {
			$.extend(search, $.unserialize(search_query), search);
			for(n in search.types) {
				$types.find('a[rel='+search.types[n]+']').addClass('active');
			}
			for(n in search.areas) {
				var $item = $areas.find('a[rel='+search.areas[n]+']');
				var $parent = $item.parents('.area-group');
				if($parent.size()) {
					$parent.attr('selected', search.areas[n]+','+($parent.attr('selected') || ""))
				} else {
					$item.addClass('active');
				}
			};
			
			$areas.find('.area-group').each(function(n, item) {
				var $item = $(item);
				var selected = $item.attr('selected') ? $item.attr('selected').split(',') : [];
				selected.pop();
				if(selected.length == $item.find('ul li a').size()) {
					$item.find('a').eq(0).addClass('active');
				} else {
					for(n in selected) {
						$item.find('a[rel='+selected[n]+']').addClass('active');
					}
				}
				
			});
			
			update_slider_texts();
			if(filter_string.length) {
				$filter_string.html(filter_string);
			}
			if(areas_string.length) {
				$areas_string.html(areas_string);
			}
			$search_button.attr('href', m2.baseUrl + search_url);
		}
		
		function update_slider_texts() {
			$rooms
				.siblings('.slider-min').html(search.rooms[0])
				.siblings('.slider-max').html(search.rooms[1] == 8 ? '8+' : search.rooms[1]);
			$size
				.siblings('.slider-min').html(search.size[0])
				.siblings('.slider-max').html(search.size[1] == 300 ? '300+' : search.size[1]);
			$price
				.siblings('.slider-min').html(fix_number(search.price[0]))
				.siblings('.slider-max').html(search.price[1] == 8000000 ? '8 000 000+' : fix_number(search.price[1]));
		}
		
		var height = $box.show().height()+10;
		if($.browser.msie) height += 85;
		$box.hide();
		
		if($box.hasClass('open')) {
			$box.removeClass('open').removeClass('closed').show().css('height', height);
		}
		
		$reset_button.click(function() {
			$.cookie('search', false, cookie);
			$.cookie('search_url', false, cookie);
			$.cookie('filter_string', false, cookie);
			$.cookie('search_count', false, cookie);
			$.cookie('areas_string', false, cookie);
			
			search = $.extend(true, {}, search_default);
			
			$types.find('a').removeClass('active');
			$areas.find('a').removeClass('active');
			
			$rooms.slider('values', 0, search.rooms[0]);
			$rooms.slider('values', 1, search.rooms[1]);
			$size.slider('values', 0, search.size[0]);
			$size.slider('values', 1, search.size[1]);
			$price.slider('values', 0, search.price[0]);
			$price.slider('values', 1, search.price[1]);
			
			update_slider_texts();
			
			count_results();
			
			_gaq.push(['_trackEvent', 'Search', 'Reset']);
			return false;
		});
		
		$bar.disableSelection().click(function() {
			if($box.hasClass('closed')) {
				$box.show().removeClass('closed').css({ height: 0 }).animate({ height: height }, 200);
				$areas.masonry({ itemSelector: '.search-area'});
				_gaq.push(['_trackEvent', 'Search', 'Open']);
			} else { 
				$box.animate({ height: 0 }, 200, function() {
					$box.hide().addClass('closed');
					_gaq.push(['_trackEvent', 'Search', 'Close']);
				});
			}
		});
		
		// Types
		$types.find('a').click(function() {
			var $link = $(this);
			$link.toggleClass('active');
			search.types.length = 0;
			$types.find('a.active').each(function(n, item) {
				search.types.push(item.rel);
			});
			count_results();
			if($link.hasClass('active')) {
				_gaq.push(['_trackEvent', 'Search', 'Type', $link.attr('rel')]);
			}
			return false;
		});
		
		// Sliders
		$rooms.slider({
			min: 1,
			max: 8,
			step: 1,
			range: true,
			values: search.rooms,
			slide: function(event, ui) {
				$(this).siblings('.slider-min').html(ui.values[0]);
				$(this).siblings('.slider-max').html(ui.values[1] == 8 ? '8+' : ui.values[1]);
			},
			stop: function(event, ui) {
				search.rooms = ui.values;
				count_results();
				_gaq.push(['_trackEvent', 'Search', 'Rooms', search.rooms]);
			}
		});
		
		$size.slider({
			min: 0,
			max: 300,
			step: 20,
			range: true,
			values: search.size,
			slide: function(event, ui) {
				$(this).siblings('.slider-min').html(ui.values[0]);
				$(this).siblings('.slider-max').html(ui.values[1] == 300 ? '300+' : ui.values[1]);
			},
			stop: function(event, ui) {
				search.size = ui.values;
				count_results();
				_gaq.push(['_trackEvent', 'Search', 'Size', search.size]);
			}
		});
		
		$price.slider({
			min: 0,
			max: 8000000,
			step: 100000,
			range: true,
			values: search.price,
			slide: function(event, ui) {
				$(this).siblings('.slider-min').html(fix_number(ui.values[0]));
				$(this).siblings('.slider-max').html(ui.values[1] == 8000000 ? '8 000 000+' : fix_number(ui.values[1]));
			},
			stop: function(event, ui) {
				search.price = ui.values;
				count_results();
				_gaq.push(['_trackEvent', 'Search', 'Price', search.price]);
			}
		});
		
		function fix_number(n) {
			if(!n) return 0;
			if(typeof n == 'number') n = n.toString();
			var a = [], r = '', i = n.length, l = 0;
			for(var x = 0;x < i;x++) a.push(n.charAt(x));
			a.reverse();
			while(i > 0) {
				l++;
				if(l%3==1) r = ' ' + r;
				r = a.shift() + r;
				i--;
			}
			return r.toString();
		}
		
		// Areas
		$areas.find('a').click(function() {
			search.areas.length = 0;
			var $item = $(this);
			var $group = $item.parents('.search-area');
			if($group.hasClass('area-group')) {
				$item.toggleClass('active');
				if($item.attr('rel') == "0") {
					$group.find('li a').removeClass('active');
				} else {
					$group.find('a[rel=0]').removeClass('active');
				}
			} else {
				$item.toggleClass('active');
			}
			
			$areas.find('a.active').each(function(n, item) {
				if(item.rel == "0") {
					$(item).siblings('ul').find('li a').each(function(n, item) {
						search.areas.push(item.rel);
					});
				} else {
					search.areas.push(item.rel);
				}
			});
			_gaq.push(['_trackEvent', 'Search', 'Area', $item.text()]);
			count_results();
			return false;
		});
		
		// Counter
		function count_results() {
			var url = 'types='+search.types+'&areas='+search.areas+'&rooms='+search.rooms+'&size='+search.size+'&price='+search.price;
			var search_url = 'sok/types:'+search.types+'/areas:'+search.areas+'/rooms:'+search.rooms+'/size:'+search.size+'/price:'+search.price;//+'#resultat';
			$.cookie('search_url', search_url, cookie);
			$search_button.attr('href', m2.baseUrl + search_url);
			$.cookie('search', decodeURIComponent($.param(search)), cookie);
			$.ajax({
				url: m2.baseUrl+'object_items/search',
				data: url + '&count=true',
				dataType: 'json',
				type: 'post',
				success: function(response) { display_results(response); }
			});
			_gaq.push(['_trackEvent', 'Search', 'Update Results', url]);
		}
		
		function display_results(response) {
			$counter.trigger('hw2count', parseInt(response.count));
			$filter_string.html((response.filter_text.length ? response.filter_text : $filter_string.attr('title')));
			$areas_string.html(response.areas_text);
			
			$.cookie('search_count', response.count, cookie);
			$.cookie('filter_string', response.filter_text, cookie);
			$.cookie('areas_string', response.areas_text, cookie);
		}
		
		$counter.hw2counter({ numbers: 4, reset: true, height: 40, initial: search_count });
		
	});
	
});

$.extend({
	unserialize: function() {
		var str = arguments[0];
		var obj = arguments[1] || {};
		var pairs = str.split('&');
		for(n in pairs) {
			var item = pairs[n].split('=');
			var key = item[0].replace('[]','');
			var value = item[1];
			if(obj[key] === undefined) {
				obj[key] = [];
			}
			
			if(typeof obj[key] !== 'object') {
				var tmp = obj[key];
				obj[key] = [];
				obj[key].push(tmp);
			}
			obj[key].push(value);
		}
		return obj;
	}
});

(function($) {
	var all_images_window;
	$.fn.m2gallery = function() {
		return this.each(function() {
			
			var $gallery = $(this);
			var $images = $('.gallery-image-list a', $gallery);
			var $prev = $('.gallery-prev', $gallery);
			var $next = $('.gallery-next', $gallery);
			var $comment = $('.gallery-comment', $gallery);
			var $image = $('.gallery-image', $gallery);
			var $prev_image = $('.gallery-prev-image', $gallery);
			var $next_image = $('.gallery-next-image', $gallery);
			var $all_images = $('.all-images', $gallery);
			
			var image = 0;
			var images = $images.size();
			var speed = 120;
			
			if(images > 1) {
				$gallery.hover(function() {
					show_controls();
					preload_images();
				}, function() {
					hide_controls();
				}).disableSelection();
			}
			
			$prev.click(function() {
				image = prev_image();
				show_image(image);
				_gaq.push(['_trackEvent', 'Gallery', 'Previous', '/objekt/'+$gallery.attr('id').replace('object-', '')]);
			});
			
			$next.click(function() {
				image = next_image();
				show_image(image);
				_gaq.push(['_trackEvent', 'Gallery', 'Next', '/objekt/'+$gallery.attr('id').replace('object-', '')]);
			});
			
			$all_images.click(function() {
				//all_images_window = window.open(this.href, 'images', "width=1040,height=950,toolbars=0,scrollbars=1");
				//all_images_window.focus();
				all_images_window = window.open(this.href, '_blank');
				return false;
			});
			
			function preload_images() {
				(new Image()).src = $images.eq(prev_image()).attr('href');
				(new Image()).src = $images.eq(next_image()).attr('href');
			};
			
			function prev_image() {
				var prev_image = image;
				--prev_image;
				if(prev_image < 0) prev_image = images - 1;
				return prev_image;
			}
			
			function next_image() {
				var next_image = image;
				++next_image;
				if(next_image >= images) next_image = 0;
				return next_image;
			}
			
			function show_image(index) {
				var $new_image = $images.eq(index)
				preload_images();
				$image.stop(true, true).css({ 'background-image': 'none' }).fadeOut(50, function() {
					$image.css({'background-image': 'url('+$new_image.attr('href')+')'}).fadeIn(300);
					if($new_image.attr('title').length) {
						$comment.html('').html('<span>'+(image+1) + '/' + images + ': ' + $new_image.attr('title')+'</span>');
					} else { 
						$comment.html('').html('<span>'+(image+1) + '/' + images +'</span>');
					}
				});
			};
			
			function show_controls() {
				if($.browser.msie) {
					$prev.show();
					$next.show();
				} else {
					$prev.stop(true, true).fadeIn(speed);
					$next.stop(true, true).fadeIn(speed);
				}
				$comment.stop(true, true).slideDown(speed);
			};
			
			function hide_controls() {
				if($.browser.msie) {
					$prev.hide();
					$next.hide();
				} else {
					$prev.stop(true, true).fadeOut(speed);
					$next.stop(true, true).fadeOut(speed);
				}
				$comment.stop(true, true).slideUp(speed);				
			};
			
		});
	}
})(jQuery);












