//$.noConflict();
jQuery(document).ready(function(){
	
	loginEngine();
	searchEngine();
	menuEngine();
	checkWeatherCookie();
	changeCityWeatherHead();
	weatherEngine();
	hoverEngine();
	tabbed_Boxs_Engine();
	
	if (jQuery('.foreFrontTabs_Box').size() > 0) {
		foreFrontTabEngine();
	}
	
	if (jQuery('.modernSlider_box').size() > 0) {
		modernSliderEngine();
	}

    jQuery('#searchRoller').bind('click', function() {
       	if(jQuery('#weatherCities').is(':visible')) {
       		jQuery('#weatherCities').slideUp('200');
       	}else {
       		jQuery('#weatherCities').slideDown('200', function() {
       			jQuery(this).bind('mouseleave click', function() {
       				jQuery('#weatherCities').slideUp('200');
       			});					
       		});
       	}
    });
	
    jQuery('.elementHeader_More').bind('mouseenter', function() {
		var sFilePath = jQuery(this).attr('src');
		var sPath = jQuery(this).attr('src').substring(0, jQuery(this).attr('src').lastIndexOf('/') + 1);
		var aFile = jQuery(this).attr('src').substring(jQuery(this).attr('src').lastIndexOf('/') + 1).split('.');
		//alert(sPath + aFile[0] + '_hover.' + aFile[1]);
		jQuery(this).attr('src', sPath + aFile[0] + '_hover.' + aFile[1]);
		jQuery('.elementHeader_More').bind('mouseleave', function() {
			//alert(sPath + aFile[0] + '.' + aFile[1]);
			jQuery(this).attr('src', sPath + aFile[0] + '.' + aFile[1]);
		});
	});

	if (jQuery('.newsFlash_Box').size() > 0) {
		newsFlashEngine();
	}

	if (jQuery('.mainTopic_Box').size() > 0) {
            if(!jQuery('.mainTopic_Box .mainTopic_Top').hasClass('mainTopic2_Top_specialReport')) {
                mainTopicEngine();
            }
	}

	mostTabbedEngine();
	TabbedEngine();

	if (jQuery('.slider_Box').size() > 0) {
		sliderInit();
	}
	
	if (jQuery('.galleryRotator_Box').size() > 0) {
		galleryRotatorInit();
	}

	if (jQuery('.mostViewedTabs_Box').size() > 0) {
		modernMostViewedInit();
	}
	if(jQuery('.logosRotatorItem').size() > 0){
		prefooterLogoRotator();
	}
	confDialogBox();
	setAsHomepageInit();

	footerLogoInit();
	
	poll();
	
	if(jQuery('#recommendationIcon').size() > 0){
		recommendations();
	}
	if(jQuery('#story').size() > 0){
		fontSize();
		showCopyright();
		slidingPopUp();
	}
	if (jQuery('.galleryTab_Box').size() > 0) {
		photoGalleryTabEngine()
	}
	
	showCI();
	
	// Okienko dla quotationTable wyświeltające mini wykres notowań.
	jQuery('body').append('<div id="mxmenu" style="position: absolute; visibility: visible;" onMouseover="clearhidemenu();" onMouseout="dynamichide(event)"></div>')
	
	if (jQuery('.searchPersonBox').size() > 0) {
		searchPersonBox()
	}
	if (jQuery('.askQuestion').size() > 0) {
		askQuestionInit()
	}
	
	recommendations_ForeFront();
	
	if(jQuery('.newsletterInputFld').size() > 0){
		jQuery('.newsletterInputFld').bind('focus', function(){
			jQuery(this).val('');
		});
	};
});

function hoverEngine() {
    if(jQuery.browser.msie && (parseInt(jQuery.browser.version) == '6')) {
        jQuery('.returnButton, .submitBtn, .submitForm').each(function(){
            var $this = jQuery(this);
            var objClassName = this.className;

            $this.bind('mouseover', function(){
                $this.addClass(objClassName + 'Hover');
            });

            $this.bind('mouseout', function(){
                $this.removeClass(objClassName + 'Hover');
            });
        });
    }
}

function setAsHomepageInit() {
	if(navigator.userAgent.match('Firefox')) {
		//alert(navigator.userAgent);
		jQuery('#startBox').fadeIn(200);
		jQuery('#startBox').bind('click', function() {
			setAsHomepageEngine();
		})
	}
}

function setAsHomepageEngine() {
	//alert('KLIK');
	jQuery('#dialogBox').addClass('dialogBox_homepage');
	sImg = '<img src="http://www.rp.pl/static/img/layout/instrukcja_pc.jpg" width="534" height="497">';
	jQuery('#dialogBody').html(sImg);
	setDialogBox('Ustaw stronÄ™ jako startowÄ…', '');
}

function modernMostViewedInit() {
	jQuery('.mostViewedTabs_Tab').bind('click', function() {
		if(!jQuery(this).hasClass('mostViewedTabs_ActiveTab')) {
			jQuery('.mostViewedTabs_Tab').removeClass('mostViewedTabs_ActiveTab');
			jQuery(this).addClass('mostViewedTabs_ActiveTab');
			
			var nTab = jQuery('.mostViewedTabs_Box').find('li').index(jQuery(this));
			jQuery('.mostViewedContent_ActiveElement').slideUp(200, function() {
				jQuery('.mostViewedContent_Element').removeClass('mostViewedContent_ActiveElement');
				jQuery('#mostViewedContent_' + nTab).slideDown(200).addClass('mostViewedContent_ActiveElement');
			});
		}
	});
}

function poll() {
	jQuery('.pollCharts .pollChart_Body').each(function() {
	    var pollid = jQuery(this).attr('id');
		pollid = pollid.replace("poll_","");
		var values = "";
		var votes = "";
		jQuery("form#poll_"+pollid+" > ul li label span").each(function(index) {
		  values+=jQuery(this).text()+";";
		});
		values = values.substring(0, values.length-1);
		jQuery("form#poll_"+pollid+" > ul li input.answerCount").each(function(index) {
			votes+=jQuery(this).val()+";";
		});
		votes = votes.substring(0, votes.length-1);
		// Sprawdz czy jest cookies sondy
		if (checkPollCookie(pollid) ) {			// cookies nie ma, ruchamiamy funckje ktĂłra wysle glosowanie i pokaze wyniki
			jQuery('form#poll_'+pollid+' button#submit_'+pollid).bind('click', function() {
				  jQuery("form#poll_"+pollid+" > ul li label input").each(function(index) {
					if( jQuery(this).attr('checked')=='checked' ) {
						sendDatePoll('vote='+jQuery(this).attr('value')+'&idpoll='+pollid+'&values='+values+'&votes='+votes,pollid);
					}
				  });
			      setCookie("poll_"+pollid,pollid,4);
			});
		}else {									// cookies jest, uruchamiamy funckje ktĂłra pokaze wyniki
			sendDatePoll('vote=-1&idpoll='+pollid+'&values='+values+'&votes='+votes,pollid);
		}
	});
}
function sendDatePoll(datePoll,idpoll) {
	jQuery.ajax({
		type: "GET",
		url: "/commonService/sonda",
		async:false,
		data: datePoll,
		success: function(data){
		  var xml = data,
		      xmlDoc = jQuery.parseXML( xml ),
		      $xml = $( xmlDoc ),
		      $set = $xml.find( 'set' );
		  $list = jQuery('form#poll_'+idpoll).find('ol.legend');
		  $set.each(function(index) {
		    $list.append('<li style="background-color:#'+jQuery(this).attr('color')+';"><span style="background-color:#fff;">'+jQuery(this).attr('name')+' (Głosy:'+jQuery(this).attr('value')+')</span></li>');
		  });
		  var flashvars = {dataXML:data,chartWidth:"230",chartHeight:"130"};
		  var params = {wmode: "transparent",quality: "high"};
		  swfobject.embedSWF("/static/flash/poll/FCF_Bar2D.swf", "chart"+idpoll, "230", "130", "8.0.35.0", "", flashvars, params, "");
		  jQuery('form#poll_'+idpoll+' button#submit_'+idpoll).hide();
		  jQuery('form#poll_'+idpoll+' ul').hide();
		}
	});
}

