function toggleMainMenu(){
	//resetowanie wartosci z css
	$('#site-header .main-menu .item:hover ul .dropbox').css("display","none");
	$('#site-header .main-menu .item ul .dropbox').css("display","block");
	$('#site-header .main-menu .item ul .dropbox').hide();

	function dropdownShow(element){
		$(element).addClass("active");
		$(element).find("ul .dropbox").show();
		$(element).find("ul .dropbox .content").show();
		$(element).find("ul .dropbox .content .inner").slideDown(200);
	}

	function dropdownHide(element){
		$(element).removeClass("active");
		$(element).find("ul .dropbox .content .inner").slideUp(200);
		$(element).find("ul .dropbox .content").hide();
		$(element).find("ul .dropbox").hide();
	}

	// kontroler dropdownu

			$('#site-header .main-menu .item').hover(function(){
				if($(this).find("ul .dropbox").length>0){
					dropdownHide($('#site-header .main-menu').children('.item').hasClass("active"));
				}
				dropdownShow(this);
			},function(){
				dropdownHide(this);
			});



}

function servicesListFxMainMenu(){
		$(".services-list li a").hover(function(){
			if($(this).parent().next(".middle")){
				$(this).parent().next(".middle").children("a").css("border-left-color", "#ffffff");
			}
			if($(this).parent().prev(".middle")){
				$(this).parent().prev(".middle").children("a").css("border-right-color", "#ffffff");
			}
		},
		function(){
			if($(this).parent().next(".middle")){
				$(this).parent().next(".middle").children("a").css("border-left-color", "#9eccac");
			}
			if($(this).parent().prev(".middle")){
				$(this).parent().prev(".middle").children("a").css("border-right-color", "#9eccac");
			}
		});
	}
function clearNewsletterInputs(conteiner){
	$(conteiner+" label").show();
	$(conteiner+" input#subscription_email").each(function() {

		if($(this).val()){
			$(this).val("");
		}

		$(this).focus(function(){
				$('#new_subscription label').hide();
		}).blur(function(){
			if($(this).val()){
					$('#new_subscription label').hide();
				}
				else{
					$('#new_subscription label').show();
				}
			}
		);

	});
}

function clearInputs(conteiner){
	$(conteiner+" label").show();
	$(conteiner+" input[type!='submit'][type!='hidden']").each(function() {

		if($(this).val()){
			$(this).val("");
		}

		$(this).focus(function(){
				$(this).prev().hide();
		}).blur(function(){
			if($(this).val()){
					$(this).prev().hide();
				}
				else{
					$(this).prev().show();
				}
			}
		);

	});
}

function clearTextarea(conteiner){
	$(conteiner+" label").show();
	$(conteiner+" textarea").each(function() {

		if($(this).val()){
			$(this).val("");
		}

		$(this).focus(function(){
				$(conteiner).find("label").hide();
		}).blur(function(){
			if($(this).val()){
					$(conteiner).find("label").hide();
				}
				else{
					$(conteiner).find("label").show();
				}
			}
		);

	});
}


// Ocenianie przepisów
var canRate = true;
var x;
var toHide;
function rate(){
	$(".rate button").hover(function(){
	  if (canRate) {
	    toHide = $(this).parent().parent().next();
	    toHide.text('oceń przepis').show();

	    x = $(this).parent().children(".rated");
	    x.removeClass("rated");
	    $(this).addClass("over");
  		$(this).prevAll().addClass("over");
	  }
	},function(){
	  if (canRate) {
      $(this).removeClass("over");
      $(this).prevAll().removeClass("over");
      x.addClass("rated");
      if (toHide) { toHide.hide(); }
	  }
	});

	$('form.recipe-rating').ajaxForm({
    dataType: 'json',
    beforeSubmit: function() {
      // canRate = false;
    },
    success: function(data) {
      if (data.success) {
        $('#recipe-feedback-' + data.slug).text('dziękujemy za ocenę!').show();
        $('#recipe-rating-' + data.slug + ' .rate button').removeClass("rated");
        $('#recipe-rating-' + data.slug + ' .rate button:lt(' + data.rating + ')').addClass("rated");
      }
      else {
        $('#recipe-feedback-' + data.slug).text('już oceniałeś ten przepis!').show();
        toHide = null;
        $('#recipe-rating-' + data.slug + ' .rate button').removeClass("rated");
        x.addClass("rated");
      }
    }
  });
}

