Subversion Repositories DevTools

Rev

Rev 7240 | Rev 7291 | 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,
        deferred : 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();
    };

    if(typeof(defaults.deferred) == typeof(true)){
        if ( defaults.deferred ) {
            defaults.deferred = new $.Deferred();
        }
    }
    
    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();    
                    }
                    if ( defaults.deferred != null ) {
                        defaults.deferred.resolve();
                    }
                    $(this).dialog("close");
                }
        });
    }

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

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

     // If using deferred objects
     if ( defaults.deferred ) {
         return defaults.deferred.promise();
     }
     
     // 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
//          - other and that a 'data-href' will specify the 'url'
//  
//      Uses VixConfirm to do the heavy lifting
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function vixConfirmDelete (txt)
{
    var href = window.event.currentTarget.href;
    if ( !href ) {
        href = $(event.currentTarget).data('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;
if (typeof vixIframe === 'undefined') {
    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 window 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 + '" height="50px" width="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) {
        var iframe = vixIframe.IFrame;
                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 = {};
    }
}

//  Load a dialog into a dialog element
//  Like iFrame, but without the iFrame
//  Useful options:
//      title   - Window Title
//      onLoad  - Function name to call after load
//      class   - Optional class to add to the dialog
//
function vixDialog( theURL, usrOptions ) {

    $("body").addClass("cursor-wait");

    var options = $.extend({title : 'Dialog ', width : 300}, usrOptions,);

        vixIframe.parent = this;
        vixIframe.pagetitle = options.title;
        vixIframe.url = theURL;

    var $dialog = $('<div></div>');
    $(document.body).append($dialog);
    $dialog.load( theURL, function(){
        var $dialog2 = $dialog.dialog({
            autoOpen: true,
            modal: true,
            height : 'auto', 
            width : options.width,
            resizable: true,
            position : { my:'top', at: 'top+100', of : window },
            dialogClass: options.class,
            minHeight: 10,
            title: 'Loading - ' + vixIframe.pagetitle,
            close: function(event, ui){
                //console.log('closing dialog');
                $(this).dialog("destroy");
                vixIframe = {};
                $(this).remove();
                window.onbeforeunload = null;
                window.onunload = null;
                },
            dragStop: function( event, ui ){
                // Dragging adds a height which kill autosizing
                vixIframe.Dialog.closest('.ui-dialog').height('auto');
                },
        });
        vixIframe.Dialog = $dialog;
        vixIframe.DialogProps = $dialog2;

        // Save to resize iframe
        vixIframe.IFrame = $dialog;

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

        // Run init code for the frame
        // Have a possible function name
        if ( options.onLoad ) {
            try {
                eval (options.onLoad + '();');
            } 
            catch (e) {
                console.log ("vixDialog failed to run the onLoad script:" + options.onLoad );
            }
        }
        $("body").removeClass("cursor-wait");
    });
}

//
//  Copy the HTML from an element into the clipboard
//  Highlight the element clipped
//
function vixEl2Clip( el ) {
    // Get the text and clean it up
    var html = $.trim(el.html());

    var breakToken = '_______break_______';
    var lineBreakedHtml = html.replace(/<br\s?\/?>/gi, breakToken).replace(/<p\.*?>(.*?)<\/p>/gi, breakToken + '$1' + breakToken);
    var text = $('<div>').html(lineBreakedHtml).text().replace(new RegExp(breakToken, 'g'), '\r\n');
    text = $.trim(text);

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


    // Highlight the text that has been selected
    el.effect("highlight", {}, 1000);
    // el.css('background-color', 'rgba(0, 102, 255, .5)');
    // el.animate({backgroundColor: 'transparent'}, '1000');

    return el;
}

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

    $('.clip').on("click", myClipHandler).on("dblclick", myClipHandler);

    // Add a clip image to every class of either .clip
    $('.clip').wrapInner('<span class=clipSel></span>').append(
        $('<img />')
            .attr({
                title : "Copy to clipboard",
                src : "images/CopyToClipboard.ico",
                height : "12px",
                width : "12px",
                hspace : "0px",
                align : "absmiddle",
                border : "0"
                })
    );
});

