var DialogError = Error;
$.extend(DialogError.prototype, {
  toDialog: function () {
    return $('<div class="dialog"><div class="body"><div class="content"><h3>ERROR:</h3><p class="first">' + this.message + '</p></div></div><div class="foot"><a class="close">close</a></div></div>');
  }
});

/*
var DialogError = function(A) {
  this.message = A;
  this.content = null;
  this.toDialog();
};

$.extend(DialogError.prototype, {
  toDialog: function () {
    this.content = $('<div class="dialog"><div class="body"><div class="content">' + this.message + '</div></div><div class="foot"><a class="close" onclick="">close</a></div></div>');
    this.content.prependTo("BODY").show();
    var _this = this;
    this.content.find(".close").click(function (evt) {
      _this.content.hide()
    })
  }
});
*/

var Dialog = function (E, A, C, B) {
  this.enableLog = false;
  try {
    this.init(E, A, C, B);
  } catch(F) {
    this.log(F);
  }
};

$.extend(Dialog.prototype, {
  init: function (E, A, C, B) {
    this.el = $(E);
    this.mount = A;
    this.autoTrigger = C || false;
    this.content = null;
    this.cbs = {};
    this.attachCallbacks(B);
    if (this.autoTrigger) {
      this.trigger();
    }
  },
  attachCallbacks: function (A) {
    var C = ["onTrigger", "onShow", "onPreShow", "onPost", "onPostComplete", "onCancel"],
    B = function () {
      return true;
    };
    this.cbs.onCancel = function () {
      this.hide();
    };
    var E = this;
    $.each(C, function () {
      E.cbs[this] = A[this] ? A[this] : B;
    });
  },
  trigger: function () {
    if (this.cbs.onTrigger()) {
      this.fetch();
    } else {
      throw new DialogError("Dialog failed to trigger");
    }
  },
  fetch: function () {
    if (!this.content) {
      var B = this.el.attr("href");
      var A = $.testSelector(B);
      try {
        if (A instanceof jQuery && A.length > 0) {
          this.content = A;
        } else {
          if (B) {
            var E = this;
            $.ajax({
              url: B,
              async: false,
              type: "GET",
              dataType: "html",
              success: function (html) {
                E.content = $(html);
                if (E.content.length > 1) {
                  E.content = $("<div>" + html + "</div>")
                }
                currentDialog = E.content;
              },
              error: function (xml) {
                var json = eval("(" + xml.responseText + ")");
                throw new DialogError(json.message ? json.message : "Something bad happened while looking for dialog at:\n" + B);
              }
            });
          } else {
            throw new DialogError("No can do, I ain't got no content.");
          }
        }
      } catch(C) {
        this.error(C);
      }
    }
    this.show();
  },
  show: function (count) {
    var _this = this;
    if (!count) {
      count = 0;
    }
    if (count == 20) {
      this.mount = "BODY";
    }
    var mount = $(this.mount);
    if (mount.length) {
      if (this.mount == "BODY") {
        this.content.hide().prependTo(mount).hide();
      } else {
        this.content.hide().insertBefore(mount).hide();
      }
    } else {
      setTimeout(function () {
        _this.show(++count);
      }, 100);
      return;
    }
    hideDialogs();
    $(".close", this.content).unbind().click(function (evt) {
      _this.hide();
      _this.cbs.onCancel();
      evt.preventDefault();
    });
    var forms = this.content.find("form");
    if (forms.size() > 0) {
      count = 0;
      forms.unbind().submit(function (evt) {
        //count++;
        //if (count > 1) {
        //  _this.hide();
        //  evt.preventDefault();
        //  return false;
        //}
        var form = $(this);
        var onPostCheck = _this.cbs.onPost(form);
        try {
          if (String(form.attr("action")).length > 0 && onPostCheck == true) {
            var data = new Object();
            form.find(":input").each(function (i) {
              if (["button", "submit", "reset", "image"].indexOf($(this).attr("type")) > -1) {
                return true;
              }
              var key = $(this).attr("name") || i;
              var checkCheck = ($(this).attr("type") == "checkbox" && $(this).attr("checked")) ? true : false;
              data[key] = checkCheck ? true : $(this).val();
            });
            $.ajax({
              url: form.attr("action"),
              type: "post",
              dataType: "json",
              data: data,
              success: function (json) {
                if (_this.cbs.onPostComplete(json)) {
                  _this.hide();
                }
              },
              error: function (xml) {
                var json = eval("(" + xml.responseText + ")");
                throw new DialogError("Darn! That dialog post failed:\n" + json.message);
              }
            });
          }
        } catch(err) {
          _this.error(err);
        }
        if (onPostCheck) {
          evt.preventDefault();
        }
      });
      forms.find(".cancel").unbind().click(function (evt) {
        _this.hide();
        _this.cbs.onCancel();
        evt.preventDefault();
      });
    }
    //$(".ad, .ad *, select, object").css("visibility", "hidden");
    $(".dialog select").css("visibility", "visible");
    if (!$.browser.msie) {
      _this.content.fadeTo("normal", 0.1, function () {
        _this.cbs.onPreShow();
        _this.content.show();
        _this.content.fadeTo("normal", 1, function () {
          _this.cbs.onShow();
        });
      });
    } else {
      _this.content.css("opacity", 0.01);
      _this.content.show(function () {
        _this.cbs.onPreShow();
        _this.content.css("opacity", "");
        _this.cbs.onShow();
      });
    }
  },
  hide: function () {
    try {
      this.content.hide();
      //$(".ad, .ad *, select, object").css("visibility", "visible");
    } catch(A) {}
  },
  reset: function () {
    try {
      this.content.html("");
      this.content = null;
    } catch(A) {}
  },
  error: function (A) {
    if (!this.el.is(":visible")) {
      this.content = A.toDialog();
      this.show();
    } else {
      try {
        this.content.find(".error").text(A).show();
      } catch(B) {
        throw new Error(A);
      }
    }
  },
  log: function (A) {
    if (this.enableLog && console) {
      console.log(A);
    }
  }
});

var dialogs = {};
var currentDialog = "";

function buildDialogs(C, A, B, F) {
  try {
    C = C || ".dialog-anchor";
    A = A || "BODY";
    B = B || false;
    F = F || {};
    $(C).each(function () {
      var G = $(this).attr("id");
      G = (G != "") ? G : "d" + Math.floor(Math.random() * 200 + 1);
      if (!dialogs[G]) {
        dialogs[G] = new Dialog(this, A, B, F)
      } else {
        dialogs[G].reset();
        dialogs[G].attachCallbacks(F);
        dialogs[G].trigger();
      }
    })
  } catch(E) {
    if (console && console.log) {
      console.log("Dialog Error: " + E)
    }
  }
}

function findDialog(A) {
  return dialogs[A] ? dialogs[A] : false;
}

function hideDialogs() {
  $.each(dialogs, function (A, B) {
    B.hide();
  })
};

