var lang = {
	compressor: {
		bits24			: "24 bity"
	},
	error: {
		session_expired	: "Twoja sesja wygasła. Strona zostanie przeładowana bo wybraniu Ok.",
		main						: "Błąd",
		requestFailure		: "Wystąpił problem z serwerem. Proszę spróbować za chwilę."
	},
	buttons: {
		ok						: "Ok",
		cut						: "Wytnij",
		cancel				: "Anuluj",
		saveOnDisc		: "Pobierz zdjęcie",
		backToForm		: "Wróć do formularza"
	},
	loading				: "Pobieranie danych, proszę czekać...",
	toolbar: {
		closeButton: {
			hide			: "Ukryj pasek narzędzi",
			show			: "Pokaż pasek narzędzi"
		},
		backButton: {
			back			: "Pokaż główny pasek narzędzi"
		},
		warnings: {
			valueError	: "Wprowadzono nieprawidłową wartość"
		}
	}	
}; var Dom = YAHOO.util.Dom,
	Event = YAHOO.util.Event,
	DDM = YAHOO.util.DragDropMgr,
	Connect = YAHOO.util.Connect,
	configuration = {
		CSS: {
			IDs: {
				errorDialog				: "error-dialog",
				// top menu bar
				topMenuBar				: "top-menu-bar",
				topMenuBarHelp		: "top-menu-bar-help",
				topMenuBarEffects	: "top-menu-bar-effects",
				topMenuBarRotate		: "top-menu-bar-rotate",
				topMenuBarTools		: "top-menu-bar-tools",
				topMenuBarEdit			: "top-menu-bar-edit",
				topMenuBarFile			: "top-menu-bar-file",
				// 'loading' animation
				wait: "wait",
				// user img
				img: "userImage",
				// editor
				topRuler: "top-ruler",
				leftRuler: "left-ruler",
				editor: "editor",
				photoContainer: "photo-container",
				// toolbar
				toolbar: "toolbar",
				toolbarBackButton: "toolbar-back-button",
				toolbarCloseButton: "toolbar-close-button",
				toolbarTools: "toolbar-tools",
				photoInfo: "photo-info",
				photoWidth: "photo-width",
				photoHeight: "photo-height",
				photoWeight: "photo-size",
				photoWidthWarning: "photo-width-warning",
				photoHeightWarning: "photo-height-warning",
				imageRatioChecbox: "image-ratio-checkobx",
				metricType: "metric-type",
				
				defaultImgButton						: "default-img-button",
				defaultImgButtonContainer	: "default-img-button-container",
				// upload
				uploaderOverlay: "uploader-overlay",
				uploadPanel: "upload-panel",
				selectLink: "select-link",
				uploadPanelResizeIMG: "upload-panel-resizeIMG",
				uploadPanelResize: "upload-panel-resize",
				uploadPanelControls: "upload-panel-controls",
				uploadPanelLabel: "upload-panel-label",

				uploadPanelProgressbar		: "upload-progress-bar-container",
				uploadTick						: "upload-tick",
				// progress bar
				progressBarInner: "progressbar-inner",
				progressBarOuter: "progressbar-outer",
				progressBarStatus: "progressbar-status",
				// tooltip
				tooltip: "tooltip",
				// cropper
				croppHeight: "cropp-height",
				croppWidth: "cropp-width",
				croppX: "cropp-x",
				croppY: "cropp-y",
				croppInfo: "cropp-info",
				croppPosition: "cropp-position",
                croppSelectTotal        : "cropp-select-all",
				// contrast dialog
				contrast				: "contrast",
				contrastImg			: "contrast-image-miniature",
				contrastImgMask	: "contrast-image-miniature-mask",
				contrastSlider		: "contrast-slider",
				contrastThumb		: "contrast-thumb",
				contrastValue		: "contrast-value",
				// save image dialog
				savePhoto								: "saving-photo",
				savePhotoFormat					: "saving-photo-format",
				savingPhotoContent				: "saving-photo-content",
				savingPhotoFormatMenu		: "saving-photo-format-menu",
				saveCompressionDegree	: "saving-photo-compression-degree",
				saveFileName							: "filen",
				saveCompressorSlider			: "save-slider",
				saveCompressorThumb		: "save-thumb",
				saveSliderBD							: "save-slider-bd",
				saveColorBD							: "save-color-bd",
				saveColorsButton					: "save-colors-button",
				saveCopy									: "save-copy",
				
				topContent						: "top-content",
				forwardButton					: "forward-button",
				backButton						: "back-button",
				cmdBlocks						: "cmd-block",
                
                contrastControls             : "contrast-controls",
                basicControls                  : "photo-info"
				
			}
		}
	}; /**
 * tools module
 * @module tools
 */

/**
 * main tools
 * @class tools
 * @static
 */
var tools = {
	/**
	 * convert string to number
	 * @method toInt
	 * @param {String | Number} value	-
	 * @return Number
	 */
	toInt: function( value ) {
		if( YAHOO.lang.isNumber( value ) ) {
			return value;
		}
		return parseInt( value, 10 );
	},
	/**
	 * check if value is string like "123px"
	 * @method isPx
	 * @param {String} value
	 * @return Boolean
	 */
	isPx: function( value ) {
		return  ( /^\d{1,3}px$/ ).test( value );
	},
	/**
	 * check if value has number format
	 * @param {String} value
	 * @return {Boolean}
	 */
	isStringNumber: function( value ) {
		return ( /^\d{1,4}(\.\d+)?$/ ).test( value );
	},
	/**
	 * standard ajax request failure callback
	 * @method handleFailure
	 */
	handleFailure: function() {
		dialogs.errorDialogShow( "requestFailure" );
	},
	/**
	 * get basic callback
	 * @method getBasicCallback
	 */
	getBasicCallback: function() {
		var handleSuccess = function( o ) {
			eyp.loadImage( o.responseText );
		};
		
		return { 
		  	success	: handleSuccess, 
		  	failure		: this.handleFailure,
			timeout		: 1000*60
		};	
	},
	destroyMask: function( el ) {
		
		el.parentNode.removeChild( el );
	},	
	/**
	 * @method createMask
	 */
	createMask: function( cfg ) {
		var wrap = Dom.get( "ef-wrap" );
		var mask = document.createElement( "div" );
		wrap.appendChild( mask );
		
		Dom.setStyle( mask, "display", "block" );
		Dom.setStyle( mask, "height", Dom.getStyle( wrap, "height" ) );
		Dom.setStyle( mask, "width", Dom.getStyle( wrap, "width" ) );
		Dom.setStyle( mask, "position", "absolute" );
		Dom.setStyle( mask, "left", "0px" );
		Dom.setStyle( mask, "top", "0px" );
		Dom.setStyle( mask, "zIndex", "1" );
		
		for( var key in cfg ) {
			if( cfg.hasOwnProperty( key ) ) {
				Dom.setStyle( mask, key, cfg[ key ] );
			}
		}
		return mask;
		
	}

}; /**
 * @description cropper manager
 * @class cropper
 * @static
 */
