//global
var baseUrl = '/';
var wizardPage = baseUrl + 'wizard';
var appsPage = baseUrl + 'apps.php';

//populate widgetlist
function buildWidgetList(){
    $('#loadingIndicator').show();
    var d = new Date();
    var options = {
        url: '/transponder/app/list',
        data: {
            page: 0,
            count: 1000,
            owner: true
        },
        success: function(json){
            $('#loadingIndicator').hide();
            if (json.success) {
                var table = $('#myAppTable').empty();
                
                $.each(json.data.widgets, function(i, v){
                    // dont even bother displaying legacy apps
                    if(v.builderType != 'express') { return; }
                    
                    var tr = $('<tr/>');
                    var deleteCell =  $('<td/>').addClass('delete').html('X').bind('click', function() {
                        modifyWidget(v, 'delete');
                    });
                    var editCell = $('<td/>').addClass('edit').html('Edit').bind('click', function() {
                        modifyWidget(v, 'edit');
                    });
                    var cloneCell = $('<td/>').addClass('clone').html('Clone').bind('click', function() {
                        modifyWidget(v, 'clone');
                    });
                    var titleCell = $('<td/>').addClass('title').html(v.title || "Untitled");
                    
                    var idCell = '';
                    if (wb.account.getSuperUser()) {
                        idCell = $('<td/>').addClass('id').html(v.id || 0);
                    }
                    
                    var sourceCell1 = '';
                    var sourceCell2 = '';
                    var commercialCell = '';
                    if (wb.account.getSuperUser()) {
                        sourceCell1 = $('<td/>').addClass('source').html('DraftJSON').bind('click', function() {
                            modifyWidget(v, 'source1');
                        });
                        sourceCell2 = $('<td/>').addClass('source').html('ProdJSON').bind('click', function() {
                            modifyWidget(v, 'source2');
                        });
                        commercialCell = $('<td/>').addClass('commercial').html('Commercial').bind('click', function() {
                            modifyWidget(v, 'commercial');
                        });
                    }
                    
                    var publist = 'Not published';
                    if (this.publishedDestinations && this.publishedDestinations.length > 0) {
                        var jpd, x, publishedUrl, platform;
                        publist = [];
                        jpd = this.publishedDestinations;
                        for (x = 0; x < jpd.length; x++) {
                            publishedUrl = jpd[x].url;
                            platform = jpd[x].platform;
                            
                            // Currently we are treating phonegap and android native as the same as web flow
                            if (platform.indexOf("android") > -1) {
                                platform = "android";
                            } else if (platform.indexOf("iphone") > -1) {
                                platform = "iphone";
                            } else if(platform.indexOf("facebook") > -1) {
                                platform = "facebook";
                            }
                            
                            var img = '<img src="' + baseUrl + 'wizard/images/' + platform + '-20' + '.png">';
                            if (publishedUrl) {
                                if (platform == "embed") {
                                    publishedUrl += "standalone";
                                }
                                img = '<a href="' + publishedUrl + '" target="_out">'+img+'</a>';
                            }
                            publist.push(img);
                        }
                        publist = publist.join(' ');
                    }
                    var destinationsCell = $('<td/>').addClass('destinations').append(publist);
                    
                    // pricing cell
                    // var pricing = this.pricing.draft;
                    // if (this.pricing.published && this.pricing.published.price > 0) pricing = this.pricing.published;
                    // var isCommercial = parseInt(this.isCommercial, 10);
                    var paid = parseInt(this.paid, 10);
                    // var hasAds = !(isCommercial || paid>=pricing.price);
                    var paidMarkup = "";
                    if (paid>0) {
                        paidMarkup = '<div class="paidText"></div>';
                    }
                    var subscriptionCell = $('<td/>').addClass('subscription').append(paidMarkup);
                    
                    // var adsMarkup = "";
                    // if (hasAds) {
                    //     if (!paid) {
                    //         adsMarkup = '<div class="adsText" title="ad supported app, update your subscription to remove transpond ads"></div>';
                    //     } else {
                    //         adsMarkup = '<div class="adsText" title="showing ads, the app costs $'+pricing.price+'"></div>';
                    //     }
                    // }
                    // var adsCell = $('<td/>').addClass('adsc').append(adsMarkup);

                    tr.append(idCell, editCell, cloneCell, sourceCell1, sourceCell2, commercialCell, titleCell, subscriptionCell, /*adsCell,*/ destinationsCell, deleteCell);
                    table.append(tr);
                });
            }
        }
    };
    
    wb.util.ajaxCall(options);
}

function deleteWidget(id){
    var options = {
        url: '/transponder/app/delete/'+id,
        success: function(json){
            if (json.success) {
                buildWidgetList();
            }
        }
    };
    wb.util.ajaxCall(options);
}

function editWidget(json){
    if (json.builderType == 'full') {
        window.location.href = 'http://leg.transpond.com/builder?action=edit&widgetId=' + json.id;
    }
    else 
        window.location.href = wizardPage + '?id=' + json.id;
}

function cloneWidget(id){
    var options = {
        url: '/transponder/app/clone/'+id,
        data: {},
        success: function(json){
            buildWidgetList();
        },
        type: 'POST'
    };
    wb.util.ajaxCall(options);
}

function sourceWidget(id, state){
    var options = {
        url: '/transponder/app/load',
        data: {
            id : id,
            state:state
        },
        success: function(response){
            $("#sourceControl").find(".sourceId").val(id);
            $("#sourceControl").find(".sourceCode").val(response.data.widgetJson);
            wb.dialog.saveOp = state?'preview':'publish';
            $('#sourceControl').removeClass('preview').removeClass('publish').addClass(wb.dialog.saveOp);
            wb.dialog.show("#sourceControl", {
                onClose: function() {
                    buildWidgetList();
                }
            });
        },
        type: 'GET'
    };
    wb.util.ajaxCall(options);
}

function toggleCommercial(id){
    var isCommercial = false;
    if (confirm("Do want this app to be commercial?  Cancelling will set this app to non-commercial")) {
        isCommercial = true;
    }
    
    var options = {
        url: '/transponder/app/toggle_commercial',
        data: {
            id : id,
            isCommercial : isCommercial
        },
        type: 'POST'
    };
    wb.util.ajaxCall(options);
}

function modifyWidget(json, action){
    switch (action) {
        case 'delete':
            if (confirm('Delete this App?')) {
                deleteWidget(json.id);
            }
        break;
        case 'edit':
            if (json.builderType != 'express') {
                alert('This app was created in v1 of Transpond.com. While it will still work, we can not guarantee all of its functionality will continue to work. Please recreate the widget in our new express builder at http://www.transpond.com/wizard.');
            }
            editWidget(json);
        break;
        case 'clone':
            cloneWidget(json.id);
        break;
        case 'source1':
            sourceWidget(json.id, 1); // draft
        break;
        case 'source2':
            sourceWidget(json.id, 0); // prod
        break;
        case 'commercial':
            toggleCommercial(json.id);
        break;
    }
}

function init(){
    if (!wb.account.isReallyLoggedIn()) {
        document.location = "/";
        return;
    }
    
    buildWidgetList();
    
    $('#newApp').click(function(){
        wb.tabList.show('app');
    });
}