

jQuery.noConflict( );



var blank = {
  config:
  {
    wrapperId: '#wrapper'
  },
  init: function()
  {
    if(!jQuery(this.config.wrapperId).length) return false;
  }
};

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

//find max value in array
var max = function(array)
{
  var mxm = array[0];
  for (i = 0; i < array.length; i++) 
  {
    if (array[i] > mxm) 
    {
      mxm = array[i];
    }
  }
  return mxm;
 };

//preloader of images
var preloader = {
  load: function(source)
  {
    var key = this.images.length;
    this.images[key] = new Image();
    this.images[key].src = source;
  },
  images: new Array()
};

//auto rollovers
var imageHover = {
  elementsFilter: '*[src*=but_]',
  replaceSrcNormal: '.png',
  replaceSrcHover:  '_hover.png',
  init: function()
  {
    if(!jQuery(this.elementsFilter).length) return false;
    jQuery(this.elementsFilter).each(function(key){
      imageHover.images[key] = new Image();
      imageHover.images[key].src = jQuery(this).attr('src').replace(imageHover.replaceSrcNormal,imageHover.replaceSrcHover);
      if(imageHover.isLoaded(imageHover.images[key]))
      {
        jQuery(this).hover(
          function(){ jQuery(this).attr('src',jQuery(this).attr('src').replace(imageHover.replaceSrcNormal,imageHover.replaceSrcHover)); },
          function(){ jQuery(this).attr('src',jQuery(this).attr('src').replace(imageHover.replaceSrcHover,imageHover.replaceSrcNormal)); }
        );
      }
    });
  },
  isLoaded: function(el)
  {
     if (!el.complete) {
        return false;
     }
     if (typeof el.naturalWidth != "undefined" && el.naturalWidth == 0) {
        return false;
     }
     return true;
  },
  images: new Array()
};

var autoTableHover = {
  config:
  {
    table: '.autoHover',
		hoverClass: 'hover'
  },
	settings:
	{
		rowClick: false
	},
  init: function(settings)
  {
    if(!jQuery(this.config.table).length) return false;
		this.settings = settings;
		jQuery(this.config.table+' tr').hover(function(){ jQuery(this).addClass(autoTableHover.config.hoverClass); },function(){ jQuery(this).removeClass(autoTableHover.config.hoverClass); })
		if(this.settings.rowClick)
			jQuery(this.config.table+' tr').each(function(){ jQuery(this).children().css('cursor','pointer').click(function(){ window.location = jQuery(this).parent().find('a').get(0).href }) })
  }
};

// pridat stranku do zaloziek
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;
}
/*
<a href="#" onclick="return AddFavorite(this,'http://<?=jQuery_SERVER['HTTP_HOST'].jQuery_SERVER['PHP_SELF'].(jQuery_GET['lang']?'?lang='.jQuery_GET['lang']:'')?>','Energy 21 - <?=jQuerytitle?>');">Přidat do oblíbených</a>
*/

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/lightbox-blank.gif',
    containerResizeSpeed:200,
    txtImage:'Obrázek:<br />',
    txtOf:'z',
    keyToClose:'c',
    keyToPrev:'p',
    keyToNext:'n',
    imageArray:[],
    activeImage:0
  },
  init: function()
  {
    jQuery('a[rel=lightbox]').lightBox(customLightbox.config); //only rel="lightbox"
    var lbRels = new Array();  var thisRel = ''; var trIsIn = false;
    jQuery('a[rel*="lightbox["]').each(function(){ //each rel="lightbox[..."
        thisRel = jQuery(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] = jQuery(this).attr('rel').replace('lightbox[','').replace(']',''); //not i array of rels => store rel
    });
    for(i=0; i<lbRels.length; i++) { jQuery('a[rel="lightbox['+lbRels[i]+']"]').lightBox(customLightbox.config); } //each unique rel => apply lightbox
  }
};

var inputImageClickFix = {
  init: function()
  {
    jQuery('*:image').click(function(){ inputImageClickFix.submitEvent(jQuery(this)); return false; })
  },
  submitEvent: function(e)
  {
    e.parents('form').submit();
  }
};

