function add_items()
{
	var rows = document.getElementById('item_list').childNodes[0];
	while(rows.nodeType != 1)
		rows = rows.nextSibling;
	rows = rows.childNodes;
	var item_list = "";

	for(var i=1; i<rows.length; i++)
	{
		if(rows[i].nodeType == 1)
		{
			item_list += rows[i].getAttribute("item_num") + "##";
			item_list += rows[i].getAttribute("qty") + ";";
		}
	}

	var callback = function(text)
	{
		if(text.substring(0,5) == "ERROR")
		{
			window.location = 'login.php?cart_add=true' + text.substring(5);
		}
		else
		{
			if(text)
				document.getElementById('cart_count').innerHTML = " &nbsp;(" + text + " items)";
			else
				document.getElementById('cart_count').innerHTML = "";
			
			location.href = "cart.php";
		}
	}
	
	AJAX("cart/add_to_cart.php", "item_list=" + item_list + "&meta_item_id=" + meta_item_id, callback);
}
function login_start()
{
	var pwd = document.getElementById('pwd');
	var username = document.getElementById('username');

	pwd.value = pwd.value.replace("'", "");
	username.value = username.value.replace("'", "");

	var callback = function(text)
	{
		var second_callback = function(text)
		{
			location.href = "item_" + last_meta_item + ".html";
		}
		
		var error_code = (text) ? text.split(" ")[0] : "";

		switch(error_code)
		{
			case "ERROR":
				var message = document.getElementById('message');
				message.innerHTML = 'Invalid username or password.';
				message.style.display = 'block';

				pwd.value = "";
				username.value = "";
				username.focus();
			break;

			case "UNVERIFIED":
				var message = document.getElementById('message');
				switch(text.split(" ")[1])
				{
					case "CONSUMER":
						message.innerHTML = "You still need to confirm your email before you can log in. ";
						message.innerHTML += "<a href='#' onclick='resend_verification();'>Click here</a> to resend an email verification.";
					break;
					case "PROCESSING":
						message.innerHTML = "We are still processing your customer information request. <br><br>";
						message.innerHTML += "You should receive a confirmation via email once your pricing and account terms are verified. <br>";
						message.innerHTML += "We regret any inconvenience and will have your information ready as soon as possible.";
					break;
					case "REJECTED":
						message.innerHTML = "We're sorry, but we have been unable to confirm your customer information. <br><br>";
						message.innerHTML += "You should receive an email from our Administration Department explaining the issue. <br>";
						message.innerHTML += "We regret any inconvenience this may have caused.";
					break;
					case "CONFIRMED":
						message.innerHTML = "Your pricing is ready, but you still need to confirm your email before you can log in. <br>";
						message.innerHTML += "<a href='#' onclick='resend_verification();'>Click here</a> to resend an email verification.";
					break;
					case "LOCKED":
						message.innerHTML = "Your account has been locked due to multiple failed login attempts. <br>";
						message.innerHTML += "Please email us at <a href='mailto:ncmwebmaster@ncmedical.com?Subject=Locked Account'>ncmwebmaster@ncmedical.com</a> to reinstate your account.";
					break;
				}
				message.style.display = 'block';

				pwd.value = "";
				username.focus();
			break;

			default:
				if(cart_add == "true")
				{
					AJAX("cart/add_to_cart.php", "item_list=" + tried_to_order_list, second_callback);
				}
				else
					location.reload();
			break;
		}
	}

	AJAX('account/login_start.php', 'pwd=' + pwd.value + '&username=' + username.value, callback);
}
function sign_out()
{
	var callback = function()
	{
		location.reload();
	}
	AJAX('account/sign_out.php', null, callback);
}
function change_qty(object, change_num)
{
	if(!object.target)
	{
		var target = object.childNodes[0];
		while(target.nodeType != 1)
			target = target.nextSibling;
		object.target = target;
	}
	else
		target = object.target;

	target.value = parseInt(target.value) + change_num;
	if(isNaN(target.value))
		target.value = change_num;

	if(target.value < 0)
		target.value = 0;

	object.parentNode.setAttribute("qty", target.value);

	target.focus();
}
function get_password()
{
	var callback = function(text)
	{
		if(text == "ERROR")
		{
			alert("Couldn't send email. Did you type it correctly?");
			return;
		}

		if(text == "UNREGISTERED")
		{
			alert("Couldn't find a user with that username. Did you type it correctly?");
			return;
		}

		alert("An email has been sent with your new password.");
		location.href = "login.php";
	}

	var username = document.getElementById('username');
	AJAX("account/forgot_password.php", "username=" + username.value, callback);
}
function get_username()
{
	var callback = function(text)
	{
		if(text == "ERROR")
		{
			alert("Couldn't send email. Did you type it correctly?");
			return;
		}

		if(text == "UNREGISTERED")
		{
			alert("Couldn't find a user with that email address. Did you type it correctly?");
			return;
		}

		alert("An email has been sent with your username.");
		location.href = "login.php";
	}

	var email = document.getElementById('email');
	var emailRE = new RegExp(email.getAttribute("validation"), "");
	if( !emailRE.test(email.value) )
		alert("Couldn't send email. Did you type it correctly?");
	else
		AJAX("account/forgot_password.php", "email=" + email.value, callback);
}
function resend_verification()
{
	var username = document.getElementById('username');
	var callback = function(text)
	{
		var message = document.getElementById('message');

		if(text == "1")
			message.innerHTML = "An email has been sent to the email address you specified when registering.";
		else if(text == "3")
			message.innerHTML = "Your customer pricing confirmation is currently under review.<br>You should receive an email confirmation within 24 hours.";
		else
		{
			message.innerHTML = "There was an error sending your verification email. <br>";
			message.innerHTML += "Please contact us at <a href='mailto:ncmwebmaster@ncmedical.com?Subject=Could not send verification email'>ncmwebmaster@ncmedical.com</a>.";
		}

		message.style.display = 'block';
	}

	AJAX("account/resend_verification.php", "login=" + username.value, callback);
}

