var ie=document.all?1:0;
var ns=document.getElementById&&!document.all?1:0;
var hideSub;
var fdTimer="No";
var siteVars ={};


function _o(name){
	return document.getElementById(name);
}

function newScriptLoad(url, id){

	newScript=document.createElement('script');
	target=url; //'/js/forum.js';
	newScript.src=target;
	newScript.id = id? id: 'f_script';
	document.getElementsByTagName('body')[0].appendChild(newScript);
}

function CheckLen3(o) {
	t=document.getElementById("count");
	i=255-o.value.length;
	t.value="Осталось: "+i;
	if (i<0) t.style.color="red";
	else t.style.color="#404040";
}


function show(id){
//	alert(id);
	for (var i=0; i<20; i++) {

		if(document.getElementById('Sub'+i)){
       obj = document.getElementById('Sub'+i);
			if(id != 'Sub'+i){

				obj.className = 'hideSub';
//				alert(obj.id+' - '+obj.className);

			} else{
				obj.className = 'showSub';	
				


//				alert(obj.id+' - '+obj.className);
						
			}
		}	
	}
}
function showEmptySub(){
	
	if(hideSub) clearTimeout(hideSub); 
	hideSub=setTimeout( "show('Sub0')", 2000);
}

function setLongTimer(){
	
	if(hideSub) clearTimeout(hideSub); 
	hideSub=setTimeout( "show('Sub0')", 20000); // минута
}



function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);

if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function FixCookieDate (date) {
  var base = new Date(0);
  var skew = base.getTime(); // dawn of (Unix) time - should be 0
  if (skew > 0)  // Except on the Mac - ahead of its time
    date.setTime (date.getTime() - skew);
}

function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
return null;
}

function SetCookie(cookieName,cookieValue,nDays, path) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString()+";path="+((path==null || path=="")?"/":path)+";domain=."+document.domain.replace(/www\./,"");
}

function DeleteCookie (name,path,domain) {
  var dd = document.domain

  if (GetCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=."+document.domain : "") +
      "; expires=Thu, 01-Jan-1970 00:00:01 GMT";
  }
}


function massage(adr){
	
	var str=adr
	var reg=/~/
	var reg_1=/[%]/g;
	var result=str.replace(reg, "@")
	var result_1=result.replace(reg_1, ".")
	
	document.location = 'mailto:'+result_1.substring(3);
}

function topMenuAlign(n)
{
	var n;
    var w = 0;
    var w_b = 0;
    var p = 0;
    

    w = document.documentElement.clientWidth;
    w_b = Math.round(w/n);
    
    for (var i = 1; i < n+1; i++ ){
    	if(i <= n/2 ) p = w_b*(i-1)+20
    	else p = w - w_b*i+20
    	
    	if(i == 3) p=p+20;
    	if(i == 5) p=p-20;
		document.getElementById('box_'+i).style.width = parseInt(p)+'px';
    }
}
   var http_request = false;
   
   function makePOSTRequest(parameters, url, switchVal) {
	 switch (switchVal){
		case 'alertContents':{
		    document.getElementById('fb_button').disabled=true;
		    document.getElementById('changeable').innerHTML="<a>Sending...</a>";
		}break;
	 }	
	 http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
	  siteVars['s']=switchVal;
      http_request.onreadystatechange = function(){
		//alert(switchVal);
		
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {		
				switch (siteVars.s){
					case 'alertContents':
						alertContents();
					break;
					case 'postSent':
						postSent();
					break;
					case 'new_thread_sent':
						newThreadSent();
					break;
					case 'loadScript':
						// eval(http_request.responseText); 
						ls=''+http_request.responseText+'';
						ls = ls.split('\n');
						sqtt = ls.length;
						for(i=0;i<sqtt; i++){
							//_o('test').innerHTML = i+"__"+ls[i];
							eval(ls[i]);
						}
						//s=document.createElement('script');s.type='text/javascript';s.innerHTML = ls; alert(22);document.getElementsByTagName('body')[0].appendChild(s);
					break;
				}	
			} else {
            alert('There was a problem with the request.');
			}
		}	  
	  }
	  if(switchVal!='loadScript'){

	      http_request.open('POST', url, true);
	      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
	      http_request.setRequestHeader("Content-length", parameters.length);
	      http_request.setRequestHeader("Connection", "close");
	      http_request.send(parameters); 
	  }else{
            http_request.open("GET", url, true);
            if (window.XMLHttpRequest)http_request.send(null); else http_request.send();
	  }
   }

   function alertContents() {

            document.getElementById('changeable').innerHTML = http_request.responseText;
            //result = http_request.responseText;
            //document.getElementById('myspan').innerHTML = result;

   }
 function send2Admin(){ 
	if(true){
		daLetter = 'feedback_text='+encodeURI(document.getElementById('feedbackArea').value)+'&loc_href='+location.href;
		makePOSTRequest(daLetter, '/sendMail2Admin.php', 'alertContents');
	}
 }
 function hideSend2Admin(){
   document.getElementById('feedbackArea').style.display='none';
 }
 function send2AdminFocus(){
   x=document.getElementById('feedbackArea');
   flag = x.getAttribute('flag');
   if (flag=="no"){
      x.value="";
      x.setAttribute('flag', 'changed');
      x.style.color="black";
   }
 }
 function closeWindow(obj){
   obj.style.display="none";
 }
 function showobj(obj,posX,posY){
   obj.style.display="block";
   obj.style.left = posX-330+"px";
   obj.style.top = posY+20+"px";
 }
 function findPosU(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
 }
