function externalLinkListener() {
	$$('a[rel=external]').each(function(el) {
		$(el).observe('click', function(event) {
			event.stop();
			window.open(this.href);
		});
	});
}

document.observe('dom:loaded', externalLinkListener);

function searchListener() {
	var autocomplete = new Autocomplete('search_field', {
		width: 400,
		minChars:3,
		serviceUrl: '/search/hint/product',
		onInit: function() {
			$('search_field').addClassName('searching');
		},
		onComplete: function() {
			$('search_field').removeClassName('searching');
		}
	});
    
	$('prod_radio').observe('change', function() {
		if ($(this).checked) {
			autocomplete.serviceUrl = '/search/hint/product';
		}
	});
	
	$('article_radio').observe('change', function() {
		if ($(this).checked) {
			autocomplete.serviceUrl = '/search/hint/article';
		}
	});
}

//document.observe('dom:loaded', searchListener);
window.onload = searchListener;

function sortByListener() {
	if ($('sort_by')) {
		$('sort_by').observe('change', function() {
			$(this).up('form').submit();
		});
	}
}

document.observe('dom:loaded', sortByListener);

function refineProductList() {
	if ($('refine_products_list')) {
		$('refine_products_list_submit').hide();
		$$('#refine_products_list input[type="checkbox"]').each(function(el) {
			$(el).hide();
			var submitted = false;
			
			$(el).observe('change', function() {
				$$('#refine_products_list li.selected').each(function(elm) {
					$(elm).down('input[type="checkbox"]').checked = false;
				});
				
				if ($(el).checked) {
					// uncheck other selected items in this category
					$(el).checked = true;
				}
				else {
					// submit unchecked if the same filter was checked again
					$(el).checked = false;
				}
			
				$('refine_products_list').submit();
				submitted = true;
			});
			
			// IE checkbox change event workaround
			if (!submitted) {
				$(el).up('li').down('a').observe('click', function() {
					// uncheck other selected items in this category
					$$('#refine_products_list li.selected').each(function(elm) {
						$(elm).down('input[type="checkbox"]').checked = false;
					});
					
					if ($(el).checked) {
						$(el).checked = false;
					}
					else {
						// submit unchecked if the same filter was checked again
						$(el).checked = true;
					}

					$('refine_products_list').submit();
				});
			}
		});
	}
	
	if ($('current_tags')) {
		$$('#current_tags a').each(function(el) {
			$(el).observe('click', function(e) {
				e.stop();
				$($(this).readAttribute('rel')).checked = false;
				$('refine_products_list').submit();
			});
		});
	}
	
	if ($('enews_sign_form')) {
		$('enews_sign_form').observe('focus', function() {
			if ($('enews_sign_form').getValue() == 'Email Address') {
				$('enews_sign_form').setValue('');
			} 
		});
		
		$('enews_sign_form').observe('blur', function() {
			if ($('enews_sign_form').getValue() == '') {
				$('enews_sign_form').setValue('Email Address');
			}
		});
	}
}

document.observe('dom:loaded', refineProductList);

/*
 * Used to display and modify the delete modal box for both pages and widgets
 * used on the Pages index page in the CP and all front-end admin pages
 */
