/* EVENTS */
Events.Gallery = {
	HASH_CHANGE:		'hashchange.GALLERY',
	UPDATE:				'update.GALLERY'
}
Events.Strip = {
	PAGE_CHANGE:		'pageChange.STRIP'
}
Events.VideoPlayer = {
	SET_VIDEO_SOURCE:	'setVideoSource.VIDEOPLAYER',
	SHOW_EXTRA:			'showExtra.VIDEOPLAYER'
}
Events.ImagePlayer = {
	SET_GALLERY:		'setGallery.IMAGEPLAYER',
}
Events.Player = {
	SHOW_EXTRA:			'showExtra.PLAYER',
}


/* GALLERY CLASS */
Gallery = function (_container, _params, _content) {
	Gallery.prototype._ 			= function (text) { return Lang(text) };
	Gallery.prototype.fragment		= FragmentParser;
	
	var that						= this;
	this.container					= _container;
	this.data						= _content;
	
	this.init = function (params) {
		//console.log('Bon.Gallery Data', _content);
		//SORT PARAMETERS
		if (params == undefined) {
			//this.cfg = {type:'video', lang:'se', /*debug:true, /*debugLevel:5*/}
		} else {
			this.cfg = params;
			this.cfg.type		= (_params.type == null) ? 'video' : _params.type;
			this.cfg.lang		= (params.lang == null) ? 'se' : _params.lang;
			this.cfg.debug	 	= (params.debug == null) ? false : _params.debug;
			this.cfg.from		= params.from;
			//this.cfg.debugLevel	= (_params.debugLevel == null) ? true : _params.debugLevel;
		}
		//START
						
		//SHOW MAIN GALLERY
		that.container.parent().show();
		that.container.show();
		this.renderGallery(this.cfg.type);
		
		//ON IPAD, HIDE THE TWITTER FEED
		if($('html').hasClass('ipad')) {
			$('.twtr-tweets').hide();
		}
		// STOP POSTER
		$('.poster_container').trigger('posterAnimStop.LANDING');

				
		//LISTENERS
		$(window).unbind(Events.Gallery.UPDATE);
		$(window).bind(Events.Gallery.UPDATE, that.update);
		$(window).bind('closeAllWindows.BON', that.closeGallery);
		$(window).bind('closeSection.GALLERY', that.closeGallery);
		this.update();
	}
	
	this.getDataFromFragment = function () {
		var frag = that.fragment().get();
		if(that.cfg.type == 'video') {
			return that.getVideoDataFromIDs(frag.gid, frag.vid);
		} else if(that.cfg.type == 'image' && frag.aid) {
			var aidData = that.getItemByKeyValue('id', frag.aid, that.data.collections);
			var gidData = false;
			var pidData = false;
			if(frag.gid && aidData) {
				gidData = that.getItemByKeyValue('id', frag.gid, aidData.contents);
			}
			if(frag.pid && gidData){
				pidData = that.getItemByKeyValue('pid', frag.pid, gidData.photos);
			}
			var ret = { aid:aidData, gid:gidData, pid:pidData };
			//console.log('Gallery::getDataFromFragment("image")', ret);
			return ret;
		}
	}
	
	this.getItemByKeyValue = function(_key, _value, _group) {
		var res = false;
		for (var i in _group) {
			if( _group[i][_key] == _value ){
				res = _group[i];
			} 
		}
		return res;
	}
	
	this.getVideoDataFromIDs = function (_gid, _vid) {
		var g = this.getGroupFromID(_gid);
		var v = this.getVideoFromID(_vid, g.contents);
		return {collection:g, video:v}
	}
	
	this.getGroupFromID = function (_id) {
		var res = false;
		for (var i in this.data.collections) {
			if( this.data.collections[i].id == _id ){
				res = this.data.collections[i];
			} 
		}
		return res;
	}
	
	this.getVideoFromID = function (_id, _contents) {
		var res = false;
		for (var i in _contents) {
			if( _contents[i].id == _id ){
				res = _contents[i];
			} 
		}
		return res;
	}
	
	this.update = function () {
		var frag = that.fragment().get();
		var contentData = that.getDataFromFragment();
		console.log('Gallery::update', frag, contentData);
		if(frag.go == 'videogallery' && that.cfg.type == 'video'){
			
			if(frag.gid){
				//debugger;
				if(that.strip){
				} else {
					that.renderVideoPlayer(contentData.collection);
				}
				if(frag.vid){
					$(window).trigger($.Event(Events.VideoPlayer.SET_VIDEO_SOURCE, { video:contentData.video} ));
				} else {
					
				}
			} else {
				$('.btn_closeplayer').trigger('click');
			}
		} else if (frag.go == 'imagegallery' && that.cfg.type == 'image') {
			
			if(frag.aid){
				if(that.strip){
				} else {
					that.renderImagePlayer(contentData.aid);
				}
				if(frag.gid){
					if(frag.pid){
						//console.log('Gallery::update');
						$(window).trigger($.Event(Events.ImagePlayer.SET_GALLERY, { gallery:contentData.gid, photo:contentData.pid} ));
					} else {
						$(window).trigger($.Event(Events.ImagePlayer.SET_GALLERY, { gallery:contentData.gid} ));
					}
				} else {
					
				}
			} else {
				// TRIGGER IMAGE PLAYER CLOSE
				$('.btn_closeplayer').trigger('click');
			}
		} else {
			console.log('Gallery::update() - switch gallery type');
			//that.switchGalleryType();
		}
	}
	
	this.switchGalleryType = function () {
		that.closeGallery();
		if(that.cfg.type == 'video') {
			that.fragment().set({go:'imagegallery'});
		} else if (that.cfg.type == 'image') {
			that.fragment().set({go:'videogallery'});
		}
	}
	
	this.renderGallery = function (type) {
		// RENDER BASE
		obj = this;
		//console.log(this.container);
		this.container.removeClass('video');
		this.container.removeClass('image');
		this.container.addClass(type);
		navData =  {
			film: this._('film'),
			close: this._('close'),
			image: this._('image')
		}
		navData.gallery_title = (type == 'video') ? this._('film') : this._('image');
		//console.log(this.templates, this.templates(), this.templates.base, this.templates.base());
		this.templates.base().tmpl(navData).appendTo(this.container);
		
		// RENDER LIST
		//console.log(this.data.collections);
		for (var i=0; i<this.data.collections.length; i++) {
			var data = this.data.collections[i];
			var typeOfContent = (type == 'video') ? this._('films') : this._('galleries');
			if(this.data.collections[i].contents.length < 2){
				console.log(this.data.collections[i].contents.length);
				typeOfContent = (type == 'video') ? this._('one_film') : this._('one_gallery');
			}
			data.contentCount = this.data.collections[i].contents.length+' '+typeOfContent;
			data.updated = this.findLastUpdatedContent(data.contents);
			data.lastUpdated = this._('last_updated')+' '+data.updated;
			data.collectionId = i;
			this.templates.gallery_item().tmpl( data ).appendTo(".gallery_list");
		}
		$('<div class="clearfix"></div>').appendTo(".gallery_list");
		// SET SCROLLBAR BASED ON DEVICE
		if(Modernizr.touch){
			//console.log('TOUCH DEVICE');
			$('.gallery_list').jScrollTouch();
		} else {
			//console.log('NOT A TOUCH DEVICE');
			$('.gallery_list').scrollbar();
		}
		// SET LISTENERS
		$('.gallery_item').bind('click', this.clickCollectionItem);
		$('.btn_closegallery').bind('click', this.closeGalleryButton);
		
		//TRIGGER SCROLL
		$(window).trigger(Events.Bon.SCROLL_TO_TOP);
	}
	
	this.findLastUpdatedContent = function (contents) {
		var key = 0;
		var latest = 0;
		for (var i=0; i<contents.length; i++) {
			if (contents[i].timestamp_modified > latest) {
				latest = contents[i].timestamp_modified;
				key = i;
			}
		}
		return contents[key].modified;
	}
	
	this.closeGalleryButton = function () {
		console.log('Gallery::closeGallery()');
		location.hash = '';
	}
	
	this.closeGallery = function () {
		console.log('Gallery::closeGallery()');
		//ON IPAD, REENABLE THE TWITTER FEED
		if($('html').hasClass('ipad')) {
			$('.twtr-tweets').show();
		}
		// RESTART POSTER
		$('.poster_container').trigger('posterAnimPlay.LANDING');
		
		that.container.parent().hide();
		that.container.html('');
		$(window).unbind('.GALLERY');
		$(window).unbind('.STRIP');
	}
	
	this.clickCollectionItem = function(e) {
		// UPDATE FRAGMENT DEPENDING ON GALLERY TYPE
		var frag = that.fragment().get();
		var collectionId = $(this).find('.collection_id').val();
		var collectionData = that.data.collections[collectionId];
		if(that.cfg.type == 'video') {
			frag.gid = collectionData.id;
			frag.vid = collectionData.contents[0].id;
		} else if (that.cfg.type == 'image') {
			frag.aid = collectionData.id;
			frag.gid = collectionData.contents[0].id;
			frag.pid = collectionData.contents[0].photos[0].pid;
		}
		console.log('Gallery::clickCollectionItem', collectionData);		
		that.fragment().set(frag);
		
		// HIDE THE GALLERY LIST
		$('.gallery_base').hide();
	}
	
	this.renderVideoPlayer = function (data) {
		// RENDER THE VIDEO PLAYER
		console.log('Gallery::renderVideoPlayer', data);
		data.close = this._('close');
		data.film = this._('film');
		data.image = this._('image');
		// SET NAVIGATION
		$('.gallery_player_container').html(this.templates.player().tmpl(data).clone());
		$('.btn_closeplayer').click(this.closePlayer);

		// SET THE CONTENT STRIP AND PLAYER
		this.strip = new Strip(data, that.cfg.type, that.cfg.lang);
		this.player = new VideoPlayer();
	}
	
	this.renderImagePlayer = function (data) {
		// RENDER THE IMAGE PLAYER
		console.log('Gallery::renderImagePlayer', data);
		data.close = this._('close');
		data.film = this._('film');
		data.image = this._('image');
		$('.gallery_player_container').html(this.templates.player().tmpl(data).clone());
		$('.btn_closeplayer').click(this.closePlayer);
		
		this.strip = new Strip(data, that.cfg.type, that.cfg.lang);
		this.player = new ImagePlayer();
	}
	
	this.closePlayer = function (e) {
		console.log('Gallery::closePlayer()', that.cfg.type, that.cfg.from);
		e.preventDefault();
		//UPDATE FRAGMENT, REMOVE GROUP ID and VIDEO ID
		var frag = that.fragment().get();
		if(that.cfg.type == 'video'){
			delete frag.gid;
			delete frag.vid;
			$(window).unbind('.VIDEOPLAYER');
		} else if(that.cfg.type == 'image') {
			delete frag.aid;
			delete frag.gid;
			delete frag.pid;
			$(window).unbind('.IMAGEPLAYER');
		}
		that.player = false;
		that.strip = false;
		$('.gallery_base').show();
		$('.gallery_player').remove();
		$(window).unbind('.PLAYER');
		$(window).unbind('.STRIP');
		// RESTORE ARTICLE IF IT CAME FROM IT
		if(that.cfg.from.go == 'article'){
			that.fragment().set(that.cfg.from);
		} else {
			that.fragment().set(frag);
		}
	}
	
	this.templates = {
		base : function () { return $( "#gallery_base_template" ) },
		gallery_item : function () { return $( "#gallery_item_template" ) },
		player: function () { return $("#gallery_player_template" ) }
	}
	
	this.init(_params);
	return this;
}



