var loader = new Image();
loader.src = 'images/loader_red.gif';
function doNav(theUrl) {
	document.location.href = theUrl;
}
function pleaseWait(id) {
	$('pleaseWait'+id).show();
}
function showLoader() {
	$('loaderProcessing').style.display = 'block';
}
function deleteAccount(id) {
	if(confirm('Are you sure you want to delete this account?')) {
		doNav('admin_accounts.php?action=process&section=delete&id='+id);
	}
	return false;
}
function deleteParagraph(id,page,ret) {
	if(confirm('Are you sure you want to delete this paragraph?')) {
		doNav('page_info.php?action=process&section=delete&id='+id+'&return='+ret+'&page='+page);
	}
	return false;
}
function deleteThis(id,type) {
	if(confirm('Are you sure you want to completely remove this '+type+'?')) {
		var url = $(id).href;
		doNav(url);
	}
	return false;
}
function submitForm(id) {
	$(id).submit();
	return false;
}
function refundOrder(id) {
	if(confirm('Are you sure you want to refund the total amount of this order to the customer?')) {
		doNav('admin_orders.php?action=process&section=refund&id='+id);
	}
	closeLightBox();
	return false;
}
function refundPartialOrder(id) {
	var amount = prompt('Please enter the total amount you want to refund for this order:');
	if(amount) {
		doNav('admin_orders.php?action=process&section=partialrefund&id='+id+'&amount='+amount);
	} else {
		closeLightBox();
	}
	return false;
}
function refundPopup(id) {
	showLightBox('Refund Order','<div>Which would you like to do?<br /><br /><input type="button" onclick="refundOrder(\''+id+'\');" value="Refund Full Amount" />&nbsp;&nbsp;&nbsp;<input type="button" onclick="refundPartialOrder(\''+id+'\');" value="Refund Partial Amount" /></div>')
}
function toggleOptions(id) {
	var divs = $$('div.optionsMenu');
	for(i=0;i<divs.length;i++) {
		if(divs[i]['id'] == 'optionsMenu'+id) {
			new Effect.toggle(divs[i]['id'],'appear',{duration:.2});		
		} else {
			new Effect.Fade(divs[i]['id'],{duration:.2});
		}
	}
	return false;
}
function showLightBox(title,message) {
	var viewport = document.viewport.getDimensions();
	var page = $(document.body).getDimensions();
	var width, height;
	if(viewport.width < page.width) {
		width = page.width;
	} else {
		width = viewport.width;
	}
	if(viewport.height < page.height) {
		height = page.height;
	} else {
		height = viewport.height;
	}
	doNav('#');
	$(document.body).insert('<div id="popupMessage" class="popupMessage"><div style="float:right;"><a href="#" onclick="return closeLightBox();"><img src="images/icons/close.gif" border="0" alt="Close Window" /></a></div><h1>'+title+'</h1>'+message+'<br /><br /></div>');
	$(document.body).insert('<div id="overlay" class="overlay" style="width:'+width+'px;height:'+(height+60)+'px;position:fixed;"></div>');
	return false;
}
function closeLightBox() {
	if(Object.isElement($('popupMessage'))) {
		$('popupMessage').remove();
	}
	if(Object.isElement($('overlay'))) {
		$('overlay').remove();
	}
}
function displaySecurityCodeBox() {
	showLightBox('Security Code','A security code helps us to verify that you are the holder of this credit card.  Take a look at the image below to find the security code on your credit card.<br /><br /><div align="center"><img src="thumb_gen.php?s=images/cv_card.jpg&w=280" /></div>');
	return false;
}
function loadShoppingCart() {
	new Ajax.Updater('cartDisplay','ajax_cart.php?ajax=yes',{
		evalScripts:true
	});
}
function showError(message) {
	showLightBox('Error Encountered',message);
	return false;
}
function updateShoppingCart() {
	var elements = $('shoppingCartForm').serialize();
	new Ajax.Request('cart.php?action=updatecart&ajax=yes&'+elements,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				showError(response);
			}
			loadShoppingCart();
		},
		onFailure:function() { showError('There was a problem communicating with the server. Please try again.'); }
	});
	return false;
}
function removeProduct(id,options) {
	if(confirm('Are you sure you want to remove this item from your cart?')) {
		new Ajax.Request('cart.php?action=remove&ajax=yes&id='+id+'&options='+options,{
			method:'get',
			onSuccess:function(transport) {
				var response = transport.responseText;
				if(response != '') {
					showError(response);
				}
				loadShoppingCart();
			},
			onFailure:function() { showError('There was a problem communicating with the server. Please try again.'); }
		});
	}
	return false;
}
function continueCheckout() {
	updateShoppingCart();
	doNav('checkout_billing.php');
	return false;
}
var AjaxRequest;
function lookupEmail() {
	if(AjaxRequest) {
		AjaxRequest.transport.abort();
	}
	var email = $('email').value;
	$('loadingEmail').innerHTML = '<img src="images/loader_small.gif" border="0" align="absbottom" /> <span class="dkgray">Looking for previous orders. Please wait.</span>';
	$('loadingEmail').show();
	new Ajax.Request('ajax_billing.php?email='+email,{
		method:'get',
		onCreate:function(request) { AjaxRequest = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				response = response.split('+');
				$('loadingEmail').innerHTML = '<span class="red">Some of your information was filled in from a previous order.</span>';
				$('first').value = response[0];
				$('last').value = response[1];
				$('address').value = response[2];
				$('city').value = response[3];
				$('state').value = response[4];
				$('zip').value = response[5];
				$('phone').value = response[6];
			} else {
				$('loadingEmail').hide();
			}
		},
		onFailure:function() { alert('There was a problem retrieving your information.'); }
	});
}
function lookupCityState() {
	if(AjaxRequest) {
		AjaxRequest.transport.abort();
	}
	var zip = $('zip').value;
	new Ajax.Request('ajax_billing.php?action=citystate&zip='+zip,{
		method:'get',
		onCreate:function(request) { AjaxRequest = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				response = response.split('+');
				$('city').value = response[0];
				$('state').value = response[1];
				$('zip').value = response[2];
			}
		},
		onFailure:function() { alert('There was a problem retrieving your information.'); }
	});
}
function calculateShipping() {
	if(AjaxRequest) {
		AjaxRequest.transport.abort();
	}
	var subtotal = $('subTotal').value;
	$('shippingDisplay').innerHTML = '<img src="images/loader_small.gif" border="0" alt="Loading"/>';
	var ship = $('shippingSelection').selectedIndex;
	ship = $('shippingSelection').options[ship].value;
	var zip = $('zipCode').value;
	var weight = $('shippingWeight').value;
	new Ajax.Request('ajax_shipping.php?ship='+ship+'&zip='+zip+'&weight='+weight+'&total='+subtotal,{
		method:'get',
		onCreate:function(request) { AjaxRequest = request; },
		onComplete:function(transport) {
			var response = transport.responseText;
			if(response.match('international') || response.match('domestic')) {
				updateShippingOptions(response);
			} else if(response != '') {
				if(response.search('Error:') == '-1') {
					if(response == '0.00') {
						$('shippingDisplay').innerHTML = 'FREE';
					} else {
						$('shippingDisplay').innerHTML = '$'+(response*1).toFixed(2);
					}
					$('shippingValue').value = response;
					calculateSalesTax(zip);
					/*var newtotal = (subtotal*1)+(response*1);
										var tax = $('salesTax').value;
										if(tax != '') {
											newtotal = newtotal+(tax*1);
										}
										$('totalDisplay').innerHTML = '$'+newtotal.toFixed(2);*/
				} else if(response.search('Error: The requested service is invalid from the selected origin.') != '-1') {
					alert('We cannot ship to the zip code you have specified.  If you are in the US, please select a shipping method that does not say "International".  If you are in Canada, please select an International shipping method.');
					$('shippingDisplay').innerHTML = '-';
					calculateSalesTax(zip);
					//$('totalDisplay').innerHTML = '$'+subtotal.toFixed(2);
				} else {
					alert(response);
					$('shippingDisplay').innerHTML = '-';
					calculateSalesTax(zip);
					//$('totalDisplay').innerHTML = '$'+subtotal.toFixed(2);
				}
			} else {
				$('shippingDisplay').innerHTML = '-';
			}
		},
		onFailure:function() { alert('There was a problem retrieving shipping information.'); }
	});
}
function updateShippingOptions(type) {
	var subtotal = $('subTotal').value;
	var weight = $('shippingWeight').value;
	$('shippingDisplay').innerHTML = '<img src="images/loader_small.gif" border="0" alt="Loading"/>';
	new Ajax.Request('ajax_shipping.php?action=options&type='+type+'&total='+subtotal+'&weight='+weight,{
		method:'get',
		onComplete:function(transport) {
			var response = transport.responseText;
			$('shippingOptions').innerHTML = response;
			calculateShipping();
		}
	});
}
var isCalculating = false;
function calculateShippingFinal() {
	$('shippingDisplay').innerHTML = '<img src="images/loader_small.gif" border="0" alt="Loading" align="absmiddle"/> Retrieving shipping rates.';
	var subtotal = $('subTotal').value;
	var address = $('address').value;
	var city = $('city').value;
	var state = $('state').value;
	var zip = $('zip').value;
	var weight = $('shippingWeight').value;
	new Ajax.Request('ajax_shipping.php?action=final&address='+address+'&city='+city+'&state='+state+'&zip='+zip+'&weight='+weight+'&total='+subtotal,{
		method:'get',
		onCreate:function(request) { isCalculating = request; },
		onComplete:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				$('shippingDisplay').innerHTML = response;
			} else {
				$('shippingDisplay').innerHTML = 'Error: We could not find rates based on the information you entered.';
			}
			isCalculating = false;
		},
		onFailure:function() { alert('There was a problem retrieving shipping information.'); }
	});
}
function allowShipping() {
	if(isCalculating) {
		$('pleaseWaitLoading').update('Please wait for the shipping rates to finish loading and then click continue.');
		return false;
	}
}
function calculateSalesTax(zip) {
	var subtotal = $F('subTotal');
	new Ajax.Request('ajax_taxes.php?zip='+zip+'&subtotal='+subtotal,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				$('taxDisplay').update('$'+response+'<input type="hidden" name="salesTax" id="salesTax" value="'+response+'" />');
				$('taxRow').show();
			} else {
				$('taxDisplay').update('$0.00<input type="hidden" name="salesTax" id="salesTax" value="0.00" />');
				$('taxRow').hide();
			}
			updateTotal();
		},
		onFailure:function() { alert('There was a problem communicating with the server. Please hit refresh.'); }
	});
}
function updateTotal() {
	var subtotal = $F('subTotal');
	var tax = $F('salesTax');
	var ship = $F('shippingValue');
	var total = '0.00';
	total = total*1;
	if(subtotal != '') {
		total = total+(subtotal*1);
	}
	if(ship != '') {
		total = total+(ship*1);
	}
	if(tax != '') {
		total = total+(tax*1);
	}
	$('totalDisplay').update('$'+total.toFixed(2));
}
function focusField(id,def) {
	if($(id).value == def) {
		$(id).value = '';
		$(id).setStyle({
			color:'#333'
		});
	}
}
function blurField(id,def) {
	if($(id).value == '') {
		$(id).setStyle({
			color:'#CCC'
		});
		$(id).value = def;
	}
}

