var IMDTUploadHandlers = {
    
    fileDialogStart : function(){
        //alert('IMDTUploadHandlers::fileDialogStart');
    },

    fileQueued : function(file, swfuInstance){
        //alert('IMDTUploadHandlers::fileQueued');
    },
    
    fileQueuedError : function(file, errorCode, message){
        //alert('IMDTUploadHandlers::fileQueuedError');
    },
    
    fileDialogComplete : function(selectedFilesCount, queuedFilesCount, fileQueueCount, swfuInstance){
        //alert('IMDTUploadHandlers::fileDialogComplete');
        swfuInstance.startUpload();
    },
    
    uploadStart : function(file){        
        $("#upload-progress").dialog({
            resizable: false,
            draggable: false,
            width: 350,
            minHeight: 70,
            modal: true,
            title: 'Enviando arquivos...'
        });
        $("#upload-progress").append('<div id="'+file.id+'">')
        $("#upload-progress").css('overflow','hidden');
        $("#"+file.id).progressbar().append('<div class="ui-progressbar-text" id="'+file.id+'_label"></div>');
        $("#"+file.id).css('margin-bottom', '5px');
        $("#"+file.id).find('.ui-progressbar-text').css({'font-weight': 'bold','position': 'relative', 'text-align': 'center', 'top': '-22px'});
        $('#ui-dialog-title-upload-progress').css('font-size',11);
    },
    
    uploadProgress : function(file, uploadedBytes, totalBytes){
        //alert('IMDTUploadHandlers::uploadProgress');
        percentUploaded = uploadedBytes*100/totalBytes;
        if(percentUploaded < 100)
            $("#"+file.id).progressbar({value: percentUploaded}).find('.ui-progressbar-text').html(file.name+' ('+Math.round(percentUploaded)+'%)').end();
        else
            $("#"+file.id).progressbar({value: 99}).find('.ui-progressbar-text').html(file.name+' (99%)').end();
    },
    
    uploadError : function(file, errorCode, message){
        //alert('IMDTUploadHandlers::uploadError');
        $("#"+file.id).progressbar({value: percentUploaded}).find('.ui-progressbar-text').html(file.name+' ('+errorCode+': Ocorreu um erro ao enviar o arquivo.)').end()
    },
    
    uploadSuccess : function(file, serverData, response, swfuInstanceCustomProperties){    
        var options = $.extend(jQuery.parseJSON(serverData), swfuInstanceCustomProperties);
        options.autoResize = $('input#automaticResize-' + swfuInstanceCustomProperties.widgetId).is(':checked');      
        $("#"+file.id).progressbar({value: 99}).find('.ui-progressbar-text').html(file.name+' (99%)').end();
        if(appendUploadedImage(file, options))
            $("#"+file.id).progressbar({value: 100}).find('.ui-progressbar-text').html(file.name+' (100%)').end();
    },
     
    uploadComplete : function(file){    
        //alert('IMDTUploadHandlers::uploadComplete');        
    },
    
    queueComplete : function(){
        //alert('IMDTUploadHandlers::queueComplete');
        $("#upload-progress").dialog({
            title: 'Arquivos enviados com sucesso!',
            buttons: [
                {
                    text: "Fechar",
                    click: function() { 
                    $(this).dialog("close"); 
                    $(this).dialog("destroy");
                    $(this).html(''); }
                }
            ]   
       });
       $('.ui-dialog-buttonset').css({'float':'none','text-align':'center'});        
    }
}



/*SEPARAR AQUI*/
iMDTPerformResize = function(fileObj, options){
    
    var largura = options.dimensions.width;
    var altura = options.dimensions.height;
    
    var returnValue = $.ajax({
        url             : '/index2.php/upload/resize/',
        method 		: 'post',
        data		: 'id=' + fileObj.name + '&width=' + largura + '&height=' + altura,
        dataType	: 'json',
        async           : false,
        success	: function(a,b){
            if("success" == b){
                return a;
            }
        }
    }).responseText;
    
    var objRetorno = jQuery.parseJSON(returnValue);
    return objRetorno;
}

appendUploadedImage = function(file, options){
    var resolutions = options.resolutions;
    var files       = new Array();
    var objResized;

    $(resolutions).each(function(i, curr){
        objResized = iMDTPerformResize(file, {dimensions:curr});
        files[files.length] = objResized;
    });
    
    $(files).each(function(i, curr){
        imageContainerNode($.extend(options, curr));
    });
    
    return true;
}

