function gotoHomepage(a){
	window.location.href = '/strona-glowna/'
}

$(function(){

// open rule in popup
	$(document.body).delegate('#openInPopup', 'click', function(e){
		e.preventDefault();
		
		var link = $(this).attr('href');

		$('#popup').fadeIn('fast');
		$('#popupBody').load(	link + ' #mainContentBody > *');
		
	});

// if ie...
	if( $.browser.msie ){
		if( $.browser.version < 9 )
			$('body').addClass('ie');
	} else {
		$('body').addClass('non-ie');
	}
	
	function isIE(){
		if( $.browser.msie && $.browser.version < 9 ){
			return true;
		}
	}

// bind events to get location		
	$('#formMeetingPlace, #formMeetingCity').live('blur', function(){
		var place = $('#formMeetingPlace').val();
		var city = $('#formMeetingCity').val();	
		var address, url;
		
		if( city != '' ){
			address = place +', ' + city;
			url = city + ' ' + place;

			url = url.replace(/ /g,"+");
			showAddress(address, url);		
		}
	});					

// set layer to document height
	function updateDocument(){
		var pageHeight = $('#mainContent').height() + 100,
				pageWidth = $(document).width();
				
		$('.layers').css({
			'min-height' : pageHeight
		});	
	}
	updateDocument();

// open custom link in new window
	$('#mainNavi .menu-item-type-custom').delegate('a', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				link = $this.attr('href');
				
		window.open(link);
		return false;
	});

// win gold coin
  $(document.body).delegate('#goldCoinSend', 'click', function(e){
  	e.preventDefault();
  	
  	var $this = $(this),
  			nextAction = $this.attr('data-action'),
  			args = {},
  			inputs = {},
  			errors = [],
  			validEmail = /^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$/i,
  			error = false;
  	
  	$('#errors').html('').removeClass('active');
  	
  	if( nextAction == 'step_2' ){
  	
  		args = {
  			action : nextAction
  		}
  		
  	} else if( nextAction == 'step_3' ){
  	
  		inputs = {
  			userAnswer : $('#formAnswer').val()
  		}
  		
  		args = {
  			action : nextAction,
  			userAnswer : inputs.userAnswer
  		}
  		
  		if( inputs.userAnswer.length > 250 ){
  			errors.push('Odpowiedź jest za długa. Dopuszczalna długość to 250 znaków. ');
  			error = true;
  		}
  		
  	} else if( nextAction == 'step_4' ){
  		var checkbox = $('#formCondition');
  		
  		if( !checkbox.is(':checked') ){
  			errors.push('Proszę zaakceptować warunki konursu. ');
  			error = true;
  		}
  		
  		inputs = {
  			userName : $('#formUserName').val(),
  			userAddres : $('#formUserAddres').val(),
  			userZipCode : $('#formUserZipCode').val(),
  			userCity : $('#formUserCity').val(),
  			userEmail : $('#formUserEmail').val()
  		} 
  		  	
  		args = {
  			action : nextAction,
  			userName : inputs.userName,
  			userAddres : inputs.userAddres,
  			userZipCode : inputs.userZipCode,
  			userCity : inputs.userCity,
  			userEmail : inputs.userEmail
  		}  	
  	}

		for( var i in inputs ){
			if( inputs[i] == '' ){
				error = true;  				
			}
		}  		
		
  	if( error == true ) {
  		errors.push('Proszę uzupełnić poprawnie wszystkie pola');
  		for( var e in errors ){
  			$('#errors').append(errors[e]).addClass('active');
  		}	
  	} else {
  		$this.attr('disabled', true);
  		
  		if( nextAction != 'step_2' ){
  			$this.hide().parent().append('<img class="ajaxLoader" src="/wp-content/themes/stock/style/css/i/ajax-loader.gif" />');
  		}
  			
	  	$('#winGoldCoinWrap').load('/zlota-moneta #winGoldCoinWrap > *', args, function(){
	  		getData();
	  		$this.attr('disabled', false);
	  		updateDocument();
	  	});		
  	}
  });	
 
// drink carusel
	var drinksCount,
			drinkWidth = 104,
			drinksWrapWidth,
			currentDrinkPosition = 0,
			maxDrinkPosition,			
			drinkStep = 0;
			
	$(document.body).delegate('.drinkCtrls', 'click', function(e){
		e.preventDefault();
		e.stopPropagation();
	
		drinksCount = $('#drinkCarousel').find('li').length;
		drinksWrapWidth = drinksCount * drinkWidth;
		maxDrinkPosition = drinksWrapWidth - ( 6 * drinkWidth );
		
		var $this = $(this),
				$drinkList = $('#drinkCarousel ul');
				
		$this.attr('disabled', true);

		if( $this.attr('id') == 'prevDrink' && currentDrinkPosition < 0 ){
			drinkStep = drinkStep + drinkWidth;
		} else if( $this.attr('id') == 'nextDrink' && Math.abs(currentDrinkPosition) < maxDrinkPosition ){
			drinkStep = drinkStep - drinkWidth;
		}
		$drinkList.stop().animate({ 'left' : drinkStep }, 500, function(){
			currentDrinkPosition = parseInt( $drinkList.css('left').slice(0, $drinkList.css('left').length-2), 10 );
			$this.attr('disabled', false);
		});		

	});
	
// small drink carusel
	var smallDrinksCount,
			smallDrinkWidth = 84,
			smallDrinksWrapWidth,
			smallCurrentDrinkPosition = 0,
			maxSmallDrinkPosition,			
			smallDrinkStep = 0;
			
	$(document.body).delegate('.smallDrinkCtrls', 'click', function(e){
		e.preventDefault();
		e.stopPropagation();
		
		var $this = $(this),
				$drinkList = $this.parent().find('ul');
		
		smallDrinksCount = $drinkList.find('li').length;
		smallDrinksWrapWidth = smallDrinksCount * smallDrinkWidth;
		maxSmallDrinkPosition = smallDrinksWrapWidth - ( 3 * smallDrinkWidth );		
				
		$this.attr('disabled', true);

		if( $this.attr('id') == 'prevDrink' && smallCurrentDrinkPosition < 0 ){
			smallDrinkStep = smallDrinkStep + smallDrinkWidth;
		} else if( $this.attr('id') == 'nextDrink' && Math.abs(smallCurrentDrinkPosition) < maxSmallDrinkPosition ){
			smallDrinkStep = smallDrinkStep - smallDrinkWidth;
		}
		$drinkList.stop().animate({ 'left' : smallDrinkStep }, 500, function(){
			smallCurrentDrinkPosition = parseInt( $drinkList.css('left').slice(0, $drinkList.css('left').length-2), 10 );
			$this.attr('disabled', false);
		});		

	});	
   
// send action    
  $(document.body).delegate('#sendInvitation', 'click', function(e){
  	e.preventDefault();
  	
  	var $this = $(this),
  			nextAction = $this.attr('data-action'),
  			args = {},
  			inputs = {},
  			errors = [],
  			validEmail = /^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$/i,
  			error = false;
  	
  	$('#errors').html('').removeClass('active');
  			
  	if( nextAction == 'step_2' ){  	
  	
  		inputs = {
  			inputImgName : $('#inputImgName').val(),
  			inputImgSrc : $('#inputImgSrc').val()
  		}
  		
  		args = {
  			action : nextAction,
  			drinkName : inputs.inputImgName,
  			drinkImage : inputs.inputImgSrc
  		}
  		
  		if( inputs.inputImgName == '' || inputs.inputImgSrc == '' ){
  			error = true;
  			errors.push('Proszę wybrać drink z listy. ');  		
  		}
  		
  	} else if( nextAction == 'step_3' ){

  		inputs = {
  			formUserName : $('#formUserName').val(),
  			formUserEmail : $('#formUserEmail').val(),
  			formUserFriendEmail : $('#formUserFriendEmail').val()
  		}
  		
  		if( !validEmail.test( inputs.formUserEmail ) ){
  			error = true;
  			errors.push('Proszę wpisać poprawny adres E-mail. ');
  		}
  		  	
  		args = {
  			action : nextAction,
  			userName : inputs.formUserName,
  			userEmail : inputs.formUserEmail,
  			userFriendEmail : inputs.formUserFriendEmail
  		}
  		
  	} else if( nextAction == 'step_4' ){
  	
  		inputs = {
  			formMeetingDay : $('#formMeetingDay').val(),
  			formMeetingMonth : $('#formMeetingMonth').val(),
  			formMeetingYear : $('#formMeetingYear').val(),
  			formMeetingPlace : $('#formMeetingPlace').val(),
  			formMeetingCity : $('#formMeetingCity').val(),
  			formMeetingOccasion : $('#formMeetingOccasion').val(),
  			formGoogleLink : $('#formMeetingGoogleLink').val()
  		}
  		  	
  		args = {
  			action : nextAction,
        meetingDay: inputs.formMeetingDay, 
        meetingMonth: inputs.formMeetingMonth, 
        meetingYear: inputs.formMeetingYear, 
        meetingPlace: inputs.formMeetingPlace, 
        meetingCity: inputs.formMeetingCity, 
        meetingOccasion: inputs.formMeetingOccasion, 
        meetingGoogleLink: inputs.formGoogleLink   			
  		}
  	}

		for( var i in inputs ){
			if( inputs[i] == '' ){
				error = true;  				
			}
		}  		
		
  	if( error == true ) {
  		errors.push('Proszę uzupełnić poprawnie wszystkie pola.');
  		
  		for( var e in errors ){
  			$('#errors').append(errors[e]).addClass('active');
  		}
  		
  	} else {
			$this.hide().parent().append('<img class="ajaxLoader" src="/wp-content/themes/stock/style/css/i/ajax-loader.gif" />');  	  	
	    $.get('/zapros-znajomych-na-drinka', args,
	      function(data){
	        $("#popupBody").html(data);
	    });  	
    }
  	
  });

// invite friends for drink
	$(document.body).delegate('.showPopup', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				link = $this.attr('href');
				
		$('#popup').fadeIn().find('#popupBody').html('<img class="ajaxLoader" src="/wp-content/themes/stock/style/css/i/ajax-loader.gif" />');
				
		$('#popup #popupBody').load(link);
	});
	
