/*
 * desc - Base functionality for uploading
 */
var UploadUI = Class.create({
	
	
	/* errors codes returned */
	ERROR_CODES			: {400:"Incorrect File Type"},
	
	/* should the default handlers be used */
	use_default_handlers: false,

	//row container
	row_container 		: null,
	row_container_style : 'row-container',
	
	//instructions
	instructions 		: null,
	instructions_style 	: 'follow-me',
	
	//browsing
	browse_button 		: null,
	browse_button_style : 'browse-button',
	
	browse_swf 			: null,
	browse_swf_style 	: 'browse-button-swf',
	
	//upload button
	upload_button 		: null,
	upload_button_style : 'upload-button',
	
	//cancel button
	cancel_button 		: null,
	cancel_button_style : 'cancel-button',
	
	//swfupload object
	swfu 				: null,
	
	// bound event listeners (easier to remove)
	bfx_rollover		: null,
	bfx_rollout			: null,
	bfx_edit			: null,
	bfx_cancel			: null,
	bfx_remove			: null,
	bfx_save			: null,
	
	//successful upload message
	success_msg			: 'Upload Complete',

	//fired on creation
	initialize:function(control_id, config)
	{
		var ui_form=$(control_id+'_ui');

		// setup the bound event listeners
		this.bfx_rollover = this.rollover_row.bindAsEventListener(this);
		this.bfx_rollout = this.rollout_row.bindAsEventListener(this);
		this.bfx_edit = this.edit_row.bindAsEventListener(this);
		this.bfx_cancel = this.cancel_edit.bindAsEventListener(this);
		this.bfx_remove = this.remove_row.bindAsEventListener(this);
		this.bfx_save = this.update_file_name.bindAsEventListener(this);
				
		// Set up all the UI Elements
		this.browse_swf 	= $$("#" + ui_form.id + " ." + this.browse_swf_style)[0];
		this.instructions 	= $$("#" + ui_form.id + " ." + this.instructions_style)[0];
		this.upload_button 	= $$("#" + ui_form.id + " ." + this.upload_button_style)[0];
		this.cancel_button 	= $$("#" + ui_form.id + " ." + this.cancel_button_style)[0];
		this.browse_button 	= $$("#" + ui_form.id + " ." + this.browse_button_style)[0];
		this.row_container 	= $$("#" + ui_form.id + " ." + this.row_container_style)[0];
		
		// the config object can be passed in for convenience
		if(config==undefined)
		{
			// build the config object
			var	config=new Object();
			this.configure(config, control_id);
		}
		
		// add the event handlers 
		if(this.use_default_handlers)
			this.default_handlers(config);
		else 
			this.form_handlers(config, control_id);
		
		// build the submit button
		this.build_submit(config);
		
		// instantiation
		this.swfu = new SWFUpload(config);
		
		Event.observe(this.upload_button,"click",function(evt)
		{
			this.prep_upload();
		}.bind(this));
		Event.observe(this.cancel_button,"click",function(evt)
		{
			if(this.swfu.cancelUpload()==undefined)
				this.loadedEventHandler();
		}.bind(this));
	}
});

/* Configures based on a form */
UploadUI.prototype.configure=function(config, control_id)
{
	var up_form=$(control_id+'_form');
	
	//upload destination		
	config['upload_url']=up_form.action;
	
	$$("#"+up_form.id+" label").each(function(item,ct){
		config[item.id]=item.innerHTML.strip();
	});
	
	$$("#"+up_form.id+" input[type='file']").each(function(item,ct){
		config["file_post_name"]=item.name;
	});
	
	$$("#"+up_form.id+" input[type='hidden']").each(function(item,ct){
		if(config.post_params==undefined)
			config.post_params=new Object();
		config.post_params[item.name]=item.value;
	});
	config.post_params['upload_type']="flash";
	
};

