
(function($) {

$.fn.annotateImage = function(options) {
        
        var opts = $.extend({}, $.fn.annotateImage.defaults, options);
        var image = this;

        this.image = this;
        this.mode = 'view';

        // Assign defaults        
        this.getPageData = opts.getPageData == undefined ? false : true;   // DJ        

        this.getUrl = opts.getUrl;
        this.saveUrl = opts.saveUrl;
        this.deleteUrl = opts.deleteUrl;
        this.editable = opts.editable;
        this.useAjax = opts.useAjax;

        this.notes = opts.notes;

        /// Remove/clear previous the view item  (i.e., from the previous banner) :
        $(".image-annotate-canvas").remove();

        // Add the canvas          
        this.canvas = $('<div id="div_canvas" class="image-annotate-canvas" style="cursor:default" ><div id="an_view" class="image-annotate-view"></div><div id="an_edit" class="image-annotate-edit"><div id="an_editarea" class="image-annotate-edit-area" style="position:absolute"></div></div></div>');
        this.canvas.children('.image-annotate-edit').hide();
        this.canvas.children('.image-annotate-view').hide();
        this.image.after(this.canvas);

        // Give the canvas and the container their size and background
        this.canvas.height(this.height());
        this.canvas.width(this.width());
        this.canvas.css('background-image', 'url("' + this.attr('src') + '")');

        this.canvas.children('.image-annotate-view, .image-annotate-edit').height(this.height());
        this.canvas.children('.image-annotate-view, .image-annotate-edit').width(this.width());

        // Add the behavior: hide/show the notes when hovering the picture
        this.canvas.hover(function() {
            if ($(this).children('.image-annotate-edit').css('display') == 'none') {
                 $(this).children('.image-annotate-view').show();  
                 $('.image-annotate-product').css('display', 'none');

            }
        }, function() {
            $(this).children('.image-annotate-view').hide(); // (DJ) hide(); //the part to remove annotation when the mouse is out of the picture
        });

        this.canvas.children('.image-annotate-view').hover(function() {
            $(this).show();
        }, function() {
            $(this).hide();
        });

        // load the notes
        if (this.useAjax) {
            $.fn.annotateImage.ajaxLoad(this);
        } else {
            $.fn.annotateImage.load(this);
        }

        // Hide the original
        this.hide();

        return this;
    };

    /**
    * Plugin Defaults
    **/
    $.fn.annotateImage.defaults = {
        getUrl: 'your-get.rails',
        saveUrl: 'your-save.rails',
        deleteUrl: 'your-delete.rails',
        editable: true,
        useAjax: true,
        notes: new Array()
    };

    $.fn.annotateImage.clear = function(image) {
        ///	<summary>
        ///		Clears all existing annotations from the image.
        ///	</summary>    
        for (var i = 0; i < image.notes.length; i++) {
            image.notes[image.notes[i]].destroy();
        }
        image.notes = new Array();
    };

    $.fn.annotateImage.ajaxLoad = function(image) {
        ///	<summary>
        ///		Loads the annotations from the "getUrl" property passed in on the
        ///     options object.
        ///	</summary>


        if (image.getPageData) {

            image.notes = eval($("[id$=hfPhotoNoteData]").val());
            // image.notes = $("[id$=lblPhotoNoteData]").html();

            if (image.notes == undefined) {
                return;
            }

            $.fn.annotateImage.load(image);
        }
        else {
            $.getJSON(image.getUrl + '?ticks=' + $.fn.annotateImage.getTicks(), function(data) {
                image.notes = data;
                $.fn.annotateImage.load(image);

            });
        }
    };


    $.fn.annotateImage.load = function(image) {
        ///	<summary>
        ///		Loads the annotations from the notes property passed in on the
        ///     options object.
        ///	</summary>

        if (image.notes != undefined) {

            for (var i = 0; i < image.notes.length; i++) {
                image.notes[image.notes[i]] = new $.fn.annotateView(image, image.notes[i]);
            }
        }

    };


    $.fn.annotateImage.getTicks = function() {
        ///	<summary>
        ///		Gets a count og the ticks for the current date.
        ///     This is used to ensure that URLs are always unique and not cached by the browser.
        ///	</summary>        
        var now = new Date();
        return now.getTime();
    };




    function PageMethod(fn, paramArray, successFn, errorFn) {
        var pagePath = window.location.pathname;
        //Create list of parameters in the form:   
        //{"paramName1":"paramValue1","paramName2":"paramValue2"}   
        var paramList = '';
        if (paramArray.length > 0) {
            for (var i = 0; i < paramArray.length; i += 2) {
                if (paramList.length > 0) paramList += ',';
                paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
            }
        }
        paramList = '{' + paramList + '}';
        //Call the page method   
        $.ajax({
            type: "POST",
            url: pagePath + "/" + fn,
            contentType: "application/json; charset=utf-8",
            data: paramList,
            dataType: "json",
            success: successFn,
            error: errorFn
        });
    }

    function AjaxSucceeded(result) {
        //    $('#suggestions').fadeIn(); // Show the suggestions box
        //    $('#suggestions').html(result.d); // Fill the suggestions box        
    }

    function AjaxSucceededToDBUpdate(result) {

        //$("[id$=lblPhotoNoteData]").html(result.d);
        $("[id$=hfPhotoNoteData]").val(result.d);
        form1.submit();
    }

    function AjaxFailed(result) {
        alert("An error occured saving that note.")
        alert(result.d);
    }
        
    // DJ annotate view 
    $.fn.annotateView = function(image, note) {
        ///	<summary>
        ///		Defines a annotation area.
        ///	</summary>
        this.image = image;

        this.note = note;

        if (note != undefined) {
            this.editable = (note.editable && image.editable);
        }
        else {
            this.editable = (image.editable);
        }

        // Add the area  : Square
        this.area = $('<div class="image-annotate-area' + (this.editable ? ' image-annotate-area-editable' : '') + '"><div></div></div>');
        image.canvas.children('.image-annotate-view').prepend(this.area);
      
        if (note != undefined) {
            this.form = $('<div id="note_area" class="image-annotate-product" >' + note.text + '</div>');

            if (note.noteTextWidth != undefined) {
                this.form.css('width', (note.noteTextWidth) + 'px');
            }
        }
        else {
            this.form = $('<div id="note_area" class="image-annotate-product" ></div>');
            this.form.css('width', '30px');
        }
        

        this.form.hide();
        image.canvas.children('.image-annotate-view').append(this.form);
        this.form.children('span.actions').hide();

        // Set the position and size of the note
        this.setPosition();

        // Add the behavior: hide/display the note when hovering the area
        var annotation = this;

        // -------------
        // Square Area 
        // -------------
        this.area.hover(function() {        
            annotation.show();   // ==> single annotation       
        }, function() {
            annotation.hide(); // changed from hide() to show() by (DJ) : to allow user to click the hyperlink in the note
        });

        // Edit a note feature
        if (this.editable) {
            var form = this;
            this.area.click(function() {
                form.edit();
            });
        }
    };


    // ------------------------------------
    // Set the Location of the Note
    // ------------------------------------    
    $.fn.annotateView.prototype.setPosition = function() {        
        ///		Sets the position of an annotation.        
        this.area.children('div').height((parseInt(this.note.height) - 2) + 'px');
        this.area.children('div').width((parseInt(this.note.width) - 2) + 'px');

        this.area.css('left', (this.note.left) + 'px');

        this.area.css('top', (this.note.top) + 'px');
        this.form.css('left', (this.note.left) + 'px');    

        this.form.css('top', (parseInt(this.note.top) + parseInt(this.note.height) + 7) + 'px');
    };


    // SHOW
    $.fn.annotateView.prototype.show = function() {
        ///	<summary>
        ///		Highlights the annotation
        ///	</summary>
        this.form.fadeIn(150);

        // alert('show');
        if (!this.editable) {
            this.area.addClass('image-annotate-area-hover');
        } else {
            this.area.addClass('image-annotate-area-editable-hover');
        }

    };

    // HIDE 
    $.fn.annotateView.prototype.hide = function() {
        ///	<summary>
        ///		Removes the highlight from the annotation.
        ///	</summary>

        var removeForm = this.form;
     
        var tid = setTimeout(function() { removeForm.fadeOut(10); }, 300); // give some time to move mouse over the text

        removeForm.hover(function() {
            clearTimeout(tid);
        }, function() {
            removeForm.fadeOut(400);  // when the mouse is out from the text (with url)            
        });

        this.area.removeClass('image-annotate-area-hover');
        this.area.removeClass('image-annotate-area-editable-hover');

    };

    $.fn.annotateView.prototype.destroy = function() {        
        ///		Destroys the annotation.        
        this.area.remove();
        this.form.remove();
    }    

})(jQuery);

