//#####################-----REALPLEXOR START------####################

// Constructor.
// Create new Dklab_Realplexor object.
function Dklab_Realplexor(fullUrl, namespace, viaDocumentWrite)
{
	// Current JS library version.
	var VERSION = "1.24";

	// Detect current page hostname.
	var host = 'dowith.ru';

	// Assign initial properties.
	if (!this.constructor._registry) this.constructor._registry = {}; // all objects registry
	this.version = VERSION;
	this._map = {};
	this._realplexor = null;
	this._namespace = namespace;
	this._login = null;
	this._iframeId = "mpl" + (new Date().getTime());
	this._iframeTag =
		'<iframe'
		+ ' id="' + this._iframeId + '"'
		+ ' onload="' + 'Dklab_Realplexor' + '._iframeLoaded(&quot;' + this._iframeId + '&quot;)"'
		+ ' src="' + fullUrl + '?identifier=IFRAME&amp;HOST=' + host + '&amp;version=' + this.version + '"'
		+ ' style="position:absolute; width:200px; display:none; height: 200px; left: -1000px"' +
		'></iframe>';
	this._iframeCreated = false;
	this._needExecute = false;
	this._executeTimer = null;

	// Register this object in the registry (for IFRAME onload callback).
	this.constructor._registry[this._iframeId] = this;

	// Validate realplexor URL.
	if (!fullUrl.match(/^\w+:\/\/([^/]+)/)) {
		throw 'Dklab_Realplexor constructor argument must be fully-qualified URL, ' + fullUrl + ' given.';
	}
	var mHost = RegExp.$1;
	if (mHost != host && mHost.lastIndexOf("." + host) != mHost.length - host.length - 1) {
		throw 'Due to the standard XMLHttpRequest security policy, hostname in URL passed to Dklab_Realplexor (' + mHost + ') must be equals to the current host (' + host + ') or be its direct sub-domain.';
	}

	// Create IFRAME if requested.
	if (viaDocumentWrite) {
		document.write(this._iframeTag);
		this._iframeCreated = true;
	}

	// Allow realplexor's IFRAME to access outer window.
	document.domain = 'dowith.ru';
}

// Static function.
// Called when a realplexor iframe is loaded.
Dklab_Realplexor._iframeLoaded = function(id)
{
	var th = this._registry[id];
	// use setTimeout to let IFRAME JavaScript code some time to execute.
	setTimeout(function() {
		var iframe = document.getElementById(id);
		th._realplexor = iframe.contentWindow.Dklab_Realplexor_Loader;
		if (th.needExecute) {
			th.execute();
		}
	}, 50);
}

// Set active login.
Dklab_Realplexor.prototype.logon = function(login) {
	this._login = login;
}

// Set the position from which we need to listen a specified ID.
Dklab_Realplexor.prototype.setCursor = function(id, cursor) {
	if (!this._map[id]) this._map[id] = { cursor: null, callbacks: [] };
	this._map[id].cursor = cursor;
	return this;
}

// Subscribe a new callback to specified ID.
// To apply changes and reconnect to the server, call execute()
// after a sequence of subscribe() calls.
Dklab_Realplexor.prototype.subscribe = function(id, callback) {
	if (!this._map[id]) this._map[id] = { cursor: null, callbacks: [] };
	var chain = this._map[id].callbacks;
	for (var i = 0; i < chain.length; i++) {
		if (chain[i] === callback) return;
	}
	chain.push(callback);
	return this;
}

// Unsubscribe a callback from the specified ID.
// You do not need to reconnect to the server (see execute())
// to stop calling of this callback.
Dklab_Realplexor.prototype.unsubscribe = function(id, callback) {
	if (!this._map[id]) return;
	if (callback == null) {
		this._map[id].callbacks = [];
		return;
	}
	var chain = this._map[id].callbacks;
	for (var i = 0; i < chain.length; i++) {
		if (chain[i] === callback) {
			chain.splice(i, 1);
			return;
		}
	}
	return this;
}

// Reconnect to the server and listen for all specified IDs.
// You should call this method after a number of calls to subscribe().
Dklab_Realplexor.prototype.execute = function() {
	// Control IFRAME creation.
	if (!this._iframeCreated) {
		var div = document.createElement('DIV');
		div.innerHTML = this._iframeTag;
		document.body.appendChild(div);
		this._iframeCreated = true;
	}

	// Check if the realplexor is ready (if not, schedule later execution).
	if (this._executeTimer) {
		clearTimeout(this._executeTimer);
		this._executeTimer = null;
	}
	var th = this;
	if (!this._realplexor) {
		this._executeTimer = setTimeout(function() { th.execute() }, 30);
		return;
	}

	// Realplexor loader is ready, run it.
	this._realplexor.execute(
		this._map,
		this.constructor._callAndReturnException,
		(this._login != null? this._login + "_" : "") + (this._namespace != null? this._namespace : "")
	);
}