function horizontalScroller(conteiner){
	if($(conteiner).length > 0) {
		// scroll content setup
		var scrollPane = $(conteiner+' .wrapper');
		var scrollContent = $(conteiner+' .wrapper .gallery');
		var scrollContentElement = $(conteiner+' .wrapper .gallery li');
		$(conteiner+' .wrapper .gallery li:last').css({'padding': 0});
		scrollContent.css({'width': scrollContentElement.size() * scrollContentElement.outerWidth() + 'px'});
		$(conteiner+' .previous').attr("disabled", "disabled" );
		$(conteiner+' .next').removeAttr("disabled");

		// slider controler

		$(conteiner+' .slider').slider({
			orientation: "horizontal",
			value: 0,
			min: 0,
			step: scrollContentElement.outerWidth(),
			max: scrollContent.width()-scrollPane.width(),
			slide:function(event, ui) {
				scrollContent.css({'left': -ui.value + 'px'});
			}
		});


		$.extend($.ui.slider.prototype, {
			next: function() {
				this.value(this.value() + this.options.step);
				var x = parseInt(scrollContent.css("left"));
				scrollContent.css({'left': x-this.options.step + 'px'});

				if(this.value() == this.options.max){
					$(conteiner+' .next').attr("disabled", "disabled" );
				}
				if(this.value() != this.options.min){
					$(conteiner+' .previous').removeAttr("disabled");
				}
			},
			previous: function() {
				this.value(this.value() - this.options.step);
				var x = parseInt(scrollContent.css("left"));
				scrollContent.css({'left': x+this.options.step + 'px'});

				if(this.value() == this.options.min){
					$(conteiner+' .previous').attr("disabled", "disabled" );
				}
				if(this.value() != this.options.max){
					$(conteiner+' .next').removeAttr("disabled");
				}
			}
		});

		$(conteiner+' .previous').click(function() {
			$(conteiner+' .slider').slider("previous");
			return false;
		});
		$(conteiner+' .next').click(function() {
			$(conteiner+' .slider').slider("next");
			return false;
		});

		// tooltip setup
		scrollContentElement.hover(function(){
			$(this).css('zIndex', 9998);
			$(this).find('.tooltip').fadeIn();
			var tooltipWidth = $(this).find('.tooltip').width();
			$(this).find('.tooltip').css({'margin-left': -tooltipWidth/2});

			$(conteiner+' .wrapper .gallery li:first').find(".tooltip").css({'margin-left': 0, 'left': 0});
			$(conteiner+' .wrapper .gallery li:first').find(".tooltip .tail").css({'left': 30});
			$(conteiner+' .wrapper .gallery li:last').find(".tooltip").css({'margin-left': 0, 'right': 0, 'left': 'auto'});
			$(conteiner+' .wrapper .gallery li:last').find(".tooltip .tail").css({'right': 30, 'left': 'auto'});

		},function(){
			$(this).css('zIndex', 0);
			$(this).find('.tooltip').fadeOut("fast");
		});
	}
}

function appendCategory(newCategoryName, checked) {
  // var newCategoryName = $(nameField).val();
  if (newCategoryName != "") {
    var catList = $('.recipe-add-page .form dl dd.category dl dd ul');
    catList.children('.list-float-clear').remove();
    var count = catList.children().size();
    var checkedString = "";
    if (checked == true)
      checkedString = ' checked="checked"';
    catList.append('<li><input type="checkbox" id="category-item-' + count + '"' + checkedString + '/><label for="category-item-' + count + '">' + newCategoryName + '</label></li>');
    catList.append('<li class="list-float-clear"></li>');
    $('.recipe-add-page .form dl dd.category dl dd .user-category input').val('');

  }
}