var cropper = {
	on_: false,
	/**
	 * @description get  imageCropper cords
	 * @return {Object}
	 */
	getCroppCoords: function() {
		var coords = this.cropp.getCropCoords();
		return coords;
	},
	/**
	 * @description cropper position information show during draggin
	 * @param {Number} x 			-
	 * @param {Number} y 			- 
	 * @param {Boolean} isStart	- flag indicates if this is start of showing position window
	 */
	positionShow: function( x, y, isStart ) {
		var coords = this.getCroppCoords();
		if( isStart ) {
			this.cacheLeft = coords.left;
			this.cacheTop = coords.top;
		}
		
		var xd = coords.left - this.cacheLeft;
		var yd = coords.top - this.cacheTop;
		this.positionDiv.innerHTML = YAHOO.lang.substitute("{x} x {y}<br/>{xd} x {yd}", {
			x		: coords.left,
			y		: coords.top,
			xd	: xd > 0 ? "+" + xd : xd,
			yd	: yd > 0 ? "+" + yd : yd
		});
		Dom.setStyle( this.positionDiv, "display", "block" );
		Dom.setXY( this.positionDiv, [ x, y ] );
	},
	/**
	 * @description cropper position information hide
	 */
	positionHide: function() {
		if( this.positionDiv ) {
			Dom.setStyle( this.positionDiv, "display", "none" );	
		}
	},
	/**
	 * @description
	 * @param {Number} width		-
	 */
	setWidth: function( width, el, flag ) {
		
		if( YAHOO.lang.isNumber( width ) ) {
			this.hideWarning( el );
			var coords = this.getCroppCoords();
			var imgWidth = photoMgr.getDimensions()[0];
			if( width > ( imgWidth - coords.left ) ) {
				width = imgWidth - coords.left;
			}
			if( flag ) {
				this.setCroppWidth( width );
			}
			el.value = width;
		}
		else {
			this.showWarning( el );
		}
	},
	setCroppY: function( y ) {
		var resizeEl = this.cropp.getResizeEl();
		Dom.setStyle( resizeEl, "top", y + "px" );
		this.cropp._syncBackgroundPosition();
	},
	setCroppX: function( x ) {
		var resizeEl = this.cropp.getResizeEl();
		Dom.setStyle( resizeEl, "left", x + "px" );
		this.cropp._syncBackgroundPosition();
	},
	setCroppHeight: function( height ) {
		var resizeObject = this.cropp.getResizeObject();
		resizeObject.set( "height", height, false );
		this.cropp._syncBackgroundPosition();
	},
	setCroppWidth: function( width ) {
		var resizeObject = this.cropp.getResizeObject();
		resizeObject.set( "width", width, false );
		this.cropp._syncBackgroundPosition();
	},
	/**
	 * @description
	 * @param {Number} height 	-
	 */
	setHeight: function( height, el, flag ) {
		if( YAHOO.lang.isNumber( height ) ) {
			this.hideWarning( el );
			var coords = this.getCroppCoords();
			var imgHeight = photoMgr.getDimensions()[1];
			if( height > ( imgHeight - coords.top ) ) {
				height = imgHeight - coords.top ;
			}
			if( flag ) {
				this.setCroppHeight( height );
			}
			el.value = height;
		}
		else {
			this.showWarning( el );
		}
	},
	/**
	 * @description
	 * @param {Number} x 	-
	 */
	setX: function( x, el ) {
		if( YAHOO.lang.isNumber( x ) ) {
			this.hideWarning( el );
			if ( x < 0) {
				x = 0;
			} 
			else {
				var coords = this.getCroppCoords();
				var imgWidth = photoMgr.getDimensions()[0];
				if( x > ( imgWidth - coords.width ) ) {
					x = imgWidth - coords.width;
				}
			}
			var resizeEl = this.cropp.getResizeEl();
			Dom.setStyle( resizeEl, "left", x + "px" );
			this.cropp._syncBackgroundPosition();
			el.value = x;
		}
		else {
			this.showWarning( el );
		}
	},
	/**	
	 * @description
	 * @param {Number} y
	 */
	setY: function( y, el ) {
		if( YAHOO.lang.isNumber( y ) ) {
			this.hideWarning( el );
			if ( y < 0 ) {
				y = 0;
			}  
			else {
				var coords = this.getCroppCoords();
				var imgHeight = photoMgr.getDimensions()[1];
				if ( y > ( imgHeight - coords.height ) ) {
					y = imgHeight - coords.height;
				}
			}
			var resizeEl = this.cropp.getResizeEl();
			Dom.setStyle( resizeEl, "top", y + "px" );
			this.cropp._syncBackgroundPosition();
			el.value = y;
		}
		else {
			this.showWarning( el );
		}
	},
	/**
	 * @description crooper toolbar initialization
	 *
	 */
	toolbarInit_: function() {
		var that = this;
		
		this.widthText = Dom.get( configuration.CSS.IDs.croppWidth );
		this.heightText = Dom.get( configuration.CSS.IDs.croppHeight );
		this.xText = Dom.get( configuration.CSS.IDs.croppX );
		this.yText = Dom.get( configuration.CSS.IDs.croppY );
		this.coordsContainer = Dom.get( configuration.CSS.IDs.croppInfo );
		
		function onSelect() {
			this.select(); 
			Dom.setStyle( this, "color", "#000" ); 
		}
		
		this.widthText.onfocus = onSelect;
		this.heightText.onfocus = onSelect;
		this.xText.onfocus = onSelect;
		this.yText.onfocus = onSelect;
		
		this.widthText.onblur = function(){
			that.setWidth( tools.toInt( this.value ), this, true );
		};
		this.heightText.onblur = function(){
			that.setHeight( tools.toInt( this.value ), this, true );
		};
		this.xText.onblur = function() {
			that.setX( tools.toInt( this.value ), this );
		};				
		this.yText.onblur =  function(){
			that.setY( tools.toInt( this.value ), this );
		};
	},
	hideCoords: function() {
		Dom.setStyle( this.coordsContainer, "display", "none" );
	},
	showCoords: function() {
		Dom.setStyle( this.coordsContainer, "display", "block" );
	},
	/**
	 * @description on cropper toolbar
	 */
	toolbarOn: function() {
		var that = this;
		toolbar.off( function() {
			toolbar.hideCoords();
			that.showCoords();
			that.toolbarRefresh_();
			toolbar.on( function() {
				that.tipOn();
			}); 
		});
	},
	/**
	 * @description off cropper toolbar
	 */
	toolbarOff: function() {
		var that = this;
		toolbar.off( function() {
			toolbar.showCoords();
			that.hideCoords();
			toolbar.on( function() {
				that.tipOff();
			});
		});
	},
	/**
	 * @description toolbar information refresh
	 */
	toolbarRefresh_: function() {
		try {
		var coords = this.getCroppCoords();
		this.setWidth( coords.width, this.widthText );
		this.setHeight( coords.height, this.heightText );
		this.setX( coords.left, this.xText );
		this.setY( coords.top, this.yText );
		} catch(e) {
			console.debug( e ) ;
		}
	},
	/**
	 * @description cropper tooltip show
	 */
	tipOn: function() {
		//dialogs.tooltipShow( lang.tip.cropp );
	},
	/**
	 * @description cropper tooltip hide
	 */
	tipOff: function() {
		//dialogs.tooltipHide();
	},
	/**
	 * @description context menu initialization
	 */
	cmInit_: function() {
			return;
	},
	/**
	 * @description switch cropper mode
	 */
	switchMode: function() {
		var that = this;
		if ( this.cropp ) {
			this.off();
		}
		else {
			if ( queue.getAll().length > 0 ) {
				var request = new Ajax( {
					data			: eyp.createData( "resize" ),
					callback: {
						onSuccess 	: function( o ) {
							eyp.loadImage( o.responseText, { resize: false } );
							that.on();
						},
						onFailure		: function( o ) { }
					}
				});
				request.send();
			}
			else {
				this.on();
			}
		}		
	},
	/**
	 * @description
	 */
	showWarning: function( el ) {
		
		el.tooltip = new YAHOO.widget.Tooltip( el.id + "-tooltip", { 
			context			: el,
			text				: lang.toolbar.warnings.valueError,
			showDelay	: 50 
		});
		Dom.setStyle( el, "color", "#F34A4A" );
		
	},
	/**
	 * @description
	 */
	hideWarning: function( el ) {
		if( el.tooltip ) {
			el.tooltip.destroy();
			el.tooltip = null;
		}
		Dom.setStyle( el, "color", "#000" );
	},
	/**
	 * @description shortcuts initialization
	 */
	shortcutsInit_: function() {
		this.enter = new YAHOO.util.KeyListener( document, 
			{ keys: YAHOO.util.KeyListener.KEY.ENTER },                               
			{ fn: function(e, ev) { Event.stopEvent(ev); this.send(); } }
		);
		this.enter.disable();
	},
	/**
	 * @description cropper initialization
	 */
	init: function() {
		this.toolbarInit_();
		this.shortcutsInit_();
		this.positionDiv = Dom.get( configuration.CSS.IDs.croppPosition );
        this.selectTotalIMGButton = new YAHOO.widget.Button( configuration.CSS.IDs.croppSelectTotal );
        var that = this;
        this.selectTotalIMGButton.on( "click", function() {
            that.selectTotalIMG();
        }); 
	},
	/**
	 * @description cropper enable
	 */
	on: function() {
		this.on_ = true;
		this.widgetOn_();
		this.enter.enable();							
		this.toolbarOn();
		this.cmInit_();
	},
	
	selectTotalIMG: function() {
		var img = photoMgr.getImg();
		this.setCroppX( 0 );
		this.setCroppY( 0 );
		this.setCroppWidth( tools.toInt( Dom.getStyle( img, "width" ) ) );
		this.setCroppHeight( tools.toInt( Dom.getStyle( img, "height" ) ) );
	},
	/**
	 * @description on cropper widget
	 */
	widgetOn_: function() {
		var that = this;
		eyp.resize.destroy();
		
		var img = photoMgr.getImg();

		this.cropp = new YAHOO.widget.ImageCropper( img, {
			keyTick			: 5, 
			shiftKeyTick	: 50
		});
		
		
		var img = photoMgr.getImg();
		var width = tools.toInt( Dom.getStyle( img, "width" ) );
		var height = tools.toInt( Dom.getStyle( img, "height" ) );
		this.setCroppWidth( Math.round( width * 0.8 ) );
		this.setCroppHeight( Math.round( height * 0.8 ) );
		
		
		this.cropp.on( "dragEvent", function(e) {
				e = e[0][0].e;
				that.positionShow( e.clientX + 10, e.clientY + 10 );
				that.toolbarRefresh_();
		});
		
		
		
		this.cropp.on( "resizeEvent", function(e) {
				that.toolbarRefresh_();
		});
		
		Event.addListener(
			this.cropp.getResizeEl(),
			"mousedown",
			function(e) {
				that.positionShow( e.clientX + 10, e.clientY + 10, true );
			}
		);
		
		Event.addListener(
			this.cropp.getResizeEl(),
			"mouseup",
			function(e) {
				that.positionHide();
			}
		);
	},
	/**
	 * @description off cropper widget
	 */
	widgetOff_: function() {
		if ( this.cropp ) {
			this.cropp.destroy();
			this.cropp = null;
			this.enter.disable();
			//eyp.resize.init();
		}
	},
	/**
	 * @method isOn
	 * @return boolean
	 */
	isOn: function() {
		return this.on_;
	},
	/**
	 * @description off cropper
	 */
	off: function() {
		if ( this.cropp ) {
			this.widgetOff_();
			this.toolbarOff();
		}
		this.on_ = false;
	},
	/**
	  * @method getCroppData
	  * @description get cropper data
	  * @return {String} cropper data
	  * @private
	  * @static
	  */
	getCroppData: function() {
		var coords = this.getCroppCoords();
		return YAHOO.lang.substitute( "cmd=cropping&x={x}&y={y}&w={w}&h={h}"/*&position={position}"*/, {
			x				: coords.left,
			y				: coords.top,
			w				: coords.width,
			h				: coords.height//,
			//position		: historyIMG.getPosition()
		});
	},
	/**
	 * @description
	 */
	url: "main.php",
	/**
	 * send cropp command
	 * @method send
	 */
	send: function() {
		loading.show();
		var request = YAHOO.util.Connect.asyncRequest( "POST", this.url, tools.getBasicCallback(), this.getCroppData() );	
		eyp.environmentReset();
	}
}; /**
 * @description dialogs manager
 * @class dialogs
 * @static
 */
var dialogs = {
	/**
	 * @value {Boolean} 
	 */
	sessionExpired: false,
	/**
	 * @description show error dialog
	 * @param {String} txt 	- error message
	 */
	errorDialogShow: function( txt ) {

		if( txt == "session_expired" ) {
			this.sessionExpired = true;
		}
		if( lang.error.hasOwnProperty( txt ) ) {
			txt = lang.error[ txt ];
		}
		
		
		if( !this.errorDialog ) { // initialization on first use
			this.errorDialogInit();
		}
		this.errorDialog.cfg.setProperty( "text", txt );
		this.errorMask = tools.createMask({
			"backgroundColor"	: "#000",
			"opacity"				: "0.25"
		});
		this.errorDialog.show();
		this.errorDialog.blurButtons();
	},
	/**
	 * @description error dialog initialization
	 */
	errorDialogInit: function() {
		var that = this;
		var handleYes = function() {
			tools.destroyMask( that.errorMask );
			this.hide();
			if( that.sessionExpired ) {
				location.reload( false );
				that.sessionExpired = false;
			}
			else {
				location.reload( false );
			}
		};
		this.errorDialog = new YAHOO.widget.SimpleDialog( configuration.CSS.IDs.errorDialog,  { 
			width							: "300px",
			fixedcenter				: true,
			visible						: false,
			draggable					: true,
			close							: false,
			text								: "",
			icon							: YAHOO.widget.SimpleDialog.ICON_WARN,
			constraintoviewport	: true,
			buttons						: [ { text:"Ok", handler: handleYes } ]
		});
		this.errorDialog.setHeader( lang.error.main );
		this.errorDialog.render( document.body );
	},
	/**
	 * @description show program tooltip
	 * @param {String} text 	-
	 */
	tooltipShow: function( text ) {	
		if( !this.tooltip ) {
			this.tooltipInit();
		}
		this.tooltip.setBody( text );	
		this.tooltip.moveTo( Math.round( Dom.getViewportWidth() - 210 ), 20 );
		this.tooltip.show();
		if( this.tooltipTimeout ) {
			clearTimeout( this.tooltipTimeout );
		}
		var that = this;
		this.tooltipTimeout = setTimeout( function() {
			that.tooltipHide();
		}, 20*1000 );
	},
	/**
	 * @description hide program tooltip
	 */
	tooltipHide: function() {
		if( !this.tooltip ) {
			return;
		}
		if( this.tooltip.cfg.getConfig( "visible" ).visible ) {
			clearInterval( this.tooltipTimeout );
			this.tooltip.hide();
		}
	},
	/**
	 * @description program tooltip initialization
	 */
	tooltipInit: function() {
		this.tooltip = new YAHOO.widget.Overlay( configuration.CSS.IDs.tooltip, { visible:false, width: "198px" } );		
		Dom.setStyle( configuration.CSS.IDs.tooltip, "display", "block" );
		this.tooltip.render();
	},
	/**
	 * @description show program small tooltip
	 */
	smallTooltipShow: function( text ) {
		if( !this.smallTooltip ) {
			this.smallTooltipInit();
		}
		this.smallTooltip.setBody( text );	
		this.smallTooltip.moveTo( Math.round( ( Dom.getViewportWidth() - tools.toInt( Dom.getStyle( configuration.CSS.IDs.sendSuccessDialog, "width") ) ) / 2 ), 1 );
		this.smallTooltip.show();
		if( this.smallTooltipTimeout ) {
			clearTimeout( this.smallTooltipTimeout );
		}
		var that = this;
		this.smallTooltipTimeout = setTimeout( function() {
			that.smallTooltipHide();
		}, 1000*5 );
	},
	init: function() {
		this.tooltipInit();
	}
};
 /**
 * The ajax module provides helper methods for manipulating ajax request.
 * @module upload
 */

 /**
 * upload manager
 * @class upload
 * @static
 */