var articleSlider = {
  config:
  {
    wrapperEl: '#articlesSlider .articlesOuter',
    innerEl: '#articlesSlider .articlesInner',
    itemsEl: '#articlesSlider .item',
    totalEl: '#articlesSliderTotal',
    currentEl: '#articlesSliderCurrent',
    sliderControlsEl: '#articleSliderControlsInner',
    prevEl: '#articlesSliderPrev',
    nextEl: '#articlesSliderNext',
    maxItems: 22,
    dotWidth: 13,
    pagerWidthOffset: 90,
    sliderHTML: '<div id="articleSliderControls"><div id="articleSliderControlsInner"><span id="articlesSliderPager"><span id="articlesSliderTotal"><span id="articlesSliderCurrent"><!--  --></span></span></span><a href="#" id="articlesSliderPrev"><span class="forBlind">&lt;</span></a><a href="#" id="articlesSliderNext"><span class="forBlind">&gt;</span></a></div></div>'
  },
  init: function()
  {
    if( !jQuery(articleSlider.config.wrapperEl).length ) return false;
    
    jQuery(articleSlider.config.itemsEl+':gt('+( articleSlider.config.maxItems - 1 )+')').remove();
    articleSlider.totalCount = jQuery(articleSlider.config.itemsEl).length;
    
    if(articleSlider.totalCount <= 1) return false;

    articleSlider.frameWidth = jQuery(articleSlider.config.itemsEl+':first').width();
    
    jQuery(articleSlider.config.wrapperEl).after(articleSlider.config.sliderHTML);
    
    jQuery(articleSlider.config.totalEl).width( articleSlider.totalCount * articleSlider.config.dotWidth );
    
    jQuery(articleSlider.config.sliderControlsEl).width( articleSlider.totalCount * articleSlider.config.dotWidth + articleSlider.config.pagerWidthOffset );
    
    jQuery(articleSlider.config.prevEl).click(function(){ articleSlider.slidePrev(); return false; });
    jQuery(articleSlider.config.nextEl).click(function(){ articleSlider.slideNext(); return false; });

    
  },
  slidePrev: function()
  {
    if(articleSlider.lock) return false;
    
    articleSlider.lock = true;
    if(articleSlider.current>0)
    {
      articleSlider.current--;
    }
    else
    {
      articleSlider.current = articleSlider.totalCount - 1;
    }
    articleSlider.setPager(articleSlider.current);
    articleSlider.slide(articleSlider.current);
  },
  slideNext: function()
  {
    if(articleSlider.lock) return false;
    
    articleSlider.lock = true;
    if(articleSlider.current<articleSlider.totalCount-1)
    {
      articleSlider.current++;
    }
    else
    {
      articleSlider.current = 0;
    }
    articleSlider.setPager(articleSlider.current);
    articleSlider.slide(articleSlider.current);
  },
  slide: function()
  {
    jQuery(articleSlider.config.innerEl).animate({ marginLeft: - articleSlider.current * articleSlider.frameWidth + 'px' }).queue(function(){
      articleSlider.lock = false;
      jQuery(this).dequeue();
    });
  },
  setPager: function(n)
  {
    jQuery(articleSlider.config.currentEl).css('left', articleSlider.config.dotWidth * n);
  },
  current: 0
};