function confirmDelete() {	
	// deleting categories from the library
	$$('.rp-cat-delete').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			var slash = elm.href.lastIndexOf('/');
			var delete_all_href = elm.href.substring(0, slash) + '_all' + elm.href.substring(slash);
			
			var content = new Element('div');
			if(elm.hasClassName('rp-has-files')) {
				var option1 = new Element('a', {'href':delete_all_href, 'id':'rp_remove_option_1', 'class':'modal-choice'});
				var option1_text = new Element('span').update('Delete Category & Files');
				var option2 = new Element('a', {'href':elm.href, 'id':'rp_remove_option_2', 'class':'modal-choice'});
				var option2_text = new Element('span').update('Delete Category & Keep Files');
				option1 = option1.update(option1_text).insert('This category and all associated files will be removed from the site.');
				content.update(option1).insert(option2.update(option2_text).insert('This category will be deleted and all associated files will become "Uncategorized".'));
			} else {
				var option1 = new Element('a', {'href':delete_all_href, 'id':'rp_remove_option_1', 'class':'modal-choice'});
				var option1_text = new Element('span').update('Delete Category');
				content = option1.update(option1_text).insert('This category will be removed from the site.');
			}
			var modal_box = createModalBox('Are you sure you want to delete this category?', elm.title, content);
			
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
		});
	});
	
	// create wish list
	$$('.add-wish-list').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			var content = '<form action="/customer/wish_lists/add_list" method="post"><input id="WishListName" name="data[WishList][name]" /><input type="submit" value="Create List" /></form>';
			var modal_box = createModalBox('Create Wish List', elm.title, content);
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
		});
	});
	
	// delete wish list confirmation
	$$('.delete-wish-list').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			var content = new Element('a', {'href':elm.href, 'id':'rp_remove_option_1', 'class':'modal-choice'}).update(new Element('span').update('Delete Wish List'));
			var modal_box = createModalBox('Are you sure you want to delete this wish list?', elm.title, content);
			
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
		});
	});
	
	// delete saved address confirmation
	$$('.customer-address-delete').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			var content = new Element('a', {'href':elm.href, 'id':'rp_remove_option_1', 'class':'modal-choice'}).update(new Element('span').update('Delete Address'));
			var modal_box = createModalBox('Are you sure you want to delete this address?', elm.title, content);
			
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
		});
	});
}

function closeModal() {
	// setup method handle close click on modalbox
	$$('.rp-close-modal').each(function(elm) {
		elm.stopObserving();
		elm.observe('click', function(event) {
			event.stop();
			$('rp_modal_confirm').fade({duration:0.3});
		});
	});
}

/*
 * Create general modal box wrapper for deletes/warnings
 */
function createModalBox(title, subtitle, content) {
	var modal_div = new Element('div', {'id':'rp_modal_confirm', 'style':'display:none;'});
	var modal_wrap = new Element('div', {'id':'rp_modal_wrapper'});
	var modal_head = new Element('div', {'id':'rp_modal_head'});
	var modal_head_title = new Element('span').update(title);
	var modal_x = new Element('a', {'class':'rp-close-modal'});
	modal_head = modal_head.update(modal_head_title).insert(modal_x);
	var modal_content = new Element('div', {'id':'rp_modal_text'});
	var modal_text_title = new Element('h2', {'id':'rp_modal_text_title'}).update(subtitle);
	var modal_close = new Element('a', {'class':'modal-choice rp-close-modal'}).update(new Element('span', {'class':'red'}).update('Cancel'));
	modal_content = modal_content.update(modal_text_title).insert(content).insert(modal_close);
	var modal_foot = new Element('div', {'id':'rp_modal_foot'});

	var modal_box = modal_div.update(modal_wrap.update(modal_head).insert(modal_content).insert(modal_foot));

	return modal_box;
}

document.observe('dom:loaded', confirmDelete);

