chat_window = '';
var pings_array = new Array();
function $(id){return document.getElementById(id);}

//запуск системы
function start()
{    ping();
	scan_request_chat();
}

//------------------------------- сканер запросов на чат --------------
// сканирование запросов на чат
function scan_request_chat()
{
  AjaxRequest.get({'url':'/chat.php?action=chat_requst&ids='+act_chat.join(),'onSuccess':function(req)
    {
    	txt = req.responseText;
    	//addMsgStatusChat({text:'rec->'+act_chat.join()});
    	if (txt!='' && txt!='0')
		{
		    msg = txt.split('|####|');
		    len = msg.length;
		    for(var i=0; i<len; i++)
			add_request(msg[i]);
		}
    }
  });
  setTimeout('scan_request_chat()',time_requst);
}
// добавление запроса на чат
function add_request(msg)
{

	msg=msg.split('|#|');
	if (msg[0]!='clos' && msg[0]!='accept' && msg[0]!='close_all')
	{
		createRightElement({id:parseInt(msg[0]),
										text:msg[1],
										pos:'incoming'});
	}
	else if (msg[0]=='accept' && $(msg[1]))
	{
		AjaxRequest.get({'url':'/chat.php?action=chng_stat&chat_id='+msg[1],'onSuccess':function(req)
		{
			if (parseInt(req.responseText)!=0) acceptChat(req.responseText);
			else alert(req.responseText);
		}
		});
	}
	else if(msg[0]=='clos') {unActiveChat(parseInt(msg[1]));}
	else if(msg[0]=='close_all')closeAllchats();
}

// запус к нового чата
function start_chat(user_id)
{
    if (user_gender==1)
    {    	AjaxRequest.get({'url':'/chat.php?action=is_paid','onSuccess':function(req){    		var flag = false;
    		if (req.responseText == '0')
    		{
	    		AjaxRequest.get({'url':'/chat.php?action=is_maney','onSuccess':function(req){	    			if (req.responseText =='0') {self.location = '/content.php?page=price'; return;}
	    			else{	    					if (confirm(pay_msg))
					    	{
					    		AjaxRequest.get({'url':'/chat.php?action=pay','onSuccess':function(req)
						    		{
						    			if (req.responseText=='1')
						    			{
						    				paid =1;
						    				flag = true;
						    				if (window.opener) window.opener.paid = 1;
						    				if (typeof(chat_window)!='object' || chat_window.closed)
										    chat_window = window.open('/chat.php?action=start_chat&to_id='+user_id, 'chat', "menubar=no,width=800,height=600,toolbar=no,resizable=yes");
										    else chat_window.addChat(user_id);
						    			}
						    			else
						    			{						    				paid =0;
						    				if (window.opener)window.opener.paid = 0;
						    			}
						    		}
					    		});
					    	}
					    	else
					    	{					    		paid =0;
					    		if (window.opener) window.opener.paid = 0;
					    	}
	    			}	    		}});
	   		}
	   		else
	   		{   				if (typeof(chat_window)!='object' || chat_window.closed)
			    chat_window = window.open('/chat.php?action=start_chat&to_id='+user_id, 'chat', "menubar=no,width=800,height=600,toolbar=no,resizable=yes");
			    else chat_window.addChat(user_id);	    	}
        }});
    }
    else
    {
	    if (typeof(chat_window)!='object' || chat_window.closed)
	    chat_window = window.open('/chat.php?action=start_chat&to_id='+user_id, 'chat', "menubar=no,width=800,height=600,toolbar=no,resizable=yes");
	    else
	    {	    	chat_window.addChat(user_id);	    }
    }
}

// добавление чата к существующим + создание
function addChat(uid)
{	if (countActiveChats()>max_chats_active) alert('SORRY!\rD\'not create chat!');
	else
	{
		AjaxRequest.get({'url':'/chat.php?action=add_start_chat&to_id='+uid,'onSuccess':function(req){			txt = req.responseText.split('|#|');
			if (txt[0]!='0')
			{
				if (!$(txt[0]) || $(txt[0]).id!=txt[0])
				{
					createRightElement({id:parseInt(txt[0]),
										text:txt[1],
										pos:'outing'});
				}
				resize();
			}
			else {alert(txt[1]);}		}
		});
	}}

// отменить запрос на новый чат
function chat_decline(chat_id)
{
	dat = '/chat.php?action=decline&chat_id='+chat_id;
	if (typeof(chat_window)!='object' || chat_window.closed)
		if ($(chat_id)) $(chat_id).innerHTML = '';
	AjaxRequest.get({'url':dat,'onSuccess':function(req){}});
}

