/**
 * This is part of a patch to address a jQueryUI bug.  The bug is responsible
 * for the inability to scroll a page when a modal dialog is active. If the content
 * of the dialog extends beyond the bottom of the viewport, the user is only able
 * to scroll with a mousewheel or up/down keyboard keys.
 *
 * @see http://bugs.jqueryui.com/ticket/4671
 * @see https://bugs.webkit.org/show_bug.cgi?id=19033
 * @see /views_ui.module
 * @see /js/jquery.ui.dialog.min.js
 *
 * This javascript patch overwrites the $.ui.dialog.overlay.events object to remove
 * the mousedown, mouseup and click events from the list of events that are bound
 * in $.ui.dialog.overlay.create
 *
 * The original code for this object:
 * $.ui.dialog.overlay.events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
 *  function(event) { return event + '.dialog-overlay'; }).join(' '),
 *
 */

(function ($, undefined) {
  if ($.ui && $.ui.dialog) {
    $.ui.dialog.overlay.events = $.map('focus,keydown,keypress'.split(','),
                                 function(event) { return event + '.dialog-overlay'; }).join(' ');
  }
}(jQuery));
;
/*
 * jQuery Orbit Plugin 1.2.3
 * www.ZURB.com/playground
 * Copyright 2010, ZURB
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/

var viewportwidth;
var viewportheight;
var viewportar;
var freezeOrbit;

(function($) {

    $.fn.orbit = function(options) {

        //Defaults to extend options
        var defaults = {
				animation : 'horizontal-push', // fade, horizontal-slide, vertical-slide, horizontal-push
				animationSpeed : 1000, // how fast animtions are
				timer : true, // true or false to have the timer
				advanceSpeed : 5000, // if timer is enabled, time between transitions
				pauseOnHover : false, // if you hover pauses the slider
				startClockOnMouseOut : false, // if clock should start on MouseOut
				startClockOnMouseOutAfter : 1000, // how long after MouseOut should the timer start again
				directionalNav : true, // manual advancing directional navs
				captions : true, // do you want captions?
				captionAnimation : 'fade', // fade, slideOpen, none
				captionAnimationSpeed : 800, // if so how quickly should they animate in
				bullets : true, // true or false to activate the bullet navigation
				bulletThumbs : false, // thumbnails for the bullets
				bulletThumbLocation : '', // location from this file where thumbs will be
				imagear : 1.33,
            	afterSlideChange: function(){} 		// empty function
     	};
        
        //Extend those options
        var options = $.extend(defaults, options); 
	
        return this.each(function() {
        
// ==============
// ! SETUP   
// ==============
        
            //Global Variables

			var activeSlide = 0, oldActiveSlide = 0, numberSlides = 0, orbitWidth, orbitHeight, locked;
			var resizeTimer;
			var timerWasRunning;
            var timerRunning;

			//var global = $(this).addClass('global'),
			//globalWrapper = global.wrap('<div class="global-wrapper" />').parent();

			//Initialize
			window.onresize = onScreenResize;

            
            //Initialize
            var orbit = $(this).addClass('orbit'),         
            	orbitWrapper = orbit.wrap('<div class="orbit-wrapper" />').parent();
            orbit.add(orbitWidth).width('1px').height('1px');
	    	            

			//Collect all slides and set slider size of largest image
			var slides = orbit.find('div');
			slides.each(function() {
				var _slide = $(this),
                _slideWidth = _slide.width(),
                _slideHeight = _slide.height();

				if (_slideWidth > orbit.width()) {
					orbit.add(orbitWrapper).width(_slideWidth);
					orbitWidth = orbit.width();
				}
				if (_slideHeight > orbit.height()) {
					orbit.add(orbitWrapper).height(_slideHeight);
					orbitHeight = orbit.height();
				}

				//$('#slide-content-'+numberSlides).hide();
				numberSlides++;

			});
            
            //Animation locking functions
            function unlock() {
                locked = false;
            }
            function lock() { 
                locked = true;
            }
            

			//Set initial front photo z-index and fades it in
			slides.eq(activeSlide).css( {
				"z-index" : 3
			}).fadeIn(1000, function() {
				//brings in all other slides IF css declares a display: none
				slides.css( {
					"display" : "block"
				})
			});

			onScreenResize();


			function onScreenResize() {
				// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
				var scrollOffset;

				if (typeof window.innerWidth != 'undefined') {
					//alert("inner width");
					scrollOffset = $.getScrollbarWidth();
					viewportwidth = window.innerWidth,
					viewportheight = window.innerHeight
				}

				// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

				else if (typeof document.documentElement != 'undefined'
					&& typeof document.documentElement.clientWidth != 'undefined'
						&& document.documentElement.clientWidth != 0) {
					//alert("client width");
					scrollOffset = 0;
					viewportwidth = document.documentElement.clientWidth,
					viewportheight = document.documentElement.clientHeight
				}

				// older versions of IE

				else {
					//alert("body client width");
					scrollOffset = 0;
					viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
					viewportheight = document.getElementsByTagName('body')[0].clientHeight
				}
				

				viewportwidth = Math.max(viewportwidth - scrollOffset, 980);
				viewportheight = Math.max(viewportheight, 470);

				//viewportheight = parseInt(viewportheight - $('header').height());
                
				$("#top").height(viewportheight);
                $("#scroll-stories").css("display", "block");
                $("#top-bg-loader").fadeOut();
                


				if (clock != null)
				{
					if (timerRunning)
					{
						timerWasRunning = true;
						stopClock();
					}
					if (timerWasRunning)
					{
						if (resizeTimer) clearTimeout(resizeTimer);
					    resizeTimer = setTimeout(startClock, 1000);
					}
				}
				

				viewportar = viewportwidth / viewportheight;
				slides.each(function() {
					var _slide = $(this);
					if (options.imagear > viewportar) {
						_slide.children().height(viewportheight);
						_slide.children().width(viewportheight * options.imagear);
					} else {
						_slide.children().width(viewportwidth);
						_slide.children().height(viewportwidth / options.imagear);
					}
				})
				//centerImageY(activeSlide);

			}
			
			
			function centerImageY(slide)
			{
				var yFocusPoint = 0.5; // 0-1. 0.5 = center on middle of image
				//dont offset unless visible (offset doesnt work on hidden elements)
				if ($("#featured").is(":visible"))
					slides.eq(slide).find('img').offset({top:(-(slides.eq(slide).find('img').height() - viewportheight) * yFocusPoint)})
			}

			function centerImageX(slide)
			{
				if ($("#featured").is(":visible"))
					slides.eq(slide).find('img').offset({left:(-(slides.eq(activeSlide).find('img').width() - viewportwidth)/2)});
			}



			// ==============
			// ! TIMER
			// ==============




			//Timer Execution
			function startClock() {
				timerWasRunning = false;
				if (!options.timer) {
					return false;
					//if timer is hidden, don't need to do crazy calculations
				} else if (timer.is(':hidden')) {
					clock = setInterval(function(e) {
						shift("next");
					}, options.advanceSpeed);
					//if timer is visible and working, let's do some math
				} else {
					
					timerRunning = true;
					pause.removeClass('active');
					clock = setInterval(function(e) {
						if (freezeOrbit != true)
						{
							var degreeCSS = "rotate(" + degrees + "deg)"
							degrees += 2
						/*
							rotator.css( {
								"-webkit-transform" : degreeCSS,
								"-moz-transform" : degreeCSS,
								"-o-transform" : degreeCSS
							}); 
							
							*/
							if ($('html').hasClass('csstransforms'))
							{
								if (degrees > 180)
								{
									rotator.addClass('move');
									mask.addClass('move');
								}
								if (degrees > 360)
								{
									rotator.removeClass('move');
									mask.removeClass('move');
									degrees = 0;
									shift("next");
								}
							}
							else
							{
								rotator.addClass('move');
								mask.addClass('move');
								if (degrees > 360)
								{
									degrees = 0;
									shift("next");
								}
							} 
						}
					}, options.advanceSpeed / 180);
				} 
			}

			function stopClock() {
				if (!options.timer) {
					return false;
				} else {
					timerRunning = false;
					clearInterval(clock);
					pause.addClass('active');
				}
			}


			//Timer Setup
			if (options.timer) {
				var timerHTML = '<div class="timer controls"><span class="mask"><span class="rotator"></span></span></div><span class="pause controls"></span>'
					//  globalWrapper.append(timerHTML);
					orbitWrapper.append(timerHTML);
				var timer = $('div.timer'), timerRunning;
				if (timer.length != 0) {
					var rotator = $('div.timer span.rotator'), mask = $('div.timer span.mask'), pause = $('span.pause'), degrees = 0, clock;
					startClock();
					pause.click(function() {
						if (!timerRunning) {
							startClock();
						} else {
							stopClock();
						}
					});
					if (options.startClockOnMouseOut) {
						var outTimer;
						orbitWrapper.mouseleave(function() {
							outTimer = setTimeout(function() {
								if (!timerRunning) {
									startClock();
								}
							}, options.startClockOnMouseOutAfter)
						})
						orbitWrapper.mouseenter(function() {
							clearTimeout(outTimer);
						})
					}
				}
			}

			//Pause Timer on hover
			if (options.pauseOnHover) {
				orbitWrapper.mouseenter(function() {
					stopClock();
				});
			}
            
