/* AJAT Config */

var ajatConfig = {
	fl : false,
	mode : 'left',
	theme: 'default',
	frequency : 10
};

/* End Of AJAT Config*/

/* AJAT Class >:) */

function ajatClass(config) {
	var config = config;
	var myName = "ajat";
	var data = "";
	var inProgress = false;

	// quick access to elements
	var $ = function(element) {
		  if (typeof element == "string")
		    element = document.getElementById(element);
		  return element;
	};

	// misc chat functions
	this.chatHide = function() {
		$("chat").style.left = "-152px";
		$("chatshow").style.display = "block";
		$("chathide").style.display = "none";
		$("chatsend").style.display = "none";
		return false;
	};

	this.chatShow = function() {
		$("chat").style.left = "50%";
		$("chatshow").style.display = "none";
		$("chathide").style.display = "block";
		$("chatsend").style.display = "block";
		return false;
	}

	this.chatSend = function() {
		text = $("chattext").value.replace(/^\s+|\s+$/g,"");
		$("chattext").value = "";
		if (text == "") { return false; }
		this.Say('text', text);
		return false;
	}

	var chatScroll = function() {
		if ($("chatlog")) {
			$("chatlog").scrollTop = $("chatlog").scrollHeight;
		}
		return false;
	}

	// ajax functions
  this.Say = function(param, val) {
		if (inProgress)
		{
			return false;
		}
    req = false;

    try {
        req = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try {
            req = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {
            if(window.XMLHttpRequest){
               req = new XMLHttpRequest();
            }
        }
    }
    if (req){
       req.onreadystatechange = this.OnGetText;
       req.open("POST", path + "engine.php", true);
       req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
       if ((typeof param != 'undefined') && (typeof val != 'undefined'))
       {
          req.send(param + "=" + encodeURIComponent(val));
       }
       else
       {
          req.send("null");
       }
       inProgress = true;
    } else {
    	alert ("У вас нет поддержки ajax... О_о");
    }
    return false;
  };

	this.OnGetText = function () {
    if (req.readyState == 4){
        if (req.status == 200) {
        	if (data != req.responseText)
        	{
						data = req.responseText;
						$("chatlog").innerHTML = data;
						// В админке автоскролла к новому сообщению нет
						if (config['mode'] != 'admin')
							chatScroll();
					}
        }
		inProgress = false;
    setTimeout("ajat.Say()", config['frequency'] * 1000);
    }
    return false;
  };

	// constructors... :)
  this.GetMyPath = function () {
		  var scripts = document.getElementsByTagName('SCRIPT');

      var r = new RegExp(myName+'\\.js(\\?.+)?$');
      r.compile(myName+'\\.js(\\?.+)?$');

		  for (var i=0; i < scripts.length; i++) {
		    if (scripts[i].src.match(r)) {
		      var path = scripts[i].src.replace(r, '');
		      return path;
		      break;
		    }
		  }
		  return null;
  };

  this.GetConfig = function () {
		if (typeof ajatDisplayMode == 'string')
		{
			config['mode'] = ajatDisplayMode;
		}
  }

  this.Construct = function(mode) {
        document.write('<link rel="stylesheet" href="'+path+'themes/'+config['theme']+'/chat.style.css" type="text/css" />');

        if (!config['fl'])
          document.write('<style type="text/css">#chat P:first-letter {color:black; font-size:100%; font-weight:normal;}</style>');

        document.write('<div id="chat" class="'+mode+'">');
        document.write('<div id="chatlog" class="'+mode+'"></div>');
        document.write('<input type="text" id="chattext" class="'+mode+'" maxlength="200" value="" onkeypress="if (event.keyCode == 13) return ajat.chatSend();"/>');
        document.write('<a class="'+mode+'" id="chatsend" href="" onclick="return ajat.chatSend();"></a>');

        if (mode != 'inline' && mode != 'admin')
        {
            document.write('<a class="hide" id="chathide" href="" onclick="return ajat.chatHide();"></a>');
            document.write('<a class="show" id="chatshow" href="" onclick="return ajat.chatShow();" title="Мини-чат. Можно оставить отзыв."></a>');
        }

        document.write('</div>');

        return false;
     };

  this.GetConfig();
  var path = this.GetMyPath();
  if (path != null)
    this.Construct(config['mode']);
  this.Say();
}


var ajat = new ajatClass(ajatConfig);