/*
 *
 * AJAX upload functions
 *
 */

/* Configuration */
var CUupload_host;
var CUstore_url;
var CUupload_url = "aupload/upload.php";
var CUupload_file=null;
var CUreq, CUareq, CUport;
var CUie_counter = 0;
var CUtimeout = 1000;
var CUupload_started=false;
var CUillegal_fnchars = "!\"£$%^&*()+=~#{}[];:,?/\\|`@'";

/* Globals */
var CUstartTime;

function CUvalidateSubmit()
{
    /* Do not submit if an upload is already in progress */
    if (CUupload_started)
    {
        return false;
    }

    /* Do not submit if the filename is invalid */
    if (CUvalidateFiles() < 0)
    {
        return false;
    }
    
    /* Flag the upload as in progress */
    CUupload_started = true;
    return true;
}

function CUcheckDisable(inst)
{
    if (CUupload_started)
    {
        inst.blur();
    }
}

function CUvalidateUpload()
{
    var ftypes = base64_decode(document.getElementById('allowedFileTypes').value);
    ftypes = ftypes.toLowerCase();
    
    /* Determine if an upload is already in progress */
    if (CUupload_started)
    {
        return false;
    }

    res = CUvalidateFiles();
    
    if (res == 0)
    {
        return true;
    }
    else if (res == -1)
    {
        alert("One or more filenames are of the wrong type (shown in red) or are missing.");
        return false;
    }
    else
    {
        alert("The highlighted filename(s) contain one or more of the following invalid characters: " + CUillegal_fnchars);
        return false;
    }
}

function CUgetXmlHttpReq()
{
    if (window.XMLHttpRequest)
    {
        xmlHttpObj = new XMLHttpRequest();
    }
    else
    {
        try
        {
            xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                xmlHttpObj = null;
            }
        }
    }
    
    return xmlHttpObj;
}

function CUgetUploadPort()
{
    if (!CUvalidateUpload())
    {
        return;
    }

    /* Set up the globals */
    CUupload_host = document.getElementById('serverName').value;
    CUstore_url = document.getElementById('storeURL').value;

    if ((CUreq = CUgetXmlHttpReq()) != null)
    {
        CUreq.open("GET", CUupload_host + CUstore_url + CUupload_url, false);
        var ret = CUreq.send(null);

        CUport = CUreq.responseText;

        if (CUport > 0)
        {
            var uf = document.getElementById('uploadform');
            uf.action = CUupload_host + '/uploadserver?pv=' + CUport;

            var us = document.getElementById('upload_status');
            us.innerHTML = 'Initialising Upload';

            var uc = document.getElementById('upload_popup');
            uc.style.display = 'block';

            /* Record the time to allow estimated completion time and transfer rate
             * to be calculated
             */
            CUstartTime = new Date();
            setTimeout('CUgetUploadStatus()', CUtimeout);
        }
        else
        {
            alert("Upload failed: could not connect to server");
        }
    }
    else
    {
        alert("Your browser does not support XMLHttp uploads.\nPlease upgrade your browser to the latest version.");
    }
        
}

function CUgetUploadStatus()
{    
    var url = CUupload_host + "/uploadserver?pv=" + CUport;

    if ((CUareq = CUgetXmlHttpReq()) != null)
    {
        CUareq.onreadystatechange = CUhandleUploadStatus;
        CUareq.open("GET", url, true);
        CUareq.send(null);
    }
}

function CUhandleUploadStatus()
{
    if (CUareq.readyState == 4)
    {
        if (CUareq.status == 200)
        {
            var r_status = CUareq.responseText;
            
            // Validate the response
            if ((r_status == undefined) || (r_status == ''))
            {
                // If an empty response was received, just reset the timer and do nothing
                setTimeout('CUgetUploadStatus()', CUtimeout);
                return;
            }

            // Process the response
            var split_status = r_status.split(',');
            var pc_complete = split_status[2];
            var bytesupld = split_status[0];
            var bytestotal = split_status[1];
            var bytesRemain = bytestotal - bytesupld;

            /* Calculate the elapsed time in seconds */
            var timeNow = new Date();
            var elapsedTime = (timeNow - CUstartTime) / 1000;
          
            if (elapsedTime > 0)
            {
                var xfrate = eval(bytesupld / elapsedTime);
                var dXfrate = CUgetDisplaySpeed(xfrate);
            }
            else
            {
                var xfrate = 0;
                var dXfrate = "0 B/sec";
            }

            if (xfrate > 0)
            {
                var timeRem = CUgetDisplayTime(eval(bytesRemain / xfrate));
            }
            else
            {
                var timeRem = "";
            }

            var et = document.getElementById('timeRemaining');
            et.innerHTML = timeRem + ' (' + CUgetDisplaySize(bytesupld) + ' of ' +
                                CUgetDisplaySize(bytestotal) + ' copied)';

            var us = document.getElementById('uploadDest');
            us.innerHTML = CUupload_host;

            var xr = document.getElementById('xferRate');
            xr.innerHTML = dXfrate;

            var fb = CUgetUploadFilePath();

            var us = document.getElementById('upload_status');
            us.innerHTML = pc_complete + '%' + ' completed';

            var uc = document.getElementById('upload_container');
            var mult = uc.clientWidth/100;
            
            var up = document.getElementById('upload_progress');
            up.style.width = eval(pc_complete * mult) + 'px';

            var complete_int = parseInt(pc_complete);
            if (complete_int < 100)
            {
                setTimeout('CUgetUploadStatus()', CUtimeout);
            }
        }
        else
        {
            setTimeout('CUgetUploadStatus()', CUtimeout);
        }
    }
}

