var hours;
var days;
var intervals;
var hourTypes;
var hourSections;
var counties;
var numCounties;
var errorClass = "input-label-error";
var noErrorClass = "input-label";
var selectedCounty = "Dallas";
var yearstart=1920;

function load() {
	counties = new Array(
"Anderson", "Andrews", "Angelina", "Aransas", "Archer", "Armstrong", "Atascosa", "Austin",
"Bailey", "Bandera", "Bastrop", "Baylor", "Bee", "Bell", "Bexar", "Blanco", "Borden", "Bosque", "Bowie", "Brazoria", "Brazos", "Brewster", "Briscoe", "Brooks", "Brown", "Burleson", "Burnet",
"Caldwell", "Calhoun", "Callahan", "Cameron", "Camp", "Carson", "Cass", "Castro", "Cambers", "Cherokee", "Childress", "Clay", "Cochran", "Coke", "Coleman", "Collin", "Collinsworth", "Colorado", "Comal", "Comanche", "Concho", "Cooke", "Coryell", "Cottle", "Crane", "Crockett", "Cosby", "Culberson",
"Dallam", "Dallas", "Dawson", "Deaf Smith", "Delta", "Denton", "Dewitt", "Dickens", "Dimmit", "Donley", "Duval",
"Eastland", "Ector", "Ellis", "El Paso", "Erath",
"Falls", "Fannin", "Fayette", "Fisher", "Floyd", "Foard", "Fort Bend", "Franklin", "Freestone", "Frio",
"Gaines", "Galveston", "Garza", "Gillespie", "Glasscock", "Golaid", "Gonzales", "Gray", "Grayson", "Gregg", "Grimes", "Guadalupe",
"Hale", "Hall", "Hamilton", "Hansford", "Hardeman", "Hardin", "Harris", "Harrison", "Hartley", "Haskell", "Hays", "Hemphill", "Henderson", "Hidalgo", "Hill", "Hockley", "Hood", "Hopkins", "Houston", "Howard", "Hudspeth", "Hunt", "Hutchinson",
"Irion",
"Jack", "Jackson", "Jasper", "Jeff Davis", "Jefferson", "Jim Hogg", "Jim Wells", "Johnson", "Jones", "Karnes", "Kaufman", "Kendall", "Kenedy", "Kent", "Kerr", "Kimble", "King", "Kinney", "Kleberg", "Knox",
"Lamar", "Lamb", "Lampasas", "La Salle", "Lavaca", "Lee", "Leon", "Liberty", "Limestone", "Lipscomb", "Live Oak", "Llano", "Loving", "Lubbock", "Lynn",
"McColloch", "McLennan", "McMullen", "Madison", "Marion", "Martin", "Mason", "Matagorda", "Maverick", "Medina", "Menard", "Midland", "Milam Mills", "Mitcell", "Montague", "Montgomery", "Moore", "Morris", "Motley",
"Nacogdoches", "Navarro", "Newton", "Nolan", "Nueces",
"Ochiltree", "Oldham", "Orange",
"Palo Pinto", "Panola", "Parker", "Parmer", "Pecos", "Polk", "Potter", "Presidio",
"Rains", "Randall", "Reagan", "Real", "Red River", "Reeves", "Refugio", "Roberts", "Robertson", "Rockwall", "Runnels", "Rusk",
"Sabine", "San Augustine", "San Jacinto", "San Patricio", "San Saba", "Schleicher", "Scurry", "Shackelford", "Shelby", "Sherman", "Smith", "Somervell", "Starr", "Stephens", "Sterling", "Stonewall", "Sutton", "Swisher",
"Tarrant", "Taylor", "Terrell", "Terry", "Throckmorton", "Titus", "Tom Green", "Travis", "Trinity", "Tyler",
"Upshur", "Upton", "Uvalde",
"Val Verde", "Van Zandt", "Victoria",
"Walker", "Waller", "Ward", "Washington", "Webb", "Wharton", "Wheeler", "Wichita", "Wilbarger", "Wellacy", "Williamson", "Wilson", "Winkler", "Wise", "Wood",
"Yoakum", "Young",
"Zapata", "Zavala"
	);
	
	var detail_birth_day = document.getElementById("detail_birth_day").options;
	var detail_arrested_on_day = document.getElementById("detail_arrested_on_day").options;
	detail_birth_day.length = 31;
	detail_arrested_on_day.length = 31;
	
	for ( var i=0; i<31; i++ ) {
		detail_birth_day[i].text = ""+(i+1);
		detail_arrested_on_day[i].text = ""+(i+1);
	}
	
	var yearend = 2006;
//	var date = new Date();
//	var yearend=date.getYear();

	var detail_birth_year = document.getElementById("detail_birth_year").options;
	var detail_arrested_on_year = document.getElementById("detail_arrested_on_year").options;
	detail_birth_year.length = yearend-yearstart+1;
	detail_arrested_on_year.length = yearend-yearstart+1;
	for ( var i=yearend; i>=yearstart; i-- ) {
		detail_birth_year[yearend-i].text = ""+(i);
		detail_arrested_on_year[yearend-i].text = ""+(i);
	}
	detail_birth_year[0].selected = true;
	detail_arrested_on_year[0].selected = true;
	
	var countyOptions = document.getElementById("county_1").options;
	var countyMoreOptions = document.getElementById("county_more").options;
	var detail_arrested_in = document.getElementById("detail_arrested_in").options;
	var detail_resident = document.getElementById("detail_resident").options;
	
	detail_arrested_in.length = counties.length;
	detail_resident.length = counties.length;
	countyOptions.length = counties.length;
	countyMoreOptions.length = counties.length+1;
	countyMoreOptions[0].text = "more...";
	numCounties = 1;
	
	var selectedIndex = 0;
	for ( var i=0; i<counties.length; i++ ) {
		if ( counties[i] == selectedCounty ) {
			selectedIndex = i;
		}
		countyOptions[i].text=counties[i];
		detail_arrested_in[i].text=counties[i];
		detail_resident[i].text=counties[i];
		countyMoreOptions[i+1].text=counties[i];
	}
	
	countyOptions[selectedIndex].selected = true;
	detail_arrested_in[selectedIndex].selected = true;
	detail_resident[selectedIndex].selected = true;
	
	days = new Array();
	days[days.length] = "monday";
	days[days.length] = "tuesday";
	days[days.length] = "wednesday";
	days[days.length] = "thursday";
	days[days.length] = "friday";
	days[days.length] = "saturday";
	days[days.length] = "sunday";
	
	hourSections = new Array();
	for ( var i=0; i<days.length; i++ ) {
		hourSections[hourSections.length] = 1;
	}

	intervals = new Array();
	intervals[intervals.length] = "00";
	intervals[intervals.length] = "15";
	intervals[intervals.length] = "30";
	intervals[intervals.length] = "45";
	
	var ampm = new Array();
	ampm[ampm.length] = "am";
	ampm[ampm.length] = "pm";
	
	hours = new Array();
	for ( var i=0; i<ampm.length; i++ ) {
		for ( var j=0; j<12; j++ ) {
			for ( var k=0; k<intervals.length; k++ ) {
				var hour = j;
				if ( hour == 0 ) {
					hour = 12;
				}
				hours[hours.length] = hour+":"+intervals[k]+ampm[i];
			}
		}	
	}
	
	hourTypes = new Array();
	hourTypes[hourTypes.length] = "from";
	hourTypes[hourTypes.length] = "to";
	
	for ( var k=0; k<days.length; k++ ) {
		updateHoursDiv(k);
		addMoreDiv(k);
	}
}

