// Global object for JQuery reference purposes.
var GLOBAL = {};

// Default locale will be overridden
var locale = "en_US";

var serverBaseUrl = "";

var isApp = false;

// Set footer copyright year.
var thisYear = new Date().getFullYear();
$("#thisYear").html(" - " + thisYear);

$(document).ready(function () {
  // When not the pozzy app.
  if (isApp === false) {
    consoleLog("webtrigger appStart event");
    $(GLOBAL).trigger("appStart");
  }
  checkGenderMenuItems();
  timerEvent();
});

// Turn random text into a color. Usage: intToARGB(hashCode("YOUR TEXT"));
// Usage 2: argbToRGB(hashCode("YOUR TEXT"));
function hashCode(str) { // java String#hashCode
  var hash = 0;
  for (var i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  return hash;
}

/**
 * Check if given fields are not empty.
 * This is an AND compare, so when one of the given input fields as argument
 * is empty this function will return false.
 * Only when all the given fields are not empty will this function return true.
 * And if no arguments are given then this function will always return true.
 */
function notEmpty() {
  var result = true;
  for (var i = 0; i < arguments.length; i++) {
    if ($(arguments[i]).val().length == 0) {
      $(arguments[i]).focus();
      result = false;
      break;
    }
  }
  return result;
}

function htmlEncode(value) {
  return String(value)
          .replace(/&/g, '&amp;')
          .replace(/"/g, '&quot;')
          .replace(/'/g, '&#39;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;');
}

function htmlDecode(value) {
  return $('<div/>').html(value).text();
}

/**
 * Get cookie value by name.
 */
function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i].trim();
    if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
  }
  return null;
}

/**
 * Set cookie
 */
function setCookie(c_name, value, expiredays, path) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toUTCString()) + "; path=" + path + ";";
}

/**
 * Social button locale detection.
 */
if (localStorage["locale"] != null) {
  locale = localStorage["locale"];
  if(locale == "pirate") {
    locale = "en_US";
  }
  $(".twitter-follow-button").attr("data-lang", locale);
  window.___gcfg = { lang: locale };
} else if (getCookie("locale") != null && getCookie("locale").length > 0) {
  locale = getCookie("locale");
  if (locale == "pirate") {
    locale = "en_US";
  }
  $(".twitter-follow-button").attr("data-lang", locale);
  window.___gcfg = { lang: locale };
}

function intToARGB(i) {
  return ((i >> 24) & 0xFF).toString(16) +
         ((i >> 16) & 0xFF).toString(16) +
         ((i >> 8) & 0xFF).toString(16) +
         (i & 0xFF).toString(16);
}

function argbToRGB(color) {
  return ('000000' + (color & 0xFFFFFF).toString(16)).slice(-6);
}

// Reveal Modal handles.
var revealFunctionStack = [];
var revealModal;

$(document).on('click', '.reveal-modal-bg', function () {
  if ($(".reveal-modal").is(":visible") === false) {
    $(this).hide();
  }
});

$(document).on('open open.fndtn.reveal', '[data-reveal]', function () {
  revealModal = $(this);
  consoleLog("Reveal Modal open");
});

$(document).on('opend opened.fndtn.reveal', '[data-reveal]', function () {
  revealModal = $(this);
  consoleLog("Reveal Modal opened");
});

$(document).on('close close.fndtn.reveal', '[data-reveal]', function () {
  revealModal = $(this);
  consoleLog("Reveal Modal close");
  $('.off-canvas-wrap').css("min-height", "auto");
  $(".canDis").show();
});

$(document).on('closed closed.fndtn.reveal', '[data-reveal]', function () {
  revealModal = null;
  /**
   * Call every function 
   */
  while (revealFunctionStack.length > 0) {
    var f = revealFunctionStack.shift();
    f();
    consoleLog("Reveal closed, revealFunctionStack called");
  }
});

/**
 * Add extra height to page to offset the possible soft-keyboard of mobile devices.
 */
$("input:text").focus(function () {
  console.log("show mobileKeyboardPlaceholder");
  $('.off-canvas-wrap').css("min-height", ($('.off-canvas-wrap').height() + 600) + "px");
})
$("input:text").blur(function () {
  console.log("hide mobileKeyboardPlaceholder");
  $('.off-canvas-wrap').css("min-height", ($('.off-canvas-wrap').height() - 600) + "px");
})

