/* 
This is an object oriented version of the poll javascript
This script does everything our ajax polls implementation needs, including:

1. showing appropriate html depending on if the person has voted or not
2. handle submission of the form
3. get results
etc
*/

/* object constructor */
function miPollAjax() {
    this.poll_id;
    this.story_id;
    this.section_id;
    this.stretched = false;
    this.vote_casted = false;

    // When you click to cast your vote this get's called
    this.submitPoll = function()
    {
        var poll_value = this.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 ( this.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%20have%20already%20voted.%20Limit%201%20vote%20per%20user.&save=Cast%20Vote&value=Cast%20Vote";
                url = url + "&poll_id=" + this.poll_id;
                url = url + "&section_id=" + this.section_id;
                url = url + "&story_id=" + this.story_id;
                url = url + "&poll_response=" + poll_value;

		$("#poll_result").load(url); 
		this.hidePollForm();
            	this.fetchPollResults();
            	this.showPollResults();
                this.vote_casted = true;
            }
        }
        else
        {
            alert( "Please choose an option to vote for" )
        }
    }

    // This will retrieve poll results without casting a vote, by calling in the cgi results via jquery's 
    // AJAX support
    // Note: not passing "save" or "value" like the submitPoll function does prevents this call
    // from casing a vote. 
    this.fetchPollResults = function()
    {
        // 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%20have%20already%20voted.%20Limit%201%20vote%20per%20user.";
        url = url + "&poll_id=" + this.poll_id;
        url = url + "&section_id=" + this.section_id;
        url = url + "&story_id=" + this.story_id;

	$("#poll_result").load(url); 
    }

    this.register_response = function( element )
    {
        this.tempElement = element;
        //this.handleResponse( 1, this.tempElement );
        this.stretch_graphs();
    }


    // This helper function looks at the list of poll responses and returns the index of the one selected
    this.getPollValue = function()
    {
        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;
    }

    // Onload, hide either the poll form or the poll results based on the cookie
    this.visibilityCheck = function()
    {
        if ( this.alreadyVoted() )
        {
            //alert( "You have already voted." );
            this.hidePollForm();
            this.fetchPollResults();
            this.showPollResults();
            //this.showAlreadyVotedMessage();
            this.vote_casted = true;
        }
        else  // Otherwise show the form so they can vote
        {
            this.showPollForm();
        }
    }

    //checks to see if the user has voted already
    this.alreadyVoted = function()
    {
        // Get the cookie and parse it to see if this poll ID has been submitted before
        content = this.getPollCookie('mi_polls');
        //alert( "poll cookie => '" + this.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;
            //alert( "id => '" + id + "', value => '" + poll_submitted + "'" );
        }

        // If they already voted, hide the form, and show a message saying they already voted
        if ( key[this.poll_id] == 1 )
        {
            //alert( "You have already voted" );
            return true;
        }
        else
        {
            return false;
        }
    }

    // Grab the cookie so we can check if they've already submitted or not
    this.getPollCookie = function(cookie_name)
    {
        dc = document.cookie;
        cname = cookie_name + "=";
        clen = dc.length;
        cbegin = 0;
    
        while ( cbegin < clen )
        {
            vbegin = cbegin + cname.length;
    
            if ( dc.substring ( cbegin, vbegin ) == cname )
            {
                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;
    }

    // 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
    this.stretch_graphs = function()
    {
        this.stretched = true;
        var element_poll_result = document.getElementById("poll_result");
        var element_poll_form = document.getElementById("poll_form");
   
        // Detect how much room the box has that the results are going into 
        if ( element_poll_result.offsetWidth > 0 )
            div_width = element_poll_result.offsetWidth;
        else
            div_width = element_poll_form.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 element_bar_result = document.getElementsByName("bar_result");

        for ( count = 0; count < element_bar_result.length; count++ )
        {
            pixels = element_bar_result[count].width;
            if ( pixels > 0 )
                element_bar_result[count].width = pixels * multiplier;
        }
    
    }

    // Hide/Show the poll form and poll results  
    this.hidePollForm = function()
    {
        //alert( "hide poll form" );
        var element = document.getElementById("poll_form");
        if (element) element.style.display= "none";
    }

    this.showPollForm = function()
    {
        var element = document.getElementById("poll_form");
        if (element) element.style.display= "block";
    }

    this.hidePollResult = function()
    {
        var element = document.getElementById("poll_result");
        if (element) element.style.display= "none";
    }

    this.hideAlreadyVotedMessage = function()
    {
        var element = document.getElementById("poll_already_voted");
        if (element) element.style.display="none";
    }

    this.showPollResults = function()
    {
        this.fetchPollResults();
        var element = document.getElementById("poll_result");
        if (element) element.style.display = "block";
	 if (this.stretched == false)
        {
            this.stretch_graphs();
        }
    }

    this.showAlreadyVotedMessage = function()
    {
        element = document.getElementById("poll_already_voted");
        if (element) element.style.display = "block";
    }

} /* end object */