function updateHoursDiv(dayId,section) {
	var k=dayId;
	for ( var i=0; i<hourTypes.length; i++ ) {
		var formOptions = document.getElementById("hours_"+days[k]+"_"+hourTypes[i]+"_"+hourSections[dayId]);
		formOptions.options.length = hours.length;
		for ( var j=0; j<hours.length; j++ ) {
			formOptions.options[j].text = hours[j];
		}
	}
	
}

function addMoreDiv(dayId) {
	var k = dayId;		
	var formOptions = document.getElementById("hours_"+days[k]+"_from_more");
	formOptions.options.length = hours.length+1;
	formOptions.options[0].text="more...";
	for ( var j=0; j<hours.length; j++ ) {
		formOptions.options[j+1].text = hours[j];
	}
}

function updateHours(formField) {
	updateHoursByName( formField.name );
}

function updateHoursByName ( formField ) {
	var dayId;
	
	for ( var i=0; i<days.length && !dayId; i++ ) {
		if( formField.indexOf(days[i]) >= 0 ) {
			dayId = i;
		}
	}
	
	//adjust the 'to' time if needed
	var maxTime = 0;
	for ( var i=0; i<hourSections[dayId]; i++ ) {
		if ( document.getElementById("hours_"+days[dayId]+"_from_"+(i+1)) ) {
			var fromIndex = document.getElementById("hours_"+days[dayId]+"_from_"+(i+1)).options.selectedIndex;
			if ( fromIndex < maxTime ) {
				fromIndex = maxTime;
			}
			var toIndex = document.getElementById("hours_"+days[dayId]+"_to_"+(i+1)).options.selectedIndex;	
			if ( fromIndex > toIndex ) {
				toIndex=fromIndex;
			}
			document.getElementById("hours_"+days[dayId]+"_from_"+(i+1)).options[fromIndex].selected = true;
			document.getElementById("hours_"+days[dayId]+"_to_"+(i+1)).options[toIndex].selected = true;
			maxTime = toIndex;
		}
	}
	
	updateTotal(dayId);
	
	return maxTime;
}

