var tabs = ['hardware', 'software', 'prislusenstvi', 'zaruky'];
var ceny = {};
var price_formats = {'elektroodpad' : '%P %S', 'dph' : '%P %S'};
var original_action = '';

function init()
{ //Inicializuje taby
	var tabs2 = tabs.concat('drivery', 'komentare');
	for (var i = 0; i < tabs2.length; i ++)
	{ //Projdi vsechny zalozky, co existuji
		var tab = tabs2[i];
		if($('#tab_'+tab).length)
		{ //Pokud tam je tab, tak pri kliknuti zmen aktivni tab
			$('#button_'+tab).click(function()
			{
				for (var i = 0; i < tabs2.length; i ++)
				{
					$('#button_'+tabs2[i]).removeClass('active');
					$('#tab_'+tabs2[i]).css('display','none');
				}
				$(this).addClass('active').removeClass('unread');
				$('#tab_'+$(this).attr('id').toString().substr(7)).css('display','block');
				zvolena_konfigurace();
				return false;
			});
		}
		else { $('#button_'+tab).click(function () { return false; }); }
	}
	$('.selection_card select').bind('change', zvolena_konfigurace).bind('click', zvolena_konfigurace);
	$('.selection_card :checkbox').bind('change', zvolena_konfigurace).bind('click', zvolena_konfigurace);
	$('#count').bind('change', zmena_poctu);
	$('[name=grade]').bind('change', zvolena_konfigurace).bind('click', zvolena_konfigurace);
	$('#produkt_form').bind('submit', submit_check);
	original_action = $('#produkt_form').attr('action');
	$('[name=comment]').bind('click', function () { $('#produkt_form').attr('action', location.href); });
	zvolena_konfigurace();
	
	var resize = function (index, element, timeout) {
			if (!$('#gallery_0_'+index).length) return;
			var animated = false;
			if ($('#gallery_0_'+index).is(':animated'))
			{ //Pokud byl animovan
				animated = $('#gallery_0_'+index).css('opacity');
				$('#gallery_0_'+index).stop(false, true);
			}
			var h = $('#gallery_0_'+index).height();
			var w = $('#gallery_0_'+index).width();
			var ratio = h/w;
			if (h > 500)
			{
				h = 500;
				w = 500 / ratio;
			}
			var left = (500 - w) / 2;
			var top = ((500 - h - 112) > 0 ? (500 - h - 112) : 0) / 2;
			$('#gallery_0_'+index).width(w).height(h)
				.css('margin-left', left+'px')
				.css('margin-top', top+'px');
			if (animated) $('#gallery_0_'+index).css('opacity', animated).animate({opacity: 1.0}, 
				{queue: false,
            	duration: 200,
            	easing: 'linear'});
		};
	$('#photos').gallery({
					interval: 1000,
					slideshow: false,
					toggleBar: false,
					onChange: function (index,element) {/*alert('change');*/ resize(index, element)},
					height: 500,
					width: 500,
					ratio: 0.2
				});
	$('.preview img').each(function (index) 
		{
			$(this).click(function ()
			{
				tb_show(null, '#TB_inline?height=500&width=500&inlineId=photos', false);
				$('.galleryBar a').eq(index + 1).click();
			});
		});
	$('.images img:first').click(function ()
		{
			tb_show(null, '#TB_inline?height=500&width=500&inlineId=photos', false);
			$('.galleryBar a').eq(0).click();
		});
}
function not_thru ()
{
	if ($('.unread').length)
	{ //Pokud jsou nejake neprectene taby
		var unread = '';
		$('.unread').each(function () { unread += (unread.length > 0 ? ', ' : '') + $.trim($(this).text());});
		$('#configuration .center').append('<div style="background:transparent"><h3>Zbývá konfigurovat</h3><div>'+unread+'</div></div>');
		$('#submit_button').removeClass('submit').addClass('not_submit');
	}
	else
	{
		$('#submit_button').removeClass('not_submit').addClass('submit');
	}
}
function submit_check ()
{ //Kontrola pred odeslanim
	if($('#produkt_form').attr('action') == location.href)
	{ //Pokud to jsou komentare
		if (!$('#comment_nadpis').val() || !$('#comment_text').val())
		{ //Prazdne
			alert("Všechny položky je potřeba vyplnit.");
			return false;
		}
		if ($('#comment_nadpis').val().strlen > 255)
		{ //Pokud je moc dlouhy
			alert("Nadpis komentáře je příliš dlouhý.");
			return false;
		}
		return true;
	}
	$('#produkt_form').attr('action', original_action); //Nastav spravnou cestu
	if ($('.unread').length)
	{ //Pokud jsou nejake neprectene taby, tak otevri neprecteny a neodesli
		$('.unread:eq(0)').trigger('click');
		return false;
	}
	return true;
}

