var cleared_fields = [];

function clear_field(field) {
	if(cleared_fields[field.name] == null) {
		cleared_fields[field.name] = field.value;		
		field.value = "";
	}
}

function restore_field(field) {
	if(cleared_fields[field.name] != null && field.value == "") {
		field.value = cleared_fields[field.name];
		cleared_fields[field.name] = null;
	}
}

function takeFromHandler(form, rules) {
	if(form.elements["take_from"].checked == false) return;
	for(destination in rules) {
		source = rules[destination];
		if (typeof(form.elements[destination]) !== 'undefined' && 
			typeof(form.elements[source]) !== 'undefined') {
			form.elements[destination].value = form.elements[source].value;
		}
	}
}

function takeFromCheckboxHandler(element, fields) {
	var new_value;

	if(element.checked) {
		new_value = "hidden";
		$(element).parent('.take-from').removeClass('unchecked');
	} else {
		new_value = "visible";
		$(element).parent('.take-from').addClass('unchecked');
	}		
		
	for(field_index in fields) {
		field = element.form.elements[fields[field_index]];
		if(typeof(field) !== 'undefined') {
			label = document.getElementById("label_" + field.name);
			field.style.visibility = new_value;
			label.style.visibility = new_value;
		}
	}
	
}

function stfSendAnother(){
	$('.panel-send-to-friend .message a').click(function(){
		$('.panel-send-to-friend .message').css('display', 'none');
		return false;
	});
}

function verifySearch(defaultText) {
	var field = $('.panel-search .entry-field');
	if (field.val() == defaultText) {
		field.val("");
	}
}

function treeMenuHiding(el) {
	var lastChild = el.nextSibling;
	
	if (lastChild != null && lastChild.tagName == "UL") {
		$(lastChild).toggle();
		
		return false;
	} else {
		return true;
	}
}

function autoUpdatePrice() {
	var input = $('input[name="add_product_count"]');

	function count() {
		var c = parseInt(input.val());
		if (isNaN(c) || c < 1) {
			input.val('1');
			c = 1;
		}
		return c;
	}
	
	function calculate() {
		var priceInput = $(".price .value");
		var currency = priceInput.text().parseCurrency();

		lastCount = currentCount;
		currentCount = count();

		var price = priceInput.text().parsePrice();
		price = price / lastCount * currentCount;
		priceInput.text(price.formatPrice(currency));
		
		if (currentCount > 1) {
			$('.price-per-item').show();
		} else {
			$('.price-per-item').hide();
		}
	}

//	var lastCount = count();
//	var currentCount = count();
	// pocitame s tim, ze je vzdy predvyplnen 1 ks
	var lastCount = 1;
	var currentCount = 1;

	$('input[name="add_product_count"]').change(function(){
		calculate();
	
	// zabranime odeslani pomoci Enteru
	}).keydown(function(event){
		if (event.keyCode == '13') {
			calculate();
			
			event.preventDefault();
			event.stopPropagation();
		}
	});
}

function variantSelect(id) {
	var select = $('#variant-select-'+id);
	var overlay = $('#variant-options-'+id);
	var input = $('#variant-input-'+id);

	// vymazeme vyplnenou hodnotu, napriklad FF takto doplnuje naposledy odeslane hodnoty
	input.val('');
	$(document).ready(function(){
		$('input[name="add_product_count"]').val('1');
	});

	select.click(function(event){
		// skryjeme vsechny existujici selecty
		$('.variant-options[id!=variant-options-'+id+']').css('display', 'none');

		overlay.css('display', overlay.css('display') == 'block' ? 'none' : 'block');
		overlay.css('top', $(this).offset().top - 232 - 70); // 232 = vyska hlavicky

		event.stopPropagation();
	});

	// po kliknuti kamkoliv mimo vse skryjeme
	$('body').click(function(e){
	    var t = jQuery(e.target);
	    if (!(jQuery.contains(overlay.get(0), t.get(0)) || overlay.get(0) == t.get(0))) {
	    	overlay.css('display', 'none');
	    }
	});

	// zjistime si priplatky ke vsem variantam
	var variantsPrices = {};
	$('#variant-options-'+id+' a').each(function(){
		var vid = $(this).attr('rel');
		var price = $(this).find('.price').text().parsePrice();
		variantsPrices[vid] = price;
	});
	
	// po zvoleni varianty
	$('#variant-options-'+id+' a').click(function(){
		var currency = $(".price .value").text().parseCurrency();
		var countField = $('input[name="add_product_count"]');
		var count = parseInt(countField.val());
		var oldVid = input.val();
		var vid = $(this).attr('rel');
		var name = $(this).find('.label').text();
		var img = $(this).find('img').attr('src');
		var selectName = $('#variant-select-'+id+' .name');
		var selectImg = $('#variant-select-'+id+' img');

		selectName.text(name);
		selectImg.attr('src', img);
		input.val(vid);
		
		// zjistime aktualni cenu produktu
		var productPrice = $(".price .value").text().parsePrice();
		// zjistime cenu vybrane varianty
		var oldVariantPrice = (oldVid == "" ? 0 :variantsPrices[oldVid]) * count;
		// zjistime cenu nove varianty
		var newVariantPrice = variantsPrices[vid] * count;
		
		// dopocteme cenu
		var finalPrice = (productPrice - oldVariantPrice + newVariantPrice);
		$(".price .value").text(finalPrice.formatPrice(currency));
		$(".price-per-item .value").text((finalPrice/count).formatPrice(currency));
		
		// oznacime variantu za vybranou
		select.removeClass('not-selected');

		// pokud jsou jiz vsechny varianty vybrany,
		// zobrazime tlacitko pro pridani do kosiku
		if ($('.variant-select .field.not-selected').length == 0) {
			$('.buy-button-container .warning').addClass('hidden');
			$('.buy-button-container .buy-button').removeClass('hidden');
		}

		overlay.css('display', 'none');

		return false;
	});
	
	$('body').keydown(function(event){
		if (event.keyCode == '27') {
			overlay.css('display', 'none');
		}
	});
	
	overlay.find('.close-button').click(function(){
		overlay.css('display', 'none');
	});
}

