/**
 * bjorsq.js
 * bjorsq.net site scripts
 */
document.documentElement.className = 'js';
jQuery(function($){
	SyntaxHighlighter.defaults['smart-tabs'] = false;
	SyntaxHighlighter.all();
	if ($('#gallery-images').length) {
	    $('#gallery-images').prepend('<div id="slidesnav"><ul id="nav" /></div><div id="slideshow" />');
	    var thumbs = [];
		$('#gallery-images .image').each(function(idx){
			/* hide thumbnail */
			$(this).hide();
			/* get data for image */
			var im = {};
			im.caption = $(this).find('p.caption:first').html();
			var $at = $(this).find('a:first');
			im.imgsrc = $at.attr('href');
			im.fullsrc = $at.attr('rel');
			im.title = $at.attr('title');
			im.thumbsrc = $(this).find('img:first').attr("src");
			/* save data */
			$(this).data("im", im);
			thumbs[idx] = {src:im.thumbsrc,title:im.title};
			/* re-insert large format images as slides */
			$('#slideshow').append('<img id="slide'+idx+'" src="'+im.imgsrc+'" title="'+im.title+'" alt="'+im.title+'" />');
		});
		function refreshThumbs(cIdx)
    	{
    		var sc = $('#slidesnav li').length;
    		$('#slidesnav li').each(function(i){
	    		if (i == cIdx) {
	    			$(this).fadeTo('fast',1);
	    		} else {
	    			if (!$(this).hasClass('slidehover')) {
	   	    			$(this).fadeTo('fast',0.67);
	    			}
	    		}
	    	});
			if (sc > 17) {
				var offSet = 0;
				if (cIdx > 8) {
					if (cIdx < (sc - 8)) {
				        offSet = -(cIdx * 56) + 448;
					} else {
						offSet = -((sc - 8) * 56) + 448
					}
				}
			    $('#nav').animate({"left": offSet});
			}
    	}
		var opts = $('#slideshow').cycle({ 
		    speed: 500, 
		    timeout: 5000, 
		    pager:  '#nav',
		    delay: 5000,
		    next: '#nextSlide',
		    prev: '#prevSlide',
		    containerResize: false,
		    slideResize: false,
		    pagerAnchorBuilder: function(idx, slide) {
			    if (idx < thumbs.length) {
    			    return '<li><a href="#" id="slide_'+idx+'_thumb" class="slidethumb"><img src="'+thumbs[idx].src+'" /></a></li>';
			    }
		    },
		    before: function(curr, next, opts, flag) {
		    	refreshThumbs(opts.nextSlide);
		    },
		    onPagerEvent: function(idx, slide){
		    	setSlideAndPause(idx);
		    },
		    onPrevNextEvent: function(isNext, idx, slide){
		    	setSlideAndPause(idx);
		    }
		}).data('cycle.opts');
		function setSlideAndPause(idx)
		{
			opts.timeout = 0;
			$('#slidesnav li').removeClass('activeSlide').css({"opacity":0.67}).eq(idx).addClass('activeSlide');
			refreshThumbs(idx);
		}
    	$('#slidesnav li').hover(function(){
    		$(this).addClass('slidehover');
    		if (!$(this).hasClass('activeSlide')) {
    			$(this).fadeTo('fast',1);
    		}
    	},function(){
    		if (!$(this).hasClass('activeSlide')) {
       			$(this).fadeTo('fast',0.67);
    		}
    		$(this).removeClass('slidehover');
    	});
    	refreshThumbs(0);
	}
});

(function($) {

    $.backstretch = function(src, options, callback) {
        var settings = {
            centeredX: true,         // Should we center the image on the X axis?
            centeredY: true,         // Should we center the image on the Y axis?
            speed: 0                // fadeIn speed for background after image loads (e.g. "fast" or 500)
        },
        rootElement = ("onorientationchange" in window) ? $(document) : $(window), // hack to acccount for iOS position:fixed shortcomings
        imgRatio, bgImg, bgWidth, bgHeight, bgOffset, bgCSS;
        
        // Extend the settings with those the user has provided
        if(options && typeof options == "object") $.extend(settings, options);
    
        // Initialize
        $(document).ready(_init);
  
        // For chaining
        return this;
    
        function _init() {
            // Prepend image, wrapped in a DIV, with some positioning and zIndex voodoo
            if(src) {
                var container = $("<div />").attr("id", "backstretch")
                                            .css({left: 0, top: 0, position: "fixed", overflow: "hidden", zIndex: -9999}),
                    img = $("<img />").css({position: "relative", display: "none"})
                                      .bind("load", function(e) {                                          
                                          var self = $(this);
                                          imgRatio = $(e.target).width() / $(e.target).height();
    
                                          _adjustBG(function() {
                                              self.fadeIn(settings.speed, function(){
                                                  if(typeof callback == "function") callback();
                                              });
                                          });
                                      })
                                      .appendTo(container);
                  
                $("body").prepend(container);
                img.attr("src", src); // Hack for IE img onload event

                // Adjust the background size when the window is resized or orientation has changed (iOS)
                $(window).resize(_adjustBG);
            }
        }
            
        function _adjustBG(fn) {
            try {
                bgCSS = {left: 0, top: 0}
                bgWidth = rootElement.width();
                bgHeight = bgWidth / imgRatio;

                // Make adjustments based on image ratio
                // Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
                if(bgHeight >= rootElement.height()) {
                    bgOffset = (bgHeight - rootElement.height()) /2;
                    if(settings.centeredY) $.extend(bgCSS, {top: "-" + bgOffset + "px"});
                } else {
                    bgHeight = rootElement.height();
                    bgWidth = bgHeight * imgRatio;
                    bgOffset = (bgWidth - rootElement.width()) / 2;
                    if(settings.centeredX) $.extend(bgCSS, {left: "-" + bgOffset + "px"});
                }

                $("#backstretch img").width( bgWidth ).height( bgHeight ).css(bgCSS);
            } catch(err) {
                // IE7 seems to trigger _adjustBG before the image is loaded.
                // This try/catch block is a hack to let it fail gracefully.
            }
      
            // Executed the passed in function, if necessary
            if (typeof fn == "function") fn();
        }
    };
  
})(jQuery);

