$(function(){
  
/*--------------------------------------------------
	KALENDÁŘ
--------------------------------------------------*/
// Obsluha možnosti výběru "prošlého" data v kalendáři
// projdeme všechny inputy typu datum
$('.fi-date').each(function(){
    // Lze vybirat data i v minulosti
    if($(this).hasClass('unlimited-date')){
    	// kalendářová komponenta
    	$(this).datePicker({
        	displayClose: true,    // zobrazit tlacitko pro zavreni
            clickInput: false,   // kliknutí do inputu zobrazí kalendář
            startDate: '01/01/1900' // nastaveni počátečního data.
        });
    }
    // Pristupne budou jen budouci data + dnesni
    else {
    	// kalendářová komponenta
    	$(this).datePicker({
            displayClose: true,    // zobrazit tlacitko pro zavreni
            clickInput: false   // kliknutí do inputu zobrazí kalendář
        });
    }
});

/*--------------------------------------------------
	TOOLTIP
--------------------------------------------------*/
// ikona s otazníkem, po najetí nad ní, se zobrazí element zobrazující nápovědný text 
$(".ico-tooltip").mouseenter(function(){
        var tooltipText = $(this).html();
        
        $("body").append("<div id='tooltip'><div class='arrow arrow-right'></div><div id='content'>" + tooltipText + "</div></div>");
       
        // pozice prvku, po jehož přejetí se zobrazuje nápověda
        var pos = $(this).offset();
        var width = $(this).width();
        // tooltip zobrazíme přímo nad tímto prvkem, pomocí CSS ho pozicujeme dle potřeby
        $("#tooltip").css( { "left": (pos.left + width) + "px", "top":pos.top + "px" } );
    }).mouseleave(function(){
        $('#tooltip').remove();
});

/*--------------------------------------------------
	STYLOVÁNÍ STANDARDNĚ NESTYLOVATELNÝCH ELEMENTŮ
--------------------------------------------------*/
// SELECTBOX (nezahrnujeme selecty s atributem MULTISELECT)
$("select").not('select[multiple]').selectbox();

	// Pro uživatele čteček přidáme tlačítko, které vrátí select do původního stavu
	$('.jquery-selectbox:first').append('<button type="button" class="disable-styled-select">Máte-li problém s výběrem položky, klikněte zde</button>');

		// Skryté tlačítko pro zrušení nahrazeného selectu
		$(".disable-styled-select").click(function(){
			$(".jquery-selectbox").unselectbox();
		});
						
// INPUT pro NAHRÁNÍ SOUBORU
$("input[type='file']").each(function(){
									  
	var parent = $(this).parent();
	var label = $('label', parent);
	var input = $(this).addClass('input-file-overlay').css({'opacity': 0});

	input.wrap('<div class="file-upload-row" />');
	input.after('<div class="wrapper"><div class="form-row file-upload"><input class="fi-text selected-file-name" value="Není vybrán žádný soubor"><button type="button" class="button">Procházet</button></div></div>');
	input.change(function () {
		var selectedFileName = this.value;
	
		if($.browser.msie){
			selectedFileName = extractFileName(selectedFileName);
		}
	
		var context = input.next();
	
		$('.selected-file-name', context).attr('value', selectedFileName);
	});
});

// Dbl click na label - focus na příslušný input
$('form .label-outer').dblclick(function(){
	$(this).next().trigger('focus');
});

// END OF DOCUMENT READY
});

/*--------------------------------------------------
	VALIDACE FORMULÁŘE
--------------------------------------------------*/
// Vytvoření elementu pro ch. hlášku
function errorMessageElement(id, sender) {
   var el = document.getElementById(id);
    if(!el) {
        var el = $('<div id="' + id + '"></div>');
        var parent = $(sender).parent();    // Rodič inputu, do kterého umístíme hlášku
        $(parent).append(el);
    }
    else {
        $(el).css('display','block');   // položka ztratila focus, ale není dobře vyplněna
    }
    return el;
}

// Zobrazí příslušnou chybové hlášku 
function addError(sender, message) {
    $(sender).parent().addClass('error');   // rodič prvku dostane class
    var elementID = sender.id+'_message';   // reference na el. s ch. hláškou
    var el = errorMessageElement(elementID, sender);
    $(el).addClass('error-msg');
    $(el).text(message);
}

// Odtranění chybové hlášky
function removeError(sender) {
    $(sender).parent().removeClass('error');    // rodiči prvku odebereme class
    var elementID = sender.id+'_message';       // reference na el. s ch. hláškou
    el = errorMessageElement(elementID, sender);
    $(el).remove();     //Položka správně vyplněna, odstranime ch. hlašku z DOM
}

// Po klikniti na submit, kontrola zda je vše řádně vyplněno
function informError(submitter) {}

// Položka byla správně vyplněna/opravena
function onValid(sender) {
    el = errorMessageElement(sender.id+'_message', sender);
    $(el).addClass('form-valid-message');
    $(el).html('');
}

/*---------------------------------------------------
	INPUT pro NAHRÁNÍ SOUBORU
--------------------------------------------------*/
// Extrahování jména souboru a jeho přípony (z celé cesty k souboru)
function extractFileName(data){
	var m = data.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/);
	return m[2];
}