var selectReplace = {
  init: function(select, seo)
  {
    if(!jQuery(select).length) return false;

    selectReplace.selectName = jQuery(select).attr('name');

    selectReplace.list = '<div id="selectReplaced">';
    selectReplace.list += '<p id="current_selection">&nbsp;</p>';
    selectReplace.list += '<ul id="select_list">';
    jQuery(select).children('option').each(function(){
        if(jQuery(this).attr('selected'))
        {
          selectReplace.selectAfterVal = jQuery(this).attr('value');
          selectReplace.selectAfterName = jQuery(this).text();
        }
        selectReplace.list += '<li class="lang'+jQuery(this).attr('value')+'"><span onclick="selectReplace.select(\''+jQuery(this).attr('value')+'\', \''+jQuery(this).text()+'\')">'+jQuery(this).text()+'</span></li>'
    });
    selectReplace.list += '</ul></div>';

    jQuery(select).after('<input type="hidden" name="'+selectReplace.selectName+'" id="selected_stack" />');
    jQuery(select).replaceWith(selectReplace.list);
    if(selectReplace.selectAfterVal)
    {
      selectReplace.select(selectReplace.selectAfterVal, selectReplace.selectAfterName);
    }
    jQuery('#current_selection').click(function(){selectReplace.open()});
    jQuery('#select_list').hide();

    if(seo)
    {
      jQuery('#selectReplaced').parents('form').bind('submit', function(){
        var link = jQuery('#selectReplaced').parents('form').serialize().split('=');
        link = link[1]+'/';
        var url = String(document.location).split('/');
        var urlComplete = '';
        for(i=0; i<4; i++)
        {
          urlComplete += url[i]+'/';
        }
        window.location.href = urlComplete+link+'#content';

        return false;
      });
    }
  },
  select: function(value, name)
  {
    jQuery('#selected_stack').attr('value', value);
    jQuery('#current_selection').text(name);
    selectReplace.close();
    if(selectReplace.canSubmit)
    {
      jQuery('#selectReplaced').parents('form').submit();
    }
  },
  open: function()
  {
    jQuery('#select_list').toggle();
    selectReplace.canSubmit = true;
  },
  close: function()
  {
    jQuery('#select_list').hide();
  }
};

//--------------------------------------------------------------------------


// pridat stranku do zaloziek
/* 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;
} */
//--------------------------------------------------------------------------


function show_map(map_element_id, gps1, gps2, zoom) {
	if (typeof(GBrowserIsCompatible)=='function' && GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById(map_element_id));
		var pozice = new GLatLng(gps1, gps2); //seskladani pozice
//		var companyMarker = new GIcon();
//		companyMarker.image= "/images/logo-smartcompanies.png";
//		companyMarker.iconSize = new GSize(55, 52); //width, height
//		companyMarker.iconAnchor = new GPoint(6, 20);
//		companyMarker.infoWindowAnchor = new GPoint(5, 1);
		var marker = new GMarker(pozice)//, companyMarker);
      	//var companyMarker = createMarker(pozice, companyMarkerImage, companyMarkerSize);
		map.addControl(new GSmallMapControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,20))); //tlacitka pozice, nastaveni pozice tlacitek, paddingy
		map.addControl(new GMapTypeControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,0))); //tlacitka typ
		map.setCenter(pozice, zoom); //nastaveni stredu mapy
		map.addOverlay(marker); //nastaveni markeru na pozici
//		GEvent.addListener(map, "click", function() {
//	      window.location.href='http://maps.google.com/maps?f=q&hl=cs&geocode=&time=&date=&ttype=&q=Kon%C4%9Bvova+2660%2F141,+Praha&sll=37.0625,-95.677068&sspn=33.435463,81.738281&ie=UTF8&ll=50.091787,14.474809&spn=0.006608,0.019956&z=16&iwloc=addr&om=0';
//	    });
	}
}


var officeMapPhoto = {
	init: function()
	{
		jQuery('.boxOfficeInfo .colRight .officePhoto').hide();
		jQuery('.buttonShowOfficeMap').click(function(){ officeMapPhoto.showMap( jQuery(this) ); });
		jQuery('.buttonShowOfficePhoto').click(function(){ officeMapPhoto.showPhoto( jQuery(this) ); });
	},
	
	showMap: function(el)
	{
		var col = el.parents('.colRight');
		col.find('.buttonShowOfficePhoto').removeClass('buttonSelected');
		el.addClass('buttonSelected');
		col.find('.officePhoto').hide();
		col.find('.officeMap').show();
	},
	
	showPhoto: function(el)
	{
		var col = el.parents('.colRight');
		col.find('.buttonShowOfficeMap').removeClass('buttonSelected');
		el.addClass('buttonSelected');
		col.find('.officePhoto').show();
		col.find('.officeMap').hide();
	}
}


