//========================================================================================================================
// Control panel fields
//========================================================================================================================

function ControlIds(master, nav, content, element, app) {
  this.Master = master;
  this.Nav = nav;
  this.Content = content;
  this.Element = element;
}
var _ControlIds = new ControlIds("", "", "", "");

function AppUrls(webmanager, webmanagers, clients, home, stat) {
  this.WebManager = webmanager;
  this.WebManagerS = webmanagers;
  this.Clients = clients;
  this.Home = home;
  this.Static = stat;
}
var _AppUrls = new AppUrls("", "", "", "", "");
 
var _IsMasterPage = false;
var _NoEdit = false;
var _IsPageLoaded = false;
var _IsFieldChanged = false;
var _IsConfirmedSave = false;
var _KeepLoggedInFailed = 0;
var _DialogPanelType = null;

var _BeforeUnloadWarning =
  "____________________________________________________            \n\n\n" +
  "WARNING:  You have made changes to this form without saving\n" +
  "them.  If you leave this page now, any changes you have made\n" +
  "will be lost.\n\n" +
  "____________________________________________________            \n";

//========================================================================================================================
// Element selectors
//========================================================================================================================

function g(id) { return $("#" + id).get(0); }
function gm(id) { return g(_ControlIds.Master + id); }
function gn(id) { return g(_ControlIds.Nav + id); }
function gc(id) { return g(_ControlIds.Content + id); }
function ge(id) { return g(_ControlIds.Element + id); }

function $m(id) { return $("#" + _ControlIds.Master + id); }
function $n(id) { return $("#" + _ControlIds.Nav + id); }
function $c(id) { return $("#" + _ControlIds.Content + id); }
function $e(id) { return $("#" + _ControlIds.Element + id); }

//========================================================================================================================
// AJAX
//========================================================================================================================

function JsonFormData(sel) {
  var fields = [];
  $(sel + " :text,:password,select,:checked,input[type='hidden']").not("[id^='__'],[id^='btn'],[id='']").each(function () {
    var id = this.id.split("_");
    id = id[id.length - 1];
    fields.push(id, this.value);
  });

  var data = {};
  data.sessionId = _SessionId;
  data.formFields = fields;
  return data;
}

function AjaxPost(url, data, func1, func2) {
  $.ajax({
    type: "POST",
    cache: false,
    url: url,
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
      if (func1) { func1(result.d); }
    },
    error: function (req, status, ex) {
      if (func2) { func2(); }
      if (_Environment != "Production" && req.statusText != "Unknown") {
        UnfreezePage();
        Dialog_Info("Ajax Error", "<div class=\"error\">" + req.statusText + "</div><iframe id=\"frmAjaxError\" style=\"width: 800px; height: 400px; border: 0px;\"></iframe>", true);
        $("#frmAjaxError")[0].contentWindow.document.write(req.responseText);
      }
    }
  });
}

function AjaxForm(title, url, sel, func1, func2) {
  if (title !== null) { FreezePage(title); }
  AjaxPost(url, JsonFormData(sel), func1, func2);
}

function AjaxJson(title, url, data, func1, func2) {
  if (title !== null) { FreezePage(title); }
  if (data === null) { data = {}; }
  data.sessionId = _SessionId;
  AjaxPost(url, data, func1, func2);
}

//========================================================================================================================
// Navigation
//========================================================================================================================

function ReloadPage() {
  _IsConfirmedSave = true;
  window.location.reload(true);
}

function PageLink(page, sid) {
  var pageparts = page.split("?");
  var sessionid = (sid)?sid:_SessionId;
  return _AppUrls.WebManager + page + ((pageparts.length == 1) ? "?" : "&") + _SessionKey + "=" + sessionid;
}

function Go(url) {
  if (url.substring(0,4) != "http") { url = PageLink(url); }
  location.href = url;
}

function HelpCenter(topic) {
  var helpWindow = window.open(PageLink("Support/Default.aspx?T=" + topic), "HelpWindow", "height=500, width=900, location=yes, menubar=yes, resizable=yes, scrollbars=yes, status=yes, toolbar=yes");
  helpWindow.focus();
}

