function transformLink(url) {
	return url.replace(/\.html/, '/ajax');
}

Array.prototype.contains = function (element) {
	for (var i = 0; i < this.length; ++i) {
		if (this[i] == element) {
			return true;
		}
	}
	return false;
}

Array.prototype.unique = function () {
	var r = new Array();
	o:for(var i = 0, n = this.length; i < n; i++)
	{
		for(var x = 0, y = r.length; x < y; x++)
		{
			if(r[x]==this[i])
			{
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	return r;
}

String.prototype.pad = function(l, s, t){
	return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length) + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2)) + this + s.substr(0, l - t) : this;
}

String.prototype.crop = function(m, c, s){
	if(this.length > m) {
		out = this.substr(0, m);
		out = c ? out.replace(/ +[^ ]*$/, '') : out.replace(/ +$/, '');
		return out + s;
	}
	return this;
}

$.fn.extend({
	equalHeight: function() {
		var maxHeight = 0;
		this.each(function() { maxHeight = Math.max(maxHeight, $(this).height()); });
		return this.each(function() { $(this).css({minHeight: maxHeight}); });
	}
});

var lang, langID, langList, imgCount, carouselPos, carouselRunning;

var carouselWidth = 400;
var carouselHeight = 50;
var zoomEffect = 0.4;

var fadeSpeed = $.browser.msie?0:200;

// carousel functions
function initCarousel() {
	imgCount = $('#carousel_content').children().length;
	carouselPos = 0;
	$('#carousel').append('<div id="description" />');
	$('#carousel_content img').each(function(i) {
		$(this).data('alt', $(this).attr('alt'));
		$(this).attr('alt', '');
		$(this).css({position: 'absolute'});
		var origWidth = 80;
		var origHeight = 60;
		$(this).data('origWidth', origWidth);
		$(this).data('origHeight', origHeight);
		if(!$.browser.msie || $.browser.version.match(/^8|9/)) {
			var highlight = $(this).after('<div />').next().css({
				display: 'block',
				width: origWidth,
				height: origHeight,
				position: 'absolute',
				background: '#fff'
			});
			$(this).data('highlight', highlight);
		}
	});
	$('#carousel_content a').hover(function() {
		$('#description').html($(this).children('img').data('alt'));
		stopCarousel();
	},
	function() {
		if(!$.browser.msie || !$.browser.version.match(/6/)) startCarousel();
		$('#description').empty();
	});
}

function startCarousel() {
	if(!carouselRunning) {
		carouselRunning = true;
		$('#carousel_content').everyTime(100, 'carousel', function() {
			carouselPos = (carouselPos + 1) % 360;
			if(carouselPos >= 360) carouselPos = 0;
			$('#carousel_content img').each(function(i) {
				var imagePos = (carouselPos + (i / imgCount) * 360) % 360;
				var x = (1 - Math.sin(imagePos / 360 * 2 * Math.PI)) * (carouselWidth / 2);
				var y = (1 - Math.cos(imagePos / 360 * 2 * Math.PI)) * (carouselHeight / 2);
				var z = (y/carouselHeight) * 100;
				var zoom = Math.pow((1 - zoomEffect) + y / (carouselHeight / 2) / 2 * zoomEffect, 2);
				//var zoom = 1;
				x = Math.round(x);
				y = Math.round(y);
				z = Math.round(z);
				var origWidth = $(this).data('origWidth');
				var origHeight = $(this).data('origHeight');
				var zoomWidth = Math.abs(zoom * origWidth);
				var zoomHeight = Math.abs(zoom * origHeight);
				x = (carouselWidth / 2) + (x - carouselWidth / 2) * zoom;
				x -= zoomWidth / 2;
				y = y * zoom;
				//y += (origHeight - zoomHeight) / 2;
				$(this).css({
					left: x + 'px',
					top: y + 'px',
					zIndex: z,
					width: zoomWidth + 'px',
					height: zoomHeight + 'px'
				});
				if(!$.browser.msie || $.browser.version.match(/^(8|9)/)) {
					$(this).data('highlight').css({
						left: x + 'px',
						top: y + 'px',
						zIndex: z + 1,
						width: zoomWidth + 'px',
						height: zoomHeight + 'px',
						opacity: (1 - zoom) / 2
					});
				}
			});
		});
	}
}

function stopCarousel() {
	if(carouselRunning) {
		carouselRunning = false;
		$('#carousel_content').stopTime('carousel');
	}
}

