<!--
// SL Regapi ajax script, written by Max Burns
var waitOutput;
var inputName;
var checkingMembers = new Array();
var switchWait = 0;
var switchWait1 = 0;
var xmlHttp = new Array();
var resultsShown = 0;

var startC;

// array of them
for (startC=0;startC<=9;startC++)
{
xmlHttp[startC] = createXmlHttpRequestObject();
xmlHttp[startC].fired = 0;
xmlHttp[startC].checkedName = new Array();
}


function CheckLastNames()
{
//alert('checklastnames');
inputName = '';
inputName=document.getElementsByName("username")[0].value;

waitOutput=document.getElementById('lastNameCheck').firstChild;

waitOutput.nodeValue = '';

RemoveWaitOutputChilds();
RemoveLastNamesOutputChilds();
HideSubmitButton();

if (inputName == '')
{
waitOutput.nodeValue = 'Ошибка: вы не ввели имя аватара.';
}
else
{


checkingMembers = [];
for (var uncheckedLastNameId in lastNames )
checkingMembers[checkingMembers.length] = uncheckedLastNameId; 
resultsShown = 0;
// randomize last names
checkingMembers.sort( randOrd );

var startC2;

for (startC2=0;startC2<=9;startC2++)
{
xmlHttp[startC2].fired = 0;
xmlHttp[startC2].checkedName = [];
PushNextName(startC2);
}

}// end if inputName is empty

} // end of CheckLastNames


function PushNextName(xmlHttpId)
{

var checkNameScript = '';

var currentMember = checkingMembers[0];

// remove one
checkingMembers.splice(0,1);

waitOutput.nodeValue = 'Ждите, проверяю имена пользователей...';

checkNameScript="/wp-content/plugins/chknm.php?username=" + inputName + "&last_name_id=" + currentMember;
// only continue if xmlHttp isn't void


if (xmlHttp[xmlHttpId])
{

// try to connect to the server
try
{
// initiate reading the async.txt file from the server
xmlHttp[xmlHttpId].open("GET", checkNameScript, true);
xmlHttp[xmlHttpId].onreadystatechange = handleRequestStateChange;
xmlHttp[xmlHttpId].send(null);
}

// display the error in case of failure
catch (e)
{
alert("Ошибка: не могу соединиться с сервером:\n" + e.toString());
}

//waitOutput.nodeValue += 'Отослано.' + checkNameScript + '|';
} // end of if (xmlHttp)



} // end PushNextName


function EmptyWaitBlock()
{
waitOutput=document.getElementById('lastNameCheck').firstChild;
waitOutputRoot=document.getElementById('lastNameCheck');


RemoveWaitOutputChilds();


waitOutput.nodeValue = 'Введите имя аватара и нажмите на кнопку.';
// commented because not needed
var htmlToAdd = '<br/><input type="button" value="Искать фамилии" onClick="CheckLastNames()"><br/>';
var newDiv = document.createElement('DIV');
newDiv.innerHTML = htmlToAdd;
waitOutputRoot.appendChild(newDiv);



} // end of EmptyWaitBlock

function RemoveWaitOutputChilds()
{
waitOutputRoot=document.getElementById('lastNameCheck');
// remove unneeded excess blocks from ouput div
if ( waitOutputRoot.hasChildNodes() )
{
    while ( waitOutputRoot.childNodes.length > 1 )
    {
        waitOutputRoot.removeChild( waitOutputRoot.lastChild );       
    } 
}
}

function RemoveLastNamesOutputChilds()
{
var checkedOutput=document.getElementById('checkedResultsShow');
// remove unneeded excess blocks from ouput div
if ( checkedOutput.hasChildNodes() )
{
    while ( checkedOutput.childNodes.length > 0 )
    {
        checkedOutput.removeChild( checkedOutput.lastChild );       
    } 
}
}