function getCurrentUnitId() {
  if ($("input[name='ingredient_unit'][selected='true']").size() > 0)
    return $("input[name='ingredient_unit'][selected='true']").val();
  else if ($("input[name='ingredient_unit']").size() > 0)
    return $("input[name='ingredient_unit']").val();
}

function recipeCleanErrors() {
  $('.recipe-add-page .form-error').hide();
  $('.recipe-add-page .error').removeClass('error');
}

function recipeShowErrorsFor(errors) {
  recipeCleanErrors();
  for ( var i in errors ) {
    if (errors[i].name=="description") {
      $('#error-'+errors[i].name).html(errors[i].error).show();
      $('#recipe_'+errors[i].name).parent('div').parent('div').addClass('error');
    } if (errors[i].name=="tag_list") {
      $('#error-'+errors[i].name).html(errors[i].error).show();
      $('#recipe_'+errors[i].name).parent('dt').addClass('error');
    } else if (errors[i].name!="slug") {
      $('#error-'+errors[i].name).html(errors[i].error).show();
      $('#recipe_'+errors[i].name).parent('span').addClass('error');
    }
  }
}

function hideIngredientsErrors() {
  $('#error-ingredient-quantity').hide();
  $('#ingredient-quantity').parent('span').removeClass('error');
  $('#error-ingredient-name').hide();
  $('#ingredient-name').parent('span').removeClass('error');
}

function checkIngredients() {
  var res = true;
  if ($('#ingredient-quantity').val()=="") {
    $('#error-ingredient-quantity').text("Pole ilość składnika nie może być puste.").show();
    $('#ingredient-quantity').parent('span').addClass('error');
    res = false;
  } else if (!(/^[0-9]+[,|.]?[0-9]*$/.test($('#ingredient-quantity').val()))) {
    $('#error-ingredient-quantity').text("Wartość pola ilość składnika musi być liczbą.").show();
    $('#ingredient-quantity').parent('span').addClass('error');
    res = false;
  }

  if ($('#ingredient-name').val()=="") {
    $('#error-ingredient-name').text("Pole nazwa składnika nie może być puste.").show();
    $('#ingredient-name').parent('span').addClass('error');
    res = false;
  } else {
    var repeated = false;
    $('#ingredients_list span.name').each( function(n) {
      if ($(this).text()==$('#ingredient-name').val()) repeated = true;
    });
    if (repeated) {
      $('#error-ingredient-name').text("Podany składnik został już dodany do przepisu.").show();
      $('#ingredient-name').parent('span').addClass('error');
      res = false;
    }
  }
  return res;
}

function recipeFormValidation() {
	  var dat = $('.recipe-add-page .form form').serialize();
	  $('#spinner').show();
    $.post("/przepisy-kulinarne/przepisy/validate", dat, function(data) {
      $('#spinner').hide();
      if (data.valid) {
        $('.recipe-add-page .form form').unbind('submit',recipeFormValidation);
        $('.recipe-add-page .form form').submit();
      } else {
        recipeShowErrorsFor(data.errorFields);
      }
    },"json");
    return false;
}


