/**
 * Console hooks
 */
if(typeof console != 'object')
{
	console = {};
	if( !console.hasOwnProperty('log') || typeof console.log != 'function')
	{
		console.log = function(){ };
	}
	if( !console.hasOwnProperty('error') || typeof console.error != 'function')
	{
		console.error = function(){ };
	}
	if( !console.hasOwnProperty('group') || typeof console.group != 'function')
	{
		console.group = function(){ };
	}
	if( !console.hasOwnProperty('trace') || typeof console.trace != 'function')
	{
		console.trace = function(){ };
	}
	if( !console.hasOwnProperty('groupEnd') || typeof console.groupEnd != 'function')
	{
		console.groupEnd = function(){ };
	}
}

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 externalLinks = {
  config:
  {
    externalClass: 'external',
    titleAppend:   ' [odkaz na jiný web]'
  },
  init: function()
  {
    $('#main a[href^="http"]:not([href*='+window.location.host+'])').each(
      function()
      {
        $(this).addClass(externalLinks.config.externalClass ).attr('title', $(this).attr('title') + externalLinks.config.titleAppend );
      }
    );
  }
};

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

var mapPhotoSwitch = {
  init: function()
  {
  	if(typeof titlePhoto == 'undefined' || typeof titleMap == 'undefined')
  	{
  		return false;
  	}
  	
    $('.mapPhoto .map' ).hide();
    //$('.mapPhoto .photo' ).hide();
    $('.mapPhoto .map' ).append('<a href="#" class="switch">' + titlePhoto + '</a>' );
    $('.mapPhoto .photo' ).append('<a href="#" class="switch">' + titleMap + '</a>' );

    $('.mapPhoto .map .switch' ).click(
      function()
      {
        $(this).parent().hide();
        $(this).parent().next('.photo').show();
        return false;
      }
    );

    $('.mapPhoto .photo .switch' ).click(
      function()
      {
        $(this).parent().hide();
        $(this).parent().prev('.map').show();
        return false;
      }
    );
  }
};

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');
        }
      }
    );
  }
};


/**
 * Google maps class
 */
