﻿/*

File Upload HTTP module for ASP.Net (v 2.0)
Copyright (C) 2007-2008 Darren Johnstone (http://darrenjohnstone.net)

--------------------------------------------------------------------
Updated Nov 2009 to work with jQuery library

Karl Maynard, Indicia Danmark A/S (www.indicia.dk)

--------------------------------------------------------------------

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either 
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

var up_xhttp;
var up_key;
var up_loading = false;
var up_imagePath;

function up_AddUpload(id)
{
    $("#" + id + " > .upUploadBox").children(".upHiddenDynamic:first").removeClass("upHiddenDynamic");
}

function up_ValidateUpload(source, clientside_arguments)
{        
    var ok = false;
    
    $("input", $(source).parent()).each(function() {
        
        if (this.type == 'file')
        {
            if ($(this).val() != null && $(this).val() != '')
            {
                ok = true;
                return false; // break
            }
        }
    
    
    });
  
    clientside_arguments.IsValid = ok;
}

function up_ValidateUploadExtensions(source, clientside_arguments)
{        
    var extField = source.previousSibling;
    var ok = true;        

    if (extField.value != null && extField.value != '')
    {
        var exts = extField.value.split(',');
        
         $("input", $(source).parent()).each(function() {
             if (this.type == 'file')
             {
                var fname = $(this).val();
                if (fname != null && fname != '')
                {                    
                    var valid = false;
                    for (var j=0; j<exts.length; j++)
                    {
                        if (fname.toLowerCase().lastIndexOf(exts[j]) != -1)
                        {
                            valid = true;
                            break;
                        }
                    }
                    
                    ok = ok && valid;
                    if (!ok) return false; // break
                 
                }             
             }
         
         });
        
    
    }
    clientside_arguments.IsValid = ok;
}

function up_ValidateHaveUploads()
{        
    var valid = false;
    $('input', $('.upUploadBox')).each(function (i) {
        
        if (this.type == 'file')
        {
            if ($(this).val() != null && $(this).val() != '')
            {
                valid = true;
                return false;
            }
        }
    
    
    });
    
    return valid;
}

function up_ClearUploadElement(el)
{
    var newItem = document.createElement('input');
    newItem.type = 'file'
    newItem.id = el.id;
    newItem.name = el.name;
    newItem.className = el.className;
    newItem.relatedElement = el.relatedElement;
    newItem.onchange = el.onchange;
    newItem.onmouseout = el.onmouseout;
    
    var parent = el.parentNode;
    parent.replaceChild(newItem, el);
    
    parent.className += ' upHiddenDynamic';
}

function up_RemoveUpload(e)
{
    $('input', $(e.parentNode)).each(function() {
    
        if (this.type == 'text')  $(this).val('');            
        if (this.type == 'file')  up_ClearUploadElement(this);
    
    });        
}

function up_BeginUpload(key, showcancel, url)
{

    if (typeof(Page_ClientValidate) == 'function')
    {
        //Page_ClientValidate();
        if (!Page_IsValid) return;
    }
    
    if (navigator.userAgent.indexOf("Opera") != -1) return;
    
    if ($('#' + key) == null) return; 
    
    if (!up_ValidateHaveUploads()) return;
    
    up_key = $('#' + key).val();
    up_showCancel = showcancel;
    
       
    up_SetProgress(0, '');
    
    window.setInterval('up_ReportProgress()', 1000); //1500);
}

function up_SetProgress(progress, file)
{
    var html;    
    html  = "<div class='upContainer'>";
    html += "<div class='upOuterBar'>";
    html += "<div id='upProgressBar' class='upInnerBar' style='width:" + progress + "%'>";
    html += "</div>";
    html += "<div id='upLabel' class='upLabel'>";
    
    if (progress == '100')
    {
        html += "Processing.....";
    } else {
        html += (progress == 0 ? "Waiting for uploads to start" : "Now uploading " + file + " " + progress + "%");
    }
        
    html += "</div>";
    html += "</div>";
    html += "</div>";
    
    // Cancel button
    if (up_showCancel)
    {
        html += "<img src='" + up_imagePath + "cancelbutton.gif' onclick='document.location=document.location' style='cursor:hand;margin-top:5px' />";
    }
    
    if (!up_loading)
    {
        $("FORM").append('<div id="progress"></div>');
        $("#progress").html(html);
        $("#progress").dialog({
                        title: 'File Upload Progress',
			            bgiframe: true,
			            autoOpen: false,
			            width: 600,			       	
			            modal: true,
			            closeText: '',
			            buttons: { },
			            close: function() {
				             $(this).dialog('destroy');
			            }
		            });
        
        $('#progress').dialog('open');        
    }
    else
    {
        $("#progress").html(html);
    }

    up_loading = true;
}

var up_waiting = false;

function up_ReportProgress()
{  
   if (up_waiting) return;
   up_waiting = true;
   
    var ts = new Date().getTime(); // Time stamp to stop caching
    
    var url = 'UploadProgress.ashx?DJUploadStatus=' + up_key + '&ts=' + ts;
    $.get(url, function (xml, sts) { 
    
        if (sts != 'success' || xml == null || xml == '') 
        {
            up_SetProgress(0, sts);
        } 
        else
        {  
            try 
            {                      
                var badlen = $('status',xml).attr("badlength");          
            
                if (badlen == 'true')
                {
                    document.location=document.location + "&toobig=1";                        
                }
                else if ($('status',xml).attr("empty") == 'true') {
                    up_SetProgress(0, '');
                    
                } else {           
                    var pcnt = $('status',xml).attr("progress");

                    if (pcnt == 'undefined') {
                        up_SetProgress(0, '');
                        
                    } else {
                        //var fsize = $('status',xml).attr("size");
                        //var fbytes = $('status',xml).attr("bytes");                    
                        //var fuplcid = $('status',xml).attr("containerid");                                
                        up_SetProgress(pcnt, $('status',xml).attr("file"));
                    }
                }
            }
            catch (e)
            {
                up_SetProgress(0, e);
            }
        }
    }, 'xml')
    
	up_waiting = false;
}

function up_createDynamicStyles(cssPath)
{
//    var cssNode  = $('<link id="upDynaStyles" href="' + cssPath + 'dynamicstyles.css" rel="stylesheet" type="text/css" />');
//    $('head').append(cssNode);
    
}

function up_killProgress(id)
{
    if (navigator.userAgent.indexOf("Opera") != -1) return;
    
    var el = document.getElementById(id);
    el.parentNode.removeChild(el);
}


/* ======================================================================
The following function for styling input controls comes from
http://www.quirksmode.org/dom/inputfile.html
========================================================================= */