function updateMoreHours(formField) {

	var maxTime = updateHours(formField);
	
	var dayId;
	
	for ( var i=0; i<days.length && !dayId; i++ ) {
		if( formField.name.indexOf(days[i]) > 0 ) {
			dayId = i;
		}
	}
	hourSections[dayId]++;
	
	var selectedTime = document.getElementById("hours_"+days[dayId]+"_from_more").options.selectedIndex;
	if (selectedTime == 0) {
		return;
	}
	selectedTime--;
	
	if ( selectedTime < maxTime ) {
		selectedTime = maxTime;
	}

	var newSection = hourSections[dayId];
	
	//create a new section
	
	var topElement = document.createElement("div");
	topElement.setAttribute("id","hours_"+days[dayId]+"_"+newSection);
	
	var fromLabel = document.createElement("label");
	fromLabel.setAttribute("for","hours_"+days[dayId]+"_from_"+hourSections[dayId]);
	fromLabel.setAttribute("id","hours_"+days[dayId]+"_from_"+hourSections[dayId]+"_label");
	fromLabel.appendChild(document.createTextNode("From: "));
	topElement.appendChild(fromLabel);
	
	var fromSelect = document.createElement("select");
	fromSelect.setAttribute("id","hours_"+days[dayId]+"_from_"+hourSections[dayId]);
	fromSelect.setAttribute("name","hours_"+days[dayId]+"_from_"+hourSections[dayId]);
	fromSelect.onchange="updateHoursByName('"+days[dayId]+"')";
	var onChangeHandler = new Function(fromSelect.onchange);
	if (fromSelect.addEventListener) {
	    fromSelect.addEventListener('change', onChangeHandler, false );
	} else if (fromSelect.attachEvent) {
	    fromSelect.attachEvent('onchange', onChangeHandler);
	} 
	topElement.appendChild(fromSelect);
	
	var toLabel = document.createElement("label");
	toLabel.setAttribute("for","hours_"+days[dayId]+"_to_"+hourSections[dayId]);
	toLabel.setAttribute("id","hours_"+days[dayId]+"_to_"+hourSections[dayId]+"_label");
	toLabel.appendChild(document.createTextNode(" Until: "));
	topElement.appendChild(toLabel);
	
	var toSelect = document.createElement("select");
	toSelect.setAttribute("id","hours_"+days[dayId]+"_to_"+hourSections[dayId]);
	toSelect.setAttribute("name","hours_"+days[dayId]+"_to_"+hourSections[dayId]);
	toSelect.onchange="updateHoursByName('"+days[dayId]+"')";
	var onChangeHandler = new Function(toSelect.onchange);
	if (toSelect.addEventListener) {
	    toSelect.addEventListener('change', onChangeHandler, false );
	} else if (toSelect.attachEvent) {
	    toSelect.attachEvent('onchange', onChangeHandler);
	} 
	topElement.appendChild(toSelect);
	
	var removeLink = document.createElement("a");
	removeLink.setAttribute("href","javascript:removeSection("+hourSections[dayId]+","+dayId+");");
	removeLink.appendChild(document.createTextNode("Remove"));
	topElement.appendChild(removeLink);
	
	var insertThing = document.getElementById("hours_"+days[dayId]);
	var total = insertThing.removeChild(document.getElementById("hours_"+days[dayId]+"_total"));
	var more = insertThing.removeChild(document.getElementById("hours_"+days[dayId]+"_more"));
	insertThing.appendChild(topElement);
	insertThing.appendChild(more);
	insertThing.appendChild(total);
	
	updateHoursDiv(dayId);

	document.getElementById("hours_"+days[dayId]+"_from_"+hourSections[dayId]).options[selectedTime].selected=true;
	document.getElementById("hours_"+days[dayId]+"_to_"+hourSections[dayId]).options[selectedTime].selected=true;
	document.getElementById("hours_"+days[dayId]+"_from_more").options[0].selected=true;
	
//	updateTotal(dayId);
}

