// we need these two files to be included
document.write('<scr' + 'ipt src="/js/standardFunctionality/Connect.js">' + '<\/script>');
document.write('<scr' + 'ipt src="/js/standardFunctionality/CanSetCookies.js">' + '<\/script>');
document.write('<scr' + 'ipt src="/js/standardFunctionality/FormValues.js">' + '<\/script>');

var canSubmit = 1;
var totalVotes = 0;
window.onload = ResetVariable;

function ResetVariable(){
	canSubmit = 1;
	
}

function EraseAnswers(pnid){
	var theForm = document.getElementById("poll_form_" + pnid);
	// loop through each field and get create a query string for it
    for (var i = 0; i < theForm.elements.length; i++) {
	    var type = theForm.elements[i].type;
		if((type == "checkbox") || (type == "radio")){
			SetFormElementValue(theForm.elements[i],"");	
		}
    }
}

function SubmitForm(pnid){

	// get the form
	var theForm = document.getElementById("poll_form_" + pnid);
	if(canSubmit){
		// don't want to record a vote unless we know cookies are enabled
		var canSetCookie = CanSetCookies();
		theForm.cookiesEnabled.value=canSetCookie;
		canSubmit = 0;
		
		// get the query string for this form
		var queryString = GetQueryStringForForm(theForm) + "&ajax=true"; 
		
		//make a request to the poll CGI to process the form data
		var pollCGI = '/cgi-bin/Poll.pl';
		var connection = new Connect();
		// handle the response
		var myFunction = function (xmlObject) { 
			document.getElementById("Poll_" + pnid).innerHTML = xmlObject.responseText;
			ResetVariable();
		};
		connection.connect(pollCGI,"POST",queryString,myFunction);
	}
}



function TotalVotes(checkbox,maxTotalVotes) {
	if (checkbox.checked == true) {
		totalVotes++;
	} else if (checkbox.checked == false) {
		totalVotes--;
	}
	if (totalVotes > maxTotalVotes) {
		checkbox.checked = false;
		totalVotes--;		
		alert("You can only select up to " + maxTotalVotes + " items.");
	}
}	

function InsertPoll(currentPoll){
	var display = "pollForms";
	// let's figure out if we are going to display the form or the results
	var pollsTaken = Get_Cookie("PollsTaken");
	if(pollsTaken){
		var pollsTakenA = pollsTaken.split("|");
		// loop through all the different polls we have stored in the cookie
		for (i = 0 ; i < pollsTakenA.length; i++){
			if(pollsTakenA[i]){
				var pollsTakenDataA = pollsTakenA[i].split(":");
				// parse out the time to expire and poll id
				var timeToExpire = pollsTakenDataA[0];
				var pollID = pollsTakenDataA[1];
				
				// if the poll we are looping through is the same as the poll that should be displayed to the user
				if(pollID == currentPoll){
					var epochTime = (new Date().getTime())/1000;
					// check to see if they should get the poll result or the pollForm
					if(timeToExpire > epochTime){
						display = "pollResults";
					}
					
				}
			}
		}
	}
	var pollHTMLPath = "/components/utilities/polls/" + display + "/" + currentPoll + ".html";
	var connection = new Connect();
	var myFunction = function (xmlObject) { 
		document.getElementById("Poll_" + currentPoll).innerHTML = xmlObject.responseText;
		pollFillValidator();
	};
	connection.connect(pollHTMLPath,"GET","",myFunction);
}


function GetQueryStringForForm( form ) {
    var valueString = "";

	// loop through each field and get create a query string for it
    for (var i = 0; i < form.elements.length; i++) {
	    var field = form.elements[i];
		var value = "";
        if (!field.disabled) {
			value = GetFormElementValue(field);
			if(value){
           		valueString += ((i) ? '&' : '') + field.name + '=' + escape(value);
			}
        }
    }

    return valueString;
}

function randomString(string_length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

function pollFillValidator()
{
	//NOTE: this will run once for each poll on the page.  There's really no way around this without 
	//editing the javascript outputted by the poll generator.

	//get all our inputs
	var inputs = document.getElementsByTagName("INPUT");
	for( var input_index = 0; input_index < inputs.length; input_index++ ){
		//get the current ID
		var pnid = inputs[input_index].id;
		if( pnid ){
			//if this input even has an ID...
			if( pnid.substring(0,15) == 'poll_validator_'){
				//found one.  get just the ID
				pnid = pnid.substring(15);
				
				var randomStr = randomString(10);
				
				//update the hidden field
				document.getElementById('poll_validator_' + pnid).value = randomStr;
				
				//add this validator to the current set
				var poll_str = readCookie('poll_validator');
				if( poll_str ){
					//they have a cookie
					
					//get all their polls into an associative array
					polls = poll_str.split(',');
					var assoc_polls = new Array();
					for( var i = 0; i < polls.length; i++ ){
						var poll = polls[i].split(':');
						assoc_polls[poll[0]] = poll[1];
					}
					
					//add or overwrite the current poll
					assoc_polls[pnid] = randomStr;
					
					//pack the array back into a str.
					var cookieValue = '';
					for( assoc_polls_key in assoc_polls ){
						cookieValue += assoc_polls_key + ':' + assoc_polls[assoc_polls_key] + ',';
					}
					cookieValue = cookieValue.substring(0,cookieValue.length -1);
					
					//update the cookie
					createCookie('poll_validator', cookieValue, 30);
				}else{
					//no cookie
					createCookie('poll_validator', pnid + ':' + randomStr, 30);
				}
			}
		}
	}
}

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=/;domain=.nwsource.com";
}

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;
}
