/*
  $('input.image_url_input').fileuploader();
  will add an image upload form before the input.

  The next sibling after the field needs to contain
  a.preview with an img tag for the preview link
  and a a.remove link.
*/
// FIXME: fileuploader has been marked as depreciated, its old, unsafe, and semantically incorrect in most cases
// TODO: fileuploader has been marked as depreciated, its old, unsafe, and semantically incorrect in most cases
//
// Use instead ajax.uploader
//
(function($){
 $.fn.fileuploader = function(options) {
    var options = $.extend({
    }, options);
    if (!options.url) {
        options.url = '/fileupload/' + options.field_name + '/';
    }

    var get_complete_func = function(field) {
        return function (response) {
            if(typeof(auth) != "undefined") {
                $('#auth-form').submit(auth.submitForm);
            }
            /* iframe response will be wrapped in <pre> tags */
            response = response.replace(/^<[^>]*>/, '').replace(/<[^>]*>$/, '');
            try {
                var retdic = eval("("+response+")");
            } catch (e) {
                alert("err:"+e+" "+response+retdic);
                return false;
            }
            if (retdic.error) {
                alert(retdic.error);
                return;
            };


            var fileurls = retdic.fileurls;
            var img_url = fileurls.original;
            for(key in fileurls) {
                if(key != 'original') {
                    img_url = fileurls[key];
                }
            }

            field.val(img_url).change();
        }
    }

    var q = $(this);

    q.each(function() {

        var f = $(this);
        var remove_link = f.next().find('a.remove').hide();
        if (!remove_link.length && typeof(options.remove_link) != 'undefined') {
            remove_link = options.remove_link
        }
        var preview_link = f.next().find('a.preview').hide();
        if (!preview_link.length && typeof(options.preview_link) != 'undefined') preview_link = options.preview_link
        var preview_img = preview_link.find('img');
        if (!preview_img.length && typeof(options.preview_img) != 'undefined') preview_img = options.preview_img

        var changer = function(field, remove_link, preview_link) {
            return function () {
                var url = f.val();
                if (url) {
                    var preview_img = preview_link.find('img');
                    if (!preview_img.length) {
                        preview_img = $('<img>').appendTo(preview_link);
                    }
                    preview_img.attr('src', url);
                    preview_link.attr('href', url).attr('target', '_blank').show();
                    remove_link.show();
                } else {
                    preview_link.attr('href', '#').hide();
                    preview_link.find('img').remove();
                    remove_link.hide();
                }
                return false;
        }}(f, remove_link, preview_link);

        f.change(changer);
        changer();

        remove_link.click(function (field) {
            return function() {
                field.val('').change();
                return false;
            }}(f));

        var form = $('<form method="post" enctype="multipart/form-data"><input type="hidden" name="width" value="'+options.width+'"/><input type="hidden" name="height" value="'+options.height+'"/><input type="hidden" name="mwidth" value="'+options.mwidth+'"/><input type="hidden" name="mheight" value="'+options.mheight+'"/><input type="file" class="image" name="image"/><input type="button" value="Add image" class="button" style="display:none"><input type="hidden" name="file_type" value="image"/></form>');

        form.attr({'action':options.url}).insertBefore(f).submit( function() {
            if(typeof(auth)!="undefined") {
                $('#auth-form').unbind('submit');
            }
            return AIM.submit(this, {
                'onComplete' : get_complete_func(f)
            });
         }).find('input[type=file]').change(function(){
            // lets hack, this is due to fact that form in ad_placement.js is redirected if certain classes
            // are found on the page, html for that form is generated by views and injected via ajax
            // success callback, generally speaking ad_placement.js, lines 370 down
            if ($('.ajax_reload_post').size() || $('.ajax_reload_get').size()) {
                $('.ajax_reload_get').each(function () {
                    $(this).attr('class', 'ajax_reload_noajaxzkh');
                });
                $('.ajax_reload_post').each(function () {
                    $(this).attr('class', 'ajax_reload_noajaxzkh');
                });
            }
            form.submit();
            $(this).val('');
        });
    });

    return q;
 };
})(jQuery);

