function AgQuickAjax (url,keys,values,async,func)
{
	var queryStr="";
	for(var i=0; i < keys.length; i++)
	{
		if(i>0) queryStr += "&";
		queryStr += keys[i] + "=" + values[i];
	}
	xmlHttp = AgXmlHttp();
	xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState==4) func(xmlHttp); };
	xmlHttp.open("POST",url,async);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
	xmlHttp.send(queryStr);
}

function AgXmlHttp ()
{
	var xmlHttp;
	try
	{
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				MessageBox("Your browser does not support AJAX!");
			}
		}
	}
	return xmlHttp;
}

function MySetCookie(name, value, days, path, domain, secure) 
{
	var expires = -1;
	if ( typeof days == "number" ) {
		var d = new Date();
		if ( days > 0 ) {
			d.setTime(d.getTime()+(days*24*60*60*1000));
			expires = d.toGMTString();
		}
		else if ( days == 0 ) {
			d.setTime(d.getTime()+(1*24*60*60*1000));
			d.setHours( 0, 0, 0 ,0 );
			expires = d.toGMTString();
		}
	}
	value = escape(value);
	document.cookie = name + "=" + value + ";"
		+ (expires != -1 ? " expires=" + expires + ";" : "")
		+ (path ? "path=" + path : "")
		+ (domain ? "; domain=" + domain : "")
		+ (secure ? "; secure" : "");
}

function SetCookie(name, value, days, path, domain, secure) 
{
	var expires = -1;
	if(typeof days == "number" && days >= 0) {
		var d = new Date();
		d.setTime(d.getTime()+(days*24*60*60*1000));
		expires = d.toGMTString();
	}
	value = escape(value);
	document.cookie = name + "=" + value + ";"
		+ (expires != -1 ? " expires=" + expires + ";" : "")
		+ (path ? "path=" + path : "")
		+ (domain ? "; domain=" + domain : "")
		+ (secure ? "; secure" : "");
}

function GetCookie(name) 
{
	var idx = document.cookie.indexOf(name+'=');
	if(idx == -1) { return null; }
	value = document.cookie.substring(idx+name.length+1);
	var end = value.indexOf(';');
	if(end == -1) { end = value.length; }
	value = value.substring(0, end);
	value = unescape(value);
	return value;
}

function DeleteCookie(name) 
{
	SetCookie(name, "-", 0);
}

