// JavaScript Document
// jQuery 1.6
var onCart = false;
var sliderSize = 0;     
var sliderStarted = false;

function sliderCycle()
{
     jQuery('.top-img').cycle({
     fx:      'scrollHorz',
     speed:    2000,
     timeout:  5000,
     after: function(currSlideElement, nextSlideElement, options, forwardFlag)
     {
         var number = jQuery(nextSlideElement).attr('rel');
         jQuery('.top-img-control .number').html(number + '/' + sliderSize);
         if (number==sliderSize)
         {
             jQuery('.top-img-control .right-arrow').hide();
         }
         else
         {
             jQuery('.top-img-control .right-arrow').show();
         }
         if (number==1)
         {
             jQuery('.top-img-control .left-arrow').hide();
         }
         else
         {
             jQuery('.top-img-control .left-arrow').show();
         }
     }
    });
    sliderStarted = true;
}

jQuery(document).ready(function(){
	//add event for top-images
	jQuery(".top-img-control .left-arrow").click(function() {                
		jQuery('.top-img').cycle('prev', 'scrollRight');
	});
	jQuery(".top-img-control .right-arrow").click(function() {
		jQuery('.top-img').cycle('next');
	});
	changeTop("");

    replaceEuro(jQuery('.product-options .price, .cart .price, #checkout-review-submit .price'));

	//add event for slider		
	jQuery(".slider .left-arrow").click(function() {
		var slider = jQuery(this).parent().parent();
		moveSlider(slider, "+", 1);
	});
	jQuery(".slider .right-arrow").click(function() {
		var slider = jQuery(this).parent().parent();
		moveSlider(slider, "-", 1);
	});
	jQuery(".slider").each(function(event) {
		moveSlider(jQuery(this), "", 1);
	});
	
	
	
	//add event for sliderThree			
	jQuery(".sliderThree .left-arrow").click(function() {
		var slider = jQuery(this).parent().parent();
		moveSlider(slider, "+", 2);
	});
	jQuery(".sliderThree .right-arrow").click(function() {
		var slider = jQuery(this).parent().parent();
		moveSlider(slider, "-", 2);
	});
	jQuery(".sliderThree").each(function(event) {
		moveSlider(jQuery(this), "", 2);
	});		
	
	
	//add event for left arrow in cookblog-block
	jQuery(".cookblog-block .left-arrow").click(function() {
		var block = jQuery(this).parent().parent().parent();
		moveProduct(block, "+");
	});
	jQuery(".cookblog-block .right-arrow").click(function() {
		var block = jQuery(this).parent().parent().parent();
		moveProduct(block, "-");
	});
	jQuery(".cookblog-block").each(function(event) {
		moveProduct(jQuery(this));
	});
	
	
	
	//add event for left arrow in about-block
	jQuery(".about-block .left-arrow").click(function() {
		var block = jQuery(this).parent().parent().parent();
		moveProduct(block, "+");
	});
	jQuery(".about-block .right-arrow").click(function() {
		var block = jQuery(this).parent().parent().parent();
		moveProduct(block, "-");
	});
	jQuery(".about-block").each(function(event) {
		moveProduct(jQuery(this));
	});

        jQuery(".block-cart ").hover(function() {
            onCart = true;
        }, function() {
            onCart = false;
            setTimeout('hideCart()', 100);
        });    

        jQuery('.wrapper').click(function() {
            if (!onCart && jQuery('.block-cart .bottom').is(':visible'))
                {
                    hideCart();
                }
        });
	
	jQuery(".block-cart").data({cart:"hide"});
	//add event to cart show/hide
	jQuery(".block-cart .block-title").click(function() {
		if (jQuery(".block-cart").data().cart == "hide") {
			showCart();
		} else {
			hideCart();
		}
               //showCart();
	});

        jQuery(".block-cart .block-title").hover(function() {
            if (jQuery(".block-cart").data().cart == "hide") {
			showCart();
		} 
        });

         jQuery('.single_image').fancybox({type: 'image', 'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic', 'speedIn':1000, 'speedOut':300});
         jQuery('.single_image').click(function(){
             if (jQuery('.video object').length) {
                jQuery('.video').css('display', 'none');
             }
         })
         jQuery('#fancybox-close').click(function(){
             if (jQuery('.video object').length) {
                jQuery('.video').css('display', '');
             }
         });

         if (jQuery('.all_list').size()>0)
         {
             setupReviewsPager(jQuery('.all_list .content .block').size());
             showReviews(1);
         }

          jQuery('.slider .product .overlay').click(function(e) {
              e.preventDefault();
               categoryId = null;
               var categoryId = jQuery(this).parent().find('.product-category').html();
               var click_url = jQuery(this).attr('rel');
               //window.location=click_url;
              var url = click_url.split('?');
              var url_params = url[1].split('&');
              var params = {};
              for (var i = 0; i < url_params.length; i++) {
                  hash = url_params[i].split('=');
                  params[hash[0]] = hash[1];
              }
              params['category'] = categoryId;
              //alert(categoryId);
              postToUrl(url[0], params);
          });


    if (jQuery('.top-img').children().size() > 1) {
        jQuery('.top-img').css('display', 'block');
      //  jQuery('.top-img .block .title').css('margin-left', '0px');
      sliderSize = jQuery('.top-img').children().size();

    setTimeout("sliderCycle()", 1);
     jQuery('.top-img-control, .top-img').mouseover(function() {
        if (sliderStarted)
        {
            jQuery('.top-img').cycle('pause');
        }
    });

    jQuery('.top-img-control, .top-img').mouseout(function() {
        if (sliderStarted)
        {
            jQuery('.top-img').cycle('resume');
        }
    });
    }

    // Shopping Cart
    jQuery('#checkout-discount-coupon-checkbox, #checkout-gift-message-checkbox').change(function(){
        var checkbox = jQuery(this);
        var content = jQuery('.wrapper', jQuery(this).parent());
        if (checkbox.attr('checked')) {
            content.slideDown('fast')
        } else {
            content.slideUp('fast');
        }
    });
    var inputFields = jQuery('#checkout-discount-coupon input:text, #checkout-gift-message textarea')
    if (inputFields.size()) {
        jQuery.each(inputFields, function (i, inputNode) {
            var input = jQuery(inputNode);
            var hint = input.attr('title');
            if (hint) {
                input.blur(function(){
                    if (jQuery(this).val() === '') {
                        input.val(hint).addClass('blur');
                    }
                }).blur();
                input.focus(function(){
                    if (jQuery(this).val() === hint) {
                        jQuery(this).val('').removeClass('blur');
                    }
                });

            }
        });
    }




    // Product reviews
    if (jQuery('.product-about-block .content .block').size() > 3) {
        jQuery('.product-about-block .content .block').each(function(i, node) {
            if (i > 2) {
                jQuery(node).hide();
            }
        });
        jQuery('.product-about-block .all').click(function(e){
            e.preventDefault();
            $(this).hide();
            jQuery('.product-about-block .content .block:hidden').slideDown('fast');
        });
    }



   

});




