var TImagesSelectorItem = Class.create();
TImagesSelectorItem.prototype = {
	initialize: function (container, jsonObj) {
		Object.extend (this, TemplatedElement);
		this._buildFromTemplate('images_selector_item_template');
		this.jsonObj = jsonObj;
		this.container = container;

		this.setupImage(false);

		this.element.title = jsonObj.filename;
		this.infoElement.innerHTML = jsonObj.filename;

		this.container.imagesListElement.appendChild (this.element);
		this.selected = false;
	},
	setupImage: function (disableCache) {
		this.imageElement.src = this.container.files_dir + '/' + this.jsonObj.filename;

		var imgW = this.jsonObj.width;
		var imgH = this.jsonObj.height;
		var mxdW = this.container.listMaxImageWidth;
		var mxdH = this.container.listMaxImageHeight;

		if (imgW > mxdW || imgH > mxdH) {
			if (imgW/imgH > mxdW/mxdH) {
				this.imageElement.style.width = '100%';
				var scaledHeight = mxdW * imgH / imgW;
				this.imageElement.style.marginTop = (mxdH - scaledHeight ) / 2 + "px";
			} else {
				this.imageElement.style.height = '100%';
			}
		} else {
			this.imageElement.style.marginTop = (mxdH - imgH) / 2 + "px";
		}
	},
	// when the user overrides with new image
	rebuildWithNewData: function (jsonObj) {
		jsonObj.filename += '?r=' + Math.random() * 100
		this.jsonObj = jsonObj;
		this.setupImage(true);
	},
	free: function () {
		this.container.imagesListElement.removeChild (this.element);
	},
	select: function () {
		this.selected = true;
		this.container.onImageSelected(this);
		Element.addClassName (this.element, 'selected');
	},
	deselect: function () {
		this.selected = false;
		Element.removeClassName (this.element, 'selected');
	},
	onElementClick: function (event) {
		if (!this.selected)
			this.select();
		else
			this.container.setNoSelected();
	},
	onDblClick: function (event) {
		if (!this.selected) this.select();
		this.container.onClickOK();
	},
	onMouseOver: function (event) {
		Element.addClassName (this.element, 'hovered');
	},
	onMouseOut: function (event) {
		Element.removeClassName (this.element, 'hovered');
	},
/* */
	onClickDelete: function () {
		var text = 'Are you sure you want to permanently delete this image?';
		if (this.jsonObj.players)
			text += "\nThis image is used in " + this.jsonObj.players + " players.\n" +
				"Deleting this image will result in changes of the looks of them";
		if (confirm(text)) {
			this.container.deleteImage(this);
		}
	},
/* */
	setMarginRight: function (margin) {
		this.element.style.marginRight = margin + "px";
	},
	setMarginLeftRight: function (l, r) {
		this.element.style.marginRight = r + "px";
		this.element.style.marginLeft = l + "px";
	}
}
var TImagesSelector = Class.create();
TImagesSelector.prototype = {
	scriptImagesURL: '/edit_embedded_images.php',
	currentSelected: null,
	maxImageWidth: 100,
	maxImageHeight: 100,
	// these are just for the list display:
	listMaxImageWidth: 100,
	listMaxImageHeight: 100,
	listItemWidth: 106,
	listItemHeight: 130,
	previewWidth:245,previewHeight:250,
	expandToMaximumIfSmaller: false, // if true the image is allowed to scale UP to fill the maximum allowed space, in case it is smaller
	inputName: 'image',
	selectedImage: '',
	loadOnEveryOpen: false,
	containers: [],
	container: null,
	useFileName: false,

	initialize: function (options) {
		Object.extend (this, TemplatedElement);
		Object.extend (this, options || {});
		this._buildFromTemplate('images_selector_template', false);
		//this.container = $(container);

		//this.container.appendChild (this.element);
		this.visible = false;
		this.items = new Array();

		this._loadImages_handler = this.loadImages_handler.bind(this);
		this._checkUploadProgress = this.checkUploadProgress.bind(this);
		this._checkUploadProgress_handler = this.checkUploadProgress_handler.bind(this);
		this._deleteImage_handler = this.deleteImage_handler.bind(this),
		this.onmm = this.onUpdateMove.bindAsEventListener(this);
		this.onmu = this.onEndMove.bindAsEventListener(this);
		this.onmmr = this.onUpdateResize.bindAsEventListener(this);
		this.onmur = this.onEndResize.bindAsEventListener(this);
		this.clc = this.calculateListColumns.bind(this);

		this.scroll = new Scrollbar (this.imagesListElement, this.imagesListScroll);
		this.scroll.button_height = 15;
		/*this.scroll.button.src = TB_SCROLL_BTN;
		// some fucked up IE issue - makes the new image with the old size!
		this.scroll.button.style.height = '15px';
		this.scroll.button.style.width = '17px';
		this.btnScrollUp.src = TB_SCROLL_UP;
		this.btnScrollDown.src = TB_SCROLL_DOWN;*/

		this.inpFileUpload = new TCustomFileInput('image');
		this.customFileInputContainer.appendChild(this.inpFileUpload.element);
		this.inpFileUpload.allowedExtensions = ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'tiff'];

		//this.attachSelector (container, options);

		// load box size and position information
		/*var p = Cookies.getValue ('img_sel_box_s', '');
		if (p) {
			var s = p.split(',');
			this.selectBox.style.width = s[0] + "px";
			this.selectBox.style.height = s[1] + "px";
			this.rightColumn.style.height = this.imagesListElement.style.height = parseInt(s[1]) - 10 + "px";
			this.element.style.left = s[2] + "px";
			this.element.style.top = s[3] + "px";
		}*/

		/*if (!this.loadOnEveryOpen)
			this.loadImages();*/
	},
	setOptions: function (name, options) {
		for (var i = 0, n = this.containers.length; i < n; i ++)
			if (this.containers[i].options.name == name) {
				Object.extend (this.containers[i].options, options);
				var container = this.containers[i];
				var selItem = null;
				// set the button and the input
				if (container.options.selectedImage) {
					container.selectedImageInput.value = container.options.selectedImage;
					if (container.options.useFileName) { // if container.options.selectedImage is file name....
						var selItem = this.getItemByFilename(container.options.selectedImage);
					} else {
						var selItem = this.getItemById(container.options.selectedImage);
					}
					if (selItem) {
						//container.openButton.innerHTML = container.options.selectedImage;
						container.openButton.innerHTML = '[ ' + selItem.jsonObj.filename + ' ]';
						if (container.options.scaledWidthInputName || container.options.scaledHeightInputName) {
							var ss = this.getMaxImageSizes (selItem.jsonObj.width, selItem.jsonObj.height, container.options.maxImageWidth, container.options.maxImageHeight, container.options.expandToMaximumIfSmaller);
							container.scaledWidthInput.value = ss.scaledWidth;
							container.scaledHeightInput.value = ss.scaledHeight;
						}
						if (container.options.onChange)
							container.options.onChange (selItem.jsonObj.id, ss.scaledWidth, ss.scaledHeight); // stupid IE
					} else {
						container.openButton.innerHTML = '[ ' + (container.options.disabledText?container.options.disabledText:'no image') + ' ]';
						container.selectedImageInput.value = '';
						if (container.options.onChange)
							container.options.onChange ('');
					}
				} else {
					container.openButton.innerHTML = '[ ' + (container.options.disabledText?container.options.disabledText:'no image') + ' ]';
					container.selectedImageInput.value = '';
					if (container.options.onChange)
						container.options.onChange ('');
				}
				if (!container.options.enabled)
					Element.addClassName (container.openButton, 'disabled');
				else
					Element.removeClassName (container.openButton, 'disabled');
				break;
			}
	},

	attachSelector: function (container, options) {
		container = $(container);
		var data = {options:{maxImageWidth:'auto', maxImageHeight:'auto', useFileName: false, expandToMaximumIfSmaller: false, enabled: true, disabledText: ''}, container: $(container)};
		Object.extend (data.options, options || {});

		data.openButton = document.createElement ('span');
		data.openButton.className = 'images_selector_open_button';
		data.openButton.onclick = this.showhideBox.bindAsEventListener(this, this.containers.length); // which container opens the box
		data.openButton.innerHTML = (data.options.selectedImage? data.options.selectedImage: '[ ' + (data.options.disabledText?container.options.disabledText:'no image') + ' ]');

		data.selectedImageInput = document.createElement ('input');
		data.selectedImageInput.type = 'hidden';
		data.selectedImageInput.name = data.options.inputName;
		data.selectedImageInput.value = '';

		data.container.appendChild (data.openButton);
		data.container.appendChild (data.selectedImageInput);

		if (options.scaledWidthInputName) {
			data.scaledWidthInput = document.createElement('input');
			data.scaledWidthInput.type = 'hidden';
			data.scaledWidthInput.name = options.scaledWidthInputName;
			data.scaledWidthInput.value = 0;
			data.container.appendChild(data.scaledWidthInput);
		} else
			data.scaledWidthInput = {};

		if (options.scaledHeightInputName) {
			data.scaledHeightInput = document.createElement('input');
			data.scaledHeightInput.type = 'hidden';
			data.scaledHeightInput.name = options.scaledHeightInputName;
			data.scaledHeightInput.value = 0;
			data.container.appendChild(data.scaledHeightInput);
		} else
			data.scaledHeightInput = {};

		//{container: container, options: options, openButton: openButton, selectedImageInput: selectedImageInput}
		this.containers.push (data);
	},

	showhideBox: function (event, containerItem) {
		if (!this.visible) {
			if (!this.containers[containerItem]) return;
			if (this.containers[containerItem].options.onBeforeOpen)
				this.containers[containerItem].options.onBeforeOpen();
			if (!this.visible) {
				if (!this.containers[containerItem].options.enabled) {
					if (this.containers[containerItem].options.onClickDisabled)
						this.containers[containerItem].options.onClickDisabled();
					return false;
				}
			}
		}
		this.visible = !this.visible;
		this.element.style.display = (this.visible?'block':'none');
		if (this.visible) {
			// restore the container
			this.container = this.containers[containerItem].container;
			this.openButton = this.containers[containerItem].openButton;
			this.selectedImageInput = this.containers[containerItem].selectedImageInput;
			this.maxImageWidth = this.containers[containerItem].options.maxImageWidth || 'auto';
			this.maxImageHeight = this.containers[containerItem].options.maxImageHeight || 'auto';
			this.selectedImage = this.containers[containerItem].options.selectedImage || '';
			this.useFileName = this.containers[containerItem].options.useFileName;
			this.currentContainerItem = containerItem;
			this.boxTitle.innerHTML = this.containers[containerItem].options.boxTitle || 'Select Image';
			this.scaledWidthInput = this.containers[containerItem].scaledWidthInput;
			this.scaledHeightInput = this.containers[containerItem].scaledHeightInput;
			if (this.loadOnEveryOpen)
				this.loadImages ();
			else {
				// select the image
				if (this.selectedImage) {
					if (this.useFileName)
						this.selectImageByName (this.selectedImage);
					else
						this.selectImageById (this.selectedImage);
				} else
					this.setNoSelected();
				// draw the columns properly
				setTimeout(this.clc, 1);
			}
			if (this.onBoxShow)
				this.onBoxShow();
		} else {
			if (this.onBoxHide)
				this.onBoxHide();
		}
	},

	loadImages: function () {
		this.clearImages();
		this.showLoading();
		new Ajax.Request (this.scriptImagesURL + '?action=get', {method:'post', onSuccess: this._loadImages_handler})
	},
	loadImages_handler: function (ajaxRequest) {
		this.hideLoading();
		var t = ajaxRequest.responseText;
		var jsonObj = null;
		eval ('jsonObj = ' + t );
		this.files_dir = jsonObj.filesdir;
		if (jsonObj && !jsonObj.error) {
			for (var i = 0, n = jsonObj.items.length; i < n; i ++)
				this.items[i] = new TImagesSelectorItem (this, jsonObj.items[i]);
		}
		this.imagesLoaded = true;
		if (this.visible)
			this.calculateListColumns();
		if (this.selectedImage != '') {
			if (this.useFileName)
				this.selectImageByName (this.selectedImage);
			else
				this.selectImageByID (this.selectedImage);
		} else
			this.setNoSelected();
	},
	clearImages: function () {
		for (var i = this.items.length - 1; i >=0; i--)
			this.items[i].free();
		this.items.length = 0;
		this.imagesLoaded = false;
		this.setNoSelected();
	},