// select drink
	$(document.body).delegate('#drinkCarousel a', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				link = $this.find('img').attr('src'),
				title = $this.find('img').attr('alt'),
				$src = $('#inputImgSrc'),
				$name = $('#inputImgName');
				
		$('#drinkCarousel').find('li').removeClass('selected');
		$this.parent().addClass('selected');
		
		$src.val(link);
		$name.val(title);
	});

// next/prev
	var eventsCount = $('#historyList, #newsList').find('li').length,
			singleWidth = 245,
			eventsWrapWidth = eventsCount * singleWidth,
			currentPosition = 0,
			maxPosition = eventsWrapWidth - 4 * singleWidth,
			step = 0,
			click = 1;


	$(document.body).delegate('.eventCtrls', 'click', function(e){
		e.preventDefault();
		e.stopPropagation();
	
		var $this = $(this),
				$historyList = $('#historyList, #newsList');
				
		$this.attr('disabled', true);
		if( $this.attr('id') == 'prevEvent' && currentPosition < 0 ){
			step = step + singleWidth;
			click--;
		} else if( $this.attr('id') == 'nextEvent' /* && Math.abs(currentPosition) < maxPosition */ ){
			step = step - singleWidth;
			click++;
		}

		$historyList.stop().animate({ 'left' : step }, 500, function(){
			currentPosition = parseInt( $historyList.css('left').slice(0, $historyList.css('left').length-2), 10 );
			$sliderWrap.slider( 'option', 'value', click );
			$this.attr('disabled', false);
		});		

	});
	