function CUcancelUpload()
{
    /* Get the user to confirm they really want to cancel */
    if(confirm('Are you sure you want to cancel the upload?'))
    { 
        var uc = document.getElementById('upload_popup');
        uc.style.display = 'none';

        /* Reload the current page to cancel the upload */
        location.reload(true);

        CUupload_started = false;
    }
}

function CUvalidateFiles()
{
    var success = 0;
    var num_blanks = 0;
    var num_file_inputs = 0;
    var x = document.getElementsByTagName('input');
    
    for (var i = 0; i < x.length; i++)
    {
        // Look for input controls of type file that are visible
        if ((x[i].type == 'file') && (x[i].style.display == 'block'))
        {           
            // Keep a count of the number of file inputs
            num_file_inputs++;
        
            // Get the product prid and sequence number
            var pridseq = x[i].name.replace("id[", "").replace("]", "").split("_");
            
            // Get the artwork option associated with any already uploaded files for this product
            var artwork_option = document.getElementById("awtype_" + pridseq[0]).value;
            
            // Get the selected artwork option for this product
            var artwork_option_sel = document.getElementById(pridseq[0]).value;
                        
            // Get the allowed filetypes for this product
            var allowed_ftypes = base64_decode(document.getElementById("aft_" + pridseq[0]).value);
          
            // Validate the filenames in the file input controls
            var fnRes = CUvalidFileName(x[i].value, allowed_ftypes);
                        
            if (fnRes == 0)
            {
                // No filename specified, obtain the file upload ID determine if files are already uploaded
                var fupl_id = "fupl_" + ((x[i].id.split("_")[1]) - pridseq[1]);               
                
                // Determine if this product already has files uploaded and the artwork type has not been changed
                if ((document.getElementById(fupl_id).value == 1) && 
                    (artwork_option == artwork_option_sel))
                {
                    // Files already uploaded for this input
                    num_blanks++;
                }
                else
                {
                    success = -1;
                }
            }
            else if (fnRes != 1)
            {
               
                // Mark the offending input box in red
                x[i].style.backgroundColor = "#FF0000";
                
                // Set the onclick handler to clear the red background when the browse button is clicked
                x[i].onclick = fi_onclk;
                
                // Invalid filetype specified or illegal characters present
                success = fnRes;
            }
            else
            {
                // Ensure the input box with a valid filename is displayed in white
                x[i].style.backgroundColor = "#FFFFFF";
            }
        }
    }    
    
    // Ensure at least one input has a filename specified
    if (num_blanks == num_file_inputs)
    {
        // No file inputs had a value
        success = -1;
    }
    return success;
}

function fi_onclk()
{
    // When the browse button is clicked, clear the error condition
    this.style.backgroundColor = "#FFFFFF";
}

function CUvalidFileName(fPath, prod_allowed_ftypes)
{
    if (fPath.length == 0)
    {
        // The filename is not specified
        return 0;
    }

    // Obtain and decode the list of allowed file types    
    if (prod_allowed_ftypes == '')
    {
        var ftypes = base64_decode(document.getElementById('allowedFileTypes').value);
    }
    else
    {
        var ftypes = prod_allowed_ftypes;
    }
    
    ftypes = ftypes.toLowerCase();
    
    // Convert the file type list into an array
    var ftype_list = ftypes.split(",");
    
    // Obtain the upload filename
    var chosenFileName = CUbaseName(fPath);

    // Ensure the filename does not contain any illegal characters
    if (CUvalidFnChrs(chosenFileName) < 0)
    {
        // The filename contains illegal characters
        return -2;
    }

    // Convert to lowercase and extract the extension part
    chosenFileName = chosenFileName.toLowerCase();
    var cfnext = chosenFileName.split(".");
    
    // Search the allowed file type array to see if the filename extension is valid
    var valid_fn = -1;
    for (var i = 0; i < ftype_list.length; i++)
    {
        if (cfnext[(cfnext.length - 1)] == ftype_list[i])
        {
            // The filename is valid
            valid_fn = 1;
            break;
        }
    }
    
    return  valid_fn;
}