function getCookie(c_name) {
  var i,x,y,ARRcookies=document.cookie.split(";");
  for (i=0;i<ARRcookies.length;i++) {
	x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	x=x.replace(/^\s+|\s+$/g,"");
	if (x==c_name) {
	  return unescape(y);
	}
  }
}
function setCookie(c_name,value,exdays) {
	var exdate=new Date();
	exdate.setHours(exdate.getHours() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}
function checkPollCookie(name) {
	var cookie_poll=getCookie("poll_"+name);
	if (cookie_poll==null) return true;
    else return false;
}
function checkCookie(name) {
	var cookie_poll=getCookie(name);
	if (cookie_poll==null) return true;
    else return false;
}

function loginEngine() {
	var errorShown = false;
	
	jQuery('#loginInput').bind('focus', function() {
		jQuery(this).val('').addClass('loginInputActive');
	});
	
	jQuery('#smscodeInput').bind('focus', function() {
		jQuery(this).val('').addClass('loginInputActive');
	});
	
	jQuery('.loginBtnLink').bind('click', function(){
		jQuery('html, body').animate({scrollTop: '0px'}, 300);
		showLoginForm(jQuery(this).offset());
	})
	jQuery('.articleLoginBtn').bind('click', function(){
		jQuery('html, body').animate({scrollTop: '0px'}, 300);
		showLoginForm(jQuery('.loginBtnLink').offset());
	});
	function showLoginForm(elPosition){
		if(errorShown == true) {
			jQuery('#loginPanel .loginPanelInfoBox').removeClass('show');
			errorShown = false;
		}
		
		var cssValue = {
			'top': '25px',
			'right': '20px'
		};
		jQuery('.loginPanelBox').fadeOut(200);
		jQuery('#loginPanel').css(cssValue).fadeIn(200);
	}
	jQuery('.smsBtnLink').bind('click', function(){
		jQuery('html, body').animate({scrollTop: '0px'}, 300);
		showSMSForm(jQuery(this).offset());
	})
	jQuery('.articleSmsBtn').bind('click', function(){
		jQuery('html, body').animate({scrollTop: '0px'}, 300);
		showSMSForm(jQuery('.smsBtnLink').offset());
	});
	function showSMSForm(elPosition){
		if(errorShown == true) {
			jQuery('#smsPanel .loginPanelInfoBox').removeClass('show');
			errorShown = false;
		}
		
		var cssValue = {
			'top':'25px',
			'right':'10px'
		};
		jQuery('.loginPanelBox').fadeOut(200);
		jQuery('#smsPanel').css(cssValue).fadeIn(200);
	}
	
	jQuery('.loginPanelBoxCloseIcon').bind('click', function(){
		jQuery(this).parent('.loginPanelBox').fadeOut(200);
	});
	jQuery('#passInput').bind('focus', function(){
		if(jQuery(this).attr('type')=='text') {
			jQuery(this).val('');
			var input = jQuery(this); 
			var password = jQuery('<input type="password" id="'+input.attr('id')+'" value="'+input.val()+'" class="'+input.attr('class')+'" name="'+input.attr('name')+'" />').insertBefore(input); 
			input.remove(); 
			password.focus();
		}
	});
	
	jQuery(document).ready(function(){
		function showErrorBox(errorBox) {
			if(errorBox != undefined && errorBox != '') {
				switch(errorBox) {
				case 'loginPanel':
					showLoginForm(jQuery('.loginBtnLink').offset());
					errorShown = true;
					break;
				case 'smsPanel':
					showSMSForm(jQuery('.smsBtnLink').offset());
					errorShown = true;
					break;
				default:
					errorShown = true;
					break;
				}
			}
			return true;
		}
		
		jQuery('.loginPanelInfoBox').each(function(){
			if(jQuery(this).hasClass('show')) {
				var errorBox = jQuery(this).parent().attr('id');
					errorShown = false;
					showErrorBox(errorBox);
			}
		});
	});

}

function weatherEngine() {
	var weatherBox = jQuery('.componentBox.weatherBox'); 
	
	if(weatherBox.size() > 0) {
		weatherBox.find('select').bind('change', function() {
			var componentId = weatherBox.attr('id').split('_')[1];
			var componentValue = weatherBox.find('select').val();
			
			jQuery.ajax({
					type: 'GET',
					url: '/ComponentAjax',
					data: 'componentId=' + componentId + '&city=' + componentValue,
					dataType: 'xml',
					success: function(xml){
						var xmlParent, weatherComponent = null;
						
						xmlParent = jQuery(xml).find('weather');
						weatherComponent = jQuery('#weather_' + componentId + '_result');						
						
						var xmlDays = xmlParent.children();
						var weatherDays = weatherComponent.find('div.weatherDay');
						
						jQuery(xmlDays).each(function(index){
							var temps = jQuery(weatherDays[index]).find('div.weatherTemps').children();
							
							jQuery(weatherDays[index]).find('div.weatherImage img').attr('src', 'http://www.rp.pl/static/img/components/weather/' + jQuery(this).find('icon').text().toLowerCase() + '.png');
							jQuery(temps[0]).html(jQuery(this).find('tempDay').text() + '&deg;C');
							jQuery(temps[1]).html(jQuery(this).find('tempNight').text() + '&deg;C');
						});
					},
					error: function() {
						//alert('WystÄ…piĹ‚ bĹ‚Ä…d podczas pobierania informacji!');
					}
				});			
		});
	}
}

function weatherHeadEngine(cityId) {
	var weatherBox = jQuery('.panelWeather'); 
	if(weatherBox.length > 0){
		jQuery.ajax({
			type: 'GET',
			url: '/weather',
			data: 'city=' + cityId + '&componentId=',
			dataType: 'xml',
			success: function(xml){
				var xmlParent, weatherComponent = null;
				xmlParent = jQuery(xml).find('weather');
				var weatherToday = xmlParent.children();
				
				jQuery(weatherBox).children('.weatherIcon').children('img').attr('src', 'http://www.rp.pl/static/img/components/weather/' + weatherToday.children('icon').text().toLowerCase() + '.png');
				jQuery(weatherBox).children('.weatherIcon').children('img').attr('alt', weatherToday.children('icon').text().toLowerCase());
				jQuery(weatherBox).children('.weatherIcon').attr('title', weatherToday.children('icon').text().toLowerCase());
				jQuery(weatherBox).children('.Day').html(weatherToday.children('tempDay').text() + '&deg;C');
				jQuery(weatherBox).children('.Night').html(weatherToday.children('tempNight').text() + '&deg;C');
				jQuery(weatherBox).addClass('panelWeatherActive');
			},
			error: function() {
				jQuery(weatherBox).append('<span>Nie moĹĽna pobraÄ‡ informacji</span>');
				jQuery(weatherBox).removeClass('panelWeatherActive');
				jQuery(weatherBox).hide();
			}
		});	
	}
}
function changeCityWeatherHead () {
	jQuery('.weatherCity').bind('click', function(){
		var cId = jQuery(this).attr('name');
		var cName = jQuery(this).text();
		jQuery('#inputCityName').val(cName);
		jQuery('#inputCityId').val(cId);
		setCookie('weatherCookie',cId,'360');
		weatherHeadEngine(cId);
	});
}
function checkWeatherCookie () {
	if(!checkCookie('weatherCookie')){
		var cId =  getCookie('weatherCookie');
		weatherHeadEngine(cId);
		// ustawianie wartosc miasta
		jQuery('.weatherCity').each(function(index) {
			if (jQuery(this).attr('name') == cId ){
				var cName = jQuery(this).text();
				jQuery('#inputCityName').val(cName);
			}
		});
	}else {
		weatherHeadEngine(1408);
		jQuery('#inputCityName').val('Warszawa');
	}
}

function searchEngine() {
	var aSubrangeString = new Array();
	
	jQuery('#searchInput').bind('focus', function() {
            jQuery(this).val('').addClass('searchInputActive');
            jQuery(this).parent().addClass('shadowBox1hover');
	}).bind('blur', function() {
            if(jQuery(this).val() == '') {
            	if(!jQuery(this).hasClass('przekrojSearch')) {
            		jQuery(this).val('Szukaj w rp.pl').removeClass('searchInputActive');            		
            	}
            }
            jQuery(this).parent().removeClass('shadowBox1hover');
        });
	
	jQuery('#searchSelBtn').bind('click', function() {
		if(jQuery('#searchExpander').is(':visible')) {
			jQuery('#searchExpander').slideUp('200');
		}
		else {
			jQuery('#searchExpander').slideDown('200', function() {
				jQuery(this).bind('mouseleave', function() {
					jQuery('#searchExpander').slideUp('200');
				});
				
				jQuery('.searchExpanderElement').bind('click', function() {
					aSubrangeString = jQuery(this).attr('id').split('_');
					jQuery('#searchInput').removeClass('searchInputActive').val(jQuery(this).text());
					jQuery('#searchTopicId').val(aSubrangeString[1]);
					jQuery('#searchExpander').slideUp('200');
				});
			});
		}
	});
	
	jQuery('#searchBtn').bind('click', function() {
		if(jQuery('#searchInput').val() != '' && jQuery('#searchInput').hasClass('searchInputActive')) {
			jQuery('#searchForm').submit();
		}
	});
}

function menuEngine() {
	jQuery('.midLvlElement').bind('mouseenter', function() {
		jQuery(this).addClass('midLvlActive');
	});

	jQuery('.midLvlElement').bind('mouseleave', function() {
		jQuery(this).removeClass('midLvlActive');
	});

	jQuery('.lowLvlElement').bind('mouseenter', function() {
		jQuery(this).addClass('lowLvlActive');
	});

	jQuery('.lowLvlElement').bind('mouseleave', function() {
		jQuery(this).removeClass('lowLvlActive');
	});
}

function newsFlashEngine() {
	var nDelay = 3000;
	var nSliderWidth = newsFlashSlider();
	var nScrollSpeed = nSliderWidth * 12; 
	var nLeftScroll = nSliderWidth - jQuery('.newsFlash_Window').innerWidth();
	var sLeftScroll = '-=' + nLeftScroll;
	
	setTimeout(function() {
		newsFlashScroll(sLeftScroll, nScrollSpeed);
	}, nDelay);
	
	jQuery('.newsFlash_Box').bind('mouseenter', function() {
		jQuery('.newsFlash_Slider').stop(true);
	});

	jQuery('.newsFlash_Box').bind('mouseleave', function() {
		newsFlashScroll(sLeftScroll, nScrollSpeed);
	});
}

function newsFlashScroll(sLeftScroll, nScrollSpeed) {
	jQuery('.newsFlash_Slider').animate({
    left: sLeftScroll
  }, nScrollSpeed, "linear", function() {
		jQuery('.newsFlash_Slider').children('div:first-child').clone().appendTo('.newsFlash_Slider');
		if(jQuery('.newsFlash_Slider').children('div:first-child').size() > 1) {
			jQuery('.newsFlash_Slider').children('div:first-child').remove();
		}
		newsFlashSlider();
    newsFlashScroll(sLeftScroll, nScrollSpeed);
  });
}

function newsFlashSlider() {
	var nSliderWidth = 0;
	jQuery('.newsFlash_Element').each(function() {
		nSliderWidth += jQuery(this).innerWidth(); 
	});
	jQuery('.newsFlash_Divider').each(function() {
		nSliderWidth += jQuery(this).innerWidth(); 
	});
	jQuery('.newsFlash_Slider').css('width', nSliderWidth);
	
	return nSliderWidth;
}

function newsFlashEngine_2() {
	var nDelay = 3000;
	var nSliderWidth = newsFlashSlider();
	//var nWindowWidth = newsFlashWindow();
	var nScrollSpeed = nSliderWidth * 12;
	var nLeftScroll = nSliderWidth;
	var sLeftScroll = '-=' + nLeftScroll;
	
	setTimeout(function() {
		newsFlashScroll_2(sLeftScroll, nScrollSpeed, nSliderWidth);
	}, nDelay);
	
	jQuery('.newsFlash_Box').bind('mouseenter', function() {
		jQuery('.newsFlash_Slider').stop(true);
	});

	jQuery('.newsFlash_Box').bind('mouseleave', function() {
		newsFlashScroll_2(sLeftScroll, nScrollSpeed, (nSliderWidth - 50));
	});
}

function newsFlashScroll_2(sLeftScroll, nScrollSpeed, nSliderWidth) {
	jQuery('.newsFlash_Slider').animate({
    left: sLeftScroll
  }, nScrollSpeed, "linear", function() {
		jQuery('.newsFlash_Slider').css('left', jQuery('.newsFlash_Window').innerWidth());
		
		nLeftScroll = nSliderWidth + jQuery('.newsFlash_Window').innerWidth();
		sLeftScroll = '-=' + nLeftScroll;
    newsFlashScroll_2(sLeftScroll, nScrollSpeed, nSliderWidth);
  });
}

function newsFlashSlider() {
	var nSliderWidth = 0;
	jQuery('.newsFlash_Element').each(function() {
		nSliderWidth += jQuery(this).innerWidth(); 
	});
	jQuery('.newsFlash_Divider').each(function() {
		nSliderWidth += jQuery(this).innerWidth(); 
	});
	jQuery('.newsFlash_Slider').css('width', nSliderWidth);
	
	return nSliderWidth;
}

function mainTopicEngine() {
	var nDelay = 10000;
	var intervalId = setInterval(function() {
		mainTopicRotate();
	}, nDelay);
	
	jQuery('.mainTopic_Element').bind('mouseenter', function() {
		mainTopicRotate(jQuery(this));
		clearInterval(intervalId);
	});

	jQuery('.mainTopic_Element').bind('mouseleave', function() {
		intervalId = setInterval(function() {
			mainTopicRotate();
		}, nDelay);
	});

	// main topic autowidth 
	var mtAw = jQuery('.mainTopicAw');
	
	if(mtAw.length > 0) {
		var mtAwImgBox = jQuery('.mainTopic_ImgBox', mtAw);
		var mtAwRBox = jQuery('.mainTopic_RightBox', mtAw);
		
		var desiredImgBoxW = parseInt(mtAw.width()) - parseInt(mtAwRBox.width()) - 10;
		
		mtAwImgBox.width(parseInt(desiredImgBoxW));
		mtAwImgBox.css('visibility', 'visible'); // show it, because it's hidden by CSS
	}
	
}

function mainTopicRotate(oActiveElement) {
	var newMainTopic = false;
	var nMainTopicElements = 4;
	
	if(jQuery('.mainTopic_Box').hasClass('mainTopic3')) {
		nMainTopicElements = 3;
	}
	if(jQuery('.mainTopic_Box').hasClass('mainTopic2') && (!jQuery('.mainTopic_Box').hasClass('mtWeekend'))) {
		newMainTopic = true;
	} else {
		newMainTopic = false;
	}
	
	// lazy check
	nMainTopicElements = jQuery('.mainTopic_Element').size();
	
	if (oActiveElement == undefined) {
		var nActiveElementId = jQuery('.mainTopic_ElementActive').attr('id');
		nActiveElementId = nActiveElementId.substring(nActiveElementId.lastIndexOf('_') + 1);
		nActiveElement = nActiveElementId - 1;
		if (nActiveElementId < nMainTopicElements) {
			nNextElement = nActiveElementId;
		}
		else {
			nNextElement = 0;
		}
		
		jQuery('.mainTopic_Element:eq(' + nActiveElement + ')').removeClass('mainTopic_ElementActive');
		jQuery('.mainTopic_Element:eq(' + nNextElement + ')').addClass('mainTopic_ElementActive');
		jQuery('.mainTopic_Headline:eq(' + nActiveElement + ')').removeClass('mainTopic_Headline_Active');
		jQuery('.mainTopic_Headline:eq(' + nNextElement + ')').addClass('mainTopic_Headline_Active');
		jQuery('.mainTopic_ImgBox').children('.mainTopic_Img:eq(' + nActiveElement + ')').fadeOut(0, function(){
			jQuery('.mainTopic_ImgBox').children('.mainTopic_Img:eq(' + nNextElement + ')').fadeIn(0);
		});
		
		if(jQuery('.mainTopic_Box').hasClass('mainTopic3')){
			if(nNextElement == 0){
				jQuery('.mainTopic_Element:eq(1)').removeClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(2)').addClass('mainTopic_ElementBG');
			}
			if(nNextElement == 1){
				jQuery('.mainTopic_Element:eq(2)').removeClass('mainTopic_ElementBG');
			}
			if(nNextElement == 2){
				jQuery('.mainTopic_Element:eq(1)').addClass('mainTopic_ElementBG');
			}
		}
		
		if(jQuery('.mainTopic_Box').hasClass('mainTopicEko24')){
			jQuery('.mainTopic_Element').removeClass('mainTopic_ElementBG');
			
			if(nNextElement == 0){
				jQuery('.mainTopic_Element:eq(1)').removeClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(2)').addClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(3)').addClass('mainTopic_ElementBG');
			}
			if(nNextElement == 1){
				jQuery('.mainTopic_Element:eq(1)').removeClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(2)').removeClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(3)').addClass('mainTopic_ElementBG');
			}
			if(nNextElement == 2){
				jQuery('.mainTopic_Element:eq(1)').addClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(2)').removeClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(3)').removeClass('mainTopic_ElementBG');
			}
			if(nNextElement == 3){
				jQuery('.mainTopic_Element:eq(1)').addClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(2)').addClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(3)').removeClass('mainTopic_ElementBG');
			}
		}
		
		if(jQuery('.mainTopic_Box').hasClass('mtWeekend')) {
			var nActElement = parseInt(jQuery('.mainTopic_ElementActive').attr('id').split('_')[2], 10) - 1;
			if(nActElement == 5) {
				jQuery('#mainTopic_Floater').stop(true, true).animate({left: 0}, 'slow');
			} else {
				jQuery('#mainTopic_Floater').stop(true, true).animate({left: parseInt(nActElement * (175 + 11), 10)}, 'slow');
			}
		}
	}
	else {
		var nActiveElementId = oActiveElement.attr('id');
		nActiveElementId = nActiveElementId.substring(nActiveElementId.lastIndexOf('_') + 1);
		nActiveElement = nActiveElementId - 1;
		nSeledtedElementId = jQuery('.mainTopic_ElementActive').attr('id');
		nSeledtedElementId = nSeledtedElementId.substring(nSeledtedElementId.lastIndexOf('_') + 1);
		nSeledtedElement = nSeledtedElementId - 1;
		
		jQuery('.mainTopic_Element:eq(' + nSeledtedElement + ')').removeClass('mainTopic_ElementActive');
		jQuery('.mainTopic_Element:eq(' + nActiveElement + ')').addClass('mainTopic_ElementActive');
		jQuery('.mainTopic_Headline:eq(' + nSeledtedElement + ')').removeClass('mainTopic_Headline_Active');
		jQuery('.mainTopic_Headline:eq(' + nActiveElement + ')').addClass('mainTopic_Headline_Active');
		jQuery('.mainTopic_ImgBox').children('.mainTopic_Img:eq(' + nSeledtedElement + ')').fadeOut(0, function(){
			jQuery('.mainTopic_ImgBox').children('.mainTopic_Img:eq(' + nActiveElement + ')').fadeIn(0);
		});
		
		if(jQuery('.mainTopic_Box').hasClass('mainTopic3')){
			if(nActiveElement == 0){
				jQuery('.mainTopic_Element:eq(1)').removeClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(2)').addClass('mainTopic_ElementBG');
			}
			if(nActiveElement == 1){
				jQuery('.mainTopic_Element:eq(2)').removeClass('mainTopic_ElementBG');
			}
			if(nActiveElement == 2){
				jQuery('.mainTopic_Element:eq(1)').addClass('mainTopic_ElementBG');
			}
		}		
		
		if(jQuery('.mainTopic_Box').hasClass('mainTopicEko24')){
			jQuery('.mainTopic_Element').removeClass('mainTopic_ElementBG');
			
			if(nActiveElement == 0){
				jQuery('.mainTopic_Element:eq(1)').removeClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(2)').addClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(3)').addClass('mainTopic_ElementBG');
			}
			if(nActiveElement == 1){
				jQuery('.mainTopic_Element:eq(1)').removeClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(2)').removeClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(3)').addClass('mainTopic_ElementBG');
			}
			if(nActiveElement == 2){
				jQuery('.mainTopic_Element:eq(1)').addClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(2)').removeClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(3)').removeClass('mainTopic_ElementBG');
			}
			if(nActiveElement == 3){
				jQuery('.mainTopic_Element:eq(1)').addClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(2)').addClass('mainTopic_ElementBG');
				jQuery('.mainTopic_Element:eq(3)').removeClass('mainTopic_ElementBG');
			}
		}		
		
		if(jQuery('.mainTopic_Box').hasClass('mtWeekend')) {
			var nActElement = parseInt(jQuery('.mainTopic_ElementActive').attr('id').split('_')[2], 10) - 1;
			if(nActElement == 5) {
				jQuery('#mainTopic_Floater').stop(true, true).animate({left: 0}, 'slow');
			} else {
				jQuery('#mainTopic_Floater').stop(true, true).animate({left: parseInt(nActElement * (175 + 11), 10)}, 'slow');
			}
		}
	}
	
	if(newMainTopic) {
		jQuery('.mainTopic_Element').each(function(){
			if(jQuery(this).hasClass('mainTopic_ElementActive')) {
				jQuery(this).prev().addClass('mainTopic_nextElementActive');
			} else {
				jQuery(this).removeClass('mainTopic_nextElementActive');
			}
		});
	}
}

