// ajax to control the options for each item in the dealer order form

// dictionary mapping pricing tier ids to display names
var pricing_map = []
pricing_map[1] = "(Wholesale)";
pricing_map[2] = "(Program)";
pricing_map[3] = "(P.U.D.)";

$(document).ready(function() {
	
	// define a function to be called when a product is selected
	var setOptions = function(selected_product, product_div, line_item_no) {
		// get rid of any previously added options
		$("#line-items div.custom"+ line_item_no).remove();
		
		// get pricing information for each item
		$.post("/orders/ajax/price/", {product_id: selected_product}, function(data) {
			var price_data = JSON.parse(data);
			var base_price = price_data[0].fields.price;
			var price_value = base_price.substring(0, base_price.length - 4);
			var price_display = price_value + " (Retail)";
			var price_identifier = line_item_no + "-price";
			product_div.after(	"	<div class='detail_break custom" + line_item_no + "'>" 						+
								"		Price"																	+
								"		<select name='" + price_identifier + "' id='" + price_identifier + "'>"	+
								"			<option value='" + price_value + "'>" + price_display + "</option>"	+
								"		</select>"																+
								"	</div>");
			// get the tiered pricing for each item
			$.post("/orders/ajax/price/tiers/", {product_id: selected_product}, function(data) {
				var tiered_price_data = JSON.parse(data);
				$.each(tiered_price_data, function() {
					var tiered_price = this.fields.price.substring(0, base_price.length - 4);
					// set the correct display value for the dropdown (price + name of pricing tier)
					var tiered_price_display = tiered_price + ' ' + pricing_map[this.fields.pricingtier];
					// put them in the pre-existing price dropdown
					$("select#"+price_identifier).append(
						$("<option></option>")
							.attr("value", tiered_price)
							.text(tiered_price_display)
					);
				});
				// add the 'no charge' option
				$("select#"+price_identifier).append(
					$("<option></option>")
						.attr("value", "0.00")
						.text("0.00 (No Charge)")
				);
			});
		});
		
		// get the option_groups for the selected object
		$.post("/orders/ajax/options/", {product_id: selected_product}, function(data) {
			var field_counter = 0;
			var option_group = JSON.parse(data);
			$.each(option_group, function() {
				var group_name = this.fields.name
				var group_identifier = line_item_no + "-custom_" + field_counter;
				product_div.after(	"	<div class='detail_break custom" + line_item_no + "'>" 						+
											group_name																+
									"		<select name='" + group_identifier + "' id='" + group_identifier + "'>"	+
									"		</select>"																+
									"	</div>");
				field_counter++;
				// add the options for each option group
				$.post("/orders/ajax/options/list/", {group_id: this.pk}, function(options_data) {
					var options = JSON.parse(options_data);
					$.each(options, function() {
						$("select#"+group_identifier).append(
							$("<option></option>")
								.attr("value", group_name + ": " + this.fields.name)
								.text(this.fields.name));
					});
				});
			});
		});
	};
	
	// remove the default options
	$("div.dexterity").remove();
	$("div.shaft").remove();
	$("div.length").remove();
	$("div.lie").remove();
	$("div.price").remove();
	$("div.grip").remove();
	$("div.head_cover").remove();
	$("div.price").remove();
	
	// get the integer value of the hidden input
	var items = parseInt($("input#line-item-count").val());
	
	$("#add-line-item").click(function() {
		// set the zero index for the next <tr>
		var items_index = items;
		
		// update the count for the line-items variable
		items += 1;
		$("input#line-item-count").val(items);
		
		// set the correct names and ids for the new <select>s and
		// <input>s
		var putter_id = "id_" + items_index + "-putter"
		var putter_name = items_index + "-putter"
		var quantity_id = "id_" + items_index + "-quantity"
		var quantity_name = items_index + "-quantity"
		var comments_id = "id_" + items_index + "-comments"
		var comments_name = items_index + "-comments"
		
		$("table#line-items tbody")
			.append("	<tr>																												" +
					"		<td>																											" +
					"			<div class='detail product'>																				" +
					"				Product  <select name='" + putter_name + "' id='" + putter_id + "'>										" +
					"				</select>																								" +
					"			</div>																										" +
					"			<div class='detail'>																						" +	
					"				Quantity  <input id='" + quantity_id + "' type='text' name='" + quantity_name + "' size='5' />			" +
					"			</div>																										" +
					"			<div class='detail_break'>																					" +
					"				Special Instructions  <input id='" + comments_id + "' type='text' name='" + comments_name + "' maxlength='500' />	" +
					"			</div>																										" +
					"		</td>																											" +
					"		<td class='remove_button_holder'>																				" +
					"			<span class='remove_line_item'>																				" +
					"				<img src='/static/images/dealers/icon_delete_item.png' title='Remove this line item' />					" +
					"			</span>																										" +
					"		</td>																											" +
					"	</tr>");
					
		// get the options for the products dropdown
		var product_options = $("#id_0-putter").children().clone();
		$("select#" + putter_id).append(product_options);
	});
	
	$(".remove_line_item").live("click", function() {
		items -= 1;
		// update the count for the line-items variable
		$("input#line-item-count").val(items);
		// remove the entire tr for this row
		$(this).parent().parent().remove();
	});
	
	// Copy the values from the Account Contact field to the Accounts Payable
	// field if the appropriate checkbox is clicked
	$("#same-person").bind('click', function() {
		// get the values from the "Account Contact" fields
		contact_first = $("#id_contact_first").val();
		contact_last = $("#id_contact_last").val();
		contact_phone = $("#id_contact_phone").val();
		contact_fax = $("#id_contact_fax").val();
		contact_email = $("#id_contact_email").val();
		
		// a map of the target field ids
		var contact_map = {
			"#id_ap_first": contact_first, 
			"#id_ap_last": contact_last, 
			"#id_ap_phone": contact_phone,
			"#id_ap_fax": contact_phone,
			"#id_ap_email": contact_email
		};
		
		// for each field in the "Accounts Payable" field, check if 
		// if it's already readonly. If not, copy the value from the 
		// "Account Contact" field and set the input as readonly
		$.each(contact_map, function(target, source) {
			if ($(target).attr("readonly") == true) {
				$(target).removeAttr("readonly").removeAttr("style");
			} else {
				$(target).val(source);
				$(target).attr("readonly", true).attr("style", "color:#666666");
			}
		});
		
	});
	
	// Same as above, for the addresses
	$("#same-address").bind('click', function() {
		// get the values from the "Billing Address" fields
		bill_street_1 = $("#id_bill_street_1").val();
		bill_street_2 = $("#id_bill_street_2").val();
		bill_city = $("#id_bill_city").val();
		bill_state = $("#id_bill_state").val();
		bill_zip = $("#id_bill_zip").val();
		bill_country = $("#id_bill_country").val();
		if (bill_street_2.length != 0) {
			full_address = bill_street_1 + "\n" + bill_street_2 + "\n" + bill_city + ", " + bill_state + " " + bill_zip + "\n" + bill_country
		} else {
			full_address = bill_street_1 + "\n" + bill_city + ", " + bill_state + " " + bill_zip + "\n" + bill_country
		}
		
		// check if the "Shipping Address" field is readonly. If not,
		// copy each value from the "Billing Address" into it
		if ($("#id_shipping_address").attr("readonly") == true) {
			$("#id_shipping_address").removeAttr("readonly").removeAttr("style");
		} else {
			$("#id_shipping_address").val(full_address);
			$("#id_shipping_address").attr("readonly", true).attr("style", "color:#666666");
		}
		
		
		// a map of the target field ids
		// var address_map = {
		// 	"#id_ship_street_1": bill_street_1, 
		// 	"#id_ship_street_2": bill_street_2, 
		// 	"#id_ship_city": bill_city,
		// 	"#id_ship_state": bill_state,
		// 	"#id_ship_zip": bill_zip,
		// 	"#id_ship_country": bill_country
		// };
		
		// for each field in the "Accounts Payable" field, check if 
		// if it's already readonly. If not, copy the value from the 
		// "Account Contact" field and set the input as readonly
		// $.each(address_map, function(target, source) {
		// 	if ($(target).get(0).tagName == "SELECT") {
		// 		
		// 		if ($(target).attr("disabled") == true) {
		// 			$(target).removeAttr("disabled");
		// 			$("#added-state-value").remove();
		// 		} else {
		// 			$(target).val(source);
		// 			$("#shipping-address").append("<input id='added-state-value' type='hidden' value='"+ source +"' name='"+ $(target).attr("name") +"' />");//.attr("type", "hidden").attr("id", $(target).attr("id")).attr("name", $(target).attr("name")).attr("value", $(target).val());
		// 			$(target).attr("disabled", true);
		// 		}
		// 		
		// 	} else {
		// 		
		// 		if ($(target).attr("readonly") == true) {
		// 			$(target).removeAttr("readonly").removeAttr("style");
		// 		} else {
		// 			$(target).val(source);
		// 			$(target).attr("readonly", true).attr("style", "color:#666666");
		// 		}
		// 		
		// 	}
		// 	
		// });
		
	});
	
	// $("#line-items dd.dup_price input").attr("disabled", true);
	
	// call the function when a product is selected
	$(".product select").live("change", function() {
		var selected_product = $(this).val();
		var product_div = $(this).parent();
		var line_item_no = $(this).attr('name').charAt(0);
		$("dl.dup_custom#"+line_item_no).remove();
		setOptions(selected_product, product_div, line_item_no);
	});
	
	// call the function when the edit button is clicked
	$("dl.dup_custom button").live("click", function() {
		var field_index = $(this).val();
		var selected_product = $("#id_"+field_index+"-putter option:selected").val();
		var product_div = $("#id_"+field_index+"-putter option:selected").parent().parent();
		$(this).parent().parent().remove();
		setOptions(selected_product, product_div, field_index);
	});
	
});
