/**
 * @version $Id: LTWSlider 0.1
 * @copyright 2010-2012 Copyright (C) Daniel Lowhorn
 * @author Daniel Lowhorn <daniel@ltwproductions.com> - http://www.ltwproductions.com
 * @license GNU/GPL v.2 http://www.gnu.org/licenses/old-licenses/gpl-2.0.html or, at your option, any later version
 */

if(jQuery) (function($){
	
	$.fn.LTWSlider = function(options,callbacks) {

		// Setup options
		var opts = $.extend($.fn.LTWSlider.defaults , options);
		

		// Handle requested methods		
		if ((typeof(options) != 'undefined') && (!(options instanceof Object))) {
					
			this.each(function(index,el) {
				
					
				// Perform requested method
				switch(options) {
					
					
				}
					
				return true;
			});
				
			return;
		} // end method request handler

		
		//
		// Global variables
		//
		var els        = new Array();
		var sliding    = 'none'; // indicate movement of filmstrip = { 'none' , 'left' , 'right' } 
		
		// --------------------------------
		//
		// Plugin Constructor
		//
		// --------------------------------
		return this.each(function(index,el) {			
		
			// Get element and ID and store for later use
			var cEL        = $(this);
			var cEL_parent = cEL.parent();
			var cEL_ID     = cEL.attr('id');
			els.push(cEL);
			
			// Hide element while working on it (make hidden, then fadeOut so I can fadeIn later)
			$(this).css('visibility','hidden');
			$(this).fadeOut();
			
			//
			// Add wrapper div and show loader 
			//
			cEL.wrap('<div class="LTWSliderGallery"></div>');
			cEL.parent()
				.prepend('<div class="contentWindow" />')
				.append('<div class="navArrow slideRightArrow"></div>')
				.append('<div class="navArrow slideLeftArrow"></div>')
				.append('<div class="filmstripWrapper" />');
				
			$('div.filmstripWrapper',cEL.parent()).append('<div class="filmstrip" />');
			$('div.contentWindow',cEL.parent()).append('<div class="ajaxPage" />');
			$('div.contentWindow',cEL.parent()).append('<div class="slider_cover" />');
			$('div.contentWindow',cEL.parent()).append('<div class="slider_cover_processing" />');
			$('div.slideLeftArrow',cEL.parent()).click(function()  { slideFilmstrip('slideLeft',cEL_ID); });
			$('div.slideRightArrow',cEL.parent()).click(function() { slideFilmstrip('slideRight',cEL_ID); });

			// Transfer ID to new wrapper div
			cEL.parent().attr('id',cEL_ID);
			cEL.removeAttr('id');
				
			// 
			// Build the filmstrip based on the images provided (pass in original set of divs)
			//		(the defined click events will handle loading the content via ajax)
			buildFilmstrip(cEL);

		}); // END CONSTRUCTOR
				
		// -------------------------------	
		//
		// Helper Functions
		//
		// -------------------------------
		
		function buildFilmstrip(cEL) {

			var filmstrip = cEL.parent().find('div.filmstrip');  
			var fsWrapper = filmstrip.parent();		
			var panels    = $('li',cEL);			

			// Iterate over each li to create the filmstrip
			$(panels).each(function(index,el) {
				
				// Get image and the content
				var img     = $('img.filmstrip',el).attr('src');
				var content = $('a.ajax',el).attr('href');
				
				$('<div class="frame" ><img src="' + img + '" alt="View Site Preview"/></div>')
					.click(loadPanel)
					.appendTo(filmstrip)
					.data('content',content)
					.css({'cursor' : 'pointer'});

				// Remove li from DOM
				$(el).remove();
				
			});

			// Remove cEL (the original set of divs)
			cEL.remove();
			
			// Set width of filmstrip, starting slideIndex (0), and loading flag
			filmstrip.css({'width' : ((panels.length + 1) * 140)+ 'px'});
			filmstrip.data('slideIndex',0);			
			filmstrip.data('panelLoading' , false);
			
			// Create the frame marker and set initial position
			var defaultFramePos = $('div.frame:first',filmstrip).position();
			$('<div class="marker"><img src="system/modules/LTWSlider/images/marker.png" /></div>')
				.appendTo(filmstrip.parent())
				.css({"left" : (defaultFramePos.left + 1) + 'px' , "top" : (defaultFramePos.top) + 'px' , 'visibility' : 'visible'});
			
			
			// If necessary (the filmstrip is wider than the wrapper) add arrows
			if (filmstrip.width() > fsWrapper.width()) {
				fsWrapper.siblings('div.navArrow').css({visibility: 'visible'});
			};
			
			//After building the filmstrip, wait for images to load
			// and then fade out the loader, show the filmstrip and load first content
			var count = 0;	
			$(window).load(function(){

				// Show finished element			
				$.each(filmstrip,function(index,value) { $(value).css('visibility','visible'); $(value).fadeIn(); });

				// Show first panel
				$('div.frame:first',filmstrip).click();
								
			});			
			
		} // end buildFilmstrip

		
		function loadPanel() {
				
		 	var me        = $(this);
		 	var content   = me.data('content'); 
		 	var filmstrip = me.parent();
		 	var fsPos     = filmstrip.position();
		 	var myPos     = me.position();
		 	var fsPos     = filmstrip.position();
		 	var contentW  = filmstrip.parent().siblings('div.contentWindow');		 
		 	var marker    = filmstrip.siblings('div.marker');

			// If a panel is already loading, do nothing.		 
			if (filmstrip.data('panelLoading') == true) return;

			// ...If reached then set to true for upcoming load
			filmstrip.data('panelLoading',true);

		 	// Execution:
		 	//		- Make sure the content parent is visible
			//		- Position the marker
		 	//		- Show Loader...when finished fading in:
		 	//			- Fade in the cover and the processing image, then...
		 	//			- Fade out currently-loaded panel content...when finished fading out:
		 	//				- Make AJAX call to load the content for this panel...when finished loading:
		 	//					- Fade in the page and fade out the cover and processing.
		 	//					- Set panelLoading to false

			// Set parent to visible
			contentW.css({'visibility' : 'visible'});
	
			// Position marker
			marker.animate({"left" : (fsPos.left + myPos.left + 1) + 'px' , "top" : (myPos.top) + 'px'},500,'swing');

			// Load content			
		 	//$('div.slider_cover , div.slider_cover_processing',contentW).fadeIn(function() {
			$('div.slider_cover',contentW).css({visibility: 'visible'}).animate({opacity: .65},500,'linear',function() {
			
				$('div.slider_cover_processing',contentW).fadeIn(function() {
					
					$('div.ajaxPage',contentW).fadeOut(function() {
					
						$('div.ajaxPage',contentW).load(content,function() {
							
							$('div.ajaxPage',contentW).fadeIn();								
							$('div.slider_cover',contentW).animate({opacity: 0},function() { $(this).css({visibility: 'hidden'}); });
							$('div.slider_cover_processing',contentW).fadeOut();
							filmstrip.data('panelLoading',false);															
															
						});// end load contentW callback
											
					});// end ajaxPage fadeOut callback
					
				});// end fadeIn slider_cover_processing callback
			
			});// end animate slider_cover callback
			

		} // end loadPanel

		function slideFilmstrip(mode,cEL) {
			
			var gallery      = $('#' + cEL);
			var filmstrip    = $('div.filmstripWrapper > div.filmstrip',gallery);
			var fsSlideIndex = filmstrip.data('slideIndex');
			var marker       = $('div.filmstripWrapper > div.marker',gallery);
			var fsPosition   = filmstrip.position();
			var numPanels    = $(gallery + 'div.filmstripWrapper > div.filmstrip > div.frame').length;
	
			switch(mode) {
				
				case 'slideLeft' : // slide filmstrip all the way to the left
												
					if (fsSlideIndex <= -1 * (numPanels - 6)) {
						$('div.slideLeftArrow', gallery).css({cursor: 'default' , visibility: 'hidden'});
						return;						
					}
												
					filmstrip.animate({left : '-=143'},750,'swing',function() {						
						var myPos = $(this).position();						
						if (fsSlideIndex <= -1 * (numPanels - 6)) {
							$('div.slideLeftArrow', gallery).css({cursor: 'default' , visibility: 'hidden'});
							return;						
						}
					});
					
					marker.animate({left : '-=143'},750,'swing');
					$('div.slideRightArrow',gallery).css({cursor: 'pointer' , visibility : 'visible'});
					filmstrip.data('slideIndex',--fsSlideIndex);

				break;
				
				case 'slideRight' : // slide filmstrip all the way to the right									
				
					if (fsSlideIndex >= 0) {
						$('div.slideRightArrow', gallery).css({cursor: 'default' , visibility: 'hidden'});
						return;						
					}
							
					filmstrip.animate({left : '+=143'},750,'swing',function() {						
						var myPos = $(this).position();

						if (fsSlideIndex >= 0) {
							$('div.slideRightArrow', gallery).css({cursor: 'default' , visibility: 'hidden'});
							return;						
						}
					});
					
					marker.animate({left : '+=143'},750,'swing');
					$('div.slideLeftArrow',gallery).css({cursor: 'pointer' , visibility : 'visible'});
					filmstrip.data('slideIndex',++fsSlideIndex);
				
				break;

			} // end switch mode

		} // end slideFilmstrip


		// Simple debug
		function debug(obj) {
			if (window.console && window.console.log)
	      		window.console.log(obj);				
		};

	};

	
	// LTWSlider Defaults
	$.fn.LTWSlider.defaults = {
		
	};	
	
})(jQuery);			