// 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 have an attribute of data-target=elementId
$( document ).on('click', '.clipElement', function(event){

    var ename = $(this).data('target');
    var el = $('#' + ename);
    vixEl2Clip(el);
});

// 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});
});


// 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');
    var uname =  $(this).data('uname');
    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>';
    }
    if ( uname ) {
        menu += '<div class="mmItem clipData" data-clip="' + uname + '">Copy Login 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
// Need to append a dummy eleemnt to a point inthe document that can be selected
// In a modal dialog, the 'body' cannot be used. Use 'clipRoot' if its available
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 useEl = $('#clipRoot');
    if ( useEl.length === 0  ){
        useEl =$('body') ;
    }
    
    var $temp = $("<textarea>");
    useEl.prepend($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,
            modal : false,
            minHeight: 10,
            hide: { effect: 'fade', duration: opts.duration }
            });
    }
}

//  Export Table as CSV support functions
//      Allow a table that has been tagged with a class of etable to be exported
// 
// Global variable for use of the table to CSV widget
// Used to convey info though the selection callback
//
var vixEtableData;

$( document ).ready(function() {
    vixEtableInit();
});

//      vixPostPageLoad is called when dynamic DOM elements are loaded 
function vixPostPageLoad(){
    vixEtableInit();
}

//  Init all elements marked with a class of 'etable'
//      Insert an icon
//      Remove original class so that the DOM can be scanned again
function vixEtableInit(){
    $('.etable').css('position', 'relative');
    $('.etable th:last-child').append(
            $('<img />')
                .attr({
                    title : "Export table as CSV",
                    src : "images/CopyToClipboard.ico",
                    height : "12px",
                    width : "12px",
                    hspace : "0px",
                    align : "absmiddle",
                    border : "0"
                    })
                .css({position : 'absolute', top : '0px', right : '0px'})
                .click(function(event){
                    vixEtableData =  $(this).closest('table');
                    var menu = '<div class="rex_clm" >&nbsp;Select Operation</div>';
                    menu += '<div class="mmItem" onClick="vixEtableProc(\'popup\');">Show&nbsp;in&nbsp;New&nbsp;Window</div>';
                    menu += '<div class="mmItem" onClick="vixEtableProc(\'modal\');">Show in Dialog</div>';
                    menu += '<div class="mmItem" onClick="vixEtableProc(\'download\');">Download File</div>';
                    menu += '<div class="mmItem" onClick="vixEtableProc(\'clip\');">Copy to Clipboard</div>';
                    showmenu(event,menu);
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    return false;
                    })
        );
    $('.etable').addClass('etable-done').removeClass('etable');
}

//  Global function to support post-selection processing of CSV data
function vixEtableProc(mode) {
    var tdata = vixEtableData.data('etable')
    var defData = {
        delivery: mode,
        filename: 'data.csv',
        rowFilter: '.csvData'
        };
    $.extend(defData, tdata) ;
    var data = vixEtableData.TableCSVExport(defData);
    if ( mode == 'clip' ) {
        vixTextToClipBoard(data, {note : "CSV copied to Clipboard", duration : 1000});
    }
}

// Create a new window in the center of the current screen
//  A wrapper for window.open(), with a few smarts
//  Does not position correctly on Widows-Edge
function PopupCenter(url, title, w, h) {
    // Fixes dual-screen position                         Most browsers      Firefox
    var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : window.screenX;
    var dualScreenTop = window.screenTop != undefined ? window.screenTop : window.screenY;

    var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
    var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

    var left = ((width / 2) - (w / 2)) + dualScreenLeft;
    var top = ((height / 2) - (h / 2)) + dualScreenTop;
    var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

    // Puts focus on the newWindow
    if (window.focus) {
        newWindow.focus();
    }

    return newWindow;
}