
// Django CSRF protection now requires the CSRF token to be passed with 
// every POST request. Boilerplate to get jQuery to do this automatically.
// See: http://docs.djangoproject.com/en/dev/ref/contrib/csrf/

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
            // Only send the token to relative URLs i.e. locally.
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    }
});


// Resource object handles stock markup and JS initialisation for the
// 3 types of media associated with sessions (image, video & audio).

function Resource() {
    this.container = $('#resources div');

    this.set = function (url, type) {
        this.container.html(this.html(url, type));
    };

    this.html = function (url, type) {
        switch (type) {
            case 'Image': var html = this.getImageHtml(url); break;
            case 'Video': var html = this.getVideoHtml(url); break;
            case 'Audio': var html = this.getAudioHtml(url); break;
        }
        return html;
    };

    this.getImageHtml = function (url) {
        var fullSizeUrl = url.replace(/\d+x\d+\./, '');
        var node = $('\
            <div class="image-resource" style="background:#fff url(' + url + ') 50% 50% no-repeat;">\
                <a href="' + fullSizeUrl + '" title="View full-size in a new window."><img src="/static/images/_.gif" alt="" /></a>\
            </div>\
        ');
        node.find('a').click(function(e){
            window.open(this.href);
            return false;
        });
        return node;
    };

    this.getVideoHtml = function (url) {
        var id = 'video-player-' + (new Date()).getTime();
        var swf = '/static/js/lib/flowplayer-3.2.2/flowplayer-3.2.2.swf'; 
        var html = '\
            <div class="video-resource"><a id="' + id + '" href="' + url + '"></a></div>\
            <script type="text/javascript">\
                flowplayer("' + id + '", "' + swf + '", { clip:{ scaling:"fit" } });\
            </script>\
        ';
        return html;
    };

    this.getAudioHtml = function (url) {
        var id = 'audio-player-' + (new Date()).getTime();
        var html = '\
            <div class="audio-resource"><span id="' + id + '">You must have the Adobe Flash Player installed in order to see this content.</span></div>\
            <script type="text/javascript">\
                AudioPlayer.embed("' + id + '", { soundFile:"' + url + '" });\
            </script>\
        ';
        return html;
    };
}

function initAudioPlayer() {
    // Generic setup for AudioPlayer used with resources.
    if (typeof AudioPlayer != 'undefined') {
        AudioPlayer.setup('/static/js/lib/audio-player/player.swf', {
            width: 346,
            transparentpagebg: "yes",
            autostart: "yes",
            lefticon: "000",
            righticon: "000",
            volslider: "000"
        });
    }
}

function initResourceLinks() {
    // Resource links on the admin area's session transcripts page and thumbnails
    // on the session lobby page open resources in a pop-up widget when clicked.

    // Re-use the same dialog rather than opening a new one each time.
    var dialog = $('<div></div>');

    // Is the jQuery UI widget available?
    if (dialog.dialog) {
        dialog.dialog({ width:406, resizable:false, autoOpen:false });

        $('.resource-link').click(function(){

            // Add the resource HTML after the dialog is displayed, 
            // otherwise FlowPlayer doesn't initialise properly.
            var href = $(this).attr('href');
            var type = $(this).attr('data-resource-type');
            var rsrc = new Resource();
            
            dialog.html('<div class="resource-container"></div>');
            dialog.find('.resource-container').append(rsrc.html(href, type));
            dialog.dialog('option', 'title', type + ' Resource');
            dialog.dialog('open');

            return false;
        });
    }
}

function initPlaceholderText() {
    if ($.fn.placeholder) {
        $('#id_comment').placeholder({ values:["Type your comment here..."] });
        $('.chat-input input').placeholder({ values:["Type your message here..."] });
    }
}

$(function(){
    initAudioPlayer();
    initResourceLinks();
    initPlaceholderText();
});



