var xmlhttp;

function getXmlHttpObj()
{
   if(typeof XMLHttpRequest != "undefined") 
   { 
          
    return new XMLHttpRequest();
   } else 
		if(window.ActiveXObject) 
		{ // для Internet Explorer (all versions)
          var aVersions = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0",
                   "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp",
                   "Microsoft.XMLHttp"
                   ];
          for (var i = 0; i < aVersions.length; i++) {
            try { //
              var oXmlHttp = new ActiveXObject(aVersions[i]);
              return oXmlHttp;
            } catch (oError) 
			{               
            }
          }
          throw new Error("Невозможно создать объект XMLHttp.");
        }
}

function sendRequest(params)
{ 
	var xmlhttp = getXmlHttpObj();
		
	xmlhttp.open('POST', 'engine.php?is_ajax=1', true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.onreadystatechange = function(){	  
	    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
		    var type = xmlhttp.responseText.split('|')[0]; 
			var status = xmlhttp.responseText.split('|')[1]; 
			var params = xmlhttp.responseText.split('|')[2];
			
			switch(type)
			{
				case 'SWORD':	go_to_secret(status); 
								break;
				case 'POOL':	set_votes(status, params);
								break;
				case 'MAIL':	show_send_mail_status(status);
								break;
			}
		}
	}

	xmlhttp.send(params);
}

function goToSecretPage()
{
	var sword = document.getElementById('sword'); 
	sendRequest('type=SWORD&sword=' + sword.value);
}

function sendPressForm()
{
   var form = document.forms['press_form'];
   var params = "type=MAIL&";
   var separator = "";

   for(var i = 0; i < form.length; i++)
   {
        var item = form.elements[i];
        if(item.name == "")
            continue;
        params += separator + item.name + "=" + encodeURIComponent(item.value);
        separator = "&";
   }
   
   sendRequest(params);
}

function sendPurchaseForm()
{
   var form = document.forms['purchase_form'];
   var params = "type=MAIL_PURCHASE&";
   var separator = "";

   for(var i = 0; i < form.length; i++)
   {
        var item = form.elements[i];
        if(item.name == "")
            continue;
        params += separator + item.name + "=" + encodeURIComponent(item.value);
        separator = "&";
   }
   
   sendRequest(params);
}

function sendVote(vote)
{
	sendRequest('type=POOL&vote=' + vote);
}

function go_to_secret(status)
{
	if(status == 'OK')
	{
		window.location.href = "password.php";
	}
	else
	{
		alert('Wrong secret word');
	}
}

function show_send_mail_status(status)
{
	if(status == 'OK')
	{
		alert('Thank you');
	}
	else
	{
		alert('Can\'t send mail. Please try later.');
	}
}

function set_votes(status, params)
{
	if(status == 'FAIL')
	{
		return false;
	}
	
	var votes = params.split(':');
	var total_votes = votes[votes.length - 1];
	
	var pool_div = document.getElementById('pool_div');
	clearNode(pool_div);
	
	var n = 1;
	for(var i = 0; i < votes.length - 2; i+=2, n++)
	{
		setVoteLine(votes[i], votes[i+1], total_votes, n);
		if(status == 'VOTED')
		{
			hideCheckbox(n);
		}
	}	
}

function clearNode(dest)
{
  while (dest.firstChild)
  {
	dest.removeChild(dest.firstChild);
  }
}

function hideCheckbox(i)
{
	var elem = document.getElementById('pool_checkbox' + i);
	if(elem != null)
	{
		//elem.style.visibility = 'hidden';
		elem.style.display = 'none';
	}
	else
		return;
}

function setVoteLine(name, value, total, num)
{
	var percent;
	var line_width;
	
	if(0 == parseInt(total) || 0 == parseInt(value))
	{
		percent = 0;
		line_width = 4;
	}
	else	
	{
		percent = (parseInt(value) * 100) / parseInt(total);
		percent = percent.toFixed(2);	
		line_width = Math.ceil(percent) * 2;
	}
		
	
	
	var pool_div = document.getElementById('pool_div');
	
	var pool_line = document.createElement('div');
	pool_line.style.marginTop = '10px';
	
	var pool_line_name = document.createElement('div');
	var pool_line_checkbox = document.createElement('div');
	var pool_line_div = document.createElement('div');
	var pool_line_per = document.createElement('div');
	
	pool_line_name.style.color = 'red';
	pool_line_name.style.marginTop = '2px';
	pool_line_name.appendChild(document.createTextNode(name));
	
	var checkbox = document.createElement('input');
	checkbox.id = 'pool_checkbox' + num;
	checkbox.type = 'checkbox';
	checkbox.onclick = function(){
					sendVote(name);
					return false;
				}
	
	pool_line_checkbox.appendChild(checkbox);
	pool_line_checkbox.style.width = '25px';
	pool_line_checkbox.style.cssFloat = 'left';
	pool_line_checkbox.style.styleFloat = 'left'; // if ie
	
	pool_line_div.style.backgroundColor = 'blue';
	pool_line_div.style.marginTop = '3px';
	pool_line_div.style.marginRight = '4px';
	pool_line_div.style.cssFloat = 'left';
	pool_line_div.style.styleFloat = 'left'; // if ie
	pool_line_div.style.width = line_width + 'px';
	pool_line_div.style.height = "10px";
	//pool_line_div.innerHTML = '&nbsp';
	
	pool_line_per.style.marginTop = '3px';
	pool_line_per.appendChild(document.createTextNode(' ' + percent + '%'));
	
	pool_line.appendChild(pool_line_name);
	pool_line.appendChild(pool_line_checkbox);
	pool_line.appendChild(pool_line_div);
	pool_line.appendChild(pool_line_per);
	
	pool_div.appendChild(pool_line);
}