function mostTabbedEngine() {
	if(jQuery('.mostTabbed_Box').size() > 0) {
		jQuery('.mostTabbed_Box').children('.elementHeader').children('div').bind('click', function() {
			if(!jQuery(this).hasClass('mostTabbed_Tab_Active')) {

				oClickedElement = jQuery(this);
				sTabId = oClickedElement.attr('id');
				aTabId = sTabId.split('_');
				aAjaxData = aTabId[1].split('-');
				
				jQuery.ajax({
					type: 'POST',
					url: '/ComponentAjax',
					data: 'componentId=' + aAjaxData[0] + '&chosenTab=' + aAjaxData[1] + '&localId=' + aAjaxData[2],
					success: function(answer){
						jQuery('#mostTabbed_' + aAjaxData[0]).find('.mostTabbed_Header').children().removeClass('mostTabbed_Tab_Active');
						//jQuery('.mostTabbed_Body').children().removeClass('mostTabbed_Element_Active');
						
						oClickedElement.addClass('mostTabbed_Tab_Active');
						//jQuery('.mostTabbed_Element-' + sTabId).addClass('mostTabbed_Element_Active');
						
						oClickedElement.parents('.componentBox').find('.mostTabbed_Element').children().remove();
						oClickedElement.parents('.componentBox').find('.mostTabbed_Element').append(answer.trim());

						oClickedElement.parents('.mostTabbed_Header').find('div').removeClass('mostTabbed_Tab_noBorder');
						oClickedElement.next('div').addClass('mostTabbed_Tab_noBorder');
					},
					error: function(answer) {
						alert('wystÄ…piĹ‚ bĹ‚Ä…d');
					}
				});
			}
		});
	}
}

