Cufon.replace('.box h2, .box p, h1, #nav a, #footernav a, .button, button, .secbutton, .thumbs h2, a.catalogue, a.pricelist, #submenu a, h4.fn', { hover: true });

var Baseco = window.Baseco || {};

Baseco.Order = {
	
	validateStep1: function(obj) {
		Hello.XhrHandler.executeRequest(ROX_MOUNTPOINT + 'check-form', $(obj).serialize());
	}
	
};

Baseco.Gallery = (function() {
	
	var NUMBER_OF_THUMBS     = 6;
	var HIDE_THUMBNAV        = true;
	var THUMBNAIL_ITEM_WIDTH = 120;
	var IMAGE_WIDTH          = 745;
	
	var init = function() {
	
		// only one image? No need for the gallery
		if (numberOf() <= 1) {
			return;
		} else {
			$('#gallery').addClass('active');
		}
	
		// showControls
		$('#thumbnav').css('display', 'block');
		
		// set thumbnav width
		$('#thumbnav ul').width(numberOf() * THUMBNAIL_ITEM_WIDTH);
	
		// show/highlight only 1st image
		$('#gallerycontent>ul>li').hide();
		show(0);
	
		// hide/show thumbnav
		if (HIDE_THUMBNAV) {
			window.setTimeout(function() {
				$('#thumbnav>div').animate({height: '7px' });
			}, 600);
			$('#thumbnav')
				.hover(function() {
					$('#thumbnav>div').stop().animate({ height: '80px'});
				}, function() {
					$('#thumbnav>div').stop().animate({ height: '7px'});
				})
			;
		}
	
		// navigation handler
		$('#gallery .next').click(function(e) {
			e.preventDefault();
			if (!isAnimated()) {
				Baseco.Gallery.next();
			}
		});
		$('#gallery .prev').click(function(e) {
			e.preventDefault();
			if (!isAnimated()) {
				Baseco.Gallery.previous();
			}
		});
		
		// navigation handler thumbnav
		$('#thumbnav li').click(function(e) {
			e.preventDefault();
			if (!isAnimated()) {
				show($(this).index(), true);
			}
		});
	
		if (!Baseco.isTouchEnabled()) {
			// mouseover effect in gallery
			$('#gallery .ctrl')
				.hover(function() {
					$(this).find('span').fadeIn();
				}, function() {
					$(this).find('span').fadeOut();
				})
				.find('span')
				.hide()
			;
		}
	};
	
	var numberOf = function() {
		return $('#gallerycontent>ul>li').length;
	};

	var current = function() {
		return $('#gallerycontent>ul>li:visible').index();
	};
	
	var isAnimated = function() {
		return $('#gallery.animated').length > 0;
	};
	
	var show = function(index, animation) {
		// the new is the current -> do nothing
		if (index === current()) {
			return;
		}
		
		if (animation) {
			var direction = index > current() ? 1 : -1;
			var visible = $('#gallerycontent>ul>li:visible');
			
			$('#gallery').addClass('animated');
			
			$('#gallerycontent>ul>li')
				.eq(index)
				.css('left', IMAGE_WIDTH * direction)
				.show()
				.stop()
				.animate(
					{
						left: 0
					},
					{
						step: function(now, fx) {
							visible.css('left', (fx.cur() - direction * IMAGE_WIDTH));
						},
						complete: function() {
							visible.css('left', 0).hide();
							$('#gallery').removeClass('animated');
						},
						duration: 700
					}
				)
			;

		} else {
			$('#gallerycontent>ul>li:visible').hide();
			$('#gallerycontent>ul>li').eq(index).show();
		}

		$('#thumbnav li.here').removeClass('here');
		$('#thumbnav li').eq(index).addClass('here');
		
		// move thumb so that it is visible
		var rangeLeft  = - Math.round(parseInt($('#thumbnav ul').css('left'), 10) / 120);
		var rangeRight = rangeLeft + NUMBER_OF_THUMBS - 1;
		var newRangeLeft;
		
		if (index < rangeLeft || index > rangeRight) {
			if (Math.abs(rangeLeft - index) > Math.abs(index - rangeRight)) {
				// item glues to the right side
				newRangeLeft = index - NUMBER_OF_THUMBS + 1;
			} else {
				// item glues to the left side
				newRangeLeft = index;
			}
			$('#thumbnav ul').animate({left: -120 * newRangeLeft});
		}
		
		// show or hide controls
		
		if (index > 0) {
			$('#gallery .prev').fadeIn();
		} else {
			$('#gallery .prev').fadeOut();
		}
		if (index < numberOf() - 1) {
			$('#gallery .next').fadeIn();
		} else {
			$('#gallery .next').fadeOut();
		}

	};
	
	return {
	
		init: init,
	
		next: function() {
			var next = current() + 1;
			if (next >= numberOf()) {
				next = 0;
			}
			show(next, true);
		},
	
		previous: function() {
			var previous = current() - 1;
			if (previous < 0) {
				previous = numberOf() - 1;
			}
			show(previous, true);
		}
		
	};
	
}());

