function addEvent(o,evt,f) {
    if (o.attachEvent) window.attachEvent("on"+evt, f); 
    else o.addEventListener(evt, f, false);
}

function createHttpRequest() {
	var xmlhttp;
	if (window.XMLHttpRequest) {
		xmlhttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Your browser does not support XMLHTTP!");
	}
	return xmlhttp;
}

function executeSyncronRequest(url) {
	var xmlhttp = createHttpRequest();
	xmlhttp.open("GET", url, false);
	xmlhttp.send(null);
	return xmlhttp.responseXML;
}

function executeAyncronRequest(xmlhttp, url, callback) {
	xmlhttp.open("GET", url, true);
	xmlhttp.onreadystatechange = callback;
	xmlhttp.send(null);
	return xmlhttp;
}

function updateState(updater) {
	updater.xmlhttp = createHttpRequest();
	executeAyncronRequest(updater.xmlhttp, updater.url, function () {updater.response();});
}

function updateProfil(updater,expertId) {
	updater.xmlhttp = createHttpRequest();
    try{
	    updater.refreshExpert(expertId);
    } catch (err) {}
}

var quickreadingIsAvailable = true; // show quickreading buttons in expertboxes (default true)
function setQuickreadingAvailable(val) {
	quickreadingIsAvailable = val;
}

