/***********
*/
var qg = function() {
	var in_state = 0;
	var arr_in_state = new Array('IL'); //allow Illinois as in state

	var div_open = 'open';
	var div_msg = 'msg';
	var div_crux = 'crux';

	var rs_shipping_fee = 5; //regular season competition set
	var pq_shipping_fee = 0; //practice questions per set //email only
	var wk_shipping_fee = 0; //weeklies - email only;

	var ci_fee = 10; //custom instructions for competition sets (per set)

	var total_amount = 0;

	var books_count = 0;
	var iesa_count = 0;

	/****************************
	*
	*
	*
	****************************/
	function calculate_shipping_cost_for_iesa_books() {
		//shipping calculation for iesa and books - delegated here
		var books_iesa_count = eval(books_count+iesa_count);
		var books_iesa_shipping_cost = 0;

		//$5 for upto 2 items
		if (books_iesa_count>=1 && books_iesa_count<=2) {
			books_iesa_shipping_cost += 5;
		}
		//$10 for 3 items or more
		else if (books_iesa_count >= 3) {
			books_iesa_shipping_cost += 10;
		}

		if (books_iesa_count >= 1) {
			total_amount += books_iesa_shipping_cost;
			$('#shipping_for_books_iesa').attr("value", books_iesa_shipping_cost.toFixed(2));
		}
		else {
			$('#shipping_for_books_iesa').attr("value", "");
		}
	}


	/****************************
	*
	*
	*
	****************************/
	return {
		/******
		*
		******/
		fill_test_data: function() {
			$('#po').attr("value", '232323');
			$('#school').attr("value", '232323');
			$('#ba').attr("value", '232323');
			$('#sa').attr("value", '232323');

			$('#coach_name').attr("value", 'Coach Man');
			$('#coach_email').attr("value", 'abhi@excelisys.com');
			$('#coach_phone').attr("value", '854-785-8569');

			$('#school_phone').attr("value", '125-854-4545');
			$('#school_fax').attr("value", '252-856-9654');

			$('#contact_name').attr("value", 'Test Man');
			$('#contact_email').attr("value", 'abhi@excelisys.com');
			$('#contact_phone').attr("value", '458-856-9632');
		}, //end fill_test_data


		/******
		*
		******/
		in_out_state_selection: function() {
			in_state = 0;

			//state drop down box value is blank
			if ($('#state').attr("value") == "") {
				alert("Please select a State.");
				$('#'+div_crux).hide();
				$('#'+div_msg).html("");
				$('#'+div_msg).hide();
			}
			//state drop down box value is not blank
			else {
				var ios = jQuery.inArray($('#state').attr("value"), arr_in_state);
				if ((ios != -1) && (ios > -1)) {
					in_state = 1;
				}

				//update session variable
				$('#'+div_msg).html("Loading....");
				$('#'+div_msg).show();
				$('#'+div_crux).hide();

				var form_data = 'in_out_state_h=1&ios='+in_state;

				//set session
				$.ajax ({
					type: "POST",
					url: $('#frm_order').attr("action"),
				 	cache: false,
					data: form_data,
					complete: function(resp) {
						$('#'+div_msg).html("");
						$('#'+div_msg).hide();

						$('#'+div_crux).html(resp.responseText);
						$('#'+div_crux).show();
					}
				});
			}
		}, //end in_out_state_selection


		/******
		*
		******/
		contact_same_as_coach: function(cbox) {
			if ($('#'+cbox).is(':checked')) {
				$('#contact_name').attr("value", $('#coach_name').attr("value"));
				$('#contact_email').attr("value", $('#coach_email').attr("value"));
				$('#contact_phone').attr("value", $('#coach_phone').attr("value"));
			}
		}, //end contact_same_as_coach


		/******
		*
		******/
		shipping_same_as_billing: function(cbox) {
			if ($('#'+cbox).is(':checked')) {
				$('#sa').attr("value", $('#ba').val());
			}
		}, //end shipping_same_as_billing


		/******
		*
		******/
		calculate_subitem_total: function(type_name) {
			var arr_tmp = type_name.split('_');
			var cost_var = arr_tmp[0]+'_cost_h_'+arr_tmp[2];

			if (jQuery.trim($('#'+type_name).attr("value")) != "") {
				if (isInteger($('#'+type_name).attr("value"))) {
					var amount = $('#'+cost_var).attr("value") * $('#'+type_name).attr("value");
					$('#'+arr_tmp[0]+'_amount_'+arr_tmp[2]).attr("value", amount.toFixed(2));
				}
				else {
					alert("Please enter a valid number.");
					//reset qty and amount
					$('#'+type_name).attr("value", "");
					$('#'+arr_tmp[0]+'_amount_'+arr_tmp[2]).attr("value", "");
				}
			}
			else {
				//reset qty and amount
				$('#'+type_name).attr("value", "");
				$('#'+arr_tmp[0]+'_amount_'+arr_tmp[2]).attr("value", "");
			}

			//recalculate subtotal
			this.calculate_item_subtotal(arr_tmp[0]);
		}, //end calculate_subitem_total


		/******
		*
		******/
		calculate_item_subtotal: function(type_idt) {
			var qty = 0;
			var subtotal_field_idt = type_idt + '_subtotal';

			//get qty count
			$("input[name^='"+type_idt+"_qty_']").each(function() {
				if (jQuery.trim($(this).attr("value")) != "") {
					if (isInteger($(this).attr("value"))) {
						qty += parseInt($(this).attr("value"));
					}
				}
			});


			//found one or more
			if (qty >= 1) {
				var shipping_method_idt = type_idt + '_shipping_method';
				var amount = 0;

				//add-up amounts for all sub items
				$("input[name^='"+type_idt+"_amount_']").each(function() {
					if (jQuery.trim($(this).attr("value")) != "") {
						amount += parseInt($(this).attr("value"));
					}
				});

				//add the shipping fee, if any
				$("input[name^='"+type_idt+"_shipping_method']").each(function() {
					//checked
					if ($(this).is(":checked")) {
						//print and mail
						if ($(this).attr("value") == 2) {
							var shipping_fee = 0;

							//exception for books and iesa
							if (type_idt == 'bk') {
								books_count = qty;
							}
							else if (type_idt == 'iesa') {
								iesa_count = qty;
							}


							if ((type_idt == 'bk') || (type_idt == 'iesa')) {
								//defer shipping calculation to calculate_total
							}
							//other items (non books)
							else {
								shipping_fee = parseInt(eval(type_idt + '_shipping_fee')) * qty;
								amount += eval(shipping_fee);
							}


							//exception for rs
							if (type_idt == 'rs') {
								$('#rs_shipping_cost').attr("value", shipping_fee.toFixed(2));
							}
						}
						else {
							//exception for rs
							if (type_idt == 'rs') {
								$('#rs_shipping_cost').attr("value", "");
							}
						}
					}
				});


				//custom instructions for RS
				var ci = type_idt+'_ci';
				//test element existence
				if ($('#'+ci).length > 0) {
					var ci_cost = 0;
					var ci_cost_elem = type_idt + '_ci_cost';

					if (jQuery.trim($('#'+ci).val()) != "") {
						ci_cost = parseInt(eval(qty * ci_fee));
						$('#'+ci_cost_elem).attr("value", ci_cost.toFixed(2));
						amount += eval(ci_cost);
					}
					else {
						$('#'+ci_cost_elem).attr("value", "");
					}
				}


				//write to the subtotal field
				$('#'+subtotal_field_idt).attr("value", amount.toFixed(2));
			}
			//reset if qty is null
			else {
				$('#'+subtotal_field_idt).attr("value", "");
				//reset books and iesa count
				if (type_idt == 'bk') {
					books_count = 0;
				}
				else if (type_idt == 'iesa') {
					iesa_count = 0;
				}
				else if (type_idt == 'rs') {
					$('#rs_shipping_cost').attr("value", "");
				}
			}

			//trigger update final amount
			this.calculate_total();
		}, //end calculate_item_subtotal


		/******
		*
		******/
		show_hide_guides: function() {
			if ($('#guides').is(":visible")) {
				$('#guides').hide();
			}
			else {
				$('#guides').show();
			}
		}, //end show_hide_guides


		/******
		*
		******/
		process_study_guides: function() {
			var qty = 0;
			var unit_cost = 5; //per guide //constant
			var amount = 0;

			var per_bundle_cost = 100; //$100 per 25
			var bundle_qty = 25;

			$("input[name^='guides_cbox_']").each(function() {
				if ($(this).is(":checked")) {
					qty++;
				}
			});

			if (qty >= 1) {
				var mod = qty%bundle_qty;
				var bundles = parseInt(qty/bundle_qty)

				amount = (mod * unit_cost) + (bundles * 100);
				amount = amount.toFixed(2);

				$('#sg_qty').attr("value", qty);
				$('#sg_subtotal').attr("value", amount);
			}
			else {
				$('#sg_qty').attr("value", "");
				$('#sg_subtotal').attr("value", "");
			}

			//trigger update final amount
			this.calculate_total();
		}, //end show_hide_guides


		/******
		*
		******/
		calculate_total: function(type_idt) {
			total_amount = 0;

			//recursively add all subtotal fields
			$("input[name$='_subtotal']").each(function() {
				if (jQuery.trim($(this).attr("value")) != "") {
					total_amount += eval($(this).attr("value"));
				}
			});


			//deferred
			calculate_shipping_cost_for_iesa_books();

			if (total_amount != "") {
				$('#total_amount').attr("value", '$'+total_amount.toFixed(2));
			}
			else {
				$('#total_amount').attr("value", "");
			}
		}, //end calculate_total


		/******
		*
		******/
		checkout: function() {
			if (confirm("Are you sure you want to submit your order?")) {
				//run checks
				var err = "";

				//first level of checks

				//state
				if ($('#state').attr("value") == "") {
					err += "\n\t- Your State"
				}

				//PO
				if (jQuery.trim($('#po').attr("value")) == "") {
					err += "\n\t- Purchase Order Number"
				}

				//billing address
				if (jQuery.trim($('#ba').val()) == "") {
					err += "\n\t- Billing address"
				}

				//shipping address
				if (jQuery.trim($('#sa').val()) == "") {
					err += "\n\t- Shipping address"
				}

				//coach name
				if (jQuery.trim($('#coach_name').attr("value")) == "") {
					err += "\n\t- Coach's name"
				}

				//coach email
				if (!validEmail($('#coach_email').attr("value"))) {
					err += "\n\t- Coach's email"
				}

				//coach phone
				if (jQuery.trim($('#coach_phone').attr("value")) == "") {
					err += "\n\t- Coach's phone"
				}

				//school phone
				if (jQuery.trim($('#school_phone').attr("value")) == "") {
					err += "\n\t- School phone"
				}

				//contact name
				if (jQuery.trim($('#contact_name').attr("value")) == "") {
					err += "\n\t- Contact name"
				}

				//contact email
				if (!validEmail($('#contact_email').attr("value"))) {
					err += "\n\t- Contact email"
				}

				//contact phone
				if (jQuery.trim($('#contact_phone').attr("value")) == "") {
					err += "\n\t- Contact phone"
				}


				//date of competition for RS competition sets
				//if rs subtotal is not blank
				if (jQuery.trim($("#rs_subtotal").attr("value")) != "") {
					//date of first competition
					if (jQuery.trim($("#rs_doc").attr("value")) == "") {
						err += "\n\t- Date of first competition";
					}

					//competitor list
					var comp_school_found = 0;
					$("input[name^='rs_school_']").each(function() {
						if (jQuery.trim($(this).attr("value")) != "") {
							var arr_tmp = $(this).attr("id").split('_');
							var city_field_name = 'rs_city_' + arr_tmp[2];
							if (jQuery.trim($('#'+city_field_name).attr("value")) != "") {
								comp_school_found++;
							}
						}
					});

					if (comp_school_found == 0) {
						err += "\n\t- Competitor list";
					}
				}

				//second level of checks
				if (jQuery.trim(err) == "") {
					if ($('#total_amount').attr("value") == "") {
						alert("Please select at least one item.");
					}
					//all good - submit
					else {
						$('#'+div_open).hide();
						$('#'+div_crux).hide();
						$('#'+div_msg).html("Submitting....");
						$('#'+div_msg).show();

						//set session
						$.ajax ({
							type: "POST",
							url: $('#frm_order').attr("action"),
						 	cache: false,
							data: $('#frm_order').serialize(),
							complete: function(resp) {
								if (resp.responseText == 1) {
									var txt = "Your order has been submitted. An email confirmation has been sent to the contact email and the coach email address that you entered.";
									$('#'+div_msg).html(txt);
									alert(txt);
								}
								else {
									$('#'+div_msg).html("An error occured while processing your request. Please try again.");
									window.location.reload();
								}
							}
						});
					}
				}
				else {
					err = "Please make sure the following fields are complete and valid:\n" + err;
					alert(err);
				}
			} // end if confirm checkout
		} //end checkout

	}; //end return


}(); //end qg declaration
