﻿(function($){

/* ******************************************************************
	idleTimer by Paul Irish - http://paulirish.com/2009/jquery-idletimer-plugin/
	for added carousel functionality
****************************************************************** */

$.idleTimer = function(newTimeout, elem){

    // defaults that are to be stored as instance props on the elem

    var idle = false, //indicates if the user is idle
        enabled = true, //indicates if the idle timer is enabled
        timeout = 30000, //the amount of time (ms) before the user is considered idle
        events = 'mousemove keydown DOMMouseScroll mousewheel mousedown touchstart touchmove'; // activity is one of these events


    elem = elem || document;



    /* (intentionally not documented)
* Toggles the idle state and fires an appropriate event.
* @return {void}
*/
    var toggleIdleState = function(myelem){

        // curse you, mozilla setTimeout lateness bug!
        if (typeof myelem === 'number'){
            myelem = undefined;
        }

        var obj = $.data(myelem || elem,'idleTimerObj');

        //toggle the state
        obj.idle = !obj.idle;

        // reset timeout
        var elapsed = (+new Date()) - obj.olddate;
        obj.olddate = +new Date();

        // handle Chrome always triggering idle after js alert or comfirm popup
        if (obj.idle && (elapsed < timeout)) {
                obj.idle = false;
                clearTimeout($.idleTimer.tId);
                if (enabled)
                  $.idleTimer.tId = setTimeout(toggleIdleState, timeout);
                return;
        }
        
        //fire appropriate event

        // create a custom event, but first, store the new state on the element
        // and then append that string to a namespace
        var event = jQuery.Event( $.data(elem,'idleTimer', obj.idle ? "idle" : "active" ) + '.idleTimer' );

        // we dont want this to bubble
        event.stopPropagation();
        $(elem).trigger(event);
    },

    /**
* Stops the idle timer. This removes appropriate event handlers
* and cancels any pending timeouts.
* @return {void}
* @method stop
* @static
*/
    stop = function(elem){

        var obj = $.data(elem,'idleTimerObj');

        //set to disabled
        obj.enabled = false;

        //clear any pending timeouts
        clearTimeout(obj.tId);

        //detach the event handlers
        $(elem).unbind('.idleTimer');
    },


    /* (intentionally not documented)
* Handles a user event indicating that the user isn't idle.
* @param {Event} event A DOM2-normalized event object.
* @return {void}
*/
    handleUserEvent = function(){

        var obj = $.data(this,'idleTimerObj');

        //clear any existing timeout
        clearTimeout(obj.tId);



        //if the idle timer is enabled
        if (obj.enabled){


            //if it's idle, that means the user is no longer idle
            if (obj.idle){
                toggleIdleState(this);
            }

            //set a new timeout
            obj.tId = setTimeout(toggleIdleState, obj.timeout);

        }
     };


    /**
* Starts the idle timer. This adds appropriate event handlers
* and starts the first timeout.
* @param {int} newTimeout (Optional) A new value for the timeout period in ms.
* @return {void}
* @method $.idleTimer
* @static
*/


    var obj = $.data(elem,'idleTimerObj') || {};

    obj.olddate = obj.olddate || +new Date();

    //assign a new timeout if necessary
    if (typeof newTimeout === "number"){
        timeout = newTimeout;
    } else if (newTimeout === 'destroy') {
        stop(elem);
        return this;
    } else if (newTimeout === 'getElapsedTime'){
        return (+new Date()) - obj.olddate;
    }

    //assign appropriate event handlers
    $(elem).bind($.trim((events+' ').split(' ').join('.idleTimer ')),handleUserEvent);


    obj.idle = idle;
    obj.enabled = enabled;
    obj.timeout = timeout;


    //set a timeout to toggle state
    obj.tId = setTimeout(toggleIdleState, obj.timeout);

    // assume the user is active for the first x seconds.
    $.data(elem,'idleTimer',"active");

    // store our instance on the object
    $.data(elem,'idleTimerObj',obj);



}; // end of $.idleTimer()


// v0.9 API for defining multiple timers.
$.fn.idleTimer = function(newTimeout){
    if(this[0]){
        $.idleTimer(newTimeout,this[0]);
    }

    return this;
};


})(jQuery);


/* ******************************************************************
	carousel plugin
	
	rewritten by P Steffens, Macaw
	09-2011
	
	note:	animation time of arrow is determined by transition styling in css
			and is therefore not linked to transitionTime for slide animation
	
****************************************************************** */