var gmap = {
	/**
	 * Push map data into stack
	 * @param {Object} id
	 * @param {Object} lat
	 * @param {Object} lon
	 * @param {Object} markerTitle
	 * @param {Object} address
	 * @param {Object} zoom
	 */
	push: function(id, lat, lon, markerTitle, address, zoom){
		var mdata = {
			id: id,
			lat: lat,
			lon: lon,
			markerTitle: markerTitle,
			address: address,
			zoom: zoom
		};
		gmap.stack[gmap.stack.length] = mdata;
		return mdata;
	},
	/**
	 * Show map
	 * @param {Object} id
	 * @param {Object} lat
	 * @param {Object} lon
	 * @param {Object} markerTitle
	 * @param {Object} zoom
	 */
	showMaps: function(){
		if (typeof(google) == 'undefined')
			return false;
		for (var i = 0; i < gmap.stack.length; i++)
		{
			var mdata = gmap.stack[i];
			//		map.ggeocoder = new google.maps.Geocoder();
			gmap.placeMap(gmap.stack[i]);
			//map.codeAddress(map.stack[i].address);
		}
	},
	placeMap: function(mdata){
		var myLatlng = new google.maps.LatLng(mdata.lat, mdata.lon);
		var myOptions = {
			zoom: mdata.zoom ? mdata.zoom : 14,
			center: myLatlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var ngmap = new google.maps.Map(document.getElementById(mdata.id), myOptions);
		var marker = new google.maps.Marker({
			position: myLatlng,
			map: ngmap,
			title: mdata.markerTitle
		});
	},
	stack: []
};


(function(){


	/**
	 *
	 * Equalizer plugin
	 *
	 */
	$.fn.equalize = function(rwdl, trueHeight){
		/**
		 * Equalizer class
		 * @param {Object} elements
		 * @param {Object} rwdl
		 */
		function HeightsEqualizer(elements, rwdl, trueHeight){
			var self = this;
			self.elements = elements;
			self.rwdl = typeof rwdl != 'undefined' ? rwdl : false;

			self.equalize = function(){
				var max = 0;
				$(self.elements).each(function(){
					if ($(this).css('min-height', '0').height('auto').height() > max)
					{
						max = $(this).height();
					}
				});
				if ( (typeof trueHeight != 'undefined' && trueHeight) || $.browser.msie && parseInt($.browser.version) < 7)
				{
					$(self.elements).each(function(){
						var cmax = max - ( $(this).css('padding-top') + $(this).css('padding-bottom') );
						$(this).height(cmax + 'px');
					});
				}
				else
				{
					$(self.elements).each(function(){
						var cmax = max - ( $(this).css('padding-top') + $(this).css('padding-bottom') );
						$(this).css('min-height', max + 'px');
					});
				}
			};

			self.equalize();

			if (self.rwdl)
			{
				self.timer = window.setInterval(function(){
					try
					{
						self.equalize();
					}
					catch (e)
					{
					}
				}, 50);
				$(window).load(function(){
					window.clearInterval(self.timer);
				});
			}
		};

		/*
		 * Instantiante
		 */
		new HeightsEqualizer($(this), rwdl, trueHeight);
	};

	
	/**
	 * Accordion
	 *
	 * @param {Object} config
	 */
	$.fn.accordion = function(config){
	
		function accordion(wrapper, config)
		{
			var self = this;
	
			// Apply config
			self.config = $.extend({
				speed: 300,
				shadowFade: 300/2,
				contentFade: 120,
				autoSlideInterval: 7000
			}, config);
			
			self.wrapper = wrapper;
			self.items = self.wrapper.find('.item');
			self.itemsCount = self.items.length;
			self.wrapperWidth = self.wrapper.width();
			self.locked = false;
			self.autoSlideEnabled = true;
			self.openedSlide = -1;
			self.prevOpenedSlide = -1;
			
			/*
			 * Support functions 
			 */
			self._slideGetWidth = function(){
				return Math.ceil(self.wrapperWidth / self.itemsCount);
			};
			self._slideGetLeft = function(slide){
				return slide.index() * self.slideWidth;
			};
			self._slideGetContent = function(slide){
				return slide.children('.contentA');
			};
			self._slideGetShadow = function(slide){
				return slide.children('.shadow');
			};
			self._slideGetClose = function(slide){
				return slide.find('.close');
			};
			
			/**
			 * Place items to space
			 */
			self.placeItems = function(){
				self.slideWidth = self._slideGetWidth();
				self.items.width(self.slideWidth);
				self.items.each(function(i){
					self._slideGetContent($(this)).hide();
					$(this).css('left', self._slideGetLeft($(this))); // ABS
				});
			};
			
			/**
			 * Expand some slide
			 */
			self.expandSlide = function(slide){
				
				var shadow = self._slideGetShadow(slide);
				
				// Fade out
				shadow.fadeOut(self.config.shadowFade);
				
				slide.css('z-index', 2); // ABS

				 // Expand slide
				slide.animate({
					width: self.wrapperWidth,
					left: 0 // ABS
					//,'background-position': '0px 0'
				}, {
						duration: self.config.speed,
			      step: function(now, fx){
			      	if(fx.prop=='left')
			      	{
			      		$(fx.elem).css('background-position', '-'+now+'px 0');
			      	}
			      }
					}).queue(function(){
					
					// Slide content fade in
					self._slideGetContent(slide).fadeIn(self.config.contentFade).queue(function(){
						slide.addClass('opened');
						slide.removeClass('opening');
						self.locked = false;
						
						slide.find('#projectOfTheYear').slideUp(0).slideDown(200);
						
						$(this).dequeue();
					});
					
					$(this).dequeue();
				});
				
				self.prevOpenedSlide = slide.index();
			};
			
			/**
			 * Collapse some slide
			 */
			self.collapseSlide = function(slide){
				
				var shadow = self._slideGetShadow(slide);
				
				slide.find('#projectOfTheYear').slideDown(0).slideUp(200);
							
				// Slide content fade out
				self._slideGetContent(slide).fadeOut(self.config.contentFade).queue(function(){ 
					
					// Fade out
					shadow.delay(self.config.shadowFade).fadeIn(self.config.shadowFade);
						
						// Slide collapse
						slide.animate({
							width: self.slideWidth,
							left: self._slideGetLeft(slide)
						}, {
							duration: self.config.speed,
				      step: function(now, fx){
				      	if(fx.prop=='left')
				      	{
				      		$(fx.elem).css('background-position', '-'+now+'px 0');
				      	}
				      }
						}).queue(function(){
							slide.removeClass('opened');
							slide.removeClass('opening');
							self.locked = false;
							slide.css('z-index', 1); // ABS
							
						
							$(this).dequeue();
						});
							
						$(this).dequeue();
					});
					/*	
					$(this).dequeue();
				});*/
			};
			
			/**
			 * Cycle between slides
			 */
			self.cycleSlides = function(){
				var index = self.openedSlide;
				if(index >= self.itemsCount-1)
				{
					index = 0;
				}
				else
				{
					index++;
				}
				self._slideGetClose(self.items.eq(self.prevOpenedSlide)).click();
				setTimeout(function(){ self.items.eq(index).click(); }, self.config.speed+self.config.contentFade);
				//self.items.eq(index).click();
				self.openedSlide = index;
			};
			
			/**
			 * Init autoslide process
			 */
			self._initAutoslide = function(){
				if(self.config.autoSlideInterval)
				{
					self.intervalHandler = window.setInterval(function(){
							self.cycleSlides();
					}, self.config.autoSlideInterval);
				}
			};
			
			/*
			 * Bindings
			 */
			self.items.bind('click', function(evt){
				if(evt.target == evt.currentTarget){
					if(!self.locked)
					{
						var slide = $(this);
						slide.addClass('opening');
						self.locked = true;
						self.openedSlide = slide.index();
						self.expandSlide(slide);
						/*
						setTimeout(function(){
							self.collapseSlide(slide);
						}, 2000);
						*/
					}
				}
			});
			self.items.each(function(){
				var slide = $(this);
				self._slideGetClose(slide).click(function(){
					self.collapseSlide(slide);
					self.openedSlide = slide.index();
				});
			});
			

			// Pause autoslide when hovered
			self.wrapper.hover(function(){
				clearInterval(self.intervalHandler);
				self.autoSlideEnabled = false;
			}, function(){
				self.autoSlideEnabled = true;
				self._initAutoslide();
			});
			
			self.placeItems();
			self._initAutoslide();
	
			return self;
		}
	
		return new accordion($(this), config);
	};
	
		
	/**
	 * GuidePost tweaks
	 *
	 * @param {Object} config
	 */
	$.fn.guidePost = function(config){
	
		function guidePost(wrapper, config)
		{
			var self = this;
	
			// Apply config
			self.config = $.extend({
				speed: 300
			}, config);
			
			self.wrapper = wrapper;
			self.items = self.wrapper.find('li');
			
			/*
			 * Support functions 
			 */
			self._getItemContent = function(item){
				return item.children('p');
			};
			
			self.wrapper.removeClass('nojs');
			
			self.items.hoverIntent(function(){
				self._getItemContent($(this)).slideDown(self.config.speed);
			}, function(){
				self._getItemContent($(this)).slideUp(self.config.speed);
			});
	
			return self;
		}
	
		return new guidePost($(this), config);
	};	
	
})(jQuery);

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

  $('#page').prepend('<a href="#content" accesskey="0" class="forBlind">Přejít na obsah<'+'/a>');
  Cufon.replace('.cufon, .wsw h2, .wsw h3, .wsw h4, .wsw h5', { hover: true });
  
  ACC = $('#accordion').accordion();
  $('#accordion .contentB').css('visibility', 'visible');
  $('#guidePost').guidePost();
  
	$(window).resize(function(){
		var minwidth = $('#accordion').width();
		var wwidth = $(window).width();
		if( wwidth < minwidth ){
			$('#accordionWrap').width( wwidth );
			$('#accordion').css('margin-left', (wwidth-minwidth)/2);
		}
		else
		{
			$('#accordionWrap').width('auto');
			$('#accordion').css('margin', '0 auto');
		}
	}).resize();
  
  /* TABLE TR TABLE COLOR */
  
  $("tr:even").css("background-color", "#f8f8f8");
  
  
  /* MILESTONES */
  
  $('#milestones a').click(function(){
    $(this).toggleClass('active');
    $(this).next('p').toggle();
    if($(this).parent().find('p:visible').length)
    {
       $(this).parent().addClass('active');    
    }
    else
    {
      $(this).parent().removeClass('active');
    }
    return false;    
  });
  
  
  /* ORGANIZATION STRUCTURE */
  
  $('#ngl').click(function(){
    $('#nglBox').show();
    return false;    
  });
  
  $('#nig').click(function(){
    $('#nigBox').show();
    return false;    
  });
  
  $('#npe').click(function(){
    $('#npeBox').show();
    return false;    
  });
  
  $('.hiddenBox').click(function(){
    $('#nglBox, #nigBox, #npeBox').hide();
    return false;    
  });
      
  
  //externalLinks.init();
  trackLinks.init();
  //mapPhotoSwitch.init();
  inputValue.init();
  
  $('.personBox').each(function(){
  	$(this).find('.inner').equalize();
  });

  $('.keyProjectBox').each(function(){
  	$(this).find('.inner').equalize();
  });


  // Photogallery
  $('.photogallery').filter(function(){
    return !$(this).parent().is('#gallery');
  }).find('.inner').each(function(){
  	if( $(this).children().children().length > 3)
	{
		$(this).after('<span class="prevPage"><!-- --></span><span class="nextPage"><!-- --></span><p class="navi"><!-- --></p>');
  	$(this).scrollable({ size: 3, speed: 400 }).circular().navigator();
	}
  });
  // Disable gallery autocsroll on item click
  $('.photogallery li').unbind('click');
  
  
  /* FANCYBOX */
  $(".fancybox").fancybox({
  	prevEffect: 'fade',
  	nextEffect: 'fade'
  });

});

window.onload = function(){
  if (typeof(gmap) != 'undefined')
	{
		gmap.showMaps();
	}
};

