﻿if (typeof (jsModweb) === "undefined") jsModweb = {};
if (typeof (jsModweb.admin) === "undefined") jsModweb.admin = {};
if (typeof (jsModweb.admin.editing) === "undefined") jsModweb.admin.editing = {};
if (typeof (jsModweb.admin.ajax) === "undefined") jsModweb.admin.ajax = {};
//if (typeof (jsModweb.admin.users) === "undefined") jsModweb.admin.users = {};
jsModweb = {
    debug:
    {
        write: function (o) {
            if (!jQuery.jqModweb.debug._consoleLog('DEBUG: ' + o)) {
                jQuery.jqModweb.debug._messageBox('DEBUG: ' + o);
            }
        },
        log: function (o) {
            jQuery.jqModweb.debug._consoleLog('LOG: ' + o);
        },
        warning: function (o) {
            jQuery.jqModweb.debug._consoleLog('WARNING: ' + o);
        },
        validation: function (o) {
            jQuery.jqModweb.debug._consoleLog(o);
            jQuery.jqModweb.debug._messageBox(o);
        },
        error: function (o) {
            jQuery.jqModweb.debug._consoleLog('ERROR: ' + o);
            jQuery.jqModweb.debug._messageBox('ERROR: ' + o);
        },
        _consoleLog: function (o) {
            var hasConsole = typeof console !== "undefined";
            if (hasConsole == true) {
                // write to firebug.
                console.log(o);
            }
            return hasConsole;
        },
        _messageBox: function (o) {
            alert(o);
        }
    },
    random: function (o) {
        var defaults = {
            min: 0,
            max: 9999999
        }
        var o = jQuery.fn.extend({}, defaults, o);
        var min = o.min;
        var max = o.max;
        return min + Math.floor((max - min + 1) * (Math.random() % 1));
    },
    loader: {
        show: function (o) {
            var overlayContainer = jQuery('<div class="modweb-admin-loaderOverlay"></div>').css({
                'width': '100%'
            , 'height': '100%'
            , 'position': 'fixed'
            , 'left': '0'
            , 'top': '0'
            , 'opacity': '0.4'
            , 'background-color': '#888888'
            , 'z-index': '3001'
            });
            if (typeof (o) !== 'undefined' && typeof (o.id) !== 'undefined') {
                overlayContainer.attr('id', o.id);
            }
            /*var text = jQuery('<div></div>').text('Loading...').css({
            backgroundColor: '#ffffff'
            , 'left': '50%'
            , 'top': '50%'
            , width: '100px'
            , height: '40px'
            , 'z-index': '3001'
            ,'fontSize':'16px'
            , 'position': 'fixed'
            , 'opacity': '1.0'
            ,'color':'#000000'

            });
            overlayContainer.append(text);
            */
            jQuery('body').append(overlayContainer);
        },
        hide: function (o) {
            if (typeof (o) !== 'undefined' && typeof (o.id) !== 'undefined') {
                jQuery('div#' + o.id + '.modweb-admin-loaderOverlay').remove();
            }
            else {
                jQuery('div.modweb-admin-loaderOverlay').remove();
            }
        }
    },
    users: {
        getCurrentUserGuid: function () {
            var guid = jQuery.cookie('dotnet_loginsessionguid');
            if (jQuery.jqModweb.isNullOrEmpty(guid))
                jQuery.jqModweb.debug.error("No user guid!");
            //alert('guid='+guid);
            return guid;
        }
    }/*,
    session: {
        getNodeId: function () {
            debugger;
        }
    }*/





    , AdvancedModalWindow: function (o) {
        var defaults = {
            url: 'http://www.example.com/'
            , ascxPath: null // overrides 'url'. NOTE: The ascx file you call should inherit from ModWindowUserControl to gain access to method to properly manipulate the window.
            , content: null // overrides both ascxPath and url parameters.
            , width: null
            , height: null // NOTE: setting this to 'auto' will set a fixed width based on the current browser height. this has nothing to do with the AutoResizing that takes place after an iframe's .ascx content is loaded. to control this you want to modify the server-side properties of the .ascx template itself.
            , onClose: null // TODO: what's this for?
            , onClosing: null
            , onClosed: null
            , onContentReady: null
            , params: null
            , backgroundColor: '#F5F5F5'
            , borderColor: '#CDCDCD'
            , borderWidth: '1px'
            , showTitleBar: true
            , titleBarBackgroundColor: '#E9E9E9'
            , titleBarBorderRadius: '0.75em'
            , modal: false
            , animate: true
            , animationSpeed: null
            , overflow: 'auto' // can se to hidden to remove scrollbars.
            , title: '' // param ignored if showTitleBar is set to false.
            , scrolling: true
            , preserveForm: true // enabling this will keep the HTML stack inplace when rendering the modal window, but disallowing multiple instances. this is only applicable when loading with the 'content' parameter and not an .ascx (which is a dynamic iframe internally).
            //, allowContentCopying: false
        }
        var o = jQuery.extend({}, defaults, o);
        if (!o.width || o.width === 0)
            o.width = 600;
        if (!o.height || o.height === 0)
            o.height = 400;
        this._o = o;
        this._container = null;
        this._overlayContainer = null;
        this._id = ('window_' + Math.random()).replace(/[.]/g, ''); // used internally to keep track of window. allows opening iframe to have control to close/resize.
        var self = this;
        this.open = function () {
            if (this._o.modal) {
                this._overlayContainer = jQuery('<div id="modweb-jsmodwebadvancedmodalwindow-modalWindow-overlay"></div>').css({
                    'width': '100%'
            , 'height': '100%'
            , 'position': 'fixed'
            , 'left': '0'
            , 'top': '0'
            , 'opacity': '0.25'
            , 'background-color': '#000000'
            , 'z-index': '2999'
                });
                jQuery('body').append(this._overlayContainer);
            }

            if (this._o.ascxPath) {
                this._o.url = "/_framework/modules/website/ModWindow-AscxLoader.aspx?windowid=" + this._id + "&templatepath=" + this._o.ascxPath;

                if (this._o.params) {
                    for (var p in this._o.params) {
                        this._o.url += "&" + p + "=" + this._o.params[p];
                    }
                }
            }

            // auto width if required.
            if (this._o.width === 'auto')
                this._o.width = window.innerWidth - 220;
            if (this._o.height === 'auto')
                this._o.height = window.innerHeight - 200;

            // at this point convert the width and height to integers incase the class was called with {width:'100px'} rather than {width:100}
            this._o.width = parseInt(this._o.width);
            this._o.height = parseInt(this._o.height);

            if (this._o.height < 50 && this._o.ascxPath) {
                // set a min height otherwise the ajax loader will cut off.
                this._o.height = 50;
            }


            // main modal window container.
            this._container = jQuery('<div x-modweb-jsmodwebadvancedmodalwindow-modalwindow="yes" id="' + this._id + '"></div>');
            this._container.css({
                'position': 'fixed'
             , 'display': 'none'
             , 'left': '50%'
             , 'top': '50%'
             , 'z-index': '3000'
             , 'margin-left': '-' + (this._o.width / 2 + 32 / 2) + 'px' // the 32 is the estimated caption title bar height.
             , 'margin-top': '-' + (this._o.height / 2 + 32 / 2) + 'px' // the 32 is the estimated caption title bar height.
            })
            .bind('close', function (e, o) {
                if (self._o.onClosing !== null) {
                    self._o.onClosing(e, o);
                }

                jQuery(self._container).trigger('beforeClose', o);
                self._container.remove();
                if (self._overlayContainer)
                    self._overlayContainer.remove();

                if (self._o.onClosed !== null) {
                    self._o.onClosed(e, o);
                }
            })
            .bind('beforeClose', function (e, o) {
                if (self._o.onClose !== null) {
                    self._o.onClose(o);
                }
            }).bind('modweb_modalwindow_oncontentready', function () {
                if (self._o.onContentReady !== null) {
                    self._o.onContentReady();
                }
            });


            // title bar.
            var titleBar = null;
            if (this._o.showTitleBar) {
                titleBar = jQuery('<div></div>').addClass('title-bar');
                titleBar.width(this._o.width + this._o.borderWidth * 2); // plus the border on the contentPane.
                titleBar.css({
                    backgroundColor: this._o.titleBarBackgroundColor
                    , height: '16px'
                    , 'border-top': '1px solid ' + this._o.borderColor
                    , 'border-right': '1px solid ' + this._o.borderColor
                    , 'border-left': '1px solid ' + this._o.borderColor
                    //, '-moz-border-radius-topleft': this._o.titleBarBorderRadius
                    //, 'border-top-left-radius': this._o.titleBarBorderRadius
                    //, '-moz-border-radius-topright': this._o.titleBarBorderRadius
                    //, 'border-top-right-radius': this._o.titleBarBorderRadius
                });
                if (this._o.title) {
                    titleBar.append(jQuery('<span></span>').text(this._o.title).css({
                        color: 'white'
                         , height: '16px'
                         , float: 'left'
                         , 'font-size': '12px'
                         , 'font-weight': 'bold'
                         , 'font-family': 'sans-serif'
                         , 'text-shadow': '0px 0px 1px #cccccc'
                         , 'cursor': 'default'
                         , color: '#666666'
                         , 'padding-left': '2px'
                         , 'padding-right': '3px'
                         , 'background-color': this._o.titleBarBackgroundColor
                    }));
                }
                titleBar.append(
                jQuery('<span></span>')
                .click(function () {
                    self.close();
                })
                // "Close" button container.
                .css({
                    float: 'right'
                    , width: '21px'
                    , height: '16px'
                    , 'cursor': 'pointer'
                    , 'background-color': this._o.titleBarBackgroundColor
                })
                .append(
                    jQuery('<img src="/_framework/admin/images/advancedmodalwindow_close.gif" />').css({
                        float: 'left'
                        , 'margin-top': '3px'
                        , 'margin-left': '4px'
                    })
                 ));


                // render the title bar background canvas.
                {
                    var titleBarBackgroundContainer = jQuery('<div></div>');
                    titleBarBackgroundContainer.css({
                        height: '16px'
                        , 'padding-left': '2px'
                        //, 'background-color': 'yellow'
                    });
                    for (var i = 0; i < 3; i++) {
                        var spacer = jQuery('<div></div>').css({ height: '3px' });
                        spacer.appendTo(titleBarBackgroundContainer);

                        var line = jQuery('<div></div>');
                        line.css({ 'border-top': '1px dotted #666666' });
                        line.appendTo(titleBarBackgroundContainer);
                    }
                    /*var titleBarBackgroundCanvas = jQuery('<canvas></canvas>');
                    titleBarBackgroundCanvas.css({ height: '16px' });
                    titleBar.append(titleBarBackgroundCanvas);
                    var context = titleBarBackgroundCanvas.get(0).getContext("2d");
                    for (var i = 0; i < 10; i++) {
                    context.moveTo(i * 10, 4);
                    context.lineTo(i * 10 + 8, 4);
                    context.stroke();
                    }*/
                    titleBar.append(titleBarBackgroundContainer);
                }
            }

            // content pane.
            var contentPane = jQuery('<div></div>').addClass('content-pane');
            if (this._o.content) {
                // there was content sent into the class.
                if (typeof this._o.content.show !== 'undefined')
                    this._o.content.show(); // incase it was hidden.
            }
            else {
                // there was no content sent into the class, create a content container using an iframe.
                //this._o.preserveForm = false; // turn off preserving form because this is dynamically created now so there is nothing to preserve.
                var h = '';
                var overflowStyle = this._o.overflow === null ? '' : ('overflow:' + this._o.overflow + ';');
                var scrollingAttribute = ' scrolling="' + (this._o.scrolling ? 'yes' : 'no') + '"';
                scrollingAttribute = '';
                h += '<iframe width="' + this._o.width + '" height="' + this._o.height + '" style="border-style:none;' + overflowStyle + ';"' + scrollingAttribute + '>';
                h += '</iframe>';
                this._o.content = jQuery(h);
                jQuery('body').append(this._o.content); // content needs to go somewhere if dynamically created.
            }

            contentPane.css({
                'background-color': this._o.backgroundColor
             , 'border-bottom': this._o.borderWidth + ' solid ' + this._o.borderColor
             , 'border-left': this._o.borderWidth + ' solid ' + this._o.borderColor
             , 'border-right': this._o.borderWidth + ' solid ' + this._o.borderColor
            });
            // if there is no title bar, add a top border too.
            if (!this._o.showTitleBar)
                contentPane.css({ 'border-top': this._o.borderWidth + ' solid ' + this._o.borderColor });



            // render ajax loader.
            if (this._o.ascxPath) {
                //contentPane.children('iframe').css({
                //if (this._o.content) {
                this._o.content.css({
                    'background': "url(/_framework/images/modalwindow-ajax-loader.gif) no-repeat"
                    , 'background-position': 'center'
                    , 'background-color': '#eeeeee'
                });
                //}
            }



            // build the html stack.
            if (this._o.preserveForm) {
                /*
                <form>
                * <!-- this._container -->
                * <div id="window_05701228040097444" x-modweb-jsmodwebadvancedmodalwindow-modalwindow="yes">
                *** <div class="title-bar">
                ***** <span>
                ******* The Title...
                ***** </span>
                ***** <span>
                ******* <img src="/_framework/admin/images/advancedmodalwindow_close.gif" style="float: left; margin-top: 4px; margin-left: 4px;"/>
                ***** </span>
                *** </div>
                *** <div class="content-pane" >
                ***** <!-- this._o.content -->
                ***** <div id="Window1" x-isadmin="True" x-modweb-designerwebcontrol-enableeditableregions="True" data-showtitlebar="True" data-parameters="{}" data-height="0" data-width="0" data-onclientclose="" data-uniqueid="Window1" data-modweb-designer-window="yes">
                ******* <input type="submit" id="ButtonInside" value="inside modal window" name="ButtonInside">
                ***** </div>
                *** </div>
                * </div>
                </form>
                */
                this._o.content.show();
                this._o.content.wrap(contentPane);
                contentPane = this._o.content.parent('.content-pane'); // reselect it after using wrap().
                contentPane.wrap(this._container.show());
                this._container = contentPane.parent('[x-modweb-jsmodwebadvancedmodalwindow-modalwindow]'); // reselect it after using wrap().
                this._container.prepend(titleBar);
            }
            else {
                /*
                <body>
                * ...
                * <!-- this._container -->
                * <div id="window_05701228040097444" x-modweb-jsmodwebadvancedmodalwindow-modalwindow="yes">
                *** <div class="title-bar">
                ***** <span>
                ******* The Title...
                ***** </span>
                ***** <span>
                ******* <img src="/_framework/admin/images/advancedmodalwindow_close.gif" style="float: left; margin-top: 4px; margin-left: 4px;"/>
                ***** </span>
                *** </div>
                *** <div class="content-pane" >
                ***** <!-- this._o.content -->
                ***** <div id="Window1" x-isadmin="True" x-modweb-designerwebcontrol-enableeditableregions="True" data-showtitlebar="True" data-parameters="{}" data-height="0" data-width="0" data-onclientclose="" data-uniqueid="Window1" data-modweb-designer-window="yes">
                ******* <input type="submit" id="ButtonInside" value="inside modal window" name="ButtonInside">
                ***** </div>
                *** </div>
                * </div>
                </body>
                */
                this._container.show();
                jQuery('body').append(this._container);
                this._container.append(titleBar);
                this._container.append(contentPane);
                contentPane.append(this._o.content);
            }


            if (typeof (jQuery.fn.draggable) !== 'undefined') {
                this._container.css({ cursor: 'move' }).draggable({ cursor: 'default' });
            }


            // add the src to the iframe at the end, this has to be done very last otherwise some browsers will start calling the src url before it is properly inserted into the dom.
            contentPane.find('iframe').attr('src', this._o.url);



            //jQuery(h).ready(function () { alert('iframe ready!'); });
        };
        this.close = function (o) {
            this._container.trigger('close', o);
        };
        // reload() will reload the window if needing to find it by the id.
        this.reload = function (id) {
            this._container = jQuery('#' + id);
            if (this._container.length === 0)
                jsModweb.debug.error("Could not load window with ID '" + id + "' does it exist?.");
        };
        // onContentReady() will be called by the loading .aspx page after the iframe is fully loaded. it is called by the iframe's content to the parent window.
        this.onContentReady = function () {
            this._container.trigger('modweb_modalwindow_oncontentready');
            var iframeContainer = this._container.find('iframe:first');
            iframeContainer.css({ 'background': 'none' });
        };
        this.resize = function () {
            var iframeContainer = this._container.find('iframe:first');
            //iframeContainer.css({ 'background': 'none' });
            var contentHeight = null;

            if (jQuery.browser.msie && jQuery.browser.version <= 8) {
                contentHeight = iframeContainer.get(0).contentWindow.document.body.clientHeight;
            }
            else {
                contentHeight = iframeContainer.get(0).contentDocument.body.clientHeight;
            }

            var newContentHeight = contentHeight + 32;
            var browserHeight = document.documentElement.clientHeight;
            var maxHeight = browserHeight - 80;

            if (newContentHeight > maxHeight)
                newContentHeight = maxHeight;

            this._container.animate({
                'margin-top': '-' + (newContentHeight / 2 + 32 / 2) + 'px' // the 32 is the estimated caption title bar height.
            });
            iframeContainer.css({ 'overflow-x': 'hidden' });

            iframeContainer.animate({ height: newContentHeight });
            //iframeContainer.height(newContentHeight);
        }
    }


};