$(document).ready(function() {
	lang = $('html').attr('lang');
	langID = {'de': 0, 'en': 1, 'fr': 2, 'es': 3, 'ro': 4, 'ru': 5, 'cn': 6, 'vn': 7}[lang];

	var textSearch = $('#search').attr('value');

	//submenu hover foldout
	$('#menu>ul>li').hover(function() {
		$(this).stopTime('hideSubmenu');
		$(this).siblings().removeClass('hover').children('ul').stop().hide();
		if(!$(this).hasClass('hover')) {
			$(this).addClass('hover');
			$(this).children('ul').hide().fadeIn(fadeSpeed);
		}
	},
	function() {
		$(this).oneTime(800, 'hideSubmenu', function() {
			$(this).removeClass('hover');
			$(this).children('ul').fadeOut(fadeSpeed);
		});
	});

	// show search field default keyword
	$('#search')
		.css({color: '#666'})
		.focus(function() {
			$(this).css({color: '#000'});
			if($(this).val() == textSearch) $(this).val('');
		})
		.blur(function() {
			$(this).css({color: '#666'});
			if($(this).val() == '') $(this).val(textSearch);
		});

	// turn language list into selector box
	langList = $('#lang_menu ul');
	$('#lang_selector')
		.click(function() {
			if(langList.is(':visible')) langList.hide();
			else langList.show();
			return false;
		})
		.children().addClass(lang).html($('#lang_menu a.' + lang).html());
	langList.find('a').click(function() {
		$('#lang_selector').children().removeClass().addClass($(this).attr('class')).html($(this).html());
		return true;
	});
	$('body').click(function() {
		if(langList.is(':visible')) langList.hide();
		if($('#favorites ul').is(':visible')) $('#favorites ul').hide();
	});

	// init currency mode link
	$('#currency_mode a[href=#]').click(function() {
		$.cookie('currency', $(this).attr('id'), {path: '/', expires: 365});
		location.reload();
		return false;
	});

	// equal height for tree and content
	$('#tree,#content_wrapper').equalHeight();

	$('#tree>ul>li a').each(function() {
		var html = $(this).html();
		var maxLen = (lang == 'ru') ? 21 : 23;
		if(html.length > maxLen) {
			html = html.crop(maxLen, 0, '.');
			$(this).html(html);
		}
	});

	// show submenu of active branch
	$('#tree>ul>li.active>ul').show();

	// init machine tree menu
	if($('#tree>ul>li>ul').length) $('#tree>ul>li>a').live('mouseenter', function() {
		$(this).oneTime(200, 'openMenu', function() {
			var $li = $(this).parent();
			$('#tree li.active').removeClass('active');
			$li.addClass('active');
			if($li.children('ul').is(':visible')) {
				$li.children('ul').slideUp(200);
			}
			else {
				$li.children('ul').slideDown(200);
				$li.siblings().children('ul:visible').slideUp(200);
			}
			$(this).blur();
			return false;
		});
	});
	$('#tree>ul>li>a').live('mouseleave', function() {
		$(this).stopTime('openMenu');
	});

	// init back buttons
	$('.back').live('click', function() {
		history.back();
	});


	// init preview on machine tree hover
	$('#tree>ul>li').each(function() {
		var number = $(this).attr('id').replace('m', '');
		var src = $('#preview img:eq(0)').attr('src');
		if(src.replace(/^.*([0-9]+).*$/, '$1') != number) {
			$('#preview').append('<img src="' + src.replace(/[0-9]+/, number) + '" id="p' + number + '" />');
		}
	});
	$('#tree ul li a').live('mouseenter', function() {
		$(this).oneTime(100, 'showImage', function() {
		var cat_id = $(this).parents('#tree>ul>li').attr('id');
		if(cat_id) {
			var preview_id = cat_id.replace('m', 'p');
			var image = $('#' + preview_id);
			if((image.length > 0) && !image.hasClass('active')) {
				//$('#preview img.prev').removeClass('prev');
				$('#preview img.active').removeClass('active').addClass('prev');
				image.hide().addClass('active').fadeIn(fadeSpeed, function() {
					$('#preview img.prev').removeClass('prev');
				});
			}
		}
		});
	});
	$('#tree ul li a').live('mouseleave', function() {
		$(this).stopTime('showImage');
	});

	// init preview image on thumbnail hover in machine detail view
	$('.thumbs a:not(.video)').live('mouseenter', function() {
		$(this).oneTime(100, 'showImage', function() {
		var letters = ' abcdefghijklmnopqrstuvwxyz';
		var index = $(this).index('.thumbs a');
		var letter = index ? letters.substr(index, 1) : '';
		var id = $(this).parents('.thumbs').attr('id');
		var sel;
		if(id) sel = id.replace('thumbs_', '');
		if(sel) {
			var filename = '/fotos/'+sel+letter+'.jpg';
			var image = $('#image_main img[src$="'+filename+'"]');
			if(image.length > 0) {
				/*$('#image_main img.active').removeClass('active').addClass('prev');
				$(image).hide().addClass('active').fadeIn(0, function() {
					$('#image_main img.prev').removeClass('prev');
				});*/
				image.show().siblings().hide();
			}
			else {
				$('#image_main').append('<img src="'+filename+'" alt="Bild '+(index+1)+'" id="image'+(index)+'" class="loading" />');
				$('#image_main .loading').load(function() {
					$(this).show().siblings().hide();
					/*$('#image_main img.active').removeClass('active').addClass('prev');
					$(this).hide().removeClass('loading').addClass('active').fadeIn(0, function() {
						$('#image_main img.prev').removeClass('prev');
					});*/
				});
			}
		}
		});
	});
	$('.thumbs a').live('mouseleave', function() {
		$(this).stopTime('showImage');
	});

	// init fancybox on thumbnail click in machine detail view
	$('.thumbs a:not(.video) img').each(function() { $(this).attr('alt', $('h1').html() + ' (' + $(this).attr('alt') + '/' + $('.thumbs a:not(.video) img').length + ')'); });
	$('.thumbs a:not(.video)').fancybox({titlePosition: 'over'});

	// init fancybox on main image click
	if(!$('#image_main img.active').length) $('#image_main img:eq(0)').addClass('active');
	$('#image_main').click(function() {
		$('.thumbs a').eq($(this).children('img.active').attr('id').replace(/image/, '')).trigger('click');
	});

	// init fancybox on YouTube video links
	$('a.video').fancybox({width: 480, height: 385, type: 'swf', swf: {allowfullscreen: 'true'}});

	// init fancybox on other images
	$('a.fancybox_link').fancybox({titleShow: false});

	// init table row select on result page
	$('.machines tr:has(td)').live('mouseenter', function() {
		$(this).addClass('hover');
	});
	$('.machines tr:has(td)').live('mouseleave', function() {
		$(this).removeClass('hover');
	});
	$('.machines tr:has(td)').live('click', function(event) {
		if($(this).parents('form').length) {
			var checkbox = $(this).find('input[type=checkbox]');
			if(!event.target.nodeName.match(/input/i)) checkbox.attr('checked', !checkbox.is(':checked'));
		}
		else {
			document.location.href = $(this).children('td').children('a:eq(0)').attr('href');
		}
	});

	$('#technical_condition').hover(function() {
		$('#legend_technical').css({top: $(this).position().top + 'px'}).show();
	},
	function() {
		$('#legend_technical').hide();
	});
	$('#optical_condition').hover(function() {
		$('#legend_optical').css({top: $(this).position().top + 'px'}).show();
	},
	function() {
		$('#legend_optical').hide();
	});

	// change form field colors on focus and blur
	$('input.text,textarea,select')
		.focus(function() {
			$(this).data('background_orig', $(this).css('background'));
			$(this).css('background', '#fff');
			$(this).data('color_orig', $(this).css('color'));
			$(this).css('color', '#032b60');
		})
		.blur(function() {
			$(this).css('background', $(this).data('background_orig'));
			$(this).css('color', $(this).data('color_orig'));
		});

	// carousel
	initCarousel();
	startCarousel();
	if($.browser.msie && $.browser.version.match(/6/)) $('body').oneTime(100, 'stopCarousel', function() {stopCarousel()});

	/*$('#fav_selector').click(function() {
		if($('#favorites ul').is(':visible')) $('#favorites ul').hide();
		else  $('#favorites ul').show();
		return false;
	});*/

	$('#fav_selector').hover(function() {
		$('#favorites ul').show();
	},
	function() {
		$('#favorites ul').oneTime(800, 'hideFavorites', function() {
			$(this).hide();
		});
	});

	$('#favorites ul').hover(function() {
		$('#favorites ul').stopTime('hideFavorites');
	},
	function() {
		$('#favorites ul').hide();
	});

	// option bar functions
	$('#fav').click(function() {
		var sel = $('input[name=sel]').attr('value');
		var action = $('input[name=action]').attr('value');
		var title = $('h1').html();
		var favArr = new Array();
		var cookieName = (action == 'V') ? 'fav_sale' : 'fav_rental';
		var fav = $.cookie(cookieName);
		if(fav) {
			favArr = fav.split(',');
			if((favArr.length == 1) && (favArr[0] == ''))favArr = new Array();
		}
		favArr.push(sel);
		var newFav = favArr.unique().join(',');
		$.cookie(cookieName, newFav, {path: '/', expires: 365});
		if(!$('#favorites').is(':visible')) {
			$('#favorites').show();
			$(this).append('<div class="info_box">Maschine zu Favoriten hinzugefügt.</div>').children().last().css({position: 'absolute', top: '-12px', left: '0', width: '200px'}).animate({top: '-50px'}).oneTime(500, 'hideInfo', function() {
				$(this).hide();
			});
		}
		if(!$('#f' + sel).length) $('#favorites ul').append('<li><a href="#" id="f' + sel + '">' + title + '</a></li>');
		return false;
	});

	$('#print').live('click', function() {
		window.open($(this).attr('href'),'print','width=580,height=' + (screen.height >= 700 ? '700' : '560') + ',scrollbars=yes,location=no,status=no');
		return false;
	});

	// table sorter
	var getSortValue = function(node)
	{
		var col = $(node).attr('class');
		var text = $(node).html();
		text = text.replace(/<.*?>/g, '');
		if(col == 'weight') {
			var text1 = text.replace(/(,.*)/, '');
			var text2 = text.replace(/(.*,)/, '');
			text1 = text1.pad(5);
			text = text1 + '.' + text2;
		}
		if(col == 'price') {
			text = text.replace(/[^0-9]*/g, '');
			text = text.pad(7);
		}
		return text; 
	}
	if(!$('#contact_form').length) {
		$('.machines').tablesorter({textExtraction: getSortValue, widgets: ['zebra'], headers: {0: {sorter: false}}});
	}

	// news tab
	$('#right_column h2:eq(1)').detach().insertAfter('#right_column h2:eq(0)');
	$('#right_column .news_list_view').hide();
	$('#right_column h2:last').after('<div id="h2_wrapper" style="height:26px;" />');
	$('#right_column h2').detach().appendTo('#h2_wrapper').css({cssFloat: 'left', display: 'block', width: '102px', cursor: 'pointer'}).hover(function() {$(this).css({textDecoration: 'underline'});}, function() {$(this).css({textDecoration: 'none'});}).click(function() {
		var index = $(this).index('#right_column h2');
		if(index == 0) {
			$('.news_list_view').hide();
			$('#offers').show();
			$('#right_column').removeClass('news_tab_active');
		}
		else {
			$('#offers').hide();
			$('.news_list_view').show();
			$('#right_column').addClass('news_tab_active');
		}
	});

	// init fancybox for news
	$('.news_list_view a').fancybox({'transformLink': transformLink, titleShow: false});

	// init hover flashes on home buttons
	if(!document.location.href.match(/trans=1/i)) {
	$('.home_image_button,.home_button').each(function() {
		var href = $(this).find('a:eq(0)').attr('href');
		var layer = $(this).append('<a href=' + href + ' style="display:block;position:absolute;top:0;left:0;width:' + $(this).outerWidth() + 'px;height:' + $(this).outerHeight() + 'px"></a>').children().last();
		if(!$.browser.msie || $.browser.version.match(/^(8|9)/)) {
			layer.css({background: '#f6f6f6', opacity: 0.01}).hover(function() {
				$(this).animate({opacity: 0.2}, 200, function() {$(this).animate({opacity: 0.01})});
			},
			function() {
				//$(this).animate({opacity: 0.01});
			});
		}
	});
	}

	//if($.browser.msie && $.browser.version.match(/^(5|6)/)) $('#header_image>div.hidden').remove();
	if($('#header_image>div').length > 1) $('#header_image').everyTime(8000, 'header_cycle', function() {
		var activeHeader = $('#header_image>div.active');
		if(!activeHeader.length) activeHeader = $('#header_image>div:first-child');
		var nextHeader = activeHeader.next();
		if(!nextHeader.length) nextHeader = $('#header_image>div:first-child');
		activeHeader.addClass('active_prev');
		nextHeader.css({opacity: 0.0})
			.addClass('active')
			.animate({opacity: 1.0}, 400, function() {
				activeHeader.removeClass('active active_prev');
			});
	});

	// init translation buttons
	$('a.trans').fancybox({onComplete: function() {
		$('#translation_form').submit(function() {
			var trans = $('#translation_text').val();
			var sid = $('#sid').val();
			var id = $('#id').val();
			$('a.trans[href*="id=' + id + '&"]').addClass('trans_selected');
			var transText = $('.trans_selected').prev('span.trans_text');
			if(!transText.length) transText = $('.trans_selected').prev().find('span.trans_text');
			transText.html(trans);
			$.ajax({
				url: $(this).attr('action'),
				type: 'post',
				cache: false,
				data: {
					'id': id,
					'sid': sid,
					'trans': trans
				}
			});
			$.fancybox.close();
			return false;
		});
		$('#cancel_translation').click(function() {
			$.fancybox.close();
		});
	},
	onCleanup: function() {
		$('.trans_selected').removeClass('trans_selected');
	},
	ajax: {
		cache: false
	}});
});