// history slider
	var $sliderWrap = $('#slider'),
			count = $sliderWrap.attr('data-count'), 
			ymin = $sliderWrap.attr('data-min'),
			ymax = $sliderWrap.attr('data-max'),
			defPosition = 1;
			
	$sliderWrap.slider({

		value: defPosition,
		min: defPosition,
		max: count,
		step: 1,
		change: function( event, ui ) {
			$('#historyList').find('li').removeClass('active');
			
			if( defPosition < ui.value ){
				step = -( singleWidth * ( ui.value - 1 ) );
			} else if( defPosition > ui.value ) {
				step = step - ( step + ( singleWidth * ( ui.value - 1 ) ) );
			}
			defPosition = ui.value;
			$('#historyList, #newsList').animate({ 'left' : step }, 500, function(){
				$('#historyList').find('li:eq('+(defPosition - 1)+')').addClass('active');

			});	
			click = defPosition;
			currentPosition = step;
		}
	});	

// get drinks
	$('.recommendedDrinks').delegate('a', 'click', function(e){
		e.preventDefault();
		
		var link = $(this).attr('href');
		$('#popup').fadeIn().find('#popupBody').html('<img class="ajaxLoader" src="/wp-content/themes/stock/style/css/i/ajax-loader.gif" />');
		
		$('#popup #popupBody').load(link + ' #mainContentBody > *', initFbLike);
	});
	
	function initFbLike(){	
		var $wrap = $('#drinkLikeButton'),
				link = $wrap.attr('data-link'), 
				title = $wrap.attr('data-title'), 
				img = $wrap.attr('data-img'), 
				fbLike = '<fb:like href="'+link+'" show_faces="true" width="450" font=""></fb:like>';
							
		window.fbAsyncInit = function() {	
			FB.init({appId: '205608102785269', status: true, cookie: true, xfbml: true});
		};
		(function() {					
			var e = document.createElement('script'); e.async = true;
			e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
			document.getElementById('fb-root').appendChild(e);
		}());
	
				
		$wrap.html(fbLike);
	}
	