function Logout_Result() {
  Go(_AppUrls.WebManagerS + "Login.aspx");
}

function Logout() {
  HtmlChangedCheck();
  if (IsFieldChanged() && !_IsConfirmedSave && !_NoEdit) {
    Dialog_SmartClick();
    _SmartClickUrl = PageLink("Logout.aspx");
  } else {
    AjaxJson("Logging out...", ((location.protocol == "https:") ? _AppUrls.WebManagerS : _AppUrls.WebManager) + "Services/Security.asmx/Logout", null, Logout_Result);
  }
  return false;
}

function KeepLoggedIn_Error(result) {
  _KeepLoggedInFailed += 1;
  if (_KeepLoggedInFailed >= 4) {
    var content = "Connection lost.";
    if (result) {
      content = result.ErrorMessage;
    }
    Dialog_SetContent(content, true);
    Dialog_Open("Invalid Session", true, { "Close" : function(){ Dialog_Close("KLI_Close"); } });
  } else {
    $("#divKLI > b > span").first().hide().end().eq(_KeepLoggedInFailed).show();
    window.setTimeout("KeepLoggedIn();", 5000);
  }
}

function KeepLoggedIn_Success(result) {
  if (result.Success) {
    _KeepLoggedInFailed = 0;
    $("#divKLI > b > span").hide().first().show();
    window.setTimeout("KeepLoggedIn();", 15000);
  } else {
    KeepLoggedIn_Error(result);
  }
}

function KeepLoggedIn() {
  AjaxJson(null, ((location.protocol == "https:") ? _AppUrls.WebManagerS : _AppUrls.WebManager) + "Services/Security.asmx/KeepLoggedIn", null, KeepLoggedIn_Success, KeepLoggedIn_Error);
}

//========================================================================================================================
// Interface
//========================================================================================================================

function BookmarkPage() {
  title = document.title;
  url = window.location.href;
  if (document.all) {
    window.external.AddFavorite(url, title);
  } else {
    if (window.sidebar) { window.sidebar.addPanel(title, url, ""); }
  }
}

function RemoteSupport() {
  Go(_AppUrls.Home + "support/remote-support.aspx");
}

function BrowserValidation() {
  if (!_IsValidBrowser) {
    Dialog_Dynamic("Browser Compatibility Warning", _AppUrls.WebManager + "Dialogs/BrowserCompatibility.html", 700, 240);
  }
}

function LoadQuickHelp(topic) {
  $("#divQuickHelp").load(_AppUrls.WebManager + "Support/QuickHelp.aspx?Topic=" + escape(topic), function () {
    $("#divQuickHelpContainer").show();
  });
}

//========================================================================================================================
// Document ready
//========================================================================================================================

$(function(){
  if ($("html").hasClass("master-page")) {
    _IsMasterPage = true;
    _NoEdit = ($m("xNoEdit").val() == "1");

    if (window.location.href != top.location.href) {
      top.location.replace(window.location.href);
    }

    BrowserValidation();
    
    window.onbeforeunload = function(){
      HtmlChangedCheck();
      if (IsFieldChanged() && !_IsConfirmedSave && !_NoEdit) {
        return _BeforeUnloadWarning;
      }
    };
    
    if (_SessionId !== "") { window.setTimeout("KeepLoggedIn();", 15000); }
  }

  if ($("html").hasClass("master-page-inner")) {
    _NoEdit = ($m("xNoEdit").val() == "1");
  }
  
  $(document).keydown(function(e){
    if (e.keyCode == 13) {
      if (e.target.tagName != "TEXTAREA") {
        e.preventDefault();
        if (window.Dialog_Open) {
          if (_DialogPanel.dialog("isOpen")) {
            $(".ui-dialog-buttonpane button").eq(0).trigger("click");
            return;  
          }
        }
        
        if (window.Click_Enter) { Click_Enter(); }
        return;
      }
    }
  });
  
  _IsPageLoaded = true;
  _IsFieldChanged = false;
  _IsConfirmedSave = false;
});