/* STRIP CLASS */
Strip = function (_data, _type, _lang) {
	Strip.prototype._					= function (text) { return Lang(text) };
	Strip.prototype.fragment			= FragmentParser;
	
	var that = this;
	this.data = _data;
	that.lang = _lang;
	that.type = _type;
	this.paginator = {};
	
	this.init = function () {
		console.log('Strip::init()', that.data, that.lang, that.type );
		this.data.stripTitlePrefix	= (that.type == 'video') ? that._('films_from') : that._('more_from');
		this.data.previous			= this._('previous');
		this.data.next				= this._('next');
		this.data.arrow_back_img	= (that.type == 'video') ? 'arrow_back.png' : 'arrow_back_whitebg.png';
		this.data.arrow_forward_img	= (that.type == 'video') ? 'arrow_forward.png' : 'arrow_forward_whitebg.png';
		$('.strip_container').html($('#strip_template').tmpl(this.data).clone());
		this.renderStrip();
		//this.showContent(0)
	}
	this.renderStrip = function () {
		// RENDER ITEMS
		var list_width = 0;
		for (var i=0; i<that.data.contents.length; i++) {
			str = 	'<li class="strip_item" style="width:218px; margin-right:27px;">\
						 <img src="'+that.data.contents[i].thumb+'" style="width:218px; height:118px; background:none;" />\
						 <input type="hidden" class="item_id" value="'+i+'" />\
						 <h5>'+that.data.contents[i].title+'</h5>\
					 </li>';
			$('.strip').find('ul').append(str);
			list_width += $(str).outerWidth(true);
		}
		$('.strip .list_container').width(list_width);
		// ADD LISTENERS TO LIST
		obj = this;
		$('.strip li').unbind('click.STRIP');
		$('.strip li').bind('click.STRIP', that, that.clickStripItem);
		// ADD LISTENERS TO PAGINATION
		$('.btn_strip_prev').unbind('click.STRIP');
		$('.btn_strip_prev').bind('click.STRIP', this.prevPage);
		$('.btn_strip_next').unbind('click.STRIP');
		$('.btn_strip_next').bind('click.STRIP', this.nextPage);
		// SET PAGINATION
		this.paginator.stripWidth = $('.list_wrap').width();
		this.paginator.currentPos = $('.list_container').position().left;
		this.paginator.currentPage = 1;
		this.paginator.totalPages = Math.ceil($('.list_container').width()/this.paginator.stripWidth);
		$('body').unbind(Events.Strip.PAGE_CHANGE);
		$('body').bind(Events.Strip.PAGE_CHANGE, this.paginatorHandler);
		that.updatePageCount();
	}
	this.paginatorHandler = function (e) {
		var pageChanged = false;
		if(e.action == 'next') {
			if(that.paginator.currentPage < that.paginator.totalPages){
				that.paginator.currentPage += 1;
				pageChanged = true;
			}
		} else {
			if(that.paginator.currentPage > 1){
				that.paginator.currentPage -= 1;
				pageChanged = true;
			}
		}
		if(pageChanged) {
			that.updatePageCount();
		}
		console.log('Strip::paginatorHandler', e, e.action);		
	}
	
	this.updatePageCount = function () {
		var pg = that.paginator;
		$('.list_container').animate({ left:(pg.currentPage-1)*-pg.stripWidth-(26*(pg.currentPage-1)) }, {queue:false, duration:1000});
		$('.page_count').html(this.paginator.currentPage+'/'+this.paginator.totalPages);
	}
	
	this.prevPage = function (e) {
		console.log('Strip::prevPage()');
		$('body').trigger($.Event(Events.Strip.PAGE_CHANGE, {action:'prev'}));
	}
	
	this.nextPage = function (e) {
		console.log('Strip::nextPage()');
		$('body').trigger($.Event(Events.Strip.PAGE_CHANGE, {action:'next'}));
	}
	
	this.clickStripItem = function (e) {
		var itemData = e.data.data.contents[Number($(this).find('.item_id').val())];
		var frag = that.fragment().get();
		if(that.type == 'video') {
			frag.gid = itemData.parent;
			frag.vid = itemData.id;
		} else if (that.type == 'image') {
			frag.gid = itemData.id;
			frag.pid = itemData.photos[0].pid;
			//delete frag.pid;
		}
		that.fragment().set(frag);
		console.log('Strip::clickStripItem()', itemData);
	}
	
	this.init();
};

