// scrollTo plugin {* http://flesler.blogspot.com/2007/10/jqueryscrollto.html *}
(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

$(function() {
	// GLOBAL - TOOLTIP setting
	$('.tooltip').tooltip({ 
		delay: 0, 
		showURL: false,
		opacity:0.95,
		showBody: " - ",
		track: true
	});
	
	// Special wishes form submit
	$("#special_contact_form a.special_contact_send").click(function(event){
		event.preventDefault();
		$("#special_contact_form form").submit();
	});

	$('a[rel=newwindow]').attr('target','_blank');

	// CATALOG - items on itemsOnPage switch
	$('select[name=itemsOnPage]').change(function(event){
		$(this).parents('form').submit();
	});
	
	// CATALOG - items handling
	$(".skladove_variace .images a").click(function(event){
		event.preventDefault();
		$(this).toggle_sizes();
	});
  
	// display sizes for main variation item
	$('.mainvar').each(function() {
		$(this).toggle_sizes();
	});


	$('div.variace').scrollTo( 0 ); // resets all scrolls
  
  
// CATALOG ITEMBOX - scroll handling
if ($('.products').length != 0) {
  var scrollBoxesCatalog = $(".products .skladove_variace div.variace")
	  scrollBoxesCatalog.data('position',0);	// ads position data to remember the position of scrolled elements
	  scrollBoxesCatalog.each(function() {
		  $(this).scroll_arrows(4);
	  });
  
  var scrollBoxesCatalog = $(".products .sizescontainer div.sizes")
	  scrollBoxesCatalog.data('position',0);
	  scrollBoxesCatalog.each(function() {
		  $(this).scroll_arrows(8);
	  });

  $(".products .skladove_variace .go").click(function(event){
		event.preventDefault();
		var scrollbox = $(this).parents('.skladove_variace').find('div.variace');
		$(this).scroll_variants(scrollbox,4,'go');
  });
  $(".products .skladove_variace .back").click(function(event){
		event.preventDefault();
		var scrollbox = $(this).parents('.skladove_variace').find('div.variace');
		$(this).scroll_variants(scrollbox,4);
  });
  $(".products .sizescontainer .down").click(function(event){
		event.preventDefault();
		var scrollbox = $(this).parents('.sizescontainer').find('.sizes');
		$(this).scroll_variants(scrollbox,8,'go');
  });
  $(".products .sizescontainer .up").click(function(event){
		event.preventDefault();
		var scrollbox = $(this).parents('.sizescontainer').find('.sizes');
		$(this).scroll_variants(scrollbox,8);
  });
}

  	// CATALOG - just in stock check box event handling 
	$("#just-stocked").click(function(event){
		  $(".just-stocked").submit();
	});


	// DETAIL - size table hide and event handling
	$(".detail #sizetable").hide();
	$(".detail a.sizetable").click(function(event){
		event.preventDefault();
		$(".detail #sizetable").animate({'opacity': 'toggle'}, 300);
	});

// CONFIGURATOR
if ($('#configurator').length != 0) {
	// configurator first page switcher
	$("a.jun_sen").click(function(event){
		event.preventDefault();
		$('#hidden_other_price').attr('value',$(this).attr('name').replace(/idop/,""));
		$('a.jun_sen').removeClass('aktiv');
		$(this).addClass('aktiv');
		// set correct price
		var cfg_price = $('#cfg_price');
		cfg_price.text(cfg_price.text().replace(/.*/,$(this).attr('rel')));
	});

	// hover fix for IE6 - it did not loose hover by only css
	$('a.jun_sen').hover(function(){
	    $(this).addClass('active');
	    }, function() {
	    $(this).removeClass('active');
	});
	
	// input box ks handling
	if ($("input.cfgks").attr('value') == '?') $("input.cfgks").css("color","#999");
	$("input.cfgks").click(function(event){
		if ($(this).attr('value') == '?') {
			$(this).attr('value','');
			$(this).css('color','#000');
		}
	});
	$("form[name='cfgfirst']").submit(function(event){
		return $().configurator_ks();
	});

	// scroll sizes
	var scrollBoxesConfigurator = $("#configurator #sizes_values .sizes")
	scrollBoxesConfigurator.data('position',0);	// ads position data to remember the position of scrolled elements
	scrollBoxesConfigurator.each(function() {
	  $(this).scroll_arrows(6);
	});

	$("#configurator #sizes_values .go").click(function(event){
		event.preventDefault();
		var scrollbox = $(this).parents('#sizes_values').find('.sizes');
		$(this).scroll_variants(scrollbox,6,'go');
	});
	$("#configurator #sizes_values .back").click(function(event){
		event.preventDefault();
		var scrollbox = $(this).parents('#sizes_values').find('.sizes');
		$(this).scroll_variants(scrollbox,6);
	});	
	
	// scroll colors
	var scrollBoxesConfigurator = $("#configurator .skladove_variace div.variace")
	scrollBoxesConfigurator.data('position',0);	// ads position data to remember the position of scrolled elements
	scrollBoxesConfigurator.each(function() {
	  $(this).scroll_arrows(7);
	});

	$("#configurator .skladove_variace .go").click(function(event){
		event.preventDefault();
		var scrollbox = $(this).parents('.skladove_variace').find('div.variace');
		$(this).scroll_variants(scrollbox,7,'go');
	});
	$("#configurator .skladove_variace .back").click(function(event){
		event.preventDefault();
		var scrollbox = $(this).parents('.skladove_variace').find('div.variace');
		$(this).scroll_variants(scrollbox,7);
	});	
	if ($('#configurator .skladove_variace .images').length != 0) {
		$("#configurator .skladove_variace .images a").click(function(event){
			event.preventDefault();
		    $(this).choose_color();
		});
		$("#configurator .skladove_variace .images a.mainvar").choose_color();
	}
	$("#configurator #sizetable").hide();
	$("#configurator a.sizetable").click(function(event){
		event.preventDefault();
		$("#technologie").hide();
		$("#sizetable").animate({'opacity': 'toggle'}, 300);
	});
		
	$("#configurator #technologie").hide();
	$("#configurator a.technologie").click(function(event){
		event.preventDefault();
		$("#sizetable").hide();
		$("#technologie").animate({'opacity': 'toggle'}, 300);
	});	  	  

	$('#configurator #sizes_values input').keyup(function(event){
		$().configurator_leftToChoose(false);
	});
		
	$("#configurator #nastaveni form.cfgcheckcounts").submit(function() {
		var countLeft = $().configurator_leftToChoose(true);
	    if (countLeft == 0) {
	      	return true;
	    }
	    alert('Počet velikostí zbývajících k výběru musí být nula.');
		return false;
	});
}
	
	// USER REG/PROFILE FORM
	if ($("form[id='regform']").length != 0)
	{
		$("a.pokracovat").click(function(event){
			event.preventDefault();
			// form verification
			if (verifyProfile() == false)	$("#regform").submit();
		});
			
		$.fn.toggle_visibility = function(visibleState) {
			$(this).css("visibility",(visibleState ? "visible" : "hidden"));
		};	
		$("input[name='next_delivery_address']").click(function(event){
			var visibleState = $(this).attr('checked');
			$('#shop_next_delivery_address').toggle_visibility(visibleState);       				
		});
		$("input[name='company_record']").click(function(event){
			var visibleState = $(this).attr('checked');
			$('#shop_company_record').toggle_visibility(visibleState);      				
		});
		if ($("input[name='next_delivery_address']:checked").length != 0)
		{
		  	$('#shop_next_delivery_address').toggle_visibility(true);
		}
		if ($("input[name='company_record']:checked").length != 0)
		{
		 	$('#shop_company_record').toggle_visibility(true);
		}
		if ($("form[class='verify']").length != 0)
		{
			verifyProfile();
		}
	}
	

	//DETAIL - GALLERY handling - must be activated only if gallery exists ...
	if ($('#gallery').length >0)
	{
		$('ul.gallery').galleria({history:false, clickNext:false});
		$('.detail #shop_image_reload_href').change_image();
		$(".detail .colors a").click(function(event){
			//var link = $(this).attr('href');
			$('#shop_image_reload_href').change_image();
		});
		// activate current image in gallery after clicking on main detail image
		$('.detail #shop_image_reload_href').click(function(event){
		  var link = $(this).data('link');
		  //var imagelink = $(this).next('img').attr('href');
			var actualImage = $("ul.gallery li img[rel='"+link+"']");
			if (actualImage.size()==0)
			{
				//add image to gallery
			};
			$.galleria.activate(link);
		});
	}
	
	//BASKET - transport/payment
	$("form[name='payment_transport'] input[name='transport']").each(function() {
		$(this).click(function(event){
				$(this).correct_payment();
		});
	});
	$("form[name='payment_transport'] input[name='transport']:checked").correct_payment();
	// payment info switching
	$("form[name='payment_transport'] input[name='payment']").each(function() {
		$(this).click(function(event){
				$(this).payment_info();
		});
	});
	$("form[name='payment_transport'] input[name='payment']:checked").payment_info();
	
	
	$("form[name='payment_transport'] a.pokracovat").click(function(event){
		event.preventDefault();
		if ($("input[name='transport']:checked").length == 0) {
			alert("Není vybrána doprava zboží.");
			return false;
		}
		if ($("input[name='payment']:checked").length == 0) {
			alert("Není vybrán způsob platby.");
			return false;
		}
		$("form[name='payment_transport']").submit();
	});
	
	if ($("#shop_basket_now").length != 0)
	{
		$().basket_use_credits();
		$("#shop_basket_use_next").click(function(event){
			$().basket_use_credits();
		});
		$("#shop_basket_now").click(function(event){
			$().basket_use_credits();
		});	
	}
	// BASKET - submit
	$("#basketnext").click(function(event){
		event.preventDefault();
		$("#basketform").submit();
	});
	
	// PAYMUZO - submit
	$("#paymuzo_link").click(function(event){
		event.preventDefault();
		$("#paymuzo_form").submit();
	});
	
// end on document ready actions
}); 



//USER REG/PROFILE FORM
function verifyProfile()
{
	var error = false;
	error = !$("#regform input[name='hname']").check_form('Zadejte jméno a přijmení','^.+[ ].+$') || error;
	error = !$("#regform input[name='login']").check_form('Zadejte e-mail','^.+@.+\..{2,4}$') || error;
	error = !$("#regform input[name='phone']").check_form('Zadejte telefon') || error; // '^\+?[0-9 ]+$'
	error = !$("#regform input[name='street']").check_form('Zadejte ulici','^.+[ ].+$') || error;
	error = !$("#regform input[name='city']").check_form('Zadejte město') || error;
	error = !$("#regform input[name='psc']").check_form('Zadejte PSČ') || error;
	if ($("form[class='register']").length != 0)
	{
		error = !$("#regform input[name='pass_aa']").check_form('Zadejte heslo') || error;
		error = !$("#regform input[name='pass_check']").check_form('Zopakujte heslo') || error;
	}
	// company records
	if ($("#regform input[name='company_record']").attr('checked')){
		error = !$("#regform input[name='company']").check_form('Zadejte název firmy') || error;
		error = !$("#regform input[name='ic']").check_form('Zadejte IČ') || error;
		error = !$("#regform input[name='dic']").check_form('Zadejte DIČ') || error;
	}
	// delivery adress
	if ($("#regform input[name='next_delivery_address']").attr('checked')){
		error = !$("#regform input[name='delivery_street']").check_form('Zadejte ulici','^.+[ ].+$') || error;
		error = !$("#regform input[name='delivery_city']").check_form('Zadejte město') || error;
		error = !$("#regform input[name='delivery_psc']").check_form('Zadejte PSČ') || error;
	}
	return error;
}

	$.fn.check_form = function(errmsg,rule) {
		if (typeof rule != "undefined") var regrule = new RegExp(rule);
		$(this).prev('span').remove();
		if (($(this).attr('value') == '')||((typeof rule != "undefined")&&(!regrule.test($(this).attr('value')))))
		{
			$(this).addClass('errorinput');
			$(this).before('<span class="error">'+errmsg+'<\/span>');
			return false;
		} else {
			$(this).removeClass('errorinput');
		};
		return true;
	};


	// BASKET - display credits usage according to switch
	$.fn.basket_use_credits = function() {
		var use = $("#shop_basket_now").attr('checked');
		var useNow = $('label[for=shop_basket_now] span:hidden').text();
		var totalPrice = parseInt($('#basket_nodiscount_total_price').text());
		useNow = Math.min(totalPrice,useNow);
		var price = totalPrice - (use==0 ? 0 : useNow);
		$('#shop_basket_total_price').text($('#shop_basket_total_price').text().replace(/[0-9.]+/,price));
		if (use == 0) 
			$('#shop_summ_credits').hide();
		else {
			$('#shop_summ_credits').show();
			$('#shop_summ_credits_detail').text($('#shop_summ_credits_detail').text().replace(/[0-9.]+/,useNow));
		}
	}


// BASKET - display correct payment method
$.fn.correct_payment = function() {
	if ($(this).attr('name') == 'transport')
	{
		$('#deliveryinfo > h4').text($(this).next('label').text());
		$('#deliveryinfo > p').text($(this).next('label').attr('title'));
		var classes = $(this).attr('class').split(' ');
		if (classes[1])
		{
		  var payments = classes[1].split('_');
		  $("input[name='payment']").hide().next('label').hide();
		  for ( var i in payments )
		  {
		    payment_block = $("input[name='payment'][value='"+payments[i]+"']");
		    payment_block.show().next('label').show();
		  }
		  //recalculate delivery cost
		  $("input[name='payment']").each(function() {
			//$(this).recalculate_cod();
			var $costs = $("input[name='transport']:checked + label").attr('class').split(' ');
			var $price = '(+'+$costs[1]+' '+$('#currency').attr('value')+')';
			var $label = $(this).next('label');
			if ($label.attr('class')=='1')
			{
				if ($label.text().match(/\(+.*\)+/))
				{
					// remove parenthesis if there are ones
					$label.text($label.text().replace(/\(+.*\)+/,''));
				}
				$label.text($label.text() + $price);
			}
			if ($(this).is(':hidden')) $(this).removeAttr('checked');
		  });
		}
	}
};


$.fn.payment_info = function() {
	if ($(this).attr('name') == 'payment')
	{
		$('#paymentinfo > h4').text($(this).next('label').text());
		$('#paymentinfo > p').text($(this).next('label').attr('title'));
	}
};


//DETAIL - GALLERY - fn to make variation image open gallery
$.fn.change_image = function() {
	//var imagelink = image.next('img').attr('href');
	this.data('link',this.attr('href'));
	this.addClass('displaygallery').attr('href','#TB_inline?width=800&amp;height=620&amp;inlineId=gallery');
};



// CONFIGURATOR - FUNCTION TO CHOOSE COLOR VARIATION
$.fn.choose_color = function() {
	var page = $('#page_mem').attr('value');
	if (this.length == 0)
	{
		var image = $('#shop_image_reload_href').attr('href');
		$('#shop_image_reload_href').attr('href',image.replace(/ObrazekMaly/,"ObrazekOriginal")); // set link
		$('#product_page'+page+' img:first').attr('src',image); // set image
	} else {
		var image = this.attr('href');
		$('#shop_image_reload_href > img').attr('src',image); // set image
		$('#shop_image_reload_href').attr('href',image.replace(/ObrazekMaly/,"ObrazekOriginal")); // set link
		$('#product_page'+page+' img:first').attr('src',image); // set image
		var shopvar = this.attr('class');
		shopvar = shopvar.replace(/.*shop_var_/,"shop_var_");
		var color_var = shopvar.replace(/shop_var_/,"");
		$('#color_var_id').attr('value',color_var); // set hidden input color variation
		$('#sizes_values ul li').not('[class*='+shopvar+']').hide().find('a').hide();
		$('#sizes_values ul li[class*='+shopvar+']').show().find('a').show();
	}
	var scrollbox = $("#configurator #sizes_values .sizes");
	scrollbox.data('position',0);
	scrollbox.scroll_arrows(6);
	scrollbox.scrollTo(scrollbox.find('a:eq(0)'));
	$().configurator_leftToChoose(false);
};

$.fn.configurator_ks = function() {
	var input_ks = $("input.cfgks");
	if (input_ks.length != 0)
	{
		ks = input_ks.attr('value');
		if (!isFinite(ks) || (ks <=0))
		{
			alert("Počet kusů musí být kladné číslo.");
			return false;
		} else {
			if (!(($("#senior").attr('class') == 'jun_sen aktiv')||($("#junior").attr('class') == 'jun_sen aktiv')))
			{
				alert('Musí být zvolena varianta "Senior" nebo "Junior"!');
				return false;
			} else {
				return true;
			}
		}
	}

};

// CONFIGURATOR - FUNCTION TO RECALCULATE LEFT COUNT
$.fn.configurator_leftToChoose = function($submit) {
	var inputCount = $('#ks').attr('value');
	var selectedCount = 0;
	$('#sizes_values input').each(function(event){
		var countAct = $(this).attr('value');
		if (countAct != '')
		{
			if (!isFinite(countAct))
			{
				$(this).attr('value','');
			} else {
 				if ($(this).is(':visible')) selectedCount += parseInt(countAct);  // count only visible sizes
			}
		}
		if ($submit && $(this).is(':hidden')) $(this).attr('value','');  // reset hidden sizes on submit
	});
	$('#leftToChoose').text(inputCount-selectedCount);
	return inputCount-selectedCount;
};

	// FUNCTION TO SHOW/HIDE ARROWS FOR SCROLLBOX
	$.fn.scroll_arrows = function(maxitems) {
		var count = this.find('a').not(':hidden').size();
		var position = this.data('position');
		if (maxitems < (count-position))
		{
			this.parent().find('a.next').show();
		} else {
			this.parent().find('a.next').hide();
		}
		if (position > 0)
		{
			this.parent().find('a.prev').show();
		} else {
			this.parent().find('a.prev').hide();
		}	
	};	

	// FUNCTION TO SCROLL
	$.fn.scroll_variants = function(scrollbox,maxitems,direction) {
	//	var posmax = scrollbox.find('a').size()-3;
		var count = scrollbox.find('a').not(':hidden').size();
		var position = scrollbox.data('position');
		if (direction == 'go')
		{
			if (maxitems < (count-position)) position++;
		} else {
			if (position > 0) position--;
		}
		scrollbox.data('position',position);
		scrollbox.scrollTo(scrollbox.find('a:eq('+position+')'));
		scrollbox.scroll_arrows(maxitems);
	};	


	// FUNCTION TO SHOW/HIDE SIZES
	$.fn.toggle_sizes = function() {
			var image = this.find('img').attr('src');
    	    var sizes = $(this).parents('li').find('.sizes');
    	    var instock =  $(this).parents('li').find('.instock');
    	    // toggle sizes in stock
    	    if (sizes.size() > 0) {
	    	    var shopvar = this.attr('class');
	    	  //  shopvar = shopvar.replace(/ .*/,"shop_var_"); // take first class only
	    	    shopvar = shopvar.replace(/.*shop_var_/,"shop_var_");
	    	    var v0var = '_v0-'+shopvar.replace(/shop_var_/,"");
	    	    sizes.find("a."+shopvar).animate({'opacity': 'show'}, 0).attr('href', function (arr) {
			        return this.href.replace(/_v0-[0-9]*/, v0var);
			      });
	    	    sizes.find("a").not("."+shopvar).animate({'opacity': 'hide'}, 0);
    	    }
    	    // display icon "skladem" only for color variants which are in stock or if there is only one color variant
    	    var countsizes = $(this).parents('li').find('.sizes a').not(':hidden').size();
    	    var color_instock = $(this).hasClass('isinstock');
    	    if (countsizes > 0 || color_instock == 1) {
    	    	//sizes.parent().find('img').show();
    	    	instock.show();
					} else {
    	    	//sizes.parent().find('img').hide();
				instock.hide();
    	    }
    	    // change main image and link
    	    var varlink = $(this).parents('li').find('a.productlink');
    	    varlink.attr('href',this.attr('href'));
    	    varlink.find('img').attr('src',image);
	};