var upload = {
	/**
	 * default upload url
	 * @property uploadURL
	 * @type String
	 */
	uploadURL: "upload2.php",
	/**
	 * return scale img flag
	 * @method scaleIMG
	 * @return Boolean
	 */
	scaleIMG_: function() {
		return Dom.get(configuration.CSS.IDs.uploadPanelResizeIMG).checked;
	},
	/**
	 * creating POST data
	 * @method createPOST
	 * @return Object
	 */
	createPOST: function() {
		if(this.scaleIMG_()) {
			return {
				editorWidth: editor.getWidth() - 20,
				editorHeight: editor.getHeight() - 20
			};
		} 
		return {};
	},
	/**
	 * show default view
	 * @method defaultView
	 */
	defaultView: function() {
		Dom.setStyle(Dom.get(configuration.CSS.IDs.uploadPanelProgressbar), "display", "none");
		Dom.setStyle(Dom.get("upload-panel-controls"), "display", "block");
		Dom.setStyle(Dom.get(configuration.CSS.IDs.selectLink), "display", "block");	
		Dom.setStyle(configuration.CSS.IDs.uploadPanelLabel, "display", "block");	
		Dom.get(configuration.CSS.IDs.uploadPanelResizeIMG).checked = false;
		Dom.setStyle(Dom.get(configuration.CSS.IDs.editor), "overflow", "hidden");
	},
	/**
	 * show upload view
	 * @method uploadView
	 */
	uploadView: function() {
		Dom.setStyle(Dom.get(configuration.CSS.IDs.uploadPanelProgressbar), "display", "block");
		Dom.setStyle(Dom.get("upload-panel-controls"), "display", "none");
		Dom.setStyle(Dom.get(configuration.CSS.IDs.selectLink), "display", "none");
		Dom.setStyle(configuration.CSS.IDs.uploadPanelLabel, "display", "none");
		Dom.setStyle(Dom.get(configuration.CSS.IDs.editor), "overflow", "auto");
		this.tickHide();
	},
	/**
	 * on hide default callback
	 * @method onHide
	 */
	onHide: function() {
		tools.destroyMask( this.mask );
		
		Dom.setStyle(Dom.get(configuration.CSS.IDs.editor), "overflow", "auto");
	},
	/**
	 * cancel upload all images
	 * @method cancelAll
	 */
	cancelAll: function() {
		this.uploader.cancel();
	},
	
	send: function() {
		//this.isFileSelected = true;
		this.uploadMgr.upload();
		
		
	},
	/**
	 * @method tickShow
	 */
	tickShow: function() {
		var tick = Dom.get( configuration.CSS.IDs.uploadTick );
		Dom.setStyle( tick, "visibility", "visible" );
	},
	/**
	 * @method tickHide
	 */
	tickHide: function() {
		var tick = Dom.get( configuration.CSS.IDs.uploadTick );
		Dom.setStyle( tick, "visibility", "hidden" );
	},
	/**
	 * @method uploadMaskShow_
	 */
	uploadMaskShow_: function() {
		this.mask = tools.createMask({
			"backgroundColor"	: "#F2F2F2",
			"opacity"					: "1.0"
		});
	},
	/**
	 * uploader object initialization
	 * @method uploaderInit
	 */ 
	uploaderInit: function() {
		var that = this;
		YAHOO.widget.Uploader.SWFURL = "uploader.swf";
		this.isFileSelected = false;
		function handleClick(){
		}
		function handleContentReady(){
			that.uploader.setAllowMultipleFiles(true);
			that.uploader.setFileFilters(new Array({
				description: "Images",
				extensions: "*.jpg;*.png;*.gif;*.bmp"
			}));
		}
		this.uploadMgr = {};
		this.uploadMgr.upload = function(){
			if (that.isFileSelected) {
				that.uploadView();
				that.uploader.setSimUploadLimit(1);
				that.uploader.uploadAll( that.uploadURL, "POST", that.createPOST(), "Filedata");
				that.uploader.clearFileList();
				that.isFileSelected = false;
			}
			else {
				alert( "Wybierz zdjęcie!" );
			}
		};
		function onFileSelect(event){
			that.isFileSelected = true;
			cmdMgr.showForwardButton();
			that.tickShow();
			//that.uploadView();
			//that.uploadMgr.upload();
		}
		function onUploadStart(event){
			Dom.setStyle(Dom.get(configuration.CSS.IDs.progressBarInner), "width", "0px");
		}
		function onUploadProgress(event){
			prog = Math.round(200 * (event["bytesLoaded"] / event["bytesTotal"]));
			Dom.get(configuration.CSS.IDs.progressBarStatus).innerHTML = Math.round(event['bytesLoaded'] / event['bytesTotal'] * 100) + "%";
			Dom.setStyle(Dom.get(configuration.CSS.IDs.progressBarInner), "width", prog + "px");
		}
		function onUploadComplete(event){
			Dom.get(configuration.CSS.IDs.progressBarStatus).innerHTML = "100%";
			Dom.setStyle(Dom.get(configuration.CSS.IDs.progressBarInner), "width", "200px");
		}
		function onUploadError(event){
		}
		function onUploadCancel(event){
		}
		function onUploadResponse(event){
			//photoMgr.resetDimensions();
			that.window.hide();
			eyp.newImage(event.data);
		}
		this.uploader = new YAHOO.widget.Uploader(configuration.CSS.IDs.uploaderOverlay);
		this.uploader.addListener("contentReady", handleContentReady);
		this.uploader.addListener("fileSelect", onFileSelect)
		this.uploader.addListener("uploadStart", onUploadStart);
		this.uploader.addListener("uploadProgress", onUploadProgress);
		this.uploader.addListener("uploadCancel", onUploadCancel);
		this.uploader.addListener("uploadComplete", onUploadComplete);
		this.uploader.addListener("uploadCompleteData", onUploadResponse);
		this.uploader.addListener("uploadError", onUploadError);
		this.uploader.addListener("click", handleClick);
	},
	/**
	 * uploader manager init
	 * @method init
	 */
	init: function() {
		var that = this;
		this.window = new YAHOO.widget.Panel(configuration.CSS.IDs.uploadPanel, {
			visible								: false,
			fixedcenter						: true,
			constraintoviewport		: true,
			effect									: { effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.4},
			close									: false,
			draggable							: false
		});
		this.window.hideEvent.subscribe(function() { 
			that.cancelAll();
			that.onHide();
		});
		
		this.window.render();
		
		this.kl = new YAHOO.util.KeyListener( document, { 
				shift	: true, 
				keys	:85 
			}, 
			{ 
				fn						: upload.show,
				scope				: upload,
				correctScope	: true
			}
		);
		this.kl.enable();
	},
	/** 
	 * show uploader panel
	 * @method show
	 */ 
	show: function(){
		this.uploadMaskShow_();
		this.uploaderInit();
		eyp.environmentReset();
		this.defaultView();
		this.window.show();
	}
};
 /**
 * toolbar module
 * @module toolbar
 */

/**
 * toolbar manager
 * @class toolbar
 * @static
 * @todo numbers rounding
 */