/* Add default handlers */
UploadUI.prototype.default_handlers=function(config)
{
	config['upload_start_handler'] = this['uploadStartEventHandler'].bind(this);
	config['upload_success_handler'] = this['uploadSuccessEventHandler'].bind(this);
	config['swfupload_loaded_handler'] = this['loadedEventHandler'].bind(this);
	config['file_queued_handler'] = this['fileQueued'].bind(this);
	config['upload_progress_handler'] = this['uploadProgress'].bind(this);
	config['upload_error_handler'] = this['uploadError'].bind(this);
	config['file_dialog_start_handler'] = this['fileDialogStart'].bind(this);
	config['file_queue_error_handler'] = this['fileQueueError'].bind(this);
};
/* Add handlers based on values in a form */
UploadUI.prototype.form_handlers=function(config, control_id)
{
	var up_form=$(control_id+'_form');
	
	$$("#"+up_form.id+" input[type='text']").each(function(item,ct){
		config[item.name]=this[item.value].bind(this);
	}.bind(this));
};

/* Builds the submit button */
UploadUI.prototype.build_submit=function(config)
{
	config['button_image_url']="/i/all/bg/swfupload_button_states.png";	// Relative to the Flash file
	config['button_width']="68";
	config['button_height']="22";
	config['button_placeholder_id']=this.browse_swf.identify();
	config['cancelButtonId']=this.cancel_button.identify();
	config['button_text']='<span class="theFont">Browse</span>';
	config['button_text_style']=".theFont { font-size:11px; color:#565656; font-family:Helvetica; }";
	config['button_text_left_padding']=12;
	config['button_text_top_padding']=5;
};

/* add a row to the UI after a file is selected */
UploadUI.prototype.add_row=function(swfu_id)
{
	//this is a row	
	var ui_row=MyBuilder.make('div',{id:swfu_id},"row",null,[	
		MyBuilder.make('a',{id:'edit_remove'+swfu_id,href:'javascript:void(0)'},'delete',"x",null),
		MyBuilder.make('p',{id:'file_size'+swfu_id},"file-sze",null,null),
		MyBuilder.make('p',{id:'file_name'+swfu_id},'file-name',null,null),
		MyBuilder.make('form',{id:'edit_file'+swfu_id},null,null,[
			MyBuilder.make('input',{id:'edit_name'+swfu_id,maxlength:64},null,null,null),
			MyBuilder.make('button',{id:'edit_save'+swfu_id,onclick:'return false;'},'save edit',"Done",null),
			MyBuilder.make('a',{id:'edit_cancel'+swfu_id,href:'javascript:void(0);'},'cancel edit',"Cancel",null)
		]),
		MyBuilder.make('div',{id:'progress_bar'+swfu_id},'progress-bar',null,[
			MyBuilder.make('div',{id:'progress_cover'+swfu_id},'meter',null,null)
		])
	]);
	//add row to the page
	this.row_container.appendChild(ui_row);
	//hide the input box
	$('edit_file'+swfu_id).hide();
	
	//inline editing of titles
	Event.observe($('file_name'+swfu_id),"click",this.bfx_edit);
	Event.observe($('file_name'+swfu_id),"mouseover",this.bfx_rollover);
	Event.observe($('file_name'+swfu_id),"mouseout",this.bfx_rollout);
	//cancel evnt	
	Event.observe($('edit_cancel'+swfu_id),"click",this.bfx_cancel);
	//to remove from que
	Event.observe($('edit_remove'+swfu_id),"click",this.bfx_remove);
	//save evnt
	Event.observe($('edit_save'+swfu_id),"click",this.bfx_save);
};

/* Remove a row */
UploadUI.prototype.remove_row=function(evt)
{
	var item=Event.element(evt).up();
	//remove the listeners`
	var id=item.id;	
	this.remove_row_listeners(id);
	//manage the que
	this.swfu.cancelUpload(item.id);	
	//remove the ui item
	if(item.up().childElements().length==1)
		this.loadedEventHandler();
	else
		item.remove();
	
	if (this.swfu.getStats().files_queued > 0)
		this.show_buttons();
};

UploadUI.prototype.cancel_edit=function(evt)
{	
	var edit_file=Event.element(evt).up();
	var file_name=edit_file.previous();
	$(file_name,edit_file).invoke("toggle");
};

UploadUI.prototype.loadedEventHandler=function()
{
	//reset everything
	this.cleanup();
	//default state
	this.instructions.show();
	this.instructions.update("Browse your computer for files you would like to upload.");
	$(this.upload_button,this.cancel_button).invoke('hide');
};