function showCart() {       
	//if (jQuery(".block-cart").data().cart == "hide") {
      if (!jQuery('.block-cart .bottom').is(':visible')) {

            var bodyelem;
            if (jQuery.browser.safari){
                bodyelem = jQuery("body")
            } else {
                bodyelem = jQuery("html")
            }
            if (jQuery(".block-cart").offset().top < bodyelem.scrollTop()) {
                bodyelem.animate({
                    scrollTop: jQuery(".block-cart").offset().top
                }, 150);
            }
            jQuery('.page').css('position', 'relative');
            jQuery('.page').css('z-index', '0');
            var cartOffset = jQuery(".block-cart").offset();
            var cart = jQuery(".block-cart").detach();
            cart.appendTo('.page');
            cart.css('left', cartOffset.left + 'px');

            var overlay = jQuery('#overlay').detach();
            overlay.appendTo('.page').show();

		jQuery(".block-cart .bottom").show();
		jQuery(".block-cart .block-content").stop(true, true).animate({
			height: "toggle"
		}, 350, "easeInOutQuint", function(){
			jQuery(".block-cart").data({cart:"show"});
		});
	 }
}



function hideCart() {
	//if (jQuery(".block-cart").data().cart == "show") {
        if (onCart == false) {
		jQuery(".block-cart .block-content").stop(true, true).animate({
			height: "toggle"
		}, 200, "easeInOutQuint", function(){
			jQuery(".block-cart .bottom").hide();
			jQuery(".block-cart").data({cart:"hide"});
                        jQuery('#overlay').hide();
		});
	}
}






function changeTop(direct) {
	var block = jQuery(".top-img .block");
	var target = jQuery(".top-img");
	var length = block.length;
	var count = getSetCount(target, direct);

	jQuery(".top-img-control").find(".number").html((count + 1) + "/" + length);

	block.hide();
	jQuery(block.get(count)).show();
	
	var arrow = jQuery(".top-img-control");
	showHideArrow(arrow, count, length);
}