function ExpertUpdater(language, country, _filter, affid, _phonetest) {
	this.prefix = 'expert_';
	this.finished = true;
	this.xmlhttp = null;
	this.filter = _filter;
	
	var _affid = '0';
	if (null!=affid && affid!='undefined')
		_affid = affid;
	this.url = '/ajax/AjaxExpertRefreshState?lang=' + language + '&country=' + country + '&affid=' + _affid + '&' + this.filter;
	if (_phonetest == 'phonetest')
		this.url += '&phonetest';
	this.dataurl = '/ajax/AjaxExpertData?lang=' + language + '&country='+country+'&affid='+_affid+'&id=';

	this.response = function() {
		if(this.xmlhttp.readyState == 4 && this.finished) {
			xml = this.xmlhttp.responseXML;
			// if response has bad format or doesnt contain any expert 
			if (xml == null || xml.getElementsByTagName('experts') == null || xml.getElementsByTagName('experts').item(0) == null) {
				return;
			}

			var root = xml.getElementsByTagName('experts').item(0);
			
			this.finished = false;
			
			var cloneBox = document.getElementById(this.prefix+"-1");
			var boxContainer = cloneBox.parentNode;
			var box;
			// ids contains all the expertids of the container
			var ids = new Array();
			var idx = 0;
			for(var i = 0; i < boxContainer.childNodes.length; i++) {
				if(boxContainer.childNodes[i].tagName == 'DIV' && boxContainer.childNodes[i].id.indexOf(this.prefix) != -1 && boxContainer.childNodes[i].id.substring(this.prefix.length) != '-1') {
					ids[idx] = boxContainer.childNodes[i].id.substring(this.prefix.length);
					idx++;
				}
			}
			
			// idsToStay contains all the expertids of the xml
			var idsToStay = new Array();
			var doinsert = false;
			var ctnbase = "expertList";
			var ctnindex = 0;
			var ctnloopindex = 0;
			if (document.getElementById(ctnbase + ctnindex) == null) {
				return;
			}
			
			// ctnsize = maximum number of expertboxes in the container
			var ctnsize = document.getElementById(ctnbase + ctnindex + 'count').value;
			
			var ii = 0;
			for (var i = 0; i < root.childNodes.length; i++) {
				var node = root.childNodes.item(i);
				expertId = node.getAttribute('id');
				expertState = node.getAttribute('state');
				onlyemail = node.getAttribute('onlyemail');
				
				if (this.moveBox(i - ii, ctnbase + ctnindex, expertId))
                {
				    idsToStay[idsToStay.length] = expertId;
				
				    if(this.isBoxChanged(expertId, expertState) && onlyemail != 'true') {
					    updateExpertBoxState(expertId, expertState);
				    }
				
				    if(onlyemail == 'true') {
					    updateExpertBoxState(expertId, 'ONLYEMAIL');
				    }
				
				    ++ctnloopindex;
			
				    // if the container is totally filled
				    if (ctnloopindex == ctnsize) {
					    var container = document.getElementById(ctnbase + ctnindex);
					    for(var j = 0; j < container.childNodes.length; j++) {
						    if (j < ctnsize) {
							    if (container.childNodes[j].style != null) {
								    // the script tag must be hidden...
								    if (container.childNodes[j].tagName != null && container.childNodes[j].tagName == 'SCRIPT') {
									    continue;
								    }
								    // ...and the cloneBox too
								    else if (container.childNodes[j].id != null && container.childNodes[j].id == 'expert_-1') {
									    continue;
								    }
								
								    container.childNodes[j].style.display = 'inline';
							    }
							    continue;
						    }
						
						    // all the other expertboxes must be hidden
						    if (container.childNodes[j].className != null && container.childNodes[j].className == 'josboxtype1') {
							    container.childNodes[j].style.display = 'none';
						    }
					    }
					
					    // looking for the next container
					    ++ctnindex;
					    ctnloopindex = 0;
					
					    // if no next container
					    if (document.getElementById(ctnbase + ctnindex) == null) {
						    break;
					    }
					
					    // offset raise
					    ii += i + 1;
					    // setting up the number of expertboxes in this container
					    ctnsize = document.getElementById(ctnbase + ctnindex + 'count').value;
				    }
                }			
			}

//			for (var i = 0; i < ids.length; ++i) {
//				var found = false;
//				for (var j = 0; j < idsToStay.length; ++j) {
//					if (idsToStay[j] == ids[i]) {
//						found = true;
//						break;
//					}
//				}
//				
//				// if the idsToStay doesnt contain this expertid...
//				if (!found) {
//					// ...then we remove it from document
//					var box = document.getElementById(this.prefix + ids[i]);
//					box.parentNode.removeChild(box);
//				}
//			}
			
			this.finished = true;
		}
	};

	this.isBoxChanged = function (expertId, expertState) {
		var box = document.getElementById(this.prefix+expertId);
		
		if (box == null) {
			return false;
		}
		
		if (document.getElementById('expert_profilestatus_' + expertId).className == ('profilestatus ' + expertState.toLowerCase())) {
			return false;
		}
		
		return true;
	};
	
	this.moveBox = function(index, containerid, expertid) {
		// if document doesnt contain an expertbox with this expertid then we...
		if (document.getElementById(this.prefix + expertid) == null) {
			// ...create and put it
			return this.addExpert(index, containerid, expertid);
		}
		
		// moves expertbox to the proper position in the container
		var container = document.getElementById(containerid);
		var inserted = false;
		var box = null;
		for (var i = 0; i < container.childNodes.length && !inserted; ++i) {
			if (i == index) {
				box = document.getElementById(this.prefix + expertid);
				if (box == container.childNodes[i]) {
					inserted = true;
					break;
				}
				box.parentNode.removeChild(box);
				container.insertBefore(box, container.childNodes[i]);
				inserted = true;
			}
		}
		
		// if expertbox is in an another container then we remove it from there and insert it to the end of the current container 
		if (!inserted) {
			box = document.getElementById(this.prefix + expertid);
			box.parentNode.removeChild(box);
			container.appendChild(box);
		}

        return true;
	};
	
	this.addExpert = function (index, containerid, expertId) {
		var response = executeSyncronRequest(this.dataurl+expertId);
		var root;

		try {
		    root = response.getElementsByTagName('expertdata').item(0);
		} catch (err) { return false; }
		
		// commented variables are not used yet
		var id;
		var image;
		var state;
		var screenname;
		// var expertise;
		var description;
		// var rating;
		var channel;
		var profileurl;
		var phonecode;
		var channel_videochat = false;
		var channel_phone = false;
		var channel_mail = false;
		var channel_quickreading = false;
		var price_more = '';
		var more_offer = '';
		
		try{

		for (var i = 0; i < root.childNodes.length; i++) {
			var node = root.childNodes.item(i);
			if(node.tagName == 'id') id = node.childNodes[0].nodeValue;
			if(node.tagName == 'state') state = node.childNodes[0].nodeValue;
			if(node.tagName == 'image') image = node.childNodes[0].nodeValue;
			if(node.tagName == 'screenname') screenname = node.childNodes[0].nodeValue;
			// if(node.tagName == 'expertise') expertise = node.childNodes[0].nodeValue;
			if(node.tagName == 'description') description = node.childNodes[0].nodeValue;
			// if(node.tagName == 'rating') rating = node.childNodes[0].nodeValue;
			if(node.tagName == 'profileurl') profileurl = node.childNodes[0].nodeValue;
			if(node.tagName == 'phonecode') phonecode = node.childNodes[0].nodeValue;
			if(node.tagName == 'channel') {
				if(node.childNodes[0].nodeValue == "videochat")
					channel_videochat = true;
				if(node.childNodes[0].nodeValue == "phone")
					channel_phone = true;
				if(node.childNodes[0].nodeValue == "email")
					channel_mail = true;
				if(node.childNodes[0].nodeValue == "quickreading")
					channel_quickreading = true;
			}
			if(node.tagName == 'pricemore') price_more = node.childNodes[0].nodeValue;
			if(node.tagName == 'moreoffer') more_offer = node.childNodes[0].nodeValue;
		}
		
        } catch (err) { return false; }

		var sourceBox = document.getElementById(this.prefix+"-1");
		var boxContainer = sourceBox.parentNode;
		var box;

		box = sourceBox.cloneNode(true);
		box.id = this.prefix+id;
		
		//////////////////////////////////////////////////////////////
		// REPLACEING FIELDS CONTENTS AND PROPERTIES WITH VALID VALUES 
			// rel (type)
			
			// profileurl_pic (href)
			var boxPs = box.getElementsByTagName('a');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'profileurl_pic') {
					button.href = profileurl;
				}
			}
			
			// imagelink (alt)
			var boxPs = box.getElementsByTagName('img');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'imagelink') {
					button.alt = screenname; // TODO + ' ((szaktudas))';
				}
			}
			
			// imagelink (src)
			var boxPs = box.getElementsByTagName('img');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'imagelink') {
					button.src = image;
				}
			}
			
			// profileurl_text (href)
			var boxPs = box.getElementsByTagName('a');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'profileurl_text') {
					button.href = profileurl;
				}
			}
			
			// profilurl_text (innerHTML)
			var boxPs = box.getElementsByTagName('a');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'profileurl_text') {
					button.innerHTML = screenname;
				}
			}
	
			// profile_status (id)
			var boxPs = box.getElementsByTagName('div');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'profile_status') {
					button.id = 'expert_profilestatus_' + id;
					button.className = 'profilestatus ' + state.toLowerCase();
				}
			}
			
			// status (id)
			var boxPs = box.getElementsByTagName('div');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'status') {
					button.id = 'expert_status_' + id;
				}
			}
			
			// status (innerHTML)
			var boxPs = box.getElementsByTagName('div');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'status') {
					if(state == 'ONLINE') {
						var loc_status = document.getElementById('expertbox_loc_short_online').innerHTML;
						button.innerHTML = loc_status;
					}
					if(state == 'BUSY') {
						var loc_status = document.getElementById('expertbox_loc_short_busy').innerHTML;
						button.innerHTML = loc_status;
					}
					if(state == 'OFFLINE') {
						var loc_status = document.getElementById('expertbox_loc_short_offline').innerHTML;
						button.innerHTML = loc_status;
					}
				}
			}
			
			// statustext (rel.style)
			var boxPs = box.getElementsByTagName('div');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == ('status_online') ) {
					button.style.display = (state == 'ONLINE') ? 'inline' : 'none';
					var statustext = document.getElementById('expertbox_loc_online').innerHTML;
					button.innerHTML = statustext;
					button.id = 'status_online_' + expertId;
				}
				if(button.getAttribute('rel') == ('status_busy') ){
					button.style.display = (state == 'BUSY') ? 'inline' : 'none';
					var statustext = document.getElementById('expertbox_loc_busy').innerHTML;
					button.innerHTML = statustext;
					button.id = 'status_busy_' + expertId;
				}
				if(button.getAttribute('rel') == ('status_offline') ) {
					button.style.display = (state == 'OFFLINE') ? 'inline' : 'none';
					var statustext = document.getElementById('expertbox_loc_offline').innerHTML;
					button.innerHTML = statustext;
					button.id = 'status_offline_' + expertId;
				}
			}
			
			// phonenumber
			var boxPs = box.getElementsByTagName('div');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'phonenumber') {
					button.id = 'expert_phonenumber_' + id;
					var text = document.getElementById('expertbox_loc_phonenumber').innerHTML;
					button.innerHTML = '<span>' + text + '</span>';
				}
			}
			
			// phonecode (div with embedded span)
			var boxPs = box.getElementsByTagName('div');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'phonecode') {
					button.id = 'expert_phonecode_' + id;
					var text = document.getElementById('expertbox_loc_extension').innerHTML;
					button.innerHTML = text + ': <span>' + phonecode + '</span>';
				}
			}
			
			// callsprice (innerHTML)
			var boxPs = box.getElementsByTagName('div');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'price') {
					button.id = 'expert_price_' + id;
					var text = document.getElementById('expertbox_loc_price').innerHTML;
					// expertbox_loc_price already contains 'price_more'..
					//if (channel_phone && price_more != '')
					//	text += price_more;
					button.innerHTML = text;
				}
			}
			
			// introtext (innerHTML)
			var boxPs = box.getElementsByTagName('p');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'introtext') {
					description = null == description ? '' : description.replace(/<[^>]*>/g, '');
					if (description.length > 80)
						description = description.substring(0, 80) + '...';
					button.innerHTML = (description != null) ? description : '';
				}
			}
			
			// introtext_more (href)
			var boxPs = box.getElementsByTagName('a');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'introtext_more') {
					var text = document.getElementById('expertbox_loc_more').innerHTML;
					button.innerHTML = text + ' »';
					button.href = profileurl;
				}
			}
			
			// channel_videochat (style.display, innerHTML)
			var boxPs = box.getElementsByTagName('a');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'channel_videochat') {
					var text = document.getElementById('expertbox_loc_video_prediction').innerHTML;
					button.innerHTML = text;
					if (channel_videochat)  {
						button.style.display =  '';
					} else {
						button.style.display =  'none';
					}
				}
			}
			
			// channel_videochat_span (style.display, innerHTML)
			var boxPs = box.getElementsByTagName('span');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'channel_videochat_span') {
					var text = document.getElementById('expertbox_loc_video_prediction').innerHTML;
					button.innerHTML = text;
					if (channel_videochat)  {
						button.style.display = 'none';
					} else {
						button.style.display = '';
					}
				}
			}
			
			// channel_quickreading (style.display, innerHTML)
			var boxPs = box.getElementsByTagName('a');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'channel_quickreading') {
					/* if quickreading is NOT available for current country then hide this text */
					var text = document.getElementById('expertbox_loc_free_prediction').innerHTML;
					button.innerHTML = text;
					if (!quickreadingIsAvailable) {
						button.style.display='none';
						break;
					}
					if (channel_quickreading)  {
						button.style.display =  '';
						button.href = '/index?page=provider&id=' + id + '&showquestion&allreadings';
					} else {
						button.style.display = 'none';
					}
				}
			}
			
			// channel_quickreading_span (style.display, innerHTML)
			var boxPs = box.getElementsByTagName('span');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'channel_quickreading_span') {
					/* if quickreading is NOT available for current country then hide this text */
					var text = document.getElementById('expertbox_loc_free_prediction').innerHTML;
					button.innerHTML = text;
					if (!quickreadingIsAvailable) {
						button.style.display='none';
						break;
					}
					if (channel_quickreading)  {
						button.style.display =  'none';
					} else {
						button.style.display = '';
					}
				}
			}
			
			// channel_mail (style.display, innerHTML)
			var boxPs = box.getElementsByTagName('a');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'channel_email') {
					var text = document.getElementById('expertbox_loc_email_prediction').innerHTML;
					button.innerHTML = text;
					if (channel_mail)  {
						button.href = '/main/emailselect?expertid=' + id;
						button.style.display = '';
					} else {
						button.style.display = 'none';
					}
				}
			}
			
			// channel_mail_span (style.display, innerHTML)
			var boxPs = box.getElementsByTagName('span');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'channel_email_span') {
					var text = document.getElementById('expertbox_loc_email_prediction').innerHTML;
					button.innerHTML = text;
					if (channel_mail)  {
						button.style.display = 'none';
					} else {
						button.style.display = '';
					}
				}
			}
			
			// more offers (style.display)
			box.innerHTML = box.innerHTML.replace(/off_-1/g, 'off_' + id).replace(/offbt_-1/g, 'offbt_' + id);
			var boxPs = box.getElementsByTagName('div');
			for (var i = 0; i < boxPs.length; i++) {
				var button = boxPs[i];
				if(button.getAttribute('rel') == 'moreoffer') {
					moreOfferParent = button.parentNode;
					button.id = 'off_' + id;
					button.innerHTML = '<div class="inside">' + more_offer + '</div>';
					//button.parentNode.style.position = 'relative';
					//button.style.bottom = '22px';
				}
				if(button.getAttribute('rel') == 'moreoffer_holder') {
					var child = button.getElementsByTagName('div')[0];
					child.id = 'offbt_' + id;
					if (more_offer == '')  {
						button.style.display = 'none';
					} else {
						button.style.display = 'block';
					}
				}
			}
		// END OF REPLACING
		///////////////////
		
		
		var container = document.getElementById(containerid);
		var inserted = false;
		for (var i = 0; i < container.childNodes.length && !inserted; ++i) {
			if (i == index) {
				container.insertBefore(box, container.childNodes[i]);
				inserted = true;
			}
		}
		
		// style.display were 'none' till now
		box.style.display='inline';
		
		if (!inserted) {
			container.appendChild(box);
		}
		
		return true;
	};
	
}

