

/* -------------------------------- */

jQuery.fn.productCount = function(sum) { // create stepper for counter

		function subtotal(sum) {
			if(sum=="cart") {
				var price = parseFloat($this.parent().prev(".price").text().replace(" ","").replace(" ","").replace(",","."));
				var subtotal = parseFloat($this.parent().next(".subtotal").text().replace(" ","").replace(" ","").replace(",","."));
				subtotal = nr*price;
				$this.parent().next(".subtotal").text(addSpaces(subtotal) + " " + currency);

				var total = 0;
				var discount_amount=0;

        $("td.price").each(function() {
					var item_id= $(this).parent().find("input").attr('id').match(/\d+/);
					var discount=discounts[item_id];

          var total_for_item = parseFloat($(this).text().replace(" ","").replace(" ","").replace(",",".")) * $(this).next().find(".count input").val();
          total += total_for_item;
			    if (discount){
             total -= Math.ceil(total_for_item * discount);
             discount_amount += Math.ceil(total_for_item * discount);
          }
         });

        $(".discount_amount.subtotal").text("-" + discount_amount + " " + currency);

         /*alert(base_rate);
         alert( payment_rate);
         alert(total);*/

				if((total )< payment_rate) {
					total = total + base_rate;
					$(".doprava.subtotal").text(base_rate + " " + currency);


                                        $(".box.ship p").html(add_more.replace(/\%s/g, addSpaces(base_rate + payment_rate - total) + " " + currency));
                                        $(".box.ship").removeClass("free");
                            } else {
					$(".doprava.subtotal").text(free);
					$(".box.ship p").html(have_discount.replace(/\%s/g, payment_rate+ " " + currency));
                                        $(".box.ship").addClass("free");
                            }

				$(".total").text(addSpaces(total) + " " + currency);
			}

			if(sum=="detail") {
				price = parseFloat($(".catalog-product-view fieldset.package input:checked").closest("label").find("em").text().replace(" ","").replace(" ","").replace(",","."));
				price = nr*price;
				$("#price").text(addSpaces(price) + " " + currency );
			}
		}

		var $this = $(this);

		$this.find("input").wrap('<div class="stepper"></div>');
	  var nr = $this.find("input").val();
	  $this.find(".stepper").append('<a class="down">–</a> <strong>'+nr+'</strong> <a class="up">+</a>');
	  $this.find(".stepper a.up").click(function() {
	  	if(nr<99) {
	  		nr++;
	  	}
	  	$this.find("input").val(nr);
	  	$this.find(".stepper strong").text(nr);

                subtotal(sum);
                $("#cart_form").ajaxSubmit();
                $("#cart-count").text(parseInt($("#cart-count").text())+1);
	  });
	  $this.find(".stepper a.down").click(function() {
	  	if(nr>1) {
	  		nr--;
	  	}
	  	$this.find("input").val(nr);
	  	$this.find(".stepper strong").text(nr);
	  	subtotal(sum);

                $("#cart_form").ajaxSubmit();
                $("#cart-count").text(parseInt($("#cart-count").text())-1);
	  });

}


$(function() {
	$("body:not(.cms-index-index) #fullcatbox").append('<a id="closefullcatbox">×</a>');
	$("#closefullcatbox").click(function() {
		$("#fullcatbox").stop(true,true).slideUp("slow");
	});
});



function addSpaces(nStr) {
			nStr = parseFloat(nStr);
                        nStr = nStr.toFixed(2);


                        nStr += '';
			nStr = nStr.replace(".",",");
                        //alert(nStr);
			x = nStr.split('.');
			x1 = x[0];
			x2 = x.length > 1 ? '.' + x[1] : '';
			var rgx = /(\d+)(\d{3})/;
			while (rgx.test(x1)) {

                                x1 = x1.replace(rgx, '$1' + ' ' + '$2');
                                //alert(x1);
			}


			return x1 + x2;


            }


//Fotky u produktu