function runScript(name){

  var l;
  var s;
  var d=document;
  var i;
  
  makePOSTRequest("", '/js/add_'+name+'.js?v=50', 'loadScript');
  var a=function(o){d.body.appendChild(o);}
  if(d.getElementById('window'+name)){
	  d.getElementById('window'+name).style.display="block";
	  waittime=15000;
	  return
  }

l=d.createElement('div');
l.innerHTML='Loading..';
	i=l.style;
	i.position='absolute';
	i.top='0';
	i.left='9px';
	i.backgroundColor='#f00';
	i.color='#fff';
	i.font='normal 14px sans-serif';
	i.padding='2px';
	i.zIndex='999';
l.id='l_blm';
a(l);//s=d.createElement('script');s.type='text/javascript';s.innerHTML=siteVars.loadedJS;a(s)
}

function addEventSimple(obj,evt,fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt,fn,false);
	else if (obj.attachEvent)
		obj.attachEvent('on'+evt,fn);
}
/**************************************************
 * dom-drag.js
 * 09.25.2001
 * www.youngpup.net
 * Script featured on Dynamic Drive (http://www.dynamicdrive.com) 12.08.2005
 **************************************************
 * 10.28.2001 - fixed minor bug where events
 * sometimes fired off the handle, not the root.
 **************************************************/

var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;
		
		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};
// hint

var HintEvntSrc;
var HintMouseX;
var HintMouseY;
var HintShowed = false;
var HintTimeout = 0;
var HintTimeoutID;
var HintSuppress = false;
var db;	// body
var de;	// documentElement
var hc;	// HintContainer
var h;	// Hint

function ShowHint(e)
{
	db=document.body;
	de=document.documentElement;
	hc=document.getElementById("HintContainer");
	if (!e) var e=window.event;
	if (e.target) HintEvntSrc=e.target;
	else HintEvntSrc=e.srcElement;
	if (!HintEvntSrc) ;
	else {
		if (HintEvntSrc.nodeType==3) // defeat Safari bug
			HintEvntSrc=HintEvntSrc.parentNode;
		if (e.pageX || e.pageY) {
			HintMouseX=e.pageX;
			HintMouseY=e.pageY;
		} else
		if (e.clientX || e.clientY) {
			HintMouseX=e.clientX+db.scrollLeft+de.scrollLeft;
			HintMouseY=e.clientY+db.scrollTop+de.scrollTop;
		}
		if (HintEvntSrc.getAttribute("dahint") && !HintSuppress)
			HintTimeoutID = window.setTimeout("DisplayHint()",HintTimeout,"JavaScript");
	}
}

