var baseUrl = baseUrl ? baseUrl : '';
var thisSite = thisSite ? thisSite : '';
var siteUrl= 'http://' + baseUrl.split('/')[2];
var globalTmp= '';

//if (!('console' in window)){
//	window.console = { 
//		log: function(data){
//			$.noop();
//		},
//		error: function(data){
//			$.noop();
//		}
//	}
//}

xtbSite = {

    /**
	 * nieużywane
	 */
    backgroundSlide : function() {
        width = parseInt($('body').css('width'));
        bgWidth = 1900;
        dif = bgWidth - width;
        halfDif = parseInt(dif / 2);
        wrapper = jQuery("#wrapper");
        BGWrapper = $('#bg');
        var bg = wrapper.css('background-position');
        hPosition = bg.split(' ')[1];
        wrapper.css('background-position', (-halfDif) + 'px ' + hPosition);

        difIterator = halfDif;
        resizeBG = false;
        pxStep = 1;
        timeStep = 60;
        resetAfter = 10;
        odd = (halfDif % 2 == 1) ? 1 : 0;
        BGIntervalId = setInterval(function() {
            difIterator += pxStep;
            wrapper.css('background-position', (-difIterator) + 'px '
                + hPosition);
            if (difIterator === resetAfter * bgWidth
                || difIterator === resetAfter * bgWidth + odd) {
                difIterator = 0;
            }
        }, timeStep);
    }

    /**
	 * niepotrzebne?
	 */
    ,
    initAwardsSlideBlock : function() {
        blockWidth = 495;
        var awardsBlocks = $('.award');
        awardsCount = awardsBlocks.length;
        awardsList = $('#awards-list');
        awardsList.css('width', blockWidth * awardsCount);
        current = 1;
        var leftArrow = $('#awards-left');
        var rightArrow = $('#awards-right');

        leftArrow.click(function() {
            if (current !== 1) {
                currLeft = parseInt(awardsList.css('left'));
                awardsList.animate({
                    left : currLeft + blockWidth + 'px'
                });
                current--;
            }
        });
        rightArrow.click(function() {
            if (current !== awardsCount) {
                currLeft = parseInt(awardsList.css('left'));
                awardsList.animate({
                    left : currLeft - blockWidth + 'px'
                });
                current++;
            }
        });
    }

    /**
	 * inicjacja górnego menu
	 */
    ,
    topMenuInit : function() {
        topMenuItems = $('.top-menu-a');
        topMenuItemsLi = $('.top-menu-li');
        topOverMenu = $('.top-over-menu');
        var cont = $('#content');
        vPadding = 4;
        topMenuItemsLi.mouseover(function(e) {
            var submenu = $(this).find('.top-over-menu')
            submenu.children('.over').width($(this).width());
            items = submenu.children('.top-over-menu-item');
            newWidth = 'auto';
            containerOffset = cont.offset().left + parseInt(cont.css('width'));
            ulOffset = $(this).offset().left;

            if (items.size() < 4) {
                newWidth = (parseInt(items.css('width')) + 7) * items.size() + vPadding;
            } else {
                newWidth = 4 * (parseInt(items.css('width')) + 7) + vPadding;
            }

            newWidth = (newWidth > containerOffset - ulOffset) ? containerOffset - ulOffset - vPadding : newWidth;
            newDivider = parseInt(newWidth / (parseInt(items.css('width')) + 7));
            newWidth = newDivider * (parseInt(items.css('width')) + 7) + vPadding;
            submenu.css('width', newWidth);

            if (!$.browser.msie) {
                items.filter(':nth-child(' + (newDivider) + 'n-1)').addClass('left');
                items.filter(':nth-child(' + (newDivider) + 'n)').addClass('right');
            } else {
                items.filter(':nth-child(' + (newDivider) + 'n)').addClass('left');
                items.filter(':nth-child(' + (newDivider) + 'n+1)').addClass('right');
            }
            submenu.show();
        });
        topMenuItemsLi.find('.over').click(function() {
            //kliknięcie na pozycje menu, która poasiada submenu
            window.location = $(this).parent().siblings('.top-menu-a').attr('href');
        });
        topMenuItemsLi.mouseleave(function() {
            $(this).find('.top-over-menu').hide();
        });

        /* inits popup menu with webtrader login */
        $('#top-login-webtrader').mouseover(function() {
            $('#top-webtrader-menu').show();
        });
        $('#top-login-webtrader').mouseout(function() {
            $('#top-webtrader-menu').hide();
        });
    }

    /**
	 * wykresy
	 */
    ,
    initCharts : function() {
        if ($('.stats-chart-box .chart-window img')) {
            $('.stats-chart-box').each(function() {
                var $this = $(this);
                var $window = $this.children('.chart-window');
                var $img = $this.children('img');
                var IMG_WIDTH = 265;
                // var WIN_WIDTH = 178;
                var WIN_WIDTH = parseInt($window.width());
                var diff = IMG_WIDTH - WIN_WIDTH;
                var h = (new Date()).getHours();
                var pos = 0;
                if (h > 16) {
                    pos = diff;
                } else if (h > 8) {
                    pos = (h - 8) * diff / 8;
                }
                $img.css('left', -pos);
            });
        }
    }

    /**
	 * zakładki - strona główna, platformy, produkty
	 */
    ,
    initTabs : function() {

        var onTabChangeControl = function(event, ui) {
            xtbSite.initGlobalControls();
        };
        var onTabChange = function(event, ui) {
            var $tabs = $('.product-tabs'), 
            allWidth = $tabs.find(
                'div.product-tabs-menu-wrapper:visible').width(), 
            ulWidth = $tabs
            .find('ul.product-tabs-menu:visible').width(), $end = $tabs
            .find('div.product-tabs-menu-end');
            $end.width(allWidth - ulWidth);
        };
        if ($('.platforms-tabs').size()) {

            $('.platforms-tabs-tab')

            $('.platforms-tabs').tabs({
                show : function(event, ui) {
                    onTabChangeControl();
                    //dodawanie hasha do adresu po kliknięciu żeby działał powrót
                    //do wybranej zakłądki. btw uciekaj póki możesz
                    var hrefHash= $(event.target).find('.ui-state-active').find('a').attr('href');
                    var currentLocation= window.location.href;
                    currentLocation= currentLocation.replace(/#.+$/, '');
                    window.location.href = currentLocation +  hrefHash;

                    var switchables = $('.product-tabs.switchable');
                    if (switchables.size()) {
                        if (switchables.size() == switchables.filter(
                            ':visible').size()) {
                            // inicjacja
                            if(typeof hrefHash == "undefined"){
                                switchables.eq(1).hide();
                            }else{
                                switchables.hide();
                                $('.product-tabs.switchable[rel="' + hrefHash + '"]').show();
                            }
    
                        } else {
                            switchables.toggle();
                        }
                        onTabChange();
                    }
                }
            });
        }
        //strona główna
        if ($('.home-tabs').size() && thisSite == 'pl') {
            //POLSKA
            /*
			 // gówniany jQuery UI tak użyteczny jak zasiłek palikotowi
			$('.home-tabs').tabs({
				select: function() {
					var selected = $( ".home-tabs" ).tabs( "option", "selected" );
					alert('#tabs-' + (selected+1));
					var selectedContent= $('#tabs-' + (selected+1));
					selectedContent.html(selected);
				}
				,show : onTabChangeControl
			});
*/
            var homeTabs= $('.home-tabs-tab');
            var homeContents= $('.home-tabs-content-body');
            var hash= window.location.hash;
            var homeStart= 1;
            homeContents.hide();
			
            if (hash != '') {
                homeStart= hash.split('-')[1];
            }
            var selected= homeStart;
            $('#tabs-' + homeStart).show();
            this.selectHomeTab('#tabs-' + homeStart);
			
            homeTabs.click(function(e) {
                var linkHref= $(this).find('a').attr('href');
                var linkNumber= linkHref.split('-')[1];
                if (selected == linkNumber) {
                    var gotoHref= $(this).find('a').attr('rel');
                    window.location.href= gotoHref;
                } else {
                    //zmiana zakładki
                    homeContents.hide();
                    $(linkHref).show();
                    xtbSite.selectHomeTab(linkHref);
                    window.location.href= window.location.href.split('#')[0] + linkHref;
                }
                selected= linkNumber;
				
                return false;
            });
        } else if ($('.home-tabs').size()) {
            //pozostałe 
            $('.home-tabs').tabs({
                show : onTabChangeControl
            });
        } 
		    
        if ($('.product-tabs').size()) {
			
            $('.product-tabs').tabs({
                show : function() {
                    onTabChange();
                    onTabChangeControl();
                }
            });
        /*
			$(".product-tabs .product-tabs-menu > li").each(function(){
			    $(this).bind("click",function() {
				var id = $(this).attr("href");
				$(this).parents(".product-tabs").find(".product-tabs-content > div").hide();
				$(id).show();
			    })
			}); 
			*/
        // alert('initTabs');
        }
    }
    ,
    selectHomeTab: function(href) {
        var found= null;
        $('.home-tabs-tab').each(function() {
            if ($(this).find('a').attr('href') == href) {
                //				$(this).addClass('ui-state-active');
                found= $(this);
            }
        });
        if (found != null) {
            $('.home-tabs-tab').removeClass('ui-state-active');
            found.addClass('ui-state-active');
        }
    }

    /**
	 * tabelka analysis & research 2
	 */
    ,
    initImpactsFilter : function() {
        // if ($('#impacts-filter').length) {
        impactsInterval = setInterval(function() {
            var $fields = $('#impacts-filter input:checked');

            $rows = $('table.impacts-data tr:not(.no-filter)');
            if ($fields.length == 0) {
                $rows.css('display', '');
            } else {
                $rows.css('display', 'none');

                if ($fields.filter('[name^=country]').length > 0) {
                    $showRows = $(null);
                    $fields.filter('[name^=country]').each(
                        function() {
                            $showRows = $showRows.add($rows.filter('.'
                                + this.value));
                        });

                    $rows = $showRows;
                }

                if ($fields.filter('[name^=impact]').length > 0) {
                    $showRows = $(null);
                    $fields.filter('[name^=impact]').each(
                        function() {
                            $showRows = $showRows.add($rows.filter('.'
                                + this.value));
                        });

                    $rows = $showRows;
                }

                $rows.css('display', '');
            }

            $rows.each(function() {
                $localRows = $('tr:not(.no-filter):visible', this.parentNode);
                var i = $localRows.index(this);
                if (!(i % 2)) {
                    $(this).addClass('highlight');
                } else {
                    $(this).removeClass('highlight');
                }
            });
        }, 100);
    // }
    },
    initDemoAccountTabs : function() {
        if ($('.demo-account-tab-input').length > 0) {
            setInterval(
                function() {
                    $('.demo-account-tab').removeClass(
                        'demo-account-tab-selected');
                    $('.demo-account-tab-input:checked').parent().addClass(
                        'demo-account-tab-selected');
                    $('.demo-account-info-box').css('display', '');
                    $(
                        '#box_'
                        + $('.demo-account-tab-input:checked')
                        .attr('id')).css('display',
                        'block');
                }, 50);
        }
    },
    initReplaceImage : function() {
        $('a[rel^=replace_image]').bind('click', function(e) {
            e.preventDefault();

            var id = this.rel.split(':')[1];

            $('#' + id + '_title').html($(this).text());
            $('#' + id).bind('load', function() {
                $(this).css('opacity', '');
            }).css('opacity', 0).attr('src', this.href);
        });
    }

    /**
	 * skrypty wykorzystywane na stronie Management Board
	 */
    ,
    initMenago : function() {
        if ($('.list_menagment_board')) {
            $('.list_menagment_board').parent().removeClass('x-content');
        }
        if (typeof ($.jcarousel) == 'undefined') {
            return;
        }
        // if ($('.list_menagment_board_text').size()) {
        var Slide = function() {
            var _this = $('.list_menagment_board_text');
            _this.find('a').click(
                function(event) {
                    event.preventDefault();
                    var _this = $(this);
                    var _ts = _this.parent().parent().find(
                        'div.list_menagment_board_text_d');
                    var _h = _ts.find('p').height();
                    _ts.animate({
                        height : _h + 9
                    })
                });
        }

        var sActive = function() {
            $('.list-person li').eq(1).addClass('active');
            $('.w-430.person .jcarousel-next').click(function() {
                var _act = $('.w-430.person .list-person li.active');
                _act.find('img').animate({
                    width : 90
                });
                _act.removeClass('active');
                _act.next().addClass('active');
                _act.next().find('img').animate({
                    width : 103
                });
            });
            $('.w-430.person .jcarousel-prev').click(function() {
                var _act = $('.w-430.person .list-person li.active');
                _act.find('img').animate({
                    width : 90
                });
                _act.removeClass('active');
                _act.prev().addClass('active');
                _act.prev().find('img').animate({
                    width : 103
                });
            });
        }

        try {
            Slide();
            $('.carousel ul').jcarousel({
                scroll : 1
            });
            $('.list-person').jcarousel({
                scroll : 1
            });
            sActive();
        } catch (e) {
            if (typeof (console) != 'undefined') {
                console.error(e);
            }
        }
    }

    ,
    initHomeMenu : function() {
        $('.submenu-item.first').hover(function() {
            $('.home-submenu-top').addClass('hover');
        }, function() {
            $('.home-submenu-top').removeClass('hover');
        });
        $('.submenu-item.last').hover(function() {
            $('.home-submenu-bottom').addClass('hover');
        }, function() {
            $('.home-submenu-bottom').removeClass('hover');
        });

    }
	
    /**
	 * slider banner na stronie UK
	 */
    ,
    homeSliderBanner: function() {
        var carouselElem = $('.home-slider-banner-ul');
        var controls = $('.home-slider-controls a');
		
        var itemVisibleIn = function(carousel, li, index, state){
            controls.removeClass('active');
            controls.eq((index-1)).addClass('active');
        }
		
        var mycarouselInitCallback = function(carousel){
            controls.bind('click', function() {
                var index = $(this).attr("id").split("_");
                carousel.scroll($.jcarousel.intval(index[1]));
                return false;
            });
        }
		
        carouselElem.jcarousel({
            scroll: 1,
            auto: 5,
            wrap: 'last',
            itemFallbackDimension: 694,
            itemVisibleInCallback: itemVisibleIn,
            initCallback: mycarouselInitCallback,
            buttonNextHTML: null,
            buttonPrevHTML: null
        });

		
    }

    /**
	 * box Contact us
	 */
    ,
    initContactBox : function() {
        var wrappers = $('.side-contact-content-container');
        wrappers.each(function() {
            $(this).find('.contact-numbers-wrapper').hide().eq(0).show();
        });
        wrappers.hide().eq(0).show();
        $('select.side-contact').change(function() {
            var selectedIndex = this.selectedIndex;
            if ($(this).hasClass('side-contact-main-select')) {
                wrappers.hide().eq(selectedIndex).show();
            } else {
                // numery
                var numbers = $(this).siblings('.contact-numbers-wrapper');
                numbers.hide().eq(selectedIndex).show();
            }
        });
    }

    /**
	 * Metoda inicjująca globalnie używane kontrolki
	 */
    ,
    initGlobalControls : function() {
        // overflow control
        var overflowControlsHeights = new Array();
        var overflowControlsFoldedHeights = new Array();
        $('.js-control-overflow:visible').each(
            function() {
                var className = $(this).attr('class').replace(
                    /js-control[^ ]*/, '');
                var elementHeight = 0;
                var marker = $(this).find('.js-overflow-control-marker');
                                
                var parentsHidden = false;
                $(this).parents().andSelf().each(function() {
                    if ($(this).css('display') == 'none') {
                        parentsHidden = true;
                    }
                });
                if (parentsHidden) {
                    return;
                }
                if (marker.size() > 0) {
                    elementHeight = marker.position().top;        
                } else if (className == '') {
                    elementHeight = 80;
                } else {
                    elementHeight = className.split('-')[1];
                }
                                
                overflowControlsHeights.push($(this).height());
                overflowControlsFoldedHeights.push(elementHeight);
                $(this).css('height', elementHeight);
                $(this).find('.js-control-overflow-body').css('height',
                    elementHeight);
                $(this).find('.fold').hide();
            });
        $('.js-control-overflow-switch:visible').click(
            function(e) {
                var _this = $(this);
                _this.css('background', 'transparent url("' + baseUrl
                    + 'image/layout/preloader.gif") no-repeat left');
                _this.css('padding-left', '18px');

                var parent = _this.parent();
                var newHeight = overflowControlsHeights[$(
                    '.js-control-overflow-switch').index(this)];
                                
                if (parseInt(parent.height()) == overflowControlsHeights[$(
                    '.js-control-overflow-switch').index(this)]) {
                    newHeight = overflowControlsFoldedHeights[$(
                        '.js-control-overflow-switch').index(this)];
                    _this.find('.fold').hide();
                    _this.find('.unfold').show();
                } else {
                    _this.find('.unfold').hide();
                    _this.find('.fold').show();
                }
                parent.animate({
                    height : newHeight
                }, 200);
                parent.children('.js-control-overflow-body').animate({
                    height : newHeight
                }, 200, function() {
                    _this.css('background', 'none');
                    _this.css('padding-left', '0px');
                });

            //e.preventBubble();

            });
			
        // GPW - giełda online - raporty
        $('.gpw-raport').find('table').addClass('border').addClass('zebra').addClass('rows');
			

        // links with target=blank
        $('a.target-blank').attr("target", "_blank");
		
        //fancybox
        if ($.fancybox != undefined) {
            $("a[rel=lightbox]").fancybox({
                'titleShow'     : false,
                'transitionIn' : 'none',
                'transitionOut' : 'none'
            });
        }
		
    //random swf token 
    //		var token= '';
    //		token= Math.random();
    //		token= token.toString().substr(2);
    //		$('object').each(function(){
    //			var value= $(this).attr('data').split('?')[0];
    //			$(this).attr('data', value + '?'+token);
    //		});
    //		$('param[name=movie]').each(function(){
    //			var value= $(this).attr('value').split('?')[0];
    //			$(this).attr('value', value + '?'+token);
    //		});	
		
    }

    /**
	 * initiates left Facebook bar.
	 */
    ,
    initFacebookWidget : function() {
        var elem = $('#fb');
        var elemLogo = $('#fb-fb');
        var elemHome = $('#set-as-homepage');
        var elemDesc = $('#sah-desc');
        var link = $('#fb-a');
        var tradingCupLogo = jQuery('#fb-trading-cup');
        var tradingCupLink = jQuery('#fb-trading-cup-a');
        if (elem) {
            if ($('#wrapper').width() < 1100) {
                var elemHiddenWidth = 16;
                var elemFullWidth = 50;

                // var set= elem.children().andSelf();
                elem.width(elemHiddenWidth);
                elem.mouseover(function() {
                    // set.mouseover(function(){
                    elem.animate({
                        width : elemFullWidth
                    }, 100);
                });
                elem.mouseout(function() {
                    // set.mouseout(function(){
                    elem.animate({
                        width : elemHiddenWidth
                    }, 100);
                });
            }

            link.attr('target', '_blank');
            tradingCupLogo.click(function() {
                window.location.href = tradingCupLink.attr('href');
            });
            elemLogo.click(function() {
                window.location.href = link.attr('href');
            // link.click();
            });

            // z netu - NIE DZIAŁA ?
            var setAsHomepage = function() {
                if (document.all) {
                    document.body.style.behavior = 'url(#default#homepage)';
                    document.body.setHomePage(siteUrl);

                } 
            };

            elemHome.click(setAsHomepage);
			
            elemDesc.hide();
            elemHome.hover(function() {
                elemDesc.show();
            }, function() {
                elemDesc.hide();
            });

        }
    }
	
    /**
	 * facebook na PL
	 */
    ,
    plFacebookFeed: function(options) {
        options= options === undefined ? {} : options;
        var url= options.url === undefined ? 'jsapi.xtb.pl/fb/query?query=xtbpl/feed' : options.url;
        //		var url= options.url === undefined ? './xtbpl-feed.html' : options.url;
        var xtbPlId= '155747967133';
        var newsCount= options.count === undefined ? 2 : options.count;
        var targetDiv= options.targetDiv === undefined ? $('#homepl-feed') : options.targetDiv;
		
        var defLink= options.defLink === undefined ? 'http://www.facebook.com/xtbpl' : options.defLink;
        var defName= options.defName === undefined ? 'X-Trade Brokers Dom Maklerski' : options.defName;
        var defText= options.defText === undefined ? 'Osoby <a href="" class="pl-fb-likes">(0)</a> lubią to. <a href="" class="pl-fb-comments">Zobacz wszystkie kometarze :<span>0</span></a>' : options.defText;
		
        var manager = pl.mediovski.technology.ConnectorRequestManager.getInstance();
		
		
        var hash = manager.get(url, function(data) {
            for (i= 0; i < newsCount; i++) {
                var post= data.data[i];
                if (post.from.id != xtbPlId) {
                    newsCount++;
                } else {

                    var row= $('<div class="pl-fb-row"/>');
                    var name= $('<a class="pl-fb-title target-blank" target="_blank" />');
                    var body= $('<div class="pl-fb-body" />');
                    var picLink= $('<a class="pl-fb-pic-wrapper target-blank" target="_blank" />');
                    var pic= $('<img class="pl-fb-pic" />');
                    var msg= $('<div class="pl-fb-msg" />');
                    var bottom= $('<div class="pl-fb-bottom" />');

                    var directLink= 'http://www.facebook.com/xtbpl/posts/' + post.id.split('_')[1];
                    var link= (post.link === undefined) ? directLink : post.link;
                    var likesCount= 0;
                    if (post.likes != undefined && post.likes.count != undefined) {
                        likesCount= post.likes.count;
                    }
                    var commentsCount= 0;
                    if (post.comments != undefined && post.comments.count != undefined) {
                        commentsCount= post.comments.count;
                    }

                    name.text( post.name === undefined ? defName : post.name );
                    msg.text(post.message === undefined ? '' : post.message);
                    name.attr('href', link);
                    bottom.html(defText);
                    bottom.find('.pl-fb-likes').attr('href', directLink).text('(' + likesCount + ')');
                    bottom.find('.pl-fb-comments').attr('href', directLink).find('span').text(commentsCount);

                    if (post.picture !== undefined) {
                        pic.attr('src', post.picture);
                        picLink.attr('href', link)
                        picLink.append(pic);
                        body.append(picLink);
                    }

                    body.append(msg);
                    row.append(name).append(body).append(bottom);
                    targetDiv.append(row);
                }
            }
        }, 'json');
    }
    ,
    roFacebookFeed: function(options) {
        options= options === undefined ? {} : options;
        var url= options.url === undefined ? 'jsapi.xtb.ro/fb/query?query=xtbro/feed' : options.url;
        //		var url= options.url === undefined ? './xtbro-feed.html' : options.url;
        var xtbRoId= '285954771203';
        var newsCount= options.count === undefined ? 2 : options.count;
        var targetDiv= options.targetDiv === undefined ? $('#homero-feed') : options.targetDiv;
		
        var defLink= options.defLink === undefined ? 'http://www.facebook.com/xtbro' : options.defLink;
        var defName= options.defName === undefined ? 'X-Trade Brokers Romania' : options.defName;
        var defText= options.defText === undefined ? '<a href="" class="pl-fb-likes">(0)</a> de persoane apreciază asta. <a href="" class="pl-fb-comments">Vezi toate cele <span>0</span> comentarii</a>' : options.defText;
		
        var manager = pl.mediovski.technology.ConnectorRequestManager.getInstance();
		
		
        var hash = manager.get(url, function(data) {
            for (i= 0; i < newsCount; i++) {
                var post= data.data[i];
                if (post.from.id != xtbRoId) {
                    newsCount++;
                } else {

                    var row= $('<div class="pl-fb-row"/>');
                    var name= $('<a class="pl-fb-title target-blank" target="_blank" />');
                    var body= $('<div class="pl-fb-body" />');
                    var picLink= $('<a class="pl-fb-pic-wrapper target-blank" target="_blank" />');
                    var pic= $('<img class="pl-fb-pic" />');
                    var msg= $('<div class="pl-fb-msg" />');
                    var bottom= $('<div class="pl-fb-bottom" />');

                    var directLink= 'http://www.facebook.com/xtbro/posts/' + post.id.split('_')[1];
                    var link= (post.link === undefined) ? directLink : post.link;
                    var likesCount= 0;
                    if (post.likes != undefined && post.likes.count != undefined) {
                        likesCount= post.likes.count;
                    }
                    var commentsCount= 0;
                    if (post.comments != undefined && post.comments.count != undefined) {
                        commentsCount= post.comments.count;
                    }

                    name.text( post.name === undefined ? defName : post.name );
                    msg.text(post.message === undefined ? '' : post.message);
                    name.attr('href', link);
                    bottom.html(defText);
                    bottom.find('.pl-fb-likes').attr('href', directLink).text('(' + likesCount + ')');
                    bottom.find('.pl-fb-comments').attr('href', directLink).find('span').text(commentsCount);
                                        
                    if (post.picture !== undefined) {
                        pic.attr('src', post.picture);
                        picLink.attr('href', link)
                        picLink.append(pic);
                        body.append(picLink);
                    }

                    body.append(msg);
                    row.append(name).append(body).append(bottom);
                    targetDiv.append(row);
                }
            }
        }, 'json');
    }
    ,
    plHomePage: function() {
        //		$('#pl-home-side').
        var buttons= $('#pl-buttons-row').find('.button');
        var contents= $('#pl-home-side').find('.pl-side-content').hide();
        contents.eq(0).show();
        buttons.eq(0).addClass('red');
		
        buttons.click(function() {
            var _this= $(this);
            var n= _this.index();

            buttons.removeClass('red');
            _this.addClass('red');
			
            contents.hide();
            contents.eq(n).show();
            return false;
        });
    }
    ,
    plKalendarium: function() {
		
        //		$('.macronext-kalendarium-gpw').find('table').eq(0).addClass('pl-kalendarium-past');
        //		$('.macronext-kalendarium-gpw').find('table').slice(1).addClass('pl-kalendarium-table-incoming');
		
        $('.macronext-kalendarium-gpw').find('table').each(function() {
            var table= $(this);
            var days = 0;
            var difference = 0;
            var tableDate= new Date(table.find('.date').text());
            var today = new Date();
            difference = tableDate - today;
            days = Math.round(difference/(1000*60*60*24));
            if (days != 0) {
                table.addClass('pl-kalendarium-table-incoming');
            } 
        //			if (days < 0) {
        //				table.addClass('pl-kalendarium-table-incoming');
        //			} else if (days > 0) {
        //				table.addClass('pl-kalendarium-table-incoming');
        //			}
        });
    }

    /**
	 * skrypty dla ie
	 */
    ,
    initIE : function() {
        if ($.browser.msie) {
            $('.top-over-menu').corner('5px');
            if (parseInt($.browser.version)<9) {
                if ($('.x-content table.zebra').length > 0) {
                    $(".x-content table.zebra tr:nth-child(even) td").each(function(){
                        $(this).css("background-color","#EDEDED");
                    });
                }
            }
        }
    }

    /**
	 * inicjacja skryptu
	 */
    ,
    init : function() {
        // this.backgroundSlide();
        this.initAwardsSlideBlock();

        // this.leftMenuInit();
        this.topMenuInit();
        this.initCharts();
        this.initFacebookWidget();
		
        this.initImpactsFilter();
		
        this.initDemoAccountTabs();
        this.initReplaceImage();

        this.initHomeMenu();

        this.initContactBox();
        // this.initGlobalControls();

        this.initTabs();
        this.initGlobalControls();

        this.initIE();

        // $("#wrapper").pan({fps: 900, speed: .4, dir: 'right'});
        this.initMenago();
    }
};

$(function() {

    xtbSite.init();

    //remeber last url
    try{
        var pos = location.href.indexOf('?');
        if(pos != -1){
            pl.mediovski.technology.cookie.set('_q',location.href.substr(pos+1),{
                path:'/'
            });
        }
    }catch(e){}	
});

// function caruselChange(n) {
// // alert(n)
// void(null);
// }

/*
 * Date Format 1.2.3 (c) 2007-2009 Steven Levithan <stevenlevithan.com> MIT
 * license
 * 
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal
 * <cixar.com/~kris.kowal/>
 * 
 * Accepts a date, a mask, or a date and a mask. Returns a formatted version of
 * the given date. The date defaults to the current date/time. The mask defaults
 * to dateFormat.masks.default.
 */

var dateFormat = function() {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function(
        val, len) {
        val = String(val);
        len = len || 2;
        while (val.length < len)
            val = "0" + val;
        return val;
    };

    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask
        // prefix)
        if (arguments.length == 1
            && Object.prototype.toString.call(date) == "[object String]"
            && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date))
            throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_
        + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_
        + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"]
        (), L = date[_ + "Milliseconds"](), o = utc ? 0 : date
        .getTimezoneOffset(), flags = {
            d : d,
            dd : pad(d),
            ddd : dF.i18n.dayNames[D],
            dddd : dF.i18n.dayNames[D + 7],
            m : m + 1,
            mm : pad(m + 1),
            mmm : dF.i18n.monthNames[m],
            mmmm : dF.i18n.monthNames[m + 12],
            yy : String(y).slice(2),
            yyyy : y,
            h : H % 12 || 12,
            hh : pad(H % 12 || 12),
            H : H,
            HH : pad(H),
            M : M,
            MM : pad(M),
            s : s,
            ss : pad(s),
            l : pad(L, 3),
            L : pad(L > 99 ? Math.round(L / 10) : L),
            t : H < 12 ? "a" : "p",
            tt : H < 12 ? "am" : "pm",
            T : H < 12 ? "A" : "P",
            TT : H < 12 ? "AM" : "PM",
            Z : utc ? "UTC" : (String(date).match(timezone) || [ "" ]).pop()
            .replace(timezoneClip, ""),
            o : (o > 0 ? "-" : "+")
            + pad(
                Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o)
                % 60, 4),
            S : [ "th", "st", "nd", "rd" ][d % 10 > 3 ? 0
            : (d % 100 - d % 10 != 10) * d % 10]
        };

        return mask.replace(token, function($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default" : "ddd mmm dd yyyy HH:MM:ss",
    shortDate : "m/d/yy",
    mediumDate : "mmm d, yyyy",
    longDate : "mmmm d, yyyy",
    fullDate : "dddd, mmmm d, yyyy",
    shortTime : "h:MM TT",
    mediumTime : "h:MM:ss TT",
    longTime : "h:MM:ss TT Z",
    isoDate : "yyyy-mm-dd",
    isoTime : "HH:MM:ss",
    isoDateTime : "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime : "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames : [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday",
    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
    monthNames : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
    "Sep", "Oct", "Nov", "Dec", "January", "February", "March",
    "April", "May", "June", "July", "August", "September", "October",
    "November", "December" ]
};

dateFormat.parseIsoString = function(isoUtcString) {
    try {
        var r = /^([0-9]{4})-([0-9]{2})-([0-9]{2})([T ]([0-9]{2}):([0-9]{2}):([0-9]{2})(\+?(\-?[0-9]{2}):?([0-9]{2})?)?)?$/;
        var d = isoUtcString.match(r);
        for ( var i = 1; i < d.length; i++) {
            if (typeof (d[i]) == 'string' && d[i] != '') {
                d[i] = parseInt(d[i], 10);
            }
        }
        var month = d[2] - 1;
        if (typeof (d[5]) == 'number' && !isNaN(d[5])) {

            var hour = d[5];
            var time = new Date(d[1], month, d[3], hour, d[6], d[7]);
            return time;
        } else {
            var time = new Date(d[1], month, d[3], 0, 0, 0);
            return time;

        }
    } catch (e) {
        return null;
    }
};

// For convenience...
Date.prototype.format = function(mask, utc) {
    return dateFormat(this, mask, utc);
};

Date.parseString = function(isoUtcString) {
    return dateFormat.parseIsoString(isoUtcString);
};

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
};

