//
// +----------------------------------------------------------------------+
// | Vision 6 - File upload input field clientside validation routines    |
// +----------------------------------------------------------------------+
// |                                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 2007 Vision 6 Pty Ltd                                  |
// +----------------------------------------------------------------------+
// | Author: Sam Pospischil <spospischil@vision6.com.au>                  |
// +----------------------------------------------------------------------+
//
// $Id$
//

var File_Upload_Field = {

    allowable_types : [
        'jpeg','jpg','png','gif','doc','pdf','rtf','txt','xls','csv',
        'swf','mpeg','mpg','wmv','avi','wav','zip','pps','ppt','vcf',
        'docx','xlsx','pptx','ppsx',
        'ics','vcs'
    ],

    allowable_types_categories : {
        Images :        ['jpeg','jpg','png','gif'],
        Documents :     ['doc','docx','pdf','rtf','txt'],
        Spreadsheets :  ['xls','xlsx','csv'],
        Media :         ['swf','mpeg','mpg','wmv','avi','wav']
    },

    return_errors : false,      //true if error string should be sent back to other validation routine
    error_string : '',

    // checks if a file extension is valid for uploading
    checkUploadFileExtension : function(oFld) {
        var ext               = oFld.value.substr(oFld.value.lastIndexOf(".")+1).toLowerCase();

        // :SHONK: file manager hack - if replace, then the extensions should be same.
        try {
            var selected_file_url = getSelectedFileUrl();
            if (document.getElementById('rs').checked && selected_file_url && selected_file_url.length > 0) {
                var selected_file_ext = selected_file_url.substr(selected_file_url.lastIndexOf(".") + 1).toLowerCase();
                if (ext != selected_file_ext) {
                    customInfoBubble(oFld, 'Cannot replace ' + oFld.value + ' with ' + getFileName() + ' as they are of different extensions', 1, 0, BOTTOM, true);
                    return false;
                }
            }
        }
        catch (Error) {
            // no file extension checking to be done over here.
            // on contacts details page.
            var isError = true;
        }
        oFld.style.color = "black";     //pourquoi?

        var valid_types;
        if (oFld.getAttribute('sf_override_exts')) {
            valid_types = oFld.getAttribute('sf_override_exts').split(',');
        } else {
            valid_types = this.allowable_types;
        }

        for (var t = 0; t < valid_types.length; ++t) {
            if(ext == valid_types[t]) {
                return true;
            }
        }
        if (!this.return_errors) {
            customInfoBubble(oFld, this.getAllowedTypesPopupHtml(valid_types), 1, 0, BOTTOM, true);
        } else {
            this.error_string += this.getAllowedTypesErrorString(valid_types, oFld.getAttribute('sf_title')) + "\n";
        }
        return false;
    },

    getAllowedTypesErrorString : function(override_types, field_name) {
        var output = ' - \'' + field_name + '\' only allows file extensions ';

        if (!override_types) {
            override_types = this.allowable_types;
        }
        output += override_types.join(', ').toUpperCase();

        return output;
    },

    // generate some error HTML to show why the file was rejected
    getAllowedTypesPopupHtml : function(override_types) {
        var output = 'Only the following file types may be uploaded:<br/><br/><table cellpadding="2" cellspacing="0">';
        var categorised_extensions = {};

        if (!override_types) {
            override_types = this.allowable_types;
        }

        for (var t = 0; t < override_types.length; ++t) {
            var category = 'Other';
            for (var cat in this.allowable_types_categories) {
                if (typeof this.allowable_types_categories[cat] == 'function') {
                    continue;
                }
                for (var i = 0; i < this.allowable_types_categories[cat].length; ++i) {
                    if (this.allowable_types_categories[cat][i] == override_types[t]) {
                        category = cat;
                    }
                }
            }
            if (!categorised_extensions[category]) {
                categorised_extensions[category] = new Array();
            }
            categorised_extensions[category].push(override_types[t]);
        }

        for (var cat in categorised_extensions) {
            if (typeof categorised_extensions[cat] == 'function') {
                continue;
            }
            output += '<tr><td>' + cat + '</td><td nowrap>(';
            var upper_extensions = new Array();
            for (var u = 0; u < categorised_extensions[cat].length; ++u) {
                upper_extensions[upper_extensions.length] = categorised_extensions[cat][u].toUpperCase();
            }
            output += upper_extensions.join(', ');
            output += ')</td></tr>';
        }
        output += "</table>";
        return output;
    },

    // check every file upload field on a form. How handy!
    // Can accept either a submit button or form object, however note that the submit button's
    // behaviour can only be applied if it is passed as the parameter.
    checkAll : function(el, skipSubmit, returnErrors) {
        var submit_button;
        var parentForm;
        if (el.form) {
            parentForm = el.form;
            submit_button = el;
        } else if (el.nodeName.toLowerCase() == 'form') {
            parentForm = el;
        } else {
            alert('Containing form was not found in form file upload validation routine!');
            return false;
        }

        this.return_errors = returnErrors ? true : false;
        this.error_string = '';          //reset this

        var i = 0;
        var error = false;
        while (i < parentForm.elements.length) {
            if (parentForm.elements[i].nodeName.toLowerCase() == 'input'
              && parentForm.elements[i].type == 'file') {
                if (parentForm.elements[i].getAttribute('mandatory') && !parentForm.elements[i].value.length) {
                    var mand = parentForm.elements[i].getAttribute('mandatory');
                    if (mand && mand != 0 && mand != '0' && mand != 'false') {
                        error = true;
                        if (!this.return_errors) {
                            customInfoBubble(parentForm.elements[i], "Please press the Browse button to select a file to upload.", 1, 0, BOTTOM, true);
                            break;          //we dont want to swarm the screen with errors!
                        }
                        // :WARNING: assuming returning errors is synonymous with quickform usage, which means mandatory checks are already made
                        /*else {
                            this.error_string += ' - \''+ parentForm.elements[i].getAttribute('sf_title') +'\' is a Mandatory field.\n';
                        }*/
                    }
                }

                if (parentForm.elements[i].value.length > 0) {
                    var file_ext = parentForm.elements[i].value.substr(parentForm.elements[i].value.lastIndexOf(".") + 1);
                    var match_array = parentForm.elements[i].value.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/);
                    if (match_array && match_array.length > 0) {
                        var upload_file_name = match_array[2];
                        if (upload_file_name && upload_file_name.length > 0) {
                            // remember >= 0 as array index begins with 0.
                            if (typeof file_array != 'undefined' && file_array && file_array.length > 0) {
                                var file_index = this.inArray(upload_file_name, file_array);
                                if (file_index >= 0) {
                                    if (confirm(upload_file_name + ' is already uploaded. Would you like to replace it')) {
                                        var replace_file_id = document.getElementById('replace_file_id');
                                        if (replace_file_id) {
                                            var file_id = js_file_id[upload_file_name];
                                            if (file_id > 0) {
                                                replace_file_id.value = file_id;
                                                // set to 1 to indicate user wishes to replace the old file.
                                                var replace_file = document.createElement('input');
                                                replace_file.setAttribute('type',  'hidden');
                                                replace_file.setAttribute('name',  'replace_selected');
                                                replace_file.setAttribute('value', '1');
                                                parentForm.appendChild(replace_file);
                                            }
                                        }
                                    } else {
                                        // user doesnt want to replace the new file with the existing file.
                                        error = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                if (parentForm.elements[i].value.length && !this.checkUploadFileExtension(parentForm.elements[i])) {
                    error = true;
                    if (!this.return_errors) {
                        break;          //we dont want to swarm the screen with errors!
                    }
                }
            }
            ++i;
        }
        if (this.error_string == '') {
            this.return_errors = false;
        }
        if (!error) {
            if (!skipSubmit) {
                if (submit_button) {
                    submit_button.disabled = true;
                    submit_button.value = "Uploading...";
                }
                document.body.style.cursor = "wait";
                parentForm.submit();
            }
            return true;
        } else {
            return this.return_errors ? this.error_string : false;
        }
    },

    inArray: function(item, from){
		var len = from.length;
		for (var i = 0; i < len; i++){
			if (from[i] === item) {
                return i;
            }
		}
		return -1;
	}
};