function DisplayHint()
{
	if (HintEvntSrc.getAttribute("dahint") && !HintSuppress)
	{
		hc.innerHTML="<table id=Hint class=Hint><tr><td>" + HintEvntSrc.getAttribute("dahint").replace(/, /g, "<br />") + "</td></tr></table>";
		h=document.getElementById("Hint");
		HintShowed=true;
		h.style.left=(HintMouseX+10)+"px";
		h.style.top=(HintMouseY+10)+"px";
		if (h.offsetLeft+h.scrollWidth>db.clientWidth+db.scrollLeft+de.scrollLeft)
			h.style.left=HintMouseX-h.scrollWidth-10;
		if (h.offsetleft-db.scrollLeft<0)
			h.style.left=db.scrollLeft+de.scrollLeft;
		if (h.offsetTop+h.scrollHeight>db.clientHeight+db.scrollTop+de.scrollTop)
			h.style.top=HintMouseY-h.scrollHeight-10;
		if (h.offsetTop-db.scrollTop<0)
			h.style.top=db.scrollTop+de.scrollTop;
	}
	else HideHint();
}

function HideHint()
{
	if (HintShowed) {
		h.style.display='none';
		HintShowed=false;
		// HintEvntSrc=undefined;
	}
	else window.clearTimeout(HintTimeoutID);
}

function runHintOnObj(o)
{
	if (!o.hinted) {
		if(window.addEventListener) {
			o.addEventListener('mousemove',ShowHint,false);
			o.addEventListener('mouseout',HideHint,false);
		} else
		if (window.attachEvent) {
			o.attachEvent('onmousemove',ShowHint);
			o.attachEvent('onmouseout',HideHint);
		}
		o.hinted='yes';
	}
}
function check4Event(){
  newX=GetCookie('evnt');
  newX=(newX==null?"No":newX);
  	//_o("test").innerHTML=newX;
  if(fdTimer!=newX && fdTimer!="No" && fdTimer && newX!="No"){ // fdtimer - prev value of NewX
    a=newX.split('|');
    execServerEvent=setTimeout("try{"+a[0]+"('"+a[1]+"');} catch(e){b=e;}", 1);
	siteVars["fdIsActive"]=1;
  }
  fdTimer=newX;
  check4EventTimer = setTimeout("check4Event()", 200);
}

function uid2cook(){
	if(palayerId==null || palayerId=="") return;
	/* d=document.domain;
	d=d.replace(/www\./,""); */
	SetCookie("userid",palayerId, 365);
	if(palayerId==21) _o("test").innerHTML="<a onclick='fdajax.start()'>sss</a>";
}

function startFDEngine(){
	cookTMP = GetCookie('fderr');
	if (cookTMP == "fail") return; //|| cookTMP == "start_p" || cookTMP == "start_aj"
	var t=new Date;t=t.getTime();
	
	if (GetCookie('ilive')*1 == 0 || (GetCookie('ilive')*1+1500<t) || cookTMP == "start_p" ){
		addEventSimple(_o("fdframe"),"onerror",fdLoadError);
		addEventSimple(_o("fdframe"),"onload",startFDEngine);
		_o("fdframe").src = "http://"+document.domain+":8080/?ver=081123";
		SetCookie('fderr', 'start_p', (1/24));
	} 
	fdRepeat = setTimeout("startFDEngine();", 5000);
}
 
function fdLoadError(){
	SetCookie('fderr', 'fail', (1/24));
	siteVars["fdIsActive"]=false; 
}

