$.fn.centerInClient = function(options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}

function more(e) {
		e.preventDefault();
		
		trigger = $(this); 
                toHide = trigger.siblings('.short');
		toExpand = trigger.siblings('.more');
		toReplace = $(this).children('span');
		toMark = $(this).parent();
		_gaq.push(['_trackEvent', $(this).parent().parent().find("h2").text(),'View', $(this).parent().children("h3").text()]);
		toExpand.toggle();	
                toHide.toggle();
		setTimeout('restyle(toExpand, toReplace, toMark, trigger)', 350);
}


function next_page(e)
{
e.preventDefault();
var box = $($(this).parents(".box")[0]);
box.load(box.attr('url') + '?page=' + (parseInt(box.attr('page'))+1), function(html)
{
    box.attr('page',  parseInt(box.attr('page'))+1);
    box.find(".newsNextPage").click(next_page);
    
    box.find(".newsPrevPage").click(prev_page);
    box.find('a.readMore').click(more);
}
);
}

function prev_page(e)
{
e.preventDefault();
var box = $($(this).parents(".box")[0]);
box.load(box.attr('url') + '?page=' + (parseInt(box.attr('page'))-1), function(html)
{

    box.attr('page',  parseInt(box.attr('page'))-1);

    box.find(".newsNextPage").click(next_page);
    box.find(".newsPrevPage").click(prev_page);
    box.find('a.readMore').click(more);   
}
);
}

