
/* Copyright (c) 2011 der|Design */

(function($) {

	/* Background Changer Class */

	Der.classes.BackgroundChanger = function() {

		var self = this;

		var backgrounds = null;

		self.current_index = null;

		self.total_slides = null;

		self.ul = $('#header-bar ul#bg-controls');

		self.playpause = $('#bg-playpause');

		this.set_backgrounds = function(array) {

			backgrounds = array;

			/* Precache Images, to prevent load times on slideshow */

			$.cacheImage(backgrounds, {
				error: function(e) {
					try { console.error('Failed to load ' + this.src); } catch (e) { }
				}
			});

			self.total_slides = backgrounds.length;

			if ( self.total_slides == 1 ) { self.playpause.remove(); }

			generate_controls();

		}

		this.get_active_background = function() {

			var override = $("#background-image.override").length;

			if ( override ) { return backgrounds[0]; }

			else {

				var bg = Der.get_cookie('milkyCurrentBackground');

				return ( bg ) ? bg : backgrounds[0];

			}

		}

		this.get_active_background_index = function() {

			return parseInt( self.ul.find('.active').attr('rel') );

		}

		this.pager_click = function(index) {

			self.ul.find('li[rel=' + index + ']').click();

		}

		this.set_active_background = function(bg) {

			Der.set_cookie('milkyCurrentBackground', bg);

		}

		this.is_loading = function() {

			return self.ul.hasClass('loading');

		}

		function generate_controls() {

			if ( backgrounds.length == 1 ) {

				$('#fs-controls ul.fs-pager, ul#bg-controls').remove();

			}

			var active_background = self.get_active_background();

			var html = '', active;

			for (var i in backgrounds) {

				active = (backgrounds[i] == active_background) ? ' class="active"' : '';

				if ( active ) {self.current_index = parseInt(i);}

				html += '\n<li' + active + ' rel="' + i + '"></li>';

			}

			self.ul.html(html);

			Der.fs = new Der.classes.FullScreenMode(); // Initialize Full Screen Mode, which requires the controls to be ready

			// Autostart the slideshow if enabled

			var autoplay = Der.get_cookie('MilkyAutoplay');

			if ( autoplay != undefined ) {  // If cookie set:

				if ( autoplay == 'true' ) { Der.fs.start_slideshow(); } // Autoplay only if cookie is set to true

			} else if ( Der.options.fullscreen_autoplay ) {  // If cookie not set, but fullscreen_autoplay option is set:

				Der.fs.start_slideshow(); // Autoplay if option is set to true

			}

			var current_image;

			/* Private function inside namespace. Avoids the need to create an anonymous
			 * function every time the click event is triggered */

			function load_image() {

				self.ul.add('#fs-controls').removeClass('loading');

				var bgimage = Der.get('bgimage', 'container');

				bgimage.append('<img class="below" src="' + current_image + '" style="width: 100%;" />');

				var above = Der.get('bgimage', 'object');

				var below = bgimage.find('.below');

				Der.set('bgimage', 'object', below);

				Der.set('bgimage', 'width', below[0].width);

				Der.set('bgimage', 'height', below[0].height);

				var t = 480;

				Der.lock('changing-background', t);

				Der.bg.resize_bgimage(below);

				above.fadeOut(t);

				setTimeout(function() {

					below.removeClass('below');

					above.remove();

					// Resume Slideshow

					Der.fs.resume_slideshow();

				}, t);

			}

			self.ul.find('li').click(function() {

				if ( Der.locked('changing-background') ) {return;} // Checking for Lock

				if ( $(this).hasClass('active') ) {return;}

				$(this).addClass('active').siblings().removeClass('active');

				var rel = parseInt( $(this).attr('rel') );

				self.current_index = parseInt(rel);

				var bg = current_image = backgrounds[rel];

				self.set_active_background(bg);

				self.ul.add('#fs-controls').addClass('loading');

				Der.fs.pause_slideshow(); // Pause Slideshow

				$.cacheImage(current_image, {
					load: load_image
				});

			});

		}

		this.resize_bgimage = function(bgimage) {

			if ( Der.is('apple_device') ) {

				var h = Der.get('cache', 'body').css({
					'background': 'url(' + bgimage.attr('src') + ') repeat',
					'-webkit-background-size' : 'auto 100%'
				}).height();

				Der.get('cache', 'bgs').height(h);

			} else {

				var window_width = Der.window.width();

				var window_height = Der.window.height();

				var image_width = Der.get('bgimage', 'width');

				var new_image_width = ( window_width < image_width ) ? image_width : window_width;

				new_image_width = ( new_image_width > window_width ) ? window_width : new_image_width;

				var new_image_height = Math.floor( ( Der.get('bgimage', 'height') * window_width ) / parseFloat(image_width) );

				new_image_height = (new_image_height < window_height) ? window_height : new_image_height;

				bgimage.css({
					'width': new_image_width + 'px',
					'height': new_image_height + 'px'
				});

			}

		}

	}

	/* Enhanced Search Class */

	Der.classes.EnhancedSearch = function(container, input, close) {

		container = $(container);

		input = container.find(input);

		var title = input.attr('title');input.removeAttr('title');

		var close = container.find(close);

		var timeout = null;

		input.focus(function() {

			clearTimeout(timeout);

			close.stop().fadeIn( (Der.is('modern_browser') ) ? 200 : 0 );

		}).blur(function() {

			function hide() {

				close.fadeOut( (Der.is('modern_browser') ) ? 120 : 0 );

				if ( $.trim( input.val() ) == '' ) {input.val( title );}

			}

			timeout = setTimeout(hide, 150);

		});

		close.click(function() {

			input.val('').focus();

		});

	}

	/* Full Screen Mode Class */

	Der.classes.FullScreenMode = function() {

		var self = this;

		self.playing = false;

		self.resume = false;

		self.fullscreen_mode = false;

		var busy = false;

		var button = $('#header-bar a#fullscreen-btn');

		var body = Der.get('cache', 'body');

		var fs_controls = $('#fs-controls');

		var pager = fs_controls.find('ul.fs-pager');

		var playpause = pager.find('> li.playpause');

		var exit_button = fs_controls.find('a.fs-button');

		var ui = $('#header-wrap, #left-sidebar, #right-sidebar, #content, #right-bg, #logo, #left-bg, #content-bg, #right-bg');

		// Create fs-controls based on Der.classes.BackgroundChanger().

		var control_lis = Der.bg.ul.find('> li').clone();

		pager.append(control_lis);

		// Full screen controls click event

		pager.find('> li:not(.playpause)').click(function() {

			var rel = $(this).attr('rel');

			$(this).addClass('active').siblings().removeClass('active');

			Der.bg.ul.find('li[rel=' + rel + ']').click();

		});

		// Enter fullscreen button click event

		button.click(function() {

			if ( busy ) {return;} busy = true;

			self.fullscreen_mode = true;

			Der.hide_visible_popups('nav_popup');

			Der.lock('nav_popups_lock');

			body.css('overflow-y', 'hidden');

			Der.window.trigger('resize');

			ui.stop().fadeOut( (Der.is('modern_browser') ) ? 500 : 0 );

			setTimeout(function() {

				fs_controls.stop().fadeIn( (Der.is('modern_browser') ) ? 800 : 0 );

				busy = false;

			}, 350);

			return false;

		});

		// Exit fullscreen button click event

		exit_button.click(function() {

			if ( busy ) {return;} busy = true;

			body.css('overflow-y', 'visible');

			fs_controls.stop().fadeOut( (Der.is('modern_browser') ) ? 300 : 0 );

			ui.stop().fadeIn( (Der.is('modern_browser') ) ? 600 : 0 );

			// Stop slideshow on exit, unlock popups, unset self.fullscreen_mode

			setTimeout(function() { busy = false; self.fullscreen_mode = false; Der.unlock('nav_popups_lock'); }, 610);

			Der.window.trigger('resize');

			return false;

		});

		$('body').keyup(function(e) {

			if ( Der.fs.fullscreen_mode ) {

				if ( e.keyCode == 27 ) { // If escape key has been pressed, exit fullscreen mode

					exit_button.click();

				} else if ( e.keyCode == 32 ) { // If spacebar has been pressed, toggle play/pause

					playpause.click();

				}

			}

		});

		// Connect ul#bg-controls with #fs-controls ul.pager

		Der.bg.ul.find('li').click(function() {

			var index = $(this).attr('rel');

			pager.find('li[rel=' + index + ']').addClass('active').siblings().removeClass('active');

		});

		// Add Play/pause controls

		playpause.click(function() {

			if ( Der.bg.playpause.hasClass('play') ) {

				Der.set_cookie('MilkyAutoplay', 'true');

				Der.bg.playpause.removeClass('play').addClass('pause')

			} else {

				Der.set_cookie('MilkyAutoplay', 'false');

				Der.bg.playpause.removeClass('pause').addClass('play')

			}


			( self.playing ) ? self.stop_slideshow() : self.start_slideshow(); // Each function modifies self.playing

		});

		// Connect #bg-playpause with self

		Der.bg.playpause.click(function() {

			playpause.click();

			return false;

		});

		/* Public Methods */

		var intervalID = null;

		this.start_slideshow = function(resume_mode) {

			self.playing = true;

			if ( ! resume_mode ) {

				playpause.addClass('stop');

				self.next_slide();

			}

			clearInterval(intervalID); // Clear any previous interval ID's

			intervalID = setInterval(function() {

				self.next_slide();

			}, Der.options.fullscreen_autoplay_interval * 1000); // Convert to seconds

		}

		this.stop_slideshow = function(pause_mode) {

			self.playing = false;

			if ( ! pause_mode ) { playpause.removeClass('stop'); }

			clearInterval(intervalID);

		}

		this.pause_slideshow = function() {

			if ( self.playing ) {

				self.resume = true;

				self.stop_slideshow(true);

			}

		}

		this.resume_slideshow = function() {

			if ( self.resume ) {

				self.resume = false;

				self.start_slideshow(true);

			}

		}

		this.next_slide = function() {

			if ( Der.bg.is_loading() ) { return; }

			var next = cycle(1, Der.bg.current_index, Der.bg.total_slides);

			Der.bg.pager_click(next);

		}

	}

	queue_ready_fn(function() {

		Der.bg = new Der.classes.BackgroundChanger();

	});

})(jQuery);
