$(document).ready(function(){
	
	document.fruitData	= {
			
	};
	
	$(document).pngFix();

	document.url		= document.location.href;
	document.language	= ( document.url.indexOf('/de/') != -1 )? 'de' : 'en' ;
	
	document.isSmartphone = true;
	var uagent = navigator.userAgent.toLowerCase();
	if( uagent.indexOf('ipad') == -1 && uagent.indexOf('iphone') == -1 && uagent.indexOf('android') == -1 && uagent.indexOf('palm') == -1 && uagent.indexOf('webos') == -1 && uagent.indexOf('ipod') == -1)
		document.isSmartphone = false;

	// set Interval for the to the 2 message blocks on the Index

	if( $('#produkt-uebersicht').length > 0 && $('#frucht-info').css('display') != 'none' ){
		var info_interval = window.setInterval('toggle_info()', 5000);
	}

	$('#country-selector div.country-scroll-pane div.country').bind('click', function(){
		$('input[name="country"]').val($(this).attr('id'));
		$('#country-selector .status').html($(this).html()).css('display', 'block'); 
		if($(this).hasClass('two_rows')){
			$('#country-selector .status').addClass('two_rows');
		}else{
			if($('#country-selector .status').hasClass('two_rows')) $('#country-selector .status').removeClass('two_rows');
		}
		$('#country-selector div.country.active').removeClass('active');
		$(this).addClass('active');
		$('#country-selector').css({'height':'35px', 'padding-top': '1px'}).children('.country-scroll-pane').css('display','none');
	});
      
	/*
	  $('#produkt-detail-auszeichnungen-medal').fancybox({
	    'width'      : 300,
	    //'height'    : 480,
	    'scrolling'    : 'no',
	    'overlayColor'    : '#000',
	    'overlayOpacity'  : '0.5',
	    'autoScale'    : false,
	    'transitionIn'    : 'fade',
	    'transitionOut'    : 'fade',
	    'autoDimensions'  : false,
	    content: function(){
	      return '<div id="popup-dyn" class="visible"><div class="scroll-pane medal">'+$('#popup-dyn').html()+'</div></div>';
	    },
	    onComplete: function(){
	      $('#fancybox-close').css('display', 'block');
	
		var divHeight  = $('#popup-dyn').height() + 40;
		$('#fancybox-inner').css('height', divHeight);
		$('#fancybox-outer').css('height', divHeight+20);
		$('#fancybox-wrapper').css('height', divHeight+20);
	
	    }
	  });
	*/
	// init scrollPane (manufacture)
	$('.scroll-pane, .country-scroll-pane').jScrollPane({showArrows: true, arrowSize: 11, animateStep: 5});

	// init fancyboxes
	$("a#text-box").fancybox({
		'width'      : 300,
		'height'    : 480,
		'scrolling'    : 'no',
		'overlayColor'    : '#000',
		'overlayOpacity'  : '0.5',
		'autoScale'    : false,
		'transitionIn'    : 'fade',
		'transitionOut'    : 'fade',
		'type'      : 'iframe'
	});
	
	$("a#formular-box").fancybox({
		'width'      : 740,
		'height'    : 560,
		'scrolling'    : 'no',
		'overlayColor'    : '#000',
		'overlayOpacity'  : '0.5',
		'autoScale'    : false,
		'transitionIn'    : 'fade',
		'transitionOut'    : 'fade',
		'type'      : 'iframe',
		'onStart' : function(){
			if( document.language == 'en')
				$('#fancybox-close').addClass('en');
			return true;
		}
	});
	$('#kontaktform input#cancel').click(function(e){
		e.preventDefault();
		parent.$.fancybox.close();
	});
	
	$('a.fancybox').fancybox({
		'overlayColor'    : 'transparent',
		'padding'    : 0,
		'overlayColor'    : '#000',
		'overlayOpacity'  : '0.5',
		'showCloseButton'  : false,
		'titlePosition' : 'inside'
	});

	$('a.fb').fancybox({
		'overlayColor'    : 'transparent',
		'padding'    : 40,
		'overlayColor'    : '#000',
		'overlayOpacity'  : '0.5',
		'showCloseButton'  : true,
		'titlePosition' : 'inside'
	});
	// ENDOF "init fancyboxes"


	$('#country-selector div.country-scroll-pane').css('display', 'none');

/*
	var sliderDo = false; var sliderSelector = '';
	if( $('#slider img').length > 1){sliderDo = true;sliderSelector = '#slider';}
	if($('#news-detail-slideshow img').length > 1){sliderDo = true;sliderSelector = '#news-detail-slideshow';}
	
	if(sliderDo)
		$(sliderSelector).nivoSlider({
			effect: 'fade', //Specify sets like: 'fold,fade,sliceDown'
			animSpeed: 500, //Slide transition speed
			pauseTime: 3000,
			startSlide: 0, //Set starting Slide (0 index)
			directionNav: 'true', //Next & Prev
			directionNavHide: 'true', //Only show on hover
			controlNav: 'true', //1,2,3...
			keyboardNav: 'true', //Use left & right arrows
			pauseOnHover: 'true', //Stop animation while hovering
			manualAdvance: 'false', //Force manual transitions
			captionOpacity: 0.8 //Universal caption opacity
		});
*/

	$('#kontaktform').submit(function(submitevent){
		var error    = false;
		var errors    = new Array();
		var errorMsg    = 'Für eine Anfrage fehlen leider noch ein paar Felder.';
		var $inputfields  = $('input:not(.submit), textarea, select', this);
		var id      = '';
		var parentp    = ''
		var regex    = new Object();
		regex.num    = /^([0-9\-\/\+ ]{2,})$/;
		regex.email    = /^[A-Z0-9._-].+@[A-Z0-9._-].+\.([A-Z]{2,4})$/i;


		$inputfields.each(function(){
			error = false;
			id  = $(this).attr('id');
			parentp = $(this).parent('p');
			
			if( ( $(this).val().length < 2 )
			    && ( !$(this).is('[type=checkbox]') )
			    && ( parentp.hasClass('required'))
			)error = true;
			
			if( ( $(this).val() == 0 )
			    && ( $(this).is('[type=select]') )
			    && ( parentp.hasClass('required'))
			)error = true;
			
			if(error == true){
			  if(parentp.hasClass('required'))parentp.addClass('error');
			  if($(this).hasClass('textfeld-medium'))$(this).addClass('error');
			  errors.push(id);
			}else{
			  if(!$(this).hasClass('textfeld-medium')){
			    parentp.removeClass('error');
			  }else{
			    $(this).removeClass('error');
			    if( $(this).siblings('.error').length == 0) parentp.removeClass('error');
			  }
			}
		});


		if( errors.length == 0){
			var inputs = new Array();
			$(':input', this).each(function() {
			  inputs.push(this.name + "=" + escape(this.value));
			});
			var params = inputs.join('&');
			
			$.ajax({
			  type:     "POST",
			  beforeSend: function() {

			  },
			  data:    params,
			  dataType:  'html',
			  url:    this.action,
			  error:    function(err) {
			    $("p.error-msg").html('Beim Versenden der Nachricht ist ein Fehler aufgetreten.');
			  },
			  success:  function(returnedString) {
			    //alert(returnedString);
			    $("p.error-msg").html(returnedString);
			  }
			});
			submitevent.preventDefault();
			//parent.$.fancybox.close();
		}else{
			submitevent.preventDefault();
		}
	});


	$('#startseite-form').submit(function(submitevent){
		if( !$('input#datum', this).val().match(/^([0-9]{2})([. ]?)([0-9]{2})([. ]?)([0-9]{4})$/i) ){
			alert('Bitte geben Sie ein gültiges Geburtsdatum im Format \'TT MM YYYY\' ein.');
			submitevent.preventDefault();
		}else{
			var params = ''
			    params+= 'country=' + escape($('input[name=country]').val());
			    params+= '&datum=' + escape($('input[name=datum]').val());
			
			$.ajax({
				type:		"POST",
				url:		'/new/helpers/save_data.php',
				data:		params,
				dataType:	'html',
				success:	function(returnString){
					document.location.href = $('#startseite-form').attr('action');
				},
				error: function(returnString){
					//alert( 'error: '+returnString );
				}
			});
			submitevent.preventDefault();
		}
		submitevent.preventDefault();
	});


	// PRODUCTS OVERVIEW

	$('span.frucht-titel').css('opacity', 0);
	$('div.frucht-info').hide();

	if(document.isSmartphone == false){

	// FRUITS OVERVIEW
	
	// PRESET
		var id = '';
		var firstHover	= '';
		var fruchtInfoHtml = '';
		if( document.language == 'de' ){
			var fruchtInfoHtml	= '<h3 class="bold">Wählen Sie Ihren</h3><h2>Tropischen Edelbrand</h2><h3 class="first">Sorgfältig kreiert von<br />Österreichischen Edelbrennern<br />im Königreich Thailand</h3><h3 class="hidden second">Markteinführung Europa: März 2011</h3>';
		}else{
			var fruchtInfoHtml	= '<h3 class="bold">Choose your</h3><h2>Finest Tropical Fruit Spirit</h2><h3 class="first">Carefully Created by<br />Austrian Distillers<br />in the Kingdom of Thailand</h3><h3 class="hidden second">Launch Europe: March 2011</h3>';
		}
		
	// ENDOF PRESET
	
		$('#fruchtelinks area').hover(
		function(){    if( $('#fruechtelinks').css('display') != 'none' ){


		// setting vars
			if( typeof document.firstHover == 'undefined' )
				window.clearTimeout(document.pfTimeout);
			
			if(document.firstHover==true){
				document.firstHover=false;
				$('#fruchtelinks area#passion_fruit').triggerHandler('mouseleave');
			}

			var id    = $(this).attr('id');
			$fruitLi  = $('ul.produktgruppe li.'+id);
			$fruit    = $fruitLi.children('img');
			
		// text animation
			content  = $('ul.produktgruppe li.'+id+' div.frucht-info').html();
			$('#flaschen_etikett').attr('src', '/new/img/layout/flaschen_etikett/flaschen_etikett_'+id+'.png');
			$('#produkt-uebersicht #frucht-info').toggleClass('fruit slogan').html(content);
			$('ul.produktgruppe li.'+id+' span.frucht-titel').stop();
			$('ul.produktgruppe li.'+id+' span.frucht-titel').animate({'opacity':1}, 200);
		
		
		
		// fruit animation
			if( !$fruit.is(':animated') ){
				var w    = $fruit.width();
				var h    = $fruit.height();
				var wNew  = Math.ceil(w + (w/15));
				var hNew  = Math.ceil(h + (h/15));
				
				document.fruitData.id = null;
				document.fruitData.id = {'w'	: w, 'h'	: h };
				
				$.data($fruit, 'dim', {'w' : w, 'h' : h});
				
				var left  = parseInt($fruitLi.css('left'));
				var top    = parseInt($fruitLi.css('top'));
				var leftNew  = (left - ((wNew-w)/15));
				var topNew  = (top - ((hNew-h)/15));
				$.data($fruitLi, 'dim', {'top' : top, 'left' : left});
				$.extend(true, document.fruitData, {
					id : {'top'	: top, 'left'	: left }
				});
				
				$fruitLi.animate({
					'left'  : leftNew,
					'top'  : topNew
				}, 'fast');
				
				$fruit.animate({
					'width'  : wNew,
					'height': hNew
				}, 'fast');
			}
		} // endif
		},
		function(){
			content  = $('ul.produktgruppe li.'+id+' div.frucht-info').html();
			
		// text animation
			$('ul.produktgruppe li.'+id+' span.frucht-titel').stop();
			$('ul.produktgruppe li.'+id+' span.frucht-titel').animate({'opacity':0}, 200);
			$('#produkt-uebersicht #frucht-info').toggleClass('fruit slogan').html(fruchtInfoHtml);
			
		// fruit animation			
			var w    = $.data($fruit, 'dim').w;
			var h    = $.data($fruit, 'dim').h;
			var left  = $.data($fruitLi, 'dim').left;
			var top    = $.data($fruitLi, 'dim').top;

			var w = document.fruitData.id.w;
			var h = document.fruitData.id.h;
			var top = document.fruitData.id.top;
			var left = document.fruitData.id.left;

			$fruitLi.stop(true, true).animate({
			  'left'  : left,
			  'top'  : top
			}, 'fast');
			
			$fruit.stop(true, true).animate({
			  'width'  : w,
			  'height': h
			}, 'fast');
		});
		
		if( $('#fruchtelinks area#passion_fruit').length > 0 ){
			 //document.pfTimeout = window.setTimeout("firstHoverF()", 5000);
		}

	// END-OF FRUITS OVERVIEW


		$('#country-selector .status').bind('click', function(){
			var h = $(this).parent('#country-selector').css('height');
			if(h == '35px'){
				$(this).css('display', 'none');
				$(this).parent('#country-selector').css({'height': '179px', 'padding-top': '5px'}).children('.country-scroll-pane').css('display','block');
			}
		});


		$('ul#fruechte li a').hover(function(){
			$img = $(this).children('img');
			$(this).next('span').css({'display' : 'block'});
			if(!$(this).parent('li').is('.aktiv'))
				$img.css('opacity', '1');
		}, function(){
			$img = $(this).children('img');
			$(this).next('span').css({'display': 'none'});
			if(!$(this).parent('li').is('.aktiv'))$(this).children('img').css('opacity', '0.5');
		});


	}else{ // isSmartphone
		$('ul#fruechte li a img').each(function(){
			$(this).css('opacity', '1');
		});
	} // endof !isSmartphone


	$('.slidetabs').tabs('#box .images > div', {
		effect: 'fade',
		fadeInSpeed: 2351,
		fadeOutSpeed: 2351,
		rotate: true
	}).slideshow();


	if( $('#slideshow .slidetabs a').length > 0 ){
		var tabsAnz    = $('#slideshow .slidetabs a').length;
		var tabsW    = 23;
		var tabsDivWInner  = tabsW * tabsAnz;
		var tabsDivW    = 618;
		var tabsDivPadLeft  = (tabsDivW - tabsDivWInner) / 2;
		
		$('#slideshow .slidetabs').css({'padding-left': tabsDivPadLeft.toString()+'px', 'display' : 'block'});
		$(".slidetabs").data("slideshow").play();
		
		$('a.autoplay.play').click(function(e){
			$(this).css('display', 'none');
			$('a.autoplay.pause').css('display', 'block');
			e.preventDefault();
		});
		$('a.autoplay.pause').click(function(e){
			$(this).css('display', 'none');
			$('a.autoplay.play').css('display', 'block');
			e.preventDefault();
		});
		
		
		if( !document.isSmartphone )
		$('#slideshow').hover(function(){
			$('a.backward, a.forward', this).show();
		},
		function(){
			$('a.backward, a.forward', this).hide();
		});
	
	}else{
		$('#slideshow .slidetabs').css('display', 'none');
	}


	if( uagent.indexOf('iphone') != -1 || uagent.indexOf('ipad') != -1 ){
		var jspWidthDifference  = 5;
		var jspNewWidth  = parseInt($('a.jspArrowUp').css('width')) + jspWidthDifference;
		jspNewWidth  = jspNewWidth.toString()+'px';
		
		$('a.jspArrow').css({
			'width' : jspNewWidth,
			'position' : 'relative',
			'right' : jspWidthDifference.toString()+'px',
			'background-position' : jspWidthDifference.toString()+'px '+jspWidthDifference.toString()+'px !important'
		});
	}



	if( document.isSmartphone )
		$('.shiny-container').css('overflow', 'visible !important');


});


function firstHoverF(){
	document.firstHover = '';
	$('#fruchtelinks area#passion_fruit').triggerHandler('mouseenter');
	document.firstHover = true;
}

function toggle_info(){
  if( $('#frucht-info').children('h3.second').is(':hidden') ){
    $('#frucht-info').children('.first').fadeOut(400, function(){
      $('#frucht-info').children('.second').fadeIn(400);
    });
  }else{
    $('#frucht-info').children('.second').fadeOut(400, function(){
      $('#frucht-info').children('.first').fadeIn(400);
    });
  }
}