// принять запрос на чат c открытием окна
function accept_chat(chat_id)
{
    if (user_gender==1 && paid == 0)
    {
    	if (many ==0) self.location = '/content.php?page=price';
    	else if (confirm(pay_msg))
    	{
    		AjaxRequest.get({'url':'/chat.php?action=pay&user='+user_ID,'onSuccess':function(req)
    		{
    			if (req.responseText=='1')
    			{
    				    paid =1;
    				    if (typeof(chat_window)!='object' || chat_window.closed)
					    {
					    	chat_window = window.open('/chat.php?action=accept&chat_id='+chat_id, 'chat', "menubar=no,width=800,height=600,toolbar=no,resizable=yes");
							document.getElementById(chat_id).innerHTML = '';
						}
						else{chat_window.addChat(user_id); }
    			}
    			else
    			{    				if (user_gender==1) self.location = '/content.php?page=price';
    				else alert (req.responseText);
    			}
    		}
    		});
    	}
    }
    else
    {
	        if (typeof(chat_window)!='object' || chat_window.closed)
		    {
		    	chat_window = window.open('/chat.php?action=accept&chat_id='+chat_id, 'chat', "menubar=no,width=800,height=600,toolbar=no,resizable=yes");
				document.getElementById(chat_id).innerHTML = '';
			}
			else{chat_window.addChat(user_id); }
    }
}

// принять запрос на чат просто
function acceptChat(chat_id)
{	if (countActiveChats()>max_chats_active) alert('SORRY!\rD\'not create chat!');
	else
	{
		AjaxRequest.get({'url':'/chat.php?action=accept&wnd=0&chat_id='+chat_id,
			'onSuccess':function(req)
			{				var txt = req.responseText.split('|#|');				if (txt[0] == '1')
				{					moveToCurrent(parseInt(txt[1]));
					resize();
				}
				else alert (txt[0]);
	    }});
	}}

// закрытие чата
function close_chats(id)
{    chat_decline(id);
	if ($('chat'+id))$('chat'+id).parentNode.removeChild($('chat'+id));
	$($(id).lang).removeChild($(id));
    if (cur_chat == id) cur_chat = false;

    clearArrays(id);}

//--------------------------------------- работа с сообщениями ----------
//сканирование Сообщений
var ping = function()
{
	dat='/chat.php?action=ping';
	AjaxRequest.get({'url':dat,'onSuccess':function(req){txt = req.responseText;
		if (txt!='0')
		{   //addMsgStatusChat({text:txt});			var msg = txt.split('|####|');
			var len = msg.length;
			for(var i=0; i<len; i++)
			add_message(msg[i]);
		}
       }});
	setTimeout('ping()',timer);
}

// новое сообщение (полученное)-- добавление
function add_message(txt)
{
	if (txt == 'close')  closeAllchats();
	else{		var txt = txt.split('|#|');
		if (txt[1]=='close' && $('msg'+txt[0])) unActiveChat(parseInt(txt[0]));
	    if ($('chat'+txt[0]))  {addNewMessage({id:parseInt(txt[0]),txt:txt[1],type:txt[2]});}     }
}
// послать сообщение
function send_nessage()
{	if (cur_chat && isChatAtive())
	{
          $('chid').value = cur_chat;
		  var status = AjaxRequest.submit( document.forms.form2,
		    {
		      'onSuccess':function(req){ txt = req.responseText; if (txt!=0) add_message(txt); }
		    }
		  );

		$('chat'+cur_chat).value='';
		$('message').value = '';
		$('message').focus();
    }}

// добавить смайл
function smail(t)
{    v = $('message').value;
	$('message').value = v+'[:'+smail_l[t]+':]';
    $('message').focus();}

//закрытие всех активных чатов
function closeAllchats()
{	var i=0;
	while(start_act_chat[i]){
		unActiveChat(start_act_chat[i]);
		i++;
	}
	paid = 0;
	window.opener.paid = 0;
    AjaxRequest.get({'url':'/chat.php?action=close_all_chats&user='+user_ID,'onSuccess':function(req){}});}


function opacity()
{
	$(arguments[0]).style.opacity = (arguments[1]/100);
	$(arguments[0]).style.MozOpacity = (arguments[1]/100);
	$(arguments[0]).style.KhtmlOpacity = (arguments[1]/100);
	$(arguments[0]).style.filter = "alpha(opacity="+arguments[1]+")";
}

	//'С вами хотят общаться NAME ';  1
	//'Запрос на чат с NAME отправлен';2
	//'Запрос на чат с NAME принят';3
	//'Запрос на чат с NAME отклонен'; 4
	//'Чат с NAME закрыт'; 6