/* --- */
	showLoading: function () {
		this.dimBackground.style.display = 'block';
		this.loadingIndicator.style.display = 'block';
	},
	hideLoading: function () {
		this.dimBackground.style.display = '';
		this.loadingIndicator.style.display = '';
	},
/* --- */
	setNoSelected: function () {
		this.imagePreviewElement.src = SHOST + '/none.gif';
		this.imagePreviewElement.style.display = 'none';
		this.imagePreviewElement.title = '';
		this.infoName.innerHTML = '';
		this.infoSize.innerHTML = '';
		this.infoUploaded.innerHTML = '';
		this.infoPlayers.innerHTML = '';
		this.infoDimentions.innerHTML = '';
		this.infoScaledDimentions.innerHTML = '';
		if (this.currentSelected) {
			this.currentSelected.deselect();
			this.currentSelected = null;
		}
	},
	/* called when initializing the component and etc */
	getItemByFilename: function (filename) {
		for (var i = 0, n = this.items.length; i < n; i ++)
			if (this.items[i].jsonObj.filename == filename) {
				return this.items[i]
			};
		return null;
	},
	getItemById: function (id) {
		for (var i = 0, n = this.items.length; i < n; i ++)
			if (this.items[i].jsonObj.id == id) {
				return this.items[i]
			};
		return null;
	},
	selectImageByName: function (filename) {
		if (this.items.length == 0) {
			this.setNoSelected();
			return -1;
		}
 		if (filename == '') filename = this.items[0].jsonObj.filename;
		for (var i = 0, n = this.items.length; i < n; i ++)
			if (this.items[i].jsonObj.filename == filename) {
				this.items[i].select();
				this.updateInput();
				return i;
			}
		this.setNoSelected();
		return -1;
	},
	selectImageById: function (id) {
		if (this.items.length == 0) {
			this.setNoSelected();
			return -1;
		}
 		if (id == '') id = this.items[0].jsonObj.id;
		for (var i = 0, n = this.items.length; i < n; i ++)
			if (this.items[i].jsonObj.id == id) {
				this.items[i].select();
				this.updateInput();
				return i;
			}
		this.setNoSelected();
		return -1;
	},
	onImageSelected: function (item) {
		if (this.currentSelected)
			this.currentSelected.deselect();
		this.currentSelected = item;

		// center the element vertically
		var imgW = item.jsonObj.width, imgH = item.jsonObj.height;
		if (imgW > this.previewWidth - 2 || imgH > this.previewHeight - 2) {
			if (imgW/imgH > this.previewWidth / this.previewHeight) {
				this.imagePreviewElement.style.width = (this.previewWidth - 2) + "px";
				this.imagePreviewElement.style.height = 'auto';
				var scaledHeight = (this.previewWidth - 2) * imgH / imgW;
				this.imagePreviewElement.style.marginTop = ((this.previewHeight - 2) - scaledHeight ) / 2 + "px";
			} else {
				this.imagePreviewElement.style.height = (this.previewHeight - 2) + "px";
				this.imagePreviewElement.style.marginTop = '0px';
				this.imagePreviewElement.style.width = 'auto';
			}
		} else {
			this.imagePreviewElement.style.width = 'auto';
			this.imagePreviewElement.style.height = 'auto';
			this.imagePreviewElement.style.marginTop = ((this.previewHeight - 2) - imgH ) / 2 + "px";
		}

		this.imagePreviewElement.src = this.files_dir + '/' + item.jsonObj.filename;
		this.imagePreviewElement.style.display = '';
		this.imagePreviewElement.title = item.jsonObj.filename;
		this.infoName.innerHTML = item.jsonObj.filename;
		this.infoSize.innerHTML = item.jsonObj.size_human;
		this.infoUploaded.innerHTML = item.jsonObj.date_uploaded;
		this.infoPlayers.innerHTML = item.jsonObj.players + ' players';
		this.infoDimentions.innerHTML = item.jsonObj.width + ' x ' + item.jsonObj.height;
		this.recalculateScaledSizes();
	},
	getMaxImageSizes: function (imgW, imgH, maxImageWidth, maxImageHeight, expandToMaximumIfSmaller) {
		var scaledWidth = imgW, scaledHeight = imgH;
		if (maxImageWidth == 'auto' && maxImageHeight == 'auto') {
			//
		} else if (maxImageWidth == 'auto') {
			if (imgH < maxImageHeight && !expandToMaximumIfSmaller) {
				// take no action if the image is smaller and is not allowed to expand
			} else {
				scaledHeight = maxImageHeight;
				scaledWidth = scaledHeight * imgW / imgH;
			}
		} else if (maxImageHeight == 'auto') {
			if (imgW < maxImageHeight && !expandToMaximumIfSmaller) {
				// take no action if the image is smaller and is not allowed to expand
			} else {
				scaledWidth = maxImageWidth;
				scaledHeight = scaledWidth * imgH / imgW;
			}
		} else { // none of the sizes is auto!
			if (imgW < maxImageWidth && imgH < maxImageHeight && !expandToMaximumIfSmaller) {
				// take no action
			} else {
				if (imgW/imgH > maxImageWidth/maxImageHeight) {
					scaledWidth = maxImageWidth;
					scaledHeight = scaledWidth * imgH / imgW;
				} else {
					scaledHeight = maxImageHeight;
					scaledWidth = scaledHeight * imgW / imgH;
				}
			}
		}
		return {scaledWidth: Math.round(scaledWidth), scaledHeight: Math.round(scaledHeight)};
	},
	recalculateScaledSizes: function () {
		if (!this.currentSelected) return;
		// calculate the size against maxImageWidth & maxImageHeight
		var item = this.currentSelected;
		var a = this.getMaxImageSizes(item.jsonObj.width, item.jsonObj.height, this.maxImageWidth, this.maxImageHeight, this.expandToMaximumIfSmaller);
		this.scaledWidth = a.scaledWidth; this.scaledHeight = a.scaledHeight;
		this.infoScaledDimentions.innerHTML = this.scaledWidth + ' x ' + this.scaledHeight;
	},
	setMaximumDimentions: function (maxWidth, maxHeight) {
		this.maxImageWidth = maxWidth;
		this.maxImageHeight = maxHeight;
		this.recalculateScaledSizes();
	},
