var page_command;

function check_action() {

	if (page_command.execute) {

		execute_request(page_command.url, page_command.command);
		page_command.execute = false;
	}
	setTimeout("check_action()", 800);
}

function PageAction() {
	this.execute = false;
	this.command = null;
	this.url = null;
}

function submit_request(url, command) {
	page_command.url = url;
	page_command.command = command;
	page_command.execute = true;
}

function execute_request(url, command) {

	var req = null;
	var iframe = null;
	var xml_request = document.getElementById("xmlrequest");
	if (xml_request) {
		xml_request.innerHTML = "";
		xml_request.style.display = "none";
	}

	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();     // Modern browsers
	}
	else
		if (window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");    // Internet Explorer
		} else {
			if (xml_request) {
				xml_request.innerHTML = "<div id=\"flash\" class=\"error\"><p>You must have ActiveX enabled.</p></div>";
				xml_request.style.display = "block";
			}
		}



	if (req != null) {


		req.onreadystatechange = function () {
			if (req.readyState == 4) {
				if (req.status == 200) {

					switch (command) {
						case 'load_depts':
							process_dept(req);
							break;
						case 'load_courses':
							process_courses(req);
							break;
						case 'load_sections':
							process_sections(req);
							break;
						case 'load_products':
							process_products(req);
							break;
					}
				}
				else {

					xml_request.innerHTML = "<div id=\"flash\" class=\"error\"><p>There has been an error processing your request.</p></div>";
					xml_request.style.display = "block";
				}
			}
		};

		if (document.getElementById("debug_xml")) {
			xml_request.innerHTML = url;
			xml_request.style.display = "block";
		}

		req.open("GET", url, true);
		req.send(null);
	}
}

function initProducts() {
	if (document.getElementById("rcdCount")) {

		initProdOption();
		initProdQty();

		if ($(".jumpbooks-substitutions").length > 0) {
			get_isbns();
		}
		//if($(".get-rentals").length>0){
		//	get_rentals();
		//}
		if ($(".barchart-list").length > 0) {
			get_barcharts();
		}

	} else {
		if (!document.getElementById("course-bookdisplay").hasChildNodes()) {
			document.getElementById("xmlrequest").innerHTML = "<div id=\"flash\" class=\"error\"><p>The textbooks for this section can not be found at this time.</p></div>";
			document.getElementById("xmlrequest").style.display = "block";
			document.getElementById("course-bookdisplay").style.display = "none";
		}
	}
}

function get_term() {
	var term = document.getElementById("fTerm");
	campusterm_id = term.value;
	pos = campusterm_id.indexOf("|");
	campus_id = campusterm_id.substr(0, pos);
	term_id = campusterm_id.substr(pos + 1, campusterm_id.length + 1);

	return term_id;
}

