var fl;
if (!fl) {
  fl = {};
}
if (!fl.Util) {
  fl.Util = {};
}
fl.Util.secondsToMinutes = function(seconds) {
    return '' + Math.round(seconds / 60);
};
fl.Util.secondsToMinutesSeconds = function(seconds) {
    var ss = seconds % 60;
    return '' + Math.floor(seconds / 60) + ':' + (ss < 10 ? ('0' + ss) : ss);
};

fl.Util.PreloadImage = function() {
    var i = arguments.length;
    while (i--) {
        (new Image()).src = fl.Init.ImageUri(arguments[i]);
    }
};
fl.Util.UniqueIndex = 0;
fl.Util.GetUniqueIndex = function() {
    return fl.Util.UniqueIndex++;
};
fl.Util.MaybeAssignID = function(el) {
/*    if ("function" != typeof el.attr) { // Temporary
        el = $(el);
    }*/
    if (!el.id()) {
        el.id('_fl_' + fl.Util.UniqueIndex++);
    }
};
fl.Util.IsEmpty = function(str) {
    return !str;
};
fl.Util.Alerted = false;
fl.Util.AlertOnce = function() {
    if (!fl.Util.Alerted) {
        fl.Util.Alerted = true;
    }
};
fl.Util.InitializedCache = {};
// Used to prevent double initialization. Note that this will set the
// element's ID if not already provided
fl.Util.isInitialized = function(prefix, el) {
    //if ("function" != typeof el.attr) { // Temporary
    //    el = $(el);
    //}
    fl.Util.MaybeAssignID(el);
    var key = prefix + el.id();
    if (!fl.Util.InitializedCache[key]) {
        fl.Util.InitializedCache[key] = true;
        return false;
    }
    return true;
};
fl.Util.setSessionCookie = function(name, value) {
    log.setup("cookie","util")("Setting Session Cookie %s=%o", name, value);
    document.cookie = name + "=" + encodeURIComponent(value) + ";path=/";
};
// expires: Number of seconds to keep this cookie. Defaults to 1 year
fl.Util.setPersistentCookie = function(name, value, expires) {
    log.setup("cookie","util")("Setting Persistent Cookie %s=%o", name, value);
    var d = new Date();
    if (expires) {
      d.setTime(d.getTime() + expires*1000);
    } else {
      d.setTime(d.getTime() + 31536000000); //365*24*60*60*1000
    }
    document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + d.toGMTString() + ";path=/";
};
fl.Util.expireCookie = function(name) {
    log.setup("cookie","util")("Expiring Cookie %s", name);
    var d = new Date();
    d.setTime(d.getTime() - 31536000000); //365*24*60*60*1000
    document.cookie = name + "=;expires=" + d.toGMTString() + ";path=/";
};

// Achtung!
// Do not use this for checksummed (hashed) cookies -- use readHashedCookie().
fl.Util.readCookie = function(name, cookieString) {
  log.setup("fl", "util")("Reading Cookie %s",name);
  return fl.Util.parseCookie(new RegExp(";?" + name + "=([^;]*);?"), cookieString);
};
fl.Util.readHashedCookie = function(name, cookieString) {
  log.setup("fl", "util")("Reading Hashed Cookie %s",name);
  return fl.Util.parseCookie(new RegExp(";?" + name + "=[^_;]*_([^;]*);?"), cookieString);
};
fl.Util.parseCookie = function(regexp, cookieString) {
  if (!cookieString) {
    cookieString = document.cookie;
  }

  var matchData = cookieString.match(regexp);

  if (matchData) {
    log("Found cookie").stop();
    return decodeURIComponent(matchData[1].replace(/\+/g, ' '));
  } else {
    log("Did not find cookie").stop();
    return null;
  }
}

fl.Util.writeHashedCookieValue = function(name,key,value,opts) {
  var cookie_data = gg.parse_json(fl.Util.readCookie(name));
  cookie_data[key] = value;
  if ((opts || {}).session === true) {
    fl.Util.setSessionCookie(name,gg.to_json(cookie_data));
  } else {
    fl.Util.setPersistentCookie(name,gg.to_json(cookie_data));
  }
};
fl.Util.readUserId = function() {
  return fl.Util.readHashedCookie('user_id');
};
// First call rewrites this function SetOpacity to the correct one
// based on browser capability.
fl.Util.SetOpacity = function(elOrId, opacity) { // Deprecated TODO: replace with jquery
    var el = $(elOrId);
    if (!el.length) {
      el = $("#" + elOrId);
    }
    el.css("opacity", (opacity / 100) - 0.001);
};
fl.Util.unescapeSlashes = function(s) {
    return(s.replace(fl.Util.unescapeSlashes.regex,'/'));
};
fl.Util.unescapeSlashes.regex = /_slash_/g;
fl.Util.escapeSlashes = function(s) {
    return(s.replace(fl.Util.escapeSlashes.regex,'_slash_'));
};
fl.Util.escapeSlashes.regex = /\//g;