function updateExpertBoxState(expertId, expertState) {
	// if we want to update a box what is not exist on page
	if (document.getElementById('expert_' + expertId) == null) {
		return;
	}
	var ps = document.getElementById('expert_profilestatus_' + expertId);
	ps.className = 'profilestatus ' + expertState.toLowerCase();
	var s = document.getElementById('expert_status_' + expertId);
	if(expertState == 'ONLINE') {
		var loc_status = document.getElementById('expertbox_loc_short_online').innerHTML;
		s.innerHTML = loc_status;
		if (document.getElementById('status_online_' + expertId) != null)
			document.getElementById('status_online_' + expertId).style.display = 'inline';
		if (document.getElementById('status_busy_' + expertId) != null)
			document.getElementById('status_busy_' + expertId).style.display = 'none';
		if (document.getElementById('status_offline_' + expertId) != null)
			document.getElementById('status_offline_' + expertId).style.display = 'none';
	}
	if(expertState == 'ONLYEMAIL') {
		var loc_status = document.getElementById('expertbox_loc_short_onlyemail').innerHTML;
		s.innerHTML = loc_status;
		if (document.getElementById('status_online_' + expertId) != null) {
			document.getElementById('status_online_' + expertId).style.display = 'inline';
			var s2 = document.getElementById('expertbox_loc_onlyemail').innerHTML;
			document.getElementById('status_online_' + expertId).innerHTML = s2;
		}
		if (document.getElementById('status_busy_' + expertId) != null)
			document.getElementById('status_busy_' + expertId).style.display = 'none';
		if (document.getElementById('status_offline_' + expertId) != null)
			document.getElementById('status_offline_' + expertId).style.display = 'none';
		
		/* hide call price, phone number, extension fields */
		if (document.getElementById('expert_phonenumber_' + expertId) != null)
			document.getElementById('expert_phonenumber_' + expertId).style.display = 'none';
		if (document.getElementById('expert_phonecode_' + expertId) != null)
			document.getElementById('expert_phonecode_' + expertId).style.display = 'none';
		if (document.getElementById('expert_price_' + expertId) != null)
			document.getElementById('expert_price_' + expertId).style.display = 'none';
		
	}
	if(expertState == 'BUSY') {
		var loc_status = document.getElementById('expertbox_loc_short_busy').innerHTML;
		s.innerHTML = loc_status;
		if (document.getElementById('status_online_' + expertId) != null)
			document.getElementById('status_online_' + expertId).style.display = 'none';
		if (document.getElementById('status_busy_' + expertId) != null)
			document.getElementById('status_busy_' + expertId).style.display = 'inline';
		if (document.getElementById('status_offline_' + expertId) != null)
			document.getElementById('status_offline_' + expertId).style.display = 'none';
	}
	// alert('expertId:' + expertId);
	if(expertState == 'OFFLINE') {
		var loc_status = document.getElementById('expertbox_loc_short_offline').innerHTML;
		s.innerHTML = loc_status;
		if (document.getElementById('status_online_' + expertId) != null)
			document.getElementById('status_online_' + expertId).style.display = 'none';
		if (document.getElementById('status_busy_' + expertId) != null)
			document.getElementById('status_busy_' + expertId).style.display = 'none';
		if (document.getElementById('status_offline_' + expertId) != null)
			document.getElementById('status_offline_' + expertId).style.display = 'inline';
	}
	
}
