// JavaScript Document

function calculateSubtotal(suffix) {
	var subtotal = (parseInt($("quantity_" + suffix).value) * parseInt($("price_" + suffix).value * 100)) / 100;
	$("subtotal_" + suffix).value = "$" + subtotal.toFixed(2);
	var pFields = ['card', 'additional_card', 'records_kit', 'lanyard', 'molly_meerkat_plush', 'safetyville_board_game', '60pc_home_safety_kit'];
	var totalSubtotal = 0;
	var totalAdditionalShipping = 0;
	for (var i = 0; i < pFields.length; i++) {
		totalSubtotal += $('quantity_' + pFields[i]).value * $('price_' + pFields[i]).value;
		if (i == 5 || i == 6) {
			// Board Game or Safety Kit
			totalAdditionalShipping += 5.95 * $('quantity_' + pFields[i]).value;
		}
		if (i == 2 || i == 3) {
			// Records Kit or Lanyard
			totalAdditionalShipping += 1.95 * $('quantity_' + pFields[i]).value;
		}
		if (i == 4) {
			// Molly Meerkat
			totalAdditionalShipping += 3.95 * $('quantity_' + pFields[i]).value;
		}
	}
	$('order_subtotal').value = "$" + totalSubtotal.toFixed(2);
	$('additional_shipping').value = totalAdditionalShipping.toFixed(2);
	$('order_additional_shipping').value = "$" + totalAdditionalShipping.toFixed(2);
	$('order_tax').value = "$" + (totalSubtotal * .07).toFixed(2);
	if ($('safenowproject_donation_check').checked == true) {
		var safenowproject_donation = 100;
	} else {
		var safenowproject_donation = 0;
	}
	// Calculate 7% Tax
	//$('order_total').value = "$" + (((parseInt(totalSubtotal * 100)) + ((parseInt(Math.round(parseInt(totalSubtotal * 100) * .07)))) + parseInt($('shipping').value * 100) + parseInt($('additional_shipping').value * 100) + safenowproject_donation) / 100).toFixed(2);
	// No Tax
	$('order_total').value = "$" + (((parseInt(totalSubtotal * 100)) + ((parseInt(Math.round(parseInt(totalSubtotal * 100) * .00)))) + parseInt($('shipping').value * 100) + parseInt($('additional_shipping').value * 100) + safenowproject_donation) / 100).toFixed(2);
}

function fetchCities(state) {
	// Fetch DAta
	new Ajax.Request('fetch_cities.html',
		{
			method: 'get',
			parameters: {state: state},
			onSuccess: function(transport) {
				var myjson = transport.responseText.evalJSON(true);
				populateCities(myjson);
			},
			onFailure: function() { alert('Something went wrong...') }
		});
}

function populateCities(data) {	
	// reset child Selects
	resetSelect('city');
	resetSelect('school');
	
	// add new elms
	var num_cities = data.cities.length;
	for (var i = 0; i < num_cities; i++) {
		$('city').options[i+1] = new Option(data.cities[i].name, data.cities[i].name);
	}
}

function fetchSchools(city, state) {
	// Fetch DAta
	new Ajax.Request('fetch_schools.html',
		{
			method: 'get',
			parameters: {city: city, state: state},
			onSuccess: function(transport) {
				var myjson = transport.responseText.evalJSON(true);
				populateSchools(myjson);
			},
			onFailure: function() { alert('Something went wrong...') }
		});
}

function populateSchools(data) {	
	// reset child Selects
	resetSelect('school');
	
	// add new elms
	var num_schools = data.schools.length;
	for (var i = 0; i < num_schools; i++) {
		$('school').options[i+1] = new Option(data.schools[i].name, data.schools[i].school_id);
	}
}

function schoolSelected() {
	if ($('school').selectedIndex != 0) {
		$('continue').show();	
	} else {
		$('continue').hide();	
	}
}

function resetSelect(id) {
	// reset child Selects
	$(id).selectedIndex = 0;
	
	if (id == 'school') {
		$('continue').hide();	
	}
	
	// remove all elms
	var lastOption = $(id).options.length - 1;
	while (lastOption > 0) {
		$(id).options[lastOption] = null;
		lastOption--;
	}
}

function verifyForm(id, Obj) {
	if ($('confirmed').checked == false) {
		alert("You must review your order for mistakes/typos and confirm by checking the box above the Add to Cart button");
		return false;
	}
	var invalidFields = [];
	if (Obj.images.length > 0) {
		for (var i = 0; i < Obj.images.length; i++) {
			if (!validateImage($(Obj.images[i]))) {
				return false;	
			}
		}
	}
	for (var i = 0; i < Obj.fields.length; i++) {
		if ($(Obj.fields[i]).value == "") {
			invalidFields.push(Obj.fields[i]);	
		}
	}
	if (invalidFields.length > 0) {
		alert("You must fill out all required fields");
		return false;
	}
	return true;	
}

function verifyFormProgram(id, Obj) {
	var invalidFields = [];
	if ($('program_a').checked == false && $('program_b').checked == false) {
		alert("You must select a program.");
		return false;
	}
	if (Obj.images.length > 0) {
		for (var i = 0; i < Obj.images.length; i++) {
			if (!validateImage($(Obj.images[i]))) {
				return false;	
			}
		}
	}
	for (var i = 0; i < Obj.fields.length; i++) {
		if ($(Obj.fields[i]).value == "") {
			invalidFields.push(Obj.fields[i]);	
		}
	}
	if (invalidFields.length > 0) {
		alert("You must fill out all required fields");
		return false;
	}
	if ($('program_b').checked == true) {
		if ($('enrollment_form_due_date').value == '') {
			alert("You must specify an enrollment form due date.");
			return false;
		}
		if ($('checks_payable_to').value == '') {
			alert("You must specify who the checks should be payable to.");
			return false;
		}
	}
	return true;	
}