function up_initFileUploads(imagepath) 
{
    up_imagePath = imagepath;

	// Bug fix: show cancel button in ModalBox in safari
	var preload_cancel = new Image();
	preload_cancel.src = up_imagePath + 'cancelbutton.gif';
    
    var W3CDOM = (document.createElement && document.getElementsByTagName);
    if (!W3CDOM) return;
    
    var html;
    html = '<input class="upFileBox"><img class="upSelectButton" style="margin-left: 5px;" src="'+ up_imagePath + 'selectbutton.gif">'
      
    $('input').each(function (i) {
     
        if (this.parentNode.className.indexOf('upFileInputs') >= 0  && this.relatedElement == null) 
        {
            if (this.type == 'file')
            {
	            this.className = 'upFile upFileHidden';
	                	        
	            $(this).parent().append(html); 
    	        
	            this.relatedElement = $(this).parent().children('input.upFileBox');
    	        
                $(this).change(function () { updatedRelated(this);});
                $(this).mouseout(function () { updatedRelated(this);});

            }
        }
        
     });
    
}

function updatedRelated(o)
{
        if (o.cleared || o.value == '') return;
        
        var val = o.value;
        val = val.substr(val.lastIndexOf('\\') + 1, val.length);
        val = val.substr(val.lastIndexOf('/') + 1, val.length);
        $(o.relatedElement).val(val);
}