/*
 * @author     Andrei Eftimie
 * @email      andrei@eftimie.com
 * @web        http://eftimie.com
 * 
 * @copyright  (c) Kairos Works
 * 
 * Custom SlideShow, specifically designed to work on Kairos Works Website.
 * Not intended for any other use.
 * 
 * Calling
 * -------
 * $('.item').kairosSlideShow({
 * });         
 * 
 */

(function($){
	$.fn.kairosSlideShow = function(options) {
        
		var opts = $.extend({}, $.fn.kairosSlideShow.defaults, options);
		
		var _speed = opts.speed;
		var _effectSpeed = opts.effectSpeed;
		var _index = opts.index;
		var $next = $(opts.next);
		var $prev = $(opts.prev);
		var $controls = $prev.add($next);
		var $slider = $(opts.slider);
		
		/*
		 * TODO: make each artists project stream separate, and changable
		 * Edit. Seems what we're now ok with this configuration
		 */
		var $itemList = $(this);
		var _length = $itemList.length;
		
		var $artists = $('#artists');
		var $projectList = $('ul a', $artists);
				
		init();
		
		/*
		 * Initialization function
		 * Shows the first Media Item (from the First Project)
		 */
		function init(){
			/*
			 * Calling the Attachment Initialisation  
			 */
			addEventsToProjectList();
			
			/*
			 * Adding Events to the Artists
			 */
			addEventsToArtists();
			
			/*
			 * Initialize Prev / Next Controls
			 */
			initPrevNext();
			
			/*
			 * Initialize the Slider
			 */
			initSlider();
			
			/*
			 * Showing the first item
			 */
			$projectList.eq(_index).click();
			
			/*
			 * Ad class to body to know we have js on
			 */
			$('body').addClass('js');
		}
		
		/*
		 * Shows an item
		 * Used whenever you need to update the visible item
		 * The project associated with the Media Item will activate automatically
		 */
		function showItem($item){
			var $oldItems = $itemList.not($item);
			
			//Only go here if the animation is finished
			if (!$oldItems.is(':animated')) {
			
				//Add new AJAX items
				if(!$item.parent().is('.ajax')){
					
					//Block UI
					$.blockUI({
						message: 'Just a moment...',
						css: {
							backgroundColor: '#fff',
							width: '120px',
							height: '30px',
							top: '50%',
							left: '50%',
							lineHeight: '30px',
							marginTop: '-40px',
							marginLeft: '-60px'
							 
						},
						overlayCSS:  { 
					        backgroundColor: '#000', 
					        opacity:         0.3 
					    }				
					});
					
					var $singleUrl = $item.siblings('.project').find('a:first').attr('href');									
					
					$.ajax({
						url: $singleUrl,
						success: function(data){
						 	data = data.substring(data.indexOf('<div class="news-single-img">')+29);
						 	data = data.substring(0,data.indexOf('</div>'));
						 	dataArray = data.split('</h1>');
						 	dataArray.pop();
	
						 	for (i=0;i<dataArray.length;i++){
						 		var item = dataArray[i].split('<h1>');
						 		item[0] = '<div class="image">' + item[0]+'</div>';
						 		item[1] = '<h1>'+item[1]+'</h1>';
						 		item = item.join(' ');
						 		dataArray[i] = '<div class="item">'+item+'</div>';
						 	}
						 	
						 	data = dataArray.splice(0,1)
						 	data = dataArray.join(' ');
						 	$item.after(data);
						 	$item.parent().addClass('ajax')
						 	$itemList = $('#projects .item');
						 	_length = $itemList.length;
						 	_index = $itemList.index($item);
						 	
						 	//Deblock UI
						 	$.unblockUI();
						},
						error: function(XMLHttpRequest, textStatus, errorThrown){
						
							if (console) console.log(XMLHttpRequest, textStatus, errorThrown);
							
							//Deblock UI
						 	$.unblockUI();
						}
					});
					
				}
				//AJAX end
				
				$oldItems.siblings('.project').hide();
				$oldItems.fadeOut(_effectSpeed, function(){	
					$item.siblings('.project').show();
				});
				$item.fadeIn(_effectSpeed);
				
				/* Center Image */
				_img = $('img', $item)[0];
				if(_img){
					_width = _img.width;
					_height = _img.height;
					if (_width >= 2*_height){
						_margin = 515/2-_height/2;
						_img.style.marginTop = _margin+'px';
					}	
				}
								
				
				/*
				 * We update the Index
				 */
				 _index = $itemList.index($item);
				
				/*
				 * We activate the artist based on the artist index and the active item index
				 */
				_IDString = $item.parent()[0].id;
				activateArtist(_IDString);				
				
				/*
				 * We also set the slider
				 */
				$slider.slider('value', $projectList.index($projectList.filter('.active')));
			}
		}
		
		/*
		 * Attaching events to the Artist Project Lists
		 */
		function addEventsToProjectList(){
		
			$.each($projectList, function(_i){
				var _href = '#'+this.href.split('#')[1];
				var $item = $(_href).find('.item:first');
				
				$(this).click(function(){
					showItem($item);
					return false;
				});
			});
		}
		
		/*
		 * Creating Events for the Artists Page
		 */
		function addEventsToArtists(){
			$('.artist', $artists)
				.mouseover(function(){
					$(this).siblings().removeClass('active');
					$(this).addClass('active');
				})
				.click(function(event){
					if ($(event.target).is('a')) {
						activateArtist(event.target.id);
					}					
				})
				.mouseout(function(){
					$(this).removeClass('active');
				});
		}
		
		/*
		 * Activate Artist
		 */		
		function activateArtist(_IDString){		
			$projectList.removeClass('active').filter('a[href$="'+_IDString+'"]').addClass('active')
				.parents('.artist').attr('id','active')
				.siblings('.artist').attr('id','');
		}
		
		/*
		 * Initialize Next / Prev Links
		 */
		function initPrevNext(){
			$prev.click(function(){
				var _newIndex = _index-1;
				if (_newIndex == -1) _newIndex = _length-1;
				if (_newIndex == _length) _newIndex = 0;
				showItem($itemList.eq(_newIndex));
				return false;
			});
			$next.click(function(){
				var _newIndex = _index+1;
				if (_newIndex == -1) _newIndex = _length-1;
				if (_newIndex == _length) _newIndex = 0;
				showItem($itemList.eq(_newIndex));
				return false;
			});
		}
		
		
		/*
		 * Init Slider
		 */
		function initSlider(){
			$slider.slider({
				animate: true,
				min: 0,
				max: $projectList.length-1,
				stop: function(event, ui){
					showItem($projectList.eq($(this).slider('value')+1).click());
				}
			});
		}
		
	    return this.each(function() {
			
                            
        });
        
	}
	
	//Defaults
	$.fn.kairosSlideShow.defaults = {
		speed: 	5000, 		//The speed between slides
		effectSpeed: 300,   //Effect Speed
		next: 	'#next', 	//The Next button
		prev: 	'#prev', 	//The prevbutton
		slider:	'#slider', 	//The prevbutton
		index:	0 			//The first element
	}
})(jQuery);
