/* 	
	DEO SLIDER
	Created by Peter Norbeck
	
*/

(function($) {

	$.deoSlider = function(el, options){
	
		// To avoid scope issues, use 'base' instead of 'this'
		// to reference this class from internal events and functions.
		var base = this;
		
		// Wraps the ul in the necessary divs and then gives Access to jQuery element
		//base.$el = $(el).addClass('deoSliderBase').wrap('<div class="deoSlider"><div class="deoSliderWindow" /></div>');
		base.$el = $(el);
		
		// Add a reverse reference to the DOM object
		base.$el.data("DeoSlider", base);
		
		base.init = function()
		{
			// Merge options with default config
			base.config	= $.extend({}, $.deoSlider.defaults, options);
			
			// Save items
			base.$items = base.$el.find('.items').children();
			
			// Turn off menuNav if only one slide and removeNavIfOneSlide=true 
			base.config.useMenuNav = (base.config.removeNavIfOneSlide && base.$items.length <= 1) ? false : true;
			
			//vars
			base.cIndex		= 0;
			base.interval 	= null;
			base.timer		= null;
			base.isAnim		= false;
			base.totItems	= base.$items.length;
			base.timerOff	= false;
			base.hovered	= false;
			
			// INIT ITEMS EVENTS
			$.each(base.$items, function(key, value){
				$(this).mouseenter(function(){ base.itemOver($(this));})
				$(this).mouseleave(function(){ base.itemOut($(this));})
				$(this).css('display','none');
							
				if($(this).find('a').length > 0){
					$(this).click(function(){ 
						window.open($(this).find('a').attr('href'));
						return false;
					});
					$(this).css('cursor','pointer');
				}
	 		});
	    	
	    		
			// INIT MENU NAV
			if(base.config.useMenuNav){
				base.$menu	= base.$el.find('.thumbs ul').children();
				$.each(base.$menu, function(key,value){
					
					$(this).click(function(event){
						event.stopPropagation();
						base.showByIndex(key);
						base.setActiveNav(key);
					});
					
				});
				base.setActiveNav(0);
				base.$el.find('.thumbs').css('display', 'block');
			}else{
				base.$el.find('.thumbs').remove();
			};
      		
			// INIT DIR NAV
			if(base.config.useDirNav){		
				base.$el.find('.navLeft').click(function(){ base.initSlide(-1) });
    	  		base.$el.find('.navRight').click(function(){ base.initSlide(1) });
      		};
      		
     		// INIT TOUCH SCREEN
     		// jquery.wipetouch.js 
			if(base.config.useWipe){
				base.$el.wipetouch({
	    	 		wipeLeft: function(result) { base.slide(1) },
    	 			wipeRight: function(result) {base.slide(-1) }
  				});
      		};
      		
      		// INIT AUTOSLIDE
			if(base.config.autoSlide){
				base.startTimer()
			};
			
			// INIT FIRST ITEM
			base.$items.eq(0).css('opacity',1);
      		base.$items.eq(0).css('display','block');
      		base.ieFilterHack(base.$items.eq(0));
      		
			// Slider Hover Events
			base.$el.mouseenter(function(e){
				base.hovered = true;
				base.sliderOver();
			});
			base.$el.mouseleave(function(e){
				base.hovered = false;
				base.sliderOut();
			});
			
			// Show slider - Used to prevent slide items to show before properly initiatet
			base.$el.css({'display':'block', 'visibility':'visible'});

		};		
	
		/**
		*	Autoslide Timer
		*/
		base.startTimer = function(){
			if(base.interval)clearTimeout(base.interval);
			base.interval = setInterval(function(){
				var nIndex   = base.cIndex + 1;
	    		nIndex    = (nIndex <0) ? base.totItems-1 : (nIndex >= base.totItems) ? 0 : nIndex;
	    		base.showByIndex(nIndex);
	    		if(base.config.useMenuNav) base.setActiveNav(nIndex);
			},base.config.transDelay);
	  	};
	  	
	  	/**
	  	*	StopTimer
	  	*/
		base.stopTimer = function stopTimer(){
			clearTimeout(base.interval); 
		};
  	 
     	/**
		*	Show By index. 
		*	Called from menu nav
		*	@nIndex - next index to show
		*/
		base.showByIndex = function (nIndex)
		{
			debug("showByIndex - nIndex: " + nIndex);
			//Transition?
			if(base.config.transType=='fade'){
				base.fade(nIndex);
			}else if(base.config.transType=='slide'){
				base.slideDir = (base.cIndex < nIndex)? -1:1;
				base.slide(base.slideDir,nIndex);
			}
		};
		
		/**
		*	Fade
		*	@nIndex - next index to fade in
		*/
		base.fade = function(nIndex)
		{
			if(base.isAnim || base.cIndex == nIndex) return;
	    	base.isAnim = true;
			var cItem = base.$items.eq(base.cIndex)
			var nItem = base.$items.eq(nIndex);
			nItem.css({'left':0,'opacity':0, 'display':'block'});
			cItem.fadeOut(base.config.transSpeed);
			nItem.animate(  {'opacity': 1 }, base.config.transSpeed, function()
	    	{ 
	    		nItem.css('opacity',1);
	    		nItem.css('display','block');
				base.cIndex = nIndex; 
				base.isAnim = false; 
				if(!base.hovered) base.startTimer();
				base.ieFilterHack(nItem);
				
			});
		};
	   
	   
	   base.initSlide = function(dir){
	   	if(base.config.transType == "fade"){
	   		var nIndex  	= base.cIndex + dir;
	    	nIndex    		= (nIndex <0) ? base.totItems-1 : (nIndex >= base.totItems) ? 0 : nIndex;
	    	base.showByIndex(nIndex);
	   		
	   	}else{
	   		base.slide(dir);
	   	}
	   
	   }
	   
	    
	  	/**
		*	Show Prev|Next|JumpTo slide. 
		* 	@dir - direction -1|1
		*	@index - jump to index
		*/
	
		base.slide = function(dir, toIndex)
		{
			if(base.isAnim) return;
			base.isAnim  	= true;
			var cItem 		= base.$items.eq(base.cIndex)
	    	var nIndex  	= (toIndex==null) ? base.cIndex + dir : toIndex;
	    	nIndex    		= (nIndex <0) ? base.totItems-1 : (nIndex >= base.totItems) ? 0 : nIndex; 
	    	var nItem   	= base.$items.eq(nIndex);
	    	var itemStartPos= (dir==1) ? base.config.width : base.config.width*-1;
	    	
	    	nItem.css({ 'left':itemStartPos, 'opacity':1, 'display':'block' });

	    	nItem.animate( {'left': 0 }, base.config.transSpeed, function()
	    	{ 
	        	cItem.css('left', base.config.width);
	        	base.cIndex += dir;
	        	base.cIndex = (base.cIndex <0) ? base.totItems-1 : (base.cIndex >= base.totItems) ? 0 : base.cIndex; 
	        	if(base.config.useMenuNav)
	        	{
	        		base.setActiveNav(nIndex); 
	        	}
	        	if(base.config.autoSlide && !base.hovered)
	        	{
	        		base.startTimer();
	      		}
	      		base.isAnim = false;
	      		
				base.ieFilterHack(nItem);		
	      		
	      	});
			
			cItem.animate( {'left': base.config.width*(dir*-1) }, base.config.transSpeed, function(){ cItem.css('display','none');} );
		};
	
		/**
		*	Set Active Navigation item
		*/
		base.setActiveNav = function (index)
		{
	    	$.each(base.$menu, function(index,value){
	    		$(this).removeClass('active');
	    	});
	    	base.$menu.eq(index).addClass('active');
	  	};
		
		/**
		*	Slider Over Action
		*/
		base.sliderOver = function()
		{ 
			if(base.config.autoSlide && base.config.pauseOnHover)
			{
				base.stopTimer();
			}
		};

		/**
		*	Slider Out Action
		*/
		base.sliderOut = function()
		{ 
			if(base.config.autoSlide && base.config.pauseOnHover){
				if(base.config.mouseOutTimerDelay > 0){
					clearTimeout(base.timer);
					base.timer = setTimeout(base.startTimer,config.mouseOutTimerDelay);	
				}else{
					base.startTimer();
				}
			}
		};
		
		/**
		*	Item Over Action
		*/
		base.itemOver = function(item)
		{ 	
			if(base.config.useMOCaption){
				var caption = item.find('.caption'); 
				if( caption.length > 0){
					base.showCaption(caption); 
				}
			} 
		};
		
		/**
		*	Item Out Action
		*/
		base.itemOut = function(item)
		{
			if(base.config.useMOCaption){	
				var caption = item.find('.caption'); 
				if(caption.length > 0){
					base.hideCaption(caption);
				}
			}
		};
	
		/**
		*	Show Caption
		*/
		base.showCaption = function(caption)
		{
			//caption.css({display: 'block'});
			//caption.animate({opacity:0.9},200);
			caption.css({'opacity':0, 'display':'block'}).fadeTo(200, 1, function(){
				base.ieFilterHack(caption);
			});
			
			//caption.css({'opacity':0, 'visibility':'visible'}).animate({opacity:0.9}, 200)
			//caption.stop().animate({'opacity':0.9}, 200);
		};

		/**
		*	Hide Caption
		*/
		base.hideCaption = function(caption)
		{
			//caption.css({display: 'none'});
			//caption.animate({'opacity':0},500)
			
			caption.fadeOut();
		};
		
		
		/**
		* IE 8- FIX.
		* IE adds filter when animating. Filter makes font-faces edgy.
		* Call this after animation finished to remove filter.
		*/
		base.ieFilterHack = function(content){
			content.css('filter', "");
		}
		
		// Trigger the initialization
		base.init();
		
		
	};

	$.deoSlider.defaults  = {
		width:960,
		transType: 'fade',          	 	// fade, horizontal-slide, vertical-slide, horizontal-push
		transSpeed: 500,     	 			// how fast animtions are
		transSpeedClick: 500,     	 			// how fast animtions are
		transDelay: 5000,         			// Transition delay
		useMenuNav: false,					// Use menu nav
		removeNavIfOneSlide: true,			// if only one slide remove bottom navigation
		useDirNav: false, 		        	// Use directional navs
		autoSlide: true,	        		// Automatic slide
		pauseOnHover: true,         		// if you hover pauses the slider
		mouseOutTimerDelay: 0, 	    		// if clock should start on MouseOut
		useMOCaption: false,				// caption that shows on Mouse Over
		useCaption: false,					// caption that show with slide
		useWipe: false,						// Use touchscrren wipe
		
		afterSlideChange: function(){}		// empty function
	};
	
	
	/**
	*	External function calls init
	*/
	$.fn.deoSlider = function( options )
	{
    	// initialize the slider
		if ((typeof(options)).match('object|undefined')){
			return this.each(function(i){
				(new $.deoSlider(this, options));
			});
		}

		// If options is a number, process as an external link to item #: $(element).deoSlider(#)
		else if (/\d/.test(options) && !isNaN(options)) {
			return this.each(function(i) {
				var deoSlide = $(this).data('DeoSlider');
				if (deoSlide) {
					var page = (typeof(options) == "number") ? options : parseInt($.trim(options),10); // accepts "  2  "
					// ignore out of bound pages
					if ( page < 1 || page > deoSlide.totItems ) { return; }
					deoSlide.showByIndex(index+1);
				}
			});
		}
	};

})(jQuery);




