/************************************************************
 * voter_module.js
 *
 * @author Steve Sanden
 * @date 04/10/2008
 * ==========================================================
 * This is a javascript library for the voter module
 *
 * To use this you will need to place 1 div tag
 * in the area of the page the you want the voter section
 * to be.
 * Example:
 *         <div id="sidebar_subvote"></div> 
 *
 * The in the script section add the following add the following 
 * to the init() function called by the body onload function:
 *
 * build_vote_module()
 *
 * ***********************************************************/

function build_vote_module() {

       var qurl = "votemodule/voteAPI.php?action=build";   
       
       load_js_css_file("CSS/voter_module.css","css");
       //load_js_css_file("script/scriptaculous.js","js");
      
       new Ajax.Request(qurl, { method:'get',
         onSuccess: function(transport,json){
         
        var question= json['question'];
         
         
         
         $('sidebar_subvote').innerHTML="<p><b>"+question+"</b></p>"; 
         $('sidebar_subvote').innerHTML+="<p><a href='javascript:issueDetails();'>[Read more on this issue]</a></p>";
         $('sidebar_subvote').innerHTML+="<br>";
         
         var formtext="<form name=\"voteform\">";
         
         var choices= json['choices'];
         
         for (var i=0; i < choices.length;i++) 
         {
         formtext +="<input name='vchoice' type='radio' value=\""+choices[i]+"\" /><strong>&nbsp;"+choices[i]+"<strong><br/>";
         }
         
        
     
         
         formtext += "<br><input type=\"button\" value='vote' onClick=\"vote();\"/>";
		 formtext +="&nbsp;&nbsp; or <a href='javascript:show();'>see results</a>";
		 formtext +="</form>";
         
         $('sidebar_subvote').innerHTML+=formtext;
        
         },
         onLoading: function(transport) {
           loading('sidebar_subvote');
        }
         });
  }

 function vote() {

 var choice;
 for (var i=0; i < document.voteform.vchoice.length; i++)
   {
   if (document.voteform.vchoice[i].checked)
      {  
        choice = document.voteform.vchoice[i].value;
      }
    }
    
  var qurl = "votemodule/voteAPI.php?action=vote&vchoice="+choice;
  new Ajax.Request(qurl, { method:'get',
  onSuccess: function(transport, json){      
       showVoteResults(json,true,choice);  
    },
    onLoading: function(transport) {
     loading('sidebar_subvote');
    }
    });

}

function getResponse(oReq, oJSON){
  var data = eval(oReq.responseText);
  alert(data);
}



function show() {

 var qurl = "votemodule/voteAPI.php?action=voteresults";  
  new Ajax.Request(qurl, { method:'get',
  onSuccess: function(transport, json){                 
     showVoteResults(json,false,'');  
    },
    onLoading: function(transport) 
     {
       $('sidebar_subvote').innerHTML = "<br><br><br><br><p align='center'> <img src='images/loading.gif' border=0/></p>";
     }
    });
}


function save_email() {
var eaddr = document.emailform.emailaddr.value;
var myvote = document.emailform.myvote.value;

//validate that the email address is in the correct format
if (!validEmail(eaddr)) {
  try {  
     $('emailerr').innerHTML = "<p style=\"color:red;text-align:center\">Address is invalid</p>";   
    } catch(ex){
     $('doemail').innerHTML += "<div id='emailerr'><p style=\"color:red;text-align:center\">Address is invalid</p></div>";
    }
     new Effect.Highlight('eid', { startcolor: '#ffff99',endcolor: '#ffffff', restorecolor: '#ffff99'});
    return; 
}


var qurl = "votemodule/voteAPI.php?action=addcontact&eaddress="+eaddr+"&myvote="+myvote;
 new Ajax.Request(qurl, { method:'get',
  onSuccess: function(transport, json){                 
     thankyou(json, eaddr);  
    },
    onLoading: function(transport) {
     $('moreinfo').innerHTML = "<br><br><p align='center'> <img src='images/loading.gif' border=0/></p>";
    
    }});
}

function validEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function thankyou(json, eaddr) {
  
  thanks="<div id='thanks'><p>Thank You. We value your opinion</p>";
  thanks+="<p>An email has been sent to the address:<b>"+eaddr+"</b></p><br>";
  thanks+="<p>We have included for you information about Pete's stance ";
  thanks+="and the House's vote on the issue you just voted on.</p></div>";
  
   $('moreinfo').innerHTML=thanks;  
   $('moreinfo').appear();
}



function showVoteResults(json,voted,choice) {
    
    load_js_css_file("CSS/voter_module.css","css");
    //load_js_css_file("script/scriptaculous.js","js");
  
     var totalView = "<p><b>"+json["question"]+"</b><br/>";
    // totalView+="<a href='' style='font-size:8pt'>[Read more on this topic]</a>";
     totalView+="</p>";       
                                
     totalView += "<table style=\"border-collapse:collapse\"><br>";  
     rows = parseInt(json['rowcount']);
      
     
     for(var i=0; i < rows ;i++) {    
  	 var cl = (i%2 == 0)?"shade":"";  
  	   
     totalView +="<tr class="+cl+">";
     totalView+="<td align=left nowrap>"+json[i]['choice']+"</td><td width=300px>&nbsp;</td>";
	 totalView +="<td align=right><strong>"+json[i]['pct']+"%</strong></td>";
	 
	 //Commented out the display of the total votes per choice
	 //totalView+="<td width=35px style=\"color:#737CA1\" align=right><b>"+json[i]['count']+"</b></td>"
	 totalView+="</tr>";
  
     }
    
    //Commented out the display of total votes
    // totalView +="<br><tr><td colspan =\"4\" align=right style=\"color:#737CA1\">Total Votes:<b>"+json['total_count']+"</b></td></tr>"; 
     totalView +="</table>";
     
     if (voted) 
     {
     totalView +="<hr><br>";
     totalView +="<div id='moreinfo'>Would you like to see Pete's opinion on this issue and what action the US House took?";
     totalView +="<br><br>If so, please enter your email address to see the results and also to stay informed on Pete's progress in Congress."; 
     totalView +="<div id='doemail'><form name='emailform' method='POST'>";
     totalView +="<table><tr>";
     totalView +="<td><input id='eid' type='text' name='emailaddr'/></td>";
     totalView +="<td><a href='javascript:save_email();'><img src='images/submit.gif' border=0 width=51 height=22 /></a></td>";
     totalView +="</tr></table>";
     totalView +="<input type='hidden' name='myvote' value='"+choice+"'/></form>";
     //totalView +=" or <a href='javascript:viewIssueStance();'>view now</a></div>";
     totalView+="</div>" 
     }
          
     $('sidebar_subvote').innerHTML = totalView;
    
  
}

 function viewIssueStance() {

 $('sidebar_subvote').innerHTML="<h3>Pete on the Issue</h3>";
 $('sidebar_subvote').innerHTML+="<div class='votestance'>Pete voted <b>Yes</b> on this issue because ....</div>";
 $('sidebar_subvote').innerHTML+="<br/><br/><hr>";
 $('sidebar_subvote').innerHTML+="<h3>In the House</h3>";
 $('sidebar_subvote').innerHTML+="<div class='votestance'>The House passed this bill that will ....</div>";

 }

function issueDetails() {

var qurl = "votemodule/voteAPI.php?action=theissue";
loading = "<br><br><center><h4 align='center'>.. Loading Data ..</h4>";

try {
  $('theissue').innerHTML = loading;
} catch(ex) {
  $('sidebar_subvote').innerHTML +="<div id='theissue'></div>";
}

 new Ajax.Request(qurl, { method:'get',
  onSuccess: function(transport, json){                 
      voteinfo="<br>"+json["theissue"];
      voteinfo+="<br><a href=\"javascript:hideissue();\">[hide]</a>";
      $('theissue').innerHTML= voteinfo;
      $('theissue').appear();
   
    }});
    
   
}

function hideissue() 
{
   Effect.SlideUp('theissue');
}

function load_js_css_file(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}



function loading(divtag) {

  $(divtag).innerHTML = "<br><br><p align='center'><img src='images/loading.gif' border=0/></p>";


}


