var cometsubscriptions = Array();

function subscribe(channel, callback) {
    cometsubscriptions[channel] = $.cometd.subscribe(channel, callback);
}

function unsubscribe(channel) {
    if (cometsubscriptions[channel[0]] != null) {
        $.cometd.unsubscribe(cometsubscriptions[channel[0]]);
        delete cometsubscriptions[channel[0]];
    }
}

(function($)
{
    var cometd = $.cometd;

    $(document).ready(function()
    {
        $( "#files" ).tabs();
        $('#keywords').bind("keypress", function(evt) {
            var charCode = (evt.which) ? evt.which : window.event.keyCode;
            if (charCode == 8 || charCode == 13)
                return true;
            var keyChar = String.fromCharCode(charCode);
            var re = /[a-zA-Z0-9, ]/
            return re.test(keyChar);

        });
        // Idempotent function called every time the connection
        // with the Bayeux server is (re-)established
        var _subscription;
        function _connectionSucceeded()
        {
            $('#body').empty().append('<div>Cometd Connection Succeeded</div>');
            
            cometd.batch(function()
            {
                
                if (_subscription)
                {
                    cometd.unsubscribe(_subscription);
                }

                var channelNames = Array();
                for(i=0;i< cometsubscriptions.length;i++) {
                    var chan = cometsubscriptions[i];
                    channelNames[channelNames.length] = chan;
                }
                
                for(i=0;i< channelNames.length;i++) {
                    var chan = channelNames[i];
                    unsubscribe(chan);
                    subscribe(chan, callback);
                }

                _subscription = cometd.subscribe('/videostatus', fileupload.videostatus);
                // Publish on a service channel since the message is for the server only
                cometd.publish('/service/hello', {
                    name: 'World'
                });
                cometd.publish('/service/videostatus',{});
            });
        }

        function _connectionBroken()
        {
            $('#body').empty().html('Cometd Connection Broken');
        }

        // Function that manages the connection status with the Bayeux server
        var _connected = false;
        function _metaConnect(message)
        {
            var wasConnected = _connected;
            _connected = message.successful === true;
            if (!wasConnected && _connected)
            {
                _connectionSucceeded();
            }
            else if (wasConnected && !_connected)
            {
                _connectionBroken();
            }
        }
        
        // Disconnect when the page unloads
        $(window).unload(function()
        {
            cometd.disconnect();
        });

        var cometURL = location.protocol + "//" + location.host + config.contextPath + "/cometd";
        cometd.configure({
            url: cometURL,
            logLevel: 'debug'
        });

        cometd.addListener('/meta/connect', _metaConnect);

        cometd.handshake();
        
    //fileupload.restartall();
    });
})(jQuery);