var toolbar = {
    hideBasicControls: function() {
        Dom.setStyle( configuration.CSS.IDs.basicControls, "display", "none" ); 
    },
    showBasicControls: function() {
        Dom.setStyle( configuration.CSS.IDs.basicControls, "display", "block" ); 
    },
    hideContrastControls: function() {
        Dom.setStyle( configuration.CSS.IDs.contrastControls, "display", "none" ); 
    },
    showContrastControls: function() {
        Dom.setStyle( configuration.CSS.IDs.contrastControls, "display", "block" ); 
    },
	/**
	 * @method getMetricSystem
	 * @return String
	 */
	getMetricSystem: function() {
		return this.metricType;
	},
	/**
	 * @method setMetricSystem
	 * @param String value	-
	 */
	setMetricSystem: function( value ) {
		this.metricType = value;
	},
	/**
	 * @method getPtRatio
	 * @return Number
	 */
	getPtRatio: function() {
		return this.ptRatio;
	},
	/**
	 * @method setPtRatio
	 * @param Number value	-
	 */
	setPtRatio: function( value ) {
		this.ptRatio = value;
	},
	/**
	 *  current metric system
	 * @property metricType
	 * @value String
	 */
	metricType: "px",
	/**
	 * px/pt ratio
	 * @property ptRatio
	 * @value Number
	 */ 
	ptRatio: 0,
	/**
	 * metric system converter initialization
	 * @method metricConverterInit_
	 * @private
	 */
	metricConverterInit_: function() {
		var width = Dom.get( "metric" ).offsetWidth;
		this.setPtRatio( width / 100 );
	},
	/**
	 * change metric system of values displayed on main toolbar
	 * @method changeMetricSystem
	 * @param String type - "px"|"pt"
	 */
	changeMetricSystem: function( type ) {
		this.setMetricSystem( type );
		var dimensions = photoMgr.getDimensions();
		switch(this.metricType) {
			case "px":
				this.setImg( dimensions[0], dimensions[1] );
				break;
			case "pt":
				this.setImg( dimensions[0] * this.getPtRatio(), dimensions[1] * this.getPtRatio() );
				break;
		}
	},
	/**
	 * toolbar buttons initialization
	 * @method buttonsInit_
	 */
	buttonsInit_: function() {
		var that = this;

		
		// metric-type menu initialization
		function click(p_sType, p_aArgs, p_oItem) { 
			var type = p_oItem.cfg.getProperty( "text") ;
			that.metricSystemButton.set( "label", type );  
			that.changeMetricSystem( type );
		} 
		var menu = [
			{ 
				text		: "px", 	
				value		: 1, 
				onclick	: { fn: click }
			},
			{ 
				text		: "pt", 	
				value		: 2, 
				onclick	: { fn: click }
			}
		];			
		this.metricSystemButton = new YAHOO.widget.Button( configuration.CSS.IDs.metricType, { 
			type		: "split", 
			menu	: menu
		});
		this.metricSystemButton.on( "focus", function() { 
			this.blur(); 
		});
		
		this.defaultImgConatiner_ = Dom.get( configuration.CSS.IDs.defaultImgButtonContainer );
		this.defaultImgButton_ = new YAHOO.widget.Button( configuration.CSS.IDs.defaultImgButton );
		
		this.defaultImgButton_.on( "click", function() {
			
			if( cropper.isOn() ) {
				var croppIsOn = true;
				cropper.off();
			}
			else {
				var croppIsOn = false;
			}
			that.request = new Ajax({
        			data        :  eyp.createData( "default", {} ),
        			callback : {
        				onSuccess: function( o ) {
        					
							eyp.loadImage( o.responseText, { cropp : croppIsOn } );
        				},
        				onFailure: function( o ) {}
        			}
        	});
        	that.request.send();
		});
		
	},
	/**
	 * show value warning
	 * @method showWarning
	 * @param HtmlElement el	-
	 */
	showWarning: function( el ) {
		el.tooltip = new YAHOO.widget.Tooltip( el.id + "-tooltip", { 
			context			: el,
			text				: lang.toolbar.warnings.valueError,
			showDelay	: 50 
		});
		Dom.setStyle( el, "color", "#F34A4A" );
	},
	/**
	 * hide value warning
	 * @method hideWarning
	 * @param HtmlElement el	-
	 */
	hideWarning: function( el ) {
		if( el.tooltip ) {
			el.tooltip.destroy();
			el.tooltip = null;
		}
		Dom.setStyle( el, "color", "#000" );
	},
	/**
	 * convert integer value to pixel metric type
	 * @param Integer value	-
	 * @return Integer
	 */
	toPx: function( value ) {
		switch( this.getMetricSystem() ) {
			case "px":
				return Math.round( value );
			case "pt":
				return Math.round( value / this.getPtRatio() );
			default:
				alert("error#101");
		}
	},
	/**
	 * refresh coords values
	 * @method coordsRefresh
	 */
	coordsRefresh: function() {
		var dimensions = photoMgr.getDimensions();
		this.setImgWidth( tools.toInt( dimensions[0] ) );
		this.setImgHeight( tools.toInt( dimensions[1] ) );
		this.setImgWeight( photoMgr.getWeight() );
	},
	/**
	 * coords controls initialization
	 * @method coordsControlsInit_
	 */
	coordsControlsInit_: function() {
		var that = this;
		
		function onFocus() {
			this.select();
			this.cache = this.value;
		}
		
		Event.addListener( this.widthText, "focus", onFocus );
		Event.addListener( this.heightText, "focus", onFocus );
		
		function onBlur( name, el ) {
			if( tools.isStringNumber( el.value ) ) {
				if( el.value == el.cache ) {
					return;
				}
				var dimensions = photoMgr.getDimensions();
				var width, height, ratio;
				if( name == "width" ) {
					width = that.toPx( tools.toInt( el.value ) );
					if ( that.keepProportionsIsChecked() ) {
						ratio = width / dimensions[0];
						height = tools.toInt( dimensions[1] * ratio );
						photoMgr.setDimensions( width, height, { anim: true } ); 
					} else {
						height = dimensions[1];
						photoMgr.setWidth( width, { anim: true} );
					}
				}
				else {
					height = that.toPx( tools.toInt( el.value ) );
					if ( that.keepProportionsIsChecked() ) {
						ratio = height / dimensions[1];
						width = tools.toInt( dimensions[0] * ratio );
						photoMgr.setDimensions( width, height, { anim: true } );
					} else {
						width = dimensions[0];
						photoMgr.setHeight( height, { anim: true } ) ;
					}
				}
				that.hideWarning( el );
				queue.add( new Command( "resize", {}) );
				/*
				historyIMG.add( {
					cmd		: "resize",
					src		: Dom.get(configuration.CSS.IDs.img).src,
					width	: width,
					height	: height,
					weight	: photoMgr.getWeight()
				});
				*/
			}
			else {
				that.showWarning( el );
			}
		}
		Event.addListener( this.widthText, "blur", function() {
			onBlur( "width", this );
		});
		Event.addListener( this.heightText, "blur", function() {
			onBlur( "height", this );
		});
		this.coordsRefresh();
	},
	/**
	 * return information about keep proportions checkbox 
	 * @method keepProportionsIsChecked
	 * @return Boolean
	 */
	keepProportionsIsChecked: function() {
		return this.keepProportions.checked;
	},
	/**
	 * hide information block
	 * @method hideCoords
	 */
	hideCoords: function() {
		Dom.setStyle( this.info, "display", "none" );
	},
	/**
	 * show information block
	 * @method showCoords
	 */
	showCoords: function() {
		Dom.setStyle( this.info, "display", "block" );
	},
	/**
	 * @method setValue_
	 * @param HtmlElement el 		-
	 * @param String|Number value 	-
	 */
	setValue_: function( el, value ) {
		if( tools.isStringNumber( value ) ) {
			this.hideWarning( el );
			switch( this.getMetricSystem() ) {
				case "px":
					el.value = value.toFixed(0);
					break;
				case "pt":
					el.value = ( value * this.getPtRatio() ).toFixed(1);
					break;
				default:
					alert("error#1230");
			}
		}
		else {
			this.showWarning( el );
		}
	},
	/**
	 * @method setImgWidth
	 * @param String|Number value 	-
	 */
	setImgWidth: function( value ) {
		this.setValue_( this.widthText, value );
	},
	/**
	 * @method setImgHeight
	 * @param String|Number value 	-
	 */
	setImgHeight: function( value ) {
		this.setValue_( this.heightText, value );
	},
	/**
	 * @method setImgWeight
	 * @param String|Number value 	-
	 */
	setImgWeight: function( value ) {
		this.weightText.firstChild.nodeValue = value + "kb";
	},
	/**
	 * @method setImg
	 * @param String|Number width		-
	 * @param String|Number height 	-
	 */
	setImg: function( width, height ) {
		this.setImgWidth( width );
		this.setImgHeight( height );
	},
	/**
	 * animations init
	 * @method animsInit_
	 */ 
	animsInit_: function() {
		var that = this;

	},
	/**
	 * core initialization
	 * @method coreInit_
	 */
	coreInit_: function() {
		this.toolbar = Dom.get(configuration.CSS.IDs.toolbar);
		this.info = Dom.get(configuration.CSS.IDs.photoInfo);
		this.widthText = Dom.get(configuration.CSS.IDs.photoWidth);
		this.heightText = Dom.get(configuration.CSS.IDs.photoHeight);
		this.weightText = Dom.get(configuration.CSS.IDs.photoWeight);
		this.keepProportions = Dom.get(configuration.CSS.IDs.imageRatioChecbox);
		var wrap = Dom.get( "ef-wrap" );
		Dom.setStyle( this.toolbar, "height", tools.toInt( Dom.getStyle( wrap, "height" ) ) - 45 + "px" );
	},
	/**
	 * @property visible_
	 * @value Boolean
	 * @private
	 */
	visible_: true,
	/**
	 * toolbar manager initialization
	 * @method init
	 */
	init: function() {
		this.coreInit_();
		this.metricConverterInit_();
		this.buttonsInit_();
		this.animsInit_();
		this.coordsControlsInit_();
	},
	/** 
	 * @method off
	 */
	off: function( f ) {
		f();
	},
	/**
	 * @method on
	 */
	on: function( f ) {
		f();
	},
	/**
	 * hide toolbar
	 * @method hide_
	 * @private
	 */
	hide_: function() {
		//this.hideAnim.animate();
	},
	/**
	 * show toolbar
	 * @method show_
	 * @private
	 */
	show_: function() {
		//this.showAnim.animate();
	},
	/**
	 * change visibility mode of toolbar
	 * @method changeMode
	 */
	changeMode: function() {
		if( this.visible_ ) {
			this.hide_();
		} 
		else {
			this.show_();
		}
	}
};
 /**
 * @description 'loading' dialog manager
 */
var loading = {
	/**
	 *  initialization loading dialog
	 * @method init
	 */
	init: function() {
		this.window = new YAHOO.widget.Panel( configuration.CSS.IDs.wait, { 
			width			: "229px", 
			fixedcenter	: true, 
			close				: false, 
			draggable		: false, 
			zindex			: 2,
			visible			: false,
			effect				: { effect:YAHOO.widget.ContainerEffect.FADE, duration : 0.4 }
		 }); 
		 var that = this;
		this.window.showEvent.subscribe( function() {
			that.mask = tools.createMask( {
				backgroundColor	: "#000",
				opacity					: "0.25"
			} );
		});
		
		this.window.hideEvent.subscribe( function() {
			tools.destroyMask( that.mask );
		});
		this.window.setHeader( lang.loading );
		this.window.setBody( "<img src='css/loading.gif'/>" );
		this.window.render( document.body );
	},
	/** 
	 * hide loading dialog
	 * @method hide
	 */
	hide: function() {
		this.window.hide();	
	},
	/** 
	 * @method show
	 * show loading dialog
	 */
	show: function() {
		if( !this.window ) {
			this.init();
		}
		this.window.show();
	}
};
 /**
 * save photo dialog manager
 * @class save
 * @static
 */