/*---------------------------------------------------
	SELECTBOX (nezahrnujeme selecty s atributem MULTISELECT)
	jQuery custom selectboxes @version 0.6.1 @ Copyright (c) 2008 Krzysztof Suszyński (suszynski.org); Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
--------------------------------------------------*/
jQuery.fn.selectbox = function(options){
	/* Default settings */
	var settings = {
		className: 'jQ-selectbox',
		classSelectedItem: 'selected',		
		animationSpeed: 0,
		listboxMaxSize: 10,
		replaceInvisible: false
	};
	var commonClass = 'jQ-custom-select-replaced';
	var listOpen = false;
	var showList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		listObj.show(settings.animationSpeed, function(){
			listOpen = true;
		});
		selectbox.addClass('selecthover');
		jQuery(document).bind('click', onBlurList);
		return listObj;
	}
	var hideList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		selectbox.removeClass('selecthover');
		listObj.hide(settings.animationSpeed, function(){
			listOpen = false;
		});
		jQuery(document).unbind('click', onBlurList);
		return listObj;
	}
	var onBlurList = function(e) {
		var trgt = e.target;
		listOpen = true;
		var currentListElements = jQuery('.' + settings.className + '-list:visible').parent().find('*').andSelf();
		if(jQuery.inArray(trgt, currentListElements)<0 && listOpen) {
			hideList( jQuery('.' + commonClass + '-list') );
		}
		return false;
	}
	
	/* Processing settings */
	settings = jQuery.extend(settings, options || {});
	/* Wrapping all passed elements */
	return this.each(function() {
		
    var _this = jQuery(this);
		if(_this.filter(':visible').length == 0 && !settings.replaceInvisible)
			return;
		var replacement = jQuery(
			'<div class="' + settings.className + ' ' + commonClass + '">' +
				'<div class="' + settings.className + '-moreButton" />' +
				'<div class="' + settings.className + '-list ' + commonClass + '-list" />' +
				'<span class="' + settings.className + '-currentItem" />' +
			'</div>'
		);
		jQuery('option', _this).each(function(k,v){
		
      var v = jQuery(v);
			var listElement =  jQuery('<span class="' + settings.className + '-item value-'+v.val()+' item-'+k+'">' + v.text() + '</span>');	
			listElement.click(function(){
				var thisListElement = jQuery(this);
				jQuery('.' + settings.className + '-item', thisListElement.parent()).removeClass(settings.classSelectedItem);	// ostraníme class selected
				thisListElement.addClass(settings.classSelectedItem);	// aktuálně vybraná položka dostane class selected
				var thisReplacment = thisListElement.parents('.'+settings.className);
				var thisIndex = thisListElement[0].className.split(' ');
				for( k1 in thisIndex ) {
					if(/^item-[0-9]+$/.test(thisIndex[k1])) {
						thisIndex = parseInt(thisIndex[k1].replace('item-',''), 10);
						break;
					}
				};
				var thisValue = thisListElement[0].className.split(' ');
/*
                for( k1 in thisValue ) {
				
				if(/^value-.*$/.test(thisValue[k1])) {
					  thisValue = thisValue[k1].replace('value-','');
						break;
					}
				};
*/                
               thisValue = this.innerHTML;
				thisReplacment
					.find('.' + settings.className + '-currentItem')
					.text(thisListElement.text());
				thisReplacment
					.find('select')
					.val(thisValue)
					.triggerHandler('change');
				var thisSublist = thisReplacment.find('.' + settings.className + '-list');
				if(thisSublist.filter(":visible").length > 0) {
					hideList( thisSublist );
				}else{
					showList( thisSublist );
				}
			}).bind('mouseenter',function(){
				jQuery(this).addClass('listelementhover');
			}).bind('mouseleave',function(){
				jQuery(this).removeClass('listelementhover');
			});
			jQuery('.' + settings.className + '-list', replacement).append(listElement);
			if(v.filter(':selected').length > 0) {
				jQuery('.'+settings.className + '-currentItem', replacement).text(v.text());
			}
		});
		
		// chování při kliknutí na tlačítko s šipkou
		replacement.find('.' + settings.className + '-moreButton').click(function(){
			
      var thisMoreButton = jQuery(this);
			var thisList = thisMoreButton.siblings('.' + settings.className + '-list');
			var otherLists = jQuery('.' + settings.className + '-list').not(thisList);

			hideList( otherLists );
			
			if(thisList.filter(":visible").length > 0) {
				hideList( thisList );
			}else{
				showList( thisList );
			}
		}).bind('mouseenter',function(){
			jQuery(this).addClass('morebuttonhover');
		}).bind('mouseleave',function(){
			jQuery(this).removeClass('morebuttonhover');
		});

		// chování při kliknutí na aktuální položku
		replacement.find('.' + settings.className + '-currentItem').click(function(){
		  var thisMoreButton = jQuery(this);
			var thisList = thisMoreButton.siblings('.' + settings.className + '-list');
			var otherLists = jQuery('.' + settings.className + '-list').not(thisList);

			hideList( otherLists );
			
			if(thisList.filter(":visible").length > 0) {
				hideList( thisList );
			}
			else {
				showList( thisList );
			}
		});

		_this.hide().replaceWith(replacement).appendTo(replacement);
		var thisListBox = replacement.find('.' + settings.className + '-list');
		var thisListBoxSize = thisListBox.find('.' + settings.className + '-item').length;
		if(thisListBoxSize > settings.listboxMaxSize)
			thisListBoxSize = settings.listboxMaxSize;
		if(thisListBoxSize == 0)
			thisListBoxSize = 1;
		var thisListBoxWidth = Math.round(_this.width());
		replacement.css('width', thisListBoxWidth + 'px');
		thisListBox.css({
			width: Math.round(thisListBoxWidth) + 'px',
			height: (thisListBoxSize * 15) + 'px' // počet položek * výška jedné položky OPTION
		});
	});
}
// Odstranění formátování selectu - je-li potřeba (pro uživatele čteček)
jQuery.fn.unselectbox = function(){
	var commonClass = 'jQ-custom-select-replaced';
	return this.each(function() {
		var selectToRemove = jQuery(this).filter('.' + commonClass);
		selectToRemove.replaceWith(selectToRemove.find('select').show());		
	});
}
