function debug (o) {
	if(typeof o != 'object' ) {
		alert(o)
	} else {
		var items = new Array();
		for(part in o) items[items.length] = part + ' = ' +/* o[part]*/+'  |  ';
		items.sort();
		alert(items);
	}
};

/*
* DEFINUJI PRACI S UDALOSTMI 
*/
function evnt(nam) {
	this.eventFolder = new Array();
	/* zachytavam udalost */
	this.getEvent = function() {
		e = arguments[0];	
		e = e ? e : window.event;
		return e;
	};
	
	/* zjistuji cil udalosti */
	this.getTarget = function(e) {
		e = window[nam].getEvent(e);
		if (!e.currentTarget) {
			e.currentTarget = e.srcElement;
		}
		return e.currentTarget;
	};

	/* zavesuj spracovani udalosti */
	this.addEvent = function(elm,eventType,fn,set){
		if(arguments[4]){
			var num = window[nam].eventFolder.length;
			window[nam].eventFolder[num] = new Object();
			window[nam].eventFolder[num].trg = elm;
			window[nam].eventFolder[num].typ = eventType;
			window[nam].eventFolder[num].action = fn;
			window[nam].eventFolder[num].bool = set;
		}
		if (document.addEventListener) {
			if (window.opera && (elm == window)){
				elm = document;
			}
			elm.addEventListener(eventType,fn,set);
		} else if (document.attachEvent) {
			elm.attachEvent('on'+eventType,fn);
		}
	};

	this.clearEvents = function(){
		for(var i = 0; i < window[nam].eventFolder.length; i++){
			try{
				dom.removeEvent(window[nam].eventFolder[i].trg,window[nam].eventFolder[i].typ,window[nam].eventFolder[i].action,window[nam].eventFolder[i].bool);
			} catch(e){
			}
			window[nam].eventFolder[i] = null;
		}
		window[nam].eventFolder = null;
	};
	
	/* rusim zpracovani udalosti  */
	this.removeEvent = function(elm,eventType,fn,set){
		if (document.removeEventListener) {
			if (window.opera && (elm == window)){
				elm = document;
			}
			elm.removeEventListener(eventType,fn,set);
		} else if (document.detachEvent) {
			elm.detachEvent('on'+eventType,fn);
		}
	};
	
	/* zabranuji prostupovani udalosti stromem dokumentu */
	this.stopEvent = function(e) {
		var e = window[nam].getEvent(e);
		
		/* clicktracker pro IE */
		if((browser.klient == 'ie') && (typeof(clickTracker) != 'undefined') && (e.type == 'click')){
			clickTracker.logger();
		}
		
		if (e.stopPropagation){
			e.stopPropagation();
		} else { 
			e.cancelBubble= true;
		}
	};
	
	/* rusim pripadnou defaultni reakci prohlizece na udalost */
	this.cancelDef = function(e){
		e = window[nam].getEvent(e);
		if(e.preventDefault) {
			e.preventDefault();
		} else {
			e.returnValue = false;
		}
	};
};

