if(!window.wb) wb = {};

// ok, what is the idea behind this? 
// note: this is modelled after really old api, I would prefer to have more "instance based" api without global state
// the changes were requested in https://www.pivotaltracker.com/story/show/3081181
//
// dialog is just a prepared <div id="myDialog"/> with display:none, put whatever you want into it (see dialog.php for some inspiration)
//
// you have two basic calls:
// wb.dialog.show('#myDialog') will show it
// wb.dialog.hide({ some:"results here"}); will hide it with optional parameters
//
// show method can take optional hash with overlay parameters, consult: http://flowplayer.org/tools/overlay.html
// probably the most useful is reading results in onClose like this
// wb.dialog.show('#myDialog', {
//   onClose: function() {
//       var result = wb.dialog.getResult();
//       // do something with result here, null means cancel
//   }
// }); 
//
// and of course having some code which triggers dialog close with some result:
// wb.dialog.hide(clickedEl.attr('name'));
//
// there are also some auxiliary functions like showLoadingIndicator/showErrorMessage/etc. those are legacy and should be removed IMHO
//
wb.dialog = (function(){
    var api; // last used overlay's api
    var result; // last result set during dialog hide()

    return {
        show: function(id, opts, continuation){
            var overlay;
            opts = opts || {};
            var onClose = function() {
                $('.dialog_loading').fadeOut();
                if (!opts.close) {
                    //                    overlay.find('.close').remove();
                } else {
                    // what to do here? should I remove custom close?
                    console.error('dialog.js HACK FIXME!');
                }
                if (opts.onClose) opts.onClose.apply(this, $.makeArray(arguments));
                if(continuation){
                    continuation();
                }
            }

            var params = $.extend(true, {
                oneInstance: true, 
                expose: {
                    color: '#CCCCCC',
                    closeSpeed: 0
                },
                effect: 'default',
                closeOnClick: false,
                closeOnEsc: false,
                speed: 0,
                closeSpeed: 0
            }, opts, {
                api: true,
                onClose: onClose
            });

            result = null;

            //if login
            if(id == '#login'){
                $('#loginEmail, #loginPassword, #createAccount_email, #createAccount_password, #createAccount_confirmPassword').val('');
            }

            var jId = $(id);
            api = jId.data('overlay');
            if (!api) {
                jId.overlay(params);
                api = jId.data('overlay');
            }
            api.load();

            overlay = api.getOverlay();
            overlay.find('input:first').focus(); // TODO: remove this a hack, caller should handle this in his onLoad routine
        },

        // dialog has ability to return result of the dialog as a first param of onResult callback, null means cancel
        getResult: function() {
            return result;
        },

        setResult: function(res) {
            result = res;
        },

        // dialog code may close itself with the result
        hide: function(res) {
            result = res; // just cache the result
            $('.dialog_loading').fadeOut();
            api.close();
        },

        showLoadingIndicator: function(id) {
            $(id).find('.dialog_loading').fadeIn();
            this.hideErrorMessage(id);
        },

        hideLoadingIndicator: function(id) {
            $(id).find('.dialog_loading').fadeOut();
        },

        showErrorMessage: function(id, msg) {
            $(id).find('.error_message').show().html(msg);
        },

        showSuccessMessage: function(id, msg) {
            $(id).find('.success_message').show().html(msg);
        },

        hideErrorMessage: function(id) {
            $(id).find('.error_message').hide();
        },

        // Create a dialog box with the given ID and HTML:
        createDialog: function(id, html){        
            var contentDiv = $("#"+id);
            var dialogDiv = $("#"+id+"-dialog");
            if(contentDiv.length == 0){
                dialogDiv = $("<div />").attr("id", id+"-dialog").addClass("wb-dialog").css("display","none");
                contentDiv = $("<div />").attr("id", id).addClass("wb-dialog-content");
                contentDiv.html(html);
                dialogDiv.append(contentDiv);
                $(document.body).append(dialogDiv);
                dialogDiv.append($("<div />").addClass("close"));                
            } else {
                contentDiv.html(html);
            }                
            return dialogDiv;
        }              
    };
})();