// This is a work-around for stupid IE. Unfortunately IE cannot
// catch exceptions which are thrown from the different frame
// (in most cases). Please see
// http://blogs.msdn.com/jaiprakash/archive/2007/01/22/jscript-exceptions-not-handled-thrown-across-frames-if-thrown-from-a-expando-method.aspx
Dklab_Realplexor._callAndReturnException = function(func, args) {
	try {
		func.apply(null, args);
		return null;
	} catch (e) {
		return "" + e;
	}
}

//##################-----REALPLEXOR END----##################

tagsStorage = new Object;
tagsStorage.exp = new Array;
tagsStorage.nowExpandedAdvanse = new Array;


function TagExpandAdvansed(tagId,opt)
{
	AllToSimpleAdvansed();

	var defOpt = {target:'tagBox_',topOffset:6,topOffsetIE6:16} ;
	var topOffset = 6;
	if(isObject(opt))
	{
		for(var a in opt)
		{
			defOpt[a] = opt[a];
		}
	}

	if(IE6){defOpt.topOffset = defOpt.topOffsetIE6;}   // ie6 must die! ^_^
	if(typeof(tagsStorage.nowExpandedAdvanse[tagId])!='undefined')
	{
		tagsStorage.nowExpandedAdvanse[tagId].show();
		var k = tagsStorage.nowExpandedAdvanse[tagId].getPosition();
        tagsStorage.nowExpandedAdvanse[tagId].setPagePosition(k[0],k[1]+defOpt.topOffset);
        tagsStorage.nowExpandedAdvanse[tagId].timer = setTimeout('tagsStorage.nowExpandedAdvanse['+tagId+'].hide()',10000);
		return ;
	}

	var html = gd('tagExpand_'+tagId);
	var ToolTipIni = {
        target: defOpt.target+tagId,
        anchor: 'bottom',
        dismissDelay: 10000,
        autoHide:false,
        anchorOffset: (Ext.get(defOpt.target+tagId).getWidth()/2)-30 // center the anchor on the tooltip
    };

    // autoload or atatic

    if(trim(html.substr(0,6))=='submit')
    {
    	ToolTipIni.autoLoad =
    	{
    		url: html.replace(/&amp;/g,'&'),
    		tag_id: tagId,
    		callback:function(a,b,c,request)
    		{
    			tagsStorage.nowExpandedAdvanse[request.tag_id].show();
    		}
    	};
    }else{
    	ToolTipIni.html = html;
    }

	// render
    tagsStorage.nowExpandedAdvanse[tagId] = new Ext.ToolTip(ToolTipIni);
    tagsStorage.nowExpandedAdvanse[tagId].show();
    var k = tagsStorage.nowExpandedAdvanse[tagId].getPosition();
    tagsStorage.nowExpandedAdvanse[tagId].setPagePosition(k[0],k[1]+defOpt.topOffset);
    tagsStorage.nowExpandedAdvanse[tagId].timer = setTimeout('tagsStorage.nowExpandedAdvanse['+tagId+'].hide()',10000);

}

function AllToSimpleAdvansed()
{
	for(var id in tagsStorage.nowExpandedAdvanse)
	{
		if(tagsStorage.nowExpandedAdvanse[id] && parseInt(id))
		{
			tagsStorage.nowExpandedAdvanse[id].hide();
			clearTimeout(tagsStorage.nowExpandedAdvanse[id].timer);
			//tagsStorage.nowExpandedAdvanse[id] = 0;
		}
	}
}



// Micro Blog Answer functions
function MBAnswer(id)
{
	var idProtect = id; //из за быдлокодеров, которые юзают глобальные переменные,
						//приходится самому становится быдлокодером (c).
	var title = '';
	if(idProtect!=-1){title = ge('qdata_'+idProtect).innerHTML;}
	var form = ge('microBlogForm_f');
	form.title.value = title;
	form.pd_questionId.value = idProtect;
	ge('microBlogForm').style.display = 'block';
	var curLoc = window.location.toString();
	if(curLoc.substr(-4)!='MBFA'){window.location += '#MBFA';}else{window.location = curLoc;}
}

