$(document).ready(function(){
	
	///////////////////SCROLLTO ANCHOR FUNCTION
	function scroll(direction) { 
        var scroll, i,
                positions = [],
                here = $(window).scrollTop(),
                collection = $('._scroll');

        collection.each(function() {
            positions.push(parseInt($(this).offset()['top'],10));
        });

        for(i = 0; i < positions.length; i++) {
            if (direction == 'next' && positions[i] > here) { scroll = collection.get(i); break; }
            if (direction == 'prev' && i > 0 && positions[i] >= here) { scroll = collection.get(i-1); break; }
        }

        if (scroll) {
            $.scrollTo(scroll, {
                duration: 350
            });
        }
        return false;
    }

    	$(".next,.prev").click(function() {
        	return scroll($(this).attr('class'));
    	});

    	$(".scrolltoanchor").click(function() {
        	$.scrollTo($($(this).attr("href")), {
            	duration: 350
        	});
        return false;
    });
		
	//INFINITE NAVIGATION CAROUSEL 	
    $.fn.infiniteCarousel = function () {
        function repeat(str, n) {
            return new Array( n + 1 ).join(str);
        }
        
        return this.each(function () {
            var $wrapper = $('> div', this).css('overflow', 'hidden'),
                $slider = $wrapper.find('> ul').width(9999),
                $items = $slider.find('> li'),
                $single = $items.filter(':first')
                
                singleWidth = $single.outerWidth(),
                visible = Math.ceil($wrapper.innerWidth() / singleWidth),
                currentPage = 1,
                pages = Math.ceil($items.length / visible);
                
            if ($items.length % visible != 0) {
                $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
                $items = $slider.find('> li');
            }
            
            $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');
            
            $wrapper.scrollLeft(singleWidth * visible);
            
            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
                }, 1000, function () {
                    if (page > pages) {
                        $wrapper.scrollLeft(singleWidth * visible);
                        page = 1;
                    } else if (page == 0) {
                        page = pages;
                        $wrapper.scrollLeft(singleWidth * visible * pages);
                    }
                    currentPage = page;
                });
            }
            
            $wrapper.after('<a href="#" class="arrow back"></a><a href="#" class="arrow forward"></a>');
            $('a.back', this).click(function () {
                gotoPage(currentPage - 1);
                return false;
            });
            
            $('a.forward', this).click(function () {
                gotoPage(currentPage + 1);
                return false;
            });
            
            $(this).bind('goto', function (event, page) {
                gotoPage(page);
            });
            
            $(this).bind('next', function () {
                gotoPage(currentPage + 1);
            });
        });
    }; 
	
	// THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL
    var autoscrolling = true;
    $('.carousel_navigation').infiniteCarousel().mouseover(function () {
        autoscrolling = false;
    }).mouseout(function () {
        autoscrolling = true;
    });
    
    setInterval(function () {
        if (autoscrolling) {
            $('.carousel_navigation').trigger('next');
        }
    },10000);
	
	/////////////EASY SLIDER
	$.fn.easySlider = function(options){
		// default configuration properties
		var defaults = {			
			prevId: 		'prevBtn',
			prevText: 		'', //insert PREVIOUS if needed //
			nextId: 		'nextBtn',	
			nextText: 		'', //insert NEXT if needed //
			controlsShow:	true,
			controlsBefore:	'',
			controlsAfter:	'',	
			controlsFade:	true,
			firstId: 		'firstBtn',
			firstText: 		'First',
			firstShow:		false,
			lastId: 		'lastBtn',	
			lastText: 		'Last',
			lastShow:		false,				
			vertical:		false,
			speed: 			800,
			auto:			false,
			pause:			2000,
			continuous:		false, 
			numeric: 		false,
			numericId: 		'controls'
		}; 
		var options = $.extend(defaults, options);  
		this.each(function() {  
			var obj = $(this); 				
			var s = $("li", obj).length;
			var w = $("li", obj).width(); 
			var h = $("li", obj).height(); 
			var clickable = true;
			obj.width(w); 
			obj.height(h); 
			obj.css("overflow","hidden");
			var ts = s-1;
			var t = 0;
			$("ul", obj).css('width',s*w);			
			
			if(options.continuous){
				$("ul", obj).prepend($("ul li:last-child", obj).clone().css("margin-left","-"+ w +"px"));
				$("ul", obj).append($("ul li:nth-child(2)", obj).clone());
				$("ul", obj).css('width',(s+1)*w);
			};				
			
			if(!options.vertical) $("li", obj).css('float','left');
			if(options.controlsShow){
				var html = options.controlsBefore;				
				if(options.numeric){
					html += '<ol id="'+ options.numericId +'"></ol>';
				} else {
					if(options.firstShow) html += '<span id="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>';
					html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>';
					html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>';
					if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>';				
				};
				
				html += options.controlsAfter;						
				$(obj).after(html);										
			};
			
			if(options.numeric){									
				for(var i=0;i<s;i++){						
					$(document.createElement("li"))
						.attr('id',options.numericId + (i+1))
						.html('<a rel='+ i +' href=\"javascript:void(0);\"></a>')
						.appendTo($("#"+ options.numericId))
						.click(function(){							
							animate($("a",$(this)).attr('rel'),true);
						}); 												
				};							
			} else {
				$("a","#"+options.nextId).click(function(){		
					animate("next",true);
				});
				$("a","#"+options.prevId).click(function(){		
					animate("prev",true);				
				});	
				$("a","#"+options.firstId).click(function(){		
					animate("first",true);
				});				
				$("a","#"+options.lastId).click(function(){		
					animate("last",true);				
				});				
			};
			
			function setCurrent(i){
				i = parseInt(i)+1;
				$("li", "#" + options.numericId).removeClass("current");
				$("li#" + options.numericId + i).addClass("current");
			};
			
			function adjust(){
				if(t>ts) t=0;		
				if(t<0) t=ts;	
				if(!options.vertical) {
					$("ul",obj).css("margin-left",(t*w*-1));
				} else {
					$("ul",obj).css("margin-left",(t*h*-1));
				}
				clickable = true;
				if(options.numeric) setCurrent(t);
			};
			
			function animate(dir,clicked){
				if (clickable){
					clickable = false;
					var ot = t;				
					switch(dir){
						case "next":
							t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1;						
							break; 
						case "prev":
							t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1;
							break; 
						case "first":
							t = 0;
							break; 
						case "last":
							t = ts;
							break; 
						default:
							t = dir;
							break; 
					};	
					var diff = Math.abs(ot-t);
					var speed = diff*options.speed;						
					if(!options.vertical) {
						p = (t*w*-1);
						$("ul",obj).animate(
							{ marginLeft: p }, 
							{ queue:false, duration:speed, complete:adjust }
						);				
					} else {
						p = (t*h*-1);
						$("ul",obj).animate(
							{ marginTop: p }, 
							{ queue:false, duration:speed, complete:adjust }
						);					
					};
					
					if(!options.continuous && options.controlsFade){					
						if(t==ts){
							$("a","#"+options.nextId).hide();
							$("a","#"+options.lastId).hide();
						} else {
							$("a","#"+options.nextId).show();
							$("a","#"+options.lastId).show();					
						};
						if(t==0){
							$("a","#"+options.prevId).hide();
							$("a","#"+options.firstId).hide();
						} else {
							$("a","#"+options.prevId).show();
							$("a","#"+options.firstId).show();
						};					
					};				
					
					if(clicked) clearTimeout(timeout);
					if(options.auto && dir=="next" && !clicked){;
						timeout = setTimeout(function(){
							animate("next",false);
						},diff*options.speed+options.pause);
					};
				};
			};
			// init
			var timeout;
			if(options.auto){;
				timeout = setTimeout(function(){
					animate("next",false);
				},options.pause);
			};		
			
			if(options.numeric) setCurrent(0);
		
			if(!options.continuous && options.controlsFade){					
				$("a","#"+options.prevId).hide();
				$("a","#"+options.firstId).hide();				
			};				
			
		});
	}
	///////////// Ticker Function
	$.fn.ticker = function(options) { 
		var opts = $.extend({}, $.fn.ticker.defaults, options); 		
		var newsID = '#' + $(this).attr('id');
		var tagType = $(this).attr('tagName'); 	
		
		return this.each(function() { 
			var settings = {				
				position: 0,
				time: 0,
				distance: 0,
				newsArr: {},
				play: true,
				paused: false,
				contentLoaded: false,
				dom: {
					contentID: '#ticker-content',
					titleID: '#ticker-title',
					titleElem: '#ticker-title span',
					tickerID : '#ticker',
					wrapperID: '#ticker-wrapper',
					revealID: '#ticker-swipe',
					revealElem: '#ticker-swipe span',
					controlsID: '#ticker-controls',
					prevID: '#prev',
					nextID: '#next',
					playPauseID: '#play-pause'
				}
			};
			
			if (tagType != 'UL' && opts.htmlFeed === true) {
				debugError('Cannot use <' + tagType.toLowerCase() + '> type of element for this plugin - must of type <ul>');
				return false;
			}

			initialisePage();
			function countSize(obj) {
			    var size = 0, key;
			    for (key in obj) {
			        if (obj.hasOwnProperty(key)) size++;
			    }
			    return size;
			};

			function debugError(obj) {
				if (opts.debugMode) {
					if (window.console && window.console.log) {
						window.console.log(obj);
					}
					else {
						alert(obj);			
					}
				}
			}
			function initialisePage() {
				$(settings.dom.wrapperID).append('<div id="' + settings.dom.tickerID.replace('#', '') + '"><div id="' + settings.dom.titleID.replace('#', '') + '"><span style="display: none;"><!-- --></span></div><p id="' + settings.dom.contentID.replace('#', '') + '"></p><div id="' + settings.dom.revealID.replace('#', '') + '"><span style="display: none;"><!-- --></span></div></div>');
				$(settings.dom.wrapperID).removeClass('no-js').addClass('has-js');
				$(settings.dom.tickerElem + ',' + settings.dom.titleElem + ',' + settings.dom.contentID).hide();
				updateTicker();
				
			}
			
			function updateTicker() {	
				if (settings.contentLoaded == false) {
					if (opts.ajaxFeed) {
						debugError('Code Me!');
					}
					else if (opts.htmlFeed) { 
						if($(newsID + ' LI').length > 0) {
							$(newsID + ' LI').each(function (i) {	
								settings.newsArr['item-' + i] = { type: opts.titleText, content: $(this).html()};
							});							
						}	
						else {
							debugError('Couldn\'t find any content for the ticker to use!');
							return false;
						}
					}
					else {
						debugError('Couldn\'t find any content for the ticker to use!');
						return false;
					}
					settings.contentLoaded = true;
				}
				
				$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
				$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
				if (settings.position == (countSize(settings.newsArr) -1)) {
					settings.position = 0;
				}
				else {		
					settings.position++;
				}
							
				distance = $(settings.dom.contentID).width();
				time = distance / opts.speed;
				
				$(settings.dom.wrapperID)
					.find(settings.dom.titleID).fadeIn()
						.end().find(settings.dom.titleElem).fadeIn('slow', revealContent);
			}

			function revealContent() {
				if(settings.play) {	
					var offset = $(settings.dom.titleElem).width() + 20;
					$(settings.dom.revealID).css('left', offset + 'px');
					$(settings.dom.revealElem).show(0, function () {
						$(settings.dom.contentID).css('left', offset + 'px').show();
						$(settings.dom.revealID).css('margin-left', '0px').delay(20).animate({
							marginLeft: distance + 'px'
						}, time, 'linear', postReveal);
					});		
				}
				else {
					return false;					
				}
			};
			
			function postReveal() {
				if(settings.play) {		
					$(settings.dom.contentID).delay(opts.pauseOnItems).fadeOut('slow');
					$(settings.dom.revealID).hide(0, function () {
						$(settings.dom.tickerID).delay(opts.pauseOnItems).fadeOut(opts.fadeOutSpeed, function () {
							$(settings.dom.wrapperID)
								.find(settings.dom.titleElem +',' + settings.dom.revealElem + ',' + settings.dom.contentID)
									.hide()
								.end().find(settings.dom.tickerID + ',' + settings.dom.revealID + ',' + settings.dom.titleID)
									.show()
								.end().find(settings.dom.tickerID + ',' + settings.dom.revealID + ',' + settings.dom.titleID)
									.removeAttr('style');								
							updateTicker();						
						});
					});
				}
				else {
					$(settings.dom.revealElem).hide();
				}
			}
		});  
	}
	
	$('#js-news').ticker({
		speed: .20,			
		ajaxFeed: false,
		htmlFeed: true,
		debugMode: false,
		controls: false,
		titleText: '',		
		pauseOnItems: 3500,
		fadeInSpeed: 200,
		fadeOutSpeed: 200,				 
	});
	
	
	//NAVIGATION SPRITE CONTROL
	$(function(){  
		$('#main_logo a, #navigation li a, #blog_nav a').append('<span class="hover"></span>');  
		$('#main_logo a, #navigation li a, #blog_nav a').hover(  
			function() {  
			$('.hover', this).stop().animate({  
			'opacity': 1  
			}, 500,'easeOutSine')  
			},  
			function() {  
			$('.hover', this).stop().animate({  
			'opacity': 0  
			}, 500, 'easeOutQuad')  
		})  
	}); 
	
	//SCROLLTO LINK TO [NM2010 GALLERY]
	$('.linkspace').find('a').each(function() {
       $(this).bind('click', function() {
        $('.content_space').scrollTo( 'li:eq(' + ($(this).attr('href').substr(1) - 1) + ')', 1600, {queue:true});
			return false;
		}); 
	});
	
	//slide up tab MASTER SLIDER CONTROL //
	$('.master_slider_desc').hover(function(){
		$('.slide_caption', this).stop().animate({bottom:'0'},{queue:false,duration:300});
			}, function() {
		$('.slide_caption', this).stop().animate({bottom:'-45px'},{queue:false,duration:300});
		});	

	$('.list_container').hover(function(){
		$('.list_overlay', this).stop().animate({bottom:'120px'},{queue:false,duration:300});
			}, function() {
		$('.list_overlay', this).stop().animate({bottom:'0px'},{queue:false,duration:300});
		});	
	
	//Control Parameter for the Index Accordion //
	$('.index_blog_article_container').hide(); 
	$('.index_blog_article_trigger:first').addClass('active').next().show();
	$('.index_blog_article_trigger').click(function(){
		if( $(this).next().is(':hidden') ) { 
			$('.index_blog_article_trigger').removeClass('active').next().slideUp(200);
			$(this).toggleClass('active').next().slideDown(200); 
			}
			return false;
		});

	//EXPERIENCE ACCORDION CONTROL
	$(".about_block, .project_block").hide();
		$(".exp_sidebar span, .view_specs").click(function () {
			if ($(this).hasClass("open")) {
				$(".about_block, .project_block").slideUp('fast')
			} else {
				$(".exp_sidebar span, .view_specs").removeClass("open");
				$(".about_block, .project_block").slideUp('fast');
				$(this).next().slideToggle('fast')
			}
			$(this).toggleClass("open");
			return false
		});
		
	//STYLE SWITCH FUNCTION
	$("a.switch_thumb").toggle(function(){
	  	$(this).addClass("swap"); 
	  	$("ul.display").fadeOut("fast", function() {
	  		$(this).fadeIn("fast").addClass("thumb_view"); 
		 	});
	  	}, function () {
      		$(this).removeClass("swap");
	  		$("ul.display").fadeOut("fast", function() {
	  		$(this).fadeIn("fast").removeClass("thumb_view");
			});
		});
	
	
	//Hover Image 
	$('ul.latest li, ul.carousel li').hover(function() { 
		var thumbOver = $(this).find('img').attr('src'); 
		$(this).find('a.thumb').css({'background' : 'url(' + thumbOver + ') no-repeat center bottom'});
		$(this).find('span').stop().fadeTo('normal', 0 , function() {
			$(this).hide()
		}); 
	} , function() { 
		$(this).find('span').stop().fadeTo('normal', 1).show();
	});
	
	
	//MICRO SLIDER 
	//Set Default State of each portfolio piece
	$(".paging, .slideshow_paging").show();
	$(".paging a:first, .slideshow_paging a:first").addClass("active");
		
	//Get size of images, how many there are, then determin the size of the image reel.
	var imageWidth = $(".micro_slide_frame, .slideshow_frame").width();
	var imageSum = $(".image_reel img, .slideshow_reel img").size();
	var imageReelWidth = imageWidth * imageSum;
	
	//Adjust the image reel to its new size
	$(".image_reel, .slideshow_reel").css({'width' : imageReelWidth});
	
	//Paging + Slider Function
	rotate = function(){	
		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

		$(".paging a, .slideshow_paging a").removeClass('active'); //Remove all active class
		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
		
		//Slider Animation
		$(".image_reel, .slideshow_reel").animate({ 
			left: -image_reelPosition
		}, 500 );
		
	}; 
	
	//Rotation + Timing Event
	rotateSwitch = function(){		
		play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
			$active = $(".paging a.active, .slideshow_paging a.active").next();
			if ( $active.length === 0) { //If paging reaches the end...
				$active = $(".paging a:first, .slideshow_paging a:first"); //go back to first
			}
			rotate(); //Trigger the paging and slider function
		}, 8000); //Timer speed in milliseconds (3 seconds)
	};
	
	rotateSwitch(); //Run function on launch
	
	//On Hover
	$(".image_reel a, .slideshow_reel a").hover(function() {
		clearInterval(play); //Stop the rotation
	}, function() {
		rotateSwitch(); //Resume rotation
	});	
	
	//On Click
	$(".paging a, .slideshow_paging a").click(function() {	
		$active = $(this); //Activate the clicked paging
		//Reset Timer
		clearInterval(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation
		return false; //Prevent browser jump to link anchor
	});	

	//THIS SCRIPT CONTROLS THE SLIDER using EASYSLIDER PLUGIN
	$('#slider').easySlider({
	auto: true,
	continuous: true,
	numeric: true,
	pause: 12000,
	speed: 500,
		});
	
});