/* VIDEO PLAYER */
VideoPlayer = function () {
	VideoPlayer.prototype.fragment			= FragmentParser;
		
	var that = this;
	
	init = function () {
		console.log('VideoPlayer::init');
	}
	
	this.src = function (src) {
		// RENDER NEW VIDEO HTML
		console.log('VideoPlayer::src', src);
		that.data = src;
		that.data.twitter_title = encodeURI(that.data.title+' - BON Magazine');
		$('.player_container').html($('#video_player_template').tmpl(that.data).clone());
		
		// UPDATE TITLE, TEXT, OTHER CONTENT & FRAGMENT
		$('.file_title').html(src.title);
		$('.info_container').html(src.description);
		if(!that.data.info) { $('.btn_info').hide(); }
		/*var frag = this.fragment().get();
		frag.vid = this.data.id;
		this.fragment().set(frag);*/
		
		// ADD LISTENERS TO EXTRA MENU BUTTONS: SHARE, EMBED & INFO
		$('.extra_buttons').bind(Events.VideoPlayer.SHOW_EXTRA, that.showExtra);
		$('.btn_share').click( function() {
			$('.extra_buttons').trigger( $.Event(Events.VideoPlayer.SHOW_EXTRA, {action:'share'}) ) 
		});
		
		$('.btn_embed').click( function() {
			$('.extra_buttons').trigger( $.Event(Events.VideoPlayer.SHOW_EXTRA, {action:'embed'}) ) 
		});
		
		$('.btn_info').click( function() {
			$('.extra_buttons').trigger( $.Event(Events.VideoPlayer.SHOW_EXTRA, {action:'info'}) ) 
		});
		
		// SETUP VIDEO PLAYER
		if(Modernizr.touch){
			// TOUCH DEVICES LEAVE PLAYER DEFAULT
			VideoJS.setupAllWhenReady({	});
		} else {
			VideoJS.setupAllWhenReady({
			  controlsBelow: true, // Display control bar below video instead of in front of
			  controlsHiding: false, // Hide controls when mouse is not over the video
			  defaultVolume: 0.85, // Will be overridden by user's last volume if available
			  flashVersion: 9, // Required flash version for fallback
			  linksHiding: true // Hide download links when video is supported
			});
		}
		
		//ANALYTICS TRACK EVENT DATA
		_gaq.push(['_trackEvent', 'Films', 'Load', location.hash+'>'+that.data.title]);
		
		return true;
	}
	
	this.listen = function (e) {
		console.log('VideoPlayer::listen', that, e);
		that.src(e.video);
	}
	
	this.showExtra = function (e) {
		//console.log('showExtra', e, that.data);
		switch(e.action) {
			case 'share':
				if($('.share_container').hasClass('hidden')){
					$('.extra_buttons .container').addClass('hidden');
				} 
				$('.share_container').toggleClass('hidden');
				break;
			case 'embed':
				if($('.embed_container').hasClass('hidden')){
					$('.extra_buttons .container').addClass('hidden');
				}
				$('.embed_container').toggleClass('hidden');
				break;
			case 'info':
				if($('.extrainfo_container').hasClass('hidden')){
					$('.extra_buttons .container').addClass('hidden');
				}
				$('.extrainfo_container').toggleClass('hidden');
				break;
			default:
				break;
		}
	}
		
	$(window).unbind(Events.VideoPlayer.SET_VIDEO_SOURCE);
	$(window).bind(Events.VideoPlayer.SET_VIDEO_SOURCE, this.listen);
	init();
	return this;
}