/* */
	updateInput: function () {
		if (this.currentSelected) {
			if (this.useFileName)
				this.selectedImage = this.selectedImageInput.value = this.currentSelected.jsonObj.filename;
			else
				this.selectedImage = this.selectedImageInput.value = this.currentSelected.jsonObj.id;
			this.openButton.innerHTML = '[ ' + this.currentSelected.jsonObj.filename + ' ]';
			this.scaledWidthInput.value = this.scaledWidth;
			this.scaledHeightInput.value = this.scaledHeight;
		} else {
			var dt = this.containers[this.currentContainerItem].options.disabledText;
			this.openButton.innerHTML = '[ ' + (dt?dt:'no image') + ' ]';
			this.selectedImageInput.value = '';
			this.selectedImage = '';
			this.scaledWidthInput.value = 0;
			this.scaledHeightInput.value = 0;
		}
		this.containers[this.currentContainerItem].options.selectedImage = this.selectedImage;
		if (this.containers[this.currentContainerItem].options.onChange) {
			this.containers[this.currentContainerItem].options.onChange(this.selectedImage);
		}
	},
	getSelected: function (name) {
		for (var i = 0, n = this.containers.length; i < n; i ++)
			if (this.containers[i].options.name == name)
				return this.containers[i].options.selectedImage;
		return 0;
	},