// creates an XMLHttpRequest instance
function createXmlHttpRequestObject()
{
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// this should work for all browsers except IE6 and older
try
{
// try to create XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
// assume IE6 or older
var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
// try every prog id until one works
for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
{
try
{
// try to create XMLHttpRequest object
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
}
catch (e) {}
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
} // end of createXmlHttpRequestObject

// function that handles the HTTP response
function handleRequestStateChange()
{

var startC3;

for (startC3=0;startC3<=9;startC3++)
{

// display the status of the request
	if (xmlHttp[startC3].readyState == 1)
	{
if (switchWait1 == 0)
{
	waitOutput.nodeValue = "Ждите. Идет поиск свободных фамилий для имени " + inputName +". \\  ";
switchWait1=1;
}
else if (switchWait1 == 1)
{
	waitOutput.nodeValue = "Ждите.. Идет поиск свободных фамилий для имени " + inputName +". | ";
switchWait1=2;
}
else if (switchWait1 == 2)
{
	waitOutput.nodeValue = "Ждите... Идет поиск свободных фамилий для имени " + inputName +". / ";
switchWait1=3;
}
else
{
	waitOutput.nodeValue = "Ждите.... Идет поиск свободных фамилий для имени " + inputName +". - ";
switchWait1=0;
}
	}
	else if (xmlHttp[startC3].readyState == 2)
	{
if (switchWait == 0)
{
	waitOutput.nodeValue = "Ждите. Идет поиск свободных фамилий для имени " + inputName +". \\  ";
switchWait=1;
}
else if (switchWait == 1)
{
	waitOutput.nodeValue = "Ждите.. Идет поиск свободных фамилий для имени " + inputName +". | ";
switchWait=2;
}
else if (switchWait == 2)
{
	waitOutput.nodeValue = "Ждите... Идет поиск свободных фамилий для имени " + inputName +". / ";
switchWait=3;
}
else
{
	waitOutput.nodeValue = "Ждите.... Идет поиск свободных фамилий для имени " + inputName +". - ";
switchWait=0;
}
	}
	else if (xmlHttp[startC3].readyState == 3)
	{
	waitOutput.nodeValue = "Имя проверяется";
	}
	// when readyState is 4, we also read the server response
	else if (xmlHttp[startC3].readyState == 4)
	{
	// continue only if HTTP status is "OK"
		if (xmlHttp[startC3].status == 200)
		{
		
try
{

/*
// read the message from the server
var response = xmlHttp[startC3].responseText;
// display the message
waitOutput.nodeValue = "Ответ получен. Сервер сообщил:";
waitOutput.nodeValue += response;
// commented out
*/

waitOutput.nodeValue = "Имя проверено";
handleServerResponse(startC3);


// now launch next last name check

if (xmlHttp[startC3].fired == 0 && checkingMembers.length > 1) PushNextName(startC3);
else
{
// for Opera
waitOutput=document.getElementById('lastNameCheck').firstChild;
waitOutput.nodeValue = "Найдены незанятые фамилии. Выберите подходящую.";
}

} // end try
catch(e)
{
//display error message
alert("Ошибка чтения ответа: " + e.toString());
}
		}
		else
		{
		// display status message
		alert("Ошибка получения данных:\n" +
		xmlHttp[startC3].statusText);
		}

	} // end of else if (xmlHttp.readyState == 4)

} // end of for every xmlhttp[] check cycle

} // end of  handleRequestStateChange

// finds next ten members
function NextTen()
{
RemoveWaitOutputChilds();
resultsShown = 0;
var startC4;
for (startC4=0;startC4<=9;startC4++)
{
xmlHttp[startC4].checkedName = [];
xmlHttp[startC4].fired = 0;
PushNextName(startC4);
}
}

// handles the XML response received from the server
function handleServerResponse(xmlHttpId1)
{

// read the message from the server
var xmlResponse = xmlHttp[xmlHttpId1].responseXML;
// obtain the XML's document element
xmlRoot = xmlResponse.documentElement;
// obtain arrays with lastnameids and results
var lastNameId = xmlRoot.getElementsByTagName("lastnameid").item(0).firstChild.data;
var lastNameResult = xmlRoot.getElementsByTagName("lastnameresult").item(0).firstChild.data;

// display the HTML output
//waitOutput.nodeValue = "Server XML says: lastnameid<" + lastNameId + '> lastnameresult<' + lastNameResult +'>';

if (lastNameResult == 'FREE') 
{
xmlHttp[xmlHttpId1].checkedName[lastNameId] = lastNames[lastNameId];
xmlHttp[xmlHttpId1].fired = 1;
}

var checkedOutput=document.getElementById('checkedResultsShow');

var firedCount = 0;
var startC1;

for (startC1=0;startC1<=9;startC1++)
{
if (xmlHttp[startC1].fired == 1) firedCount++;
}

if (firedCount == 10 && resultsShown == 0)
{
resultsShown = 1;

var startC5;
for (startC5=0;startC5<=9;startC5++)
{
for ( var checkedLastNameId in xmlHttp[startC5].checkedName )
{
var nameButtonToAdd = '<br/><input type="radio" name="last_name_id" value="'+ checkedLastNameId +'" onClick="ShowSubmitButton()"> '+inputName + ' ' + lastNames[checkedLastNameId] +' ';
var nameButtonDiv = document.createElement('DIV');
nameButtonDiv.innerHTML = nameButtonToAdd;
checkedOutput.appendChild(nameButtonDiv);

} // end for current xmlHttp 

// nullify it
xmlHttp[startC5].checkedName = [];

} // end for every xmlHttp (startC5)

// show next ten button
RemoveWaitOutputChilds();
waitOutput=document.getElementById('lastNameCheck').firstChild;
waitOutput.nodeValue = "Найдены незанятые фамилии. Выберите подходящую.";

if (checkingMembers.length > 0)
{
var waitOutputRoot = document.getElementById('lastNameCheck');
var buttonToAdd = '<br/><input type="button" value="Найти еще 10 фамилий" onClick="NextTen()"><br/>';
var buttonDiv = document.createElement('DIV');
buttonDiv.innerHTML = buttonToAdd;
waitOutputRoot.appendChild(buttonDiv);
} // end if checkingMembers.length > 0

} // end firedcount ==9 and resultsshown 0

} // end of handleServerResponse


function ShowSubmitButton()
{
HideSubmitButton();
var submitButtonOutput=document.getElementById('submitButtonBlock');
var submitButtonToAdd = '<input type="submit" value="Создать аватара" />';
var submitButtonDiv = document.createElement('DIV');
submitButtonDiv.innerHTML = submitButtonToAdd;
submitButtonOutput.appendChild(submitButtonDiv);
}

function HideSubmitButton()
{
var submitButtonOutput=document.getElementById('submitButtonBlock');

if ( submitButtonOutput.hasChildNodes() )
{
    while ( submitButtonOutput.childNodes.length > 0 )
    {
        submitButtonOutput.removeChild( submitButtonOutput.lastChild );       
    } 
}

}


function stopRKey(evt) { 
  var evt = (evt) ? evt : ((event) ? event : null); 
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
  if ((evt.keyCode == 13) && ( (node.type=="text") || (node.type=="password") ))  {return false;} 
} 

document.onkeypress = stopRKey;

function randOrd(){
return (Math.round(Math.random())-0.5); }

//-->