// Create Slideshow Component
Util.namespace('Nerland.Components.Slideshow', function () {
    var view;
    var panels;

    var current;

    var timer;
    var animating;

    var props = {
        barWidth: 25,
        imageWidth: 735,
        speed: 500,
        time: 4000
    }

    //initialize the component
    var init = function ($view, $props) {

        //set the main view
        view = $view;

        if ($props) {
            $.extend(props, $props);
        }

        //get panels add click events
        panels = $(".panel", view);
        for (var i = 0; i < panels.length; i++) {
            var cur = $(panels.get(i));
            if (i === 0) {
                cur.css({
                    "left": (i * props.barWidth) + "px"
                });
            }
            else {
                cur.css({
                    "left": ((i * props.barWidth) + props.imageWidth) + "px"
                });
            }
        }

        panels.find(".slide-bar").click(panelTabClick);

        //animating 
        animating = false;

        // choose default
        // the panel to display is stored in a cookie so see if it exists
        var currentPanelIdFromCookie = $.cookie("home_panel_id");
        if (currentPanelIdFromCookie != null && currentPanelIdFromCookie.length > 0 && currentPanelIdFromCookie != "panel0") {
            // switch to the panel specified in the cookie
            current = panels.first();
            var jumpPanel = $("#" + currentPanelIdFromCookie, view);
            //initialize timer timer
            jumpTo(jumpPanel);
        }
        else {
            // no panel specified in the cookie so just start on the first one
            //set default 
            current = panels.first();
            $.cookie("home_panel_id", current.attr("id"));
            //initialize timer timer
            timer = setTimeout(animate, props.time);
        }

    };

    var pause = function () {
        clearTimeout(timer);
    }

    var play = function () {
        //initialize timer timer
        timer = setTimeout(animate, props.time);
    }

    $(window).blur(function () {
        // lost window focus so pause the slideshow
        pause();
    });

    $(window).focus(function () {
        // got window focus so start playing the slideshow again
        play();
    });

    //handle animating the panels
    var animate = function () {

        //get next panel
        var next = current.next();

        //if next is last, then get first
        if (next.length == 0)
            next = panels.first();

        //toggle animation
        toggle(next);

    }

    // does the same thing as toggle except the animation is done instantly to $next instead of showing the animation
    var jumpTo = function ($next) {

        //kill timer if hasn't fired
        clearTimeout(timer);

        //set animating status
        animating = true;

        //loop through and animate items
        var tar = $next.index();
        for (var i = 0; i < panels.length; i++) {
            var cur = $(panels.get(i));
            var newLeft;

            var newLeft = (i <= tar) ? (i * props.barWidth) : ((i * props.barWidth) + props.imageWidth);
            if (newLeft != parseInt(cur.css("left"))) {
                cur.animate({
                    "left": newLeft + "px"
                }, 0);
            }

        }

        //update clip
        current = $next;

        // save the current home panel id to the cookie so it will be switched to when returning
        $.cookie("home_panel_id", current.attr("id"));

        //start new timer
        timer = setTimeout(function () {
            animating = false;
            timer = setTimeout(animate, props.time);
        }, props.speed);
    }

    var toggle = function ($next) {

        //if its not the same element animate
        if (current !== $next) {
            //kill timer if hasn't fired
            clearTimeout(timer);

            //set animating status
            animating = true;

            //loop through and animate items
            var tar = $next.index();
            for (var i = 0; i < panels.length; i++) {
                var cur = $(panels.get(i));
                var newLeft;

                var newLeft = (i <= tar) ? (i * props.barWidth) : ((i * props.barWidth) + props.imageWidth);
                if (newLeft != parseInt(cur.css("left"))) {
                    cur.animate({
                        "left": newLeft + "px"
                    }, props.speed);
                }

            }

            //update clip
            current = $next;

            // save the current home panel id to the cookie so it will be switched to when returning
            $.cookie("home_panel_id", current.attr("id"));

            //start new timer
            timer = setTimeout(function () {
                animating = false;
                timer = setTimeout(animate, props.time);
            }, props.speed);
        }

    }

    //handle the click of the panel side bar
    var panelTabClick = function () {

        if (animating) return;

        //toggle the current panel
        toggle($(this).parent());
    }

    //return public functions to expose
    return {
        'init': init
    };

});

