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

(function ($) {
      $.extend({
        chatWindow: function (options) {
          var window = this;
          var window_status = 1;
          var guest_user = options.id.substr(0, 1) == 'g' ? 1 : 0;

          var cookie = $.cookie("chatfactory_windows");
          if (null != cookie)
          {
            cookie = cookie.split(";");
            for (var i = 0, count = cookie.length; i < count; i++)
            {
              var temp = cookie[i];
              temp = temp.split(",");

              if (options.id == temp[0])
              {
                position = [parseInt(temp[3]), parseInt(temp[2])];
                window_status = parseInt(temp[1]);
              }
            }
          }
          else
          {
            position = [];
          }

          window.dialog = $("<div></div>").dialog({
            resizable: true,
            height: 300,
            width: 400,
            minHeight: 260,
            position: position,
            resize: function(event, ui) {
              resizeDialog();
            },
            drag: function(event, ui) {
              $("#emoticons-panel").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'); })
			        .click(function (event) {
			          event.preventDefault();

			          var link = $("<a href='#' id='taskbar-chat-" + options.id + "'>" + options.username + "</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"); window_status = 1; window.setCookie(window_status); }).remove();
			          })
			          .css("visibility", "hidden")
			          .appendTo($("#chatfactory-taskbar"));

			          window.dialog
			            .effect('transfer', { to: "#taskbar-chat-" + options.id, className: 'ui-effects-transfer' }, 500, function () {link.css("visibility", "visible"); window_status = 2; window.setCookie(window_status); } )
			            .hide();
			        })
			      .end()
          .end()
          .find(".ui-icon-closethick")
            .attr("title", txt_close)
            .click(function (event) {
              event.preventDefault();
              event.stopPropagation();

              chatfactory_windows[options.id] = undefined;
              window.dialog.find("*").remove();

              // Remove from cookie
              var cookie = $.cookie("chatfactory_windows");

              if (null == cookie)
              {
                return false;
              }

              var found = false;

              cookie = cookie.split(";");

              for (var i = 0, count = cookie.length; i < count; i++)
              {
                var temp = cookie[i];
                temp = temp.split(",");
                if (options.id == temp[0])
                {
                  cookie.splice(i, 1);

                  found = true;
                  i = count;
                }
              }

              if (found)
              {
                cookie = cookie.join(";");
                $.cookie("chatfactory_windows", cookie);
              }
            })
          .end()
          .attr("id", options.id);

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

            var link = $("<a href='#' id='taskbar-main-window'>" + options.username + "</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)
            .find(".avatars")
              .height(window.content.height() - window.content.actions.outerHeight(true) - window.content.avatars.heightMargins)
            .end()
            .find(".history")
              .width(window.content.width() - (window.content.avatars.css("display") == 'none' ? 0 : window.content.avatars.outerWidth(true)) - window.content.message.widthMargins - 2)
            .end()
            .find(".message-panel")
              .width(window.content.width() - (window.content.avatars.css("display") == 'none' ? 0 : window.content.avatars.outerWidth(true)) - window.content.message.widthMargins)
            .end()
            .find(".history")
              .height(window.content.height() - window.content.actions.outerHeight(true) - window.content.message.outerHeight(true) - window.content.find(".ui-resizable-handle").outerHeight(true))
            .end()
            .find("textarea")
              .width(window.content.message.width() - window.content.textarea.widthMargins)
            .end();
          }

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

          window.content
            .html("")
            .append("<div class='avatars'></div>")
            .append("<div class='actions'>")
              .append(chatfactory_love_integration ? "" : "<a href='#' class='action-friend' style='display: none;'></a>")
              .append("<a href='#' class='action-avatars'></a>")
              .append(chatfactory_love_integration ? "" : "<a href='#' class='block-user' style='display: none;'></a>")
              .append("<div class='user-status'>" + options.username + "<span class='status-message'></span></div>")
            .append("</div>")
            .append("<div class='history'><div class='wrapper2'></div></div>")
            .append("<div class='message-panel'></div>")

            .find(".avatars")
              .html("<div class='top_avatar'></div><div class='bottom_avatar'></div>")
            .end()

            // History panel
            .find(".history .wrapper2")
              .append(chatfactory_guest || guest_user ? "" : "<span class='recent_history'><a href='#' rel='0'>" + txt_show_recent_messages + "</a><span class='loader' style='display: none;'>" + txt_loading_messages + "</span></span>")

              .find(".recent_history a")
                .click(function (event) {
                  event.preventDefault();

                  if (0 == $(this).attr("rel"))
                  {
                    window.content.history.find(".loader").show();
                    window.content.history.find("a").hide();

                    $.post(
                      chatfactory_root + "index.php?option=com_chatfactory&controller=user&task=recent",
                      { user_id: options.id, first_message: window.firstMessageId },
                      function (messages) {
                        var div = $("<div class='recent'></div>");
                        for (var i = 0, count = messages.length; i < count; i++)
                        {
                          var message = messages[i];
                          var username = options.id == message.sender_id ? options.username : chatfactory_user;
                          div.prepend("<b>" + username + ":</b> " + message.text + "<br />");
                        }

                        window.content.history.find(".wrapper2").prepend(div);
                        window.content.history.attr({ scrollTop: window.content.history.find(".recent").height() - 40 });

                        window.content.history.find(".loader").hide();
                        window.content.history.find("a").show();
                    }, "json");

                    $(this)
                      .attr("rel", 1)
                      .html(txt_hide_recent_messages);
                  }
                  else
                  {
                    window.content.history.find(".recent").remove();
                    $(this)
                      .attr("rel", 0)
                      .html(txt_show_recent_messages);
                  }
                })
              .end()
            .end()

            .find(".message-panel")
              .append("<div class='formatting'><a href='#' class='formatting-button emoticons'></a><a href='#' class='formatting-button buzz'></a></div><textarea></textarea>")
              .resizable({
                handles: 'n',
                minHeight: 70,
                resize: function (event, ui) {
                  ui.originalElement
                    .css("bottom", 0)
                    .css("top", "")
                  .find("textarea").height(window.content.find(".message-panel").height() - window.content.find(".message-panel .formatting").outerHeight(true) - window.content.textarea.heightMargins - 1);

                  resizeDialog();
                }
              })

              // Chat message
              .find("textarea")
                .keypress(function (event) {
                  event.preventDefault;

                  var code = (event.keyCode ? event.keyCode : event.which);
                  if (code == 13)
                  {
                    var message = window.content.textarea.val();

                    if ('' == message)
                    {
                      return false;
                    }

                    window.sendMessage(message);

                    window.receiveMessage(chatfactory_user, message)
                    window.content.textarea.val("");
                    return false;
                  }
                })
                .focus()
              .end()
            .end()

            // Toggle Avatars
            .find(".action-avatars")
              .click(function (event) {
                event.preventDefault();

                window.content.avatars.toggle();
                $(this).toggleClass("expand");
                resizeDialog();
              })
            .end()

            // Friendship status
            .find(".action-friend")
              .click(function (event) {
                event.preventDefault();

                var link = $(this);

                if (link.hasClass("loading"))
                {
                  return false;
                }

                var current = link.attr("class").split(" ");
                current = current[1];

                if ('action-friend-2' == current && !confirm(txt_confirm_remove_friend.replace("%s", options.username)))
                {
                  return false;
                }

                link.addClass("loading");

                $.post(
                  chatfactory_root + 'index.php?option=com_chatfactory&controller=user&task=friendship',
                  { user_id: options.id }, function (response) {
                    link
                      .removeClass("loading")
                      .removeClass(current)
                      .addClass("action-friend-" + response.action);
                }, "json");
              })
            .end()

            // Block user
            .find(".block-user")
              .click(function (event) {
                event.preventDefault();

                if ($(this).hasClass("loading"))
                {
                  return false;
                }

                var block = $(this).hasClass("accept") ? 0 : 1;
                var button = $(this);

                if (block && !confirm(txt_confirm_block.replace("%s", options.username)))
                {
                  return false;
                }

                button.toggleClass("accept");
                button.addClass("loading");

                $.post(
                  chatfactory_root + 'index.php?option=com_chatfactory&controller=user&task=block',
                  { user_id: options.id, block: block },
                  function (response) {
                    button.removeClass("loading");
                }, "json");
              })
            .end()

            // Buzz button
            .find("a.buzz")
              .click(function (event) {
                event.preventDefault();

                window.sendBuzz();
              })
            .end()

            // Emoticons button
            .find("a.emoticons")
            .click(function (event) {
              event.stopPropagation();
              event.preventDefault();

              if (0 == $("#emoticons-panel").length)
              {
                var emoticons = $("body").append("<div id='emoticons-panel'></div>").find("#emoticons-panel");
                var count = chatfactory_emoticon_search.length;
                var k = 0;

                for (var i = 0; i < count; i++)
                {
                  emoticons.append("<a href='#' class='emoticon' title=" + chatfactory_emoticon_search[i] + ">" + chatfactory_emoticon_replace[i] + "</a>");

                  k++;

                  if (k == 4)
                  {
                    emoticons.append("<div style='clear:both;'></div>");
                    k = 0;
                  }
                }
              }

              var offset = $(this).offset();
              $("#emoticons-panel")
                .show()
                .css("top", offset.top - $("#emoticons-panel").outerHeight(true))
                .css("left", offset.left)
                .find("a.emoticon")
                .unbind()
                .click(function (event) {
                  event.preventDefault();

                  window.content.textarea.insertAtCursor($(this).attr("title"));
                });
            });

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

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

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

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

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

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

          window.firstMessage   = true;
          window.firstMessageId = 0;

          resizeDialog();

          // Get avatars
          $.get(
            chatfactory_root + 'index.php?option=com_chatfactory&controller=user&task=info',
            { user_id: options.id },
            function (response) {
              window.content.find(".bottom_avatar").html("<img src='" + response.bottom + "' />");
              window.content.find(".top_avatar").html("<img src='" + response.top + "' />");

              if ('' != response.message && !guest_user)
              {
                window.content.find(".status-message").html(' - ' + response.message);
              }

              window.content.find(".user-status").addClass(response.user_status);

              if (!guest_user && !chatfactory_guest)
              {
                window.content.find(".block-user").show();
                if (response.blocked)
                {
                  window.content.find(".block-user").addClass("accept");
                }

                // Friendship status
                window.content.find(".action-friend")
                  .show()
                  .addClass("action-friend-" + response.friend);
              }
          }, "json");

          // Set title
          this.setTitle = function (title) { window.title.html(title); }

          // Change status
          this.changeStatus = function (status) { window.content.find(".user-status").addClass(status); }

          // Receive message
          this.receiveMessage = function (username, message) {
            // Check if window is minimized
            if (2 == window_status)
            {
              var button = $("#taskbar-chat-" + options.id);
              button.addClass("new");
            }

            if ('BUZZ!!' == message)
            {
              this.buzz();
            }
            else
            {
              var message = str_replace(chatfactory_emoticon_search, chatfactory_emoticon_replace, message);
              window.content.find(".history .wrapper2")
                .append("<b>" + username + ":</b> " + message + "<br />")
                .parent()
                .attr({ scrollTop: window.content.find(".history .wrapper2").attr("scrollHeight") });
            }
          }

          // Receive system message
          this.receiveSystemMessage = function (message) {
            window.content.find(".history .wrapper2")
              .append(message + "<br />")
              .parent()
              .attr({ scrollTop: window.content.find(".history .wrapper2").attr("scrollHeight") });
          }

          // Send message
          this.sendMessage = function (message) {
            $.post(
              chatfactory_root + "index.php?option=com_chatfactory&controller=message&task=send&format=raw",
              { message: message, receiver_id: options.id, first: window.firstMessage },
              function (response) {
                window.firstMessageId = response.id;
                if (0 == response.status)
                {
                  window.receiveSystemMessage(response.message);
                }
            }, "json");

            window.firstMessage = false;
          }

          // Send buzz
          this.sendBuzz = function () {
            window.sendMessage("BUZZ!!");
            window.buzz();
          }

          // Buzz window
          this.buzz = function () {
            if (window.buzzing || 2 == window_status)
            {
              return false;
            }

            var d = new Date();
            if (d.getTime() - window.lastBuzz < 2000)
            {
              return false;
            }

            window.buzzing = true;
            window.lastBuzz = d.getTime();

            window.dialog.effect("shake", { times: 1, direction: "left", distance: 5 }, 10, function () {
              window.dialog.effect("shake", { times: 1, direction: "up", distance: 5 }, 10, function () {
                window.receiveSystemMessage("<b class='buzz'>BUZZ!!</b>");
                window.buzzing = false;
              }
          )})};

          window.lastBuzz = 0;

          // Set cookie
          this.setCookie = function (opened) {
            if (guest_user || chatfactory_guest)
            {
              return false;
            }

            var cookie = $.cookie("chatfactory_windows");
            var found = false;

            if (null == cookie)
            {
              $.cookie("chatfactory_windows", options.id + "," + opened + "," + parseInt(window.dialog.css("top")) + "," + parseInt(window.dialog.css("left")) + "," + options.username);
              return true;
            }

            cookie = cookie.split(";");

            for (var i = 0, count = cookie.length; i < count; i++)
            {
              var temp = cookie[i];
              temp = temp.split(",");
              if (options.id == temp[0] || '' == cookie[i])
              {
                cookie[i] = options.id + "," + opened + "," + parseInt(window.dialog.css("top")) + "," + parseInt(window.dialog.css("left")) + "," + options.username;

                found = true;
                i = count;
              }
            }

            if (!found)
            {
              cookie.push(options.id + "," + opened + "," + parseInt(window.dialog.css("top")) + "," + parseInt(window.dialog.css("left")) + "," + options.username);
            }

            cookie = cookie.join(";");
            $.cookie("chatfactory_windows", cookie);
          }

          window.setCookie(window_status);

          return window;
        }
      }),

      $.fn.insertAtCursor = function (tagName) {
        return this.each(function(){
          if (document.selection) {
            //IE support
            this.focus();
            sel = document.selection.createRange();
            sel.text = tagName;
            this.focus();
          }else if (this.selectionStart || this.selectionStart == '0') {
            //MOZILLA/NETSCAPE support
            startPos = this.selectionStart;
            endPos = this.selectionEnd;
            scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos) + tagName + this.value.substring(endPos,this.value.length);
            this.focus();
            this.selectionStart = startPos + tagName.length;
            this.selectionEnd = startPos + tagName.length;
            this.scrollTop = scrollTop;
          } else {
            this.value += tagName;
            this.focus();
          }
        });
      }

		})(jQueryFactory);
