// This js handles the ajax calls via iframe for the poll system

var stretched = false;
var vote_casted = false;

// Hide/Show the poll form and poll results  
function hidePollForm()
{
       x = document.getElementById("poll_form");
       if (x) x.style.display= "none";
}
function showPollForm()
{
       x = document.getElementById("poll_form");
       if (x) x.style.display= "block";
}
function hidePollResult()
{
       x = document.getElementById("poll_result");
       if (x) x.style.display= "none";
}
function hidePollAlreadyVoted()
{
	x = document.getElementById("poll_already_voted");
	if (x) x.style.display="none";
}
function showPollResult()
{
       x = document.getElementById("poll_result");
       if (x) x.style.display = "block";
       
       if (stretched == false)
       {
            stretch_graphs();
       }

	hidePollAlreadyVoted();
}
function showAlreadyVotedMessage()
{
       x = document.getElementById("poll_already_voted");
       if (x) x.style.display = "block";
}

// When you click to cast your vote this get's called
function submitPoll(choice_id, poll_id, story_id, section_id)
{
  poll_value = getPollValue();
  
  // Test if they chose a radio button to vote on
  if (poll_value != -1)
  {
 
   // vote_casted gets set in the beginning if they have already voted and set to true after voting.
   // That allows us to pop up an alert if they've already voted. 
   if (vote_casted == true)
   {
	alert("Limit 1 vote per user, you have already voted.");
   }
   else
   {

  	  // Build a url with the form data to send the iframe to to exec the perl script
	    url	="/survey-bin/tabulate_poll.cgi?mi_pb_cache=1&expire_days=5&path=/&already_voted_error=You have already voted. Limit 1 vote per user.&save=Cast Vote&value=Cast Vote"
	    url = url + "&poll_id=" + poll_id; 
	    url = url + "&section_id=" + section_id;
	    url = url + "&story_id=" + story_id;
	    url = url + "&poll_response=" + poll_value;
      
	    // Submit the form to an iframe for processing. The iframe will then trigger handleResponse with
	    // the dynamically rendered poll results.  
	    x = document.getElementById("communication_iframe");
	    x.src = url;
	    vote_casted = true;
    }

  }
  else
  {
    alert("Please choose an option to vote for")
  }
}

// This will retrieve poll results without casting a vote, via submitting the form to the iframe.
// Note: not passing "save" or "value" like the submitPoll function does prevents this call
// from casing a vote. 
function getPollResults(poll_id, story_id, section_id)
{
    // Build a url with the form data to send the iframe to to exec the perl script
    url="/survey-bin/tabulate_poll.cgi?mi_pb_cache=1&expire_days=5&path=/&already_voted_error=You have already voted. Limit 1 vote per user."
    url = url + "&poll_id=" + poll_id;
    url = url + "&section_id=" + section_id;
    url = url + "&story_id=" + story_id;

    // Submit the form to an iframe for processing. The iframe will then trigger handleResponse with
    // the dynamically rendered poll results.

    x = document.getElementById("communication_iframe");
    if (x) x.src = url;
}


// This helper function looks at the list of poll responses and returns the index of the one selected
 function getPollValue(){
    var radios = document.forms.poll_responses.poll_response;
    for(var i=0; i<radios.length; i++){
	if (radios[i].checked) return (radios[i].value);
    }
    return -1;
}    

// This function is called from the child iframe that the form is submitted through.
// It passes back a DDS rendered version of the poll results, and we innerhtml into the page.
function handleResponse(msg, graphical_results) {
   if (vote_casted) 
    {
       stretched = false;  
       hidePollForm();
       showPollResult();
    }
    else
    {
       showPollForm();
       showPollResult();
    }

   x = document.getElementById("poll_result");
   x.innerHTML = graphical_results;

   // Safari refreshes the generated source, so we need to clear out the address in the iframe so it doesn't trigger a request on refresh. 
   x = document.getElementById("communication_iframe");
   x.src = "";

}

// Grab the cookie so we can check if they've already submitted or not
function getPollCookie (name) {
    var dc = document.cookie;
    var cname = name + "=";
    var clen = dc.length;
    var cbegin = 0;
    
    while (cbegin < clen) {
    var vbegin = cbegin + cname.length;
    
    if (dc.substring(cbegin, vbegin) == cname) {
    var vend = dc.indexOf (";", vbegin);
    if (vend == -1) vend = clen;
    
    return unescape(dc.substring(vbegin, vend));
    }
    
    cbegin = dc.indexOf(" ", cbegin) + 1;
    
    if (cbegin== 0) break;
    }
    return null;
}

// Onload, hide either the poll form or the poll results based on the cookie
function visibilityCheck()
{
    // Get the cookie and parse it to see if this poll ID has been submitted before
    var content = getPollCookie('mi_polls');

    // No cookie, do nothing
    if (content == null)  
    {
	   return;
    }

    // Parse the cookie so we can see if they voted on this particular poll id
    sval=content.split(";");
    num_cookies = sval.length;
    key = new Array();
    for (x = 0; x < num_cookies / 2 + 1; x++)
    {
        qval=sval[x].split("=");
        id = qval[0];
        poll_submitted = qval[1];
        key[id]  = poll_submitted;
    }
   
    // If they already voted, hide the form, and show a message saying they already voted 
    if (key[poll_id]==1) {
        hidePollForm();
	showAlreadyVotedMessage();
        vote_casted = true;
    }
    else  // Otherwise show the form so they can vote
    {
            showPollForm();
    }

}

// The size of the box this stuff is going into can vary quite a bit so
// This will scale up the size of those bars on the bar graph so they take up
// More of the box.. If your graphs are running off the edge, bring .9 down to .8
function  stretch_graphs()
{
    stretched = true;
    x = document.getElementById("poll_result");
    y = document.getElementById("poll_form");
   
    // Detect how much room the box has that the results are going into 
    if (x.offsetWidth > 0)
      div_width = x.offsetWidth;
    else
      div_width = y.offsetWidth;

    // Magical formula or deciding how much to increase the bar width    
    multiplier = (div_width * .9 - 20)/100;

    // Get each of those bars, and expand or shrink each one of them       
    var x=document.getElementsByName("bar_result");

    for (count = 0; count < x.length; count++)
    {
      pixels = x[count].width;
      if (pixels > 0)
        x[count].width = pixels * multiplier;
      
    }
    
}