// ротатер
var RotateBoxContainer = new Object;
var RBCounter = 0;
var RBOffset = 0;
function RotateBox(fromDiv,toDiv,opt)
{
	this.curIndex = 0;
	this.duration = 1.5;   //sec
	this.timeToShow = 10000; //msec
	this.id = RBCounter;
	if(typeof(opt)=='undefined'){var opt = new Object;}
	//if(typeof(opt.offsetTime)=='number'){this.offsetTime = opt.offsetTime;}else{this.offsetTime = 0;}
	this.offsetTime = RBOffset;
	RBOffset+=3000;
	if(typeof(opt.timeToShow)=='number'){this.timeToShow = opt.timeToShow;}
	//alert(this.offsetTime);

	RBCounter++;
	this.autoShowNext = true;

	this.fromDiv = fromDiv;
	this.toDiv = toDiv;
	this.fromEl = ge(fromDiv);
	this.toEl = ge(toDiv);

	RotateBoxContainer[this.id] = this;
	this.getChildMass();
	if(!this.childMass[0]){return ;}
	this.toEl.appendChild(this.childMass[0]);
	this.go();
}

RotateBox.prototype.getChildMass = function()
{
	this.childMass = new Array;  //child elements array
	this.childMass = MyDOMGetChilds(this.fromEl);
}

RotateBox.prototype.go = function()
{
	setTimeout("RotateBoxContainer["+this.id+"].changeToNext()",this.timeToShow+this.offsetTime);
	//setTimeout("RotateBoxContainer["+this.id+"].go()",this.timeToShow);
}

RotateBox.prototype.showNext = function()
{
	var nextEl,nextIndex;
	if(this.curIndex>=(this.childMass.length-1)){nextIndex = 0;}else{nextIndex = this.curIndex+1;}

	nextEl = this.childMass[nextIndex];  //show next element
	nextEl.style.display = 'none';

//alert(Ext.get(nextEl).getViewSize().height);
//Ext.get(this.toEl).autoHeight(true);
	this.toEl.appendChild(nextEl);
	//alert(Ext.get(this.toEl).getHeight());
	Ext.get(this.toEl.firstChild).show({duration:this.duration});
	if(this.autoShowNext)
	{
		setTimeout("RotateBoxContainer["+this.id+"].changeToNext()",this.timeToShow);
	}
	//alert(Ext.get(this.toEl).getHeight());
	nextEl.style.display = 'block';


	this.curIndex = nextIndex;
}

RotateBox.prototype.hideCallback = function()
{
	this.toEl.removeChild(this.toEl.firstChild); // remove
	if(this.autoShowNext){this.showNext();}
}

RotateBox.prototype.changeToNext = function()
{
	Ext.get(this.toEl.firstChild).hide({duration:this.duration});
	setTimeout("RotateBoxContainer["+this.id+"].hideCallback()",this.duration*1000+500);
}

function PutSampleTag(tid, toBox)
{
	var el = ge(tid);
	var box = ge(toBox);
	var textInBox = box.value;
	var tagText = el.innerHTML;

	if(textInBox.indexOf(tagText)+1){return ;}  // if already exist
	if(!textInBox || textInBox.substr(-2)==', '){var glue = '';}else{var glue = ', ';}
	if(textInBox.substr(-1)==','){glue = ' ';}


	box.value +=  glue+tagText;
}
// ********************** IM ******************
function IM(opId)
{
	this.opponent_id = opId;
	this.logBoxId = 'im_log_'+opId;
	this.statusBox = ge('imStatusBox_'+opId);
	this.textArea = ge('imTextArea_'+opId);
	this.progressImg = ge('progress_'+opId);
	this.dateObject  = new Date();
	this.lastMessageTime = this.dateObject.getTime();
	this.minDelayForUpdate = 7;

	this.offsetLog = 0;

	Ext.select('.imHistoryLink').on('click',
		function(ev,el)
		{
			var opid = el.getAttribute('opid');
			IMContainer[opid].showHistory();
		}
	);

	var dwrapped = new Ext.Resizable(this.textArea, {
		wrap:true,
		pinned:true,
		handles: 's',
		minHeight: 150,
		listeners:{beforeresize:function (){Ext.getBody().setStyle('overflow-x','hidden');},resize:function (){Ext.getBody().setStyle('overflow-x','auto');}},
		dynamic: true
	});



	this.scrollDown();
}