$(document).ready(function() { // photo gallery

	var shown = false;
	var beenshown = false;
	var foo = $(".catalog-product-view div.productimages .mainimg");

	foo.click(function(event) {

                event.preventDefault();
                foo=$(this);


		if(!shown) { // not to be called twice

			var original = { // original dimensions
				"width": foo.css("width"),
				"height": foo.css("height"),
				"imgheight": foo.find("img").innerHeight(),
				"imgwidth": foo.find("img").innerWidth(),
				"imgmaxheight": foo.find("img").css("max-height"),
				"imgmaxwidth": foo.find("img").css("max-width"),
				"imgsrc": foo.find("img").attr("src")
			}


                        //if ($(this).hasClass("mainimg")) alert("Hej");




			shown = true; // it is shown
			foo.parent().addClass("shown");

                        foo.parent().find(".smallimg").hide("slow");
                        foo.parent().find(".smallimg").hide("slow");






			$("div.product").stop(true,true).hide("slow"); // hide product info

			var maximal = { // maximal dimensions
				"imgheight": foo.find("img").innerHeight(),
				"imgwidth": foo.find("img").innerWidth()
			}

                        //alert(foo.find("img").innerWidth());



			foo.find("img").css({ // get back before animation
				"height":original["imgheight"],
				"max-height":original["imgmaxheight"],
				"max-width":original["imgmaxwidth"]
			});

			if(maximal["imgheight"]>620) { // max height
				var setimgheight = 620;
			} else {
				var setimgheight = maximal["imgheight"];
			}



			foo.animate({ // stretch the img box
		    	width: ['620px', 'swing'],
		    	height: [setimgheight, 'swing']
			  }, 'slow', 'linear', function() {
		  });


			foo.find("img").css({ // maximize the image
				"max-height":"none",
				"max-width":"none"
			}).animate({
		    	height: [setimgheight, 'swing']
			  }, "slow", 'linear', function() {

			  	if(!beenshown) { // only do this once
				  	$(".productimages ul").append('<li class="selected"></li>'); // duplicate main image
				  	foo.clone().removeClass("mainimg").removeAttr("style").appendTo(".productimages ul li.selected");
				  	$(".productimages ul li.selected a img").removeAttr("style");
				  	beenshown = true;
			  	}

			  	$("html, body").animate({
						scrollTop:$("#main").offset().top+10
					},"slow");


			  	//$(".productimages ul").show("slow"); // show additional images



			  	foo.parent().append('<a id="closephotobox">×</a>'); // show close button
			  	$("#closephotobox").fadeTo("slow",1);
					$

                                        ("#closephotobox").click(function() { // set close button click action
						event.preventDefault();

						$("#closephotobox").fadeTo("slow",0);
						$("#closephotobox").remove(); // remove close button

                                                foo.parent().find(".smallimg").show("slow");


                                                shown = false; // it is not shown
						foo.parent().removeClass("shown");

						foo.find("img").attr("src",original["imgsrc"]); // show original main image

						$(".productimages ul").hide(); // hide additional images

						foo.animate({ // narrow the box
					    width: [original["width"], 'swing'],
					    height: [original["height"], 'swing']
						 }, 'slow', 'linear');

						foo.find("img").animate({ // minimize the image
	    		 		height: [original["imgheight"], 'swing']
		  		 	}, "slow", 'linear', function() {
		  		 		foo.find("img").css({
		  		 			"height":"auto",
								"max-height":original["imgmaxheight"],
								"max-width":original["imgmaxwidth"]
							});
							$("div.product").show("slow", function() {
								$("#facebook-likebutton").show();
							}); // show product info

							foo.removeAttr("style");
							foo.find("img").removeAttr("style");

						});

					});
		  });

		}

	});


       $(".productimages .smallimg").click(function(event) {
			  		event.preventDefault();
			  		if(!$(this).hasClass("selected")) {
				  		var a = $(this).find("img").attr("src"); // swap images
				  		$(".productimages .smallimg").removeClass("selected");
				  		foo.find("img").stop(true,true).fadeOut(function() {
				  			foo.find("img").attr("src",a);
				  		});
				  		$(this).addClass("selected");
				  		foo.find("img").fadeIn("slow");
						}
        });




    $("#productinfo li").click(function() {

        var that = $(this);
        $("#productinfo li").removeClass("sel");
        $("#productinfo .info div").removeClass("sel");
        $("." + that.attr("class")).addClass("sel");

        return false;
    });


// validace registrace
/*  $("#new-account").validate({
 	  rules: {
	    firstname: {
	      required: true,
	      minlength: 2
	    },
	    lastname: {
	      required: true,
	      minlength: 2
	    },
	    email: {
	      required: true,
	      email: true
	    },
	    password: {
				required: true,
				minlength: 5
			},
	    confirmation: {
				required: true,
				minlength: 5,
      	equalTo: "#password"
	    }
    },
		messages: {
			firstname: "Potřebujeme znát Vaše jméno.",
			lastname: "Potřebujeme znát i Vaše příjmení.",
			email: {
				required: "Napište prosím svůj email, bez něj to nepůjde.",
				email: "Napište prosím svůj email ve správném tvaru."
			},
			password: {
				required: "Zvolte si prosím heslo.",
				minlength: "Zvolte trochu bezpečnější heslo - 5 znaků bude stačit."
			},
			confirmation: {
				required: "Ujistěte nás prosím, že si heslo pamatujete.",
				equalTo: "Hesla se Vám neshodují. Někde bude chybička."
			}
		}
  });*/

	$(".checkout-cart-index #main form #haveaccount input[type=submit]").click(function() {

		var a = $(".checkout-cart-index #main form");
		var settings = a.validate().settings;

		$.extend(settings, { // overwrites settings from the other part of the form
      errorPlacement: function(error, element) {
				$(".checkout-cart-index #main form #haveaccount input[type=submit]").before(error);
			},rules: {
        "login[username]": {required: true, email: true},
        "login[password]": {required: true}
      },
      groups: {
			  logindetails: "login[username] login[password]"
			},
      messages: {
        "login[username]": "Nezapomeňte zadat svůj e-mail.",
        "login[password]": "Nezapomeňte zadat své heslo.",
        logindetails: "Nezapomeňte zadat oba údaje."
      }
    });

		a.validate();

	});


    // Error messages zaviraci tlacitko

    $(".messages").append('<a class="closeerrormsg">×</a>');

    $(".closeerrormsg").click(function() {

            $(this).parent().stop(true,true).slideUp("slow");
    });


    // ratings mouse over na zaklade toho jestli je uzivatel prihlasen

    var rating_count_text = $('.rating_count').text();

    $("div.product div.loggedin").ready(function(){

      var width;

      if (window.rating_start_width == undefined || !rating_start_width){
          width = 0;
      }else{
          width = rating_start_width;
      }


      var hidden = $('<input type="hidden" class="origWidth" value="'+width+'" />');
      $('.rating').after(hidden);
    });

    $("div.product div.notloggedin").mousemove(function(e){
         $('.rating_count').text(login_for_rating);
    });

    $("div.product div.notloggedin").mouseleave(function(e){
         $('.rating_count').text(rating_count_text);
    });


    $("div.product div.loggedin").mousemove(function(e){
        e.preventDefault();
        var self = $(this);

        var x = e.pageX - self.offset().left;

        var width = self.width();
        var percentage = x / width;


        if (percentage > 1) percentage = 1;
        var value = Math.floor(percentage * 100);

        self.parent().children('.rating').width(value);
        console.log(this);
        return false;
    });

    $("div.product div.loggedin").mouseleave(function(e){
        e.preventDefault();
        var self = $(this);
        $(self).parent().children('.rating').width($('.origWidth').attr('value'));
        console.log(this);
        return false;
    });


   //Výběr odstínu

   $(".tone_radio").hide();

   $(".tone_select").click(function(){
       $(".tone_radio").attr("checked", false);
       $("#tone").text($(this).attr("title"));
       var availibility = $(this).parent().find("input[name=availability]").attr("value");

       if (availibility) $("#toneAvailability").text("(" + availibility + ")");
       $(this).parent().find(".tone_radio").attr("checked", true);
       $(".tone_select").removeClass("sel");
       $(this).addClass("sel");
       return false;
   });

    $(".tone_select:first").click(); // klikneme na prvni vyberatko a tim ho oznacime

    $(".tone_select").mouseenter(function(event){
       var big=$(this).parent().find(".tone_big");
       big.show();


       big.css("top", -big.height()-10);
       big.css("left", 0);
       big.css("position", "absolute");
    });

    $(".tone_select").mouseleave(function(){
        $(this).parent().find(".tone_big").hide();
    });


    //Přidání produktu do košíku

    $("#addtocart").click(function(){
      var name = $(".tone_radio:checked").attr("name");
      var params = {};
      params[name] = "1";

	  var canFly = true;

	if ($(".tone_select.sel").length>0){
		console.log("its here");
		var availible = $(".tone_select.sel").find("input[name=availible]").attr("value");
		if (!parseInt(availible)) canFly = false;
	}else if (!($(this).hasClass("fly"))){
			canFly = false;
	}

	if (canFly){
	//Pouze pokud je na sklade

		$(".mainimg img").clone()
					   .css("position", "absolute")
					   .css("top", $(".mainimg img").offset().top)
					   .css("left", $(".mainimg img").offset().left)
					   .css("z-index", 100)
					   .css("max-width", $(".mainimg img").css("max-width"))
					   .css("max-height", $(".mainimg img").css("max-height"))
					   .removeClass("mainimg")
					   .prependTo("body")
					   .animate({  top: $(".cart").offset().top,
								   left: $(".cart").offset().left,
								   opacity: 0,
								   width:1,
								   height:1
							   }, 2000, function (){
								   $(this).remove();

							   });

	}

    $.post(addToCartUrl, params, function(res){





	  var json = jQuery.parseJSON( res );

	  $("#main").prepend("<div class='messages'><p>" + json.message + "</p></a>");
	  $(".messages").append('<a class="closeerrormsg">×</a>');
	  $(".closeerrormsg").click(function() {

		$(this).parent().stop(true,true).slideUp("slow");
	});
        if (json.type != "error") $("#cart-count").text(parseInt($("#cart-count").text())+1);
      });


      return false;
    });


    //Rozkliknutí změny hesla

        if ($("#change_password").attr("checked")==true){
            $('#current_password').parent().parent().parent().parent().show();

        }
        $("#change_password").click(function(){

           $('#current_password').parent().parent().parent().parent().toggle();

        });


        //Výběr dárků v checkoutu

        $("#checkout-presents li").click(function(){

            $("#checkout-present-id").val($(this).attr("href"));

            $("#checkout-presents li").removeClass("sel");
            $(this).addClass("sel");

        });




        //Vysouvací menu

        var timeout    = 500;
        var closetimer = 0;
        var ddmenuitem = 0;

        function jsddm_open()
        {  jsddm_canceltimer();
           jsddm_close();
           ddmenuitem = $(this).find('ul').css('visibility', 'visible');}

        function jsddm_close()
        {  if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}

        function jsddm_timer()
        {  closetimer = window.setTimeout(jsddm_close, timeout);}

        function jsddm_canceltimer()
        {  if(closetimer)
           {  window.clearTimeout(closetimer);
              closetimer = null;}}

        $(document).ready(function()
        {  $('.nav > li').bind('mouseover', jsddm_open)
           $('.nav > li').bind('mouseout',  jsddm_timer)});

        document.onclick = jsddm_close;







        $('#sorting select').change(function() {

            $('#sorting form.sort').submit();
        });

        $('#sorting div.button').addClass($('#sorting form input[name=dir]').val()).hover(function() {
            $('#sorting span.help').stop(true,true).show('slow');
        }, function() {
            $('#sorting span.help').stop(true,true).hide();
        });

        $('#sorting label:first-child').append('<span class="help">⟵ ' + $('#sorting form.sort div.button input').attr('title') + '</span>');

        $(".catalog-product-view .product .count").productCount("detail"); // product detail
        $(".catalog-product-view fieldset.package input").change(function() { // product detail - onchange packaging type
            var price = parseFloat($(".catalog-product-view fieldset.package input:checked").closest("label").find("em").text().replace(" ","").replace(",","."));
            var nr = $('.catalog-product-view fieldset.count input[name="qty"]').val();
            price = nr*price;
            $("#price").text(addSpaces(price) + ",- Kč");
        });
        $(".checkout-cart-index #main form table .count").each(function() { // cart items

            $(this).productCount("cart");
        });



});

