(function(){
/**
 *
 */
var Y = YAHOO, YU = Y.util, YL = Y.lang;
YAHOO.namespace('app').
	gallery = function(){
		
		var Dom = YAHOO.util.Dom,
			Event = YAHOO.util.Event,
			Connect = YAHOO.util.Connect,
			selectedCell,
			oDialog, menu,
			urls = {
						edit: '/gallery/images/view/',
				generate: '/gallery/images/regenerate_thumbnails/',
					resize: '/gallery/images/resize/'
			};
			
		
		/*
				"contextmenu" event handler for the element(s) that
				triggered the display of the ContextMenu instance - used
				to set a reference to the GridCell instance that triggered
				the display of the ContextMenu instance.
		 */
		
		function onTriggerContextMenu(p_oEvent) {
			
			var oTarget = this.contextEventTarget;
			
			selectedCell = oTarget;
			if (!Dom.hasClass(selectedCell, 'grid-cell')) {
				selectedCell = Dom.getAncestorByClassName(selectedCell, 'grid-cell');
			}
			
		};
		
		
		
		function gotoEditPage() {
			var oLink = selectedCell.getElementsByTagName('a')[0];
						
			document.location = oLink.href;
		};
		
		
		
		function regenerateThumbnail() {
			var oImg = selectedCell.getElementsByTagName('img')[0];
			
			Connect.asyncRequest('GET', urls.generate + selectedCell.id, {
				success: function() {
					oImg.src = oImg.src + '?regen';
				}
			});
		};
		
		
		function forceImageReload(img) {
			img.src = img.src + '?reload='+Math.random(100,200);
		};
		
		
		
		/**
		 * @constructor
		 * @param {String/HTMLElement} el HTMLElement reference
		 * @param {Object} config Object literal of configuration parameters
		 */
		var ImageResizer = function(el, config) {
			if (arguments) {
				ImageResizer.prototype.init.call(this, el, config);
			}
		};
		
		Y.extend(ImageResizer, YU.Element, {
			/**
			 * Instance of ImageCropper utility.
			 * 
			 * @type {YAHOO.widget.ImageCropper}
			 * @private
			 */
			_oImgCropper: null,
			
			/**
			 * ratio to use for ImageCropper instance.
			 * 
			 */
			ratio: null,
			
			zoom: 1,
			
			scale: 1,
			
			originalWidth: null,
			
			originalHeight: null,
			
			init: function(el, userConfig) {
				
				ImageResizer.superclass.init.call(this, el, userConfig);
				
				this.originalWidth = this.get('width');
				this.originalHeight = this.get('height');
				
				this.initCustomEvents();
				
				this.initImageCropper();
			},
			
			initAttributes: function(map) {
				
				ImageResizer.superclass.initAttributes.call(this, map);
				
				this.setAttributeConfig('target',{
					value: map.target || {},
					method: function(val) {
						this.ratio = Math.round(val.width / val.height);
					}
				});
				
				this.setAttributeConfig('width',{
					method: function(val) {
						this.get('element').width = val;
					},
					getter: function(val) {
						return this.get('element').clientWidth;
					}
				});
				
				this.setAttributeConfig('height',{
					method: function(val) {
						this.get('element').height = val;
					},
					getter: function(val) {
						return this.get('element').clientHeight;
					}
				});
				
				this.setAttributeConfig('maxHeight',{
					value: map.maxHeight || Dom.getViewportHeight(),
					getter: function(val) {
						return parseInt(Dom.getStyle(this._oImgCropper._wrap, 'height'), 10);
					},
					setter: function(val) {
						this._oImgCropper._wrap.style.overflow = 'scroll';
						
						Dom.setStyle(this._oImgCropper._wrap, 'height', val + 'px');
						
						Dom.setStyle(this._oImgCropper._mask, 'height', this.get('height') + 'px');
					}
				});
				
				this.setAttributeConfig('maxWidth',{
					value: map.maxWidth || Dom.getViewportWidth(),
					getter: function(val) {
						return parseInt(Dom.getStyle(this._oImgCropper._wrap, 'width'), 10);
					},
					setter: function(val) {
						this._oImgCropper._wrap.style.overflow = 'scroll';
						
						Dom.setStyle(this._oImgCropper._wrap, 'width', val + 'px');
						
						Dom.setStyle(this._oImgCropper._mask, 'width', this.get('width') + 'px');
					}
				});
				
			},
			
			initCustomEvents: function() {
				this.resizeEvent = this.createEvent('resizeEvent');
				this.moveEvent   = this.createEvent('moveEvent');
				
				YU.Event.addListener(window, 'resize', this.handleWindowResizeEvent, this, true);
			},
			
			initImageCropper: function() {
				var oImg = new Y.widget.ImageCropper(this.get('element'),
					{
								 ratio: this.ratio,
						initHeight: this.get('target').height,
						 initWidth: this.get('target').width
					}
				);
				
				oImg.on('moveEvent', this.handleMoveEvent, this, true);
				oImg.on('resizeEvent', this.handleResizeEvent, this, true);
				
				this._oImgCropper = oImg;
			},
			
			_calcImageSize: function() {
			},
			
			handleWindowResizeEvent: function() {
			},
			
			handleResizeEvent: function() {
				var region = this._oImgCropper.getCropCoords();
				
				// calculate relative image size
				this.zoom = this.get('target').width / region.width;
				
				this.fireEvent('change');
			},
			
			handleMoveEvent: function() {
				var region = this._oImgCropper.getCropCoords();
				
				this.fireEvent('change');
			},
			
			getCropCoords: function() {
				var region = this._oImgCropper.getCropCoords();
				
				return {
					width: this.originalWidth * this.zoom,
					height: this.originalHeight * this.zoom,
					
					top: region.top * this.zoom,
					left: region.left * this.zoom,
					
					zoom: this.zoom
				};
			}
		});
		
		
		
		
		
		
		function resizeImageThumbnail() {
			if (!oDialog) {
				var _curBodyOverflow,
				    oButtons = [
				    	{ text:'Save Thumbnail', handler:function(){this.submit();}, isDefault:true },
				    	{ text:'Cancel',         handler:function(){this.cancel();} }
				    ];
				
				oDialog = new YAHOO.widget.Dialog('resizeDialog', {
					 postmethod: 'async',
								close: true,
							visible: false,
								modal: true,
					fixedcenter: true,
							buttons: oButtons,
							 effect: { 
										 effect: YAHOO.widget.ContainerEffect.FADE,
									 duration: 0.25
								}
				});
				
				oDialog.callback.success = function() {
					forceImageReload(
						selectedCell.getElementsByTagName('img')[0]
					);
				};
				
				oDialog.setBody(' ');
				oDialog.setHeader('Image Resizing');
				
				oDialog.render(document.body);
				
				
			}
			
			Connect.asyncRequest('GET', urls.resize + selectedCell.id, {
				success: function(o) {
					oDialog.setBody(o.responseText + "<br style='clear:left;' />");
					
					oDialog.beforeShowEvent.subscribe(resizeImage);
					
					var nImg = Dom.get('resizeme'),
							lImg = new Image();
							
					lImg.onload = function() {
						oDialog.show();
					};
					
					lImg.src = nImg.src;
				}
			});
		};
		
		function resizeImage() {
			var previewEl = Dom.get('resizeme-preview'),
			    targetWidth  = parseInt(Dom.getStyle(previewEl.parentNode, 'width')),
			    targetHeight = parseInt(Dom.getStyle(previewEl.parentNode, 'height')),
					
					// form controls
					form = {
							 top: Dom.get('ImageTop'),
							left: Dom.get('ImageLeft'),
						 width: Dom.get('ImageWidth'),
						height: Dom.get('ImageHeight')
					};
			
			var image = new ImageResizer('resizeme', {
				target: {
					width: targetWidth,
					height: targetHeight
				}
			});
			
			YU.Event.addListener(window, 'resize', syncImageSize);
			
			image.on(
				'change', function(){
					
					updateForm();
					
					var region = this.getCropCoords();
					
					previewEl.style.top = (-1 * region.top) + 'px';
					previewEl.style.left = (-1 * region.left) + 'px';
					
					previewEl.style.height = region.height + 'px';
					previewEl.style.width  = region.width  + 'px';
					
				}
			);
			
			syncImageSize();
		
			oDialog.center();
			
			oDialog.beforeShowEvent.unsubscribe(resizeImage);
			
			function updateForm() {
				var region = image._oImgCropper.getCropCoords();
				
				form.top.value = region.top;
				form.left.value = region.left;
				form.width.value = region.width;
				form.height.value = region.height;
			};
				
			function syncImageSize(evt) {
					var elDialog = oDialog.element,
					    viewHeight = Dom.getViewportHeight(),
							viewWidth  = Dom.getViewportWidth();
					
					// check for the Width FIRST
					// need to ensure the Thumbnail Preview is displayed
					// to the right of the large image.
					if (elDialog.offsetWidth > viewWidth)
					{
						var chrome = elDialog.offsetWidth - image.get('maxWidth');
						
						chrome = chrome + ( previewEl.parentNode.offsetWidth + 40 );
						
						image.set('maxWidth', (viewWidth * .99) - chrome);
					}
					
					if (elDialog.offsetHeight > viewHeight)
					{
						var chrome = elDialog.offsetHeight - image.get('maxHeight');
						
						image.set('maxHeight', (viewHeight * .99) - chrome);
					}
				}
		};
		
		
			
			
		
		var menuItems = [
			{ text: 'Edit', onclick: {fn: gotoEditPage} },
			{ text: 'Regenerage Thumbnail', onclick: {fn: regenerateThumbnail} },
			{ text: 'Edit Thumbnail', onclick: {fn: resizeImageThumbnail} }
		];
		
			
		function initContextMenu() {
			menu = new YAHOO.widget.ContextMenu(
				"gallerycontextmenu",
				{
					 trigger: 'dataset',
					itemdata: menuItems
				}
			);
	
			menu.render(document.body);
			
			menu.subscribe('triggerContextMenu', onTriggerContextMenu);
		};
		
		
		YAHOO.util.Event.onAvailable('dataset', initContextMenu);
};
	
var load = new YAHOO.util.YUILoader({
	require: ["animation","connection","container","element","imagecropper","menu"],
	
	onSuccess: function(){
		YAHOO.app.gallery();
	}
});

load.insert();

})();