/* DETEKCE KLIENTA */
var browser = {
	platform	:'',
	klient		:'',
	version		:'',
	/* detekce systemu */
	_getPlatform : function() {
		var txt = navigator.userAgent;
		if(txt.indexOf('X11') != -1){
			return 'lin';
		} else if(txt.indexOf('Mac') != -1){
			return 'mac';
		} else if(txt.indexOf('Win') != -1){
			return 'win';
		} else {
			return 'oth';
		}
	},
	/* detekce prohlizece */
	_getKlient : function(){
		var txt = navigator.userAgent;
		if(document.addEventListener && !window.opera && (txt.indexOf('KHTML') == -1)){
			return 'geck';
		} else if(document.addEventListener && window.opera) {
			return 'op';
		} else if(document.attachEvent && !window.opera){
			return 'ie';
		} else if (txt.indexOf('KHTML') != -1){
			if (txt.indexOf('Safari') != -1){
				return 'saf';
			} else {
				return 'kon';
			}
		} else {
			return 'oth';
		}
	},
	/* detekce verze prohlizece */
	_getVersion : function(){
		var txt = navigator.userAgent;
		if(browser.klient == 'ie'){
			var st = txt.indexOf('MSIE');
			var ln = 8;
			var num = parseFloat(txt.substr(st + 5,3));
			if(num < 5.5) {
				return 1;
			} else if(num < 5.9){
				return 2;
			}else if(num > 5.9){
				return 3;
			}
		} else if(browser.klient == 'op') {
			var test = txt.indexOf('Opera');
			var ver = txt.substr(test + 6,5);
				num = parseInt(ver,10) > 7 ? 1 : 0;
				return num;
		} else if(browser.klient == 'kon'){
			var st = txt.indexOf('KHTML/');
			var ln = 6;
			var num = parseFloat(txt.substr(st+6,4));
			return num;
		} else{
			return 0;
		}
	},
	/* nastaveni hodnot */
	getBrowser: function(){
		browser.platform 	= browser._getPlatform();
		browser.klient 		= browser._getKlient();
		browser.version		= browser._getVersion();
	}
};

/* inicializuji objekt-tridu pro praci s udalostmi */
var dom = new evnt('dom');
/* detekuji klientovo prostredi */
browser.getBrowser();

function gE(o) { return document.getElementById(o);}
function cE(o) { return document.createElement(o);}