function cartAddListener() {
	$$('form.add-to-cart').each(function(el) {
		var submitted = false;
		
		$(el).observe('submit', function(event) {
			event.stop();
			
			if (!submitted) {
				submitted = true;
				var qty = $(el).down('input[name="data[Cart][qty]"]').getValue();
				var pid = $(el).down('input[name="data[Cart][product_id]"]').getValue();
			
				if ((qty > 0) && (pid !== '')) {
					$(el).down('.btn-add-to-cart').disable;
				
					if (!$(el).down('.add-to-cart-loading')) {
						$(el).down('input[name="data[Cart][qty]"]').previous('label').hide();
						$(el).down('input[name="data[Cart][qty]"]').hide();
						$(el).down('input[name="data[Cart][qty]"]').insert({before: '<div class="add-to-cart-loading"></div>'});
					}
			
					new Ajax.Request('/cart/add', {method: 'post', postBody: 'pid=' + pid + '&qty=' + qty, 
						onSuccess: function(t) {
							submitted = false;
							if (t.responseText == '1') {
								$(el).down('.add-to-cart-loading').remove();
								$(el).down('input[name="data[Cart][qty]"]').previous('label').remove();
								$(el).down('input[name="data[Cart][qty]"]').remove();
								$(el).down('input[name="data[Cart][product_id]"]').remove();

								$(el).down('input.btn-add-to-cart').replace('<div class="added-to-cart">Added to Cart</div>');
								$(el).next('a.small-grey-link').replace('<a class="small-grey-link proceed-checkout" href="/cart">Checkout</a>');
							
								// update cart item count
								new Ajax.Request('/cart/get_item_count', {method: 'post', 
									onSuccess: function(t) {
										if (t.responseText) {
											if (t.responseText == '0') {
												$('cart-item-count').update();
											}
											else {
												$('cart-item-count').update('(' + t.responseText + ')');
											}
										}
									}
								});
							}
							else {	// if AJAX query error submit form the old fashioned way
								$(el).submit();
							}
						}
					});
				}
			}
		});
	});
}

document.observe('dom:loaded', cartAddListener);

function wishListSelect() {
	$$('.wl-select-all').each(function(el) {
		$(el).observe('change', function() {
			if ($(el).checked) {
				$(el).up('form').getInputs('checkbox').each(function(elm) {
					$(elm).checked = 1;
				});
			}
			else {
				$(el).up('form').getInputs('checkbox').each(function(elm) {
					$(elm).checked = 0;
				});
			}
		});
	});
	
	$$('.update-wish-list').each(function(el) {
		$(el).observe('submit', function(event) {
			var selected = false;
			
			// if an item was selected return and continue
			$(el).getInputs('checkbox').each(function(elm) {
				if ($(elm).checked) {
					selected = true;
				}
			});

			if (!selected) {
				event.stop();
				alert('Please select at least one wish list item using the checkboxes to the left of each item.');
			}
		});
	});
}

document.observe('dom:loaded', wishListSelect);

function purchaseGiftCard() {
	if ($('WgtGiftCardShippingAddress')) {
		$('WgtGiftCardShippingAddress').observe('click', function() {
			if ($(this).checked) {
				$(this).up().next('fieldset').slideDown({duration:0.25});
			}
			else {
				$(this).up().next('fieldset').slideUp({duration:0.25});
			}
		});
	}
}

document.observe('dom:loaded', purchaseGiftCard);

function stateProvinceToggle() {
	$$('.country-select').each(function(el) {
		$(el).observe('click', function() {
			if ($(el).getValue() == 'US') {
				if ($(el).up('div').hasClassName('country')) {
					$(el).up('fieldset').up('fieldset').down('.province-select').up('div').hide();
					$(el).up('fieldset').up('fieldset').down('.state-select').up('div').show();
				}
				else {
					$(el).up('fieldset').down('.province-select').up('div').hide();
					$(el).up('fieldset').down('.state-select').up('div').show();
				}
			}
			else if ($(el).getValue() == 'CA') {
				if ($(el).up('div').hasClassName('country')) {
					$(el).up('fieldset').up('fieldset').down('.state-select').up('div').hide();
					$(el).up('fieldset').up('fieldset').down('.province-select').up('div').show();
				}
				else {
					$(el).up('fieldset').down('.state-select').up('div').hide();
					$(el).up('fieldset').down('.province-select').up('div').show();
				}
			}
		});
	});
}

document.observe('dom:loaded', stateProvinceToggle);