// create slider component for nerland
Util.namespace('Nerland.Components.Slider', function (){

	var view;
	var slide;
	var logos;
	
	var offset;
	var timer;
	
	var props = {
		time: 5000,
		speed: 500,
		padding:0
	}

	var init = function( $view, $props ){
		
		if($props)
		{
			$.extend(props, $props);
		}
		
		//initialize view vars
		view = $view;
		slide = $("#slide", view);
		logos = $("a", slide);
		
		//click handlers
		$("#slide-left", view).click( animatePrev);
		$("#slide-right", view).click( animateNext);
		
		//handler for logo
		logos.hover(function(){
			$(this).find(".hover").fadeIn();
		},function(){
			$(this).find(".hover").fadeOut();
		});
		
		//initialize offset
		var last = logos.last();
		offset = last.width() + props.padding;
		slide.prepend( last );
		slide.css({"left":-offset + "px"});
		
		//begin animation
		timer = setTimeout( animateNext , props.time);
			
	}
	
	var animatePrev = function(){
		
		var diff = -offset - parseInt(slide.css("left"), 10);
		if( diff != 0)return;
		
		clearTimeout(timer);
		
		//grab last item and animate
		var items = $("a", slide);
		var last = items.last();
		
		slide.prepend( last );
		slide.css({ 
			"left":-last.width() - offset + props.padding
		}).animate({
			"left":-offset
		}, props.speed);		
		
		//update offset for dynamic widths
		offset = last.width() + props.padding;
		
		//set timer
		timer = setTimeout( animateNext , props.time + props.speed);
		
	}
	
	var animateNext = function(){
		
		var diff = -offset - parseInt(slide.css("left"), 10);
		
		if( diff != 0)return;
		
		clearTimeout(timer);
		
		//grab last item and animate
		var items = $("a", slide);
		var first = items.first();
		
		slide.append( first );
		slide.css({ 
			"left":first.width() - offset + props.padding
		}).animate({
			"left":-offset
		}, props.speed);	
		
		//update offset for dynamic widths
		offset = first.width() + props.padding;		
		
		//set timer
		timer = setTimeout( animateNext , props.time + props.speed);	
	}
	
	
	//return public functions to expose
    return {
        'init': init
    };
});

// create fading slideshow component for nerland
//
// init() options:
//	speed: the number of milliseconds the fade in or fade out should last (default: 500)
//	time: the number of milliseconds to wait before automatically animating (default: 4000). Set to 0 for no automatic animation.
//	pager: the id for the div containing links for navigation (default: #pager)
//	slideWrapper: the id for the div containing all the slides (default: #slides)
//	slideClass: the css class for selecting the slides inside the slideWrapper (default: slide)
//	activeClass: the css class to add to the active pager link (default: active)
//
// The slides with the specified slideClass should have a unique html id and the
// links in the pager should link to the id of the slide they will switch to.
// Example:
// <div id="slides">
//	<div class="slide" id="slide1">...</div>
// </div>
// <div id="pager">
//	<a href="#slide1">...</a>
// </div>
//
Util.namespace('Nerland.Components.FadingSlideshow', function (){
	
	// Define this component as a Class to allow more than one to be used per page
	function FadingSlideshow()
	{
		
		var view;
		var slideWrapper;
		var slides;
		var pager;
		var pagerLinks;
	
		// contains the html id of the current slide preceded by a #
		// (that is the href of the link used to switch to the slide) 
		var current;
	
		var timer;
		var animating;
		
		var beforeAnimate;	 // a callback function to call before animating, is passed the html id of the slide to be animated
		var afterAnimate;	 // a callback function to call after animating, is passed the html id of the previous slide and the slide that was animated
	
		var props = {
			speed: 500,
			time: 4000,
			pager: '#pager',
			slideWrapper: '#slides',
			slideClass: 'slide',
			activeClass: 'active',
			beforeAnimate: null,
			afterAnimate: null
		}	
	
		//initialize the component
	    this.init = function ( $view, $props )
	    {
	    	//set the main view
	    	view = $view;
    	
	    	if($props)
			{
				$.extend(props, $props);
			}
    	
			// get the slide navigation pagerLinks and add click events
			pager = $(props.pager, view);
			pager.find('a').click(pagerLinkClick);
		
			// get the div wrapping all the slides
			slideWrapper = $(props.slideWrapper, view);

	    	//get slides and hide all but the first
			var slideSelector = "." + props.slideClass;
	    	slides = $(slideSelector, slideWrapper);
	    	current = slides.first(); //set default
			for( var i=0; i< slides.length; i++)
	    	{
	    		var cur = $( slides.get(i) );

	    		if( i === 0 )
				{
					// initialize the first
					updateActivePagerLink("#"+cur.attr('id'));
				}
				else
				{
					//cur.addClass('hide');
					cur.hide();
				}
	    	}
 		
	    	//animating 
	    	animating = false;
    	
			if(props.time > 0)
			{
	    		//initialize timer timer
	    		timer = setTimeout( animate, props.time );
			}

	  	};
    
	    // handle animating the panels
	    var animate = function(){

			var cur = $(current, slideWrapper);
			var next = cur.next();
			// if next is last, then get first
			if(next.length == 0)
				next = slides.first();
		
			toggle( '#' + next.attr('id') );
		
	    }
    
		// $next is the html id of the next slide 
	    var toggle = function( $next )
	    {
    	
	    	// if its not the same element animate
	    	if( current !== $next)
	    	{
	    		// kill timer if hasn't fired
	    		clearTimeout(timer);

    			if(props.beforeAnimate != null)
					props.beforeAnimate($next);

	    		// set animating status
	    		animating = true;

				// hide the current slide
				$(current, slideWrapper).fadeOut(props.speed, function(){
				
					//fade in the next slide after the current slide fades out
					$($next, slideWrapper).fadeIn(props.speed);
					updateActivePagerLink($next);
				
					var previous = current;
				
					//update current
		    		current = $next;
				
			    	// start new timer
			    	timer = setTimeout( function(){
			    		animating = false;
						if(props.afterAnimate != null)
							props.afterAnimate(previous, current);
			
						if(props.time > 0)
						{
			    			timer = setTimeout( animate, props.time );
						}
			    	}, props.speed );
	
				});

	    	}
    	
	    }

		// updates the pager links to show the current slide's pager link as active
		// currentSlideId should be the html id of the current slide preceded by a #
		// (that is the href of the link used to switch to the slide) 
		var updateActivePagerLink = function($currentSlideId){
		
			// remove the activeClass from all pager links
			pager.find('a').removeClass(props.activeClass);
		
			// add the activeClass to the current pager link
			$("a[href='" + $currentSlideId + "']", pager).addClass(props.activeClass);
		
		}
    
	    // handle the click of a pager link
	    var pagerLinkClick = function(){
 
			// do not toggle if animation is already in progress
			if( animating ) return; 

	 		// toggle the current slide
	 		toggle( $(this).attr("href") );
	
			return false; // avoid page jump
	 	}
	
		// pauses the slideshow
		this.pause = function(){
    		// kill timer
    		clearTimeout(timer);
		}
		
		// resumes the slideshow
		this.resume = function(){
			// make sure the right slide is shown
			// necessary to avoid a bug where multiple slides are shown
			// when hiding the entire slideshow while it's paused
			/*for( var i=0; i< slides.length; i++)
	    	{
	    		var cur = $( slides.get(i) );
				if("#" + cur.attr('id') == current)
					cur.show();
				else
					cur.hide();
	    	}*/
			// start the animation timer again
			if(props.time > 0) {
    			timer = setTimeout( animate, props.time );
			}
		}
	}
	
	// initialize a new component
	// This creates a new FadingSlideshow, initializes it, and returns it.
    var init = function ( $view, $props ) {
		var slideshow = new FadingSlideshow;
		slideshow.init($view, $props);
		return slideshow;
	}
	
	// return public functions to expose
    return {
        'init': init
    };

});