function addRecipeForm(){

	if($('.recipe-add-page .form').length > 0){

		$('.recipe-add-page .form dl dd.products dl dt').click(function(e){
		  var listId = $(this).next('dd').attr('id');
		  if (listId =='hide') {
		    $(this).next("dd").hide().attr('id','');
		  } else {
		    $('dd[id=hide]').hide().attr('id','');
		    $(this).next("dd").slideDown(400).attr('id','hide');
		  }
		  e.stopPropagation();
		});

		$('.recipe-add-page .form dl dd.category dl dt').click(function(e){
		  var listId = $(this).next('dd').attr('id');
		  if (listId=='hide') {
		    $(this).next("dd").hide().attr('id','');
		  } else {
		    $('dd[id=hide]').hide().attr('id','');
		    $(this).next("dd").slideDown(400).attr('id','hide');
		  }
		  e.stopPropagation();
		});

    // Klikanie na zielonych rozwijanych listach
    $('.recipe-add-page .form dl dd.products dl.product-category dd label').click(function(e) {
						var productGroupSlug = $(this).prev('input').val();
						var productGroupSlugLabel = $(this);

						$('.recipe-add-page .form dl dd.products dl.product-category dt').addClass("selected-value");
						$('.recipe-add-page .form dl dd.products dl.product-category dt').text(productGroupSlugLabel.text());

            $(this).closest('dd').hide().attr('id','');

						if($('.recipe-add-page .form dl dd.products dl.product-name dt').hasClass("selected-value")){
							$('.recipe-add-page .form dl dd.products dl.product-name dt').removeClass("selected-value");
							$('.recipe-add-page .form dl dd.products dl.product-name dt').text("");
						}

            $.get('/produkty/grupy/' + productGroupSlug + '/produkty/fetch', null, function(data) {
              $('.recipe-add-page .form dl dd.products dl.product-name dd ul').html(data);

              $('.recipe-add-page .form dl dd.products dl.product-name dd label').click(function(e) {
			          var productNameSlugLabel = $(this);
                var productName = $(this).prev('input').val();
                if (productName != 'on') {
                  $('#ingredient-id').val(productName);
                  $('#ingredient-name').val(productNameSlugLabel.text() + " Knorr");
                  $('#ingredient-type').val('Product');
                }
			          var productNameSlugLabel = $(this);
			          $('.recipe-add-page .form dl dd.products dl.product-name dt').addClass("selected-value");
			          $('.recipe-add-page .form dl dd.products dl.product-name dt').text(productNameSlugLabel.text());
                $(this).closest('dd').hide().attr('id','');
              });
            });

    });



    // Jeśli user coś wpisuje ręcznie w "ingredient-name" to musi to być zwykły Item (a nie Product)
    $('#ingredient-name').keypress(function(e) {
      $('#ingredient-type').val('Item');
      $('#ingredient-id').val(null);
    });

    // Kliknięcie na sugerowanych produktach z boku
    $('#suggested-products li').click(function(e) {
      if ($('#ingredient-name').size() > 0) {
        $('#ingredient-name').val($(this).find('.product-name').text());
        $('#ingredient-type').val('Product');
      }
      e.preventDefault();
    });

    // Przycisk "Podgląd"
    $('.recipe-add-page .form .buttons-wrapper .common-see-more-button-2').click(function(e) {
      $('.recipe-add-page form').attr('action', '/przepisy-kulinarne/przepisy/preview').submit();
      e.preventDefault();
    });

		$('.recipe-add-page .form dl dd.preparation textarea').autoResize({
			limit: 1000,
			// Quite slow animation:
			animateDuration : 300,
			// More extra space:
			extraSpace : 40
		});

    // Ustalenie początkowej wartości checkboksów z kategoriami
    var tagList = $('#recipe_tag_list').val();
    if (tagList == "") {
      $('#recipe_tag_list_preview').text("wybierz z listy");
    }
    else {
      $('#recipe_tag_list_preview').text(tagList);
      tagArray = tagList.split(", ");
      customTags = [];
      $.each(tagArray, function() {
        var label = $('.recipe-add-page .form dl dd.category dl dd ul li label:contains(' + this + ')');
        if (label.size() == 0)
          customTags.push(this);
        else
          label.prev('input').attr('checked', 'checked');
      });

      $.each(customTags, function() {
        appendCategory(this, true);
      })
      // add float clear for li's
    }

		$('.recipe-add-page .form dl dd.category dl dd').click(function(e) {
		  var target = $(e.target);
		  e.stopPropagation();
		  if (target.is("input")) {
		    var labels = $('.recipe-add-page .form dl dd.category dl dd ul li input:checked').next('label');
        var tagList = $.map(labels, function(n){ return $(n).text() }).join(", ");

        if (tagList.length == 0) {
          $('#recipe_tag_list').val("");
          $('#recipe_tag_list_preview').text("wybierz z listy");
        }
        else {
          $('#recipe_tag_list').val(tagList);
										$('#recipe_tag_list_preview').text(tagList.slice(0,65));
										if($('#recipe_tag_list_preview').text().length >= 65){
											$('#recipe_tag_list_preview').append("...")
										}
										else{
											$('#recipe_tag_list_preview').remove("...")
										}
        }
		  };
		});

		$('.recipe-add-page .form dl dd.category dl dd .user-category #user-category-phrase').keypress(function(e) {
		  if (e.which == 13) {
		    appendCategory($(this).val());
		    e.preventDefault();
		  }
		});

		$('.recipe-add-page .form dl dd.category dl dd .user-category button').click(function(e) {
      appendCategory($(this).prev().val());
      e.preventDefault();
		});

    // Dodawanie składników
    // $('.recipe-add-page .form dl dd.ingredients-2 button').click(function(e) {
    //   var unit_id = getCurrentUnitId();
    //
    //   var ingredientsList = $('.recipe-add-page .form dl dd.ingredients-list').find('ul');
    //   ingredientsList.append("<li>" + $('#ingredient-name').val() + "<a href=\"#\"><span>usuń z listy</span></a></li>");
    //   e.preventDefault();
    // })

    // Usuwanie składników
    $('.recipe-add-page .form dl dd.ingredients-list ul').click(function(e) {
      var target = $(e.target);
		  if (target.is("a")) {
        target.parent().remove();
      }
      e.preventDefault();
    })
	}

	// AJAX Validation
	$('.recipe-add-page .form form').submit(recipeFormValidation);
	//$('.recipe-add-page .form form .common-see-more-button-2').click(recipePreviewValidation);


}

