(function($) {
    if ($.browser.mozilla) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).css({
                    'MozUserSelect' : 'none'
                });
            });
        };
    } else if ($.browser.msie) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('selectstart.disableTextSelect', function() {
                    return false;
                });
            });
        };
    } else {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('mousedown.disableTextSelect', function() {
                    return false;
                });
            });
        };
    }
})(jQuery);

$.fn.infiniteCarousel = function () {

    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }
  
    return this.each(function () {
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),
            
            singleWidth = $single.outerWidth(), 
            visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
            currentPage = 1,
            pages = Math.ceil($items.length / visible);            


        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
        if (($items.length % visible) != 0) {
            $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
            $items = $slider.find('> li');
        }

        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
        $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li'); // reselect
        
        // 3. Set the left position to the first 'real' item
        $wrapper.scrollLeft(singleWidth * visible);
        
        // 4. paging function
        function gotoPage(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
            
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 500, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                } 

                currentPage = page;
            });                
            
            return false;
        }
        
        $wrapper.after('<a class="arrow back">&lt;</a><a class="arrow forward">&gt;</a>');
        
        // 5. Bind to the forward and back buttons
        $('a.back', this).click(function () {
            return gotoPage(currentPage - 1);                
        });
        
        $('a.forward', this).click(function () {
            return gotoPage(currentPage + 1);
        });
        
        // create a public interface to move to a specific page
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });
    });  
};

function slideSwitch() {
    var $active = $('#bilde img.active');

    if ( $active.length == 0 ) $active = $('#bilde img:last');

    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        : $('#bilde img:first');

    // uncomment the 3 lines below to pull the images in random order
    
    // var $sibs  = $active.siblings();
    // var rndNum = Math.floor(Math.random() * $sibs.length );
    // var $next  = $( $sibs[ rndNum ] );


    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 3000, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});

$(document).ready(function() {

    $("#bilde img:first").addClass("active");
    $("#albums li a").attr("rel", "galerija");
    
    $('.gallery-icon').hover(function() {
    		var image = $(this).find('img');
    		var alternative = $(image).attr('alt');
    		$(this).find('a').removeAttr('title').append('<div class=imgLabel>'+ alternative +'</div>');
    		$(this).find('img').removeAttr('title');
    }, function() {
    		$(this).find('.imgLabel').remove();
    });
        
    $("#sidebarCal .wp-availability-month").hide();
    $("#sidebarCal").find(".wp-availability-month").eq($("#showCurrMonth").html()).show();
    
    $('.albums').disableTextSelect();
    
    $('.albums').infiniteCarousel();
    $('.albums .arrow').css('opacity', '0.4');
    
    $('.albums ul li a img').hover(function() {
    		$(this).stop().fadeTo(500,0.4);
    }, function() {
    		$(this).stop().fadeTo(500,1);
    });
    
    $('.albums .arrow').hover(function() {
    		$(this).stop().fadeTo(500,1);
    }, function() {
    		$(this).stop().fadeTo(500,0.4);
    });
    
    $('#right a img').hover(function() {
    		$(this).stop().fadeTo(500,0.4);
    }, function() {
    		$(this).stop().fadeTo(500,1);
    });
    
    $("#weather").fancybox({
    	'autoScale': true,
    	'type'			: 'iframe',
    	'overlayColor'  : '#53312c',
    	'padding'       : 0,
    	'margin'        : 0,
    	'scrolling'     : 'no'
    });
    
    $("#albums li a, .post-image-larger a, #fotografijas a").fancybox({
    	'padding'       : 0,
    	'margin'        : 0,
    	'titleShow'     : false,
    	'showNavArrows' : true
    });
       
    if ($('#albums li img').length) {
        return false;
      } else {
        $('#albums').remove();
    }
    	            
});

$(window).load(function() {

    String.prototype.makeLinks = function(){
        return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(str){
            return str.link(str);
        });
    };
    
    var holder = $('#twitter-holder');
    var tweeturl = "http://twitter.com/status/user_timeline/bukdangas.json?count=5&callback=?";
    $.getJSON(tweeturl, function(data) {
        $.each(data, function(i, item) {
            holder.append('<div class="tweet"><span class="timestamp">' + prettyDate(item.created_at) + '</span><p>' + item.text.makeLinks() + '</p></div>');
        });
    });
    
});

function prettyDate(date_str){
	var time_formats = [
	[60, 'nupat', 1], // 60
	[120, 'pirms minūtes', '1 minute from now'], // 60*2
	[3600, 'minūtes', 60], // 60*60, 60
	[7200, 'pirms stundas', '1 hour from now'], // 60*60*2
	[86400, 'stundām', 3600], // 60*60*24, 60*60
	[172800, 'vakar', 'tomorrow'], // 60*60*24*2
	[604800, 'dienām', 86400], // 60*60*24*7, 60*60*24
	[1209600, 'pirms nedēļas', 'next week'], // 60*60*24*7*4*2
	[2419200, 'nedēļām', 604800], // 60*60*24*7*4, 60*60*24*7
	[4838400, 'pirms mēneša', 'next month'], // 60*60*24*7*4*2
	[29030400, 'mēnešiem', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4
	[58060800, 'pirms gada', 'next year'], // 60*60*24*7*4*12*2
	[2903040000, 'gadiem', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12
	[5806080000, 'pagājušajā gadsimtā', 'next century'], // 60*60*24*7*4*12*100*2
	[58060800000, 'gasimtiem', 2903040000] // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100
	];
	var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," ").replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	if(time.substr(time.length-4,1)==".") time =time.substr(0,time.length-4);
	var seconds = (new Date - new Date(time)) / 1000;
	var token = 'pirms', list_choice = 1;
	if (seconds < 0) {
		seconds = Math.abs(seconds);
		token = 'from now';
		list_choice = 2;
	}
	var i = 0, format;
	while (format = time_formats[i++])
		if (seconds < format[0]) {
			if (typeof format[2] == 'string')
				return format[list_choice];
			else
				return token + ' ' + Math.floor(seconds / format[2]) + ' ' + format[1];
		}
	return time;
}














