// this script handles ajax upload progress bar on our advforms.
//
// a dynamic form is created and its target is set to a hidden iframe.
// the form is posting the actual files to "/uploadProgressBar/formresp.asp?progressid=N"
// this form reports back the name of the temp file via a script it renders in its iframe that calls 
// the parent window script setNewFilename(fieldname, filename, pid)
//
// in order to avoid opening another window and show the progress on the current HTML page
// we track the file upload using an xmlhttprequest directed to "/uploadProgressBar/progressajax.asp?progressid=N"
// where the progress id matches the one submitted on the form. this process repeats itself until the file is over.
//
// we have the server assign us progress ids by sending an xmlhttprequest to 
// "/uploadProgressBar/getProgressIds.asp?amount=N" where the amount is the number of files we plan to upload
//
// to modify a page to use this script do the following:
// 1. Add an "ID=AviForm" attribute to the main form 
// 2. Add a script tag to include this file and recreate the fieldnames array using ASP
//      e.g.
//          fieldnames = new Array('< % = FieldNamesArray(32) % >', '< % = FieldNamesArray(33) % >');
//
// 3. Include the file /uploadProgressBar/gui.asp just after the <tr> that closes the form's painted area
// 4. Add IDs to the confirm buttons (inside the <td>) called 'confirm1' for the image and 'confirm2' for the text
// 5. Add a js global variable called tablename
//
// each file is uploaded seprately via this entire process, each file has its own form rebuilt from scratch
// the reason for that is the progress file object which doesn't allow tracking seperate files in a single upload
// routine


// fieldnames of file input fields
var fieldnames = new Array();

// the stack we'll use to handle multiple files upload
var filestack = new Array();

// our stack of progressids
var progressids = new Array();

// 1 - init, 2 - upload in progress, 3 - done
var cstatus = 1;

// start the show
function uploadWithProgress(advForm, fieldnames) {
    var gogogo = false;
    
    //disable the confirmation button
    var c1 = document.getElementById('confirm1');
    var c2 = document.getElementById('confirm2');
    
    c1.onclick = '';
    c2.onclick = '';
    c2.style.color = 'gray';

    
    // prep our stack
    // add only fields with values
    for (var i in fieldnames) {        
        var key = fieldnames[i];        
        if (key != '' && typeof(advForm[key].value) != 'undefined' && advForm[key].value != '') {                
            filestack.push(key);            
            gogogo = true;
        }
    }
    
    if (gogogo)  {   
        //get progress ids for the upload
        getProgressIds(filestack.length);                            
        uploadNextFile();
    } else
        submitMainForm();
}


//get next file off the stack and upload it
function uploadNextFile() {
        
    // get next file fieldname (if any)
    var nextField = filestack.pop();
               
    //main form reference    
    var advForm = document.getElementById('AviForm');
    
    //check if we finished with the stack, then submit the main form     
    if (typeof(nextField) == 'undefined' ||
        nextField == '' || 
        typeof(advForm[nextField].value) == 'undefined' || 
        advForm[nextField].value == '') {

        submitMainForm();        
        return false;        
    }
    
    // get a progress id off the stack for this file
    var nextProgressId = progressids.pop();
    
    // if somehow we are out of our premade progress ids
    if (typeof(nextProgressId) == 'undefined') {        
        var arrPid = getProgressIds(1);
        nextProgressId = arrPid[0];
    }
          
    // create a dynamic upload form for our file
    var uploadForm  = createForm('uploadform' + nextField, '/uploadProgressBar/formresp.asp?progressid=' + nextProgressId + '&tablename=' + tablename, true, 'post');   
    uploadForm.target = 'formframe';
    uploadForm.style.display = 'none';
    
    //prep filename that will be displayed on the bar
    var filename = advForm[nextField].value;
    filename = filename.slice(filename.lastIndexOf('\\') + 1);
    
    //reset progress display area
    var bdiv = document.getElementById('progressbarBorder');
    var pdiv = document.getElementById('progressbar');
	var fspan = document.getElementById('filenameLabel');	
	var ptext = document.getElementById('progressText');
	
	bdiv.style.visibility = 'visible';
	pdiv.style.width = '0px';
	setInnerText(ptext, '');
    setInnerText(fspan, 'מעלה קובץ "' + filename + '"...  ');
            
    //steal the file field from the real form            
    uploadForm.appendChild(advForm[nextField]);
    
    //add our new form to the document body    
    document.body.appendChild(uploadForm);        
            
    //xmlhttp request for progress on upload        
    var exec = function () { createRequest(nextProgressId, filename); }
    cstatus = setInterval(exec, 500);
    
    //send the file    
    uploadForm.submit();
    
    return;
}

