$(document).ready(function() {
	
	var ie6 = $.browser.msie && $.browser.version=='6.0';
	
	// Section headers
	var cufonSelector = '.news h3, #panel h1, .maincontent h2:not(.car h2)';
	$(cufonSelector).find('a').css('transition', 'none').css('-webkit-transition', 'none');
	Cufon.replace(cufonSelector, { fontFamily: 'primary', hover: true });
	
	// Sliding on HP
	if($.fn.serialScroll) {
		
		$slidingWrap = $('ul.slide');
		$slidingWrap.wrap('<div class="sliding-out"><div class="sliding"></div></div>');
		$slidingWrapTop = $slidingWrap.parent();
		$slidingItems = $slidingWrap.find('li');
		
		if($slidingItems.length > 2) {
			$slidingWrapTop
				.before('<a href="#" class="arrow" id="prev"><img src="/images/prev.png" width="16" height="24" alt="Předchozí"></a>')
				.after('<a href="#" class="arrow" id="next"><img src="/images/next.png" width="16" height="24" alt="Následující"></a>');
				
			$slidingWrap.css('width', $slidingItems.length * $slidingItems.outerWidth());
			$slidingWrapTop.serialScroll({
				items:		'li',
				prev:		'#prev',
				next:		'#next',
				axis:		'x',
				duration:	250,
				start:		0,
				force:		true,
				lazy:		true,
				step:		1,
				jump:		false,
				interval:	false,
				exclude:	1
			});
			
		}
		
	}
	
	function dateRange(start, end) {
		var range = end - start;
		return days = Math.ceil(range/(24*60*60*1000));		
	}
	
	if($.fn.datepicker) {
		
		/*$('#termin').DatePicker({
			format:'d. m. Y',
			date: $('#termin').val(),
			current: $('#termin').val(),
			starts: 1,
			calendars: 2,
			mode: 'range',
			position: 'bottom left',
			onBeforeShow: function(){
				$('#termin').DatePickerSetDate($('#termin').val(), true);
			},
			onChange: function(formated) {
				$('#termin').val(formated.join(' - '));
			},
			locale: {
					days: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
					daysShort: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
					daysMin: ['ne','po','út','st','čt','pá','so'],
					months: ['leden','únor','březen','duben','květen','červen', 'červenec','srpen','září','říjen','listopad','prosinec'],
					monthsShort: ['led','úno','bře','dub','kvě','čer', 'čvc','srp','zář','říj','lis','pro'],
					weekMin: 'Týd'
			}

		});*/
		
		$.datepicker.regional['cs'] = {
			closeText: 'Zavřít',
			prevText: '&#x3c;Dříve',
			nextText: 'Později&#x3e;',
			currentText: 'Nyní',
			monthNames: ['leden','únor','březen','duben','květen','červen',
	        'červenec','srpen','září','říjen','listopad','prosinec'],
			monthNamesShort: ['led','úno','bře','dub','kvě','čer',
			'čvc','srp','zář','říj','lis','pro'],
			dayNames: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
			dayNamesShort: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
			dayNamesMin: ['ne','po','út','st','čt','pá','so'],
			weekHeader: 'Týd',
			dateFormat: 'dd.mm.yy',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			yearSuffix: ''};
			
		$.datepicker.setDefaults($.datepicker.regional['cs']);
		
		$('#termin').datepicker({
			minDate:			'0',
			buttonImage:		'./images/calendar.gif',
			buttonImageOnly:	true,
			buttonText:			'Kalendář', 
			showOn:				'both',
			onSelect: function(dateText, inst) {
				var start = new Date($('#termin').datepicker('getDate'));
				var today = new Date();
				$('#termin2').datepicker('option', {
					minDate: '' + Math.abs(dateRange(today, start))
				});
			}
		});
		
		$('#termin2').datepicker({
			minDate:			'0',
			buttonImage:		'./images/calendar.gif',
			buttonImageOnly:	true,
			buttonText:			'Kalendář', 
			showOn:				'both'
		});
	}
	
	$('.infobox').hide().removeClass('n');

	$('.infotable .info').hover(function(){
		$link = $(this);
		$linkSibling = $link.siblings('.infobox');
		$('.infobox').fadeOut('fast');
		$('.info').removeClass('open');
		
		$linkSibling.css($link.position()).stop(true,true).fadeIn('fast');
		$link.addClass('open');
		
	},function(){
		$link = $(this);
		$linkSibling = $link.siblings('.infobox');
		$('.infobox').fadeOut('fast');
		$('.info').removeClass('open');
		
		$linkSibling.stop(true,true).fadeOut('fast');
		$link.removeClass('open');
		
	}).click(function(){
		return false;
	});
	
	$('img.over, .info img').each(function(){
		var $img = $(this);
		var src1 = $img.attr('src'); // initial src
		var newSrc = src1.substring(0, src1.lastIndexOf('.')); // let's get file name without extension
		
		$img.hover(function(){
			$(this).attr('src', newSrc + '-over.' + /[^.]+$/.exec(src1)); // last part is for extension       
		}, function(){
			$(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); // removing '-over' from the name
		});
	
	});
	
	// Validate	
	if($.fn.validate) {
		
		$('#contactform').validate({
			rules: {
				name: 'required',
				eml: {
					required: true,
					email: true
				},
				subject: 'required',
				text: 'required'
			},
			messages: {
				name: {
					required: 'Tato položka je vyžadována.'
				},
				eml: {
					required: 'Tato položka je vyžadována.',
					email: 'Prosím zapište správnou emailovou adresu.'
				},
				subject: {
					required: 'Tato položka je vyžadována.'
				},
				text: {
					required: 'Tato položka je vyžadována.'
				}
			}	
		});

	}
	
	$.fn.remoteControl = function($toggleNow) {
				
		$(this).click(function(){
			
			$link = $(this);
			
			$box = $($link.attr('href'));		
			if(!$box.length) return;
									
			if($box.is(':visible')) {
				if($toggleNow)
					$toggleNow.hide();
					
				$box.slideUp('fast');
				$link.text($link.removeClass('open').text().replace(/skrýt/i,'Zobrazit'));
			} else {
				if($toggleNow)
					$toggleNow.fadeIn('fast');
					
				$box.slideDown('fast');
				$link.text($link.addClass('open').text().replace(/zobrazit/i,'Skrýt'));
			}
			
			return false;
		});
		
	}
	
	$('a.remote, .remote a').remoteControl();
	$('a.remote, .remote a').click();

	if($.fn.fancybox)
		$('.gal a, a[rel=popup]').fancybox({
			'overlayColor'		: '#000',
			'overlayOpacity'	: 0.5
		});

	////////////////////////////////////////////////////////////////////////////
	// Bookmarks
	
	var activeclass = 'active';
	var primaryhiding = 'n';
	var secondaryhiding = 'ac';
	
	//------------------------------------------------------------------------//
	
	var $bookmarks = $('.bookmarks');
	
	$.each($bookmarks, function() {
	
		$parent = $(this);
		var $links = $parent.find('li a');
		
		// If parent has class "hover", then we bind hover event
		if($parent.hasClass('hover'))
			eventtype = 'mouseenter mouseleave';
		else
			eventtype = 'click';
		
		$.each($links, function() {
		
			$link = $(this);
			$target = $($link.attr('href'));
			
			// If the target exists
			if($target.length) {
			
				// Eliminating problem with selectbox and display="none"
				if($target.find('select').length == 0)
					hidingclass = primaryhiding;
				else
					hidingclass = secondaryhiding;
				
				// Hide all bookmarks except first
				
				if(!$link.closest('li').is(':first-child'))
					$target.addClass(hidingclass);
				else
					$link.addClass(activeclass);
				
				// Binding with click event
				$link.bind(eventtype, function() {
				
					$link = $(this);
					
					// Eliminating problem with selectbox and display="none"
					if($target.find('select').length == 0)
						hidingclass = primaryhiding;
					else
						hidingclass = secondaryhiding;
					
					$sibling = $link.closest('ul').find('.'+activeclass);
					
					// Hide bookmark from active sibling and remove active class
					$($sibling.attr('href')).addClass(hidingclass);
					$sibling.removeClass(activeclass);
					
					// Display target bookmark and add active class
					$($(this).attr('href')).removeClass(hidingclass);
					$link.addClass(activeclass);
				
					return false;
				});
			
			} else { // The target doesn't exist
			
				alert('cil neexistuje');
				$link.bind(eventtype, function() { return false; });
			
			};
		
		});
	
	});

	////////////////////////////////////////////////////////////////////////////
	// Autosending forms

	var sendclass = "autosend";
	var senditems = "input, textarea, select";

	//------------------------------------------------------------------------//

	// Input change binding
	$("."+sendclass).find(senditems).click(function() {
		alert('Automatické odeslání formuláře, zpráva pro testovací účely.');
		this.form.submit();
	});

	////////////////////////////////////////////////////////////////////////////
	// Anchors

	var anchorSelector = 'a';
	var externalTitle = 'Odkaz vede do nového okna';

	//------------------------------------------------------------------------//

	function external() {
		
		var anchors = $(anchorSelector);
		
		jQuery.each( anchors , function() {
			
			$link = $(this);
			
			if($link.attr('rel').search(/external/) == 0) {
				
				$link.attr('target','_blank');
				
				if($link.attr('title') == '')
					$link.attr('title', externalTitle);
				else
					$link.attr('title', $link.attr('title') + ' | ' + externalTitle);
				
			}
				
		});
		
	}
	external();

	////////////////////////////////////////////////////////////////////////////
	// Titleboxes
	
	var offsetX = -200;
	var offsetY = 15;
	var paddingX = paddingY = 15;
	var effectSpeed = 'slow';
	var titleSelector = '.help[title]';

	//------------------------------------------------------------------------//
	// Nice titleboxes
	
	titleMove = function(e) {
	
		var totalX = e.pageX + offsetX;
		var totalY = e.pageY + offsetY;
	
		if(totalX < paddingX)
			totalX = 0 + paddingX;
		else if (totalX > $('body').width())
			totalX = $('body').width() - paddingX;
		
	
		if(totalY < paddingY)
			totalY = 0 + paddingY;
		else if (totalY > $('body').height())
			totalY = $('body').height() - paddingY;
	
		$('#titlebox').css({ left: totalX, top: totalY });
	};
	
	$(document).mousemove(titleMove);
	
	$(titleSelector).mouseover(function(e){
	
		$('body').append('<div id="titlebox"><div id="titlebox-wrap"><div id="titlebox-in"><strong>Nápověda</strong><em></em></div></div></div>');
	
		var origText = $(this).attr('title');
		$(this).attr('title','');
	
		$('#titlebox em').text(origText).parent('#titlebox').fadeIn('normal');
	
	});
	
	
	$(titleSelector).mouseout(function(e){      
	
		$(this).attr('title',$('#titlebox em').text());
		$('#titlebox').css('background-image','none').fadeOut(effectSpeed).remove();
	
	});
	
	if(ie6 && DD_belatedPNG)
		DD_belatedPNG.fix('#panel img, .corner, #order, .gal span');

});