function Chat () {
	this.stopReceive = false;
	this.count 			= 0;
	this.updateInterval = 10000;
	this.answId = -1; // for VIP answers
	this.styleSet = false; 
	
	// docasne reseni nez bude Bind library
	var self = this;
	this.receive = function () {
		if(self.stopReceive == false) {
			self.HTTTPRequest("/getContributions?id="+self.chatId+"&have=" + self.count,"makeChat","GET");
			self.updateIntervalTimer = setTimeout(self.receive,self.updateInterval);
		}
	};

	this.stopUpdate = function () {
		if(self.stopReceive == true) {
			self.stopReceive = false;
			self.stopButton.innerHTML = 'Vypnout obnovování chatu';
			self.receive();
		} else {
			self.stopReceive = true;
			self.stopButton.innerHTML = 'Zapnout obnovování chatu';
		}
	};
	
	this.send = function (e) {
	    self.say = self.inputSend.value; //sent
	    self.HTTTPRequest("/sayContribution","makeMyChat","POST","id="+self.chatId+"&sessionId="+self.sessionId+"&question=" + (self.say.replace(/&/g,"%26")));
		self.say = '';
		dom.stopEvent(e);
		dom.cancelDef(e);
		return false;
	};
	
	this.sendAdmin = function (e) {
    	self.say = self.inputSend.value;
		self.HTTTPRequest("/admin/sayAnswer","sentAdmin","POST","id="+self.chatId+"&contributionId=-1&answer=" + (self.say.replace(/&/g,"%26")));
		dom.stopEvent(e);
		dom.cancelDef(e);
		return false;
	};
	
	this.sendVip = function(e){
	    self.say = self.inputSend.value;
		if(self.answId == -1) {
			self.HTTTPRequest("/vip/sayAnswer","sentVip","POST","id="+self.chatId+"&contributionId=-1&answer=" + (self.say.replace(/&/g,"%26")));
		}
	    else { 
			self.HTTTPRequest("/vip/sayAnswer","sentVip","POST","id=-1&contributionId=" + self.answId + "&answer=" + (self.say.replace(/&/g,"%26")));
		}
		dom.stopEvent(e);
		dom.cancelDef(e);
		return false;
	}
	
	this.sendOld = function (e) {
    	var inpQuest = gE('questionINP').value;
		var inpAnsw = gE('answerINP').value;
		self.HTTTPRequest("/admin/changeAnswer","sentOld","POST","id="+self.chatId+"&contributionId="+self.answId+"&answer=" + (inpAnsw.replace(/&/g,"%26")) + "&question=" +(inpQuest.replace(/&/g,"%26")));
	};
	
	
	this.prepareAnswer = function (id) {
		var quest = gE('question'+id);
		var questUs = gE('question');
		if (self.answId >  -1) {
			gE('question'+self.answId).style.color = "#000000";
		}
		
		if (id >= 0) {
			questUs.innerHTML = '<img src="http://1.im.cz/vipchat/img/smazat.gif" title="Needitovat" onclick="chat.prepareAnswer(-1);" /> ';
			questUs.innerHTML += quest.innerHTML;
			quest.style.color = '#ff0000';
		} else{ 
			questUs.innerHTML = '';
			self.answId = -1;
		}
		self.answId = id;
	};
	
	this.prepareAnswerOld = function (id,answer,question) {
		var quest = gE('question'+id);
		var questUs = gE('question');
		
		var inpQuest = gE('questionINP');
		var inpAnsw = gE('answerINP');
		
		if (self.answId >  -1) {
			gE('question'+self.answId).style.color = "#000000";
		}
		
		if (id >= 0) {
			inpQuest.value = question;
			inpAnsw.value = answer;
			
			questUs.innerHTML = '<img src="http://1.im.cz/vipchat/img/smazat.gif" title="Needitovat" onclick="chat.prepareAnswerOld(-1);" /> ';
			questUs.innerHTML += quest.innerHTML;
			quest.style.color = '#ff0000';
		} else{ 
			questUs.innerHTML = '';
			
			var inpQuest = gE('questionINP');
			var inpAnsw = gE('answerINP');
			if(typeof inpQuest != 'undefined' && typeof inpAnsw != 'undefined') {
				inpAnsw.value = '';
				inpQuest.value = '';
			}
			
			self.answId = -1;
		}
		self.answId = id;
	};
	
	/*- nastavi spravnou vysku chatu */
	this.adjustHeight = function () {
		var heightBody 		= document.documentElement.clientHeight && (browser.klient != 'op') ? document.documentElement.clientHeight : document.body.clientHeight;	
		var topOffsetChat 	= 0;
		var heightChat 		= self.chat.offsetHeight;
		
		/*- eto prvky ktere svou vyskou ovlivniju vysku chat okna */
		var chatFormHeight		= gE('chat-form') ? gE('chat-form').offsetHeight : 0;
		var answerFormHeight	= gE('answer') ? gE('answer').offsetHeight : 0;
		var questionFormHeight	= gE('question') ? gE('question').offsetHeight : 0;
		var myChatHeight = 0;
		if(typeof arguments[0] != 'undefined' && self.myChat != null) {
			myChatHeight = self.myChat.offsetHeight;
		}
		
		/*- chci spravny offset */
		var chatP = self.chat;
		while (chatP) {
			topOffsetChat = topOffsetChat + chatP.offsetTop;
			chatP = chatP.offsetParent;
		}
		
		/*- odecet reklamniho prouzku, oprava zmensovani okna */
		var adHeight = gE('adWide');
		if (adHeight != null && adHeight.offsetHeight != 0){
		topOffsetChat = topOffsetChat - (adHeight.offsetHeight + 10);
		}
		
		var heightAll = chatFormHeight+answerFormHeight+questionFormHeight;
		if (heightBody >= 600) {
			//if(heightBody <= (topOffsetChat+heightChat)) {
				self.chat.style.height = ((heightChat-((topOffsetChat+heightChat)-heightBody)-heightAll-60))+'px';
			/*} else if(heightBody > (topOffsetChat+heightChat)) {
				self.chat.style.height = ((heightChat-((topOffsetChat+heightChat)-heightBody)-heightAll-20))+'px';
			}*/
			this.chat.scrollTop = this.chat.scrollHeight;
		}
		
	};
};