function validateImage(image_id) {
	var img = $(image_id).value;
	if (img != '') {
		var ext = img.substring(img.length-3,img.length);
		ext = ext.toLowerCase();
		if (ext != 'jpg') {
			alert('You selected a .'+ext+' file; please select a .jpg file instead!');
			return false;
		} else {
			return true;
		}
	} else {
		alert('You must select a file to upload.');
		return false;	
	}
}

function checkFRForm() {
	if ($('first_name').value == "") {
		alert("You must enter a first name.");
		return false;
	}
	if ($('last_name').value == "") {
		alert("You must enter a last name.");
		return false;
	}
	if ($('group_name').value == "") {
		alert("You must enter a group name.");
		return false;
	}
	if ($('address').value == "") {
		alert("You must enter an address.");
		return false;
	}
	if ($('city').value == "") {
		alert("You must enter a city.");
		return false;
	}
	if ($('state').value == "") {
		alert("You must enter a state.");
		return false;
	}
	if ($('zip').value == "") {
		alert("You must enter a zipcode.");
		return false;
	}
	if ($('fundraising_goal').value == "") {
		alert("You must select a fundraising goal.");
		return false;
	}
	if ($('card_type').value == "") {
		alert("You must select a card type.");
		return false;
	}
	if ($('start_date').value == "") {
		alert("You must select a start date.");
		return false;
	}
	if ($('end_date').value == "") {
		alert("You must select an end date.");
		return false;
	}	
	if ($('email').value == "") {
		alert("You must enter an email address.");
		return false;
	}
	if ($('email').value != $('email_confirm').value) {
		alert("Email addresses must match!");
		return false;	
	}
	if (($('phone_home_areacode') == '555') || ($('phone_cell_areacode') == '555') || ($('phone_work_areacode') == '555')) {
		alert("Areacode can not be 555 for any phone number.");	
	}
	if (($('phone_home_areacode').value == $('phone_work_areacode').value) && ($('phone_work_areacode').value == $('phone_cell_areacode').value) && ($('phone_home_areacode').value == $('phone_cell_areacode').value) && ($('phone_home_prefix').value == $('phone_work_prefix').value) && ($('phone_home_prefix').value == $('phone_cell_prefix').value) && ($('phone_cell_prefix').value == $('phone_work_prefix').value) && ($('phone_home_suffix').value == $('phone_work_suffix').value) && ($('phone_cell_suffix').value == $('phone_work_suffix').value) && ($('phone_home_suffix').value == $('phone_cell_suffix').value)) {
		alert("All three phone numbers can not be the same.");	
		return false;
	}
	
	
	
	
	return true;
}

function calculateFRCards() {
	if ($('fundraising_goal').value != '') {
		$('card_quantity').value = $('fundraising_goal').value / 100;
	} else {
		$('card_quantity').value = '';	
	}
}

function popEndDate(two_weeks_date_label, two_weeks_date, four_weeks_date_label, four_weeks_date, six_weeks_date_label, six_weeks_date) {
	var endDateSel = $('end_date');
	var lastOption = endDateSel.options.length - 1;
	while (lastOption >= 0) {
		endDateSel.options[lastOption] = null;
		lastOption--;
	}
	
	endDateSel.options[0] = new Option('Select an End Date', '...');
	endDateSel.options[1] = new Option(two_weeks_date_label, two_weeks_date);
	endDateSel.options[2] = new Option(four_weeks_date_label, four_weeks_date);
	endDateSel.options[3] = new Option(six_weeks_date_label, six_weeks_date);
	endDateSel.selectedIndex = 2;
}

function popWin(image, w, h) {
	myWin = window.open('', '_blank', 'width='+parseInt(w+80)+', height='+parseInt(h+200)+' scrollbars=0, status=0, menubar=0');
	myWin.document.write("<html>\n<head>");
	myWin.document.write("<title>Image</title>\n</head>");
	myWin.document.write("<body style=\"color: #000000; background: #ffffff; margin: 0; padding: 0; font-family: Arial, Helvetica, Verdana, sans-serif;\">");
	myWin.document.write("<div style=\"text-align: center; padding-top: 20px;\"><img src=\""+image+"\" width=\""+w+"\" height=\""+h+"\" alt=\"\" style=\"border: 14px solid #FFFFFF;\"/></div>");
	myWin.document.write("<div style=\"font-size: 10px; padding: 0 20px;\"><span style=\"text-decoration: underline;\">Child Photo ID & Medical Emergency Card with Electronic ID</span>:  Both the Child Photo ID & Medical Emergency Card and the Electronic ID provide a color photo of your child with key descriptive information, medical & allergy data, and an emergency contact with three phone numbers. Plus, each has distinct features necessary for a quick and effective response to a missing child episode or medical emergency. For example, the ID Card also includes an optional medical release section, while the Electronic ID enables broad distribution of the child's data for quick action.</div>");
	myWin.document.write("<div style=\"font-size: 10px; text-align: center; padding-top: 16px;\"><a href=\"javascript: window.close();\" style=\"color: #000000;\">Close Window</a></div>");
	myWin.document.write("</body>");
	myWin.document.write("</html>");
	return false;
}