function initProdOption() {
	var recordCount = document.getElementById("rcdCount").value;
	
	$(".product-sku").click(function () {

		var rownum = $(this).attr("id").split("_")[1];
		$("#qty-" + rownum).val("1");

		if ($(this).attr("id").indexOf("digital") >= 0) {
			$("#qty-" + rownum).attr("name", "qty-" + getJumpbookRowByRowId(rownum));
		} else {
			$("#qty-" + rownum).attr("name", "qty-" + rownum);
		}
		updateTotal();
	});
	$(".undo-link").click(function () {


		//**** TODO: support jumpbooks
		var type = "sku-";
		if ($(this).attr("id").indexOf("used") >= 0) {
			type = type + "used";
		} else {
			type = type + "new";
		}
		if ($(this).attr("id").indexOf("rental") >= 0) {
			type = type + "-rental";
		}
		var rownum = $(this).attr("id").split("_")[1];
		// set qty to zero
		$("#qty-" + rownum).val("0");
		// remove "selected"
		$("#radio-" + type + "_" + rownum).removeAttr("checked");
		$("#undo-radio-" + type + "_" + rownum).removeClass("undo-radio-on");
		$("#undo-radio-" + type + "_" + rownum).addClass("undo-radio-off");
		$("#tr-radio-" + type + "_" + rownum).removeClass("selected");

		updateTotal();
		return false;
	});
	$(".book-pref > select").change(updateTotal);

	var defaultTextbookType = $("#default_textbook_type").val();
	var defaultTextbookTypeUsable = defaultTextbookType.indexOf("rental") > -1 ? "radio-" + defaultTextbookType : defaultTextbookType;

	if (defaultTextbookTypeUsable.indexOf("none") == -1) {
		if (defaultTextbookTypeUsable.indexOf("cheapest") == -1) {
			//Select the sku that matches default, if it exists
			$('input[id^="radio-sku"], input[id^="radio-radio-sku"]').each(function () {
				if ($(this).is(':disabled') == false &&
					$(this).attr("id").indexOf(defaultTextbookTypeUsable) > -1) {
					$(this).attr('checked', 'checked')
				}
			})
			//If a sku matching the default, doesnt exist, select the cheapest available
			for (i = 1; i <= recordCount; i++) {
				cheapestSku = $("#cheapest-" + i).val();
				var radio = $("[id='radio-" + defaultTextbookTypeUsable + i + "']");
				if (radio.is(":disabled") || radio.length == 0) {
					$("#qty-" + i).val("0");
				}
			}
		} else {
			var cheapestSku = "";
			for (i = 1; i <= recordCount; i++) {
			    if ($('#rental-price-list-' + i).length) {
			        cheapestSku = $("#cheapest-" + i).val();
			        $('input[id="' + cheapestSku + '"]').attr('checked', 'checked');
			        if (!$('input[id="' + cheapestSku + '"]').length) {
			            $("#qty-" + i).val("0");
			        }
			    }
			}
		}
	} else {
		// "none" selected in manager
		$(".product-qty").val("0");
	}




	$(".tr-radio-sku").hover(function () {
		var rownum = $(this).attr("id").split("_")[1];
		var msgid = "product-";
		if ($(this).attr("id").indexOf("used") >= 0) {
			msgid = msgid + "used-";
		} else {
			msgid = msgid + "new-";
		}
		if ($(this).attr("id").indexOf("rental") >= 0) {
			msgid = msgid + "rental-";
		}
		msgid = msgid + "message-" + rownum;
		if ($(this).attr("id").indexOf("digital") >= 0) {
			msgid = "product-message-" + getJumpbookRowByRowId(rownum);
		}
		$("#courseproduct-avail-message-" + rownum).html($("#" + msgid).val());
	},
    function () {
    	var rownum = $(this).attr("id").split("_")[1];
    	if ($("input[name='sku_" + rownum + "']:checked").length > 0) {
    		var id = $("input[name='sku_" + rownum + "']:checked").attr("id");
    		if (id.length > 0) {
    			var msgid = "product-";
    			if (id.indexOf("new") >= 0) {
    				msgid = msgid + "new-";
    			} else {
    				msgid = msgid + "used-";
    			}
    			if (id.indexOf("rental") >= 0) {
    				msgid = msgid + "rental-";
    			}
    			msgid = msgid + "message-" + rownum;
    			if ($(this).attr("id").indexOf("digital") >= 0) {
    				msgid = "product-message-" + getJumpbookRowByRowId(rownum);
    			}
    			$("#courseproduct-avail-message-" + rownum).html($("#" + msgid).val());
    		}
    	}
    });

	$(".rental-price-list").each(function () {
		$('td', $(this)).not($('tr:first td', $(this))).not('.undo-radio').css('border-top', 'none');
	});
	updateTotal();
}

// Updated for jumpbooks support
function initProdQty() {

	$(".product-qty").blur(productQtyAction);

}

function productQtyAction() {

	if ($(this).val() == "0") {
		var rownum = $(this).attr("id").split("-")[1];
		$("#rental-price-list-" + rownum + " tr").removeClass("selected");
		$("#rental-price-list-" + rownum + " td.undo-radio").removeClass("undo-radio-on").addClass("undo-radio-off");
		$("#rental-price-list-" + rownum + " input.product-sku").removeAttr("checked");
	}

	updateTotal();
}

function productOptionAction() {
	document.getElementById("quickProdOption").selectedIndex = 0;
	updateTotal();
}


function updateProdOption() {
	var newOption = document.getElementById("quickProdOption");
	var recordCount = document.getElementById("rcdCount").value;
	var newIndex;

	newIndex = newOption.selectedIndex;
	if (newIndex > 0) {
		newIndex -= 1;


		for (i = 1; i <= recordCount; i++) {
			if (document.getElementById("no-product-" + i).value == "0") {
				switch (document.getElementById("pf_type_id-" + i).value * 1) {
					case 2:
					case 6:
						var selectedValue = $("#quickProdOption option:selected").text();

						var inputId = "radio-sku-";
						if (selectedValue.indexOf("Used") >= 0) {
							inputId = inputId + "used";
						} else {
							inputId = inputId + "new";
						}
						if (selectedValue.indexOf("Rental") >= 0) {
							inputId = inputId + "-rental";
						}
						inputId = inputId + "_" + i;
						// check to see if selection exists for the product in question, leave alone if not available
						if ($("#" + inputId + ":enabled").length > 0) {
							// set checked = "" for all in this group
							$("input:enabled[name='sku_" + i + "']").attr("checked", "");
							// select this one
							$("#" + inputId).attr("checked", "checked");
						}
						break;
					default:

						break;

				}

			}
		}
		updateTotal();
	}
}


