/****************************************************************
*								*
*	Alcina - functions.js					*
*	Author: michael.seidel@comspace.de			*
*	Create date: 17.08.2010					*
*								*
****************************************************************/

Cufon.set('hover')
Cufon.replace('h1')('h2')('h3')('h4');
Cufon.replace('#nav > li > a', {hover: true})('#nav li.hotline > p', {hover: true});

jQuery.fn.exists = function(){return jQuery(this).length>0;}

jQuery(function($) {

	// cufon Fix for the navigation
	$('#nav > li').mouseenter(function() {
		$(this).removeClass('noenter').addClass('enter');
		Cufon.refresh();
	}).mouseleave(function() {
		$(this).removeClass('enter').addClass('noenter');
		Cufon.refresh();
	});

	// img-hover-fix for all the stupid browsers out there (aka Firefox)
	$('img[alt]:not([title])').each(function() { this.title = this.alt; });
	
	// well... initializing the tabs
	$('.tab-container').tabs();

	// toggle for the "read more" blocks (content- and productpages)
	$('div.readMore > a:last').click(function() {
		$(this).parent().find('> div:first').slideToggle(600).end().end().find('> span').toggle();
		return false;
	});

	// initializing the carousel
	$('.products-slider:has(a.left,a.right) .products-caroussel-wrapper').each(function() {
		$(this).find('.products-caroussel').jCarouselLite({
			btnPrev: '.products-slider > a.left',
			btnNext: '.products-slider > a.right',
			visible: Math.floor($(this).width() / 180)
		});
	});

	// initializing the startpage carousel
	$('.start-slider:has(a.left,a.right) .start-caroussel-wrapper').each(function() {
		$(this).find('.start-caroussel').jCarouselLite({
			btnPrev: '.start-slider > a.left',
			btnNext: '.start-slider > a.right',
			visible: 4
		});
	});

	// autosuggest for the search
	$('#search-text').keyup(function() {
		if ($(this).val().length >= 1) {
			$.get($('#search').attr('action'), {query : $('#search-text').val(), json : 1}, function(json) {
				$('#search-results').remove();
				if (json.total > 0) {
					$('<ul id="search-results"></ul>').insertAfter('#search');
					for (var i=0; i<json.results.length; i++)
						$('#search-results').append('<li><a href="' + json.results[i].link + '">' + json.results[i].title + '</a></li>');
				}
			}, 'json');
		}
		else {
			$('#search-results').remove();
		}
	});

	// preparing the stage 
	$('div.backgrounds > img:not(:first)').hide();

	// initialize the fancyboxes
	$('a.fancybox').fancybox({
		overlayOpacity	: 0.5,
		padding		: 0,
		speedIn		: 600,
		speedOut	: 400,
		titleShow	: false
	});

	// initialize the cart overlay
	$('#shopping-cart')
		.live('mouseenter', function() { $('form', this).show(); $(this).addClass('hover'); })
		.live('mouseleave', function() { $('form', this).hide(); $(this).removeClass('hover'); });

	// put items into the cart (product-page)
	$('#addToCart').submit(function () {
		var lang	= $(this).attr('action').replace(/.+[\?&]lang=(\w+).*/, "$1");

		$.post($(this).attr('action') + '&json=1', $(this).serialize(), function(data) {
			$.get('/system/modules/de.alcina/templates/cart.jsp?lang=' + lang, function(data) {	
				$('div#header').replaceWith(data);
			}, 'html');
		}, 'html');

		var offsetCart	= $('#shopping-cart').offset();
		var offsetHeader= $('#header').offset();
		var offsetImage	= $('#productImage').offset();
	
		$('#header').prepend('<img src="' + $('#productImage').attr('src') + '" id="temp" style="position:absolute; top:' + (offsetImage.top - offsetHeader.top) + 'px; left:' + (offsetImage.left - offsetHeader.left + 14) + 'px; z-index:500" />');
	
		params = {
			top     : (offsetCart.top - offsetHeader.top) + 'px',
			left    : (offsetCart.left - offsetHeader.left) + 'px',
			opacity : 0.25,
			width   : $('#shopping-cart').width(),  
			heigth  : $('#shopping-cart').height()
		};		
	
		$('#temp').animate(params, 700, false, function () {
			$('#temp').remove();
		});		

		return false;
	});			

	var unfinishedRequest = false;

	// put items into the cart (shop-view)
	$('form[name="addToCart"]').submit(function () {
		var lang	= $(this).attr('action').replace(/.+[\?&]lang=(\w+).*/, "$1");
		var form	= this;	

		if (unfinishedRequest) {
			return false;
		}

		unfinishedRequest = true;

		//set minimum value for products
		if ($('input.autoSetMinValue', this)) {
			var qty = $('input[name^="qty["]', this);
			qty.val(qty.val() || 1);
		}

		$.post($(this).attr('action') + '&json=1', $(this).serialize(), function(data) {
			$.get('/system/modules/de.alcina/templates/cart.jsp?lang=' + lang, function(data) {
				$('div#header').replaceWith(data);
				$('input[name^="qty["]', form).val('');
				unfinishedRequest = false;
			}, 'html');
		}, 'html');

		var offsetCart	= $('#shopping-cart').offset();
		var offsetHeader= $('#header').offset();
		var productImage= $('a > img', form);

		if (!productImage.length)
			productImage = $(form).parents('li').find('a:first > img');

		var offsetImage	= productImage.offset();
	
		$('#header').prepend('<img src="' + productImage.attr('src') + '" id="temp" style="position:absolute; top:' + (offsetImage.top - offsetHeader.top) + 'px; left:' + (offsetImage.left - offsetHeader.left + 14) + 'px; z-index:500" />');
	
		params = {
			top     : (offsetCart.top - offsetHeader.top) + 'px',
			left    : (offsetCart.left - offsetHeader.left) + 'px',
			opacity : 0.25,
			width   : $('#shopping-cart').width(),  
			heigth  : $('#shopping-cart').height()
		};		
	
		$('#temp').animate(params, 700, false, function () {
			$('#temp').remove();
		});		

		return false;
	});			

	// update cart items
	$('#updateCart').live('click' ,function () {
		$(this).hide();
		$('#ajaxloader').show();
		var lang = $('#cart').attr('action').replace(/.+[\?&]lang=(\w+).*/, "$1");

		$.post($('#cart').attr('action') + '&json=1', $('#cart').serialize(), function(data) {
			$.get('/system/modules/de.alcina/templates/cart.jsp?lang=' + lang, function(data) {	
				$(data).replaceAll('#header').find('#shopping-cart form').show().end().find('#shopping-cart').addClass('hover');
			}, 'html');
		}, 'html');
		return false;
	});

	$('form[name="addToCart"] input[name^="qty["]').change(function () {
		var form	= $('form[name="addToCart"]');	
		var total	= 0;
		$('input[name^="qty["]', form).each(function() {
			if ($(this).val() > 0)
				total += $(this).val() * $('input[name="' + $(this).attr('name').replace("qty", "price") + '"]', form).val();
		});
		$('#orderTotal').html(parseFloat(total).toFixed(2).replace(".", ",") + " EUR");
	});

	// Navi usibility
	$("li.salon input[type=text]").focus( function(){
	    $("li.salon").addClass("enter_permanent");
	});
	
	$("li.salon input[type=text]").blur( function(){
	    $("li.salon").removeClass("enter_permanent");
	    Cufon.refresh();
	});
	
	$("li.search input[type=text]").focus( function(){
	    $("li.search").addClass("enter_permanent_search");
	});
	
	$("li.search input[type=text]").blur( function(){
	    $("li.search").removeClass("enter_permanent_search");
	    Cufon.refresh();
	});
	
	// Hauttypberater Buttons
	$('#recommendationbutton').click(function(){
	    $('#recommendation').val(1);
	});
	
	$('#norecommendationbutton').click(function(){
	    $('#recommendation').val(0);
	});

	$('form[name="answerform"] select').change(function() {
		if ($(this).val() != "")
			location.href = $(this).val();
	});
		
	// Contact form	
	$('#privat_checkbox').click(function(){
	  $('.extrafields').addClass('no_display')
	});
	
	$('#company_checkbox').click(function(){
	  $('.extrafields').removeClass('no_display')
	});	
	
	if($('#company_checkbox')[0] && $('#company_checkbox')[0].checked){
	  $('.extrafields').removeClass('no_display')
	}	

	// startpage stage slider
	if ($('#background .backgrounds').length) {
		window.setTimeout("animateStage()", 0);
		window.setInterval("animateStage()", 6500);
	}
});

function animateStage()
{
	animateElements('.backgrounds', 'fade');
}

function animateElements(selector, effect)
{
	var container	= $(selector);
	var list	= container.children('img');
	var currentItem	= list.eq(0);
	var nextItem	= list.eq(1);

	currentItem.remove().appendTo(container);
	currentItem.fadeOut(2000);
	nextItem.fadeIn(2000);
}