Baseco.isTouchEnabled = function () {
	try {
		document.createEvent("TouchEvent");
		Baseco.isTouchEnabled = function() { return true; };
	} catch (e) {
		Baseco.isTouchEnabled = function() { return false; };
	}
	return Baseco.isTouchEnabled();
}

$(document).ready(function() {
	
	// init xhr system
	
	Hello.XhrHandler.init();
	Hello.XhrHandler.register('redirectTo', function(url) {
		location.href = url;
	});
	
	// open external links in a new window. These links must be marked with the rel attribute.

	$("a[rel=external]").click(function() {
		window.open(this.href);
		return false;
	});
	
	// Menu scrolling
	
    $(window).bind("scroll", function() {
        var scrollTop = $(document).scrollTop();
        $("#header").toggleClass('fixed', scrollTop > 45);
    });

	// Order
	
	var orderStep1Form = $('#order-step-1');
	
	if (orderStep1Form.length) {
		orderStep1Form.find('select').change(function() {
			Baseco.Order.validateStep1(orderStep1Form);
		});
		orderStep1Form.find('input[name=amount]').keyup(function() {
			Baseco.Order.validateStep1(orderStep1Form);
		});
		orderStep1Form.find('#screws input').keyup(function() {
			Baseco.Order.validateStep1(orderStep1Form);
		});
		orderStep1Form.find('#others input').keyup(function() {
			Baseco.Order.validateStep1(orderStep1Form);
		});
		orderStep1Form.find('#add-screws-toggle').change(function() {
			Baseco.Order.validateStep1(orderStep1Form);
		});
		orderStep1Form.find('#add-others-toggle').change(function() {
			Baseco.Order.validateStep1(orderStep1Form);
		});
		orderStep1Form.find('#flooring').change(function() {
			Baseco.Order.validateStep1(orderStep1Form);
		});

		// Order > synchronize fields with same product
		//         (a screw could be part of several lists)

		orderStep1Form.find('#screws input').keyup(function() {
			orderStep1Form.find('#screws input[name="' + this.name + '"]').val(this.value);
		});
		
		$('#add-screws-toggle').click(function () {
			$('#screws').toggleClass('active', this.checked);
		});
		
		$('#add-others-toggle').click(function () {
			$('#others').toggleClass('active', this.checked);
		});
		
		$('#flooring').change(function() {
			var id = $(this).val();
			if (id) {
				$('#screws div.screwoptions').removeClass('active');
				$('#screws-' + id).addClass('active');
			} else {
				$('#screws div.screwoptions').removeClass('active');
			}
		});
	
	}
	
	// Choose District
	
	$('select#district-selector').change(function() {
		$('div.district-list.active').removeClass('active');
		$('#district-' + this.value).addClass('active');
	});
	
	var districtList = $('div.district-list input[checked]').parents('div.district-list');
	if (districtList.length) {
		districtList.addClass('active');
		var districtId   = districtList.attr('id').replace('district-', '');
		$('select#district-selector').val(districtId);
	}
	
	// Set up gallery
	Baseco.Gallery.init();
	
	// Tooltips for product thumbs

	var showTooltip = function(obj) {
		obj = $(obj);
		var pos = obj.offset();
		var tooltip = $('<div class="tooltip" />');
		tooltip
			.text(obj.data('tooltip'))
			.appendTo('body')
			.css('top', pos.top - tooltip.height() - 13)
			.css('left', pos.left + (obj.width() - tooltip.width()) / 2 - 6 )
		;
	};
	
	var hideTooltip = function(obj) {
		$('div.tooltip').remove();
	};

	$('ul.thumbs img[title], ul.products img[title]').each(function() {
			$(this).data('tooltip', this.title);
			this.title = null;
		}).hover(
		function() {
			showTooltip(this);
		},
		function() {
			hideTooltip(this);
		}
	);
	
	// Tooltips > special case for 'order samples' which has a span with a
	//            higher z-index above the img
	
	$('ul.thumbs img+span').hover(
		function() {
			showTooltip($(this).prev('img'));
		},
		function() {
			hideTooltip($(this).prev('img'));
		}
	);
	
	// Tooltips for help icons
	
	var hideHelpTooltip = function() {
		$('div.help-tooltip').remove();
		$('a.help.active').removeClass('active');
	};
	
	$('a.help').click(function(e) {
		e.stopPropagation();
		var isActive = $(this).is('.active');
		hideHelpTooltip();
		if (!isActive) {
			$(this).addClass('active');
			var pos = $(this).offset();
			var tooltip = $('<div class="help-tooltip" />');
			tooltip
				.html($(this).find('span').html())
				.appendTo('body')
				.css('top', pos.top - tooltip.height() /2 + 4)
				.css('left', pos.left + $(this).width() + 1)
			;
		}
	});
	
	$(document)
		.click(hideHelpTooltip)
		.keyup(function(e) {
			if (e.keyCode == 27) {
				hideHelpTooltip();
			}
		})
	;
	
	// switch on product detail
	
	$('a.galleryswitch').click(function(e) {
		e.preventDefault();
		$('div.product_text, div.product_gallery').toggle();
	});
	
	// Samples
	
	if ($('.ordersamples').length) {
		$('.ordersamples input[type=checkbox]').each(function() {
			if (this.checked) {
				$(this).parents('label').addClass('checked');
			}
		}).click(function() {
			$(this).parents('label').toggleClass('checked', this.checked);
		});
		Hello.Form.Checkbox.numberofCheckedConstraint('variant[]', 3);
	}
	
	// Hover start page
	
	if (!Baseco.isTouchEnabled()) {
	
		var animateStartpageImages = function(panel, floor) {
			// panel and floor has to be % values!
			var duration = 400;
			var floorEasing, panelEasing;
			panel = panel || '40%';
			floor = floor || '60%';
		
			// transform from % to px: 1st to compare with other width, 2nd to fix a IE rendering bug
			var containerWidth = $('#intro').width();
			panel = containerWidth * parseInt(panel, 10) / 100;
			floor = containerWidth * parseInt(floor, 10) / 100;
		
			if ($('#floors_start').width() < floor) {
				floorEasing = 'easeInQuad';
				panelEasing = 'easeOutQuad';
			} else {
				floorEasing = 'easeOutQuad';
				panelEasing = 'easeInQuad';
			}
		
			$('#floors_start').stop().animate({width: floor}, duration, floorEasing);
			$('#panels_start').stop().animate({width: panel}, duration, panelEasing);
		};
	
		$('#panels_start').hover(function() {
			animateStartpageImages('44%', '56%');
		}, function() {
			animateStartpageImages();
		});
		$('#floors_start').hover(function() {
			animateStartpageImages('37%', '63%');
		}, function() {
			animateStartpageImages();
		});
		
	};
	
	// page tracking
	var gaTrack = function(category, action, label) {
		if ('_gaq' in window) {
			_gaq.push(['_trackEvent', category, action, label]);
		}
	};
	
	$('#fritid a').click(function() {
		gaTrack('External link', 'click', 'External link: Fritid');
	});
	$('#fbpage').click(function() {
		gaTrack('External link', 'click', 'External link: Facebook');
	});
	$('#gallery #thumbnav ul a').click(function() {
		gaTrack('Gallery', 'click', 'Gallery: Thumb');
	});
	$('#gallery #gallerycontent a.prev').click(function() {
		gaTrack('Gallery', 'click', 'Gallery: Previous');
	});
	$('#gallery #gallerycontent a.next').click(function() {
		gaTrack('Gallery', 'click', 'Gallery: Next');
	});
	$('select#district-selector').change(function() {
		gaTrack('Reseller', 'choose', $(this).find('option:selected').text());
	});
	$('body.home div#intro>a, body.home div.box>a').click(function() {
		var url = $(this).attr('href').replace(/^(https?:\/\/[^\/]+)?\//, '').replace(/\/$/, '');
		gaTrack('Homepage image', 'click', 'Homepage image: ' + url);
	});
	
});

// refresh Cufón on changed window size

(function() {
	
	var timeouthandler;
	var changed;
	
	$(window).resize(function() {
		changed = true;
		if (!timeouthandler) {
			timeouthandler = window.setTimeout(function() {
				Cufon.refresh();
				changed = false;
				timeouthandler = null;
			}, 150);
		}
	});
}());

