var civ_email = '';
var randomID = 'IyUuInnqTjTmjlVCnPsNrNmE5G';
var cs_steelers = {

 addScript: function(url){
  var obj=new JSONscriptRequest(url);      
  obj.buildScriptTag();
  obj.addScriptTag();},
survey: function(qorder, question_id, onclick, qtype){
	qtype = typeof(qtype) != 'undefined' ? qtype : 'radio';
	var b = document.getElementById("button_iuRHMRgNdi");
	if(question_id === undefined)
      var req  = 'http://www.civicscience.com/widget/survey_js/index/steelers/'+qorder+'/?email='+civ_email+'&requestid='+randomID;
    else{
    	b.onClick='';
      if(qtype=='radio'){
	      var answer_ids = cs_steelers.getValues('iuRHMRgNdi_q'+question_id);
	      if(answer_ids.length == 0){
	      	document.getElementById('q_error_iuRHMRgNdi').innerHTML = '*';
	      	b.onClick = onclick;
	      	return;
	      }	
	      else
	      var req  = 'http://www.civicscience.com/widget/survey_js/index/steelers/'+qorder+'/?email='+civ_email+'&q='+question_id+'&a='+answer_ids[0]+'&requestid='+randomID+'&url='+location.protocol+'//'+location.host+location.pathname;
      } else if (qtype == "checkbox") {
          var values = cs_steelers.getValues("iuRHMRgNdi_q" + question_id + "[]");
          var req  = 'http://www.civicscience.com/widget/survey_js/index/steelers/'+qorder+'/?email='+civ_email+'&qtype=checkbox&q='+question_id+'&requestid='+randomID+'&url='+location.protocol+'//'+location.host+location.pathname;
          for (var i = 0; i < values.length; i++) {
              req += "&a[]=" + values[i];
          }
      }else if(qtype=='textarea'||qtype=='textbox'){
      var answer = document.getElementById('iuRHMRgNdi_q'+question_id).value.replace(new RegExp('[^0-9A-Za-z. ,]', "g"), '');
      if(answer == ''){
      	document.getElementById('q_error_iuRHMRgNdi').innerHTML = '*';
      	b.onClick = onclick;
      	return;
      }else{
      var req  = 'http://www.civicscience.com/widget/survey_js/index/steelers/'+qorder+'/?email='+civ_email+'&qtype='+qtype+'&q='+question_id+'&a='+answer+'&requestid='+randomID+'&url='+location.protocol+'//'+location.host+location.pathname;
      }	
      }
	}
	cs_steelers.addScript(req);
},
surveyText: function(qorder, question_id, onclick){
	cs_steelers.survey(qorder, question_id, onclick, 'textarea');
},
surveyCheckbox: function(qorder, questionID, onclick) {
    cs_steelers.survey(qorder, questionID, onclick, "checkbox");
},
results: function(qorder){
	var req = (qorder == 'intro') ? 'http://www.civicscience.com/widget/survey_js/results/steelers/'+qorder+'/1?email='+civ_email : 'http://www.civicscience.com/widget/survey_js/results/steelers/'+qorder+'/?email='+civ_email;
	cs_steelers.addScript(req + "&requestid=" + randomID);
},
error:function(){cs_steelers.closeDiv(); document.getElementById('iuRHMRgNdi').innerHTML='<div class="widget"><div class="form_error" style="text-align:center;">Error Loading Poll</div></div>';},
loadCss: function(filename){
   var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 	if (typeof fileref!="undefined") {
 		var pbCSS = document.getElementById("panel_brand_css");
    	if(!pbCSS) {document.getElementsByTagName("head")[0].appendChild(fileref);}
  	}
},
groupSetup: function(data){
if(data !=null)
{	
	var dot = document.createElement("div");
	var box = document.getElementById('iuRHMRgNdi');
	dot.id = "box_iuRHMRgNdi";
	dot.className = 'csw';
	dot.style.position = "absolute"; 
	box.parentNode.appendChild(dot);
	var xy =  cs_steelers.findPos(box);
	dot.parentNode.style.position = "relative";
	var off=cs_steelers.findPos(box.offsetParent);
	try {if(off[0]);} catch(e){off=[0,0];} 
	dot.style.left=(xy[0] - off[0])+'px';
	dot.style.top=(xy[1] - off[1])+'px';
	var text = '<div class="widget"><div class="top"><div class="close" onClick="cs_steelers.closeDiv();" id="close_iuRHMRgNdi"></div></div><div id="main_iuRHMRgNdi" class="middle">';
	if(data.Msg){text += cs_steelers.thankYouMain(data);
	}else if(data.Forward){
	text += cs_steelers.resultSetup(data);
	}else if(data.Question)
		text += cs_steelers.questionSetup(data);
	else{ 
	text += '<div class="poll_title"></div><div class="login_box_text">Email Address</div><div class="login_box"><input type="text" class="form_field" id="email_iuRHMRgNdi" onkeypress="return cs_steelers.cswCheckSubmit('+data.OnClick.substring(0,data.OnClick.length - 3) +');" value="';
	if(cs_steelers.get_cookie("civ_steelers_email"))
	text+= cs_steelers.get_cookie ( "civ_steelers_email" );
	text +='" />';
	text +='<div id="error_iuRHMRgNdi" class="form_error"></div><div class="login_text">This information is used to protect against fraudulent voting. Your information is never shared.</div></div></div>';
	text +='<div class="bottom" id="button_iuRHMRgNdi"><div class="button"><input type="button" value="" alt="Submit" title="Submit" onClick = "'+data.OnClick+'" class="submit" />';
	}
	text +='</div>';
	dot.innerHTML = text;
	if(document.getElementById("email_iuRHMRgNdi"))
		document.getElementById("email_iuRHMRgNdi").focus();
}
else cs_steelers.error();
},
civButtons: function(Data, id){
	var b = '<div class="button">';
	b += Data.Back ? '<input type="button" value="" onclick="'+Data.Back+'" alt="Previous" title="Previous" class="previous" />' : '';
	b += Data.Forward ? '<input type="button" value="" onclick="'+Data.Forward+'" alt="Next" title="Next" class="next" />' : '';
	b+="</div>";
	return b;
},
closeDiv: function(){
document.getElementById('iuRHMRgNdi').style.visibility='visible';
if(document.getElementById("box_iuRHMRgNdi"))document.getElementById("box_iuRHMRgNdi").style.display = 'none';
},
civResults: function(Data){ Data != null ? (document.getElementById("main_iuRHMRgNdi") ? document.getElementById("main_iuRHMRgNdi").innerHTML=cs_steelers.resultsSetup(Data) : cs_steelers.groupSetup(Data)) : cs_steelers.error(); },
civQuestion: function(jsonData){ jsonData != null ? (document.getElementById("main_iuRHMRgNdi") ? document.getElementById("main_iuRHMRgNdi").innerHTML=cs_steelers.questionSetup(jsonData) : cs_steelers.groupSetup(jsonData)) : cs_steelers.error();},
civResult: function(jsonData){ jsonData != null ? (document.getElementById("main_iuRHMRgNdi") ? document.getElementById("main_iuRHMRgNdi").innerHTML=cs_steelers.resultSetup(jsonData) : cs_steelers.groupSetup(jsonData)) : cs_steelers.error();},
validateEmail: function(elementValue){
elementValue = elementValue.replace("%40", '@');
elementValue = elementValue.replace("%2e", '.');  
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
 if(emailPattern.test(elementValue))
 {var current_date = new Date;
    var cookie_year = current_date.getFullYear ( );
    var cookie_month = current_date.getMonth ( ) + 1;
    var cookie_day = current_date.getDate ( );
    cs_steelers.set_cookie ( "civ_steelers_email", elementValue, cookie_year, cookie_month, cookie_day );
 return true;
 }else
 return false; },
sendEmail: function(){
var email = document.getElementById("email_iuRHMRgNdi") ? document.getElementById("email_iuRHMRgNdi").value : civ_email;
	if(cs_steelers.validateEmail(email)){
	civ_email = email;
	cs_steelers.survey(1);
	}else{
	document.getElementById("error_iuRHMRgNdi").innerHTML = 'Invalid Email Address';
	document.getElementById("email_iuRHMRgNdi").focus();
}},
findPos: function(obj) {
	var cleft = ctop = 0;
if (obj.offsetParent) {
do {cleft += obj.offsetLeft;
			ctop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [cleft,ctop];}
},
setupGroup: function(){
	var email=cs_steelers.getQueryVariable("email");
	if(cs_steelers.validateEmail(email))
		civ_email=email;
	var csw = document.createElement("div");
	csw.id = "csw_iuRHMRgNdi";
	document.getElementById('steelers').parentNode.appendChild(csw);
	csw.setAttribute("class", "csw");
	csw.setAttribute("className", "csw");
	var text= '<div id="iuRHMRgNdi"  class="small_widget">';
	 text += '<div class="poll_title" ></div><div class="first_question">Do you think the Steelers will repeat as Super Bowl champs?</div>';
	text +=	'<div class="button"><input type="button" value="" alt="Vote" onclick="cs_steelers.civDivCheck()" title="Vote" style=" cursor: pointer; "></div>';
	text +='</div>';
	csw.innerHTML = text;
	},
civDivCheck: function(){
	document.getElementById('iuRHMRgNdi').style.visibility='hidden';
	document.getElementById("box_iuRHMRgNdi") ? document.getElementById("box_iuRHMRgNdi").style.display='block' : cs_steelers.addScript('http://www.civicscience.com/widget/survey_js/index/steelers/1/?email='+civ_email+'&requestid='+randomID);
},
cswCheckSubmit: function(event, onclickVar) {
   var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
   if(keyCode == 13) {
   if (typeof onclickVar == 'function') 
		onclickVar();
	return false;
	}
	return true;},
getValues: function(name) {
    var values = [];
    var inputs = document.getElementsByName(name);
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "radio" || inputs[i].type == "checkbox") {
            if (inputs[i].checked) {
                values.push(inputs[i].value);
            }
        }
    }
    return values;
},
thankYou: function(Data){ Data != null ? (document.getElementById("main_iuRHMRgNdi") ? document.getElementById("main_iuRHMRgNdi").innerHTML=cs_steelers.thankYouMain(Data) : cs_steelers.groupSetup(Data)) : cs_steelers.error(); },		
thankYouMain: function(Data){
if(Data != null){
var text = '<div class="poll_title">Poll Title</div><div class="thank_you_title">Thank You </div><div class="thank_you_text">';
text +='Take more polls and be heard at <a href="http://www.civicscience.com/" target="_blank">civicscience.com</a></div>';text +="<div class=\"add_widget\"><input type=\"button\" value=\"\" alt=\"Add Widget\" title=\"Add Widget\" class =\"add\" onClick=\"window.open('http://www.civicscience.com/?contentURL=/add_this_widget/setup/steelers')\" /></div>";text +='</div></div>';
document.getElementById("button_iuRHMRgNdi") ? document.getElementById("button_iuRHMRgNdi").innerHTML = cs_steelers.civButtons(Data) : text += '<div class="sbottom" id = "button_iuRHMRgNdi">'+cs_steelers.civButtons(Data)+'</div>';
return text;
}else
cs_steelers.error();},
resultSetup: function(data){
	var text ='<div class="poll_title">Poll Title</div>';
	text +='<div class="question_number">Question '+data.Question.Qorder+' of 3</div>';
	text +='<div class="question_text">'+data.Question.Qtext+'</div>';
	for (var j in data.Question.Answers)
	{ if(data.Question.Answers[j].Avg != undefined){ text += '<div class="result'+j+'"><div class="result_percent">'+data.Question.Answers[j].Avg+'%</div><div class="result_text">'+data.Question.Answers[j].Answer_Choice+'</div></div>';}}
	text+="</div>";
	document.getElementById("button_iuRHMRgNdi") ? document.getElementById("button_iuRHMRgNdi").innerHTML = cs_steelers.civButtons(data) :  text += '<div class="bottom" id = "button_iuRHMRgNdi">'+cs_steelers.civButtons(data)+'</div>';
	return text;
},
questionSetup: function(data){
	var text = '<div class="poll_title">Poll Title</div><div class="question_number">Question '+data.Question.Qorder+' of 3</div>';
	text +='<div class="question_text"><span id="q_error_iuRHMRgNdi" class="form_error"></span>'+data.Question.Qtext+'</div>';
	if(data.Question.Qtype == 'textarea' || data.Question.Qtype == 'textbox'){
	data.OnClick=data.OnClick.replace('survey', 'surveyText');
	text+='<div class="answer"><div class="answer_text"><input type="text" id="iuRHMRgNdi_q'+data.Question.Question_ID+'" /></div></div>';
	}else{
    	var type = "radio";
    	var name = "iuRHMRgNdi_q" + data.Question.Question_ID;
    	if (data.Question.Qtype == "checkbox") {
    	    type = "checkbox";
    	    name += "[]";
    	    data.OnClick = data.OnClick.replace("survey", "surveyCheckbox");
    	}
    	for (var i in data.Question.Answer_Choices)
    	  if(data.Question.Answer_Choices[i].Answer_Choice_ID != undefined)
    		text +='<div class="answer"><div class="answer_' + type + '"><input type="' + type + '" name="' + name + '" value="'+data.Question.Answer_Choices[i].Answer_Choice_ID+'" id = "iuRHMRgNdi_'+data.Question.Answer_Choices[i].Answer_Choice_ID+'"  /></div><div class="answer_text"><label for="iuRHMRgNdi_'+data.Question.Answer_Choices[i].Answer_Choice_ID +'">'+data.Question.Answer_Choices[i].Answer_Choice+'</label></div></div>';
    	}
	text +='</div>'; 
	document.getElementById("button_iuRHMRgNdi") ? document.getElementById("button_iuRHMRgNdi").innerHTML = '<div class="button"><input onClick="'+data.OnClick+', '+data.Question.Question_ID+', \''+data.OnClick+'\')" title="Vote" alt="Vote" type="button"  value="" class="vote" /></div>' : text +='<div class="bottom" id = "button_iuRHMRgNdi"><div class="button"><input onClick="'+data.OnClick+', '+data.Question.Question_ID+', \''+data.OnClick+'\')" title="Vote" alt="Vote" type="button" value = "" class="vote" /></div></div>';
	return text;
},
getQueryVariable: function(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i < vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }}return ''; },
set_cookie: function ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );
  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }
  if(path) cookie_string += "; path=" + escape ( path );
  if(domain) cookie_string += "; domain=" + escape ( domain );
  if(secure) cookie_string += "; secure";
  document.cookie = cookie_string;
},
get_cookie: function(c)
{ var r = document.cookie.match ( '(^|;) ?' + c + '=([^;]*)(;|$)' );
  if(r)
    return(unescape(r[2]));
  else return null;
}
};
function getUA(url){
	var ua = "";
	switch (navigator.appName.toLowerCase()) {
	case "microsoft internet explorer":var match = navigator.userAgent.match(/\bMSIE\s+(\d+(\.\d+)?)\b/);//(\d+(\.\d+)?)\b/);
	if (match != null) {
		switch (parseFloat(match[1])) {
		case 6:ua = "ie6"; break;
		case 7:ua = "ie7"; break;
	    case 8:ua = "ie8"; break;}} break;
	    case "netscape":if (navigator.userAgent.search(/\bFirefox\b/) != -1) {ua = "ff";
	        } else if (navigator.userAgent.search(/\bChrome\b/) != -1) {ua = "chrome";} break;
	        case "opera":ua = "opera"; break;}
	 return url + "?ua=" + encodeURIComponent(ua);
}
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') 
        window.onload = func;
     else 
        window.onload = function() {
            if (oldonload) 
                oldonload();
            func();}
     }
function JSONscriptRequest(fullUrl) {
    this.fullUrl = fullUrl; 
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;}
JSONscriptRequest.scriptCounter = 1;
JSONscriptRequest.prototype.buildScriptTag = function () {
    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);} 
JSONscriptRequest.prototype.removeScriptTag = function () {
    this.headLoc.removeChild(this.scriptObj);  }
JSONscriptRequest.prototype.addScriptTag = function () {
    this.headLoc.appendChild(this.scriptObj);}
addLoadEvent(function(){
	cs_steelers.loadCss(getUA("http://www.civicscience.com/widgets/steelers/css/ballotbox.css"));cs_steelers.setupGroup();
})