ning.loader.require('ning.hooks.*', 'ning.Bar', 'ning.social', 'trimpath.template');

(function(){

var oldAllowPanelAddition = ning.hooks.bar.allowPanelAddition;
ning.hooks.bar.allowPanelAddition = function(args) {
    // VID-622 [ David Sklar 2006-09-18 ]
    if (args.name == 'clone') {
        if (ning.CurrentProfile) {
            args.label = 'Get Your Own Videos Site!';
        } else if (! args.customClonePanel) {
            return false;
        }
    }
    // VID-621 [ David Sklar 2006-09-18 ]
    if (args.name == 'people') {
        return false;
    }
    // VID-617 [ David Sklar 2006-09-18 ]
    if (args.name == 'explore') {
        return false;
    }
    // VID-730 [Jon Aquino 2006-10-11]
    if (args.name == 'manage') {
        return false;
    }
    if (args.name == 'invite') {
        return showInviteButton;
    }
    if (oldAllowPanelAddition) {
        return oldAllowPanelAddition(args);
    } else {
        return true;
    }
}

/* @videos-domain-suffix-start */
var templateVariables = {
    app: ning.CurrentApp,
    videosUrl: ning.CurrentApp.url,
    groupUrl: 'http://group.ning.com/',
    photosUrl: 'http://photos.ning.com/',
    signInSignUpPath: 'index.php/main/index/sign',
    allSitesUrl: 'http://browse.ning.com/application/any'
};
/* @videos-domain-suffix-end */

var oldAllowBrandPanelAddition = ning.hooks.bar.allowBrandPanelAddition;
ning.hooks.bar.allowBrandPanelAddition = function(args) {
    args.open = function(div, panelWidget) {
        dojo.io.bind({
            url: "/xn/rest/1.0/profile:" + ning.CurrentApp.owner,
            mimetype: "text/json",
            encoding: "utf-8",
            preventCache: true,
            load: function(type, data, evt) {
                templateVariables.owner = data.profile;
                dojo.io.bind({
                        url: '/widgets/video/templates/_shared/brand.jst',
                        mimetype: "text/plain",
                        encoding: "utf-8",
                        load: function(type, data, evt) {
                            div.innerHTML =TrimPath.parseTemplate(data).process(templateVariables);

                            setTimeout(function() {
                                dojo.event.connect(dojo.byId("report_this_anchor"), "onclick", function(evt) {
                                    dojo.event.browser.stopEvent(evt);
                                    ning.social.reportThisApp(panelWidget);
                                });
                                dojo.event.connect(dojo.byId("owner_name_anchor"), "onclick", function(evt) {
                                    ning.hooks.viewProfile(ning.CurrentApp.owner, evt);
                                });
                                dojo.event.connect(dojo.byId("owner_send_message"), "onclick", function(evt) {
                                    dojo.event.browser.stopEvent(evt);
                                    ning.social.openSendMessageBox(panelWidget, ning.CurrentApp.owner);
                                });
                            }, 0); /* setTimeout() */
                        } /* template load() */
                }); /* template bind() */
            }, /* profile load() */
            sync: true,
            preventCache: true
        }); /* profile bind() */
    }; /* args.open function */

    if (oldAllowBrandPanelAddition) {
        return oldAllowBrandPanelAddition(args);
    } else {
        return true;
    }
}; /* allowBrandPanelAddition */

ning.Bar.whenLoaded( function() {
    if (! ning.CurrentProfile) {

        templateVariables.signInSignUpTarget = encodeURIComponent(templateVariables.videosUrl + '?xn_panel=clone');

        ning.Bar.addPanel( {
            name: "clone",
            label: "Get Your Own Videos Site!",
            order: 500,
            cache: true,
            customClonePanel: true, /* so that allowPanelAddition will let this one through */
            open: function(div) {
                dojo.io.bind({
                        url: '/widgets/video/templates/_shared/clone.jst',
                        mimetype: "text/plain",
                        encoding: "utf-8",
                        load: function(type, data, evt) {
                            div.innerHTML =TrimPath.parseTemplate(data).process(templateVariables);
                        }
                });
            }
        } ); /* addPanel() */
    } /* signed out? */
}); /* whenLoaded() */

}());

dojo.provide('xn.widget.video');

