// Global agent variables
var ua =		navigator.userAgent.toLowerCase();
var ie =		((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));
var ns =		(navigator.appName == 'Netscape');
var	gecko = 	(ua.indexOf("gecko") != -1);
var	safari = 	(ua.indexOf("safari") != -1);
var	konqueror = (ua.indexOf("konqueror") != -1);
var win =		(ua.indexOf('win') != -1);
var mac =		(ua.indexOf('macintosh') != -1);
var linux =		(ua.indexOf('linux') != -1);
var version =	navigator.appVersion;

//is IE6?
if (version.indexOf('MSIE') != -1 && version.indexOf('6.0') != -1) {
	var is_ie6 = true;
}

//onload function loader
function Loader() {
    this.action = [];
    this.add = function(obj) {
        this.action.push(obj);
    }
    this.exec = function() {
        var i;
        for (i in this.action) {
            this.action[i]();
        }
    }
}
var loader    = new Loader();
window.onload = function() { loader.exec(); };

navFlag=-1;
function init_page(){

	if (ie && document.getElementById) {
		var drop=new Array("top_nav3","my_actions");
		var str;
		for (k=0;drop[k];k++){

			var navRoot = document.getElementById(drop[k]);
			if (navRoot && navRoot.childNodes && navRoot.childNodes.length){
				//fish UL's
				var len=navRoot.childNodes.length
				if (navRoot){
					for (i=0; i<len; i++) {
						if (navRoot.childNodes[i].nodeName=='UL'){

							for (j=0;navRoot.childNodes[i].childNodes[j];j++){
								if (navRoot.childNodes[i].childNodes[j].nodeName=="LI") {
									navRoot.childNodes[i].childNodes[j].onmouseover=function() {this.className+=" over";}
									navRoot.childNodes[i].childNodes[j].onmouseout=function() {this.className=this.className.replace(" over", "");}
								}
							}
						}
					}
				}
			}
		}
	}
	//populate module navbar
	var navbar=document.getElementById("sec_nav_30");
	if (navbar && availble){
		var ul=document.createElement("UL");
		ul.setAttribute("className","dropmenu",0);
		ul.setAttribute("class","dropmenu",0);

		navbar.appendChild(ul);
		str='';
		for (i=0;availble[i];i++){
			str+='<li><a href="javascript:void(0)" onclick="add_module('+i+')">'+availble[i][0]+'</a></li>';
		}
		if (window.rss)
		{
			for (i=0;rss[i];i++){
				str+='<li><a href="'+add_rss(rss[i][1])+'">'+rss[i][0]+'</a></li>';
			}
		}
		//alert(ul.innerHTML+' '+str)
		ul.innerHTML=str;
	}

}

function toggle_advanced_search(){

	var form=getElementsByClass("advanced_search",document.getElementById("search"))
	var	j_len=form.length;
	for (j=0;j<j_len;j++){
		if (form[j].className=="advanced_search")
			form[j].className="advanced_search_on"
	}
	document.getElementById("advanced_search").style.display="none"

}

function navigation(nav) {

	if (ie) {
		navbar = document.getElementById("top_nav_main2").childNodes
	} else {
		navbar = document.getElementById("top_nav_main2").childNodes;
	}

	for (i=0; navbar[i]; i++) {
		if (navbar[i].id == "nav"+nav) {
			navbar[i].className = "top_nav2active";
		} else {
			navbar[i].className = '';
		}
	}

	navbar = document.getElementById("top_nav3").childNodes;
	for (i=0; navbar[i]; i++) {
		if (navbar[i].id == "top_nav_sec"+nav) {
			navbar[i].style.display = "block";
		} else {
			navbar[i].style.display = "none";
		}
	}

	return false;

}

function dex_navigation(nav, w) {

	if (ie) {
		navbar = document.getElementById("top_nav_main2").childNodes;
	} else {
		navbar = document.getElementById("top_nav_main2").childNodes;
	}

	for (i=0; navbar[i]; i++) {
		if (navbar[i].id == "nav"+nav) {
			navbar[i].className = "top_nav2active";
		} else {
			navbar[i].className = '';
		}
	}

	navbar = document.getElementById("top_nav3").childNodes;
	document.getElementById("top_nav3").style.right = w+'px';
	document.getElementById("top_nav3").style.display = "block";
	for (i=0; navbar[i]; i++) {
		if (navbar[i].id == "top_nav_sec"+nav) {
			navbar[i].style.display = "block";
		} else {
			navbar[i].style.display = "none";
		}
	}

	return false;

}

function dex_hide_nav() {
	document.getElementById("top_nav3").style.display = "none";
}

function update_alpha(obj){
	alpha=obj[obj.selectedIndex].value;
	fieldname=obj.id.substr(0,obj.id.length-6);
	//get old value
	val=document.getElementById(fieldname).value;
	parts=val.split("_");
	document.getElementById(fieldname).value=parts[0]+'_'+alpha;
}
function open_window(address,win_name,op_tool,op_loc_box,op_dir,op_stat,op_menu,op_scroll,op_resize,op_wid,op_heigh){
	win_name = win_name ? win_name : "Window";
	op_tool  = op_tool ? 1 : 0;
	op_loc_box  = op_loc_box ? 1 : 0;
	op_dir  = op_dir ? 1 : 0;
	op_stat  = op_stat ? 1 : 0;
	op_menu  = op_menu ? 1 : 0;
	op_scroll  = op_scroll ? 1 : 0;
	op_resize  = op_resize ? 1 : 0;
	LeftPosition = (screen.width) ? (screen.width-op_wid)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-op_heigh)/2 : 0;
	option = "top="+TopPosition+",left="+LeftPosition+"toolbar="+ op_tool +",location="+ op_loc_box +",directories="+ op_dir +",status="+ op_stat+",menubar="+op_menu+",scrollbars="+op_scroll+",resizeable="+op_resize+",width="+op_wid+",height="+ op_heigh;
	rt=window.open('', win_name, option);
	rt.location=address;
	rt.resizeTo(op_wid+10,op_heigh+50);
	return rt;
}

function msg_window(address,win_name){
	wobj=open_window(address,win_name,0,0,0,1,0,0,1,500,400)
	try{
		wobj.focus();
		wobjname = wobj.name;
	}catch(e){
		if (e.description)
			alert("Instant message has been blocked by POP-UP BLOCKER.\nPlease disable the POP-UP BLOCKER to recieve the message");
	}
}
function small_window(address,win_name){
	wobj=open_window(address,win_name,0,0,0,1,0,1,0,500,400)
	try{
		wobj.focus();
		wobjname = wobj.name;
	}catch(e){
		if (e.description)
			alert("Instant message has been blocked by POP-UP BLOCKER.\nPlease disable the POP-UP BLOCKER to recieve the message");
	}
}
function send_rss(selectobj){
	var url=selectobj.options[selectobj.options.selectedIndex].value;
	open_window(url,'rss',1,1,1,1,1,1,1,700,600)
}
function color_window(address,obj){
		var div=document.getElementById(obj.id+'_div');
		var html='<div class="color_picker" id="container-'+obj.id+'">';

		html+='<div id="picker_'+obj.id+'">';
		html+='<div class="del" style="float: left;" onclick="hide(document.getElementById(\''+div.id+'\'))"></div>';
		html+='<div class="picker" onclick="color_window_picker(event)" id="picker-'+obj.id+'" />' ;
		if (!ie)
			html+='<img src="/template/pickerbg.png" />' ;
		html+='<img src="/template/select.png" class="select" id="select-'+obj.id+'" />' ;
		html+="</div>"
		html+='<div onclick="color_window_slider(event)" id="slider-'+obj.id+'" class="slider" />';
		html+='<img src= "/template/hline.png" id="slider_img-'+obj.id+'" class="slider_img" />';
		html+='<div id="values_'+obj.id+'" class="values"  />';
		html+='</div>';
		div.innerHTML=html;

		div.style.display="block"
}
function color_window_slider(e){
	if (!e) var e = window.event;
	var y;
	if (ie)
	{
		y = e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	}
	else
	{
		y = e.pageY;
	}
	var tar= e.target || e.srcElement;
	id=tar.id.split("-");

	var realpos=getRealPos(tar,"Top");
	var relpos=y-realpos-10;
	if (relpos>0 && relpos<180){
		var col=getVertColor(relpos, 180);
		//var hexcol=hex(col.r)+hex(col.g)+hex(col.b);
		document.getElementById("picker-"+id[1]).style.backgroundColor="rgb("+col.r+","+col.g+","+col.b+")";
	}
	var selector=document.getElementById('slider_img-'+id[1]);
	selector.style.top=relpos+'px';
}
function color_window_picker(e){
	if (!e) var e = window.event;
	var x;
	var y;
	if (ie)
	{
		x = e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
		y = e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	}
	else
	{
		x = e.pageX;
		y = e.pageY;
	}

	var tar= e.target || e.srcElement;
	if (ie){ //ie does not have a parent node because we work with div
		var id=tar.id.split("-");
		var exp=tar.style.backgroundColor.split(",");
	}else{
		var id=tar.parentNode.id.split("-");
		var exp=tar.parentNode.style.backgroundColor.split(",");
	}
	var base =  new Object();

	base.r=parseInt(exp[0].substr(4,4))
	if (isNaN(base.r))
		base.r=0;
	base.g=parseInt(exp[1])
	if (isNaN(base.g))
		base.g=0;
	base.b=parseInt(exp[2])
	if (isNaN(base.b))
		base.b=0;

	//alert(base.r+' '+base.g+' '+base.b)
	var realy=y-getRealPos(tar,"Top")-(ie?6:0);
	var realx=x-getRealPos(tar,"Left")-(ie?22:0);

	var posx=Math.round((realx-(ie?0:7))*255/180)
	var posy=Math.round((realy-(ie?0:7))*255/180)

	var col=getGradientColor(posx, posy, base);
	document.getElementById(id[1]).style.backgroundColor="#"+hex(col.r)+hex(col.g)+hex(col.b);

	var el_id=id[1].split("_")
	document.getElementById(el_id[0]+'_'+el_id[1]).value=hex(col.r)+hex(col.g)+hex(col.b);

	var selector=document.getElementById('select-'+id[1]);
	if (ie){
		selector.style.top=realy+'px';
		selector.style.left=realx+'px';
	}else{
		selector.style.top=(realy-5)+'px';
		selector.style.left=(realx-5)+'px';
	}

}
function getGradientColor(x, y, Base){
	    x = x<0?0:x>255?255:x; // make sure x is between 0 and 255
	    y = y<0?0:y>255?255:y; // make sure y is between 0 and 255

	    var r = Math.round((1-(1-(Base.r/255))*(x/255))*(255-y));
	    var g = Math.round((1-(1-(Base.g/255))*(x/255))*(255-y));
	    var b = Math.round((1-(1-(Base.b/255))*(x/255))*(255-y));

	    return {r:r, g:g, b:b};
}

function getVertColor(i, sZ){
    var n=sZ/6, j=sZ/n, C=i, c=C%n;

    r=C<n?255:C<n*2?255-c*j:C<n*4?0:C<n*5?c*j:255;
    g=C<n*2?0:C<n*3?c*j:C<n*5?255:255-c*j;
    b=C<n?c*j:C<n*3?255:C<n*4?255-c*j:0;

    return {r:r, g:g, b:b};
}
function hex(c){
	    c=parseInt(c).toString(16);
	    return c.length<2?"0"+c:c
}

function rating_window(t,id){
	open_window('frames/show_rates.php?t='+t+'&id='+id,"rates",0,0,0,1,0,1,1,450,250)
}
function change_pw(userid){
	open_window('/frames/password.php?id='+userid,'change_password',0,0,0,1,0,0,1,400,300)
}
function update_pw(prtl){
	open_window('/frames/password.php?email=1&id='+prtl,'update_password',0,0,0,1,0,0,1,300,200)
}