function BarChart(title, labelWidth, barWidth, barHeight, bgColor) 
{
	this.barList = new Array();
	this.totalList = new Array();

  this.labelWidth = labelWidth;
                
  this.barWidth = barWidth;
  this.barHeight = barHeight;
  this.bgColor = bgColor;
  this.title = title;
  this.alignCaption = "top";
                
  this.replace = function (divContainer) 
  {
		// Declare variables and create the header, footer, and caption.
    var table = document.createElement("TABLE");
    table.border = "0px";
    table.bgColor = this.bgColor;
		table.className = "polltable";
                    
    if (this.title.length > 0)
    {
			var caption = document.createElement("CAPTION");
			caption.className = "pollheader";
      //caption.appendChild(document.createTextNode(this.title));
      caption.align = this.alignCaption;
      table.appendChild(caption);
    }
    
		var tbody = document.createElement("TBODY");
    table.appendChild(tbody);
                    
    var totalValue = 0;
    for (var i=0; i < this.barList.length; i++) 
    {
			totalValue += parseInt(this.barList[i].value, 10);
    }
                    
    for (i=0; i < this.barList.length; i++) 
    {
			var row = document.createElement("TR");
      tbody.appendChild(row);
                        
			// Put label in left cell align right/left
      var leftCell = document.createElement("TD");
			leftCell.className = "pollbarlabel";
			leftCell.style.width = this.labelWidth + "px";
      leftCell.appendChild(document.createTextNode(this.barList[i].label));
      row.appendChild(leftCell);
                        
      // Put bar in right cell containing a table align left
      var rightCell = document.createElement("TD");
			rightCell.className = "pollbar";

      var ratio = 0;
      if ( totalValue > 0 )
      	ratio = this.barList[i].value/totalValue;
      this.addBar(rightCell, ratio, this.barList[i].color);
      row.appendChild(rightCell);
		}

    for (i=0; i < this.totalList.length; i++) 
    {
			var row = document.createElement("TR");
      tbody.appendChild(row);
                        
			// Put label in left cell align right/left
      var leftCell = document.createElement("TD");
			leftCell.className = "polltotal";
			leftCell.setAttribute("colspan", "2");
			leftCell.colSpan = 2;
			leftCell.style.width = "100%";
      leftCell.appendChild(document.createTextNode(this.totalList[i].label+this.totalList[i].value));
      row.appendChild(leftCell);
		}
	
		// Insert the table into the document tree.
		divContainer.parentNode.replaceChild(table,divContainer);
	};
     
	this.addBarData = function (label, value, color) 
	{
		var barData = new Object();
    this.barList[this.barList.length] = barData;
                    
		barData.label = label;
    barData.value = value;
    barData.color = color ? color : "black";
    return barData;
  };

	this.addTotalData = function (label, value) 
	{
		var TotalData = new Object();
		this.totalList[this.totalList.length] = TotalData;
                    
		TotalData.label = label;
    TotalData.value = value;
    return TotalData;
  };
       
	this.addBar = function (cell, ratio, color)
  { 
		var barTable = document.createElement("TABLE");
		barTable.className = "bartable";
                   
    var barTbody = document.createElement("TBODY");
    barTable.appendChild(barTbody);
    
    var barRow = document.createElement("TR");
    barTbody.appendChild(barRow);
    barRow.style.height = this.barHeight + "px";
    
    var barData = document.createElement("TD");
    barData.height = this.barHeight;
    var pixels = Math.round(ratio * this.barWidth);
    barData.width = pixels > 0 ? pixels : 1 + "px";
		// Use color of image?
		if (color.indexOf('.gif') > -1 || color.indexOf('.jpg') > -1 || color.indexOf('.png') > -1)
		{
	    var barDataBar = document.createElement("IMG");
			barDataBar.src = color;
			barDataBar.height = this.barHeight;
	    barDataBar.width = barData.width;
	    barData.appendChild(barDataBar);
		}
		else {
			barData.bgColor = color;

		}
		barRow.appendChild(barData);
    var labelData = document.createElement("TD");
    labelData.style.height = this.barHeight;
    labelData.appendChild(document.createTextNode(Math.round(Math.round(ratio * 1000)/10) + '%'));
    barRow.appendChild(labelData);
    
    barTable.cellspacing = "0px";
    barTable.cellpadding = "0px";
    
    cell.appendChild(barTable);
	};
}
//var starturl = "/modules/poll/";
var starturl = "";
  
var XMLHttpRequestObject = new Array();
var startpollcode = "";
var myVoteName = "";

function OnVote(votename,show,pollid,polltype)
{

	//alert(votename + ":" + show + ":" + pollid + ":" + polltype);	
	myVoteName = votename;
	if (starturl.length < 1) {
		starturl = document.getElementById('pollurl').value;
	}

	var theurl = starturl + "edoris.dll?app=server&com=dialog&tem=poll";
	
	XMLHttpRequestObject[votename] = new Object();
  	XMLHttpRequestObject[votename].color = new Array();
  	XMLHttpRequestObject[votename].label = new Array();
	
	var voteallowed = false;
	if (GetCookie(votename + polltype) == null) 
		voteallowed = true;

	// save the start html
	if (show != '2'){
		startpollcode = document.getElementById('voteouter').innerHTML;
	}
	else if (show == '2'){
		document.getElementById('voteouter').innerHTML = startpollcode;
		return;
	}

	if (voteallowed == false && show != '1'){
		alert(document.getElementById('pollvoted').value);
	}
	else {
	
		var thefullurl = theurl + "&poll_id=" + pollid + "&show=" + show;
		var voteChoices=document.getElementsByName(votename);
		var done = false;
		
		
		for(var i=0; i < voteChoices.length; i++)
		{
			if ( voteChoices[i].checked && show != 1 ) {
				thefullurl += "&selected=" + voteChoices[i].getAttribute('label');
				done = true;
			}
			XMLHttpRequestObject[votename].color[i] = voteChoices[i].getAttribute("barcolor");
			XMLHttpRequestObject[votename].label[i] = voteChoices[i].getAttribute("value");
		}
		
		
		if ( done == false ) {
			thefullurl += "&selected=0";
		}
		else {
			if ( show != 1 )
				MySetCookie(votename + polltype, votename, 0, "/"); 
		}
		thefullurl += "&random=" + Math.random();
		MySetCookie("polltest", "polltest", 1, "/" ); 
		AgQuickAjax( thefullurl, [], [], true, OnVoteProcess );
	}
}


