
// We must override the createUploadForm()-function defined in ajaxfileupload.js, since we need to support the 
// additional fields required by FileWidget and ImageWidget.
function filewidgetcreateUploadForm(widget) {
    // This function created a new function that refers to the correct widgetid
    return function(id, 
                           fileElementId // This is specified by the code in ajaxfileupload.js, but we don't need it.
                           )
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
        form.log("filewidget.createUploadForm running.");
        
        
        
        // Copy all the ".new*" inputfields.
        var uploadInputElementPrefix = widget.attr("id") + ".new";
        $("input",widget) .each(
            function(index,inputElement) {
                var inputElementName = $(inputElement).attr("name");
                //if( (inputElementName != undefined) && (inputElementName.indexOf(uploadInputElementPrefix) == 0) ) {
                if( (inputElementName != undefined) ) {
                    //form.log("filewidget.createUploadForm running found .new element:" + inputElementName);
                    //$(inputElement).clone().appendTo(form);
                    var newElement = $(inputElement).clone();
                    $(inputElement).before(newElement);
					$(inputElement).appendTo(form);
                    
                }
            })
        
        // If this widget is being used by the wizard, we must also make sure that we transfer the wizard-specific
        // context. This is stored in two hidden input-fields: "serial" and "step"
        var serialElement = $("input").filter('[name=serial]')
        if( serialElement !=undefined) {
            $(serialElement).clone().appendTo(form);
        }
        var stepElement = $("input").filter('[name=step]')
        if( stepElement !=undefined) {
            $(stepElement).clone().appendTo(form);
        }
        
        //set attributes
        $(form).css('position', 'absolute');
        $(form).css('top', '-1200px');
        $(form).css('left', '-1200px');
        $(form).appendTo('body');		
        
        form.log("filewidget.createUploadForm finished form:" + form.html( ));
        
		return form;
    }
}


function closeUpload(event) { 
    //var results = $(this).parents('.results');
    var uploadcontrols = $(this).parents('.inner').find('.uploadcontrols');
    uploadcontrols.hide();
    
    var fileCtrl = uploadcontrols.find('.new');
    fileCtrl.attr("value","");
    
    
    $(this).parents('.inner').find('.associationscontrols').show();
    //results.slideUp(200).remove();
}



function openUpload(event) {
    var inner = $(this).parents('.inner');
    var uploadcontrols = inner.find('.uploadcontrols');
    uploadcontrols.show();

    var loadingimg = uploadcontrols.find("#loading");
    loadingimg.hide();    
    
    // Disable the submitbutton and the title-field. They will be enabled once a filename has been entered
    uploadcontrols.find('.submit_new').attr("disabled","disabled");
    
    var fileCtrl = uploadcontrols.find(".new")
    fileCtrl.attr("value","");
    fileCtrl.removeAttr("disabled")
    fileCtrl.change(onBrowseCtrlChanged);
    
    uploadcontrols.find(".new_inputfields").each(function(index,inputfield) {
        $(inputfield).attr("disabled","disabled").attr("value","");
        });
    
    
    inner.find('.associationscontrols').hide();    
}

function uploadFile(event) 
{
    event.stopPropagation();
    event.preventDefault();
    var inner = $(this).parents('.inner');
    var widget = $(this).parents('.widget');
    var form = $(this).parents('form');
    
    var uploadcontrols = inner.find('.uploadcontrols');
    var fileCtrl = uploadcontrols.find('.new')

    
	var loadingimg = uploadcontrols.find("#loading");
    loadingimg.show();
    widget.log("calling ajaxFileUpload()... widget.id:"+widget.attr("id"))
    
    // We must override the createUploadForm()-function defined in ajaxfileupload.js, since we need to support the 
    // additional fields required by FileWidget and ImageWidget.
    oldcreateUploadForm = jQuery.createUploadForm;
    jQuery.extend({ createUploadForm: filewidgetcreateUploadForm(widget)
                      });


	var url = $('.imageuploadurl', widget).val();
	if (!url){
		url = form.attr('action');
	}
                         
    $.ajaxFileUpload
		(
			{
				url:url,
				secureuri:false,
				fileElementId:"", // We have specified our own createUploadForm function, and it doesn't need this parameter.
				dataType: 'html', // this is the dataType of the returned data.
				success: function(data,status) {
                      ajaxFileUploadSuccess(widget,form,data,status);
                },
				error: function(data,status) {
                      ajaxFileUploadError(widget,form,data,status);
                }
			}
		)
    widget.log("done calling ajaxFileUpload()...")
    
    // Restore the old createUploadForm function.
    jQuery.extend({createUploadForm: oldcreateUploadForm})
		
    // disable the submitbutton and the file-control, so that the user can't trigger multiple uploads.
    uploadcontrols.find('.submit_new').attr("disabled","disabled");
    fileCtrl.attr("disabled","disabled");
    uploadcontrols.find('.new_inputfields').each(function(index,inputField){
	$(inputField).attr("disabled","disabled");
      });
    
    
}