function audioDo(url){
	if (ie)
		document.body.innerHTML+='<bgsound src="'+url+'" loop="0">';
	else
		document.body.innerHTML+'<embed id="mssngr" src="'+url+'" loop="flase" autostart"true" hidden="true" mastersound="mastersound" ></embed>';
}
/******
Recursive function to get the real position
of an html element
*******/
function getRealPos(i,which)
{
	iPos = 0
	while (i!=null) {
	 	iPos += i["offset" + which]
		i = i.offsetParent
	}
	return iPos
}
function go(whichURL){
	if (whichURL)
		location=whichURL[whichURL.selectedIndex].value;
	else
		return;
}
function setDisplayExplain(nid,prop){
	if (document.getElementById('explain_text_'+nid)){
		el=document.getElementById('explain_text_'+nid)

		if (el.className=='explanation')
			el.className='explanation_hidden';
		else
			el.className='explanation';
	}
}
function dodelected(obj,indx){
	opts=document.getElementById(obj).options;
	ln=opts.length
	for (j=0;ln>j;j++)
		if (opts[j].value==indx){
			opts[j].selected=true;
		}
}
function submitonce(theform) {
	// if IE 4+ or NS 6+
	//check_form();
	if (document.all || document.getElementById) {
		// hunt down "submit" and "reset"
		if(theform.elements){
			for (i=0;i<theform.length;i++) {
				var tempobj=theform.elements[i];
				if(tempobj.type.toLowerCase()=="submit") {
					//disable it
					tempobj.disabled=true;
				}
			}
		}
	}
}

function check_all(theform,button){
	if (document.all || document.getElementById) {
		ok=button.checked;
		for (i=0;i<theform.length;i++) {
			var tempobj=theform.elements[i];
			temp=tempobj.name.toLowerCase()
			if(temp.slice(0,3)=="msg") {
				if (ok)
					tempobj.checked=true;
				else
					tempobj.checked=false;
			}
		}
	}
}
function submit_delete(theform){
	//theform.action='mail.php';
	theform.todo='delete';
	theform.submit();
}
function submit_block(theform){
	//theform.action='mail.php';
	theform.todo='block';
	theform.submit();
}
function change_css_class(td,class_name){
td.className=class_name;
}
function report(type,id,email){
	//open_window(address,win_name,op_tool,op_loc_box,op_dir,op_stat,op_menu,op_scroll,op_resize,op_wid,op_heigh){
	var email = (email == null) ? '' : '&email=yes';
	open_window('frames/report.php?typeid='+type+'&id='+id+email,"report",0,0,0,0,0,0,1,550,600);
	return false;
}
function grow_elm(elm,interval,trgetHeight){
  globaleml=elm;
  //alert(nextHeight+' '+trgetHeight)
  height=parseInt(elm.style.height);
  if (height<(trgetHeight)){
    elm.style.height=height+interval+'px';
    setTimeout("grow_elm(globaleml,"+interval+","+trgetHeight+")",1)
  }

}
function show_hide(elm){
	if(elm.style.display=='none' || !elm.style.display)
		elm.style.display='block';
	else
		elm.style.display='none';
}
function show(elm){
	elm.style.display='block';
}
function hide(elm){
	elm.style.display='none';
}
function switch_file_url(elm,fieldname,fieldid){
	var elm_name = elm.name.substring(6,(elm.name.length))

	var htmlElm = document.getElementById(elm_name)

	if(elm.value=='url'){
		str='<input class="file_uploads" type="text" maxlength="1024" ';
		str+='name="'+fieldname+'['+fieldid+']" id="'+fieldname+'_'+fieldid+'" ';
		str+='onfocus="this.select();setDisplayExplain(\''+fieldname+'\',\'block\')" ';
		str+='value="http://" style="width:80%;direction:ltr;" ';
		str+='onblur="setDisplayExplain(\''+fieldname+'\',\'none\');" />';
	}else{
		str='<input class="file_uploads" type="file" name="'+fieldname+'['+fieldid+']" id="'+fieldname+'_'+fieldid+'" ';
		str+='onfocus="setDisplayExplain(\''+fieldname+'\',\'block\')" ';
		str+='onblur="setDisplayExplain(\''+fieldname+'\',\'none\');;check_file()" ';
		str+='onpropertychange="check_file()" />';
	}
	htmlElm.parentNode.innerHTML=str;
}
function another_file(field){
	for (i=0;document.getElementById("div_"+field+'_'+i);i++){
		if (document.getElementById("div_"+field+'_'+i).style.display=='none'){
				// show input
				document.getElementById("div_"+field+'_'+i).style.display='block'
				// if this was last one, hide "another" link
				if (document.getElementById("div_"+field+'_'+(i+1))==null) {
					document.getElementById("another_file").style.display='none';
				}
				break;
			//}
		}
	}
}
function remove_file_input(field, i) {
	// remove & empty input
	document.getElementById('div_'+field+'_'+i).style.display = 'none';

	// show "another" link
	if (document.getElementById("another_file").style.display=='none') {
		document.getElementById("another_file").style.display='block';
	}
}
function enable_field(field, flag) {
	if (flag==null) flag = false;

	el = document.getElementById(field);
	el.disabled  = flag;
	el.className = 'add'+(flag?' disabled':'');
}

function disable_fields (fields,flag) {
	if(flag) {
		for(i=0; fields[i]; i++) {
			el = document.getElementById(fields[i]);
			el.disabled  = flag;
			el.className = 'add'+(flag?' disabled':'');
		}
	}
}

function checklatin(string){
	valid='1234567890-_qwertyuiopasdfghjklzxcvbnm';
	if (parseInt(string.charAt(0)))
		return false;
	for (i=0;string.charAt(i);i++){
		if (!valid.match(string.charAt(i)))
			return false;
	}
	return true;
}
function checkemail(email){
var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
var matchArray=email.match(emailPat)
if (matchArray==null) {
	return false
}
var user=matchArray[1]
var domain=matchArray[2]
if (user.match(userPat)==null) {
    return false
}
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
			return false
	    }
    }
    return true
}
var domainArray=domain.match(domainPat)
if (domainArray==null) {
    return false
}
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
    domArr[domArr.length-1].length>4) {
   return false
}
if (len<2) {
   return false
}

return true;
}
/*function encodeMyHtml(html) {
     encodedHtml = encodeURI(html);
     encodedHtml = encodedHtml.replace(/\//g,"%2F");
     encodedHtml = encodedHtml.replace(/\?/g,"%3F");
     encodedHtml = encodedHtml.replace(/=/g,"%3D");
     encodedHtml = encodedHtml.replace(/&/g,"%26");
     encodedHtml = encodedHtml.replace(/@/g,"%40");
    return encodedHtml;
}*/


function detectPlugin() {
    var daPlugins = detectPlugin.arguments;
    var pluginFound = 0;
    if (navigator.plugins && navigator.plugins.length > 0) {
		var pluginsArrayLength = navigator.plugins.length;
		for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) {
	    	var numFound = 0;
	    	for(namesCounter=0; namesCounter < daPlugins.length; namesCounter++) {
				if( (navigator.plugins[pluginsArrayCounter].name.indexOf(daPlugins[namesCounter]) >= 0) ||
		    	(navigator.plugins[pluginsArrayCounter].description.indexOf(daPlugins[namesCounter]) >= 0) ) {
		    		numFound++;
				}
	    	}
	    	if(numFound == daPlugins.length) {
				pluginFound = 1;
				break;
	    	}
		}
    }
    return pluginFound;
}
function get_width(obj){
	width=0;
	for (i=0;!width && obj;i++){
		if (obj.offsetWidth){
			width=parseInt(obj.offsetWidth);
		}else if (obj.style && obj.style.width){
			width=parseInt(obj.style.width);
		}else
			obj=obj.parentNode
	}
	return width;
}



//ajax functions/////////////////////////////////////////////////////////////////////
function init_ajax(){
	var xmlhttp
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
		try {
			xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
		} catch (e) {
			try {
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
			} catch (E) {
				xmlhttp=false
			}
		}
	@else
		xmlhttp=false
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!="undefined") {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp=false
		}
	}
	if (xmlhttp.overrideMimeType) {
		xmlhttp.overrideMimeType('text/xml');
	}
	return xmlhttp;
}
hp_ajax_cache = new Array();
function tab_ajax(click_ul,obj_id,portelid,sort,typeid,my,image,lang,indx,func,limit,outercms){
	var xmlhttp=init_ajax();
	if (!xmlhttp)
		return false;
	var obj=document.getElementById(obj_id);
	var i=0;
	while (obj.hasChildNodes()){
		obj.removeChild(obj.firstChild);
	}
	//hide error messages
	for (i=0;obj.parentNode.childNodes[i];i++){
		if (obj.parentNode.childNodes[i].className=="error_message")
			obj.parentNode.childNodes[i].style.display="none"
	}
	var indicator=document.createElement("img");
	indicator.setAttribute("src","/template/ajax_indicator.gif",0);
	indicator.setAttribute("style","padding:40px;",0);
	indicator.id=obj_id+'_indicator';
	obj.appendChild(indicator);

	ul=click_ul.parentNode.parentNode.childNodes;
	for (i=0;ul[i];i++)
	{
			ul[i].className="";
	}
	ul[click_ul.parentNode.parentNode.childNodes.length-1].className="last";
	if (click_ul.parentNode.className == "last") {
		click_ul.parentNode.className="current last";
	} else {
		click_ul.parentNode.className="current";
	}

	url='/frames/homepage_query.php';

	str='sort='+sort+'&typeid='+typeid+'&portelid='+portelid+'&my='+my+'&image='+image+'&lang='+lang+'&func='+func+'&limit='+limit+'&outercms='+outercms;
	var index=outercms*1000+sort*100+typeid*10+my;

	if (!hp_ajax_cache[typeid])
		hp_ajax_cache[typeid]=new Array();

	if (hp_ajax_cache[typeid][index]){
		//show list
		updateHp(obj_id,obj,typeid,index,indx);
	}else{
		xmlhttp.open("POST", url,true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send(str);

		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {

				if (xmlhttp.responseXML){
					hp_ajax_cache[typeid][index]=xmlhttp.responseXML;
					updateHp(obj_id,obj,typeid,index,indx)
				}

			}
		}

	}
	//fix link
	var par=obj.parentNode.childNodes;

	var len = par.length
	for(i=0;i<len;i++){

  	if (par[i].tagName=="A"){
			if (my==2)
				par[i].href="index.php?t="+typeid+"&c="+portelid+"&oid="+getCookie("i")+"&sort="+sort;
			else if (my==1)
				par[i].href="index.php?t="+typeid+"&c="+portelid+"&fr=1&sort="+sort;
			else
				par[i].href="index.php?t="+typeid+"&c="+portelid+"&sort="+sort;
		}
	}
	setCookie("tab_"+obj_id, indx, 0, '/', 0, 0)
}
function updateHp(obj_id,obj,typeid,index,indx){
	//remove indicator
	if (document.getElementById(obj_id+'_indicator')){
		var elm=document.getElementById(obj_id+'_indicator');
		elm.parentNode.removeChild(elm);
	}
	var items=hp_ajax_cache[typeid][index].getElementsByTagName("item");
	var i;
	//show list
	if (items[0]){
		for (i=0;items[i];i++){
			if (items[i].textContent)
				obj.innerHTML+=items[i].textContent;
			else if (items[i].firstChild.nodeValue)
				obj.innerHTML+=items[i].firstChild.nodeValue;
		}
	}
	//show error message
	else{
		if (document.getElementById(obj_id+"_"+indx)){
			document.getElementById(obj_id+"_"+indx).style.display="block";
		}
	}
}
function init_tab_ajax(obj_id,portelid,sort,typeid,my,image,lang,func){
	var indx=getCookie("tab_"+obj_id);
	var elm=document.getElementById(obj_id+'_tabs');
	if (!indx)
		indx=0;
	if (!elm.childNodes[indx])
		indx=0;
	//get event from tab and parse to execute
	var exec_string=elm.childNodes[indx].firstChild.onclick+' ';
	var temp=exec_string.split("this");
	temp=temp[1].split("}")
	exec_string='tab_ajax(elm.childNodes[indx].firstChild'+temp[0];
	eval(exec_string);
}

