/** 
 * @author Ample, Taylor C. MacDonald <taylor at helloample dot com>
 */
var IPSWITCH = (function () { 
	var my = {}; 
	var $slider;
	var $sliderPanels;
	var $bullets; 
	var currPanel = 0;
	var previousPanel = 0;
	var in_transit = false; 
	var interval = 0; 
	var running = false; 
	var ie = false; 
	var ff = false;

	/**
	 * constructor: setup elements & actions
	 */
	my.init = function() {
		$slider = $('#features');
		$sliderPanels = $slider.children('.feature');
		IPSWITCH.cleanup(); 
		IPSWITCH.reposition(true); 
		IPSWITCH.bullets();
		IPSWITCH.activation();
		IPSWITCH.events();
		IPSWITCH.start();
	}; 

	/**
	 * get/set whether the slider is in motion
	 * @param t Boolean
	 * @return Boolean
	 */
	my.in_transit = function(t) {
		if(t!=undefined) in_transit = t; 
		return in_transit; 
	}; 

	/**
	 * browser specific cleanup for IE<8 && FF<3.5
	 */
	my.cleanup = function() {
		ie = $.browser.msie && parseInt($.browser.version,10)<9 ? true : false; 
		ff = $.browser.mozilla && $.browser.version<'1.9.1' ? true : false; 

		if(ie) {
			$.each($('#features img[data-iefix]'),function(i,el){
				$(el).attr('src',$(el).attr('src').replace('.png','-ie.png')); 
			}); 
		}

		if(ie||ff) {
			$('#topnav').css({
				'z-index': 1000000
			}); 
			$('.feature').each(function(){
				var src = $(this).css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
				$(this).css('background-image','none'); 
				$(this).prepend('<div class="ie-fix"><img src="'+src+'"></div>')
			}); 
		}
	}; 

	/**
	 * reset inital positions 
	 * @param init Boolean - initial execution?
	 */
	my.reposition = function(init) {
		$('.feature *[data-role=subject], .feature *[data-role=call-to-action]').each(function(){
			IPSWITCH.position(this); 
			if(init) { $(this).fadeIn(); }
		}); 
	}; 

	/**
	 * set inital positions for absolutely positioned els based on width of user's browser
	 * @param el Object
	 */
	my.position = function(el) {
		var x = $(el).attr('data-position-x') ? $(el).attr('data-position-x') : 0; 
				x = parseInt(x) + this.offset(); 
		var y = $(el).attr('data-position-y') ? $(el).attr('data-position-y') : 0;;	 
		$(el).css({
			position: 'absolute',
			top: parseInt(y)+'px',
			left: parseInt(x)+'px'
		});
	};

	/**
	 * get distance from left edge of window to left edge of container element
	 * @return integer
	 */
	my.offset = function() {
		var w = $(window).width(); 
		var d = Math.round((w-950)/2); 
		return d; 
	}; 

	/** 
	 * initiate slide sequence- start by sliding out active elements 
	 * @param prevPanel Integer
	 * @param newPanel Integer
	 * @param dir String - 'left', 'right'
	 */
	my.slide = function(prevPanel,newPanel,dir) {
		if(this.in_transit()) return; 
		var cta = $( $sliderPanels[prevPanel] ).find('*[data-role=call-to-action]'); 
		var subject = $( $sliderPanels[prevPanel] ).find('*[data-role=subject]'); 
		var exit_left = subject.attr('data-exit-left'); 
		var margin_left = parseInt(exit_left); 
		in_transit = true; 
		cta.fadeOut(); 
		if(subject.length) {
			if(!ie) {
			var opts = {opacity: 0, easing:'easeOutQuart', 'margin-left': margin_left}; 
				subject.animate(opts,800,null,function(){
					IPSWITCH.slidePanel(newPanel,dir); 
				}); 
			} else {
				setTimeout(function(){
					IPSWITCH.slidePanel(newPanel,dir); 
				},400); 
			}
		} else {
			cta.fadeOut(800,function(){
				IPSWITCH.slidePanel(newPanel,dir); 
			}); 
		}
	}

	/** 
	 * second part of slide sequence- slide in the next set of elements
	 * @param newPanel Integer
	 * @param dir String - 'left', 'right'
	 */
	my.slidePanel = function(newPanel,direction) {
		// define the offset of the slider obj, vis a vis the document
		var offsetLeft = $slider.offset().left;
		// offset required to hide the content off to the left / right
		var hideLeft = -1 * ( offsetLeft + $slider.width() );
		var hideRight = $(window).width() - offsetLeft;
		// change the current / next positions based on the direction of the animation
		if ( direction == 'left' ) {
			currPos = hideLeft;
			nextPos = hideRight;
		} else {
			currPos = hideRight;
			nextPos = hideLeft;
		}
		
		var speed = 800; 
		// slide out the current panel, then remove the active class
		$slider.children('.feature.active').animate({
			left: currPos,
			easing: 'easeOutInBack'
		}, speed, function() {
			$(this).removeClass('active');
		});

		// slide in the next panel after adding the active class
		$( $sliderPanels[newPanel] ).css('left',nextPos).addClass('active').animate({left: 0, easing: 'easeOutInBack'}, speed, null, function(){
			IPSWITCH.activate(newPanel); 
			IPSWITCH.reset(); 
			IPSWITCH.in_transit(false); 
		});
	}

	/**
	 * restore elements to their initial positions
	 */
	my.reset = function() {
		var cta = $( $sliderPanels[prevPanel] ).find('*[data-role=call-to-action]'); 
		var subject = $( $sliderPanels[prevPanel] ).find('*[data-role=subject]'); 
		if(subject.length) {
			var x = subject.attr('data-position-x') ? subject.attr('data-position-x') : 0; 
					x = parseInt(x)+this.offset(); 
			var y = subject.attr('data-position-y') ? subject.attr('data-position-y') : 0; 
			subject.css({left:x,top:y,opacity:1,'margin-left':0,'filter':''}); 
		}
		cta.show(); 
	}; 

	/** 
	 * slide in specific set of elements
	 * @param i Integer
	 */
	my.goto = function(i) {
		if(this.in_transit() || i==currPanel) return; 
		prevPanel = currPanel; 
		currPanel = i;
		if ( currPanel >= $sliderPanels.length ) currPanel = 0;
		this.slide(prevPanel,currPanel,'left')
	}; 

  my.activation = function() {
    if($slider.find('active').length == 0) {
      $($sliderPanels.first()).addClass('active'); 
    }
  }

	/** 
	 * activate indicator bullets based on current set of elements
	 * @param i Integer
	 */
	my.activate = function(i) {
		var els = $bullets.find('a'); 
				els.removeClass('on'); 
		$bullets.find('a[data-iteration='+i+']').addClass('on'); 
	}

	/** 
	 * slide to next sequential set of elements
	 */
	my.next = function() {
		if(this.in_transit() || $sliderPanels.length < 2) return; 
		prevPanel = currPanel; 
		currPanel++;
		if ( currPanel >= $sliderPanels.length ) currPanel = 0;
		IPSWITCH.slide(prevPanel, currPanel, 'left'); 
	};

	/** 
	 * slide to previous sequential set of elements
	 */
	my.prev = function() {
		if(this.in_transit() || $sliderPanels.length < 2) return; 

		prevPanel = currPanel; 
		currPanel--;
		if ( currPanel < 0 ) currPanel = $sliderPanels.length - 1;
		IPSWITCH.slide(prevPanel, currPanel, 'right'); 
	}; 

	/** 
	 * add events to left & right keypress
	 */
	my.keys = function(e) {
		this.stop(); 
		switch(e.keyCode) { 
			case 37:
				this.prev(); 
				break; 
			case 39:
				this.next(); 
				break; 
		}
	}; 

	/** 
	 * create bullets el unless there's only one slide
	 */
	my.bullets = function() {
		if($sliderPanels.length < 2) return; 
		$bullets = $('<div id="features-bullets"></div>').prependTo($slider); 
		$('.feature').each(function(i){
			var a = $('<a href="#" data-iteration="'+i+'" class="bullet"></a>'); 
					a.click(function(){
						IPSWITCH.stop(); 
						IPSWITCH.goto($(this).attr('data-iteration')); 
					}); 
			$bullets.prepend(a); 
		});
		$('.bullet[data-iteration=0]').addClass('on'); 
	}

	/** 
	 * attach event handlers 
	 */
	my.events = function() {
		$(window).resize(function() {
			IPSWITCH.reposition(false);
		}); 
	}

	/** 
	 * start the auto rotation
	 */
	my.start = function() {
		if($sliderPanels.length < 2) return; 
		interval = setInterval(function(){
			my.next(); 
		}, 6500);
	}; 

	/** 
	 * stop the auto rotation
	 */
	my.stop = function() {
		if(interval) { clearInterval(interval); }
		running = false;		
	}; 

	return my; 
}());