function removeSection(section,dayId) {
	
	var insertThing = document.getElementById("hours_"+days[dayId]);
	insertThing.removeChild(document.getElementById("hours_"+days[dayId]+"_"+section));
	
}

function updateTotal (dayId) {
	//tally total
	var total=0;
	for ( var i=0; i<hourSections[dayId]; i++ ) {
		if ( document.getElementById("hours_"+days[dayId]+"_from_"+(i+1)) ) {
			var fromIndex = document.getElementById("hours_"+days[dayId]+"_from_"+(i+1)).options.selectedIndex;
			var toIndex = document.getElementById("hours_"+days[dayId]+"_to_"+(i+1)).options.selectedIndex;	
			total += toIndex-fromIndex;
		}
	}
	
	var tooMuchTime = false;
	if ( total > (intervals.length*12) ){
		tooMuchTime = true;
	}
	
	var hours = Math.floor(total/intervals.length);
	var minutes = total%intervals.length;
	
	var timeArea = document.getElementById("hours_"+days[dayId]+"_total");
	timeArea.removeChild ( timeArea.childNodes[0] );
	timeArea.appendChild ( document.createTextNode("Total: "+hours+":"+intervals[minutes]+"hrs") );
	if ( tooMuchTime ) {
		timeArea.className="hours-bad";
	} else {
		timeArea.className="hours-good";
	}	
	
	return total;
	
}

function updateMoreCounties( formField ) {
	var moreCounty = document.getElementById("county_more").options.selectedIndex;
	
	if ( moreCounty == 0 ) {
		return;
	}
	moreCounty--;
	
	var moreArea = document.getElementById("counties").removeChild(document.getElementById("county_more_area"));
	
	numCounties++;
	
	var nextCounty = document.createElement("div");
	nextCounty.setAttribute("id","county_area_"+numCounties);
	nextCounty.appendChild(document.createTextNode("County: "));
	var nextCountySelect = document.createElement("select");
	nextCountySelect.setAttribute("id","county_"+numCounties);
	nextCounty.appendChild(nextCountySelect);
	var removeLink = document.createElement("a");
	removeLink.setAttribute("href","javascript:removeCounty("+numCounties+");");
	removeLink.appendChild(document.createTextNode("Remove"));
	nextCounty.appendChild(removeLink);
	
	
	document.getElementById("counties").appendChild(nextCounty);
	document.getElementById("counties").appendChild(moreArea);
	
	var countyOptions = document.getElementById("county_"+numCounties).options;
	
	countyOptions.length = counties.length;
	for ( var i=0; i<counties.length; i++ ) {
		countyOptions[i].text=counties[i];
	}
	countyOptions[moreCounty].selected = true;
	
	document.getElementById("county_more").options[0].selected = true;
	
}

function removeCounty(countyId) {
	document.getElementById("counties").removeChild(document.getElementById("county_area_"+countyId));
}

