/*
 * Copyright (C) 2012 KTH, Royal Institute of Technology (http://www.kth.se/)
 * 
 * This file is part of tinywhiteboard.
 * 
 * Tiny Whiteboard is free software: you can redistribute it and/or modify
 * it under the terms of a MIT style license which is included in 
 * the software.
 */

tinyMCEPopup.requireLangPack();


/* 
 * JavaScript object driving the whiteboard dialog.
 */
var TinyWhiteboardDialog = {
    url : null,
    span : null,
    drawing : false,
    context : null,
    history : [],
    scale : {
        x : 1,
        y : 1
    },


    /*
     * Start of stroke. Adds the current image to the undo history
     * and begins drawing.
     */
    drawStart : function(ev) {
        var tw = TinyWhiteboardDialog;
    
        tw.scale.x = ev.currentTarget.width / ev.currentTarget.offsetWidth;
        tw.scale.y = ev.currentTarget.height / ev.currentTarget.offsetHeight;

        tw.drawing = true;
        tw.history.push(tw.context.getImageData(0, 0, ev.currentTarget.offsetWidth, ev.currentTarget.offsetHeight));

        tw.context.beginPath();
        tw.context.moveTo(
            tw.scale.x * (ev.pageX - $(ev.currentTarget).offset().left),
            tw.scale.y * (ev.pageY - $(ev.currentTarget).offset().top) 
        );

        $("#undo").removeClass("disabled");
    },


    /*
     * Currently in stroke.
     */
    draw : function(ev) {
        var tw = TinyWhiteboardDialog;
        
        if (tw.drawing) {
            ev.preventDefault();   
            tw.context.lineTo(
                tw.scale.x * (ev.pageX - $(ev.currentTarget).offset().left),
                tw.scale.y * (ev.pageY - $(ev.currentTarget).offset().top)
            );
            tw.context.stroke();
        }
    },


    /*
     * Finish up the current stroke.
     */
    drawEnd : function(ev) {
        var tw = TinyWhiteboardDialog;

        if (tw.drawing) {
            tw.context.closePath();
            tw.drawing = false;
        }
    },


    /*
     * Restore data from the undo history and maintain button state.
     */
    undo : function() {
        var tw = TinyWhiteboardDialog;
        if (tw.history.length) {
            tw.context.putImageData(tw.history.pop(), 0, 0);
            tw.context.save();
        }
        if (! tw.history.length) {
            $("#undo").addClass("disabled");
        }
    },


    /*
     * Set up the window and populate data from selection in editor if any.
     */
    init : function() {
        var tw = this,
            ed = tinyMCEPopup.editor,
            canvas = $("#canvas"),
            selected;
    
        $("#undo")
            .click(tw.undo)
            .addClass("disabled");
            
        canvas
            .bind('mousedown touchstart', tw.drawStart)
            .bind('mousemove touchmove', tw.draw)
            .bind('mouseup mouseleave touchleave touchend', tw.drawEnd);
            
        /* Chrome cursor workaround */
        $(document).bind('selectstart', function(ev) {
            ev.preventDefault();
        });
        
        tw.context = canvas[0].getContext('2d');
        tw.context.lineCap = "round";

        tw.selectColor("black");
        $("#pens div").click(function() {
            tw.selectColor(this.id);
        });

        tw.url = tinyMCEPopup.getWindowArg('whiteboard_url');
        tw.span = tinyMCEPopup.getWindowArg('marker');

        selected = ed.dom.get(tw.span);
        if (selected && selected.hasChildNodes()) {
            tw.context.drawImage(ed.dom.get(tw.span).firstChild, 0, 0);
        }      
    },
    


    selectColor : function(color) {
        var tw = this,
            pen = $("#" + color);
        
        tw.context.strokeStyle = color;
        if (color == "white") {
            tw.context.lineWidth = 8;
        } else {
            tw.context.lineWidth = 1;
        }
        $("#pens div").removeClass("selected");
        pen.addClass("selected");
        $("#canvas")
            .css("cursor", "url(img/" + color + "-cursor.png), crosshair")
            .css("cursor:focus", "url(img/" + color + "-cursor.png), crosshair")
            .css("cursor:active", "url(img/" + color + "-cursor.png), crosshair");
    },


    /*
     * Send synchronous call to whiteboard backend service for image,
     * will update the editor if successful, indicate error states
     * otherwise.
     */
    callWhiteboard : function(img) {
        var tw = this;

        $("#inProgress").show();

        $.ajax({
                url: tw.url,
                type: 'POST',
                dataType: 'json',
                data: JSON.stringify({
                    id: $(img).attr('id'),
                    src: $(img).attr('src'),
                    width: $(img).attr('width'),
                    height: $(img).attr('height'),
                    data: $("#canvas")[0].toDataURL("image/png", 1)
                })
            })
            .done(function(d, s, xhr) {
                $("#inProgress").hide();
        		$(img)
        		  .attr('id', d.id)
        		  .attr('src', d.src)
        		  .attr('width', d.width)
        		  .attr('height', d.height)
                tw.updateEditor(img);
            })
            .fail(function(d, s, xhr) {
                alert("failed store image, please try again.");
            })
            .always(function() {
                $("#inProgress").hide();
            });
    },


    /*
     * Attempt to store the image as a data URI directly in document. 
     */
    noWhiteboardFallback : function(img) {
        var tw = this;
        
        $(img).attr('src', $("canvas")[0].toDataURL("image/png"), 0.1);
        tw.updateEditor(img);
    },


    /*
     * Update the editor and close popup.
     */
    updateEditor : function(img) {
        var tw = this,
            ed = tinyMCEPopup.editor;

        ed.dom.setHTML(ed.dom.get(tw.span), img.outerHTML);
        ed.execCommand('mceRepaint', false);
        tinyMCEPopup.close();
    },
    
    
    /*
     * Indicates whether there is ongoing fetch activity in UI or not.
     */
    inProgress : function(inProgress) {
        $("#inProgress").toggle(inProgress);
    },


    /*
     * Callback for the insert button in dialog. 
     */
    insert : function() {
        var tw = this,
            ed = tinyMCEPopup.editor,
            canvas = $("canvas"),
            img = ed.dom.create('img', {
                'alt' : 'Whiteboard image',
                'class' : 'whiteboard',
                'width' : canvas.width(),
                'height' : canvas.height()
            });

        if (tw.url != null) {
            tw.callWhiteboard(img);
        } else {
            tw.noWhiteboardFallback(img);
        }
    }
};


tinyMCEPopup.onInit.add(TinyWhiteboardDialog.init, TinyWhiteboardDialog);

@@ -2936,16 +2936,19 @@
 %0A       
+ //
  $(docum
@@ -2990,32 +2990,35 @@
 v) %7B%0A           
+ //
  ev.preventDefau
@@ -3026,24 +3026,27 @@
 t();%0A       
+ //
  %7D);%0A       

Remove chrome work around for a moment.