function faqForm(){

	if($('.tips-page .faq fieldset').length > 0){
		$('.tips-page .faq fieldset .textarea-wrapper textarea').autoResize({
				limit: 1000,
				// Quite slow animation:
				animateDuration : 300,
				// More extra space:
				extraSpace : 40
		});
	}

}

function commentsForm(){

	if($('.recipe-page .comments fieldset').length > 0){
		$('.recipe-page .comments fieldset .textarea-wrapper textarea').autoResize({
				limit: 1000,
				// Quite slow animation:
				animateDuration : 300,
				// More extra space:
				extraSpace : 40
		});
	}

}

function showIngredients(element) {
	$(element).next('dd').hide();
	if($(element).length > 0) {
		$(element).click(function(e) {
		e.preventDefault();
		$(element).next('dd').slideToggle();
	})
	}

}

function reloadScroller(element) {
  var scrollPane = $(element).find('.vertical-scroller .scroll-wrapper');
  var scrollContent = $(element).find('.vertical-scroller .scroll-content');

  $(element).find('.vertical-scroller .scroll-bar').slider({
    orientation: "vertical",
    value: scrollContent.height()-scrollPane.height(),
    min: 0,
    max: scrollContent.height()-scrollPane.height(),
    slide:function(event, ui) {
      scrollContent.css({'bottom': -ui.value + 'px'});
    }
  });
}

function isKazdyPosilekControls(){

  $('.is-kazdy-posilek-page .content').tabs({
    show: function(event, ui) { reloadScroller(ui.panel); }
  });

}

function registerForm(){
	if($('.layer-box').length > 0 && $('.layer-curtain').length > 0){
		$('.layer-box .register .common-layer-form-clauses input:checkbox').checkbox({cls:'jquery-checkbox'});
	}
}

var loginRedirect = null;
var submitRedirect = null;

