﻿/*
* Facebox (for jQuery)
* version: 1.2 (05/05/2008)
* @requires jQuery v1.2 or later
*
* Examples at http://famspam.com/facebox/
*
* Licensed under the MIT:
*   http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
*
* Usage:
*
*  jQuery(document).ready(function() {
*    jQuery('a[rel*=facebox]').facebox()
*  })
*
*  <a href="#terms" rel="facebox">Terms</a>
*    Loads the #terms div in the box
*
*  <a href="terms.html" rel="facebox">Terms</a>
*    Loads the terms.html page in the box
*
*  <a href="terms.png" rel="facebox">Terms</a>
*    Loads the terms.png image in the box
*
*
*  You can also use it programmatically:
*
*    jQuery.facebox('some html')
*    jQuery.facebox('some html', 'my-groovy-style')
*
*  The above will open a facebox with "some html" as the content.
*
*    jQuery.facebox(function($) {
*      $.get('blah.html', function(data) { $.facebox(data) })
*    })
*
*  The above will show a loading screen before the passed function is called,
*  allowing for a better ajaxy experience.
*
*  The facebox function can also display an ajax page, an image, or the contents of a div:
*
*    jQuery.facebox({ ajax: 'remote.html' })
*    jQuery.facebox({ ajax: 'remote.html' }, 'my-groovy-style')
*    jQuery.facebox({ image: 'stairs.jpg' })
*    jQuery.facebox({ image: 'stairs.jpg' }, 'my-groovy-style')
*    jQuery.facebox({ div: '#box' })
*    jQuery.facebox({ div: '#box' }, 'my-groovy-style')
*
*  Want to close the facebox?  Trigger the 'close.facebox' document event:
*
*    jQuery(document).trigger('close.facebox')
*
*  Facebox also has a bunch of other hooks:
*
*    loading.facebox
*    beforeReveal.facebox
*    reveal.facebox (aliased as 'afterReveal.facebox')
*    init.facebox
*    afterClose.facebox
*
*  Simply bind a function to any of these hooks:
*
*   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
*
*/
(function($) {
    $.facebox = function(data, klass) {
        $.facebox.state = "closed";
        $.facebox.loading(data);
        if (data.ajax) fillFaceboxFromAjax(data.ajax, klass)
        else if (data.image) fillFaceboxFromImage(data.image, klass)
        else if (data.href) fillFaceboxFromHref(data.href, klass)
        else if (data.div) fillFaceboxFromHref(data.div, klass)
        else if ($.isFunction(data)) data.call($)
        else $.facebox.reveal(data, klass);
    }

    /*
    * Public, $.facebox methods
    */

    $.extend($.facebox, {
        settings: {
            opacity: 0.5,
            isModal: true,
            overlay: true,
            loadingImage: '/Portals/1/Skins/Main/images/ajax-loader.gif',
            closeImage: '/Portals/1/Skins/Main/images/close.png',
            imageTypes: ['png', 'jpg', 'jpeg', 'gif'],
            faceboxHtml: '\
    <div id="facebox" class="facebox" style="display:none;"> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="th"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="lv"/> \
              <td> \
                <div class="body"> \
                    <div class="header" align="right"> \
                      <a href="#" class="close"> \
                        <span align="center" style="padding-top:9px;">\
                             Close <span style="color:#6E5637;">X</span>\
                        </span>\
                      </a> \
                    </div> \
                    <div class="content"></div> \
                </div> \
              </td> \
              <td class="rv"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="bh"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
        },

        loading: function(data) {
            var $content = $('#facebox .content');
            var sWidth = 0;
            var sHeight = 0;
            var width = 307;
            var height = 143;
            if (data.href) {
                var queryString = data.href.replace(/^[^\?]+\??/, '');
                var params = fb_parseQuery(queryString);
                sWidth = parseInt(params.sWidth, 10);
                sHeight = parseInt(params.sHeight, 10);
                width = parseInt(params.width, 10);
                height = parseInt(params.height, 10);
            }
            else if (data.div) {
                width = $content.width();
                height = $content.height();
            }

            init();

            if ($('#facebox .loading').length == 1) return true;
            showOverlay()

            $('#facebox').click(function(event) {
                var vTarget = event.target || event.which;
                if ($(vTarget).hasClass("popup") && !$.facebox.settings.isModal)
                    $(document).trigger('close.facebox');
            });

            if ($content.find("iframe").length) {
                $content.empty();
            }
            else {
                $(document.body).append($content.children().hide());
            }

            $(document).bind('keydown.facebox', function(e) {
                var keyCode = e.charCode || e.keyCode;
                switch (keyCode) {
                    case 27:
                        if (e.keyCode == 27) $.facebox.close();
                        break;
                }
                return;
            });
            
            if (sWidth > 0 && sHeight > 0) {
                $content.css({ width: sWidth + "px", height: sHeight + "px" });
                $content.attr({ eWidth: width, eHeight: height });
            }
            else {
                $content.css({ width: width + "px", height: height + "px" });
                sWidth = width;
                sHeight = height;
            }
            $("#facebox .header .close").css({ visibility: "hidden" });
            $('#facebox .body').children().hide().end().append('<div class="loading" style="width:' + sWidth + 'px;height:' + sHeight + 'px;"><img src="' + $.facebox.settings.loadingImage + '" style="position:relative; top:' + (sHeight / 2 - 24) + 'px;" alt=""/></div>');
            //$('#facebox').show();
            $('#facebox').centerInClient({ left: false, top: true }).show();
            $(document).trigger('loading.facebox');
        },

        reveal: function(data, klass) {
            if (window.supersleight) {
                supersleight.run("facebox");
            }
            /*
            var $close = $("#facebox .header .close");

            $close.mousedown(function() {
            $(this).css("backgroundImage", "url(/Portals/1/Skins/Main/images/close.png)");
            });
            $close.mouseout(function() {
            if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
            $(this).css("backgroundImage", "url(/Portals/1/Skins/Main/images/close.png)");
            }
            else {
            $(this).css("backgroundImage", "");
            }
            });
            if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
            $close.mouseover(function() {
            $(this).css("backgroundImage", "url(/Portals/1/Skins/Main/images/close.png)");
            });
            }
            */
            var $content = $('#facebox .content');
            $(document).trigger('beforeReveal.facebox');

            if (klass) $content.addClass(klass);
            if (data && data.parent) {
                if (data.parent().get(0) != $content.get(0))
                    $content.append(data);
            }
            else {
                $content.append(data);
            }

            var $close = $("#facebox .header .close").css({ visibility: "hidden" });
            var $iframe = $content.find("iframe");
            var $body = $('#facebox .body');
            var contentWidth = 0;
            var contentHeight = 0;
            $content.css({ display: "block", position: "absolute", top: "-2000px" });
            
            if ($iframe.length) {
            
                contentWidth = parseInt($iframe.css("width"));
                contentHeight = parseInt($iframe.css("height"));
            
                try {
                    var contentWindow = ($iframe[0].contentWindow ? $iframe[0].contentWindow : $iframe[0]);
                    contentWidth = contentWindow.$(contentWindow.document).width();
                    var containerWidth = contentWindow.$("#container").width();
                    if (containerWidth > contentWidth) {
                        contentWidth = containerWidth;
                    }
                    contentHeight = contentWindow.$(contentWindow.document).height();
                    $iframe.css({ width: contentWidth + "px", height: contentHeight + "px" });
                }
                catch (exc) { }
            }

            if (contentWidth == 0 || contentHeight == 0) {
                contentWidth = parseInt($content.attr("eWidth"), 10);
                contentHeight = parseInt($content.attr("eHeight"), 10);
            }

            if (contentWidth == 0 || contentHeight == 0) {
                contentWidth = $content.width();
                contentHeight = $content.height();
            }

            $content.css({ display: "none", position: "", top: "0px" });

            if (contentWidth > 0 && contentHeight > 0) {
                $body.children().css({ display: "block", visibility: "hidden" });
                $('#facebox .loading').remove();
                $content.animate({
                    width: contentWidth,
                    height: contentHeight
                },
                {
                    duration: "fast",
                    step: function() {
                        $('#facebox').centerInClient({ left: false, top: true });
                    },
                    complete: function() {
                        if ($iframe) {
                            $iframe.show();
                        }
                        /*$close.fadeIn('normal');
                        $body.children().css({ display: "block", visibility: "hidden" }).fadeIn('normal');*/
                        $close.show();
                        $body.children().show();
                        $('#facebox').centerInClient({ left: false, top: true });
                        $(document).trigger('reveal.facebox').trigger('afterReveal.facebox');
                        $.facebox.state = "open";
                    }
                });
            }
            else if (data.show) {
                data.show();
                if ($iframe) {
                    $iframe.show();
                }
                $('#facebox .loading').remove();
                $close.show();
                $body.children().show();
                /*$close.fadeIn('normal');
                $body.children().css({ display: "block", visibility: "hidden" }).fadeIn('normal');*/
                $('#facebox').centerInClient({ left: false, top: true });
                $(document).trigger('reveal.facebox').trigger('afterReveal.facebox');
                $.facebox.state = "open";
            }
        },

        close: function() {
            $(document).trigger('close.facebox');
            return false;
        }
    })

    /*
    * Public, $.fn methods
    */

    $.fn.facebox = function(settings) {
        if ($(this).length == 0) return;
        init(settings);

        function clickHandler() {
            $.facebox.loading(this);

            // support for rel="facebox.inline_popup" syntax, to add a class
            // also supports deprecated "facebox[.inline_popup]" syntax
            var klass = this.rel.match(/facebox\[?\.(\w+)\]?/);
            if (klass) klass = klass[1];
            fillFaceboxFromHref(this.href, klass);
            return false;
        }

        return this.bind('click.facebox', clickHandler);
    }

    /*
    * Private methods
    */

    // called one time to setup facebox on this page
    function init(settings) {
        if ($.facebox.settings.inited) return true;
        else $.facebox.settings.inited = true;

        $(document).trigger('init.facebox');
        makeCompatible();

        var imageTypes = $.facebox.settings.imageTypes.join('|')
        $.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i')

        if (settings) $.extend($.facebox.settings, settings)

        $('body').append($.facebox.settings.faceboxHtml);
        //$('#aspnetForm').append($.facebox.settings.faceboxHtml)


        var preload = [new Image(), new Image()];
        //preload[0].src = $.facebox.settings.closeImage;
        preload[0].src = $.facebox.settings.loadingImage;

        $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
            if (this.style.backgroundImage) {
                preload.push(new Image());
                preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1');
            }
        });

        $(window).resize(function(e) {
            $('#facebox').centerInClient({ left: false, top: true });
        })
        .scroll(function(e) {
            var isScrollLeft = false;
            var isScrollTop = false;

            if ($(window).width() > $('#facebox').width()) {
                isScrollLeft = true;
            }

            if ($(window).height() > $('#facebox').height()) {
                isScrollTop = true;
            }

            if (isScrollLeft || isScrollTop) {
                $('#facebox').centerInClient({ left: isScrollLeft, top: isScrollTop });
            }
        });

        $('#facebox .close').click($.facebox.close);
        //$('#facebox .close_image').attr('src', $.facebox.settings.closeImage);
    }

    // Backwards compatibility
    function makeCompatible() {
        var $s = $.facebox.settings

        $s.loadingImage = $s.loading_image || $s.loadingImage
        //$s.closeImage = $s.close_image || $s.closeImage
        $s.imageTypes = $s.image_types || $s.imageTypes
        $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
    }

    // Figures out what you want to display and displays it
    // formats are:
    //     div: #id
    //   image: blah.extension
    //    ajax: anything else
    function fillFaceboxFromHref(href, klass) {
        // div
        if ((typeof (href) == "string" && href.match(/#/)) || typeof (href) == "object") {
            var target = href;
            if (typeof (href) == "string") {
                var url = location.href.split('#')[0]
                target = href.replace(url, '');
            }
            //$.facebox.reveal($(target).clone(), klass);
            $.facebox.reveal($(target), klass);

            // image
        } else if (href.match($.facebox.settings.imageTypesRegexp)) {
            fillFaceboxFromImage(href, klass)
            // ajax
        } else {

            var queryString = href.replace(/^[^\?]+\??/, '');

            //force iframe to load from server
            if (href.indexOf("?") < 0) {
                href += "?";
            }
            else {
                href += "&";
            }
            href += "t=" + new Date().getTime();

            var params = fb_parseQuery(queryString);
            $('#facebox .content').append("<iframe frameborder='0' scrolling='no' hspace='0' src='" + href + "' id='iframeContent' name='iframeContent" + Math.round(Math.random() * 1000) + "' onload='$.facebox.reveal($(\"#iframeContent\"));'  style='width:" + params['width'] + "px;height:" + params['height'] + "px;'> </iframe>");
        } /*
        else {
            fillFaceboxFromAjax(href, klass)
        }*/
    }


    function fillFaceboxFromImage(href, klass) {
        var image = new Image()
        image.onload = function() {
            var height = image.height > 500 ? 500 : image.height;
            $.facebox.reveal('<div class="image" style="height: ' + height + 'px;"><img src="' + image.src + '" style="height: ' + height + 'px;"/></div>', klass)
        }
        image.src = href
    }



    function fillFaceboxFromAjax(href, klass) {
        $.get(href, function(data) { $.facebox.reveal(data, klass) })
    }

    function skipOverlay() {
        return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
    }

    function showOverlay() {
        if (skipOverlay()) return

        if ($('#facebox_overlay').length == 0)
            $(document.body).append('<div id="facebox_overlay" class="facebox_hide"></div>')

        $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() {
          if (!$.facebox.settings.isModal)
              $(document).trigger('close.facebox')
          //window.location.reload() // sf reloads window, but need to link it to the form button for comments
      })
      .fadeIn(200)
        return false;
    }

    function hideOverlay() {
        if (skipOverlay()) return

        $('#facebox_overlay').fadeOut(200, function() {
            $("#facebox_overlay").removeClass("facebox_overlayBG")
            $("#facebox_overlay").addClass("facebox_hide")
            $("#facebox_overlay").remove()
        })

        return false
    }




    /*
    * Bindings
    */

    $(document).bind('close.facebox', function() {
        $(document).unbind('keydown.facebox');

        //if (jQuery.browser.msie) {
            $('#facebox').hide();
            var $content = $('#facebox .content');
            $content.removeClass().addClass('content');
            hideOverlay();
            $('#facebox .loading').remove();
            $(document).trigger('afterClose.facebox');
            if ($content.find("iframe").length) {
                $content.empty();
            }
            $.facebox.state = "closed";
        /*}
        else {
            $('#facebox').fadeOut(function() {
                var $content = $('#facebox .content');
                $content.removeClass().addClass('content');
                hideOverlay();
                $('#facebox .loading').remove();
                $(document).trigger('afterClose.facebox');
                if ($content.find("iframe").length) {
                    $content.empty();
                }
                $.facebox.state = "closed";
            });
        }*/
    });



    //    function find_them() {

    //        var descendantOrSelf = jQuery('#facebox .content').find("*").andSelf();

    //        var strUniqueSuffix = 'cloned';

    //        function appendUniqueSuffix(id) {
    //            alert(id);
    //            // Remove suffix of "_" 4-digit-alphanum (if it exists), then append
    //            new suffix
    //            return id.replace(/_[0-9a-z]{4}$/, "") + "_" + strUniqueSuffix;

    //        };

    //        descendantOrSelf.filter("[id]").each(function() {
    //            this.id = appendUniqueSuffix(this.id);
    //            //alert(this.id);
    //        });

    //        descendantOrSelf.filter("label").each(function() {
    //            this.htmlFor = appendUniqueSuffix(this.htmlFor);
    //        });

    //        descendantOrSelf.filter(":input[name]").each(function() {
    //            //if ($ektron.browser.msie){
    //            // Microsoft JScript allows the name to be changed at run time.
    //            // HOWEVER!
    //            // This does not cause the name in the programming model to change
    //            // in the collection of elements, but it does change the name used
    //            // for submitting elements. The NAME attribute cannot be set at run time
    //            // on elements dynamically created with the createElement method.
    //            // To create an element with a name attribute, include the attribute
    //            // and value when using the createElement method.
    //            /*var strHTML = this.outerHTML + "";
    //            strHTML = strHTML.replace(new RegExp("name=" + this.name, "g"),
    //            "name=" + appendUniqueSuffix(this.name));
    //            $ektron(this).replaceWith(strHTML);*/
    //            //} else {
    //            this.name = appendUniqueSuffix(this.name);
    //            //}
    //        });

    //    }

})(jQuery);