var save = {
	/**
	 * compressor slider initialization
	 * @method sliderInit
	 */
	sliderInit: function() {
		this.slider = YAHOO.widget.Slider.getHorizSlider( configuration.CSS.IDs.saveCompressorSlider, configuration.CSS.IDs.saveCompressorThumb, 0, 200, 10 );
		
		this.slider.subscribe( "change", function( offsetFromStart ) {
			Dom.get( configuration.CSS.IDs.saveCompressionDegree ).innerHTML = value + "%";	
		}); 
		
		this.slider.subscribe( "slideEnd", function( ) {
			
			var value = Math.floor( this.getValue() / 2 );
			
			var request = new Ajax( {
				data			: eyp.createData( "compress", {
					value		: value 
				}),
				callback: {
					onSuccess 	: function( o ) {
						eyp.loadImage( o.responseText, {} );
					},
					onFailure		: function( o ) { }
				}
			});
			request.send();
			Dom.get( configuration.CSS.IDs.saveCompressionDegree ).innerHTML = value + "%";	
		});
	},
	/**
	 * @method hideButton
	 * @param Int index
	 */ 
	hideButton: function( index ) {
		var buttons = this.window.getButtons();
		buttons[ index ].setStyle( "display", "none" );
	},
	/**
	 * @method showButton
	 * @param Int index
	 */
	showButton: function( index ) {
		var buttons = this.window.getButtons();
		buttons[ index ].setStyle( "display", "block" );
	},
	/**
	 * @description compressor format menu initialization
	 * @param {String} format
	 */
	compressMenuInit: function( format ) {
		var that = this;
		
		function click(p_sType, p_aArgs, p_oItem) { 
			that.colors = p_oItem.value;
			
			var request = new Ajax( {
				data			: eyp.createData( "compress", {
					value		: that.colors
				}),
				callback: {
					onSuccess 	: function( o ) {
						eyp.loadImage( o.responseText, {} );
					},
					onFailure		: function( o ) { }
				}
			});
			request.send();
			
			that.colorsButton.set( "label", p_oItem.cfg.getProperty( "text" ) );  
		} 
		switch( format ) {
			case "bmp":
				that.colors = "16777216";
				var menu = [
					{ text	: lang.compressor.bits24, value: "16777216", onclick: { fn: click }},
					{ text	: "256", value: "256", onclick: { fn: click }}
				];
				Dom.get( configuration.CSS.IDs.saveColorsButton ).value = lang.compressor.bits24;
				break;
			case "gif":
				that.colors = "256";
				var menu = [
					{ text	: "256", value: "256", onclick: { fn: click }},
					{ text	: "16", value: "16", onclick: { fn: click }},
					{ text	: "2", value: "2", onclick: { fn: click }}
				];
				Dom.get( configuration.CSS.IDs.saveColorsButton ).value = "256";
				break;
		}
		if( this.colorsButton ) {
			var items = this.colorsButton.getMenu().getItems();
			var len = items.length;
			this.colorsButton.getMenu().addItems( menu );
			that.colorsButton.set( "label", menu[0].text ); 
			for( var i=0; i < len; i++ ) {
				this.colorsButton.getMenu().removeItem( 0 );
			}
		} 
		else {
			this.colorsButton = new YAHOO.widget.Button( configuration.CSS.IDs.saveColorsButton, { type: "split", menu: menu } );
			this.colorsButton.on( "focus", function() { this.blur(); } );
		}
	},
	/**
	 * @description save manage rinitialization
	 */
	init: function() {
		var that = this;
		this.window = new YAHOO.widget.Dialog( configuration.CSS.IDs.savePhoto, {
			visible			: false,
			fixedcenter	: true,
			close				: false,
			draggable		: true,
			modal			: false,
			width				: "320px",
			effect				: {
				effect		: YAHOO.widget.ContainerEffect.FADE, 
				duration : 0.4
			}
		});
		var handleCancel = function() {
			this.cancel();
		};
		
		var handleBackToForm = function() {
			alert("back to form");
		}
		
		var handleSubmit = function() {
			
			var fileName = Dom.get( configuration.CSS.IDs.saveFileName ).value;
			switch( that.mode ) {
				case "slider": 
					var compressValue = Math.floor( that.slider.getValue() / 2 );
					break;
				case "menu":
					var compressValue = that.colors;
					break;
				default:
					// error
					break;
			}
			
			if( !cmdMgr.isRedirectUrl() ) {
				
				var loc = YAHOO.lang.substitute( "download.php?format={format}&fc={fc}&compress={compress}&position={position}", {
					format		: that.formatMenu.get( "label" ),
					fc					: fileName,
					compress	: compressValue
				});
				var dimensions = photoMgr.hasChanged();
				if( dimensions ) {
					loc += YAHOO.lang.substitute( "&width={width}&height={height}", {
						width	: dimensions[0],
						height	: dimensions[1]
					});
				}
				location.href = loc;
			}
			
			
		};
		this.window.cfg.queueProperty( "buttons", [ 
			{ text	: lang.buttons.saveOnDisc, handler : handleSubmit },
			{ text	: lang.buttons.backToForm, handler : handleBackToForm }
		]);
		this.formatMenuInit(); // format menu init
		this.sliderInit(); // compressor slider init
		this.window.render();	
		
		this.kl = new YAHOO.util.KeyListener( document, 
			{ 
				shift	: true, 
				keys	: 83 
			}, 
			{ 
				fn: save.show, 
				scope: save,
				correctScope:true 
			}
		);
		this.kl.enable();
	},
	/**
	 * @description format menu initialization
	 */
	formatMenuInit: function() {
		var that = this;
		function click( p_sType, p_aArgs, p_oItem ) { 
			that.formatMenu.set( "label", p_oItem.cfg.getProperty( "text" ) );
			that.compressControlShow( p_oItem.cfg.getProperty( "text" ) );
		}
		var menu = [
			{ text	: "bmp", value: 1, onclick: { fn: click} },    
			{ text	: "gif", value: 2, onclick: { fn: click} },    
			{ text	: "jpg", value: 3, onclick: { fn: click} },
			{ text	: "png", value: 5, onclick: { fn: click} }
		];
		this.formatMenu = new YAHOO.widget.Button( configuration.CSS.IDs.savePhotoFormat, { type: "split", menu: menu } );
		this.formatMenu.on( "focus", function() { this.blur(); } );
	},
	/**
	 * @description clear save dialog form 
	 */
	clearForm: function() {
		Dom.get( configuration.CSS.IDs.saveFileName ).value = "";
		this.slider.setValue( 0, true, true, true );
	},
	/**
	 * @description set new format in photo format menu
	 */
	setFormat: function() {
		var img = photoMgr.getImg();
		var format = img.src.substring(img.src.length-3);
		this.formatMenu.set( "label", format );
	},
	/**
	 * @description compressor slider show
	 */
	compressSliderShow: function() {
		this.slider.setValue( 0, true, true, true );
		Dom.setStyle( configuration.CSS.IDs.saveSliderBD, "display", "block" );
		Dom.setStyle( configuration.CSS.IDs.saveColorBD, "display", "none" );
	},
	/**
	 * @description compressor menu show
	 */
	compressMenuShow: function() {
		Dom.setStyle( configuration.CSS.IDs.saveColorBD, "display", "block" );
		Dom.setStyle( configuration.CSS.IDs.saveSliderBD, "display", "none" );
	},
	/**
	 * @description display appropriate compressor's control
	 * @param {String} format - "bmp"|"png"|"jpg"|"gif"
	 */
	compressControlShow: function( format ) {
		switch( format ) {
			case "bmp":
			case "gif":
				this.mode = "menu";
				this.compressMenuShow();
				this.compressMenuInit( format );
				break;
			case "jpg":
			case "png":
				this.mode = "slider";
				this.compressSliderShow();
				break;
			default:
				break;
		}
	},
	hide: function() {
		this.window.hide();
	},
	/**
	 * display save photo dialog
	 * @method show
	 */
	show: function() {
		eyp.environmentReset();
		//if( ! cmdMgr.isRedirectUrl() ) {
			this.hideButton( 1 );
		//}
		var img = photoMgr.getImg();
		var format = img.src.substring(img.src.length-3);
		this.compressControlShow( format );
		this.setFormat();
		this.clearForm();
		this.window.show();
	}
};
 function Command(name, cfg) {
	this.name = name;
	this.cfg = cfg;
}
Command.prototype.getName = function() {
	return this.name;
};

var queue = function() {
	var buffer = [];
	return {
		add: function(obj) {
			buffer.push(obj);
		},
		clear: function() {
			buffer = [];	
		},
		getAll: function() {
			var tmp = buffer;
			this.clear();
			return tmp;	
		}	
	};
}();


/**
 * @description eyp is a singleton responsible for initialization application and major tasks
 * @class eyp
 * @static
 */
var eyp = function() {
	var photo, // photo element
		//croppPosition, // cropp's position window
		croppButton, // cropp's cmd button
		menu, // main menu
		dd, // drag&drop object
		resize, // resize object
		//container,
		http = /^http:\/\//,
		error = /^_error_\((.*)\)$/,
		startLeft_,
		startTop_,
		
		url = "main.php";
		
	/**
	 * @description load new image
	 * @param {String} src
	 * @param {Object} cfg configuration object
	 */
	var load_ = function(src, config) {
		var cfg = config || {}; // configuration object

		photo.onload =  function() {
			Dom.setStyle(photo, "width", "");
			Dom.setStyle(photo, "height", "");
			photoMgr.setDimensions( photo.offsetWidth, photo.offsetHeight, { anim: false, commit: true } ); 	
			toolbar.coordsRefresh(); // refreshing photo's info on toolbar
			eyp.dd.refresh();
			if( cfg.resize !== false ) {
				eyp.resize.refresh();
			}
			
			if( cfg.cropp ) {
				cropper.on();
			}

			loading.hide();
			
			if( cfg.onSuccess ) {
				cfg.onSuccess();
			}

		};
		var result = error.exec(src);
		if(result) { // server's error handling
			loading.hide();
			dialogs.errorDialogShow(result[1]);
			return;
		}
		
		result = src.search(/\n/);
		if(result == -1) {
			alert("Błąd#102: zły format odpowiedzi z serwera: " + src);	
			loading.hide();
		}
		else {
			path = src.substr(0, result);
			size = src.substr(result+1);
			var ext = path.substring(path.length-3);
			if(http.test(path) && (ext == "png" || ext == "bmp" || ext == "jpg" || ext == "gif") ) {
				loading.show();
				eyp.refreshIMG(path, size, {cropper: cfg.cropper});
			}
			else {
				alert("Błąd#103: zły format odpowiedzi z serwera: " + src);	
				loading.hide();
			}
		}
	};

	return {
		/**
		 * @description reset application environment
		 */ 
		environmentReset: function() {
			cropper.off();
			//dialogs.tooltipHide();
		},
		refreshIMG: function(src, weight, cfg) {
			eyp.resize.destroy();
			photo.src = src; // set path to the new image
            
			//photo.alt = src;
			//converter.setFormat(src.substring(src.length-3)); // set new format in converter object
			photoMgr.setWeight( weight );
			if(cfg && cfg.cropper) {
				//historyIMG.modifyWeight( photoMgr.getWeight() );
				return;
			}			
		},
		/**
		 * @description loading new image
		 * @param {String} src
		 * @param {Object} cfg
		 */
		loadImage: function(src, cfg) {
			load_(src, cfg);
		},
		getCropp: function() {
			return croppObj;
		},
		photo: function() {
			return photo;
		},
			
		dd: {
			lock: function() {
				dd.lock();
			},
			destroy: function() {
				
			},
			refresh: function() {
				this.init();
			},
			/**
			 * @description constraints initialization
			 */
			constraintsInit_: function() {
				var xy = Dom.getXY( photo );
				var y = tools.toInt( xy[1] );
				var x = tools.toInt( xy[0] );
				
				var editorXY = Dom.getXY( editor.get() );

				var topConstraint = y - editorXY[ 1 ] ;
				var leftConstraint = x - editorXY[ 0 ] ;
				dd.setYConstraint( topConstraint, "" );
				dd.setXConstraint( leftConstraint, "" );		
			},
			init: function() {
				dd = new YAHOO.util.DD( configuration.CSS.IDs.photoContainer );
				this.constraintsInit_();
			}
		},
		/**
		 * @description set cookies
		 */
		setCookie_: function() {
			document.cookie = 'PHPSESSID=; epath=/dev/; expires=Thu, 01-Jan-1970 00:00:01 GMT';
			document.cookie = 'PHPSESSID=; path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT';
		},
		/**
		 * @description tools initialization
		 */
		toolsInit_: function() {
			//converter.init(); 
			upload.init(); 
			dialogs.init(); 
			save.init();
			//compressor.init();
			loading.init(); 
			cropper.init();
			this.scaleCheckboxInit_();
			//dialogs.tooltipShow( lang.tip.start );
		},
		/**
		 * @description core initialization
		 */ 
		coreInit_: function() {
			
			var wrap  = Dom.get( "ef-wrap" );
			
			var topRegion = Dom.getRegion( "top-content" ); 
			var topRegionHeight = topRegion.bottom - topRegion.top;

			var bottomRegion = Dom.getRegion( "ft" ); 
			var bottomRegionHeight = topRegion.bottom - topRegion.top;
			
			//alert( Dom.getClientHeight()  + "---" + topRegionHeight + "---" + bottomRegionHeight );
			//alert( Dom.getClientHeight() - topRegionHeight - bottomRegionHeight  );
			Dom.setStyle( wrap, "height", Dom.getClientHeight() - topRegionHeight - bottomRegionHeight + "px" );

			editor.init();
			
			photoMgr.init();
			toolbar.init();
			photo = photoMgr.getImg();
			if( photoMgr.imageIsSet_() ) {
				this.dd.init(); 
				this.resize.init();
			}
		},
		/** 
		  * @method init
		  * @description application initialization
		  * @private
		  * @static
		  */
		init: function() {
			this.coreInit_();
			this.toolsInit_();
            
			//this.setCookie_();
			//historyIMG.init();
			//converter.setFormat( "jpg" );
			
			cmdMgr.init();
		},
		/**
		 * @description set PHPSESSID variable
		 */
		setPHPSESSID: function(value) {
			document.cookie = "PHPSESSID=" + value;
		},
		/**
		  * @description add new image
		  * @todo opera 9.51 bug
		  */
		newImage: function( path ) {
			var result = path.search( /\n/ );
			this.setPHPSESSID( path.substr( 0,result ) );
	        this.loadImage( path.substr( result+1 ), { init: true } );
		},
		/**
		 *  @method scaleCheckboxInit_
		 */
		scaleCheckboxInit_: function() {
			var that = this;
			Event.addListener( configuration.CSS.IDs.imageRatioChecbox, "change", function() { 
				that.resize.refresh();
			});
		},
		/**
		 * @description resize object
		 */
		resize: {
			refresh: function() {
				this.destroy();
				this.init();
			},
			destroy: function() {
				if( resize ) {
					resize.destroy();
					resize = null;
				}
			},
			init: function( ) {
				if ( resize ) {
					return;
				}
				
				var ratio = false;
				if( Dom.get( configuration.CSS.IDs.imageRatioChecbox ).checked ) {
					ratio = true;
				}
				xy = Dom.getXY ( editor.get() );

				resize = new YAHOO.util.Resize( configuration.CSS.IDs.photoContainer, { // resize initialization
					handles				: "all", 
					knobHandles	: true,
					ratio					: ratio,
                    autoRatio           : true,
					status				: true,
					minX					: xy[ 0 ],
					minY					: xy[ 1 ]
				});
				
				resize.subscribe( "startResize", function( e ) {
					//dialogs.tooltipShow( lang.tip.resize );
					this.startWidth = Dom.getStyle( photo, "width" );
					this.startHeight = Dom.getStyle( photo, "height" );
				});
				resize.subscribe( "endResize", function( e ) {
					queue.add( new Command( "resize", {} ) );
					/*
					historyIMG.add( {
						cmd		: "resize",
						src		: photoMgr.getImg().src,
						width	: e.width,
						height	: e.height,
						weight	: photoMgr.getWeight()
					});
					*/
					photoMgr.setDimensions( e.width, e.height , { resizeRefresh: true } ); 
				});
				resize.subscribe( "resize", function( e ) {
					//if(e.shiftKey) { // hide tooltip when user uses Shift key during resize
					//	dialogs.tooltipHide();
					//}
					if( e.width && e.height ) {
						photoMgr.setDimensions( e.width, e.height, {} );
					}
					else {
						if(e.width) {
							photoMgr.setWidth( e.width, {} );
						}
						else {
							Dom.setStyle( photoMgr.getImg(), "width", Dom.getStyle( photoMgr.getImg(), "width" ) );
						}
						if(e.height) {
							photoMgr.setHeight( e.height, {} );
						}
						else {
							Dom.setStyle( photoMgr.getImg(), "height", Dom.getStyle( photoMgr.getImg(), "height" ) );
						}
					}
				});
			}	
		},
		/**
		 * @description creating request data
		 * @param {String} cmd		-
		 * @param {Object} config	- 
		 */
		createData: function( cmd, config ) {
			var cfg = config || {};
			var data = "";
			for ( var key in cfg ) {
				if ( cfg.hasOwnProperty( key ) ) {
					data += YAHOO.lang.substitute( "{key}={value}&", {
						key		: key,
						value		: cfg[ key ]
					});
				}
			}
			data = YAHOO.lang.substitute( "cmd={cmd}&" + data /* + "position={position}" */, {
				cmd		: cmd//,
				//position	: historyIMG.getPosition()
			});
			
			var dimensions = photoMgr.hasChanged();
			if( dimensions && !cfg.width && !cfg.height ) {
				data += YAHOO.lang.substitute( "&width={width}&height={height}", {
					width	: dimensions[0],
					height	: dimensions[1]
				});
			}
			return data;
		},	
		/**
		 * @description bridge for rotation effect
		 */
		rotationBridge: function( en, e, direction ) {
			this.rotation( direction );
		},
		/**
         * @method rotation
         * @description sending rotation command
         * @private
         * @static
         */
		rotation: function( direction ) {
			loading.show();
			this.send( "rotation",  this.createData( "rotation", { direction: direction } ) );
		},
		/**
		 * @description bridge for send methodf
		 */
		sendBridge: function( en, e, effectName ) {
			this.send ( effectName );
		},
		/**
		 * @description
		 * @param {String} effectName 	-
		 * @param {Object} data				-
		 */
		send: function( effectName, data ) {
			eyp.environmentReset();
			
			this.request = new Ajax( {
				data			: data || eyp.createData( effectName ),
				callback: {
					onSuccess 	: function( o ) {
						eyp.loadImage( o.responseText );
					},
					onFailure		: function( o ) { }
				}
			});
			this.request.send();
		},
		gmb: function() {
			return menu;
		}
	};
}();
 /**
 * The ajax module provides helper methods for manipulating ajax request.
 * @module ajax
 */