function CUvalidFnChrs(fname)
{    
    // Loop through the list of illegal filename characters
    for (var i = 0; i < CUillegal_fnchars.length; i++)
    {
        if (fname.indexOf(CUillegal_fnchars[i]) != -1)
        {
            // Invalid character found
            return -1;
        }
    }
    
    // No invalid characters found
    return 0;
}

function CUbaseName(afile)
{
    var fn = '' + afile;
    var Parts = fn.split('\\');
    if (Parts.length < 2)
    {
        Parts = fn.split('/');
    }
    return Parts[Parts.length-1];
}

function CUgetEndofPath(path, len)
{ 
    var filename = path.substring((path.length-len), path.length);
    return filename;
}

function CUgetDisplayTime(timef)
{
    var mins = 60;
    var hours = mins * 60;
    var dTime;
    var rTime;
    var htime;
    var mtime;
    var stime;
     
    rtime = timef;

    /* Calculate the hours component */
    htime = Math.floor(rtime / hours);
    rtime = rtime - (htime * hours);
    htime += '';

    /* Calculate the minutes component */
    mtime = Math.floor(rtime / mins);
    rtime = rtime - (mtime * mins);
    mtime += '';

    /* Calculate the seconds component */
    stime = Math.floor(rtime);
    stime += '';

    dTime = '';

    /* Only display hours if there are some */
    if (htime != '0')
    {
        dTime = htime + ' hr '
    }

    if (mtime != '0')
    {
        dTime += mtime + ' min '
    }

    /* Only display seconds when there are minutes and seconds are remaining */
    if ((htime == '0'))
    {
        dTime += stime + ' sec';
    }
    return dTime;
}

function CUgetDisplaySpeed(rate)
{
    var kbps = 1024;
    var mbps = kbps * 1024;
    var dRate;
        
    if (rate < kbps)
    {
        dRate = CUroundNumber(rate, 2) + " B/sec";
    }
    else if (rate < mbps)
    {
        dRate = CUroundNumber(eval(rate / kbps), 2) + " KB/sec";
    }
    else
    {
        dRate = CUroundNumber(eval(rate / mbps), 2) + " MB/sec";
    }
    return dRate;
}

function CUgetDisplaySize(size)
{
    var kbytes = 1024;
    var mbytes = kbytes * 1024;
    var tbytes = mbytes * 1024;
    var dSize;
        
    if (size < kbytes)
    {
        dSize = size + " bytes";
    }
    else if (size < mbytes)
    {
        dSize = Math.ceil(eval(size / kbytes), 2) + " KB";
    }
    else if (size < tbytes)
    {
        dSize = CUroundNumber(eval(size / mbytes), 2) + " MB";
    }
    else
    {
        dSize = CUroundNumber(eval(size / tbytes), 2) + " TB";
    }
    return dSize;
}

function CUgetUploadFilePath()
{
    return CUupload_file;
}

function CUsetUploadFilePath(id)
{
    upload_file = document.getElementById(id);
}

function CUroundNumber(num, dec)
{
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}

/*
 * Javascript functions to handle file upload notice
 */

function CUshow_uploading()
{
    /* Validate upload */
    if (!validateUpload())
    {
        return;
    }

    var x = document.getElementsByTagName('input');
    for (var i=0; i<x.length; i++)
    {
        if (x[i].type == 'file')
        {
            // We found the file input
            if ((x[i].value != "") && (document.getElementById('CustomerID').value != ""))
            {
                //Display the uploading message
                document.getElementById('ULInfo').style.visibility='visible';
            }
        }
    }
}

// base64 decode function
function base64_decode(data)
{ 
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];
 
    if (!data) 
    {
        return data;
    }
 
    data += '';
 
    do 
    {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));
 
        bits = h1<<18 | h2<<12 | h3<<6 | h4;
 
        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;
 
        if (h3 == 64)
        {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } 
        else if (h4 == 64)
        {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        }
        else
        {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);
 
    dec = tmp_arr.join('');
 
    return dec;
}