<script>
    {% comment %} this was taken directly from https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/
    // except for the last couple lines.  You should edit the ajax request to fit your needs
    {% endcomment %}

    $(window).load(function(){
        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;
        }
        var csrftoken = getCookie('csrftoken');

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        function sameOrigin(url) {
            // test that a given url is a same-origin URL
            // url could be relative or scheme relative or absolute
            var host = document.location.host; // host + port
            var protocol = document.location.protocol;
            var sr_origin = '//' + host;
            var origin = protocol + sr_origin;
            // Allow absolute or scheme relative URLs to same origin
            return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                    (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                        // or any other URL that isn't scheme relative or absolute i.e relative.
                    !(/^(\/\/|http:|https:).*/.test(url));
        }
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                    // Send the token to same-origin, relative URLs only.
                    // Send the token only if the method warrants CSRF protection
                    // Using the CSRFToken value acquired earlier
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });


        /*****************************************************************************/
        /*****************************************************************************/

        function strip_path(path){
            {# returns upload directory and filename of an image's URL #}

            {# the following regex matches everything after MEDIA_URL for any allowed encodings #}
            {# for example, default settings would yield: r'media\/(.*\.(jpg|jpeg|png))' #}
            pattern = "{{ MEDIA_URL|slugify }}\/(.*\.({{ encodings }}))";


            results = path.match(pattern);
            if (results != null && results.length > 0)
                return results[1];
            else
                return "";

            //return path;

        }
        function new_width(element){
            return parseInt(element.width() * window.screen.width/$(window).width());
        }

        {% autoescape off %}
            $.fn.extend({
                findImages: function(){
                    {% comment %}
                    I'm sure there's a better way to do this, but I'll get around to doing that later.

                    We're going to create a string that will be converted to a python list of tuples on the server-side.
                    It will look like this:
                    [
                        (<upload-folder>/<filename>, <new image size>),
                    ]
                    {% endcomment %}

                    var images = "[";
                    this.find("{{ SELECTORS }}").each(function(){
                        var image = strip_path($(this)[0].src);
                        images += "('" + image + "'," + new_width($(this)) + "), ";
                    });
                    images += "]";
                    return images;
                },  // findImages
                findBackgrounds: function(){
                    {# similar to above but for background-image definitions #}
                    var backgrounds = "[";
                    this.find('{{media_helper.BACKGROUND_SELECTORS}}').each(function(){
                        if ($(this).css('background-image') != "none"){
                            var background = strip_path($(this).css('background-image'));

                            if (background != window.location.pathname) {
                                backgrounds += "('" + background + "'," + new_width($(this)) + "), ";
                            }
                        }

                    });
                    backgrounds += "]";
                    return backgrounds;
                },  // findBackgrounds
                swapImage: function(new_path){
                    {# a simple plugin to pre-load an image before replacing it #}
                    {# It can be used on any img at any time.   #}
                    var self = this;
                    var dummy_image = new Image();
                    dummy_image.onload = function(){
                        self.attr('src', this.src);
                    };
                    dummy_image.src = new_path;
                    return this;
                },  //swapImage
                swapBackground: function(new_path){
                    {# same as above, but for background images #}
                    var self = this;
                    var dummy_image = new Image();
                    dummy_image.onload = function(){
                        self.css('background-image', 'url("' + this.src+ '")');
                    };
                    dummy_image.src = new_path;
                },  // swapBackground
                replaceAll: function(){
                    head = this;
                    $.ajax({
                        type: "POST",
                        url: '{% url "media_helper" %}',
                        data: {
                            'width' :window.screen.width,
                            'height': window.screen.height,
                            'images': this.findImages(),//images,
                            'backgrounds': this.findBackgrounds()
                        },  // data {}
                        success: function(data){

                            head.find("{{SELECTORS}}").each(function(){
                                {# for each image, search the returned dict for a new request path #}
                                {% comment %}
                                    Just a reminder what is sent to the server and what is returned
                                    sent:
                                    [
                                        (<upload_to>/<filename.ext>, <new size>),
                                    ]

                                    returned:
                                    {
                                        'MEDIA_URL/<upload_to>/filename.ext': 'MEDIA_URL/<upload_to>/<size>/filename.ext'
                                    }
                                {% endcomment %}
                                var new_path = $(this)[0].src;
                                if (new_path != undefined){
                                    new_path = data['images']["{{MEDIA_URL}}" + strip_path($(this)[0].src)];
                                    if(new_path != undefined)
                                        $(this).swapImage(new_path);
                                }

                            }); // SELECTORS loop

                            head.find('{{media_helper.BACKGROUND_SELECTORS}}').each(function(){
                                var full_path = window.location.href;
                                var url = $(this).css('background-image');

                                {# in case background names are empty #}
                                if (url != undefined && url != 'none' && strip_path(url) != ""){
                                    var new_path = data['backgrounds']["{{MEDIA_URL}}" + strip_path(url)];

                                    if(new_path != undefined)
                                        $(this).swapBackground(new_path);
                                }
                            });  // BACKGROUND_SELECTORS loop
                        }, // success
                    });  // ajax
                }  // replaceAll
            });  // extend


            $('body').replaceAll();

        {% endautoescape %}
    });

</script>

