/* 
	Arlind Nushi gallery plugin (especially made for Kolor theme)
	Created by: Arlind Nushi 
	Version: 0.1
	Date: Aug 21, 2012
*/

(function($)
{
	"use strict";
	
	var settings = {
		slideShow: $(null),
		itemSelector: '> li > a, > a',
		duration: 1,
		activeImgOpacity: 0.25,
		controls: {
			nextPrev: true,
			keyBoardNav: true,
			popup: true
		},
		hashID: 'image-%',
		detectHashChange: false // Requires HASH CHANGE PLUGIN
	};
	
	// Class vars
	var vars = {
		body: $("body"),
		win: $(window),
		
		// DOM
		container: $(null),
		images: $(null),
		currentImage: $(null),
		popup: $(null),
		
		// for HashChange Plugin (checker)
		hashChangeDisable: false
	};
	
	var methods = {
		
		// Init Gallery
		init: function(opts, arg1, arg2)
		{
			// Init
			var s = settings, v = vars;
			
			v.container = $(this);
			
			// Check if is a function call
			if(v.container.data('angallery-installed'))
			{
				var instance = v.container.data('angallery-instance');
				
				if(typeof opts == 'string')
				{					
					var args = new Array(arguments);
					
					args.pop();
					
					if(instance[opts])
					{
						instance[opts].apply(this, [arg1, arg2]);
					}
				}
				
				return;
			}
						
			// Extend Default Settings
			$.extend(settings, opts);
			
			// Add Images
			v.images = v.container.find(s.itemSelector);
			
			// SlideShow Image Wrapper
			var ss_wrapper = $('<div class="an_slideshow_img_wrapper" />');
			
			var slideshow_img = s.slideShow.find('img');
			
			if( ! slideshow_img.length)
			{
				// Insert a blank image
				s.slideShow.prepend( $('<img src="" />') );
			}
			
			s.slideShow
				.data('img_wrapper', ss_wrapper)
					.find('img')
						.appendTo(ss_wrapper);
					
			
			
			s.slideShow.prepend(ss_wrapper);

			
			// Remove Empty Images
			v.images = v.images.filter(function()
			{
				var a = $(this);
				var img = a.find('img');
				
				if(img.length)
				{
					return true;
				}
				
				return false;
			});
			
			
			// Set Default Active Image
			var active_index = 0, requested_id = false;
			
			// Lookup for active index
			var hash = window.location.hash.toString().replace('#', '');
			var reg = s.hashID.replace('%', '([0-9]+)'), _reg = new RegExp(reg, 'i'), res;
			
			
			if(res = hash.match(reg))
			{
				active_index = res[1] - 1;
				requested_id = true;
			}
				
			methods.setActive(active_index, true);
			
			
			// Preload all images & Setup Events
			var load_count = 0;
			
			v.images.each(function(i)
			{
				var $this = $(this);
				
				$this.data('index', i);
				
				var img = $this.find('img');
				
				var img_src = img.attr('src');
				
				if(img_src && img_src.length)
				{
					img.fadeTo(0,0);
					
					img.load(function()
					{
						if(requested_id == false || active_index != i) // In case when its not active image (do not animate/fade)
						{
							TweenMax.to(img, s.duration, {css: {autoAlpha: 1}, delay: i/v.images.length, ease: Sine.easeInOut});
						}
							
						load_count++;
						
						if(load_count == v.images.length)
						{
							// Last Loaded
							methods.setActive(active_index, true);
						}
					});
				}
				
				// On Click
				$this.live('click', function(ev)
				{
					ev.preventDefault();

					methods.setActive($this.data('index'));
				})
			});
			
			
			// Setup Controls
			methods.setupControls();
			
			// Smart Hash Change Detection if requested, plugin needed!
			if(s.detectHashChange)
			{
				v.win.hashchange(function(hash)
				{
					hash = window.location.hash.toString().replace('#', '');
					
					if((res = hash.match(reg)) && v.hashChangeDisable == false)
					{
						methods.setActive(res[1]);
					}
				});
			}
			
			
			// Save Installation Data
			v.container
				.data('angallery-installed', true)
				.data('angallery-instance', methods);
		},
		
		
		// Set Active Image
		setActive: function(index, noHash)
		{
			var v = vars, s = settings, d = s.duration / 4;
			
			// Modulate Index
			index = index % v.images.length;
			
			if(index < 0)
			{
				index = 0;
			}
			
			var image = $(v.images.get(index));
			var img = image.find('img');
			
			v.images.not(image).each(function()
			{
				var a = $(this);
				
				a.removeClass('active');
				
				var _img = a.find('img');
				
				if(_img.length)
				{
					TweenMax.to(_img, d, {css: {autoAlpha: 1}});
				}
			});
			
			image.addClass('active');
			
			TweenMax.to(img, d, {css: {autoAlpha: s.activeImgOpacity}});
			
			
			// Check if is already selected
			if(image.data('index') == v.currentImage.data('index'))
			{
				return false;
			}
			
			// Disable HashChaange
			v.hashChangeDisable = true;
			
			
			// Set URL hash id
			if( ! noHash)
			{
				var current_st = v.body.scrollTop();
				window.location.hash = s.hashID.replace('%', (index+1)); 
				
				v.body.scrollTop(current_st);
			}
			
			// Switch Image
			methods.switchImage(image.attr('href'));
			
			// Set Popup Link If has
			var large_img_href;
			if(large_img_href = image.data('large'))
			{
				v.popup.attr({href: large_img_href, target: '_blank'}).show();
			}
			else
			{
				v.popup.attr({href: '#', target: '_self'}).hide();
			}
			
			// Set Last/Current Image
			v.currentImage = image;
			
			return true; // if success
		},
		
		
		// Switch Image on Slideshow
		switchImage: function(src)
		{
			var s = settings, ss = s.slideShow, d = s.duration, v = vars;
			
			var ss_wrapper = ss.data('img_wrapper');
			
			var current_img = ss_wrapper.find('img');
			
			var timeline = new TimelineMax({duration: d});
			
			TweenMax.to(current_img, d / 2, {css: {autoAlpha: 0}, onComplete: function()
			{	
				var next_img = $('<img src="'+src+'" />');
				next_img.fadeTo(0,0);
				
				var old_height = ss.height();
				
				// Enable HashChange
				v.hashChangeDisable = false;
								
				next_img.load(function()
				{
					var old_width = current_img.width(), old_height = current_img.height();
					
					current_img.before(next_img);
					current_img.remove();
					
					var img_width = this.width, img_height = this.height, resize_ratio, new_height;
					
					if(img_width > img_height)
						resize_ratio = ss.width() / img_width;
					else
						resize_ratio =  ss.width() / img_height;
					
					new_height = resize_ratio * img_height;
					
					// Start Animation
					if(old_height > 0)
						ss.height(old_height);
					
					var timeline = new TimelineMax();
					
					
					timeline.append( TweenMax.to(ss, d / 4, {css: {height: new_height}}) );
					timeline.append( TweenMax.to(next_img, d / 2, {css: {autoAlpha: 1}}) );
				});
				
			}});
			
			//console.log(src);
		},
		
		
		// Setup Controls
		setupControls: function()
		{
			var s = settings, ss = s.slideShow, v = vars;
			
			var controls = $('<div class="controls" />');
			
			// Prev Next Nav
			if(s.controls.nextPrev && v.images.length > 1)
			{
				var prev = $('<a href="#" class="nav prev">Previous</a>');
				var	next = $('<a href="#" class="nav next">Next</a>');
				
				prev.data('direction', -1);
				next.data('direction', 1);
				
				prev.add(next).on('click', function(ev)
				{
					ev.preventDefault();
					
					var direction = parseInt($(this).data('direction'), 10);
					methods.nextPrev(direction);
				});
				
				controls.append(prev).append(next);
				
				// Setup Keyboard Arrows (if allowed)
				if(s.controls.keyBoardNav)
				{
					v.win.on('keydown', function(ev)
					{
						var key = ev.keyCode;
						
						if(key == 39) // right arrow
							methods.nextPrev(1);
						else
						if(key == 37) // left arrow
							methods.nextPrev(-1);
					});
				}
			}
			
			
			// Popup Link
			if(s.controls.popup)
			{
				v.popup = $('<a href="#" class="popup" title="See Full Image">See Full Image</a>');
				controls.append(v.popup);
			}
			
			if(controls.children().length > 0)
			{
				ss.append(controls);
			}
		},
		
		
		// Next/Prev Image
		nextPrev: function(direction)
		{
			var s = settings, ss = s.slideShow, v = vars, index_to_set;
			
			if(direction > 0)
			{
				// Go to next image				
				var next_img = v.currentImage.next();
				
				if( ! next_img.length)
					next_img = v.images.first();
				
				index_to_set = next_img.data('index');
			}
			else
			if(direction < 0)
			{
				// Go to previous image		
				var prev_img = v.currentImage.prev();
				
				if( ! prev_img.length)
					prev_img = v.images.last();
				
				index_to_set = prev_img.data('index');
			}
			
			methods.setActive(index_to_set);
		},
		
		
		// Relayout Elements
		relayout: function()
		{
			var s = settings, ss = s.slideShow, v = vars, index_to_set, d = s.duration;
			
			var ss_wrapper = ss.data('img_wrapper');
			var current_img = ss_wrapper.find('img');
			
			if(current_img.is(':visible'))
			{
				var old_width = current_img.width(), old_height = current_img.height();
				
				var img_width = current_img.get(0).width, img_height = current_img.get(0).height, resize_ratio, new_height;
				
				if(img_height)
				{
					if(img_width > img_height)
						resize_ratio = ss.width() / img_width;
					else
						resize_ratio =  ss.width() / img_height;
					
					new_height = resize_ratio * img_height;
						
					// Resize the Container
					TweenMax.to(ss, d / 4, {css: {height: new_height}});
				}
			}
			
			//var old_width = current_img.width(), old_height = current_img.height();
		}
	};
	
	// jQuery Func
	$.fn.anGallery = function(opts, arg1, arg2)
	{			
		return this.each(function()
		{
			methods.init.apply(this, [opts, arg1, arg2]);
		});
	}
	
})(jQuery);