var font = (function () {
    var test_string = 'mmmmmmmmmwwwwwww';
    var test_font = '"Comic Sans MS"';
    var notInstalledWidth = 0;
    var testbed = null;
    var guid = 0;
    
    return {
        // must be called when the dom is ready
        setup : function () {
            if ($('#fontInstalledTest').length) return;

            $('head').append('<' + 'style> #fontInstalledTest, #fontTestBed { position: absolute; left: -9999px; top: 0; visibility: hidden; } #fontInstalledTest { font-size: 50px!important; font-family: ' + test_font + ';}</' + 'style>');
            
            
            $('body').append('<div id="fontTestBed"></div>').append('<span id="fontInstalledTest" class="fonttest">' + test_string + '</span>');
            testbed = $('#fontTestBed');
            notInstalledWidth = $('#fontInstalledTest').width();
        },
        
        isInstalled : function(font) {
            guid++;
        
            var style = '<' + 'style id="fonttestStyle"> #fonttest' + guid + ' { font-size: 50px!important; font-family: ' + font + ', ' + test_font + '; } <' + '/style>';
            
            $('head').find('#fonttestStyle').remove().end().append(style);
            testbed.empty().append('<span id="fonttest' + guid + '" class="fonttest">' + test_string + '</span>');
                        
            return (testbed.find('span').width() != notInstalledWidth);
        }
    };
})();

function ieFix(){
	if ($.browser.msie && parseInt($.browser.version, 10) < 9){
	    $('#content')
	        .css({"opacity":0})
	        .delay(200)
	        .css({"opacity":'none'});
			
		$('#logo').hover(function(){
			
		}, function(){
			$(this).css('opacity','none')
		})
		
		$('#homepage-images ul').mouseover(function(){
			$(this).trigger('mouseover');
		})
		
		$('div, span, a, ul, li, p, h1, h2, h3, h4, h5').filter(function(){
			return $(this).css('opacity');
		}).css({
			opacity:'none'
		}).addClass('hover');
	}
}


// FIXME pokud nepomůže na win, vypnout vše krom Arial a sans-seruf
// function replaceFont(){
	// font.setup();
	// var fontname = 'Helvetica Neue';
	// if(! font.isInstalled(fontname)){
		// $('body *').css({
			// 'font-family': "HelveticaNeue, Helvetica Neue, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif"
		// })
	// }
// }