function init_tag_ajax(obj_id, portelid, tagid) {
	alert('m00');
	var elm = document.getElementById(obj_id + '_tags');
	var exec_string = elm.childNodes[0].firstChild.onclick + ' ';
	var temp = exec_string.split("this");
	temp = temp[1].split("}")
	exec_string = 'tab_ajax(elm.childNodes[0].firstChild' + temp[0];
	console.log(exec_string);
	eval(exec_string);
}

tags_ajax_cache = new Array();
function tag_ajax(click_ul, obj_id, portelid, tagid, comid, indx) {
	var xmlhttp = init_ajax();
	if (!xmlhttp)
		return false;
	var obj = document.getElementById(obj_id);
	var i = 0;
	while (obj.hasChildNodes()){
		obj.removeChild(obj.firstChild);
	}
	//hide error messages
	for (i=0; obj.parentNode.childNodes[i]; i++) {
		if (obj.parentNode.childNodes[i].className == "error_message")
			obj.parentNode.childNodes[i].style.display = "none"
	}
	/*
	var indicator=document.createElement("img");
	indicator.setAttribute("src","/template/ajax_indicator.gif",0);
	indicator.setAttribute("style","padding:40px;",0);
	indicator.id=obj_id+'_indicator';
	obj.appendChild(indicator);
	*/

	ul = click_ul.parentNode.parentNode.childNodes;
	for (i=0; ul[i]; i++) {
		ul[i].className = "";
	}
	ul[click_ul.parentNode.parentNode.childNodes.length-1].className = "last";
	if (click_ul.parentNode.className == "last") {
		click_ul.parentNode.className = "current last";
	} else {
		click_ul.parentNode.className = "current";
	}

	url = '/frames/homepage_query.php';

	str = 'comid='+comid+'&tagid='+tagid+'&sort=2&typeid=15&portelid='+portelid+'&lang=1&func=8&limit=5';
	var index = 1000+tagid*100+15*10;

	if (!tags_ajax_cache) {
		tags_ajax_cache = new Array();
	}

	if (tags_ajax_cache[index]){
		//show list
		updateTags(obj_id, obj, index, indx);
	} else {
		xmlhttp.open("POST", url, true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send(str);

		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {

				if (xmlhttp.responseXML) {
					tags_ajax_cache[index] = xmlhttp.responseXML;
					updateTags(obj_id, obj, index, indx);
				}
			}
		}
	}
	//fix link
	/*
	var par = obj.parentNode.childNodes;

	var len = par.length
	for(i=0; i<len; i++){
	  	if (par[i].tagName == "A") {
			par[i].href = "index.php?t=15&c=" + portelid + "&tagid=" + tagid;
		}
	}
	*/
}
function updateTags(obj_id,obj,index,indx){
	//remove indicator
	/*
	if (document.getElementById(obj_id+'_indicator')){
		var elm=document.getElementById(obj_id+'_indicator');
		elm.parentNode.removeChild(elm);
	}
	*/
	var items = tags_ajax_cache[index].getElementsByTagName("item");
	var i;
	//show list
	if (items[0]) {
		for (i=0; items[i]; i++){
			if (items[i].textContent)
				obj.innerHTML+=items[i].textContent;
			else if (items[i].firstChild.nodeValue)
				obj.innerHTML+=items[i].firstChild.nodeValue;
		}
	}
	//show error message
	else{
		if (document.getElementById(obj_id + "_" + indx)) {
			document.getElementById(obj_id + "_" + indx).style.display = "block";
		}
	}
}

function load_region(obj,cid){

	var xmlhttp=init_ajax();
	if (xmlhttp) {
		var url='/frames/region.php';
		var str='country='+cid+'&lang='+lang;
		var dropbox=document.getElementById(obj);
		xmlhttp.open("POST", url,true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send(str);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				var check=xmlhttp.responseText;
				dropbox.options.length=0;
				if (check=='NULL' && document.getElementById('city')){
					document.getElementById('city').options.length=0;
				}else{
					chunks=check.split('|');
					for (j=0;chunks[j];j++){
						bits=chunks[j].split('!');
						dropbox.options[j] = new Option(bits[0],bits[1]);
					}
					if (document.getElementById('city')){
						if (window.r){
							load_city("city",cid,r)
						}else
							load_city("city",cid,1)
					}
					if (window.r)
						dodelected("region",r);
				}
			}
		}
	}
}
function load_city(obj,cid,rid){
	var xmlhttp=init_ajax();
	if (xmlhttp) {
		var url='/frames/city.php';
		var str='country='+cid+'&region='+rid+'&lang='+lang;
		var dropbox=document.getElementById(obj);
		xmlhttp.open("POST", url,true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send(str);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				var check=xmlhttp.responseText;
				dropbox.options.length=0;
				if(check!='NULL'){
					chunks=check.split('|');
					for (j=0;chunks[j];j++){
						bits=chunks[j].split('!');
						dropbox.options[j] = new Option(bits[0],bits[1]);
					}
					if (window.city)
						dodelected("city",city);
				}
			}
		}
	}
}
function get_http(obj,error,t,field, val,uid){
	if (val.length<1)
		return;
	url="/frames/check.php";
	xmlhttp=init_ajax();
	if (xmlhttp) {
		xmlhttp.open("POST", url,true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send('p='+pid+'&f='+field+'&s='+val+'&id'+uid+'&t='+t);
		xmlhttp.onreadystatechange=function() {

			if (xmlhttp.readyState==4) {
				check=xmlhttp.responseText;
				if (check=="bad"){
					error_msg+=error;
					obj.parentNode.className="error_active";
					obj.style.display="block";
					obj.innerHTML=error_msg;
				}
			}
		}
	}
}
function change_com_status(obj,domain){
	if (obj.className=='com_status_on'){
	    var status='0';
	    obj.className='com_status_off'
	}else{
		var status='1'
		obj.className='com_status_on'
	}
    setCookie('com_status', status, 0, '/', domain,0);
	communication(domain,'cng'+status)
}
//count requests
communication_requests=0;
function communication(domain,com_status){

	//document.cookie='';
	var http=init_ajax();

	var url='communication.php';

	//change com status
	if (com_status=='cng1')
		url+='?com_status=1'
	else if (com_status=='cng0')
		url+='?com_status=0'

	if (http) {
		http.open("GET", url,true);
		http.send(null);

		//timeout after 2000 sec
		if (communication_requests>100)
			clearInterval(communication_interval);

		communication_requests++;

		http.onreadystatechange=function() {
			if (http.readyState==4 && http.status==200) {
				var root = http.responseXML.getElementsByTagName('root');
				//email
				if (root[0] && root[0].getElementsByTagName('i')[0]){
					var email = root[0].getElementsByTagName('i')[0].firstChild.nodeValue;

					if (parseInt(email) && document.getElementById("msgs_alert"))
						document.getElementById("msgs_alert").style.display='inline';
					if (document.getElementById("email_num"))
						document.getElementById("email_num").innerHTML=email;
					setCookie('email', email, 0, '/', domain,0);
				}
					//alert(http.responseText);

				//updates
				if (root[0] && root[0].getElementsByTagName('updated')
				 && root[0].getElementsByTagName('updated')[0]){
					var online = root[0].getElementsByTagName('updated')[0].firstChild.nodeValue;
					setCookie('online', online, 0, '/', domain,0);
				}
				//get chat requests
				if (root[0].getElementsByTagName('c')){
					chatReq = root[0].getElementsByTagName('c');
					for (i=0;chatReq[i];i++){
						sid=chatReq[i].getAttribute("id");
						user=chatReq[i].getElementsByTagName('u');
						userid=user[0].getAttribute("id");
						username=user[0].firstChild.nodeValue;
						askChat(username,userid,sid);

					}
				}
			}
		}
	}
}
function loadJSON(url, func) {
	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.src = url;
	headID.appendChild(newScript);
	newScript.onreadystatechange= function () {
      if (this.readyState == 'complete' || this.readyState == 'loaded') {
      	 func();
      }
   }
	newScript.onload= func;
}

function communication_json(domain,com_status, backend){
	domain = domain;
	com_status = com_status;

	if (backend) {
		var url = backend;
	}
	else {
		var url = 'communication.php?time='+new Date().getTime()+'&json=1';
	}
	//change com status
	if (com_status=='cng1')
		url+='&com_status=1'
	else if (com_status=='cng0')
		url+='&com_status=0'

	//timeout after 2000 sec
	if (communication_requests>100)
		clearInterval(communication_interval);
	communication_requests++;

	loadJSON(url, function(){
		//email
		if (connect.i){
			var email = parseInt(connect.i);

			if (email && document.getElementById("msgs_alert"))
				document.getElementById("msgs_alert").style.display='inline';
			if (document.getElementById("email_num"))
				document.getElementById("email_num").innerHTML = email;
			setCookie('email', email, 0, '/', domain,0);
		}

		//updates
		if (connect.updated){
			var online = connect.updated;
			setCookie('online', online, 0, '/', domain,0);
		}

		//get chat requests
		if (connect.c){
			chatReq = connect.requests;
			for (i=0;chatReq[i];i++){
				var sid			= connect.c;
				var userid		= chatReq[i].uid;
				var username	= chatReq[i].username;
				askChat(username,userid,sid);
			}
		}
	}
	)
}

function askChat(username,userid,sid){
	if (typeof(userid)=='undefined')
		return false;

	errmsg=document.getElementById('chatPop');
	if (!errmsg.style.display || errmsg.style.display=='none'){
		errmsg.style.display='block';
		errmsg.style.left = parseInt(document.body.offsetWidth/2-180)+(document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft)+(ns?'px':'');
//alert(document.documentElement.scrollTop+' '+document.documentElement.clientHeight/2);
		errmsg.style.top = parseInt(document.documentElement.scrollTop+document.documentElement.clientHeight/2-100)+(ns?'px':'');//(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)+(ns?'px':'');
		document.getElementById('chatPopAvatar').src='media.php?t=u&id='+userid+'&k=s&i=0&alt=1&ext=jpg';
		//document.getElementById('chatPopUser').href='view.php?u='.userid;
		document.getElementById('chatPopUser').innerHTML=username;
		document.getElementById('chatPopOk').href='javascript:acceptChat('+sid+')';
		document.getElementById('chatPopCancel').href='javascript:rejectChat('+sid+')';
		hide=document.getElementById('chatPopHide');
		hide.style.display='block';
		hide.style.width = parseInt(document.body.offsetWidth)+(ns?'px':'');
		hide.style.height = parseInt(document.body.offsetHeight)+(ns?'px':'');//(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)+(ns?'px':'');
		window.focus();
	}
}

function acceptChat(sid){
	msg_window("im.php?sid="+sid,sid);
	document.getElementById("chatPop").style.display="none";
	document.getElementById("chatPopHide").style.display="none";
}
function rejectChat(sid){
	document.getElementById('chatPop').style.display='none';
	document.getElementById("chatPopHide").style.display="none";
	var http=init_ajax();
	xml='xml='+escape('<?xml version="1.0" ?><root><c chatsid="'+sid+'">-1</c></root>')
	http.open("POST", 'frames/chat.php',true);
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.send(xml);
	http.onreadystatechange=function() {
		if (http.readyState==4 && http.status==200) {
			//alert(http.responseText);
		}
	}

}
function show_add_content(){
	var elm=document.getElementById('add_content_div');
	if (!elm.style.display || elm.style.display=='none'){
		elm.style.display='block';
		elm.style.left = parseInt(document.body.offsetWidth/2-180)+(document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft)+(ns?'px':'');
//alert(document.documentElement.scrollTop+' '+document.documentElement.clientHeight/2);
		elm.style.top = parseInt(document.documentElement.scrollTop+document.documentElement.clientHeight/2-100)+(ns?'px':'');//(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)+(ns?'px':'');
		//var hide=document.getElementById('add_content_hide');
		//hide.style.display='block';
		//hide.style.width = parseInt(document.body.offsetWidth)+(ns?'px':'');
		//hide.style.height = parseInt(document.body.offsetHeight)+(ns?'px':'');//(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)+(ns?'px':'');
		window.focus();
	}
}

function hide_add_content(sid){
	document.getElementById("add_content_div").style.display="none";
	//document.getElementById("add_content_hide").style.display="none";
}

function sug_show(key,tag_obj){
	obj = document.getElementById("info_"+key);
	obj.style.width=tag_obj.style.width;
	obj.style.display="block";
}
function sug_hide(key){
	obj = document.getElementById("info_"+key);
	sug_blur(obj);
}
function sug_blur(obj){
	obj.style.display="none";
	//show form elements
	if (ie){
		set_form_elm("visible");
	}
}
function sug_out(obj){
	obj.style.backgroundColor=mem;
}
function sug_over(obj){
	mem=obj.style.backgroundColor;
	obj.style.backgroundColor="blue";
}
function set_form_elm(attrib){
	for (i=0;document.forms[i];i++){
		tempForm=document.forms[i];
		for (j=0;tempForm.elements[j];j++){
			if (tempForm.elements[j].nodeName.toLowerCase()=="select"){
				tempForm.elements[j].style.visibility=attrib;
			}
		}
	}
}
function ck_tags(obj,update,myid){
	//this textbox
	tag_obj=obj;
	//suggest box
	tag_update=update;
	bakid=myid;
	if (!window.callflag || callflag!=1){
		callflag=1;
		setTimeout("get_tags()",500);
	}
}
function get_tags(fieldid){
	//variable defined in ck_tags function
	callflag=0;
	str=tag_obj.value;
	if (window.old_str && old_str==str)
		return;
	old_str=str;
	up_obj=document.getElementById(tag_update);
	url="frames/tags.php";
	xmlhttp=init_ajax();
	if (xmlhttp) {
		xmlhttp.open("POST", url,true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send('t='+str);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4 && xmlhttp.responseText) {
				check=xmlhttp.responseText;
				sp=check.split(',');
				up_obj.innerHTML='';
				if (check!='error' && sp[0]){
					rv='';
					for (i=0;sp[i];i++){
						//alert(i);
						chunks=sp[i].split('|');
						rv+='<div onmousedown="u_tags(\''+tag_obj.id+'\',\''+chunks[0]+'\',1);"';
						rv+=' onmouseover="sug_over(this)"';
						//<p class="floater"> X'+chunks[1]+'</p>
						rv+=' onmouseout="sug_out(this)">'+chunks[0]+'</div>';
					}
					up_obj.innerHTML=rv;
					up_obj.style.width=tag_obj.style.width;
					up_obj.style.display="block";
					//hide form elements
					if (ie){
						//set_form_elm("hidden");
					}
				}
			}else{
				sug_blur(up_obj);
			}

		}
		//xmlhttp.send(null)
	}
}
function u_tags(objid,tag,replace){
	//clear suggest box
	if (!replace)
		replace=0;
	if (window.up_obj){
		up_obj.innerHTML='';
		up_obj.style.display="none";
	}
	tag_string=document.getElementById(objid).value;
	chunks=tag_string.split(' ');
	if (tag.match(' '))
		tag='"'+tag+'"';
	rt='';
	if (replace){
		for (i=0;chunks[(i+1)];i++){
			rt+=chunks[i]+' ';
		}
	}else{
		for (i=0;chunks[i];i++){
			rt+=chunks[i]+' ';
		}

	}
	document.getElementById(objid).value=rt+tag+' ';
	return false;
}
/**
 * Tag rich gui
 */