function addressToggle() {
	if ($('CartBillingAddress')) {
		var ba_fields_visible = true;
		
		if ($('billing-address-fieldset').hasClassName('collapsed')) {
			$('billing-address-fieldset').slideUp({duration:0.25});
			ba_fields_visible = false;
		}
		
		$('CartBillingAddress').observe('change', function() {
			if ($(this).getValue() == '') {
				$('billing-address-fieldset').slideDown({duration:0.25});
				ba_fields_visible = true;
			}
			else if (ba_fields_visible) {
				$('billing-address-fieldset').slideUp({duration:0.25});
				ba_fields_visible = false;
			}
		});
	}
	
	if ($('CartShippingAddress')) {
		var sa_fields_visible = true;
		
		if ($('shipping-address-fieldset').hasClassName('collapsed')) {
			$('shipping-address-fieldset').slideUp({duration:0.25});
			sa_fields_visible = false;
		}
		
		$('CartShippingAddress').observe('change', function() {
			if ($(this).getValue() == '') {
				$('shipping-address-fieldset').slideDown({duration:0.25});
				sa_fields_visible = true;
			}
			else if (sa_fields_visible) {
				$('shipping-address-fieldset').slideUp({duration:0.25});
				sa_fields_visible = false;
			}
		});
	}
}

document.observe('dom:loaded', addressToggle);

function shippingAddressCopyToggle() {
	if ($('CartSameAsBilling')) {
		if ($('shipping-address-fields').hasClassName('collapsed')) {
			$('shipping-address-fields').slideUp({duration:0.25});
		}
		
		$('CartSameAsBilling').observe('click', function() {
			if ($(this).checked) {
				$('shipping-address-fields').slideUp({duration:0.25});
			}
			else {
				$('shipping-address-fields').slideDown({duration:0.25});
			}
		});
	}
}

document.observe('dom:loaded', shippingAddressCopyToggle);

function shippingMethods() {
	if ($('CartShippingAddress1')) {
		$('CartShippingAddress1').observe('blur', function() {
			checkShippingRateFields();
		});
	}
	
	if ($('CartShippingAddress2')) {
		$('CartShippingAddress2').observe('blur', function() {
			checkShippingRateFields();	
		});
	}
	
	if ($('CartShippingCity')) {
		$('CartShippingCity').observe('blur', function() {
			checkShippingRateFields();
		});
	}
	
	if ($('CartShippingCity')) {
		$('CartShippingCity').observe('blur', function() {
			checkShippingRateFields();
		});
	}

	if ($('CartShippingState')) {
		$('CartShippingState').observe('change', function() {
			checkShippingRateFields();
		});
	}

	if ($('CartShippingPostal')) {
		$('CartShippingPostal').observe('blur', function() {
			checkShippingRateFields();
		});
	}

	$$('input[name="data[Cart][country]"]').each(function(el) {
		$(el).observe('change', function() {
			checkShippingRateFields();
		});
	});

	if ($('CartShippingAddress')) {
		$('CartShippingAddress').observe('change', function() {
			if ($('CartShippingAddress').getValue() !== '') {
				var tokens = $('CartShippingAddress').getValue().split('|');
				
				$('CartShippingFirstName').setValue(tokens[0]);
				$('CartShippingLastName').setValue(tokens[1]);
				$('CartShippingAddress1').setValue(tokens[2]);
				$('CartShippingCity').setValue(tokens[3]);
				$('CartShippingState').setValue(tokens[4]);
				$('CartShippingPostal').setValue(tokens[5]);
				
				
				$$('.country-select').each(function(el) {
					if ($(el).getValue() == tokens[6]) {
						$(el).checked = true;
					}
				});
				
				checkShippingRateFields();
			}
		});
	}
	
	if ($('CartBillingAddress')) {
		$('CartBillingAddress').observe('change', function() {
			if ($('CartBillingAddress').getValue() !== '') {
				var tokens = $('CartBillingAddress').getValue().split('|');
				
				$('CartFirstName').setValue(tokens[0]);
				$('CartLastName').setValue(tokens[1]);
				$('CartAddress1').setValue(tokens[2]);
				$('CartCity').setValue(tokens[3]);
				$('CartState').setValue(tokens[4]);
				$('CartPostal').setValue(tokens[5]);
				$('CartCountry').setValue(tokens[6]);

				checkShippingRateFields();
			}
		});
	}
	
	// if the shipping is the same as billing attach listeners
	billingAsShippingListener();
	
	if ($('CartSameAsBilling')) {
		$('CartSameAsBilling').observe('click', function() {		
			billingAsShippingListener();
			checkShippingRateFields();
		});
	}
}

