﻿


(function($) {

    $.fn.vEdit = function(options) {



        if (this.length > 1) {
            alert("vEdit can only be applied to a single DOM element");
            return false;
        }

        //an element can only have one instance of a datasource
        return this.each(function() {
            var element = $(this);
            var lookfor = "vEdit-" + options.applyto;
            // Return early if this element already has a plugin instance
            if (element.data(lookfor)) {
                vLog('vEdit', 'already instantiated!' + lookfor);
                return;
            }
            // pass options to plugin constructor
            var vrs = new vEdit(this, options);
            // Store plugin object in this element's data
            element.data(lookfor, vrs);
            $(document).trigger('vnx-reg-vedit', vrs);

        });
    };

    var vEdit = function(element, options) {
        var dc = function(a) { return document.createElement(a); };

        var config = {
            applyto: 'vedit',
            applytoclass: 'vedit',
            editon: 'doubleclick',              //[doubleclick|click|display]
            infoid: 'info',
            textclasses: 'head,body,note',
            imageclasses: 'imgleft,imgright',
            imageroot: '',
            imagedirectories: '',
            imageajaxurl: '/vui/vedit-images.aspx/ShowFiles',
            editingclass: 'editing',
            textboxid: ''
        };

        $.extend(config, options);

        var beingedited = null;         //the container element being edited (with the applytoclass on)
        var currenttarget = null;       //the element as a target (could be an element within beingedited)
        var currenttagname = null;      //the tag of the element as a target P,IMG,B etc,.

        var $contextmenu = null;

        var $textmenu = null;
        var $imagemenu = null;

        var $dialogimage = null;

        var $element = this;
        var Us = this;


        this.applyto = function() {
            return config.applyto;
        }



        function updateimagelist() {
            //prepare the parameters

            var sdata = JSON.stringify({ "r": config.imageroot, "d": $dialogimage.find('#vedit-imgdialog-directories').val() });

            //make the ajax call
            $.vServerRequest({
                url: config.imageajaxurl,
                cache: false,
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function(json) {
                    $dialogimage.find('#vedit-imgdialog-filelisting').html("");
                    for (var i = 0; i < json.d.length; i++) {
                        $dialogimage.find('#vedit-imgdialog-filelisting').append("<a href='#' rel='" + json.d[i].Path + "'>" + json.d[i].Name + "</a>");
                    }
                },
                type: 'POST',
                data: sdata
            });

        }

        this.endediting = function($theElement) {
            $theElement.removeClass(config.editingclass);
            $theElement.attr('data-vedit-editing', 'false');
        }

        //add a div for editing
        this.beginediting = function($theElement) {

            //set up the element initially
            $theElement.attr('data-vedit-editing', 'true');
            $theElement.addClass(config.editingclass);          //show visually that we're editing

            //is there any content?
            var tc = $theElement.html();
            var tcp = $theElement.find("p");
            if (tcp.length == 0) {
                $theElement.prepend("<p></p>");
            }
            tcp = $theElement.find("p");
            $theElement.data('oldvalue', $theElement.html());     //store the old data
            $theElement[0].contentEditable = true;              //allow the div to be editable

            //bind a new click event to short cut bubbling up to the top

            /*
            $theElement.bind('click', function() {
            
            $(this).one('blur', function() {
            $(this).removeClass(config.editingclass);
            $(this).attr('data-vedit-editing', 'false');
            if ($(this).html() != $(this).data('oldversion')) {
            //what should we do with this now the focus has gone?
                        
            //if we have a textboxid then we can alter it's contents
            if (config.textboxid.length > 0) $('#' + config.textboxid).val($(this).html());
          
                        //this triggers a change event that will bubble up and be caught by the document
            $(this).trigger('vnx-change', [$(this).data('oldversion'), $(this).html()]);
            }
            });

            }); //bindclick*/

            //add context menu for this div, this is the main functionality
            $theElement.bind("contextmenu", function(e) {

                $('.vedit-cm-active').removeClass('vedit-cm-active').hide();           //hide any other menus on the page
                var evt = e;
                currenttarget = evt.target;
                currenttagname = currenttarget.tagName;
                $contextmenu = null;
                $('#' + config.infoid).html("context on " + currenttagname);
                switch (currenttagname) {
                    case 'IMG': $contextmenu = $imagemenu;
                        break;
                    default:
                        $contextmenu = $textmenu;
                        break;
                }
                if ($contextmenu == null) return false;  //no menu
                // Detect mouse position
                var d = {}, x, y;
                if (self.innerHeight) {
                    d.pageYOffset = self.pageYOffset;
                    d.pageXOffset = self.pageXOffset;
                    d.innerHeight = self.innerHeight;
                    d.innerWidth = self.innerWidth;
                } else if (document.documentElement && document.documentElement.clientHeight) {
                    d.pageYOffset = document.documentElement.scrollTop;
                    d.pageXOffset = document.documentElement.scrollLeft;
                    d.innerHeight = document.documentElement.clientHeight;
                    d.innerWidth = document.documentElement.clientWidth;
                } else if (document.body) {
                    d.pageYOffset = document.body.scrollTop;
                    d.pageXOffset = document.body.scrollLeft;
                    d.innerHeight = document.body.clientHeight;
                    d.innerWidth = document.body.clientWidth;
                }
                (e.pageX) ? x = e.pageX : x = e.clientX + d.scrollLeft;
                (e.pageY) ? y = e.pageY : x = e.clientY + d.scrollTop;

                $contextmenu.addClass('vedit-cm-active');
                $contextmenu.css({ top: y, left: x, position: 'absolute' }).show();     //show the menu
                return false;                                           //to disable normal context menu
            });

            $theElement.bind("paste", function(e) {
                var sourcestring = window.clipboardData.getData("Text");
                var stripped = sourcestring.replace(/(<([^>]+)>)/ig, "");
                window.clipboardData.setData("Text", stripped);
                alert("Pasting this: " + stripped.substr(0,200));
            });
            //why no update

        }


        //initialise the menus and dialogs on document ready, this happens once per instance of vEdit
        //however we can have more than one instance on a page


        $(document).ready(function() {


            $(document).bind("click", function() {
                //bind to the document so a click outside our element removes the active class
                vLog('vEdit', "Hiding context menu:" + Us.applyto());
                $('.vedit-cm-active').removeClass('vedit-cm-active').hide();
            });

            //create the context menus (if not already in the DOM)

            //so there is only one instance of the menus per config.applyto 
            var tmid = '#' + config.applyto + '-txtcm';
            if ($(tmid).length == 0) {
                $textmenu = $(dc('div'));
                $textmenu.addClass('vedit-cm');
                $textmenu.append('<i>Change Style</i>');
                $textmenu.append('<a href="#" class="vc-addclass changestyle" rel="">Remove Styles</a>');
                $(config.textclasses.split(",")).each(function() {
                    $textmenu.append('<a href="#" class="vc-addclass changestyle" rel="' + this + '">' + this + '</a>');
                });
                $textmenu.append('<i>Actions</i>');
                $textmenu.append('<a href="#" class="vc-addimage addimage">Add Image</a>');
                $textmenu.append('<a href="#" class="vc-viewhtml viewHTML">Toggle HTML</a>');
                $('body').append($textmenu);
            }
            else {
                $textmenu = $(tmid);
            }

            //create the image menu
            var imid = '#' + config.applyto + '-imgcm';
            if ($(imid).length == 0) {
                $imagemenu = $(dc('div'));
                $imagemenu.addClass('vedit-cm');
                $imagemenu.append('<i>Image Styles</i>');
                $(config.imageclasses.split(",")).each(function() {
                    $imagemenu.append('<a href="#" class="vc-addclass changestyle" rel="' + this + '">' + this + '</a>');
                });
                $imagemenu.append('<i>Image Options</i>');
                $imagemenu.append('<a href="#" class="vc-addimage addimage">Change Image</a>');
                $imagemenu.append('<a href="#" class="vc-delimage deleteimage">Remove Image</a>');
                $('body').append($imagemenu);
            }
            else {
                $imagemenu = $(imid);
            }

            //create the image dialog box
            $dialogimage = $('#vedit-imgdialog');
            if ($dialogimage.length == 0) {

                $dialogimage = $(dc('div')).addClass('vdialog vimagedialog');
                $leftcol = $(dc('div')).attr('id', 'left');
                $midcol = $(dc('div')).attr('id', 'mid');
                $rightcol = $(dc('div')).attr('id', 'right');
                $dialogimage.append('<h1>Choose an image</h1>');
                $midcol.append('<div id="vedit-imgdialog-filelisting"></div>');
                $leftcol.append('<label>image directory</label>');
                var smenu = '<select id="vedit-imgdialog-directories">';
                var dirs = config.imagedirectories.split(",");
                for (var i = 0; i < dirs.length; i++) {
                    smenu += "<option>" + dirs[i] + "</option>";
                }
                smenu += "</select>";

                $leftcol.append(smenu);
                $leftcol.append('<label>image filename</label>');
                $leftcol.append('<input id="vedit-imgdialog-filename" type="text" />');
                $leftcol.append('<label>image title</label>');
                $leftcol.append('<input id="vedit-imgdialog-title" type="text" />');
                $leftcol.append('<label>image alt</label>');
                $leftcol.append('<input id="vedit-imgdialog-alt" type="text" />');

                var $ifr = $('<iframe>', { id: 'vedit-imgdialog-iframe', css: { height: '96px', width: '600px', overflow: 'hidden', border: '3px solid orange', position: 'absolute', bottom: '32px', left: '50px', backgroundColor: '#000', display: 'none'} });
                $leftcol.append($ifr);

                setTimeout(function() {
                    var f = $('#vedit-imgdialog-iframe')[0].contentWindow.document;
                    var $b = $('body', f);
                    $b.html("<form id='uf' action='/vui/vedit-images.aspx' method='POST' enctype='multipart/form-data' name='uf'><h1 style='margin:0px 0px 8px 0px;color:#fff;font-family:Tahoma;font-weight:normal;font-size:24px'>Upload Image to : <b id='headd'></b></h1><input type='hidden' name='r' value='" + config.imageroot + "' /><input type='hidden' id='d' name='d' value='' /><input type='file' id='fup' name='fup' /><input type='submit' name='up' value='uploadimage' /><input type='button' name='cl' value='close' onclick='parent.vEditCloseUpload()' /></form>");
                }, 100);


                $rightcol.append('<img id="vedit-imgdialog-preview" />');

                $dialogimage.append($leftcol);
                $dialogimage.append($midcol);
                $dialogimage.append($rightcol);

                $dialogimage.append('<hr />');
                $dialogimage.append('<a href="#" id="vedit-imgdialog-upload" class="button" style="float:left;margin-left:0px">Upload an Image</a>');
                $dialogimage.append('<a href="#" id="vedit-imgdialog-ok" class="button">Okay</a>');
                $dialogimage.append('<a href="#" id="vedit-imgdialog-cancel" class="button vdialog-close">Cancel</a>');

                $('body').append($dialogimage);
            }

            //make the image dialog into an actual vdialog
            $dialogimage.vDialog();

            /////////////////////////////////
            //EVENTS for running IMAGE DIALOG

            //click on image within the image dialog
            $dialogimage.find('#vedit-imgdialog-directories').bind("change", function(e) {
                updateimagelist();
            });
            //directory menu update
            $dialogimage.find('#vedit-imgdialog-filelisting').bind("click", function(e) {
                if ($(e.target).attr('rel') != null) {
                    $dialogimage.find('#vedit-imgdialog-filename').val($(e.target).attr('rel'));
                    $dialogimage.find('#vedit-imgdialog-preview').attr('src', $(e.target).attr('rel'));
                }
            });
            //image upload panel
            $dialogimage.find('#vedit-imgdialog-upload').bind("click", function(e) {
                //update the target details based on the current directory
                var f = $dialogimage.find('#vedit-imgdialog-iframe')[0].contentWindow.document;
                $('#d', f).val($('#vedit-imgdialog-directories').val());
                $('#headd', f).html($('#vedit-imgdialog-directories').val());
                $currentuploadwindow = $dialogimage;
                $dialogimage.find('#vedit-imgdialog-iframe').show();
            });
            //click the okay button of the image dialog
            $dialogimage.find('#vedit-imgdialog-ok').bind("click", function(e) {
                if ($dialogimage.find('#vedit-imgdialog-filename').val().length > 0) {
                    //lets create (or update the image);
                    var imagepath = $dialogimage.find('#vedit-imgdialog-filename').val();
                    var imagetitle = $dialogimage.find('#vedit-imgdialog-title').val();
                    var imagealt = $dialogimage.find('#vedit-imgdialog-alt').val();
                    if (currenttagname == "IMG") {
                        //change the source of the current image
                        $(currenttarget).attr('src', imagepath);
                        $(currenttarget).attr('title', imagetitle);
                        $(currenttarget).attr('alt', imagealt);
                    }
                    else {
                        //add a new image element into the data, lets make sure we have the nearest P
                        if (currenttagname != "P") {
                            $(currenttarget).closest("P").prepend("<img src='" + imagepath + "' unselectable='on' alt='' />");
                        }
                        else {
                            $(currenttarget).prepend("<img src='" + imagepath + "' unselectable='on' alt='' />");
                        }
                    }
                    $dialogimage.trigger("vdialog-close", this);
                }
            });


            //////////////////////////////////
            //EVENTS for running CONTEXT MENUS


            //bind the commands in these menus to the functions in here...
            $('.vc-addclass').bind("click", function(e) {
                if (currenttagname == "IMG") {
                    $(currenttarget).removeClass().addClass($(this).attr('rel'));
                } else {
                    //apply to the closest P
                    var $cp = $(currenttarget).closest("P");
                    if ($cp != null) {
                        $cp.removeClass().addClass($(this).attr('rel'));
                    } else {
                        alert("can't find a P to apply a style to");
                    }
                }
            });

            $('.vc-delimage').bind("click", function(e) {
                if (currenttagname == "IMG") {
                    $(currenttarget).remove();
                }
            });

            //bind the commands in these menus to the functions in here...
            $('.vc-addimage').bind("click", function(e) {
                //is the current target an image?
                if (currenttagname == "IMG") {
                    //fill in the fields in the dialog with the current image details
                    $dialogimage.find('#vedit-imgdialog-filename').val($(currenttarget).attr('src'));
                    $dialogimage.find('#vedit-imgdialog-title').val($(currenttarget).attr('title'));
                    $dialogimage.find('#vedit-imgdialog-alt').val($(currenttarget).attr('alt'));
                }
                //open the image dialog
                $dialogimage.trigger("vdialog-open", this);
                //update the file list via ajax
                updateimagelist();
            });

        });

        var te = this;


    } //fn.vedit

    vEditCloseUpload = function() {
        $currentuploadwindow.find('#vedit-imgdialog-iframe').hide();
        $currentuploadwindow = null;
    };

    var $currentuploadwindow = null;

    vEditUploaded = function(nameofimage) {
        $currentuploadwindow.find('#vedit-imgdialog-filename').val(nameofimage);
        $currentuploadwindow.find('#vedit-imgdialog-iframe').hide();
        $currentuploadwindow.find('#vedit-imgdialog-directories').trigger("change");
        $currentuploadwindow.find('#vedit-imgdialog-preview').attr('src', nameofimage);
        $currentuploadwindow = null;
    };

})(jQuery);
