// <%@page contentType="application/x-javascript; charset=UTF-8" %>
// <%@taglib uri="/WEB-INF/tld/c.tld" prefix="c"%>

/*
Class: PACDocumentEntry
	This class represents document entries in lists. 
	Please implement a method openChildMenu() for the menuLink. 
	If you want to alter the look of the entries, implement a method createChildElement()

Author: 
	Dominik

Syntax: 
	myParentObject.includeChild(dataObject, 'PACDocumentEntry').show();
	
Arguments: 
	data - the dataObject from the server. 
  
*/
 
PACUploadEntry = PACEntry.extend({
	
	initialize: function(data) {
		this.parent(data);
	
		this.createElement(this.uploadLook);
		this.element.injectTop(this.parentObject.element);
		return this;
	},
	
	update: function(data) {
		console.log(data);
		//PACH. will include parentObject too late, I need it in initialize :(
		this.parentObject = data.parentObject;
		this.parent(data);

		this.uploadLook = $pick(this.data.uploadLook, this.parentObject.options.uploadLook);
		this.data.fileName = PACHelper.unescapeEntities(this.data.name);
		this.data.attributes = this.data.attributes || {};
	},

	/*
	Method: prepareTemplateData
		Sets up data for the templating engine. 
	*/
	prepareTemplateData: function(){
		var options = this.parentObject.options;
		var listPos = this.getListPosition();
		this.progressBarFactor = (listPos.width-10) / 100;
		this.templateData = {
			'id': this.data.ID,
			'cancelClass': options.uploadItemCancelClass,
			'barClass': options.uploadItemBarClass,
			'barRunningClass': options.uploadItemBarRunningClass,
			'filename': this.data.fileName,
			'initialWidth': 0 //(listPos.width - 10) // or -38 TODO: handle in PACUploadEntry.css
		};
	},
	
	/*
	Method: createDefaultElement
		creates a DOM representation for this Entry.
	
	Arguments: 
		elementOnly - (boolean) if true, the method just returns the plain DOM element, w/o any events  
	*/
	createDefaultElement: function(elementOnly) {
		var element = PAC.templates.render('PACUploadEntry.themeDefault', this.templateData, false );
		
		if(elementOnly) {
			return element;
		}
		this.initialProgress = 100;
		return this.bindElementEvents(element);
	},
	
	/*
	Method: createExtendedElement
		creates a DOM representation for this Entry.
	
	Arguments: 
		elementOnly - (boolean) if true, the method just returns the plain DOM element, w/o any events  
	*/
	createExtendedElement: function(elementOnly) {
		$extend(this.templateData, {
			'suggestedName': this.suggestName(),
			'suggestedAuthor': this.suggestAuthor(),
			'suggestedTags': this.suggestTags()
		});
		var element = PAC.templates.render('PACUploadEntry.themeExtended', this.templateData, false );
		if(elementOnly) {
			return element;
		}
		this.initialProgress = 28;
		return this.bindElementEvents(element);
	},
	
	/*
	Method: bindElementEvents
		binds functionality to the created Element; 
	*/
	bindElementEvents: function(element){
		this.uploadItemName = $E('.uploadItemName', element);
		this.deleteLink = $E('.' + this.templateData.cancelClass, element);
		if(this.deleteLink) {
			this.deleteLink.makeLink(this.fireEvent.bind(this, ["onUploadCancelFile", [this.data.app, this.data.upl, this.data.ID]]));
		}
		this.progressBar = $E('.' + this.templateData.barClass, element);
		if(this.progressBar){
			// bar effect
			this.progressEffect = this.progressBar.effect("width", {
				duration:    700,
				wait:       false,
				unit:       "px",
				transition: Fx.Transitions.linear
			}).set(this.initialProgress);			
		}
		return element;		
	},
		
	
	/* returns attributes to save, plus fileName */
	getData: function(){
		data = {
			'fileName': this.data.fileName,
			'tags' : $E("input.uploadFileTags", this.element).value
		};
		data[PAC.documentAttributes.getAttributeID('TITLEID')] = $E("input.uploadFileTitle", this.element).value;
		data[PAC.documentAttributes.getAttributeID('AUTHORID')] = $E("input.uploadFileAuthor", this.element).value;
		
		return data;
	},
	
	getListPosition: function() {
		this.listPosition = this.listPosition || this.parentObject.element.getCoordinates();
		return this.listPosition;
	},
	
	/* discovery methods: */
	suggestName: function(){
		var title = this.data.attributes[PAC.documentAttributes.getAttributeID('TITLEID')];
		if(title) return title;
		return this.data.fileName.humanReadable().replace(/.[^\.]*$/g, "");
	},
	
	suggestAuthor: function(){
		return this.data.attributes[PAC.documentAttributes.getAttributeID('AUTHORID')] || "";
	},
	
	suggestTags: function(){
		if(this.data.userTags) return this.data.userTags.join(", ");
		//tags are all title words longer than 3 char or in capital letters
		return this.suggestName().split(" ").filter(function(item) { return (item.length > 3 || item.test(/^[A-Z]+$/)); }).join(", ");
	},
	
	/* uploader event callbacks: */	
	updateProgress: function(progress){
		if(this.progressEffect && this.progressBarFactor){
			try{
				this.progressEffect.start(progress.percentage * this.progressBarFactor);
			}catch(e){
				//console.log(e);
			}
		}
	},
	
	uploadComplete: function(){
		var extension = (this.data.fileName.valueOf(".") != -1) ? this.data.fileName.match(/[^\.]*$/g)[0] : "";
		this.updateProgress({'percentage':100 });
		if($defined(this.uploadItemName.setStyle)) this.uploadItemName.setStyle("background", 'url(/gfx/formats/' + extension.toUpperCase() + '.png) no-repeat');
		if(this.deleteLink){
			if($defined(this.deleteLink.removeClass)){
				this.deleteLink.removeEvents();
				this.deleteLink.removeClass(this.parentObject.options.uploadItemCancelClass);
			}
		}
		if($defined(this.progressBar.removeClass)) this.progressBar.removeClass(this.parentObject.options.uploadItemBarRunningClass);
	},
	
	uploadCancel: function(){
		var el=$(this.data.ID);
		if($defined(el)){
			el.removeClass(this.parentObject.options.uploadItemBarRunningClass);
			el.addClass(this.parentObject.options.uploadItemBarFailedClass);
		}else{
			this.uploadFail();
		}
	},

	uploadFail: function(){
		SwfupCancelFile(this.data.app,this.data.ID);
		if(!$defined(SwfGetFlashMovie(this.data.app))){
			SwfupCancelAll(this.data.app);
		}
	}
	
});

PACUploadEntry.availableLooks = [ 'DEFAULT' , 'EXTENDED'];