// ajax call to fill in the next drop-down //
function get_options( form_id, field_name ) {
	$.getJSON(
		"ajax_targets/get_product_alert_options.php",
		{field: field_name, current_values: $("#" + form_id).serialize()}, 
		function(j){ update_options(j) }
	)
}

// ajax success function //
function update_options( joptions ) {
	all_required_set = true;
	show_optional = false;

	$.each(joptions, function(field,settings) {
		show = (settings.display && settings.options.length == undefined);

		$("#" + field + "_row").toggleClass("hide", !show);

		if( show ) {
			selected_value = settings.value;

			field_list = $("#" + field)[0];
			field_list.length = 0;

			if( settings.required ) {
				add_option(field_list, "0", "Choose...", false);
			} else {
				add_option(field_list, "0", "Any", false);
			}

			found_selected = false;
			$.each(settings.options, function(key,val) { 
				if( key==selected_value ) {
					found_selected = true;
				}
				add_option(field_list, key, val, (key==selected_value));
			});
			if( !found_selected && settings.required ) {
				all_required_set = false;
			}
			if( !settings.required ) {
				show_optional = true;
			}
		}
	});

	$(".submit_settings").toggleClass("hide", !all_required_set);
	$(".optional_settings").toggleClass("hide", !show_optional);
}

// add an option to a select list //
function add_option(select_list, value, label, selected) {
	try{
		select_list.add(new Option(label, value, null, selected), null);
	}
	catch(e){ //in IE, try the below version instead of add()
		select_list.add(new Option(label, value, null, selected));
	}
}

function validate_alert_selection( form_id ) {
	var initial_error_message = "The following required fields are missing:\n";  
	var error_message = initial_error_message;  

	$("#" + form_id + " select.alert_required_option").each(function () { 
		if( $(this)[0].selectedIndex < 1 ) {
			error_message += "    " + $(this)[0].name + "\n";
		}
	});

	$("#" + form_id + " input:text").each(function () { 
		if( $(this)[0].value == '' ) {
			error_message += "    " + $(this)[0].name + "\n";
		}

		if( $(this)[0].name == "email" && !validate_email($(this)[0].value) ) {
			error_message += "    Invalid email address\n";
		}
	});

	if( error_message != initial_error_message ) {
		alert(error_message);
		return false;
	}
	return true;	
}


$(function(){
	$("select.alert_required_option").change(function(){ get_options($(this)[0].form.name, $(this).attr("name")) });
	$("form#alert").submit(function() { return validate_alert_selection($(this)[0].name); });
})

