﻿// JSLint Config:
/*jslint browser: true */
/*global cc, jQuery, Element, FancyUpload3, cc_resx_TR_Processing , cc_resx_TR_Retry, 
cc_resx_TR_Processing, cc_resx_TR_Cancel, cc_resx_THEME_KEY, cc_resx_SITE_URL, cc_resx_CDN_URL
*/

//  
//  Author: Kevin Burkitt
//  Date:   2010-04-08
//  
//  Upload Controller
//
cc.upload = function() {
    return {
        uploader: null,
        ajaxRequestsOpen: 0,
        uploadQueueEmpty: true,

        themekey: cc_resx_THEME_KEY,
        siteUrl: cc_resx_SITE_URL,
        cdnUrl: cc_resx_CDN_URL,

        onCompleteRedirectUrl: '',
        onCompletePostBackUrl: '',
        onCompletePostBackTarget: '',

        uploadUrl: '',
        inboxUrl: '',
        username: '',
        vipStatus: 'notset',
        filenameKey: '',
        ccusername: '',

        /*
        * Initialise Uploader Object
        */
        init: function(settings) {

            if (typeof settings === 'object') {
                // Override settings for profile picture & blog uploads
                if (typeof settings.onCompleteRedirectUrl !== 'undefined') {
                    cc.upload.onCompleteRedirectUrl = settings.onCompleteRedirectUrl;
                }
                if (typeof settings.onCompletePostBackUrl !== 'undefined') {
                    cc.upload.onCompletePostBackUrl = settings.onCompletePostBackUrl;
                }
                if (typeof settings.onCompletePostBackTarget !== 'undefined') {
                    cc.upload.onCompletePostBackTarget = settings.onCompletePostBackTarget;
                }
                if (typeof settings.uploadUrl !== 'undefined') {
                    cc.upload.uploadUrl = settings.uploadUrl;
                }
                if (typeof settings.inboxUrl !== 'undefined') {
                    cc.upload.inboxUrl = settings.inboxUrl;
                }
                if (typeof settings.username !== 'undefined') {
                    cc.upload.username = settings.username;
                }
                if (typeof settings.vipStatus !== 'undefined' && settings.vipStatus !== '') {
                    cc.upload.vipStatus = settings.vipStatus;
                }
                if (typeof settings.filenameKey !== 'undefined' && settings.filenameKey !== '') {
                    cc.upload.filenameKey = settings.filenameKey;
                }
                if (typeof settings.ccusername !== 'undefined' && settings.ccusername !== '') {
                    cc.upload.ccusername = settings.ccusername;
                }
                

            }

            var config = {
                path: '' + cc_resx_CDN_URL + 'swf/Swiff.Uploader.swf',
                url: cc.upload.uploadUrl,
                fileSizeMax: 1000 * 1024 * 1024,
                fileListMax: 10,
                timeLimit: 10000,
                verbose: true,

                fieldName: 'SourceFile',

                data: {
                    themeKey: cc.upload.themekey,
                    siteUrl: cc.upload.siteUrl,
                    inboxUrl: cc.upload.inboxUrl,
                    cdnUrl: cc.upload.cdnUrl,
                    username: cc.upload.username,
                    vipStatus: cc.upload.vipStatus,
                    filenameKey: cc.upload.filenameKey,
                    ccusername: cc.upload.ccusername
                    
                },

                onFileComplete: cc.upload.fileQueueItemUploadComplete,

                onComplete: cc.upload.fileUploadQueueComplete,

                onFileOpen: cc.upload.fileUploadStart,

                onFileStop: cc.upload.fileUploadCancel,

                onSelectFail: cc.upload.errorFileSelectFailure,

                onFileError: cc.upload.errorFileUploadFailure,

                onFileRequeue: cc.upload.onFileRequeue

            };

            var options = jQuery.extend(config, settings || {});
            cc.upload.uploader = new FancyUpload3.Attach('uploadFileList', '#file-attach, #file-attach-2', options);
        },


        /*
        *
        *   UPLOAD EVENTS
        *
        */


        // File Upload Starts
        fileUploadStart: function(file) {
            // Show 'Upload in Progress' Message
            jQuery('#upload-in-progress').show();
        },

        // A single file upload has completed - there maybe other uploads
        // in process or in the upload queue 
        fileQueueItemUploadComplete: function(file) {
            var fileSelector = 'li#file-' + file.id + '';
            jQuery(fileSelector).prepend('<span class="file-processing">' + cc_resx_TR_Processing + '</span>');
            
            if (cc.upload.onCompletePostBackTarget === '' && cc.upload.onCompletePostBackUrl !== '') {
                cc.upload.ajaxRequestsOpen += 1;
                cc.ajax.getJSON(
                    cc.upload.onCompletePostBackUrl,
                    { 'filename': file.name },
                    function(msg) {
                        cc.upload.ajaxRequestsOpen -= 1;
                        if (cc.upload.ajaxRequestsOpen < 1 && cc.upload.uploadQueueEmpty) {
                            jQuery('#upload-in-progress').hide();
                            window.location = cc.upload.onCompleteRedirectUrl;
                        }
                    }
                );
            } else {
                if (typeof cc.upload.onCompletePostBackTarget !== 'undefined' && cc.upload.onCompletePostBackTarget !== '') {
                    var url = cc.helpers.addQSParam(cc.upload.onCompletePostBackUrl, 'filename=' + cc.helpers.encodeQsParam(file.name));
                    cc.ajax.load(cc.upload.onCompletePostBackTarget, url);
                } else {
                    if (cc.upload.ajaxRequestsOpen < 1 && cc.upload.uploadQueueEmpty) {
                        jQuery('#upload-in-progress').hide();
                        window.location = cc.upload.onCompleteRedirectUrl;
                    }
                }
            }
        },

        // The upload queue is empty - all uploads have completed ...
        fileUploadQueueComplete: function() {

            cc.upload.uploadQueueEmpty = true;
            
            // All uploads are complete, but Ajax requests to initiate Transcode probably
            // are not - so change message to tell the user to wait a bit longer (status bar is
            // at 100%, so it's a bit confusing)


            // ... however, we need to wait for the ajax request in
            // cc.upload.fileQueueItemUploadComplete to finish before
            // we redirect - if this condition fails, the same piece of
            // code is in the ajax requests' 'Complete' event - this
            // duplication is to ensure that the order events occur is 
            // not an issue
            if (cc.upload.ajaxRequestsOpen < 1) {
                jQuery('#upload-in-progress').hide();
                window.location = cc.upload.onCompleteRedirectUrl;
            }
        },

        /*
        *
        *   ERROR EVENTS
        *
        */

        // File select failure - user chose a file in the browse tab that we don't like
        errorFileSelectFailure: function(files) {
            files.each(function(file) {
                // cc.log('Select Fail: ' + file.validationErrorMessage || file.validationError + '');
                var mooToolsElement = new Element('li', {
                    'class': 'file-invalid',
                    events: {
                        click: function() {
                            this.destroy();
                        }
                    }
                }).adopt(
					new Element('span', { html: file.validationErrorMessage || file.validationError })
				).inject(this.list, 'bottom');
            }, this);
        },

        // This particular file failed to upload (the rest of the queue might be ok)
        errorFileUploadFailure: function(file) {
            // cc.log(file.response.code);

            if (file.response.code !== 201 || file.response.code !== 0) {
                file.ui.cancel.set('html', cc_resx_TR_Retry).removeEvents().addEvent('click', function() {
                    file.requeue();
                    return false;
                });

                var mooToolsElement = new Element('span', {
                    html: file.errorMessage,
                    'class': 'file-error'
                }).inject(file.ui.cancel, 'after');
            }
        },


        /*
        *
        *   MISC EVENTS
        *
        */

        // User clicked to 'retry' a file (perhaps it failed earlier)
        onFileRequeue: function(file) {
            file.ui.element.getElement('.file-error').destroy();

            file.ui.cancel.set('html', cc_resx_TR_Cancel).removeEvents().addEvent('click', function() {
                file.remove();
                return false;
            });

            this.start(); 
        }

    };

} ();

