var PROMPT_IMAGE="/communicator/images/in.gif";
var PROMPT_TIME_OUT=1000*120;
var PROMPT_HEADER="\u0417\u0430\u043f\u0440\u043e\u0441 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u044f...";
var dialog_open = false;
var net=new Object();
var pingcount = 0;

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;
var ERROR_INFORMATION='';

net.ContentLoader=function(url,onload,onerror,method,params,contentType){
  this.req=null;
  this.onload=onload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url,method,params,contentType);
}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){

  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType='application/x-www-form-urlencoded';
  }
  
  if (window.XMLHttpRequest){
    this.req=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    this.req=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (this.req){
    try{
      var loader=this;
      this.req.onreadystatechange=function(){
        if( typeof net !== "undefined")
	     net.ContentLoader.onReadyState.call(loader);
      }
      this.req.open(method,url,true);
      if (contentType){
        this.req.setRequestHeader('Content-Type', contentType);
      }	 
      this.req.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}

net.ContentLoader.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;
  if (ready==net.READY_STATE_COMPLETE){
    var httpStatus=req.status;
    if (httpStatus==200 || httpStatus==0){
      this.onload.call(this);
    }else{	     
      this.onerror.call(this);
    }
  }
}

net.ContentLoader.prototype.defaultError=function(){
  ERROR_INFORMATION="error fetching data!"
                          +"\n\nreadyState:"+this.req.readyState
                          +"\nstatus: "+this.req.status
                          +"\nheaders: "+this.req.getAllResponseHeaders();
}
var urlXML="http://"+location.hostname+"/communicator/libs/ping.php?reffer="+location.href;
var ping_params="";
 ping_params="referrer="+encodeURIComponent(document.referrer);
 ping_params+="&type=1";

jQuery(document).ready(function()
{
	$('body').append('<div style="color:#000;position:fixed;top:200px;left: -265px; background:#CCC; width: 260px; min-height: 200px; padding: 5px 25px 5px 5px;font-size:12px;border-radius:5px;-webkit-border-radius:5px;-moz-border-radius:5px;" id="strip"><a id="closebtn" style="float:right;display:block;padding:2px 5px;margin-right: 11px;background:red;color:#fff;text-decoration:none;" href="#">[x]</a><div class="txt">\u041d\u0430\u0448 \u043a\u043e\u043d\u0441\u0443\u043b\u044c\u0442\u0430\u043d\u0442 \u0433\u043e\u0442\u043e\u0432 \u043e\u0442\u0432\u0435\u0442\u0438\u0442\u044c \u043d\u0430 \u0412\u0430\u0448\u0438 \u0432\u043e\u043f\u0440\u043e\u0441\u044b, \u043d\u0430\u043f\u0438\u0448\u0438\u0442\u0435 \u0447\u0442\u043e \u0432\u0430\u0441 \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u0443\u0435\u0442</div><div><textarea style="width:230px;height:80px;" id="firstMessage"></textarea><input type="submit" onclick="pretext = $(\'#firstMessage\').val();if(navigator.userAgent.toLowerCase().indexOf(\'opera\') != -1 &amp;&amp; window.event.preventDefault) window.event.preventDefault();this.newWindow = window.open(\'/communicator/client.php?locale=ru&msg=\'+pretext, \'communicator\', \'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=600,height=420,resizable=1\');this.newWindow.focus();this.newWindow.opener=window;getchat(this);return false;" target="_blank" value="\u041d\u0430\u043f\u0438\u0441\u0430\u0442\u044c" /></div><div class="btn" style="color:#fff;padding:0 12px;background:#2E9496;height:100%;right:0;top:0;position:absolute;border-radius:5px;-webkit-border-radius:5px;-moz-border-radius:5px;cursor:pointer;font-size:11px;"><div style="height:2px;"></div>\u043a<br>\u043e<br>\u043d<br>\u0441<br>\u0443<br>\u043b<br>\u044c<br>\u0442<br>\u0430<br>\u043d<br>\u0442</div></div>');
	stripper();
	
 if (!jQuery('#add-sticky'))
 {
  $('body').append('<div><a href="#" id="add-sticky"></div>');
 }
});
	
jQuery.extend({	
	ImpromptuDefaults: { prefix:'jqi', buttons:{ Ok:true }, loaded:function(){}, submit:function(){return true;}, callback:function(){}, opacity:0.6, zIndex: 999, overlayspeed:'slow', promptspeed:'fast', show:'fadeIn', focus:0, useiframe:false, top: '100px', persistent: true },
	SetImpromptuDefaults: function(o){ 
		jQuery.ImpromptuDefaults = jQuery.extend({},jQuery.ImpromptuDefaults,o);
	},
	prompt: function(m,o){
		o = jQuery.extend({},jQuery.ImpromptuDefaults,o);
		
		var ie6 = (jQuery.browser.msie && jQuery.browser.version < 7);	
		var b = jQuery(document.body);
		var w = jQuery(window);
		
		var msgbox = '<div class="'+ o.prefix +'box" id="'+ o.prefix +'box">';		
		if(o.useiframe && ((jQuery.browser.msie && jQuery('object, applet').length > 0) || ie6))//if you want to use the iframe uncomment these 3 lines
			msgbox += '<iframe src="javascript:;" class="'+ o.prefix +'fade" id="'+ o.prefix +'fade"></iframe>';
		else{ 
			if(ie6) jQuery('select').css('visibility','hidden');
			msgbox +='<div class="'+ o.prefix +'fade" id="'+ o.prefix +'fade"></div>';
		}	
		msgbox += '<div class="'+ o.prefix +'" id="'+ o.prefix +'"><div class="'+ o.prefix +'container"><div class="'+ o.prefix +'close">X</div><div class="'+ o.prefix +'message">'+ m +'</div><div class="'+ o.prefix +'buttons" id="'+ o.prefix +'buttons">';
        var buttons= '<span class="close" id="error"><input type="button" onclick="if(navigator.userAgent.toLowerCase().indexOf(\'opera\') != -1 &amp;&amp; window.event.preventDefault) window.event.preventDefault();this.newWindow = window.open(\'/communicator/client.php?locale=ru\', \'communicator\', \'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=600,height=420,resizable=1\');this.newWindow.focus();this.newWindow.opener=window;getchat();return false;" target="_blank" value="\u041e\u0442\u0432\u0435\u0442\u0438\u0442\u044c" /></span>';
		msgbox += '</div></div></div></div>';

		var textbox='<div><textarea id="firstMessage"></textarea></div>';

	var unique_id = $.gritter.add({
	// (string | mandatory) the heading of the notification
	title: PROMPT_HEADER,
	// (string | mandatory) the text inside the notification
	text: m+textbox+buttons,
	// (string | optional) the image to display on the left
	image: PROMPT_IMAGE,
	// (bool | optional) if you want it to fade out on its own or just sit there
	sticky: false, 
	// (int | optional) the time you want it to be alive for before fading out
	time: PROMPT_TIME_OUT,
	before_close : function(){
		session = Get_Cookie('PHPSESSID');
		$.get('/communicator/libs/ping.php',{forced_closed:session});
		
	}
	});

		
/*		var jqib =b.append(msgbox).children('#'+ o.prefix +'box');
		var jqi = jqib.children('#'+ o.prefix);
		var jqif = jqib.children('#'+ o.prefix +'fade');

		var getWindowScrollOffset = function(){ 
			return (document.documentElement.scrollTop || document.body.scrollTop) + 'px'; 
		};		
		
		var getWindowSize = function(){ 
			var size = {
				width: window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth),
				height: window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight)
			};
			return size;
		};
		
		var ie6scroll = function(){ 
			jqib.css({ top: getWindowScrollOffset() }); 
		};
		
		var fadeClicked = function(){
			if(o.persistent){
				var i = 0;
				jqib.addClass(o.prefix +'warning');
				var intervalid = setInterval(function(){ 
					jqib.toggleClass(o.prefix +'warning');
					if(i++ > 1){
						clearInterval(intervalid);
						jqib.removeClass(o.prefix +'warning');
					}
				}, 100);
			}
			else removePrompt();
		};		
		

		var escapeKeyClosePrompt = function(e){
			var key = (window.event) ? event.keyCode : e.keyCode; // MSIE or Firefox?
			if(key==27) removePrompt();
		};

		var positionPrompt = function(){
			var wsize = getWindowSize();
			jqib.css({ position: (ie6)? "absolute" : "fixed", height: wsize.height, width: "100%", top: (ie6)? getWindowScrollOffset():0, left: 0, right: 0, bottom: 0 });
			jqif.css({ position: "absolute", height: wsize.height, width: "100%", top: 0, left: 0, right: 0, bottom: 0 });
			jqi.css({ position: "absolute", top: o.top, left: "50%", marginLeft: ((((jqi.css("paddingLeft").split("px")[0]*1) + jqi.width())/2)*-1) });					
		};
		
		var stylePrompt = function(){
			jqif.css({ zIndex: o.zIndex, display: "none", opacity: o.opacity });
			jqi.css({ zIndex: o.zIndex+1, display: "none" });
			jqib.css({ zIndex: o.zIndex });
		}
		
		var removePrompt = function(callCallback, clicked, msg){
			jqi.remove(); 
			if(ie6)b.unbind('scroll',ie6scroll);//ie6, remove the scroll event
			w.unbind('resize',positionPrompt);			
			jqif.fadeOut(o.overlayspeed,function(){
				jqif.unbind('click',fadeClicked);
				jqif.remove();
				if(callCallback) o.callback(clicked,msg);
				jqib.unbind('keypress',escapeKeyClosePrompt);
				jqib.remove();
				if(ie6 && !o.useiframe) jQuery('select').css('visibility','visible');
			});
		}
		
		positionPrompt();
		stylePrompt();	 
		
		if(ie6) w.scroll(ie6scroll);
		jqif.click(fadeClicked);
		w.resize(positionPrompt);
		jqi.find('.'+ o.prefix +'close').click( function(){
		  removePrompt();
		  $.post(urlXML,{stop_chat:"yes"});
		});
		jqi.find('.close').click(removePrompt);
		jqif.fadeIn(o.overlayspeed);
		jqi[o.show](o.promptspeed,o.loaded);
		jqi.find('#'+ o.prefix +'buttons button:eq('+ o.focus +')').focus();
		return jqib;
*/
	}
});

function handleServerResponse() 
{ 
   var xmlResponse = this.req.responseXML;      
   var xmlRoot = xmlResponse !== null ? xmlResponse.documentElement : null;
   var openchat = xmlResponse !== null ? xmlRoot.getElementsByTagName("openchat") : null;
   if(openchat !== null){
   if(openchat.length>0){  	
    if(openchat.item(0).firstChild.data!==null){
/*
if(/microsoft/i.test(navigator.appName))
{
	openchat.item(0).firstChild.data = 'test';
}
*/
    	chat_win = Get_Cookie('PHPSESSID');
    	
    	$('#strip .txt').html(openchat.item(0).firstChild.data);
    	if(dialog_open == false)
    	$('#strip').stop().animate({left:'0px'},500);
    	
    /*  				$.prompt(openchat.item(0).firstChild.data,{
					callback: function(v,m){
					}
				});
		*/
	} 
   }
  }
} 

function common(){
 pingcount++;
 if(pingcount > 20)
 	clearInterval(interval);

 urlXML="http://"+location.hostname+"/communicator/libs/ping.php";
 if (ping_params!="")
 {
  ping_params+="&";
 }
 ping_params+="&location="+encodeURIComponent(location.href);
 ping_params+="&title="+encodeURIComponent(document.title);

 new net.ContentLoader(urlXML,handleServerResponse,net.ContentLoader.defaultError,"POST",ping_params);
 ping_params="";
}

$(document).ready(function(){
	common();
	$('#closebtn').click(function(){
		closeStriper();
	});
});

var interval = setInterval("common()", 4000);

function getchat(obj)
{
	$.ajaxSetup({
		scriptCharset: "utf-8" 
	});
	var msg = $("#firstMessage").val();

	$.post('/communicator/client.php?locale=ru&type=answer',{ajax:true,msg:msg},function(d){

		var postdata = {
				act		: 'post',
				thread	: d.thread,
				token	: d.token,
				lastid	: 0,
				user	: true,
				message	: msg,
				_		: '',
				first_message : 1
			};

			$.post('/communicator/thread.php?first_message=1',postdata,function(){
					$('#strip').stop().animate({left:'-275px'},500);
					$('#firstMessage').val('');

			});
			var chaturl = '/communicator/client.php?thread='+d.thread+'&token='+d.token+'&level=ajaxed';
		//	window.open(chaturl,'commnunicator', 'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=600,height=450,resizable=1');
		},'json');
	return false;
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function stripper()
{
	$('#strip .btn').toggle(
			function(){
				$(this).parent().stop().animate({left:'0px'},500);
			},
			function(){
				closeStriper();
			}
	);
}
function closeStriper()
{
	$('#strip').stop().animate({left:'-265px'},500);
	session = Get_Cookie('PHPSESSID');
	$.get('/communicator/libs/ping.php',{forced_closed:session});
}


