(function($) {
	/**
	 *
	 * RoyalSlider video module
	 * @version 1.1.0:
	 *
	 * 1.0.3:
	 * - Added rsOnDestroyVideoElement event
	 *
	 * 1.0.4:
	 * - Added wmode=transparent to default YouTube video embed code
	 *
	 * 1.0.5
	 * - Fixed bug: HTMl5 YouTube player sometimes keeps playing in ie9 after closing
	 *
	 * 1.0.6
	 * - A bit lightened Vimeo and YouTube regex 
	 *
	 * 1.0.7
	 * - Minor optimizations
	 * - Added autoHideCaption option
	 *
	 * 1.0.9
	 * - Fixed error that could appear if updateSliderSize method is called directly after video close
	 *
	 * 1.1.0
	 * - Video is now removed in rsAfterSlideChange event to avoid transition lag
	 * - Fixed bug that could cause appearing of arrows with auto-hide
	 */
	$.extend($.rsProto, {
		_initVideo: function() {
			var self = this;
			self._videoDefaults = {
				autoHideArrows: true,
				autoHideControlNav: false,
				autoHideBlocks: false,
				autoHideCaption: false,
				youTubeCode: '<iframe src="http://www.youtube.com/embed/%id%?rel=1&autoplay=1&showinfo=0&autoplay=1&wmode=transparent" frameborder="no"></iframe>',
				vimeoCode: '<iframe src="http://player.vimeo.com/video/%id%?byline=0&amp;portrait=0&amp;autoplay=1" frameborder="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
			};

			self.st.video = $.extend({}, self._videoDefaults, self.st.video);

			self.ev.on('rsBeforeSizeSet', function() {
				if(self._isVideoPlaying) {
					setTimeout(function() {
						var content = self._currHolder;
						content = content.hasClass('rsVideoContainer') ? content : content.find('.rsVideoContainer');
						if(self._videoFrameHolder) {
							self._videoFrameHolder.css({
								width: content.width(),
								height: content.height()
							});
						}
					}, 32);
				}
			});
			var isFF = self._browser.mozilla;
			self.ev.on('rsAfterParseNode', function(e, content, obj) {
				var jqcontent = $(content),
					tempEl,
					hasVideo;

				if(obj.videoURL) {
					if(!hasVideo && isFF) {
						hasVideo = true;
						self._useCSS3Transitions = self._use3dTransform = false;
					}
					var wrap = $('<div class="rsVideoContainer"></div>'),
						playBtn = $('<div class="rsBtnCenterer"><div class="rsPlayBtn"><div class="rsPlayBtnIcon"></div></div></div>');
					if(jqcontent.hasClass('rsImg')) {
						obj.content = wrap.append(jqcontent).append(playBtn);
					} else {
						obj.content.find('.rsImg').wrap(wrap).after(playBtn);
					}
				}
			});

			self.ev.on('rsAfterSlideChange', function() {
				self.stopVideo();
			});

		},
		toggleVideo: function() {
			var self = this;
			if(!self._isVideoPlaying) {
				return self.playVideo();
			} else {
				return self.stopVideo();
			}
		},
		playVideo: function() {
			var self = this;
			if(!self._isVideoPlaying) {
				var currSlide = self.currSlide;
				if(!currSlide.videoURL) {
					return false;
				}

				
				var content = self._currVideoContent = currSlide.content;
				var url = currSlide.videoURL,
					videoId,
					regExp,
					match;

				if( url.match(/youtu\.be/i) || url.match(/youtube\.com/i) ) {

					regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;


				    match = url.match(regExp);
				    if (match && match[7].length==11){
				        videoId = match[7];
				    }

					if(videoId !== undefined) {
						self._videoFrameHolder = self.st.video.youTubeCode.replace("%id%", videoId);
					}
				} else if(url.match(/vimeo\.com/i)) {
					regExp = /(www\.)?vimeo.com\/(\d+)($|\/)/;
					match = url.match(regExp);
					if(match) {
						videoId = match[2];
					}
					if(videoId !== undefined) {
						self._videoFrameHolder = self.st.video.vimeoCode.replace("%id%", videoId);
					}
				}
				self.videoObj = $(self._videoFrameHolder);

				self.ev.trigger('rsOnCreateVideoElement', [url]);


				if(self.videoObj.length) {
					self._videoFrameHolder = $('<div class="rsVideoFrameHolder"><div class="rsPreloader"></div><div class="rsCloseVideoBtn"><div class="rsCloseVideoIcn"></div></div></div>');
					self._videoFrameHolder.find('.rsPreloader').after(self.videoObj);
					content = content.hasClass('rsVideoContainer') ? content : content.find('.rsVideoContainer');
					self._videoFrameHolder.css({
						width: content.width(),
						height: content.height()
					}).find('.rsCloseVideoBtn').off('click.rsv').on('click.rsv', function(e) {
						self.stopVideo();
						e.preventDefault();
						e.stopPropagation();
						return false;
					});
					content.append(self._videoFrameHolder);
					if(self.isIPAD) {
						content.addClass('rsIOSVideo');
					}

					self._toggleHiddenClass(false);

					setTimeout(function() {
						self._videoFrameHolder.addClass('rsVideoActive');
					}, 10);
					self.ev.trigger('rsVideoPlay');
					self._isVideoPlaying = true;
				}
				return true;
			}
			return false;
		},
		stopVideo: function() {
			var self = this;
			if(self._isVideoPlaying) {
				if(self.isIPAD) {
					self.slider.find('.rsCloseVideoBtn').remove();
				}
				
				self._toggleHiddenClass(true);

				setTimeout(function() {
					self.ev.trigger('rsOnDestroyVideoElement', [self.videoObj]);
					var ifr = self._videoFrameHolder.find('iframe');
					if(ifr.length) {
						try {
							ifr.attr('src', "");
						} catch(ex) { }
					}
					self._videoFrameHolder.remove();
					self._videoFrameHolder = null;
				}, 16);
				self.ev.trigger('rsVideoStop');
				self._isVideoPlaying = false;
				return true;
			} 
			return false;
		},
		_toggleHiddenClass: function(remove) {
			var arr = [],
				self = this,
				vst = self.st.video;
			if(vst.autoHideArrows) {
				if(self._arrowLeft) {
					arr.push(self._arrowLeft, self._arrowRight);
					self._arrowsAutoHideLocked = !remove;
				}
				if(self._fsBtn) {
					arr.push(self._fsBtn);
				}
			}
			if(vst.autoHideControlNav && self._controlNav) {
				arr.push(self._controlNav);
			}
			if(vst.autoHideBlocks && self.currSlide.animBlocks) {
				arr.push(self.currSlide.animBlocks);
			}
			if(vst.autoHideCaption && self.globalCaption) {
				arr.push(self.globalCaption);
			}

			if(arr.length) {
				for(var i = 0; i < arr.length; i++) {
					if(!remove) {
						arr[i].addClass('rsHidden');
					} else {
						arr[i].removeClass('rsHidden');
					}
				}
			}
		}
	});
	$.rsModules.video = $.rsProto._initVideo;
})(jQuery);