// close popup
	$('#popup').delegate('.closePopup', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this);
		
		$this.parent().fadeOut('fast');
	});	

/*

	ANIMATE HOME PAGE
	
*/	
// show boxes @ homepage	
	var homepageBox = 0,
			homepageBoxCount = $('#homepageMenu').find('li').length,
			timer = '';
	
	function showImages(){
		if( homepageBox < homepageBoxCount ){
			$('#homepageMenu').find('img:eq('+homepageBox+')')
				.css({
					'opacity' : 0
				})
				.stop()
				.animate({
					'margin-top' : 0,
					'opacity' : 1
				}, 800 );
			homepageBox++;
		} else if( homepageBox >= homepageBoxCount) {
			window.clearInterval(timer)
		}
	}
	
// aniamte navi	
	var $navi = $('#mainNavi'),
			$naviElements = $navi.find('li'),
			naviElementsCount = $naviElements.length,
			timer2,
			naviElement = 0;
	
	function animateNavi(){
		if( naviElement < naviElementsCount ){
		
			$navi.find('li:eq('+naviElement+')').animate({
				marginLeft : 0,
				opacity : 1
			}, 800 );
			naviElement++;
			
		} else if( naviElement == naviElementsCount ) {
			window.clearInterval(timer2);
			timer = window.setInterval( showImages, 150 );
		}
	}	
	
	if( !isIE() ){	
	
	// open animation 
		$('#mainContent').animate({ 
				opacity: 1 
			}, {
				duration: 1000, 
				complete: function(){
					
					if( $('body').hasClass('page-template-home-page-php') ){
						timer2 = window.setInterval( animateNavi, 150 );
					}
				}
		});
	
	// end animation	
		$('#mainNavi, h1').delegate('a', 'click', function(e){
			e.preventDefault();
			
			var $this = $(this),
					link = $this.attr('href');
					
			$('#mainContent').animate({ 'opacity' : 0 }, 500, function(){
				window.location.href = link;
			});
		});
		
	} else { // if IE less then 9
	
		timer2 = setInterval( animateNavi, 400 );
		timer = setInterval( showImages, 400 );
		
	}
	
