Subversion Repositories DevTools

Rev

Rev 6592 | Rev 6625 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

//  Vix specific Javascript for jquery use
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//  Generate a confirmation dialog
//  Args:   text - Body of the message
//          parms - A simple object of options - see defaults
//                  Special: position of 'center' will place in center of visible screen.
//  Note: will return BEFORE the user makes a selection
//        Can call a function and/or a URL if confirmed
//        Can 'show' a progress element
//        See 'defaults' below for bits that can be modified
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function vixConfirm(text, parms){
     var defaults = {
        resizable: true,
        height: 'auto',
        width : 'auto',
        modal: true,
        position: { my: "top", at: "top+100", of: window },
        title: "Confirm",
        icon: "images/i_warning.gif",
        url : null,
        ok : null,
        post : null,
        button : "Confirm",
        progress : "#ProgressBar",
        cancel : true,
        timeout : null,
        dlg : null
     };
     $.extend( defaults, parms);

     defaults.open = function() {
        $(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus(); 
        var markup = "";
        if (defaults.icon != null ) {
            markup += '<img src="'+ defaults.icon+ '" style="float:left; margin:0 7px 20px 0;">';
            }
        markup += text;
        $(this).html(markup);
         if ( defaults.timeout != null ) {
             setTimeout(function(){
                 defaults.dlg.dialog("close");
                }, defaults.timeout);
         }
     };

    defaults.close = function() {
        $(this).remove();
    };

    defaults.buttons = [];
    if ( defaults.button != null ) {
        defaults.buttons.push({
            text : defaults.button,
            click : function (){
                    if (defaults.ok != null ){
                        defaults.ok(defaults);
                    }
                    if ( defaults.progress != null) {
                        $(defaults.progress).show().css("visibility", "visible");    
                    }
                    if (defaults.url != null ) {
                        window.location.href = defaults.url;
                    }
                    if (defaults.post != null ) {
                        $('form[name="'+defaults.post+'"]').submit();    
                    }
                    $(this).dialog("close");
                }
        });
    }

    if(typeof(defaults.cancel) == 'boolean' && defaults.cancel) {
        defaults.buttons.push({
            text : 'Cancel',
            click : function (){
                $(this).dialog("close");
                }
        });
    }

     var dd = $( "<div>Confirm</div>" ).dialog(defaults);
     defaults.dlg = dd;
     // Once the dialog has been instantiated the autosize dimensions are known
     // and the dialog can be correctly positioned
     if (defaults.position == 'center')
     {
         dd.dialog("widget").center();
         //console.log("Center in Window");
     }
     else
     {
         dd.dialog("widget").position(defaults.position);
         //console.log("Original position");
     }
     
     // Return false incase this is used as an onClick
     return false;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Compatability function
//      Confirm Deletion of an item
//      Assumes that the item is within an 'anchor' and that an href can be located
//      Uses VixConfirm to do the heavy lifting
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function vixConfirmDelete (txt)
{
    var href = window.event.currentTarget.href;
    vixConfirm('Are you sure you want to delete '+ txt +'?', {url : href})
    return false;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//  Similar to 'alert', but uses the jquery dialog mechnaism
//  Note: will return BEFORE the user makes a selection
//  Returns a Defereed object that will be rejected when the dialog is closed.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function vixAlert(text){
     var dbo = $.Deferred();
     var dd = $( "<div>Alert</div>" ).dialog({
        resizable: true,
        height: 'auto',
        width : 'auto',
        modal: true,
        title:'Alert',
        position: { my: "top", at: "top+100", of: window },
        open: function() {
            $(this).html('<img src="images/i_critical.gif" style="float:left; margin:0 7px 20px 0;">' + text);
        },
        close : function() {
            $(this).remove();
            dbo.reject();
        },
        buttons: {
            "Ok": function() {
                $(this).dialog("close");
            }
        }
     });
     // Once the dialog has been instantiated the autosize dimensions are known
     // and the dialog can be correctly positioned
     // Note: Appears that we need to position it twice
     //       Once in the dialog creation, and once here
     dd.dialog("widget").position({ my: "top", at: "top+100", of: window });

     return dbo;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//  jQuery extension function
//  Position an element inthe center of the visible window. Not the document and not the window(viewport).
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
jQuery.fn.center = function () {

    //  Support many browsers
    var w = window.innerWidth  || document.documentElement.clientWidth  || document.body.clientWidth;
    var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

    this.css("position","fixed");
    this.css("top", Math.max(0,  ((h - $(this).outerHeight()) / 2) ) + "px");
    this.css("left", Math.max(0, ((w - $(this).outerWidth()) / 2) ) + "px");
    return this;
}

//--------- Support to open modal dialog in an iFrame
//  Example: <a class="vixIframeDialog" href="aaa.asp" title="Some Title">Link Text</a>
//
var vixIframe = {};
$(document).ready(function () {
    $('.vixIframeDialog').on('click', function(e){
                if (!vixIframe.parent) {
                        e.preventDefault();
                        vixIframe.parent = this;
                        vixIframe.pagetitle = $(this).attr("title");
                        if (! vixIframe.pagetitle) {
                                vixIframe.pagetitle = $(this).text();
                        }
                        vixIframe.url = $(this).attr("href");
                        vixIframeDialogCommon();
                }
        });

    //
    // Prevent (at least control) the user from navigating within the iframe
    // If this invocation is within an iFrame, then close the iFrame if
    // the user attempt to navigate away from the iFrame.
    //      This means that the iFrame cannot replace itself
    // 
    if (typeof parent.vixIframe.pagetitle !== 'undefined')
    {
        //console.log("DocumentReady within iframe");
        window.onunload = function(){
            //console.log("Unloading within iframe");
        }
    }

});

//
//      Callable function to instantiate an Iframe Dialog
//  Used in a replacement for MM_openBrWindow called MM_openVixIFrame
//      Parameters:
//              pthis   - The parent's context
//              url             - URL of the windoe content
//      winName - Title of the new Window

function vixIframeDialog2(pthis, url, winName)
{
        vixIframe.parent = pthis;
        vixIframe.pagetitle = winName;
        vixIframe.url = url;
        vixIframeDialogCommon();
}

function vixIframeDialogCommon()
{
        var iframe = $('<iframe onload="IframeLoaded(this);" id="iframe" style="border:0px; overflow: scroll;" src="' + vixIframe.url + '" width="100%" height="100%" ></iframe>');
        var $dialog = $('<div></div>').html(iframe);
        var $dialog2 = $dialog.dialog({
                autoOpen: true,
                modal: true,
                height : 'auto,', 
                width : 'auto',
                resizable: false,
                position : { my:'top', at: 'top+100', of : window },
                dialogClass: "rounded_box",
                title: 'Loading - ' + vixIframe.pagetitle,
                close: function(event, ui){
                        //console.log('closing dialog');
                        $(this).dialog("destroy");
                        vixIframe = {};
                        window.onbeforeunload = null;
                        window.onunload = null;
                        },
                // Prevent Chrome from adding scrollbars when dragged
                dragStop: function( event, ui ){
                        vixIframe.IFrame.parentElement.style.overflow = "";
                        },
                dragStart: function( event, ui ){
                        vixIframe.IFrame.parentElement.style.overflow = "hidden";
                        }
        });
        vixIframe.Dialog = $dialog;
        vixIframe.DialogProps = $dialog2;
        vixIframe.DialogWidget = $($dialog2).dialog('widget');

        return false;
}
//
//      Called when the iframe is loaded or reloaded
//
function IframeLoaded(iframe) {
        // Save to resize iframe
        vixIframe.IFrame = iframe;

        // Reset the title
        vixIframe.Dialog.dialog('option','title', vixIframe.pagetitle);

        // Resize the frame
        resizeIframe();
};
//
//      This function can be called from within the iframe to have it resized
//      Used if the iframe is too dynamic and extends itself from time to time
//
function resizeIframe()
{
    if (vixIframe.IFrame != null) {
                iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
                $(vixIframe.Dialog).height(iframe.height);
                //console.log ("Resize Iframe:",iframe.height );

                iframe.width = iframe.contentWindow.document.body.scrollWidth + "px";
                $(vixIframe.Dialog).width(iframe.width);
                //console.log ("Resize Iframe:",iframe.width );

                // Reposition the dialog
                $(vixIframe.DialogWidget).position($(vixIframe.DialogProps).dialog("option").position);
        }
}
//
//      This function can be called from with the iframe to close the Iframe
//      Often wired up to the cancel button
function closeIFrame()
{
    if (vixIframe.Dialog != null) {
        //console.log('closing iframe');
        vixIframe.Dialog.dialog('close');
        vixIframe = {};
    }
}

//
//  Add copy to clipboard icon to every element with a class of 'clip'
//
$( document ).ready(function() {
    var myClipHandler = function (event)
    {
        // Get element to clip
        var el = $(this).closest('.clip').eq(0);

        // Get the text and clean it up
        var text = $.trim(el.text());
            text = text.replace(/\s+/g, ' '); 

        // Copy to clipboard
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val(text).select();
        document.execCommand("copy");
        $temp.remove();

        // Highlight (the text that has been selected
        //  Appears to be no nice way to do this :(
        var doc = document, range, selection;    
        if (window.getSelection) {
            selection = window.getSelection();        
            range = document.createRange();
            range.selectNodeContents(el[0]);
            selection.removeAllRanges();
            selection.addRange(range);
            setTimeout(function(){selection.removeAllRanges();},500);
        } else { 
            range = document.body.createTextRange();
            range.moveToElementText(el[0]);
            range.select();
            setTimeout(function(){document.selection.empty();},500);
        }
    }

    $('.clip').append(
        $('<img />')
            .attr({
                title : "Copy to clipboard",
                src : "images/CopyToClipboard.ico",
                height : "12px",
                width : "12px",
                hspace : "0px",
                align : "absmiddle",
                border : "0"
                })
            .on("click", myClipHandler)
        )
        .on("dblclick", myClipHandler);

});

// Add a clipThis handler to each element with a clipThis class
//      Will copy the text of the element to the clipboard
//      Add dynamically so that it will be invoked on dynamically created elements
$( document ).on('click', '.clipThis', function(event){
    var txt = $(this).eq(0).text();
    vixTextToClipBoard(txt, {note : "Copied to Clipboard", duration : 1000});
});

// Copy data from element to clipboard
//      Elements have a class of clipData and an attribute of data-clip=xxx
//  Add dynamically so that it will be invoked on dynamically created elements
$( document ).on('click', '.clipData', function(event){
    var txt = $(this).data('clip');
    vixTextToClipBoard(txt, {note : "Copied to Clipboard", duration : 1000});
});

// Copy data from a named element to clipboard
// Supports multi-line data with <p> and <br> in it
//      Elements have a class of clipElement and an attribute of data-target=elementId
$( document ).on('click', '.clipElement', function(event){
    var ename = $(this).data('target');
    var html = $('#' + ename).eq(0).html();
    var breakToken = '_______break_______';
    var lineBreakedHtml = html.replace(/<br\s?\/?>/gi, breakToken).replace(/<p\.*?>(.*?)<\/p>/gi, breakToken + '$1' + breakToken);
    var txt = $('<div>').html(lineBreakedHtml).text().replace(new RegExp(breakToken, 'g'), '\r\n');

    vixTextToClipBoard(txt.trim(), {note : "Copied to Clipboard", duration : 1000});
});


// Invoke mailto on elements with a suitable class
//  Elements with class mailto. and a data item of email
// Add dynamically so that it will be invoked on newly created elements
$( document ).on('click', '.mailto', function(event){
    var email = $(this).data('email');
    var name =  $(this).data('name');
    if ( !name ) {
        name =  $(this).eq(0).text();
    }
    
    var menu = '<div class="rex_clm" >&nbsp;Select Operation</div>';
    if ( name ) {
        menu += '<div class="mmItem clipData" data-clip="' + name + '">Copy Name to Clipboard</div>';
    }
    menu += '<div class="mmItem clipData" data-clip="' + email + '">Copy Email Address to Clipboard</div>';
    menu += '<div onClick="window.open(\'mailto:' + email + '\', \'_blank\');" class="mmItem">Send Email</div>';
    showmenu(event,menu);
    event.stopImmediatePropagation();
    event.stopPropagation();
    return false;
});

// Copy text to clipboard
function vixTextToClipBoard(txt, options){
    if ( txt == null ) {
        return;
    }
    var opts  = {
        note : "Data copied to Clipboard",
        title: "Notification",
        notify : true,
        timeout : 100,
        duration: 2000,
    }
    $.extend(opts, options);

    var $temp = $("<textarea>");
    $("body").append($temp);
    $temp.val(txt).select();
    document.execCommand("copy");
    $temp.remove();

    if ( opts.notify ) {
        vixConfirm(opts.note, {
            title: opts.title,
            icon : "images/i_info.png", 
            cancel: false, 
            button: null,
            timeout : opts.timeout,
            not_on_firefox_position : {my: 'center', at: 'top', of: event},
            modal : false,
            minHeight: 10, 
            hide: { effect: 'fade', duration: opts.duration }
            });

    }
}