/* Load error variables */
var error1 = 'We encountered an error while trying to communicate with the server. Please refresh the page.';

function printWindow() {
	window.print();
}
function doNav(url) {
	document.location.href = url;
}
function doNavNewWindow(url) {
	window.open(url,'_blank');
}
function doNavLightView(url) {
	Lightview.show({
		href: url,
		rel: 'ajax',
		options: {
			autosize: true,
			topclose: true
		}
	});
}
function closeLightView() {
	Lightview.hide();
}
function pleaseWait(id) {
	$('pleaseWait'+id).show();
}
function showLoader() {
	$('loaderProcessing').style.display = 'block';
}
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 deleteThisLightView(id,type) {
	if(confirm('Are you sure you want to completely remove this '+type+'?')) {
		var url = $(id).href;
		doNavLightView(url);
	}
	return false;
}

/* Products */
var loadingProducts = false;
function loadProducts(newSearch) {
	if(!newSearch) {
		newSearch = 'no';
	}
	if(loadingProducts) {
		loadingProducts.transport.abort();
	}
	$('productDisplay').update('<div align="center"><br /><br /><br /><br /><img src="images/loader_gray_lg.gif" border="0" /><br /><br /><span class="dkgray t16">Loading Products...Please Wait</span><br /><br /><br /><br /></div>');
	var search = $F('ajaxSearch');
	if($('ajaxInactive').checked) {
		var inactive = '';
	} else {
		var inactive = 'no';
	}
	new Ajax.Request('ajax_products.php?action=products&search='+search+'&inactive='+inactive+'&new='+newSearch,{
		method:'get',
		onCreate:function(request) { var loadingProducts = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('productDisplay').update(response);
			loadingProducts = false;
		},
		onFailure:function() { alert(error1); }
	});
	return false;
}
function changeProductPage(page) {
	if(loadingProducts) {
		loadingProducts.transport.abort();
	}
	var search = $F('ajaxSearch');
	if($('ajaxInactive').checked) {
		var inactive = '';
	} else {
		var inactive = 'no';
	}
	new Ajax.Request('ajax_products.php?action=products&search='+search+'&inactive='+inactive+'&page='+page,{
		method:'get',
		onCreate:function(request) { var loadingProducts = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('productDisplay').update(response);
			loadingProducts = false;
		},
		onFailure:function() { alert(error1); }
	});
	return false;
}
function addProductImage(x) {
	var newx = x;
	new Ajax.Request('ajax_products.php?action=addProductImage&x='+x,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('imagesContainer').insert(response);
		},
		onFailure:function() { alert(error1); }
	});
	newx++;
	$('newImageLink').onclick = function() { return addProductImage(newx); };
	return false;
}
function removeProductImage(x,image) {
	if(confirm('Are you sure you want to completely remove this image?')) {
		new Ajax.Request('ajax_products.php?action=removeProductImage&image='+escape(image),{
			method:'get',
			onSuccess:function(transport) {
				var response = transport.responseText;
				if(response) {
					alert(response);
				} else {
					$('image'+x).remove();
				}
			},
			onFailue:function() {
				alert(error1);
			}
		});
	}
	return false;
}
function onFocus(element,text) {
	if($(element).value == text) {
		$(element).value = '';
		$(element).removeClassName('gray');
	}
}
function onBlur(element,text) {
	if($(element).value == '') {
		$(element).value = text;
		$(element).addClassName('gray');
	}
}
function checkDefaultImage(element) {
	if($(element).checked) {
		var checkboxes = $('productForm').getInputs('checkbox');
		checkboxes.each(function(el) {
			if(el != element) {
				$(el).checked = false;
			}
		});
	}
}
function addOptionGrouping(x) {
	var newx = x;
	new Ajax.Request('ajax_products.php?action=addOptionGrouping&x='+x,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('optionsContainer').insert(response);
		},
		onFailure:function() { alert(error1); }
	});
	newx++;
	$('newOptionGroupLink').onclick = function() { return addOptionGrouping(newx); };
	return false;
}
function removeOptionGrouping(x) {
	if(confirm('Are you sure you want to completely remove this group of options?')) {
		$('optiongrouping'+x).remove();
	}
	return false;
}
function addOption(a,x,i) {
	var newi = i;
	new Ajax.Request('ajax_products.php?action=addOption&x='+x+'&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('optiongrouping'+x).insert(response);
		},
		onFailure:function() { alert(error1); }
	});
	newi++;
	$(a).onclick = function() { return addOption(a,x,newi); };
	return false;
}
function removeOption(id) {
	if(confirm('Are you sure you want to completely remove this option?')) {
		$('option'+id).remove();
	}
	return false;
}
/* page editor functions */
var editorLoaded = false;
function loadEditor(id) {
	tinyMCE_GZ.init({
	      themes : "advanced",
	      plugins : "safari,spellchecker,pagebreak,style,layer,table,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager,tinyBrowser",
	      languages : "en",
	      disk_cache : true
	   }, function() {
			tinyMCE.init({
				// General options
				mode : "exact",
				elements : "diy",
				theme : "advanced",
				plugins : "safari,spellchecker,pagebreak,style,layer,table,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager,tinyBrowser",

				// Theme options
				theme_advanced_buttons1 : "save,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,|,formatselect,fontselect,fontsizeselect",
				theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,cleanup,code,|,preview,|,forecolor,backcolor,|,image",
				theme_advanced_buttons3 : "tablecontrols,|,removeformat,|,sub,sup,|,charmap,iespell,advhr",
				theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker",
				theme_advanced_toolbar_location : "external",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "none",
				theme_advanced_resizing : false,
				
				noneditable_leave_contenteditable : true,
				noneditable_noneditable_class: 'non-editable',
				content_css: 'stylesheet.css',
				width:'762',
				height:$('diy').getHeight(),
				oninit:function() { editorLoaded = true; },
				file_browser_callback: 'tinyBrowser',
				setup : function(ed) {
				        // Add a custom button
				        ed.addButton('save', {
				            title : 'Save Changes',
				            image : 'images/icons/save.gif',
				            onclick :function() { savePage(ed.id); return false; }
				        });
				    }
			});
		});
}
function toggleEditor(id) {
	if(editorLoaded) {
		if (!tinyMCE.get(id)) {
			tinyMCE.execCommand('mceAddControl', false, id);
		} else {
			savePage(id);
		}
	} else {
		loadEditor(id);
	}
}
function showEditor(id) {
	if(editorLoaded) {
		if (!tinyMCE.get(id)) {
			tinyMCE.execCommand('mceAddControl', false, id);
		}
	} else {
		loadEditor(id);
	}
}
function checkLoadEditor(event) {
	var element = Event.element(event);
	var load = false;
	if(element.descendantOf('mainContent')) {
		load = true;
		var noneditable = $$('.non-editable');
		noneditable.each(function(el) {
			var elid = $(el).identify();
			if(element.descendantOf(elid)) {
				load = false;
			}
		});
		if(load) {
	 	   showEditor('diy');
		}
	} else {
		var save = true;
		if(Object.isElement($('menu_diy_diy_formatselect_menu')) && element.descendantOf('menu_diy_diy_formatselect_menu')) {
			save = false;
		} else if(Object.isElement($('menu_diy_diy_fontselect_menu')) && element.descendantOf('menu_diy_diy_fontselect_menu')) {
			save = false;
		} else if(Object.isElement($('menu_diy_diy_fontsizeselect_menu')) && element.descendantOf('menu_diy_diy_fontsizeselect_menu')) {
			save = false;
		} else if(Object.isElement($('menu_diy_diy_spellchecker_menu')) && element.descendantOf('menu_diy_diy_spellchecker_menu')) {
			save = false;
		} else if(Object.isElement($('diy_backcolor_menu')) && element.descendantOf('diy_backcolor_menu')) {
			save = false;
		}
		if(save) {
			savePage('diy');
		}
	}
}
function savePage(id) {
	var ed = tinyMCE.get(id);
	if(ed) {
		var pagename = $('pagename').value;
		ed.setProgressState(1);
		var original = ed.getContent();
		html = ed.dom.get(ed.dom.select('div.non-editable'));
		ed.dom.setHTML(ed.dom.select('div.non-editable'),'%s');
		ed.dom.remove(ed.dom.select('div.non-editable'),true);
		var content = ed.getContent();
		ed.setContent(original);
		new Ajax.Request('ajax_pages.php?action=save',{
			method:'post',
			postBody:'page='+escape(content)+'&url='+pagename,
			onSuccess:function(transport) {
				var response = transport.responseText;
				if(response) {
					alert(response);
				}
				setTimeout(function() {
					ed.setProgressState(0);
					tinyMCE.execCommand('mceRemoveControl', false, id);
				},500);
			},
			onFailure:function() { alert(error1); ed.setProgressState(0); }
		}); 
	}
	return false;
}