// ==============
// ! CAPTIONS   
// ==============
                     
            //Caption Setup
            if(options.captions) {
                var captionHTML = '<div class="orbit-caption"></div>';
                orbitWrapper.append(captionHTML);
                var caption = orbitWrapper.children('.orbit-caption');
            	setCaption();
            }
			
			//Caption Execution
            function setCaption() {
            	if(!options.captions || options.captions =="false") {
            		return false; 
            	} else {
	            	var _captionLocation = slides.eq(activeSlide).data('caption'); //get ID from rel tag on image
	            		_captionHTML = $(_captionLocation).html(); //get HTML from the matching HTML entity            		
	            	//Set HTML for the caption if it exists
	            	if(_captionHTML) {
	            		caption
		            		.attr('id',_captionLocation) // Add ID caption
		                	.html(_captionHTML); // Change HTML in Caption 
		                //Animations for Caption entrances
		             	if(options.captionAnimation == 'none') {
		             		caption.show();
		             	}
		             	if(options.captionAnimation == 'fade') {
		             		caption.fadeIn(options.captionAnimationSpeed);
		             	}
		             	if(options.captionAnimation == 'slideOpen') {
		             		caption.slideDown(options.captionAnimationSpeed);
		             	}
	            	} else {
	            		//Animations for Caption exits
	            		if(options.captionAnimation == 'none') {
		             		caption.hide();
		             	}
		             	if(options.captionAnimation == 'fade') {
		             		caption.fadeOut(options.captionAnimationSpeed);
		             	}
		             	if(options.captionAnimation == 'slideOpen') {
		             		caption.slideUp(options.captionAnimationSpeed);
		             	}
	            	}
				}
            }
            
