// Set is app. Needed to start as application as app.
isApp = true;

serverBaseUrl = "https://www.pozzy.nl";
if (getUrlVars()["debug"] == "true") {
  serverBaseUrl = "http://pozzy";
}

var pushNotification;
autoloadRankings = false;
autoloadRankingsPersonal = false;

var navHistory = ["map"];

$('#gettingStartedNickname').keyup(function (e) {
  $('#nickname').val($('#gettingStartedNickname').val());
});

$(GLOBAL).bind("appStart", function () {
  cordova.plugins.notification.badge.clear();
  $("#rankingsMagellan").hide();
});

$(GLOBAL).bind("checkinDone", function () {
  consoleLog("checkinDone event captured: vibrate");
  navigator.notification.vibrate(200);
});

$(GLOBAL).bind("loadingDone showError", function () {
  console.log("enable controls");
  $('#conquerControlsLoader').hide();
  $('#conquerControls').show();
  // Close getting started modal if eventually we loaded settings.
  var revealId = $(revealModal).attr("id");
  if (typeof (revealId) != undefined && revealId != null && revealId == "gettingStartedModal") {
    if ((localStorage["#male"] != null && localStorage["#male"].length > 0) ||
      (localStorage["#female"] != null && localStorage["#female"].length > 0)) {
      closeRevealModal();
    }
  }

  /**
   * Push notifications
   */
  registerPushNotifications();
});

function selectMenu(menu) {
  if (menu == "settings") {
    if (navHistory.indexOf("settings") != -1) {
      navHistory.splice(navHistory.indexOf("settings"), 1);
    }
    navHistory.push("settings");
    $("#mapContainer").hide();
    $("#settingsContainer").show();
    $("#faqContainer").hide();
    $("#rankingsContainer").hide();
    $("#rankingsMagellan").hide();
  } else if (menu == "faq") {
    if (navHistory.indexOf("faq") != -1) {
      navHistory.splice(navHistory.indexOf("faq"), 1);
    }
    navHistory.push("faq");
    $("#mapContainer").hide();
    $("#settingsContainer").hide();
    $("#faqContainer").show();
    $("#rankingsContainer").hide();
    $("#rankingsMagellan").hide();
  } else if (menu == "map") {
    // Reset to map.
    navHistory = new Array();
    navHistory.push("map");
    $("#mapContainer").show();
    $("#settingsContainer").hide();
    $("#faqContainer").hide();
    $("#rankingsContainer").hide();
    $("#rankingsMagellan").hide();
    $(".sub-nav").hide();
  } else if (menu == "rankings") {
    if (navHistory.indexOf("rankings") != -1) {
      navHistory.splice(navHistory.indexOf("rankings"), 1);
    }
    navHistory.push("rankings");
    $("#mapContainer").hide();
    $("#settingsContainer").hide();
    $("#faqContainer").hide();
    $("#rankingsContainer").show();
    $("#rankingsMagellan").show();

    getPointsMenVsWomen();
    getRankings("getRankingsAllUsers", null, processRanking);
    getRankings("getRankingsAllMen", null, processRanking);
    getRankings("getRankingsAllWomen", null, processRanking);
    getRankings("getRankingsTitles", "PlacesConquered", processTitles);
    getRankings("getRankingsConquestAll", "PlacesConquered", processRanking);
    getRankings("getRankingsConquestMen", "PlacesConquered", processRanking);
    getRankings("getRankingsConquestWomen", "PlacesConquered", processRanking);
    getRankings("getRankingsCheckinAll", "CheckinCount", processRanking);
    getRankings("getRankingsCheckinMen", "CheckinCount", processRanking);
    getRankings("getRankingsCheckinWomen", "CheckinCount", processRanking);

    getCheckins("getCheckins", "Show more trails!");
    getCheckins("getConquests", "Show more conquests!");
  }
}

/**
 * Override default logout function.
 */
function logout() {
  $(".pointsTotal").html("");
  localStorage.clear();
  $(GLOBAL).trigger("isLoggedOut");
  gettingStarted();
  // Uncheck the gender options to mimic a fresh start.
  $("#male").prop("checked", false);
  $("#female").prop("checked", false);
  $(GLOBAL).trigger("appStart");
}

document.addEventListener('deviceready', function () {
  consoleLog("deviceready");

  /**
   * Google Analytics SDK.
   */
  var platform = device.platform.toString().toLowerCase();
  consoleLog("Platform: " + platform);
  if (platform == 'android') {
    analytics.startTrackerWithId('UA-46299521-7');
    analytics.trackView(window.location.href);
  }
  if (platform == "ios") {
    StatusBar.overlaysWebView(false)
    StatusBar.hide();
  }

  /**
   * Add fastclick.
   */
  FastClick.attach(document.body);

  /**
   * Hide splash screen.
   */
  navigator.splashscreen.hide();

  /**
   * Update WP8 LiveTile
   */
  updateLiveTile();

  /**
   * Check if gettingStarted modal should be shown.
   */
  gettingStarted();

  /**
   * Start the app.
   */
  console.log(platform + " trigger appStart event");
  $(GLOBAL).trigger("appStart");

}, false);