function tag_gui(field){
	this.field=field
	this.OpenTag=0;
	//this div hold suggestions
	this.suggest=document.getElementById("tag_suggest_"+field);
	//this div holds the tags
	this.container=document.getElementById("tag_container_"+field);
	//this is where u type the tags
	this.tagfiled=document.getElementById('text_'+field);
	xmlhttp=init_ajax();

	/**
	 * onkeyup - parse tags
	 */
	this.onkeyup=function(){

		var tag= this.tagfiled.value;

		var taglen=this.tagfiled.value.length;

		//delet leading space
		if (taglen==1 && tag.charAt(taglen-1)==' ')
			tag='';

		if (taglen>2)
			this.ajax();
		//open tag
		if (tag.charAt(taglen-1)=='"'){
			if (taglen==1)
				this.OpenTag=1;
			else{
				this.OpenTag=0;
				tag+=' ';
			}
		}

		if (!this.OpenTag && tag.charAt(taglen-1)==' '){

			this.tagfiled.value='';
			if (taglen>2)
				this.add_tag(tag)
		}
	}
	/**
	 * add tag to tag array
	 */
	this.add_tag=function (str){
		var span=document.createElement("SPAN");
		span.onclick=function(){onclick_edit(this)};
		var contnent = document.createTextNode(str.replace(/"/gi,''));
		span.appendChild(contnent);
		var tags=this.container.childNodes;
		for (i=0;tags[i];i++){
			if (tags[i].tagName!='SPAN'){
				this.container.insertBefore(span,tags[i]);
				break;
			}
		}
		this.save();
	}
	/**
	 * get suggestions
	 */
	this.ajax=function(){
		if (xmlhttp) {
			if (this.timeout)
				clearTimeout(this.timeout)
			this.timeout=setTimeout("eval('sug_"+this.field+".ajax_request()');",500);
		}
	}
	this.ajax_request = function(){
		ajax_update=this.suggest;
		field=this.field
		xmlhttp.open("POST", "frames/tags.php",true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send('t='+this.tagfiled.value);

		xmlhttp.onreadystatechange=function(){
			if (
					xmlhttp.readyState==4 &&
					xmlhttp.responseText
				) {
				var check=xmlhttp.responseText;

				var sp=check.split(',');
				if (check!='error' && sp[0]){
					ajax_update.innerHTML='';
					var rv='';
					for (i=0;sp[i];i++){
						//alert(i);
						chunks=sp[i].split('|');
						rv+='<a href="javascript:void(0)" onclick="sug_'+field+'.add_tag(\''+chunks[0]+'\')">'+chunks[0]+'</a> ';
					}
					ajax_update.innerHTML=rv;
					ajax_update.style.display="block";
				}
			}
		}
	}
	/**
	 * save tag array into field
	 */
	this.save = function(){

		var save='';
		var tags=this.container.childNodes;
		for (i=0;tags[i];i++){
			if (tags[i].nodeName=='INPUT' && tags[i].value.length>2)
				save+='"'+tags[i].value.replace(/"/gi,'')+'" ';
			else if (tags[i].nodeName=='SPAN' && tags[i].textContent.length>2)
				save+='"'+tags[i].textContent.replace(/"/gi,'')+'" ';
		}
		document.getElementById(this.field).value=save;
	}

}
//edit tags
// reference from http://www.quirksmode.org/dom/cms.html
function onclick_edit(obj){
	if (!document.getElementById || !document.createElement) return;

	while (obj.nodeType != 1) {
		obj = obj.parentNode;
	}
	//if (obj.tagName == 'TEXTAREA' || obj.tagName == 'A') return;
	while (obj.nodeName != 'SPAN' && obj.nodeName != 'HTML') {
		obj = obj.parentNode;
	}
	if (obj.nodeName == 'HTML') return;

	var x = obj.innerHTML;
	var y = document.createElement('INPUT');
	var z = obj.parentNode;
	z.insertBefore(y,obj);
	//z.insertBefore(butt,obj);
	z.removeChild(obj);
	y.onblur=form_tags_onblur_save;
	y.id='form_tag_edit';
	y.value = x;
	y.autocomplete="off";
	y.onkeyup=function (){eval('sug_'+this.field+".onkeyup(this,'form_tag_edit')")}
	y.focus();
	y.select();
	editing = true;
}
function onblur_save() {
	var obj = document.getElementById('form_tag_edit');
	var z = obj.parentNode;
	if (obj.value){
		var y = document.createElement('SPAN');
		y.innerHTML = obj.value;
		y.onclick=function(){form_tags_onclick(this)};
		z.insertBefore(y,obj);
	}
	z.removeChild(obj);
	editing = false;
	this.save();
}

dex = function (){

}









dex.auto_suggest = function(object,backend,event_kind)  {
	var elm = this;

	this.backend					= backend;
	this.sug_mark					= 0;
	this.suggest_count				= 10;
	this.ajax_in_process			= 0;
	this.show_res 					= null;
	this.lang 						= 0;
	this.selection 					= 0;
	this.edit_mode 					= false;


	// some DOM manipulation

	//SELECT
	this.sug_div    = document.createElement("SELECT");
	this.sug_div.id = "ajax_selctor";

	this.sug_div.size  					= 10;

	//UL lang
	this.ul_lang	= document.createElement("UL");
	this.ul_lang.className = "lng";

	// Letters menu
	this.ul_letters = document.createElement("UL");
	this.ul_letters.className = "abc";


	this.li_lang1			= document.createElement("li");
	this.li_lang1.style.marginLeft	= "101px";
	//elm.li_lang1.className = "clicked";
	a  = document.createElement('a');
	a.href      = 'javascript://';
	a.innerHTML = 'עברית';
	a.onclick    = function() {
		if (elm.sug_div.disabled) {
			return false;
		}
		else {
			elm.lang_action(1);
			elm.li_lang1.className = "clicked";
			elm.li_lang0.className = "";
		}
	}

	this.li_lang1.appendChild(a);
	this.ul_lang.appendChild(this.li_lang1);

	this.li_lang0			= document.createElement("li");
	elm.li_lang0.className = "clicked";
	a  = document.createElement('a');
	a.href      = 'javascript://';
	a.innerHTML = 'English';
	a.onclick    = function() {
		if (elm.sug_div.disabled) {
			return false;
		}
		else {
			elm.lang_action(0);
			elm.li_lang0.className = "clicked";
			elm.li_lang1.className = "";
		}
	}
	this.li_lang0.appendChild(a);
	this.ul_lang.appendChild(this.li_lang0);




	// Insert elments child
	object.parentNode.appendChild(elm.ul_lang);
	object.parentNode.appendChild(elm.ul_letters);
	object.parentNode.appendChild(elm.sug_div);

	// create base for ajaxon
	indicator=document.createElement("img");
	indicator.id='ajax_indicator';
	indicator.setAttribute("src","/template/ajax_indicator.gif");
	indicator.style.display = "none";
	object.parentNode.appendChild(indicator);


	this.go_there = function (obj) {
		for (i=0; elm.sug_div.options[i]; i++) {
			if (elm.sug_div.options[i].text.substring(0,1).toUpperCase() == obj.index) {
				elm.sug_div.options[i].selected = true;
			}
		}
	}


	this.event_kind = event_kind;


	this.lang_action = function(langid) {
		elm.lang = langid;
		elm.operate_req();
		object.checked = true;
		while (elm.ul_letters.hasChildNodes()) {
			elm.ul_letters.removeChild(elm.ul_letters.firstChild);
		}


		switch(elm.lang) {
			case 0:
			  language = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

			  for(i=0; language[i]; i++) {
				li = document.createElement('li');
				li.className = "en";
				a  = document.createElement('a');
				a.href      = 'javascript://';
				a.innerHTML = language[i];
				a.index		= language[i];
				a.onclick	= function () {
					if (elm.sug_div.disabled) {
						return false;
					}
					else {
						elm.go_there(this);
					}
				}
				li.appendChild(a);
				elm.ul_letters.appendChild(li);
			  }
			  break;

			case 1:

			  language = new Array('א','ב','ג','ד','ה','ו','ז','ח','ט','י','כ','ל','מ','נ','ס','ע','פ','צ','ק','ר','ש','ת');

			  for(i=0; language[i]; i++) {
				li = document.createElement('li');
				li.className = "he";
				a  = document.createElement('a');
				a.href      = 'javascript://';
				a.innerHTML = language[i];
				a.index		= language[i];
				a.onclick	= function () {
					if (elm.sug_div.disabled) {
						return false;
					}
					else {
						elm.go_there(this);
					}
				}
				li.appendChild(a);
				elm.ul_letters.appendChild(li);
			  }
		  	  break;
		}
	}


	this.unchecked_radio = function (flag) {
		if (flag) {
			elm.sug_div.disabled = flag;
			elm.sug_div.style.background="none";
			elm.ul_letters.className = "abc disabled";
			elm.ul_lang.className = "lng disabled";


			if(elm.copy_to) {
				document.getElementById(elm.copy_to).value = '';
			}

			for (var index in elm.request_fields_args) {
				el = (document.getElementById(elm.request_fields_args[index]));
				if (el.selectedIndex != 0) {
					document.getElementById(elm.copy_to).value += ' '+el.options[el.selectedIndex].text;
				}
			}

		}
	}

	this.set_copy_fields = function (copy_from,copy_to) {
		elm.copy_from = copy_from;
		elm.copy_to   = copy_to;
	}

	this.copy_fields = function() {
		document.getElementById(elm.copy_to).value = '';
		for(j=0;elm.copy_from[j];j++) {
			el = (document.getElementById(elm.copy_from[j]));
			if (el.type == 'text') {
				document.getElementById(elm.copy_to).value += ' '+el.value;
			}
			else {
				document.getElementById(elm.copy_to).value += ' '+el.options[el.selectedIndex].text;
			}
		}
	}


	this.set_show_res = function(arr) {
		elm.show_res = arr;
		for(j=0;arr[j];j++) {
			elm.j = j;
			document.getElementById(arr[elm.j]).onclick = function() {
				/*
				for(k=0;elm.show_res[k];k++) {
					document.getElementById(elm.show_res[k]).value = '';
				}

				for(k=0;elm.response_fields_values[k];k++) {
					document.getElementById(elm.response_fields_values[k]).value = '';
				}
				*/
			}

			document.getElementById(arr[elm.j]).onblur = function() {
				for(k=0;elm.show_res[k];k++) {
					document.getElementById(elm.show_res[k]).value = this.value;
				}
			}
		}
	}

	this.request_fields = function(args) {
		this.request_fields_args = args;
	}

	this.response_fields = function(args){
		i=0;
		this.response_fields_values = new Array();
		for (var index in args) {
			this.response_fields_values[i] =  args[index];
			i++;
		}
	}

	this.fields_minpulation = function(extra) {
		flag = true;
		for (var index in elm.request_fields_args) {
			if(document.getElementById(elm.request_fields_args[index]).value == 0 ) {
				flag = false;
			}
		}

		if (flag) {
			for(j=0;elm.show_res[j];j++) {
				document.getElementById(elm.show_res[j]).disabled = true;
				document.getElementById(elm.show_res[j]).className = 'add disabled';
			}
			elm.lang_action(elm.lang);

			for (var index in elm.request_fields_args) {
				el = (document.getElementById(elm.request_fields_args[index]));
				if (el.selectedIndex != 0) {
					document.getElementById(elm.copy_to).value += ' '+el.options[el.selectedIndex].text;
				}
			}
		}
		else {
			if(extra != "undefined"){
				for(i=0; extra[i]; i++) {
					el = document.getElementById(extra[i]);
					el.disabled  = true;
					el.className = 'add disabled';
				}
			}
			elm.unchecked_radio(true);
		}


	}

	this.set_edit_mode = function (flag) {
		this.edit_mode = flag;
	}


	object.populate_radio = function (response) {
		elm.ajax_in_process = false;
		var tags = response.responseXML.getElementsByTagName('tag');
		elm.sug_div.length = 0;
		var len = elm.response_fields_values.length;

		if (!elm.edit_mode) {
			for(k=0;elm.show_res[k];k++) {
						document.getElementById(elm.show_res[k]).value = '';
			}

			for(k=0;elm.response_fields_values[k];k++) {
				document.getElementById(elm.response_fields_values[k]).value = '';
			}
		}
		// Can happen only for the first time.
		else {
			elm.set_edit_mode(false);
		}


		// This inserting operation does not insert alphabetical options, must get sorted tags for this.
		if(tags[0])	{

			document.getElementById("ext_error").style.display = "none";

			for (i=0; tags[i]; i++) {
				tagtext = (tags[i].firstChild.nodeValue);
				elm.sug_div.onclick = function() {
					opt = elm.sug_div.options[elm.sug_div.selectedIndex];
					for(j=0;elm.show_res[j];j++) {
						document.getElementById(elm.show_res[j]).value = opt.text;
					}

					for (j=0 ; j<len ;j++)
					{
						document.getElementById(elm.response_fields_values[j]).value = opt.id;
					}

					elm.copy_fields();
				}
				elm.sug_div.options[i] = new Option(tagtext, tagtext);

				for (j=0 ; j<len ;j++)
				{
					elm.sug_div.options[i].id = tags[i].getAttribute(elm.response_fields_values[j]);
				}

				if (elm.sug_div.options[i].id == elm.selection) {
					elm.sug_div.options[i] = new Option(tagtext, tagtext);
					elm.sug_div.selectedIndex = i;
					elm.sug_div.options[i].id = elm.selection;
					opt = elm.sug_div.options[elm.sug_div.selectedIndex];
					for(j=0;elm.show_res[j];j++) {
						document.getElementById(elm.show_res[j]).value = opt.text;
					}

					for (j=0 ; j<len ;j++)
					{
						document.getElementById(elm.response_fields_values[j]).value = opt.id;
					}
					elm.copy_fields();
				}
			}
		}
		else {
				elm.extra_js_noresults();
				if(elm.copy_to) {
					document.getElementById(elm.copy_to).value = '';
				}

				for (var index in elm.request_fields_args) {
					el = (document.getElementById(elm.request_fields_args[index]));
					if (el.selectedIndex != 0) {
						document.getElementById(elm.copy_to).value += ' '+el.options[el.selectedIndex].text;
					}
				}
		}

		//ajax gif remove
		elm.ajax_indicator_service(elm.ajax_in_process);
	}

	object.onchange = function(evnt) {
		elm.operate_req();
	}

	this.operate_req = function () {
		elm.sug_div.disabled = false;
		elm.sug_div.style.background="#fff";
		elm.ul_letters.className = "abc";
		elm.ul_lang.className = "lng";

		elm.ajax_in_process = true;

		var request_string = 'action=categories_suggest&c='+elm.suggest_count;

		if (elm.behavior != 'tags') {
			request_string += '&b='+elm.behavior+'&lang='+elm.lang;
		}

		if (elm.request_fields_args)
		{
			i=0;
			this.request_fields_values = new Array();
			for (var index in elm.request_fields_args) {
				this.request_fields_values[i] = elm.request_fields_args[index];
				var elmid = elm.request_fields_args[index];
				request_string += '&' + elmid + '=' + document.getElementById(elmid).value;

				i++;
			}
		}
		//create ajax gif
		elm.ajax_indicator_service(elm.ajax_in_process);

		elm.req.request(request_string,'POST');

	}

	this.ajax_indicator_service = function(flag) {
		if (flag) {
			document.getElementById("ajax_indicator").style.display = "block";
		}
		else {
			document.getElementById("ajax_indicator").style.display = "none";
		}

	}

	this.set_selector = function (value) {
		elm.selection = value;
	}

	this.intial_run = function() {
		if (this.event_kind == 'radio_event') {
			flag = false;
			this.req = new dex.ajax(this.backend,object.populate_radio);
			if (elm.request_fields_args) {
				flag = true;
				for (k in elm.request_fields_args) {
					if( document.getElementById(elm.request_fields_args[k]).value == 0) {
						flag = false;
						break;
					}
				}
			}

			if(flag) {
				elm.lang_action(elm.lang);
				object.disabled=false;
			}
			else {
				elm.unchecked_radio(true);
			}

			if ((document.getElementById(elm.show_res[1]).value != '') && (document.getElementById(elm.response_fields_values[0]).value == 0)) {
				document.getElementById(elm.show_res[0]).value = document.getElementById(elm.show_res[1]).value;
				elm.extra_js_revertfields();
				elm.unchecked_radio(true);
			}

		}
	}


}










/**
 * Autocomplete
 * Make autocomplete element
 * @param string object_id
 * @param string backend
 * @return void
 */
dex.autocompleate = function(object,backend) {

	var elm = this
	this.backend			= backend;
	this.ajax_in_process	= 0;
	this.string				= '';
	this.old_string			= '';
	//pointer to option
	this.sug_mark			= 0;
	this.suggest_count		= 10;
	this.behavior			= 'tags';

	//some DOM manipulation
	object.setAttribute("autocomplete","off");
	this.sug_div = document.createElement("UL");
	this.sug_div.style.zindex = 100;
	this.sug_div.className				= "suggest_tags";
	this.sug_div.style.position			= "absolute";
	this.sug_div.style.display			= "none";
	this.sug_div.style.width			= object.style.width;
	this.sug_div.style.zIndex			= 100;
	this.sug_div.style.borderWidth		= 1;
	this.sug_div.style.top = (getRealPos(object,"Top") + object.offsetHeight) + 'px';
	if (is_ie6) {
		// ie6 renders absolute diffrently
		this.sug_div.style.left = (getRealPos(object,"Left") + 100) + 'px';
	} else {
		this.sug_div.style.left = (getRealPos(object,"Left")) + 'px';
	}
	object.parentNode.appendChild(this.sug_div)
	this.suggest_field = object;
	/**
	 * specifiy extra field to send to backend
	 * @param object args
	 * @return void
	 */
	this.request_fields = function(args) {
		this.request_fields_args = args;
	}
	/**
	 * specifiy extra field to update
	 * @param object args
	 * @return void
	 */
	this.response_fields = function(args){
		i=0;
		this.response_fields_values = new Array();
		for (var index in args) {
			this.response_fields_values[i] =  args[index];
			i++;
		}
	}
	/**
	 * specify suggested items count
	 * @param object args
	 * @return void
	 */
	this.set_suggest_count = function(count){
		this.suggest_count = count;
	}
	/**
	 * sepcify suggest field behavior.
	 * possible values:
	 * 1. tags	: many tags seperated by spaces
	 * 2. 1-term: one term
	 * @param object args
	 * @return void
	 */
	this.set_behavior = function(behavior){
		this.behavior = behavior;
	}
	/**
	 * set input object methods
	 * @param event
	 * @return void
	 */
	object.onkeyup = function(evnt) {
		if (window.event) keycode = window.event.keyCode;
		else if (evnt) keycode = evnt.which;

		//do nothing
		if (keycode == 13 || keycode == 27 || keycode == 38 || keycode == 40) {
			return false;
		}

		if (elm.behavior == '1-term') {
			do_suggest = (this.value.length>1  && elm.old_string != this.value);

			// if we need to reset the dependent fields
			if (elm.old_string != this.value) {
				//use custom fields and reset them
				if (elm.response_fields_values) {
					var len = elm.response_fields_values.length;
					for (i=0 ; i<len ;i++) {
						document.getElementById(elm.response_fields_values[i]).value = 0;
					}
				}
			}
		} else {
			do_suggest = (this.value.length>1 && this.value.substr(-1)!=' ' && elm.old_string != this.value);
		}

		//if has length and not space
		if (do_suggest)
		{
			elm.old_string = this.value;
			elm.ajax_in_process = true;

			var request_string = 'action=suggest_tags&c='+elm.suggest_count+'&t='+this.value.toLowerCase();

			if (elm.behavior != 'tags') {
				request_string += '&b='+elm.behavior;
			}

			//add custom request fields
			if (elm.request_fields_args)
			{

				i=0;
				this.request_fields_values = new Array();
				for (var index in elm.request_fields_args) {
					this.request_fields_values[i] = elm.request_fields_args[index];

					var elmid = elm.request_fields_args[index];
					request_string += '&' + elmid + '=' + document.getElementById(elmid).value;

					i++;
				}
							}
			elm.req.request(request_string,'POST');
		}else
			this.hide_suggest();
		this.sug_mark = 0;
	}
	/**
	 * populate suggest box
	 * @param responseXML http object response
	 * @return void
	 */
	object.populate = function(response){

		elm.ajax_in_process = false;
		var i = 0;
		if (response.responseXML) {

			var tags = response.responseXML.getElementsByTagName('tag');

			//remove old entities
			while (elm.sug_div.hasChildNodes()) {
				elm.sug_div.removeChild(elm.sug_div.firstChild);
			}
			if (elm.response_fields_values) {
				var len = elm.response_fields_values.length;
			}
			//build new html
			if (tags[0]) {
				for (i=0; tags[i]; i++) {
					var li	= document.createElement('li');
					var a	= document.createElement('a');
					a.href	= 'javascript://';
					a.innerHTML = tags[i].firstChild.nodeValue;
					if (!i) {
						li.className='over';
					}
					li.appendChild(a);
					li.onclick		= function (){ elm.use_suggestion(this) };
					li.onmouseover	= function (){ elm.mark_mouse_suggestion(this) };

					//add custom fields
					if (elm.response_fields_values) {
						for (j=0 ; j<len ;j++) {
							//set values
							var newAttr = document.createAttribute(elm.response_fields_values[j]);
							newAttr.nodeValue = tags[i].attributes.getNamedItem(elm.response_fields_values[j]).value
							li.setAttributeNode(newAttr);

							//li.onmouseover	= function (){ elm.mark_mouse_suggestion(this) };
							//li.onclick		= function (){ elm.use_suggestion(this) };

						}
					}
					elm.sug_div.appendChild(li);
				}
				elm.sug_div.style.display = "block";
			} else {
				elm.sug_div.style.display = "none";
			}
		}

		if (i>10) {
			elm.sug_div.style.height = "150px";
			elm.sug_div.style.overflow = "auto";
		} else {
			elm.sug_div.style.height = "auto";
		}

		elm.sug_mark = 0;
	}
	/**
	 * on key down event
	 *
	 * special actions: use, esc, up and down
	 * @param event
	 * @return false
	 */
	object.onkeydown = function(evnt) {
		if (window.event) keycode = window.event.keyCode;
		else if (evnt) keycode = evnt.which;

		//enter
		if (keycode == 13) {
			this.use_suggestion(elm.sug_div.childNodes[elm.sug_mark]);
			return false;
		//esc - hide suggestion
		}else if (keycode == 27) {
			this.hide_suggest();
			return false;
		}
		//move selection up
		else if (keycode == 38) {
			this.mark_suggestion(elm.sug_mark-1);
			return false;
		}
		//move selection down
		else if (keycode == 40) {
			this.mark_suggestion(elm.sug_mark+1);
			return false;
		}

	}
	/**
	 * hide suggest
	 */
	object.hide_suggest = function() {
		elm.sug_div.style.display = "none";
	}

	/**
	 * hide suggest
	 */
	this.hide_suggest = function() {
		elm.sug_div.style.display = "none";
	}

	/**
	 * mark suggestion li
	 *
	 * @param li element
	 */
	this.mark_mouse_suggestion = function(li) {
		//get selection index
		var index = 0;
		var new_sug_mark =-1;

		while (elm.sug_div.childNodes[index]) {
			if (li.innerHTML == elm.sug_div.childNodes[index].innerHTML) {
				new_sug_mark = index;
				break;
			}
			index ++;
		}
		if (new_sug_mark >= 0) {
			this.set_maker(new_sug_mark)
		}
	}

	/**
	 * mark suggestion li
	 *
	 * @param li index
	 */
	object.mark_suggestion = function(new_sug_mark) {
		//get index
		if (new_sug_mark >= 0 && elm.sug_div.childNodes[new_sug_mark]) {
			elm.set_maker(new_sug_mark);
		}
	}

	/**
	 * moves selection from li to li
	 *
	 * @param li element
	 */
	this.set_maker = function(new_sug_mark) {
		this.sug_div.childNodes[new_sug_mark].className ='over';
		this.sug_div.childNodes[this.sug_mark].className ='';
		this.sug_mark = new_sug_mark;
	}

	/**
	 * use selected suggestion
	 *
	 * @param li index
	 */
	object.use_suggestion = function(li)
	{
		return elm.use_suggestion(li,object);
	}

	/**
	 * use selected suggestion
	 *
	 * @param li index
	 * @param obj ul
	 * @return void
	 */
	this.use_suggestion = function(li, obj) {

		var string = li.firstChild.firstChild.nodeValue
		if (obj) {
			this.suggest_obj = obj;
		} else {
			this.suggest_obj = this.suggest_field;
		}
		//1 term expression
		if (elm.behavior == '1-term') {
			this.suggest_obj.value = '"' + string + '"';
		}
		//find last expression for tag behavior
		else {


			var len = this.suggest_obj.value.length;

			var chr = '';
			var breakpoint = len;
			for (i=len; i >= 0; i--){
				chr = this.suggest_obj.value.charAt(i)
				if (chr=='"'){
					breakpoint = i+1;
					break;
				}else if (chr == ' ' && breakpoint == len){
					breakpoint = i;
				}
			}

			if (breakpoint == len)
				this.suggest_obj.value = '"' + string + '"';
			else
				this.suggest_obj.value = this.suggest_obj.value.substr(0,breakpoint)+' "' + string +'"';
		}
		//use custom fields and update them
		if (this.response_fields_values)
		{
			var len = elm.response_fields_values.length;
			for (i=0 ; i<len ;i++)
			{
				document.getElementById(elm.response_fields_values[i]).value = li.getAttribute(elm.response_fields_values[i]);
			}
		}

		this.hide_suggest();

		return false;
	}
	this.req = new dex.ajax(this.backend,object.populate);
}

dex.session = new function _session() {
	this.dex_domain = "";
	this.cookie_domain = "";
	this.communication_requests = 0;

	this.connect = function (com_status) {
			if (this.dex_domain) {
				if (this.dex_domain.substring(0,4) == 'http') {
					var url = this.dex_domain;
				} else {
					var url = 'http://' + this.dex_domain;
				}
				url = url + '/communication.php?time='+new Date().getTime()+'&json=1';
			}
			else {
				var url = '/communication.php?time='+new Date().getTime()+'&json=1';
			}
			//change com status
			if (com_status=='cng1')
				url+='&com_status=1'
			else if (com_status=='cng0')
				url+='&com_status=0'

			//timeout after 2000 sec
			if (this.communication_requests>100)
				clearInterval(this.communication_interval);
			this.communication_requests++;

			loadJSON(url, function(){
				//email

				var check_connect = (typeof(connect) == "undefined");
				if (!check_connect) {
					if (connect.i){
						var email = parseInt(connect.i);

						if (email && document.getElementById("msgs_alert"))
							document.getElementById("msgs_alert").style.display='inline';
						if (document.getElementById("email_num"))
							document.getElementById("email_num").innerHTML = email;
						if (document.getElementById("email_classname")) {
							if (email > 2) {
								document.getElementById("email_classname").className = "email_2";
							} else {
								document.getElementById("email_classname").className = "email_" + email;
							}
						}
						setCookie('email', email, 0, '/', this.cookie_domain,0);
					}

					//updates
					if (connect.updated){
						var online = connect.updated;
						setCookie('online', online, 0, '/', this.cookie_domain,0);
					}

					//get chat requests
					if (connect.c){
						chatReq = connect.requests;
						for (i=0;chatReq[i];i++){
							var sid			= connect.c;
							var userid		= chatReq[i].uid;
							var username	= chatReq[i].username;
							dex.session.chat_request(username,userid,sid);
						}
					}
				}
			}
			)
	}

	this.init = function() {
		this.communication_interval = setInterval("dex.session.connect()",20000);
	}

	this.set_dex_domain = function(val) {
		this.dex_domain = val;
	}

	this.set_cookie_domain = function (val) {
		this.cookie_domain = val;
	}

	this.chat_request = function (username,userid,sid){
		if (typeof(userid)=='undefined')
			return false;

		errmsg=document.getElementById('chatPop');
		if (!errmsg.style.display || errmsg.style.display=='none'){
			errmsg.style.display='block';
			errmsg.style.left = parseInt(document.body.offsetWidth/2-180)+(document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft)+(ns?'px':'');
			//alert(document.documentElement.scrollTop+' '+document.documentElement.clientHeight/2);
			errmsg.style.top = parseInt(document.documentElement.scrollTop+document.documentElement.clientHeight/2-100)+(ns?'px':'');//(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)+(ns?'px':'');
			document.getElementById('chatPopAvatar').src='media.php?t=u&id='+userid+'&k=s&i=0&alt=1&ext=jpg';
			//document.getElementById('chatPopUser').href='view.php?u='.userid;
			document.getElementById('chatPopUser').innerHTML=username;
			document.getElementById('chatPopOk').href='javascript:dex.session.chat_accept('+sid+')';
			document.getElementById('chatPopCancel').href='javascript:dex.session.chat_reject('+sid+')';
			hide=document.getElementById('chatPopHide');
			hide.style.display='block';
			hide.style.width = parseInt(document.body.offsetWidth)+(ns?'px':'');
			hide.style.height = parseInt(document.body.offsetHeight)+(ns?'px':'');//(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)+(ns?'px':'');
			window.focus();
		}
	}

	this.chat_accept = function(sid){
				msg_window(this.dex_domain+"/im.php?sid="+sid,sid);
				document.getElementById("chatPop").style.display="none";
				document.getElementById("chatPopHide").style.display="none";
	}

	this.chat_reject = function(sid){
			document.getElementById('chatPop').style.display='none';
			document.getElementById("chatPopHide").style.display="none";
			var url = this.dex_domain + "/frames/chat.php?json=1&chatsid="+sid+"&value=-1";
			loadJSON(url, "");

			/*var http=init_ajax();
			xml='xml='+escape('<?xml version="1.0" ?><root><c chatsid="'+sid+'">-1</c></root>')
			http.open("POST", 'frames/chat.php',true);
			http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			http.send(xml);
			http.onreadystatechange=function() {
				if (http.readyState==4 && http.status==200) {
					//alert(http.responseText);
				}
			}*/

	}
}
/**
 * make ajax request
 */
dex.ajax = function(backend,callback){

	var elem		= this;
	this.backend	= backend;
	this.callback	= callback;

	if (!this.http){
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
			try {
				this.http = new ActiveXObject("Msxml2.XMLHTTP")
			} catch (e) {
				try {
					this.http = new ActiveXObject("Microsoft.XMLHTTP")
				} catch (E) {
					this.http = false
				}
			}
		@else
			this.http = false
		@end @*/
		if (!this.http && typeof XMLHttpRequest!="undefined") {
			try {
				this.http = new XMLHttpRequest();
			} catch (e) {
				this.http = false
			}
		}
		if (this.http.overrideMimeType) {
			this.http.overrideMimeType('text/xml');
		}
	}

	this.request = function(query,method){

		//alert(this.callback)
		if (this.http){
			if (method == "POST"){
				this.http.open("POST", this.backend, true);
				this.http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				this.http.send(query);
			}else{
				this.http.open("GET", this.backend, true);
		        this.http.send(null);
			}
			this.http.onreadystatechange = function() {
				if (elem.http.readyState == 4) {
					elem.callback(elem.http);
				}
			}
		}
	}
}

rate_in_porcess=false;
function rate_ajax(score, dat,htmlid,portalid,returnparam){
	url="frames/rate.php";
	if (!returnparam) {
		returnparam = "return";
	}

	//check if rate is in process
	if (rate_in_porcess)
		return false;
	else
		rate_in_porcess=true;
	info=dat.split('_');
	document.getElementById('rate_'+info[2]).innerHTML='';
	//send to login
	if(!parseInt(info[0])){
		window.location.href="login.php?id="+portalid+"&"+returnparam+"="+escape(window.location);
		return false;
	}
	xmlhttp=init_ajax();
	if (xmlhttp) {

		xmlhttp.open("POST", url,true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send('dat='+dat+'&score='+score);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				check=xmlhttp.responseText;
				error=check.split(':');
				if (error[0]=='error'){
					if (error[1]=='User error')
						window.location.href="login.php?id="+portalid+"&"+returnparam+"="+escape(window.location);
					else
						document.getElementById(htmlid).innerHTML=error[1];
				}else{
					var el=document.getElementById(htmlid);
					el.innerHTML=check;
					//add score
					for (i=0;el.parentNode.childNodes[i];i++){
						if (el.parentNode.childNodes[i].className &&
						el.parentNode.childNodes[i].className=='rate_score'){
							var current_score= parseInt(el.parentNode.childNodes[i].firstChild.nodeValue);
							if (score>0)
								current_score++;
							else
								current_score--;
							el.parentNode.childNodes[i].firstChild.nodeValue=current_score;
							// Update credit cookie
							if (document.getElementById("credit1")) {
								credit_var = getCookie("credit1");
								if ((typeof(credit_var) != 'undefined') && (credit_var > 0)) {
									credit_var--;
									var domain = window.location.toString().split("//")[1];
									domain = domain.split("/")[0];
									setCookie("credit1", credit_var, 0, "/", domain);
									document.getElementById("credit1").innerHTML = credit_var;
								}
							}
						}
					}
				}
				rate_in_porcess = false;
			}
		}
	}
}
function get_community(t,c,updateobj){

	if (t==1)
		url="backend/index.php?t=1&fr=1&c="+c;
	else if (t==2)
		url="backend/index.php?t=2&c="+c;
	xmlhttp=init_ajax();
	if (xmlhttp && updateobj.length<=1) {
		var nod=document.createElement("OPTION");
		if (ie)
			nod.innerText='Loading...';
		else
			nod.text='Loading...';
		nod.id="temploading"
		updateobj.insertBefore(nod,updateobj.lastChild);
		updateobj.insertBefore(updateobj.lastChild,nod);
		xmlhttp.open("GET", url,true);

		//xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send(null);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				xml=xmlhttp.responseXML;
				if (xml)
				{
					var items = xmlhttp.responseXML.getElementsByTagName('item');
					var buffer='';
					var len = updateobj.childNodes.length;
					updateobj.removeChild(document.getElementById("temploading"));
					for (i=0;items[i];i++)
					{
						var nod=document.createElement("OPTION");
						nod.value=items[i].getElementsByTagName("link")[0].firstChild.nodeValue;
						if (ie)
							nod.innerText=items[i].getElementsByTagName("title")[0].firstChild.nodeValue;
						else
							nod.text=items[i].getElementsByTagName("title")[0].firstChild.nodeValue;

						updateobj.insertBefore(nod,updateobj.lastChild);
						updateobj.insertBefore(updateobj.lastChild,nod);
					}
					updateobj.onchange=function(){ go(this)};
				}else
					updateobj.options[1] = new Option(' ','#');
			}
		}
	}
}

// MEDIA CHOOSER FUNCTIONS
function media_chooser_go(typeid, key) {
	//alert(usersid);
	mc_index = new Array();
	mc_old_item = new Array();
	mc_old_typeid = new  Array();
	mc_items = new Array();
	mc_results_bank = new Array();
	how_many_item_to_list = 6;
}

function mc_tab_switch(key, typeid) {
	var keyIndex = key.split("stage")[1];
	mc_index[keyIndex] = 0;
	for(i=0; i<100; i++) {
		if (document.getElementById(key+"_mc_"+i)) {
			document.getElementById(key+"_mc_"+i).className = "";
		}
	}
	document.getElementById(key+"_mc_"+typeid).className = "selected";
	mc_old_typeid[keyIndex] = typeid;
	media_chooser_get_items(usersid, typeid, "mc_ul_"+key, 0, key);
}

function mc_move_items(index, key) {
	var keyIndex = key.split("stage")[1];

	//edge cases
	if (index < 0) {
		index = 0;
	} else if (index+how_many_item_to_list > mc_items[keyIndex].length) {
		index = mc_items[keyIndex].length - how_many_item_to_list;
	}

	if((index+how_many_item_to_list)%20 == 0) {
		var page = (index+how_many_item_to_list)/20;
		//populate with more results case
		media_chooser_get_items(usersid, mc_old_typeid[keyIndex], key.split('stage')[1], index, key, page);
	}

	if (index+how_many_item_to_list-1 < mc_items[keyIndex].length && index > -1) {
		mc_index[keyIndex] = index;
		media_chooser_populate(index, key, mc_old_typeid[keyIndex]);
	}
}


function media_chooser_get_items(usersid, typeid, frameid, itemindex, key, page){
	var keyIndex = key.split('stage')[1];
	if (typeof mc_results_bank[typeid] == 'undefined' || typeof page != 'undefined') {
		if (typeof page != 'undefined') {
			//getting more results
			var url = "backend/index.php?refresh=1&t="+typeid+"&c="+usersid+"&num="+((page+1)*20);
		} else {
			var url = "backend/index.php?refresh=1&t="+typeid+"&c="+usersid;
		}
		var xmlhttp = init_ajax();
		if (xmlhttp) {
			xmlhttp.open("GET", url, true);
			xmlhttp.send(null);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4) {
					xml=xmlhttp.responseXML;
					if (xml){
						mc_items[keyIndex] = xmlhttp.responseXML.getElementsByTagName('item');
						if (xmlhttp.readyState==4) {
							mc_results_bank[typeid] = mc_items[keyIndex];
							//alert(itemindex);
							xmlhttp.onreadystatechange = media_chooser_populate(itemindex, key, typeid);
						}
					}
				}
			}
		}
	} else {
		mc_items[keyIndex] = mc_results_bank[typeid];
		media_chooser_populate(itemindex, key, typeid);
	}

}

