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){
            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));
            }
            
            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('');
            }
            
            api = $(id).overlay(params);
            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();
        }
    };
})();

(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','survey','sweepstakes']) > -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];
                
                //hack for hiding mobile
                if($.inArray(type,['ecard','flash','invite','survey','sweepstakes']) > -1){
                    $('#appKindsDialog').addClass('hideMobile');
                } else {
                    $('#appKindsDialog').removeClass('hideMobile');
                }
                
                //hack for hiding social
                if($.inArray(type,['loco']) > -1) {
                    wb.dialog.hide();
                    bootWizard(type,'mobile');
                    return;
                }
                
                wb.dialog.show('#appKindsDialog', {
                    onClose: function() {
                        var result = wb.dialog.getResult();
                        if (!result) return;
                        bootWizard(type, result.kind);
                    }
                });
            });
            $('.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();
            }
            
            wb.dialog.show('#tabListDialog');
        }
    };
    
    
    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});
    });
});
