/*!
	tinyRotary.js: jQuery Content Carousel plugin - v0.7 - 10/22/2011
	http://frankiejr.com/tiny/rotary
	Copyright (c) 2011 Frankie Benevides Jr. "frankiejr"
	Made possible with gracious help from ViridianSpark.com
	Dual licensed under the MIT and GPL licenses
	Modified for use in LIU.edu
*/
(function($){
	$.rotary = {
		opt: {
			multiplier : 1,              // The multiplier: How many tiles are visible at once
			speed      : 0,            // Length of tile change animation (in milliseconds)
			interval   : 12000,              // Autoplay interval (in milliseconds / 0 for no autoplay)
			rtl        : true,           // Right to left auto animation (false for "left to right")
			tray       : 'ul',           // Tray selector
			tile       : 'li',           // Tile selector
			win        : 'window',       // Class of the viewable "window" area
			prev       : 'prev',         // Class of the "previous" button (leave empty for no previous button)
			next       : 'next',         // Class of the "next" button (leave empty for no next button)
			prevTxt    : '&laquo;',      // Previous button text
			nextTxt    : '&raquo;',      // Next button text
			btnBox     : 'navContainer', // Class of previous/next button container
			nav        : 'LIUsliderNav', // Class of List Navigation (leave empty for no list navigation)
			active     : 'active',       // Active class for current nav item
			autoplay   : true            // Option to prevent autoplay after any feature interaction
		}
	};
	$.fn.tinyRotary = function(opt) {
		// Get the options
		var opt = $.extend({}, $.rotary.opt, opt);
		this.each(function() {
			// Create a new rotary, apply the options
			$(this).data(new Rotary($(this), opt));
		});
	};

	function Rotary(el, opt){

		// Set up basic variables
		var obj = $(el);
		var tray = obj.find(opt.tray);
		var tiles = tray.children();
		var total = tiles.length;
		// Set tile width based on the first tile (used for calculation)
		var tileW = $(tiles[0]).outerWidth(true);
		// Buttons & container
		var btnBox;
		var prev;
		var next;
		var nav;

		// Create window & set width of window & tray
		tray.wrap('<div class="'+opt.win+'" style="width: '+(opt.multiplier*tileW)+'px;" />');
		tray.css('width', (total*tileW)*2);

		// Calculate the multiplier
		if ( total > opt.multiplier ) {
			var m = opt.multiplier;
			// if there is at least one button, create a button container
			if( opt.prev.length > 0 || opt.next.length > 0 || opt.nav.length > 0 ) {
				btnBox = obj.append('<div class="'+opt.btnBox+'" />').find('.'+opt.btnBox);
			}
			// If list navigation class exists
			if ( opt.nav.length > 0 ) {
				buildNav();
			};
			// If either the prev or next button class exists
			if( opt.prev.length > 0 || opt.next.length > 0 ) {
				buildButtons();
			};
			// If autoplay is true
			if ( opt.interval > 0 ) {
				autoPlay();
			};
		};
		if ( total < opt.multiplier*2 && total > opt.multiplier ) {
			// If the amount of tiles is less than 2x multiplier, but more than 1x multiplier
			m = 1;
		} else if ( total <= opt.multiplier ) {
			// If the number of tiles is equal to or less than the multiplier
			m = 0;
		};

		// Previous & Next buttons
		function buildButtons() {
			// Add previous button & bind click
			if( opt.prev.length > 0 ) {
				prev = btnBox.append('<a href="#" class="'+opt.prev+'">'+opt.prevTxt+'</a>').find('.'+opt.prev);
				prev.bind('click.prev', function(event) {
					event.preventDefault();
					animateTray('prev', m);
					stopAutoPlay();
				});
			};
			// Add next button & bind click
			if( opt.next.length > 0 ) {
				next = btnBox.prepend('<a href="#" class="'+opt.next+'">'+opt.nextTxt+'</a>').find('.'+opt.next);
				next.bind('click.next', function(event) {
					event.preventDefault();
					animateTray('next', m);
					stopAutoPlay();
				});
			};
		};

		// List navigation
		function buildNav() {
			// Create list, place between prev/nav buttons
			nav = btnBox.append('<ul class="'+opt.nav+'" />').find('.'+opt.nav);
			// Loop through tiles and create nav buttons
			for (var t=0; t < total; t++) {
				// Add data-num to tile for reference later
				$(tiles[t]).attr('data-num', t);
				// Create the button
				var button = nav.append('<li data-num="'+t+'"><a href="#">'+t+'</a></li>').find('li:last');
				// Bind each button to corresponding tile
				button.bind('click', function(event) {
					event.preventDefault();
					stopAutoPlay();
					// Only animate if tray is not moving
					if( tray.is(':animated') != true ) {
						// Find the corresponding target tile by getting the data-num
						var target = parseInt($(this).attr('data-num'));
						// Find where indexed tile is in the current tray order
						var currentOrder = tray.children();
						var loc;
						for (loc=0; loc < currentOrder.length; loc++) {
							if ( $(currentOrder[loc]).attr('data-num') == target ) {
								break;
							};
						};
						// Find which tile is currently at zero
						var current = parseInt($(currentOrder[0]).attr('data-num'));
						// Calculate difference between current and target, which reveals animation count							
						var diff = target-current;
						if( diff > 0 ) {
							// Target is ahead of current
							animateTray('next', diff);
						} else if( diff < 0 ) {
							// Target is behind current
							diff = Math.abs(diff);
							animateTray('prev', diff);
						};
					};
				});
			};
			// If list navigation exists, set active states
			if ( opt.nav.length > 0 ) {
				setActive(0);
			};
		};

		// Set & keep track of nav active state
		function setActive(num) {
			nav.children().removeClass(opt.active).find('a').removeAttr('style');
			// Find the new active button & tile
			var activeBtn = nav.find('li:eq('+num+')');
			var activeTile = tray.find('li:first');
			// Add the active class to the new active button
			activeBtn.addClass(opt.active);
			// Per-school button styles
			var hex = activeTile.find('.hex').attr('style');
			activeBtn.find('a').attr('style', hex);




		};

		// Tray animation
		function animateTray(dir, count) {
			// Only animate if tray is not moving
			if( tray.is(':animated') != true ) {
				var loopers;
				var distance = (count*tileW);
				if( dir === 'prev' ) {
					// If clicking "previous"
					var dir = '+';
					// Prepare tiles for cloning & animation
					loopers = tray.find(opt.tile+':gt('+(total-count-1)+')');
					loopers.clone().prependTo(tray);
					// Set tray position to prepare for animation back to zero
					tray.css('left', -distance);
				} else if( dir === 'next' ) {
					// If clicking "next"
					var dir = '-';
					// Prepare tiles for cloning & animation
					loopers = tray.find(opt.tile+':lt('+count+')');
					loopers.clone().appendTo(tray);
				};
				// Animate
				tray.animate({
					left: dir+'='+distance
				}, opt.speed, function() {
					// After animation, remove clone sources & reset tray to zero
					loopers.remove();
					tray.css('left',0);
					cities();
					// If list navigation exists, set active states
					if ( opt.nav.length > 0 ) {
						setActive( parseInt(tray.find(':first-child').attr('data-num')) );
					};
				});
			};
		};

		// Autoplay
		function autoPlay() {
			// If the interval is set and there are enough tiles to animate
			if( opt.interval > 0 && m != 0 ){
				var timer;
				function slideTimer() {
					// Set the autoplay interval & direction
					if( opt.autoplay === true ) {
						timer = setInterval(function() {
							if( opt.rtl === true ) {
								animateTray('next', m);
							} else {
								animateTray('prev', m);
							};
						}, opt.interval);
					};
				};
				slideTimer();
				// Stop autoplay on mouseover, restart on mouseout
				obj.hover(
					function() {
						clearInterval(timer);
					},
					function() {
						slideTimer();
					}
				);
			};
		};

		function stopAutoPlay() {
			opt.autoplay = false;
		};

		obj.find('a').bind('click', function() {
			stopAutoPlay();
		});

/////// LIU specific functions
		function cities(){
			var first = tray.children(":first");$("#cities a").removeClass("active");
			if(first.hasClass("cityRockland")==true)$("#cities .cityRockland").addClass("active");
			if(first.hasClass("cityWestchester")==true)$("#cities .cityWestchester").addClass("active");
			if(first.hasClass("cityBrooklyn")==true)$("#cities .cityBrooklyn").addClass("active");
			if(first.hasClass("cityRockland")==true)$("#cities .cityRockland").addClass("active");
			if(first.hasClass("cityPharmacy")==true)$("#cities .cityPharmacy").addClass("active");
			if(first.hasClass("cityGlobal")==true)$("#cities .cityGlobal").addClass("active");
			if(first.hasClass("cityCW")==true)$("#cities .cityCW").addClass("active");
			if(first.hasClass("cityBrentwood")==true)$("#cities .cityBrentwood").addClass("active");
			if(first.hasClass("cityRiverhead")==true)$("#cities .cityRiverhead").addClass("active")
		};
		function LIUactive() {
			var hex;
			for (var b=0; b < tiles.length; b++) {
				var hex = $(tiles[b]).find('.hex').css('background-color');
				$(tiles[b]).find('h2, h3, h4, h5, h6').attr('style', 'color:'+hex)
			};
			// LIU page specific button color styles
			var hex = obj.find(".hex_top").attr("style");
			var newStyle='<style type="text/css" media="screen">.LIUslider .active a{'+hex+"}</style>";
			$("head").append(newStyle);
		};
		LIUactive();

	};
})(jQuery);
