/*
	GalleryView - jQuery Content Gallery Plugin
	Author: 			Jack Anderson
	Version:			1.1 (April 5, 2009)
	Documentation: 		http://www.spaceforaname.com/jquery/galleryview/
	Modified Version:	Yair Even-Or, Jan 26, 2010
*/
function GalleryViewBuilder(json, galId, options){
	var domReadyInterval = setInterval(function(){
		if( j$('#' + galId).length ){
			clearInterval(domReadyInterval);
			var newHgb = new hgb();
			newHgb.init(json, galId, options);
		}
	}, 500);
}

function CarouselViewBuilder(json, galId){
	GalleryViewBuilder(json, galId, { type:'carousel',fancybox:false, version:2 } );
}

function videoViewBuilder(json, galId){
	GalleryViewBuilder(json, galId, { type:'video',fancybox:false, version:1 } );
}

function imagesViewBuilder(json, galId){
	GalleryViewBuilder(json, galId, { type:'images' } );
}

// headup galleryBuilder object
function hgb(){
	var _hgb = this;
	
	var opts = {
		type 		: 'images', // can be any of [carousel,video,images]
		fancybox 	: true,
		description	: false,
		version		: 1
	};
	
	var videoFlag 		= false,
		array_thumbs 	= j$([]),
		desc 			= j$('<ul/>'),
		oFilmStrip 		= j$('<ul/>').addClass('ad-thumb-list'),
		videoType 		= [],
		json, gal, items_size, oGallery, timeout;
	
	
	// this is the first function called, which sets the options needed, then preload the thumbnails
	this.init = function(data, galId, options){
		// merge the default opts object with the specific options sent
		j$.extend(opts, options);
		
		json = j$(data);
		gal = j$('#' + galId);
		items_size = json.size();
		oGallery = gal.find('.ad-thumbs');
		
		if( opts.type == 'carousel' ){
			prepareCarousel(true);
			return;
		}
		gal.addClass('loading');
		
		// timeout in case the image preloading is stuck on some image, and don't continue to buildNow()
		clearTimeout(timeout);
		timeout = setTimeout(function(){ buildNow(); }, 15000);

		preload();
	};
	
	// After preload() complete or timeout, build the video / images / carousel galleries
	var buildNow = function(){
		clearTimeout(timeout);
		//alert(prompt('',oFilmStrip.html() ));

		gal.removeClass('loading');
		// append the ready gallery to the DOM
		oFilmStrip.appendTo(oGallery);
		if( videoFlag || opts.type == 'video' ){
			if( opts.version == 1 )
				buildVideoGallery();
			else
				buildVideoGallery2();
			return false;
		}
		
		if( opts.fancybox )
			initFancybox();
	};
	
	var buildCarouselGallery = function(){
		setTimeout( function(){
			// init adGallery plugin, from file jquery.ad-gallery.js
			var galleries = gal.adGallery({
				thumb_opacity: 1,
				loader_image: 'images/ajax-loader.gif'
			});
		}, 10);
	};
	
	// build Fancybox, which opens images in a modal window
	var initFancybox = function(){
		oFilmStrip.find("li > a").fancybox({ 
			zoomSpeedIn: 300, 
			zoomSpeedOut: 300, 
			overlayShow: true,
			transitionIn: 'elastic', 
			transitionOut: 'elastic', 
			hideOnContentClick: true
		});
	};
	
	var buildVideoGallery = function(){
		oFilmStrip.addClass('video');
		gal.addClass('video2');
		var htmlCode = json[0].displayHtml;
		var temp = j$('<div/>').addClass('player');
		if( htmlCode ){
			htmlCode = htmlCode.replace( /&autoplay=1+/g, '' );
			temp.html(htmlCode);
		}
		oGallery.prepend(temp).find("li").delegate('a','click',function(){  
			temp.html( j$(this).data('displayHtml') );
			return false;
		});
	};
	
	// init Video gallery thumbnails, this is the gallery with the filter and video popup.
	var buildVideoGallery2 = function(){
		gal.addClass('video');
		var htmlCode = json[0].displayHtml;
		
		// disable the default autoplay
		htmlCode = htmlCode.replace( /&autoplay=1+/g, '' );
		
		// build the video gallery filter menu
		if( videoType.length > 1 ){
			var filter = j$('<ul/>');
			
			j$.each(videoType, function(i){
				filter.append('<li><a>' + videoType[i] + '</a></li>');
			});
			
			filter.children('li:first').addClass('active');
			
			var filterCont = j$('<div/>').addClass('filter').append(filter).append('<strong>Show:</strong>');
			oGallery.parents('div.headupwidget').prepend( filterCont );
		
		
			// bind events to the filter links
			oGalleryItems = oGallery.find('li');
			filter.delegate('a','click',function(){
				j$(this).parent('li').addClass('active').siblings('li').removeAttr('class');
				oGalleryItems.hide().filter('.' + this.innerHTML).show();
			});
		}
		
		_hgb.buildVideoPlayer(htmlCode);
		
		oGallery.find("ul").delegate('a', 'click', function(){
			var title = this.title.length > 75 ? this.title.substring(0, 75) + "&hellip;" : this.title;
			var video_html = j$(this).parent('li').find('a.thumb:first').data('displayHtml');
			var link = j$(this).parent('li').data('link');
			initShare(link);
			
			_hgb.loadMovie( title, video_html );
			_hgb.showModal();
			return false;
		});
	};
	
	this.showModal = function(){
		j$('#overlay').fadeTo(200, 0.4, function(){
			j$('#playerModal').center().fadeIn(200);
		});
	}
	
	this.buildVideoPlayer = function(htmlCode){
		// check the player container has already been initialized
		if( !j$('#playerModal').length ){
			var player = j$('<div/>').addClass('player');
			player.html(htmlCode);
			var playerModal = j$('<div id="playerModal"><a class="close">Close</a><a class="share"></a><h2>Video title</h2></div>').append(player);
			playerModal.find('a.close:first').click(function(){
				closeModal();
			});
			j$('body').append(playerModal);
		}
	};
	
	this.loadMovie = function(title, embedCode){
		j$('#playerModal').children('h2').html( decodeURI(title) );
		j$('#playerModal').children('div.player').html( embedCode );
	};
	
	function closeModal(){
		j$('#playerModal').fadeOut(200, function(){
			j$('#overlay').fadeOut(200);
		});
	};
	
	// prepare all links for all items, then init the buildCarouselGallery without waiting for all thumbnails to load
	function prepareCarousel(useSpan){
		json.each(function(index, item){
			var lnk = useSpan ? document.createElement('span') : document.createElement('a');
			if(typeof(item) == 'undefined')
				return;
			if( item.thumbnailSrc ){
				var img = new Image();
				
				img.onload = function(){
					this.onload = null;
					this.removeAttribute ("width");
					this.removeAttribute ("height");
					lnk.appendChild(img);
				}
				img.onerror = function(){
					lnk.className = 'error';
				}
				if(!useSpan)
					lnk.href = item.ImagePage;
				
				img.src = item.thumbnailSrc;
				img.alt = item.ThumbAlt;
				img.longdesc = item.ThumbAlt;
				img.index = index;
			}
			else
				lnk.className = 'error';
			// if there's a link to be added to the item
			if (item.ImagePage){
				j$(lnk).bind('click', {'href':item.ImagePage}, function(event) { window.open(event.data.href, '_blank') } );
				j$(lnk).addClass('clickable');
				j$(lnk).data('link', item.ImagePage);
			}
				
			var listItem = j$('<li/>').append(lnk).append('<small>'+ unescape(item.Caption) +'</small>');
			if( index > json.length - 4 )
				listItem.addClass('right');
				
			listItem.appendTo(oFilmStrip);
		});
		
		gal.addClass("type" + opts.version);
		gal.addClass( opts.type );
		
		oFilmStrip.appendTo(oGallery);
		
		buildCarouselGallery();
	}
	
	// iterate of the JSON object and preload the thumbnails
	function preload(){
		json.each(function(index, item){
			//item.videoType = (Math.random() > 0.5) ? 'interviews,songs' : 'music';
			var class_types = '';
			var temp_cont;
			var aimg = new Image();

			if( item)
			{
				if( !item.ImageSource )
					item.ImageSource = horizon.path + 'horizon/images/image_not_found.png';
				
				j$(aimg).data('source', item.ImagePage);
				aimg.onload = function(){
					this.onload = null;
					this.removeAttribute ("width");
					this.removeAttribute ("height");
					
					titleHtml = '<img src="' + horizon.path + item.Favicon +'" /><a target="_blank" href="'+ item.ImagePage +'">'+ unescape(item.Caption) +'</a>';
					temp_cont = j$('<a/>').html(aimg).attr('rel','image gallery').prepend('<b/>');
					
					if( opts.type == 'images' )
						temp_cont.data('title',titleHtml);
					if( opts.type == 'video' )  // || item.displayHtml != null && item.displayHtml != ''
						prepareVideo();
					else
						temp_cont.attr('href', item.ImageSource);
					
					var listItem = j$('<li/>').html(temp_cont).addClass(class_types);
					if( item.link )
						listItem.data('link', item.link);
					
					// if we're dealing with video items, version 2, so initially show only the ones that are associated with the first (active) filter
					if( opts.type == 'video' && opts.version == 2 && !listItem.hasClass(videoType[0]) )
						listItem.hide();
					
					if( opts.type == 'carousel' ){
						temp_cont.attr('href', item.ImagePage);
						if( opts.description )
							j$('<li/>').html(unescape(item.Caption)).appendTo(desc);
						else
							listItem.append('<small>'+ unescape(item.Caption) +'</small>');
					}
					
					listItem.appendTo(oFilmStrip);
					
					if( items_size-- == 1 )
						buildNow();
				}
				aimg.onerror = function(){  };
				
				aimg.src = item.thumbnailSrc;
				aimg.alt = item.ThumbAlt;
				aimg.longdesc = item.ThumbAlt;
				aimg.index = index;
				if( opts.type == 'images' )
					aimg.title = unescape(item.Caption);
					
				function prepareVideo(){
					videoFlag = true;
					//var dispdiv = j$('<div/>').addClass('displaycontainer');
					//dispdiv.attr('displayHtml', item.displayHtml);
					//dispdiv.appendTo(temp_cont);
					var caption = item.Caption.length > 60 ? unescape(item.Caption).substring(0, 60) + "&hellip;" : unescape(item.Caption);
					var title_cont = j$('<a/>').html( unescape(caption) ).attr('title',unescape(item.Caption)).attr('href','#').addClass('title');

					var date_cont = item.date ? j$('<span/>').text(item.date) : "";
					var duration_cont = item.duration ? j$('<span/>').text('[' + item.duration + ']') : "";
					
					temp_cont.addClass('thumb').attr('title', unescape(item.Caption)).attr('rel', 'gallery').data('displayHtml', item.displayHtml);
						
					//temp_cont = j$('<div/>').append(temp_cont).append(title_cont).append(date_cont).append(duration_cont);
					if( opts.version == 2 )
						temp_cont = j$.fn.add.call(temp_cont,title_cont).add(date_cont).add(duration_cont);
					
					// check 'video type' and add it to global videoType array for the filter
					if( item.videoType ){
						item.videoType = item.videoType.split(',');
						class_types = [];
						
						for( var j=0; j < item.videoType.length; j++ ){
							if( j$.inArray(item.videoType[j], videoType) == '-1' )
								videoType.push( item.videoType[j] );
							class_types.push( item.videoType[j] );
						}
						
						//class_types.push('fl_eveything');
						class_types = class_types.join(' ');
					}
				}	
			}
		});
	}
}
