    jQuery.fn.extend({
        unifyHeights: function(children) {
        	return this.each(function(){
        		var maxHeight = 0;
				$(children, this).each(function(){
					var height = $(this).height();

					if ( height > maxHeight ) {
						maxHeight = height; 
					}
				});
				
				$(children, this).css(bs.vars.ie ? 'height' : 'minHeight', maxHeight);
        	})
        },
        
        inputFocus: function() {
        	return this.each(function(){
        		$(this).focus(function(){
        			if(this.value == this.defaultValue) {
        				this.value = ''
        			}
        		}).blur(function(){
        			if(this.value == '' || this.value == this.defaultValue) {
        				this.value = this.defaultValue
        			}        			
        		})
        	})
        },
        
        /*
        	Twitter regex snippet from:
        	http://www.prodevtips.com/2009/08/08/jqueryregex-snippet-for-managing-twitter/
        	slightly modified by me
        */
        twitterRegex: function() {
			return this.each(function(){ 
			    $(this).html(  
			      $(this).html(). 
				      replace(/http:\/\/\S+/g,  '<a href="$&">$&</a>'). 
				      replace(/(@)(\w+)/g,    ' <a href="http://twitter.com/$2">@$2</a>'). 
				      replace(/\s(#)(\w+)/g,    '<a href="http://search.twitter.com/search?q=%23$2">$&</a>')
			    ); 
			});
        }
    })
    
    
    var bs = {
    	vars: {
    		ie: $.browser.msie && ($.browser.version == '6.0' || $.browser.version == '6.0') ? 1 : 0
    	},
    	
    	init: function() {
	   		$('body').addClass('js');
    
    		this.globalBehavior();
    		
    		if($('#page-contact').length) { this.contact() }
    
    		if($('#promo-ul').length) { this.promo() }
    		
    		if($('#twitter').length) { this.twitter() }
    
    		if(bs.vars.ie) { this.ie() }
    		
    		setTimeout(function() {
    			bs.ga()
    		}, 1000)
    	},
    	
    	globalBehavior: function() {
    		$('#search').inputFocus();
    		
    		$('#content').unifyHeights('.excerpt')
    		
			$('#page-portfolio #promo .img a').hover(
				function(){ $(this).stop().animate({marginLeft: '5px'}, 100) },
				function(){ $(this).stop().animate({marginLeft: 0}, 100) }
			)
			
			if($('#page-portfolio').length && $('dl.project').length) {
				$('dl dd.img a').fancybox({
					hideOnContentClick: true,
					zoomOpacity: true,
					overlayOpacity: 0.75,
					imageScale: false,
					centerOnScroll: false
				});
				
				$('dl dd.img a')
					.css('position', 'relative')
					.append('<span />')
					.find('span')
						.css('opacity', 0)
						.end()
					.hover(
						function(){
							$('span', this).stop().animate({opacity: 0.5}, 200)
						},
						function(){
							$('span', this).stop().animate({opacity: 0}, 200)							
						}
					)
			}

			if($('form.contact').length) {
	        	$('form.contact .text')
	        		.focus(function(){ $(this).prevAll('label:first').addClass('focus') })
	        		.blur(function(){ $(this).prevAll('label:first').removeClass('focus') }) 							
			}			

    	},
        
        contact: function() {
       		var $f = $('#content form'),
    			$msg = $('fieldset', $f).append('<p class="message"></p>').find('p.message').hide()
    			
			function checkField(field) {
        		if($(field).val()) {
        			$(field).removeClass('error')
        		} else {
        			$(field).addClass('error')
        		}
        		
        		if($(field).is('#email')) {
					if (!$(field)[0].value.match(/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{1,4}$/)) {
						$(field).addClass('error')
					} else {
						$(field).removeClass('error')
					}
        		}
        		
        		formMsg();
			}
			
			function formMsg() {
				if($('.error:not(p)', $f).length) {
					$msg
						.show()
						.removeClass('ok')
						.addClass('error')
						.text('Wypełnij poprawnie wszystkie pola')
				} else {
					$msg
						.hide()
						.removeClass('error')
						.text('')
				}
			}

        	$('#content form').submit(function(){
	        	$(':text, textarea', $f)
		        	.blur(function() { checkField(this) })
		        	.keyup(function() { checkField(this) })
		        	.blur();

        		var name = $('#name', $f).val(),
        			email = $('#email', $f).val(),
        			subject = $('#subject', $f).val(),
        			message = $('#message', $f).val();

				if(!$('.error:not(p)', $f).length) {
					$(':submit', $f).replaceWith('<span id="sending">Wysyłam...</span>');
				
				    $.ajax({
				        type: 'post',
				        url: 'sendMail.php',
				        data: 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message,
				        success: function(response) {
				        	setTimeout(function() {
				        		$('html, body').animate({scrollTop: 0}, 400)
			        			$f.replaceWith('<p class="message ok">' + response + '</p>')
				        	}, 1000)
				        },
				        error: function() {
				        	$('#sending').replaceWith('<input type="submit" value="Wyślij" class="submit">');
				            $msg.removeClass('ok').addClass('error').text('Wystąpił błąd podczas wysyłania wiadomości.').show()
				        }
				    });
				}

				return false;
        	})
        },
        
        promo: function() {
        	$('#promo').append('<div id="temp" />')
        		.find('#temp')
        		.load('http://bstankowski.pl/load/promo_load.html', function(data) {
	        		$(data).appendTo('#promo-ul');
	        		$(this).remove();
	        	

			        var $p = $('#promo-ul'),
			        		promoWidth = $('li', $p).width() * $('li', $p).length + 'px',
			        		
			       	promoPager = function(id) {
						    if(!$('#pager').length) {
					        $('<div id="pager" />').prependTo('#promo');
						    } else {
						    	$('#pager').css({ marginLeft: -$('#pager', $p).width()/2 })
						    }
						    
						    return $('<a href="#' + id + '"></a>').appendTo('#pager');
							},
							
							promoRun = function() {
					    	var $pager = $('#pager');
				    	
					    	$('a:first', $pager).addClass('current');
		
				    		var run = setInterval(function() {
				    			$('.current', $pager).is(':last-child') ? $('a:first', $pager).click() : $('.current', $pager).next().click();
				    		}, 8000)
				    		
				    		$('#promo li').hover(
					    			function(){ clearInterval(run) },
					    			function(){
							    		run = setInterval(function() {
							    			$('.current', $pager).is(':last-child') ? $('a:first', $pager).click() : $('.current', $pager).next().click();
							    		}, 8000)
					    			})
							};
							
			        $p.unifyHeights('li')
			        	.wrap('<div id="promo-wrap"></div>')
			        	.css({width: promoWidth, height: $('li:first', $p).height()})
			        
			        $('li', $p).each(function(index){
								this.id = 'promo-' + index;
								
		            var page = promoPager($(this).attr('id'));
		 
		            page.click(function() {
		            		$(this).siblings('a').removeClass('current').end().addClass('current')
		                var id = $(this).attr('href').split('#')[1],
		                		diff = $('#promo-ul').offset().left - $('#promo-ul li#' + id).offset().left;
		                						
		                $('#promo-ul').animate({ left: diff }, 600);
		                
		                return false;
		            });
			        });
			        
			        promoRun()	        	
	        	})
        },
        
        twitter: function() {
					$.getJSON('http://twitter.com/status/user_timeline/art_stk.json?count=1&callback=?', function(data){
						$.each(data, function(index, item){
							$('#twitter div p').html(item.text).twitterRegex();
						});
					});	
				},
        
        ie: function() {
					if(document.cookie.indexOf("iemsgbs") == -1) {
						var iemsg = '<h2>Mam Cię!</h2><p>Zostałeś przyłapany na korzystaniu z Internet Explorera 6 - <em>najgorszej</em> dostępnej przeglądarki internetowej!</p>'
							+ '<p>W IE6 niektóre elementy tej strony mogą nie wyglądać tak, jak powinny.</p>'
							+ '<p>Nawet Microsoft <em>nie wspiera</em> już tej przeglądarki - dlaczego ja miałbym to robić?</p>'
							+ '<p>IE6 jest <em>przestarzały</em> i stwarza <em>zagrożenie</em> dla twojego komputera  - <a href="http://ie6.pl/">dowiedz się więcej</a>.</p>'
							+ '<p>Zrób sobie przysługę i <a href="http://browsehappy.pl/">zmień przeg­lądar­kę na no­wo­cześ­niej­szą i wygodniejszą!</a></p><a href="/" id="close-ie">zamknij</a>';
						
						$('#promo')
							.find('#pager').hide().end()
						
						var $msg = $('<div id="ie-msg"><div></div></div>').prependTo('body')
						$('div', $msg).html(iemsg);
						
						$('#close-ie', $msg).click(function(){
							$msg.remove()
						
							$('#promo')
							.find('#pager').show().end()
							  
							var ttl =  new Date();
							ttl.setTime(ttl.getTime()+1000*60*60*24*5);
							document.cookie="iemsgbs=true;expires=" + ttl.toGMTString();
							
							return false;
						})				
					}
        },
    	


    	
        ga: function() {
        	var GAID = 'UA-3516059-4',
            	head = document.getElementsByTagName('head')[0],
            	scr = document.createElement('script');
            scr.type = 'text/javascript';
            scr.src = (location.protocol == 'http:' ? 'http://www.' : 'https://ssl.') + 'google-analytics.com/'+'ga.js';
            var once = 0;
                function runMe() { 
                    if (scr.readyState == 'loading' || _gat == undefined || once) { return; }
                    clearInterval(timer);
                    once++;

                    var pageTracker = _gat._getTracker(GAID);
                    pageTracker._initData();
                    pageTracker._trackPageview();
                }

            var timer = setInterval(runMe, 2000);
            scr['onload'] = runMe;
            scr['onreadystatechange'] = runMe;
            head.appendChild(scr); 
        }
    }

$(function(){	
	bs.init()
});