function TabbedEngine() {
	if(jQuery('.Tabbed_Box').size() >= 0) {
		jQuery('.Tabbed_Tab').bind('click', function() {
			if(!jQuery(this).hasClass('Tabbed_Tab_Active')) {
				oClickedElement = jQuery(this);
				sTabId = oClickedElement.attr('id');
				aTabId = sTabId.split('_');
				aData = aTabId[1].split('-');
				jQuery('#Tabbed_' + aData[0]).find('.Tabbed_Header').children().removeClass('Tabbed_Tab_Active');
				oClickedElement.addClass('Tabbed_Tab_Active');
				jQuery('#Tabbed_' + aData[0]).find('.Tabbed_Body').children().removeClass('Tabbed_Element_Active');
				jQuery('#Tabbed_' + aData[0]).find('.Tabbed_Body').children('#Tabbed_Element_'+aData[1]).addClass('Tabbed_Element_Active');
			}
		});
	}
}


/***** slider *****/
function sliderInit() {
	jQuery('.slider_Box').each(function() {
		var nElementsNo = jQuery(this).find('.slider_Element').size();
		jQuery(this).find('.slider_Panel').width(function() {
			var __width1 = jQuery(this).find('.slider_Element').find('img').width();
			var __width2 = (jQuery(this).find('.slider_Separator').width());
			return (__width1 + __width2) * (nElementsNo+1);
		});
		console.log('Szerokość elementów to: '+ jQuery(this).find('.slider_Panel').width() );
		jQuery(this).find('.slider_NoElements').text(nElementsNo);
		var nElementsVisible = jQuery(this).find('.slider_param_VisibleElements').text();
		//alert('nElementsVisible: ' + nElementsVisible);
		if(nElementsVisible == 1) {
			jQuery(this).find('.slider_VisibleElements').text('1');
		}
		else if(nElementsVisible > 1){
			jQuery(this).find('.slider_VisibleElements').text('1-' + (1 * nElementsVisible));
		}
		if (nElementsVisible >= nElementsNo) {
			//alert('nElementsVisible >= nElementsNo');
			jQuery(this).find('.slider_SlideRight').removeClass('slider_ArrowBoxActive');
			jQuery(this).find('.slider_SlideRight').addClass('slider_ArrowBoxInactive');
			var sLinkPath = jQuery(this).find('.slider_SlideRight').children('img').attr('src').replace('link', 'inactive');
			jQuery(this).find('.slider_SlideRight').children('img').attr('src', sLinkPath);
		}
	});
  
  jQuery('.slider_SlideLeft').click(function() {
    sliderMove(jQuery(this).parents('.slider_Box'), 'left');
  });
  
  jQuery('.slider_SlideRight').click(function() {
    sliderMove(jQuery(this).parents('.slider_Box'), 'right');
  });
}