UploadUI.prototype.uploadError=function(file_object, error_code, message)
{
	/*error_code -280 message = File Cancelled*/
	if(error_code==-280)
		return;
	if(this.ERROR_CODES[message])
	{		
		message = this.ERROR_CODES[message];
	}
	/*console.log('ops! there\'s been a problem.' + "\nerror_code:" + error_code + "\nmessage:"+ message);*/ 
//	this.swfu.cancelUpload();
	var id = file_object['id'];
	
	this.swfu.setButtonDisabled(true);
	var name = file_object['name'];
	this.instructions.update("An error occurred. Remove the file from the queue to continue.")
	
	//to remove from que
	Event.observe($('edit_remove'+id),"click",this.bfx_remove);
	$('edit_remove'+id).show();
	
	$('progress_bar'+id).setOpacity(0);
	$('file_size'+id).update("");
	$('file_name'+id).update("<b>Error: "+message+"</b>");
};

UploadUI.prototype.fileDialogStart=function()
{
//	this.swfu.cancelUpload();
//	$("file_name").value = "";
};

UploadUI.prototype.uploadProgress=function(file_object, bytesLoaded, bytesTotal)
{
	var id=file_object['id'];
	var ratio=bytesLoaded / bytesTotal;
	
	//show the progress bar
	var opacity = 0;
	if(ratio<0.1)
	{
		opacity = 0;
		$('file_size'+id).update("Initializing");
	}
	else if(ratio>0.99)
	{
		opacity = 0;
		$('file_size'+id).update("Processing");
	}
	else
	{
		opacity = 1;
		$('file_size'+id).update("");
	}

	$('progress_bar'+id).setOpacity(opacity);
	var width=$('progress_cover'+id).getDimensions().width;
	var moveto=Math.ceil((ratio)*width);
	$('progress_cover'+id).setStyle({marginLeft:(moveto+'px')});
};

UploadUI.prototype.show_buttons=function()
{
	if(!this.upload_button.visible())
	{
		$(this.upload_button,this.instructions,this.cancel_button).invoke('show');
		this.instructions.update("Click upload to begin.");
		this.swfu.setButtonDisabled(false);
	}
};

/* Error handler for queueing */
UploadUI.prototype.fileQueueError=function(file_object, errorCode, message)
{	
	var stats = this.swfu.getStats();
	var queued = stats.files_queued;
	
	if(queued === 0)
		this.instructions.update(message);
	else
	{
		var id=file_object['id'];
		var name=file_object['name'];
		
		//add another row to the mix
		this.add_row(id);
		
		//display the file name
		$('file_name'+id).update(name);
		$('file_name'+id).show();
		
		//display the file name
		$('file_size'+id).update(message);
		$('file_size'+id).show();
		
		//hide the "x"
		$('edit_remove'+id).hide();
		
		//
		$('progress_bar'+id).setOpacity(0);	
	}
};

UploadUI.prototype.fileQueued=function(file_object)
{
	this.show_buttons();
	
	var id=file_object['id'];
	var name=file_object['name'];
	
	//add another row to the mix
	this.add_row(id);
	
	//display the file name
	$('file_name'+id).update(name);
	$('file_name'+id).show();
	//
	$('progress_bar'+id).setOpacity(0);
	
	//show the file size
	var size=file_object['size'];
	var _long=(size/1024);
	var kb=String(_long).slice(0,String(_long).indexOf(".")+2)+'kb';
	$('file_size'+id).update(kb);
	$('file_size'+id).show();
};

UploadUI.prototype.uploadSuccessEventHandler=function(file,server_data)
{
	server_data=server_data.evalJSON();
	if(server_data.message=="OK")
	{
		var id=file['id'];
		
		//remove progress bar
		$('progress_bar'+id).setOpacity(0);
		
		//update the file name
//		$('file_name'+id).update(file['name']);
		
		//update the status text
		$('file_size'+id).update("Complete");
		
		//if no more files in the que
		if (this.swfu.getStats().files_queued === 0) {
			this.finished(server_data.data);
			this.cleanup();
		} else {
			this.swfu.startUpload();
		}
	}
	else
	{
		this.loadedEventHandler();
		this.instructions.update("An error occurred. Please try again.");
		/*console.log('file: ' + file + '; server_data: ' + server_data);*/
	}
};

// extend or overwrite for custom functionality
UploadUI.prototype.finished=function()
{
	this.instructions.update(this.success_msg);
	$(this.instructions).show();
};


