/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
This is an old copy of imagepicker.js. relextra/django/apps/imadj/rsrc/js/imagepicker.js should be use now.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Image Picker JavaScript Widget

This script can transform a form input or simple image into a more user-friendly
thumbnail picker. Text input fields and images will be transformed if their HTML
class contains the keyword 'imadjselect', e.g.:

    <input id="restaurant:5:photo_id" name="logo" type="text" class="imadjselect size:featureLandscape" />
        or
    <img id="restaurant:5:photo_id" class="imadjselect size:featureLandscape tag:ETHKG" src="/media/imadj/data/thumbs/RLIMG_6b99707edc834471446640df5b94b1c8.JPEG.jpg" />


Required JS:
    jquery-1.2.6.min.js
    thickbox.js

Required CSS:
    imagepicker.css
    thickbox.css
    stylesheet.css
    fancy.css
*/


var $imgSize = "";
var $imgTag = "";
var $description = "";

$(document).ready(function() {
    // Convert every input text element with the imadjselect class into special image picker widget
    $("input:text.imadjselect").each(function() {
        updateWidget($(this).attr("id"),"input");
    });

    // Convert every inline jeditable image element with the imadjselect class into special image picker widget
    $("img.imadjselect").each(function() {
        updateWidget($(this).attr("id"),"jeditable");
    });

    alert("This is an old copy of imagepicker.js. rldjango/apps/imadj/rsrc/js/imagepicker.js should be use now.")
});


// Display the picker widget in place of imadjselect input or img. Items this
// widget will replace have 'imadjselect' in the HTML class name.
updateWidget = function(fieldId, type, selectedId) {
    // Our IDs contains ':' characters so need escaping
    // as the ':' means something special in CSS selectors
    var escFieldId = fieldId.replace(/:/g, '\\:')
    var field = $('#' + escFieldId);
    var fieldClass = " "+field.attr("class")+" ";
    var pickerFieldName = "image_picker_field";

    // Hide the orriginal input text field
    field.hide();

    $("#"+escFieldId+"_field_container").remove();
    var $fieldOptionsContainer = $('<div>')
        .attr("class", "image_picker_field_container")
        .attr("id", fieldId+"_field_container")
        .appendTo(field.parent());
    if (type == "jeditable")
        pickerFieldName = "image_picker_field_inline"
    var $fieldPicker = $('<div>')
        .attr("class", pickerFieldName)
        .attr("id", fieldId+"_picker")
        .click(function() {
            loadPicker(fieldId, type);
        })
        .appendTo($fieldOptionsContainer);


    var fieldUri = "";
    var fieldRlimg = "";
    if (type == "input" && field.val() != "") {
        fieldUri = "/media/imadj/data/thumbs/"+field.val()+".jpg";
        fieldRlimg = field.val();
    }
    else if (type == "jeditable" && field.attr("src") != "" && field.attr("src").search(/^.*\/(RLIMG_[0-9a-fA-F]{32}\.[^\.]+)/) >= 0) {
        fieldUri = field.attr("src");
        fieldRlimg = field.attr("src").match(/^.*\/(RLIMG_[0-9a-fA-F]{32}\.[^\.]+)/)[1];
    }

    if (fieldUri != "" && fieldRlimg != "") {
        $.getJSON("/imagegallery/api/image/"+fieldRlimg,
            function(data){
                $.each(data, function(i, data){
                    $("#"+escFieldId+"_picker")
                        .html('<img src="'+fieldUri+'" /><br />'+data.fields.description);
                });
            });
        var $fieldOptions = $('<div>')
            .attr("class", "optional_buttons")
            .appendTo($fieldOptionsContainer);
        var $fieldOptionInfo = $('<a>')
            .click(function() {
                tb_show(null, "/imagegallery/image/"+fieldRlimg+"/?height=400&width=600", null);
            })
            .html('<div class="alter_button"><img src="/media/img/_bg/icon_infolink.gif"/><p>Info</p></div>')
            .css("cursor", "pointer")
            .appendTo($fieldOptions);
        var $fieldOptionInfo = $('<a>')
            .click(function() {
                loadPicker(fieldId, type);
            })
            .html('<div class="alter_button"><img src="/media/img/_bg/icon_changelink.gif"/><p>Change</p></div>')
            .css("cursor", "pointer")
            .appendTo($fieldOptions);
        // If there is no string 'required' in the class, display an option to delete selection
        if (fieldClass.search(/^.*\s+required\s+/) < 0) {
            var $fieldOptionInfo = $('<a>')
                .click(function() {
                    clearWidget(fieldId, type);
                })
                .html('<div class="alter_button"><img src="/media/img/_bg/icon_deletelink.gif"/><p>Delete</p></div>')
                .css("cursor", "pointer")
                .appendTo($fieldOptions);
        }
    }
    // Create blank image widget box
    else {
        $("#"+escFieldId+"_picker")
            .html('<img src="/media/img/_bg/icon_addlink.gif" style="margin-top: 60px" /><br />Add image '+ type);
    }
    $('<div>').attr("class", "image_picker_clear").appendTo($fieldOptionsContainer);

}