IM.prototype.showHistory = function()
{
	window.open('ajax.php?ln=_im_history&_page=1&opId='+this.opponent_id,'history','width=600,height=400,toolbar=no,location=no,resizable=no,menubar=no,scrollbars=yes');
}

IM.prototype.setStatus= function(status)
{
	this.statusBox.innerHTML = status;
}

IM.prototype.addToLog = function(str)
{
	if(!str){return ;}
	//Ext.get(this.logBoxId).update(ge(this.logBoxId).innerHTML + str,true);
	Ext.get(this.logBoxId).update(str,true);
	this.scrollDown();
}


IM.prototype.scrollDown = function()
{
	//alert(this.logBoxId);
	var objDiv = ge(this.logBoxId);
	if(objDiv=='undefined' || !objDiv){return ;}
	objDiv.scrollTop = objDiv.scrollHeight;
}

IM.prototype.submitMessageForm = function()
{
	var form = ge('imMessageForm_'+this.opponent_id);
	if(!form.text.value){return ;}
	this.setStatus('Идет отправка сообщения..');

	Ext.Ajax.request({
		url: 'submit.php?pd_act=IM_messageAdd&clear=1&offsetLogMid='+this.offsetLogMid,
		method: 'POST',
		source:this,
		success: IMContainer[this.opponent_id].submitMessageFormSuccess,
		failure: IMContainer[this.opponent_id].submitMessageFormFailure,
		params: {text: form.text.value, pd_to: form.pd_to.value }
	});

	this.textArea.disabled = true;
}
IM.prototype.submitMessageFormSuccess = function(response,request)
{
	request.source.textArea = ge('imTextArea_'+request.source.opponent_id);
	request.source.setStatus('');
	request.source.textArea.disabled = false;
	request.source.textArea.value = '';
	request.source.textArea.focus();
	request.source.updateLogAdd(response.responseText);
}

IM.prototype.submitMessageFormFailure = function(response,request)
{
	request.source.setStatus('Не удалось отправить сообщение');
	request.source.textArea.disabled = false;
}

IM.prototype.updateLog = function(text)
{
	Ext.get('im_log_'+this.opponent_id).update(text+'<script>IMContainer['+this.opponent_id+'].scrollDown();</script>',true);
}

IM.prototype.updateLogAdd = function(text)
{
	var was = ge('im_log_'+this.opponent_id).innerHTML;
	Ext.get('im_log_'+this.opponent_id).update(was+text+'<script>IMContainer['+this.opponent_id+'].scrollDown();</script>',true);
}

/*
IM.prototype.startUpdateLog = function()
{
	// check observer
	//alert(this.offsetLogMid);
	//if(!IM.prototype.checkObserver(this.opponent_id)){this.onBadObserver();return ;}   !!!!!!

	this.progressImg.style.display = 'inline';
	var url = "submit.php?clear=1&pd_act=IM_getNewMessages&opId="+this.opponent_id+"&offsetLogMid="+this.offsetLogMid;
	var dateObj = new Date();
	var delay = (dateObj.getTime()-this.lastMessageTime)/1000/9;

    //this.setStatus(delay);
	if(delay<this.minDelayForUpdate){delay = this.minDelayForUpdate;}  //sec
	if(dateObj.getTime()-this.lastMessageTime<90000){delay = this.minDelayForUpdate;} // first 90 second max speed
	if(delay>300){delay = 300;}

	delay = delay*1000;

	if(!Ext.get('im_log_'+this.opponent_id)){return ;} // if close
                                             n
	Ext.get('im_loaderBox_'+this.opponent_id).load({
        url: url,
        source: this,
        disableCaching:true,
        nocache:true,
       // scripts: true,
        text: "Loading...",
        callback:IMContainer[this.opponent_id].startUpdateLogCallback
   });

   this.startUpdateLogTimer = setTimeout("IMContainer["+this.opponent_id+"].startUpdateLog()",delay);
}
*/

IM.prototype.startUpdateLog = function()
{
	var rpe = new RPE();
	rpe.listen('im'+this.opponent_id,{callback:IMContainer[this.opponent_id].onGetNewMessage,rpCallback:IMContainer[this.opponent_id].rpSyncReaded, scope: IMContainer[this.opponent_id], requestVars:{}});
}

IM.prototype.onGetNewMessage = function(messageObject)
{
	var ob = this;
	if(!Ext.get('im_log_'+ob.opponent_id)){return ;}     // if close
	ob.updateLogAdd(messageObject.log);
	//alert(messageObject.log);
	if(parseInt(getCookie('remix_im_sound'))){ob.playNewMessageAlert();}
	ob.setTabAsWithNewMessages();
}