function moveProduct(target, direct) {
	var block = target.find(".block");
	var length = target.find(".block").length;
	var count = getSetCount(target, direct);
	
	target.find(".number").html((count + 1) + "/" + length);

	block.hide();	
	jQuery(block.get(count)).show();

	showHideArrow(target, count, length);
}


function moveSlider(target, direct, qvan) {
	var scroll = target.find(".scroll");
	var length = target.find(".product").length - qvan;
	var width = target.find(".product").width();
	var count = getSetCount(target, direct);;
	
	var mov;	
	if (direct == "+") {
		 mov = "+=" + width;
	}
	if (direct == "-") {
		 mov = "-=" + width;
	}
	showHideArrow(target, count, length);
	
	if (mov != null && count < length + 1) {
		scroll.animate({left: mov}, 350 );	
	}
}







//utill function 
function getSetCount(target, direct) {
	var count = target.attr("count");
	if (count == null) {
		target.attr("count", "0");
		count = 0;
	}
	if (direct == "+") {
		 count --;
	}
	if (direct == "-") {
		 count ++;
	}
	target.attr("count", count);
	return count;
}


function showHideArrow(target, count, length) {
	var left = target.find(".left-arrow");
	var right = target.find(".right-arrow");
	left.hide();
	right.hide();	
	if (length <= 0) {
		return null;
	}
	if (count >= 0 && count < length - 1) {
		right.show();
	}
	if (count > 0) {
		left.show();
	}
}

var rQVAN = 9;
var reviewsPage = 0;
var reviewsFilterObj = [];

//setup arrow and paginations
function setupReviewsPager(qvan) {
	if (qvan <= rQVAN) {
		jQuery(".pager ol").html("<li class='current'>1</li>");
		jQuery(".pager .amount").html(qvan + ' beoordelingen');
		return;
	}

	var list = "";
	var pager = "<li><span class='previous'>prev</span></li>"+
				"<li><span class='next'>next</span></li>";

	for (var i = 0; i<Math.ceil(qvan / rQVAN); i++) {
		list += "<li><span>" + (i + 1) + "</span></li>";
	}
	list += pager;

	jQuery(".pager ol").html(list);
	jQuery(".pager .amount").html(qvan + ' beoordelingen');

	jQuery(".pager li").each(function() {
		jQuery(this).click(function() {
			showReviews(jQuery("span", this).html());
		});
	});
}
function showReviews(str) {
	//switch in paginations
	switch (str) {
		case "next":
			reviewsPage ++;
		break;

		case "prev":
			reviewsPage --;
		break;

		default:
			reviewsPage = Number(str) - 1;

	}

	//if first start add items to productFilterObj
	if (reviewsFilterObj.length == 0) {
		jQuery(".all_list .content .block").each(function(index) {
			reviewsFilterObj.push(jQuery(this));
		});
	}


	var pages = Math.ceil(reviewsFilterObj.length / rQVAN);
	var next = jQuery(".pager .next");
	var prev = jQuery(".pager .previous");

	//disable arrow button
	if (reviewsPage < 0) {
		reviewsPage = 0;
		return;
	}
	if (reviewsPage > pages - 1) {
		reviewsPage = pages;
		return;
	}

	if (jQuery(".pager").offset().top < jQuery("html, body").scrollTop()) {
		jQuery("html, body").animate({
			scrollTop: jQuery(".pager").offset().top
		}, 500);
	}

	//hide all items
	jQuery(".all_list .content .block").hide();
	//show items by current page
	for (var i = 0; i<reviewsFilterObj.length; i++) {
		if (i >= reviewsPage * rQVAN && i < (reviewsPage + 1) * rQVAN) {
			jQuery(reviewsFilterObj[i]).show();
		}
	}	

	//show/hide arrow buttons
	next.each(function() {
		jQuery(this).addClass("disable");
	});
	prev.each(function() {
		jQuery(this).addClass("disable");
	});

	if (reviewsPage < pages - 1) {
		next.removeClass("disable");
	}
	if (reviewsPage > 0) {
		prev.removeClass("disable");
	}

	//select current page
	jQuery(".pages").each(function() {
		jQuery("li", this).each(function(index) {
			jQuery(this).removeClass("current");
			if (index == reviewsPage) {
				jQuery(this).addClass("current");
			}
		});
	});
}