function layer(){
	if($('.layer-box').length > 0 && $('.layer-curtain').length > 0){

		function layerHide(){
			$('.layer-curtain').hide();
			$('.layer-box .content').hide();
			$('.layer-box').hide();
		}

		function layerShow(element){
			$('.layer-curtain').show();
			$('.layer-curtain').css('height', $(document).height()+'px');
			$('.layer-box').show();
      $('.layer-box '+element).fadeIn();
      $('.layer-box').css('marginTop', -$('.layer-box').height()/2+$(window).scrollTop()+'px');
		}

    // Przed submitem formularza logowania
		function loginPrepare() {
      $('.layer-box .login .login-error').slideUp('fast');
		}

    // Powrót z akcji logowania
		function loginSuccess(data) {
		  if (data.success) {
		    layerHide();
		    if (loginRedirect != null)
  		    window.location = loginRedirect;
  		  else if (submitRedirect != null)
  		    $(submitRedirect).unbind('submit').submit();
  		  else
  		    window.location.reload();
		  } else {
        $('.layer-box .login .login-error').text(data.message).slideDown('fast');
		  }
		}

    // Powrót z akcji rejestracji
/*    function registerSuccess(responseText, statusText) {
      if (responseText == "OK") {
        Recaptcha.create("6LcNdQcAAAAAAHmdLQj22dwE_8lgEPLZFJIsZJNN", 'recaptcha_placeholder', {
          theme: "white",
          callback: Recaptcha.focus_response_field
        });
        layerHide();
        layerShow(".captcha");
      }
      else {
        $('.layer-box .register form fieldset').html($(responseText).find('fieldset').contents());
      }
    }
*/
    function captchaSuccess(data) {
      if (data.status == "OK") {
        Recaptcha.destroy();
        layerHide();
        layerShow(".confirmation");
        $('.layer-box .confirmation .layer-control-button').click(function(){
          layerHide();
        });
      }
      else if (data.status == "invalid_recaptcha") {
        Recaptcha.reload();
      }
    }


function registerSuccess(responseText, statusText) {
  if (responseText == "OK") {
      layerHide();
      layerShow(".confirmation");
      $('.layer-box .confirmation .layer-control-button').click(function(){
        layerHide();
      });
  }
  else {
    $('.layer-box .register form fieldset').html($(responseText).find('fieldset').contents());
  }
}



    // Przed submitem formularza przywracania hasła
		function resetPasswordPrepare() {
      $('.layer-box .reset-password .reset-password-error').slideUp('fast');
		}

		// Powrót z akcji przywracania hasła
		function resetPasswordSuccess(data) {
		  if (data.success) {
		    layerHide();
        layerShow(".reset-password-confirmation");
        $('.layer-box .reset-password-confirmation .layer-control-button').click(function(){
          layerHide();
        });
		  } else {
        $('.layer-box .reset-password .reset-password-error').text(data.message).slideDown('fast');
		  }
		}

		$('#site-header .user-menu .login-button').click(function(e){
      loginRedirect = null;
			layerShow(".login");
			e.preventDefault();
		});

		$('#site-header .user-menu .register-button').click(function(e){
			layerShow(".register");
			e.preventDefault();
		});

		$('#site-header .user-menu .captcha-button').click(function(e){
			layerShow(".captcha");
			e.preventDefault();
		});

		$('.layer-box .login .buttons-wrapper .register-button').click(function(e) {
			layerHide();
			layerShow(".register");
			e.preventDefault();
		});

		$('.layer-box .login .buttons-wrapper .password-reset-button').click(function(e) {
			layerHide();
			layerShow(".reset-password");
		});

    // $('.layer-box .register .buttons-wrapper .form-submit-button').click(function(e){
    //       layerHide();
    //  layerShow(".confirmation");
    //  $('.layer-box .confirmation .layer-control-button').click(function(){
    //    layerHide();
    //  });
    // });

		$('.layer-box .close-button').click(function(e){
				layerHide();
				e.preventDefault();
		});

    // Automatyczne wyskakiwanie loginu dla linków oznaczonych '.login-required'
    // Dodatkowo - przekierowanie po sukcesie
    $('a.login-required').click(function(e) {
      e.preventDefault();
      loginRedirect = $(this).attr('href');
      layerShow(".login");
    });

    $('form.login-required').submit(function(e) {
    	submitRedirect = $(this);
      if($(this).attr("id") == "new_comment"){
    	  layerShow(".addNewComment");
      }else{
    	  layerShow(".login");
      }
      e.preventDefault();
    });

    // Ajaxowe formy
    $('.layer-box .login form').ajaxForm({
      dataType: 'json',
      beforeSubmit: loginPrepare,
      success: loginSuccess
    });

    $('.layer-box .register form').ajaxForm({
      success: registerSuccess
    });

    $('.layer-box .captcha form').ajaxForm({
      dataType: 'json',
      success: captchaSuccess
    });

    $('.layer-box .reset-password form').ajaxForm({
      dataType: 'json',
      beforeSubmit: resetPasswordPrepare,
      success: resetPasswordSuccess
    });
	}
}