function sliderMove(oActiveElement, sDir) {
	try {
		if (slideSpeed) 
			nSlideSpeed = slideSpeed;
	} 
	catch (e) {
		var nSlideSpeed = 500;
	}
	var nSlideLenght = (oActiveElement.find('.slider_Element').innerWidth() + oActiveElement.find('.slider_Separator').innerWidth()) * 2;
	//alert('nSlideLenght: ' + nSlideLenght);
	var sSlideLeft = '+=' + nSlideLenght;
	var sSlideRight = '-=' + nSlideLenght;
	var nElementsVisible = oActiveElement.find('.slider_param_VisibleElements').text();
	var nElementsNo = oActiveElement.find('.slider_Element').size();
	//alert('nElementsVisible: ' + nElementsVisible + ' | nElementsNo: ' + nElementsNo);
	
	var nCounter = parseInt(oActiveElement.find('.slider_Counter').text());
	//alert('nCounter: ' + nCounter);
  //alert('sDir: ' + sDir); 
	
	//alert('nElementsVisible: ' + nElementsVisible + ' | nElementsNo: ' + nElementsNo + ' | nCounter: ' + nCounter);
	
	if (nElementsVisible < nElementsNo) {
		switch (sDir) {
			case 'left':
				if (nCounter > 0) {
					oActiveElement.find('.slider_Panel').animate({
						left: sSlideLeft
					}, nSlideSpeed);
					nCounter--;
				}
				//if (nCounter == (nElementsNo - nElementsVisible - 3)) {
				if ((nCounter + 1) < (Math.ceil(nElementsNo / nElementsVisible))) {
					if (oActiveElement.find('.slider_SlideRight').hasClass('slider_ArrowBoxInactive')) {
						oActiveElement.find('.slider_SlideRight').removeClass('slider_ArrowBoxInactive');
						oActiveElement.find('.slider_SlideRight').removeClass('slider_ArrowRightInactive');
						oActiveElement.find('.slider_SlideRight').addClass('slider_ArrowBoxActive');
						//var sLinkPath = oActiveElement.find('.slider_SlideRight').children('img').attr('src').replace('inactive', 'link');
						//oActiveElement.find('.slider_SlideRight').children('img').attr('src', sLinkPath);
					}
				}
				if (nCounter == 0) {
					oActiveElement.find('.slider_SlideLeft').removeClass('slider_ArrowBoxActive');
					oActiveElement.find('.slider_SlideLeft').addClass('slider_ArrowBoxInactive');
					oActiveElement.find('.slider_SlideLeft').addClass('slider_ArrowLeftInactive');
					//var sLinkPath = oActiveElement.find('.slider_SlideLeft').children('img').attr('src').replace('link', 'inactive');
					//oActiveElement.find('.slider_SlideLeft').children('img').attr('src', sLinkPath);
				}
				break;
				
			case 'right':
				//if (nCounter < (nElementsVisible)) {
				if ((nCounter + 1) < (Math.ceil(nElementsNo / nElementsVisible))) {
					oActiveElement.find('.slider_Panel').animate({
						left: sSlideRight
					}, nSlideSpeed);
					nCounter++;
				}
				if (nCounter == 1) {
					if (oActiveElement.find('.slider_SlideLeft').hasClass('slider_ArrowBoxInactive')) {
						oActiveElement.find('.slider_SlideLeft').removeClass('slider_ArrowBoxInactive');
						oActiveElement.find('.slider_SlideLeft').removeClass('slider_ArrowLeftInactive');
						oActiveElement.find('.slider_SlideLeft').addClass('slider_ArrowBoxActive');
						//var sLinkPath = oActiveElement.find('.slider_SlideLeft').children('img').attr('src').replace('inactive', 'link');
						//oActiveElement.find('.slider_SlideLeft').children('img').attr('src', sLinkPath);
					}
				}
				//if (nCounter == (nElementsNo - nElementsVisible - 2)) {
				if ((nCounter + 1) == (Math.ceil(nElementsNo / nElementsVisible))) {
					oActiveElement.find('.slider_SlideRight').removeClass('slider_ArrowBoxActive');
					oActiveElement.find('.slider_SlideRight').addClass('slider_ArrowBoxInactive');
					oActiveElement.find('.slider_SlideRight').addClass('slider_ArrowRightInactive');
					//var sLinkPath = oActiveElement.find('.slider_SlideRight').children('img').attr('src').replace('link', 'inactive');
					//oActiveElement.find('.slider_SlideRight').children('img').attr('src', sLinkPath);
				}
				break;
				
		//default:
		}
	} /* if (nElementsVisible < nElementsNo) */
	
	oActiveElement.find('.slider_Counter').text(nCounter); 
	if(nElementsVisible == 1) {
		jQuery(this).find('.slider_VisibleElements').text(nCounter);
	}
	else if(nElementsVisible > 1){
		oActiveElement.find('.slider_VisibleElements').text((nCounter * nElementsVisible + 1) + '-' + ((nCounter + 1) * nElementsVisible));
	}
}

/**
 * SPRAWDZIÄ† CZY BĹ�Ä�DY W IE ZNIKNÄ„ PO PRZEJĹšCIU DO ONLINE
 * 
 * Niestety niestabilny serwer powoduje, ĹĽe obrazki wyĹ›wietlajÄ… siÄ™ losowo, w zaleĹĽnoĹ›ci na ktĂłry z dwĂłch serwerĂłw wpadnie zapytanie :/
 * Problem po stronie Kefira?
 */
function galleryRotatorInit() {
	jQuery('.galleryRotator_Box').each(function() {
		var sGalleryLink = jQuery(this).find('.galleryRotator_Start').children('a').attr('href');
		jQuery(this).find('.galleryRotator_Tech').load(sGalleryLink + ' .filmstrip', function(){
			
			jQuery(this).find('.filmstrip').find('li').each(function(){
				//jQuery(this).find('img').attr('src', jQuery(this).find('img').attr('src').replace(',6.jpg', ',7.jpg'));
				jQuery(this).find('img').attr('src', jQuery(this).find('img').attr('src').replace(/[,][0-9]{1,3}[.]/gi, ',' + jQuery('#componentParam_imgSize').text() + '.'));
				jQuery(this).find('a').attr('target', '_blank');
			});
					
			var sLink = jQuery(this).parents('.galleryRotator_Body').children('.galleryRotator_Start').children('a').attr('href');
			var nElementsQty = jQuery(this).find('li').size();
			var nCounter = sLink.substring(sLink.indexOf(',') + 1, sLink.lastIndexOf(','));   //DO WERSJI ONLINE
			//var nCounter = 1;   //DO WERSJI OFFLINE
			var oActiveElement = jQuery(this);
			
			//alert(sLink + ' | ' + nElementsQty + ' | ' + nCounter + ' | ' + oActiveElement.attr('class'));

			oActiveElement.find('li:nth-child(' + nCounter + ')').children('img').wrap('<a href="' + sLink + '" target="_blank" />')
			oActiveElement.find('li').css('display', 'none').css('position', 'absolute').css('left', '0').css('top', '0'); // lepsze wygaszanie i pojawianie
			oActiveElement.find('li:nth-child(' + nCounter + ')').fadeIn(100);

			setInterval(function(){
				(nCounter < nElementsQty) ? nCounter++ : nCounter = 1;
				galleryRotator(nCounter, nElementsQty, oActiveElement);
			}, 5000);
					
		});
	});
}

/**
 * lepsze wygaszanie i pojawianie
 * @param {Object} nCounter
 * @param {Object} nElementsQty
 * @param {Object} oActiveElement
 */
function galleryRotator(nCounter, nElementsQty, oActiveElement) {
	//alert(oActiveElement.find('li:nth-child(' + (nCounter-1) + ')').parent().html());
	oActiveElement.find('li:nth-child(' + nCounter + ')').fadeIn(500, function() {
		if(nCounter == 1) {
			oActiveElement.find('li:nth-child(' + nElementsQty + ')').fadeOut(500);
		}
		else {
			oActiveElement.find('li:nth-child(' + (nCounter-1) + ')').fadeOut(500);
		}
	});
}

function footerLogoInit() {
	jQuery('.footer_LogoElement').bind('mouseenter', function() {
		footerLogoOver(jQuery(this));
	});

	jQuery('.footer_LogoElement').bind('mouseleave', function() {
		footerLogoOut(jQuery(this));
	});
}

function footerLogoOver(oActiveElement) {
	var sImgSrc = oActiveElement.children('img').attr('src');
	//alert(sImgSrc);
	var sFileName = sImgSrc.substring(sImgSrc.lastIndexOf('/') + 1);
	var sFilePath = sImgSrc.substring(0, sImgSrc.lastIndexOf('/') + 1);
	//alert(sFileName + '|' + sFilePath);
	var aFileName = sFileName.split('.');
	//alert(aFileName);
	//alert(sFilePath + aFileName[0] + '_hover.' + aFileName[1]);
	oActiveElement.children('img').attr('src', sFilePath + aFileName[0] + '_hover.' + aFileName[1]);
}

function footerLogoOut(oActiveElement) {
	var sImgSrc = oActiveElement.children('img').attr('src');
	oActiveElement.children('img').attr('src', sImgSrc.replace('_hover', ''));
}





/**
 * funkcja obslugujaca konfiguracje okien dialogowych
 */
function confDialogBox() {
	var nDialogFadeOut = 300; 
	var nGlassFadeOut = nDialogFadeOut + 50;
	var sCloseBtnTxt = 'zamknij';
	
	var D = document;
  var nDocHeight = Math.max(Math.max(D.body.scrollHeight, D.documentElement.scrollHeight), Math.max(D.body.offsetHeight, D.documentElement.offsetHeight), Math.max(D.body.clientHeight, D.documentElement.clientHeight));
	//alert(nDocHeight);
  jQuery('#glassBox').css('height', nDocHeight);

	jQuery('#dialogBox').css('left', (document.body.clientWidth - jQuery('#dialogBox').innerWidth()) / 2);
	jQuery('#dialogCloseBtn').bind('mouseup', function() {
		closeDialogBox(nDialogFadeOut, nGlassFadeOut);
	});
}

function closeDialogBox(nDialogFadeOut, nGlassFadeOut) {
	jQuery('#dialogBox').fadeOut(nDialogFadeOut);
	jQuery('#glassBox').fadeOut(nGlassFadeOut, function() {
		resetDialogBox();
	});
}

function resetDialogBox() {
  jQuery('#dialogBox').removeClass();
  jQuery('#dialogTitle').removeClass().text('');
  jQuery('#dialogBody').removeClass().html('<p></p>');
	jQuery('#dialogCloseBtn').text('zamknij');
	jQuery('#dialogBtnsBox').children().removeClass().addClass('dialogBtn');
	jQuery('#dialogBtnsBox').children().each(function() {
		if(jQuery(this).attr('id') != 'dialogCloseBtn') {
			jQuery(this).remove();
		}
		else {
			jQuery(this).show();
		}
	}); 
}