(function(){

    // app names are here: https://github.com/transpond/wizard/tree/master/public/fixtures
    function bootWizard(demoAppName, appKind) {
        // Stop apps from being created that are mobile
        if($.inArray(demoAppName,['ecard','flash','invite']) > -1 && appKind == 'mobile') {
            return false;
        }

        document.location = "/wizard/?boot="+demoAppName+"&kind="+appKind;
    }

    wb.tabList = {
        init: function(){
            var that = this;
            this.submit = $('.btn_add-this-tab', '#tabListDialog');
            this.submit.click(function(){
                wb.dialog.hide();
                var type = this.id.split('_')[1];
                wb.wizard.initNewTab(type, '', function() {
                    // wb.wizard.updateTabs();
                    // wb.wizard.schedulePageModelUpdate(wb.wizard.currentPageId, false, true, true);
                });
            });
            $('.btn_add-this-app', '#tabListDialog').click(function(){
                var type = this.id.split('_')[1];
                document.location = "/wizard/?boot=" + type + "&kind=social";
            });
            $('.appIcon', '#tabListDialog').click(function() {
                $(this).siblings('span.btn_add-this-tab').click();
            });
        },
        show: function(mode){
            if (!mode) mode = 'tab';

            //resize
            var windowHeight = parseInt($(window).height(), 10);
            var wrap = $('#tabListDialog');
            wrap.attr('class', mode+'-mode');
            var h = parseInt(windowHeight * 0.8, 10);
            wrap.css('height', h + 'px');
            wrap.find('.tabList_apps').css('height', (h - 100) + 'px');

            // hide app only features in tab mode
            if (mode == "tab") {
                wrap.find(".appOnly").hide();
            }

            if (wb && wb.wizard && wb.wizard.model.uiState.kind == "mobile") {
                wrap.find(".socialOnly").hide();
            }
            if (wb && wb.wizard && wb.wizard.model.uiState.kind == "social") {
                wrap.find(".mobileOnly").hide();
            }
            wb.dialog.show('#tabListDialog');

            // Lets make the lines only on the last 2
            wrap.find(".appList").each(function(){
                var liElements = $(this).find("li:visible");
                liElements.removeClass("last");
                var liElementCount = liElements.length;
                $(liElements.get(liElementCount-1)).addClass("last");
                if (liElementCount%2 == 0) {
                    $(liElements.get(liElementCount-2)).addClass("last");
                }
            });


        }
    };


    wb.platformsDialog = {
        setDisabledView: function(name) {
            var dialog = $('#appPlatformsDialog');
            dialog.find('input[name='+name+']').attr('disabled', 'disabled');
        },
        val: function(data) {
            var dialog = $('#appPlatformsDialog');
            dialog.find('input').removeAttr('disabled');
            if (data) {
                // write state
                dialog.find('.kindBoxOption input').attr('checked', null);
                for (prop in data) {
                    if (data[prop]) {
                        dialog.find('.kindBoxOption input[name='+prop+']').attr('checked', 'checked');
                    }
                }
            } else {
                // read state
                var res = {};
                dialog.find('.kindBoxOption input').each(function() {
                    var input = $(this);
                    var name = input.attr('name');
                    var val = input.attr('checked');
                    res[name] = !!val;
                    //if facebook, include newsfeed
                    res['facebook_newsfeed'] = res['facebook_canvas'];
                });

                return res;
            }
        }
    };

})();    

$(function(){
    wb.tabList.init();

    // init appKindsDialog
    $('#appKindsDialog .kindBox').bind('click', function() {
        var box = $(this);
        var kind = box.attr('kind');
        wb.dialog.hide({kind: kind});
    });

    $('#appPlatformsDialog').find('.btn_finished').click(function(){
        wb.dialog.hide({finished: true});
    });
});

wb.dialog.options = function(options){
    var default_options = { 
        autoOpen: false, 
        dialogClass:'framed', 
        modal:true, 
        open: function(){ 
            $('.ui-widget-overlay').hide().fadeIn();
        }, 
        show: "fade", 
        hide: "fade" 
    };    
    return $.extend(default_options, options);
}