function updateTypes(type) {

	var newOption = document.getElementById("f" + type);
	var recordCount = document.getElementById("rcdCount").value;
	var newQty;

	if (newOption.checked) {
		newQty = 1;
	} else {
		newQty = 0;
	}

	for (i = 1; i <= recordCount; i++) {
		if (document.getElementById("no-product-" + i).value == "0") {
			if (document.getElementById("product-opt-" + i).value == type) {
				document.getElementById("qty-" + i).value = newQty;
			}
		}
	}

	updateProdOption();
}


// updated for jumpbooks support
function updateTotal() {
	var total = document.getElementById("course-bookdisplay-total-amt");
	var recordCount = document.getElementById("rcdCount").value;
	var tempTotal = 0;
	var qtyTotal = 0;

	$(".product-rowid").each(function () {

		var i = $(this).val();


		if (document.getElementById("no-product-" + i).value == "0") {

			var itemQty = document.getElementById("qty-" + i).value * 1;

			if (itemQty == 0) {
				//document.getElementById("qty-" + i).value = "0";
				$("#rental-price-info-" + i + " span.book-price-list").css("text-decoration", "none");
			}

			if (itemQty > 0) {
				qtyTotal += itemQty;
				switch (document.getElementById("pf_type_id-" + i).value * 1) {
					case 1:
						var priceArray = new Array();
						var priceList = document.getElementById("gmprice-" + i).value;

						priceArray = priceList.split(',');

						tempTotal += itemQty * priceArray[document.getElementById("sku_" + i).selectedIndex];

						break;
					case 2:
					case 6:

						$("table#rental-price-list-" + i + " tr").removeClass("selected");
						$("table#rental-price-list-" + i + " td.undo-radio").removeClass("undo-radio-on");
						$("table#rental-price-list-" + i + " td.undo-radio").addClass("undo-radio-off");
						$("#price-message-" + i).hide();

						var id = ($("input[name='sku_" + i + "']:checked")).attr("id");
						var itemPrice = 100000;
						var listPrice = $("#mostprice-" + i).val() * 1;

						if ($("input[name='sku_" + i + "']:checked").length > 0) {

							if (id.indexOf("used") >= 0) {
								if (id.indexOf("rental") >= 0) {
									// add used rental price to tempTotal
									itemPrice = $("#product-used-rental-price-" + i).val() * 1;
									tempTotal += itemQty * itemPrice;
									// show message
									$("#courseproduct-avail-message-" + i).html($("#product-used-rental-message-" + i).val());
									$("#rental_flag-" + i).val('1');
								} else {
									// add used price to tempTotal
									itemPrice = $("#product-used-price-" + i).val() * 1;
									tempTotal += itemQty * itemPrice;
									// show message
									$("#courseproduct-avail-message-" + i).html($("#product-used-message-" + i).val());
									$("#rental_flag-" + i).val('0');
								}

							} else {
								if (id.indexOf("rental") >= 0) {
									// add new rental price to tempTotal
									itemPrice = $("#product-new-rental-price-" + i).val() * 1;
									tempTotal += itemQty * itemPrice;
									// show message
									$("#courseproduct-avail-message-" + i).html($("#product-new-rental-message-" + i).val());
									$("#rental_flag-" + i).val('1');
								} else if (id.indexOf("digital") >= 0) {
									itemPrice = $("#product-new-price-" + getJumpbookRowByRowId(i)).val();
									tempTotal += itemQty * itemPrice;
									$("#courseproduct-avail-message-" + i).html("Digital Download");
								} else {
									// add new price to tempTotal
									itemPrice = $("#product-new-price-" + i).val() * 1;
									tempTotal += itemQty * itemPrice;
									// show message
									$("#courseproduct-avail-message-" + i).html($("#product-new-message-" + i).val());
									$("#rental_flag-" + i).val('0');

								}
							}
						}

						// price difference
						if (listPrice > itemPrice) {
							$("#price-message-" + i).show();
							$("#rental-price-info-" + i + " span.book-price-list").css("text-decoration", "line-through");
							$("#courseproduct-price-message-" + i).html(displayCurrency(listPrice - itemPrice));
						} else {
							$("#rental-price-info-" + i + " span.book-price-list").css("text-decoration", "none");
						}


						// add "selected" class to parent <tr>
						$("#tr-" + id).addClass("selected");
						// display "remove" link

						if ($("#" + id).is(":checked") && $("#qty-" + i).val() != "0") {
							$("#undo-" + id).removeClass("undo-radio-off");
							$("#undo-" + id).addClass("undo-radio-on");
						}



						$(".selected").find("td").css("border-top", "1px solid #C9C9C9").css("border-bottom", "1px solid #C9C9C9");
						$(".selected").nextAll().find("td").css("border-bottom", "1px solid #C9C9C9").css("border-top", "none");
						$(".selected").prevAll().find("td").css("border-bottom", "none").css("border-top", "1px solid #C9C9C9");
						break;

					default:
						tempTotal += itemQty * document.getElementById("gmprice-" + i).value;
						break;
				}


			} else {
				switch (document.getElementById("pf_type_id-" + i).value * 1) {
					case 2:
					case 6:

						$("table#rental-price-list-" + i + " tr").removeClass("selected");
						$("table#rental-price-list-" + i + " td.undo-radio").removeClass("undo-radio-on");
						$("table#rental-price-list-" + i + " td.undo-radio").addClass("undo-radio-off");
						$("input[name='sku_" + i + "']:checked").removeAttr("checked");
						$("#price-message-" + i).hide();

						break;
					default:
						break;
				}
			}

		} else {
			$("#price-message-" + i).hide();
			$("#rental-price-info-" + i + " span.book-price-list").css("text-decoration", "none");
		}

	});

	if (document.getElementById("btn-addtocart")) {
		if (qtyTotal > 0) {
			document.getElementById("btn-addtocart").disabled = false;
		} else {
			document.getElementById("btn-addtocart").disabled = true;
		}
	}
	if (document.getElementById("btn-reserve")) {
		if (qtyTotal > 0) {
			document.getElementById("btn-reserve").disabled = false;
		} else {
			document.getElementById("btn-reserve").disabled = true;
		}
	}

	total.innerHTML = displayCurrency(tempTotal);
	if ($(".get-rentals").length > 0) {
		get_rentals();
	}
}