function fetchComments(path) {
  var count = $('.comments dl dd').size();
  // alert(count);

  $.get(path, { offset: count }, function(data) {
    if (data != "") {
      $(data).hide().appendTo('.comments dl').show("slow");
      if ($('.comments dl dd').size() < count + 3)
        $('.comments .common-see-more-button-2').hide();
    } else {
      $('.comments .common-see-more-button-2').hide();
    }
  });
}

// Podpięcie funkcjonalności "Czy wiesz że" (okienko z przełączaniem następna/poprzednia)
function hookupTidbits() {
  $('.curiosities .common-see-more-button-1').click(function(e) {
    var nextId = parseInt($('.curiosities span#tidbit_id').text()) + 1;
    $.getJSON("/tidbits/" + nextId, function(data) {
      $('.curiosities span#tidbit_id').text(data.id);
      $('.curiosities p').text(data.body);
    });
    e.preventDefault();
  });
}

// Podpięcie wyskakującego logina dla linków z klasą .login-required
// Usunąć. Przeniesione do layer()
// function hookupLoginRequired() {
//   $('.login-required').click(function(e) {
//     e.preventDefault();
//     loginRedirect = $(this).attr('href');
//     layerShow(".login");
//   });
// }

function contactClearErrors() {
  $('#message_name').parent('dd').removeClass('error');
  $('#message_email').parent('dd').removeClass('error');
  $('#message_body').parents('dd').removeClass('error');

  $('.form-error').hide();
}

function contactFormValidator(e) {
  var error = false;
  contactClearErrors();
  if ($('#message_name').val()=='') {
    $('#message_name').parent('dd').addClass('error');
    $('#message_name').parent().next('.form-error').text('Pole nie może być puste.').show();
    error = true;
  }

  if ($('#message_email').val()=='') {
    $('#message_email').parent('dd').addClass('error');
    $('#message_email').parent().next('.form-error').text('Pole nie może być puste.').show();
    error = true;
  } else {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (!(reg.test($('#message_email').val()))) {
      $('#message_email').parent('dd').addClass('error');
      $('#message_email').parent().next('.form-error').text('Niepoprawny adres email.').show();
      error = true;
    }
  }

  if ($('#message_body').val()=='') {
    $('#message_body').parents('dd').addClass('error');
    $('#message_body').parents('dd').next('.form-error').text('Pole nie może być puste.').show();
    error = true;
  }

  if (error) { return false; }
  else {
    return true;
  }
}

function commonForms() {
  $('.common-form select').selectReplace();
  if ($('#contact-form').length > 0) {

    $('form').submit(function(e) { return contactFormValidator(e);});
  }
}

// loads jcarousel, only for "special news"
function carouselForNews() {
  if (('#site-body .special-news').length > 0) {
    $('#recipe-carousel').jcarousel({'scroll': 4});
    $('#recipe-carouse2').jcarousel({'scroll': 4});
    $('#recipe-carousel3').jcarousel({'scroll': 4});
  }
}