/**
 * Utility function for toggeling to show more or less text.
 */
function readmore(buttonSelector, textSelector) {
  $(textSelector).slideToggle();
  $(buttonSelector).text($(buttonSelector).text() == $("#i18ReadMoreLabel").html() ? $("#i18ShowLessLabel").html() : $("#i18ReadMoreLabel").html());
}

/**
 * Set the timezone.
 */
function setTimezone(timezone) {
  consoleLog(timezone);
  $.ajax({
    dataType: "json",
    url: serverBaseUrl + "/api/v1/setTimezone.php",
    cache: true,
    type: "POST",
    data: {
      timezone: timezone
    },
    error: function (data) {
      consoleLog("Set timezone error: " + JSON.stringify(data));
    },
    success: function (data) {
      consoleLog("Set timezone success: " + JSON.stringify(data));
    }
  });
}

function consoleLog(message) {
  if (getUrlVars()["debug"] == "true" || 1 == 1) {
    var d = new Date();
    console.log(d.toLocaleTimeString() + " - " + message);
  }
}

function betaAndroidAppConfirm() {
  return confirm($("#i18BetaAndroidAppLabel").html());
}

/**
 * Check if gender is already known. In case it's known we shall change our menu structure.
 */
function checkGenderMenuItems() {
  if (localStorage["#female"] == "checked" || localStorage["#male"] == "checked") {
    $(".maleEntrance").hide();
    $(".femaleEntrance").hide();
    $(".allGenderEntrance").show();
  }
}

/**
 * Get array of url parameters.
 */
function getUrlVars() {
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
  function (m, key, value) {
    vars[key] = value;
  });
  return vars;
}

/**
 * Close reveal dialog.
 */
function closeRevealModal() {
  if (revealModal != null) {
    revealModal.foundation('reveal', 'close');
  }
}


/**
 * Reveal dialog.
 */
function revealDialog(selector) {
  consoleLog("Hide all .canDis elements prior to Reveal Modal.");
  $('.off-canvas-wrap').css("min-height", $('.off-canvas-wrap').height() + "px");
  $('.canDis').hide();

  $(selector).foundation('reveal', 'open');
}

/**
 * Show message dialog with given title and message.
 */
function revealMessageDialog(title, message) {
  consoleLog("Hide all .canDis elements prior to Reveal Modal.");
  $('.off-canvas-wrap').css("min-height", $('.off-canvas-wrap').height() + "px");
  $('.canDis').hide();

  $("#messageModalTitle").html(title);
  $("#messageModalMessage").html(message);
  $("#messageModal").foundation('reveal', 'open');
}

function revealProcessingDialog() {
  revealMessageDialog($("#i18ProcessingLabel").html(), $("#i18ProcessingDescription").html());
}

/**
 * Check if localStorage is available.
 */
function hasLocalStorage() {
  if (localStorage != null) {
    return true;
  }
  else {
    alert($("#i18NoLocalStorageDescription").html());
    return false;
  }
}

function checkStringLength(theString, maxLength) {
  var result = theString;
  if (theString != null && theString.length > maxLength) {
    result = theString.substring(0, (maxLength - 3)) + "...";
  }
  return result;
}

function joyRideStart() {
    $(document).foundation('joyride', 'start');
}