/**
 * xhr request object 
 * @class Ajax
 * @param {Object} cfg 	-
 * @constructor
 */
function Ajax( cfg ) {
	this.data = cfg.data || null;
	this.callback = cfg.callback || {
		onSuccess	: null, 
		onFailure		: null
	};
	this.method = cfg.method || "POST";
	this.url = cfg.url || "main.php";
}

Ajax.prototype = {
	/**
	 * default timeout
	 * @property timeout
	 * @type int
	 */
	timeout: 1000*60,
	/**
	 * default start request event callback
	 * @method onStart
	 */
	onStart: function() {
		loading.show();
	},
	/**
	 * default end request event callback
	 * @method onEnd
	 */
	onEnd: function() {
		loading.hide();
	},
	/**
	 *  request success callback
	 * @method onSuccess
	 * @param {Object} o 	-
	 */
	onSuccess: function( o ) {
		if( this.callback.onSuccess ) {
			this.callback.onSuccess.call( this.callback.scope, o );
		}
		else {
			this.onEnd();
		}
	},
	/**
	 *  request failure callback
	 * @method onFailure
	 * @param {Object} o 	-
	 */
	onFailure: function( o ) {
		if( this.callback.onSuccess ) {
			this.callback.onFailure.call( this.callback.scope, o );
		}
		else {
			dialogs.errorDialogShow( lang.error.requestFailure );
			this.onEnd();
		}
	},
	/**
	 *  send request
	 * @method send
	 */
	send: function() {
		this.onStart();
		var callback = {
			success	: this.onSuccess,
			failure		: this.onFailure,
			timeout		: this.timeout,
			scope		: this
		};
		this.request = Connect.asyncRequest( this.method, this.url, callback, this.data );
	},
	/**
	 *  abort xhr connection
	 * @method abort
	 */
	abort: function() {
		Connect.abort( this.request );
	}
}; var SliderDialog = function(cmd, IDs, cfg) {
	this.cmd = cmd;
	this.dialogId = IDs.dialogId;
	this.miniatureId = IDs.miniatureId;
	this.maskId = IDs.maskId;
	this.sliderId = IDs.sliderId;
	this.sliderThumbId = IDs.sliderThumbId;
	this.degreeInfo = IDs.degreeInfo;
	this.onChangeCallback = cfg.changeCallback || function() {};
	this.startValue = cfg.startValue || 0;
	this.initialize = cfg.initialize || null;
	this.okCallback = cfg.okCallback || function(n) { return Math.floor(n / 2); };
};

SliderDialog.prototype = {
	sliderInit: function() {
		var that = this;
		var handleSuccess = function(o){
			var imgTemp = new Image();
			imgTemp.onload = function() {
				Dom.setStyle(that.miniatureId, "background", "#fff url(" + this.src + ")");
			};
			imgTemp.src = o.responseText;
			that.slider.unlock();
		};
		this.callback = {
			success: handleSuccess,
			failure: tools.handleFailure,
			timeout: 1000*60
		};
		this.slider = YAHOO.widget.Slider.getHorizSlider(this.sliderId, this.sliderThumbId, 0, 200, 1);
		this.slider.subscribe("change", function(offsetFromStart) {
			that.onChangeCallback(offsetFromStart);
        });
		Dom.setStyle(this.dialogId, "display", "block");
	},
	createRequestData: function() {
		var config = {}
		var size = photoMgr.hasChanged();			
		if(YAHOO.lang.isNumber(this.type)) {
			config.type = this.type
		}
		config.degree = this.okCallback(this.slider.getValue());
		if(size) {
			config.width = size[0];
			config.height = size[1];
		}
		return eyp.createData(this.cmd, config);
	},
	/** 
	 * @method submit
	 */
	submit: function() {
		var that = this;
		this.request = new Ajax({
			data: this.createRequestData(),
			callback: {
				onSuccess: function(o) {
					tools.destroyMask( that.mask );
					that.mask = null;
					that.dialog.cancel();
					eyp.loadImage( o.responseText, { stop: true } );
				},
				onFailure: function(o) {}
			}
		});
		this.request.send();
	},
	dialogInit: function() {
		var that = this;
		var handleCancel = function() {
			tools.destroyMask( that.mask )
			this.cancel(); // hide dialog
		};
		var handleSubmit = function() {
			that.submit();
		};
		if(this.initialize) { // custom dialog content initialize method
			this.initialize();
		}
		this.dialog = new YAHOO.widget.Dialog(this.dialogId, {
			visible: false,
			fixedcenter: true,
			close: false,
			draggable: true,
			buttons: [ 
				{ text: lang.buttons.ok, handler: handleSubmit }
			],
			effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.4}
		});
		this.dialog.beforeHideEvent.subscribe(function(){
			YAHOO.util.Connect.abort(that.request);
			//dialogs.tooltipHide();
		});
		this.sliderInit();
		this.dialog.render();
	},
	init: function() {
		this.dialogInit();
	},
	loadingShow: function() {
		Dom.setStyle(this.miniatureId, "background", "#fff url(css/loading_min.gif) no-repeat center center");
	},
	miniatureInit: function() {
		var sizeArray = photoMgr.getDimensions();
		if(sizeArray[1] > sizeArray[0]) {
			this.miniatureWidth = Math.round(sizeArray[0] / ( sizeArray[1] / 140 ));
			this.miniatureHeight = 140;
		}
		else {
			this.miniatureHeight = Math.round(sizeArray[1] / ( sizeArray[0] / 140 ));
			this.miniatureWidth = 140;
		}
		var miniature = Dom.get(this.miniatureId); // miniature img tab initialization
		Dom.setStyle(miniature, "width", this.miniatureWidth + "px");
		Dom.setStyle(miniature, "height", this.miniatureHeight + "px");
	},
	hide: function() {
		if( this.mask ) {
			tools.destroyMask( this.mask );
			this.mask = null;
		}
		this.dialog.hide();
	},	
	resetSlider: function() {
		this.slider.setValue(this.startValue, true, true, true);
		this.onChangeCallback(this.startValue);
	},
	updateDegreeInfo: function(degree) {
		Dom.get(this.degreeInfo).innerHTML = degree + "%";
	},
	show: function() {
		eyp.environmentReset();
		if(!this.slider) { // initialization on first use
			this.init();
		}
		this.miniatureInit();
		
		this.mask = tools.createMask({
			"backgroundColor"	: "#000",
			"opacity"				: "0.25"
		});
		this.dialog.show();	
		this.resetSlider();
		//dialogs.tooltipShow( lang.tip.sliderDialog );
	}
};