function media_chooser_populate(itemindex, key, typeid) {
	//cleaning the ul
	var ul_obj = document.getElementById("mc_ul_"+key);
	var keyIndex = key.split('stage')[1];
	//alert(mc_items[keyIndex]);
	while (ul_obj.hasChildNodes()){
		ul_obj.removeChild(ul_obj.firstChild);
	}
	for (i=itemindex;((mc_items[keyIndex][i]) && ((itemindex+how_many_item_to_list-i)>0));i++) {
		var li = document.createElement("LI");
		var a = document.createElement("A");
		var img = document.createElement("IMG");
		var span = document.createElement("SPAN");
		var item_name = "";
		var item_id = mc_items[keyIndex][i].getElementsByTagName('guid')[0].firstChild.nodeValue.split("=")[1];
		if ( temp = mc_items[keyIndex][i].getElementsByTagName('title')) {
			temp = temp[0].firstChild;
			//console.log(temp.nodeValue);
			if (temp != null) {
				 item_name = mc_items[keyIndex][i].getElementsByTagName('title')[0].firstChild.nodeValue;
			}
		}
		var item_mime = "";
		if (typeof mc_items[keyIndex][i].getElementsByTagName('enclosure')[0] != 'undefined'
			&& mc_items[keyIndex][i].getElementsByTagName('enclosure')[0] ) {
				item_mime = mc_items[keyIndex][i].getElementsByTagName('enclosure')[0].attributes[0].firstChild.nodeValue.split(".").pop();
		}
		//slice the name if it is to big
		if (temp != null) {
			if (item_name.length > 11) {
				item_name_s = item_name.slice(0, 11) + '...';
			} else {
				item_name_s = item_name;
			}
			item_name = item_name.replace('|', ''); //protect from pipes
		}
		a.setAttribute("href", "javascript:mc_select("+item_id+", \'"+key+"\', \'|"+item_mime+"\', \'|"+item_name+"\', '|"+typeid+"')");
		img.setAttribute("src", "/media.php?t=t&id="+item_id+"&k=small&e=jpg&i=0&alt="+typeid);
		img.setAttribute("id", "mc_img_"+key+"_"+item_id);
		img.removeAttribute("class");
		if (mc_old_item[keyIndex] != 0 && mc_old_item[keyIndex] == item_id) {
			//if it was already selected
			//alert(i);
			img.setAttribute("class", "selected");
		} else {
			//regular
			img.setAttribute("class", "thumb");
		}
		if (item_name) {
			span.innerHTML = item_name_s;
		} else {
			span.innerHTML = 'ללא שם';
		}
		li.appendChild(a);
		a.appendChild(img);
		a.appendChild(span);
		ul_obj.appendChild(li);
	}
}

