/*
	HMF Engineering JavaScript Functions
	Created by Kory Sharp
	Last Update: 12/07/2008
*/

	var email_check = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	document.observe("dom:loaded", function() {
		$('sub_nav').childElements().each(function(x) {
			x.onmouseover = function() { 
				$(this).addClassName('selected');
				if (x.down('iframe')) x.down('iframe').show();
			}
			x.onmouseout = function() { 
				$(this).removeClassName('selected');
				if (x.down('iframe')) x.down('iframe').hide();
			}
		});
		$('search_text').onfocus = function() { if (this.value == 'search by keyword or part number') this.value = ''; }
		$('search_text').onblur = function() { if (this.value == '') this.value = 'search by keyword or part number'; }
		
		$$('iframe').each(function(x) {
			var ul = x.next('ul');
			x.setStyle({ height: ul.getHeight() + 'px', width: ul.getWidth() + 'px' });
		});
	});
	
	// Image Viewer
	var ImageViewer = Class.create({
		images: [], // images in current pop set
		loaded: [], // images that have been preloaded
		heights: [], // height of image image
		widths: [], // width of each image
		speed: .3,  // duration for transitions below
		pos: undefined, // index position (from var images) of the current image
		initialize: function() {
		
			// makes sure the keyboard event as well as "this" (PopImg class) are available
			this.key_events = this.key_events.bindAsEventListener(this);
		
			// build out the skeleton of the popimg viewer (overlay and interior)
			var body = $$('body')[0];
			new Insertion.Bottom(body, $(Builder.node('div', { id: 'overlay' })).hide());
			new Insertion.Bottom(body, 
				$(Builder.node('div', { id: 'viewer' }, [
					Builder.node('div', { id: 'viewer_thumbs' }),
					Builder.node('a', { href: '#', id: 'viewer_close' }),
					Builder.node('div', { id: 'viewer_image_holder' }, [
						$(Builder.node('img', { id: 'viewer_image' })).hide(),
						Builder.node('div', { id: 'viewer_loading' })
					])
				])).hide()
			);
			
			$$('#product_thumbs a').each(function(x) {
				new Insertion.Bottom('viewer_thumbs', x.innerHTML);
			});
		
			// generate onclick events for the navigational items		
			$('viewer_close').observe('click', (function(event) { event.stop(); this.close(); }).bind(this));
			$('overlay').observe('click', (function(event) { event.stop(); this.close(); }).bind(this));
			
			$$('a[rel^=viewer]').each((function(x) {
				x.onclick = (function(img) {
					this.open(img);
					return false;
				}).bind(this, x);
			}).bind(this));
			
			// read the click event for any link containing popimg
			/*document.observe('click', (function(event){
	            var img = event.findElement('a[rel^=viewer]');
	            if (img) {
	                event.stop();
	                this.open(img);
	            } else {
	            	var thumb = Event.element(event).up('#viewer_thumbs');
	            	if (thumb) {
						this.switch_image(Event.element(event).previousSiblings().length);
	            	}
	            }
	        }).bind(this));*/
		},
		open: function(img) {
			// set the height of the overlay
			$('overlay').setStyle({ height: this.get_window_height() + "px" });
			// set the left position of the popimg viewer
			$('viewer').setStyle({ marginLeft: (document.viewport.getWidth() / 2) - ($('viewer').getWidth() / 2) + 'px' });
			
			// fade in the overlay and the popimg container
			new Effect.Appear('overlay', { 
				from: 0, 
				to: .6, 
				duration: this.speed,
				afterFinish: (function() {
					new Effect.Appear('viewer', { 
						from: 0, 
						to: 1, 
						duration: this.speed,
						afterFinish: (function() {
							this.find_images(img);
							this.enable_keyboard();
						}).bind(this)
					});	
				}).bind(this)
			});
		},
		close: function() {
			$('viewer').hide();
			$('viewer_image').hide();
			this.disable_keyboard();
			new Effect.Fade('overlay', { duration: this.speed });	
		},
		find_images: function(img) {
			this.images = [];
			this.loaded = [];
			this.pos = 0;
			if (img.readAttribute('rel') == 'viewer') {
				this.images.push([img.readAttribute('href')]);
				this.loaded.push(false);
			} else {
				$$('a[href][rel="' + img.readAttribute('rel') + '"]').uniq().each((function(img) {
					this.images.push([img.readAttribute('href')]);
					this.loaded.push(false);
				}).bind(this));
				for (var i = 0; i < this.images.length; i++ ) {
					if (this.images[i][0] == img.readAttribute('href')) {
						this.pos = i;
						break;
					}
				}
			}
			
			this.switch_image(this.pos);
		},
		switch_image: function(pos) {
			if (this.images.length > 1 || !$('viewer_image').visible()) {
				// make sure pos is in range
				if (pos < 0) pos = this.images.length - 1;
				else if (pos >= this.images.length) pos = 0;
				this.pos = pos;
				
				$$('#viewer_thumbs img').each(function(img) { img.removeClassName('selected'); });
				$$('#viewer_thumbs img')[this.pos].addClassName('selected');							
				
				new Effect.Fade('viewer_image', {
					duration: this.speed,
					afterFinish: (function() {
						if (!this.loaded[this.pos]) $('viewer_loading').show();
						var preload = new Image();
						preload.onload = (function() {
							this.loaded[this.pos] = true;
							
							if (arguments[0].width > 650) {
								new_width = (arguments[0].width > 650) ? 650 : arguments[0];
								new_height = (new_width / arguments[0].width) * arguments[0].height;
							} else {
								new_width = arguments[0].width;
								new_height = arguments[0].height;
							}
								
							this.widths[this.pos] = new_width;
							this.heights[this.pos] = new_height;
							
							width_diff = $('viewer_image_holder').getWidth() - new_width;
							new_left = (document.viewport.getWidth() / 2) - ((($('viewer').getWidth()) - width_diff) / 2);
							
							$('viewer_loading').hide();
							this.preload();
							
							new Effect.Morph('viewer', {
								style: { marginLeft: new_left + 'px' },
								duration: .5
							});
							new Effect.Morph('viewer_image_holder', {
								style: {
									height: new_height + 'px',
									width: new_width + 'px'
								},
								duration: .5,
								afterFinish: (function() {
									$('overlay').setStyle({ height: this.get_window_height() + "px" });
									$('viewer_image').src = this.images[this.pos][0];
									$('viewer_image').writeAttribute('width', new_width);
									new Effect.Appear('viewer_image', { duration: this.speed });
								}).bind(this)
							});
							
						}).bind(this, preload);
						preload.src = this.images[this.pos][0];
					}).bind(this)
				});
			}
		},
		preload: function() {
			// preload the previous and next images
			var previous = (this.pos > 0 && !this.loaded[this.pos - 1]) ? this.pos - 1 : this.images.length - 1;
			var back_preload = new Image();
			back_preload.onload = (function() { this.loaded[previous] = true; }).bind(this);
			back_preload.src = this.images[previous][0];
			
			var next = (this.pos < (this.images.length - 1) && !this.loaded[this.pos + 1]) ? this.pos + 1 : 0;
			var next_preload = new Image();
			next_preload.onload = (function() { this.loaded[next] = true; }).bind(this);
			next_preload.src = this.images[next][0];
		},
		enable_keyboard: function() { Event.observe(document, "keydown", this.key_events); },
		disable_keyboard: function() { Event.stopObserving(document, "keydown", this.key_events); },
		key_events: function(event) {
			switch (event.keyCode) {
				// 'b' or left arrow
				case 37:
				case 66:
					this.switch_image(this.pos - 1);
					break;
				// 'n' or right arrow
				case 39:
				case 78:
					this.switch_image(this.pos + 1);
					break;
				// esc, 'x', or 'c'
				case 27:
				case 67:
				case 88:
					this.close();
					break;
				default:
					break;
			}
		},
		get_window_height: function() {
			// retrieve the height of the document including scrollable area
			var document_height, window_height;
			
			if (window.innerHeight && window.scrollMaxY) document_height = window.innerHeight + window.scrollMaxY;
			else if (document.body.scrollHeight > document.body.offsetHeight) document_height = document.body.scrollHeight;
			else document_height = document.body.offsetHeight;
			
			if (self.innerHeight) window_height = self.innerHeight;
			else if (document.documentElement && document.documentElement.clientHeight) window_height = document.documentElement.clientHeight;
			else if (document.body) window_height = document.body.clientHeight;
			
			return (document_height < window_height) ? window_height : document_height;
		}
	});
	Event.observe(document, "dom:loaded", function() { var image_viewer = new ImageViewer(); });
	
	function exhaust_visualizer() {
		window.open('/misc/color/app.html','exhaust_help','width=690,height=443,top=150,left=150,scrollbars=0');
	}
	
	function series_comparison() {
		window.open('/series-comparison','series_comparison','width=1024,height=725,top=0,left=0,scrollbars=1');
	}
