/*
	jQuery - siteFeature2 Plugin
	@copyright Michael Kafka - http://www.makfak.com
	@version 1.2
*/
(function($){

	$.fn.siteFeature2 = function(options) {
		var opts = $.extend({}, $.fn.siteFeature2.defaults, options);

		return this.each(function(i) {
			obj = $(this);
			var set = {};
				set.btns = '';
				set.content = '';
				set.btnsRev = [];
				set.which = i;
				set.autoPlay = [];
				if(opts.autoPlay){
					set.autoPlay['which'+set.which] = true;
				}
				
				// character encoding bulletproofing
				if($.browser.msie){
					set.pause = '&#x2225;';
					set.play = '&#x25b6;';
				} else {
					set.pause = '&#x2161;';
					set.play = '&#x25b6;';
				}
				
				if(opts.pauseChar != ''){
					set.pause = opts.pauseChar;
				}
		
				if(opts.playChar != ''){
					set.play = opts.playChar;
				}
		
			// contains all DOM traversal and manipulation
			createFeature(opts, set);

			// binds all associated events
			eventFeature(opts, set);
		}); 
    }; // end $.fn.siteFeature2


	$.fn.siteFeature2.defaults = {
		outputElementId: 'siteFeature2',		// this is the ID given to the container div generated by siteFeature2
		contentIdPrefix: 'SFcontent',			// creates the naming convention for the Content (ie: SFcontentContainer) 
		btnIdPrefix: 'SFbtn',					// creates the naming convention for the Buttons (ie: SFbtnContainer)
		autoPlay: true,							// determines if the tabs cycle automatically
		autoPlayInterval: 5000,					// sets the autoPlay interval
		menuText: '>',							// sets the text of the 'nav' launch button
		pauseChar: '',							// ('string' or '&amp;') : allows users to set the Pause button text. ASCII and Unicode ok.
		playChar: '',							// ('string' or '&amp;') : allows users to set the Play button text.  ASCII and Unicode ok. 
		pauseBtn: true,							// (true / false) : determines whether or not to show the play/pause button
		pauseBtnLocation: 'left',				// positions the play/pause button relative to the rest of the nav
		pauseOnHover: true,						// pause the autoPlay when hovering on siteFeature2
		menuExist: true,						// determines whether or not to display the menu
		menuStatus: 'closed',					// determines whether or not the menu animates: 'open' / 'closed'
		menuLocation: 'right',					// determines the direction the 'nav' opens: 'right' / 'left'
		menuDirection: 'vertical',				// determines the direction the 'nav' opens: 'vertical' / 'horizontal'
		showHideMenu: 'show',					// ('show' / 'hide') : determines whether the menu is visible at all times or on hover
		showHideMenuSpeed: 250,					// (in milliseconds) : sets the menu fade in/out speed
		activeWindowIsLink: true,				// determines if the current Image and Text are links
		imgAnimationDirection: 'left',			// sets animation direction: 'left' / 'right' / 'up' / 'down' / 'fade'
		imgAnimationDuration: 500,				// sets image animation durations
		imgAnimationEasing: 'linear',			// ('string') : hooks for jQuery Easing Plugin
		txtAnimationPause: 500,					// sets delay between when the image begins to animate and when the text begins to animate
		txtAnimationDistance: 25,				// sets the offset of text as it animates in (matches the images' direction)
		txtAnimationDuration: 350,				// sets text animation durations
		txtAnimationEasing: 'linear',			// ('string') : hooks for jQuery Easing Plugin
		endCreateFunction: null					// creates a userdefined Callback (with access to all plugin Options) that fires after everything has been written to the DOM but before events are bound.
	}; // end $.fn.siteFeature2.defaults
	
	// simple utility function to replicate jQuery's InnerHTML function but to include the containing Element
    function outerHTML(element) {
		return $('<div>').append( element.eq(0).clone() ).html();
	};

	// This function contains all of the DOM traversal and manipulation.  All part of Progressive Enhancement and Unobtrusive Javascript.
	function createFeature(opts, set){
		
		// Injecting into the DOM wastes time. Write to memory (create a string) and inject once when finished
		var siteFeature2;
		var content = "<div id='" + opts.contentIdPrefix + "Container' class='" + opts.menuLocation + "'>";
		var btns = "<div id='" + opts.btnIdPrefix + "Container' class='" + opts.menuLocation + "'>";
		
		// Loop through each Item and create all necessary HTML
		obj.children().each(function(i){
			
			current = $(this);
			var href = current.find('a:last').attr('href');
			cloned = current.clone()
				.attr({id: opts.btnIdPrefix + i})
				.css({'background-image':'url(' + current.find('img').attr('src') + ')'})
				.find('img').remove().end()
				.wrapInner('<div>')
				.children().prepend('<span></span>')
				.children('a').remove().end().end()
			;

			content += outerHTML(cloned);
			btns += '<a href="#' + opts.btnIdPrefix + i + '" id="' + opts.btnIdPrefix + i + '" rel="' + href + '">' + (i + 1) + '</a>';
			
		}); // end Each

		content += '</div>';
		if(opts.pauseBtn){
			if(opts.autoPlay){
				btns += '<a href="#" class="pause" id="SF2trigger">' + set.pause + '</a></div>';
			} else {
				btns += '<a href="#" class="play" id="SF2trigger">' + set.play + '</a></div>';
			}
		} else {
			btns += '<a href="#" id="SF2trigger">' + opts.menuText + '</a></div>';
		}
		siteFeature2 = (content + btns);
		
		// Clear the current HTML and inject the siteFeature2 HTML
		obj.empty().attr({'id':opts.outputElementId,'class':opts.tabsLocation}).append(siteFeature2);
		obj.addClass('SF2-' + set.which);
		
		// Callback for DOM manipulation before event binding
		if($.isFunction(opts.endCreateFunction)){
			opts.endCreateFunction.apply(this, [opts]);
		}

		// stores jQuery selections we'll be using later (speeds things up)
		set.sf2 = obj;
		set.contentCon = $('#' + opts.contentIdPrefix + 'Container',obj);
		set.content = set.contentCon.children();
		set.contentWidth = set.content.parent().width();
		set.contentHeight = set.content.parent().height();
		set.btnsCon = $('#' + opts.btnIdPrefix + 'Container',obj);
		set.btns = $('#' + opts.btnIdPrefix + 'Container',obj).children('a:not(a#SF2trigger)').wrapAll('<div></div>').parent();
		set.btns.children().each(function(){
			set.btnsRev.push($(this)[0]);
		});
		set.btnsRev = set.btnsRev.reverse();
		set.btnsPlay = set.btnsCon.children('a#SF2trigger');
		set.btnsTrigger = set.btnsCon.children('a#SF2trigger');

		// style the Images
		if(opts.menuDirection == 'horizontal'){
			set.btns.children().css({'float':'left'});
		}

	} // end createFeature()


	
	// This function binds all associated events
	function eventFeature(opts, set){
		
		// the following is for the 'nav'
		// these are for the staggered fade-in animation
		var timer = 0; 
		var time = 25;
		var multiplier = 1;

		set.btnsOpen = set.btns.height();
		set.btnHeight = set.btns.children('a:first').height();
		set.btnWidth = set.btns.children('a:first').width();
		
		if(opts.menuStatus == 'closed'){
			
			if(opts.menuDirection == 'horizontal'){
				
				if(opts.menuLocation == 'left'){
					set.btns.parent().children('a').clone().insertBefore(set.btns).css({'float':'left'}).end().end().remove();
				} else {
					set.btns.parent().children('a').css({'float':'right'});
				}
				
				set.btns
					.css({'float':'left','width':'auto'})
					.children().css({'display':'none'})
					.parent().parent()
					.hover(function(i){
						set.btns.css({'width':'auto'});
						set.btns.parent().addClass('open');
						$.each(set.btnsRev, function(){
								$(this).css({'display':'block','height':'0','width':'0'})
									.stop().animate({'letter-spacing':'normal'},timer,function(){
										$(this).animate({'height':set.btnHeight,'width':set.btnWidth},150);								 
									})
								;
								timer = (timer * multiplier + time);
							})
						;
					},function(){
						timer = 0;
						set.btns.children().each(function(){
							$(this).stop().animate({'letter-spacing':'normal'},timer,function(){
								$(this).css({'display':'none'});								 
							});
							timer = (timer * multiplier + time);
						}).parent().parent().removeClass('open');
					})
				;
			} else {
	
				set.btns
					.css({'height':'0'})
					.parent()
					.hover(function(i){
						set.btns.css({'height':'auto'});
						set.btns.parent().addClass('open');
						$.each(set.btnsRev, function(){
								$(this).css({'display':'block','height':'0','width':'0'})
									.stop().animate({'letter-spacing':'normal'},timer,function(){
										$(this).animate({'height':set.btnHeight,'width':set.btnWidth},150);								 
									})
								;
								timer = (timer * multiplier + time);
							})
						;
					},function(){
						timer = 0;
						set.btns.animate({'height':'0'},250).parent().removeClass('open');
					})
				;
			} // end 'nav' hover events
			
		} else {
			
			if(opts.pauseBtnLocation == 'left' && opts.menuDirection == 'horizontal'){
				set.btns.css({'float':'right'}).parent().children('a').css({'float':'right'});
			} else if(opts.menuDirection == 'horizontal') {
				set.btns.css({'float':'left'}).parent().children('a').css({'float':'left'});
			}
			
		}


		// 'nav' item click event
		// these set preferences based on animation direction
		if(opts.imgAnimationDirection == 'left'){
			set.imgAnimDis = set.contentWidth;
			set.txtAnimDis = opts.txtAnimationDistance;
		} else if(opts.imgAnimationDirection == 'right'){
			set.imgAnimDis = set.contentWidth * -1;
			set.txtAnimDis = opts.txtAnimationDistance * -1;
		} else if(opts.imgAnimationDirection == 'up'){
			set.imgAnimDis = set.contentHeight;
			set.txtAnimDis = opts.txtAnimationDistance;
		} else if(opts.imgAnimationDirection == 'down'){
			set.imgAnimDis = set.contentWidth * -1;
			set.txtAnimDis = opts.txtAnimationDistance * -1;
		}
		
		set.content.css({'z-index':'0'});
		
		// 'nav' click event
		set.btns.children().click(function(){
			
			var hash = this.hash;
			
			if($(this).hasClass('current') || set.content.filter(hash).hasClass('current')){
				return false;	
			}

			if(opts.imgAnimationDirection == 'left' || opts.imgAnimationDirection == 'right'){
				set.btns.children().filter('.current').removeClass('current').end().filter(hash).addClass('current');
				set.content.filter('.current').css({'z-index':'50'})
					.end().filter(hash)
					.css({'z-index':'100','left':set.imgAnimDis})
					.animate({'left':'0'},opts.imgAnimationDuration,opts.imgAnimationEasing, function(){
							set.content.filter('.current').removeClass('current').css({'z-index':'0'})
								.end().filter(hash).addClass('current')
							;
						})
					.children().children('p').css({'opacity':'0','left':set.txtAnimDis})
					.animate({'letter-spacing':'normal'},opts.txtAnimationPause, function(){
						$(this).animate({'opacity':'1','left':'0'},opts.txtAnimationDuration,opts.txtAnimationEasing);
					})
				;
				
			}
			
			if(opts.imgAnimationDirection == 'up' || opts.imgAnimationDirection == 'down'){
				set.btns.children().filter('.current').removeClass('current').end().filter(hash).addClass('current');
				set.content.filter('.current').css({'z-index':'50'})
					.end().filter(hash)
					.css({'z-index':'100','top':set.imgAnimDis})
					.animate({'top':'0'},opts.imgAnimationDuration,opts.imgAnimationEasing, function(){
							set.content.filter('.current').removeClass('current').css({'z-index':'0'})
								.end().filter(hash).addClass('current')
							;
						})
					.children().children('p').css({'opacity':'0','top':set.txtAnimDis})
					.animate({'letter-spacing':'normal'},opts.txtAnimationPause, function(){
						$(this).animate({'opacity':'1','top':'0'},opts.txtAnimationDuration,opts.txtAnimationEasing);
					})
				;
			}
			
			if(opts.imgAnimationDirection == 'fade'){
				set.btns.children().filter('.current').removeClass('current').end().filter(hash).addClass('current');
				set.content.filter('.current').css({'z-index':'50'})
					.end().filter(hash)
					.css({'z-index':'100','opacity':'0'})
					.animate({'opacity':'1'},opts.imgAnimationDuration,opts.imgAnimationEasing, function(){
							set.content.filter('.current').removeClass('current').css({'z-index':'0'})
								.end().filter(hash).addClass('current')
							;
						})
					.children().children('p').css({'opacity':'0'})
					.animate({'letter-spacing':'normal'},opts.txtAnimationPause, function(){
						$(this).animate({'opacity':'1'},opts.txtAnimationDuration,opts.txtAnimationEasing);
					})
				;
			}
			
			// reset timer
			if(!opts.pauseOnHover && set.autoPlay['which'+set.which]){
				clearInterval(siteFeature2AutoPlayInterval['which'+set.which]);
				siteFeature2AutoPlayInterval['which'+set.which] = setInterval("siteFeature2AutoPlayer(" + set.which + ")",opts.autoPlayInterval);
			}

			return false;
		});
		
		set.content.css({'z-index':'0'}).filter(':first').css({'z-index':'100'}).addClass('current');
		set.btns.children().filter(':first').addClass('current');
		
		// bind nav fade in/out on #siteFeature2 hover
		if(opts.showHideMenu == 'hide'){
			// hide the nav
			$('#' + opts.btnIdPrefix + 'Container').hide();
			
			// show the nav when hovered over the #siteFeature2 DIV
			$('#' + opts.outputElementId).hover(function(){
				$('#' + opts.btnIdPrefix + 'Container').stop().css({'opacity':'0','display':'block'}).animate({'opacity':'1'},opts.showHideMenuSpeed);
			},function(){
				$('#' + opts.btnIdPrefix + 'Container').stop().animate({'opacity':'0'},opts.showHideMenuSpeed);
			});
		}

		if(!opts.menuExist){
			$('#' + opts.btnIdPrefix + 'Container').css({'display':'none'});
			$('#' + opts.contentIdPrefix + 'Container').addClass('nomenu');
		}

		// binds a click to the ImgBg that calls the original link
		if(opts.activeWindowIsLink){
			$('#' + opts.contentIdPrefix + 'Container').css({'cursor':'pointer'}).click(function(e){
				if(e.target.tagName == 'A'){
					return;
				} else {
					window.location = set.btns.children().filter('.current').attr('rel');
					return false;
				}
			});
		}

		// binds the AutoPlay
		if(set.autoPlay['which'+set.which]){
			siteFeature2AutoPlayInterval['which'+set.which] = setInterval("siteFeature2AutoPlayer(" + set.which + ")",opts.autoPlayInterval);
		}
		
		// binds the play/pause behavior
		if(opts.pauseBtn){
			set.btnsPlay.click(function(){
				if(set.autoPlay['which'+set.which]){
					set.btnsPlay.removeClass().addClass('play').html(set.play);
					set.autoPlay['which'+set.which] = false;
					clearInterval(siteFeature2AutoPlayInterval['which'+set.which]);
				} else {
					set.btnsPlay.removeClass().addClass('pause').html(set.pause);
					set.autoPlay['which'+set.which] = true;
					if(!opts.pauseOnHover){
						siteFeature2AutoPlayInterval['which'+set.which] = setInterval("siteFeature2AutoPlayer(" + set.which + ")",opts.autoPlayInterval);
					}
				}
				return false;
			});
		} else {
			set.btnsTrigger.click(function(){
				return false;												
			});
		}

		// binds pause on hover
		if(opts.pauseOnHover){
			set.sf2.hover(function(){
				if(set.autoPlay['which'+set.which]){
					clearInterval(siteFeature2AutoPlayInterval['which'+set.which]);
				}
			},function(){
				if(set.autoPlay['which'+set.which]){
					siteFeature2AutoPlayInterval['which'+set.which] = setInterval("siteFeature2AutoPlayer(" + set.which + ")",opts.autoPlayInterval);
				}
			});
		}
		
	} // end eventFeature()
	

})(jQuery);

// this is the AutoPlay function
var siteFeature2AutoPlayInterval = [];
function siteFeature2AutoPlayer(id){
	var btns = $('.SF2-' + id).find('#' + $.fn.siteFeature2.defaults.btnIdPrefix + 'Container').children('div').children('a');
	if( (btns.length - 1) == btns.index(btns.filter('.current'))){
		btns.filter(':first').click();
	} else {
		btns.filter('.current').next().click();
	}
}

