Enjin_Gallery = function(params) {
	this.init(params);
}


Enjin_Gallery.__instances = {};
Enjin_Gallery.getInstance = function(preset_id) {	
	return Enjin_Gallery.__instances[preset_id];
}

Enjin_Gallery.__DEFAULT_EDIT_TEXT = 'Type image caption here';

Enjin_Gallery.prototype = {
	main_el: null,
	el_container: null,
	preset_id: null,
	thumb_width: 180,
	border_width: 0,
	thumbs_per_row: 0,
	thumb_scale_width: 0,
	thumb_scale_height: 0,
	numbers_row: 0,
	images_pending: null,
	images_processed: null,	
	images_processed_index: null,	
	pages: null,
	current_page: null,
	detail_url: null,
	popup_window: null,
	thumb_width: null,
	thumb_height: null,
	//el_popup: null,
	//edit_image_id: null,
		
	init: function(params) {
		var defparams = {
			preset_id: 0,
			numbers_row: 4,
			detail_url: null,
			thumb_width: 285,
			thumb_height: 200
		}		
		$.extend(defparams, params);

		var self = this;
		Enjin_Gallery.__instances[defparams.preset_id] = this;
		
		this.detail_url = defparams.detail_url;
		this.preset_id = defparams.preset_id;
		this.images_processed = {};
		this.images_processed_index = 0;		
		this.images_pending = this.getImages().concat([]); //copy of array
		
		this.border_width = 5;
		this.el_container = $('.m_gallery_'+defparams.preset_id+' .section-full .block-container-images .items');
		this.main_el = $('.m_gallery_'+defparams.preset_id+' .section-full');
		
		this.main_el.show();
		this.numbers_row = defparams.numbers_row;
		this.thumb_width = defparams.thumb_width;
		this.thumb_height = defparams.thumb_height;
		this.params = defparams;
		//this.el_popup = $('.m_gallery-image-edit-caption');
				
		this.current_page = 1;
		this.prepareImages();		
		
		$(window).bind('resize', function(event) {
			self.updateGrid();
		});
/*
		$('.m_gallery-image-edit-caption input[type=text]').bind('focus', function(event) {
			if ($('.m_gallery-image-edit-caption').data('default_text'))
				$(event.target).val('');
			
		});		
		$('.m_gallery-image-edit-caption input[type=text]').bind('keydown', function(event) {
			$('.m_gallery-image-edit-caption').data('default_text', false);
		});
		
		$(document).bind('click', function(event) {
			if (self.edit_image_id) {
				if ($(event.target).closest('.m_gallery-image-edit-caption').length == 0) {
					event.stopPropagation();
					event.preventDefault();
					
					self.saveEdit();
				}
			}
		});*/
	},
	
	calcGrid: function() {
		//console.log("AV: "+this.el_container.width());
		var available_width = this.el_container.width();
		
		this.thumbs_per_row = Math.ceil((available_width - this.border_width) / (this.thumb_width + this.border_width));
		this.thumb_scale_width = (available_width - (this.border_width * (this.thumbs_per_row))) / this.thumbs_per_row;
		this.thumb_scale_width = Math.floor(this.thumb_scale_width);
		/*console.log("THUMBS_PER_ROW: "+this.thumbs_per_row);
		console.log("thumb_scale_width: "+this.thumb_scale_width);*/
	},
	
	prepareGrid: function() {
		//we need to check if the new size will 
		//genereate scrollbars, so re-calculate		
		this.calcGrid();
		
		var ratio = (this.thumb_scale_width*1.0) / this.thumb_width;
		this.thumb_scale_height = Math.floor(this.params.thumb_height * ratio);
						
		var docwidth = $(document).width();
		var number_rows = Math.ceil(this.getImages().length / this.thumbs_per_row);
		var containerheight = this.thumb_height * ratio * number_rows;
		
		/*console.log("HEIGHT: "+ this.thumb_height)
		console.log("RATIO: "+ratio);
		console.log("CONTHEIGHT: "+containerheight);		
		console.log("NUMBER_ROWS: "+number_rows);
		console.log("CHECK: "+docwidth);*/
		$('.m_gallery_'+this.preset_id+' .items').css('height', containerheight);
		//console.log("CHECK2: "+$(document).width());
		
		if ($(document).width() < docwidth) {
			this.calcGrid();
		}
		$('.m_gallery_'+this.preset_id+' .items').css('height', 'auto');
	},
	
	updateGrid: function() {
		var self = this;
		
		this.prepareGrid();
		jQuery.each(this.images_processed, function(image_id, el) {
			$(el).find('.cimage img').css('width', self.thumb_scale_width);
			
			
			$(el).find('.cimage').css('width', self.thumb_scale_width);
			$(el).find('.cimage').css('height', self.thumb_scale_height);
		});		
	},
	
	prepareImages: function() {
		var self = this;
		var remain = 0;		
		var images = this.getImages();
		
		//calculate size
		this.prepareGrid();
		this.images_processed = {};
		this.images_processed_index = 0;
		
		this.el_container.html('');
		if(images.length == 0) this.el_container.html(this.getEmptyMessage());		
		remain = images.length;
		this.addBatchImages(remain);
		
		this.updateGrid();
		
		//add sortable
		if (this.params.can_admin_album) {
			//show sortable
			this.el_container.sortable({
				items: '.image',
				handle: '.sortable-handler',
				stop: function(event, ui) {
					//enable simpletip
					var image_id = ui.item.attr('imageid');
					self.simpletipEnable(image_id, true);
				
					self.updateOrdering(); 
				},
				start: function(event, ui) {
					//disable simpletip
					var image_id = ui.item.attr('imageid');
					self.simpletipEnable(image_id, false);						
				}
			});
		}
	},
	
	simpletipEnable: function(image_id, value) {
		var stip = this.el_container.find('.image-'+image_id+' .cimage').data('simpletip');
		stip.enable(value);
		if (!value)
			stip.hide();
	},	
	
	updateOrdering: function() {
		var data = {
			op: 'image-save-ordering',
			preset_id: this.preset_id,
			album_id: this.params.album_id,
			ordering: {}
		};
		var items = {};
		var index = 0;
		
		this.el_container.find('.image').each(function() {
			var el = $(this);
			data.ordering[el.attr('imageid')] = index;
			index++;
		});
		
		$.post('/ajax.php?s=gallery', data, function(response) {});
	},
	
	
	addBatchImages: function(remain) {
		var keep_adding = true;
		var image;
		
		if (this.images_pending.length < 1)
			return; //nothing to do
		
		do {
			//console.log("REMAIN: "+remain+" -- "+this.thumbs_per_row+" -- "+this.numbers_row);
			image = this.images_pending.shift();
			this.addImage(image);
			if (this.images_pending.length < 1)
				keep_adding = false; //no more elements
						
			remain--;			
			if (remain < 1)
				keep_adding = false; //showed a page
			
		} while(keep_adding);		
	},
	
	move: function(image_id) {
		var album_id = this.params.album_id;
		var el = $('.m_gallery.album-change select')[0];
		el.options.length = 0;
		jQuery.each(this.params.albums, function(key, value) {
			if (key != album_id)
				el.options[el.options.length] = new Option(value, key);
		});
		
		$('.m_gallery.album-change').data('image_id', image_id);
		Enjin_Core.showCustomPopup('.m_gallery.album-change');
	},
	
	doMove: function() {
		var album_id = $('.m_gallery.album-change select').val();
		
		if (album_id != this.params.album_id) {
			var image_id = $('.m_gallery.album-change').data('image_id');
			var data = {
				op: 'image-move',
				image_id: image_id,
				album_id: album_id,
				preset_id: this.preset_id
			}
						
			this.removeImage(image_id);
			
			$.post("/ajax.php?s=gallery", data, function(response) {});			
		}
		Enjin_Core.hideCustomPopup($('.m_gallery.album-change'));
	},
	
	cancelMove: function() {
		Enjin_Core.hideCustomPopup($('.m_gallery.album-change'));
	},
	
	doEdit: function(event, image_id) {
		Enjin_Gallery_Common.setEditCallback(this, this.onEdited);
		Enjin_Gallery_Common.detailEditShow(this.preset_id, image_id, {
			event: event,
			parent_wrap: true,
			offset_top: 10
		});
	},
	
	/*editImage: function(event, image_id) {
		if (event)
			event.stopPropagation();
		
		//show popup
		var self = this;
		var preset_id = this.preset_id;
		var el_container = this.el_container.closest('.m_gallery-album');
		var el_image = this.el_container.find('.image-'+image_id+' .cimage');
		var el_popup = this.el_popup;
		var py = el_image.offset().top - el_container.offset().top + (el_image.height() - el_popup.height())*0.5;
		var px = el_image.offset().left - el_container.offset().left + el_popup.width()*0.5;
		var image = Enjin_Gallery_CommonImages.getInstance(preset_id).getImage(image_id);
		
		if ($.trim(image.title) == '') {
			el_popup.find('input[type=text]').val(Enjin_Gallery.__DEFAULT_EDIT_TEXT);
			el_popup.data('default_text', true);
		} else {
			el_popup.find('input[type=text]').val(image.title);
			el_popup.data('default_text', false);
		}
		el_popup.css('top', py);
		el_popup.css('left', px);
		el_popup.show();
		this.edit_image_id = image_id;
		
		//force focus
		$('.m_gallery-image-edit-caption input[type=text]').focus();
	},
	
	saveEdit: function() {
		$('.m_gallery-image-edit-caption input[type=text]').unbind('blur');
		
		var title = $.trim(this.el_popup.find('input[type=text]').val());
		if (this.el_popup.data('default_text'))
			title = '';
		
		var data = {
			op: 'image-edit',
			preset_id: this.preset_id,
			image_id: this.edit_image_id,
			title: title
		};
		this.el_popup.removeData('default_text');
		Enjin_Gallery_CommonImages.getInstance(this.preset_id).updateImageParams(this.edit_image_id, {
			title: title
		});
		this.onEdited(this.preset_id, this.edit_image_id, title);
		
		$.post("/ajax.php?s=gallery", data, function(response) {});
		this.edit_image_id = null;
		this.el_popup.hide();		
	},*/
	
	onEdited: function(preset_id, image_id, title, description) {
		//update simpletip
		var stip = this.el_container.find('.image-'+image_id+' .cimage').data('simpletip');
		if (stip)
			stip.update('<div class="inner">'+Enjin_Core.htmlentities(title)+'</div>');		
	},
	
	newImage: function(image) {
		this.addImage(image);
		this.el_container.sortable("refresh");
	},
	addImage: function(image, prepend) {
		if (image == undefined || !image.number_comments)
			image.number_comments = 0;
		
		if(this.el_container.find('.no-pictures').length != 0) this.el_container.html('');
		
		var url = this.detail_url.replace('ALBUMID', image.album_id);	
		url += '#pid='+image.image_id;
		
		var html_image = '<div imageid="'+image.image_id+'" class="image image-'+image.image_id+'">';
		
		html_image += '<div class="cimage"><a href="'+url+'">';			
		html_image += '<img src="'+image.url+'" style="width: '+this.thumb_scale_width+'px; " /></a></div>';
		if (image.number_comments > 0)
			html_image += '<div class="number-views"><a href="'+url+'">'+image.number_comments+'</a></div>';
		
		//check if can add admin links
		if (this.params.can_admin_album || this.params.cuid == image.user_id) {
			html_image += '<div class="admin-links">';
			html_image += '<div class="item-link item-link-single">';
			html_image += '<a href="javascript:void(0);" onclick="Enjin_Gallery.getInstance('+this.preset_id+').doEdit(event, '+image.image_id+')">Edit</a>';
			html_image += '&nbsp;&middot;&nbsp;';			
			html_image += '<a href="javascript:void(0);" onclick="Enjin_Gallery.getInstance('+this.preset_id+').confirmDelete('+image.image_id+');">Delete</a>';
			html_image += '</div>';
			
			if (this.params.can_admin_album) {
				html_image += '<div class="item-link item-link-single">&nbsp;&middot;&nbsp;';			
				html_image += '<a href="javascript:void(0);" onclick="Enjin_Gallery.getInstance('+this.preset_id+').move('+image.image_id+');">Move</a>';
				html_image += '&nbsp;&middot;&nbsp;</div>';
				
				//add sortable
				html_image += '<div class="item-link"><a class="sortable-handler" href="javascript:void(0);"><img src="'+this.params.move_icon+'" /></a></div>';				
			}
			html_image += '</div>';
		}		
		
		html_image += '</div>';
		
		if (prepend) {
			//new image
			this.el_container.prepend(html_image);
		} else {
			this.el_container.append(html_image);
		}
				
		//parse with the jquery tooltip
		this.el_container.find('.image-'+image.image_id+' .cimage').simpletip({ 
			content: '<div class="inner">'+image.title+'</div>',
			baseClass: 'element_popup m_gallery tooltip',
			offset: [10, 10],
			fixed: false,
			showEffect: "none", 
			hideEffect: "none",
			onShow: function() {
				if (!this.updatepos) {
					this.updatepos = true;
					this.getTooltip().appendTo($(document.body));
				}
			}
		});

		
		this.images_processed[image.image_id] = this.el_container.find('.image-'+image.image_id);
		this.images_processed_index++;		
	},
	
	confirmDelete: function(image_id) {
		var self = this;
		Enjin_Gallery_Common.confirmDelete(this.preset_id, image_id, function(image_id, response) {
			self.removeImage(image_id);
		}, true);
	},
	
	openImagePopup: function(image_id) {
		if (this.popup_window)
			this.popup_window.close();
		
		var url = '/popup/m/'+this.preset_id+'/detail/'+image_id;
		this.popup_window = window.open(url,'gallery_detail','location=0,status=0,scrollbars=1,resizable=0,menubar=0,height=720,width=830');
	},
	
	removeImage: function(image_id) {
		Enjin_Gallery_CommonImages.getInstance(this.preset_id).removeImage(image_id);
		
		//remove small images
		this.el_container.find('.image-'+image_id).remove();
		this.images_processed_index--;
		
		this.updateGrid();	
		if(this.getImages().length == 0) this.el_container.html(this.getEmptyMessage());		
	},
	
	getImages: function() {
		return Enjin_Gallery_CommonImages.getInstance(this.preset_id).getImages();
	},
	
	getEmptyMessage: function() {
		return '<div class="no-pictures">There are no images in this gallery. Start uploading images.</div>';
	}
};