(function($) {

    $.fn.carrousel = function () {
    
    	var cthis = $(this),
    		cfragments = cthis.find(".fragments"),
    		cslides = cfragments.find("> div"),
    		cctas = cthis.find(".carrouselcta"),
    		clista = cthis.find(".carrousellist a"),
    		cpaused = false,
    		transitionTime = 500,
    		slideTime = 6000,
    		idleTime = 30000,
    		carInTransit = false;
    	
    	function init() {
    		
    		// callback to load remaining imgs and build carousel
    		var start = function() {
    			for ( x = 1 ; x < cslides.length ; x++ ) {
    				loadImg( x );
    			}
    			startCarousel();
    		}
    		
    		// load first image and pass callback
    		loadImg( 0, start );
    		
    	}
    	
    	function loadImg( urlIndex, f ) {
    	
    		var img = new Image(),
    			cslide = cslides.eq(urlIndex);
    			
			img.src = cslide.data("imgurl"); // this feature is dependant on jquery > v.1.4.3
			img.onload = function() {
				// place img
				$(this).attr("alt","").css({ "width" : 960, "height" : 350}).appendTo( cslide );
				// do passed callback
    			if (f) { f() };
			};
			img.onerror = function() {
				// still do passed callback (to dl other images through callback if possible)
    			if (f) { f() };
			};
    		
    	}
    	
    	function startCarousel() {
    	
    		// remove loading bg image
    		cfragments.css("background","transparent none");
    		
    		// add bogus carrouselcta block outside of slide loop
    		// so green square is always 100% visible, even during transition
    		$("<div>")
    			.addClass("carrouselcta")
    			.prependTo( cthis );
    			
    		// add arrow
    		$("<b>")
    			.addClass("cararrow")
    			.append( $("<b>") )
    			.appendTo( cthis );
    			
    		var carrow = cthis.find(".cararrow");
    		
			// do cycle plugin coupling
			cfragments
				.cycle({
					fx: 'fade',
					speed: transitionTime,
					timeout: slideTime,
					before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
						// mark transition to counteract extra mouseover events generated by changing slides
						carInTransit = true;
						// move arrow to next slide, transitions will take care of the rest for modern browsers
						carrow.css(
								"left",
								clista.eq( $(nextSlideElement).index() ).position().left + 29
							);
						// set correct menuitems
						clista.eq( $(currSlideElement).index() ).removeClass("current");
						clista.eq( $(nextSlideElement).index() ).addClass("current");
					},
					after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
						// set it back again
						carInTransit = false;
					}
				});
				
			// set events for buttons
			clista.click(moveMe);
			
			// set events for pausing
			cctas.mouseenter(pauseMe).mouseleave(resumeMe);
			
			// kickstart cycle plugin	
			cfragments.cycle('resume');	

    	}
    	
    	function moveMe(event) {
    		event.preventDefault();
    		cfragments.cycle( $(this).closest("li").index() );
    	}
    	
    	function pauseMe() {
    		// don't pause after resumeMeAuto (a new slide will trigger this)
    		if ( cpaused === false ) {
    			cfragments.cycle("pause");
    			// do idle timer to start playin again after 30s of inactivity
				$.idleTimer(idleTime);
				$(document).bind("idle.idleTimer", resumeMeAuto );
			}
    	}
    	
    	function resumeMe(event) {
    		// don't do anything when transitioning between slides (event was created from false positive)
    		if ( carInTransit === false ) {
    			// resume playback of slides
    			cpaused = false;
    			cfragments.cycle("resume");
    			$.idleTimer('destroy');
    		}
    	}
    	
    	function resumeMeAuto() {
    		// after 30s of inactivity, start playin' again
    		cpaused = true;
    		cfragments.cycle("resume");
    		// no unneccesary events on the document, please
    		$.idleTimer('destroy');
    	}
    	
    	return init();
    
    }
    
})(jQuery);

/*
	Start the caroussel!
 */
$(function() {

	$("#carrousel").carrousel();

});

/* ******************************************************************
	service lint plugin for VGZ
	written by P Steffens, Macaw
	09-2011

****************************************************************** */

