var currentScreenName = "";
var pe = null;

var bannerController = {
    initialize: function() {
        this.bindEvents();
    },

    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.addEventListener('BannerLoaded', this.handleBannerLoaded, false);
        document.addEventListener('BannerLoadFailed', this.handleBannerLoadFailed, false);
    },

    onDeviceReady: function() {
        console.log('device is ready!');

        pe = window.plugins.pokktExtension;
    },

    handleBannerLoaded: function(params) {
        
        pe.showLog("params: " + params);
        
        var object = JSON.parse(params.param);
        
        var screenName = object.SCREEN_NAME;
        
        if (object.SCREEN_NAME != currentScreenName)
            return;
        
        console.log(" banner loaded for " + screenName);
        
        
        document.getElementById('labelStatus').innerHTML = "Banner Loaded!";
        document.addEventListener("backbutton", onBackKeyDown, false);
        function onBackKeyDown(e) {
            console.log("destroy banner for " + currentScreenName);
            pe.destroyBanner(currentScreenName);
            document.removeEventListener("backbutton", onBackKeyDown);
        }
    },

    handleBannerLoadFailed: function(params) {

        pe.showLog("params: " + params);
        
        var object = JSON.parse(params.param);
        
        var screenName = object.SCREEN_NAME;

        
        if (object.SCREEN_NAME != currentScreenName)
            return;
        
        console.log(" banner load failed for "+ screenName + "! message: " + object.ERROR_MESSAGE);
        
        
        document.getElementById('labelStatus').innerHTML = "Banner Load Failed!";
    },

    onClickLoadBanner: function() {
        var screenName = document.getElementById('editscreenname').value;
        currentScreenName = screenName;
        document.getElementById('labelScreenName').innerHTML = currentScreenName;
        pe.loadBanner(screenName);
    },

    onClickBack: function() {
        history.back();
        pe.destroyBanner(currentScreenName);
        document.removeEventListener("backbutton", onBackKeyDown);
    },

    onClickDestroyBanner: function() {
        pe.destroyBanner(currentScreenName);
        document.removeEventListener("backbutton", onBackKeyDown);
    },
};