function validate() {
	var allGood = true;
	
	allGood = validateText("detail_name") && allGood;
	allGood = validateText("detail_license") && allGood;
	allGood = validateText("detail_occupation") && allGood;
	allGood = validateText("detail_arrested_num") && allGood;
	allGood = validateCheckbox("detail_understand") && allGood;
	
	for ( var i=0; i<days.length; i++ ) {
		var total = updateTotal ( i );
		if ( total > ( intervals.length * 12 ) ) {
			allGood = false;
		}
	}
	return allGood;
}

function validateCheckbox(textName) {
	if ( !document.getElementById(textName).checked ) {
		document.getElementById(textName+"_label").className = errorClass;
		return false;
	} else {
		document.getElementById(textName+"_label").className = noErrorClass;
	}
	return true;
		
}

function validateText(textName) {
	if ( document.getElementById(textName).value == "" ) {
		document.getElementById(textName+"_label").className = errorClass;
		return false;
	} else {
		document.getElementById(textName+"_label").className = noErrorClass;
	}
	return true;
		
}

function submitInfo() {

	if ( !validate() ) {
		window.scrollTo(0,0);
		alert("There were errors processing your form, please correct the items in red.");
		return;
	}

	var NL = "NEWLINE";
	
	var subInfo = "";
	subInfo += NL;
	subInfo += "Name: "+document.getElementById("detail_name").value;
	subInfo += NL;
	subInfo += "Resident of county: "+getSelectedValue("detail_resident");
	subInfo += NL;
	subInfo += "DOB: "+getSelectedValue("detail_birth_month");
	subInfo += " "+getSelectedValue("detail_birth_day");
	subInfo += ", "+getSelectedValue("detail_birth_year");
	subInfo += NL;
	subInfo += "DL: "+getSelectedValue("detail_license_state");
	subInfo += " "+document.getElementById("detail_license").value;
	subInfo += NL;
	subInfo += "Arrested in county: "+getSelectedValue("detail_arrested_in");
	subInfo += NL;
	subInfo += "Arrested on: "+getSelectedValue("detail_arrested_on_month");
	subInfo += " "+getSelectedValue("detail_arrested_on_day");
	subInfo += ", "+getSelectedValue("detail_arrested_on_year");
	subInfo += NL;
	subInfo += "Case number: "+document.getElementById("detail_arrested_num").value;
	subInfo += NL;
	subInfo += "Occupation: "+document.getElementById("detail_occupation").value;
	subInfo += NL;
	subInfo += "Gave breath/blood: "+( document.getElementById("detail_breath_yes").checked ? "Yes" : "No" );
	subInfo += NL;

	var timeInfo = "";
	timeInfo += NL;
	for ( var i=0; i<days.length; i++ ) {
		timeInfo += capitalizeMe(days[i]);
		timeInfo += NL;
		for ( var j=0; j<hourSections[i]; j++ ) {
			timeInfo += getSelectedValue("hours_"+days[i]+"_from_"+(j+1));
			timeInfo += " through ";
			timeInfo += getSelectedValue("hours_"+days[i]+"_to_"+(j+1));	
			timeInfo += NL;
		}	
		timeInfo += NL;
	}
	
	var countyInfo = "";
	countyInfo += NL;
	countyInfo += "Counties wish to drive in: ";
	countyInfo += NL;
	countyInfo += getSelectedValue("county_1");
	for ( var i=1; i<numCounties; i++ ) {
		if ( document.getElementById("county_"+(i+1)) ) {
			countyInfo += ", "+getSelectedValue("county_"+(i+1));
		} 
	}
	
	document.getElementById("mailtext").value=subInfo+timeInfo+countyInfo;
//	alert(document.getElementById("mailtext").value);
	document.forms["tosend"].submit();
}

function getSelectedValue(idName) {
	try {
   		return document.getElementById(idName).options[document.getElementById(idName).options.selectedIndex].text
   	} catch(err) {
		alert(idName+" unknown");
		return "";
	}
}

function capitalizeMe(val) {
        newVal = '';
        val = val.split(' ');
        for(var c=0; c < val.length; c++) {
                newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + ' ';
        }
        return newVal;
}