dojo.provide("epages.cartridges.de_epages.mediagallery.widget.Filelistitem");
dojo.require("epages.widget.TypedWidget");
dojo.require("epages.widget.Elementlistitem");
dojo.require("epages.localize");
dojo.require("dojo.regexp");

dojo.declare(
	"epages.cartridges.de_epages.mediagallery.widget.Filelistitem",
	[epages.widget.Elementlistitem],
	{

		/**
		 * public properties
		 */

		preview:             '',
		fullpath:            '',                   // full path including filname
		directory:           '',
		size:                '',
		mimetype:            '',
		extension:           '',
		imagewidth:          '',
		imageheight:         '',
		previewwidth:        '48',
		previewheight:       '48',
		modified:            '',
		canChangeTitle:      'false',
		canDelete:           'false',
		canOpen:             'false',
		name:                "",
		parentId:            "",
		store:               undefined,
		siteId:              epages.vars.SiteID,
		disabled:            false,
		fileName:            '',

		/**
		 * dojo widget properties
		 */
		imagePath:        epages.themeUrl('images'),
		storeImgBase:     epages.vars.StoreRoot+'/BO/icons',

		templateString     : '', // override epages.widget.Elementlistitem default, without scrinksafe
		templateType       : 'normal',
		defaultTemplateType: 'normal',
		templatePath       : dojo.moduleUrl('epages.cartridges.de_epages.mediagallery.widget','templates/Filelistitem.html'),
		_templateMapping   : {
			'normal' : {templatePath: dojo.moduleUrl('epages.cartridges.de_epages.mediagallery.widget', 'templates/Filelistitem.html')},
			'image'  : {templatePath: dojo.moduleUrl('epages.cartridges.de_epages.mediagallery.widget', 'templates/FilelistitemImage.html')}
		},
		translationName  : dojo.moduleUrl('epages.cartridges.de_epages.mediagallery.widget','templates/translation'),
		widgetsInTemplate : true,

		postMixInProperties: function() {
			this._templateDirectory = dojo.moduleUrl('epages.cartridges.de_epages.mediagallery.widget' , 'templates');
			this.inherited("postMixInProperties", arguments);
			this.fileName = this.title;
			this.title = '';

			if(this.size != '') {
				this.size = epages.localize.formatBytes(this.size, 1);
			}
			// define preview
			if (this.preview == '') {
				this.preview = this.imagePath + '/ico_xl_file_unknown.png';
			}
			else if(this.imagewidth != '' && this.imageheight != '') {
				var ratio = parseInt(this.imagewidth, 10) / parseInt(this.imageheight, 10);
				var previewwidth  = this.previewwidth  != '' ? parseInt(this.previewwidth , 10) : undefined;
				var previewheight = this.previewheight != '' ? parseInt(this.previewheight, 10) : undefined;
				if (previewwidth === undefined && previewheight === undefined){
					previewwidth = parseInt(this.prototype.previewwidth);
				}
				if (previewheight === undefined){
					previewheight = previewwidth;
				}
				if (previewwidth  === undefined){
					previewwidth  = previewheight;
				}

				var calc_previewheight = Math.round(previewwidth / ratio);
				var calc_previewwidth  = Math.round(previewheight * ratio);

				if (previewheight < calc_previewheight){
					previewwidth  = calc_previewwidth;
				}
				if (previewwidth < calc_previewwidth){
					previewheight = calc_previewheight;
				}

				this.previewwidth  = previewwidth;
				this.previewheight = previewheight;
			}

			if(!this.disabled) {
				this.canChangeTitle = this.canChangeTitle == 'true' || this.canChangeTitle == '1' ? true : false;
				this.canDelete = this.canDelete == 'true' || this.canDelete == '1' ? true : false;
				this.canOpen = this.canOpen == 'true' || this.canOpen == '1' ? true : false;
			}

			var extension=this.extension.toLowerCase().replace(/^\./,"");
			if(extension == 'jpg' || extension == 'gif' || extension == 'png' || extension == 'bmp' ||
				 extension == 'tif' || extension == 'ico' || extension == 'swf' || extension == 'pdf' ||
				 extension == 'htm' || extension == 'html'|| extension == 'css' || extension == 'txt'){
				this.canOpen=true;
			}

			if(!epages.vars.BaseUrl) {
				console.warn("epages.vars.BaseUrl not defined in "+this.declaredClass);
			}
		},

		pathFromSite: function() {
			if(epages.vars.SiteRoot!== undefined) {
				return this.fullpath.replace(epages.vars.SiteRoot+"/", "");
			} else {
				return null;
			}
		},

		postCreate: function() {
			this.inherited("postCreate", arguments);

			if (this.nodePixel !== undefined && (this.imagewidth == '' || this.imagewidth == null)){
				this.nodePixel.style.display = 'none';
			}
			if (this.nodeSize !== undefined && (this.size == '' || this.size == null)){
				this.nodeSize.style.display = 'none';
			}

			if(! this.disabled) {
				if (this.canChangeTitle) {
					this.connect(this.domNode,        'ondblclick', '_selectTitle');
					this.connect(this.nodeTitle,      'onclick', '_selectTitle');
					this.connect(this.nodeInputTitle, 'onchange', '_changeTitle');
					this.connect(this.nodeInputTitle, 'onkeydown', '_onKeyDown');
					this.connect(this.nodeInputTitle, 'onkeyup', '_onKeyUp');
					this.connect(this.nodeInputTitle, 'onblur', '_selectItem');
				}
			} else {
				this.domNode.removeChild(this.actionButtonsNode);
				dojo.addClass(this.domNode, "Disabled ToolTipCursor");
				// hide alt+title image tags
				//  this.nodeImage.removeAttribute('alt');
				//  this.nodeImage.removeAttribute('title');
				// show info tooltop
				dojo.require("epages.widget.Tooltip");
				var toolTipNode = document.createElement('tt');
				var toolTipText = document.createElement('div');
				toolTipText.innerHTML = '<strong>'+this.translate('UnsupportedFileFormat')+'</strong>';
				toolTipNode.appendChild(toolTipText);
				this.domNode.appendChild(toolTipNode);

				var toolTipWidget = new epages.widget.Tooltip({
     			tooltipArea: this.domNode,
     			interactive: true,
     			forceOrientation: 'B',
     			'class' : 'Wide'
    		}, toolTipNode);
			}
		},

		_selectTitle: function(){
			this.nodeTitle.style.display="none";
			this.nodeInputTitle.style.display="block";
			this.nodeInputTitle.value = this.nodeTitle.firstChild.nodeValue;
			this.nodeInputTitle.focus();
		},

		_changeTitle: function(){
			var me = this;
			if(this.store){
				if(this.nodeInputTitle.value != ''){
					var newName = this.store.renameFile(this.directory,this.path,this.nodeInputTitle.value);
					if(newName != false) {
						this.nodeTitle.firstChild.nodeValue = newName;
						this.path = this.path.replace((new RegExp(dojo.regexp.escapeString(this.name) + '$')),newName);
						this.fullpath = this.fullpath.replace((new RegExp(dojo.regexp.escapeString(this.name) + '$')),newName);
						this.name = newName;
						// remove error class
						dojo.removeClass(this.nodeInputTitle,"DialogError");
						dojo.removeClass(this.nodeTitle,"DialogError");
						// toggle to text label
						this._selectItem();
						//this.nodeInputTitle.style.display="none";
						//this.nodeTitle.style.display="block";
					} else {
						// error case, fill the string the user entered back into the input
						this.nodeTitle.firstChild.nodeValue = this.nodeInputTitle.value;
						// add error class
						dojo.addClass(this.nodeInputTitle,"DialogError");
						dojo.addClass(this.nodeTitle,"DialogError");
						// toggle to edit box
						this._selectTitle();
					}
				}
			}
		},

		_selectItem: function(){
			this.nodeInputTitle.style.display="none";
			this.nodeTitle.style.display="block";
		},

		_onKeyDown: function(evt) {
			// on enter switch title input with title span, like blur
			if(this.nodeInputTitle.value == '') {
				dojo.addClass(this.nodeInputTitle,"DialogError");
			}else{
				this._updateNodeInputTitle();
				if (evt.keyCode == 13) {
					this._selectItem();
				}
			}
		},

		_onKeyUp: function(evt) {
			this._updateNodeInputTitle();
		},

		_onDownload: function () {
			var TargetFile = this.store.removeMediaGalleryFromString(this.path);
			window.open(epages.vars.BaseUrl+'?ObjectID='+this.siteId+'&ViewAction=View&ChangeAction=ActionDownloadFile&File='+TargetFile,'Download');
		},

		_updateNodeInputTitle: function() {
			if(epages.Browser.engine === "MSIE") {
				this.nodeInputTitle.className += "";
			}
		}
	}
);