imageContainerNode = function(options){
    var widgetTemplate = '<div class="tableSortable">';
        widgetTemplate += '<h2 style="font-size: 14px;">Imagens Adicionadas</h2>';
        widgetTemplate += '<table width="100%" align="center" cellpadding="0" cellspacing="0" border="0" id="uploaded-images">';
        widgetTemplate += '<thead>';
        widgetTemplate += '<tr>';
        widgetTemplate += '<th width="3%">&nbsp;</th>';
        widgetTemplate += '<th width="6%">Miniatura</th>';
        widgetTemplate += '<th>Nome</th>';
        widgetTemplate += '<th width="33%">Descri&ccedil;&atilde;o</th>';
        widgetTemplate += '<th width="20%">Criada em</th>';
        widgetTemplate += '<th width="5%">A&ccedil;&otilde;es</th>';
        widgetTemplate += '</tr>';
        widgetTemplate += '</thead>';
        widgetTemplate += '<tbody>';
        widgetTemplate += '</tbody>';
        widgetTemplate += '</table>';       
        widgetTemplate += '</div>'; 

    var widgetElement  = $('#main').find('table#uploaded-images tbody'); 
    var widgetExists   = $(widgetElement).size() > 0;

    if(!widgetExists) {
        $('#submit-label').before(widgetTemplate); 
        widgetElement  = $('#main').find('table#uploaded-images tbody'); 
        widgetExsits   = true;
    }
    
      
    var bagElement     = $(widgetElement).find('tr#preview-' + options.originalId);
    var bagExists      = $(bagElement).size() > 0;
    
    var imageBagTemplate = '';
    
    if(bagExists) {
        imageBagTemplate = '<input type="hidden" name="{8}[images][{5}][fileName]" value="{5}"/>';
        imageBagTemplate += '<input type="hidden" name="{8}[images][{5}][childImages][{2}][fileName]" value="{2}"/>';
        imageBagTemplate += '<input type="hidden" name="{8}[images][{5}][childImages][{2}][width]" value="{6}"/>';
        imageBagTemplate += '<input type="hidden" name="{8}[images][{5}][childImages][{2}][height]" value="{7}"/>';
    } else {
        imageBagTemplate = '<tr id="preview-{1}">';
        imageBagTemplate += '<td width="3%" class="values">';
        imageBagTemplate += '<input type="hidden" name="{8}[images][{5}][fileName]" value="{5}"/>';
        imageBagTemplate += '<input type="hidden" name="{8}[images][{5}][childImages][{2}][fileName]" value="{2}"/>';
        imageBagTemplate += '<input type="hidden" name="{8}[images][{5}][childImages][{2}][width]" value="{6}"/>';
        imageBagTemplate += '<input type="hidden" name="{8}[images][{5}][childImages][{2}][height]" value="{7}"/>';
        imageBagTemplate += '</td>';
        imageBagTemplate += '<td width="6%" style="text-aling: center;padding: 5px 0;">';
        imageBagTemplate += '<img style="float: left;" src="{4}"/>';
        imageBagTemplate += '</td>';
        imageBagTemplate += '<td>';
        imageBagTemplate += '{5}';
        imageBagTemplate += '</td>';
        imageBagTemplate += '<td width="33%">';
        imageBagTemplate += '<input style="margin: 0;" type="text" name="{8}[images][{5}][description]" />';
        imageBagTemplate += '</td>';
        imageBagTemplate += '<td width="20%">';
        imageBagTemplate += '{9}';
        imageBagTemplate += '</td>';
        imageBagTemplate += '<td width="5%">';
        imageBagTemplate += '<a class="link-acao link-delete" onclick="$(this).parent(\'td\').parent(\'tr\').fadeOut(\'slow\',function(){$(this).remove()});return false;" href=""></a>';
        imageBagTemplate += '</td>';
        imageBagTemplate += '</tr>';
    }

    var imageUrl       = options.imageUrl;
    
    if(!imageUrl || imageUrl == 'undefined'){
        imageUrl       = '/index2.php/upload/show/id/' + options.friendlyFileName; 
    }

    bagNode = imageBagTemplate.replace(/\{1\}/gi, options.originalId);
    bagNode = bagNode.replace(/\{2\}/gi, options.friendlyFileName);
    bagNode = bagNode.replace(/\{3\}/gi, options.uploadedAt);
    bagNode = bagNode.replace(/\{4\}/gi, imageUrl);
    bagNode = bagNode.replace(/\{5\}/gi, options.originalFileName);
    bagNode = bagNode.replace(/\{6\}/gi, options.resolution.width);
    bagNode = bagNode.replace(/\{7\}/gi, options.resolution.height);
    bagNode = bagNode.replace(/\{8\}/gi, options.widgetName);
    bagNode = bagNode.replace(/\{9\}/gi, options.uploadedAtFormatted);
    
    if(bagExists)         
        $(bagElement).children('td.values').append(bagNode);
    else
        $(widgetElement).append(bagNode);
}