$.fn.centerInClient = function(options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
        container: window,    // selector of element to center in
        completeHandler: null,
        left: true
        , top: true
    };
    $.extend(opt, options);

    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        if (x < 0)
            x = 0;

        if (y < 0)
            y = 0 + heightFudge;

        if (opt.left)
            el.css("left", x + jWin.scrollLeft());
        if (opt.top)
            el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
};
$.facebox.showFaceboxLoading = function(aWindow, data, loadUrl) {
    aWindow = aWindow || window;

    var width = 0;
    var height = 0;

    if (data && data.href) {
        var queryString = "";
        var href = decodeURIComponent(data.href);
        queryString = href.replace(/^[^\?]+\??/, '');
        var params = fb_parseQuery(queryString);
        width = parseInt(params.width, 10);
        height = parseInt(params.height, 10);
    }

    if ($.facebox.state != "open") {
        $.facebox({});
    }
    var $body = aWindow.$('#facebox .body');

    if (!width && !height) {
        width = $body.outerWidth();
        height = $body.outerHeight();
    }
    $body.find("#facebox_loading").remove();
    $content = aWindow.$('#facebox .content');

    if (data) {
        if (data.href) {
            if (loadUrl) {
                $content.empty();
                aWindow.$.facebox({ href: data.href });
            }
            $body.children().hide();
            $body.append('<div id="facebox_loading" class="loading" style="width:' + width + 'px;height:' + height + 'px;"><img src="' + aWindow.$.facebox.settings.loadingImage + '" style="position:relative; top:' + (height / 2 - 24) + 'px;" alt=""/></div>');
        }
        else {
            $body.children().show();
            $content.children().hide();
            if (data.div) {
                $content.append(data.div);
            }
            else {
                $content.append(data);
            }
        }
    }
    else {
        $body.children().hide();
        $body.append('<div id="facebox_loading" class="loading" style="width:' + width + 'px;height:' + height + 'px;"><img src="' + aWindow.$.facebox.settings.loadingImage + '" style="position:relative; top:' + (height / 2 - 24) + 'px;" alt=""/></div>');
    }
    aWindow.$('#facebox').centerInClient({ left: false, top: true });
};
$.facebox.hideFaceboxLoading = function(aWindow) {
    aWindow = aWindow || window;
    var $body = aWindow.$('#facebox .body');
    $body.find("#facebox_loading").remove();
    $body.children().css({ display: "block", visibility: "hidden" }).fadeIn('normal');
    $body.children().fadeIn('normal');
    aWindow.$('#facebox').centerInClient({ left: false, top: true });
};