Chat.prototype.init = function (userName,chatId,sessionId) {
	this.userName = userName;
	this.chatId = chatId;
	this.sessionId = sessionId;
	this.chat = gE('chat');
	this.myChat = gE('myChat'); // nemusi existovat
	this.sendForm = gE('chForm');
	this.isAdmin = arguments[3];
	
	if(gE('chSwitch')){
		this.stopButton = gE('chSwitch');
		dom.addEvent(this.stopButton,"click",this.stopUpdate,false);
	}
	
	if(userName != '') {
		this.buttonSend = gE('send');
		this.inputSend = gE('say');
		//dom.addEvent(this.buttonSend,"click",this.send,false);
		dom.addEvent(this.sendForm,"submit",this.send,false);
	}
	
	if(this.isAdmin == 'admin') {
		this.buttonSend = gE('send');
		this.inputSend = gE('say');
		//dom.addEvent(this.buttonSend,"click",this.sendAdmin,false);
		dom.addEvent(this.sendForm,"submit",this.sendAdmin,false);
	}
	
	if(this.isAdmin == 'vip') {
		this.buttonSend = gE('send');
		this.inputSend = gE('say');
		//dom.addEvent(this.buttonSend,"click",this.sendVip,false);
		dom.addEvent(this.sendForm,"submit",this.sendVip,false);
	}
	
	if(this.isAdmin == 'old') {
		this.buttonSend = gE('send');
		this.inputSend = gE('say');
		dom.addEvent(this.sendForm,"submit",this.sendOld,false);
		//dom.addEvent(this.buttonSend,"click",this.sendOld,false);
	}
	
	if (userName != '') {
		// neprihlaseny
		this.receiveMy();
	} else {
		// prihlaseny
		if (this.isAdmin != 'old') { this.receive(); }
	}
	window.onresize = this.adjustHeight;
};

Chat.prototype.receiveMy = function () {
	 this.HTTTPRequest("/getMyContributions?id="+this.chatId+"&sessionId="+this.sessionId,"makeMyChat","POST","");
};

Chat.prototype.makeChat = function (data) {
	this.count = this.count + data.count; // update count
	for (x = 0;x < data.row.length;x++) {
		var rowHTML = '<div class="chRow">';
		//alert('username='+data.row.username+' answer='+data.row[x].answer)
		if (data.row[x].username != '') {
			rowHTML += '<div class="user"><strong class="userName">'+data.row[x].username+':</strong> '+data.row[x].question+'</div>';
		}
		if (data.row[x].answer != '') {
			rowHTML += '<div class="vip"><strong class="vipName">'+data.vip+':</strong> '+data.row[x].answer+'</div>';
		} else {
			this.chat.innerHTML+= '';
		}
		this.chat.innerHTML+= rowHTML + '</div>';
		/*- mazem userovi otazky na ktere vip uz odpovedel*/
		if(this.myChat != null) {
			for(h=0;h<this.myChat.childNodes.length-1;h++) {
				if(('chRowId-'+data.row[x].contributionId) == this.myChat.childNodes[h].id) {
					this.myChat.childNodes[h].parentNode.removeChild(this.myChat.childNodes[h]);
				}
			}
		}
	}
	
	if (data.row.length > 0) { this.chat.scrollTop = this.chat.scrollHeight; }
	
	if(document.getElementById('chat') && (browser.klient == 'ie') && !this.styleSet){
		var width = document.getElementById('chat').offsetWidth
		if(width > 750){
			this.repairStyle();
		}
	}

	// nastavim vysku okna 
	this.adjustHeight();
};
/*
	upravim 
*/
Chat.prototype.repairStyle = function(){
	var st = document.styleSheets;
	var act = '';
	for(var i = 0; i < st.length; i++){
		if(st[i].id == 'chatCSS'){
			act = st[i];
		}
	}

	if(!act) return;
	var rul = act.rules
	var myRul = '';
	for(var i = 0; i < rul.length; i++){
		if(rul[i].selectorText == '#chat .chRow'){
			myRul = rul[i];
			break;
		}
	}
	
	if(!myRul) return;
	myRul.style.width = '700px';
	myRul.style.overflow = 'hidden';
	this.styleSet = true;
	
}