/* IMAGE PLAYER */
ImagePlayer = function () {
	ImagePlayer.prototype.fragment			= FragmentParser;
	var that = this;
	
	this.init = function () {
		console.log('ImagePlayer::init()');
	}
	
	this.src = function (_src, _photo) {
		console.log('ImagePlayer::src', _src);
		//debugger;
		that.data			= _src;
		that.data.thumblist = that.renderThumblist();
		that.data.info		= that.data.credits;
		/*
		<iframe class="social_item" src="${fb_share_url}send=false&amp;layout=standard&amp;width=230&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font&amp;height=62" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:230px; height:62px;" allowTransparency="true"></iframe>
		<iframe class="social_item" src="http://platform.twitter.com/widgets/tweet_button.html#count=vertical&amp;id=twitter_tweet_button_0&amp;lang=en&amp;url=${twitter_share_url}&amp;text=${twitter_title}" style="width:55px; height:62px;" allowtransparency="true" frameborder="0" scrolling="no" ></iframe>
		*/
		var template = $('#image_player_template').clone();
		
		if(_photo) {
			//that.data.fb_share_url		= _photo.fb_share_url;
			//that.data.twitter_share_url	= _photo.twitter_share_url;
			var fb_iframe = '<iframe class="social_item" src="'+_photo.fb_share_url+'send=false&amp;layout=standard&amp;width=230&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font&amp;height=62" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:230px; height:62px;" allowTransparency="true"></iframe>';
			var tw_iframe = '<iframe class="social_item" src="http://platform.twitter.com/widgets/tweet_button.html#count=vertical&amp;id=twitter_tweet_button_0&amp;lang=en&amp;url='+_photo.twitter_share_url+'&amp;text='+_photo.twitter_title+'" style="width:55px; height:62px;" allowtransparency="true" frameborder="0" scrolling="no" ></iframe>';
			that.data.social_iframes = fb_iframe+tw_iframe;
		} else {
			that.data.social_iframes = '';
		}
		
		$('.player_container').html(template.tmpl(that.data).clone());
		//$('.player_container').html($('#image_player_template').tmpl(that.data).clone());
		$('.image .thumb_display img').load(that.centerThumblist);
		$('.file_title').html(that.data.title);
		$('.info_container').html(that.data.description);
		
		$('.prev_image').bind('click', that.prevImage);
		$('.next_image').bind('click', that.nextImage);
		$('.current_image').bind('click', that.nextImage);
		$('.thumbitem').bind('click', that.gotoImage);
		$('.btn_thumbs').bind('click', that.showThumbs);
				
		if(_photo){
			// RENDER & GO TO PHOTO
			console.log('ImagePlayer::src -> photo', _photo);
			$('.current_image').html('<img src="'+_photo.imageURL+'" />');
			$('.current_image img').hide();
			$('.current_image img').load(function() {
				$(this).delay(500).fadeIn(2000);
			})
			$('.image_description').html(_photo.description);
			$('.current_image').hide();
			$('.current_image').fadeIn('fast');
			$('.thumb_display').hide();
			that.currentImage = _photo;
		} else {
			// DISPLAY THUMBNAILS
			console.log('ImagePlayer::src -> thumbs');
			$('.image .thumb_display').hide();
			$('.image .thumb_display').fadeIn('fast');
			$('.extra_buttons').hide();
		}
		
		if(!that.data.info) { $('.btn_info').hide(); }
		
		// ADD LISTENERS TO EXTRA MENU BUTTONS: SHARE, EMBED & INFO
		$('.extra_buttons').bind(Events.Player.SHOW_EXTRA, that.showExtra);
		$('.btn_share').click( function() {
			$('.extra_buttons').trigger( $.Event(Events.Player.SHOW_EXTRA, {action:'share'}) ) 
		});
				
		$('.btn_info').click( function() {
			$('.extra_buttons').trigger( $.Event(Events.Player.SHOW_EXTRA, {action:'info'}) ) 
		});
		//ANALYTICS
		_gaq.push(['_trackEvent', 'Photos', 'Load', location.hash+'>'+that.data.title]);
	}
	
	this.showExtra = function (e) {
		//console.log('showExtra', e);
		switch(e.action) {
			case 'share':
				if($('.share_container').hasClass('hidden')){
					$('.extra_buttons .container').addClass('hidden');
				} 
				$('.share_container').toggleClass('hidden');
				break;
			case 'info':
				if($('.extrainfo_container').hasClass('hidden')){
					$('.extra_buttons .container').addClass('hidden');
				}
				$('.extrainfo_container').toggleClass('hidden');
				break;
			default:
				break;
		}
	}
	
	this.renderThumblist = function () {
		//console.log('Thumblist', that.data.photos);
		var temp = '';
		var thumbsize = (that.data.photos.length > 20) ? 'small' : '';
		$(that.data.photos).each(function () {
			temp += '<li class="thumbitem '+thumbsize+'"><input type="hidden" name="pid" value="'+this.pid+'"><img src="'+this.thumbURL+'" /></li>';
		});
		return temp;
	}
	
	this.centerThumblist = function (e) {
		// CENTER THUMBNAILS WHEN IMAGES GET LOADED
		$('.image .thumb_display ul').vAlign();
	}
	
	this.showThumbs = function () {
		var frag = that.fragment().get();
		delete frag.pid;
		that.fragment().set(frag);
		//$('.image_player .main_display').hide();
		//$('.thumb_display').show();
	}
	
	this.gotoImage = function (e) {
		var frag = that.fragment().get();
		var pid = $(e.currentTarget).find('input[name=pid]').val();
		frag.pid = pid;
		console.log('gotoImage', frag, pid, e);
		//$('.current_image').fadeOut('fast');
		that.fragment().set(frag);
	}
	
	
	this.prevImage = function (e) {
		console.log('ImagePlayer::prevImage()');
		that.switchImage('prev');
	}
	
	this.nextImage = function (e) {
		console.log('ImagePlayer::nextImage()', that.data);
		that.switchImage('next');
	}
	
	this.switchImage = function (action) {
		console.log('ImagePlayer::switchImage()', that.data);
		var frag = that.fragment().get();
		var data = that.data;
		var currentIndex = false;
		for(var i=0; i<data.photos.length; i++){
			if(data.photos[i].pid == frag.pid){
				currentIndex = i;
				console.log('photofound', i);
			}
		}
		if(action == 'next' && currentIndex < data.photos.length-1){
			frag.pid = data.photos[currentIndex+1].pid;
			console.log('frag', frag);
			$('.current_image img').fadeOut('fast');
			setTimeout(function () {that.fragment().set(frag)}, 500);
		}
		
		if(action == 'prev' && currentIndex > 0){
			frag.pid = data.photos[currentIndex-1].pid;
			console.log('frag', frag);
			that.fragment().set(frag);
		}
	}
	
	this.listen = function (e) {
		console.log('ImagePlayer::listen', that, e);
		if(e.photo){
			that.src(e.gallery, e.photo);
		} else {
			that.src(e.gallery);
		}
		
	}
	
	$(window).unbind(Events.ImagePlayer.SET_GALLERY);
	$(window).bind(Events.ImagePlayer.SET_GALLERY, this.listen);
	this.init();
	return this;
}



