// JavaScript Document
var dc = {
	
	theInputs : [], totalInputs : null,
	theSelects : [], totalSelects : null,                    
	
	//Initialize and call other functions
	init : function () {
	  if(dc.checkCookies() != -1) {return;}
		var theSubmit = document.getElementById('voteButton');
		dc.addEvent(theSubmit, 'click', dc.validateForm);
	},
	
	checkCookies : function() {
  	if(!navigator.cookieEnabled) {
			var warning = document.createElement('div');
			warning.appendChild(document.createTextNode('Cookie Support is Required'));
			warning.className = 'warning';
			var theBody = document.getElementsByTagName('body')[0];
			var firstHeading = document.getElementsByTagName('h1')[0];
			dc.insertAfter (theBody,warning,firstHeading);
			return 0;
		} else {return -1;}
	},
	
	readForm : function () {
		//read form elements
		dc.theInputs = document.getElementsByTagName('input');
		dc.totalInputs = dc.theInputs.length;
    dc.theSelects = document.getElementsByTagName('select');
    dc.totalSelects = dc.theSelects.length;
	},
	
	openWindow : function () {	
		for (var i = 0; i<dc.totalInputs-1; i++) {
			dc.createCookie (dc.theInputs[i].name, dc.theInputs[i].value);
		}
		for (i = 0; i<dc.totalSelects; i++) {
			dc.createCookie (dc.theSelects[i].name, dc.theSelects[i].value);
		}		
		window.open('lab6results.html','_blank','top=40,left=40,width=400,height=400,scrollbars=1,resizable=1,location=1');
	},
	
	validateForm : function (e) {
		dc.readForm();
		var baddata = [];
		var counter = 0;
		for (var i=0;i<dc.totalInputs;i++) {
			switch (dc.theInputs[i].name) {
				case 'voter' : 
					if (dc.theInputs[i].value == '') {baddata[counter] = 'Please provide a name.'; counter++;}
					break;
				case 'email' : 
					var emailaddy = dc.theInputs[i].value;
					emailaddy = emailaddy.match(/^([\w\.\-])+\@(([\w\-])+\.)+([\w]{2,4})+$/);
					if (!emailaddy) {baddata[counter] = 'Please provide a valid email address.'; counter++;}
					break;
				case 'city' :
					if (dc.theInputs[i].value == '') {baddata[counter] = 'Please provide a city.'; counter++;} 
					break;
				case 'state' : 
					var stateAbbr = dc.theInputs[i].value;
					stateAbbr = stateAbbr.match(/^[a-zA-Z]+$/);
					if (!stateAbbr) {baddata[counter] = 'Please enter a valid state abbreviation.'; counter++;}
					break;
				case 'age' : 
					var theAge = dc.theInputs[i].value;
					theAge = theAge.match(/^\d+$/);
					if (!theAge || theAge < 1 || theAge > 130) {baddata[counter] = 'Please provide a valid age.'; counter++;}
					break;
			} 
		}
		for (i=0;i<dc.totalSelects;i++) {
			switch (dc.theSelects[i].name) {
				case 'gender' : 
					if (dc.theSelects[i].selectedIndex <= 0) {baddata[counter] = 'Please select a gender.'; counter++;}
					break;
				case 'choice' : 
					if (dc.theSelects[i].selectedIndex <= 0) {baddata[counter] = 'Please select your candidate.'; counter++;}
					break;
			}							
		}
		if (baddata.length) {
			dc.stopDefault(e);
			
			//create error messages and insert'
			var errors = document.createElement('p');
			errors.appendChild(document.createTextNode('Your poll results could not be processed due to the following errors:'));
			var errorUL = document.createElement('ul');
			errorUL.className = 'errors';
			var errorLI = [];
				for (i=0;i<baddata.length;i++) {
				errorLI[i] = document.createElement('li');
				errorLI[i].appendChild(document.createTextNode(baddata[i]));
				errorUL.appendChild(errorLI[i]); 
			}
			var theBody = document.getElementsByTagName('body')[0];
			var firstHeading = document.getElementsByTagName('h1')[0];
			dc.insertAfter(theBody, errorUL, firstHeading);
			dc.insertAfter(theBody, errors, firstHeading);
		} else {
			dc.openWindow();
		}
		
	},
	 
	insertAfter : function(parent, nodeToInsert, referenceNode) {
  	parent.insertBefore(nodeToInsert, referenceNode.nextSibling);
	},
	
	createCookie : function (name,value,expiration,path,domain,secure) {
  	var data = name + "=" + escape(value);
  	if (expiration) { data += "; expires=" + expiration.toGMTString(); }
  	if (path) { data += "; path=" + path; }
  	if (domain) { data += "; domain=" + domain; }
  	if (secure) { data += "; secure"; }
  	document.cookie = data;
	},
	
	stopDefault : function(e) {
    if (!e) {e = window.event;}
    if (!e.preventDefault) {
    	e.preventDefault = function() { this.returnValue = false; }
    }
    e.preventDefault();
    return false;
	},
	
	// associating nodes with events and functions
   addEvent : function(obj, type, func) {
       if (obj.addEventListener) {obj.addEventListener(type, func, false);}
       else if (obj.attachEvent) {
           obj["e" + type + func] = func;
           obj[type + func] = function() {obj["e" + type + func] (window.event);					 }
           obj.attachEvent("on" + type, obj[type + func]);
       }
       else {obj["on" + type] = func;}
   }
}

dc.addEvent(window, 'load', dc.init);   