xn.widget.video = dojo.lang.mixin(xn.widget.video, {

    /**
     * Fixes two problems with img tags in IE:
     * <ul>
     *     <li>png transparency doesn't work</li>
     *     <li>img tags created with Javascript sometimes fail to display if they aren't preloaded</li>
     * </ul>
     *
     * @param imgs array of image tags, typically found using node.getElementsByTagName('img')
     * @param sync whether to fix the image synchronously or asynchronously i.e. whether it is more important to display the image
     *         as soon as possible (as in the case of the app header image) or to allow processing to continue (important when preloading
     *         all of the images of a panel -- you want the panel to appear ASAP, and the images can be filled in afterwards).
     *         Setting sync to true reduces the duration of the flash of opaque in the app header icon for some reason (from 1 second to instantaneous).
     * @param width optional. Used if img.width is 0, which sometimes happens
     * @param height optional. Used if img.height is 0, which sometimes happens
     * @see Guyon Roche, "JavaScript Image Preloader", http://www.webreference.com/programming/javascript/gr/column3/
     */
    fixImagesInIE: function(imgs, sync, width, height) {
        if (! (dojo.render.html.ie50 || dojo.render.html.ie55 || dojo.render.html.ie60)) { return; }
        dojo.lang.forEach(imgs, function(img) {
            if (dojo.lang.inArray(xn.widget.video.fixedImageURLs, img.src)) { return; }
            var fixImage = function() {
                var image = new Image();
                image.onload = image.onerror = image.onabort = function() {
                    img.src = img.src;
                    xn.widget.video.fixTransparencyInIEProper(img, width, height);
                    xn.widget.video.fixedImageURLs.push(img.src);
                }
                image.src = img.src;
            }
            if (sync) { fixImage(); }
            else { dojo.lang.setTimeout(fixImage, 0); }
        });
    },

    fixedImageURLs: [],

    /**
     * Consider fixImagesInIE instead of using this function directly; fixImagesInIE takes care of both
     * preloading images loaded with javascript and fixing transparency.
     *
     * img.width and img.height are sometimes 0 for some reason. If this happens, you can specify the
     * width and height explicitly.
     * @see fixImagesInIE
     */
    fixTransparencyInIEProper: function(img, width, height) {
        if (img && (dojo.render.html.ie50 || dojo.render.html.ie55 || dojo.render.html.ie60) && img.src.match(/png/) && dojo.style.isShowing(img)) {
            // The header image is sometimes distorted in IE (half-loaded, or incorrectly sized).
            // Preloading (as is done with fixImagesInIE) probably fixes this, but it also delays the image
            // from appearing for a couple of seconds. [Jon Aquino 2006-05-31]
            width = width ? width : img.width;
            height = height ? height : img.height;
            img.style.width = width + "px";
            img.style.height = height + "px";
            img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img.src + "', sizingMethod='scale')";
            img.src = "/xn/static/ningbar/css/gfx/shared/x.gif";
        }
        if (img) { img.style.visibility = 'visible'; }
    },

    fixTransparencyInIE: function(node) {
        if (dojo.render.html.ie50 || dojo.render.html.ie55 || dojo.render.html.ie60) {
            dojo.lang.forEach(node.getElementsByTagName('img'), function(img) {
                xn.widget.video.fixTransparencyInIEProper(img);
            });
        }
    }

});

dojo.provide('xn.widget.video');

/**
 * Returns an object that will execute the callback when its trigger() method is called, but only after a
 * given "quiescent period" in which trigger() is not called. Useful for triggering an expensive event; it will
 * run only after the triggers quiet down.
 */
xn.widget.video.createQuiescenceTimer = function(milliseconds, callback) {
    var lastTriggerId = 0;
    return {
        trigger : function() {
            lastTriggerId++;
            var triggerId = lastTriggerId;
            window.setTimeout(function() {
                if (triggerId == lastTriggerId) { callback(); }
            }, milliseconds);
        }
    };
};