function showAllCategories() {
	$('a.show-all-categories').click(function(){
		$('.subcategories').toggleClass('collapsed');
		$(this).css('display', 'none');
		return false;
	});
}


// vlastni fce
String.prototype.parsePrice = function(){
	return parseFloat(this.replace(/[^\d,.-]/g, "").replace(",", "."));
};
String.prototype.parseCurrency = function(){
	return this.replace(/^.+\d/g, "");
};
Number.prototype.formatPrice = function(currency){
	var number = Math.round(this*100)/100;
	var numberParts = (new String(number)).split('.'); // [integer, decimal]
	var integer = numberParts[0];
	var num = new Array();
	while (integer.length > 0) {
		var substrFrom = integer.length - 3;
		if (substrFrom < 0) substrFrom = 0;
		num.push(integer.substr(substrFrom));
		integer = integer.substr(0, substrFrom);
	}
	
	var ret = num.reverse().join(" ");
	
	if (numberParts[1]) ret += ","+numberParts[1];
	return ret+currency;
};


// overeni podporovaneho prohlizece
(function() {
	if (jQuery.jCookie('skipUnsupported') == "true") return false;

	var b = jQuery.browser;
	var allowed = 
		b.mozilla || b.chrome || b.opera || b.safari ||
		(b.msie && parseInt(b.version) >= 7);

	if (!allowed) {
		$(document).ready(function(){
			var open = function(){
				Shadowbox.open({
					content:
						'<div class="unsupported-browser">'+
							'<p>Váš prohlížeč bohužel nepatří mezi podporované prohlížeče. Je možné že nebudete moci přidat zboží do košíku, některé sekce se nemusí zobrazovat správně a mohou se vyskytnou další komplikace. Abyste mohli náš obchod využívat bez starostí, <strong>doporučujeme používat jeden z následujících internetových prohlížečů</strong>:</p>'+
							'<ul>'+
							'<li><a href="http://www.mozilla-europe.org/cs/firefox/" title="Mozilla Firefox">Mozilla Firefox</a></li>'+
							'<li><a href="http://www.opera.com/" title="Opera">Opera</a></li>'+
							'<li><a href="http://www.microsoft.com/cze/windows/internet-explorer/" title="Microsoft Internet Explorer">Microsoft Internet Explorer verze 7 a vyšší</a></li>'+
							'<li><a href="http://www.google.cz/chrome" title="Google Chrome">Google Chrome</a></li>'+ 
							'<li><a href="http://www.apple.com/safari/" title="Apple Safari">Apple Safari</a></li>'+
							'</ul>'+
							'<p>Děkujeme za pochopení.</p>'+
							'<p>&nbsp;</p>'+
							'<p>Pokud si náš obchod přesto chcete prohlédnout, <a href="#" onclick="Shadowbox.close();jQuery.jCookie(\'skipUnsupported\',\'true\');return false;">pokračujte zde</a>.</p>'+
						'</div>',
					player:     "html",
					title:      "Váš prohlížeč není podporován",
					height:     350,
					width:      500
				});
			};
			
			// pockame az se nacte shadowbox
			setTimeout(open, 100);
		});
	}
})();



/**
 * FIX IE7 bugu s obrazky v odkazech
 * 
 * problem je hezky videt zde:
 *   http://www.daniel-rico.com/demos/ie/
 *
 * nastin moznych reseni:
 *   http://stackoverflow.com/questions/805865/html-css-link-problem-on-ie6-and-ie7
 *   http://robertnyman.com/2008/01/22/cant-make-links-appear-clickable-in-ie/#comment-240054
 *
 * bohuzel ani jedno z css reseni v nasem pripade nefunguje, proto pouzijeme JS
 */
if (jQuery.browser.msie && parseInt(jQuery.browser.version) <= 7) {
	$(document).ready(function(){
		if ($('#main').hasClass('page-category')) {
			$('.subcategories .category .image img').click(function(){
				location.href = $(this).parent().parent().attr('href');
			});
		}
	});
}