IM.prototype.rpSyncReaded = function()
{
	Ext.Ajax.request({
		url: 'submit.php?pd_act=IM_rpSyncReaded&clear=1&opId='+this.opponent_id,
		success: this.ajaxOnAnswer,
		method: 'GET'
	});
}

/*
IM.prototype.startUpdateLogCallback = function(a,b,response,c)
{
	c.source.progressImg.style.display = 'none';
	response.responseText = trim(response.responseText);
	if(!response.responseText){return ;}

	var dateObj = new Date();
	c.source.lastMessageTime = dateObj.getTime();

	clearTimeout(c.source.startUpdateLogTimer);
	if(!Ext.get('im_log_'+c.source.opponent_id)){return ;}     // if close
	c.source.startUpdateLogTimer = setTimeout("IMContainer["+c.source.opponent_id+"].startUpdateLog()",c.source.minDelayForUpdate*1000);

	c.source.updateLog(response.responseText);
	if(parseInt(getCookie('remix_im_sound'))){c.source.playNewMessageAlert();}
	c.source.setTabAsWithNewMessages();

	return true;
}
*/


IM.prototype.onTabActivate = function()
{
	ge('im_tabTitle_'+this.opponent_id).className = '';
	this.scrollDown();
}

IMObserverContainer = new Array(); //  <--
IM.prototype.onBadObserver = function()
{
	//Ext.get('im_sd_box_'+this.opponent_id).mask('Диалог с этим пользователем был открыт в каком-то другом месте.<br/> Вы не можете иметь несколько открытых окон для одного собеседника.');
}

IM.prototype.setTabAsWithNewMessages = function()
{
	if(imTabPanel.getActiveTab().id == imTabPanel.getItem('u_'+this.opponent_id).id){return ;}  // if this tab open
	ge('im_tabTitle_'+this.opponent_id).className = 'ico_newMessage i';
}

IM.prototype.setObserver = function(contactId)
{
	//if(typeof(IMObserverContainer)=='undefined'){IMObserverContainer = new Array();}
	var dateObj = new Date();
	var uniq = dateObj.getTime();
	var expire = 36000;

	var cookName = 'remix_im_observer_'+contactId;
	setCookie(cookName,uniq,expire);
	IMObserverContainer[contactId] = uniq; // set cookie
	return uniq;
}

IM.prototype.getObserver = function(contactId,opt)
{
	if(!isObject(opt)){opt = new Object;}

	var cookName = 'remix_im_observer_'+contactId;
	var cur = getCookie(cookName);
	if(!cur && opt.setIfNotExist)
	{
		return window.IM.prototype.setObserver(contactId);
	}

	return cur;
}

IM.prototype.checkObserver = function(contactId,opt)
{
	if(!isObject(opt)){opt = new Object;}
	if(opt.setIfNotExist){var setINE = true;}else{var setINE = false;}

	if(window.IM.prototype.getObserver(contactId,{setIfNotExist:setINE})!=IMObserverContainer[contactId]){return false;}
	return true;
}

IM.prototype.clearObserver = function(contactId)
{
	var cookName = 'remix_im_observer_'+contactId;
	setCookie(cookName,'');

	return true;
}

IM.prototype.clearObserverForThisTab = function(contactId)
{
	IMObserverContainer[contactId] = false;
	return true;
}



IM.prototype.playNewMessageAlert = function()
{
	var delay = 5000;
	var dateObj = new Date();
	var alertId = dateObj.getTime();
	var html =
'<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="1" HEIGHT="1">\
 <PARAM NAME="movie" VALUE="img/newmes.swf">\
 <PARAM NAME="quality" VALUE="high">\
 <PARAM NAME="bgcolor" VALUE="#FFFFFF">\
 <EMBED src="img/newmes.swf" quality="high" bgcolor="#FFFFFF" WIDTH="1" HEIGHT="1" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>\
</OBJECT>';
	html = '<div id="im_newMesAlert_'+alertId+'">'+html+'</div>';
	ge('data2').innerHTML+=html;

	setTimeout("Ext.get('im_newMesAlert_"+alertId+"').remove();",delay);

	return true;
}

IM.prototype.showHistory = function(b)
{
	var w = new Ext.Window(
	{
		title:'История сообщений',
		closable: true,
		width:500,
		height:500,
		preventBodyReset:true,
		autoScroll:true,
		autoLoad:{url:"submit.php?clear=1&pd_act=IM_getHistory&opId="+b.contact_id}
	}).show();
	return true;
}

