function log(e){
    //return false;
    if (typeof(console) == 'object')
        console.log(e);
    //else alert(e);
};

function AddFavorite(linkObj, addUrl3, addTitle3){
    if (document.all && !window.opera) {
        window.external.AddFavorite(addUrl3, addTitle3);
        return false;
    }
    else
        if (window.opera && window.print) {
            linkObj.title = addTitle3;
            return true;
        }
        else
            if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addPanel == 'function')) {
                window.sidebar.addPanel(addTitle3, addUrl3, '');
                return false;
            }
    window.alert('Po potvrzení stiskněte CTRL-D,\nstránka bude přidána k Vašim oblíbeným odkazům.');
    return false;
}

var customLightbox = {
    config: {
        overlayBgColor: '#000',
        overlayOpacity: 0.8,
        fixedNavigation: false,
        imageLoading: '/images/lightbox-ico-loading.gif',
        imageBtnPrev: '/images/lightbox-btn-prev.png',
        imageBtnNext: '/images/lightbox-btn-next.png',
        imageBtnClose: '/images/lightbox-btn-close.png',
        imageBlank: '/images/transparent.png',
        containerResizeSpeed: 200,
        txtImage: 'Obrázek:<br />',
        txtOf: 'z',
        keyToClose: 'c',
        keyToPrev: 'p',
        keyToNext: 'n',
        imageArray: [],
        activeImage: 0
    },
    init: function(){
        $('a[rel=lightbox],a.lightbox').lightBox(customLightbox.config); //only rel="lightbox"
        var lbRels = new Array();
        var thisRel = '';
        var trIsIn = false;
        $('a[rel*="lightbox["]').each(function(){ //each rel="lightbox[..."
            thisRel = $(this).attr('rel').replace('lightbox[', '').replace(']', ''); //curren rel
            for (i = 0; i < lbRels.length; i++) { //find if is not yet in array of rels
                if (thisRel == lbRels[i])
                    trIsIn = true;
                else
                    trIsIn = false;
            }
            if (!trIsIn)
                lbRels[lbRels.length] = $(this).attr('rel').replace('lightbox[', '').replace(']', ''); //not i array of rels => store rel
        });
        for (i = 0; i < lbRels.length; i++) {
            $('a[rel="lightbox[' + lbRels[i] + ']"]').lightBox(customLightbox.config);
        } //each unique rel => apply lightbox
    }
};

var inputValue = {
    config: {
        rememberEl: '.rememberValue',
        values: new Array()
    },
    init: function(){
        $(inputValue.config.rememberEl).focus(function(){
            inputValue.name = $(this).attr('name');
            if (inputValue.config.values[inputValue.name] == null || $(this).val() == inputValue.config.values[inputValue.name]) {
                inputValue.config.values[inputValue.name] = $(this).val();
                $(this).val('').addClass('filled');
            }
        }), $(inputValue.config.rememberEl).blur(function(){
            inputValue.name = $(this).attr('name');
            if ($(this).val() == '') {
                $(this).val(inputValue.config.values[inputValue.name]).removeClass('filled');
            }
        })
    }
};

var priceList = {
  init: function()
  {
    if ( !($.browser.msie && $.browser.version < 8 ) )
    {
      $('#priceListLinks').hide();
      $('.priceList:first').parent().before('<span id="toggleAll" class="png">Rozbalit vše<'+'/span>');
      $('#toggleAll').click(function()
        {
          if ( $(this).hasClass('open') )
          {
            $('.priceList.open tbody').slideToggle('slow');
            $('.priceList.open').toggleClass('open');
            $(this).text('Rozbalit vše');
          }
          else
          {
            $('.priceList:not(.open) tbody').slideToggle('slow');
            $('.priceList:not(.open)').toggleClass('open');
            $(this).text('Sbalit vše');
          }
          $(this).toggleClass('open');
        }
      );
      $('.priceList tbody').hide();
      $('.priceList caption').addClass('active').click(function()
        {
          $(this).next('tbody').slideToggle('slow');
          $(this).parent().toggleClass('open');
        }
      );
    }
  }
};