function ajaxFileUploadError (widget,form, data, status)
{
    humanMsg.displayMsg('File upload failed');
}

function ajaxFileUploadSuccess (widget,form, result, status)
{
    // Ask the server for an updated list of associations
	var errormessage = jQuery('#json', result).text();
	if (errormessage) {
		refreshAfterFileUploadFailed(errormessage, widget);
		return false;
	}
	
	try {
    	eval( "result = " + result );
	} catch (e){
		//ie hack
		result= result.replace(/<\/?pre>/ig, '');
	}    

	
    var data = {}, 
    	operation = {'operation' : 'refresh', 'serial': String(result) };
    	
    data[widget.attr('ztm:marker')] = operation

    // If this widget is being used by the wizard, we must also make sure that we transfer the wizard-specific
    // context. This is stored in two hidden input-fields: "serial" and "step"    
    addWizardInfoIfNeeded(data,widget);
    var jsonarg = { url : form.attr('action')
                , data: data
                , timeout: 600000
                , success: refreshAfterFileUploadSucceded
                , error: refreshAfterFileUploadFailed
                };
    jQuery.postJSON(jsonarg);
    //widget.log("ajaxFileUploadSuccess() done.")
    
    //add clickevent to the search and upload buttons
    var widgettype = $(widget).attr('ztm:widgettype');
    if (widgettype == 'imagewidget')
		imagewidget(widget);
    else
    	filewidget(widget);
   
}


function refreshAfterFileUploadSucceded(result, status) {
    for (name in result) {
        var data = result[name];
        var widget = $('#' + name);
        var uploadcontrols = widget.find('.uploadcontrols');
        var loadingimg = uploadcontrols.find("#loading");
        loadingimg.hide();
        var fileCtrl = widget.find('.new');
        fileCtrl.attr("value","");
        
        uploadcontrols.hide();
        widget.find('.associationscontrols').show();
        widget.log("refreshAfterFileUploadSucceded() running...")
    }
    rebuildList(result);
    
    
}
function refreshAfterFileUploadFailed(message, widget) {
    humanMsg.displayMsg('File upload failed: '  + message);
    //add clickevent to the search and upload buttons
    var widgettype = $(widget).attr('ztm:widgettype');
    if (widgettype == 'imagewidget')
		imagewidget(widget);
    else
    	filewidget(widget); 
	$('.associationscontrols', widget).show(); 	   	   
}


function onBrowseCtrlChanged(event)
{    
    var $this = $(this);
    var widget = $(this).parents('.widget');
    var filename = $this.attr("value");
    var extension = filename.substring(filename.lastIndexOf(".")).toLowerCase();
    //disabled allowed extensionchecking for nofima
    var valid = false;

    var validExtensionsString = "";
    $(".validextensions",widget).children().each(function(index,element) {
        element = $(element);
        var validExtension = element.text();
        if( validExtensionsString != "" ) {
            validExtensionsString += ", ";
        }
        validExtensionsString += validExtension;
        if( extension == validExtension) {
            valid = true;
        }        
    });

    //if no validextensions given all are good
    if ($(".validextensions",widget).children().length == 0){
      valid = true;
    }
    
    var inner = $(this).parents('.inner');
    var uploadcontrols = inner.find('.uploadcontrols');
    if(valid){
      $(".errormsg", widget)
        .text("")
        .hide();
      // Enable the upload button and the title field
      uploadcontrols.find(".submit_new").removeAttr("disabled");
      uploadcontrols.find(".new_inputfields").each(function(index,inputField) {
        $(inputField).removeAttr("disabled");
      });    
      
    }
    else{
      $(".errormsg", widget)
        .text("You are only allowed to upload files of the following types: " + validExtensionsString)
        .show();
    }
    
    
}

function filewidget(element) {
  // TODO: Animate adding and removal
  // TODO: Disable checking of already associated topics
  // TODO: Disable search when cardinality constraints reached.
  // TODO: Mark as incomplete
  // TODO: Animate waiting for server
  // TODO: Handle error messages from server.
  $('li', element).each(associationline);
  $('input.search', element).click(associationsearch);
  $('input.upload', element).click(openUpload);
  $('input.delete', element).hide();
  
  $('.uploadcontrols', element).find('.closer').show().click(closeUpload);
  
  
  $('.uploadcontrols', element).find('.new').change(onBrowseCtrlChanged);
  $('.uploadcontrols', element).find('.submit_new').click(uploadFile);
  
  
  //$('input.search', element).click(imagesearch);
  //$('input.create', element).click(createassociation).disable();
  $('.uploadcontrols', element).hide();
  //$('.associationscontrols', element).hide();
}

WIDGETHANDLERS['filewidget'] = filewidget