var cSelection = {
	init: function()
	{
    if(!jQuery('#companySelection').length) return false;
    jQuery('#companySelection').find('.info').hide(); 
    jQuery('#companySelection .mmore').click(function(el){ jQuery(this).parents('.mswitch').addClass('sless').removeClass('smore').parents('.col').find('.info').show();  return false; });
    jQuery('#companySelection .mless').click(function(el){ jQuery(this).parents('.mswitch').addClass('smore').removeClass('sless').parents('.col').find('.info').hide();  return false; });
	}
}


var formRegistration = {
	init: function()
	{
    if(!jQuery('#formRegistrationA').length) return false;
    jQuery('#formRegistrationA').show(); 
    jQuery('#formRegistrationB').hide(); 
    jQuery('#formRegistrationA button').click(function(el){ jQuery('#formRegistrationA').hide();  jQuery('#formRegistrationB').show();  return false; });
	}
}

var bLogin = {
	init: function()
	{
    if(!jQuery('#loginBox').length) return false;
    jQuery('#userLogin').hide(); 
    jQuery('#userAccount .button a').click(function(el){ jQuery('#userLogin').show(); jQuery('#userAccount').hide();   return false; });
	}
}

var bHelp = {
	init: function()
	{
    if(!jQuery('#helpBox #helpSupport').length || !jQuery('#chatBox').length ) return false;
		jQuery('#helpBox #helpSupport').click(function(){ jQuery('#helpBox').hide(); jQuery('#chatBox').show(); return false; });
	  	jQuery('#chatBox').hide();
	}
}

var balanceCols = {
	balance: function(ela, elb)
	{
    if(!ela.length||!elb.length) return false;
   
    if( jQuery.browser.msie && jQuery.browser.version <= 6 )
      var minHeightAttr = 'height';
    else
      var minHeightAttr = 'min-height';
      
    if( ela.height() > elb.height() )
    {
      elb.css(minHeightAttr, ela.height() );
      ela.css(minHeightAttr, ela.height() );
    }
    else if(ela.height() < elb.height())
    {
      ela.css(minHeightAttr, elb.height() );
      elb.css(minHeightAttr, elb.height() );
    }
	}
}

