// JavaScript Document

/* Everything from now on gets called when the page loads */
$(document).ready(function() {

	// When the page has fully loaded
	$(window).load( function () {
		// Check if the slider exists
		if ($('.slider').length > 0) {
			// Pause for a fraction of a second, basically
			$(this).delay(600).fadeIn(1);
		};
	});

/* 
Karl Swedberg's js class technique
via http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx

Tip: One thing that's great about Web Design is that there are so many tips, tricks and techniques you can find, if you know how to use Google.

*/

$('body').addClass('js');

/* 
Detect if we're on iPhone / iPad / iPod and add a class to the body, so the CSS can be altered
Also, we can sniff for the variable agentID elsewhere in the jQuery script
Code found here -> http://snipplr.com/view/31607/iphone-ipad-ipod-detect/
*/
    var deviceAgent = navigator.userAgent.toLowerCase();
	var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
	if (agentID) {$('body').addClass('iOS');}


/*
This next bit of code is a custom slider for the portfolio
*/

// Add some extra divs around the portfolio list, for the slider
var slideDrawer = $('#portfolio-list');     // As we're using it a few times, using a variable will 
                                            // improve perfomace compared to getting jQuery to look it up each time

// Duplicate the slide drawer as another list, so we can use for thumbnails

									
											
slideDrawer.wrap('<div id="portfolio-outer" />').parent().wrap('<div id="portfolio-container" />').before('<div id="portfolio-box" />');

var slideContainer = $('#portfolio-container'); // So we can reuse it
slideContainer.prepend('<div id="portfolio-links"><a href="#" id="lnk-next">next</a><a href="#" id="lnk-prev">prev</a></div>');

// Duplicate the slide drawer as another list, so we can use for thumbnails
thumbList = slideDrawer.html();
thumbList = '<ul id="portfolio-thumbs">' + thumbList + '</ul>';
slideContainer.append(thumbList);

$('#portfolio-thumbs li img').wrap('<a href="#" />');


// Store the portfolio box as a variable, so we can calculate the width later
var portfolioBox = $('#portfolio-box');

// Work out the size of the list
var portfolioSize = slideDrawer.children("li").length;

// Duplicate the last LI at the start of the list
var lastLI = '<li>' + $('li:last-child',slideDrawer).html() + '</li>';
slideDrawer.prepend(lastLI);

// Duration of the slide, in thousandths of a second
var slideTime = 400;

// Set a counter, so we know which portolio piece we're on
var currentPos = 1;

// Disable sliders - while in animation
var theSliders = $("#lnk-next, #lnk-prev");
theSliders.each(function() {
	$(this).attr('rel', 'enabled');
});
function disableSliders() {
	theSliders.each(function() {
		$(this).attr('rel', 'disabled');
		$('#portfolio-thumbs li a').attr('rel', 'disabled');
	});
};
function enableSliders() {
	theSliders.each(function() {
		$(this).attr('rel', 'enabled');
		$('#portfolio-thumbs li a').attr('rel', 'enabled');
	});
};

// Set the size of the slider drawer
var drawerSize = (portfolioSize + 1) * portfolioBox.width();
slideDrawer.attr('style', 'width: ' + drawerSize + 'px;');

// Adjust various meansurements if the layout is resized

var portfolioBoxSize = portfolioBox.width();
$(window).resize(function() {
    if (portfolioBoxSize != portfolioBox.width()) {
        portfolioBoxSize = portfolioBox.width();
        slideDistance = portfolioBoxSize;
        drawerSize = (portfolioSize + 1) * portfolioBoxSize;
        slideDrawer.css('width', drawerSize + 'px;');
        if (currentPos <= 0) {
            slideDrawer.attr('style', 'left: 0px;');
        } else {
            slideDrawer.attr('style', 'left: -' + (currentPos * slideDistance) +  'px;');
        }
    }
});
   
var cPos = 0;
var totalThumbs = $('#portfolio-thumbs li').length;

 
slideMe = function (direction) {
    // Distance of the slide, in pixels - calculated based on width of the page / holding box
    var slideDistance = portfolioBox.width();
    var textShow = slideDrawer.attr('style') + ' : ' + slideDistance + ' : ' + currentPos + ' : ' + portfolioSize + ' : ' + direction;

    // If we've reached the end OR beginning of the list AND we're going forward, go back to the beginning
    if ((currentPos >= portfolioSize || currentPos <= 0) && direction == '-') {
        slideDrawer.attr('style', 'left: 0px; width: ' + drawerSize + 'px;');
        currentPos = 0;
    } else if ((currentPos >= portfolioSize || currentPos <= 0) && direction == '+') {
        // If we've reached the end OR beginning of the list AND we're going backwards, go forward to the end
        slideDrawer.attr('style', 'left: -' + (portfolioSize * slideDistance) +  'px; width: ' + drawerSize + 'px;');
        currentPos = portfolioSize;
    }
    
    slideDrawer.animate({
        left: direction + '=' + slideDistance
    }, slideTime, function() {
        // Animation complete.
        enableSliders();
    });
	
	// Remove current class from all lis
	$('#portfolio-thumbs li').removeClass('current');
	
    if (direction == '+') {
        // Note, this is the opposite "sign" to the slide direction
        currentPos--;
    } else {currentPos++;}
	
	// Update the current position of the thumbnails
	cPos = currentPos;
	if (cPos < 1) {
		cPos = totalThumbs;
	}
	var whichChild = '#portfolio-thumbs li.i' + cPos;
	$(whichChild).addClass('current');
}


slideTo = function (position) {
	if (currentPos > tPos) {
		direction = '+';
		slideMultiplier = currentPos - tPos;
	} else {
		direction = '-';
		slideMultiplier = tPos - currentPos;
	}
	
    // Distance of the slide, in pixels - calculated based on width of the page / holding box
    var slideDistance = portfolioBox.width();
	// Then use multiply the slideDistance by the multiplier
	
	slideDistance = slideDistance * slideMultiplier;
    var textShow = slideDrawer.attr('style') + ' : ' + slideDistance + ' : ' + currentPos + ' : ' + portfolioSize + ' : ' + direction;
	
    // If we've reached the end OR beginning of the list AND we're going forward, go back to the beginning
    if ((currentPos >= portfolioSize || currentPos <= 0) && direction == '-') {
        slideDrawer.attr('style', 'left: 0px; width: ' + drawerSize + 'px;');
        currentPos = 0;
    } else if ((currentPos >= portfolioSize || currentPos <= 0) && direction == '+') {
        // If we've reached the end OR beginning of the list AND we're going backwards, go forward to the end
        slideDrawer.attr('style', 'left: -' + (portfolioSize * slideDistance) +  'px; width: ' + drawerSize + 'px;');
        currentPos = portfolioSize;
    }
    
    slideDrawer.animate({
        left: direction + '=' + slideDistance
    }, slideTime, function() {
        // Animation complete.
        enableSliders();
    });
	
	// Update the current Position
    currentPos = tPos;
	
	if (currentPos == totalThumbs) {
		currentPos = 0;	
	}
}


//
$('#portfolio-thumbs li a').attr('rel', 'enabled');

// Control what happens when you click a thumbnail
$('#portfolio-thumbs li a').click(function(){

	// Remove current class from all lis
	$('#portfolio-thumbs li').removeClass('current');
	
	// extract the current position from the class
	tPos = $(this).parent().attr('class').replace(' ', '').replace('current', '').replace('i', '');
	
	if (currentPos != tPos) {
		if($(this).attr("rel") == "enabled") {
        	disableSliders();
			slideTo(tPos);
		}
	};
	
	// make this li the current one
	$(this).parent().addClass('current');
    return false;
});

// Fade the slider buttons out and in (they're on to start with, though)

var slideButtonNext = $('#lnk-next');
var slideButtonPrev = $('#lnk-prev');

$('#portfolio-links').hover(
  function () {
    slideButtonNext.fadeIn("fast");
    slideButtonPrev.fadeIn("fast");
  }, 
  function () {
    slideButtonNext.fadeOut("fast");
    slideButtonPrev.fadeOut("fast");
  }
);

// Slide an element (eg portfolio)
slideButtonNext.click(function(){
    if($(this).attr("rel") == "enabled") {
        disableSliders();	
        slideMe('-');
    }
    return false;
});

slideButtonPrev.click(function(){
    if($(this).attr("rel") == "enabled") {
        disableSliders();    
        slideMe('+');
    }
    return false;
});

});