function zmena_poctu ()
{ //Kontroluje pocet kusu
	var value = $(this).val();
	if (!/^\d*$/.test(value.toString()) || parseInt(value) <= 0)
	{ //Pokud je spatne, tak ho nastav na jedna
		$(this).val(1);
	}
	zvolena_konfigurace(); //A prepocitej to cele
}

function price_format(price, id)
{ //Naformatuje cenu a ulozi ji do ID
	var new_price = Math.round(price * Math.pow(10, precision)) / Math.pow(10, precision);  //Count new price
	var to_add = (new_price.toString().indexOf('.') > -1 ? precision - new_price.toString().length + new_price.toString().indexOf('.') + 1 : precision); //How many zeros suppose to be added?
	new_price = new_price.toString()+((precision == to_add && precision > 0) ? '.' : '')+(function (count) { var r = ''; for (var i = 0; i < count; i ++) { r += '0'; } return r;})(to_add); //Return the new price
	var format = '%P%C';
	if (price_formats[id])
	{ //Pokud mas specialni formatovani
		format = price_formats[id];
	}
	text = format.replace(/%P/g, new_price).replace(/%C/g, kod_meny).replace(/%S/g, kod_meny_single);
	$('#'+id).html(text);
}

function recount(polozky)
{ //Prepocita cenu produktu
	var grade = grades[parseInt($('[name=grade]:checked').val())];
	var cena = parseFloat(grade[1]);
	var zaruka = grade[2];
	var elektroodpad = parseFloat(el);
	var pocet = parseInt($('#count').val());
	for (var i = 0; i < polozky.length; i ++)
	{ //Projdi vsechny polozky a pricti jejich cenu
		cena += parseFloat(polozky[i][0]);
		elektroodpad += parseFloat(polozky[i][1]);
	}
	var cena_sleva = cena * (100 - parseFloat(sleva)) / 100;
	var cena_dph = (cena_sleva + elektroodpad) * (dph / 100);
	var cena_celkem = cena_sleva + cena_dph + elektroodpad;
	//Nastav hodnoty
	if (parseFloat(sleva)) price_format(cena_sleva * pocet, 'sleva_procent');
	price_format(cena * pocet, 'cena_bez_dph');
	price_format(elektroodpad * pocet, 'elektroodpad');
	price_format(cena_dph * pocet, 'dph');
	price_format(cena_celkem * pocet, 'price');
	
	$('#zaruka').html(zaruka);
	$('.product_list_quantity').hide().filter('#'+grade[4]).css('display','inline'); //Mnozstvi na sklade
}

function zvolena_konfigurace()
{ //Zmeni text pri zvoleni jine konfigurace a nastavi cenu
	var zaklad = [];
	$('#configuration .center h3~div').remove();
	for (var i = 0; i < tabs.length; i ++)
	{ //Projdi vsechny zalozky, co existuji
		var text = '';
		$('#tab_'+tabs[i]+' select').add('#tab_'+tabs[i]+' :checkbox:checked').each(function ()
			{
				if (text) text += ', ';
				if (this.tagName.toString().toLowerCase() == 'select')
				{ //Je-li to select
					var nadpis = $.trim($(this).siblings('label').html().toString()); //Nazev
					var popisek = $.trim($('option:selected',this).text().toString()); //Popisek
					popisek = popisek.substr(0, popisek.indexOf('|') - 1);
					text += nadpis + ' ' + popisek;
					zaklad.push(ceny[$(this).attr('name')][$('option:selected',this).val()]);
				}
				if (this.tagName.toString().toLowerCase() == 'input')
				{ //Je-li to zaskrtnuty checkbox
					text += $.trim($(this).siblings('strong').html().toString());
					zaklad.push(ceny[$(this).attr('name')]);
				}
			});
		if (text) $('#configuration .center').append('<div>'+text+'</div>'); //Pridej text pokud je
		$('#configuration .center').append('<div class="space"></div>'); //Pridej oddelovac
	}
	recount(zaklad); //Prepocitej cenu
	not_thru();
}

$(document).ready(init);