function mc_select(mediaid, key, mediaext, medianame, mediatype) {
	//clear old one
	var keyIndex = key.split('stage')[1];
	if (mc_old_item[keyIndex] != 0 && document.getElementById("mc_img_"+key+"_"+mc_old_item[keyIndex])) {
		document.getElementById("mc_img_"+key+"_"+mc_old_item[keyIndex]).className = "thumb";
	}
	document.getElementById("mc_img_"+key+"_"+mediaid).className = "selected";
	document.getElementById("mc_img_"+key+"_"+mediaid).blur();
	document.getElementById("old_item_"+key).style.visibility = "visible";
	document.getElementById("media_chooser_"+key).value = mediaid + mediaext + medianame + mediatype;
	//remember pervious selection for various uses
	mc_old_item[keyIndex] = mediaid;
	//old item div
	var old_item_div = document.getElementById("old_item_"+key);
	var img = document.createElement("IMG");
	img.setAttribute("src", "/media.php?t=t&id="+mediaid+"&k=small&e=jpg&i=0&alt="+mediatype.split('|')[1]);
	while (old_item_div.hasChildNodes()){
		old_item_div.removeChild(old_item_div.firstChild);
	}
	old_item_div.appendChild(img);


}

function mc_clear(key) {
	document.getElementById("media_chooser_"+key).value = "";
	document.getElementById("old_item_"+key).style.visibility = "hidden";
}