var trackLinks = {
    init: function(){
        $('a[href^="http"]:not([href*=' + window.location.host + '])').each(function(){
            $(this).click(function(){
                // ulozime do GA
                if (typeof(pageTracker) == 'object') {
                    pageTracker._trackPageview($(this).attr('href').replace(/(http|https):\/\//, '\/out\/'));
                }
            });
        });
    }
};

var externalLinks = {
    config: {
        externalClass: 'external',
        titleAppend: ' [odkaz na jiný web]'
    },
    init: function(){
        $('a[href^="http"]:not([href*=' + window.location.host + '])').each(function(){
            $(this).addClass(externalLinks.config.externalClass).attr('title', $(this).attr('title') + externalLinks.config.titleAppend);
        });
    }
};

/*
 * FB FUNCTIONS
 */

function fbLogin() {
	FB.login(function(response) {
		if (response.session) {
			if (response.perms) {
				//console.log(response.perms);
				//console.log(response);
  	        	// user is logged in and granted some permissions.
  	        	// perms is a comma separated list of granted permissions
  	        	//window.location.href='http://www.zlutelazne.cz/registrace/';
  	      	}
			else {
  	        	// user is logged in, but did not grant any permissions
  	        	//window.location.reload();
  	        	//alert('Nepovoleno nic')
			}
		}
		else {
			// user is not logged in
			//alert('Vubec nic');
  	    }
	},{perms:'email,offline_access'});
}

/**
 * Balance menu items into columns in dependency of count of subitems
 */
function balanceMenu(){
	var columns = 3;
	var mlist = $('#menu .level-2');
	mlist.each(function(){
		var liItems = $(this).children();
		if (liItems.length >= 5) {
			// resize to count inner size
			$(this).parent().width('2000px');
			var cheight = 0;
			// count heights
			liItems.each(function(){
				cheight += $(this).height();
			});
			// create cols
			var listStack = [];
			for (var i = 0; i < columns; i++) {
				// clone list
				listStack[i] = $(this).clone().addClass('column-' + i).appendTo($(this).parent());
				// clear content
				listStack[i].children().remove();
			}
			// divide items into cols
			var breakHeight = Math.floor(cheight / columns);
			var weight = (cheight % columns) / columns;
			breakHeight = breakHeight * 1.0; // TODO vypocitavani je potreba udelat tak, aby vlivem zaokrohlouvani nezustavalo vic polozek v poslednim sloupci nez v predchozich
			var sheight = 0;
			var x = 0;
			var y = columns;
			// foreach in reverse order
			$(liItems.get().reverse()).each(function(i){
				sheight += $(this).height();
				//log('accum height is ' + sheight);
				//log('breaking height is ' + breakHeight * x);
				var offset = weight * (columns - x + 1); // TODO tady to dopilovat - zvyhodneni sloupciu
				if (sheight > breakHeight * x + offset && x < columns) {
					x++;
					y--;
					//log('-breaking ' + (weight * (columns - x + 1)));
				}
				$(this).removeClass('first');
				//log('appending to ' + (y));
				$(this).appendTo(listStack[y]);
			});
			// count wrapper width
			var cwidth = 0;
			var maxheight = 0;
			var cheight = 0;
			for (var i = 0; i < columns; i++) {
				cwidth += listStack[i].outerWidth();
				cheight = listStack[i].outerHeight();
				if (cheight > maxheight) {
					maxheight = cheight;
				}
			}
			//log('------');
			$(this).siblings().height(maxheight + 'px');
			$(this).parent().width(cwidth+1 + 'px'); // + 1px Mac FF fix 
			// remove original list
			$(this).remove();
		}
	});
}

/*******************************************
 *
 *  on DOM ready
 *
 ********************************************/
$(document).ready(function(){

    $('#page').prepend('<a href="#content" accesskey="0" class="forBlind">Přejít na obsah<' + '/a>');

    // tabs
    $('.dayOverview legend.boxTitle').hide();
    $('ul.tabs').tabs('.dayOverview' ).history();
    $('ul.tabs .tab a').click( function() {Cufon.set('fontFamily', 'rockwell').replace('ul.tabs .tab a'); } );

    // cufon
    Cufon.set('fontFamily', 'rockwell').replace('.cufon, .wsw h2, .wsw h3, .wsw h4, .wsw caption');
    Cufon.set('fontFamily', 'qlassik').replace('.calendar .day');
    Cufon.set('fontFamily', 'qlassik').replace('#menu > li > .normal', {
        textShadow: '1px 1px #bf8200',
        hover: {
            textShadow: '1px 1px #aa6300'
        }
    });
    Cufon.set('fontFamily', 'qlassik').replace('#menu > li > .selected', {
        textShadow: '1px 1px #086689',
        hover: {
            textShadow: '1px 1px #aa6300'
        }
    });

    // scroll
    $('div.scrollable').before('<a class="prevPage browse png"><!-- --></a>').after('<a class="nextPage browse png"><!-- --></a>')
    .scrollable({
        size: 3,
        speed: 500
    })
    .circular()
    //.mousewheel({speed: 100 } )
    .autoscroll({
        interval: 5000,
        steps: 3,
        autoplay: true,
        autopause: true
    });

    priceList.init();
    inputValue.init();
    customLightbox.init();
    externalLinks.init();
    trackLinks.init();

    try {
        DD_belatedPNG.fix('.png, .icon');
    }
    catch (e) {
    }

    $('.sportgrounds .free input').attr('checked', '');
    $('.sportgrounds .free').click(
      function()
      {
        if ( $(this).hasClass('checked') )
        {
          $(this).removeClass('checked').children('input').attr('checked', '');
        }
        else
        {
          $(this).addClass('checked').children('input').attr('checked', 'checked');
        }
      }
    );


	balanceMenu();


	
	/**
	 * FB INIT
	 */
	
	window.fbAsyncInit = function() {
        FB.init({
          appId  : '114471605242259',
          status : true, // check login status
          cookie : true, // enable cookies to allow the server to access the session
          xfbml  : true  // parse XFBML
        });

        // whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', function() {
          window.location.reload();
        });
        
        FB.Event.subscribe('auth.logout', function() {
          window.location.href = 'http://www.zlutelazne.cz/prihlaseni/';
        });
        
        
    };

    (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
    }());
	
	/**
	 * FB INIT
	 */
    
    


});