// stock carousel
	var $stock = $('#stockClean'),
			$stockCitron = $('#stockCitron'),
			$stockCranberry = $('#stockCranberry');	
						
	var firstView = {
		'top' : '30px',
		'left' : '270px',
		'width' : '370px',
		'height' : '700px',
		'opacity' : 1			
	};		
	
	var secondView = {
		'top' : '65px',
		'left' : '0px',
		'width' : '250px',
		'height' : '473px',
		'opacity' : 0.7
	};

	var thirdViewClean = {
		'top' : '75px',
		'left' : '180px',
		'width' : '215px',
		'height' : '407px',
		'opacity' : 0.7			
	};
	
	var thirdViewCitron = {
		'top' : '75px',
		'left' : '160px',
		'width' : '215px',
		'height' : '407px',
		'opacity' : 0.7			
	};		
	
	var thirdViewCranberry = {
		'top' : '75px',
		'left' : '160px',
		'width' : '215px',
		'height' : '407px',
		'opacity' : 0.7			
	};	
	
	var options = {
		duration : 1400
		//easing : 'swing'
	}

	$('#carouselImages').delegate('img', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				id = $this.attr('id');
		
		// reset settings for small drink carousel		
		smallCurrentDrinkPosition = 0;
		smallDrinkStep = 0;
		
		if( !$this.hasClass('firstView') ){
			//showDetails($this.attr('id'), 'hide');	
			$('.detailsWrap:visible').fadeOut();
			$this.css('opacity', 1);
			
			switch(id){
				case 'stockClean':
				
					$stock.animate(firstView, options['duration'], function(){
						showDetails($this.attr('id'), 'show');
						changeGlowColor('blue');
					}).attr('class', '').addClass('firstView');
					
					$stockCitron.animate(secondView, options).attr('class', '').addClass('secondView');					
					$stockCranberry.animate(thirdViewCranberry, options).attr('class', '').addClass('thirdView');
					
					break;
				case 'stockCitron':
				
					$stockCitron.animate(
						firstView, options['duration'], function(){
							showDetails($this.attr('id'), 'show');
							changeGlowColor('yellow');											
					}).attr('class', '').addClass('firstView');		
					
					if( $this.parent().hasClass('carouselDetailsView') ){
						$stockCranberry.animate(secondView, options).attr('class', '').addClass('secondView');						
						$stock.animate(thirdViewClean, options).attr('class', '').addClass('thirdView');				
					} else {
						/* DEFAULT VIEW */														
						$stock.animate(secondView, options).attr('class', false).addClass('secondView');
						$stockCranberry.animate(thirdViewCranberry, options).attr('class', '').addClass('thirdView');
					}
									
					break;
				case 'stockCranberry':
				
					$stockCranberry.animate(firstView, options['duration'], function(){
						showDetails($this.attr('id'), 'show');
						changeGlowColor('red');
					}).attr('class', '').addClass('firstView');
								
					$stock.animate(secondView, options).attr('class', '').addClass('secondView');					
					$stockCitron.animate(thirdViewCitron, options).attr('class', '').addClass('thirdView');					

					break;
			}
						
			$this.parent().addClass('carouselDetailsView');
		}
	
	});
	
	function showDetails(id, status){
		if( status == 'show' ){
			$('#'+id+'Details').fadeIn();
		} else {
			$('#'+id+'Details').fadeOut();
		}
		
	}
	
// blue glow @ bottom
	if( !isIE() ){
		var canvas = document.getElementById('blueGlow'),
		    glow = null,
		    grad = null;
		    
		if (canvas && canvas.getContext('2d')) {
		  glow = canvas.getContext('2d');
		  glow.clearRect(0, 0, 800, 800);
		  glow.save();
		  
		  // create radial gradient
		  grad = glow.createRadialGradient(400,400,0,400,400,400); 
		  grad.addColorStop(0, '#062444'); //#001731	  
		  grad.addColorStop(1, 'rgba(0,0,0,0)');  
		
		  glow.fillStyle = grad;
		
		  glow.fillRect(0,0,800,800);
		  glow.save();
		} 
	}


	function changeGlowColor(color){
		if( color == 'blue' ){
			$('#layer-1').removeClass('yellow red');
		} else if( color == 'yellow' ){
			$('#layer-1').removeClass('red').addClass('yellow');			
		} else if( color == 'red' ){
			$('#layer-1').removeClass('yellow').addClass('red');			
		}
	}	
	
	