document.observe('dom:loaded', shippingMethods);

function billingAsShippingListener() {
	if ($('CartSameAsBilling') && $('CartSameAsBilling').checked) {			
		$('CartAddress1').observe('blur', function() {
			checkShippingRateFields();
		});

		$('CartAddress2').observe('blur', function() {
			checkShippingRateFields();
		});
		
		$('CartCity').observe('blur', function() {
			checkShippingRateFields();
		});
		
		$('CartState').observe('change', function() {
			checkShippingRateFields();
		});
		
		$('CartPostal').observe('blur', function() {
			checkShippingRateFields();
		});
	}
	else {
		if ($('CartAddress1')) {
			$('CartAddress1').stopObserving('blur');
		}
		
		if ($('CartAddress2')) {
			$('CartAddress2').stopObserving('blur');
		}
		
		if ($('CartCity')) {
			$('CartCity').stopObserving('blur');
		}
	
		if ($('CartState')) {
			$('CartState').stopObserving('change');
		}
	
		if ($('CartPostal')) {
			$('CartPostal').stopObserving('blur');
		}
	}
}

function checkShippingRateFields() {
	if ((($('CartShippingCity').getValue() !== '') && ($('CartShippingState').getValue() !== '') && ($('CartShippingPostal').getValue() !== '') && ($('CartShippingPostal').getValue().length >= 5)) ||
		($('CartSameAsBilling').checked && ($('CartCity').getValue() !== '') && ($('CartState').getValue() !== '') && ($('CartPostal').getValue() !== '') && ($('CartPostal').getValue().length >= 5))) {
		// if this remains from an interrupted or halted call
		if ($('shipping-options-status')) {
			$('shipping-options-status').remove();
		}
	
		var address = $('CartShippingAddress1');	// used for PO check
		var address2 = $('CartShippingAddress2');	// used for PO check
		var city = $('CartShippingCity').getValue();
		var state = $('CartShippingState').getValue();
		var postal = $('CartShippingPostal').getValue();
		
		var country = '';
		if ($('CartShippingCountry')) {
			country = $('CartShippingCountry').getValue();
		}
		else {
			$$('input[name="data[Cart][shipping_country]"]').each(function(el) {
				if ($(el).checked) {
					country = $(el).getValue();
				}
			});
		}
		
		if ($('CartSameAsBilling').checked) {
			address = $('CartAddress1');		// used for PO check
			address2 = $('CartAddress2');		// used for PO check
			city = $('CartCity').getValue();
			state = $('CartState').getValue();
			postal = $('CartPostal').getValue();
			if ($('CartCountry')) {
				country =  $('CartCountry').getValue();
			}
			else {
				$$('input[name="data[Cart][country]"]').each(function(el) {
					if ($(el).checked) {
						country = $(el).getValue();
					}
				});
			}
		}
		
		// check if address is PO box
		var pobox = false;
		if ($(address).getValue().match(/[Pp]\.?[Oo]\.?\s?[Bb][Oo][Xx]/g) || $(address2).getValue().match(/[Pp]\.?[Oo]\.?\s?[Bb][Oo][Xx]/g)) {
			pobox = true;
			clearShippingOptions();
		}

		if ((country == 'US') && !pobox) {	// FedEx shipping currently only available for US, non-PO box addresses
			new Ajax.Request('/cart/get_shipping_rates', {method: 'post', postBody: 'city=' + city + '&state=' + state + '&postal=' + postal + '&country=' + country, 
				onCreate: function() {
					// if shipping rates are listed from POSTed data
					clearShippingOptions();
			
					$('shipping-options').down('.radio').insert('<div id="shipping-options-status">Calculating shipping charges...</div>');
				}, 
				onSuccess: function(t) {
					$('shipping-options-status').remove();
				
					if (t.responseText !== 0) {
						if ($('fedex-shipping-options')) {
							$('fedex-shipping-options').remove();
						}
					
						var fedex_options = t.responseText.evalJSON();
						var html = '';
					
						var shipping_discount = 0.00;
						if ($('CartShippingDiscount')) {
							shipping_discount = $('CartShippingDiscount').getValue();
						}
					
						fedex_options.each(function(el) {
							if (el.rate !== false) {
								var shipping_total = el.rate - shipping_discount;
								
								if (shipping_total < 0) {
									shipping_total = 0.00;
								}
								
								shipping_total = parseFloat(shipping_total).toFixed(2);
								
								html += '<input type="radio" name="data[Cart][shipping_method]" id="CartShippingMethod' + el.id + '" value="' + shipping_total + '|' + el.name + '" /><label for="CartShippingMethod' + el.id + '">' + el.name + '  - $' + shipping_total + ' ' + el.transit + '</label><br />';
							}
						});
					
						$('shipping-options').down('.radio').insert('<div id="fedex-shipping-options" style="display:none;">' + html + '</div>');
						$('fedex-shipping-options').appear({duration:1});
					}
				}
			});
		}
		else {	// if customer is switching from US to Canada address remove rates
			clearShippingOptions();
		}
	}
}