var contrastDialog = new SliderDialog("contrast", {
		dialogId: configuration.CSS.IDs.contrast,
		miniatureId: configuration.CSS.IDs.contrastImg,
		maskId: configuration.CSS.IDs.contrastImgMask,
		sliderId: configuration.CSS.IDs.contrastSlider,
		sliderThumbId: configuration.CSS.IDs.contrastThumb,
		degreeInfo: configuration.CSS.IDs.contrastDegree
	},
	{
		startValue: 100,
		okCallback: function(n) {
			return n-100;
		},
		changeCallback: function(offsetFromStart){
			loading.show();
			var degree = Math.floor(offsetFromStart - 100);
            
			this.request = YAHOO.util.Connect.asyncRequest("POST", "thumbnail.php", this.callback, eyp.createData("contrast", {
				degree: degree,
				width: this.miniatureWidth,
				height: this.miniatureHeight
			}));
		}
	}
);
 var photoMgr = {
	photo: null,
	resetSize: false,
	commitWidth: null,
	commitHeight: null,
	/**
	 * @method getFormat
	 * @return String
	 */
	getFormat: function() {
		var src = this.photo.src;
		return src.substring( src.length - 3 );
	},
	/**
	 * @method getImg
	 * @return HtmlElement
	 */
	getImg: function() {
		return this.photo;
	},
	/**
	 * @method getDimensions
	 * @return Array
	 */
	getDimensions: function() {
		return [ this.width, this.height ];
	},
    /**
     * @method isSet
     * @return boolean
     */
    isSet: function() {
        if( this.canGo === false ) {
            return false;
        }   
        else {
            return true;
        }
    },
    set: function() {
    	this.canGo = true;
    	cmdMgr.setPointer();
    },
    unSet: function() {
    	this.canGo = false;
    	cmdMgr.hideForwadButton();
    	cmdMgr.hideBackButton();
    	cmdMgr.unsetPointer();
    		
    },
	/**
	 * @method init
	 */
	init: function() {
		
		this.photo = Dom.get( configuration.CSS.IDs.img );
		this.photoContainer = Dom.get( configuration.CSS.IDs.photoContainer );

		if( cmdMgr.isRedirectUrl() ) {
			
			
			this.weight = SETTINGS.weight;
			this.width = SETTINGS.dimensions[ 0 ];
			this.commitWidth = SETTINGS.dimensions[ 0 ];
			this.height = SETTINGS.dimensions[ 1 ];
			this.commitHeight = SETTINGS.dimensions[ 1 ];
			
			
			
			var container = Dom.get( configuration.CSS.IDs.topContent );
			all = container.getElementsByTagName( "span" );
       		this.els = [];
			for( var i = 0; i < all.length; i++ ) {
				if( all[ i ].className == "cmd-block" ) {
				this.els.push( all[ i ] );
				}
			}
			
			//var container = Dom.get( configuration.CSS.IDs.topContent );
			//firstBlock = Dom.get( configuration.CSS.IDs.topContent ).getElementsByTagName( "span" )[0];
			//lastBlock = Dom.get( configuration.CSS.IDs.topContent ).getElementsByTagName( "span" )[1];
			
			Dom.setStyle( this.els[0], "display", "none");
			Dom.setStyle( this.els[4], "display", "none");
			
			
			if (Dom.getStyle( this.photo, "width") == "auto" || Dom.getStyle( this.photo, "height") == "auto") { // ie
				Dom.setStyle( this.photo, "width", this.width + "px" );
				Dom.setStyle( this.photo, "height", this.height + "px" );
			} 
		}
	},
	getWeight: function() {
		return this.weight;
	},
	/**
	 *
	 * @param {Integer} weight
	 */ 
	setWeight: function( weight, cfg ) {
		cfg = cfg || {};
		if( this.weight != weight ) {
			this.weight = weight;
			toolbar.setImgWeight( weight );
		}
	},
	/**
	 * @method imageIsSet_
	 * @return Boolean
	 */
	imageIsSet_: function() {
		var img = this.getImg();
		if( img.src === "" ) {
			return false;
		}
		else {
			return true;
		}
	},
	/**
	 * @param {Integer} height
	 * @param {Object} cfg
	 */
	setHeight: function( height, cfg ) {
		cfg = cfg || {};
		var that = this;
		this.height = height;
		if( cfg.anim ) {
			eyp.resize.destroy(); // avoid ugly effect since animation when knobs are visibled
			var anim = new YAHOO.util.Anim( this.photo, { height: { to: height } }, 0.4 );
			anim.onComplete.subscribe(function(){
				Dom.setStyle( that.photoContainer, "height", height + "px");
				eyp.resize.refresh();
			});
			anim.animate();
		}
		else {
			Dom.setStyle( this.photo, "height", height + "px" );
			Dom.setStyle( this.photoContainer, "height", height + "px" );
		}
		toolbar.setImgHeight( height );
	},
	/**
	 * @param {Integer} width
	 * @param {Object} cfg
	 */
	setWidth: function( width, cfg ) {
		cfg = cfg || {};
		var that = this;
		this.width = width;
		if (cfg.anim) {
			eyp.resize.destroy(); // avoid ugly effect since animation when knobs are visibled
			var anim = new YAHOO.util.Anim( this.photo, { width: { to: width } },  0.4 );
			anim.onComplete.subscribe(function(){
				Dom.setStyle( that.photoContainer, "width", width + "px");
				eyp.resize.refresh();
			});
			anim.animate();
		} 
		else {
			Dom.setStyle( this.photo, "width", width + "px" );
			Dom.setStyle( this.photoContainer, "width", width + "px" );
		}
		toolbar.setImgWidth( width );
	},
	/**
	 * @param {Integer} width	- 
	 * @param {Integer} height	- 
	 * @param {Object} cfg		- 
	 */
	setDimensions: function( width, height, cfg ) {
		cfg = cfg || {};
		var that = this;
		this.width = width;
		this.height  = height;
		if( cfg.commit ) {
			this.commitWidth = width;
			this.commitHeight = height;
			this.resetDimensions = false;
		}			
		if( cfg.anim ) {
			eyp.resize.destroy(); // avoid ugly effect since animation when knobs are visibled
			var anim = new YAHOO.util.Anim(this.photo, { width: { to: width }, height: { to: height } }, 0.4 );
			anim.onComplete.subscribe( function(){
				Dom.setStyle( that.photoContainer, "width", width + "px" );
				Dom.setStyle( that.photoContainer, "height", height + "px" );
				eyp.resize.refresh();
			});
			anim.animate();
		}
		else {
			Dom.setStyle( this.photo, "width", width + "px" );
			Dom.setStyle( this.photo, "height", height + "px" );
			Dom.setStyle( this.photoContainer, "width", width + "px" );
			Dom.setStyle( this.photoContainer, "height", height + "px" );
		}
		if( cfg.resizeRefresh ) {
			eyp.resize.refresh();
		}
		toolbar.setImg( width, height );
	},
	/** 
	 * @description
	 * @return {Boolean}
	 */
	hasChanged: function() {
		if( this.commitWidth != this.width || this.commitHeight != this.height ) {
			return [ this.width, this.height ];
		}
		else {
			return false;
		}
	}
};
 /**
 * The editor module
 * @module editor
 */

/**
 * editor manager
 * @class editor
 * @static
 */
var editor = {
	/**
	 * return editor element
	 * @method get
	 * @return HtmlElement
	 */
	get: function() {
		return this.editor;
	},
	/**
	 * editor manager initalziation
	 * @method init
	 */
	init: function() {
		this.editor = Dom.get( configuration.CSS.IDs.editor );
		this.topRuler = Dom.get( configuration.CSS.IDs.topRuler );
		this.leftRuler = Dom.get( configuration.CSS.IDs.leftRuler );	
		
		
		var wrap = Dom.get( "ef-wrap" );
		//Dom.setStyle( this.toolbar, "height", tools.toInt( Dom.getStyle( wrap, "height" ) ) - 30 + "px" );
		//alert( Dom.getStyle( wrap, "width" ) + "---" + wrap.offsetWidth);

		Dom.setStyle( this.topRuler, "width", tools.toInt( Dom.getStyle( wrap, "width" ) )  - tools.toInt( Dom.getStyle( this.editor, "left" ) ) - 20 +2  + "px" );
		
		Dom.setStyle( this.leftRuler, "height",  tools.toInt( Dom.getStyle( wrap, "height" ) ) - 43 + "px" );
		
		Dom.setStyle( this.editor, "width", tools.toInt( Dom.getStyle( wrap, "width" ) ) - tools.toInt( Dom.getStyle( this.editor, "left" ) ) - 20 + "px" );
		Dom.setStyle( this.editor, "height", tools.toInt( Dom.getStyle( wrap, "height" ) ) - 45 + "px" );
	},
	/**
	 * move editor element to the left
	 * @method moveToLeft
	 */
	moveToLeft: function() {
		var width =  tools.toInt( Dom.getStyle( this.editor, "width" ) ) + 134 + "px";
		Dom.setStyle( this.editor, "width", width );
		Dom.setStyle( this.editor, "left", "40px" );
		Dom.setStyle( this.leftRuler, "left", "25px" );
		Dom.setStyle( this.topRuler, "left", "40px" );
		Dom.setStyle( this.topRuler, "width", width );
		eyp.dd.refresh();
		eyp.resize.refresh();
	},
	/**
	 * move editor element to the right
	 * @method moveToRight
	 */
	moveToRight: function() {
		var width = tools.toInt( Dom.getStyle( this.editor, "width" ) ) - 134 + "px";
		Dom.setStyle( this.editor, "width", width );
		Dom.setStyle( this.editor, "left", "174px" );
		Dom.setStyle( this.leftRuler, "left", "159px" );
		Dom.setStyle( this.topRuler, "left", "174px" );
		Dom.setStyle( this.topRuler, "width", width );
		eyp.dd.refresh(); 
		eyp.resize.refresh();
	},
	/**
	 * get editor element width
	 * @return int
	 * @method getWidth
	 */
	getWidth: function() {
		return tools.toInt( Dom.getStyle( this.editor, "width" ) );
	},
	/**
	 * get editor element height
	 * @return int
	 * @method getHeight
	 */
	getHeight: function() {
		return tools.toInt( Dom.getStyle( this.editor, "height" ) );
	}
}; 
/**
 * commands manager. Store information about which operation in currently executing
 * @class cmdMgr
 * @static
 */