// ==================
// ! DIRECTIONAL NAV   
// ==================

            //DirectionalNav { rightButton --> shift("next"), leftButton --> shift("prev");
            if(options.directionalNav) {
            	if(options.directionalNav == "false") { return false; }
                var directionalNavHTML = '<div class="slider-nav"><span class="right">Right</span><span class="left">Left</span></div>';
                orbitWrapper.append(directionalNavHTML);
                var leftBtn = orbitWrapper.children('div.slider-nav').children('span.left'),
                	rightBtn = orbitWrapper.children('div.slider-nav').children('span.right');
                leftBtn.click(function() { 
                    stopClock();
                    shift("prev");
                });
                rightBtn.click(function() {
                    stopClock();
                    shift("next")
                });
            }


			// ==================
			// ! BULLET NAV
			// ==================
            //Bullet Nav Setup
            if(options.bullets) {
				var bulletHTML = '<div class="orbit-bullets-wrapper controls"><span class="bullets-left"></span><ul class="orbit-bullets"></ul><span class="bullets-right"></span></div>';
            	orbitWrapper.append(bulletHTML);

				$('.controls').wrapAll('<div id="slide-info"/>');
				$('#slide-info').wrapInner('<div id="controls-wrapper">');
				$('#controls-wrapper').wrapAll('<div class="slide-controls-inner">');
				$('#scroll-stories').detach().appendTo('.slide-controls-inner');
				$('#slide-captions').detach().appendTo('#slide-info');
				
				

            	var bullets = $('ul.orbit-bullets');
            	for(i=0; i<numberSlides; i++) {
            		var liMarkup = $('<li>'+(i+1)+'</li>');
            		if(options.bulletThumbs) {
            			var	thumbName = slides.eq(i).data('thumb');
            			if(thumbName) {
            				var liMarkup = $('<li class="has-thumb">'+i+'</li>')
            				liMarkup.css({"background" : "url("+options.bulletThumbLocation+thumbName+") no-repeat"});
            			}
            		}
            		$('ul.orbit-bullets').append(liMarkup);
            		liMarkup.data('index',i);
            		liMarkup.click(function() {
            			stopClock();
            			shift($(this).data('index'));
            		});
            	}
            	setActiveBullet();
				
				//$('#slide-info').wrapInner('<div class="slide-info-winner">');
            }


			//Bullet Nav Execution
			function setActiveBullet() {
				if (!options.bullets) {
					return false;
				} else {
					centerImageY(activeSlide);

					$(timer).css("left", bullets.children('li').eq(activeSlide).position().left + 2);

					bullets.children('li').removeClass('active').eq(activeSlide).addClass('active');


					//alert("#slide-content-"+activeSlide);
					$("#slide-content-"+oldActiveSlide).fadeOut(500);
					//$("#slide-content-"+activeSlide).show(500);
					$("#slide-content-"+activeSlide).fadeIn(500);
					$('#scroll-stories').fadeIn(500);
					oldActiveSlide = activeSlide;
				}
			}

			// ====================
			// ! SHIFT ANIMATIONS
			// ====================

			//Animating the shift!
			function shift(direction) {
				//remember previous activeSlide
				var prevActiveSlide = activeSlide, slideDirection = direction;
				//exit function if bullet clicked is same as the current image
				if (prevActiveSlide == slideDirection) {
					return false;
				}
				//reset Z & Unlock
				function resetAndUnlock() {
					slides.eq(prevActiveSlide).css( {
						"z-index" : 1
					});
					unlock();
					options.afterSlideChange.call(this);
				}
				if (!locked) {
					lock();
					//deduce the proper activeImage
					if (direction == "next") {
						activeSlide++
						if (activeSlide == numberSlides) {
							activeSlide = 0;
						}
					} else if (direction == "prev") {
						activeSlide--
						if (activeSlide < 0) {
							activeSlide = numberSlides - 1;
						}
					} else {
						activeSlide = direction;
						if (prevActiveSlide < activeSlide) {
							slideDirection = "next";
						} else if (prevActiveSlide > activeSlide) {
							slideDirection = "prev"
						}
					}
					//set to correct bullet
					setActiveBullet();

					//set previous slide z-index to one below what new activeSlide will be
					slides.eq(prevActiveSlide).css( {
						"z-index" : 2
					});

					//fade
					if (options.animation == "fade") {
						slides.eq(activeSlide).css( {
							"opacity" : 0,
							"z-index" : 3
						}).animate( {
							"opacity" : 1
						}, options.animationSpeed, resetAndUnlock);
					}
					//horizontal-slide
					if (options.animation == "horizontal-slide") {
						if (slideDirection == "next") {
							slides.eq(activeSlide).css( {
								"left" : orbitWidth,
								"z-index" : 3
							}).animate( {
								"left" : 0
							}, options.animationSpeed, resetAndUnlock);
						}
						if (slideDirection == "prev") {
							slides.eq(activeSlide).css( {
								"left" : -orbitWidth,
								"z-index" : 3
							}).animate( {
								"left" : 0
							}, options.animationSpeed, resetAndUnlock);
						}
					}
					//vertical-slide
					if (options.animation == "vertical-slide") {
						if (slideDirection == "prev") {
							slides.eq(activeSlide).css( {
								"top" : orbitHeight,
								"z-index" : 3
							}).animate( {
								"top" : 0
							}, options.animationSpeed, resetAndUnlock);
						}
						if (slideDirection == "next") {
							slides.eq(activeSlide).css( {
								"top" : -orbitHeight,
								"z-index" : 3
							}).animate( {
								"top" : 0
							}, options.animationSpeed, resetAndUnlock);
						}
					}

					//horizontal-push
					if (options.animation == "horizontal-push") {
						var easeType = 'easeOutQuint'; //easeOutCubic
						if (slideDirection == "next") {
							slides.eq(activeSlide).css( {
								"left" : viewportwidth + "px", //- 15
								"z-index" : 3
							}).animate( {
								"left" : 0
							}, {duration:options.animationSpeed,easing:easeType, complete:resetAndUnlock});
							slides.eq(prevActiveSlide).animate( {
								"left" : -viewportwidth + "px" //+ 15
							}, {duration:options.animationSpeed,easing:easeType});
						}
						if (slideDirection == "prev") {
							slides.eq(activeSlide).css( {
								"left" : -viewportwidth  + "px", //+ 15
								"z-index" : 3
							}).animate( {
								"left" : 0
							}, {duration:options.animationSpeed,easing:easeType,complete:resetAndUnlock});
							slides.eq(prevActiveSlide).animate( {
								"left" : viewportwidth + "px" //- 15
							}, {duration:options.animationSpeed,easing:easeType});
						}
					}


					//push-over
					if (options.animation == "vertical-push") {
						if (slideDirection == "next") {
							slides.eq(activeSlide).css( {
								"top" : -viewportheight,
								"z-index" : 3
							}).animate( {
								"top" : 0
							}, options.animationSpeed, resetAndUnlock);
							slides.eq(prevActiveSlide).animate( {
								"top" : viewportheight
							}, options.animationSpeed);

						}
						if (slideDirection == "prev") {
							slides.eq(activeSlide).css( {
								"top" : viewportheight,
								"z-index" : 3
							}).animate( {
								"top" : 0
							}, options.animationSpeed, resetAndUnlock);
							//slides[activeSlide].getElementsByTagName("h1")[0].css.animate({"top" : 0}, options.animationSpeed + 500);
							slides.eq(prevActiveSlide).animate( {
								"top" : -viewportheight
							}, options.animationSpeed);
						}
					}

					setCaption();

				} //lock

			}//orbit function
        });//each call
    }//orbit plugin call
})(jQuery);