// Shopping Cart functions
var qty = new Array;
function loadShoppingCart() {
	new Ajax.Request('ajax_cart.php?ajax=yes',{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('cartDisplay').update(response);
			var quantities = $('shoppingCartForm').getInputs('text');
			quantities.each(function(el) {
				qty[el.id] = el.value;
			});
		},
		onFailure:function() { alert(error1); }
	});
	return false;
}
var updatingCart = false;
var updatingCartTimer;
function updateShoppingCart() {
	if(updatingCartTimer) {
		clearTimeout(updatingCartTimer);
	}
	updatingCartTimer = setTimeout(function() {
		var changes = false;
		var quantities = $('shoppingCartForm').getInputs('text');
		quantities.each(function(el) {
			if(el.value != qty[el.id]) {
				changes = true;
				qty[el.id] = el.value;
			}
		});
		if(updatingCart) {
			updatingCart.transport.abort();
			updatingCart = false;
		}
		if(changes) {
			var action = $('shoppingCartForm').action;
			$('shoppingCartForm').action = action+'&ajax=yes';
			$('shoppingCartForm').request({
				onCreate:function(request) {
					updatingCart = request;
					$('shoppingCartForm').action = action;
				},
				onSuccess:function(transport) {
					var response = transport.responseText;
					if(response) {
						alert(response);
					} else {
						loadShoppingCart();
					}
					updatingCart = false;
				},
				onFailure:function() { alert(error1); }
			});
		}
	},300);
	return false;
}
function removeItem(element) {
	if(confirm('Are you sure you want to remove this item from your shopping cart?')) {
		new Ajax.Request($(element).href+'&ajax=yes',{
			method:'get',
			onSuccess:function(transport) {
				var response = transport.responseText;
				if(response) {
					alert(response);
				} else {
					loadShoppingCart();
				}
			},
			onFailure:function() { alert(error1); }
		});
	}
	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_gray_sm.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;
	var weight = $('shippingWeight').value;
	if(weight > 0) {
		$('shippingDisplay').update('<img src="images/loader_gray_sm.gif" border="0" alt="Loading"/>');
		var ship = $('shippingSelection').selectedIndex;
		ship = $('shippingSelection').options[ship].value;
		var zip = $('zipCode').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_gray_sm.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_gray_sm.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*1) > '0') {
				$('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 refundOrder(id) {
	if(confirm('Are you sure you want to completely refund this order?')) {
		doNav('admin-orders.php?action=process&section=refund&id='+id);
	}
	return false;
}
function addImage(x) {
	var newx = x;
	new Ajax.Request('admin-gallery.php?action=process&section=addImage&x='+x,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('imagesContainer').insert(response);
		},
		onFailure:function() { alert(error1); }
	});
	newx++;
	$('newImageLink').onclick = function() { return addImage(newx); };
	return false
}
function removeImage(x,image) {
	if(confirm('Are you sure you want to completely remove this image?')) {
		if(image) {
			new Ajax.Request('admin-gallery.php?action=process&section=removeImage&image='+escape(image),{
				method:'get',
				onSuccess:function(transport) {
					var response = transport.responseText;
					if(response) {
						alert(response);
					} else {
						$('image'+x).remove();
					}
				},
				onFailure:function() { alert(error1); }
			});
		} else {
			$('image'+x).remove();
		}
	}
	return false;
}
function onFocus(element,text) {
	if($(element).value == text) {
		$(element).value = '';
		$(element).removeClassName('gray');
	}
}
function onBlur(element,text) {
	if($(element).value == '') {
		$(element).value = text;
		$(element).addClassName('gray');
	}
}
function loadGallery(page) {
	new Effect.ScrollTo('galleryDisplay');
	new Ajax.Request('ajax_gallery.php?page='+page,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('galleryDisplay').update(response);
		},
		onFailure:function() { alert(error1); }
	});
	return false;
}
function selectDiscountType() {
	if($('percent_discount').checked) {
		$('percentContainer').show();
		$('flatContainer').hide();
		$('shippingContainer').hide();
	} else if($('flat_discount').checked) {
		$('percentContainer').hide();
		$('flatContainer').show();
		$('shippingContainer').hide();
	} else if($('shipping_discount').checked) {
		$('percentContainer').hide();
		$('flatContainer').hide();
		$('shippingContainer').show();
	}
}
function submitCouponCode() {
	updateShoppingCart();
}