function ImOnSelectContact(contactId)
{
	if(imTabPanel.getItem('u_'+contactId)){imTabPanel.getItem('u_'+contactId).show(); return ;}
	window.IM.prototype.setObserver(contactId);
	var newTab = imTabPanel.add({
            title: '<span id="im_tabTitle_'+contactId+'">'+ge('im_cname_'+contactId).innerHTML+'</span>',
            //title:'<span id="im_tabTitle_'+contactId+'">Загрузка..</span>',
            id: 'u_'+contactId,
            contactId:contactId,
            listeners: {'activate': ImOnTabActivate,'close':ImOnTabBeforeClose},
            autoLoad: {url:'ajax.php?ln=_im_show_dialog_simple&with='+contactId,scripts:true,disableCaching:true,nocache:true},
            closable:true,
            autoHeight:true,
            autoWidth:true,
            tbar:[{text:'Показать всю историю',contact_id: contactId,iconCls: 'icoClsHistory',listeners: {click: window.IM.prototype.showHistory}}],
            autoShow: true
        });

          newTab.show();
        // setActiveTab()
        //alert(print_r(imTabPanel.items.findById(contactId)));
        //alert(imTabPanel.getItem(contactId).getUpdater());

}

function ImOnContatcListActivate(tab)
{
	if(!tab.wasLoaded){tab.wasLoaded = true; return ;}
	tab.getUpdater().update(tab.autoLoad);
}

function ImOnTabActivate(tab)
{
	if(typeof(IMContainer)=='undefined' || typeof(IMContainer[tab.contactId])=='undefined'){return ;}
	IMContainer[tab.contactId].onTabActivate();
}

function ImOnTabBeforeClose(tab)
{
	if(typeof(IMContainer)=='undefined' || typeof(IMContainer[tab.contactId])=='undefined'){return ;}
	window.IM.prototype.clearObserverForThisTab(tab.contactId);
	if(CONFIG.RPE_MODE == 'rp')
	{
		RP_obj.unsubscribe(USER.mesKey+'_im'+tab.contactId,null);
		RP_obj.execute();
	}
	//clearTimeout(IMContainer[tab.contactId].startUpdateLogTimer);
}

/* sendMessageToUser */
function OpenIM(uid,second)
{
	var url = 'im.php?cw='+uid;
	var wnd = window.open('','imwindow','status=0,toolbar=0,location=0,menubar=0');
	try{
		//alert(print_r(wnd.IM));
	    if(!wnd.IM)
	    {
	    	wnd.document.location.href = url;
	    }else{
	    	alert('Окно сообщений уже открыто :)');
	    	if(uid){wnd.ImOnSelectContact(uid)};
	    	wnd.focus();
	    }
	 }catch(e){
	 alert('catch');
	 	wnd.close();
	 	if(!second){OpenIM(uid,true);}
	 }

}

/***** messages upater *****/
function UpdateNewMessagesCounter(f)
{
	var delay = 30000;  // ms
	//var delay = 0;  // ms
	if(f){GLOBALS.updateNewMesFTimer = setTimeout('UpdateNewMessagesCounter()',delay); return ;}
	Ext.Ajax.request({
		url: 'submit.php?pd_act=getNewMessagesCounter&clear=1',
		method: 'GET',
		success: UpdateNewMessagesCounterSuccess
		//failure: UpdateNewMessagesCounterFailure,
	});
}

function UpdateNewMessagesCounterSuccess(request)
{
	var delay = 60000;
	//var delay = 5000;
	var boxId = 'NMC';  // 'new mes counter'
	var answer = request.responseText;
	var clearCounter = 0;

	try{
		var jsonData = Ext.util.JSON.decode(answer);
	}catch (err){
		clearTimeout(GLOBALS.updateNewMesFTimer);
		GLOBALS.updateNewMesFTimer = setTimeout('UpdateNewMessagesCounter()',delay);
		return ;
	}

	for(var i = 0;i<jsonData.length;i++)
	{
		//if(window.IM.prototype.checkObserver(jsonData[i].from)){continue ;}
		clearCounter++;
	}

	if(clearCounter){ge(boxId).innerHTML = '('+clearCounter+')';}else{ge(boxId).innerHTML = '';}
	setTimeout('UpdateNewMessagesCounter()',delay);
}