/**
 * Override default back button behaviour.
 */
document.addEventListener('backbutton', handleBackButton, false);

/**
 * Register push notifications.
 */
var pushRegistered = false;
function registerPushNotifications() {
  if (pushRegistered === false &&
    window.plugins != null &&
    window.plugins.pushNotification != null) {
    pushNotification = window.plugins.pushNotification;
    var platform = device.platform.toString().toLowerCase();
    if (platform == 'android') {
      pushNotification.register(androidSuccessHandler, pushErrorHandler, { "senderID": "701902199774", "ecb": "onNotificationGCM" });
    } else if (platform == 'ios') {
      pushNotification.register(iOsTokenHandler, pushErrorHandler, { "badge": "true", "sound": "true", "alert": "true", "ecb": "onNotificationAPN" });
    } else if (platform == 'wince' || platform == 'win32nt') {
      pushNotification.register(wp8SuccessHandler, pushErrorHandler, { "channelName": "pozzy", "ecb": "onNotificationEcb" });
    } else if (platform == 'firefoxos') {
      consoleLog("Register FirefoxOS push notification service");
      navigator.mozSetMessageHandler("push", function (message) {
        consoleLog("push notification endpoint: " + message.pushEndpoint);
        consoleLog("push notification: " + message.version);
        var notification = navigator.mozNotification.createNotification("Pozzy", "An event has occurred");
        notification.show();
      });
      navigator.mozSetMessageHandler("push-register", function () {
        registerPushNotifications();
      });
      var req = navigator.push.register();
      req.onsuccess = function () {
        consoleLog("Register FirefoxOS push channel success");
        var endpoint = req.result;
        // send uri to notification server
        consoleLog('FireFoxOS push registered: ' + endpoint);
        pushRegistered = true;
        setPushChannel("pozzy", endpoint);
      }
      req.onerror = function (e) {
        consoleLog("FireFoxOS push register error: " + JSON.stringify(e))
      }
    }
  }
}


function gettingStarted() {
  /**
   * If neither #male or #female is set.
   */
  var revealId = $(revealModal).attr("id");
  if ((localStorage["#male"] == null || localStorage["#male"].length == 0)
    && (localStorage["#female"] == null || localStorage["#female"].length == 0)) {
    revealDialog("#gettingStartedModal");
  } else if (typeof (revealId) != undefined && revealId != null && revealId == "gettingStartedModal") {
    closeRevealModal();
  }
}

function updateLiveTile() {
  if (typeof(device) != "undefined" &&
    (device.platform.toString().toLowerCase() == "wince" ||
    device.platform.toString().toLowerCase() == "win32nt")) {
    var femalePercentage = "51.2";
    var malePercentage = "48.8";
    if (localStorage["femalePercentage"] != null) {
      femalePercentage = parseFloat(localStorage["femalePercentage"]).toFixed(0);
      malePercentage = parseFloat(localStorage["malePercentage"]).toFixed(0);
    }
    // Update the applications live tile
    LiveTiles.updateAppTile(tileSuccess, tileFail, {
      title: 'Pozzy',
      image: 'www/img/logo336x336.png',
      count: 0,
      backTitle: 'Men vs. Women',
      backContent: 'Men ' + malePercentage + '% vs Women ' + femalePercentage + '%',
      //backImage: 'www/img/logo336x336.png',
      smallImage: 'www/img/logo159x159.png',
      wideImage: 'www/img/logo336x336.png',
      wideBackImage: 'www/img/logo672x336.png'
    });
  }
}

/**
 * WP8
 */
function wp8SuccessHandler(result) {
  // send uri to notification server
  consoleLog('push registered: ' + JSON.stringify(result));
  pushRegistered = true;
  setPushChannel(result.channel, result.uri);
}

/**
 * Android
 */
function androidSuccessHandler(result) {
  consoleLog('push registered: ' + result);
  pushRegistered = true;
}

/**
 * iOS
 */
function iOsTokenHandler(result) {
  console.log('push registered, device token: ' + result);
  pushRegistered = true;
  setPushChannel("pozzy", result);
}

// result contains any error description text returned from the plugin call
function pushErrorHandler(error) {
  console.log('push error: ' + error);
}

// WP8
function onNotificationEcb(e) {
  navigator.notification.alert(e.text2, function () { }, e.text1);
}

// iOS
function onNotificationAPN(event) {
  if (event.alert) {
    navigator.notification.alert(event.alert);
  }

  if (event.sound) {
    var snd = new Media(event.sound);
    snd.play();
  }

  if (event.badge) {
    pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
  }
}