/* */
	onClickOK: function () {
		this.updateInput();
		if (this.visible) this.showhideBox();
	},
	onClickCancel: function () {
		if (this.visible) this.showhideBox();
	},
	onClickRemove: function () {
		// send info to input fields
		this.setNoSelected();
		this.updateInput();
		if (this.visible) this.showhideBox();
	},
/*  */
	onStartUploading: function () {
		if (this.inpFileUpload.value == '') {
			alert ('Please, select a file first!');
			return false;
		}
		// extract file name
		if (this.inpFileUpload.value.match(/\\/))
			this.upload_original_name = this.inpFileUpload.value.split('\\').last();
		else if (this.inpFileUpload.value.match(/\//))
			this.upload_original_name = this.inpFileUpload.value.split('/').last();
		else
			this.upload_original_name = this.inpFileUpload.value;

		// check if there is a file with the same name!
		var existingFile = this.getItemByFilename (this.upload_original_name)
		if (existingFile) {
			if (!confirm ("There is already a file with the same name!\nDo you want to ovewrite it?"))
				return false;
		}
		this.uploadFormContainer.style.display = 'none';
		this.uploadProgressContainer.style.display = 'block';
		this.uploadProgressBar.style.width = '0%';
		this.uploadProgressText.innerHTML = 'Starting upload...';

		setTimeout (this._checkUploadProgress, 500);
		return true;
	},
	checkUploadProgress: function () {
		new Ajax.Request (this.scriptImagesURL + '?action=check_upload', {onSuccess: this._checkUploadProgress_handler, method:'post', parameters: $H({'original_name' : this.upload_original_name}).toQueryString()});
	},
	checkUploadProgress_handler: function (ajaxRequest) {
		var jsonObj = null, t = ajaxRequest.responseText;
		eval ('jsonObj = ' + t);
		if (jsonObj) {
			this.uploadProgressText.innerHTML = jsonObj.seccondsLeft + ' left, speed: ' + jsonObj.speed;
			this.uploadProgressBar.style.width = jsonObj.percent * 100 + '%';
			if (jsonObj.done)
				this.onUploadOver(jsonObj.newimage);
			else
				setTimeout (this._checkUploadProgress, 500);
		} else {
			setTimeout (this._checkUploadProgress, 500);
		}
	},
	onUploadOver: function (newImage) {
		this.setNoSelected();
		this.uploadFormContainer.style.display = 'block';
		this.uploadProgressContainer.style.display = 'none';
		if (newImage.isn) {
			this.items.push(new TImagesSelectorItem (this, newImage));
			this.items.last().select();
		} else {
			var item = this.getItemById(newImage.id);
			if (item) {
				item.rebuildWithNewData(newImage);
				item.select();
			}
			///this.items.selectImageById(newImage.ovrwrid);
		}
		this.calculateListColumns();
		this.inpFileUpload.clear();
		this.imagesListElement.scrollTop = this.imagesListElement.scrollHeight - this.imagesListElement.clientHeight;
	},
/* --- */
	indexOfItem: function (item) {
		for (var i = 0, n = this.items.length; i < n; i ++)
			if (item == this.items[i]) return i;
		return -1;
	},
	deleteImage: function (item) {
		this.showLoading();
		this.deleting_item = item;
		new Ajax.Request (this.scriptImagesURL + '?action=delete&id=' + item.jsonObj.id, {onSuccess: this._deleteImage_handler});
	},
	deleteImage_handler: function () {
		this.hideLoading();
		if (this.deleting_item.selected) {
			var i = this.indexOfItem(this.deleting_item);
			if (i >= 0) {
				if (i > 0)
					this.items[i-1].select();
				else if (i < this.items.length - 1)
					this.items[i+1].select();
				else
					this.setNoSelected();
			}
		}
		this.deleting_item.free();
		this.items = this.items.without(this.deleting_item);
	},
/* --- */
	boxMarginLeft : -300,
	boxMarginTop  : -210,
	onStartMove: function (event) {
		if (this.moving) {this.onEndMove(event); return; }
		this.sx = Event.pointerX(event) - this.element.offsetLeft + this.boxMarginLeft;
		this.sy = Event.pointerY(event) - this.element.offsetTop + this.boxMarginTop;
		Event.observe(document, "mousemove", this.onmm);
		Event.observe(document, "mouseup", this.onmu);
		this.moving = true;
		Event.stop(event);
	},
	onUpdateMove: function (event) {
		if (!this.moving) return;
		var nx = Event.pointerX(event) - this.sx;
		var ny = Event.pointerY(event) - this.sy;
		this.element.style.left = nx + "px";
		this.element.style.top = ny + "px";
		Event.stop(event);
	},
	onEndMove: function (event) {
		if (!this.moving) return;
		this.moving = false;
		Event.stopObserving(document, "mousemove", this.onmm);
		Event.stopObserving(document, "mouseup", this.onmu);
		Event.stop(event);
		this.setSizeCookie();
	},
/* --- */
	onStartResize: function (event) {
		if (this.resizing) {this.onEndResize(event); return; }
		this.sw = Event.pointerX(event) - this.selectBox.offsetWidth;
		this.sh = Event.pointerY(event) - this.selectBox.offsetHeight;

		Event.observe(document, "mousemove", this.onmmr);
		Event.observe(document, "mouseup", this.onmur);
		this.resizing = true;
		Event.stop(event);
	},
	onUpdateResize: function (event) {
		if (!this.resizing) return;
		var nw = Math.max (Event.pointerX(event) - this.sw, 540);
		var nh = Math.max (Event.pointerY(event) - this.sh, 420);
		this.selectBox.style.width = nw + "px";
		this.selectBox.style.height = nh + "px";
		this.element.style.width = nw+2 + "px";
		this.rightColumn.style.height = this.imagesListElement.style.height = nh - 10 + "px";
		//this.listBoxScrollContainer.style.height = this.listBoxContent.style.height = (nh-70) + "px";
		//this.scroll.update(nh-70);
		this.calculateListColumns();
		Event.stop(event);
	},
	onEndResize: function (event) {
		if (!this.resizing) return;
		this.resizing = false;
		Event.stopObserving(document, "mousemove", this.onmmr);
		Event.stopObserving(document, "mouseup", this.onmur);
		Event.stop(event);
		this.setSizeCookie();
		this.calculateListColumns();
	},
	setSizeCookie: function () {
		var c = parseInt (this.selectBox.style.width) + ',' + parseInt(this.selectBox.style.height) + ',' +
			parseInt (this.element.style.left) + ',' + parseInt(this.element.style.top);
		Cookies.setValue ('img_sel_box_s', c);
	},
	/* the dummy parameter is because of the bind sending the event details when deferred */
	calculateListColumns: function (dummy, listInnerWidth) {
		if (arguments.length < 2) var listInnerWidth = this.imagesListElement.clientWidth;
		var w = listInnerWidth;// - 4; // left-most and right-most items margins
		var cols = Math.floor(w / this.listItemWidth);
		w -= this.listItemWidth * cols;
		//var midspace = Math.floor (w / (cols-1)) - 4;
		var margin = Math.floor (w / (2 * cols)) - 1;
		for (var i = 0, n = this.items.length; i < n; i ++)
			//this.items[i].setMarginRight( ((i+1) % cols == 0)? 0 : midspace );
			/*if ( (i + 1) % cols == 0 ) // rightmost
				this.items[i].setMarginLeftRight(margin, 0);
			else if (i % cols == 0 ) //leftmost
				this.items[i].setMarginLeftRight(0, margin);
			else*/
				this.items[i].setMarginLeftRight(margin, margin);
	},
	//
	onScrollUpClick: function () {
		this.scroll.scrollUp();
	},
	onScrollDownClick: function () {
		this.scroll.scrollDown();
	}
}


var TCustomFileInput = Class.create();
TCustomFileInput.prototype = {
	wrongFileTypeMessage: 'This file type is not supported!',
	allowedExtensions: [],
	initialize: function (name) {
		Object.extend (this, TemplatedElement);
		this._buildFromTemplate('custom_file_input_template');
		this.inputName = name;
		this.clear();
	},
	onValueChange: function () {
		var value = this.fileInput.value;
		if (this.allowedExtensions.length > 0) {
			var ext = value.split('.').last().toUpperCase();
			var allowed = false;
			for (var i = 0; i < this.allowedExtensions.length && !allowed; i ++)
				if (ext == this.allowedExtensions[i].toUpperCase())
					allowed = true;
			if (!allowed) {
				alert (this.wrongFileTypeMessage);
				this.clear();
				return;
			}
		}
		this.value = this.textInput.value = this.fileInput.value;
	},
	clear: function () {
		if (this.fileInput)
			this.fileInput.parentNode.removeChild(this.fileInput);
		this.fileInput = document.createElement ('input');
		this.fileInput.type = "file";
		this.fileInput.className = "fi"
		this.fileInput.onchange = this.onValueChange.bindAsEventListener(this);
		this.fileInput.name = this.inputName;
		this.btnElement.appendChild (this.fileInput);
		this.value = this.textInput.value = '';
	}
}