Chat.prototype.makeMyChat = function (data) {
	if(typeof data.row != 'undefined') {
		this.myChat.innerHTML = '';
		for (x = 0;x < data.row.length;x++){
			var div = cE('div')
			div.className= 'chRow';
			div.id= 'chRowId-'+data.row[x].contributionId;
			var html = '<div class="user"><strong class="userName">'+this.userName+':</strong> '+data.row[x].question.replace(/&/g,"&amp;").replace(/</g,"&lt;")+'</div>';
			div.innerHTML = html;
			if(this.myChat.firstChild == null) {
				this.myChat.appendChild(div);
			} else {
				this.myChat.insertBefore(div,this.myChat.firstChild);
			}
		}
		this.myChat.scrollTop = (0+'px');
		this.receive();
	}
	this.inputSend.value = '';
};

Chat.prototype.sent = function (data) {
    if ((data.status == 1) && (this.say != '')){
      var div = cE('div')
	  div.className= 'chRow';
	  var html = '<div class="user"><strong class="userName">'+this.userName+':</strong> '+this.say.replace(/&/g,"&amp;").replace(/</g,"&lt;")+'</div>';
	  div.innerHTML = html;
	  
	  if(this.myChat.firstChild == null)
			this.myChat.appendChild(div);
		else
			this.myChat.insertBefore(div,this.myChat.firstChild);
	  //this.myChat.innerHTML += '<div class="chRow"><div class="user"><strong class="userName">'+this.userName+':</strong> '+this.say+'</div></div>';
      this.myChat.scrollTop = (0+'px');
      this.inputSend.value = '';
	  this.say = '';
	  
	  this.adjustHeight(1);
    }
};

Chat.prototype.sentAdmin = function (data) {
    if ((data.status == 1) && (this.say != '')){
      var div = cE('div')
	  div.className= 'chRow';
	  var html = '<div class="user"><strong class="userName">'+this.userName+':</strong> '+this.say.replace(/&/g,"&amp;").replace(/</g,"&lt;")+'</div>';
	  div.innerHTML = html;
	  
	  this.chat.innerHTML += '<div class="chRow"><div class="user"><strong class="userName">Redakce:</strong> '+this.say.replace(/&/g,"&amp;").replace(/</g,"&lt;")+'</div></div>';
      
	  this.inputSend.value = '';
	  this.say = '';
	  this.chat.scrollTop = this.chat.scrollHeight;
    }
};

Chat.prototype.sentOld = function (data) {
    if ((data.status == 1) && (this.say != '')){
    	location.reload();
    }
};

Chat.prototype.sentVip = function (data) {
    if ((data.status == 1) && (this.say != '')){
      this.say.value='';
	  //alert(gE('say').value + ' ?')
	  this.inputSend.value = '';
      location.reload();
    }
}

Chat.prototype.HTTTPRequest = function (strURL,callBackFunction,method) {
    var self = this;
    // Mozilla/Safari
    if(typeof(XMLHttpRequest) != 'undefined') {
		var XHR = new XMLHttpRequest();
	}
	else {
		try {
			/*- IE */
			var XHR = new ActiveXObject("Msxml2.XMLHTTP"); /*- "Microsoft.XMLHTTP*/
		}
		catch (e) {
			try { 
				var XHR = new ActiveXObject("Microsoft.XMLHTTP"); 
			}
			catch (e) {
				return 0;
			}
		}
	}
    XHR.open(method, strURL, true);
    XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    XHR.onreadystatechange = onreadystatechangeFunction;
	function onreadystatechangeFunction() {
        if( XHR.readyState == 4 ) {
            if( XHR.status == 200 ) {
				eval('self.'+callBackFunction+'('+XHR.responseText+')')
            }
        }
    }
	if(method == 'POST')
	    XHR.send(arguments[3]);
	else
		XHR.send(null);
};



/*- decode crypted mail address */
String.prototype.mailDecrypt = function() {
    var r = '';
    for(i=0; i < this.length; i++)	{
 		n = this.charCodeAt(i);
 		if (n>=8364) { n = 128; }
		r += String.fromCharCode(n-4);
    }
	return '<a href="mailto:'+r+'">'+r+'</a>';
}


