(function($){
	//-------------------------------------------------------------------------
	// Main plugin code
	$.MediaPanel = function(el, json, options) {
		// To avoid scope issues, use 'base' instead of 'this'
		// to reference this class from internal events and functions.
		var base = this;

		// Create HTML markup
		base.$el = $($.MediaPanel.defaultOptions.markup);
		$(el).replaceWith(base.$el);
		base.el = base.$el.get(0);
		base.oldImage = el;

		// Add a reverse reference to the DOM object
		base.$el.data("MediaPanel", base);

		// Member variables
		base.numTabs = 0;
		base.curTab = -1;
		base.animating = false;
		base.sidebarTimer = false;
		base.hasFlash = false;
		base.autoTabRotateTimer = false;
		base.mpHover = false;


		//---------------------------------------------------------------------
		// Init function - Called when plugin starts
		base.init = function() {
			if( typeof(json) !== "object" && typeof(json) !== "string" ) {
				base.warn('JSON is not a URL or OBJECT - aborting mediaPanel creation');
						
				// Revert to old content
				base.$el.replaceWith(base.oldImage);
				
				return false;
			}

			base.options = $.extend({}, $.MediaPanel.defaultOptions, options);
			
			if (typeof(swfobject) !== 'undefined' && swfobject.hasFlashPlayerVersion("9.0.115")) {
				base.hasFlash = true;
			}

			// Bind some events
			base.$el.bind('showTab.mediaPanel', base.showTab);
			base.$el.bind('showMedia.mediaPanel', base.showMedia);


			// Clicking on a tab
			$('#mpp-tabs', base.$el).click(function(e) {
				e.preventDefault();

				if (e.target.tagName == 'SPAN') {
					e.target = e.target.parentNode;
				}

				// Get the id of the tab we clicked on
				var id = e.target.id.match(/mpp-tab-([0-2])/);
				if (id && typeof (id[1]) !== 'undefined') {
					base.$el.trigger('showTab.mediaPanel', [id[1]]);
				}

				return false;
			});

			// Clicking on an image
			$('#mpp-sidebar-content', base.$el).click(function(e) {
				e.preventDefault();

				// Get the id of the tab we clicked on
				var id = e.target.id.match(/mpp-thumb-([0-9]+)/);
				if (id && typeof (id[1]) !== 'undefined') {
					base.$el.trigger('showMedia.mediaPanel', [id[1]]);
				}
				
				return false;
			});
			
			
			
			$(base.$el).hover(function(e) {
				base.mpHover = true;
				clearTimeout(base.autoTabRotateTimer);
			}, function() {
				base.mpHover = false;
				base.setupAutoTabRotate();
			});
			
			
			$('#mpp-content-container', base.$el).hover(function(e) {
				
			
			}, function() {
				base.hoverFlag = false;
				if (base.json.tabs[base.curTab].media.length > 1 && !base.sidebarTimer) {
					base.sidebarTimer = setTimeout(function() {
						$('#mpp-sidebar', base.$el).stop().animate({right: -131}, 450, base.openArrow);
					}, 500);
				}
			});
			
			$('#hover-mat', base.$el).hover(function(e){
					
					if(!base.hoverFlag){
					  if (base.json.tabs[base.curTab].media.length > 1) {
					  	clearTimeout(base.sidebarTimer);
					  	base.sidebarTimer = false;
						$('#mpp-sidebar', base.$el).stop().animate({right: 0}, 450, base.closeArrow);
					  }
					}else{
					  if (base.json.tabs[base.curTab].media.length > 1 && !base.sidebarTimer) {
						  base.sidebarTimer = setTimeout(function() {
							  $('#mpp-sidebar', base.$el).stop().animate({right: -131}, 450, base.openArrow);
						  }, 500);
					  }					
					}
			   }, function(){
					base.hoverFlag = !base.hoverFlag;
			});

			// Scroll events
			$('#mpp-sidebar-down', base.$el).click(base.scrollDown);
			$('#mpp-sidebar-up', base.$el).click(base.scrollUp);


			// Load / parse JSON
			if( typeof(json) === "string" ) {
				// JSON is in a URL
				base.info('JSON is a URL - ajax loading JSON...', json);

				// Do the ajax request
				$.ajax({
					type: 'get',
					url: json,
					dataType: 'json',
					success: function(json) {
						base.info('JSON loaded from URL', json);
						base.json = json;
						base.parseJSON();
					},
					error: function() {
						base.warn('Error loading JSON');
						
						// Revert to old content
						base.$el.replaceWith(base.oldImage);
					}
				});
			} else {
				// JSON passed directly!
				base.info('JSON is an OBJECT - using directly');
				base.json = json;
				base.parseJSON();
			}
			
		};

		base.openArrow = function(){
			$('#mpp-sidebar .side-arrow').removeClass('close-side');
		}
		
		base.closeArrow = function(){
			$('#mpp-sidebar .side-arrow').addClass('close-side');
		}
		
		base.hoverFlag = false;

		//---------------------------------------------------------------------
		// Parse the JSON object
		base.parseJSON = function() {
			base.info('Parsing JSON...', base.json);

			// Defaults if doesn't exist
			if (!base.json.name) base.json.name = '';
			if (!base.json.tabs) base.json.tabs = {};
			if (!base.json.autoTabRotate) base.json.autoTabRotate = 0;	// Time to rotate

			// Create the tabs
			base.numTabs = base.json.tabs.length;
			base.info('Media Panel has '+base.numTabs+' tabs');
			

			if (base.numTabs == 1) {
				// Only one tab so no need to display them
				$('#mpp-tabs', base.$el).hide();
			} else {
				// Create the tabs
				for (var n=0; n<base.numTabs; n++) {
					$('#mpp-tabs', base.$el).append('<a href="#" id="mpp-tab-'+n+'"><span>'+base.json.tabs[n].name+'</span></a>');
				}
				$('#mpp-tabs', base.$el).addClass('mpp-tabs-'+base.numTabs).show();
			}

			// Pre-load images
			for (var n=0; n<base.numTabs; n++) {
				var numMedia = base.json.tabs[n].media.length;
				for (var i=0; i<numMedia; i++) {
					if (i < 3) {
						// Pre-loading
						base.info('Pre-loading ' + base.json.tabs[n].media[i].image.thumb);
						var preloadThumb = new Image(); 
						preloadThumb.src = base.json.tabs[n].media[i].image.thumb; 
						
						base.info('Pre-loading ' + base.json.tabs[n].media[i].image.large);
						var preloadLarge = new Image(); 
						preloadThumb.src = base.json.tabs[n].media[i].image.large; 
					}
				}
			}
			
			// Show the first tab
			base.showTab(null, 0);
		};

		//Show video player
		base.showVideo = function(media,numMedia) {
		    clearTimeout(base.sidebarTimer);
		    
		    // TODO: Show Video
		    $('#mpp-content').html('<div id="mpp_video_replace"></div>');
		    // Taken from VW gallery video player
		    var flashvars = {
			    autoPlay: "true",
			    basePath: "/uploads/mediapanel/"+base.json.uid+"/",
			    videoFileName: media.video,
			    startImageURL: media.image['medium']
		    }

		    var params = {
			    allowfullscreen: "true", 
			    allowscriptaccess: "always",
			    wmode: "transparent",
			    bgcolor: "#000000"
		    }

		    var attributes = {
			    id: "mpp_player",
			    name: "mpp_player"
		    }

		    if(numMedia){
			
		    }

		    swfobject.embedSWF("/assets/common/swf/VideoPlayer.swf", "mpp_video_replace", "613", "311", "9.0.115", false, flashvars, params, attributes);

		}

		//---------------------------------------------------------------------
		// Show a specific tab
		base.showTab = function(e, tabId) {
			// We are animating so not changing tab
			if (base.animating) {
				return;
			}

			// Same tab, doesn't need to do anything
			if (tabId == base.curTab) {
				return;
			}

			// Tab does not exist
			if (tabId >= base.numTabs) {
				return;
			}

			base.info('Showing tab: ' + tabId);
			base.curTab = tabId;
			var numMedia = base.json.tabs[tabId].media.length;

			$('#mpp-tabs a span').removeClass('mpp-tab-active');
			$('#mpp-tab-'+tabId+' span', base.$el).addClass('mpp-tab-active');
			$('#mpp-sidebar', base.$el).css('right', '-171px');
			$('#mpp-sidebar-content', base.$el).empty();

			if ($('#mpp-content img:eq(0)', base.$el).length) {
				$('#mpp-content img:eq(0)', base.$el).animate({opacity: 0}, 150, function() {
					$(this).css('filter', '');
					$(this).parent().empty();

	
					// Show the first media
					base.showMedia(null, 0);
					if (numMedia > 1) {
						// Scroll up/down buttons
						$('#mpp-sidebar-up span', base.$el).addClass('disabled');
						if (numMedia < 4) {
							$('#mpp-sidebar-down span', base.$el).addClass('disabled');
						} else {
							$('#mpp-sidebar-down span', base.$el).removeClass('disabled');
						}
		
						// Thumbnails
						for (var n=0; n<numMedia; n++) {
							// Don't display a play button if we do not have flash
							if (!base.hasFlash) {
								base.json.tabs[tabId].media[n].image.thumb = base.json.tabs[tabId].media[n].image.thumb.replace('-video.jpg', '-thumb.jpg')
							}
							$('#mpp-sidebar-content', base.$el).append('<a href="#"><img src="'+base.json.tabs[tabId].media[n].image.thumb+'" alt="" id="mpp-thumb-'+n+'" width="163" height="82"></a>');
						}
						
						// Slide in sidebar
						$('#mpp-sidebar', base.$el).stop().animate({right: 0}, 450, base.closeArrow);
					    base.sidebarTimer = setTimeout(function() {
						$('#mpp-sidebar', base.$el).stop().animate({right: -131}, 450, base.openArrow);
					    }, 1500);
					}else{
						$('#mpp-sidebar', base.$el).css('right', '-171px');
					}
					
					base.setupAutoTabRotate();

				});
			} else {

				$('#mpp-content').empty();

				// Show the first media
				base.showMedia(null, 0);
				if (numMedia > 1) {
					// Scroll up/down buttons
					$('#mpp-sidebar-up span', base.$el).addClass('disabled');
					if (numMedia < 4) {
						$('#mpp-sidebar-down span', base.$el).addClass('disabled');
					} else {
						$('#mpp-sidebar-down span', base.$el).removeClass('disabled');
					}
	
					// Thumbnails
					for (var n=0; n<numMedia; n++) {
						// Don't display a play button if we do not have flash
						if (!base.hasFlash) {
							base.json.tabs[tabId].media[n].image.thumb = base.json.tabs[tabId].media[n].image.thumb.replace('-video.jpg', '-thumb.jpg')
						}
						$('#mpp-sidebar-content', base.$el).append('<a href="#"><img src="'+base.json.tabs[tabId].media[n].image.thumb+'" alt="" id="mpp-thumb-'+n+'" width="163" height="82"></a>');
					}
					
					// Slide in sidebar
					$('#mpp-sidebar', base.$el).stop().animate({right: 0}, 450, base.closeArrow);
				    base.sidebarTimer = setTimeout(function() {
					$('#mpp-sidebar', base.$el).stop().animate({right: -131}, 450, base.openArrow);
				    }, 1500);
				}else{
					$('#mpp-sidebar', base.$el).css('right', '-171px');
				}
				
				base.setupAutoTabRotate();
			}
		};
		
		base.setupAutoTabRotate = function() {
			// If we have autoTabRotate time
			if (!base.mpHover && base.json.autoTabRotate != 0 && base.numTabs > 1) {
				base.autoTabRotateTimer = setTimeout(function() {
					var nextTab = base.curTab + 1;
					if (nextTab >= base.numTabs) {
						nextTab = 0;
					}
					
					base.showTab(null, nextTab);
				}, base.json.autoTabRotate);
			}
		};

		//---------------------------------------------------------------------
		// Show a specific media item
		base.showMedia = function(e, mediaId) {
			if (e) {
				e.preventDefault();
			}

			// If we are already animating don't do anything
			if (base.animating) {
				return false;
			}

			var media = base.json.tabs[base.curTab].media[mediaId];
			var numMedia = base.json.tabs[base.curTab].media.length;
			
			// Remove any exiting captions
			$('#mpp-caption', base.$el).remove();

			// Remove video
			swfobject.removeSWF('mpp_player');

			base.info('Showing media: ' + mediaId, media);

			base.animating = true;

			var $newImage = $('<img src="'+media.image['large']+'" alt="">');
			$newImage.css('opacity', 0);

			$('#mpp-content', base.$el)
				.append($newImage)
				.css('cursor', 'default')
				.unbind('click');
			
			if (e === null) {
				if (media.video !='' && base.hasFlash) {
				    base.showVideo(media,numMedia);
				    base.animating = false;
				} else {
					// Creating image from show tab
					$('#mpp-content img:eq(0)', base.$el).animate({opacity: 1}, 250, function() {
						$(this).css('filter', '');
						base.animating = false;
						base.info('Image loaded');
					});
				}
			} else {
				if (media.video !='' && base.hasFlash) {
					// Show Video					
					$('#mpp-content img:eq(0)', base.$el).animate({opacity: 0}, 250, function() {
						$(this).remove();
						base.showVideo(media,numMedia);
						base.animating = false;
					});
				} else {
					// Changing images
					if ($('#mpp-content img:eq(1)', base.$el).length) {
					    $('#mpp-content img:eq(0)', base.$el).animate({opacity: 0}, 250, function() {
						    $(this).remove();
						    base.animating = false;
						    $('#mpp-content img:eq(0)', base.$el).animate({opacity: 1}, 250, function() {
								$(this).css('filter', '');
							    base.info('Image loaded');
						    });
					    });
					} else {
						    base.animating = false;
						    $('#mpp-content img:eq(0)', base.$el).animate({opacity: 1}, 250, function() {
								$(this).css('filter', '');
							    base.info('Image loaded');
						    });
					}
				}
			}

			// If we have a caption
			if (typeof(media.caption) === 'string' && media.caption != '' && media.video == '') {
				base.showCaption(media.caption);
			}
			
			// If we have a link
			if (typeof(media.link) === 'string' && media.link != '' && media.video == '') {
				base.showLink(media.link);
			}
			
			return false;
		};
		
		//---------------------------------------------------------------------
		// Show a link
		base.showLink = function(link) {
			base.info('Showing link:', link);
			
			// Make it clickable
			$('#mpp-content', base.$el)
				.css('cursor', 'pointer')
				.click(function() {
					document.location = link;
					return false;
				});
		};

		//---------------------------------------------------------------------
		// Show a caption
		base.showCaption = function(caption) {
			base.info('Showing caption:', caption);

			var $caption = $('<div id="mpp-caption"><span></span><p>'+caption+'</p></div>');
			$('span', $caption).css('opacity', 0.5);
			
			$('#mpp-content', base.$el).append($caption);

			$caption.animate({'height': parseInt($('p', $caption).height())+20}, 150);
		};


		//---------------------------------------------------------------------
		// Scroll up the thumbnail
		base.scrollUp = function(e) {
			e.preventDefault();

			// If we are already animating don't do anything
			if (base.animating) {
				return false;
			}

			// Check we are not disabled
			if ($(this).find('.disabled').length > 0) {
				return false;
			}

			base.info('Scrolling up');

			base.animating = true;

			// Enable the up button
			$('#mpp-sidebar-down span', base.$el).removeClass('disabled');

			// Get the current offset
			var numMedia = base.json.tabs[base.curTab].media.length;
			var $firstThumb = $('#mpp-sidebar-content a:eq(0)', base.$el);
			var oT = parseInt($firstThumb.css('margin-top'));
			if (isNaN(oT)) {
				oT = 0;
			}

			// Adjust by one
			oT += 85;

			// Disable the down button if we run out of images
			if (oT == 0) {
				$('#mpp-sidebar-up span', base.$el).addClass('disabled');
			}

			// Set the offset
			$firstThumb.animate({marginTop: oT}, 150, function() {base.animating = false;});

			return false;
		};


		//---------------------------------------------------------------------
		// Scroll down the thumbnails
		base.scrollDown = function(e) {
			e.preventDefault();

			// If we are already animating don't do anything
			if (base.animating) {
				return false;
			}

			// Check we are not disabled
			if ($(this).find('.disabled').length > 0) {
				return false;
			}
			base.info('Scrolling down');

			base.animating = true;

			// Enable the up button
			$('#mpp-sidebar-up span', base.$el).removeClass('disabled');

			// Get the current offset
			var numMedia = base.json.tabs[base.curTab].media.length;
			var $firstThumb = $('#mpp-sidebar-content a:eq(0)', base.$el);
			var oT = parseInt($firstThumb.css('margin-top'));
			if (isNaN(oT)) {
				oT = 0;
			}

			// Adjust by one
			oT -= 85;

			// Disable the down button if we run out of images
			if ((numMedia*85)+oT < 340) {
				$('#mpp-sidebar-down span', base.$el).addClass('disabled');
			}

			// Set the offset
			$firstThumb.animate({'marginTop': oT}, 150, function() {
				base.animating = false;
			});

			return false;
		};


		//---------------------------------------------------------------------
		// Debug functions
		base.info = function(msg) {
			/*
			if (window.location.hostname != "www.volkswagen.co.uk" && window.console && console.info) {
				console.info.apply(null, arguments);
			}
			*/
		};
		base.warn = function(msg) {
			/*
			if (window.location.hostname != "www.volkswagen.co.uk" && window.console && console.warn) {
				console.warn.apply(null, arguments);
			}
			*/
		};

		// Run initializer
		base.init();
	};


	//-------------------------------------------------------------------------
	// Options
	$.MediaPanel.defaultOptions = {
		width: 150,
		height: 320,
		markup: '<div id="mediaPanel"><div id="mpp-content-container"><div id="mpp-content"></div><div id="mpp-sidebar"><div id="hover-mat"><div class="side-arrow"></div></div><a href="#" id="mpp-sidebar-up"><span>&nbsp;</span></a><div id="mpp-sidebar-content"></div><a href="#" id="mpp-sidebar-down"><span>&nbsp;</span></a></div></div><div id="mpp-tabs"></div></div>'
	};


	//-------------------------------------------------------------------------
	// jQuery function
	$.fn.mediaPanel = function(json, options) {
		return this.each(function() {
			(new $.MediaPanel(this, json, options));
		});
	};

})(jQuery);

