var OPT_ID = 0;
var OPT_TITLE = 1;
var OPT_VOTES = 2;

var votedID;
var relPath 		= window.location.protocol + "//" + window.location.host;
var pollCookieId 	= '90A91548-862B-11DD-ADB9-6F8855D89593';
var prevSelPollOption   = '';


$(document).ready(function()
{
	startupProcess('');
	startupProcess('1');

});

function startupProcess( _divSuffix )
{
  	if ( $("#poll_container"+_divSuffix).get(0) == undefined )
  	return;

	try {
		$.get(relPath + "/sonda/default,1", {}, function(reqData){
			$("#poll_container" + _divSuffix).get(0).innerHTML = reqData;
			if ($("#poll_form" + _divSuffix)) {
				$("#poll_form" + _divSuffix).submit(formProcess); // setup the submit handler for poll_form
			}
			
			animateResults(_divSuffix);
			
		});
	} catch(e) {}
		
}

function formProcess(event)
{
  event.preventDefault();
  var id = $("input[@name='pollvotingchoice']:checked").attr("value");
  var fullid = $("input[@name='pollvotingchoice']:checked").attr("id");
  if ( id == undefined )
  {
  		alert('Proszę wskazać jedną odpowiedź.');
		return;
  }
  id = id.replace("opt",'');
  fullid = fullid.split("_");

	$memoelem_id = "polloption_"+fullid[1]+"_"+fullid[2]+"_memo";
	if ( $("#"+$memoelem_id).get(0) != undefined )
	{
		$memo_param = document.getElementById($memoelem_id).value;
	}
	else
	{
		$memo_param = "";
	}

	fadeoutFn('', fullid);

	fadeoutFn('1', fullid);
 
}


function fadeoutFn( _divSuffix, fullid )
{
  $("#poll-container"+_divSuffix).fadeOut("slow",function()
  {
  	$(this).empty();
	
	$.post(relPath + "/sonda/addvote,"+parseInt(fullid[1])+","+parseInt(fullid[2]), { memoval: $memo_param },
	  function(reqData){
	  	var cc = $.cookie(pollCookieId);
		if ( cc == null )
		{
			$.cookie(pollCookieId, "#"+fullid[1], {
				expires: 365
			});
		}
		else if (cc.indexOf("#"+fullid[1]) == -1) {
			cc += "#"+fullid[1];
			$.cookie(pollCookieId, cc, {
				expires: 365
			});
		}
		$("#poll_container"+_divSuffix).get(0).innerHTML = reqData;
		animateResults( _divSuffix );
	  });

  });	
} 


function animateResults( _divSuffix  ){
  $("#poll-results div"+_divSuffix).each(function(){
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({
				width: percentage}, 'slow');
  });
}

function onSelectPollOption( poid )
{
	if ( (prevSelPollOption != '') && (document.getElementById( prevSelPollOption + "_memo")) )
	{
		document.getElementById( prevSelPollOption +  "_memo").style.display = 'none';
	}	
		
	if (document.getElementById( poid + "_memo"))
	{
		document.getElementById( poid +  "_memo").style.display = 'inline';
	}
	
	prevSelPollOption = poid;
}