function clearShippingOptions() {
	if ($('shipping-options').down('.radio').childElements().length > 3) {
		var num = $('shipping-options').down('.radio').childElements().length - 1;

		while (num > 2) {
			$('shipping-options').down('.radio').down(num).remove();
			num--;
		}
	}
}

function paymentMethodToggle() {
	if ($('CartCardInformation')) {
		$$('.card-info-field').each(function(el) {
			if ($(el).hasClassName('collapsed')) {
				$(el).hide();
			}
		});
		
		$('CartCardInformation').observe('change', function() {
			if ($(this).getValue() !== '') {
				$$('.card-info-field').each(function(el) {
					$(el).hide();
				});
			}
			else {
				$$('.card-info-field').each(function(el) {
					$(el).show();
				});
			}
		});
	}
}

document.observe('dom:loaded', paymentMethodToggle);

function useGiftCardToggle() {
	if ($('use_gift_certificate_balance')) {
		$('use_gift_certificate_balance').hide();
	}
	
	if ($('balance-totals')) {
		if ($('balance-totals').hasClassName('collapsed')) {
			$('balance-totals').hide();
		}
		
		$('CartUseGiftCard').observe('change', function() {
			if ($('CartUseGiftCard').checked) {
				$('use_gift_certificate_balance').slideDown({duration:0.25});
				
				if ($('CartGiftCardTotal').getValue() > 0) {
					// calculate new totals
					var gc_balance = $('CartGiftCardTotal').getValue();
					var order_balance = $('CartOrderTotal').getValue();
				
					$('cart-items-totals').insert('<tr><td colspan="5" id="gift-card-applied" class="gift-card-total">Amount Applied to Gift Card: $' + $('CartGcApplied').getValue() + '</td></tr>');
				
					$('balance-totals').show();
				
					// check if payment is needed
					if ($('billed-total').innerHTML == 0.00) {
						$('payment-information').hide();
					}
				}
			}
			else {
				$('use_gift_certificate_balance').slideUp({duration:0.25});
				$('balance-totals').hide();
				if ($('gift-card-applied')) {
					$('gift-card-applied').remove();
				}
				$('payment-information').show();
			}
		});
	}
}

document.observe('dom:loaded', useGiftCardToggle);

function orderHistoryRange() {
	if ($('CustomerRange')) {
		$('CustomerRange').observe('change', function() {
			$(this).up('form').submit();
		});
	}
}

document.observe('dom:loaded', orderHistoryRange);

function cvvDetailPopup() {
		if ($('cvv-detail')) {
			$('cvv-detail').observe('click', function(e) {
				e.stop();
				window.open(this.href, 'cvv_detail', 'width=579, height=233');
			});
		}
}

document.observe('dom:loaded', cvvDetailPopup);
