// Mother fuckin' Pop up!
// author: christian@rgbfab.com

var rgb_pop_count;
var rgb_pop_current_index;
var rgb_pop_current_width;
var rgb_pop_current_height;
var rgb_pop_content_loaded;
var rgb_pop_set_width;
var rgb_pop_set_height;
var rgb_pop_open = false;

(function($) {
	// Preparation for newly loaded content
	$.fn.rgb_pop = function(options) {
		var settings = $.extend({},{
			pop_class: 'rgb_pop',			// if we need to specify alternate sets of images
			link_attribute: 'href',			// attribute to find the url from
			loading_text: 'loading',		// what to toss up when something is loading
			next_text: 'next',				// what to put in for the next button
			prev_text: 'prev',			// what to put in for the prev button
			close_text: 'close',			// what to put in for the close button
			counter_separator: ' / ',		// what to put between the current index and the total
			alternate_counter_content: '',	// if we want to use something other than the count
			vimeo_color: 'E63D90',			// object to base x position off of
			html5_video_maybe_not_supported_text: 'Your browser may not support this video format.<br />',
			html5_video_maybe_not_supported_download_text: 'Right click here to download the video.',
			html5_video_not_supported_text: 'Your browser does not support html5 video playback.<br />',
			html5_video_not_supported_download_text: 'Right click here to download the video.'
		},options||{});
		
		
		$(this)
			.addClass( settings.pop_class )
			.click(function(event){

				event.preventDefault();

				pop_count(); // update the number of pop-ups on the page	
				
				var url_string = $(this).attr( settings.link_attribute );
				
				if ( base_url ) { // if base_url is set we'll push notifications to Google Analytics
					var google_tracking_url = url_string.replace(base_url,'');
				}
				
				var this_index = $(this).attr( settings.pop_class + '_index');
						
				rgb_pop_content_loaded = false;
				rgb_pop_current_index = this_index;
		
				calculate_size(); // figure out how big to make the content
		
				add_rgb_structure( rgb_pop_settings );
		
				prep_pop(); // prepare the pop-up parts
		
				$('#rgb_pop_counter_index').html( parseInt(this_index) );

				if ( is_image(url_string) ) {
					$('#rgb_pop_content')
						.html( html_image(url_string) )
						.find('img')
							.load(function(){
								content_ready(url_string);
							}).each(function(){
								if ( this.complete || this.complete === undefined ) {
									this.src = this.src;
									content_ready(url_string);
								}
							});
		
				} else if ( is_vimeo(url_string) ) {
					var vimeo_id = parse_vimeo_id(url_string);

					// go to vimeos json api to get the video dimensions
					$.getJSON('http://www.vimeo.com/api/v2/video/' + vimeo_id + '.json?callback=?', {format: "json"}, function(data) {
						rgb_pop_current_width = data[0].width;
						rgb_pop_current_height = data[0].height;
						
						$('#rgb_pop_content')
							.html(html_vimeo(vimeo_id));

						content_ready(url_string);
					});
		
				} else if ( is_youtube(url_string) ) {
					// assume basic 4:3 dimensions
					rgb_pop_current_width = 640;
					rgb_pop_current_height = 480;
			
					$('#rgb_pop_content')
						.html(html_youtube(url_string));
		
					content_ready(url_string);
			
				} else if ( is_html5_video(url_string) ) {
					$('#rgb_pop_content')
						.html(html_html5_video(url_string))
						.find('video')
							.bind('loadedmetadata',function(){
								content_ready(url_string);
							});
					
					// get ready for this not to work - after 4 seconds of waiting we throw this message
					$('#rgb_pop_loading').delay(4000).fadeOut(600, function(){
						$('#rgb_pop_loading')
							.html('<span id="rgb_pop_video_loading">' + settings.html5_video_maybe_not_supported_text + '<a href="' + url_string + '" target="_blank">' + settings.html5_video_maybe_not_supported_download_text + '</a>')
							.fadeIn(600);
					});
		
				} else {
					close_pop();
				}
	
				if ( google_tracking_url ) {
					_gaq.push(['_trackPageview', google_tracking_url]);			
				}
				
			}); // click function
	
	
		// execute a new count of pops each time we add one
		pop_count();

		// Stuff to do when content is loaded
		function content_ready(url_string) {
			if ( !rgb_pop_content_loaded ) {
				rgb_pop_content_loaded = true;

				$('#rgb_pop_content').hide();

				if ( is_image(url_string) ) {
					rgb_pop_current_width = $('#rgb_pop_content').width();
					rgb_pop_current_height = $('#rgb_pop_content').height();
				}

				calculate_size();

				$('#rgb_pop_loading').fadeOut();
				
				$('#rgb_pop_content').fadeIn();

			}
		} // content_ready()


		// Prepare the background field, prev button, next button, counter, close, loading, and close
		function prep_pop() {
			$('#rgb_pop_content').hide();

			$('#rgb_pop_background, #rgb_pop_close, #rgb_pop_loading').fadeIn();
		
			// if we're on handheld we'll get rid of the main content - relies on everything being contained in #wrapper
			if ( BrowserDetect.handheld ) {
				$('#wrapper, #footer').fadeOut();
			}
		
			// if there's more than one pop-up, we give navigation buttons and the counter
			if ( rgb_pop_count > 1 ) {
				$('#rgb_pop_counter_total').html(rgb_pop_count);
			
				$('#rgb_pop_next, #rgb_pop_prev, #rgb_pop_counter').fadeIn();
			}
			
		} // prep_pop()


		// determine the number of pop-ups present
		function pop_count() {
			var pops = $('.' + settings.pop_class);

			rgb_pop_count = pops.length;

			var pop_i = 1;

			$(pops).each(function(){
				$(this).attr( settings.pop_class + '_index',pop_i++);
			});
		} // pop_count()


		// returns an image
		function html_image(url_string) {			
			return '<a href="' + url_string + '" target="_blank"><img src="' + url_string + '" /></a>';			
		} // html_image()

		
		// returns an html5 video
		function html_html5_video(url_string){
			return '<video src="' + url_string + '" controls autoplay>' + settings.html5_video_not_supported_text + ' <a href="' + url_string + '">' + settings.html5_video_not_supported_download_text + '</a></video>';
		} // html_html5_video()


		// returns a vimeo player
		function html_vimeo(vimeo_id){
			return '<iframe src="http://player.vimeo.com/video/' + vimeo_id + '?api=1&amp;title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1&amp;color=' + settings.vimeo_color + '" width="' + rgb_pop_current_width + '" height="' + rgb_pop_current_height + '" frameborder="0"></iframe>';
		} // html_vimeo()


		// returns a youtube player
		function html_youtube(url_string){
			return '<iframe src="http://www.youtube.com/embed/' + parse_youtube_id(url_string) + '" frameborder="0" width="' + rgb_pop_current_width + '" height="' + rgb_pop_current_height + '" allowfullscreen></iframe>';
		} // html_youtube()

		
		// gets a vimeo id out of a link to a vimeo video
		function parse_vimeo_id(url_string) {
			var regExp = /http:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/;

			var match = url_string.match(regExp);

			if ( match ) {
				return match[2];
			} else {
				return false;
			}
		} // parse_vimeo_id()
		

		// gets a youtube id out of a link to a youtube video
		function parse_youtube_id(url_string) {
			var id;
			
			if ( url_string.indexOf('youtube.com') > 1) {
				id = url_string.split('v=')[1];
			} else if ( url_string.indexOf('youtu.be') > 1) {
				id = url_string.split('e/')[1];
			}

			if ( id ) {
				var ampersandPosition = id.indexOf('&');
				if ( ampersandPosition != -1 ) {
				  id = id.substring(0, ampersandPosition);
				}

				return id;
			} else {
				return false;
			}
		} // parse_youtube_id()

		// activates the next pop-up
		function next_pop() {			
			
			var next_index = parseInt(rgb_pop_current_index) + 1;

			if ( next_index > rgb_pop_count ) {
				next_index = 1;
			}

			$('[' + settings.pop_class + '_index="' + next_index + '"]').click();
		} // next_pop()


		// activates the previous pop-up
		function prev_pop() {
			var next_index = parseInt(rgb_pop_current_index) - 1;

			if ( next_index == 0 ) {
				next_index = rgb_pop_count;
			}

			$('[' + settings.pop_class + '_index="' + next_index + '"]').click();
		} // prev_pop()


		// closes all the pop-up stuff
		function close_pop() {
			$('#rgb_pop_background, #rgb_pop_content, #rgb_pop_loading, #rgb_pop_next, #rgb_pop_prev, #rgb_pop_close, #rgb_pop_counter').fadeOut(600,function(){
				$('#rgb_pop_content').html('');
			});

			if ( BrowserDetect.handheld ) {
				$('#wrapper, footer').fadeIn();
			}

			remove_rgb_structure();

		} // close_pop()


		// boolean if it's an image
		function is_image(url_string) {
			if ( url_string.indexOf('.jpg') > 0 || url_string.indexOf('.png') > 0 || url_string.indexOf('.jpeg') > 0 || url_string.indexOf('.gif') > 0 ) {
				return true;
			}

			return false;
		} // is_image()


		// boolean if it's a video of any kind
		function is_video(url_string) {
			if ( is_mov(url_string) || is_wmv(url_string) || is_mp4(url_string) || is_vimeo(url_string) || is_youtube(url_string) ) {
				return true;
			} else {
				return false;
			}
		} // is_video()


		// boolean if it's HTML5 video
		function is_html5_video(url_string) {
			if ( is_mov(url_string) || is_wmv(url_string) || is_mp4(url_string) ) {
				return true;
			}
			return false;
		} // is_html5_video()

		function is_mov(url_string) { if ( url_string.indexOf('.mov') > 0 ) { return true; } else { return false; } }

		function is_wmv(url_string) { if ( url_string.indexOf('.wmv') > 0 ) { return true; } else { return false; } }

		function is_mp4(url_string) { if ( url_string.indexOf('.mp4') > 0 ) { return true; } else { return false; } }

		function is_vimeo(url_string) { if ( url_string.indexOf('vimeo.com') > 0 ) { return true; } else { return false; } }

		function is_youtube(url_string) { if ( url_string.indexOf('youtube.com') > 0 || url_string.indexOf('youtu.be') > 0 ) { return true; } else { return false; } }


		// Add the background field, prev button, next button, counter, close, loading, and close
		function add_rgb_structure( settings ) {

			if ( $('#rgb_pop_force').length == 0 && BrowserDetect.handheld && $('body').height() < 420 ) {
				$('body').append('<div id="rgb_pop_force"></div>');
				window.scrollTo(0,1);
			}

			if ( $('#rgb_pop_background').length == 0 ) {
				$('body').append('<div id="rgb_pop_background"></div>');
				
				$('#rgb_pop_background')
					.click( function(){
						if ( !BrowserDetect.handheld ) {
							close_pop();
						}
					});
					
					$(window)
						.bind('resize.rgb_pop', function() {
							calculate_size();

							if ( $('#rgb_pop_background').length > 0 && !BrowserDetect.handheld ) {
								/*$('#rgb_pop_background')
									.width( $('body').width() )
									.height( $('body').height() );*/
							}
						})
						.bind('scroll.rgb_pop', function(){
							if ( BrowserDetect.handheld ) {
								calculate_size();
							}
						});

					$(window)
						.bind('onorientationchange.rgb_pop', function() { calculate_size() })
						.bind('keydown.rgb_pop', function(event) {
							if ( event.keyCode == 39 ) {
								event.preventDefault();
							
								next_pop();
							} else if ( event.keyCode == 37 ) {
								event.preventDefault();

								prev_pop();
							} else if ( event.keyCode == 27 ) {
									event.preventDefault();

									close_pop();
							}
						});
			}

			if ( $('#rgb_pop_loading').length == 0 ) {
				$('body').append('<div id="rgb_pop_loading">' + settings.loading_text + '</div>');
			}

			if ( $('#rgb_pop_content').length == 0 ) {
				$('body').append('<div id="rgb_pop_content"></div>');
			}

			if ( $('#rgb_pop_next').length == 0 ) {
				$('body').append('<div id="rgb_pop_next">' + settings.next_text + '</div>');
				
				$('#rgb_pop_next').click(function(){ next_pop(); });
			}

			if ( $('#rgb_pop_prev').length == 0 ) {
				$('body').append('<div id="rgb_pop_prev">' + settings.prev_text + '</div>');
				
				$('#rgb_pop_prev').click(function(){ prev_pop(); });
			}

			if ( $('#rgb_pop_counter').length == 0 ) {
				var counter_content = '<span id="rgb_pop_counter_index"></span><span id="rgb_pop_counter_separator">' + settings.counter_separator + '</span><span id="rgb_pop_counter_total"></span>';

				if ( settings.alternate_counter_content ) {
					counter_content = settings.alternate_counter_content;
				}

				$('body').append('<div id="rgb_pop_counter">' + counter_content + '</div>');
			}

			if ( $('#rgb_pop_close').length == 0 ) {
				$('body').append('<div id="rgb_pop_close">' + settings.close_text + '</div>');
				
				$('#rgb_pop_close').click(function(){ close_pop(); });
			}

		} // add_rgb_structure()

		// removes the pop structure
		function remove_rgb_structure() {
			$('#rgb_pop_background, #rgb_pop_loading, #rgb_pop_content, #rgb_pop_next, #rgb_pop_prev, #rgb_pop_counter, #rgb_pop_close').fadeOut('normal',function(){ $(this).remove()});

			$(window)
				.unbind('resize.rgb_pop')
				.unbind('scroll.rgb_pop')
				.unbind('onorientationchange.rgb_pop')
				.unbind('keydown.rgb_pop');
		}

		// determine the size that we're going to make the content that we're loading
		function calculate_size() {		
			if ( $('#rgb_pop_content').length > 0 ) {
				rgb_pop_set_width = rgb_pop_current_width;
				rgb_pop_set_height = rgb_pop_current_height;				

				var url_string = $('#rgb_pop_content [src]:first').attr('src');

				if ( url_string && is_html5_video(url_string) ) {
					rgb_pop_set_width = 2 * rgb_pop_current_width;
					rgb_pop_set_height = 2 * rgb_pop_current_height;
				}

				var window_width = $(window).width();
				var window_height = $(window).height();

				if ( BrowserDetect.handheld ) {
					window_width = window.innerWidth - 88;
					window_height = window.innerHeight - 88;

				} else {
					var prev_button = $('#rgb_pop_prev:first');
					var next_button = $('#rgb_pop_next:first');
					var close_button = $('#rgb_pop_close:first');
					var the_counter = $('#rgb_pop_counter:first');

					if ( next_button.length > 0 || prev_button.length > 0 ) {
						var prev_pos = prev_button.offset();
						var next_pos = next_button.offset();

						window_width = next_pos.left - prev_pos.left - prev_button.width();					
					}

					var close_pos = close_button.offset();

					if ( the_counter.length > 0 ) {
						var counter_pos = the_counter.offset();

						window_height = counter_pos.top - close_pos.top - close_button.height();
					} else {
						window_height = window_height - 2 * ( close_pos.top + close_button.height() - $(window).scrollTop() );
					}

					var window_width = window_width - 60;
					var window_height = window_height - 60;
				}

				if ( rgb_pop_set_width > window_width ) {
					rgb_pop_set_height = window_width * ( rgb_pop_set_height / rgb_pop_set_width );
					rgb_pop_set_width = window_width;
				}

				if ( rgb_pop_set_height > window_height ) {
					rgb_pop_set_width = window_height * ( rgb_pop_set_width / rgb_pop_set_height );
					rgb_pop_set_height = window_height;
				}

				if ( BrowserDetect.handheld ) {				
					var window_scroll_left = $(window).scrollLeft();
					var window_scroll_top = $(window).scrollTop();
					var content_left_position = window_scroll_left + ( window_width - rgb_pop_set_width ) / 2 + 44;
					var content_top_position = window_scroll_top + ( window_height - rgb_pop_set_height ) / 2 + 44;
					var loading_left_position = window_scroll_left + ( window_width - $('#rgb_pop_loading').width() ) / 2 + 44;
					var loading_top_position = window_scroll_top + ( window_height - $('#rgb_pop_loading').height() ) / 2 + 44;
					var next_left_position = window_scroll_left + window_width + 44;
					var next_top_position = window_scroll_top + window_height / 2 + 22;
					var prev_left_position = window_scroll_left;
					var close_top_position = window_scroll_top + 5;
					var counter_left_position = window_scroll_left + window_width / 2 - $('#rgb_pop_counter').width() / 2 + 44;
					var counter_top_position = window_scroll_top + window_height + 66;

					$('#rgb_pop_background')
						.width( $(document).width() )
						.height( $(document).height() );

					$('#rgb_pop_content')
						.css('left', content_left_position)
						.css('top', content_top_position);

					$('#rgb_pop_loading')
						.css('left', loading_left_position)
						.css('top', loading_top_position);

					$('#rgb_pop_next')
						.css('left', next_left_position)
						.css('top', next_top_position);

					$('#rgb_pop_prev')
						.css('left', prev_left_position)
						.css('top', next_top_position);

					$('#rgb_pop_close')
						.css('left', next_left_position)
						.css('top', close_top_position);

					$('#rgb_pop_counter')
						.css('left', counter_left_position)
						.css('top', counter_top_position);

				} else {
					var content_margin_top =- rgb_pop_set_height / 2;
					var content_margin_left =- rgb_pop_set_width / 2;

					content_margin_top = Math.round( content_margin_top ) + "px";
					content_margin_left = Math.round( content_margin_left ) + "px";

					$('#rgb_pop_content')
						.css('margin-top', content_margin_top)
						.css('margin-left', content_margin_left);
				}

				rgb_pop_set_width = Math.round( rgb_pop_set_width ) + "px";
				rgb_pop_set_height = Math.round( rgb_pop_set_height ) + "px";

				$('#rgb_pop_content')
					.find('img, video')
						.css('width', rgb_pop_set_width).end()
					.find('iframe')
						.css('width', rgb_pop_set_width)
						.css('height', rgb_pop_set_height);

			} // if ( $('#rgb_pop_content').length > 0 )
		} // calculate_size()

		return this;


	} // $fn.rgb_pop
		
		

	
})(jQuery);
