var DIM6 = {
	// Begin site scripts.
	begin: function(){
		DIM6.makeHovers();
		DIM6.makeOneSubmitForms();
		DIM6.makeHelpTips();
		DIM6.makeTextBoxMaxChars();
		DIM6.makeCaptchaReload();
		DIM6.unhideEmailAddresses();
		DIM6.makeProductPrintButtons();
		DIM6.makePrintButtons();
		DIM6.setupProductSearchBox();
		DIM6.setupProductFilterControl();
		DIM6.setupProductFilterMoreLess();
		DIM6.setupProductResultsControl();
		DIM6.setupAddToCart();
		DIM6.makeSelectToggle();
		DIM6.makeShippingSameToggle();
		DIM6.makePaymentMethodToggle();
	},

	// Make hover buttons hoverable and preload hover images.
	makeHovers: function(){
		$$('.HoverButton').each(function(el){
			var OverImageSrc = el.getProperty('src');
			if (!$defined(OverImageSrc.match('-on.'))){
				OverImageSrc = OverImageSrc.replace('.','-over.')
				var PreloadImageObj = new Element('img', {'src': OverImageSrc});
				el.addEvent('mouseover', function(){
					el.setProperty('src', OverImageSrc);
				});
				el.addEvent('mouseout', function(){
					el.setProperty('src', OverImageSrc.replace('-over.','.'));
				});
			}
		});
	},

	// Make forms one-time submittable.
	makeOneSubmitForms: function(){
		// Preload Submitting Button
		var PreloadImageObj = new Element('img', {'src': './images/btn-sending.gif'});
		var Submitted = false;
		$$('form').each(function(el){
			// Keep track of submist status.
			// Bind submit event to form.
			el.addEvent('submit', function(){
				if (Submitted){
					return false;
				} else {
					Submitted = true;
					// Change submit button style to indicate submitting.
					var SendingButton = new Element('img',{'src':'./images/btn-sending.gif','styles':{'width':'93','height':'26'}});
					$$('.btnSubmit').each(function(btn){
						btn.removeEvents();
						btn.setProperty('src', './images/btn-sending.gif');
					});
					return true;
				}
			});
		});
	},

	// Make Help Tips
	makeHelpTips: function(){
		$$('.HelpTips').each(function(el){
			var full_title	= el.getProperty('title');
			var dual = full_title.split('::');
			var tip_title = dual[0].trim();
			var tip_text = dual[1].trim();
			el.store('tip:title', tip_title);
			el.store('tip:text', tip_text);
		});
		var HelpTips = new Tips($$('.HelpTips'), {
			showDelay: 200,
			onShow: function(tip) {
				tip.set('tween', {duration: 250}).fade('in');
			},
			onHide: function(tip) {
				tip.set('tween', {duration: 250}).fade('out');
			}
		});
	},

	// Make Text Box Max Character Note/Limit
	makeTextBoxMaxChars: function(){
		$$('.MaxChars').each(function(el){
			var MaxChars = el.getProperty('title').toInt();
			el.addEvent('focus', function(){
				new Element('div', {
				'styles': {
					'color': '#b7b0aa',
					'font-size': '9px',
					'text-align': 'right',
					'width': el.getStyle('width')
				},
				'id': 'MaxCharDiv'
				}).injectAfter(el);
				if (MaxChars - el.value.length < 0){
					$('MaxCharDiv').setStyle('color','#ff0000');
					$('MaxCharDiv').setHTML('Please Remove '+(el.value.length-MaxChars)+' Character'+((el.value.length-MaxChars)==1?'':'s'));
				} else {
					$('MaxCharDiv').setStyle('color','#b7b0aa');
					$('MaxCharDiv').setHTML((MaxChars-el.value.length)+' Character'+((MaxChars-el.value.length)==1?'':'s')+' Remaining');
				}
			});
			el.addEvent('keyup', function(){
				if (MaxChars - el.value.length < 0){
					$('MaxCharDiv').setStyle('color','#ff0000');
					$('MaxCharDiv').setHTML('Please Remove '+(el.value.length-MaxChars)+' Character'+((el.value.length-MaxChars)==1?'':'s'));
				} else {
					$('MaxCharDiv').setStyle('color','#b7b0aa');
					$('MaxCharDiv').setHTML((MaxChars-el.value.length)+' Character'+((MaxChars-el.value.length)==1?'':'s')+' Remaining');
				}
			});
			el.addEvent('blur', function(){
				$('MaxCharDiv').remove();
			});
		});
	},

	// Make CAPTCHA Reload Functionality
	makeCaptchaReload: function(){
		if ( ($defined($('CAPTCHA_RELOAD'))) && ($defined($('CAPTCHA_IMAGE'))) ){
			$('CAPTCHA_RELOAD').addEvent('click', function(){
				$('CAPTCHA_IMAGE').set('src','./?captcha=XH4ma9ScXg298p3uYr4X73iqPmG'+$random(10000,99000));
				if ($defined($('CAPTCHA'))) $('CAPTCHA').value = '';
			});
		}
	},

	// Unhide Email Addresses
	unhideEmailAddresses: function(){
		$$('.HideEmail').each(function(el){
			var DecodedEmail = unescape(el.getProperty('rel'));
			el.set('href','mailto:'+DecodedEmail);
			el.set('html',DecodedEmail);
		});
	},

	// Make Product Print Buttons
	makeProductPrintButtons: function(){
		if ($defined($('ProductPrintButton'))){
			new IFrame({
				id: 'iFramePrint',
				name: 'iFramePrint',
				events: {
					load: function(){
						// Fire Print
						DIM6.firePrintCommand();
					}
				}
			}).inject($('iFramePrint_Container'),'top');
			$('ProductPrintButton').addEvent('click', function(){
				if (confirm('You are about to print this product\'s details. You will have the option to include full-size Photos and/or Frame Sketches.\nOK = Continue | Cancel = Cancel Print')){
					var ProductNumber = $('ProductPrintButton').get('rel');
					// Prompt for options.
					var PrintPhotos = confirm('Option 1 of 2:\nWould you like to print full-size product Photos?\nOK = Yes | Cancel = No');
					var PrintSketches = confirm('Option 2 of 2:\nWould you like to print full-size product Frame Sketches?\nOK = Yes | Cancel = No');
					var PrintOptions = '';
					if ( (!PrintPhotos) || (!PrintSketches) ){
						if (!PrintPhotos) PrintOptions = PrintOptions+'&photo=no';
						if (!PrintSketches) PrintOptions = PrintOptions+'&sketch=no';
					}
					$('iFramePrint').set('src','./?page=product-print&part='+ProductNumber+PrintOptions);
				}
				return false;
			});
		}
	},
	firePrintCommand: function(){
		if ($defined($('iFramePrint').get('src'))){
			if (Browser.Engine.trident){
				document.iFramePrint.focus();
				document.iFramePrint.document.execCommand('print', false, null);
			} else {
				window.frames['iFramePrint'].focus();
				window.frames['iFramePrint'].print();
			}
		}
	},

	// Make Print Buttons
	makePrintButtons: function(){
		if ($defined($('PrintButton'))){
			new IFrame({
				id: 'iFramePrint',
				name: 'iFramePrint',
				events: {
					load: function(){
						// Fire Print
						DIM6.firePrintCommand();
					}
				}
			}).inject($('iFramePrint_Container'),'top');
			$('PrintButton').addEvent('click', function(){
				$('iFramePrint').set('src',$('PrintButton').get('rel'));
				return false;
			});
		}
	},
	firePrintCommand: function(){
		if ($defined($('iFramePrint').get('src'))){
			if (Browser.Engine.trident){
				document.iFramePrint.focus();
				document.iFramePrint.document.execCommand('print', false, null);
			} else {
				window.frames['iFramePrint'].focus();
				window.frames['iFramePrint'].print();
			}
		}
	},

	// Product Search Box
	setupProductSearchBox: function(){
		var el = $('SearchBox');
		var def = 'Keywords or Part Number';
		if ($defined(el)){
			el.value = def;
			el.addEvent('focus', function(){
				if (el.value == def){
					el.value = '';
					el.setStyles({color: '#000000'});
				}
			});
			el.addEvent('blur', function(){
				if (el.value == ''){
					el.value = def;
					el.setStyles({color: '#898989'});
				}
			});
			// Block search submission if nothing entered.
			$('SearchForm').addEvent('submit', function(){
				if ( (el.value == '') || (el.value == def) ) return false;
				else return true;
			});
		}
	},

	// Product Filter Control
	setupProductFilterControl: function(){
		var Domain = document.domain.replace(/www./,'').replace(/secure./,'');
		if ($defined($('ProductFilterControl'))){
			// Bind Control
			$('ProductFilterLinkView').addEvent('click', function(){
				$('ProductFilterLinkView').setStyles({display: 'none'});
				$('ProductFilterDropView').setStyles({display: 'inline'});
				$('ProductFilters_Links').setStyles({display: 'inline'});
				$('ProductFilters_Drop').setStyles({display: 'none'});
				Cookie.write('ProductFilterView', 'link', {duration: 365, domain: '.'+Domain});
				return false;
			});
			$('ProductFilterDropView').addEvent('click', function(){
				$('ProductFilterLinkView').setStyles({display: 'inline'});
				$('ProductFilterDropView').setStyles({display: 'none'});
				$('ProductFilters_Links').setStyles({display: 'none'});
				$('ProductFilters_Drop').setStyles({display: 'inline'});
				Cookie.write('ProductFilterView', 'drop', {duration: 365, domain: '.'+Domain});
				return false;
			});

			// Determine Current State
			var FilterViewCookie = Cookie.read('ProductFilterView');
			var FilterView = 'drop';
			if ($defined(FilterViewCookie)){
				FilterView = FilterViewCookie.toLowerCase();
			}
			if (FilterView == 'link'){
				$('ProductFilterLinkView').setStyles({display: 'none'});
				$('ProductFilterDropView').setStyles({display: 'inline'});
				$('ProductFilters_Links').setStyles({display: 'inline'});
				$('ProductFilters_Drop').setStyles({display: 'none'});
			} else {
				$('ProductFilterLinkView').setStyles({display: 'inline'});
				$('ProductFilterDropView').setStyles({display: 'none'});
				$('ProductFilters_Links').setStyles({display: 'none'});
				$('ProductFilters_Drop').setStyles({display: 'inline'});
			}
		}
	},

	// Product Result Display Control
	setupProductResultsControl: function(){
		var Domain = document.domain.replace(/www./,'').replace(/secure./,'');
		if ($defined($('ProductResultControl'))){
			// Bind Control
			$('ProductResultDetailView').addEvent('click', function(){
				$('ProductResultDetailView').setStyles({display: 'none'});
				$('ProductResultListView').setStyles({display: 'inline'});
				$('ProductResults_Detailed').setStyles({display: 'inline'});
				$('ProductResults_List').setStyles({display: 'none'});
				Cookie.write('ProductResultView', 'detailed', {duration: 365, domain: '.'+Domain});
				return false;
			});
			$('ProductResultListView').addEvent('click', function(){
				$('ProductResultDetailView').setStyles({display: 'inline'});
				$('ProductResultListView').setStyles({display: 'none'});
				$('ProductResults_Detailed').setStyles({display: 'none'});
				$('ProductResults_List').setStyles({display: 'inline'});
				Cookie.write('ProductResultView', 'list', {duration: 365, domain: '.'+Domain});
				return false;
			});

			// Determine Current State
			var ResultsViewCookie = Cookie.read('ProductResultView');
			var ResultsView = 'list';
			if ($defined(ResultsViewCookie)){
				ResultsView = ResultsViewCookie.toLowerCase();
			}
			if (ResultsView == 'detailed'){
				$('ProductResultDetailView').setStyles({display: 'none'});
				$('ProductResultListView').setStyles({display: 'inline'});
				$('ProductResults_Detailed').setStyles({display: 'inline'});
				$('ProductResults_List').setStyles({display: 'none'});
			} else {
				$('ProductResultDetailView').setStyles({display: 'inline'});
				$('ProductResultListView').setStyles({display: 'none'});
				$('ProductResults_Detailed').setStyles({display: 'none'});
				$('ProductResults_List').setStyles({display: 'inline'});
			}
		}
	},

	// Product Filter More and Less Links
	setupProductFilterMoreLess: function(){
		if ($defined($('ProductFilterControl'))){
			// Bind "More"
			$$('.ProductFilterMoreLink').each(function(el){
				// Get ID
				var LinkIDArray = new Array();
				LinkIDArray = el.get('id').split('_');
				var LinkID = LinkIDArray[1];
				// Bind Click
				el.addEvent('click', function(){
					$('ProductFilterMore_'+LinkID).setStyles({display: 'none'});
					$('ProductFilterMoreValues_'+LinkID).setStyles({display: 'inline'});
					return false;
				});
			});
			// Bind "Less"
			$$('.ProductFilterLessLink').each(function(el){
				// Get ID
				var LinkIDArray = new Array();
				LinkIDArray = el.get('id').split('_');
				var LinkID = LinkIDArray[1];
				// Bind Click
				el.addEvent('click', function(){
					$('ProductFilterMore_'+LinkID).setStyles({display: 'inline'});
					$('ProductFilterMoreValues_'+LinkID).setStyles({display: 'none'});
					return false;
				});
			});
		}
	},

	// Add to Cart
	setupAddToCart: function(){
		$$('.CartButton').each(function(el){
			// Bind Click
			el.addEvent('click', function(){
				// Check for Part
				var PartNumber = '';
				if ($defined($('CartPart'))) PartNumber = $('CartPart').value; // Get Part Number from hidden field.
				else {
					// Get Part Number from button link id "AddToCart_[PartNumber]"
					var LinkIDArray = new Array();
					LinkIDArray = el.get('id').split('_');
					PartNumber = LinkIDArray[1];
				}
				// Check for Quantity
				var Quantity = 1;
				if ($defined($('CartQuantity'))) Quantity = $('CartQuantity').value;

				// Do Request. Display response in Mediabox.
				if (PartNumber != ''){
					// Inject new div element into document.
					var CartReplyElement = new Element('div', {'id':'mb_CartReplyElement', 'html':'Adding to cart...', 'styles':{'display':'none'}});
					CartReplyElement.inject($('Container'),'after');

					// Do request and put response into new div element and open with Mediabox.
					var HTMLRequest = new Request.HTML({
						url:'./',
						method:'post',
						data:'page=cart-add&ajax=1&part='+PartNumber+'&CartQuantity='+Quantity,
						onSuccess: function(html){
							$('mb_CartReplyElement').set('html', '');
							$('mb_CartReplyElement').adopt(html);
							// Open MediaBox
							Mediabox.open('#mb_CartReplyElement', 'Item "'+PartNumber+'" Added to Cart', '600 300');
							// Remove div element
							$('mb_CartReplyElement').destroy();
						},
						onFailure: function(){
							$('mb_CartReplyElement').set('html', 'The request failed.');
							// Open MediaBox
							Mediabox.open('#mb_CartReplyElement', 'Error: Add to Cart failed', '600 300');
							// Remove div element
							$('mb_CartReplyElement').destroy();
						}
					}).send();
				}

				// Disable link or form submit.
				return false;
			});
		});
	},

	// Make Checkbox Select Toggles
	makeSelectToggle:  function(){
		var Status = 0;
		$$('.SelectToggle').each(function(el){
			// Bind Click
			el.addEvent('click', function(){
				if (Status == 0){
					Status = 1;
					$$('.SelectToggleBox').each(function(el){
						el.checked = true;
					});
				} else {
					Status = 0;
					$$('.SelectToggleBox').each(function(el){
						el.checked = false;
					});
				}
				return false;
			});
		});
	},

	// Make Shipping Same as Billing Toggle
	makeShippingSameToggle: function(){
		// Bind Click
		if ($defined($('ShippingSame'))){
			$('ShippingSame').addEvent('change', function(){
				if ($('ShippingSame').checked == true){
					// Set all Shipping fields to Billing counterpart if toggled on.
					$$('.BillingField').each(function(el){
						$$('.ShippingField[name='+el.get('name')+'Ship]').each(function(els){
							els.value = el.value;
						});
					});
				} else {
					// Clear all Shipping Fields if toggled off.
					$$('.ShippingField').each(function(el){
						el.value = '';
					});
				}
			});
			// Uncheck "Same as Billing" field if any Shipping Field is changed.
			$$('.ShippingField').each(function(el){
				el.addEvent('keydown', function(){
					$('ShippingSame').checked = false;
				});
			});
		}
	},

	// Make Cehckout Payment Method Toggle
	makePaymentMethodToggle: function(){
		if ($defined($('PaymentMethod_CREDITCARD'))){
			// Inital Page Load set.
			if ($('PaymentMethod_CREDITCARD').checked == true){
				// Hide Purchase Order fields if toggled on.
				$$('.CheckoutCreditCard').each(function(el){
					el.setStyles({display: ''});
				});
				$$('.CheckoutPurchaseOrder').each(function(el){
					el.setStyles({display: 'none'});
				});
			} else {
				// Hide Credit Card fields if toggled off.
				$$('.CheckoutCreditCard').each(function(el){
					el.setStyles({display: 'none'});
				});
				$$('.CheckoutPurchaseOrder').each(function(el){
					el.setStyles({display: ''});
				});
			}
			$('PaymentMethod_CREDITCARD').addEvent('click', function(){
				if ($('PaymentMethod_CREDITCARD').checked == true){
					// Hide Purchase Order fields if toggled on.
					$$('.CheckoutCreditCard').each(function(el){
						el.setStyles({display: ''});
					});
					$$('.CheckoutPurchaseOrder').each(function(el){
						el.setStyles({display: 'none'});
					});
				} else {
					// Hide Credit Card fields if toggled off.
					$$('.CheckoutCreditCard').each(function(el){
						el.setStyles({display: 'none'});
					});
					$$('.CheckoutPurchaseOrder').each(function(el){
						el.setStyles({display: ''});
					});
				}
			});
			$('PaymentMethod_PURCHASEORDER').addEvent('click', function(){
				if ($('PaymentMethod_PURCHASEORDER').checked == true){
					// Hide Credit Card fields if toggled off.
					$$('.CheckoutCreditCard').each(function(el){
						el.setStyles({display: 'none'});
					});
					$$('.CheckoutPurchaseOrder').each(function(el){
						el.setStyles({display: ''});
					});
				} else {
					// Hide Purchase Order fields if toggled on.
					$$('.CheckoutCreditCard').each(function(el){
						el.setStyles({display: ''});
					});
					$$('.CheckoutPurchaseOrder').each(function(el){
						el.setStyles({display: 'none'});
					});
				}
			});
		}
	}
};

window.addEvent('domready', DIM6.begin);

// Exclude Print option from AddThis widget.
var addthis_exclude = 'print';

