if ('undefined' == typeof(chatfactory_love_integration))
{
  chatfactory_love_integration = 0;
}

(function ($) {
  $.extend({
    mainWindow: function () {
      var window = this;
      var window_status = 1;

      var search_request = null;
      var search_timer   = null;
      var avatar_window  = null;
      var avatar_request = null;
      var avatars        = [];
      var archive_window = null;

      var cookie = $.cookie("chatfactory_main");
      if (null != cookie)
      {
        cookie = cookie.split(";");
        position = [parseInt(cookie[2]), parseInt(cookie[1])];
        window_status = parseInt(cookie[0]);
      }
      else
      {
        position = [];
      }

      window.dialog = $("<div></div>").dialog({
        resizable: true,
        height: 450,
        width: 200,
        minHeight: 260,
        minWidth: 200,
        position: position,
        resize: function(event, ui) {
          resizeDialog();
        },
        drag: function(event, ui) {
          $("#emoticons-panel").hide();
          $("#statuses").hide();
        },
        dragStop: function(event, ui) {
          window.setCookie(1);
        }
      })
      .parent(".ui-dialog")
      .find(".ui-dialog-titlebar")
      .append('<a class="ui-dialog-titlebar-minimize ui-corner-all" title="' + txt_minimize + '"><span class="ui-icon ui-icon-minusthick" unselectable="on" style="-moz-user-select: none;">minimize</span></a>')
      .find('.ui-dialog-titlebar-minimize')
      .hover(
        function () { $(this).addClass('ui-state-hover'); },
        function () { $(this).removeClass('ui-state-hover'); })

      /* Minimize button */
      .click(function (event) {
        event.preventDefault();

        var link = $("<a href='#' id='taskbar-main-window'>" + txt_main_window + "</a>")
          .click(function (event) {
            event.preventDefault();

            window.dialog.css("visibility", "hidden").show();
            link.effect('transfer', { to: "#" + window.dialog.attr("id"), className: 'ui-effects-transfer' }, 500, function () { window.dialog.css("visibility", "visible"); }).remove();
            window.setCookie(1);
          })
          .css("visibility", "hidden")
          .appendTo($("#chatfactory-taskbar"));

        window.dialog
          .effect('transfer', { to: "#taskbar-main-window", className: 'ui-effects-transfer' }, 500, function () {link.css("visibility", "visible"); } )
          .hide();

        window.setCookie(2);
      })
      .end()
      .end()

      // Close button
      .find(".ui-icon-closethick")
        .attr("title", txt_close)
        .click(function (event) {
          event.preventDefault();
          event.stopPropagation();

          window.dialog.find("*").remove();
          window.setCookie(0);

          document.location.href = chatfactory_root + "index.php?option=com_chatfactory&controller=user&task=disable";
        })
      .end()

      .attr("id", "chatfactory-main");

      if (2 == window_status)
      {
        window.dialog.css("visibility", "hidden");

        var link = $("<a href='#' id='taskbar-main-window'>" + txt_main_window + "</a>")
          .click(function (event) {
            event.preventDefault();

            window.dialog.css("visibility", "hidden").show();
            link.effect('transfer', { to: "#" + window.dialog.attr("id"), className: 'ui-effects-transfer' }, 500, function () { window.dialog.css("visibility", "visible"); resizeDialog(); }).remove();
            window.setCookie(1);
          })
          .appendTo($("#chatfactory-taskbar"));
      }

      function resizeDialog() {
        $("#emoticons-panel").hide();
        window.dialog
          .find(".ui-dialog-content")
            .css("top", 0)
            .css("left", 0);

          window.content.menu
            .width(window.content.width() - window.content.menu.widthMargins);

          window.content.info
            .width(window.content.width() - window.content.info.widthMargins);
          window.content.info.find("table").width(window.content.info.width() - 13);

          window.content.search
            .width(window.content.width() - window.content.search.widthMargins);

          window.content.search.input
            .width(window.content.search.width() - window.content.search.input.widthMargins);

          window.content.ads
            .width(window.content.width() - window.content.ads.widthMargins);

          window.content.list
            .width(window.content.width() - window.content.list.widthMargins)
            .height(window.content.height() - window.content.list.heightMargins - window.content.panelsHeight);

          window.contacts_per_page = Math.ceil(window.content.list.height() / window.content.contact.height);
      }

      window.content = window.dialog.find(".ui-dialog-content");

      window.content.html("")
        .append("<div class='menu'></div>")
        .append("<div class='info'></div>")
        .append(chatfactory_guest ? "" : "<div class='search-bar'></div>")
        .append("<div class='list'></div>")
        .append("<div class='ads'></div>")

        .find(".menu")
          .append("<a href='#' id='configure'>" + txt_configure + "</a>")
          .append(chatfactory_guest ? "" : "<a href='#' id='cf-archive'>" + txt_archive + "</a>")
        .end()

        .find(".ads")
          .append(chatfactory_advertisment.link ? "<a href='" + chatfactory_advertisment.link + "' target='_blank'><img src='" + chatfactory_advertisment.image + "' /></a>" : "")
        .end()

        // Archive button
        .find("#cf-archive")
          .click(function (event) {
            event.preventDefault();

            if (null == archive_window)
            {
              archive_window = new $.archiveWindow();
            }

            $.ajax({
              url: chatfactory_root + "index.php?option=com_chatfactory&view=archive&format=raw",
              cache: false,
              success: function (response) {
                archive_window.updateWindow(response);
              },
              error: function (request) {
                alert("There was a problem. A \"" + request.statusText + "\" error was returned with a " + request.status + " error code!");
              },
              dataType: "html"
            });
          })
        .end()

        // Configure button
        .find("#configure")
          .click(function (event) {
            event.preventDefault();

            var options = new $.optionsWindow();

            $.ajax({
              url: chatfactory_root + "index.php?option=com_chatfactory&view=settings&format=raw",
              cache: false,
              success: function (response) {
                options.updateWindow(response);
              },
              error: function (request) {
                alert("There was a problem. A \"" + request.statusText + "\" error was returned with a " + request.status + " error code!");
              },
              dataType: "html"
            });
            //options.updateWindow();
          })
        .end()

        .find("#about")
          .click(function (event) {
            event.preventDefault();

            var about = new $.aboutWindow();
          })
        .end()

        // Search box
        .find(".search-bar")
          .append(chatfactory_guest ? "" : "<input />")
          .find("input")
            .keyup(function (event) {
              var input = $(this);

              if ('' == input.val())
              {
                clearTimeout(search_timer);
                if (null != search_request)
                {
                  search_request.abort();
                }
                input.removeClass("search-loader");
                $("#tester").contents().find("div.chatfactory-user-list").show();
                $("#tester").contents().find("div.chatfactory-search-list").html("");
              }
              else
              {
                $("#tester").contents().find("div.chatfactory-user-list").hide();

                input.addClass("search-loader");

                clearTimeout(search_timer);
                // Abort previous request (if any)
                if (null != search_request)
                {
                  search_request.abort();
                }

                search_timer = setTimeout(function () {
                  // New request
                  search_request = $.ajax({
                    type: "POST",
                    url: chatfactory_root + "index.php?option=com_chatfactory&controller=user&task=search",
                    data: "query=" + input.val() + "&show_offline=" + chatfactory_show_offline,
                    success: function(response) {
                      //alert( "Data Saved: " + msg );
                      input.removeClass("search-loader");
                      $("#tester").contents().find("div.chatfactory-search-list").html(response);
                    }
                  });
                }, 500);
              }
            })
          .end()
        .end()

        .find(".info")
          //.append("<div class='avatar'></div>")
          .append("<table><tr><td id='cell1'></td><td id='cell2'></td></tr></table>")
            .find("#cell1")
              .append("<div class='avatar'></div>")
            .end()
            .find("#cell2")
              .append("<div id='statuses'></div><a href='#' id='status' class='" + chatfactory_status + "'>" +  chatfactory_user + "</a>")
              .append(chatfactory_guest ? "" : "<input id='message' value=\"" + ('' != chatfactory_message ? chatfactory_message : txt_share_a_message) + "\" />")
                .find("#statuses").css("display", "none")
                  .append("<a href='#' class='available'>" + txt_available + "</a><br /><a href='#' class='busy'>" + txt_busy + "</a><br /><a href='#' class='invisible'>" + txt_invisible + "</a>")
                .end()
            .end()
          //.append("<table style='width: 90%;'><tr><td style='width: 48px;'><div class='avatar'></div></td><td class='cell2'><div style='margin-bottom: 3px;'><a href='#' id='status'>administrator</a><div id='statuses' style='position: absolute; display: ;'>select</div></div><input value='share a status message...' /></td></tr></table>")
          .find("#status")
            .click(function (event) {
              event.preventDefault();
              event.stopPropagation();

              if (!chatfactory_guest)
              {
                $("#statuses").toggle();
              }
            })
          .end()

          // Status change
          .find("#statuses a")
            .click(function (event) {
              event.preventDefault();

              var status = $(this).attr("class");
              $("#status").attr("class", status);

              $.post(
                chatfactory_root + 'index.php?option=com_chatfactory&controller=user&task=status',
                { status: status},
                function (response) {
                }, "json");
            })
          .end()

          // Share a status message
          .find("#message")
            .focus(function () {
              if (txt_share_a_message == $(this).val())
              {
                $(this).val("");
              }

              $(this).select();
            })
            .blur(function () {
              if ("" == $(this).val())
              {
                $(this).val(txt_share_a_message);
              }
            })
            .change(function () {
              $.post(
                chatfactory_root + 'index.php?option=com_chatfactory&controller=user&task=message',
                { message: $(this).val() },
                function (response) {

              }, "json");
            })
            .keypress(function (event) {
              var code = (event.keyCode ? event.keyCode : event.which);
              if (code == 13)
              {
                $(this).change().blur();
              }
            })
          .end()
        .end()
      .end()

      window.content.menu               = window.content.find(".menu");
      window.content.menu.heightMargins = window.content.menu.outerHeight(true) - window.content.menu.height();
      window.content.menu.widthMargins  = window.content.menu.outerWidth(true) - window.content.menu.width();
      window.content.menu.fullHeight    = window.content.menu.outerHeight(true);

      window.content.info               = window.content.find(".info");
      window.content.info.heightMargins = window.content.info.outerHeight(true) - window.content.info.height();
      window.content.info.widthMargins  = window.content.info.outerWidth(true) - window.content.info.width();
      window.content.info.fullHeight    = window.content.info.outerHeight(true);

      window.content.search               = window.content.find(".search-bar");
      window.content.search.heightMargins = window.content.search.outerHeight(true) - window.content.search.height();
      window.content.search.widthMargins  = window.content.search.outerWidth(true) - window.content.search.width();
      window.content.search.fullHeight    = window.content.search.outerHeight(true);

      window.content.search.input               = window.content.find(".search-bar input");
      window.content.search.input.widthMargins  = window.content.search.input.outerWidth(true) - window.content.search.input.width();

      window.content.ads               = window.content.find(".ads");
      window.content.ads.heightMargins = window.content.ads.outerHeight(true) - window.content.ads.height();
      window.content.ads.widthMargins  = window.content.ads.outerWidth(true) - window.content.ads.width();
      //window.content.ads.fullHeight    = window.content.ads.outerHeight(true);
      window.content.ads.fullHeight    = parseInt(window.content.ads.css("height"));

      window.content.panelsHeight = window.content.menu.fullHeight + window.content.info.fullHeight + window.content.search.fullHeight + window.content.ads.fullHeight;

      window.content.list               = window.content.find(".list");
      window.content.list.heightMargins = window.content.list.outerHeight(true) - window.content.list.height();
      window.content.list.widthMargins  = window.content.list.outerWidth(true) - window.content.list.width();

      window.content.contact        = window.content.find(".list li:first");
      window.content.contact.height = window.content.contact.outerHeight(true);

      window.title = window.dialog.find(".ui-dialog-title");

      resizeDialog();
      //window.content.contact.remove();

      // Set avatar
      if ('' != chatfactory_avatar)
      {
        window.content.find(".info .avatar").html("<img src='" + chatfactory_avatar + "' />");
      }

      window.content.list.append("<iframe id='tester' frameborder='0' style='width: 100%; height: 100%; border: 0px;' src='" + chatfactory_root + "index.php?option=com_chatfactory&controller=user&task=userslist'></iframe>");

      // Set update
      var timer = setInterval(function () {
        getMessages();
      }, chatfactory_messages_interval * 1000);

      function getMessages()
      {
        $.ajax({
          url: chatfactory_root + "index.php?option=com_chatfactory&controller=user&task=update",
          cache: false,
          dataType: "json",
          success: function (messages) {
            for (var i = 0, count = messages.length; i < count; i++)
            {
              var message   = messages[i];
              var sender_id = message.sender_id;

              if (undefined == chatfactory_windows[sender_id])
              {
                if (1 == message.is_ad)
                {
                  var chat = new $.adWindow({ username: message.username, id: sender_id });
                }
                else
                {
                  var chat = new $.chatWindow({ username: message.username, id: sender_id });
                }

                chatfactory_windows[sender_id] = chat;
              }

              var window = chatfactory_windows[sender_id];

              if (1 == message.offline)
              {
                message.username += ' (' + txt_offline + ')';
              }

              window.receiveMessage(message.username, message.text);
            }
          }});
      }

      getMessages();

      // Get new freindships requests
      if (!chatfactory_guest && !chatfactory_love_integration)
      {
        setInterval(function () {
          $.ajax({
            url: chatfactory_root + 'index.php?option=com_chatfactory&controller=user&task=requests',
            cache: false,
            dataType: "json",
            success: function (response) {
              for (var i = 0, count = response.requests.length; i < count; i++)
              {
                var request = response.requests[i];

                if (0 == request.notification)
                {
                  if (undefined == chatfactory_requests[request.user_id])
                  {
                    chatfactory_requests[request.user_id] = new $.requestWindow({ sender_id: request.user_id, username: request.username });
                  }
                }
                else
                {
                  alert(request.username + " " + txt_added_friend);
                }
              }
            }
          })
        }, chatfactory_request_interval * 1000);
      }

      this.startConversation = function (id, username) {
        if (undefined == chatfactory_windows[id])
        {
          var chat = new $.chatWindow({ username: username, id: id });

          chatfactory_windows[id] = chat;
        }
      }

      this.setTitle = function (title) { window.title.html(title); }
      this.setCookie = function (opened) {
        $.cookie("chatfactory_main", opened + ";" + parseInt(window.dialog.css("top")) + ";" + parseInt(window.dialog.css("left")));
      }

      // Show the avatar on hover
      this.showAvatar = function (link) {
        var iframe  = $("#tester").offset();
        var user_id = link.attr("rel");

        if (null == avatar_window)
        {
          avatar_window = $("body")
            .append("<div id='chatfactory-hover-avatar'></div>")
            .find("#chatfactory-hover-avatar");
        }

        var left = iframe.left - avatar_window.outerWidth(true) - 10;
        if (left < 0)
        {
          left = iframe.left + window.dialog.outerWidth(true);
        }

        avatar_window
          .show()
          .html("undefined" == typeof(avatars[user_id]) ? txt_loading : avatars[user_id])
          .offset({ top: iframe.top + link.offset().top, left: left });

        if (null != avatar_request)
        {
          avatar_request.abort();
        }

        if ("undefined" == typeof(avatars[user_id]))
        {
          avatar_request = $.post(
            chatfactory_root + "index.php?option=com_chatfactory&controller=user&task=gethoverinfo",
            { user_id: user_id },
            function (response) {
              var img = "<img src='" + response.avatar + "' />";
              avatar_window.html(img);

              avatars[user_id] = img;
          }, "json");
        }
      }

      // Hide the avatar
      this.hideAvatar = function () {
        avatar_window.hide();

        avatar_request.abort();
      }

      // Close avatar window
      this.closeArchiveWindow = function () {
        archive_window = null;
      }

      this.setCookie(window_status);

      return window;
    }
  })
})(jQueryFactory);