var outgoingTracker = {
  config:
  {
    externalClass: 'externalTracker',
    titleAppend:   ' [odkaz na jiný web]'
  },
  init: function()
  {
    jQuery('a[href^="http"]:not([href*='+window.location.host+'])').each(
      function()
      {
        // pridame class a title
        jQuery(this).addClass(outgoingTracker.config.externalClass ).attr('title', jQuery(this).attr('title') + outgoingTracker.config.titleAppend );
        jQuery(this).click(
          function()
          {
            // ulozime do GA
            if(typeof(pageTracker)=='object')
            {
              pageTracker._trackPageview(jQuery(this).attr('href').replace(/(http|https):\/\//, '\/out\/' ) );
            }
          }
        );
      }
    );
  }
};

function openNewWin(form)
{
  var url = form.attr('action');
  var get = form.serialize();
  isNewWin = window.open(url+'?'+get);
  return (typeof(isNewWin)=='object') ? true : false;
}


/**
 * Promptchat window hiding and displaying
 */
var pcControls = {
	init: function(){
		pcControls.chatWindow = jQuery('#promptChatWindow');
		pcControls.chatControls = jQuery('#promptChatControls');
		if(pcControls.isActive())
		{
			pcControls.open();
		}
		else
		{
			pcControls.close();
		}	
		pcControls.chatControls.find('a').click(function(){ pcControls.open(); return false; });
	},
	postCheck: function()
	{
		if(pcControls.isActive())
		{
			pcControls.open();
		}
	},
	isActive: function(){
		return pcControls.chatWindow.find('.chat_log').children().length > 0 ? true : false;
	},
	open: function()
	{
		pcControls.chatControls.fadeOut(200);
		pcControls.chatWindow.fadeIn(200);
		pcControls.opened = true;
	},
	close: function()
	{
		pcControls.chatWindow.hide();	
		pcControls.opened = false;	
	}
};

/**
 * Video GA tracking
 * 
 * http://developer.longtailvideo.com/trac/wiki/Player4Api#Sendingevents
 * http://developer.longtailvideo.com/trac/wiki/Player4Events#Viewevents
 * 
 * Tracking only for one video player on page.
 * 
 */
var  videoTracking = {	
	evtdata: {
		category: 'Video',
		action: 'Spustit',
		actionStop: 'Přehráno do konce',
		value: 1
	},
	init: function()
	{	
		videoTracking.player = jQuery('.flashPlayerObject').get(0);
		if( typeof(videoTracking.player)!='undefined' && videoTracking.player!=null )
		{
			videoTracking.bindEvents();
		}
	},
	bindEvents: function()
	{
		if(typeof(videoTracking.player.addViewListener)!='undefined')
		{
			if( !videoTracking.binded ) 
			{
				videoTracking.player.addViewListener('PLAY','videoTracking.detectPlayEvent');
				videoTracking.player.addModelListener('STATE','videoTracking.detectStopEvent');
				videoTracking.binded = true;
			}
		}
		else
		{
			window.setTimeout(function(){ videoTracking.bindEvents(); }, 100);
		}
	},
	detectPlayEvent: function()
	{
		videoTracking.evtdata.label = jQuery(videoTracking.player).parent().parent().find('.title').text();
		if(! videoTracking.played)
		{
			videoTracking.trackEvent(videoTracking.evtdata.category, videoTracking.evtdata.action, videoTracking.evtdata.label, videoTracking.evtdata.value);
		}
		videoTracking.played = true;
	},
	detectStopEvent: function(evt)
	{
		if(evt.newstate == 'COMPLETED')
		{
			videoTracking.trackEvent(videoTracking.evtdata.category, videoTracking.evtdata.actionStop, videoTracking.evtdata.label, videoTracking.evtdata.value);
		}
	},
	trackEvent: function(a, b, c, d)
	{
		if(typeof(_gaq)=='object' && typeof(_gaq.push)=='function' )
		{
			log(a+b+c+d);
			_gaq.push(['_trackEvent', a, b, c, d]);
		}
	},
	binded: false,
	played: false
};

jQuery(document).ready(function() {     

	pcControls.init(); 
	
	
  articleSlider.init();

  outgoingTracker.init();

  officeMapPhoto.init();
  
  if(GLANG!='ru')
  {
    Cufon.replace('#topHeading .lineB', { fontFamily: 'Franklin Gothic Book' });
    Cufon.replace('#topHeading .lineA,.secondaryTitle,.boxTitle,.mainTitle,.bigTitle', { fontFamily: 'Franklin Gothic Demi' });
  }
  
  //jQuery(".inFieldLabel").addClass('inFieldLabelActive').find('label').inFieldLabels();
  jQuery(".inFieldLabel").addClass('inFieldLabelActive').find('label').removeClass('hidden').inFieldLabels();
  
  selectReplace.init('#selectLanguage', false);
 
	cSelection.init();
	bLogin.init();
	formRegistration.init();
	bHelp.init();

	balanceCols.balance( jQuery('.splitBox .colA .sboxTitle'), jQuery('.splitBox .colB .sboxTitle') );
	balanceCols.balance( jQuery('.splitBox .colA .sboxContent'), jQuery('.splitBox .colB .sboxContent') );
  
  jQuery('#mSlider').cSlider({
		inner: '.sliderInner',
		controlsAfter: '#mSlider .sliderInner',
		autoSlideTimer: 8000
		//,debug: true
	});
	
	
  
  //videoTracking.init();
  
});


window.onload = function() { 
	if( jQuery('#officeBrnoMap').length )
		show_map('officeBrnoMap', 49.199485, 16.599634, 13);
	if( jQuery('#officeOstravaMap').length )
		show_map('officeOstravaMap', 49.839285, 18.306195, 13);
	if( jQuery('#officePragueMap').length )
		show_map('officePragueMap', 50.091705, 14.474823055555555, 13);
};
