var UploadPhotoDialog = {
	dialog: null,
	showChangeUserPhoto: function() {
		if(typeof UploadPhotoDialogSettings=="undefined" || typeof UploadPhotoDialogSettings!="object") {
			alert('UploadPhotoDialogSettings is required and must be an object!');
			return;
		}
		//если в шаблоне заданы тексты сообщений с учетом интернационализации, то будем выводить их, ежели нет - то как и раньше из класса Messages
		var photoSelectMessage = UploadPhotoDialogSettings.uploadPhotoSelectMessage ? UploadPhotoDialogSettings.uploadPhotoSelectMessage : Messages.UPLOAD_PHOTO_SELECT; 
		var uploadingMessage = UploadPhotoDialogSettings.defaultUploadingMessage ? UploadPhotoDialogSettings.defaultUploadingMessage : Messages.DEFAULT_UPLOADING;
		
		if (UploadPhotoDialogSettings.dialogBody != undefined) {
			if (this.path) {
				ref_path = this.getRefreshPath(UploadPhotoDialogSettings.userPhotoPath);
				dialogBody = UploadPhotoDialogSettings.dialogBody.replace('_image_url', ref_path);
			} else {
				dialogBody = UploadPhotoDialogSettings.dialogBody.replace('_image_url', UploadPhotoDialogSettings.userPhotoPath)
			}


			var container = document.createElement('div');
			container.innerHTML = dialogBody;
			dialogWidth = '650px';

			self = this
			this.dialog = DialogManager.createDialog({withTitle:false, dialogWidth: dialogWidth});
			this.dialog.setChild(container);
			this.dialog.show();

			cancel = $("upload_photo_dialog_cancel_button");
			cancel.onclick = function() {
				self.dialog.destroy();
				if(typeof self.lastTimeOut!="undefined")
					clearTimeout(self.lastTimeOut);
				return false;
			}
			submit = $("upload_photo_dialog_submit_button");
			inputfile = $("userPhotofileinput");
			this.submit = submit;
			this.cancel = cancel;
			this.inputfile = inputfile;

			submit.onclick=function() {
				if(inputfile.value=='') {
					alert(photoSelectMessage);
					return false;
				}
				LoadingDialog.setText(uploadingMessage);
				LoadingDialog.show();
				return true;
			}
			self.statusBar = $("upload_photo_dialog_status_bar");
			//if (this.path)
			//	$(UploadPhotoDialogSettings.userPhotoId+'imageOnForm').src = this.getRefreshPath(this.path);

			return false;

		}  else {
			var container = document.createElement('div'),
				containerLeft = document.createElement('div'),
				containerRight = document.createElement('div'),
				containerClear = document.createElement('div'),
				text = document.createElement('div'),
				form = document.createElement('FORM'),
				inputfile = document.createElement('INPUT'),
				submit = null,
				cancel = null,
				br = document.createElement('BR'),
				self = this,
				width = "120px",
				dialogWidth = "650px";

			this.statusBar = document.createElement('div');
			this.submit = document.createElement('INPUT');
			this.cancel = document.createElement('INPUT');
			submit = this.submit;
			cancel = this.cancel;

			if(
				typeof UploadPhotoDialogSettings.placeBigInsteadSmall!="undefined" &&
				UploadPhotoDialogSettings.placeBigInsteadSmall
			) {
				width = "270px";
				dialogWidth = "780px";
			}

			Element.addClassName(containerLeft, 'pip');
			Element.addClassName(containerRight, 'pip_text');
			Element.addClassName(containerRight, 'wrap');
			Element.setStyle(containerClear, {clear:"both", fontSize: "0", padding:"5px"});

			//если картинка задана через стили
			var userPhotoPath = $(UploadPhotoDialogSettings.userPhotoId).src ? $(UploadPhotoDialogSettings.userPhotoId).src : UploadPhotoDialogSettings.userPhotoPath; 
			
			container.appendChild(containerLeft);
			container.appendChild(containerRight);
			container.appendChild(containerClear);
			containerLeft.innerHTML =
				//'<img id="'+UploadPhotoDialogSettings.userPhotoId+'imageOnForm" src="'+$(UploadPhotoDialogSettings.userPhotoId).src+'" style="border:0;" />';
				'<img id="'+UploadPhotoDialogSettings.userPhotoId+'imageOnForm" src="'+userPhotoPath+'" style="border:0;" />';

			Element.setStyle(this.statusBar, {paddingTop: "10px", textAlign: "center"});
			this.statusBar.innerHTML = '';
			containerLeft.appendChild(this.statusBar);

			form.method='POST';
			form.enctype='multipart/form-data';
			form.encoding='multipart/form-data'; // for fucking IE!

			form.action=UploadPhotoDialogSettings.userUploadPath;
			//в sharebox iframe называется также, поэтому чтобы не пересекались можно задавать название в настройках
			if (UploadPhotoDialogSettings.uploadIframeName) {
				form.target = UploadPhotoDialogSettings.uploadIframeName;
			} else {
				form.target='uploadIframe';
			}
			form.id='userPhotoUploadForm';

			inputfile.type="file";
			inputfile.name=UploadPhotoDialogSettings.inputFileName;
			inputfile.className=UploadPhotoDialogSettings.inputTextClassName;
			inputfile.id=UploadPhotoDialogSettings.userPhotoId+"fileinput";

			submit.type="submit";
			submit.value=UploadPhotoDialogSettings.submitValue;
			Element.setStyle(submit, {marginTop: "5px"});
			submit.className=UploadPhotoDialogSettings.inputSubmitClassName;

			submit.onclick=function() {
				if(inputfile.value=='') {
					alert(photoSelectMessage);
					return false;
				}
				LoadingDialog.setText(uploadingMessage);
				LoadingDialog.show();
				return true;
			}

			cancel.type="submit";
			cancel.value=UploadPhotoDialogSettings.submitCancel;
			Element.setStyle(cancel, {marginTop: "5px", marginLeft: "5px"});
			cancel.className=UploadPhotoDialogSettings.inputSubmitClassName;

			cancel.onclick = function() {
				self.dialog.destroy();
				if(typeof self.lastTimeOut!="undefined")
					clearTimeout(self.lastTimeOut);
				return false;
			}

			form.appendChild(inputfile);
			form.appendChild(br);
			form.appendChild(submit);
			form.appendChild(cancel);
			text.innerHTML =
				'<div style="'+UploadPhotoDialogSettings.uploadMessageDivStyle+'">' +
				UploadPhotoDialogSettings.uploadMessage +
				'</div>';
			text.appendChild(form);
			containerRight.appendChild(text);
			this.dialog = DialogManager.createDialog({withTitle:false, dialogWidth: dialogWidth});
			this.dialog.setChild(container);
			this.dialog.show();
			return false;
		}
	},

	userPhotoChanged: function(iframeInstance) {
		var inner=iframeInstance.contentDocument?iframeInstance.contentDocument:iframeInstance.Document,
			errors, path, bigPath, noHide=false;
		// inner.body can be used alert(inner.body.innerHTML);

		errors=inner.getElementById(UploadPhotoDialogSettings.uploadingErrorId);
		path=inner.getElementById(UploadPhotoDialogSettings.uploadingPathId);
		bigPath=inner.getElementById(UploadPhotoDialogSettings.uploadingBigPathId);
		uploadingItemIdE=inner.getElementById(UploadPhotoDialogSettings.uploadingItemId);

		if(errors==null && path!=null && bigPath!=null) {
			this.uploadingItemId = uploadingItemIdE.innerHTML.strip();
			this.bigPath = bigPath.innerHTML.strip();
			this.path = path.innerHTML.strip();
			this.path16x16 = inner.getElementById('uploading16x16').innerHTML.strip()
			this.path32x32 = inner.getElementById('uploading32x32').innerHTML.strip()
			this.path80x80 = inner.getElementById('uploading80x80').innerHTML.strip()
			this.path50x50 = inner.getElementById('uploading50x50').innerHTML.strip()
			this.checkUserpicStatus();
			noHide=true;
		}
		else {
			if(errors!=null)
				alert(errors.innerHTML.stripTags().strip());
			//else
			//	alert(Messages.SYSTEM_ERROR);
		}

		try {
			$(UploadPhotoDialogSettings.userPhotoId+"fileinput").value='';
			$(UploadPhotoDialogSettings.userPhotoId+"fileinput").hide();
		}
		catch(e) {
		}
		if(!noHide)
			LoadingDialog.hide();
		return false;
	},

	checkUserpicStatus: function() {
		
		//если в шаблоне заданы тексты сообщений с учетом интернационализации, то будем выводить их, ежели нет - то как и раньше из класса Messages
		var processingMessage = UploadPhotoDialogSettings.defaultProcessingMessage ? UploadPhotoDialogSettings.defaultProcessingMessage : Messages.DEFAULT_PROCESSING;
		var doneMessage = UploadPhotoDialogSettings.defaultDoneMessage ? UploadPhotoDialogSettings.defaultDoneMessage : Messages.DEFAULT_DONE;
		var systemErrorMessage = UploadPhotoDialogSettings.systemErrorMessage ? UploadPhotoDialogSettings.systemErrorMessage : Messages.SYSTEM_ERROR;
		
		if(typeof this.uploadingItemId!="undefined") {
			Element.hide(this.submit);
			Element.hide(this.cancel);
			var params = 'itemId='+this.uploadingItemId, self=this;
			LoadingDialog.setText(processingMessage);
			LoadingDialog.show();

			new Ajax.Request(UploadPhotoDialogSettings.userCheckStatusPath, {
				method: 'post',
				parameters: params,
				onComplete: function(response) {
					LoadingDialog.hide();
					try {
						var result = response.responseXML.getElementsByTagName('result').item(0), resultResponse='';
						if(result!=null) {
							resultResponse=result.firstChild.nodeValue;
						}
						if(resultResponse=='completed') {
							self.statusBar.innerHTML = doneMessage/* + result.getAttribute('fileDescriptor')*/;
							self.uploadingAndProcessingDone();
						}
						else if(resultResponse=='converting') {
							self.statusBar.innerHTML = processingMessage/* + ' ' + result.getAttribute('fileDescriptor')*/;
							self.lastTimeOut=setTimeout(function(){self.checkUserpicStatus();}, 5000);
							Element.setStyle(self.statusBar, {color: "#FA76B2", fontWeight: "bold"});
							new Effect.Pulsate(self.statusBar);
						}
						else {
							alert(systemErrorMessage + ' (Debug):' + response.responseText);
							self.uploadingAndProcessingDone();
						}
					}
					catch (e) {
						alert('Exception: ' + e + ' ' + response.responseText);
					}
				}
			});
		}
	},

	uploadingAndProcessingDone: function() {
		if(typeof this.lastTimeOut!="undefined")
			clearTimeout(this.lastTimeOut);
		Element.show(this.submit);
		Element.show(this.cancel);
		if($(UploadPhotoDialogSettings.userPhotoId+'imageOnForm')!=null)
			$(UploadPhotoDialogSettings.userPhotoId+'imageOnForm').src = this.getRefreshPath(this.path);

		if($(UploadPhotoDialogSettings.userPhotoId)!=null) {
			if(typeof UploadPhotoDialogSettings.placeBigInsteadSmall!="undefined" && UploadPhotoDialogSettings.placeBigInsteadSmall) {
				//$(UploadPhotoDialogSettings.userPhotoId).src = this.getRefreshPath(this.bigPath);
				var path = this.getRefreshPath(this.bigPath);
			} else {
				//$(UploadPhotoDialogSettings.userPhotoId).src = this.getRefreshPath(this.path);
				var path = this.getRefreshPath(this.path);
			}
			//если картинка задана через стили
			if ($(UploadPhotoDialogSettings.userPhotoId).src) {
				$(UploadPhotoDialogSettings.userPhotoId).src = path;
			} else {
				$(UploadPhotoDialogSettings.userPhotoId).style.backgroundImage = 'url('+path+')';
			}
		}
		if(typeof UploadPhotoDialogSettings.theMostTopUsetPicId!="undefined" && $(UploadPhotoDialogSettings.theMostTopUsetPicId)!=null) {
			$(UploadPhotoDialogSettings.theMostTopUsetPicId).setAttribute('src', this.getRefreshPath(this.path));
		}
		UploadPhotoDialogSettings.userPhotoPath = this.getRefreshPath(this.bigPath);
		if(this.dialog)
		    this.dialog.destroy();
		if(typeof UploadPhotoDialogSettings.onComplete=="function") {
			UploadPhotoDialogSettings.onComplete();
		}
		preload_images = [new Image(), new Image(), new Image(), new Image(), new Image(), new Image()]
		preload_images[0].src = (this.path)
		preload_images[1].src = (this.bigPath)
		preload_images[2].src = (this.path16x16)
		preload_images[3].src = (this.path32x32)
		preload_images[4].src = (this.path80x80)
		preload_images[5].src = (this.path50x50)
	},

	getRefreshPath: function(path) {
		var i = Math.random();
		if(path.gsub(/\?/, '')!=path) {
			path+='&randomValue='+i;
		}
		else {
			path+='?randomValue='+i;
		}
		return path;
	},

	close: function() {
		if(this.dialog!=null)
			this.dialog.destroy();
		this.dialog=null;
	}
};