// get the upload status
function createRequest(progressId, filename) {        
    if (cstatus == 1 || cstatus == 3)  {
    var xmlhttp = newXmlHttpRequest();  
    
    // build our request
    var exec = function () { return cbUpdateProgress(xmlhttp, progressId, filename); };
    xmlhttp.onreadystatechange = exec
    xmlhttp.open('GET','/uploadProgressBar/progressajax.asp?progressid=' + progressId, true);
    xmlhttp.send(null);

}
    return;
}

//callback function for our main xmlhttpRequest, 
//this function updates the html and calls the next createRequest() or next uploadNextFile()
function cbUpdateProgress(xmlhttp, progressId, filename) {
        
    if (xmlhttp.readyState != 4) { return; }
        
    if (xmlhttp.status == 200) {                              
        var response = xmlhttp.responseText;                                
        var pdiv = document.getElementById('progressbar');
        var ptext = document.getElementById('progressText');
                                          
        if (response != 'done') {
                            
            //if upload has started display some info
            if (typeof(response) != 'undefined'
                 && response != ''
                 && !isNaN(response)) {	                                                
                
                setInnerText(ptext, response + '%');                    
                pdiv.style.width = response + '%';
            }
            
            //xmlhttp = null
            //var exec = function() { return createRequest(progressId, filename); };
            //setTimeout(exec, 1000);
            //createRequest(progressId, filename);
        } else {                	                                
            setInnerText(ptext, '100%');
            pdiv.style.width = '100%';            
            
            setInnerText(ptext, 'הקובץ הועלה בהצלחה');
            var hdiv = document.getElementById('progressHistory');
                            
            hdiv.innerHTML += 'העלאת הקובץ <i>' + filename + '</i> נסתיימה <br />';
            
            //clearInterval(mainInterval);
            //xmlhttp = null
            cstatus = 3;
            setTimeout('uploadNextFile()', 1500);
           
        }
    }
      
    return;
}

//createRequest(progressId, filename);
//setTimeout('uploadNextFile()', 1500);

//ask the server (sync) to assign progress ids for each file
function getProgressIds(amount) {
    var xmlhttp = newXmlHttpRequest();  
                                       
    xmlhttp.open('GET','/uploadProgressBar/getProgressIds.asp?amount=' + amount, false);
    xmlhttp.send(null);

    // we must have atleast one comma in the response                                                
    if (xmlhttp.status == 200) {  
        var response = xmlhttp.responseText;
        
        if (response.indexOf(',') != -1) {
            progressids = response.split(',');
            
            //remove the last undefined element due to extra comma                                                    
            progressids.pop()
        } else {
            alert('העלאת הקבצים נכשלה, אנא נסה שוב לאחר סיום תהליך, דרך ניהול המודעה או פנו להנהלת האתר');
            submitMainForm();
        }
    } else {
        alert('העלאת הקבצים נכשלה, אנא נסה שוב לאחר סיום תהליך, דרך ניהול המודעה או פנו להנהלת האתר');
        submitMainForm();                                                   
    }


    return progressids;
}

// this function is called by the iframe after the file has finished uploading
// it this inject a hidden field to the main form
function setNewFilename(fieldname, filename, pid) {
    //init state
    cstatus = 1;

    var form = document.getElementById('AviForm');
    
    //inject the field
    if (typeof(form[fieldname]) == "undefined") {
        
        if (fieldname != '' && filename != '') {            
            var newfield = createField('hidden', fieldname, filename, '')
            form.appendChild(newfield);        
        }
    }
    
    return true;
}

// set text inside a node
function setInnerText(node, text) {
    if(document.all){
        node.innerText = text;
        return node.innerText;
    } else{
        node.textContent = text;
        return node.textContent;
    }

    return false;
}

function getInnerText(node) {
     if(document.all){        
        return node.innerText;
    } else{        
        return node.textContent;
    }
}

function submitMainForm() {
    setTimeout('document.getElementById("AviForm").submit()', 1500);
}