function scrollForVideos() {
  $('#video-thumbnails-inner').jScrollHorizontalPane({scrollbarHeight:19, scrollbarMargin:0,showArrows:true,arrowSize:22});
  $('#video-thumbnails-small-inner').jScrollHorizontalPane({scrollbarHeight:19, scrollbarMargin:0,showArrows:true,arrowSize:22});
  $('#video-thumbnails-small2-inner').jScrollHorizontalPane({scrollbarHeight:19, scrollbarMargin:0,showArrows:true,arrowSize:22});
}

function recipe_switchTo(i) {
  $('.recipe-holder .recipe-current').removeClass('recipe-current').fadeOut(250);
  $('.recipe-holder #recipe-'+i).addClass('recipe-current').fadeIn(250);
  return false;
}

function recipe_switchTo1(i) {
  $('.recipe-holder-first .recipe-current').removeClass('recipe-current').fadeOut(250);
  $('.recipe-holder-first #recipe-'+i).addClass('recipe-current').fadeIn(250);
  return false;
}

function recipe_switchTo2(i) {
  $('.recipe-holder-second .recipe-current').removeClass('recipe-current').fadeOut(250);
  $('.recipe-holder-second #recipe-'+i).addClass('recipe-current').fadeIn(250);
  return false;
}


$(document).ready(function() {

	rate();
	toggleMainMenu();
	servicesListFxMainMenu();
	addRecipeForm();
	faqForm();
	clearTextarea(".tips-page .faq fieldset");
	clearTextarea(".main-column .comments fieldset");
	clearInputs("#site-header .main-search");
	clearNewsletterInputs(".common-newsletter fieldset");
	clearNewsletterInputs(".press-newsletter fieldset");
	clearInputs(".search-results-page .search fieldset");
	clearInputs(".recipe-add-page .form dl dd.category dl dd .user-category");
	clearInputs(".recipes-page .search .main");

	isKazdyPosilekControls();

	registerForm();
	layer();
	commonForms();
	carouselForNews();

	hookupTidbits();

	horizontalScroller(".recipes-page .popular .common-content-scroller");
	horizontalScroller(".recipe-page .popular .common-content-scroller");
	horizontalScroller(".product-category-page .popular .common-content-scroller");
	horizontalScroller(".product-page .popular .common-content-scroller");
        scrollForVideos();

	showIngredients(".product-page .description .content .ingredients dt");

	$(".carousel-news").easySlider({
		numeric: true,
		auto: true,
		continuous: true,
		numericId: 'carousel-controler',
		pause: 3000,
		speed: 400
	});

	$(".carousel-recipe").easySlider({
		numeric: true,
		auto: true,
		continuous: true,
		numericId: 'carousel-controler',
		pause: 3000,
		speed: 400
	});

	$(".carousel-products").easySlider({
		numeric: true,
		auto: true,
		continuous: true,
		numericId: 'carousel-controler',
		pause: 3000,
		speed: 400
	});

	$(".carousel-product").easySlider({
		numeric: true,
		auto: true,
		continuous: true,
		numericId: 'carousel-controler',
		pause: 3000,
		speed: 400
	});

	$(".carousel-tips").easySlider({
		numeric: true,
		auto: true,
		continuous: true,
		numericId: 'carousel-controler',
		pause: 3000,
		speed: 400
	});


  // Link "drukuj"
	var popupParams = 'width=800, height=600, resizable=yes, locations=no, status=no, scrollbars=yes, toolbar=no, directories=no, menubar=no, fullscreen=no';

  $('#print_link').click(function(event) {
    window.open($(this).attr('href'), '', popupParams);
    event.preventDefault();
  });

  // Facebox
  $('a[rel*=facebox]').facebox();
  //Rollovery w gotowaniu z dziecmi

  $('#roll-links li').each(function(index){
	$(this).hover(
		function(){
			$(this).addClass('on')
		},
		function(){
			$(this).removeClass('on');
		
   });
   });
});