// Removes the source ID from the original element and calls updateWidget().
clearWidget = function(fieldId, type) {
    var escFieldId = fieldId.replace(/:/g, '\\:')
    $("#"+escFieldId).val("");
    if (type == "jeditable") {
        var oldSrc = $("#"+escFieldId).attr("src");
        $("#"+escFieldId).attr("oldsrc", oldSrc);
        $("#"+escFieldId).attr("src", "");
        // POST RLIMG_ID back to API to save data change
        $.post("/api/jeditable_save/", { id: fieldId, value: "" } );
   
    }
    updateWidget(fieldId, type);
}


// Creates the thickbox and modifies it to have header and search box etc.
// Calls the loadImages() function to display the appropriate thumbnails.
loadPicker = function(fieldId, type) {
    escFieldId = fieldId.replace(/:/g, '\\:')
    var field = $("#"+escFieldId);
    var fieldClass = " "+field.attr("class")+" ";
    // Use regular expressions to match size and tag attributes in the input field's class
    if (fieldClass.search(/^.*\s+size:([^\s]+)\s+/) >= 0)
        $imgSize = fieldClass.match(/^.*\s+size:([^\s]+)\s+/)[1];
    else
        $imgSize = "";
    if (fieldClass.search(/^.*\s+tag:([^\s]+)\s+/) >= 0)
        $imgTag = fieldClass.match(/^.*\s+tag:([^\s]+)\s+/)[1];
    else
        $imgTag = "";
    $description = "";
    // Launch Thickbox and the picker within it
    tb_show(null, "#TB_inline?height=500&width=810", null);

    // Setup the thickbox layout with header, search box and results section
    $("#TB_ajaxContent").css("width", "100%");
    $("#TB_ajaxContent").css("padding", "0");

    $("#TB_ajaxWindowTitle").html("<h4>Please select an image or use the search box to filter the results.</h4>");

    var $header = $('<div>')
        .attr("id", "image_picker_header")
        .html("<div id=\"image_picker_header_text\">SIZE: "+$imgSize+"<br />TAG: "+$imgTag+"</div>")
        .appendTo($("#TB_ajaxContent"));

    $('<div>')
        .attr("id", "image_picker_search")
        .html('<div id="image_picker_outer_search_box"><div id="image_picker_inner_search_box"><form method="get" action="" id="image_picker_form"><input type="text" name="search" id="image_picker_searchbox" value="" style="width:185px;border:none;"/></form></div></div>')
        .appendTo($header);

    // When search form is submitted load value into $description variable and reload images
    $("#image_picker_form").submit(function() {
        $description = $("input#image_picker_searchbox").val();
        loadImages(fieldId, type);
        return false;
    });

    // Create the spinner icon in the thickbox. This will display automatically whenever we wait for ajax results
    $('<div>')
        .attr("id", "image_picker_spindicator")
        .html('<img src="/media/img/spindicator.gif" />')
        .ajaxStart(function(){ $(this).show(); })
        .ajaxStop(function(){ $(this).hide(); })
        .ready(function() {loadImages(fieldId, type)})
        .appendTo($("#TB_ajaxContent"));

    $('<div>')
        .attr("id", "image_picker_results")
        .appendTo($("#TB_ajaxContent"));
};


// Called after the thickbox has been displayed. Calls API URI with relevant
// limit, size and tag query, which returns JSON of all images to display.
loadImages = function(fieldId, type) {
    // Clear results area
    escFieldId = fieldId.replace(/:/g, '\\:')
        
    $("#image_picker_results").html("");

    var url = "/imagegallery/api/image/?__limit=20";
    if ($imgSize != "")
        url += "&size="+$imgSize;
    if ($imgTag != "")
        url += "&tags="+$imgTag;
    if ($description != "")
        url += "&description__icontains="+$description;

    // Load in the JSON using Ajax API, create thumbnails for each one and the
    // associated click event action to update form content and close Thickbox.
    $.getJSON(url,
        function(data){
          $.each(data, function(i, data){
            $('<div>')
                .attr("class","image_picker_item")
                .attr("title",data.fields.description+"   "+data.fields.source+"   "+data.fields.date_modified)
                .html('<img src="/media/imadj/data/thumbs/'+data.pk+'.jpg" /><br />'+data.fields.description)
                .click(function() {
                    var field = $("#"+escFieldId);
                    if (type == "jeditable") {
                        var newSrc = field.attr("src", "/media/imadj/data/thumbs/"+data.pk+".jpg");

                        // POST RLIMG_ID back to API to save data change
                        $.post("/api/jeditable_save/", { id: fieldId, value: data.pk } );
                    }
                    else {
                        field.val(data.pk);
                    }
                    updateWidget(fieldId, type, data.pk);
                    tb_remove();
                })
                .appendTo($("#image_picker_results"));
            if ( i == 99 ) return false;
          });
        });
};

