// ===================================================================
// Author: Matt Kruse <matt@ajaxtoolbox.com>
// WWW: http://www.AjaxToolbox.com/
// ===================================================================

function AjaxRequest(){
var req =new Object();
req.timeout =null;
req.generateUniqueUrl =true;
req.url =window.location.href;
req.method ="GET";
req.async =true;
req.username =null;
req.password =null;
req.parameters =new Object();
req.requestIndex =AjaxRequest.numAjaxRequests++;
req.responseReceived =false;
req.groupName =null;
req.queryString ="";
req.responseText =null;
req.responseXML =null;
req.status =null;
req.statusText =null;
req.aborted =false;
req.xmlHttpRequest =null;
req.onTimeout=null;
req.onLoading=null;
req.onLoaded=null;
req.onInteractive=null;
req.onComplete=null;
req.onSuccess=null;
req.onError=null;
req.onGroupBegin=null;
req.onGroupEnd=null;
req.xmlHttpRequest =AjaxRequest.getXmlHttpRequest();
if(req.xmlHttpRequest==null){return null;}req.xmlHttpRequest.onreadystatechange =
function(){if(req==null || req.xmlHttpRequest==null){return;}if(req.xmlHttpRequest.readyState==1){req.onLoadingInternal(req);}if(req.xmlHttpRequest.readyState==2){req.onLoadedInternal(req);}if(req.xmlHttpRequest.readyState==3){req.onInteractiveInternal(req);}if(req.xmlHttpRequest.readyState==4){req.onCompleteInternal(req);}};
req.onLoadingInternalHandled=false;
req.onLoadedInternalHandled=false;
req.onInteractiveInternalHandled=false;
req.onCompleteInternalHandled=false;
req.onLoadingInternal=
function(){if(req.onLoadingInternalHandled){return;}AjaxRequest.numActiveAjaxRequests++;
if(AjaxRequest.numActiveAjaxRequests==1 && typeof(window['AjaxRequestBegin'])=="function"){AjaxRequestBegin();}if(req.groupName!=null){if(typeof(AjaxRequest.numActiveAjaxGroupRequests[req.groupName])=="undefined"){AjaxRequest.numActiveAjaxGroupRequests[req.groupName] =0;}AjaxRequest.numActiveAjaxGroupRequests[req.groupName]++;
if(AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==1 && typeof(req.onGroupBegin)=="function"){req.onGroupBegin(req.groupName);}}if(typeof(req.onLoading)=="function"){req.onLoading(req);}req.onLoadingInternalHandled=true;};
req.onLoadedInternal=
function(){if(req.onLoadedInternalHandled){return;}if(typeof(req.onLoaded)=="function"){req.onLoaded(req);}req.onLoadedInternalHandled=true;};
req.onInteractiveInternal=
function(){if(req.onInteractiveInternalHandled){return;}if(typeof(req.onInteractive)=="function"){req.onInteractive(req);}req.onInteractiveInternalHandled=true;};
req.onCompleteInternal=
function(){if(req.onCompleteInternalHandled || req.aborted){return;}req.onCompleteInternalHandled=true;
AjaxRequest.numActiveAjaxRequests--;
if(AjaxRequest.numActiveAjaxRequests==0 && typeof(window['AjaxRequestEnd'])=="function"){AjaxRequestEnd(req.groupName);}if(req.groupName!=null){AjaxRequest.numActiveAjaxGroupRequests[req.groupName]--;
if(AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==0 && typeof(req.onGroupEnd)=="function"){req.onGroupEnd(req.groupName);}}req.responseReceived =true;
try {req.status =req.xmlHttpRequest.status } catch(e) {
if(typeof(req.onError)=="function"){req.onError(req);}
delete req.xmlHttpRequest['onreadystatechange'];
req.xmlHttpRequest =null;
return null
}
req.statusText =req.xmlHttpRequest.statusText;
req.responseText =req.xmlHttpRequest.responseText;
req.responseXML =req.xmlHttpRequest.responseXML;
if(typeof(req.onComplete)=="function"){req.onComplete(req);}if(req.xmlHttpRequest.status==200 && typeof(req.onSuccess)=="function"){req.onSuccess(req);}else if(typeof(req.onError)=="function"){req.onError(req);}delete req.xmlHttpRequest['onreadystatechange'];
req.xmlHttpRequest =null;};
req.onTimeoutInternal=
function(){if(req!=null && req.xmlHttpRequest!=null && !req.onCompleteInternalHandled){req.aborted =true;
req.xmlHttpRequest.abort();
AjaxRequest.numActiveAjaxRequests--;
if(AjaxRequest.numActiveAjaxRequests==0 && typeof(window['AjaxRequestEnd'])=="function"){AjaxRequestEnd(req.groupName);}if(req.groupName!=null){AjaxRequest.numActiveAjaxGroupRequests[req.groupName]--;
if(AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==0 && typeof(req.onGroupEnd)=="function"){req.onGroupEnd(req.groupName);}}if(typeof(req.onTimeout)=="function"){req.onTimeout(req);}delete req.xmlHttpRequest['onreadystatechange'];
req.xmlHttpRequest =null;}};
req.process =
function(){if(req.xmlHttpRequest!=null){if(req.generateUniqueUrl && req.method=="GET"){req.parameters["AjaxRequestUniqueId"] =new Date().getTime() + "" + req.requestIndex;}var content =null;
for(var i in req.parameters){if(req.queryString.length>0){req.queryString +="&";}req.queryString +=encodeURIComponent(i) + "=" + encodeURIComponent(req.parameters[i]);}if(req.method=="GET"){if(req.queryString.length>0){req.url +=((req.url.indexOf("?")>-1)?"&":"?") + req.queryString;}}req.xmlHttpRequest.open(req.method,req.url,req.async,req.username,req.password);
if(req.method=="POST"){if(typeof(req.xmlHttpRequest.setRequestHeader)!="undefined"){req.xmlHttpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');}content =req.queryString;}if(req.timeout>0){setTimeout(req.onTimeoutInternal,req.timeout);}req.xmlHttpRequest.send(content);}};
req.handleArguments =
function(args){for(var i in args){if(typeof(req[i])=="undefined"){req.parameters[i] =args[i];}else{req[i] =args[i];}}};
req.getAllResponseHeaders =
function(){if(req.xmlHttpRequest!=null){if(req.responseReceived){return req.xmlHttpRequest.getAllResponseHeaders();}alert("Cannot getAllResponseHeaders because a response has not yet been received");}};
req.getResponseHeader =
function(headerName){if(req.xmlHttpRequest!=null){if(req.responseReceived){return req.xmlHttpRequest.getResponseHeader(headerName);}alert("Cannot getResponseHeader because a response has not yet been received");}};
return req;}AjaxRequest.getXmlHttpRequest =function(){if(window.XMLHttpRequest){return new XMLHttpRequest();}else if(window.ActiveXObject){/*@cc_on @*/
/*@if(@_jscript_version >=5)
try{return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{return new ActiveXObject("Microsoft.XMLHTTP");}catch(E){return null;}}@end @*/}else{return null;}};
AjaxRequest.isActive =function(){return(AjaxRequest.numActiveAjaxRequests>0);};
AjaxRequest.get =function(args){AjaxRequest.doRequest("GET",args);};
AjaxRequest.post =function(args){AjaxRequest.doRequest("POST",args);};
AjaxRequest.doRequest =function(method,args){if(typeof(args)!="undefined" && args!=null){var myRequest =new AjaxRequest();
myRequest.method =method;
myRequest.handleArguments(args);
myRequest.process();}};
AjaxRequest.submit =function(theform, args){var myRequest =new AjaxRequest();
if(myRequest==null){return false;}var serializedForm =AjaxRequest.serializeForm(theform);
myRequest.method =theform.method.toUpperCase();
myRequest.url =theform.action;
myRequest.handleArguments(args);
myRequest.queryString =serializedForm;
myRequest.process();
return true;};
AjaxRequest.serializeForm =function(theform){var els =theform.elements;
var len =els.length;
var queryString ="";
this.addField =
function(name,value){if(queryString.length>0){queryString +="&";}queryString +=encodeURIComponent(name) + "=" + encodeURIComponent(value);};
for(var i=0;i<len;i++){var el =els[i];
if(!el.disabled){switch(el.type){case 'text': case 'password': case 'hidden': case 'textarea':
this.addField(el.name,el.value);
break;
case 'select-one':
if(el.selectedIndex>=0){this.addField(el.name,el.options[el.selectedIndex].value);}break;
case 'select-multiple':
for(var j=0;j<el.options.length;j++){if(el.options[j].selected){this.addField(el.name,el.options[j].value);}}break;
case 'checkbox': case 'radio':
if(el.checked){this.addField(el.name,el.value);}break;}}}return queryString;};
AjaxRequest.numActiveAjaxRequests =0;
AjaxRequest.numActiveAjaxGroupRequests =new Object();
AjaxRequest.numAjaxRequests =0;

if (!BASE_URL) {var BASE_URL='http://www.chesshere.com/play-chess/';}
if(!window.$) window.$ = function(e) { return document.getElementById(e); };

function toggleDiv(id) {
var d=$(id).style;
if (d.display=='none') {
d.display='block';
} else {d.display='none';}
}

if (!Array.prototype.push) {
    Array.prototype.push = function(elem) {
        this[this.length] = elem;
    }
}

function keepSessionAlive() {
	var img = new Image();
	img.src = BASE_URL+"sesska.php?rnd=" + new Date().getTime();
}

function load_incomes()
{
AjaxRequest.get(
  {
     'url':BASE_URL+'mini/incomes_mini.php'
    ,'timeout':8000
    ,'onTimeout':function(req){ load_incomes(); }
    ,'onError':function(req){ setTimeout( 'load_incomes()' ,3000 ); }
    ,'onSuccess':function(req){ 
    var re=req.responseText;
    var data = parseJSON(re);
    if (data) {
    updateComeTable(data);
    }
    setTimeout('load_incomes()',6500);    
    }
  }
);

}

function openPlayerDetails(pid, e) {

ie = document.all? true: false;

e = window.event || e;

var y = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
var x = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;


if (!$('profile_rtc'))
{
			var el = document.createElement('div');			
			el.style.top = '240px';
			el.style.left = '400px';
			el.style.position = 'absolute';
			el.setAttribute('id','profile_rtc');
			document.body.appendChild(el);
}

try
{
var h = $('profile_rtc').offsetHeight;
var w = $('profile_rtc').offsetWidth;

$('profile_rtc').style.left=(x-w)+'px';
$('profile_rtc').style.top=(y-h-4)+'px';

} catch(ex){}

AjaxRequest.get(
  {
     'url':'/profile_rtc.php'
    ,'parameters': { 'id': pid  }
    ,'timeout':4000
    ,'onSuccess':function(req){ 
    var re=req.responseText;
    if (re) {    
    $('profile_rtc').innerHTML=re;

    $('profile_rtc').style.display='block';
    
    
    }
    }
  }
);
return false;
}



function ton() {
$('actajaxon').innerHTML='<img src="'+BASE_URL+'demo-images/loading.gif" alt="" />';
}
function workingp() {
$('workingp').innerHTML='<img src="'+BASE_URL+'demo-images/loading.gif" alt="" />';
}
function workingm() {
$('workingm').innerHTML='<img src="'+BASE_URL+'demo-images/loading.gif" alt="" />';
}

function join(inv)
{
inv=inv.toString();
if (!userID){openWin(BASE_URL+"mini/login_mini.php","reg");return;}

openWin(BASE_URL+"mini/join_mini.php?inv="+inv,"chess"+inv);
}

function joinTo(inv) {
inv=inv.toString();
openWin(BASE_URL+"mini/chess_mini.php?inv="+inv,"chess"+inv);
}

function viewGame(inv)
{
inv=inv.toString();
openWin("http://www.chesshere.com/live-chess/game-viewer.php?inv="+inv,"chess"+inv);
}

function remove(inv)
{
inv=inv.toString();

AjaxRequest.post(
  {
     'url':BASE_URL+'remove.php'
    ,'timeout':5000
    ,'parameters': { 'inv': inv }    
  }
);
}

function openWin(strUrl, strWindowName)
{
/* /newchess = window.open(strUrl, strWindowName,"height=580,width=880,left=100;top=100;status=no,toolbar=no,scrollbars=yes,menubar=no,location=no,resizable=yes");
*/
location.href=strUrl;
}

function updateComeTable(data) {

if (!data) {return;}

var htmlPrivate='';
var htmlAll='';
var htmlOut='';

var pl='';
var st='';
var rate;
var rateMatch;
var my_rating=userRate*1;

var pout=0;
var k=22;
var my_expected_rating;
var draw_rating;
var win_rating;
var loss_rating;
var rating_stats='';


var rating;

for (var j = 0; j < data.out.length-1; j++) {

switch(parseInt(data.out[j][10]))
{
case 0:
mem='';
break;
case 4:
mem = 'ms.png';
break;
case 5:
mem = 'mg.png';
break;
case 6:
mem = 'fm.png';
break;
case 7:
mem = 'wim.png';
break;
case 8:
mem = 'im.png';
break;
case 9:
mem = 'wgm.png';
break;
case 10:
mem = 'gm.png';
break;
case 11:
mem = 'mod2.png';
break;
case 12:
mem = 'f.png';
break;
case 13:
mem = 'c.png';
break;
default:
mem='';
}
if (mem != '')
{
mem = ' <img src="http://www.chesshere.com/play-chess/icons/'+ mem +'" alt="">';
}

rating=parseInt(data.out[j][9]);

if (rating && rating>0) {
my_expected_rating = 1/(1+Math.pow(10,(rating-my_rating)/400));
draw_rating = my_rating + k * (0.5-my_expected_rating);
win_rating = my_rating + k * (1-my_expected_rating);
loss_rating = my_rating + k * (0-my_expected_rating);

win_rating = Math.round(win_rating-my_rating);
loss_rating = Math.round(loss_rating-my_rating);
draw_rating = Math.round(draw_rating-my_rating);

rating_stats='Win:'+win_rating+', Draw:'+draw_rating+', Loss:'+loss_rating;
} else {
rating_stats='';
}


if (userID && data.out[j][2]==userID) { // private invitations
   htmlPrivate += '<tr>';
   htmlPrivate += '<td class="pls"><a title="'+rating_stats+'" href="../player.php?id='+data.out[j][0]+'" target="players"  onclick="return openPlayerDetails('+data.online[j][0]+',event)">'+data.out[j][1]+' ('+data.out[j][9]+')</a>'+mem+'</td>';
   //htmlPrivate += '<td>' + data.out[j][4] + '</td>';   
   htmlPrivate += '<td>' + data.out[j][5] + '</td>';
   htmlPrivate += '<td>' + data.out[j][6] + '</td>';

   st= '<input class="join" type="button" value="Join" onmousedown="this.disabled=true;workingm();join('+data.out[j][7]+');" />';
   htmlPrivate += '<td>' + st + '</td>';   
   st='<input class="remove" type="button" value="Reject" onmousedown="this.disabled=true;workingm();remove('+data.out[j][7]+');" />';
   htmlPrivate += '<td>' + st + '</td></tr>';

} else if (userID && data.out[j][0]==userID) { // my invitations

   htmlOut += '<tr>';
   htmlOut += '<td style="color:#6DB923;font-weight:bold;text-align:center"> Me </td>';
   //htmlOut += '<td>' + data.out[j][4] + '</td>';   
   htmlOut += '<td>' + data.out[j][5] + '</td>';
   htmlOut += '<td>' + data.out[j][6] + '</td>';
   
   st='<input class="remove" type="button" value="Cancel" onmousedown="this.disabled=true;workingm();remove('+data.out[j][7]+');" />';

   htmlOut += '<td> - </td><td>' + st + '</td></tr>';

} else if (data.out[j][0] && data.out[j][2]==0) { // public invitations

rateMatch=0;

rate=parseInt(data.out[j][8]);

neededCompleted=parseInt(data.out[j][11]);

switch (rate) {

case 0:
rateMatch=1;
break;
case 1:
if (my_rating < 1400) { rateMatch=1; }
break;
case 2:
if (my_rating > 1399 && my_rating < 1600) { rateMatch=1; }
break;
case 3:
if (my_rating > 1599 && my_rating < 1800) { rateMatch=1; }
break;
case 4:
if (my_rating > 1799 && my_rating < 2000) { rateMatch=1; }
break;
case 5:
if (my_rating > 1999 && my_rating < 2200) { rateMatch=1; }
break;
case 6:
if (my_rating > 2199) { rateMatch=1; }
break;
default:
rateMatch=1;
}

if (rateMatch == 1 && neededCompleted <= completedGames) {

   htmlAll += '<tr>';
   htmlAll += '<td class="pls"><a title="'+rating_stats+'" href="../player.php?id='+data.out[j][0]+'" target="players"  onclick="return openPlayerDetails('+data.out[j][0]+',event)">'+data.out[j][1]+' ('+data.out[j][9]+')</a>'+mem+'</td>';
   //htmlAll += '<td>' + data.out[j][4] + '</td>';
   htmlAll += '<td>' + data.out[j][5] + '</td>';
   htmlAll += '<td>' + data.out[j][6] + '</td>';
   if (data.out[j][0]==userID) {
st= '<td>-</td><td><input class="remove" type="button" value="Cancel" onmousedown="this.disabled=true;workingp();remove('+data.out[j][7]+');" /></td>';   

   } else {
st= '<td><input class="join" type="button" value="Join" onmousedown="this.disabled=true;workingp();join('+data.out[j][7]+');" /></td><td>-</td>';  
   }
   htmlAll += st;   
   htmlAll += '</tr>';
}

}

}

var output='<table border="0" cellpadding="0" cellspacing="0" id="cball" class="onlinetbl"><thead><tr><th class="th_js">Player</th><th class="th_js">Time</th><th class="th_js">Color</th><th class="th_js"><b id="workingp">+</b></th><th class="th_js"><b id="workingm">-</b></th></tr></thead><tbody>';

output += htmlPrivate + htmlAll + htmlOut;

if (htmlPrivate + htmlAll + htmlOut == '') {
output += "<tr><td colspan='5'><div style='padding:10px 0; font-weight:bold;'>please wait for the next chess invitation...</div></td></tr>"
}

output += "</tbody></table>";

$('challengesbox').innerHTML=output;

}

function parseJSON(text) {
if (!text) return false;
try {
var re=eval('('+text+')');
return re;
} catch(e) {
return false;
}
}

window.onload = function() {
load_incomes();
window.setInterval('keepSessionAlive();', 1000 * 60 * 10);
}