function addOptionGrouping(id,i) {
	var id = $(id).identify();
	var newi = i;
	new Ajax.Request('ajax_products.php?action=addgroup&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('optionsContainer').insert(response);
		},
		onFailure:function() { alert('There was a problem communicating with the server. Please try again.'); }
	});
	newi++;
	$(id).onclick = function() { return addOptionGrouping(id,newi); };
	return false;
}
function removeOptionGrouping(i) {
	$('optiongrouping'+i).remove();
	return false;
}
function addOption(id,group,i) {
	var id = $(id).identify();
	var newi = i;
	new Ajax.Request('ajax_products.php?action=addoption&group='+group+'&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('optiongrouping'+group).insert(response);
		},
		onFailure:function() { alert('There was a problem communicating with the server. Please try again.'); }
	});
	newi++;
	$(id).onclick = function() { return addOption(id,group,newi); };
	return false;
}
function removeOption(id) {
	$('option'+id).remove();
	return false;
}
function addProductToOrder(i) {
	new Ajax.Request('ajax_orders.php?action=addproduct&i='+i,{
		method:'get',
		onSuccess: function(transport) {
			var r = transport.responseText;
			showLightBox('Add Product To Order',r);
		},
		onFailure:function() { showError('We encountered an error while communicating with the server. Please try again.'); }
	});
	return false;
}
function getProductDetails(i) {
	var id = $F('productname');
	new Ajax.Request('ajax_orders.php?action=getdetails&id='+id+'&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			$('productDetails').update(r);
		},
		onFailure:function() { showError('We encountered an error while communicating with the server. Please try again.'); }
	});
	return false;
}
function insertProduct(i) {
	var newi = i;
	var elements = $('productForm').serialize();
	new Ajax.Request('ajax_orders.php?action=insertproduct&'+elements+'&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			$('productTable').insert(r);
			closeLightBox();
			updateAdminOrder();
		}
	});
	newi++;
	$('addProductLink').onclick = function() { 'return addProductToOrder(newi);'; };
	return false;
}
function removeAdminOrderProduct(id) {
	$('product'+id).remove();
	updateAdminOrder();
	return false;
}
function updateAdminOrder() {
	setTimeout(function() {
		var elements = $('adminOrderForm').serialize();
		new Ajax.Request('ajax_orders.php?action=updateadmincart&'+elements,{
			method:'get',
			onSuccess:function(transport) {
				var r = transport.responseText;
				$('adminCartDisplay').update(r);
			},
			onFailure:function() { showError('There was a problem communicating with the server. Please try again.'); }
		});
	},200);
	return false;
}
function quickAddToCart(id) {
	new Ajax.Request('cart.php?action=quickaddpopup&id='+id,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			showLightBox('',response);
		},
		onFailure:function() { showError('There was a problem communicating with the server. Please try again.'); }
	});
	return false;
}