// END OF MEDIA CHOOSER FUNCTIONS

//page through years
function blog_slider(go){


	var years=document.getElementById("blog_archive").childNodes;

	var years_count=years.length;

	//find current year
	for (i=0;years[i];i++){
		if (years[i].className=='current_year'){
			var current_year_index=i;
			break;
		}
	}
	//if there is no where to go
	if (
		(go==1 && current_year_index==0) ||
		(go==-1 && current_year_index==(years_count-1))
	){

	}else{
		years[current_year_index].className='not_current';
		//alert((current_year_index+go));
		years[(current_year_index+(-go))].className='current_year';
	}

}
//images at homepage
function images_jump(counter,delta){
	url_array=eval("image_arr"+counter);
	player=eval("player"+counter);
	var index=player.pointer+delta;
	placeholder=document.getElementById("placeholder"+counter)
	//placeholder.style.width=placeholder.offsetWidth;
	//placeholder.style.height=placeholder.offsetHeight;
	var size=url_array.length-1;
	if (index<0)
		index=size;
	if (index>size)
		index=0;
	player.pointer=index;

	player.setFilename(url_array[index][0]);
	player.setExt(url_array[index][1])
	player.setLink(url_array[index][2])
	player.frameOrImage(0,1);

}

function vertical_scroller(elm_id){

	scrollerelm = this;
	this.scroller = document.getElementById(elm_id);

	var up = document.createElement("A");

	up.setAttribute('href','javascript://');
	up.setAttribute('class','moveup');
	up.onmousedown = function(){
		scrollerelm.speed = scrollerelm.base_speed;
		scrollerelm.call = 1;
		scrollerelm.moveup();
	}
	up.onmouseup = function(){
		scrollerelm.call = 0;
	}

	var down = document.createElement("A");
	down.setAttribute('href','javascript://');
	down.setAttribute('class','movedown');
	down.onmousedown = function(){
		scrollerelm.speed = scrollerelm.base_speed;
		scrollerelm.call = 1;
		scrollerelm.movedown();
	}
	down.onmouseup = function(){
		scrollerelm.call = 0;
	}

	this.base_speed = 10;
	this.speed = this.base_speed;

	this.scroller.parentNode.insertBefore(up,this.scroller);
	this.scroller.parentNode.appendChild(down);

	this.moveup = function(){
		if (this.scroller){
			if (this.scroller.scrollTop-this.speed>0)
				this.scroller.scrollTop = this.scroller.scrollTop-this.speed;
			else
				this.scroller.scrollTop = 0;
		}

		this.speed = this.speed + 5;

		if (this.call)
			this.call = setTimeout("scrollerelm.moveup()",100);
	}
	this.movedown = function(){
			//if (this.scroller.scrollTop+this.speed>0)
				this.scroller.scrollTop = this.scroller.scrollTop+this.speed;
			//else
				//this.scroller.scrollTop--;

		this.speed = this.speed + 5;

		if (this.call)
			this.call = setTimeout("scrollerelm.movedown()",100);

	}
}
//next previous widget
function next_prev(){

	this.ImageArr = new Array();

	//set array of image
	this.setArray = function(arr){
		for (i=0;arr[i];i++){
			this.setImage(arr[i]);
		}
	}

	this.setImage = function (image_array){
		var id=this.ImageArr.length;
		this.ImageArr[id]= new next_prev_image();
		this.ImageArr[id].set(image_array);
	}
}
//image object
function next_prev_image(){

	this.set = function(image_array){
		this.id=image_array[0];
		this.url=image_array[1];
		this.ext=image_array[2];
		this.link=image_array[3];
	}
}