function rotator1_items(items_page)
{
    var startingSlide = 0,
        per_page=10;
    if(items_page)
    {
        startingSlide = (items_page * per_page-1)+1;
    }
    $('#rotator-1 .items').cycle({
        fx: 'fade',
        speed: 1000,
        timeout: 4000, 
        startingSlide:startingSlide,
        prev: '#rotator-1 .prev a',
        next: '#rotator-1 .next a',
        before: function(currSlideElement, nextSlideElement, options, forwardFlag){
            //alert(currSlideElement);
            var index = parseInt($(currSlideElement).attr('index'))+1;
            var page = ((index/per_page)|0)+1;
            //alert(index + " "+ page);

            var $items = $("#rotator-1 .items"),
                $pageItems = $("#rotator-1 .page_" + page);

            if($pageItems.length == 0 && page < 7)
            {

             $.ajax({
                url: "/ajax/case-study/" + page,
                dataType: 'html',
                async:false,
                success: function(data){
                  var $itemsCache = $("#items_cache");
                  $itemsCache.html(data);
                  $itemsCache.find('li').each(function(){
                    options.addSlide($('<div>').append($(this).clone()).remove().html());
                  });
               }             
            });
            }
        }
    });
    
}
$(document).ready(function() {	

// rotators
(function(){
    rotator1_items();
	
	$('#rotator-2 .items').cycle({
		fx: 'fade',
		speed: 1000,
		timeout: 4000,
		prev: '#rotator-2 .prev a',
		next: '#rotator-2 .next a'
	});
	
	$('#rotator-1, #rotator-2').hover(function(){
		$(this).find('.items').cycle('pause');
	}, function(){
		$(this).find('.items').cycle('resume');
	});
})();


jQuery.each(jQuery.browser, function(i) {
  if($.browser.opera){
     $("#markiza").css("margin-top","-2px");
  } else if($.browser.msie){
     $("#markiza").css("margin-top","-10px");
  } else if($.browser.safari){
     $("#markiza").css("margin-top","-8px");
     $("#bubble").css("top","");
  } else {
     $("#markiza").css("margin-top","-2px");
  }
});

$("#refs a.more").click(function(e)
{
   e.preventDefault();
   _gaq.push(['_trackEvent', 'Referencje', 'View', $(this).parent().children(".ref-author").text() + ' ' + $(this).attr('href')]);
setTimeout(" window.location = '"+$(this).attr('href')+"'", 3000);
});

// $jScroller.config.refresh = 1;  
// $jScroller.add("#markiza","#markizaContent","left",1,true);
// $jScroller.start();
//$("#markizaContent").liScroll();
$(".clickFancy").fancybox({imageScale:false, centerOnScroll:false});
$(".clickVideo").click(function(e)
{
  e.preventDefault();
  var who = $("#whoWeAreVideo");
  $("#blackOverlay").fadeIn(100);
  $("#blackOverlay").click(function(e)
  {
		  who.fadeOut(100);
		  $("#blackOverlay").fadeOut(100);
		
  });

  who.fadeIn();
  who.centerInClient({container:window,forceAbsolute:true});
}
);
$(".fancy_close").click(function(e)
		  {
			  e.preventDefault();
			  who.fadeOut(100);
			  $("#blackOverlay").fadeOut(100);	  
		  });


// clear inputs 
$(".clearInput").click(function() {
	if(!$(this).attr('cleanInput'))
	{
		$(this).attr('cleanInput', true); 
		$(this).val('');
	}
});

// Newsletter form 
$("#subscribeButton").click(function(event){
	event.preventDefault();
	$("#newsletterForm").submit();
});
$("#unsubscribeButton").click(function(event){
	event.preventDefault();
	$("#newsletterForm").attr('action', $(this).attr("href"));
	$("#newsletterForm").submit();
});
var theme = readCookie('theme');
switch(theme) {
	case 't01':
		$('#t01').addClass('activeTheme'); 
		$('body').attr('id','bodyTheme01');	
	break;
	case 't02':
		$('#t02').addClass('activeTheme'); 
		$('body').attr('id','bodyTheme02');	
	break;
	case 't03':
		$('#t03').addClass('activeTheme'); 
		$('body').attr('id','bodyTheme03');	
	break;
	case 't04':
		$('#t04').addClass('activeTheme'); 
		$('body').attr('id','bodyTheme04');
	case 't05':
		$('#t05').addClass('activeTheme'); 
		$('body').attr('id','bodyTheme05');		
	break;
	case 't06':
		$('#t06').addClass('activeTheme'); 
		$('body').attr('id','bodyTheme06');		
	break;
}

$(".showCaseStudy1").click(function(event){
	$("#blackOverlay").fadeIn(100);
    $("#caseStudy1").fadeIn(400);
});  
$(".showCaseStudy2").click(function(event){
	$("#blackOverlay").fadeIn(100);

    $("#caseStudy2").fadeIn(400);
    
}); 
$(".showCaseStudy3").click(function(event){
	$("#blackOverlay").fadeIn(100);
    $("#caseStudy3").fadeIn(400);
});

$(".showCaseStudy4").click(function(event){
    $("#blackOverlay").fadeIn(100);
    $("#caseStudy4").fadeIn(400);
});

$(".showCaseStudy5").click(function(event){
    $("#blackOverlay").fadeIn(100);
    $("#caseStudy5").fadeIn(400);
});

$(".showCaseStudy6").click(function(event){
    $("#blackOverlay").fadeIn(100);
    $("#caseStudy6").fadeIn(400);
});

$(".showCaseStudy7").click(function(event){
    $("#blackOverlay").fadeIn(100);
    $("#caseStudy7").fadeIn(400);
});

$(".casestudies a").click(function(e){
    e.preventDefault();
    $("#blackOverlay").fadeIn(100);
    //strange hack
    var casestudy_id = this.href.split('_')[1];
    $("#caseStudy" + casestudy_id).fadeIn(400);
});
$("a.close").click(function(event){
    $(this).parent().parent().fadeOut(400);
    $("#blackOverlay").hide();
    $f("*").each(function(){
        this.stop();
    });
});
$('.closeIcon').click(function(event) {
	event.preventDefault();
	$('#whoOverlay').fadeOut(300);
});

$('#whoTrigger').click(function() {
	$('#whoOverlay').fadeIn(400);
});
	
$('a.readMore').click(more);
$('a.arrow').click(function(event) {
	event.preventDefault();	
});

$("#closeLoginButton").click(function(e)
{
    $(this).parents("#loginBox").css('display','none');
});

$('p.toHighlight').hover(
		function() {
			el = $(this).attr('id');
			el = el.split('_')[1];
			$(this).removeClass('inactive');
			$('#icon_'+el).addClass('activeIcon');
		},
		function() {
			$(this).addClass('inactive');
			$('#icon_'+el).removeClass('activeIcon');
		}
	);

$(function() {
	$("#submitLoginButton").click(function(){
		$("#extranetLoginForm").submit();
		
		
	});
	
//    $("a.reference_image").fancybox();
	$("#refs").scrollable({
		size: 3,
		items: '.items',
		clickable: false,
		api: true,
		onReload: function() { 
   					var currentPage = this.getPageIndex();
   					var allPages = this.getPageAmount(); 
    
    				$('#counter').html((currentPage + 1) + '/' + allPages);
}, 	
		onSeek: function() { 
   					var currentPage = this.getPageIndex();
   					var allPages = this.getPageAmount(); 
					if (currentPage ==0)
					{
					$("#moveLeft").css('display','none');
					
					}
					else
					{

					$("#moveLeft").css('display','block');
					}
						if (currentPage ==allPages-1)
					{
					$("#moveRight").css('display','none');
					
					}
					else
					{

					$("#moveRight").css('display','block');
					}				
    
    				$('#counter').html((currentPage + 1) + '/' + allPages);
} 	
});
});	
/*$(function() {
	$("#logotypesContainer").scrollable({
		size: 1,
		item: '.logotypes',
		items: '.items2',
		nextPage: '.hiddenArrow',
		prevPage: '.hiddenArrow',
		clickable: false,	
	}).autoscroll(2000, {autoplay: true}).circular();
});*/

$(".newsNextPage").click(next_page);
$(".newsPrevPage").click(prev_page);
$('#logotypesContainer').cycle({
            timeout: 1000,
            speed: 1000,
            cleartypeNoBg: true
});

$('#themeSelection a').click(function(event) { 
	event.preventDefault();  
	var theme = $(this).attr('id');
	createCookie('theme',theme, 720);
});

$('#t01').click(function() { $('#themeSelection a').removeClass('activeTheme'); $(this).addClass('activeTheme'); $('body').attr('id','bodyTheme01');  });
$('#t02').click(function() { $('#themeSelection a').removeClass('activeTheme'); $(this).addClass('activeTheme'); $('body').attr('id','bodyTheme02');  });
$('#t03').click(function() { $('#themeSelection a').removeClass('activeTheme'); $(this).addClass('activeTheme'); $('body').attr('id','bodyTheme03');  });
$('#t04').click(function() { $('#themeSelection a').removeClass('activeTheme'); $(this).addClass('activeTheme'); $('body').attr('id','bodyTheme04');  });
$('#t05').click(function() { $('#themeSelection a').removeClass('activeTheme'); $(this).addClass('activeTheme'); $('body').attr('id','bodyTheme05');  });
$('#t06').click(function() { $('#themeSelection a').removeClass('activeTheme'); $(this).addClass('activeTheme'); $('body').attr('id','bodyTheme06');  });

$(".audioContainer").flowplayer("/webroot/f/flowplayer.swf", {          
                                                                        
    // fullscreen button not needed here                                
    plugins: {                                                          
        audio: {                                                        
        url: '/webroot/f/flowplayer.audio.swf'                          
       },                                                               
        controls: {                                                     
            fullscreen: false                                          
        }                                                               
    },                                                                  
    clip: {                                                             
        autoPlay: false                                                 
        }                                                               
    } );                                                                
$(".videoContainer").flowplayer({wmode:'transparent',src:"/webroot/f/flowplayer.swf"},{
        clip:{
            autoPlay:false,
            autoBuffering:false
        }, play:{opacity:0}
    });

$('#loginItem').click(function(event) {
	event.preventDefault();

	$('#loginBox').toggle();
});
$('#nsTrigger').click(function(event) {
	event.preventDefault();
	$('#newsletterBox').toggle(100);
});

$('.subBox li a').hover(function() {
		var iconSrc = '/webroot/' + $(this).attr('title') ;
		$('#foo').attr('src',iconSrc);	
});
$('.subBox li a').hover(function() {
		var iconSrc = '/webroot/' + $(this).attr('title') ;
		$('#foo').attr('src',iconSrc);	
});
$('#searchButton').click(function(event) {
	event.preventDefault();
	$('#searchForm').submit();
});

$(".reference_image").fancybox({ imageScale:false, 'hideOnContentClick': false });});