var cmdMgr = {
	/**
	 * icons backgrounds
	 */
    backgrounds_: [
        {
            selected        : "1.png",
            unselected    : "1n.png"
        },
        {
            selected        : "2.png",
            unselected    : "2n.png"
        },
        {
            selected        : "3.png",
            unselected    : "3n.png"
        },
        {
            selected        : "4.png",
            unselected    : "4n.png"
        },
        {
            selected        : "5.png",
            unselected    : "5n.png"
        }
    ],
	/**
	 * @property redirectUrl
	 * @value String|null
	 */
	redirectUrl_: null,
	/**
	 * @method setRedirectUrl
	 * @param String url	-
	 */
	setRedirectUrl: function( url ) {
		this.redirectUrl_ = url;
	},
	/**
	 * @method getRedirectUrl
	 * @return String
	 */
	getRedirectUrl: function() {
		return this.redirectUrl_;
	},
	/**
	 * @method isRedirectUrl
	 * @return Boolean
	 */
	isRedirectUrl: function() {
		if( this.redirectUrl_ === null ) {
			return false;
		}
		return true;
	},
	/**
	 * @property currentCmd
	 * @value Int
	 * @private
	 */
	currentCmd_: 0,
	/**
	 * @method init
	 */
	init: function() {
		var that = this;
		
		this.nextButton = Dom.get( configuration.CSS.IDs.forwardButton );
		this.prevButton = Dom.get( configuration.CSS.IDs.backButton );
			
		Event.addListener( this.nextButton, "click", function() {
			that.next(); 
			that.showBackButton();
		});
		
		Event.addListener( this.prevButton, "click", function() {
			that.previous(); 
		});
		
		if( photoMgr.imageIsSet_() ) { // if image is set go to step 2.
			this.nextStep();
			this.showForwardButton();
		}
        
        var container = Dom.get( configuration.CSS.IDs.topContent );
		all = container.getElementsByTagName( "span" );
        this.els = [];
		for( var i = 0; i < all.length; i++ ) {
			if( all[ i ].className == "cmd-block" ) {
				this.els.push( all[ i ] );
			}
		}
		
        this.select( this.getStep() );
        this.start( this.getStep() );
	},
	/** 
	 * next operation
	 * @method next
	 */
    next: function() {

        this.end( this.getStep(), { next: true, onEnd: function() { this.nextCmd(); }, scope: this } );
    },
    
    previous: function() {
    	this.end( this.getStep(), { next: true, onEnd: function() { this.previousCmd(); }, scope: this } );
    },
	/**
	 * @method hideForwardButton
	 */
	hideForwadButton: function() {
		Dom.setStyle( this.nextButton, "display", "none" );
		Dom.setStyle( this.nextButton, "cursor", "default" );
	},
	/**
	 * @method showForwardButton
	 */
	showForwardButton: function() {
		Dom.setStyle( this.nextButton, "display", "block" );
		Dom.setStyle( this.nextButton, "cursor", "pointer" );
		
	},
	showBackButton: function() {
		Dom.setStyle( this.prevButton, "display", "block" );
		Dom.setStyle( this.prevButton, "cursor", "pointer" );
	},
	hideBackButton: function() {
		Dom.setStyle( this.prevButton, "display", "none" );
		Dom.setStyle( this.prevButton, "cursor", "default" );
	},
	setPointer: function() {
		
		for( var i = 0; i < all.length; i++ ) {
			Dom.setStyle(all[i],"cursor", "pointer");
		}

		
	},
	unsetPointer: function() {
		
		for( var i = 0; i < all.length; i++ ) {
			Dom.setStyle(all[i],"cursor", "default");
		}
		
	},

 
	/**
	 * @method backToForm
	 */
	backToForm: function() {
		var that = this;
		var request = new Ajax({
			data				:  "cmd=save&format=" + photoMgr.getFormat() + "&compress=0&file=",
			callback		: {
				onSuccess	: function( o ) {
					loading.hide();
					if( o.responseText === "ok" ) {
						location.href =  that.getRedirectUrl() ;
					}
					else {
						dialogs.errorDialogShow( o.responseText );
					}
				},
				onFailure		: function( o ) { 
					dialogs.errorDialogShow( o.responseText );
				}
			}
		});
		request.send();
		
	},
    /**
     * select icon
     * @method select
     * @param int index
     */
    select: function( index ) {
         var el = this.els[ index ];
        var img = this.backgrounds_[ index ].selected;
        Dom.setStyle( el, "backgroundImage", "url( images/" + img + ")" );
        var text = el.getElementsByTagName( "span" )[ 0 ];
		Dom.setStyle( text, "fontWeight", "bold" );
    },
    /**
     * unselect icon
     * @method unselect
     * @param int index
     */
    unselect: function( index ) {
		//console.debug( "unselect", index );
        var el = this.els[ index ];
        var img = this.backgrounds_[ index ].unselected;
        Dom.setStyle( el, "backgroundImage", "url( images/" + img + ")" );
        var text = el.getElementsByTagName( "span" )[ 0 ];
		Dom.setStyle( text, "fontWeight", "normal" );
    },
	/**
	 * return current step
	 * @method getSteop
	 * @return int
	 */
    getStep: function() {
        return this.currentCmd_;
    },
	/**
	 * set step
	 * @method setStep
	 * @param int index	-
	 */
    setStep: function( index ) {
        this.currentCmd_ = index;
    },
	/**
	 * go to the next step
	 * @method nextStep
	 */
    nextStep: function() {
        this.setStep( this.getStep() + 1 );
    },
    backStep: function() {
    	this.setStep(this.getStep() - 1);	
    },
    /**
     * @method goToStep
     * @param int index     -
     */
    goToStep: function( index ) {
		
		var that = this;
		
        if( !photoMgr.isSet() ) { // wait until photo is downloaded
            return false;
        }
        
        if(index == this.getStep()) {
        	return false;
        }
        
        this.end( this.getStep(), { next: false, onEnd: function() {
			this.start( index );
		}, scope: this } );
        this.unselect( this.getStep() );
		this.setStep( index );
        this.select( index );
        
        if( index == 3 && this.isRedirectUrl() ) {
		
			this.nextButton.firstChild.nodeValue = lang.buttons.backToForm;
			Event.addListener( this.nextButton, "click", function() { 
				that.backToForm();
			});
			Dom.setStyle( this.nextButton, "background", "#fff" );
		}
        
        
    },
    /**
     * @method start
     * @param int index
     */
    start: function( index ) {
        var item = COMMANDS[ index ];
        item.onStart.call( item.scope );
    },
    /**
     * @method end
     * @param int index
     */
    end: function( index, cfg )  {
        var item = COMMANDS[ index ];
		item.onAccept.call( item.scope, cfg );
    },
	/**
	 * next command
	 * @method nextCmd
	 */
	nextCmd: function() {
		var that = this;
		this.unselect( this.getStep() );
        this.nextStep();
        this.select( this.getStep() );
		
        var step = this.getStep();
        
		if( step == 3 && this.isRedirectUrl() ) {
		
			this.nextButton.firstChild.nodeValue = lang.buttons.backToForm;
			Event.removeListener( this.nextButton, "click" );
			Event.addListener( this.nextButton, "click", function() { 
				that.backToForm();
			});
			Dom.setStyle( this.nextButton, "background", "#fff" );
		}
        this.start( step );
	},
	/**
	 * previous command
	 * @method previousCmd
	 */
	previousCmd: function() {
		this.unselect( this.getStep() );
        this.backStep();
        this.select( this.getStep() );
        
        var step = this.getStep();
        
        this.start( step );
        
	}
};

/**
 * @class contrastMgr
 * @static
 */
contrastMgr = {
    /**
     * @method init
	 * @private
     */
    init_: function() {
		var that = this;
		
		this.slider_ = YAHOO.widget.Slider.getVertSlider( "contrast-slider-bg",  
			"contrast-slider-thumb", 
			0, 
			200
		);
		
		this.slider_.subscribe( "change", function( offsetFromStart ) {
			Dom.get( configuration.CSS.IDs.contrastValue ).firstChild.nodeValue = offsetFromStart - 100;
		});

		this.slider_.subscribe( "slideStart", function() {tooltipMgr.hide();} );

		this.slider_.subscribe( "slideEnd", function() {
			that.request = new Ajax({
				data        :  eyp.createData( "contrast", {
					degree : this.getValue() - 100
				}),
				callback : {
					onSuccess: function(o) {
						eyp.loadImage( o.responseText, {
							stop: true
						});
					},
					onFailure: function(o) {}
				}
			});
			that.request.send();
		});
    },
	/**
	 * @method show
	 */
	show: function() {
		if( !this.slider_ ) {
			this.init_();
		}
		toolbar.hideBasicControls();
        toolbar.showContrastControls();
		this.slider_.setValue( 100, true, true, true );
        tooltipMgr.show( "Wykorzystaj suwak aby zmienić kontrast zdjęcia" );
	}
};

/**
 * comands in execution order
 */
var COMMANDS = [
	{ 
		onStart		: function () {photoMgr.unSet();upload.show();},
		scope		: upload,
		onAccept	: function( cfg ) { 
            upload.send();
			cfg.onEnd.call( cfg.scope );
        }
	},
	{
		onStart		: function() { 
			photoMgr.set();
			
			if( cmdMgr.isRedirectUrl() ) {
				cmdMgr.hideBackButton();
			}
		},
		scope		: null,
		onAccept	: function( cfg ) { 
			
			if ( queue.getAll().length > 0 ) {
				var request = new Ajax( {
					data			: eyp.createData( "resize" ),
					callback	: {
							onSuccess 	: function( o ) {
								eyp.loadImage( o.responseText, { resize: false } );
								eyp.resize.destroy();
								
								cfg.onEnd.call( cfg.scope );
								
							},
							onFailure		: function( o ) { }
						}
					});
				request.send();
			}
            else {
				cfg.onEnd.call( cfg.scope );
            }
		}
	},
	{
		onStart		: function() { cropper.on();photoMgr.set();},
		scope		: cropper,
		onAccept	: function( cfg ) {
            cropper.send();
			cfg.onEnd.call( cfg.scope );
        }
	},
	{
		onStart		: function() {
			contrastMgr.show();
			photoMgr.set();
		},
		scope		: contrastMgr,
		onAccept	: function( cfg ) { 
			toolbar.hideContrastControls();
            toolbar.showBasicControls();
			tooltipMgr.hide();
			eyp.resize.init();
			cfg.onEnd.call( cfg.scope );
		}
	},
	{
		onStart		: function() {
			save.show();
		},
		scope		: save,
		onAccept	: function ( cfg ) {
			
			cfg.onEnd.call( cfg.scope );
			
			if( cfg && cfg.next === true ) {
				location.href = "/";
			}
			else {
				save.hide();
			}
		}
	}
];
 /**
 * @class tooltipMgr
 * @static
 */
var tooltipMgr = {
	tooltipDialog_ 		: undefined,
	tooltipEl_				: undefined,
	tooltipTimeout_		: undefined,
	tooltipTime_			: 1000 * 20,

	/**
	 * initialization
	 * @method init_
	 */
	init_ : function() {
		var that = this;
	
		this.tooltipEl_ = Dom.get( configuration.CSS.IDs.tooltip );
		this.tooltipDialog_ = new YAHOO.widget.Overlay( this.tooltipEl_, { 
			visible	: false, 
			width	: "198px" 
		});		
		
		Dom.setStyle( this.tooltipEl_, "display", "block" ); // show dialog container
		this.tooltipDialog_.render();
        
		// dialog positioning
        var editorEl = editor.get()
        var xy = Dom.getXY( editorEl );

		this.tooltipDialog_.moveTo( xy[ 0 ] -312 ,  xy[ 1 ] + 60 );
        
		this.tooltipCloseButton = Dom.get( configuration.CSS.IDs.tooltipCloseButton );
		Event.addListener( this.tooltipCloseButton, "click", function() {
			that.hide();
		});
	},
	/**
	 * @method resetTimeout_
	 * @param Number timeout	-
	 */
	resetTimeout_: function( timeout ) {
		if( this.tooltipTimeout_ ) {
			clearTimeout( this.tooltipTimeout_ );
		}
		var that = this;
		this.tooltipTimeout_ = setTimeout( function() {
			that.hide();
		}, timeout || this.tooltipTime_ );
	},
	/**
	 * @method init
	 * @param String txt				-
	 * @param Number timeout	-
	 */
	show : function( txt, timeout ) {
		if( !this.tooltipDialog_ ) {
			this.init_();
		}
		this.tooltipDialog_.setBody( txt );	
		this.tooltipDialog_.show();
		this.resetTimeout_( timeout );
	},
	/**
	 * @method hide
	 */
	hide : function() {
		if( !this.tooltipDialog_ ) {
			return;
		}
		this.tooltipDialog_.hide();
		clearTimeout( this.tooltipTimeout_  );
	}
}; 