/**
 * funkcja obslugujaca wywolanie okna dialogowego
 * 
 * DO PRZENIESIENIA DO GLOWNEGO SKRYPTU OBSLUGUJACEGO DANY SERWIS!!!
 * 
 * funkcja wymaga podania dwĂłch parametrow:
 * - sTitle : tytul okna dialogowego
 * - sText : tresc komunikatu, dla komunikatow kilkuakapitowych poszczegolne parametry mozna ujac w znacznik <p> 
 * 
 * w przypadku kiedy ktorykolwiek z parametrow wymaganych nie zostanie podany 
 * lub nie bedzie zawieral tresci okno dialogowe nie zostanie wyswietlone
 * 
 * funkcja umozliwia podanie dwoch parametrow opcjonalnych:
 * - sKind : typ okna dialogowego, parametr moze przyjac jedna z ponizszych wartosci
 *   - choose : okno dialogowe umozliwiajace wybor tak/nie
 *   - warning : okno zawierajace ostrzezenie
 *   - error : okno zawierajace komunikat o bledzie
 *   okna powyzszych typow zawieraja jedynie przycisk "zamknij", 
 *   jedynie okno typu "choose" zawiera przyciski "tak", "nie"
 *   
 * - sButtons : zawiera ciag znakow umozliwiajacy zdefiniowanie indywidualnych 
 *              przyciskow dla danego okna dialogowego
 *              parametr musi miec postac:
 *              id1,tekst1,class1;id2,tekst2,class2;...;id(n),tekst(n),class(n)
 *              funkcja tworzy elementy <button>, ktore do dzialania wymagaja 
 *              indywidualnego jQ
 * 
 * @param string sTitle
 * @param string sText
 * @param string sKind
 * @param string sButtons
 * 
 * @TODO funkcjonalnosc dla parametru sButtons
 */
function setDialogBox(sTitle, sText, sKind, sButtons) {
	//alert('setDialogBox(' + sTitle + ', ' + sText + ', sKind, sButtons)');
	var nDialogFadeIn = 300; 
	var nGlassFadeIn = 200; 
	confDialogBox();
	
	jQuery('#dialogTitle').text(sTitle);
	if (sText != '') {
		if (sText.indexOf('<p>') == -1) {
			jQuery('#dialogBody').children('p').html(sText);
		}
		else {
			jQuery('#dialogBody').html(sText);
		}
	}
	
	if(sKind != 'null' && sKind != 'undefined' && sKind != ' ') {
		switch(sKind) {
			case 'error':
		    jQuery('#dialogBox').addClass('dialogBox_error');
		    jQuery('#dialogTitle').addClass('dialogTitle_error');
		    jQuery('#dialogBody').addClass('dialogBody_error');
		    jQuery('.dialogBtn').addClass('dialogBtn_error');
				break;

			case 'warning':
		    jQuery('#dialogBox').addClass('dialogBox_warning');
		    jQuery('#dialogTitle').addClass('dialogTitle_warning');
		    jQuery('#dialogBody').addClass('dialogBody_warning');
		    jQuery('.dialogBtn').addClass('dialogBtn_warning');
				break;

			case 'choose':
				var sLeftBtn = '<button class="dialogBtn" id="dialogLeftBtn">tak</button>';
				var sRightBtn = '<button class="dialogBtn" id="dialogRightBtn">nie</button>';
		    jQuery('.dialogBtn').addClass('dialogBtn_choose');
				jQuery('#dialogCloseBtn').hide();
				jQuery('#dialogBtnsBox').html(jQuery('#dialogBtnsBox').html() + sLeftBtn + sRightBtn);
				break;
		}
	}
	
	//jQuery('#glassBox').fadeIn(nGlassFadeIn, function() {
	jQuery('#glassBox').fadeTo(nGlassFadeIn, 0.5, function() {
		//alert(jQuery(window).scrollTop() + ' | ' + jQuery('#dialogBox').css('top'));
		jQuery('#dialogBox').css('top', jQuery(window).scrollTop() + 50);
		jQuery('#dialogBox').fadeIn(nDialogFadeIn);
	});
}

function trim(sData) {
	return sData.replace(/^\s+|\s+$/g,"");
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}


function recommendations(){
	var articleId = jQuery('#newsItemId').val();
	checkRecommend();
	jQuery.ajax({
		cache: false,
		url: '/commonService/rekomendacje',
		type: "GET",
		data: ({
				 	newsitemid: articleId
				 }),
		success: function(data){
			jQuery('#totalRecommendationsNumber').text(data);
		}
	});
	
	function checkRecommend(){
		if (getCookie('recomendations')== articleId) {
			jQuery('#addRecommendationButton').html('Dziękujemy za oddany głos,&nbsp;')
		} else {
			jQuery('#addRecommendationButton').bind('click', function(){
				jQuery.ajax({
					cache: false,
					url: '/commonService/rekomendacje',
					type: "POST",
					data: ({
							 	newsitemid: articleId
							 }),
					success: function(data, jqXHR){
						jQuery('#totalRecommendationsNumber').text(data);
						setCookie('recomendations', articleId, 365);
						jQuery('#addRecommendationButton').html('Dziękujemy za oddany głos,&nbsp;');
						jQuery('#addRecommendationButton').unbind('click');
					}
				});
				
			})
		}
	}
}

function fontSize(){
	jQuery('.bigText').bind('click', function(){
		jQuery('#story').find('p').each(function(){
			jQuery(this).removeClass('bigerFont');
			jQuery(this).removeClass('bigFont');
			jQuery(this).addClass('bigFont');
		})
	})
	jQuery('.bigerText').bind('click', function(){
		jQuery('#story').find('p').each(function(){
			jQuery(this).removeClass('bigerFont');
			jQuery(this).removeClass('bigFont');
			jQuery(this).addClass('bigerFont')
		})
	})
	jQuery('.normalText').bind('click', function(){
		jQuery('#story').find('p').each(function(){
			jQuery(this).removeClass('bigerFont');
			jQuery(this).removeClass('bigFont');
		})
	})
}
function slidingPopUp(){
	
	function f_clientWidth(){
		return f_filterResults(window.innerWidth ? window.innerWidth : 0, document.documentElement ? document.documentElement.clientWidth : 0, document.body ? document.body.clientWidth : 0);
	}
	
	function f_clientHeight(){
		return f_filterResults(window.innerHeight ? window.innerHeight : 0, document.documentElement ? document.documentElement.clientHeight : 0, document.body ? document.body.clientHeight : 0);
	}
	
	function f_scrollLeft(){
		return f_filterResults(window.pageXOffset ? window.pageXOffset : 0, document.documentElement ? document.documentElement.scrollLeft : 0, document.body ? document.body.scrollLeft : 0);
	}
	
	function f_scrollTop(){
		return f_filterResults(window.pageYOffset ? window.pageYOffset : 0, document.documentElement ? document.documentElement.scrollTop : 0, document.body ? document.body.scrollTop : 0);
	}
	
	function f_filterResults(n_win, n_docel, n_body){
		var n_result = n_win ? n_win : 0;
		if (n_docel && (!n_result || (n_result > n_docel))) n_result = n_docel;
		return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
	}
	
	
	if (jQuery('.articleToolBoxBottom').size() > 0) {
	 	var pos = jQuery('.articleToolBoxBottom').offset()
	 	//alert(pos.top);
			//wHeight = jQuery(window).height()
			
			var checkPos = false;
			jQuery(window).scroll(function(){
				//jQuery('#test').val(f_scrollTop());
				
				if (f_scrollTop() > (pos.top - f_clientHeight()) && checkPos == false) {
					//jQuery('.slidingPopup').addClass('ieVisible')
					jQuery(".slidingPopup").animate({
						//"left": "-=450px"
						"right": '0'
					}, 300);
					checkPos = true;
				} else if (f_scrollTop() < (pos.top - f_clientHeight()) && checkPos == true) {
					jQuery(".slidingPopup").animate({
						//"left": f_clientWidth()
						"right": '-100%'
					}, 300);
					checkPos = false;
					
				}
				
			})
			/*
			jQuery('.slidingPopup').css({
				'left': (f_clientWidth())
			});
			*/
			jQuery('#closeSlidingPopup').bind('click', function(){
				jQuery('.slidingPopup').fadeOut(200);
				return false;
			})
		}
}
function drukuj( windowURL, windowName, windowFeatures ) {
	var feat = 'width=620,height=600,toolbar=0,location=0,directories=0,status=1,menuBar=0,scrollBars=1,resizable=1';
	return window.open( windowURL, windowName, feat ) ;
}

function wyslijArtykul( windowURL, windowName, windowFeatures ) {
	var feat = 'width=320,height=190,toolbar=0,location=0,directories=0,status=1,menuBar=0,scrollBars=1,resizable=1';
	return window.open( windowURL, windowName, feat ) ;
}
function showCopyright(){
	jQuery('#articleCopyrightButton').bind('click', function(){
		jQuery('#articleCopyrightBox').fadeIn(200);
	})
	jQuery('#articleCopyrightCloseIcon').bind('click', function(){
		jQuery('#articleCopyrightBox').fadeOut(200);
	})
}
function bug(windowURL, windowName, windowFeatures){
	var feat = 'width=510,height=600,toolbar=0,location=0,directories=0,status=0,menuBar=0,scrollBars=0,resizable=1';
	return window.open(windowURL, windowName, feat);
}


function showCI() {
	jQuery('form#CompareInvestments').submit(function() {
		getCompareInvestments($(this).serialize());
		return false;
	});
}