// push-down notifacation dialog:
wb.dialog.notify = function(message, type, duration, onClose, parent){
    var notificationBoxes = $("#notificationBoxes:visible");
    if(!notificationBoxes.length){
        notificationBoxes.die().remove();
        notificationBoxes = $("<div />", {id:"notificationBoxes"});  
        var mainContainer = $(".notificationBoxes:visible");                      // prepared area for notifications
        if(parent){
            mainContainer = parent;
        }
        if(mainContainer.length == 0){   mainContainer = $("#content");          }// site pages
        if(mainContainer.length == 0){   mainContainer = $("#main_container");   } // wizard
        //if(mainContainer.length == 0){   mainContainer = $("#main");   }  // pre-login pages
        if(!mainContainer.hasClass("notificationBoxes")){
            var tree = $(".navTree");
            if(tree.length){
                if(mainContainer.find("div.rightContainer:visible").length){
                    mainContainer = mainContainer.find("div.rightContainer:visible");
                } else {
                    notificationBoxes.css("marginLeft", tree.width());
                }
            }
        }
        mainContainer.prepend(notificationBoxes);
    }
    var notification = $("<div />").addClass("notificationBox")
    if(typeof type != "undefined" && type){
        notification.addClass(type);
    }
    notification.append($("<div />").addClass("close").click(function(e){
        $(e.target).parent().hide();
        if($("#notificationBoxes div:visible").length == 0){
            $("#notificationBoxes").hide();
        };
        if(onClose){
            onClose();
        }
    }).html("X"));
    if(typeof(message) == "String"){
        notification.append($("<div />").addClass("content").html(message));
    } else {
        notification.append($("<div />").addClass("content").append(message));
    }
    notificationBoxes.append(notification);
    notificationBoxes.append($("<div />").addClass("clear"));
    notificationBoxes.show();
    if(typeof duration != "undefined" && duration){
        clearTimeout(wb.dialog._notifyFadeout);
        wb.dialog._notifyFadeout = setTimeout(function(){$("#notificationBoxes").fadeOut('slow', function(){ $("#notificationBoxes").hide(); })}, duration);
        setTimeout(function(){notification.fadeOut('slow', function(){ notification.hide(); })}, duration);        
    }
}

wb.dialog.firebugWarning = function(){
    if (window.console && (window.console.firebug !== undefined) && $.cookie && !$.cookie("hideFirebugWarning") && $("#notificationBoxes .firebug:visible").length == 0) {
        var div = $("<div />");
        div.html('Firebug is known to make Webtrends Social slow unless it is <a target="#">configured correctly</a>. ').find("a").click(function(){
            $("<div />").html("For faster performance, we suggest disabling Firebug for "+String(location.host)+"<br /><br />You can find instructions for the most recent version of Firebug at the <a href='http://getfirebug.com/wiki/index.php/Main_Page' target='_blank' >Firebug documentation site</a>.<br/><br/>If disabling Firebug for Webtrends Social doesn't improve performance results, you may have to entirely disable Firebug.").wbdialog({title:"Firebug can make Webtrends Social slow",width:700,autoOpen:true,buttons:{Okay:function(){($(this).dialog("close"));}}});
        });
        wb.dialog.notify(div,"error firebug",0, function(){ $.cookie("hideFirebugWarning", true); });
    }
}

wb.dialog.msieWarning = function(){
    // still use the firebug class, should never encounter both of these at once.
    if (($.browser.msie) && $.cookie && !$.cookie("hideMSIEWarning") && $("#notificationBoxes .firebug:visible").length == 0) {
        var div = $("<div />");
        div.html('You are currently using Internet Explorer without chromeframe installed. For faster performance, <a target="#">install the chromeframe plugin</a>. ').find("a").click(function(){
            if(typeof CFInstall != "undefined"){
                CFInstall.check({
                        mode: "overlay",
                        destination: window.location.href
                });
            } else {
                window.location = "http://www.google.com/chromeframe/eula.html?user=true";
            }
        });
        wb.dialog.notify(div,"error firebug",0, function(){ $.cookie("hideMSIEWarning", true); });
    }
}
// wrap all of our default options and fade in for the overlay into this.
$.fn.wbdialog = function(param) {
    if(typeof param == "string"){
        return this.dialog(param);
    } else {
        var default_options = { 
            autoOpen: false, 
            dialogClass:'', 
            modal:true, 
            open: function(){ 
                $('.ui-widget-overlay').hide().fadeIn();
            }, 
            show: "fade", 
            hide: "fade" 
        };  
        default_options.show = false;
        default_options.hide = false;
        default_options.open = false; // Fix for wizard

        options = default_options;
        options.dialogClass += " dialog_framed";
        if(typeof param == "object"){
            if(param.title){
                options.dialogClass += " dialog_titled";
            }              
            if(param.buttons){
                options.dialogClass += " dialog_buttons";
            }
            options = $.extend(default_options, param);  
        }
        if(typeof param == "boolean"){
            options.autoOpen = param;
        }
        return this.dialog(options); 
    }
};