// create office slideshow pager scroller to scroll office slideshow thumbnails
Util.namespace('Nerland.Components.OfficePagerScroller', function(){
	
	var props = {
		thumbnailWidth: 85	// the width of each thumbnail (including any margin)
	}	

	//initialize the component
    var init = function ( $props )
    {
    	if($props)
		{
			$.extend(props, $props);
		}
	
		// the scrolling div containing the pager
		var officePagerScroll = $("#office-pager-scroll");
		// the pager div
		var officePager = $("#office-pager");
		// the number of thumbnails
		var numThumbs = $("#office-pager a").size();
		// the scroll left link
		var officeLeft = $("#office-left");
		// the scroll right link
		var officeRight = $("#office-right");
		// the current thumbnail page
		var officePage = 0;
		// the amount to scroll when the arrows are clicked
		var officeStep = officePagerScroll.width();
		// the max left scroll location
		var officeScrollMax = officePager.width() - officePagerScroll.width();
		// the current left scroll location
		var officeScrollLocation = 0;
		
		// initialize the width of the pager based on the calculated number of
		// thumbnails and their specified width
		officePager.css('width',numThumbs*props.thumbnailWidth);
		
		officePagerScroll.css('overflow','hidden');
		
		// handle right arrow click
		officeRight.click(function(){
			officePage++;
			officeScrollLocation = officePage * officeStep;
			// don't scroll beyond max scroll location
			if(officeScrollLocation > officeScrollMax) {
				officeScrollLocation = officeScrollMax;
				officePage--;
			}
			officePagerScroll.animate({scrollLeft: officeScrollLocation}, 500);
			return false;
		});
		
		// handle left arrow click
		officeLeft.click(function(){
			officePage--;
			officeScrollLocation = officePage * officeStep;
			// don't scroll beyond min scroll location
			if(officeScrollLocation < 0){
				officeScrollLocation = 0;
				officePage = 0;
			}
			officePagerScroll.animate({scrollLeft: officeScrollLocation}, 500);
			return false;
		});
	}
	
	//return public functions to expose
    return {
        'init': init
    };

});