var fileupload = {
    deleteButton: function(type) {
        return " <a href='#' title='Cancel' onclick=\"$.cometd.publish('/service/removefile',{type:'"+type+"'});return false;\"><img src='img/101.png' alt='cancel'/></a>";
    },
    deleteButtonIndex: function(type, index) {
        return " <a href='#' title='Cancel' onclick=\"$.cometd.publish('/service/removefile',{type:'"+type+"',index:"+index+"});return false;\"><img src='img/101.png' alt='cancel'/></a>";
    },
    deleteButton2:  function(type) {
        return " <a href='#' title='Cancel' onclick=\"$('#"+type+" iframe').remove();return false;\"><img src='img/101.png' alt='cancel'/></a>"
    },
    refresh: function(){

    },
    videostatus: function(msg) {
        var status = msg.data.fileInfo;
        var types = ["audio","image"];
        if (msg.data.hasOwnProperty("action")){
            if (msg.data.action == "connect_to_youtube"){
                window.location = config.authSubUrl;
                return;
            }
        }
        //mp3Movie channel
        if (cometsubscriptions["/movie/"+status.ticketid] == undefined){
            subscribe("/movie/"+status.ticketid,fileupload.videostatus);
        }
        if (status.hasFailed)
            alert(status.errormessage);

        //file managers
        //audio
        if (status['audio'] == null) {
            $('#name').val("");
            $('#description').val("");
            if ($('#audio iframe').length == 0){
                fileupload.restart('audio');
            }
        }
        else {
            var audioFile = status.audio;
            if (audioFile.validates) {
                $('#audio').html("<img src='img/mp32tube/Ok-48x48.png' alt='ok'>" + audioFile.filename.substring(0,20));
                if (!(status.inqueue || status.processing || status.complete)){
                    $('#audio').append(fileupload.deleteButton('audio'));
                }
                if (audioFile.duration > 0)
                    $('#audio').append("<br/><span style='font-size:10px'>" +audioFile.duration + " seconds</span>");
                $('.error').text('');
            }
            else {
                if (!audioFile.inProgress)
                    fileupload.restart('audio');
            }
        }




        //Images
        var filestatus = $('#images .done');
        filestatus.text('');

        //Check if an image is being uploaded
        var upload = false;
        var num_images = 0;
        for(index in status['images']){
            var file22 = status['images'][index];
            if (parseInt(index) > num_images) num_images = parseInt(index);
            if (file22.inProgress)
                upload = true;
        }
        for(var indexa = 1 ; indexa <= num_images ; indexa++){
            var file = status.images[indexa];
            if (file.validates) {
                filestatus.append("<img src='img/mp32tube/Ok-48x48.png' alt='ok'>" + file.filename.substring(0,20));
                if (!(status.inqueue || status.processing || status.complete || upload)){
                    filestatus.append(fileupload.deleteButtonIndex('image', file.index));
                }
                filestatus.append("<br/>");
                $('.error').text('');
                if (upload==false){
                    $('#image').text('');
                }
            }
        }

        if (upload == false){
            //if ($('#image iframe').length == 0){
            if (status.premiumuser|| num_images < 1){
                if ($('#image iframe').length == 0){
                    fileupload.restart('image');
                }
            }
            else if (!status.premiumuser){
                $('#image').html("<a class='addimagefile' href='/signup.html'><b>+</b> Add an image file</a>")
            }
        //}
        }
        //FIN DEUX
        //during the process
        if (status.inqueue || status.processing||status.complete){
            if(status.complete) {
                $('#upload').hide();
                $('#complete').show();
                
                fileupload.createnewon();
                
                $('#complete #result').html("Your file was successfully created.");
                if (status.youtube != null){
                    $('#complete #result').append(" Your video is now being processed by the Youtube servers.");
                }
                $('#complete #result').append("<br/><br/>");
                if (status.youtube != null){
                    var youtubeUrl = "http://www.youtube.com/watch?v="+status.youtube.youtubeid;
                    $('#complete #result').append("Url :<br/><span class='linker'><a href='"+youtubeUrl+"'>"+youtubeUrl+"</a></span><br/><br/>");
                    //FB
                    $('#complete #result').append("Share :<div class='buttonshare'><a title='Click to share this video on Facebook' href='http://www.facebook.com/sharer.php?u="+youtubeUrl+"&t="+status.youtube.title+"'><img src='img/facebook.png'></a></div>");
                    //twit
                    $('#complete #result').append("<div class='buttonshare'><a href='http://twitter.com/home?status="+youtubeUrl+"' title='Click to share this post on Twitter'><img src='img/twitter.gif'/></a></div>");
                }
                $('#complete #result').append(" Download :<div class='buttonshare'><a title='Save the mpg File' href='download'><img src='img/download.png'/></a></div>");
                $('#complete #result').append("<br/><br/>");
        
            //after the process
            } else  {

                $('#upload').show();
                $('#complete').hide();

                fileupload.linkoff('.createnew');
                if (status.inqueue)
                    $('#upload span.msg').text("You are now in queue, please wait");//, in position "+status.queueposition);
                else
                    $('#upload span.msg').text("Your file is now being created on MP32Tube's server");

            }
            $('#files').tabs("option","enabled", 2);
            $('#files').tabs("select", 2);
            $('#files').tabs("option","disabled", [0,1]);
            $('#files').tabs("select", 2);
            fileupload.linkoff("#youtube");
            fileupload.linkoff("#convert");
        //before the process
        }else {
            //if the images & audio are uploaded'
            if (status.images != null && status.images[1].validates && status.audio != null && status.audio.validates && !status.hasfailed){
                if ($('#name').val() == "")
                    $('#name').val(status.audio.title);
                

                $('#files').tabs("option","enabled", [1,0]);
                $('#files').tabs("select", 0);
                $('#files').tabs("option","disabled", [2]);
                $('#files').tabs("select", 0);
                fileupload.linkon('#convert', function(){
                    $.cometd.publish('/service/convert',{
                        name:$('#name').val(),
                        description:$('#description').val(),
                        keywords: $('#keywords').val(),
                        _private: $('#private').is(':checked')
                    });
                    return false;
                });
                fileupload.linkon('#youtube', function(){
                    $.cometd.publish('/service/convert', {
                        action:'youtube',
                        name:$('#name').val(),
                        description:$('#description').val(),
                        keywords: $('#keywords').val(),
                        _private: $('#private').is(':checked')
                    });
                    return false;
                });
                fileupload.linkon("#next_step",function() {
                    $('#files').tabs('select', 1);
                    return false;
                });
            } else{
                $('#files').tabs("option","enabled", 0);
                $('#files').tabs("select", 0)
                $('#files').tabs("option","disabled", [1,2]);
                $('#files').tabs("select", 0)
                fileupload.linkoff("#youtube");
                fileupload.linkoff("#convert");
                fileupload.linkoff("#next_step");
            }
            fileupload.createnewon();
        }
        if ($('#files').css('display')=='none')
        {
            $('#files').css('display','block');
            $('#loadinit').hide();
        }
    },
    createnewon: function(){
        fileupload.linkon('.createnew',function(){
            if (confirm("Are you sure you want to create a new video ? You will lose all of your current data (images, mp3).")) {
                $.cometd.publish('/service/videostatus',{
                    action:'restart'
                });
            }
            return false;
        })
    },
    linkon: function(link_id, func) {
        $(link_id).css('opacity','1');
        $(link_id).unbind('click');
        $(link_id).click(func);
        $(link_id).css("cursor","pointer");
    },
    linkoff: function(link_id) {
        $(link_id).css('opacity','0.35');
        $(link_id).unbind('click');
        $(link_id).click(function(){
            return false;
        });
        $(link_id).css("cursor","default");
    },
    progress: function(msg) {
        var chanArray = msg.channel.split('/');
        var id = chanArray[chanArray.length-1];
        var type = $('#'+id).parent().attr('id');
        
        if (msg.data.error != "") {
            $('.error').text(msg.data.error);
            fileupload.restart(type);
        //if upload is complete
        } else if (msg.data.current == 100 && msg.data.total==100){
            $('.error').text('');
            $.cometd.publish('/service/videostatus',{});
        } else {
            $('.error').text('');
            //if the progress bar is not shown
            if ($('#'+id+" .progressbar").length == 0) {
                $('#'+id).append("<div class='label'>"+fileupload.deleteButton2(type)+"</div><div class='progressbar'><div class='progress'></div></div>")
            }
            
            if (msg.data.total > 0) {
                var percent = Math.round((msg.data.current/msg.data.total)*100);
                $('#'+id+" .progressbar .progress").show();
                $('#'+id+" .progressbar .progress").css('width',percent+"px");
                $('#'+id+" .label").html(percent+"% "+fileupload.deleteButton2(type));
            }
            else{
                $('#'+id+" .progressbar .progress").hide();
                $('#'+id+" .label").text((msg.data.current/1024) + " kB" );
            }
        }
    },
    restart: function(type) {
        var id = $('#'+type+" .fileuploadstatus").attr('id');
        if (id) {
            unsubscribe(cometsubscriptions["/fileuploader/"+id]);
        }
        $('#'+type).html('').children().remove();

        $('#'+type).append("<iframe src='fileuploader.jsp?type="+type+"'></iframe>");

        $('#files').tabs("option","disabled", [1,2]);
        $('#files').tabs("option","enabled", [0]);
        $('#files').tabs("select", 0);
    },
    init: function(ticket_id) {
        subscribe("/fileuploader/"+ticket_id, fileupload.progress);
    },
    send: function(ticket_id, type) {
        $('#files #'+type).append("<div id='"+ticket_id+"' class='fileuploadstatus'></div>");
        $('#files #'+type+ ' iframe').hide();
        
    }
};