editing_address = false;

function confirm_address(entry)
{
	var address_id = entry.parentNode.getAttribute("address_id");

	var callback = function(text)
	{
		window.location = 'checkout.php?address_id=' + address_id;
	}

	AJAX("cart/save_pref_address.php", "address_id=" + address_id, callback);
}
function create_address()
{
	document.getElementById('address_selector').style.display = 'none';
	document.getElementById('subtitle').style.display = 'none';
	document.getElementById('address_creator').style.display = 'block';
}
function cancel_address()
{
	document.forms["new_address"].reset();
	document.getElementById('address_selector').style.display = 'block';
	document.getElementById('subtitle').style.display = 'block';
	document.getElementById('address_creator').style.display = 'none';
}
function edit_address(entry)
{
	editing_address = entry.parentNode;

	var form = document.forms["new_address"];
	var normal_fields = Array('name_1', 'name_2', 'address_1', 'address_2', 'city', 'state', 'zip');
	for(var i in normal_fields)
		form[normal_fields[i]].value = editing_address.getAttribute(normal_fields[i]);

	var phone_array = /^(...)(...)(....)$/.exec(editing_address.getAttribute("phone"));
	if(phone_array)
	{
		form["phone_area"].value = phone_array[1];
		form["phone_pre"].value = phone_array[2];
		form["phone_post"].value = phone_array[3];
	}

	create_address();
}
function delete_address(entry)
{
	if(!confirm("Are you sure you want to delete this address?"))
		return;

	var callback = function(text)
	{
		entry.parentNode.parentNode.removeChild(entry.parentNode);
	}

	AJAX('cart/delete_address.php', 'address_id=' + entry.parentNode.getAttribute("address_id"), callback);
}
function save_address(button)
{
	var callback = function(text)
	{
		if(isNaN(parseInt(text)))
		{
			button.disabled = "";
			switch(text)
			{
				case "CITY ERROR":
					alert('Could not validate city. Please make sure you have typed it correctly.');
				break;
				case "ADDRESS ERROR":
					alert("There was an error validating your address. Please try again. If you continue to see this message, please contact the webmaster (ncmwebmaster@ncmedical.com).");
				break;
				case "ADDRESS INVALID":
					alert("The address you entered is invalid. Please check to ensure that you entered the data correctly.");
				break;
				default:
					alert("There was an error saving your address. Please try again. If you continue to see this message, please contact the webmaster (ncmwebmaster@ncmedical.com).");
				break;
			}
		}
		else
		{
			location.reload();
		}
	}

	var params = "";
	var form = document.forms["new_address"];

	if(editing_address)
		params += "address_id=" + editing_address.getAttribute("address_id") + "&";

	var normal_fields = Array('name_1', 'name_2', 'address_1', 'address_2', 'city', 'zip');
	for(var i in normal_fields)
	{
		var value = form[normal_fields[i]].value;
		value = value.replace(/\'/g, "''");
		value = value.replace(/\&/g, "%26");

		params += normal_fields[i] + "=" + value + "&";
	}

	if(form["name_1"].value == "")
	{
		alert("You must enter a company or name for the package to ship to.");
		return;
	}
	
	var phone = form["phone_area"].value + form["phone_pre"].value + form["phone_post"].value;
	phone = phone.replace(/\s/g, "");
	var phoneRE = new RegExp(/^[0-9]{10}$/);
	if(!phoneRE.test(phone))
	{
		alert("Please enter a valid phone number.");
		return;
	}
	params += "phone=" + phone + "&";
	
	var state = form["state"].value.toUpperCase();
	var CAN_RE = new RegExp('^(BC|AB|SK|MB|ON|QC|NB|PE|NS|NL|YT|NT|NU)$', '');
	var US_RE = new RegExp('^(AL|AK|AZ|AR|CA|CO|CT|DE|DC|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|)$', '');

	if(US_RE.test(state))
		var country = "USA";
	else if(CAN_RE.test(state))
		var country = "Canada";
	else
	{
		alert("Invalid State/Province. Please enter a valid US State or Canadian Province abbreviation.");
		return;
	}
	
	params += "state=" + state + "&";
	params += "country=" + country + "&";

	button.disabled = 'true';
	AJAX('cart/save_address.php', params, callback);
}
function select_payment_method()
{
	var payment = document.forms["choose_payment"].payment;
	for(var i=0; i<payment.length; i++)
	{
		if(payment[i].checked == true)
			var value = payment[i].value;
	}
	if(value == undefined)
		value = payment.value;

	if(value == undefined || value == "")
	{
		alert("Please select a payment method");
		return;
	}

	var callback = function(text)
	{
		if(text == "ERROR")
			alert("There was an error validating your payment method. Please try again.");
		else
			window.location = location.href.replace(/\#/g, "") + '&payment=YES';
	}
	
	AJAX("cart/save_payment_method.php", "payment=" + value, callback);
}
function save_order(pending)
{
	var params = "";

	var cust_po = document.getElementById('po_number').value;
	if(po_required == "1" && cust_po == '')
	{
		alert("Please enter a PO number");
		document.documentElement.scrollTop = 0;
		document.getElementById('po_number').focus();
		return;
	}

	var cvv2 = document.getElementById('cvv2');
	if(cvv2)
	{
		if(cvv2.value == "")
		{
			alert("Please enter the three or four digit code from the back of your card.");
			cvv2.focus();
			return false;
		}
		else
			params += "cvv2=" + cvv2.value + "&";
	}

	var attn_line = "";
	var attn = document.getElementById('attn_line');
	if(attn && attn.value != attn.getAttribute('original'))
	{
		attn_line = attn.value;
	}

	var po_check_callback = function(text)
	{
		if(text != 0 && po_required == "1")
		{
			alert("The PO number you entered already exists for your account. Please enter a unique PO number.");
			document.documentElement.scrollTop = 0;
			document.getElementById('po_number').focus();
			return;
		}

		if(text != 0 && !confirm("The PO number you entered already exists for your account. Are you sure you want to re-use it?"))
			return;

		if(ship_via_override != "")
			params += "ship_code=" + ship_via_override + "&";

		var po_number = document.getElementById('po_number');
		if(po_number != undefined)
			params += "po_number=" + po_number.value + "&";

		params += "attn_line=" + attn_line + "&";

		document.getElementById('save_button').disabled = "TRUE";
		if(pending)
			AJAX("cart/save_pending_order.php", params, callback);
		else
			AJAX("cart/submit_order.php", params, callback);
	}

	var callback = function(text)
	{
		if(text.search("SUCCESS") != -1)
			window.location = "checkout.php?finish=TRUE";
		else if(text.substring(0,20) == "Authorization Failed")
		{
			document.getElementById('save_button').disabled = "";
			alert(text);
			window.location = location.href.replace("YES", "");
		}
		else
		{
			document.getElementById('save_button').disabled = "";
			alert(text);
		}
	}

	AJAX("cart/check_po_num.php", "cust_po_num=" + cust_po, po_check_callback);
}
function override_shipping(override)
{
	var url = location.href;

	var po_number = document.getElementById('po_number').value;
	
	if(url.search("ship_code=") == -1)
		url = url + "&ship_code=" + override;
	else
		url = url.replace(/ship_code=[^\&]*/, "ship_code=" + override);

	if(url.search("po_number=") == -1)
		url = url + "&po_number=" + po_number;
	else
		url = url.replace(/po_number=[^\&]*/, "po_number=" + po_number);

	if(url.search("scroll=") == -1)
		url = url + "&scroll=" + document.documentElement.scrollTop;
	else
		url = url.replace(/scroll=[^\&]*/, "scroll=" + document.documentElement.scrollTop);

	location.href = url;
}
function continue_shopping()
{
	var callback = function(text)
	{
		if(text)
		{
			var search_array = text.split("||||");
			var url = (search_array[2] != 0) ? "/search.php?group=" + search_array[2] + "&" : "/search.php?type=" + search_array[0] + "&";
			url += "query=" + search_array[1] + "&";
			url += "count=" + search_array[4] + "&";
			if(search_array[5])
				url += "page=" + search_array[5] + "&";
			if(search_array[3])
				url += "sort=" + search_array[3] + "&";
	
			window.location = url;
		}
	}

	AJAX("cart/last_search.php", null, callback);
}
function empty_cart()
{
	var callback = function(text)
	{
		location.reload();
	}

	if(confirm("Are you sure you want to remove all items from your cart?"))
		AJAX("cart/empty_cart.php", null, callback);
}
function save_favorite(object)
{
	var item_num = object.parentNode.parentNode.getAttribute("item_num");
	var callback = function(text)
	{
		object.innerHTML = "<a onclick='remove_favorite(this.parentNode);'>Remove from My List</a>";
	}

	AJAX("account/add_to_favorites.php", "item_num=" + item_num, callback);
}
function remove_favorite(object)
{
	var item_num = object.parentNode.parentNode.getAttribute("item_num");
	var callback = function(text)
	{
		object.innerHTML = "<a onclick='save_favorite(this.parentNode);'>Add to My List</a>";
	}

	AJAX("account/remove_favorite.php", "item_num=" + item_num, callback);
}
function add_catalog()
{
	var callback = function(text)
	{
		location.reload();
	}

	AJAX("cart/add_catalog.php", null, callback);
}

current_popup = "";
function info_popup(object)
{
	var cell = object.parentNode;
	if(cell.getAttribute("info") == "")
		return false;

	if(current_popup)
	{
		current_popup.style.display = 'none';
		current_popup.parentNode.removeChild(current_popup);
	}

	current_popup = document.createElement("div");
	current_popup.innerHTML = cell.getAttribute("info");
	document.body.appendChild(current_popup);

	var safari_vertical_offset = (navigator.userAgent.indexOf("Safari") != -1) ? 12 : 0;

	current_popup.style.top = (getPageOffsetY(object) - 236 + safari_vertical_offset) + "px";
	current_popup.style.left = (getPageOffsetX(object) - 741) + "px";
	current_popup.style.position = "absolute";
	current_popup.style.display = "block";
}
function getPageOffsetX(object) // the X location on a page of an object
{
	varX = object.offsetLeft;
	if (object.offsetParent != null)
		varX += getPageOffsetX(object.offsetParent);
	return varX;
}
function getPageOffsetY(object) // the Y location on a page of an object
{
	varY = object.offsetTop;
	if (object.offsetParent != null)
		varY += getPageOffsetY(object.offsetParent);
	return varY;
}
function clear_text(input)
{
	if(input.style.color != "black")
	{
		input.value = "";
		input.style.color = "black";
	}
}
function phone_advance()
{
	var area = document.getElementById("phone_area");
	var pre = document.getElementById("phone_pre");
	var post = document.getElementById("phone_post");

	area.value = area.value.replace(/[^0-9]*/g, "");
	pre.value = pre.value.replace(/[^0-9]*/g, "");
	post.value = post.value.replace(/[^0-9]*/g, "");

	if(pre.value.length == 3 && area.value.length == 3)
		post.focus();
	else if(area.value.length == 3)
		pre.focus();

	document.getElementById('new_phone').value = area.value + pre.value + post.value;
}
function fax_advance()
{
	var area = document.getElementById("fax_area");
	var pre = document.getElementById("fax_pre");
	var post = document.getElementById("fax_post");

	area.value = area.value.replace(/[^0-9]*/g, "");
	pre.value = pre.value.replace(/[^0-9]*/g, "");
	post.value = post.value.replace(/[^0-9]*/g, "");

	if(pre.value.length == 3 && area.value.length == 3)
		post.focus();
	else if(area.value.length == 3)
		pre.focus();

	document.getElementById('new_fax').value = area.value + pre.value + post.value;
}

function change_list(object)
{
	var grouping = object.getAttribute("current");

	popup = document.createElement("input");
	popup.value = grouping;
	popup.setAttribute("item_num", object.getAttribute("item_num"));
	popup.style.position = 'absolute';
	popup.style.fontSize = '8pt';
	popup.style.visibility = 'hidden';

	document.onkeypress = function()
	{
		if(event.keyCode == 13)
		{
			popup.blur();
			event.cancelBubble = true;
			return false;
		}
	}

	popup.onblur = function()
	{
		var callback = function(text)
		{
			alert("Changes Saved");
			popup.parentNode.removeChild(popup);
			location.reload();
		}

		var params = "group=" + popup.value + "&";
		params += "item_num=" + popup.getAttribute("item_num") + "&";
		AJAX("account/update_list_grouping.php", params, callback);
	}

	object.parentNode.appendChild(popup);
	popup.style.top = (getPageOffsetY(popup) - 2) + "px";
	popup.style.visibility = 'visible';
	popup.select();
}

adding_card_id = "";
function add_new_card()
{
	var form = document.forms["new_card"];
	var params = "";

	if(adding_card_id)
		params += "card_id=" + adding_card_id + "&";

	cardnum_RE = new RegExp(/^[0-9]{15}[0-9]?$/);
	if(!cardnum_RE.test(form["cc_number"].value) && form["cc_number"].value.indexOf('*') == -1)
	{
		alert("Please enter a valid Card number");
		return;
	}

	for(var i=0; i<form.length; i++)
	{
		if(form[i] && form[i].name)
		{
			var value = form[i].value;
			if(form[i].tagName == "SELECT")
				value = form[i][form[i].selectedIndex].text;
			if(value == "")
			{
				alert("Please fill in all fields");
				return;
			}

			value = value.replace(/\'/g, "''");
			value = value.replace(/\&/g, "%26");
			value = value.replace(/\*/g, "%2A");
			params += form[i].name + "=" + value + "&";
		}
	}

	var callback = function(text)
	{
		if(text == "ERROR")
			alert("Error saving card");
		adding_card_id = "";
		location.reload();
	}

	AJAX("cart/save_card.php", params, callback);
}
function edit_card(object)
{
	adding_card_id = object.getAttribute("card_id");
	var form = document.forms["new_card"];

	var input_fields = Array("card_firstname", "card_lastname", "card_address", "card_city", "card_state", "card_zip", "cc_number");
	for(var i in input_fields)
		form[input_fields[i]].value = object.getAttribute(input_fields[i]);

	var expir_array = object.getAttribute("card_expiration").split("/");
	var select_fields = Array("card_type", "expir_month", "expir_year");
	var select_values = Array(object.getAttribute("card_type"), expir_array[0], expir_array[1]);
	
	for(var i in select_fields)
	{
		var select = form[select_fields[i]];
		for(var j=0; j<select.options.length; j++)
		{
			if(select[j].text == select_values[i])
				select[j].selected = true;
		}
	}
	
	show_card_add_tool();
}
function delete_card(entry)
{
	if(!confirm("Are you sure you want to delete this card?"))
		return;

	var callback = function(text)
	{
		location.reload();
	}

	AJAX('cart/delete_card.php', 'card_id=' + entry.getAttribute("card_id"), callback);
}
function show_card_add_tool()
{
	if(adding_card_id)
		document.getElementById('save_button').value = "Save Card";
	else
		document.getElementById('save_button').value = "Add Card";

	document.getElementById('existing_payment').style.display = 'none';
	document.getElementById('new_card').style.display = 'block';
}