UploadUI.prototype.uploadStartEventHandler=function(file_object)
{
	var id=file_object['id'];
	
	//change the instructions
	this.instructions.update("&nbsp;");
	
	//remove evnt listers
	this.remove_row_listeners(id);
	
	//can't remove once started
	$('edit_remove'+id).hide();
	
	//remove buttons 
	$(this.upload_button,this.cancel_button).invoke('hide');
	
	//keeps it rolling by returning true
	return true;
};

UploadUI.prototype.prep_upload=function()
{
	//don't allow any more selections
//	this.browse_button.hide();
	//remove any file edits
	this.row_container.childElements().each(function(item,count){
		var id=item.id;
		$('file_name'+id).show();
		$('edit_file'+id).hide();
	});
	//start the upload
	this.swfu.startUpload();
};

UploadUI.prototype.cleanup=function()
{
	this.row_container.childElements().each(function(item,count){
		//remove item from the que
		this.swfu.cancelUpload(item.id);
		//remove the evnt handlers
		this.remove_row_listeners(item.id);
		//remove the ui item
		item.remove();
	}.bind(this));
};

UploadUI.prototype.update_file_name=function(evt)
{
	var e=Event.element(evt);
	var id=e.up().up().id;
	var new_value=e.previous().value;
	this.swfu.addFileParam(id,'changed_name',new_value);
	$('file_name'+id).update(new_value);
	$($('file_name'+id),e.up()).invoke("toggle");
};

UploadUI.prototype.rollover_row=function(evt)
{	
//	var e=Event.element(evt);
//	var item=e.up();
	var item=Event.element(evt);
	item.addClassName('over');
};

UploadUI.prototype.rollout_row=function(evt)
{
//	var e=Event.element(evt);
//	var item=e.up();
	var item=Event.element(evt);	
	item.removeClassName('over');
};

UploadUI.prototype.edit_row=function(evt)
{	
	var file_name=Event.element(evt);
	var edit_file=file_name.next();
	edit_file.down().value=file_name.innerHTML;
	$(file_name,edit_file).invoke("toggle");
};

UploadUI.prototype.remove_row_listeners=function(swfu_id)
{
	Event.stopObserving($('file_name'+swfu_id),"click",this.bfx_edit);
	Event.stopObserving($('file_name'+swfu_id),"mouseover",this.bfx_rollover);
	Event.stopObserving($('file_name'+swfu_id),"mouseout",this.bfx_rollout);
	Event.stopObserving($('edit_cancel'+swfu_id),"click",this.bfx_cancel);
	Event.stopObserving($('edit_remove'+swfu_id),"click",this.bfx_remove);
	Event.stopObserving($('edit_save'+swfu_id),"click",this.bfx_save);
};

/*
 * Uploads of Videos and Imagery - Media Upload
 */
var MediaUpload = Class.create(UploadUI,{
	success_message 	: '',
	preview_img 		: '',
	preview_size 		: '',
	image_server		: '',
 	initialize:function($super,id){
 		$super(id);
 	}
 });

MediaUpload.addMethods({
	finished:function($super,data){
		$super();

		this.instructions.update(this.success_message);
		
		var results = data[0];
		var img_src = this.image_server + '/' + results.destination + this.preview_size + '.jpg';
		
		$(this.preview_img).src = img_src;
	
	}
});


var Indicator = Class.create(UploadUI,{
 	initialize:function($super,id,config){
 		$super(id,config);
		
		// indicator
		this.indicator = $(id+'_ui').up(".pos-app");
 	}
});

Indicator.addMethods({
	finished:function($super,data){
		$super();
		this.indicator.addClassName("checked");
	}
});

/*
 * Uploads as Attachments
 */
var Attachment = Class.create(Indicator);
Attachment.addMethods({
	finished:function($super,data){
		$super();
		var field_id = data[0].asset_type;
		var field_value = data[0].media_id;
		
		// set the hidden field
		$(field_id).value = field_value;
	}
});


/*
 * Uploads as Attachments
 */
var Submission = Class.create(Indicator,{
	field_id:'',
	use_default_handlers:true,
 	initialize:function($super,id,config,field_id){
 		$super(id,config);
		
		this.field_id = field_id;
 	}
});

Submission.addMethods({
	finished:function($super,data){
		$super();
		
		var field_value = data[0].media_id;
		// set the hidden field
		$(this.field_id).value = field_value;
	}
});