// valid data - age checker	
	var date = new Date();
	var currentDay = date.getDate();
	var currentMonth = date.getMonth()+1;
	var validYear = date.getFullYear() - 18;
	var currentYearTemp = String( date.getFullYear() );
	var currentYear = parseInt( currentYearTemp.slice(2) );


	
	$(document.body).delegate('#checkageAction', 'click', function(e){
		e.preventDefault();		
		getAge();
	});
	
	
// inline valid date
	$('#inputsWrap').delegate('input', 'focusin focusout keyup', function(e){
		var $this = $(this),
				value;
		
		if( e.type == 'focusin' ){
			$('#inputsWrap').find('input').removeClass('error');
					
			$this.val('');					
		}
		
		if( e.type == 'keyup' ){
			value = $this.val();
			
			if( value.length >= 2 ) {
				$this.next().val('').select();
			}
		}			
		
		
	});

	$('#checkageFormWrap').delegate('input', 'keyup', function(e){
		var $this = $(this)
				value = $this.val(),
				limit = 2,
				newValue = '';
		
		if( value.length >= 2 ){
			newValue = value.substr(0, limit);
			$this.val(newValue)
		}
	});
	
	
	function getAge(){		
		var day = parseInt( $('#checkageDay').val(), 10 ),
				month = parseInt( $('#checkageMonth').val(), 10 ),
				year_temp = parseInt( $('#checkageYear').val(), 10 ),
				year = '',
				$errors = $('#formErrors'),
				$inputs = $('#inputsWrap').find('input');
		
		$errors.hide();
		
		if( isNaN(day) || isNaN(month) || isNaN(year_temp) ){
			$errors.text('Proszę wpisać poprawną date').fadeIn();
			$inputs.addClass('error');
			
		} else {		
			if( day > 31 || month > 12 ){
				$errors.text('Proszę wpisać poprawną date').fadeIn();	
				$inputs.addClass('error');				
				return false;
			}
					
			if( String( year_temp ).length == 4 ){
				year = year_temp;
			} else {
				if( year_temp <= currentYear ){
					if( year_temp <= 9 ){
						year = '200' + String( year_temp );
					} else {
						year = '20' + String( year_temp );
					}
				} else {
					year = '19' + String( year_temp );
				}		
			}
			validAge(year, month, day);
		}		
	}
	
	function setCookie(c_name,value,exdays){
		var exdate=new Date();
		exdate.setDate(exdate.getDate() + exdays);
		var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
		
		document.cookie=c_name + "=" + c_value;
	}
	
	function validAge(y, m, d){
		var year = parseInt(y),
				month = parseInt(m),
				day = parseInt(d),
				valid = false,
				$errors = $('#formErrors');		

		if( parseInt(year) > validYear ){
			valid = false;
		} else if( parseInt(year) == validYear ){
			if( month > currentMonth ){
				valid = false;
			} else if( month == currentMonth ){
				if( day <= currentDay ){
					valid = true;
				} else {
					valid = false;
				}
			} else {
				valid = true;
			}
		} else {
			valid = true;
		}		
		
		if( valid == true ){
			setCookie('stock', 'true', 30);
			window.location = '/intro';
			
		} else {
			$errors.text('Aby przejść dalej musisz mieć ukończone 18 lat').fadeIn();
		}
	}
	
}); // end dom ready

  function getBirthday(date){
  	var date_temp = date,
  			year = date_temp.split('/')[2].slice(2),
  			month = date_temp.split('/')[0],
  			day = date_temp.split('/')[1];
  			
		$('#checkageDay').val(day);
		$('#checkageMonth').val(month);
		$('#checkageYear').val(year);
  }
  
  function updateStatus(name, av){
  	$('#fbStatusBody').html('<p>Jesteś zalogowany jako: <img src="'+av+'" alt="'+name+'" width="16" height="16" /> <em>'+name+'</em></p>');
  }	
