/**
 * SbImage scripts
 *
 * @copyright (c) 2004-2008, SWsoft
 */
function InitSbImage() {
	self.parent.sbImageObject = new SbImage();
}

function SetUrl(url, width, height, alt) {
	self.parent.sbImageObject.setUrl(url, width, height, alt);
}

var SbImage = Class.create();
SbImage.prototype = {

	/**
	 * Current method for setUrl (link or image)
	 *
	 * @var method
	 * @access private
	 */
	_setUrlMethod: null,

	/**
	 * Indicates that aspect ratio is locked
	 *
	 * @var bool
	 * @access private
	 */
	_isAspectRatioLocked: true,

	/**
	 * WYSIWYG image object
	 *
	 * @var obj
	 * @access private
	 */
	_image: null,

	/**
	 * WYSIWYG link object
	 *
	 * @var obj
	 * @access private
	 */
	_link: null,

	/**
	 * Preview image object
	 *
	 * @var obj
	 * @access private
	 */
	_previewImage: null,

	/**
	 * Preview link object
	 *
	 * @var obj
	 * @access private
	 */
	_previewLink: null,

	/**
	 * Original image object
	 *
	 * @var obj
	 * @access private
	 */
	_originalImage: null,

	/**
	 * FCK editor objects structure like
	 * {
	 *		FCK: self.FCK,
	 *		FCKUndo: self.FCKUndo,
	 *		FCKSelection: self.FCKSelection,
	 *		FCKLang: self.FCKLang,
	 *		FCKConfig: self.FCKConfig,
	 *		FCKDebug: self.FCKDebug,
	 *		FCKBrowserInfo: self.FCKBrowserInfo
	 * }
	 *
	 * @var obj
	 * @access private
	 */
	_fckObject: null,

	/**
	 * Image helper object
	 *
	 * @var obj
	 * @access private
	 */
	_helper: null,

	/**
	 * Indicates that image providers banners are enabled
	 *
	 * @var bool
	 * @access private
	 */
	_isImageProvidersBannersEnabled: false,

	/**
	 * Current image src
	 *
	 * @var string
	 * @access private
	 */
	_currentSrc: '',

	/**
	 * Object constructor
	 *
	 * @access public
	 * @return void
	 */
	initialize: function() {
		this._helper = self.parent.getSbImageHelperInstance();
		this._fckObject = this._helper.getFckObject();

		var manager = this;
		var initMethod = function () { manager.initDialogControls(); };
		Event.observe(self, 'load', initMethod);
	},

	/**
	 * Enables image providers banners
	 *
	 * @access public
	 * @return void
	 */
	enableImageProvidersBanners: function() {
		this._isImageProvidersBannersEnabled = true;
		$('sbImageProvidersBannersContainer').show();
	},

	/**
	 * Saves all user data and closes form dialog
	 *
	 * @access public
	 * @return void
	 */
	ok: function() {
		var srcInput = $('sbImageSrc');
		if (0 == srcInput.value.length) {
			self.sb_panel.tooglePage('imageProperties');
			srcInput.focus();
			alert(this._fckObject.FCKLang.DlgImgAlertUrl);
			return false;
		}
		this._helper.restoreSelection();
		var isImageExists = (this._image != null);

		if (isImageExists && this._image.tagName == 'INPUT') {
			if (confirm('Do you want to transform the selected image button on a simple image?')) {
				this._image = null;
			}
		}
		if (!isImageExists) {
			this._image = this._fckObject.FCK.CreateElement('IMG');
		} else {
			this._fckObject.FCKUndo.SaveUndoStep();
		}
		this._updateImage(this._image);

		var sLnkUrl = $('sbImageLinkUrl').value.strip();
		if (0 == sLnkUrl.length) {
			if (this._link) {
				this._fckObject.FCK.ExecuteNamedCommand('Unlink');
			}
		} else {
			if (this._link) {
				this._link.href = sLnkUrl;
			} else {
				if (!isImageExists) {
					this._fckObject.FCKSelection.SelectNode(this._image);
				}
				this._link = this._fckObject.FCK.CreateLink(sLnkUrl);
				if (!isImageExists) {
					this._fckObject.FCKSelection.SelectNode(this._link);
					this._fckObject.FCKSelection.Collapse(false);
				}
			}
			this._setAttribute(this._link, '_fcksavedurl', sLnkUrl);
			this._setAttribute(this._link, 'target', $('sbImageLinkTarget').value);
		}
		this._fckObject.FCK.Commands.GetCommand('SbTranslator').Execute();

		this.close();
	},

	/**
	 * Closes form dialog without saving
	 *
	 * @access public
	 * @return void
	 */
	close: function() {
		parent.sbImageFormObject.close();
	},

	/**
	 * Executes after form has been closed
	 *
	 * @access public
	 * @return void
	 */
	onClose: function() {
		this._helper.restoreSelection();
		this._fckObject.FCK.Focus();
		this._clearDialog();
	},

	/**
	 * Executes then mouse overs on aspect ratio control
	 *
	 * @access public
	 * @return void
	 */
	onAspectRatioMouseOver: function() {
		var control = $('sbImageAspectRatioControl');
		control.className = (this._isAspectRatioLocked ? 'BtnLocked' : 'BtnUnlocked') + ' BtnOver';
	},

	/**
	 * Executes then mouse outs the aspect ratio control
	 *
	 * @access public
	 * @return void
	 */
	onAspectRatioMouseOut: function() {
		var control = $('sbImageAspectRatioControl');
		control.className = this._isAspectRatioLocked ? 'BtnLocked' : 'BtnUnlocked';
	},

	/**
	 * Switches aspect ratio control
	 *
	 * @access public
	 * @return void
	 */
	switchAspectRatio: function() {
		this._isAspectRatioLocked = !this._isAspectRatioLocked;
		this._setRatioControlVisualProperties();
		if (this._isAspectRatioLocked) {
			if ($('sbImageWidth').value.length > 0) {
				this.onSizeChanged($('sbImageWidth'));
			} else {
				this.onSizeChanged($('sbImageHeight'));
			}
		}
	},

	/**
	 * Resets image sizes
	 *
	 * @access public
	 * @return void
	 */
	resetSizes: function() {
		if (!this._originalImage) {
			return;
		}
		$('sbImageWidth').value  = this._originalImage.width;
		$('sbImageHeight').value = this._originalImage.height;
		this.updatePreviewImage();
	},

	/**
	 * Executes then size has been changed
	 *
	 * @access public
	 * @return void
	 */
	onSizeChanged: function(element) {
		if (this._originalImage && this._isAspectRatioLocked) {
			var value = element.value;
			if (value.length == 0 || isNaN(value)) {
				element.value = '';
				return;
			}
			var elementToUpdate;
			if ('sbImageWidth' == element.id) {
				value = (0 == value)
					? 0
					: Math.round(this._originalImage.height * (value / this._originalImage.width));
				elementToUpdate = $('sbImageHeight');
			} else {
				value = (0 == value)
					? 0
					: Math.round(this._originalImage.width * (value / this._originalImage.height));
				elementToUpdate = $('sbImageWidth');
			}
			if (!isNaN(value)) {
				elementToUpdate.value = value;
			}
		}
		this.updatePreviewImage();
	},

	/**
	 * Opens server browser dialog for images
	 *
	 * @access public
	 * @return void
	 */
	browseImageServer: function() {
		this._setUrlMethod = function(url, width, height, alt) { this._setImage(url, width, height, alt); };
		this._openFileBrowser(
			this._fckObject.FCKConfig.ImageBrowserURL + '&v3',
			this._fckObject.FCKConfig.ImageBrowserWindowWidth,
			this._fckObject.FCKConfig.ImageBrowserWindowHeight
		);
	},

	/**
	 * Opens server browser dialog for links
	 *
	 * @access public
	 * @return void
	 */
	browseLinkServer: function() {
		this._setUrlMethod = function(url, width, height, alt) { this._setLink(url); };
		this._openFileBrowser(
			this._fckObject.FCKConfig.LinkBrowserURL + '&v3',
			this._fckObject.FCKConfig.LinkBrowserWindowWidth,
			this._fckObject.FCKConfig.LinkBrowserWindowHeight
		);
	},

	/**
	 * Sets object params from image or link browser
	 *
	 * @access public
	 * @param string url
	 * @param string width
	 * @param string height
	 * @param string alt
	 * @return void
	 */
	setUrl: function(url, width, height, alt) {
		url = this._helper.getRelativeImageUrl(url);
		url = encodeURI(url);
		url = url.replace(/\#/ig, '%23');

		this._setUrlMethod(url, width, height, alt);
	},

	/**
	 * Sets image souce
	 *
	 * @access public
	 * @param string
	 * @return void
	 */
	setSrc: function(src) {
		this._setImage(src, '', '', '');
	},

	/**
	 * Updates image preview
	 *
	 * @access public
	 * @return void
	 */
	updatePreviewImage: function() {
		if (!this._previewImage || !this._previewLink) {
			return;
		}

		if (0 == $('sbImageSrc').value.length) {
			this._previewLink.style.display = 'none';
		} else {
			this._updateImage(this._previewImage, true);

			if ($('sbImageLinkUrl').value.strip().length > 0) {
				this._previewLink.href = 'javascript:void(null);';
			} else {
				this._setAttribute(this._previewLink, 'href', '');
			}
			this._previewLink.style.display = '';
		}
	},

	/**
	 * Creates original image object
	 *
	 * @access public
	 * @param bool flag to reset image size
	 * @param bool flag to update ratio control
	 * @param bool flag to asynchronous request for banners
	 * @return void
	 */
	updateOriginalImage: function(resetSize, updateRatioControl, asynchronous) {
		if (!this._previewImage) {
			return;
		}

		this._originalImage = document.createElement('IMG');
		var manager = this;
		var isResetSizes = resetSize;
		var isUpdateRatioControl = updateRatioControl;
		this._originalImage.onload = function() {
			if (isResetSizes) {
				manager.resetSizes();
			}
			if (isUpdateRatioControl) {
				manager.updateRatioControl();
			}
		}
		this._originalImage.src = this._previewImage.src;

		if (this._isImageProvidersBannersEnabled) {
			var browseGalleryButton = $('fotoliaBrowseGalleryButton');
			if (browseGalleryButton) {
				browseGalleryButton.onclick = null;
				self.disableButton(browseGalleryButton);
			}

			var requestParameters = new Object();
			requestParameters.src = $('sbImageSrc').value;
			var requestUrl = self.parent.baseUrl + '/Ajax/Wizard/Edit/Wysiwyg/SbImageProvidersBanners';
			var container = $('sbImageProvidersBannersContainer');

			var request = new SbAjaxRequest.ContainerUpdater(
				requestUrl,
				requestParameters,
				container,
				{
					addOverlayText: false,

					asynchronous: asynchronous
				}
			);
		}
	},

	/**
	 * Inits ratio control for current image
	 *
	 * @access public
	 * @return void
	 */
	updateRatioControl: function() {
		this._isAspectRatioLocked = true;
		if (!this._image) {
			this._setRatioControlVisualProperties();
			return;
		}
		var preiviewWidth = parseInt(this._previewImage.width);
		if (isNaN(preiviewWidth) || (0 == preiviewWidth)) {
			this._setRatioControlVisualProperties();
			return;
		}
		var preiviewHeight = parseInt(this._previewImage.height);
		if (isNaN(preiviewHeight) || (0 == preiviewHeight)) {
			this._setRatioControlVisualProperties();
			return;
		}
		var originalWidth = parseInt(this._originalImage.width);
		if (isNaN(originalWidth) || (0 == originalWidth)) {
			this._setRatioControlVisualProperties();
			return;
		}
		var originalHeight = parseInt(this._originalImage.height);
		if (isNaN(originalHeight) || (0 == originalHeight)) {
			this._setRatioControlVisualProperties();
			return;
		}
		var widthRatio = preiviewWidth / originalWidth;
		var heightRatio = preiviewHeight / originalHeight;
		if (Math.abs(widthRatio - heightRatio) > 1 / 100) {
			this._isAspectRatioLocked = false;
		}
		this._setRatioControlVisualProperties();
	},

	/**
	 * Prepares form dialog
	 *
	 * @access public
	 * @return void
	 */
	prepareNewDialog: function() {
		this._loadSelection();
		this.updatePreviewImage();
		this.updateOriginalImage(false, true, true);
		$('sbImageSrc').focus();
	},

	/**
	 * Inits dialog controls
	 *
	 * @access public
	 * @return void
	 */
	initDialogControls: function() {
		this._previewImage = $('sbImagePreview');
		this._previewLink = $('sbImageLinkPreview');
		$('sbImageResetSizeControl').title = self.SbGetLocaleByKey('resetSize');

		var manager = this;
		Event.observe($('sbImageSrc'), 'focus',
			function () { manager._currentSrc = this.value; }
		);
		Event.observe($('sbImageSrc'), 'blur',
			function () {
				if (this.value != manager._currentSrc) {
					manager.updatePreviewImage();
					manager.updateOriginalImage(false, false, true);
				}
			}
		);
		var updateMethod = function () { manager.updatePreviewImage(); };
		Event.observe($('sbImageBorder'), 'keyup', updateMethod);
		Event.observe($('sbImageHspace'), 'keyup', updateMethod);
		Event.observe($('sbImageVspace'), 'keyup', updateMethod);
		Event.observe($('sbImageAlign'), 'change', updateMethod);
		Event.observe($('sbImageLinkUrl'), 'blur', updateMethod);

		var onSizeChangedMethod = function() { manager.onSizeChanged(this); };
		Event.observe($('sbImageWidth'), 'keyup', onSizeChangedMethod);
		Event.observe($('sbImageHeight'), 'keyup', onSizeChangedMethod);

		this.prepareNewDialog();

		var prepareMethod = function() { manager.prepareNewDialog(); };
		parent.sbImageFormObject.observeOnAfterOpen(prepareMethod);

		var onCloseMethod = function() { manager.onClose(); };
		parent.sbImageFormObject.observeOnAfterClose(onCloseMethod);

		Event.observe(self, 'unload', function () { parent.sbImageFormObject.resetEventsListeners(); } );
	},

	/**
	 * Replaces image after purchase process
	 *
	 * @access public
	 * @param string
	 * @param string
	 * @return void
	 */
	replaceImage: function(fromSrc, toSrc) {
		var currentSrc = $('sbImageSrc').value;
		if (currentSrc != fromSrc) {
			return;
		}
		$('sbImageSrc').value = toSrc;
		this.updatePreviewImage();
		this.updateOriginalImage(false, false, true);
	},

	/**
	 * Loads current FCKeditor selection
	 *
	 * @access private
	 * @return void
	 */
	_loadSelection: function() {
		var imageInfo = this._helper.getSelectedImageInfo();
		if (!imageInfo || !imageInfo.image) {
			return;
		}
		this._image = imageInfo.image;

		$('sbImageSrc').value = imageInfo.src;
		$('sbImageAlt').value = imageInfo.alt;
		$('sbImageVspace').value = imageInfo.vspace;
		$('sbImageHspace').value = imageInfo.hspace;
		$('sbImageBorder').value = imageInfo.border;
		$('sbImageAlign').value = imageInfo.align;
		$('sbImageWidth').value = imageInfo.width;
		$('sbImageHeight').value = imageInfo.height;
		$('sbImageId').value = imageInfo.id;
		$('sbImageDirection').value = imageInfo.dir;
		$('sbImageLanguageCode').value = imageInfo.lang;
		$('sbImageAdvisoryTitle').value = imageInfo.title;
		$('sbImageStylesheetClasses').value = imageInfo.className;
		$('sbImageLongDescriptionUrl').value = imageInfo.longDesc;
		$('sbImageStyle').value = imageInfo.style;

		this._link = imageInfo.link;
		if (this._link) {
			$('sbImageLinkUrl').value = imageInfo.linkHref;
			$('sbImageLinkTarget').value = imageInfo.linkTarget;
		}
		tempImage = null;
	},

	/**
	 * Updates ratio control
	 *
	 * @access private
	 * @return void
	 */
	_setRatioControlVisualProperties: function() {
		var control = $('sbImageAspectRatioControl');
		control.title = this._isAspectRatioLocked
			? self.SbGetLocaleByKey('unlockRatio') : self.SbGetLocaleByKey('lockRatio');
		control.className = this._isAspectRatioLocked ? 'BtnLocked' : 'BtnUnlocked';
	},

	/**
	 * Updates image from form values
	 *
	 * @access private
	 * @param obj element
	 * @param bool Indicates that method must updates image id attribute
	 * @return void
	 */
	_updateImage: function(element, isUpdateId) {

		this._helper.setImageSrc(element, $('sbImageSrc').value);

		this._setAttribute(element, 'alt'   , $('sbImageAlt').value);
		this._setAttribute(element, 'width' , $('sbImageWidth').value);
		this._setAttribute(element, 'height', $('sbImageHeight').value);
		this._setAttribute(element, 'vspace', $('sbImageVspace').value);
		this._setAttribute(element, 'hspace', $('sbImageHspace').value);
		this._setAttribute(element, 'border', $('sbImageBorder').value);
		this._setAttribute(element, 'align' , $('sbImageAlign').value);

		if (!isUpdateId) {
			this._setAttribute(element, 'id', $('sbImageId').value);
		}
		this._setAttribute(element, 'dir', $('sbImageDirection').value);
		this._setAttribute(element, 'lang', $('sbImageLanguageCode').value);
		this._setAttribute(element, 'title', $('sbImageAdvisoryTitle').value);
		this._setAttribute(element, 'class', $('sbImageStylesheetClasses').value);
		this._setAttribute(element, 'longDesc', $('sbImageLongDescriptionUrl').value);

		if (this._fckObject.FCKBrowserInfo.IsIE) {
			element.style.cssText = $('sbImageStyle').value;
		} else {
			this._setAttribute(element, 'style', $('sbImageStyle').value);
		}
	},

	/**
	 * Sets element attribute
	 *
	 * @access private
	 * @param object element
	 * @param string element name
	 * @param string value
	 * @return string
	 */
	_setAttribute: function(element, name, value) {
		this._helper.setAttribute(element, name, value);
	},

	/**
	 * Cleares form dialog
	 *
	 * @access private
	 * @return void
	 */
	_clearDialog: function() {
		var controlsList = new Array(
			'sbImageSrc',
			'sbImageAlt',
			'sbImageWidth',
			'sbImageHeight',
			'sbImageBorder',
			'sbImageHspace',
			'sbImageVspace',
			'sbImageAlign',
			'sbImageLinkUrl',
			'sbImageLinkTarget',
			'sbImageId',
			'sbImageDirection',
			'sbImageLanguageCode',
			'sbImageLongDescriptionUrl',
			'sbImageStylesheetClasses',
			'sbImageAdvisoryTitle',
			'sbImageStyle'
		);
		for (var i = 0; i < controlsList.length; i++) {
			$(controlsList[i]).value = '';
		}
		this._image = null;
		this._link = null;
		this._originalImage = null;
		this._previewImage.src = '/images/blank.gif';
		this._currentSrc = '';
		self.sb_panel.tooglePage('imageProperties');
	},

	/**
	 * Opens file browser window
	 *
	 * @access private
	 * @param string url
	 * @param string width
	 * @param string height
	 */
	_openFileBrowser: function(url, width, height) {
		var iLeft = (this._fckObject.FCKConfig.ScreenWidth  - width) / 2;
		var iTop  = (this._fckObject.FCKConfig.ScreenHeight - height) / 2;

		var sOptions = "toolbar=no,status=no,resizable=yes,dependent=yes" ;
		sOptions += ",width=" + width ;
		sOptions += ",height=" + height ;
		sOptions += ",left=" + iLeft ;
		sOptions += ",top=" + iTop ;

		var oWindow = null;
		if (this._fckObject.FCKConfig.PreserveSessionOnFileBrowser && this._fckObject.FCKBrowserInfo.IsIE) {
			oWindow = self.open(url, 'FCKBrowseWindow', sOptions);
			if (oWindow) {
				oWindow.opener = self;
			} else {
				alert(this._fckObject.FCKLang.BrowseServerBlocked);
			}
		} else {
			oWindow = window.open(url, 'FCKBrowseWindow', sOptions);
		}
	},

	/**
	 * Sets image
	 *
	 * @access private
	 * @param string url
	 * @param string width
	 * @param string height
	 */
	_setImage: function(url, width, height, alt) {
		$('sbImageSrc').value = url;
		$('sbImageWidth').value = width ? width : '';
		$('sbImageHeight').value = height ? height : '';

		if (alt) {
			$('sbImageAlt').value = alt;
		}
		this.updatePreviewImage();
		this.updateOriginalImage(true, false, false);
	},

	/**
	 * Sets link
	 *
	 * @access private
	 * @param string url
	 * @param string width
	 * @param string height
	 */
	_setLink: function(url) {
		$('sbImageLinkUrl').value = url;
		this.updatePreviewImage();
	}
}