function changeAmount(id, action)
{
    url = '/changecart.php?product_id=' + id + '&action=' + action +'&' + Math.random();
    jQuery('.plus, .minus').css('opacity', 0.2);
    jQuery.getJSON(url, function(response) {
        if (response.deleted>0)
        {
                if (response.error) {
                    jQuery('.onepage-checkout-wrap').hide();
                } else {
                    jQuery('#item-' + response.deleted).fadeOut(1500, function() {
                        jQuery('.onepage-checkout-wrap').show();
                         jQuery('.cart').html(response.cart);
                        jQuery("#cart-sidebar").html(response.items)
                        jQuery(".block-cart .block-title .amount").html(response.items_in_cart);
                        jQuery(".block-cart .subtotal .qvan").html(response.totalprice);
                        jQuery('.block-cart .cart_discount .qvan').html(response.discount);
                        jQuery('.block-cart .cart_shipping .qvan').html(response.shipping);
                        jQuery('#checkout-review-submit .price-box').html('<span class="price checkoutPrice">'+response.finalprice+'<br/><span class="price" style="font-size:15px;display:block;position:absolute;top:63px;line-height:20px;white-space: nowrap;right:0">Totaalbedrag bestelling</span></span>');
                         if (response.items <=0 )
                            {
                                window.location.href='/checkout';
                            }
                            else
                            {
                                jQuery('#to_cart_btn').show();
                            }
                    });
                }
        }
        else
        {
            jQuery('.cart').html(response.cart);
            jQuery("#cart-sidebar").html(response.items)
            jQuery(".block-cart .block-title .amount").html(response.items_in_cart);
            jQuery(".block-cart .subtotal .qvan").html(response.totalprice);
            jQuery('.block-cart .cart_discount .qvan').html(response.discount);
            jQuery('.block-cart .cart_shipping .qvan').html(response.shipping);
            jQuery('#checkout-review-submit .price-box').html('<span class="price checkoutPrice">'+response.finalprice+'<br/><span class="price" style="font-size:15px;display:block;position:absolute;top:63px;line-height:20px;white-space: nowrap;right:0">Totaalbedrag bestelling</span></span>');
            if (response.error) {
                jQuery('.onepage-checkout-wrap').hide();
            } else {
                jQuery('.onepage-checkout-wrap').show();
            }
        }
        if (response.items <=0 )
        {
            jQuery('.onepage-checkout-wrap').hide();
            jQuery('#cart-separate').hide();
            jQuery('#checkout_three').show();
            jQuery('#to_cart_btn').hide();
            jQuery('#checkout-review-submit2').show();
        }
        else
        {
            jQuery('#to_cart_btn').show();
        }
        replaceEuro(jQuery('#checkout-review-submit .price-box .checkoutPrice, .price'));
        updateCartTooltip();
    });

}

function replaceEuro(t){
	t.each(function(){
		var txt = jQuery(this).html();
		txt = txt.split("€").join("<span class='euro'>€</span>");
		jQuery(this).html(txt);
	});
}

function postToUrl(url, params) {

    var form = jQuery("<form method='post'></form>")
    form.attr('action', url);
    for (var key in params) {
        form.append('<input type="hidden" name="'+key+'" value="'+params[key]+'">');
    }
    jQuery('body').append(form);
    form.submit();
}

function updateCartTooltip()
{
    var checkPrice = jQuery('.subtotalPrice .price').html();
    var freeShippingMinimal = parseInt(jQuery('.shipping-tooltip-wrapper .FreeShippingMinimal').html());
    
    checkPrice = checkPrice.replace('<span class="euro">€</span>', '');
    checkPrice = checkPrice.replace('<SPAN class=euro>€</SPAN>', '');
    checkPrice = checkPrice.replace('.', '');
    checkPrice = checkPrice.replace(',', '.');
    checkPrice = checkPrice.replace(' ', '');
    checkPrice = parseFloat(checkPrice);
    
    //alert(checkPrice);
    
    if (checkPrice.toString().toLowerCase() == 'nan')
        {
            checkPrice = 0;
        }
    
    if (checkPrice >= freeShippingMinimal)
    {
        jQuery('.shipping-tooltip-wrapper').css('display', 'none');
    }
    else
    {
        orderElse = freeShippingMinimal-checkPrice;
        orderElse = orderElse.toFixed(2).toString().replace('.', ',');
        jQuery('.shipping-tooltip-wrapper .tooltipPrice').html(orderElse);
        jQuery('.shipping-tooltip-wrapper').css('display', 'inline');
    }
}
