/* ------------------------------------------------------------------------
 *	Class: rbpGallery
 *	Author: Michal Skrzypek
------------------------------------------------------------------------- */

(function ($) {
    $.rbpGallery = {
        version: '0.1'
    };
    $.fn.rbpGallery = function (gallery_settings) {
    //console.log("RBPGallery");
		 gallery_settings = jQuery.extend({
		 	defaultWidth : 646,
		 	defaultHeight : 412,
		 	markup : 	'<div id="rbpGallery_overlay"></div> \
						<div id="rbpGallery_box"> \
							<a class="rbpGallery_close" href="#">Close</a> \
							<div class="rbpGallery_content" > \
								<div class="rbpGallery_fade"> \
									<div class="rbpGallery_item"> \
									</div> \
								</div> \
							</div> \
							<div class="rbpGallery_details"> \
								<div class="rbpGallery_desc"> \
									<p>CERVARIX/GSK<br />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut at risus urna, eget cursus nibh. Nulla facilisi. Maecenas eu erat leo. Donec scelerisque enim id massa blandit venenatis. Aliquam gravida, arcu vitae scelerisque</p> \
								</div> \
								<div class="rbpGallery_nav"> \
									<a href="#" class="rbpGallery_prev">Previous</a> \
									<p class="rbpGallery_current"> <span class="rbpGallery_current_big">01</span><span class="rbpGallery_current_small">/05</span></p> \
									<a href="#" class="rbpGallery_next">Next</a> \
								</div> \
							</div> \
						</div>',
			imageMarkup: '<img id="fullResImage" src="{path}" />',
			flashMarkup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
			quicktimeMarkup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',
			iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',
			animationSpeed : 500,
			overlayOpacity : 0.8,
			animationEasing: "circEaseOut",
			wmode: 'opaque',
			autoplay: 0,
		 	testsetting : ''
		 }, gallery_settings);
		 
		 var rbpGallery_dimensions , rbpGallery_boxWidth , rbpGallery_boxHeight,
		 windowHeight = $(window).height(), windowWidth = $(window).width(),
		 rbp_items, set_position;
		 
		 $(document).unbind('keydown.rbpgallery').bind('keydown.rbpgallery',function(e){
		 	//console.log("keydown.rbpgallery");
				if(typeof $rbpGallery_content != 'undefined'){
					if($rbpGallery_content.is(':visible')){
						switch(e.keyCode){
							case 37:
								$.rbpGallery.changeGalleryPage('prev');
								e.preventDefault();
								break;
							case 39:
								$.rbpGallery.changeGalleryPage('next');
								e.preventDefault();
								break;
							case 27:
								$.rbpGallery.close();
								e.preventDefault();
								break;
						};
						// return false;
					};
				};
			});
		 
		 
		$.rbpGallery.initialize = function () {
            //console.log('RBPGallery.initialize');
            settings = gallery_settings;
            
            $.RBPGallery.open();
            return false;
        }
        
        $.rbpGallery.open = function (event) {
        	//console.log('RBPGallery.open');
        
        	if(typeof settings == "undefined"){ // Means it's an API call, need to manually get the settings and set the variables
				settings = gallery_settings;
				
				rbp_items = $.makeArray(arguments[0]);
				rbp_descriptions = (arguments[1]) ? $.makeArray(arguments[1]) : $.makeArray("");
				isSet = (rbp_items.length > 1) ? true : false;
				set_position = 0;
				
				//show da boxxa
				$('body').append(settings.markup);
				
				
				$rbpGallery_box = $('#rbpGallery_box'), $rbpGallery_content = $('.rbpGallery_content'), $rbpGallery_overlay = $('#rbpGallery_overlay'); // Set my global selectors
				
				
				//
				// add button actions
				//
				$rbpGallery_box.find('.rbpGallery_next').click(function(){
					$.rbpGallery.changeGalleryPage('next');
					return false;
				});
				$rbpGallery_box.find('.rbpGallery_prev').click(function(){
					$.rbpGallery.changeGalleryPage('prev');
					return false;
				});
				$rbpGallery_box.find('.rbpGallery_close').bind('click',function(){ $.rbpGallery.close(); return false; });
				$rbpGallery_overlay
					.css({
						'opacity':0
						})
					.bind('click',function(){
						$.rbpGallery.close();
						//return false;
					});
				
				
				//
				// fade overlay
				//
				$rbpGallery_overlay.show().fadeTo( settings.animationSpeed , settings.overlayOpacity , settings.animationEasing );
			}
        	
        	
        	// Get movie dimensions
			movieWidth = ( parseFloat(getParam('width',rbp_items[set_position])) ) ? getParam('width',rbp_items[set_position]) : settings.defaultWidth.toString();
			movieHeight = ( parseFloat(getParam('height',rbp_items[set_position])) ) ? getParam('height',rbp_items[set_position]) : settings.defaultHeight.toString();
        	
        	// Display the current position
			//$rbpGallery_box.find('.rbpGallery_current').text( '<span class=\"rbpGallery_current_big\">' + (set_position+1) +'</span>' + '/' + $(rbp_items).size());
			
			var txtOne;
			var txtTwo;
			if( $(rbp_items).size() < 10 ) txtTwo = "0"+$(rbp_items).size();
			else txtTwo = $(rbp_items).size();
			
			if((set_position+1) < 10) txtOne =  "0"+(set_position+1);
			else txtOne =  (set_position+1);
			
			//$rbpGallery_box.find('.rbpGallery_current_small').text( '/' + $(rbp_items).size());
			$rbpGallery_box.find('.rbpGallery_current_small').text( '/'+txtTwo);
			$rbpGallery_box.find('.rbpGallery_current_big').text( txtOne );
			

			// Set the description
			if(rbp_descriptions[set_position] != ""){
				$rbpGallery_box.find('.rbpGallery_desc').show().html(unescape(rbp_descriptions[set_position]));
			}else{
				$rbpGallery_box.find('.rbpGallery_desc').hide();
			}
			
			// Fade the holder
			$rbpGallery_box.fadeIn( settings.animatioSpeed , settings.animationEasing , function(){

				imgPreloader = "";
				skipInjection = false;
				
				// Inject the proper content
				switch(_getFileType(rbp_items[set_position])){
					case 'image':
						imgPreloader = new Image();

						// Preload the neighbour images
						nextImage = new Image();
						if(isSet && set_position < $(rbp_items).size() -1) nextImage.src = rbp_items[set_position + 1];
						prevImage = new Image();
						if(isSet && rbp_items[set_position - 1]) prevImage.src = rbp_items[set_position - 1];

						//$pp_pic_holder.find('#pp_full_res')[0].innerHTML = settings.image_markup.replace(/{path}/g,rbp_items[set_position]);
						
						$rbpGallery_content.find('.rbpGallery_item')[0].innerHTML = settings.imageMarkup.replace(/{path}/g,rbp_items[set_position]);
						
						imgPreloader.onload = function(){
							rbpGallery_dimensions = _getDimensions(imgPreloader.width,imgPreloader.height);
							_showContent();
						};

						imgPreloader.onerror = function(){
							alert('Image cannot be loaded. Make sure the path is correct and image exist.');
							$.rbpGallery.close();
						};
					
						imgPreloader.src = rbp_items[set_position];
					break;
				
					case 'youtube':
						rbpGallery_dimensions = _getDimensions(movieWidth,movieHeight);

						
						movie = 'http://www.youtube.com/embed/'+getParam('v',rbp_items[set_position]);
						(getParam('rel',rbp_items[set_position])) ? movie+="?rel="+getParam('rel',rbp_items[set_position]) : movie+="?rel=1";
							
						if(settings.autoplay) movie += "&autoplay=1";
					
						toInject = settings.iframe_markup.replace(/{width}/g, rbpGallery_dimensions['itemWidth'] ).replace(/{height}/g,rbpGallery_dimensions['itemHeight']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,movie);
						
						$rbpGallery_content.find('.rbpGallery_item')[0].innerHTML = toInject;
						
						_showContent();
					break;
				
					case 'vimeo':
						rbpGallery_dimensions = _getDimensions(movieWidth,movieHeight);

					
						movie_id = rbp_items[set_position];
						var regExp = /http:\/\/(www\.)?vimeo.com\/(\d+)/;
						var match = movie_id.match(regExp);
						
						movie = 'http://player.vimeo.com/video/'+ match[2] +'?title=0&amp;byline=0&amp;portrait=0';
						if(settings.autoplay) movie += "&autoplay=1;";
				
						vimeo_width = rbpGallery_dimensions['itemWidth'] + '/embed/?moog_width='+ rbpGallery_dimensions['itemWidth'];
				
						toInject = settings.iframe_markup.replace(/{width}/g,vimeo_width).replace(/{height}/g,rbpGallery_dimensions['itemHeight']).replace(/{path}/g,movie);
						
						$rbpGallery_content.find('.rbpGallery_item')[0].innerHTML = toInject;
						_showContent();
					break;
				
					case 'quicktime':
						rbpGallery_dimensions = _getDimensions(movieWidth,movieHeight);
						rbpGallery_dimensions['itemWidth']+=15;
						rbpGallery_dimensions['itemHeight']+=15;
						
						//pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport
						//pp_dimensions['height']+=15; pp_dimensions['contentHeight']+=15; pp_dimensions['containerHeight']+=15; // Add space for the control bar
				
						toInject = settings.quicktimeMarkup.replace(/{width}/g,rbpGallery_dimensions['itemWidth']).replace(/{height}/g,rbpGallery_dimensions['itemHeight']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,rbp_items[set_position]).replace(/{autoplay}/g,settings.autoplay);
						$rbpGallery_content.find('.rbpGallery_item')[0].innerHTML = toInject;
						_showContent();
					break;
				
					/*				
					case 'flash':
						//pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport
					
						flash_vars = pp_images[set_position];
						flash_vars = flash_vars.substring(pp_images[set_position].indexOf('flashvars') + 10,pp_images[set_position].length);

						filename = pp_images[set_position];
						filename = filename.substring(0,filename.indexOf('?'));
					
						toInject =  settings.flash_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,filename+'?'+flash_vars);
					break;
				
					case 'iframe':
						pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport
				
						frame_url = pp_images[set_position];
						frame_url = frame_url.substr(0,frame_url.indexOf('iframe')-1);

						toInject = settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,frame_url);
					break;
					
					case 'ajax':
						doresize = false; // Make sure the dimensions are not resized.
						pp_dimensions = _fitToViewport(movie_width,movie_height);
						doresize = true; // Reset the dimensions
					
						skipInjection = true;
						$.get(pp_images[set_position],function(responseHTML){
							toInject = settings.inline_markup.replace(/{content}/g,responseHTML);
							$pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject;
							_showContent();
						});
						
					break;
					*/
				};

			});
        	
        	_checkPosition($(rbp_items).size());
        	
            return false;
        };
        
        $.rbpGallery.changeGalleryPage = function (direction) {
        	//console.log('RBPGallery.changeGalleryPage ' + direction );
        	
        	if(direction == 'prev') {
				set_position--;
				if (set_position < 0) set_position = $(rbp_items).size()-1;
			}else if(direction == 'next'){
				set_position++;
				if(set_position > $(rbp_items).size()-1) set_position = 0;
			}else{
				set_position=direction;
			};
			
			rel_index = set_position;

			//if(!doresize) doresize = true; // Allow the resizing of the images
			//$('.pp_contract').removeClass('pp_contract').addClass('pp_expand');

			_hideContent(function(){ $.rbpGallery.open(); });
        	
        };
        
        $.rbpGallery.close = function () {
        	//console.log('RBPGallery.close');
        	
        	if($rbpGallery_overlay.is(":animated")) return;
        	
        	$rbpGallery_content.stop().find('object,embed').css('visibility','hidden');
        	
        	$rbpGallery_box.fadeOut( settings.animatioSpeed , settings.animationEasing , function(){ $(this).remove(); } );
        	
        	$rbpGallery_overlay.fadeOut(settings.animation_speed , settings.animationEasing , function(){
				
				$(this).remove(); // No more need for the prettyPhoto markup
				
				//settings.callback();
				
				delete settings;
			} );
        };
        
        function _hideContent(callback){
			// Fade out the current picture
			//$rbpGallery_content.find('#rbpGallery_content object,#rbpGallery_content embed').css('visibility','hidden');
			
			//$rbpGallery_content.css('width',rbpGallery_dimensions['itemWidth']);
			$rbpGallery_content.find('.rbpGallery_fade').fadeOut( settings.animation_speed , settings.animationEasing, function(){
				//$('.pp_loaderIcon').show();
				
				callback();
			});
		};
		
		function _showContent(){
			
			//get actual window size
			windowHeight = $(window).height(), windowWidth = $(window).width();
			
			boxTop =  ((windowHeight/2) - (rbpGallery_dimensions['boxHeight']/2) );
			if(boxTop < 0) boxTop = 0;
			
			boxLeft = ( (windowWidth/2) - (rbpGallery_dimensions['boxWidth']/2) );
			if(boxLeft < 0) boxLeft = 0;
			
			$rbpGallery_box
				.animate({
					'top': boxTop,
					'left': boxLeft
				},settings.animationSpeed , settings.animationEasing );
			
			
			
			$rbpGallery_content
				.animate({
					width:rbpGallery_dimensions['itemWidth'],
					height:rbpGallery_dimensions['itemHeight']
				},settings.animationSpeed , settings.animationEasing , function(){
				
					$rbpGallery_content.find('.rbpGallery_fade').fadeIn( settings.animation_speed , settings.animationEasing );
			});
			
		
		};
        
        function _checkPosition(setCount){
        	//console.log('czek samfing ' + setCount);
			(setCount > 1) ? $('.rbpGallery_nav').show() : $('.rbpGallery_nav').hide(); // Hide the bottom nav if it's not a set.
		};
		
		function _getDimensions(width,height) {
			
			rbpGallery_boxWidth =  parseFloat(width) + 2*33;
			rbpGallery_boxHeight = 33+ parseFloat(height)+90;
			
			//console.log('boxW boxH: ' +  rbpGallery_boxWidth + '  ' + rbpGallery_boxHeight);
			
			return {
				itemWidth:Math.floor(width),
				itemHeight:Math.floor(height),
				boxWidth:Math.floor(rbpGallery_boxWidth),
				boxHeight:Math.floor(rbpGallery_boxHeight)
			};
		};
        
        function _getFileType(itemSrc){
			if (itemSrc.match(/youtube\.com\/watch/i)) {
				return 'youtube';
			}else if (itemSrc.match(/vimeo\.com/i)) {
				return 'vimeo';
			}else if(itemSrc.match(/\b.mov\b/i)){ 
				return 'quicktime';
			}else if(itemSrc.match(/\b.swf\b/i)){
				return 'flash';
			}else if(itemSrc.match(/\biframe=true\b/i)){
				return 'iframe';
			}else if(itemSrc.match(/\bajax=true\b/i)){
				return 'ajax';
			}else if(itemSrc.match(/\bcustom=true\b/i)){
				return 'custom';
			}else if(itemSrc.substr(0,1) == '#'){
				return 'inline';
			}else{
				return 'image';
			};
		};
        
        //console.log("RBPGallery przed return");
        return this.unbind('click.rbpgallery').bind('click.rbpgallery', $.rbpGallery.initialize);
	};
	
	
	
	function getParam(name,url){
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( url );
	  return ( results == null ) ? "" : results[1];
	}
	
})(jQuery);