function getCompareInvestments(dataForm) {
	jQuery.ajax({
		type: "POST",
		url: '/ComponentAjax',
		data: dataForm,
		success: function(data){
			jQuery('#Tabbed_Element_Compare').children('div').children('form').children('ul').children('li.submit').children('.floatRBox').hide();
			jQuery('#Tabbed_Element_Compare').children('div').children('form').children('ul').children('li.submit').children('.floatLBox').children('a').css('display','inline');
			jQuery('#Tabbed_Element_Compare').children('div').children('form').children('ul').children('li.short').hide();
			jQuery('#Tabbed_Element_Compare').children('div').children('.formResults').html('');
			jQuery('#Tabbed_Element_Compare').children('div').children('.formResults').append(data);
		},
		error: function(qXHR, textStatus, errorThrown) {
			alert(errorThrown);
		}
	});
}
function showformCI() {
	jQuery('#Tabbed_Element_Compare').children('div').children('form').children('ul').children('li.submit').children('.floatRBox').show();
	jQuery('#Tabbed_Element_Compare').children('div').children('form').children('ul').children('li.submit').children('.floatLBox').children('a').css('display','none');
	jQuery('#Tabbed_Element_Compare').children('div').children('form').children('ul').children('li.short').show();
	jQuery('#Tabbed_Element_Compare').children('div').children('.formResults').html('');
}

/*
 * prefooter logo rotator
 */

function prefooterLogoRotator(){
	
	var nElementsQtyLogos = jQuery('.logosRotatorContainer').find('.logosRotatorItem').size();
	var nCounterLogos = 1;   //DO WERSJI OFFLINE
	var oActiveElementLogos = jQuery('.logosRotatorContainer');
	
	oActiveElementLogos.find('.logosRotatorItem').css('display', 'none'); // lepsze wygaszanie i pojawianie
	oActiveElementLogos.find('.logosRotatorItem:nth-child(' + nCounterLogos + ')').fadeIn(100);
	
	setInterval(function(){
		(nCounterLogos < nElementsQtyLogos) ? nCounterLogos++ : nCounterLogos = 1;
		galleryRotatorLogos(nCounterLogos, nElementsQtyLogos, oActiveElementLogos);
	}, 6000);
	
	function galleryRotatorLogos(nCounterLogos, nElementsQtyLogos, oActiveElementLogos){
		oActiveElementLogos.find('.logosRotatorItem:nth-child(' + nCounterLogos + ')').fadeIn(500, function(){
			if (nCounterLogos == 1) {
				oActiveElementLogos.find('.logosRotatorItem:nth-child(' + nElementsQtyLogos + ')').fadeOut(400);
			} else {
				oActiveElementLogos.find('.logosRotatorItem:nth-child(' + (nCounterLogos - 1) + ')').fadeOut(400);
			}
			
		});
	}
	function galleryRotatorLogosLeft(){
		if(nCounterLogos > 1){
			nCounterLogos = (nCounterLogos - 1)	
		}else if(nCounterLogos == 1){
			nCounterLogos = nElementsQtyLogos
		}
		oActiveElementLogos.find('.logosRotatorItem:nth-child(' + nCounterLogos + ')').fadeIn(500, function(){
			if (nCounterLogos == nElementsQtyLogos) {
				oActiveElementLogos.find(".logosRotatorItem:nth-child(1)").fadeOut(400);
			} else {
				oActiveElementLogos.find('.logosRotatorItem:nth-child(' + (nCounterLogos + 1) + ')').fadeOut(400);
			}				
		});
	}
	
	jQuery('.logosRotatorLeft').bind('click', function(){
		galleryRotatorLogosLeft()
	})
	jQuery('.logosRotatorRight').bind('click', function(){
		if(nCounterLogos < nElementsQtyLogos){
			nCounterLogos++
		}else{
			nCounterLogos = 1;
		}
		galleryRotatorLogos(nCounterLogos, nElementsQtyLogos, oActiveElementLogos);
	})

}
function photoGalleryTabEngine(){
	jQuery('.galleryTab_Box').children('.elementHeader').children('div').bind('click', function(){
		if (!jQuery(this).hasClass('galleryTab_Active')) {
		
			oClickedElement = jQuery(this);
			sTabId = oClickedElement.children('.galleryTab_tech').val();
			aTabId = sTabId.split('_');
			aAjaxData = aTabId[1].split('-');
			
			jQuery.ajax({
				type: 'POST',
				url: '/ComponentAjax',
				data: 'componentId=' + aAjaxData[0] + '&chosenTab=' + aAjaxData[1] + '&imgServlet=' + aAjaxData[2] + '&localId=' + aAjaxData[3],
				success: function(answer){
					jQuery('#galleryTab_' + aAjaxData[0]).find('.galleryTab_Header').children().removeClass('galleryTab_Active');
					oClickedElement.addClass('galleryTab_Active');				
					oClickedElement.parents('.componentBox').find('.galleryTab_Body').empty();
					oClickedElement.parents('.componentBox').find('.galleryTab_Body').append(answer);
				},
				error: function(answer){
					alert('wystÄ…piĹ‚ bĹ‚Ä…d');
				}
			});
			
		}
	});	
}