// Subscribe to event before running initialize.js [Jon Aquino 2006-05-18]
dojo.event.topic.subscribe('/ManagePanel/acceptingSubPanels', function(managePanel) {
    dojo.provide('xn.widget.video.privacy');
    dojo.setModulePrefix("xn.widget.video.privacy", "../../../../js/privacy");
    dojo.require('xn.widget.video.privacy.VideoPrivacyPanel');
    managePanel.addSubPanel('Privacy & Members', function() {
         return dojo.widget.createWidget('VideoPrivacyPanel');
    });
    dojo.dom.insertBefore(dojo.dom.removeNode(snazzy.managePanel.tabTextToListItemMapping['Appearance']), snazzy.managePanel.tabTextToListItemMapping['Privacy & Members']);
    if (! snazzy.ManagePanelHelper.configValues.configured) {
        var cancelSetupLi = dojo.html.createNodesFromText('<li class="cancel-setup" style="visibility:hidden"><a href="#">Skip this step &ndash; I\'ll invite people later.</a></li>')[0];
        dojo.event.connect(snazzy.DomHelper.findTag('a', cancelSetupLi), 'onclick', function(event) {
            dojo.event.browser.stopEvent(event);
            snazzy.managePanel.subPanelValuesChanged = false;
            ning.Bar.close();
        });
        dojo.dom.insertAtPosition(cancelSetupLi, snazzy.DomHelper.find('xn_bar_stepnav', snazzy.managePanel).getElementsByTagName('ul')[0], 'first');
        snazzy.DomHelper.find('xn_bar_stepnav', snazzy.managePanel)
        dojo.event.connect(snazzy.managePanel, 'activateTabProper', dojo.lang.hitch(this, function() {
            // cancel2 will no longer be present anyway after Ning 4.3  [Jon Aquino 2006-10-21]
            if (snazzy.managePanel.button('cancel2')) { dojo.style.hide(snazzy.managePanel.button('cancel2')); }
            if (snazzy.managePanel.button('cancel')) { dojo.style.hide(snazzy.managePanel.button('cancel')); }
            if (snazzy.managePanel.button('next') && dojo.style.isShowing(snazzy.managePanel.button('next')) && snazzy.managePanel.button('gotoapp')) {
                dojo.style.hide(snazzy.managePanel.button('gotoapp'));
                dojo.style.setVisibility(cancelSetupLi, false);
            } else {
                dojo.style.setVisibility(cancelSetupLi, true);
            }
            var position = function(input) {
                input.style.paddingLeft = input.style.paddingRight = '30px';
            }
            if (snazzy.managePanel.button('next')) { position(snazzy.managePanel.button('next')); }
            if (snazzy.managePanel.button('gotoapp')) { position(snazzy.managePanel.button('gotoapp')); }
        }));
        dojo.event.connect(snazzy.managePanel, 'afterOpen', dojo.lang.hitch(this, function() {
            dojo.style.hide(dojo.byId('xn_bar_panel_hide'));
        }));
        // App is blank while Get Your Own panel is open (VID-751) [Jon Aquino 2006-10-27]
        snazzy.managePanel.pageRefreshPending = true;
    }
    // Settings is a hidden subpanel that is activated with a link on the Manage panel  [Jon Aquino 2006-10-26]
    dojo.style.hide(snazzy.managePanel.tabTextToListItemMapping['Settings']);
    dojo.event.connect(snazzy.managePanel, 'activateTabProper', dojo.lang.hitch(this, function(tabText) {
        if (tabText == 'Settings') {
            dojo.html.removeClass(snazzy.managePanel.tabTextToListItemMapping['Settings'], 'active');
            dojo.html.addClass(snazzy.managePanel.tabTextToListItemMapping['Manage'], 'active');
        }
    }));
    if (! snazzy.ManagePanelHelper.configValues.configured) {
        snazzy.managePanel.mode.firstActivatedTabText = function() { return 'Appearance'; }
    }
});

(function() {
    dojo.provide('xn.widget.video.appearance');
    dojo.setModulePrefix("xn.widget.video.appearance", "../../../../js/appearance");
    var substituteVideoAppearancePanel = function() {
        dojo.event.topic.subscribe('/ManagePanel/fillingInTemplate', function(managePanel) {
            dojo.event.connect('around', managePanel, 'addSubPanel', dojo.lang.nameAnonFunc(dojo.lang.hitch(this, function(invocation) {
                if (invocation.args[0] == 'Appearance') {
                    invocation.args[1] = function() {
                        dojo.require("xn.widget.video.appearance.VideoAppearancePanel");
                        return dojo.widget.createWidget('VideoAppearancePanel');
                    }
                }
                return invocation.proceed();
            }), dj_global));
          }
        );
    }
    substituteVideoAppearancePanel();
}());