(function ($) {
	$.fn.ytthumb = function (options) {
			var settings = {
			images: ['http://i.ytimg.com/vi/'+$(this).attr('id') + '/1.jpg','http://i.ytimg.com/vi/' + $(this).attr('id') + '/2.jpg','http://i.ytimg.com/vi/'+ $(this).attr('id') + '/3.jpg'],
			// user editable settings
			delay: 500,
			showProgress: false
		};

		var sys = {
			// function parameters
			version: '1.0.2',
			elem: null,
			idx: 1,
			timer: null,
			load_cnt: 0,
			mouseX: null,
			mouseY: null,
			state: false
		};

		/*
			handle transitions
		***************************************/
		function clearTimer() {
			window.clearTimeout(sys.timer);
			sys.timer = null;
		}

		// reset everything
		function stopAnimation() {

			if (sys.state) {

				clearTimer();
				sys.idx = 0;
				sys.state = false;

				// show the first image
				$(sys.elem).find("div.ytthumb img:first").css({
					"display": "block"
				});

				// hide all the other images
				$(sys.elem).find("div.ytthumb img:not(:first)").css({
					"display": "none"
				});
			}
		}

		// this function handles the image transitions.
		function setThumbnail() {
			var curImg = $(sys.elem).attr("id") + "_IMG_" + sys.idx;
			var nextImg = $(sys.elem).attr("id") + "_IMG_" + (sys.idx + 1 > settings.images.length - 1 ? 1 : sys.idx + 1);
			sys.idx = sys.idx + 1 > settings.images.length - 1 ? 1 : sys.idx + 1;
			$(sys.elem).find(".ytthumb img#" + nextImg).css({
				"display": "block"
			});
			$(sys.elem).find(".ytthumb img#" + curImg).css({
				"display": "none"
			});
			clearTimer();

			// let's make sure that the mouse is still over our element before we set another timer
			if (sys.mouseX >= $(sys.elem).offset().left && sys.mouseX <= $(sys.elem).offset().left + $(sys.elem).width() && sys.mouseY >= $(sys.elem).offset().top && sys.mouseY <= $(sys.elem).offset().top + $(sys.elem).height()) {
				sys.timer = window.setTimeout(setThumbnail, settings.delay);
			} else {
				stopAnimation();
			}
		}

		// make sure all out images have loaded before starting the transition animation
		function checkLoaded() {

			// check load count against our image array
			// (keep in mind we added an image to it, so length - 1 - 1)
			if (sys.load_cnt > settings.images.length - 2) {
			//	$(sys.elem).find("div.ytthumbProgress").hide();
				sys.timer = window.setTimeout(setThumbnail, settings.delay);
			}// else {

				// animate the progress bar (if set)
		/*		if (settings.showProgress) {
					var pbox = $(sys.elem).find("div.ytthumbProgress"),
					pbar = $(sys.elem).find("div.ytthumbProgress div.ytthumbProgressBar");
					if ($(pbox).css("display") !== "block") {
						$(pbox).show();
					}
					$(pbar).css({
						"left": parseInt($(pbar).css("left"), 10) + parseInt($(pbar).width() / (settings.images.length - 2), 10) + "px"
					});
				}*/
			//}
		}

		// setup a que container and load all the images
		function setUpImageQue() {

			var link = null;

			// add our original image to the top of the array
			settings.images.unshift($(sys.elem).find("img:first").attr("src"));

			// is the original image's parent a LINK?
			if ($(sys.elem).find("img").parent()[0].nodeName === "A") {
				link = $(sys.elem).find("img").parent()[0].href;
			}

			// need to create an container loader for the images.
			// this will help with faster transitions
			$(sys.elem).append('<div class="ytthumb">');
			$(sys.elem).find(".ytthumb").css({
				"display": "none",
				"width": $(sys.elem).width() + "px",
				"height": $(sys.elem).height() + "px",
				"overflow": "hidden",
				"position": "absolute",
				"top": "0px",
				"left": "0px"
			});

			// add a progress indicator to the main element (if set)
		/*		if (settings.showProgress) {
				$(sys.elem).find(".ytthumb").append(
			$('<div class="ytthumbProgress">').css({
					"display": "none",
					"width": ($(sys.elem).width() - 4) + "px",
					"height": "8px",
					"overflow": "hidden",
					"position": "absolute",
					"top": "0px",
					"left": "0px",
					"background-color": typeof $(sys.elem).css("border-top-color") === "string" ? $(sys.elem).css("border-top-color") : "#000",
					"border-width": "2px",
					"border-style": "solid",
					"border-color": typeof $(sys.elem).css("border-top-color") === "string" ? $(sys.elem).css("border-top-color") : "#000",
					"z-index": "20"
				}).append(
				$('<div class="ytthumbProgressBar">').css({
					"display": "block",
					"width": ($(sys.elem).width() - 4) + "px",
					"height": "6px",
					"overflow": "hidden",
					"position": "absolute",
					"top": "0",
					"left": "-" + ($(sys.elem).width() - 4) + "px",
					// the background is using a base64 encoded image, IE doesn't show this, so it will use the background color instead
					"background": "#6bc4f7 url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAGCAIAAABSPBl5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAANRJREFUeNpckUtyxDAIRGms8WIq+9lMTpzL5RC5QhYZ23QakCcfFaIQEo+P8Pb+5TDJAgzY8FOAi7ffANMi7aAFbQvbyV26Jf2MuhofnzFZTuGEWBesLoNrcvEPtwcfkUTpx8FCJ7SJQwe3WsywxTJJ5EkaLAPz/ulknM8O6+pSJ+52hXCLz2Yv3pKdjrId6HyFqHICWxYoG9vZ7BHQg3G/es/uz/iQCTS+9j+bDSKyEAVL49fgMGf3+pKPtVVCBeew+gcmy35w7B6J/pPSxTpvvwUYAKIhoZSkg7l0AAAAAElFTkSuQmCC) repeat-x top left",
					"z-index": "21"
				})));
			}*/

			// add all the images to main element.
			$(settings.images).each(function (i) {
				$(sys.elem).find(".ytthumb:first").append(
				$('<img src="' + settings.images[i] + '" id="' + $(sys.elem).attr("id") + "_IMG_" + i + '" />').css({
					"display": "none",
					"position": "absolute",
					"top": "0px",
					"left": "0px",
					"z-index": 10
				}).load(function () {
					sys.load_cnt++;
					checkLoaded();
				}));
			});

			// if we have a link, let's add a click box that sits on top of everything
			if (link) {
				$(sys.elem).find(".ytthumb").append(
				$('<div>').css({
					"display": "block",
					"width": $(sys.elem).width() + "px",
					"height": $(sys.elem).height() + "px",
					"position": "absolute",
					"top": "0px",
					"left": "0px",
					"cursor": "pointer",
					"z-index": 100
				}).click(function () {
					document.location.href = link;
				}));
			}

			// reveal our creation
			$(sys.elem).find(".ytthumb").css({
				"display": "block"
			});
		}

		/* 
			initialize the image preview
		***************************************/
		function init() {

			// check to make sure we have items in our image array and
			// at least one image in the element
			if (settings.images.length > 1 && $(sys.elem).find("img").length > 0) {

				// make sure the delay is a positive integer
				settings.delay = settings.delay < 0 ? 0 : parseInt(settings.delay, 10);

				// make sure the first image is top most 
/*				if ($(sys.elem).css("position") !== "relative" && $(sys.elem).css("position") !== "absolute") {
					alert("CJ Image Video Preview v" + (sys.version) + " Error!\n\nYou parent element (#" + $(sys.elem).attr("id") + ") must have it's positioning set to either RELATIVE or ABSOLUTE.\n\nPosition: " + ($(sys.elem).css('position')));
					return;
				}
*/
				// set up event tracking, this ensures the mouse is still in our element
				$(window).mousemove(function (e) {
					sys.mouseX = e.pageX;
					sys.mouseY = e.pageY;
					
				});

				$(sys.elem).hover(
				function (e) {
				stopAnimation();
			//						sys.mouseX = e.pageX;
			//		sys.mouseY = e.pageY;
//$('#mousepos').html(sys.mouseX + ' - ' +sys.mouseY);
					// make sure the image is loaded before continuing
					if (sys.timer === null) {
									sys.mouseX = e.pageX;
					sys.mouseY = e.pageY;
						// set the sys.state to true when we are running. Special occassions
						// can make the mouseLeave event not trigger (alerts, dialogs, etc)
						sys.state = true;

						// make sure the que container is available. If not, create it.
						if ($(sys.elem).find(".ytthumb:first").length === 0) {

							// set up our que container
							setUpImageQue();

						} else {

							// que has already been created, start out transition animation
							sys.timer = window.setTimeout(setThumbnail, settings.delay);
						}
					}
				},
				function () {

					stopAnimation();

				});
			}

		}

		/* 
			set up any user passed variables
		***************************************/
		if (options) {
			$.extend(settings, options);
		}

		/* 
			begin
		***************************************/
		return this.each(function () {

		
			sys.elem = this;
			init();
		});

	};
})(jQuery);