(function($) {

    $.fn.servicelint = function () {
    
    	var slWindowWidth = $(this).find(".slwindow").innerWidth(),
    		slBars = $(this).find(".slbar"),
    		slNav = $(this).find(".slnav"),
    		slNavContents = slNav.clone(),
    		slContainer = $(this).find(".slcontainer"),
    		slItemColl = $(this).find(".slunit"),
    		slItemLength = slItemColl.length,
    		slBreakpoints = [],
    		slSlideTime = 1000,
    		slOffset = 0,
    		slCurrPos = 0,
    		slNewPos = slCurrPos;
    	
    	function init() {
    		
    		// create breakpoint array
    		// breakpoint array contains absolute x-position for each scroll-to-point for .slcontainer
    		for ( x = 0; x < slItemLength ; x++) {
    	
    			var curItem = slItemColl.eq(x),
    				curItemX = curItem.position().left;	
    			
    			// a breakpoint is left x-pos of a unit that extends beyond the window, or the first one
    			if (  ((curItemX + curItem.outerWidth()) >  slWindowWidth + slOffset) || curItemX == 0  ) {
    				slBreakpoints.push(curItemX);
    				slOffset = curItemX;
    			}
    		}
			
			// build interface only if needed (=more than 1 breakpoint)
    		if (slBreakpoints.length > 1) {
    		
    			// create navbuttons
    			for ( x = 0; x < slBreakpoints.length ; x++) {
    				slNavContents
    					.append(
    						$("<li>")
    							.append(
    								$("<a>")
    									.attr("href","#")
    									// yes, add an event
    									.click(moveMe)
    									.append(
    										$("<i>")
    											.append(
    												$("<b>")
    											)
    									)
    							)
    					);
    					
    			}
    			// place in html
    			slNav.append(slNavContents.find("li"));
    			// make arrow thingie
    			$("<span>")
    				.addClass("slarrow")
    				.append(
    					$("<b>")
    				)
    				.insertAfter(slNav);
    			// move the arrow too
    			$(".slarrow").css("left",slNav.find("i").eq(slNewPos).position().left - 4);
    			// make sidebuttons active
    			slBars.find("a").click(moveMe);
    			// and init controls to finish off...
    			setBottomControls();	
    			setSideControls();
    		}
    	}
    	
    	// event handling starts here...
    	function moveMe(event) {
    	
    		event.preventDefault();
    		var clicked = $(event.target);
    		
    		// make sure reference is always a hyperlink
    		if ( clicked.is("a") ) { var linked = clicked } else { var linked = clicked.closest("a") }
    		
    		// no need to do anything if button is selected or disabled
    		if ( !linked.is(".disabled") && !linked.find("i").is(".selected") ) {
    		
    			var linkedparent = linked.parent();
    			
    			if ( linkedparent.is("li") ) {
    			// clicked on navbutton
    				slNewPos = linkedparent.index();
    			} else {
    				if ( linkedparent.is(".right") ) {
    			// clicked on right sidebutton
    					if ( slNewPos < slBreakpoints.length-1 ) { slNewPos++ }
    				} else {
    			// clicked on left sidebutton
    					if ( slNewPos > 0 ) { slNewPos-- }
    				}
    			}
    			
    			// start moving stuff already!
    			doMove();
    			
    		}
    	}
    	
    	// actually move the stuff here
    	function doMove() {
    	
    		slContainer
    			.stop()
    			.animate(
    				{ left: -(slBreakpoints[slNewPos]) }, 
    				slSlideTime, 
    				'swing', 
    				function() {
  						// when done, recalibrate interface
    					setSideControls();
  					}
  				);
  				
  			setBottomControls();
  			
    	}
    	
    	// set controls and states of bottom interface
    	function setBottomControls() {
    	
			// move the arrow
			$(".slarrow").css("left",slNav.find("i").eq(slNewPos).position().left - 4);
			// set state for nav elements and remove focus
			slNav
				.find("a")
					.blur()
					.find("i")
						.removeClass("selected")
						.eq(slNewPos)
							.addClass("selected");
    	
    	}
    	
    	// set controls and states of sidebuttons
    	function setSideControls() {
    							
    		// remove focus from sidebuttons
    		slBars.find("a").blur();
    		
    		// set state for left sidebutton
    		if ( slNewPos === 0 ) {
    			slBars.eq(0).find("a").addClass("disabled")
    		} else {
    			slBars.eq(0).find("a").removeClass("disabled")
    		}
    		// set state for right sidebutton
    		if ( slNewPos === slBreakpoints.length-1 ) {
    			slBars.eq(1).find("a").addClass("disabled")
    		} else {
    			slBars.eq(1).find("a").removeClass("disabled")
    		}
    		
    		// set current position index
  			slCurrPos = slNewPos;
    	}
    	
    	return init();
    
    }
    
})(jQuery);

$(function() {
	$(".servicelint").servicelint();
});
