gallery_viewer = {};

lang.gviewer = {
	'es':{'startslides':"Inicia Presentación",
		   'stopslides':"Detener Presentación"
		  },
	'en':{'startslides':"Start Slideshow",
		  'stopslides':"Stop Slideshow"
		  }
};

GalleryViewerComponent = Class.create();
GalleryViewerComponent.prototype = {
	
	initialize: function(id, app, options) {
		
		this.id 			= id;
		this.self 			= $(this.id);
		this.app     		= app;
		this.options		= options || {};
		
		this.title 			= $(this.id + '_title');
		this.media 			= $(this.id + '_media');
		this.media_inner	= $(this.id + '_media_inner');
		this.details 		= $(this.id + '_details');
		

		//if(console) console.log("Gallery Viewer Type: "+ this.options.type);
		
		updaters[this.id] = new Updater(this.id, this.app, '', {parent:this});
		this.updater = updaters[this.id];
		
		if (this.options.type != 'flash'){
			this.btn 			= {};
			this.btn.prev	 	= $(this.id + '_btn_prev');
			this.btn.next	 	= $(this.id + '_btn_next');
			this.btn.close 		= $(this.id + '_btn_close');
			this.btn.download 	= $(this.id + '_btn_download');
			
			this.prev_id = 0;
			this.next_id = 0;	
			
			this.show_id = null;
			this.pieces = [];
			this.cur_piece = 0;
			this.p_ob = {};
			this.piece_id = 0;
			
			this.timer = null;
			this.slide_show = false;

			this.injectBehaviours();
		}else {
			this.fob = $(this.id + '_object');
			this.content_border = $(this.id + '_content');
			
			if (browser.isIE) {
				var w = parseInt(this.content_border.style.width.replace('px', ''));
				var pad = parseInt(this.content_border.style.padding.replace('px', ''));
				this.content_border.style.width = (w+(pad*2)) + 'px';
			}
			
			var me = this;
			page_init.scripts[this.id] = function() {
				screen_overlay.register(me);
				me.onPageLoad();
			};	
			
		}
	},
	
	displayShow: function() {
		this.fob.displayShow();	
	},
	
	loadItem: function(str, video) {
		this.fob.loadItem(str, video);	
	},
	
	onPageLoad: function() {
		this.description = $('displayDescription');
		this.gallery_details = $('displayShow');
		this.media_details = $('displayMedia');
		
		this.btn.slide_show = btns[this.id+'_btn_slide_show'];
		
		//if (console) console.log('SHOWS: '+this.shows+', MEDIA: '+this.media);
	},
	
	getShows: function() {
		this.fob.initialize(this.options);
		this.updater.run(['gallery_id='+this.options.gallery], 'GetShows', '');	
	},
	
	setGallerySize: function(to, display, show) {
		
		if (display) { var w = 825; } else { var w = 545; }
				
		if (browser.isIE) {
			var pad = parseInt(this.content_border.style.padding.replace('px', ''));
			var perc = ((to+(pad*2))/w)*100;	
		} else {
			var perc = (to/w)*100;	
		}
		
		if (display) {
			var effect2 = new Effect.Scale(this.content_border, perc, {duration:0.5, scaleY:false, scaleContent:false, afterFinish:this.showDetails, me:this, show:show});
		} else {
			this.description.style.display = 'none'; 
			
			var me = this;
			var effect3 = new Effect.BlindUp(this.media_details, {duration:0.5, afterFinish:function() {
																								  var effect4 = new Effect.BlindDown(me.gallery_details, {duration:0.5});
																								  }});
			var effect2 = new Effect.Scale(this.content_border, perc, {duration:0.5, scaleY:false, scaleContent:false});
		}
		
		
	},
	
	showDetails: function(ob) {
		//var effect = new Effect.BlindDown(ob.options.me.description, {duration:0.5});
		ob.options.me.description.innerHTML = '';
		ob.options.me.description.style.display = '';
		var effect2 = new Effect.BlindUp(ob.options.me.gallery_details, {duration:0.5});
		ob.options.me.updater.run(['show_id='+ob.options.show,'comp_id='+ob.options.me.id], 'Show', '');	
	},
	
	injectBehaviours: function() {
		
		this.btn.prev.onmouseover = this.btnOver.bindAsEventListener(this, this.btn.prev);
		this.btn.prev.onmouseout = this.btnOut.bindAsEventListener(this, this.btn.prev);
		this.btn.prev.onclick = this.btnClick.bindAsEventListener(this, 'prev');
		
		this.btn.next.onmouseover = this.btnOver.bindAsEventListener(this, this.btn.next);
		this.btn.next.onmouseout = this.btnOut.bindAsEventListener(this, this.btn.next);
		this.btn.next.onclick = this.btnClick.bindAsEventListener(this, 'next');
		
		this.btn.close.onmouseover = this.btnOver.bindAsEventListener(this, this.btn.close);
		this.btn.close.onmouseout = this.btnOut.bindAsEventListener(this, this.btn.close);
		this.btn.close.onclick = this.btnClick.bindAsEventListener(this, 'close');
		
	},
	
	open: function (piece, show, use_type) {
		screen_overlay.show();
		screen_overlay.parent = this;	
		
		if (this.show_id == show) {
			if (piece != this.piece_id) {
				var piece = this.findPiece(piece);
				this.switchTo(piece);	
			}
			this.show();
		} else {
			this.show_id = show;
			this.loadPiece(piece, show, use_type);
		}
	},
	
	
	findPiece: function(piece) {
		//if (console) console.log('LOOKING FOR PIECE: '+piece+' IN '+this.pieces.length+' PIECES');
		for(var i=0; i<this.pieces.length; ++i) {
			if (this.pieces[i].id == piece) return this.pieces[i];
		}
	},
	
	switchTo: function(piece, force) {
		
		if (this.p_ob.id) {
					
			if ((piece.width == this.p_ob.width && piece.height == this.p_ob.height) || force) {
			
				if (console) console.log('SWITCHING TO LOADED');
			
				this.details.innerHTML = piece.title;
				
				if (piece.download && typeof(this.btn.download) !== 'undefined') {
					this.btn.download.onclick = function() {self.location = piece.download;};
				}
							
				if (force) { 
					//if (console) console.log('RUNNING ENTRY AFTER RESIZE');
					this.media_inner.innerHTML = piece.media;
					if (browser.isSafari) {
						Element.show(this.media_inner);
					} else {
						var effect = new Effect.Appear(this.media_inner, {duration:0.5});
					}
				} else {
					//if (console) console.log('RUNNING STRAIGHT SWITCH');
					if (browser.isSafari) {
						this.media_inner.innerHTML = piece.media;
					} else {
						var me = this;
						var effect = new Effect.Fade(this.media_inner, {duration:0.5, afterFinish:function() {me.media_inner.style.display = 'none';
																												  me.media_inner.innerHTML = piece.media;
																												  var effect2 = new Effect.Appear(me.media_inner, {duration:0.5});}
																						});	
					}
				}
				
				this.cur_piece = piece.order;
				this.p_ob = piece;
				this.piece_id = piece.id;
							
			} else {
				if (console) console.log('SWITCHING TO LOADED 2');
				if (!browser.isSafari) var effect = new Effect.Fade(this.media_inner, {duration:0.5});	
				this.resizeWindow(piece);
			}
		} else {
			
			if (console) console.log('SWITCHING TO NEW');
		
			this.details.innerHTML = piece.title;
			this.media.style.width = piece.width+'px';
			this.media.style.height = piece.height+'px';
			this.media_inner.style.display = 'none';
			this.media_inner.innerHTML = piece.media;
			if (piece.download && typeof(this.btn.download) !== 'undefined') {
				this.btn.download.onclick = function() {self.location = piece.download;};
			}
			var effect = new Effect.Appear(this.media_inner, {duration:0.5});
			this.cur_piece = piece.order;
			this.p_ob = piece;
			this.piece_id = piece.id;
		}
		
		
	},
	
	resizeWindow: function(piece) {
		
		var w = piece.width;
		var h = piece.height;
		
		var p = this.p_ob;
				
		var o_width = p.width;
		var o_height = p.height;
		
		var scaleX = w/o_width * 100.0;
		var scaleY = h/o_height * 100.0;
		
		var x = (o_width - w)/2;
		
		var y = (o_height - h)/2;
							   
		if (console) console.log('SCALING FROM: '+o_width+'x'+o_height+', SCALE TO: '+w+'x'+h);
		
		if (console) console.log('MOVING TO: '+x+', '+y);
		
		if (browser.isSafari) {
			this.media.style.width = w + "px";
			this.media.style.height = h + "px";
			var dims = {};
			dims.width = parseInt(w) +  this.options.interfaceWidth;
			dims.height = parseInt(h) +  this.options.interfaceHeight;
			ApexUtil.centerOnScreen(this.self, dims);
			gallery_viewer.switchTo(piece, true);
		} else {
			var effects = [];
			effects.push(new Effect.Scale(this.media, scaleX, {scaleY:false, scaleFromCenter:true, scaleMode:{originalWidth:o_width, originalHeight:o_height}}));
			effects.push(new Effect.Scale(this.media, scaleY, {scaleX:false, scaleFromCenter:true, scaleMode:{originalWidth:o_width, originalHeight:o_height}}));
			effects.push(new Effect.MoveBy(this.self, y, x));
			var effect = new Effect.Parallel(effects, {duration:0.5, afterFinish:function() {gallery_viewer.switchTo(piece, true);}});
		}

		/*var effect = new Effect.Scale(this.media, scaleX, {duration:0.5, scaleY:false, scaleFromCenter:true, scaleMode:{originalWidth:o_width, originalHeight:o_height}, 
									  						afterFinish:function() {gallery_viewer.switchTo(piece, true);} });
		var effect2 = new Effect.Scale(this.media, scaleY, {duration:0.5, scaleX:false, scaleFromCenter:true, scaleMode:{originalWidth:o_width, originalHeight:o_height}});
		var effect3 = new Effect.MoveBy(this.self, y, x, {duration:0.5});*/
	},
	
	show: function(fromOverlay) {
		
		if (fromOverlay) {
			this.self.style.visibility = '';
		} else {
			if (console) console.log('SHOWING SLIDE');
			this.self.style.visibility = 'hidden';
			this.self.style.display = '';
			var dims = {};
			dims.width = parseInt(this.p_ob.width) +  this.options.interfaceWidth;
			dims.height = parseInt(this.p_ob.height) +  this.options.interfaceHeight;
			ApexUtil.centerOnScreen(this.self, dims);
			this.self.style.display = 'none';
			this.self.style.visibility = '';
			var effect = new Effect.Appear(this.self.id, {duration:0.5});				
		}
		
		this.toggleSlideShow();	
	},
	
	hide: function(fromOverlay) {
		if (this.self) {
			if (this.slide_show) this.stopSlideShow();
			if (fromOverlay) {
				this.self.style.visibility = 'hidden';
			} else {
				this.self.style.display = 'none';
			}
		}
	},
	
	loadPiece: function(piece, show, use_type) {
		
		this.pieces = [];
		this.media_inner.innerHTML = '';
		this.details.innerHTML = '';
		this.title.innerHTML = '';
		
		var callParams = [];
		callParams.push('piece_id=' + piece);
		
		if (use_type) {
			this.piece_id = piece;
			callParams.push('type='+show);
			callParams.push('for_viewer=true');
			updaters[this.id].callService('gallery.getPieces', callParams, '');
		} else {
			if (this.options.type != 'flash') {
				this.piece_id = piece;
				callParams.push('s=' + show);
			}
			updaters[this.id].run(callParams, '');
		}
		
	},
	
	ajaxUpdate: function(ajaxResponse) {
		
		if (this.options.type != 'flash') {
						
			var pieces = ajaxResponse.getElementsByTagName('piece');
			var show_title = ajaxResponse.getElementsByTagName('title')[0];
			
			for(var i=0; i<pieces.length; ++i) {
				var p = pieces[i];
				//if (console) console.log('PIECE:'+typeof(p));
				var title = p.getElementsByTagName('title')[0];
				var rating = p.getElementsByTagName('rating')[0];
				var media = p.getElementsByTagName('media')[0];
				var ob = {'order':i,
						   'id':parseInt(p.getAttribute('id')),
						   'title':RicoUtil.getContentAsString(title),
						   'rating':rating.getAttribute('overall'),
						   'vote':rating.getAttribute('vote'),
						   'media':RicoUtil.getContentAsString(media),
						   'download':media.getAttribute('download'),
						   'width':media.getAttribute('width'),
						   'height':media.getAttribute('height')
							};
				this.pieces.push(ob);
				if (this.piece_id == ob.id) this.cur_piece = i;
			}			
			
			this.title.innerHTML = RicoUtil.getContentAsString(show_title);
			
			this.switchTo(this.pieces[this.cur_piece]);
			
			this.show();
		
		} else {
			var field_test = ajaxResponse.getElementsByTagName('field')[0];
			if (field_test) {
				this.updater.update(ajaxResponse);
			} else {
				var items = ajaxResponse.getElementsByTagName('item');
				if (items) {
					var shows = [];
					for(var i=0; i < items.length; ++i) {
						var s = {toolTip:items[i].getAttribute('toolTip'), 
									image:items[i].getAttribute('image'),
									id:items[i].getAttribute('id'),
									pieces:[]};
						
						var pieces = items[i].getElementsByTagName('piece');
						if (pieces) {
							for(var j=0; j<pieces.length; ++j) {
								s.pieces.push({file:pieces[j].getAttribute('file'),
											   download:pieces[j].getAttribute('download'),
											   code:pieces[j].getAttribute('code')});
							}
						}
						
						shows.push(s);	
					}
					this.shows = shows;
					this.fob.loadShows(this.shows);
				}
			}
				
		}
	},
	
	btnOver: function(e, src) {
		if (src) {
			src.style.cursor = 'pointer';
			src.className = ApexUtil.addClass(src, 'on');
		}
	},
	
	btnOut: function(e, src) {
		if (src) {
			src.style.cursor = '';
			src.className = ApexUtil.removeClass(src, 'on');
		}
	},
	
	btnClick: function(e, key) {
		
		switch(key) {
			case 'close':
				screen_overlay.hide();
				this.stopSlideShow();
				break;
			case 'prev':
				this.stopSlideShow();
				if (this.cur_piece > 0) {
					var target = this.pieces[this.cur_piece-1];
					this.switchTo(target);
				}
				break;
			case 'next':
				//if (console) console.log('NEXT ITEM');
				clearInterval(this.timer);
				if (this.cur_piece < this.pieces.length-1) {
					if (this.slide_show) this.startSlideShow();
					var target = this.pieces[this.cur_piece+1];
					this.switchTo(target);
				} else {
					if (this.slide_show) this.stopSlideShow();	
				}
				break;
		}
		
	},
	
	getMaxLimits: function() {
		var w = this.options.interfaceWidth;
		var h = this.options.interfaceHeight;
		
		var sw = screen_overlay.arrayPageSize[2];
		var sh = screen_overlay.arrayPageSize[3];
		
		var limits = {};
		
		limits.width = sw - w - this.options.margin;
		limits.height = sh - h - this.options.margin;
		
		return limits;

		
	},
	
	toggleSlideShow: function() {
		if (this.slide_show) {
			this.stopSlideShow();
		} else {
			this.startSlideShow();
		}
	},
	
	startSlideShow: function() {
		this.timer = setInterval(this.btnClick.bindAsEventListener(this, 'next'), 6000); 
		this.slide_show = true;
		
		if (btns[this.id+'_btn_slide_show']) {
			btns[this.id+'_btn_slide_show'].label.innerHTML = lang.gviewer[cur_lang].stopslides;	
		}
		
	},
	
	stopSlideShow: function() {
		clearInterval(this.timer);
		this.slide_show = false;
		if (btns[this.id+'_btn_slide_show']) {
			btns[this.id+'_btn_slide_show'].label.innerHTML = lang.gviewer[cur_lang].startslides;	
		}
		
	}
	
	
	
};