// Android
function onNotificationGCM(e) {
  consoleLog("Push event received: " + e.event);

  switch (e.event) {
    case 'registered':
      if (e.regid.length > 0) {
        consoleLog("Push event registered, regID: " + e.regid);
        // Your GCM push server needs to know the regID before it can push to this device
        // here is where you might want to send it the regID for later use.
        setPushChannel("pozzy", e.regid);
      }
      break;

    case 'message':
      // if this flag is set, this notification happened while we were in the foreground.
      // you might want to play a sound to get the user's attention, throw up a dialog, etc.
      if (e.foreground) {
        consoleLog("Inline push notification");

        // if the notification contains a soundname, play it.
        // var my_media = new Media("/android_asset/www/" + e.soundname);
        // my_media.play();
      }
      else {  // otherwise we were launched because the user touched a notification in the notification tray.
        if (e.coldstart) {
          consoleLog("Coldstart push notification");
        }
        else {
          consoleLog("Background push notification");
        }
      }

      navigator.notification.alert(e.payload.message, function () { });
      break;

    case 'error':
      consoleLog("Push notification error:" + e.msg);
      break;

    default:
      consoleLog("Push notification error: Unknown, an event was received and we do not know what it is");
      break;
  }
}

function tileSuccess(e) {
  consoleLog('tile was updated: ' + e);
}

function tileFail(e) {
  consoleLog('tile update failed: ' + e);
}

/**
 * Register push notification channel on notifications server.
 */
function setPushChannel(channel, token) {
  console.log("setPushChannel called: [" + channel + "] " + token);
  $(GLOBAL).trigger("setPushChannel");

  ajaxCall("/api/v1/setPushChannel.php", {
    uuid: localStorage["uniqueId"],
    device: device.platform,
    model: device.model,
    channel: channel,
    token: token
  }).fail(function (data) {
    consoleLog("setPushChannel error: " + JSON.stringify(data));
  }).done(function (data) {
    if (data.response != undefined) {
      if (data.response.responseCode == 200) {
        consoleLog("setPushChannel succeeded: " + JSON.stringify(data));
      } else {
        consoleLog("setPushChannel responsCode error: " + JSON.stringify(data));
      }
    } else {
      consoleLog("setPushChannel error unexpected response: " + JSON.stringify(data));
    }
  }).always(function () {
    consoleLog("setPushChannelDone fired");
    $(GLOBAL).trigger("setPushChannelDone");
  });
}

/**
 * Remove account override
 */
function removeAccount(redirect, forced) {
  var r = forced;
  if (forced !== true) {
    r = window.confirm($("#i18RemoveAccountPromptDescription").html());
  }
  if (r) {
    if (hasLocalStorage()) {
      consoleLog("Remove account fired");
      $(GLOBAL).trigger("removeAccount");

      ajaxCall("/api/v1/removeAccount.php", {
        uuid: localStorage["uniqueId"], password: $("#removeAccountPassword").val()
      }).fail(function (data) {
        consoleLog("removeAccount error: " + data.toString());
      }).done(function (data) {
        if (data.response != undefined) {
          switch (data.response.responseCode) {
            case 200:
              consoleLog("removeAccount succeeded: " + data.response.responseCode + ": " + data.response.message);
              localStorage.clear();
              if (redirect) {
                window.location = "index.html";
              }
              break;
            case 401:
              revealMessageDialog($("#i18AccountRemovalFailedLabel").html(), $("#i18AccountRemovalFailedDescription").html());
              break;
            case 404:
            case 412:
              revealMessageDialog($("#i18NoAccountLabel").html(), $("#i18NoAccountDescription").html());
              break;
            default:
              consoleLog("removeAccount error: " + data.response.responseCode + ": " + data.response.message);
              break;
          }
        } else {
          consoleLog("removeAccount error unexpected response: " + data);
        }
      }).always(function () {
        consoleLog("removeAccountDone fired");
        $(GLOBAL).trigger("removeAccountDone");
      });
    }
  }
}


/**
 * WP8 handle hardware back button.
 */
function handleBackButton() {
  /**
   * When reveal modal exists.
   */
  if (typeof (revealModal) != "undefined" && revealModal != null) {
    var revealId = $(revealModal).attr("id");
    if (typeof(revealId) != undefined && revealId != null && revealId != "gettingStartedModal") {
      closeRevealModal();
    } else {
      if (device.platform != "Android" && navigator.app && typeof (navigator.app.exitApp) != undefined && confirm("Exit Pozzy?")) {
        navigator.app.exitApp();
      }
      if (device.platform == "Android") {
        navigator.Backbutton.goHome(function () {
          console.log('success')
        }, function () {
          console.log('fail')
        });
      }
    }
  } else if ($(".offcanvas-overlap-right, .offcanvas-overlap-left").length > 0) {
    $(".off-canvas-wrap").removeClass("offcanvas-overlap-right offcanvas-overlap-left");
  } else if (navHistory.length > 1) {
    // Remove current page.
    navHistory.pop();
    // Goto previous page.
    selectMenu(navHistory.pop());
  } else if (navHistory[navHistory.length - 1] == "map" && navHistory.length <= 1) {
    // Exit app.
    if (navigator.app && typeof (navigator.app.exitApp) != undefined) {
      if (device.platform != "Android" && confirm("Exit Pozzy?")) {
        navigator.app.exitApp();
      }
    }
    if (device.platform == "Android") {
      navigator.Backbutton.goHome(function () {
        console.log('success')
      }, function () {
        console.log('fail')
      });
    }
  } else {
    // Reset to map.
    navHistory = new Array();
    selectMenu("map");
  }
}