// jQuery WipeTouch 1.0.3
//
// Developed and maintained by Devv: http://devv.com
// This plugin is based on TouchWipe by Andreas Waltl: http://www.netcu.de
//
// USAGE
// $(selector).wipetouch(config);
//
// The wipe events should expect the result object with the following properties:
// speed - the wipe speed from 1 to 5
// x - how many pixels moved on the horizontal axis
// y - how many pixels moved on the vertical axis
//
// EXAMPLE
//		$(document).wipetouch({
//			allowDiagonal: true,
//			wipeLeft: function(result) { alert("Left on speed " + result.speed) },
//			wipeTopLeft: function(result) { alert("Top left on speed " + result.speed) },
//			wipeBottomLeft: function(result) { alert("Bottom left on speed " + result.speed) }
//		});
//
//
// More details at http://wipetouch.codeplex.com/

(function($)
{
	$.fn.wipetouch = function(settings)
	{
		// ------------------------------------------------------------------------
		// PLUGIN SETTINGS
		// ------------------------------------------------------------------------

		var config = {
			moveX:				30,		// minimum amount of horizontal pixels to trigger a wipe event
			moveY:				30,		// minimum amount of vertical pixels to trigger a wipe event
			preventDefault:		true,	// if true, prevents default events (click for example)
			allowDiagonal:		false,	// if false, will trigger horizontal and vertical movements only
										// so wipeTopLeft, wipeBottomLeft, wipeTopRight, wipeBottomRight are ignored)

			wipeLeft:			function(result) { },	// called on wipe left gesture
			wipeRight:			function(result) { },	// called on wipe right gesture
			wipeUp:				function(result) { },	// called on wipe up gesture
			wipeDown:			function(result) { },	// called on wipe down gesture
			wipeTopLeft:		function(result) { },	// called on wipe top and left gesture
			wipeBottomLeft:		function(result) { },	// called on wipe bottom and left gesture
			wipeTopRight:		function(result) { },	// called on wipe top and right gesture
			wipeBottomRight:	function(result) { }	// called on wipe bottom and right gesture
		};

		if (settings)
		{
			$.extend(config, settings);
		}

		this.each(function()
		{
			// ------------------------------------------------------------------------
			// INTERNAL VARIABLES
			// ------------------------------------------------------------------------
			var startX; // where touch has started, left
			var startY; // where touch has started, top
			var startDate = false; // used to calculate timing and aprox. acceleration
			var curX; // keeps touch X position while moving on the screen
			var curY; // keeps touch Y position while moving on the screen
			var isMoving = false; // is user touching and moving?

			// ------------------------------------------------------------------------
			// TOUCH EVENTS
			// ------------------------------------------------------------------------

			// Called when user touches the screen
			function onTouchStart(e)
			{
				if (!isMoving && e.touches.length > 0)
				{
					startDate = new Date().getTime();

					startX = e.touches[0].pageX;
					startY = e.touches[0].pageY;
					curX = startX;
					curY = startY;

					isMoving = true;

					this.addEventListener('touchmove', onTouchMove, false);
				}
			}

			// Called when user untouches the screen
			function onTouchEnd(e)
			{
				this.removeEventListener('touchmove', onTouchMove, false);

				touchCalculate();

				startX = false;
				startY = false;
				startDate = false;
				isMoving = false;
			}

			// Called when user is touching and moving on the screen
			function onTouchMove(e)
			{
				if (config.preventDefault)
				{
					e.preventDefault();
				}

				if (isMoving)
				{
					curX = e.touches[0].pageX;
					curY = e.touches[0].pageY;
				}
			}

			// ------------------------------------------------------------------------
			// CALCULATE TOUCH AND TRIGGER
			// ------------------------------------------------------------------------
			function touchCalculate()
			{
				var endDate = new Date().getTime();	// current date to calculate timing

				var x = curX;			// current left position
				var y = curY;			// current top position
				var dx = x - startX;	// diff of current left to starting left
				var dy = y - startY;	// diff of current top to starting top
				var ax = Math.abs(dx);	// amount of horizontal movement
				var ay = Math.abs(dy);	// amount of vertical movement

				var toright = dx > 0;	// if true X movement is to the right, if false is to the left
				var tobottom = dy > 0;	// if true Y movement is to the bottom, if false is to the top

				// calculate speed from 1 to 5, being 1 slower and 5 faster
				var s = ((ax + ay) * 99) / ((startDate - endDate) / 9 * (startDate - endDate));

				if (s < 1) s = 1;
				if (s > 5) s = 5;

				var result = {speed: s, x: ax, y: ay};

				if (ax >= config.moveX)
				{
					// Checks if it's allowed and call diagonal wipe events
					if (config.allowDiagonal && ay >= config.moveY)
					{
						if (toright && tobottom)
							triggerEvent(config.wipeBottomRight, result);
						else if (toright && !tobottom)
							triggerEvent(config.wipeTopRight, result);
						else if (!toright && tobottom)
							triggerEvent(config.wipeBottomLeft, result);
						else
							triggerEvent(config.wipeTopLeft, result);
					}
					else
					{
						if (toright)
							triggerEvent(config.wipeRight, result);
						else
							triggerEvent(config.wipeLeft, result);
					}
				}
				else if (ay >= config.moveY)
				{
					if (tobottom)
						triggerEvent(config.wipeDown, result);
					else
						triggerEvent(config.wipeTop, result);
				}
			}

			// Triggers a wipe event passing a result object with
			// speed from 1 to 5, and x / y movement amount in pixels
			function triggerEvent(wipeEvent, result)
			{
				wipeEvent(result);
			}

			// ------------------------------------------------------------------------
			// ADD TOUCHSTART AND TOUCHEND EVENT LISTENERS
			// ------------------------------------------------------------------------

			if ('ontouchstart' in document.documentElement)
			{
				this.addEventListener('touchstart', onTouchStart, false);
				this.addEventListener('touchend', onTouchEnd, false);
			}
		});

		return this;
	};
})(jQuery);




/**
*	Debug - so IE doesn't have a fit
*/
function debug(value)
{
	if (window.console && window.console.log){
		console.log(value);
	}
}; 