$(document).ready(function(){
	ieFix();
	// replaceFont();

	

	
	var $body = $('body');
	// em
	$('a.em[data-em]').each(function(){
		e = $(this).data('em').replace('/','@');
		$(this).attr('href', 'mailto:'+e).not('.custom-text').text(e);
	});
	// cstypo
	$('p').cstypo();
	// main menu
	// if(! $.browser.msie){
		$('#main-menu > ul > li').not('.search').hover(function(){
		    var thisEl = $(this);
		    thisEl.find('.sub-menu').stop().css({display:'block', opacity:0}).animate({opacity:1},400);
		    thisEl.addClass('active');
		}, function(){
		    $(this).removeClass('active').find('.sub-menu').stop().animate({opacity:0},400, function(){
					$(this).css({display:'none', opacity:0});
				});
		}).find('.sub-menu').mouseenter(function(e){
			e.stopPropagation();
		});
	// }

	// #exhibition-archive
	if ($('#exhibition-archive').length > 0) {
    var yearsMore = $('#exhibition-archive #years-more-ul');
    var yearsMoreClick = $('#exhibition-archive #years-more');
		yearsMore.before('<div id="years-more-overlay"></div>');
		var yearsMoreOverlay = $('#years-more-overlay');
    yearsMoreClick.click(function(){
      if (yearsMore.hasClass('in')) {
        yearsMoreOverlay.fadeOut(0);
				yearsMore.removeClass('in').fadeOut(200);
			} else {
        yearsMoreOverlay.fadeIn(0);
				yearsMore.addClass('in').fadeIn(200);
			}
		});
		$('#years-more-overlay').live('click',function(){
      yearsMoreClick.click();
		});
	}

	// #multimedia-filter
	if ($('#multimedia-filter').length > 0) {
    var more = $('#multimedia-filter .filter-more');
    var menus = $('#multimedia-filter .filter-more-ul');
		more.eq(0).before('<div id="filter-overlay"></div>');
		var overlay = $('#filter-overlay');
    more.click(function(){
      var menu = $(this).next('.filter-more-ul');
      if (menu.hasClass('in')) {
        overlay.fadeOut(0);
				menu.removeClass('in').fadeOut(200);
			} else {
        overlay.fadeIn(0);
				menu.addClass('in').fadeIn(200);
			}
		});
		overlay.live('click',function(){
		  menus.filter('.in').prev('.filter-more').click();
		});
	}

	// exhibition detail gallery
	if ($('#exhibition-detail-body .gallery, #stable-exhibition-detail-body .gallery, #education-body .gallery').length == 1) {
	  var thisEl = $('#exhibition-detail-body .gallery, #stable-exhibition-detail-body .gallery, #education-body .gallery');
		var $showGallery = thisEl.find('.show-gallery');
		var $hideGallery = thisEl.find('.hide-gallery');
		var $galleryItem = thisEl.find('.items');
		var $galleryImages = thisEl.find('.img img');
		var $galleryUl = thisEl.find('ul.img');
		var $galleryParagraph = $galleryItem.find('p');
    $showGallery.click(function(){
      $showGallery.fadeOut(600);
      $galleryItem.slideDown(300);
		});
    $galleryImages.click(function(){
      if ($showGallery.is(':visible')) {
	      $showGallery.fadeOut(600);
	      $hideGallery.fadeIn(600);
	      $galleryItem.slideDown(600);
			} else {
	      $showGallery.fadeIn(600);
	      $hideGallery.fadeOut(600);
	      $galleryItem.slideUp(600);
			}
      //$(this).unbind('click').css({cursor:'default'});
		});
    $hideGallery.click(function(){
      $showGallery.fadeIn(600);
      $galleryItem.slideUp(600);
		});
		var $firstImg = $galleryUl.find('li img').first();
// 		$firstImg.imagesLoaded(function(){
		$galleryImages.css({position:'static', visibility:'visible'});
			var $slider = $galleryUl.bxSlider({
				infiniteLoop: false,
				controls: false,
				mode: 'fade',
				onBeforeSlide: function(currentSlideNumber, totalSlideQty, currentSlideHtmlObject) {
													$galleryParagraph.html($images.eq(currentSlideNumber).data('description'));
											}
			});
		  var $resizeThis = $('#exhibition-detail-body, #stable-exhibition-detail-body').find('.bx-wrapper, .bx-window, ul.img');
			$resizeThis.height($firstImg.height());
			$(document).keydown(function(e) {
				if (e.keyCode == 37) { // left
					$slider.goToPreviousSlide();
				}
				if (e.keyCode == 39) { // right
					$slider.goToNextSlide();
				}
			});
			var $images = $galleryItem.find('li').not('.hide-gallery').find('img');
			$images.click(function(){
				var thisImg = $(this);
				$slider.goToSlide($images.index(thisImg));
			});
// 		});
	}

	if ($('#homepage-images').length > 0) {
    //$('#homepage-images ul li').width($(window).width()-17);
// 		$('#homepage-images ul').carouFredSel({
// 					debug: true,
// 		      width: 969,
// 		      height: 360,
// 		      items: {
// 						width: 969,
// 						height: 360
// 					},
// 					//direction: 'right',
// 					scroll: {
// 						fx: 'fade',
// 						pauseOnHover: true
// 					},
// 					auto: {
// 						play: true,
// 						pauseDuration: 5000
// 					},
// 					pagination: {
// 						container: '#homepage-pagination'
// 					}
// 				});
		var $slider = $('#homepage-images ul').bxSlider({
			infiniteLoop: true,
			controls: false,
			mode: 'fade',
			auto: true,
			pause: 4000,
			autoHover: true,
			pager: true
		});
		$(document).keydown(function(e) {
			if (e.keyCode == 37) { // left
				$slider.goToPreviousSlide();
			}
			if (e.keyCode == 39) { // right
				$slider.goToNextSlide();
			}
		});
	}

	$('#footer nav .col ul li.input .arrow, #public-plastic-filter .button-submit').click(function(){
    $(this).parents('form').submit();
	});
	$('form input[type="email"]', '#footer').focus(function(){ $(this).clearOnFocus() });

	if ($('#accompanying-actions-full').length > 0) {
    $('#accompanying-actions-full #actions-filter-select').change(function(){
      var value = $(this).val();
      var items = $('#accompanying-actions-full ul li');
      var showItems = items;
      if (value !== 'all') { showItems = showItems.filter(function(){ return $(this).data('category') == value }) }
      items.not(showItems).hide(400);
      showItems.show(400);
    });
	}

	if ($('#pronajmy').length > 0) {
    $('#pronajmy .content p .more').click(function(){
			var thisMore = $(this);
			var thisText = thisMore.find('.text');
			if (thisMore.hasClass('in')) {
        thisMore.addClass('out').removeClass('in').parents('.content').find('.paragraphs').slideUp(400);
        thisText.text(thisText.data('more'));
			} else {
        thisMore.addClass('in').removeClass('out').parents('.content').find('.paragraphs').slideDown(400);
        thisText.text(thisText.data('less'));
			}
    });
	}

	if ($('#gmap-wrap #gmap-left').length == 1) {
		$('#gmap-wrap #gmap-left .items').height($('#gmap-wrap #gmap-left').height() - $('#gmap-wrap #gmap-left .filters').height() - 10).children('ul');		
	}
	
	if ($('#collections-detail-gallery').length > 0) {
	  var $collectionsGallery = $('#collections-detail-gallery');
	  var $collectionsDetailTop = $('#collections-detail-top');
	  var $collectionsGmap = $('#collections-gmap');
	  var $slider = $collectionsGallery.bxSlider({
      controls: false,
      infiniteLoop: false
		});
		//var $resizeThis = $('#collections-detail-top').find('.bx-wrapper, .bx-window, #collections-detail-gallery');
		var $slideImages = $('#collections-detail-top #collections-detail-gallery li.pager img');
		//$resizeThis.height($slideImages.eq(0).height());
		$(document).keydown(function(e) {
			if ($collectionsDetailTop.hasClass('zoomed')) {
				$wrap.click();
			}
				if (e.keyCode == 37) { // left
					$slider.goToPreviousSlide();
				}
				if (e.keyCode == 39) { // right
					$slider.goToNextSlide();
				}
		});
		var $images = $('#collections-detail-bottom .mid .thumbs li img');
		$images.click(function(){
			if ($collectionsDetailTop.hasClass('zoomed')) {
				$wrap.click();
			}
			$slider.goToSlide($images.index($(this)));
		});
		$('#collections-detail-p-toggle', '#collections-detail-bottom .mid').click(function(){
			var elThis = $(this);
			elThis.prev('p').slideToggle(400);
			elThis.toggleClass('in');
			elThis.children('.text').text(elThis.data( elThis.hasClass('in') ? 'in' : 'out' ));
			return false;
		});

		var $sliderThumbs = $('#collections-more-work ul').bxSlider({
      pager: true,
      infiniteLoop: false,
      displaySlideQty: 5,
      moveSlideQty: 5,
      prevText: '',
      nextText: '',
      hideControlOnEnd: true
		});
		if ($('#collections-more-work ul li.pager').length < 6) { $('#collections-more-work').find('a.bx-prev, a.bx-next, div.bx-pager').hide(0) }

		// cursor
		var $wrap = $('#collections-detail-top .overlay-cursor'); var $cursor = $wrap.find('.cursor');
	  var vT=$wrap.offset().top;
	  var vL=$wrap.offset().left;
	  $wrap.mousemove(function(e){
			var ypos=e.pageY-vT;
			var xpos=e.pageX-vL;
			var y=Math.round(ypos);
			var x=Math.round(xpos);
			$cursor.css({top:y, left:x});
			if ($collectionsDetailTop.hasClass('zoomed')) {
				var myImg = $slideImages.eq($slider.getCurrentSlide());
				var imgWidth = myImg.width();
				if (imgWidth < 984) { imgWidth = 984 }
				var contHeight = 460;
				var heightDiff = (myImg.height() - contHeight);
				var widthDiff = (imgWidth - 984);
				var relativeHeight = y/contHeight;
				var relativeWidth = x/984;
				var targetTop = -heightDiff*relativeHeight;
				var targetLeft = -widthDiff*relativeWidth;
// 				console.log('relativeTop: '+relativeHeight+' top: '+targetTop+' left: '+targetLeft+' widthDiff: '+widthDiff+' heightDiff: '+heightDiff+' extraWidthSpace: ');
        myImg.css({top:targetTop, left:targetLeft});
			}
	  });
		//$resizeThis.height($resizeThis.height());
		$wrap.click(function(){
    	var activeImage = $slideImages.eq($slider.getCurrentSlide());
		var parentPager = activeImage.parents('li.pager');
		var originalImage = activeImage.attr('src');
		var zoomedImage = parentPager.data('image-path');
		if ($collectionsDetailTop.hasClass('zoomed')) {
			$collectionsDetailTop.removeClass('zoomed');
			activeImage.attr('src', originalImage);
			activeImage.animate({opacity:0}, 200, function(){
				activeImage.css({height:parseInt(activeImage.data('height')), top:0, left:0}).animate({opacity:1}, 200);
			});
// 			  activeImage.parent('div').animate({top:0, left:0}, 400);
		} else {
			$collectionsDetailTop.addClass('zoomed');
			activeImage.attr('src', zoomedImage);
			var targetHeight = activeImage.height()*2;
			activeImage.data('height', activeImage.height()).animate({opacity:0}, 200, function(){
				activeImage.height(targetHeight);
				if (activeImage.width() > parentPager.width()) { activeImage.css({left:-(activeImage.width()-parentPager.width())/2}) }
				activeImage.animate({opacity:1}, 200);
			});
		}
		return false;
	});
	}
	if ($('#visit-info').length > 0) {
		$('#visit-info ul').masonry({
			columnWidth: 313,
			gutterWidth: 15,
			itemSelector: 'li'
		});
	}
	if ($('#multimedia-grid').length > 0) {
		var elList = $('#multimedia-grid ul');
		elList.find('img').imagesLoaded(function(){
			$('#multimedia-grid ul').masonry({
				columnWidth: 182,
				gutterWidth: 15,
				itemSelector: 'li'
			});
		});
	}
	if ($('#multimedia-categories').length > 0) {
		var elList = $('#multimedia-categories .all ul.list');
		elList.find('img').imagesLoaded(function(){
		elList.masonry({
			columnWidth: 180,
			gutterWidth: 15,
			itemSelector: 'li',
			isAnimated: true
		});
		});
	}

	

	// main menu search
  $('#main-menu .search .placeholder').click(function(){
    var $liSearch = $(this).parents('li.search');
    var $thisForm =  $(this).siblings('form');
    var $thisInput =  $(this).siblings('form').find('input');
    $liSearch.css({width:$liSearch.width(), overflow:'visible'}).addClass('searching');
    $thisForm.css({height:$(this).height(), width:$(this).width()}).show(0);
    $(this).hide(0);
		$thisInput.focus().siblings('.arrow-small, .arrow').addClass('visible').click(function(){ $(this).parents('form').submit() });
    $thisInput.keyup(function(e){
			var thisVal = $(this).val();

				$body.append('<span style="position: absolute; visibility: hidden;" id="input-search-test">'+thisVal+'M</span>');
				var inputTest = $('#input-search-test');
				var targetVal = inputTest.width();
				inputTest.remove();

        $thisForm.stop().animate({width:targetVal}, 150);
		});
		$thisInput.keyup();
	});

	$('#accompanying-actions .past.with-header small').click(function(){
		var items = $('#accompanying-actions li');
		$('#accompanying-actions ul').animate({height:(Math.ceil(items.length/4))*(items.first().outerHeight()+40)}, 500, function(){
      items.filter('.past:hidden').fadeIn(400);
      items.filter('.past.with-header').find('a').animate({opacity:1}, 400);
      //$('#accompanying-actions ul').animate({height:'auto'}, 500);
		});
		$(this).unbind('click').css({cursor:'default'});
	});

	if ($('#page-thirds').length > 0) {
    $('#page-thirds .col .item p .arrow-small').click(function(){
      $(this).parents('.item').find('p.hidden').slideToggle(400);
		});
	}

	if ($('#public-plastic-filter input[type="text"]').length > 0) {
  	$('#public-plastic-filter input[type="text"]').focus(function(){ $(this).clearOnFocus() });
	}

	if ($('.perex-toggler').length > 0) {
    $('.perex-toggler .perex .perex-show-more').click(function(){
		var elThis = $(this);
		if (elThis.hasClass('in')) {
			elThis.removeClass('in').children('.text').text(elThis.data('more'));
			elThis.parents('.perex-toggler').find('.paragraphs').slideUp(400);
		} else {
			elThis.addClass('in').children('.text').text(elThis.data('less'));
			elThis.parents('.perex-toggler').find('.paragraphs').slideDown(400);
		}
	});
	}
	
	if ($('#stable-exhibition-detail-body .content.form .membership').length > 0) {
	  var elForm = $('#stable-exhibition-detail-body .content.form .membership');
	  var radioTogglers = elForm.find('input.radio-toggler');
	  var togglers = elForm.find('.toggler');
	  var togglerItems = togglers.find('.item');
    radioTogglers.change(function(){
      var elThis = $(this);
      if (elThis.hasClass('in')) { return false }
      radioTogglers.removeClass('in');
      elThis.addClass('in');
      togglerItems.slideUp(400);
      togglers.removeClass('in').filter(elThis.siblings('.toggler')).addClass('in').find('.item');
		});
		togglers.children('small').click(function(){
			if ($(this).hasClass('in')) { return false }
			$(this).next('.images').children('.item').slideDown(400);
		});
		togglerItems.children('.img').click(function(){
			$(this).next('.controls').children('input').click();
		});
		togglerItems.find('input').change(function(){
		  var thisItem = $(this).parents('.item');
      $(this).parents('.images').children('.item').not(thisItem).removeClass('selected').slideUp(400);
      thisItem.addClass('selected');

		});
	}
	
	// collections-search
	var collectionsSearch = $('#collections-search');
	if (collectionsSearch.length == 1) {
		var collectionsDetailedSearch = collectionsSearch.find('#detailedSearchWrap');
		var collectionsDetailedFade = collectionsSearch.find('#detailedSearchFade');
		var letterItems = collectionsSearch.find('#detailedSearchAlphabet .letters li[data-letter]');
		var letterBoxes = collectionsSearch.find('#detailedSearchAlphabet div.letter[data-letter]');
		var inputArtist = collectionsSearch.find('#detailedSearchArtistInput');
		var searchToggler = collectionsSearch.find('#detailedSearchToggler');
		
		// submit on fulltextspan click
		collectionsSearch.find('#fullText span').click(function(){
			$(this).parents('form').submit();
		});
		
		// submit on change
		collectionsSearch.find('.form-row-row input[type="checkbox"], .form-row-row select, #resultsFilter input, #resultsFilter select').change(function(){
			$(this).parents('form').submit();
		});
		if ($.browser.msie && $.browser.version < 9) {
			collectionsSearch.find('.form-row-row input[type="text"], .form-row input[type="text"]').bind('keydown', function(event){
	      var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
	      if (keycode == 13) {
					$(this).parents('form').submit();
	      }
			});
		}
		// show hide detailed search
		if (collectionsSearch.find('#detailedSearch').hasClass('default-in')) {
      searchToggler.addClass('in');
		}
		// enable disabled inputs on submit
		var disabledInputs = collectionsSearch.find('input[disabled="disabled"]');
		collectionsSearch.find('form').submit(function(){
			disabledInputs.removeAttr('disabled');
		});
		searchToggler.click(function(){
			var elThis = $(this);
			elThis.toggleClass('in');
			if (elThis.hasClass('in')) {
			  if ($.browser.msie && $.browser.version < 9) {
					collectionsDetailedSearch.css({display:'block'});
					collectionsDetailedFade.css({display:'none'});
				} else {
					collectionsDetailedSearch.slideDown(400);
					collectionsDetailedFade.fadeOut(400);
				}
				elThis.children('.text').text(elThis.data('in'));
			} else {
			  if ($.browser.msie && $.browser.version < 9) {
					collectionsDetailedSearch.css({display:'none'});
					collectionsDetailedFade.css({display:'block'});
				} else {
					collectionsDetailedSearch.slideUp(400);
					collectionsDetailedFade.fadeIn(400);
				}
				elThis.children('.text').text(elThis.data('out'));
			}
		});
		// show letter 
		letterItems.click(function(){
			var elThis = $(this);
			if (elThis.hasClass('current')) { return false } else {
				letterItems.removeClass('current');
				elThis.addClass('current');
				var thisLetter = elThis.data('letter');
				var showThis = letterBoxes.filter(function(){ return $(this).data('letter') == thisLetter });
				letterBoxes.filter(':visible').hide(400);
				showThis.show(400);
			}
		});
		// put word into input
		letterBoxes.find('li strong').click(function(){
			inputArtist.val($(this).text());
			letterItems.removeClass('current');
			letterBoxes.filter(':visible').hide(400);
			$(this).parents('form').submit();
		});
		
	}
	
	// search top
	$('#search-top .input .arrow-small').click(function(){
		$(this).closest('form').submit();
	})

});

(function( $ ){
$.fn.clearOnFocus = function(){
		if ($(this).val() == $(this).data('default')) { $(this).val(''); }

		$(this).blur(function(){
			if ($.trim($(this).val()) == '') {$(this).val($(this).data('default'));}
		});
};
})( jQuery );