function load_search_prods(section_id) {


	var products = document.getElementById("course-bookdisplay");
	products.style.display = "block";
	products.innerHTML = "<h3>Loading textbooks...</h3>";
	var url = "textbooks_xml.asp?control=section&section=" + section_id;
	submit_request(url, "load_products");



}

function reserve_to_cart() {

	var recordCount = document.getElementById("rcdCount").value;
	for (i = 1; i <= recordCount; i++) {

		if (document.getElementById("purch_opt-" + i)) {
			document.getElementById("purch_opt-" + i).value = "R";
		}
	}

	document.getElementById("TextbookForm").submit();

}

/************
BARCHARTS
************/

function get_barcharts() {
	var url = "textbooks_xml.asp";
	$("table.data").each(function (i) {
		var isbnNos = new Array();
		var section_id = this.id.split("-", 2)[1];
		$(this).find(".product-field-isbn").each(function () {
			isbnNos.push($(this).val());
		});
		$.get(url, { control: "barcharts", isbns: isbnNos.join(","), sectionId: section_id }, function (data) {
			$("#barchart-list-" + section_id).html(data);
			addProductSeed("barchart_" + section_id);
			initProdQty();
			isbn_init();
		});
	});
}

/************
RENTALS
************/

// rental integrated = 1
function get_rentals() {
	var pfIds = new Array();
	var skus = new Array();
	var rowCounts = new Array();
	$(".product-field-pf_id").each(function () {
		pfIds.push($(this).val());
		rowCounts.push($(this).attr("id").split("-", 2)[1]);
		skus.push($("#sku_" + $(this).attr("id").split("-", 2)[1]).val());
	});
	url = "textbooks_xml.asp";

	$.getJSON(url,
		{ control: "rental", pfIds: pfIds.join(","), rowCounts: rowCounts.join(","), skus: skus.join(","), sectionId: $("#fSection").val() },
		function (data) {
			$.each(data.items, function (i, item) {
				$("#rental_message-" + item.row).html(item.message);
			});
		}
	);
}