function laskeProsentti(kokonaismaara, kysymyksenmaara){

	var temp;
	//alert(kysymyksenmaara);
	temp = Math.round((kysymyksenmaara / kokonaismaara) * 100);
	return temp;
}

function lisaaLaatikonPituus(laatikko, kysymyksenmaara, kokonaismaara){
	
	laatikko += '';
	laatikko = "block" + laatikko;
	var tempLength = (270 / kokonaismaara) * kysymyksenmaara 
	$("#" + laatikko).css({'width': tempLength});

}


function OnVoteProcess( xmlHttp )
{
	votename = myVoteName;
	backtopolltext = document.getElementById('pollbacktovote').value;
	response = xmlHttp.responseText;
	var kysymykset = [];
	var vastaukset = [];
	var kokonaistulos;
	var variables = response.split('&');
	
	//Haetaan kokonaistulos
	var totalTemp = variables[variables.length - 1].split('=');
	kokonaistulos = totalTemp[1]
	
	$("#voteQuestions").hide();
	$("#votefooter").hide();
	$("#voteouter").append('<ul id="voteList">');
	
	//KŠydŠŠn kysymykset ja vastaukset lŠpi	
	for (var i = 0; i < variables.length; i++) {
		var variable = variables[i];
    	var item = variable.split('=');

		if (i < variables.length - 1){
		//Laitetaan palkki paikoilleen
		$("#voteList").append('	<li><div class="VoteQuestionHeader">' + item[0] + '</div><div class="voteQuestionBlock" id="block' + i + '"></div><div class="voteQuestionResult">' +  laskeProsentti(kokonaistulos, item[1]) + '%</div></li>');
		lisaaLaatikonPituus(i, item[1],kokonaistulos);
		}
	    	
	}
	$("#voteouter").append('</ul>');
	$("#voteouter").append('<div class="voteResultTotal">Vastauksia yhteens&auml;: ' + kokonaistulos + '</div>');
  	/*
	// Create an BarChart instance
	var chart = new BarChart(document.getElementById('pollheader').value, document.getElementById('labelwidth').value, document.getElementById('barwidth').value, document.getElementById('barheight').value,"");
	
	for (var i = 0; i < variables.length; i++)
	{
		var variable = variables[i];
    	var item = variable.split('=');
		var colorimgstr = "";

		if (document.getElementById('colorimg').value == "color")
			colorimgstr = XMLHttpRequestObject[votename].color[i];
		else
			colorimgstr = starturl+XMLHttpRequestObject[votename].color[i]+".gif";

		if (i < variables.length-1) // Bar
	    chart.addBarData(XMLHttpRequestObject[votename].label[i], item[1], colorimgstr);
		else // Total amount 
	    chart.addTotalData(document.getElementById('totallabel').value, item[1]);
  }

	var name = "votediv";
  var divContainer = document.getElementById(name);
	var pollfooterlink = document.getElementById('votefooterlink');
	if (divContainer) {
		// Generate HTML for the BarChart using the DOM
    chart.replace(divContainer);
  }
	if (pollfooterlink) { // HAndle the footer link
		// backtopolltext = document.getElementById('pollbacktovote');
		pollfooterlink.innerHTML = backtopolltext;
		pollfooterlink.href = pollfooterlink.href.replace('\'1\'','\'2\'');
	}
                
  XMLHttpRequestObject[votename] = null;
	DeleteCookie("polltest");  
	
		$("#odotahetki").html("");
*/
}

function OnError (errortext)
{
	DeleteCookie("polltest");  
}

function addPollradio(val1, val2, val3, val4, val5){

	$("#" + val2).attr("checked", "checked");
	OnVote('pollvote','',val4,val5);
}

function checkIfVoted(val1, val2, val3, val4){

	alert("Tuli");
	if (GetCookie(votename + polltype) != null){	
		OnVote(val1, val2, val3, val4);
	}
}

function ifAllreadyVoted(val1, val2, val3, val4){

	
	if (GetCookie(val1 + val4) != null) {
	
		OnVote(val1, val2, val3, val4);
	
	}


}