/**
 * Slider object
 */
function slider(){
	/**
	 * Set position of slider
	 */
	this.pointer=1;
	this.ImageArr=new Array();
	/**
	 * Set image array
	 */
	this.set_img = function (){
		this.images_arr_len=this.ImageArr.length
		this.load();
	}

	this.set_images = function(arr){
		this.ImageArr[this.ImageArr.length]=arr;
	}
	this.set_obj = function (name){
		this.obj=name;
	}
	/**
	 * Go to next image
	 */
	this.go_next = function(){
		this.pointer++;

		if (this.pointer>=this.images_arr_len)
			this.pointer=0;
		this.move(this.pointer);
	}
	/**
	 * Go to prev image
	 */
	this.go_prev = function(){
		this.pointer--;

		if (this.pointer<0)
			this.pointer=this.images_arr_len-1;
		this.move(this.pointer);
	}
	this.move = function(id){

		this.next_image=document.getElementById("slider"+this.obj+"_next_image")
		this.prev_image=document.getElementById("slider"+this.obj+"_prev_image")

		var nextid=0
		this.prev_image.href="view.php?t="+this.ImageArr[id][0];
		document["slider"+this.obj+"_next_image"].src="media.php?t=t&id="+this.ImageArr[id][0]+"&k=small&i=0&alt=11&ext="+this.ImageArr[id][1];

		nextid=id+1;
		if (id>=(this.images_arr_len-1))
			nextid=0;
		this.next_image.href="view.php?t="+this.ImageArr[nextid][0];
		document["slider"+this.obj+"_prev_image"].src="media.php?t=t&id="+this.ImageArr[nextid][0]+"&k=small&i=0&alt=11&ext="+this.ImageArr[id][1];
		this.load();
	}
	this.load=function(){
		var temp;
		temp=this.pointer;
		temp=temp+2;
		if (temp>=this.images_arr_len)
			temp=this.images_arr_len-1;
		var img1=new Image;
		img1.src="media.php?t=t&id="+this.ImageArr[temp][0]+"&k=small&i=0&alt=11&ext="+this.ImageArr[temp][1];
		temp=temp-2;
		if (temp>=this.images_arr_len)
			temp=this.images_arr_len-1;
		var img2=new Image;
		img2.src="media.php?t=t&id="+this.ImageArr[temp][0]+"&k=small&i=0&alt=11&ext="+this.ImageArr[temp][1];
	}
}
/*function next_media(arrayid,direction){

	var imgobj=eval(arrayid);

	var len = imgobj.length();
	if (len)
	var prnt=click.parentNode;

	for(i=0;prnt.childNodes[i];i++){
		alert(prnt.childNodes[i].className);
		//thumbnail
		if (prnt.childNodes[i].className=="mediabox_image"){
			prnt.childNodes[i].href="view.php?t="+imgobj[0];
			prnt.childNodes[i].firstChild.src="media.php?t=t&id="+imgobj[0]+"&k=small&e="+imgobj[2]+"&i=0&alt=gallery";
		}
		if (prnt.childNodes[i].className=="mediabox_link"){
			prnt.childNodes[i].onclick="view.php?t="+imgobj[0];
		}
	}
}*/
/*function image_ajax(imgId,parentId,counter,media_server){
	url="frames/image.php";
	xmlhttp=init_ajax();
	if (xmlhttp) {
		xmlhttp.open("POST", url,true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send('id='+imgId+'&parentid='+parentId+'&counter='+counter);
		xmlhttp.onreadystatechange=function() {
		alert(xmlhttp.responseText);
			if (xmlhttp.readyState==4 && xmlhttp.responseXML) {
				check=xmlhttp.responseXML;

				media=check.getElementsByTagName('media')
				mediaUrl=media[0].firstChild.nodeValue;
				mediaExt=media[0].getAttribute("ext");
				mediaServer=media[0].getAttribute("server");

				//ply=eval("player"+counter)
				ply = new dexPlayer(mediaUrl,counter);
				ply.frameOrImage(mediaServer);

			}
		}
	}
}*/
function gallery_ajax(id,parentId){
	return true;
	/*url="frames/gallery.php";
	xmlhttp=init_ajax();
	if (xmlhttp) {
		xmlhttp.open("POST", url,true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send('id='+id+'&parentid='+parentId);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				check=xmlhttp.responseText;
				alert(check);
				//error=check.split(':');
				//on error do nothing
				//if (error[0]!='error'){
					//imgArr=check.split('@')
				//}
			}
		}
	}*/
}
function updateViewPermissions(kind,obj){
  //0-public,1 -comm
  val=obj[obj.selectedIndex].value;
  typ=new Array (0,1,2,3,4)
  for (i=0;typeof(typ[i])=='number'  ;i++){
  //alert('per_'+kind+'_12_'+typ[i])
    ad=document.getElementById('per_'+kind+'_12_'+typ[i]);
    if (ad){
      if (val>=typ[i])
        ad.checked=true;
      else
        ad.checked=false;
    }
  }
}
function updatePermissions(kind,obj,arr_dump){
	val=obj[obj.selectedIndex].value;
	arr=arr_dump[val];
	//alert(kind);
  var types=new Array (0,1,2,3,4,100,105,110,115,120)
  //uncheck form
  if (arr){
    //loop on retrieved array
    for (i=0;arr[i];i++){

      for(j=0;arr[i][j];j=j+2){
	  	//alert('per_'+kind+'_'+arr[i][j]);
        //loop on perm types for each perm sent
        for (k=0;typeof(types[k])=='number';k++){
          ad=document.getElementById('per_'+kind+'_'+arr[i][j]+'_'+types[k]);
          //alert('per_'+kind+'_'+arr[i][j]+'_'+types[k]);
          if (ad){
            if (types[k]<10){
              //no one case
              if (arr[i][(j+1)][0]==0){
                if (arr[i][(j+1)][0]==types[k])
                 ad.checked=true;
                else
                 ad.checked=false;
              }else if (arr[i][(j+1)][0]>=types[k] && types[k]>0){
                ad.checked=true;
              }else
                ad.checked=false;
            }else if (types[k]>=100){
              if (arr[i][(j+1)][1]==100){
                if (arr[i][(j+1)][1]==types[k])
                 ad.checked=true;
                else
                 ad.checked=false;
              }else if (arr[i][(j+1)][1]>=types[k] && types[k]>100){
                ad.checked=true;
              }else
                ad.checked=false;

            }
          }
        }
      }
    }
  }else
  	show_hide(document.getElementById('table_'+kind));
}
function permChckbx(obj){
  //simulate radio buttons
  var arr=obj.id.split("_");
  var perm_type=arr[3];
  var ad;
  var perm_arr=arr[0]+'_'+arr[1]+'_'+arr[2]
  var types=new Array (0,1,2,3,4,100,105,110,115,120)
  var arr_type=parseInt(perm_type/100);
  for (i=0;typeof(types[i])=='number';i++){
    if (parseInt(types[i]/100)==arr_type){
      ad=document.getElementById(perm_arr+'_'+types[i])
      if (ad){
        //if some perm
        if (types[i]%100){
          if (types[i]<=perm_type)
            ad.checked=true;
          else
            ad.checked=false;
        }
        //no one
        else{
          if (types[i]==perm_type)
            ad.checked=true;
          else
            ad.checked=false;
        }
      }
    }
  }
  //move checkbox
  sel=document.getElementById('perm_select_'+arr[1])
  sel.selectedIndex=(sel.options.length-1);
}
function addBookmark(title,url) {
  if (window.sidebar)
  {
    window.sidebar.addPanel(title, url,"");
  }
  else if( document.all )
  {
    window.external.AddFavorite( url, title);
  }
  else
  {
    return true;
  }
}
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return utf8_decode(unescape(dc.substring(begin + prefix.length, end)));
}
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + utf8_decode(escape(value)) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function adult_confirm(){
	setCookie("adult", 1)
	window.location.reload( false );
}
function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');

	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}
function dex_player_fix_image(img){
	var temp = new Image();
	temp.src=img.src;

	if (img.width>temp.width){
		img.width=temp.width;
		img.height=temp.height;
	}
	img.style.visibility="visible"
}

function form_api(elm,nodeid,typeid,boxid){
	var xmlhttp=init_ajax();
	if (xmlhttp) {
		if (!boxid)
			boxid=0;
		if (!typeid)
			typeid=0;
		if (!nodeid)
			nodeid=0;
		var url='/frames/form_api.php';
		var str='nodeid='+nodeid+'&boxid='+boxid+'&typeid='+typeid;

		xmlhttp.open("POST", url,true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send(str);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				elm.innerHTML=xmlhttp.responseText
			}
		}
	}
}

function questionary_radio(option, fieldset_id) {
	fieldset = document.getElementById(fieldset_id);
	inputs = fieldset.getElementsByTagName("input");
	for (var i=0; i<inputs.length; i++) {
		if (inputs[i].getAttribute("type") == "radio") {
			inputs[i].checked = "";
		}
	}
	option.checked = "checked";
}

function toggle_feed(span_id) {
	if (document.getElementById(span_id).style.display == "none") {
		document.getElementById(span_id).style.display = "block";
	} else {
		document.getElementById(span_id).style.display = "none";
	}
}
/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/

function utf8_encode(string) {
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";

	for (var n = 0; n < string.length; n++) {

		var c = string.charCodeAt(n);

		if (c < 128) {
			utftext += String.fromCharCode(c);
		}
		else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}
		else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}

	}
	return utftext;
}


function utf8_decode(utftext) {
	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;

	while ( i < utftext.length ) {

		c = utftext.charCodeAt(i);

		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224)) {
 			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}
	}
	return string;
}