function restyle(toExpand, toReplace, toMark, trigger) {
			if(toExpand.css('display') == 'block') {
				trigger.css('background-color', '#e6262b');
				trigger.addClass('hide');
				toMark.css('border-color','#e6262b');
				toReplace.fadeOut(50);
				setTimeout("toReplace.html('schowaj')", 100);
				toReplace.fadeIn(120);
				
} 
			else {
				trigger.css('font-size', '11px');
				trigger.css('background-color', '#999');
				trigger.removeClass('hide');
				toMark.css('border-color','#999');
				toReplace.fadeOut(50);
				setTimeout("toReplace.html('czytaj dalej')", 100);
				toReplace.fadeIn(120);	
}
}
function createCookie(name,value,expDate) { 
/* expDate wyrazony w minutach */
	if (expDate) {
		var date = new Date();
		date.setTime(date.getTime()+(expDate*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}   
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) {
				return c.substring(nameEQ.length,c.length);
		}
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}
case_study_lock  = false;
function callFancybox(html)
{
    $.get(html,function(data)
    {
    if(!case_study_lock){
        case_study_lock =true;
        $("#blackOverlay").fadeIn(100);
        $("#flash").before(data);
        $("div[id^=caseStudy]").fadeIn();
        $(".audioContainer").flowplayer("/webroot/f/flowplayer.swf", {

            // fullscreen button not needed here
            plugins: {
                audio: {
                url: '/webroot/f/flowplayer.audio.swf'
            },
                controls: {
                    fullscreen: false
                }
            },
            clip: {
                autoPlay: false
                }
            } );
        $(".videoContainer").flowplayer({wmode:'transparent',src:"/webroot/f/flowplayer.swf"},{
                clip:{
                    autoPlay:false,
                    autoBuffering:false
                },
                play:{opacity:0}
            });
        $("div[id^=caseStudy]").find("a.close").click(function(e)
        {
        e.preventDefault();
        case_study_lock = false;
        $("#blackOverlay").fadeOut(100);
            $f("*").each(function(){
        try{
                this.stop();
        } catch(e) {
        //alert(e);
        }
            });
        $(this).parents("div[id^=caseStudy]").remove();
    });
    }

});
}

