(function(window, $) {
  'use strict';

  // ensure Kalamba global is available
  window.Kalamba = window.Kalamba || {};

  var executehandler = function(eventType, eventData) {
    if (eventType === "loadStart") {

      GameFunctions.actionLoadStart();

      var keepalive = (QueryString.keepalive ? ~~(QueryString.keepalive) : 0);
      var keepaliveUrl = QueryString.keepaliveUrl;

      if (keepalive > 0) {
          window.setInterval(function() {
              $.get(keepaliveUrl, function() { });
          }, keepalive);
      }
    }

    if (eventType === "loadEnd") {
      GameFunctions.gameLoaded(eventData);

      
      window.Kalamba.GUI.showHistory = function(source) {
        GameFunctions.eventHistory();
      }
          }

    if (eventType === "close") {
      GameFunctions.gameClose();
    }

    if (eventType === "balance") {
      if (window.parent) {
        window.parent.postMessage({ message: "balance", param: eventData.balanceInCoins }, "*");
      }
      window.top.postMessage({ wpgaction: "balance", param: eventData.balanceInCoins }, '*');
      window.parent.postMessage({ wpgaction: "balance.parent", param: eventData.balanceInCoins }, '*');
    }

    if (eventType === "gameSpinStart") {
      window.top.postMessage({ wpgaction: "gameSpinStart" }, '*');
      window.parent.postMessage({ wpgaction: "gameSpinStart.parent" }, '*');
    }

    if (eventType === "gameSpinEnd") {
      window.top.postMessage({ wpgaction: "gameSpinEnd" }, '*');
      window.parent.postMessage({ wpgaction: "gameSpinEnd.parent" }, '*');
    }

    if (eventType === "bet") {
      
    }

    if (eventType === "gameUi") {
      
    }


    if (eventType === "quickDeposit") {
      //if (window.parent && window.parent==window.top && window.parent.postMessage) {
      if (inIframe()) {
        window.parent.postMessage({ message: "cashier", param: null}, "*");
        window.top.postMessage({ wpgaction: "cashier" }, '*');
        window.parent.postMessage({ wpgaction: "cashier.parent" }, '*');

      } else {
        if (QueryString.cashierUrl !== undefined) {
          window.location = QueryString.cashierUrl;
        }
      }
    }
  }

  var QueryString = (function() {
    var query_string = {};
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=');
      pair[0] = decodeURIComponent((pair[0] + '').replace(/\+/g, '%20'));
      pair[1] = decodeURIComponent((pair[1] + '').replace(/\+/g, '%20'));
      if (typeof query_string[pair[0]] === 'undefined') {
        query_string[pair[0]] = pair[1];
      } else if (typeof query_string[pair[0]] === 'string') {
        var arr = [query_string[pair[0]], pair[1]];
        query_string[pair[0]] = arr;
      } else {
        query_string[pair[0]].push(pair[1]);
      }
    }
    return query_string;
  })();
    var inIframe = function() {
      try {
        return window.self !== window.top;
      } catch (e) {
        return true;
      }
    };

  var GameFunctions = {};

  GameFunctions.actionLoadStart = function() {
    window.top.postMessage({ wpgaction: "loadStart" }, '*');
    window.parent.postMessage({ wpgaction: "loadStart.parent" }, '*')
  };
  GameFunctions.gameLoaded = function() {
    var gc = QueryString.gameCode;
    var gametitle = 'Kalamba';
    try {
      switch (gc) {
        case 'KLM_AOD':
        case 'KLMM_AOD':
		gametitle = "Age of Dragons";
		break;
        case 'KLM_AOD_ICE':
        case 'KLMM_AOD_ICE':
		gametitle = "Age of Ice Dragons";
		break;
        case 'KLM_ATT':
        case 'KLMM_ATT':
		gametitle = "Atlantis Thunder";
		break;
        case 'KLM_ATT_STP':
        case 'KLMM_ATT_STP':
		gametitle = "Atlantis Thunder: St Patrick's Day Edition";
		break;
        case 'KLM_BDR':
        case 'KLMM_BDR':
		gametitle = "Bangkok Dreams";
		break;
        case 'KLM_BME':
        case 'KLMM_BME':
		gametitle = "Blood Moon Express";
		break;
        case 'KLM_BRD':
        case 'KLMM_BRD':
		gametitle = "Burning Diamonds";
		break;
        case 'KLM_DEG':
        case 'KLMM_DEG':
		gametitle = "Desert Gem";
		break;
        case 'KLM_DIS':
        case 'KLMM_DIS':
		gametitle = "Dino Odyssey";
		break;
        case 'KLM_DOJ':
        case 'KLMM_DOJ':
		gametitle = "Double Joker";
		break;
        case 'KLM_FRE':
        case 'KLMM_FRE':
		gametitle = "Fire Eagle";
		break;
        case 'KLM_BAB':
        case 'KLMM_BAB':
		gametitle = "Gates of Babylon";
		break;
        case 'KLM_GFS':
        case 'KLMM_GFS':
		gametitle = "Goldfire 7s";
		break;
        case 'KLM_GRQ':
        case 'KLMM_GRQ':
		gametitle = "Griffin's Quest";
		break;
        case 'KLM_J36':
        case 'KLMM_J36':
		gametitle = "Joker 3600";
		break;
        case 'KLM_JOS':
        case 'KLMM_JOS':
		gametitle = "Joker Supreme";
		break;
        case 'KLM_JOS_CE':
        case 'KLMM_JOS_CE':
		gametitle = "Joker Supreme X-Mas Edition";
		break;
        case 'KLM_JMX':
        case 'KLMM_JMX':
		gametitle = "Joker Max";
		break;
        case 'KLM_MAC':
        case 'KLMM_MAC':
		gametitle = "Mammoth Chase";
		break;
        case 'KLM_MAC_EE':
        case 'KLMM_MAC_EE':
		gametitle = "Mammoth Chase Easter Edition";
		break;
        case 'KLM_MGA':
        case 'KLMM_MGA':
		gametitle = "Mermaids Galore";
		break;
        case 'KLM_MBW':
        case 'KLMM_MBW':
		gametitle = "Miami Bonus Wheel";
		break;
        case 'KLM_MOG':
        case 'KLMM_MOG':
		gametitle = "Monkey God";
		break;
        case 'KLM_RUH':
        case 'KLMM_RUH':
		gametitle = "Ruby Hunter";
		break;
        case 'KLM_SKH':
        case 'KLMM_SKH':
		gametitle = "Sky Hunters";
		break;
        case 'KLM_TOH':
        case 'KLMM_TOH':
		gametitle = "Temple of Heroes";
		break;
        case 'KLM_TGC':
        case 'KLMM_TGC':
		gametitle = "Tiger Claws";
		break;
        case 'KLM_TRG':
        case 'KLMM_TRG':
		gametitle = "Tree of Gold";
		break;
        case 'KLM_WIC':
        case 'KLMM_WIC':
		gametitle = "WildCraft";
		break;
        case 'KLM_WMI':
        case 'KLMM_WMI':
		gametitle = "Wild Mine";
		break;
      }
    } catch (e) {
    }
    window.top.postMessage({ wpgaction: "loadEnd", param: { gameTitle: gametitle} }, '*');
    window.parent.postMessage({ wpgaction: "loadEnd.parent", param: { gameTitle: gametitle} }, '*');

  };

  GameFunctions.gameClose = function() {

        
    if (QueryString.isGameBridge === 'true') {
	window.parent.postMessage({ message: "close", param: null}, "*");
	window.top.postMessage({ wpgaction: "close" }, '*');
	window.parent.postMessage({ wpgaction: "close.parent" }, '*');
    } else if (QueryString.lobbyUrl !== undefined && QueryString.lobbyUrl != 'LOBBY_URL' && QueryString.lobbyUrl != 'DUMMY' && QueryString.lobbyUrl != 'OFF' && QueryString.lobbyUrl != 'WCLOSE') {
        if (QueryString.lobbyUrlTarget==='TOP') {
                window.top.location = QueryString.lobbyUrl;
        } else {
                window.location = QueryString.lobbyUrl;
        }
    } else if (QueryString.lobbyUrl !== undefined && QueryString.lobbyUrl == 'WCLOSE') {
      window.close();
    } else if (inIframe()) {
      //if (window.parent && window.parent==window.top && window.parent.postMessage) {
      window.parent.postMessage({ message: "close", param: null}, "*");
      window.top.postMessage({ wpgaction: "close" }, '*');
      window.parent.postMessage({ wpgaction: "close.parent" }, '*');
    } else {
      window.history.back();
    }
  };

  GameFunctions.eventHistory = function() {
    if (QueryString.historyUrl !== undefined && QueryString.historyUrl!==false) {
        if (QueryString.historyUrl == "EVENT" || QueryString.historyUrl == "GAMEBRIDGE") {
            window.top.postMessage({ wpgaction: "openGameHistory" }, '*');
            window.parent.postMessage({ wpgaction: "openGameHistory.parent" }, '*');
        } else {
            window.open(QueryString.historyUrl, "gamehistory", "scrollbars=1,height=600,width=760");
        }
    }
  }


  // External handler implementation:
  window.Kalamba.ExternalHandler = function ExternalHandlerFactory(configuration) {
    var actions = [];

    // register action handlers (badge -> game calls)
    var handleAction = function handleAction(actionType, actionData) {
      // buffer actions in queue until game client is capable of handling them
      actions.push({ actionData: actionData, actionType: actionType });
    };

    // register event handlers (game -> badge calls)
    var handler = function handler(eventType, eventData) {
      return executehandler(eventType, eventData);
    };

    handler.handleAction = handleAction;
    handler.actions = actions;

    return handler;
  };



})(window, $);