function foreFrontTabEngine() {
	jQuery(document).ready(function() {
		jQuery('.foreFrontTabs_Panel').find('h3').bind('click', function() {
			foreFrontTab_Engine(jQuery(this));
		});
		
		jQuery('.foreFrontTabs_Panel').find('h3').bind('mouseenter', function() {
			if(!jQuery(this).hasClass('foreFrontTab_Active')) {
				jQuery(this).addClass('foreFrontTab_Hover');
			}
		});
		
		jQuery('.foreFrontTabs_Panel').find('h3').bind('mouseleave', function() {
			if(jQuery(this).hasClass('foreFrontTab_Hover')) {
				jQuery(this).removeClass('foreFrontTab_Hover');
			}
		});
		
		jQuery('.foreFrontTabs_Panel').find('h3').find('a').bind('click', function() {
			foreFrontTab_Engine(jQuery(this).parent('h3'));
			return false;
		});
	});
}

	function foreFrontTab_Engine(oActiveElement) {
		//alert('foreFrontTab_Engine');
		
		if(!oActiveElement.hasClass('foreFrontTab_Active')) {
			aTabId = oActiveElement.attr('id').split('_');
			aComponentId = oActiveElement.parents('.componentBox').attr('id').split('_');
			//sImgServlet = "${imgServlet}";
			//sSiteUrl = "${siteUrl}";
			sImgServlet = oActiveElement.parents('.componentBox').children('.imgServlet').val();
			sSiteUrl = oActiveElement.parents('.componentBox').children('.siteUrl').val();
			sLocalId = oActiveElement.parents('.componentBox').children('.localId').val();
			//alert(sImgServlet + ' | ' + sSiteUrl + ' | ' + sLocalId);

			oActiveElement.parents('.foreFrontTabs_Panel').find('h3').removeClass('foreFrontTab_Active');
			oActiveElement.addClass('foreFrontTab_Active');
			oActiveElement.parents('.foreFrontTabs_Panel').find('h3').removeClass('foreFrontTab_noBorder');
			oActiveElement.next('h3').addClass('foreFrontTab_noBorder');
			
			jQuery.ajax({
				type: 'POST',
				url: '/ComponentAjax',
				//data: 'componentId=' + aComponentId[1] + '&localId=' + ${localId} + '&chosenTab=' + aTabId[1] + '&imgServlet=' + sImgServlet + '&siteUrl=' + sSiteUrl, 
				data: 'componentId=' + aComponentId[1] + '&localId=' + sLocalId + '&chosenTab=' + aTabId[1] + '&imgServlet=' + sImgServlet + '&siteUrl=' + sSiteUrl,
				async: false, 
				success: function(sSuccess) {
					//alert('sSuccess: ' + sSuccess);
					//alert(jQuery('#foreFront_' + aComponentId[1]).children('.foreFrontTabs_Body').children('.elementBox').attr('class'));
					jQuery('#foreFront_' + aComponentId[1]).children('.foreFrontTabs_Body').children('.elementBox').remove();
					jQuery('#foreFront_' + aComponentId[1]).children('.foreFrontTabs_Body').append(sSuccess);
				},
				error: function(sError) {
					//alert('sError: ' + sError);
				}
			});
		}
		 
		function foreFrontTab_Hover(oActiveElement, sAction) {
			alert('foreFrontTab_Hover');
			//alert(sAction);
			if(!oActiveElement.hasClass('foreFrontTab_Active')) {
				if(sAction == 'enter') {
					oActiveElement.addClass('foreFrontTab_Hover');
				}
				if(sAction == 'leave' && oActiveElement.hasClass('foreFrontTab_Hover')) {
					oActiveElement.removeClass('foreFrontTab_Hover');
				}
			}
		}
	}

	function tabbed_Boxs_Engine() {
		jQuery('.Tabbed_Boxs').each( function() {
		    // Przygotowanie
		    var rootElem = jQuery(this);
		    // Przelicz ile elementów ma Tabbed_Headers i przelicz ich dlugość
		    var tabsize = rootElem.children('.Tabbed_Headers').children('.Tabbed_Tabs').size();
		    rootElem.children('.Tabbed_Headers').children('.Tabbed_Tabs').addClass('Tabbed_Tab_'+tabsize);
		    rootElem.children('.Tabbed_Headers').children('.Tabbed_Tabs').eq(0).addClass('Tabbed_noBorder Tabbed_Tab_Active');
		    rootElem.children('.Tabbed_Headers').children('.Tabbed_Tabs').eq(1).addClass('Tabbed_noBorder');
		    // Ukryj komponenty w elementBody oprócz pierwszego za pomoca klasy Tab_Hide
		    rootElem.children('.elementBody').children().addClass('Tabbed_Hide');
		    rootElem.children('.elementBody').children('div:lt(1)').addClass('Tabbed_Element_Active');

		    // Czychaj na kliknięcie
		    rootElem.children('.Tabbed_Headers').children('.Tabbed_Tabs').click(function() {
		      //Sprawdz ktory element został wciśniety. Dodaj do elementu z body klasę Tabbed_Element_Active
		      var elemindex = jQuery(this).index();
		      if(!jQuery(this).hasClass('Tabbed_Tab_Active')) {
		        jQuery(this).parent().children().removeClass('Tabbed_Tab_Active');
		        jQuery(this).addClass('Tabbed_Tab_Active');
		        rootElem.children('.Tabbed_Headers').children('div').removeClass('Tabbed_noBorder');
		        rootElem.children('.Tabbed_Headers').children().eq(elemindex).next().addClass('Tabbed_noBorder');
		        rootElem.children('.Tabbed_Headers').children().eq(0).addClass('Tabbed_noBorder');

		        rootElem.children('.elementBody').children('div').removeClass('Tabbed_Element_Active');
		        rootElem.children('.elementBody').children().eq(elemindex).addClass('Tabbed_Element_Active');

		     }
		    });
		  })
	}
	function searchPersonBox(){
		var personUrl = '';
		
		jQuery('.searchPersonHint').bind('mouseenter', function() {
			jQuery('.searchPersonTooltip').fadeIn(200);  
		});
		jQuery('.searchPersonHint').bind('mouseleave', function() {
			jQuery('.searchPersonTooltip').fadeOut(200);  
		});

		jQuery(".searchPersonInput").autocomplete({
			source : function(request, response) {
				jQuery.ajax({
					url : "/ComponentAjax",
					dataType : "json",
					type: "POST",
					cache: false,
					data : {
						type : "autocompleterJson",
						searchPersonQuery : request.term,
						componentId: jQuery('#searchPersonComponentId').val(),
						limit: "10"
					},
					success : function(data) {
						jQuery('.searchPersonError').fadeOut(200);
						response(jQuery.map(data.persons, function(item) {
							return {
								label : item.label,
								link: item.link
							};
						}));
					}
				});
			},
			minLength : 2,
			select: function(event, ui){
				jQuery(".searchPersonQuery").val(ui.item.label);
				personUrl = ui.item.link;
				return false;
			}
		});
		
		jQuery('#autocompleteForm').submit(function(){
			return false;
		});
		
		jQuery('.searchPersonSubmit').bind('click', function(){
			if(personUrl != ''){
				location.href = personUrl;	
			}else{
				jQuery('.searchPersonError').fadeIn(150);
			}
		});
	}
		
	function modernSliderEngine () {
        jQuery('.modernSlider_box .modernSlider_buttonNext, .modernSlider_box .modernSlider_buttonPrev').click(function(event) {
            var sliderRoot = jQuery(this).parent().parent();
            if (sliderRoot.find('.modernSlider_boxSlider>div:animated').length > 0) { return; }
            var slideSpeed = 500;
            var activeElement = sliderRoot.find('.modernSlider_boxSlider>div:visible');
            var prevActiveElement = activeElement;
            var countElements = sliderRoot.find('.countElements').html();
            var picturesToShow = sliderRoot.attr('picturestoshow');
            var actualElementLeft = sliderRoot.find('.actualElementLeft').html();
            var actualElementRight = sliderRoot.find('.actualElementRight').html();
            
            if (jQuery(this).hasClass('modernSlider_buttonNext')) {
                if (activeElement.is(":last-child")) {
                    activeElement = sliderRoot.find('.modernSlider_boxSlider>div:first');
                    actualElementLeft = 1;
                    actualElementRight = picturesToShow;
                }
                else {
                    activeElement = activeElement.next();
                    actualElementLeft = parseInt(actualElementLeft) + parseInt(picturesToShow);
                    actualElementRight = parseInt(actualElementRight) + parseInt(picturesToShow);
                    if(actualElementRight > countElements) { actualElementRight = countElements }
                }
                sliderRoot.find('.actualElementLeft').html(actualElementLeft);
                sliderRoot.find('.actualElementRight').html(actualElementRight);
                activeElement.css('left', activeElement.width()+'px');
                activeElement.show();
                prevActiveElement.animate({ left: '-100%'}, slideSpeed, function() { prevActiveElement.hide(); });
                activeElement.animate({ left: '0' }, slideSpeed);
            }
            else if (jQuery(this).hasClass('modernSlider_buttonPrev')) {
                if (activeElement.is(":first-child")) {
                    activeElement = sliderRoot.find('.modernSlider_boxSlider>div:last');
                    actualElementLeft = Math.floor((countElements-1)/picturesToShow) * picturesToShow + 1;
                    if(actualElementLeft > countElements) { actualElementLeft = countElements }
                    actualElementRight = countElements;
                }
                else {
                    activeElement = activeElement.prev();
                    actualElementLeft = parseInt(actualElementLeft) - parseInt(picturesToShow);
                    actualElementRight = Math.floor((actualElementLeft/picturesToShow)+1) * picturesToShow;
                }
                sliderRoot.find('.actualElementLeft').html(actualElementLeft);
                sliderRoot.find('.actualElementRight').html(actualElementRight);
                activeElement.css('left', '-'+activeElement.width()+'px');
                activeElement.show();
                prevActiveElement.animate({ left: '100%' }, slideSpeed, function() { prevActiveElement.hide(); });
                activeElement.animate({ left: '0px' }, slideSpeed);
            }
        });
	}
	function recommendations_ForeFront(){
		if(jQuery('.addRecommendation').length>0) {
		  // check for every recommendations, recommendation count of votes.
		  jQuery('.addRecommendation').each(function(index) {
		    var firstNode = jQuery(this);
		    var articleId = jQuery(this).children('input').val();
		    checkRecommend_('recomendations_'+articleId,jQuery(this),articleId);
		    jQuery.ajax({
		      cache: false,
		      url: '/commonService/rekomendacje',
		      type: "GET",
		      data: ({ newsitemid: articleId }),
		      success: function(data){
			firstNode.children('.totalRecommendationsNumber').text(data);
		      }
		    });
		  })
		}
		  function checkRecommend_(cookieName,rootNode,article){
		    if (!checkCookie(cookieName)) {
		      rootNode.html('Dziękujemy za oddany głos,&nbsp;')
		    } else {
		      rootNode.children('#addRecommendationButton').bind('click', function(){
			jQuery.ajax({
			  cache: false,
			  url: '/commonService/rekomendacje',
			  type: "POST",
			  data: ({ newsitemid: article }),
		 	  success: function(data, jqXHR){
			    rootNode.children('.totalRecommendationsNumber').text(data);
			    setCookie('recomendations_'+article, article, 365);
			    rootNode.children('#addRecommendationButton').html('Dziękujemy za oddany głos,&nbsp;');
		    	    rootNode.children('#addRecommendationButton').unbind('click');
			  }
			});
		      })
		    }
		  }

		}
	

	function askQuestionInit() {
		jQuery('.askQuestionButtonAsk').click(function() {
            jQuery('.askQuestionForm').fadeIn();
            jQuery('.askQuestionButtonAsk').hide();
        });
        
        jQuery('.askQuestionFormCancel').click(function() {
            jQuery('.askQuestionButtonAsk').fadeIn();
            jQuery('.askQuestionForm').hide();
        });
                
        jQuery('.askQuestionButtonSuccessAsk').click(function() {
            jQuery('.askQuestionForm').fadeIn();
            jQuery('.askQuestionSuccess').hide();
        });
	
		function obsluzBledy(response) {
			for (key in response.validationResult) {
				jQuery('#nowePrawoFormularz .' + key).find('.blad').show();
				jQuery('#nowePrawoFormularz .' + key).find('.blad').html(
						response.validationResult[key]);
			}
		}
		jQuery('#nowePrawoFormularz').submit(function(event) {
			
			event.preventDefault();
			var anchor = jQuery(this);
	
			jQuery('#preloader').fadeIn();
			anchor.attr('disabled', 'disabled');
	
			var rowArr = rowArr = jQuery('#nowePrawoFormularz').serialize();
			rowArr = decodeURIComponent(rowArr);
	
			jQuery.ajax({
				url : jQuery('#nowePrawoFormularz').attr('action'),
				type : "POST",
				data : rowArr,
				dataType : "json",
				success : function(response) {
	
					jQuery('.blad').hide();
					jQuery('#preloader').hide();
					anchor.removeAttr('disabled');
	
					if (response.status == "VALIDATION_ERROR") {
						obsluzBledy(response);
					} else if (response.status == "OK") {
						jQuery('.askQuestionSuccess').fadeIn();
						jQuery('.askQuestionForm').hide();
						jQuery('.askQuestionTresc').val('');
					}
				}
			});
		});
	}
