window.BASE_HREF = window.BASE_HREF || '../';

$.fn.inputDefaultText = function(options)
{
	options = $.extend({
		text: 'Hledany vyraz'
	}, options);

	return this
		.val(options.text)
		.bind('focus', function(){ if(this.value == options.text) this.value = ''; })
		.bind('blur', function(){ if(this.value == '') this.value = options.text; });
};

$.fn.kfCheckToggle = function(target, options)
{
	var $target = $(target), $this = $(this);
	var toggle = function()
	{
		if($this.is(':checked')) $target.show();
		else $target.hide();
	};

	toggle();
	return this.bind('click', toggle);
}

$.fn.kfEqualizeColumns = function(options)
{
	options = $.extend({
		column: '>li'
	}, options);

	return this.each(function(i)
	{
		var $columns = $(options.column, this);
		var maxHeight = 0;
		$columns
			.height('auto')
			.each(function(){
				var h = $(this).height();
				if(h > maxHeight) maxHeight = h;
			})
			.height(maxHeight);
	});
}

function fontSizeListener($el, callback)
{
	$el = $($el);
	var h = 0;
	var interval = setInterval(function()
	{
		if($el.height() != h){
			h = parseInt($el.height());
			callback();
		}
	}, 200);
};

$(document).ready(function()
{
	var translator = new kff.Translator({
		translations: {			
			en: 
			{
				'Hledaný výraz': 'Search'
			},
			de: 
			{
				'Hledaný výraz': 'Suchbegriff'
			}
		},
		langCode: $("html").attr("lang") || 'cs'
	});
	
	$('.jshide').hide();

	if($.fn.kfBox)
	{
		$('.lightbox').not('.shop .lightbox, .product-image-box .lightbox').kfBox();
		$('.shop').each(function(i){
			$(this).find('.lightbox').kfBox();
		});
	}

	$('table tr:nth-child(even)').addClass('even');

	$('#q').inputDefaultText({ text: translator.t('Hledaný výraz')});
	$('#login-email').inputDefaultText({ text: translator.t('E-mail')});

	$('a.ext').click(function(){return !window.open($(this).attr("href"))});

	$('.flash-player').each(function(){
		flashsize = $(this).find('a').attr('data-flashsize');
		flashsize = flashsize.split("x");
		$(this).flash(
    		{
        		 src: '/inc/flash/player.swf',
         		width: flashsize[0],
         		height: flashsize[1],
         		wmode: 'opaque',
         		allowfullscreen: true,
         		flashvars: {file: $(this).find('a').attr('href'), searchbar: 'false', autostart: 'false', frontcolor: '0x666666', image: $(this).find('img').attr('src')}
    		});
	});

	importStructure = function(potvrzeni)
	{
		var conf = "";
		if(potvrzeni != undefined){
			conf = "&potvrzeni";
		}
		$('.product-loader').removeClass('product-loader-out');
		$.ajax({
			url: "/?import&action=structure" + conf,
			success: function(html){ $('.product-loader').addClass('product-loader-out'); importProducts(potvrzeni); }
		});
	}
	importProducts = function(potvrzeni)
	{
		var conf = "";
		if(potvrzeni != undefined){
			conf = "&potvrzeni";
		}
		$.ajax({
			url: "/?import&action=products" + conf,
			beforeSend: function(){$('.product-loader').removeClass('product-loader-out');},
			success: function(html){ $('.product-loader').addClass('product-loader-out'); importAttachments(potvrzeni); }
		});
	}
	importAttachments = function(potvrzeni)
	{
		var conf = "";
		if(potvrzeni != undefined){
			conf = "&potvrzeni";
		}
		$.ajax({
			url: "/?import&action=attachments" + conf,
			beforeSend: function(){$('.product-loader').removeClass('product-loader-out');},
			success: function(html){ $('.product-loader').addClass('product-loader-out'); importRelations(potvrzeni); }
		});
	}
	importRelations = function(potvrzeni)
	{
		var conf = "";
		if(potvrzeni != undefined){
			conf = "&potvrzeni";
		}
		$.ajax({
			url: "/?import&action=relations" + conf,
			beforeSend: function(){$('.product-loader').removeClass('product-loader-out');},
			success: function(html){ $('.product-loader').addClass('product-loader-out'); importQuantity(potvrzeni); }
		});
	}
	importQuantity = function(potvrzeni)
	{
		var conf = "";
		if(potvrzeni != undefined){
			conf = "&potvrzeni";
		}
		$.ajax({
			url: "/?import&action=quantity" + conf,
			beforeSend: function(){$('.product-loader').removeClass('product-loader-out');},
			success: function(html){ $('.product-loader').addClass('product-loader-out'); importParameters(potvrzeni); }
		});
	}
	importParameters = function(potvrzeni)
	{
		var conf = "";
		if(potvrzeni != undefined){
			conf = "&potvrzeni";
		}
		$.ajax({
			url: "/?import&action=parameters" + conf,
			beforeSend: function(){$('.product-loader').removeClass('product-loader-out');},
			success: function(html){ $('.product-loader').addClass('product-loader-out'); importConfirm(potvrzeni); }
		});
	}
	importConfirm = function(potvrzeni)
	{
		var conf = "";
		if(potvrzeni != undefined){
			conf = "&potvrzeni";
		}
		if(confirm('Přejete si potvrdit příjem všech dat?')){
			$.ajax({
				url: "/?import&action=confirm" + conf,
				beforeSend: function(){$('.product-loader').removeClass('product-loader-out');},
				success: function(html)
				{
					$('.product-loader').addClass('product-loader-out');
					alert('Import proběhl');
				}
			});
		} else {
			alert('Import byl zrušen');
		}
	}

	$('.import-data').bind('click', function()
	{
		importStructure();
		return false;
	});
	$('.import-data-confirm').bind('click', function()
	{
		importStructure(true);
		return false;
	});

	/* Inicializace scrollovátka obrázků produktu */
	$('.product-image-box .more-images').append('<div class="prevnext"><a href="#" class="btn-prev">Předchozí</a><a href="#" class="btn-next">Další</a></div>');
	$('.product-image-box .more-images ul').wrap('<div class="hscroll-box"></div>');
    var productImageScroller = new kff.widgets.Scroller('.product-image-box .more-images .hscroll-box', {
		carousel: 'ul',
		items: 'li',
		prev: '.product-image-box .more-images .btn-prev',
		next: '.product-image-box .more-images .btn-next',
		scrollWidth: 2 * (72 + 15),
		carouselWidth: 245,
		speed: 500
	});
	productImageScroller.init();

	/* Inicializace rozklikávání produktových náhledů */
	var productImageController = new ProductImageController();
	productImageController.init();

	/* Inicializace tabů */
	var tabs = new kff.widgets.Tabs('.product-tabs .tabs').init();

	/* Inicializace expand boxů */
	var expandBox = new kff.widgets.ExpandBox({ selector: '.btn-expand' }).init();


	// Ovládátka pro objednávkový proces:
	$('#company-switch').kfCheckToggle('#company-switch-box');
	$('#shipping-switch').kfCheckToggle('#shipping-switch-box');


	// Ovládátka pro dopravu a platbu
	// Matice povolených kombinací dopravy a platby:
	var SPPrices = SPPrices || [
		[0, 1, 1],
		[1, 0, 1],
		[0, 1, 1]
	];
	$('input[id^=order-shipping]').bind('click', function()
	{
		var i = parseInt(this.id.substr(15)) - 1;
		for(var j = 0; j < SPPrices[i].length; j++)
		{
			if(SPPrices[i][j] == 0) $('input#order-payment-' + (j + 1)).attr('disabled', true).attr('checked', false);
			else $('input#order-payment-' + (j + 1)).removeAttr('disabled');
		}
	}).filter(':checked').triggerHandler('click');



	if($('.product-filter').size())
	{
		var formController = new FormController('.product-filter form');
		formController.init();
	}
	
	/* Inicializace ovladače detailu produktu */
	if($('.product-buy-box').size())
	{
		var productDetailController = new ahorn.ProductDetailController();
		productDetailController.init();
	} 

	/* Inicializace SVG mapy */
	var mapCountry = window.mapCountry || 'cs';
	
	var id2Url = window.id2Url || {
		'kraj-zlinsky': null,
		'kraj-ustecky': null,
		'kraj-stredocesky': null,
		'kraj-praha': null,
		'kraj-plzensky': null,
		'kraj-pardubicky': null,
		'kraj-moravskoslezsky': null,
		'kraj-olomoucky': null,
		'kraj-kralovehradecky': null,
		'kraj-karlovarsky': null,
		'kraj-liberecky': null,
		'kraj-vysocina': null ,
		'kraj-jihocesky': null,
		'kraj-jihomoravsky': null,
		
		'sk-kraj-nitriansky': null,
		'sk-kraj-banskobystricky': null,
		'sk-kraj-kosicky': null,
		'sk-kraj-presovsky': null,
		'sk-kraj-zilinsky': null,
		'sk-kraj-trenciansky': null,
		'sk-kraj-trnavsky': null,
		'sk-kraj-bratislavsky': null,
		
		'state-cs': null,
		'state-sk': null		
	};
	
	$('.svg-map-all').each(function(){
		var map = new kff.widgets.Map(this, { mapUrl: BASE_HREF + "js/map-cs.xml?v=5", scale: 2, id2Url: id2Url });
		map.init();
	});
		
	if(mapCountry == 'cs')
	{
		$('.svg-map-small').each(function(){
			var map = new kff.widgets.Map(this, { mapUrl: BASE_HREF + "js/map-cs.xml", scale: 2, id2Url: id2Url });
			map.init();
		});
	
		$('.svg-map-large').each(function(){
			var map = new kff.widgets.Map(this, { mapUrl: BASE_HREF + "js/map-cs.xml", scale: 7.2, id2Url: id2Url });
			map.init();
		});
	}
	else if(mapCountry == 'sk')
	{
		$('.svg-map-small').each(function(){
			var map = new kff.widgets.Map(this, { mapUrl: BASE_HREF + "js/map-sk.xml", scale: 2, id2Url: id2Url });
			map.init();
		});
	
		$('.svg-map-large').each(function(){
			var map = new kff.widgets.Map(this, { mapUrl: BASE_HREF + "js/map-sk.xml", scale: 7.2, id2Url: id2Url });
			map.init();
		});
	}
	
	// Date input init:
	var datePickerLangs = {
		'cs': {
				month_names: ["Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"],
				short_month_names: ["Led", "Úno", "Bře", "Dub", "Kvě", "Čer", "Čvc", "Srp", "Zář", "Říj", "Lis", "Pro"],
				short_day_names: ["Ne", "Po", "Út", "St", "Čt", "Pá", "So"],
				start_of_week: 1
			},
		'en': {
				month_names: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
				short_month_names: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
				short_day_names: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
				start_of_week: 1
			},
		'de': {
				month_names: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
				short_month_names: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
				short_day_names: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
				start_of_week: 1
			}
	};
	
	$.extend(DateInput.DEFAULT_OPTS, datePickerLangs[$("html").attr("lang")]);
	
	$.extend(DateInput.DEFAULT_OPTS, 
	{
		stringToDate: function(string)
		{
			var matches;
			if (matches = string.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4,4})$/)) {
				return new Date(matches[3], matches[2] - 1, matches[1]);
			}
			else {
				return null;
			};
		},
		
		dateToString: function(date) 
		{
			var month = (date.getMonth() + 1).toString();
			var dom = date.getDate().toString();
			return dom + '.' + month + '.' + date.getFullYear();
		}
	});
	
	$('input.date').date_input();
	$('.ico-calendar').bind('click', function(){ $(this).prev().prev('input').trigger('focus'); return false; });	
	
		
});

$(window).bind('load', function()
{
	fontSizeListener('#mid', function(){
		$('.product-list>ul').kfEqualizeColumns({ column: '>li' });
	});
});


kff.Translator = function(options)
{
	this.options = $.extend({
		translations: null,
		langCode: 'cs'
	}, options);
};

kff.Translator.prototype.init = function(){};

kff.Translator.prototype.t = function(term)
{
	if(this.options.translations && this.options.translations[this.options.langCode] && this.options.translations[this.options.langCode][term])
	{
		return this.options.translations[this.options.langCode][term];
	}
	else return term;
};

