/*

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="logo" name="logo" type="text" class="imadjselect size:team" />


Required JS:
    jquery.min.js (1.2.6)
    thickbox.js

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


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

if (!IMADJ_ROOT)
    var IMADJ_ROOT = '/media/imadj/data';
if (!save_url)
    var save_url = '/api/jeditable_save/';
if (!imadj_gallery_url)
    var imadj_gallery_url = '/imagegallery';
if (!imadj_rsrc)
    var imadj_rsrc = '/media/imadj/rsrc';

jQuery(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");
    });
});


// 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";
    if (type == "jeditable")
        pickerFieldName = "image_picker_field_inline";


    // 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 = "";

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

    var $fieldOptionsContainer = $("#"+escFieldId+"_field_container");
    var $fieldPicker = $("#"+fieldId+"_picker");
    if ($fieldOptionsContainer.length != 1) {
        /*$("#"+escFieldId+"_field_container").remove();*/
        $fieldOptionsContainer = $('<div>')
            .attr("class", "image_picker_field_container")
            .attr("id", fieldId+"_field_container");
        $(field).after($fieldOptionsContainer);
        $fieldPicker = $('<div>')
            .attr("class", pickerFieldName)
            .attr("id", fieldId+"_picker")
            .click(function() {
                loadPicker(fieldId, type);
            })
            .appendTo($fieldOptionsContainer);
    } else {
        $fieldOptionsContainer.find(".optional_buttons").remove();
        $fieldOptionsContainer.find(".image_picker_clear").remove();
    }

    var fieldUri = "";
    var fieldRlimg = "";
    if (type == "input" && field.val() != "") {
        fieldUri = IMADJ_ROOT + "/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(imadj_gallery_url + "/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, imadj_gallery_url + "/image/"+fieldRlimg+"/?height=400&width=600", null);
            })
            .html('<div class="alter_button"><img src="' + imadj_rsrc + '/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="' + imadj_rsrc + '/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="' + imadj_rsrc + '/img/_bg/icon_deletelink.gif"/><p>Delete</p></div>')
                .css("cursor", "pointer")
                .appendTo($fieldOptions);
        }
    }
    // Create blank image widget box
    else {
        var html = '<img src="' + imadj_rsrc + '/img/_bg/icon_addlink.gif" style="margin-top: 60px" />';
        html += '<br />Add image<div style="color: #666; font-size: 85%">';
        html += 'size: '+ $imgSize;
        if (imgSizeNames) {
            id = -1;
            for (var i=0; i<imgSizeNames.length; i++) {
                if (imgSizeNames[i] == $imgSize) {
                    id = i;
                }
            }
            if (id >= 0) {
                html += "<br/>("+imgSizeDimensions[id]+")";
            }
        }
        html += '</div>';

        $("#"+escFieldId+"_picker")
            .html(html);
    }
    $('<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(save_url, { 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="' + imadj_rsrc + '/img/spindicator.gif" />')
        .ajaxStart(function(){ $(this).show(); })
        .ajaxStop(function(){ $(this).hide(); })
        .appendTo($("#TB_ajaxContent"));
        
    loadImages(fieldId, type);

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


showImages = function(i, data, type, fieldId) {
    $('<div>')
        .attr("class","image_picker_item")
        .attr("title",data.fields.description+"   "+data.fields.source+"   "+data.fields.date_modified)
        .html('<img src="' + IMADJ_ROOT + '/thumbs/'+data.pk+'.jpg" /><br />'+data.fields.description)
        .click(function() {
            var field = $("#"+escFieldId);
            if (type == "jeditable") {
                field.attr("src", IMADJ_ROOT + '/thumbs/' + data.pk + '.jpg');

                // POST RLIMG_ID back to API to save data change
                $.post(save_url, { id: fieldId, value: data.pk } );
            } else if (type == "js") {
                pick_image(data.pk);
            } else if (typeof type == "function") {
                type(data.pk);
            } else {
                field.val(data.pk);
            }
            updateWidget(fieldId, type, data.pk);
            tb_remove();
        })
        .appendTo($("#image_picker_results"));
}


// 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 = imadj_gallery_url + "/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){
            var imagesExist = false;
            $.each(data, function(i, data){
                imagesExist = true;
                showImages(i, data, type, fieldId);
            });
            if (!imagesExist) {
                // Try searching by id
                var url = imadj_gallery_url + "/api/image/?__limit=20";
                if ($imgSize != "")
                    url += "&size="+$imgSize;
                if ($imgTag != "")
                    url += "&tags="+$imgTag;
                if ($description != "")
                    url += "&id__icontains="+$description;

                $.getJSON(url,
                    function(data){
                        $.each(data, function(i, data){
                            imagesExist = true;
                            showImages(i, data, type, fieldId);
                        });

                        if (!imagesExist) {
                            // try searching by tag
                            var url = imadj_gallery_url + "/api/image/?__limit=20";
                            if ($imgSize != "")
                                url += "&size="+$imgSize;
                            if ($imgTag != "") {
                                url += "&tags="+$imgTag;
                                if ($description != "")
                                    url += ","+$description;
                            }
                            else if ($description != ""){
                                url += "&tags="+$description;
                            }

                            $.getJSON(url,
                                function(data){
                                    $.each(data, function(i, data){
                                        imagesExist = true;
                                        showImages(i, data, type, fieldId);
                                    });

                                    if (!imagesExist) {
                                        var html = "<p>There are no images that match the required filters.<p>";
                                        if ($imgSize)
                                            html += "There must be a corresponding image in the gallery that matches the size for '" +$imgSize+ "'";
                                        if ($imgSize && $imgTag)
                                            html += " and be tagged with '" +$imgTag+ "'.";
                                        else
                                            html += ".";
                                        $('<div>')
                                            .html(html)
                                            .css("padding", "50px")
                                            .css("text-align", "center")
                                            .css("font-weight", "bold")
                                            .appendTo($("#image_picker_results"));
                                    }
                                }
                            );
                        }
                    }
                );
            }
        }
    );
};