function updateMBNoteRating(nid,rating)
{
	var d='',t = '';
	if(rating>0){t = "pos";d = '+';}
	if(rating==0){t = "nor";}
	if(rating<0){t = "neg";}
	ge("mbrl_"+nid).innerHTML = '<span class="'+t+'">'+d+rating+'</span>';
}

function KarmaSimpleUpdate(delta)
{
	ge('karmaVal').innerHTML = (0+parseInt(ge('karmaVal').innerHTML)+delta);
}

/* microblog edit*/
var mbOldValueContainer = new Object;
function microblogEditNote(nid)
{
	// adjustWidth getBox getComputedHeight getHeight
	var elid = 'mb_textbox_'+nid;
	var el = ge(elid);
	if(el.getAttribute('editing') && el.getAttribute('editing')!='0')
	{
		el.innerHTML = mbOldValueContainer[nid];
		el.setAttribute('editing',0);
		ge('mbOptBox_'+nid).style.display = 'block';
		return ;
	}

	el.setAttribute('editing',1);
	var extEl = Ext.get(elid);
	mbOldValueContainer[nid] = el.innerHTML;
	ge('mbOptBox_'+nid).style.display = 'none'; // hide links

	if (USER.rating < 300) {
		el.innerHTML = '\
		<form target="uploader" onsubmit="onsf(this.id);" id="mbEdFs'+nid+'" method="POST" action="submit.php"  onkeypress="ctrlEnter(event, this)";>\
			<textarea name="text" class="mb_editNoteTA" style="width:'+(extEl.getWidth()-2)+'px;height:'+extEl.getHeight()+'px;">'+el.innerHTML.replace(/<br>/g,"")+'</textarea>\
			<input type="hidden" name="pd_nid" value="'+nid+'">\
			<input type="hidden" name="pd_act" value="microblogEdit">\
		</form>\
		<span class="button1"><a onclick="sf(\'mbEdFs'+nid+'\');" class="pointer">Сохранить</a></span>\
		<span class="button1"><a onclick="microblogEditNote('+nid+');" class="pointer">Отмена</a></span>\
		';
	} else {

	var microblogText = el.innerHTML;
	el.innerHTML = '\
	<form target="uploader" onsubmit="onsf(this.id);" id="mbEdFs'+nid+'" method="POST" action="submit.php"  onkeypress="ctrlEnter(event, this)";>\
	<div id="microblogEditNoteEditor_'+nid+'"></div>\
	<input type="hidden" name="pd_nid" value="'+nid+'">\
	<input type="hidden" name="pd_act" value="microblogEdit">\
	</form>\
	<span class="button1"><a onclick="sf(\'mbEdFs'+nid+'\');" class="pointer">Сохранить</a></span>\
	<span class="button1"><a onclick="microblogEditNote('+nid+');" class="pointer">Отмена</a></span>\
	';
		Ext.QuickTips.init();
		var htmlEd = new Ext.form.HtmlEditor({
		    width: ge('mbOptBox_'+nid).getWidth + 5,
		    height: ge('mbOptBox_'+nid).getHeight - 100,
			renderTo: 'microblogEditNoteEditor_' + nid,
		    enableFont:false,
		    enableLinks:false,
		    enableSourceEdit:true,
		    enableLists:false,
		    enableColors:false,
		    enableFont:false,
		    enableFontSize:false,
		    enableAlignments:true,
		    value: microblogText,
		    name: 'text'
		});
	}
}

function microblogEditNoteOnGoodSave(nid)
{
	var elid = 'mb_textbox_'+nid;
	var el = ge(elid);
	el.setAttribute('editing',0);
	el.innerHTML = ge('mbEdFs'+nid).text.value.replace(/\n/g,"\n<br>");
	ge('mbOptBox_'+nid).style.display = 'block';
}