/************
JUMPBOOKS
************/

function getJumpbookRowByRowId(rowId) {
	var isbn = $("#isbn-" + rowId).val();
	var section = $("#section_id-" + rowId).val();
	return $("#jumpbooks-substitutions-" + section + " input[value='" + isbn + "']").attr("id").split("-")[1];
}

function digitalSelection() {
	//check to see if digital option is selected
	//if selected, rename qty-rowId field to jumpbooks row id
	//if not selected, rename to qty-rowId
}
function get_isbns() {
	var url = "textbooks_xml.asp";

	$("table.data").each(function () {
		var section_id = this.id.split("-", 2)[1];
		var values = new Array();
		$(this).find(".product-field-isbn").each(function () {
			values.push($(this).val());
		});
		$.get(url, { control: "jumpbooks", isbns: values.join(","), sectionId: section_id }, function (data) {
			$("#jumpbooks-substitutions-" + section_id).html(data);
			addProductSeed("jump_" + section_id);
			addDigitalOptions("jump_" + section_id);
			initProdQty();
			isbn_init();

		});
	});
}

function addDigitalOptions(seed) {

	var rcdCount = $("#rcdCount-" + seed).val() * 1;

	for (i = 1; i <= rcdCount; i++) {
		var seedRow = seed + "_" + i;
		var isbn10 = $("#param-" + seedRow + "-isbn10").val();
		var isbn13 = $("#param-" + seedRow + "-isbn13").val();
		$(".product-field-isbn[@value=" + isbn10 + "],.product-field-isbn[@value=" + isbn13 + "]").each(function () {
			var rowId = getRowId(this.id);
			var price = $("#product-new-price-" + seedRow).val();
			$("#tr-radio-sku-digital_" + rowId + " td.price label").text(displayCurrency(price));
			$("#tr-radio-sku-digital_" + rowId).removeClass("digital-book");
			$("#digital-" + rowId).removeClass("neg").addClass("pos");


		});
	}

}
function addProductSeed(seed) {
	if ($("#product-seeds").length > 0) {
		if ($("#product-seeds").val().length == 0) {
			$("#product-seeds").val(seed);
		} else {
			var seeds = $("#product-seeds").val().split(",");
			seeds.push(seed);
			$("#product-seeds").val(seeds.join(","));
		}
	}


}



function substituteItem(o) {

	$(".product-field-isbn[@value=" + o.isbn10 + "],.product-field-isbn[@value=" + o.isbn13 + "]").each(function () {

		$("#qty-" + getRowId(this.id)).val(0);
		$("#qty-" + o.rowId).val(1);

		$("#substitute-" + o.rowId).hide();
		$("#cancel-" + o.rowId).show();

		updateTotal();
	});

}

function cancelItem(o) {

	$(".product-field-isbn[@value=" + o.isbn10 + "],.product-field-isbn[@value=" + o.isbn13 + "]").each(function () {

		$("#qty-" + getRowId(this.id)).val(1);
		$("#qty-" + o.rowId).val(0);
		$("#substitute-" + o.rowId).show();

		updateTotal();
	});

}

function getRowId(elementId) {
	return elementId.split("-", 2)[1];
}



function initActiveResult(callback, actionName) {
	var actionName = (actionName == null) ? "" : actionName;

	$(".activeresult-action-" + actionName).each(function (item) {

		$(this).click(function () {

			var itemId = this.id.split("-", 2)[1];
			var params = new Object();

			$(".param-" + itemId).each(function (i) {
				var key = this.id.split("-", 3)[2];
				params[key] = this.value;
			});

			callback(params);
			return false;
		});

	});
}


function initProductSearchResult() {
	initActiveResult(setProduct, "select");
}

function initCatalogSearchResult() {
	initActiveResult(setCatalog);
}

function displayCurrency(numberToDisplay) {
	var displayPrice = numberToDisplay.toString();
	if (numberToDisplay == 0) {
		displayPrice = "000";
	}
	if (displayPrice.length == 2) {
		displayPrice = "0" + displayPrice;
	}
	if (displayPrice.length == 1) {
		displayPrice = "00" + displayPrice;
	}
	var displayLength = displayPrice.length;

	return "$" + displayPrice.substr(0, displayLength - 2) + "." + displayPrice.substr(displayLength - 2, displayLength);
}