fl.Util.getDialog = function(id, opts) {
  var dialog = $("#" + id);
  if (!dialog.length) {
    dialog = $("<div id='" + id + "'>" + (opts.html || Locale.please_wait_loading_spin) + "</div>");
    dialog.appendTo("body");
  }
  if (!dialog.hasClass("ui-dialog-content")) {
    var close = function() {
      dialog.dialog("close").show();
    };
    dialog.dialog($.extend({
      title: "",
      autoOpen: false,
      modal: true,
      draggable: false,
      height: "auto",
      width: "auto",
      position: ["center", ($.browser.msie && 7 > parseInt($.browser.version)) ? "top" :$("div.a_wrapper").offset().top],
      //position: "center",
      show: "custom", // fake "effect" so it doesn't just vanish.  handling it manually below.
      hide: "custom",
      closeOnEscape: (false !== opts.clickOverlay),
      open: function() {
        if ($.browser.msie && 7 > parseInt($.browser.version)) {
          $("select").filter(function() { return !$(this).closest(".ui-dialog").length; }).hide();
        }
        var ov = dialog.data("dialog").overlay.$el;
        if (false !== opts.clickOverlay) {
          ov.click(close);
        }

        dialog.closest(".ui-dialog")
          .iff("undefined" == typeof opts.show)
            .show("slide", { direction: "up" })
          .others()
            .show();

        ov.css("opacity", 0)
          .fadeTo("fast", opts.overlayOpacity || 0.65);
      },
      beforeclose: function() {
        // close in two passes, have to do this because the overlay is destroyed too quickly otherwise.
        var ov = (dialog.data("dialog") && dialog.data("dialog").overlay.$el);
        if (ov && ov.filter(":visible").length) {
          ov.unbind("click", close)
            .show().fadeOut("fast", function() {
              dialog.dialog("close");
              if (!$(".ui-widget-overlay:visible").length) {
                $("select").show();
                ov.unwrap('.ui-effects-wrapper'); //what about dialog?
              }
            }
          );

          if (opts.hide == undefined) {
            dialog.closest(".ui-dialog")
              .hide("slide", { direction: "up" }, function() {
                $(this).unwrap('.ui-effects-wrapper');
                if (dialog.data("afterClose")) {
                  dialog.data("afterClose")(dialog);
                }
              }
            );
          } else {
            dialog.closest(".ui-dialog").hide();
            if (dialog.data("afterClose")) {
              dialog.data("afterClose")(dialog);
            }
          }
          return false;
        }
      }
    }, opts)).show().prev().find(".ui-dialog-titlebar-close span").text("");
    if (opts.additionalInit) {
      dialog.show();
      opts.additionalInit(dialog);
    }
  } else {
    dialog.dialog("option", opts);
    if (opts.html) {
      dialog.html(opts.html);
      if (opts.additionalInit) {
        opts.additionalInit(dialog);
      }
    }
  }
  if (opts.afterClose) {
    dialog.data("afterClose", opts.afterClose);
  }
  return dialog;
};
fl.Util.persistentCookiesEnabled = function() {
	fl.Util.setPersistentCookie('persistentCheck', 'true');
    var enabled = fl.Util.readCookie('persistentCheck') === 'true';
    fl.Util.expireCookie('persistentCheck');
    return enabled;
};
(function() {
  var watchPollInterval = 1000;
  var watchThread;
  var watches = {};
  var watchHandler = function() {
    for (var cookie in watches) {
      var val = fl.Util.readCookie(cookie);
      if (val != watches[cookie].oldValue) {
        watches[cookie].oldValue = val;
        for (var i = 0; i < watches[cookie].callbacks.length; ++i) {
          watches[cookie].callbacks[i](val);
        }
      }
    }
  };
  fl.Util.watchCookie = function(name, callback) {
    if (!watches[name]) {
      watches[name] = {oldValue: fl.Util.readCookie(name), callbacks: []};
    }
    watches[name].callbacks.push(callback);
    if (!watchThread) {
      watchThread = setInterval(watchHandler, watchPollInterval);
    }
  };
})();

fl.Util.updateCACookie = function(url, callback) {
  if (!fl.Util.readCookie('ca_expiration') && fl.Util.readHashedCookie('guid')) {
    fl.Util.setPersistentCookie('ca_expiration', '1', 3600);
    $.getJSON(url, {user_guid: fl.Util.readHashedCookie("guid")}, function(response) {
      var old_value = fl.Util.readCookie('ca');
      var new_value = response.data.group_id_string_hashed;
      if (new_value) {
        fl.Util.setPersistentCookie("ca", new_value); // 1 hour
      } else {
        fl.Util.expireCookie("ca");
      }
      if (callback) {
        callback(old_value, new_value);
      }
    });
  }
};