/* arrow control */
var arrowControlContainer  = new Object;
function arrowControl(toElId,boxId, callbacks)
{
	this.boxId = boxId;
	this.id = toElId;
	this.callbacks = callbacks;
	this.currentNum = 0; // 1 2 3 4 1 2 3 4 1 ...
	new Ext.KeyMap(toElId, {
	    key: [38,40,13],
	    obId: this.id,
	    scope: this,
	    fn: function(keyCode){
	    	try{
				this.el = ge(toElId);
			}catch(e){return ;}

			this.childs = MyDOMGetChilds(this.el);
	    	this.childs = MyDOMGetChilds(ge(this.boxId));
	    	if(!this.childs.length){alert('empty');return ;}
	    	this.prevNum = this.currentNum;

	    	switch(keyCode)
	    	{
	    		case 38:  //press up
	    			if(this.currentNum==1 || !this.currentNum)
	    			{
	    				// set to last element
	    				this.currentNum = this.childs.length;
	    			}else{
	    				// set to prev element
	    				this.currentNum--;
	    			}
	    			break;

	    		case 40:  // press down
	    			if(this.currentNum==this.childs.length || !this.currentNum)
	    			{
	    				// set to first element
	    				this.currentNum = 1;
	    			}else{
	    				// set to next element
	    				this.currentNum++;
	    			}
	    			break;
	    		case 13: this.callbacks['onSelect'](this); return ;break ;
	    	}

	    	this.currentEl = this.childs[this.currentNum-1];
	    	if(this.prevNum){this.prevEl = this.childs[this.prevNum-1];}else{this.prevEl = false;}
	    	this.callbacks['onOver'](this);
	    }
	});
}
arrowControl.prototype.reInitial = function()
{
	this.currentNum = 0;
	try{
		this.el = ge(toElId);
	}catch(e){return ;}
}

/* RealPlextorEmulator */
var RP_obj = false;
function RPE()
{
	var RPE_mode = CONFIG.RPE_MODE;

	this.userKey = USER.mesKey;
	this.ajaxConfig = {delay : 10000, prevTime: getCookie('remix_rpe_prevTime')};
	//	alert(this.userKey);
	if(RPE_mode == 'ajax'){this.mode = 1;}  // we dont use "true" or "false" for more flexibility
	if(RPE_mode == 'rp'){this.mode = 2;}
	if(!this.userKey){return ;}
	if(!isObject(CONTAINERS['RPE'])){CONTAINERS['RPE'] = new Object;}

}


RPE.prototype.rpInit = function() {
	if (!RP_obj) {
		RP_obj = new Dklab_Realplexor(
			"http://rpl.beta.dowith.ru",
			"message" //The namespace is here
		);
		return RP_obj;
	} else {
		return RP_obj;
	}
}

RPE.prototype.listen = function(channelName, callbackOptions)
{
	this.incCallbackOptions = callbackOptions;
	this.callbackObject = this.incCallbackOptions; // скорее всего потом расширить придется
	this.channel = {name : channelName};

	CONTAINERS['RPE'][ this.channel['name'] ] = this;

	if(this.mode == 1){this.ajaxListen(); return ;}
	if(this.mode == 2) {
			this.rpInit();
			this.rpListen();
			return ;
		}
}

RPE.prototype.ajaxListen = function()
{
	var url = "submit.php?clear=1&pd_act=RPE_ajaxCheckChannel&channel=" + this.channel.name;

	//if(isObject(this))

	Ext.Ajax.request({
		url: url,
		success: this.ajaxOnAnswer,
		method: 'GET',
		scope : this,
		params: {prevTime: this.ajaxConfig.prevTime}
	});

	setTimeout("CONTAINERS['RPE']['"+this.channel.name+"'].ajaxListen()",this.ajaxConfig.delay);
}

RPE.prototype.rpOnAnswer = function(data) {
	trace = data;
	var answerObject = {responseObject : data};
	this.onAnswer(answerObject);
}

RPE.prototype.rpListen = function() {
	var a = this;
	var fullChannelName = this.userKey+'_'+this.channel.name;
	if(this.callbackObject.forceChannelName){fullChannelName = this.channel.name;}

	RP_obj.subscribe(fullChannelName, function(data){
		a.rpOnAnswer(data)
	});
	RP_obj.execute();
}



RPE.prototype.ajaxOnAnswer = function(response,request)
{
	//alert(response.responseText);
	decodedAnswer = Ext.util.JSON.decode(response.responseText);
	// формируем стандартизированный объект
	// так как за 1 раз может прийти несколько сообщений, то обрабатываем в цикле
	for(var i = 0;i < decodedAnswer.data.length; i++)
	{
		var answerObject =
		{
			responseObject : decodedAnswer.data[i]
		};
		this.onAnswer(answerObject);
	}
    this.ajaxConfig.prevTime = decodedAnswer.prevTime;
    setCookie('remix_rpe_prevTime',decodedAnswer.prevTime);
}

RPE.prototype.onAnswer = function(answerObject)
{
	this.callbackObject.callback.apply(this.callbackObject.scope,[answerObject.responseObject]);   // передаем управление callback функции
	if(this.callbackObject.rpCallback){this.callbackObject.rpCallback.apply(this.callbackObject.scope,[answerObject.responseObject]);}
}