/**
 * Month days
 */
Date.prototype.getMonthLenght = function() {
    var _monthsDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
    if (this.getMonth() == 1) {
        if ((this.getFullYear() % 4 == 0 && this.getFullYear() % 100 != 0)
            || this.getFullYear() % 400 == 0) {
            return 29;
        }
    }
    return _monthsDays[this.getMonth()]
};

/**
 * Month days
 */
Date.prototype.getLastDay = function() {
    var _date = new Date(this.getFullYear(), this.getMonth(), this
        .getMonthLenght(), 0, 0, 0, 0);
    return _date.getDay();
};

try {
    var langs = {
        en : {
            dayNames : [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
            "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
            "Friday", "Saturday" ],
            monthNames : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
            "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February",
            "March", "April", "May", "June", "July", "August",
            "September", "October", "November", "December" ]
        },
        fr : {
            dayNames : [ "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam",
            "Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi",
            "Vendredi", "Samedi" ],
            monthNames : [ "Jan", "Févr", "Mar", "Avr", "Mai", "Jui", "Jul",
            "Aou", "Sep", "Oct", "Nov", "Déc", "Janvier", "Février",
            "Mars", "Avril", "Mai", "Juin", "Juillet", "Aout",
            "Septembre", "Octobre", "Novembre", "Décembre" ]
        },
        it : {
            dayNames : [ "Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab",
            "Domenica", "Lunedì", "Martedì", "Mercoledi", "Giovedi",
            "Venerdi", "Sabato" ],
            monthNames : [ "Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug",
            "Ago", "Set", "Ott", "Nov", "Dic", "Gennaio", "Febbraio",
            "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto",
            "Settembre", "Ottobre", "Novembre", "Dicembre" ]
        },
        de : {
            dayNames : [ 
            "So", "Mo", "Die", "Mit", "Don", "Fre", "Sam",
            "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag","Freitag", "Samstag" 
            ],
            monthNames : [ 
            "Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul","Aug", "Sep", "Okt", "Nov", "Dez", "Januar", "Februar",
            "März", "April", "Mai", "Juni", "Juli", "August","September", "Oktober", "November", "Dezember" 
            ]
        },
        tr :{
            dayNames: [
            "Pzr", "Pts", "Sl", "SZe", "Çr", "Cu", "Cts",
            "Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi"
            ],
            monthNames: [
            "Ock", "Şub", "Mrt", "Nis", "May", "Haz", "Tem", "Ağs", "Eyl", "Ekm", "Kas", "Ara",
            "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
            ]
        },
        hu:{
            dayNames: [
            "V", "H", "K", "SZe", "CS", "P", "SZo",
            "Vasárnap", "Hétfő", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat", "Vasárnap"],
            monthNames: [
            "Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Szept", "Okt", "Nov", "Dec",
            "Január", "Február", "Március", "Május", "Aprilis", "Június,", "Július", "Augusztus", "Szeptember", "Október", "November", "December"
            ]
        },
        pl:{
            dayNames: [
            "Nd.", "Pn.", "Wt.", "Śr.", "Czw.", "Pt.", "Sb.",
            "Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota"
            ],
            monthNames: [
            "St.", "Lt.", "Mrz.", "Kwiec.", "Maj", "Czerw.", "Lip.", "Sierp.", "Wrzes.", "Paźdz.", "Listop.", "Grudz.",
            "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"
            ]
        },
        cz:{
            dayNames: [
            "Ne", "Po", "Út", "St", "Čt", "Pá", "So", 
            "Neděle", "Pondělí", "Úterý", "Středa", "Čtvrtek", "Pátek", "Sobota" 
            ],
            monthNames: [
            "Led", "Úno", "Bře", "Dub", "Kvě", "Čer", "Červ", "Spr", "Zář", "Říj", "Lis", "Pro",
            "Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"
            ]
        },
        sk:{
            dayNames: [
            "Ne", "Po", "Ut", "St", "Štv", "Pia", "So", 
            "Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota" 
            ],
            monthNames: [
            "Jan", "Feb", "Mar", "Apr", "Máj", "Jún", "Júl", "Aug", "Sept", "Okt", "Nov", "Dec",
            "Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"
            ]
        },
        se:{
            dayNames: [
            "So", "Må", "Tis", "Ons", "Tor", "Fre", "Lör",
            "Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"
            ],
            monthNames: [
            "Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec",
            "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
            ]
        }
    };
    if (langs[thisSite])
        dateFormat.i18n = langs[thisSite];
} catch (e) {
}
// kontrolny komentarz 

