﻿var baseUrl = 'http://www.210computing.com/qp/quickPoll.aspx';
//var baseUrl = 'http://localhost/quickpoll/quickPoll.aspx';
addLoadEvent(setupPoll);
var allRequests = new Array();
var allPollDiv = new Array();

function setupPoll()
{
    var allDivs = document.getElementsByTagName('div');
    for (var i =0;i<allDivs.length;i++)
    {
        
        if ((name = allDivs[i].getAttribute('pollName')))
        {   
            //If we find a poll element, put it into the allPolls array
            //
            
            //allRequests[name] = createXMLDoc();
//            if (!allRequests[name])
//            {    
//                alert('sorry, XMLHTTP not supported');
//                return;
//            }
            //allRequests[name].replaceDiv = allDivs[i];
            allPollDiv[name] = allDivs[i];
            var url = buildUrl(allDivs[i]);
            
            //don't read/set cookie by poll name, but by poll key
            if (readCookie(getPollKey(name)) && document.location.href.indexOf('pollTest') == -1)
                url += '&display=true';
                
                
            //alert(url);
            //loadXMLDoc(allRequests[name], url);
            
            //document.write('<script src="http://localhost/QuickPoll/js/callback.js" type="text/javascript" />');
            //TODO remove after testing
            //url += '&display=true';
            dyn_script(url);
        }
    }
}
function pollCallback(pollName)
{
    allPollDiv[pollName].innerHTML = htmlInject();
}
//thanks http://the-lastword.blogspot.com/2006/05/json-and-dynamic-tag.html
function dyn_script(url){
     var script=document.createElement('script'); // pretty self explanatory
     script.src=url; // sets the scripts source to the specified url
     script.type="text/javascript";
   
    document.getElementsByTagName('head')[0].appendChild(script); // appends the tag to the head
}

function buildUrl(pollObj)
{
    var url = baseUrl + '?name=';
        url += pollObj.getAttribute('pollName');
        url += '&options=';
        url += pollObj.getAttribute('pollOptions');
   return url;
        
}
    
function vote(refObj)
{

    //alert(refObj.parentNode.parentNode.parentNode.getAttribute('pollName'));
    //return;
    var pollDiv = refObj.parentNode.parentNode.parentNode;
    var pollName = pollDiv.getAttribute('pollName')
    var allDivs = document.getElementsByTagName('div');
//    for (var i =0;i<allDivs.length;i++)
//    {
//        if (allDivs[i].getAttribute('pollName') == pollName)
//            pollDiv = allDivs[i];
//    }

    var allRadio = pollDiv.getElementsByTagName('input');
    var voteValue;
    for (var i = 0; i< allRadio.length; i++)
    {
        if (allRadio[i].checked)
            voteValue = allRadio[i].value;
    }
    var url = buildUrl(pollDiv);
    if (!voteValue)
    {
        alert('You did not vote. We will just show you the poll results.');
        url += '&display=true';
    }
    else{
        
        createCookie(getPollKey(pollName), 'true', 1000);
        url += '&vote=';
        url += voteValue;        
    }
    dyn_script(url);
    //loadXMLDoc(allRequests[pollName], url);

}
    
function getPollKey(pollName)
{
    var allDivs = document.getElementsByTagName('div');
    var pollKey = pollName;
    for (var i=0; i<allDivs.length; i++)
    {
        if (pollName == allDivs[i].getAttribute('pollname'))
        {
            var pollOptions = allDivs[i].getAttribute('polloptions');
            var pollOptions = pollOptions.split(',');
            for (var j = 0; j<pollOptions.length; j++)
                pollKey += pollOptions[j];
                
        }
    }
    
    return pollKey;
}
//From http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}    

//from http://developer.apple.com/internet/webcontent/xmlhttpreq.html   
//function createXMLDoc()
//{
//    req = false;
//    // branch for native XMLHttpRequest object
//    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
//    	try {
//			req = new XMLHttpRequest();
//        } catch(e) {
//			req = false;
//        }
//    // branch for IE/Windows ActiveX version
//    } else if(window.ActiveXObject) {
//       	try {
//        	req = new ActiveXObject("Msxml2.XMLHTTP");
//      	} catch(e) {
//        	try {
//          		req = new ActiveXObject("Microsoft.XMLHTTP");
//        	} catch(e) {
//          		req = false;
//        	}
//		}
//    }
//    
//    return req;
//}
//function loadXMLDoc(req, url) {
//	
//	if(req) {
//		req.onreadystatechange = processReqChange;
//		req.open("GET", url, true);
//		req.send("");
//	}
//}

//function processReqChange() {
//    // only if req shows "loaded"
//    if (req.readyState == 4) {
//        // only if "OK"
//        req.replaceDiv.innerHTML = req.responseText;
//        
//    }
//}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}