function addMsgStatusChat(o)
{
	var _o = $('chat_ststus');
	_o.style.display = 'block';
	_o.innerHTML = (o.text||'Error!');
}


function AjaxRequest(){var req =new Object(); req.timeout =null; req.generateUniqueUrl =true; req.url =window.location.href; req.method ="GET"; req.async =true; req.username =null; req.password =null; req.parameters =new Object(); req.requestIndex =AjaxRequest.numAjaxRequests++; req.responseReceived =false; req.groupName =null; req.queryString =""; req.responseText =null; req.responseXML =null; req.status =null; req.statusText =null; req.aborted =false; req.xmlHttpRequest =null; req.onTimeout=null; req.onLoading=null; req.onLoaded=null; req.onInteractive=null; req.onComplete=null; req.onSuccess=null; req.onError=null; req.onGroupBegin=null; req.onGroupEnd=null; req.xmlHttpRequest =AjaxRequest.getXmlHttpRequest(); if(req.xmlHttpRequest==null){return null;}req.xmlHttpRequest.onreadystatechange = function(){if(req==null || req.xmlHttpRequest==null){return;}if(req.xmlHttpRequest.readyState==1){req.onLoadingInternal(req);}if(req.xmlHttpRequest.readyState==2){req.onLoadedInternal(req);}if(req.xmlHttpRequest.readyState==3){req.onInteractiveInternal(req);}if(req.xmlHttpRequest.readyState==4){req.onCompleteInternal(req);}}; req.onLoadingInternalHandled=false; req.onLoadedInternalHandled=false; req.onInteractiveInternalHandled=false; req.onCompleteInternalHandled=false; req.onLoadingInternal= function(){if(req.onLoadingInternalHandled){return;}AjaxRequest.numActiveAjaxRequests++; if(AjaxRequest.numActiveAjaxRequests==1 && typeof(window['AjaxRequestBegin'])=="function"){AjaxRequestBegin();}if(req.groupName!=null){if(typeof(AjaxRequest.numActiveAjaxGroupRequests[req.groupName])=="undefined"){AjaxRequest.numActiveAjaxGroupRequests[req.groupName] =0;}AjaxRequest.numActiveAjaxGroupRequests[req.groupName]++; if(AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==1 && typeof(req.onGroupBegin)=="function"){req.onGroupBegin(req.groupName);}}if(typeof(req.onLoading)=="function"){req.onLoading(req);}req.onLoadingInternalHandled=true;}; req.onLoadedInternal= function(){if(req.onLoadedInternalHandled){return;}if(typeof(req.onLoaded)=="function"){req.onLoaded(req);}req.onLoadedInternalHandled=true;}; req.onInteractiveInternal= function(){if(req.onInteractiveInternalHandled){return;}if(typeof(req.onInteractive)=="function"){req.onInteractive(req);}req.onInteractiveInternalHandled=true;}; req.onCompleteInternal= function(){if(req.onCompleteInternalHandled || req.aborted){return;}req.onCompleteInternalHandled=true; AjaxRequest.numActiveAjaxRequests--; if(AjaxRequest.numActiveAjaxRequests==0 && typeof(window['AjaxRequestEnd'])=="function"){AjaxRequestEnd(req.groupName);}if(req.groupName!=null){AjaxRequest.numActiveAjaxGroupRequests[req.groupName]--; if(AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==0 && typeof(req.onGroupEnd)=="function"){req.onGroupEnd(req.groupName);}}req.responseReceived =true; req.status =req.xmlHttpRequest.status; req.statusText =req.xmlHttpRequest.statusText; req.responseText =req.xmlHttpRequest.responseText; req.responseXML =req.xmlHttpRequest.responseXML; if(typeof(req.onComplete)=="function"){req.onComplete(req);}if(req.xmlHttpRequest.status==200 && typeof(req.onSuccess)=="function"){req.onSuccess(req);}else if(typeof(req.onError)=="function"){req.onError(req);}delete req.xmlHttpRequest['onreadystatechange']; req.xmlHttpRequest =null;}; req.onTimeoutInternal= function(){if(req!=null && req.xmlHttpRequest!=null && !req.onCompleteInternalHandled){req.aborted =true; req.xmlHttpRequest.abort(); AjaxRequest.numActiveAjaxRequests--; if(AjaxRequest.numActiveAjaxRequests==0 && typeof(window['AjaxRequestEnd'])=="function"){AjaxRequestEnd(req.groupName);}if(req.groupName!=null){AjaxRequest.numActiveAjaxGroupRequests[req.groupName]--; if(AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==0 && typeof(req.onGroupEnd)=="function"){req.onGroupEnd(req.groupName);}}if(typeof(req.onTimeout)=="function"){req.onTimeout(req);}delete req.xmlHttpRequest['onreadystatechange']; req.xmlHttpRequest =null;}}; req.process = function(){if(req.xmlHttpRequest!=null){if(req.generateUniqueUrl && req.method=="GET"){req.parameters["AjaxRequestUniqueId"] =new Date().getTime() + "" + req.requestIndex;}var content =null; for(var i in req.parameters){if(req.queryString.length>0){req.queryString +="&";}req.queryString +=encodeURIComponent(i) + "=" + encodeURIComponent(req.parameters[i]);}if(req.method=="GET"){if(req.queryString.length>0){req.url +=((req.url.indexOf("?")>-1)?"&":"?") + req.queryString;}}req.xmlHttpRequest.open(req.method,req.url,req.async,req.username,req.password); if(req.method=="POST"){if(typeof(req.xmlHttpRequest.setRequestHeader)!="undefined"){req.xmlHttpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');}content =req.queryString;}if(req.timeout>0){setTimeout(req.onTimeoutInternal,req.timeout);}req.xmlHttpRequest.send(content);}}; req.handleArguments = function(args){for(var i in args){if(typeof(req[i])=="undefined"){req.parameters[i] =args[i];}else{req[i] =args[i];}}}; req.getAllResponseHeaders = function(){if(req.xmlHttpRequest!=null){if(req.responseReceived){return req.xmlHttpRequest.getAllResponseHeaders();}alert("Cannot getAllResponseHeaders because a response has not yet been received");}}; req.getResponseHeader = function(headerName){if(req.xmlHttpRequest!=null){if(req.responseReceived){return req.xmlHttpRequest.getResponseHeader(headerName);}alert("Cannot getResponseHeader because a response has not yet been received");}}; return req;}AjaxRequest.getXmlHttpRequest =function(){if(window.XMLHttpRequest){return new XMLHttpRequest();}else if(window.ActiveXObject){/*@cc_on @*/ /*@if(@_jscript_version >=5) try{return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{return new ActiveXObject("Microsoft.XMLHTTP");}catch(E){return null;}}@end @*/}else{return null;}}; AjaxRequest.isActive =function(){return(AjaxRequest.numActiveAjaxRequests>0);}; AjaxRequest.get =function(args){AjaxRequest.doRequest("GET",args);}; AjaxRequest.post =function(args){AjaxRequest.doRequest("POST",args);}; AjaxRequest.doRequest =function(method,args){if(typeof(args)!="undefined" && args!=null){var myRequest =new AjaxRequest(); myRequest.method =method; myRequest.handleArguments(args); myRequest.process();}}; AjaxRequest.submit =function(theform, args){var myRequest =new AjaxRequest(); if(myRequest==null){return false;}var serializedForm =AjaxRequest.serializeForm(theform); myRequest.method =theform.method.toUpperCase(); myRequest.url =theform.action; myRequest.handleArguments(args); myRequest.queryString =serializedForm; myRequest.process(); return true;}; AjaxRequest.serializeForm =function(theform){var els =theform.elements; var len =els.length; var queryString =""; this.addField = function(name,value){if(queryString.length>0){queryString +="&";}queryString +=encodeURIComponent(name) + "=" + encodeURIComponent(value);}; for(var i=0;i<len;i++){var el =els[i]; if(!el.disabled){switch(el.type){case 'text': case 'password': case 'hidden': case 'textarea': this.addField(el.name,el.value); break; case 'select-one': if(el.selectedIndex>=0){this.addField(el.name,el.options[el.selectedIndex].value);}break; case 'select-multiple': for(var j=0;j<el.options.length;j++){if(el.options[j].selected){this.addField(el.name,el.options[j].value);}}break; case 'checkbox': case 'radio': if(el.checked){this.addField(el.name,el.value);}break;}}}return queryString;}; AjaxRequest.numActiveAjaxRequests =0; AjaxRequest.numActiveAjaxGroupRequests =new Object(); AjaxRequest.numAjaxRequests =0;