function json_call(a){
	var z={};
	x= function(y){if(y in z){return z[y]}return z[y]=navigator.userAgent.toLowerCase().indexOf(y)!=-1
	}
	
	var c=document.getElementsByTagName("head")[0];
	var d=document.createElement("script");
	d.type="text/javascript";
	d.id = "f_script";
	d.charset="utf-8";
	d.onerror = function(){asd=111;};
	var g=a;
	if(x("msie")||x("safari")||x("konqueror")){}
	d.src=g;
	var f=function(){
			window.fdloaded = true;
			d.onload=null;
			var i=d.parentNode;
			i.removeChild(d);
			delete d
		};
	var h=function(i){
			var j=(i?i:window.event).target?(i?i:window.event).target:(i?i:window.event).srcElement;
			if(j.readyState=="loaded"||j.readyState=="complete"){j.onreadystatechange=null;f()}
			// test
		}
;if(navigator.product=="Gecko"){d.onload=f}else{d.onreadystatechange=h}c.appendChild(d)
}
function delFD(){
	_o('f_script').src=null; 
}
var fdajax = {
	server_url: function(){
		d = "http://"+"fd."+document.domain+":8080/";
		d=d.replace(/www\./,""); 
		return d;	
	},
	win_id: Math.floor(Math.random() * 2147483646 + 1),
	redirect: function(www_id) {
		// fdajax.cancel();
		alert("Do not open a second window.");
		// window.location = "/";
	},
	relogin: function(reason) {
         alert("Please log in once again, your session id is incorrect. (" + reason + ")");
	},   
	nocookies: function() {
         alert("No cookies");
	},
	notfound: function() {
      // alert("You are not logged to Fd module.");
	  
	},
	maxwin: function() {
         alert("Too many open windows.");
		 window["fdactive"]=false;
      
	},
	no_guests: function () {
      alert("Guest users not allowed.");
	},
	peer_call: function(peer_id, ev, ob_id, par1) {
	_o("test").innerHTML="peer_call:"+peer_id+"~"+ev+"~"+ob_id+"~"+par1;
	},
	cmd_received: function(cmd, val) {
	_o("test").innerHTML="cmd:"+cmd+"~"+val;
	window.fdactive = false;
	
	switch (cmd){
		case "move":{
			if(gameType==3 || gameType==1)
			eval('gettingOppmove("'+val+'");');
			_o("test").innerHTML='gettingOppmove("'+val+'");';
		} break;
		default:{
			SetCookie('evnt', 'undef'+'|'+val, 1);
		}
	}
	},
	grp_peer_call: function (peer_id, ev, par1, par2) {
	_o("test").innerHTML="grp_call:"+peer_id+"~"+ev+"~"+par1+"~"+par2;
	},
	ping: function() {
      // In case of chunked mode the ping function might be empty
	},
	delFScript: function() {
		d = _o("f_script");
		var i=d.parentNode;
		i.removeChild(d);
	},
	start: function(){
		if (window.fdactive) return; else window["fdactive"]=true;
		if (window.fdloaded) window.fdloaded = false; else	window["fdloaded"] = false;
		// _o("test").innerHTML=fdajax.server_url() + "live.fdajax?cmd=wait&force=1&user_id="+ GetCookie('userid')+"&win_id="+fdajax.win_id+"&types=chat";
		json_call(fdajax.server_url() + "live.fdajax?cmd=wait&force=1&user_id="+ GetCookie('userid')+"&win_id="+fdajax.win_id+"&types=chat"); //%7Cgchat
		// повесить евент на window - при выходе - cancel, вывешивать предупреждение, что окно неактивно.
	}
} 

function drawWindow(windowName, leftElemName){
	var chatWnd = document.createElement("div"); 
	chatWnd.id="window"+windowName;
	chatWnd.style.position = 'absolute';

	div = document.createElement('div');
	div.id=windowName+ "_head";
	div.className="wnd_head";
	div.innerHTML = '<a class="left-element" style="cursor:move;">'+leftElemName+'</a><a class="right-element" onclick="this.parentNode.parentNode.style.display=\'none\';waittime=100000">X</a>';
	chatWnd.appendChild(div);

	if(windowName=="analyze_board"){
		chat_div = document.createElement('div');  //  чат текст
		chat_div.id = windowName+'window';
		chat_div.innerHTML="<iframe scrolling='no' height='350' width='385' src='/pgnviewer/ltpgnboard.html?SetPgnMoveText="+pgnText+"&RotateBoard=true&AllowRecording=true&MoveForward="+hist_pos+"'></iframe>";
		chatWnd.appendChild(chat_div);
	}

	if(windowName=='chat'){
		controls = document.createElement('div');
		controls.innerHTML='<input id="chatmsg" type="text" onkeyup="keyup(event.keyCode);"> 	<input type="button" value="add" onclick="submit_msg();" style="cursor:pointer;border:1px solid gray;">'; 

		chatWnd.appendChild(controls);
	}
	//
	document.getElementsByTagName('body')[0].appendChild(chatWnd);
	/*
	if (document.all) {
	document.documentElement.childNodes[1].appendChild(chatWnd);
	} else {
	document.documentElement.appendChild(chatWnd);
	}
	*/
	Drag.init(_o(windowName + '_head'), _o("window"+windowName));

}

addEventSimple(window,"load",uid2cook);
addEventSimple(window,"load",check4Event);
// addEventSimple(window,"load",startFDEngine);