function generateUniqueId(thisCallback) {
  /**
   * If uniqueId isn't set we retrieve one from the remote API.
   */
  consoleLog("getUniqueId fired");
  $(GLOBAL).trigger("getUniqueId");

  ajaxCall("/api/v1/getUniqueId.php", {}).fail(function (data) {
    consoleLog("getUniqueId error: " + JSON.stringify(data));
  }).done(function (data) {
    if (data.response != undefined) {
      if (data.response.responseCode == 200) {
        if (data.response.value != undefined) {
          if (data.response.value.uuid != undefined) {
            if (data.response.value.id != undefined) {
              localStorage["uniqueId"] = data.response.value.uuid;
              localStorage["id"] = data.response.value.id;
              consoleLog(data.response.responseCode + ": " + data.response.message);
              var qrUrl = window.location.protocol + "//" + window.location.host + "/?qr=" + localStorage["id"];
              $("#qrImage").attr("src", "/api/v1/getQrImage.php?id=" + localStorage["id"]);
              $("#fb-qr").attr("data-href", qrUrl);
              $("#tw-qr").attr("data-url", qrUrl);
              $("#qrUrl").val(qrUrl);
              if (typeof (fbStart) != "undefined") fbStart();
              if (typeof (twitterStart) != "undefined") twitterStart();
              if (typeof (gplusStart) != "undefined") gplusStart();
              $("#connect-wrapper").show();
              $(GLOBAL).trigger("getUniqueIdSuccess");
              consoleLog("getUniqueId: " + data.response.responseCode + ":" + data.response.message + " : " + JSON.stringify(data));
              if (thisCallback != null) {
                thisCallback();
              }
            } else {
              consoleLog("getUniqueId id error: " + data.response.responseCode + ":" + data.response.message + " : " + data);
            }
          } else {
            consoleLog("getUniqueId uuid error: " + data.response.responseCode + ":" + data.response.message + " : " + data);
          }
        } else {
          consoleLog("getUniqueId value error: " + data.response.responseCode + ":" + data.response.message + " : " + data);
        }
      } else {
        consoleLog("getUniqueId responsCode error: " + data.response.responseCode + ":" + data.response.message + " : " + data);
      }
    } else {
      consoleLog("getUniqueId error unexpected response: " + data);
    }
  }).always(function () {
    // Trigger event.
    consoleLog("getUniqueIdDone fired");
    $(GLOBAL).trigger("getUniqueIdDone");
  });
}

function checkCooldown() {
  consoleLog("checkCooldown fired");
  $(GLOBAL).trigger('checkCooldown');
  ajaxCall("/api/v1/getCooldown.php", {
    uuid: localStorage["uniqueId"]
  }).fail(function(data) {
    consoleLog("checkCooldown error: " + JSON.stringify(data));
  }).done(function(data) {
    if (data.response != undefined) {
      if (data.response.responseCode == 200) {
        if (data.response.value != undefined) {
          countdownCooldown(data.response.value);
        } else {
          consoleLog("getCooldown value error: " + data.response.responseCode + ":" + data.response.message + " : " + data);
        }
      } else {
        consoleLog("getCooldown responsCode error: " + data.response.responseCode + ":" + data.response.message + " : " + data);
      }
    } else {
      consoleLog("getCooldown error unexpected response: " + data);
    }
  }).always(function() {
    // Trigger event.
    consoleLog("checkCooldownDone fired");
    $(GLOBAL).trigger('checkCooldownDone');
  });
}

function ajaxCall(uri, data) {
  return $.ajax({
    dataType: "json",
    url: serverBaseUrl + uri,
    type: "POST",
    cache: false,
    data: data
  });
}

var cdTimestampStart;
var cdTimestampEnd;
function countdownCooldown(cooldownSeconds) {
  if (cooldownSeconds != null) {
    cdTimestampStart = new Date().getTime();
    cdTimestampEnd = cdTimestampStart + (cooldownSeconds*1000);
  }

  if(cdTimestampStart < cdTimestampEnd) {
    setTimeout("countdownCooldown()", 1000);
    cdTimestampStart = new Date().getTime();
    var secondsLeft = Math.round(((cdTimestampEnd - cdTimestampStart) / 1000));
    var minutes = Math.floor(secondsLeft / 60);
    var seconds = secondsLeft % 60;
    $(".cooldownTimer").html(minutes + "m " + ("0" + seconds).slice (-2) + "s");
  } else {
    $(".cooldownTimer").html("");
  }
}

var eventTimestampStart = new Date().getTime();
var eventTimestampEnd = eventTimestampStart + (60000);
function timerEvent() {
  eventTimestampStart = new Date().getTime();
  if (eventTimestampStart < eventTimestampEnd) {
    setTimeout("timerEvent()", 1000);
  } else {
    eventTimestampStart = new Date().getTime();
    eventTimestampEnd = eventTimestampStart + (60000);
    setTimeout("timerEvent()", 1000);
    $(GLOBAL).trigger("timeEvent");
  }
}

$(".main-section").on("click", function () {
  $('.off-canvas-wrap').removeClass('offcanvas-overlap-left offcanvas-overlap-right');
});