////////////////////////////////////////////////////////////////////////////////
//
// Beta Bar
//
// Author: Andrew Kallemeyn
// Date: June 2009
// Copyright (c) The Lampo Group, Inc. All rights reserved.
//
////////////////////////////////////////////////////////////////////////////////

var lampo = lampo || {};

lampo.beta_bar = Class.create({
	initialize: function(options) {
		this.options = lampo.beta_bar.util.getOptions(options, lampo.beta_bar.defaults);
		
		this.isAnimating  = false;
		this.isCollapsed  = true;
		this.isIE6 		  = lampo.beta_bar.util.isIE6();
		this.movedInView  = false; /* when beta bar is expanded, if the viewport 
									  is too small to show the entire form, the
									  beta bar is slid up to the top of the viewport
									  and this is set to true */
		
		// dynamically load our style sheet (think "CSS on-demand" ;)
		lampo.beta_bar.util.loadCSS(this.options.stylesheet);
	
		this.buildDOM();
		this.updateCommentCharCount();
		this.startWindowResizeObserver();
		
		if(this.isIE6) {
			/**
			 * in IE6, we need to delay running the IE fix function ("fixIE6();") because the stylesheet we injected
			 * into the DOM doesn't seem to immediately take effect in IE6, thus prototype's "getStyle" function (used for
			 * finding the "top" CSS value) fails
			 * 
			 */

			this.intervalID = setInterval("lpbb = lampo.beta_bar.getInstance(); lpbb.fixIE6();", 100);
		}
	},
	
	buildDOM: function() {
		//create HTML elements dynamically
		var objDivBetaBar = Builder.node('div', {'id': 'dr_betabar'},[
		                     Builder.node('div', {'id': 'dr_betabar_tab'}, [
		                          Builder.node('div', [
		                               Builder.node('a', {'href': '#'}, ["Feedback"])
		                          ])
		                     ]),
		                     
		                     Builder.node('div', {'id': 'dr_betabar_content', 'style': 'display:none'}, [
		                          Builder.node('div', {'id': 'dr_betabar_head'}, [
		                               Builder.node('div', {'id': 'dr_betabar_step1_head'}, [
		                                    Builder.node('div', {'id': 'dr_betabar_step1_icon'}),
		                                    Builder.node('h3', ["Your Feedback Counts!"]),
		                                    Builder.node('p', [
		                                         Builder.node('strong', ['The most helpful feedback we receive comes from our visitors. ']),Builder.node('br'),
		                                         'Please give us your suggestions for how we can make the website better.',Builder.node('br'), Builder.node('strong', ['Feature Requests: ']),Builder.node('br'), 'We plan all of our releases by thoroughly evaluating and implementing your requests.',
		                                    ])
		                               ]),
		                               
		                               Builder.node('div', {'id': 'dr_betabar_step2_head', 'style': 'display:none'}, [
		                                    Builder.node('div', {'id': 'dr_betabar_step2_icon', 'style': 'display:none'}),
		                                    Builder.node('h3', ['Thank You'])
		                               ])
		                          ]),
		                          
		                          Builder.node('form', {'id': 'dr_betabar_form', 'action': this.options.formAction, 'method': 'post'}, [
		                               Builder.node('div', {'id': 'dr_betabar_errors', 'style':'display:none'}),
		                               Builder.node('div', {'id': 'dr_betabar_step1_content'}, [
		                                    Builder.node('div', {'class': 'row'}, [
		                                         Builder.node('label', {'class': 'text_label', 'for': 'dr_betabar_intStarRating'}, ['Rate this website']),
		                                         Builder.node('ul', {'id': 'dr_betabar_ratings'}, [
		                                              Builder.node('li', [
		                                                   Builder.node('a', {'href': '#', 'title': '1'}, ["Poor"])
		                                              ]),
		                                              
		                                              Builder.node('li', [
		       		                                       Builder.node('a', {'href': '#', 'title': '2'}, ["Fair"])
		       		                                  ]),
		       		                                  
		                                              Builder.node('li', [
		       		       		                           Builder.node('a', {'href': '#', 'title': '3'}, ["Good"])
		       		       		                      ]),
		       		       		                      
		                                              Builder.node('li', [
		       		       		       		               Builder.node('a', {'href': '#', 'title': '4'}, ["Better than Good"])
		       		       		       		          ]),
		       		       		       		          
		                                              Builder.node('li', [
		       		       		       		       		   Builder.node('a', {'href': '#', 'title': '5'}, ["Awesome!"])
		       		       		       		       	  ])
		                                         ]),
		                                         Builder.node('div', {'id': 'dr_betabar_rating_legend'}),
		                                         Builder.node('input', {'type': 'hidden', 'name':'rating', 'id': 'dr_betabar_intStarRating'}),
		                                         Builder.node('br', {'class': 'clear'})
		                                    ]),
		                                    
		                                    Builder.node('div', {'class': 'row'}, [
		                                         Builder.node('label', {'class': 'comments', 'for': 'dr_betabar_strMessage'}, 'Comments'),
		                                         Builder.node('span', {'id': 'dr_betabar_char_count'} ,["0 of " + this.options.intCommentCharLimit + " characters"]),
		                                         Builder.node('textarea', {'name': 'comment', 'id':'dr_betabar_strMessage', 'rows':'6', 'cols':'20', 'class':'inactive'}, this.options.strDefaultCommentValue),
		                                         Builder.node('br', {'class': 'clear'})
		                                    ]),
		                                    
		                                    Builder.node('button', {'class': 'submit','type':'submit', 'id': 'dr_betabar_sendbtn'}, [
		                                         Builder.node('span', ["Send"])
		                                    ]),
		                                    
		                                    Builder.node('div', {'id': 'dr_betabar_loading_step1', 'style': 'display:none'}),
		                               ]),
		                               Builder.node('div', {'id': 'dr_betabar_step2_content', 'style':'display:none'}, [
		                                    Builder.node('p', ["Your feedback is valuable to us. If you'd like to give us more in-depth suggestions, please ",
		                                    		Builder.node('a', {'href':this.options.surveyURL, 'target':'_blank'}, ['click here']),
		                                    		". If you prefer to have the survey emailed to you, enter your email address below."]),
		                                    	 Builder.node('div', {'class': 'row'}, [
		                                         Builder.node('label', {'for': 'dr_betabar_strEmail'}, ["Email (optional)"]),
		                                         Builder.node('input', {'type': 'text', 'name':'email', 'id':'dr_betabar_strEmail','class':'inactive','value': this.options.strDefaultEmailValue}),
		                                         Builder.node('br', {'class': 'clear'})
		                                    ]),
		                                    Builder.node('button', {'class': 'submit', 'type':'submit', 'id': 'dr_betabar_finishbtn'}, [
		                                         Builder.node('span', ["Finish"])
		                                    ]),
		                                    Builder.node('div', {'id': 'dr_betabar_loading_step2', 'style': 'display:none'}),
		                                    Builder.node('br', {'class': 'clear'})		                                    
		                               ]),
		                               Builder.node('input', {'type': 'hidden', 'name': 'beta_bar_id', 'id': 'dr_betabar_betabar_id'}),
		                               Builder.node('input', {'type': 'hidden', 'name': 'date', 'id': 'dr_betabar_date'}),
		                               Builder.node('br', {'class': 'clear'}),
		                               Builder.node('div', {'id': 'dr_betabar_bottom_corner'})
		                          ])
		                     ])
		                ]);
	
		var objDivLboxOverlay = Builder.node('div', {'id': 'dr_betabar_overlay', 'style':'display:none'});
		var objDivSlideTo 	  = Builder.node('div', {'id':'dr_betabar_slideto'});

		Element.insert(document.body, objDivBetaBar);
		Element.insert(document.body, objDivLboxOverlay);
		Element.insert(document.body, objDivSlideTo);

		//Setup Events: "Feedback" Tab
		//------------------------------------------------------------------
		$$('#dr_betabar_tab a').each(function(e) {
			Event.observe(e, 'click', function(event) {
				lpbb = lampo.beta_bar.getInstance();
				lpbb.openClose();
				Event.stop(event);
			});
			
			Event.observe(e, 'mouseover', function(event) {
				this.parentNode.className = "hover";
				Event.stop(event);
			});
			
			Event.observe(e, 'mouseout', function(event) {
				this.parentNode.className = "";
				Event.stop(event);
			});
		});

		//Setup Events: Form ("Comments" Text Area)
		//------------------------------------------------------------------
		$$('#dr_betabar_step1_content textarea').each(function(e) {
			Event.observe(e, 'focus', function(event) {
				lpbb = lampo.beta_bar.getInstance();
				
				if(this.value == lpbb.options.strDefaultCommentValue) {
					this.value = "";
					this.className = "";
				}
				
				Event.stop(event);
			});
			
			Event.observe(e, 'blur', function(event) {
				lpbb = lampo.beta_bar.getInstance();
				
				if(this.value == "") {
					this.className = "inactive";
					this.value = lpbb.options.strDefaultCommentValue;
					lpbb.updateCommentCharCount();
				}
				
				Event.stop(event);
			});
			
			Event.observe(e, 'blur', function(event) {
				lpbb = lampo.beta_bar.getInstance();
				
				if(this.value == "") {
					this.className = "inactive";
					this.value = lpbb.options.strDefaultCommentValue;
					lpbb.updateCommentCharCount();
				}
				Event.stop(event);
			});
			
			Event.observe(e, 'keypress', function(event) {
				/**
				 * set "maxlength" limitation on textarea
				 * 
				 * more info:
				 * http://viralpatel.net/blogs/2008/12/set-maxlength-of-textarea-input-using-jquery-javascript.html
				 * 
				 */
				
				event = event || window.event;

				lpbb = lampo.beta_bar.getInstance();

				if(typeof(event.which) !== "undefined") {
					var key = event.which; 
				}else{
					var key = event.keyCode;	
				}

				if(key >= 33 || key == 13 || key == 32) {  
					var maxLength = lpbb.options.intCommentCharLimit;  
					var length = this.value.length;  
					if(length >= maxLength) {  
						Event.stop(event);
					}  
				}
			});
			
			Event.observe(e, 'keyup', function(event) {
				lpbb = lampo.beta_bar.getInstance();
				lpbb.updateCommentCharCount();
			});
		});
		
		//Setup Events: Star Ratings
		//------------------------------------------------------------------
		$$('#dr_betabar_ratings a').each(function(e) {
			Event.observe(e, 'mouseover', function(event) {
				if(this.parentNode.parentNode.className != "inactive") {
					this.className = "hover";
					$('dr_betabar_rating_legend').update(this.innerHTML);					
				}		
			});
			
			Event.observe(e, 'mouseout', function(event) {
				if(this.parentNode.parentNode.className != "inactive") {
					if(this.className != "active") {
						this.className = "";
					}
					$('dr_betabar_rating_legend').update('');
				}	
			});
			
			Event.observe(e, 'click', function(event) {
				lpbb = lampo.beta_bar.getInstance();
				lpbb.resetStarRatings();
				
				//log rating
				this.className = "active";
				this.parentNode.parentNode.className = "inactive";
					
				//store rating in the hidden field
				$('dr_betabar_intStarRating').value = this.title;
				$('dr_betabar_rating_legend').update(this.innerHTML);
				
				Event.stop(event);
			});	
		});

		//Setup Events: Send Button (step one)
		//------------------------------------------------------------------
		$('dr_betabar_sendbtn').observe('click', function(event) {
			lpbb = lampo.beta_bar.getInstance();
			lpbb.submitForm();
			Event.stop(event);
		});
		
		//Setup Events: Email Input (step two)
		//------------------------------------------------------------------
		oEmailInput = $$('#dr_betabar_step2_content input').each(function(e) {
			Event.observe(e, 'focus', function(event) {
				lpbb = lampo.beta_bar.getInstance();

				if(this.value == lpbb.options.strDefaultEmailValue) {
					this.value = "";
					this.className = "";
				}			
			});
			
			Event.observe(e, 'blur', function(event) {
				lpbb = lampo.beta_bar.getInstance();
				
				if(this.value == "") {
					this.value = lpbb.options.strDefaultEmailValue;
					this.className = "inactive";
				}		
			});			
		});

		//Setup Events: Finish Button (step two)
		//------------------------------------------------------------------
		$('dr_betabar_finishbtn').observe('click', function(event) {
			lpbb = lampo.beta_bar.getInstance();
			lpbb.submitForm();
			Event.stop(event);
		});

		//Setup Events: Form Submission
		//------------------------------------------------------------------
		$('dr_betabar_form').observe('submit', function(event) {
			lpbb = lampo.beta_bar.getInstance();
			lpbb.submitForm();
			Event.stop(event);
		});		

		//Setup Events: Hide overlay when clicked
		//------------------------------------------------------------------
		$('dr_betabar_overlay').observe('click', function(event) {
			lpbb = lampo.beta_bar.getInstance();
			lpbb.openClose();	
			Event.stop(event);
		});
	},
	
	updateCommentCharCount: function() {
		if($('dr_betabar_strMessage').value == this.options.strDefaultCommentValue) {
			intCharCount = 0;
			
		}else{	
			//get the length of the text area to make sure they haven't typed beyond the charater limit
			intCharCount = $('dr_betabar_strMessage').value.length;
		}
		
		//truncate length (prevents copying/pasting long messages)
		$('dr_betabar_char_count').update(intCharCount + " of " + this.options.intCommentCharLimit + " characters");
		
		if(intCharCount >= this.options.intCommentCharLimit) {
			//bring the user's attention to the character count
			$('dr_betabar_char_count').className = "error";
			
		}else{
			$('dr_betabar_char_count').className = "";
		}
	},
	
	animate: function(strEvent) {
		if(!this.isAnimating) {
			if(this.isIE6) {
				/**
				 * skip animating in IE6. instead, just show the the div's immediately (from display:none to display:block -- no transition)
				 * why? not only is animation in IE6 poor, but because position:fixed is not supported, it complicates things even more when elements move
				 * 
				 * because an IE6 hack is used to absolutely position the beta bar, we also need to change the width of the beta bar and run the
				 * IE6 fix before changing to display:block
				 * 
				 */
				
				//set class
				$('dr_betabar').className = strEvent;
				
				//determine the width to assign the beta bar (content area) and apply
				intBetaBarContentWidth = parseFloat($('dr_betabar_content').getStyle('width'));

				if(strEvent == "expand") {
					$('dr_betabar').style.width = intBetaBarContentWidth + "px";
					$('dr_betabar_content').show(); 
					
					this.isCollapsed = false;
					this.setOverlayDimensions_IE6();
					this.showOverlay();
					
					this.isInViewport = lpbb.inViewport();
					
					if(!this.isInViewport) {
						this.stopScrollObserver();
					}
					
				}else{
					this.resetForm();
					$('dr_betabar').style.width = "auto";
					$('dr_betabar_content').hide();
					
					this.isCollapsed = true;
					this.hideOverlay();
					this.startScrollObserver();
				}					

				//because we adjusted the beta bar width, run the IE6 scroll fix, which will recalculate the position
				this.absolutize();
				
			}else{
				//for all other browsers, do some fancy, cool animation
				arAnimationOptions = 
				{
					scaleX: true,
					scaleY: false,
					duration: this.options.intAnimationLength,
					
					beforeStart: function() {
						//tell the beta bar that an animation is in progress -- don't interrupt -- it creates wonkyness
						lpbb = lampo.beta_bar.getInstance();
						lpbb.isAnimating  = true;
						lpbb.isInViewport = lpbb.inViewport();
						
						if(!lpbb.isCollapsed) {
							lpbb.fixize();
						}
					},
					
					afterFinish: function() {
						lpbb = lampo.beta_bar.getInstance();
						lpbb.isAnimating  = false;
						
						if($('dr_betabar').className != "expand") {							
							$('dr_betabar').className = "expand";
							
							lpbb.isInViewport = lpbb.inViewport();

							if(!lpbb.isInViewport) {
								//if the beta bar is not within the viewport, set it to an absolute position so it can be scrolled through
								lpbb.absolutize();
								
								//if not within the viewport, move to the very top of the viewport
							    var offsets = document.viewport.getScrollOffsets();
							    var scrollY = offsets[1];
							    
							    var intOriginalTop = parseFloat($('dr_betabar').style.top);
							    
								new Effect.Tween('dr_betabar', intOriginalTop, scrollY, {duration: lpbb.options.intAnimationLength}, function(t) { this.style.top = t + "px"; } );							    
								
							}else{
								lpbb.movedInView = false;
							}
							
							lpbb.isCollapsed = false;
							
						}else{
							$('dr_betabar').className = "collapse";
							lpbb.isCollapsed = true;
							if(lpbb.movedInView) {
								lpbb.unAbsolutize();
							}
							
						}
					
						lpbb.resetForm();
					}
				};
				
				if(strEvent == "expand") {
					new Effect.BlindRight('dr_betabar_content', arAnimationOptions);
					this.showOverlay();
				}else{
					new Effect.BlindLeft('dr_betabar_content', arAnimationOptions);
					this.hideOverlay();
				}
			}
		}
	},
	
	inViewport: function() {
		/**
		 * checks to see if the beta bar is completely viewable within the viewport
		 * 
		 * - used when the beta bar is expanded to switch between position:fixed / position:absolute
		 *   if necessary
		 * 
		 */
		

		var position = $('dr_betabar').getStyle('position');
		
		if(position != "static") {
			var vheight  = document.viewport.getHeight();
			var bbheight = $('dr_betabar').getHeight();

			var offsets  = Element.positionedOffset($('dr_betabar'));
			var top = offsets[1];
			
			if($('dr_betabar').style.position == "absolute") {
			    var offsets = document.viewport.getScrollOffsets();
				var top = top - offsets[1];
			}
			
		    if(((bbheight + top) > vheight) || top < 0) {
	    		return false;
	    	}else{
	    		return true;
	    	}
		}
   	},
	
	fixIE6: function() {
		//determine the top position (defined in CSS as a percentage) -- since we need to use absolute, pixel 
		//positioning in IE6, grab the value now and use it in future pixel calculations
		this.intBetaBar_BaseY_IE6 = parseFloat($('dr_betabar').getStyle('top')) / 100;

		if(this.intervalID != null) {
			clearInterval(this.intervalID);
			this.intervalID = null;
		}
		
		this.absolutize();
		this.startScrollObserver();
	},
	
	startWindowResizeObserver: function() {
		/**
		 * when the window is resized, this function updates the absolute position coordinates to simulate position:fixed
		 * 
		 * - used in IE6 to simulate position:fixed
		 * - used if the beta bar is in the expanded state (thus, set to position:absolute) and the window is resized 
		 * 
		 */

		Event.observe(window, "resize", function() {
			lpbb = lampo.beta_bar.getInstance();
			lpbb.isInViewport = lpbb.inViewport();

			if(lpbb.isIE6 || !lpbb.isCollapsed) {
				lpbb.absolutize();
				
				if(lpbb.isIE6) {
					lpbb.setOverlayDimensions_IE6();
					
					if(!lpbb.isInViewport) {
						lpbb.stopScrollObserver();
					}else{
						lpbb.startScrollObserver();
					}
				}
			}
			
			if(!lpbb.isIE6) {
				if(!lpbb.isInViewport) {
					lpbb.absolutize();
				}else{
					lpbb.fixize();
				}
			}
		});		
	},
	
	startScrollObserver: function() {
		/**
		 * when the window is scrolled, this function updates the absolute position coordinates 
		 * 
		 * - used in IE6 to simulate position:fixed
		 * 
		 */
		
		Event.observe(window, "scroll", function() {
			lpbb = lampo.beta_bar.getInstance();
			lpbb.absolutize();			
		});
	},
	
	stopScrollObserver: function() {
		/**
		 * stops simulating position:fixed (i.e. updating absolute position coordinates on scroll)
		 * 
		 * - keeps the beta bar from "following" as the user scrolls -- used when the beta bar
		 *   is expanded in IE6
		 * 
		 */

		Event.stopObserving(window, "scroll");
	},
	
	absolutize: function() {
		/**
		 * absolutely positions the beta bar on the page, rather than using position:fixed
		 * 
		 * - used in in IE6 (on scroll) to simulate position:fixed
		 * - used when the beta bar is expanded so the form can be scrolled through
		 *   (good for smaller resolution monitors)
		 * 
		 * very loosely based off prototype's version of this function, however, prototype's function
		 * does not work correctly with position:fixed (it doesn't account for scroll position)
		 * 
		 */
	    
	    /* is the beta bar in a fixed or absolute position? */
	    var position = $('dr_betabar').getStyle('position');

	    if(position != "static") {
			/* get scroll offsets */
		    var offsets = document.viewport.getScrollOffsets();
		    var scrollY = offsets[1];
		    var scrollX = offsets[0];
		    
		    lpbb.movedInView = true;
		    
		    if(position != "fixed" || this.isIE6) {
		    	/* updates position:absolute coordinates to simulate position:fixed */
				/* get viewport dimensions */
				var dimensions = document.viewport.getDimensions();		
		    	var intBetaBarWidth = parseFloat($('dr_betabar').getWidth());
		    	var left = scrollX + dimensions.width  - intBetaBarWidth;
		    	
		    	if(this.isIE6) {
					if(typeof(this.intBetaBar_BaseY_IE6) == "undefined") { return; }
					var top = scrollY + (dimensions.height * this.intBetaBar_BaseY_IE6);
				}
	
		    }else{
		    	/* converts an element from position:fixed to position:absolute without changing position */
			    var offsets = Element.positionedOffset($('dr_betabar'));
			    
		    	var top     = offsets[1] + scrollY;
		    	var left    = offsets[0] + scrollX;
		    }
		   
		    var width   = $('dr_betabar').clientWidth;
		    var height  = $('dr_betabar').clientHeight;	

		    $('dr_betabar').style.position = 'absolute';
		    
		    if(typeof(top) != "undefined") {
		    	$('dr_betabar').style.top      = top + 'px';
		    }
	
		    $('dr_betabar').style.left     = left + 'px';
		    $('dr_betabar').style.width    = width + 'px';
		    $('dr_betabar').style.height   = height + 'px';
	    }
	},
	
	fixize: function() {
		/**
		 * takes an element from position:absolute to position fixed:while maintaining the top position
		 * (reverts to CSS definitions and applies a top position) 
		 * 
		 * - used as the beta bar is closing to prevent a jump as the beta bar reverts from position:absolute
		 *   back to position:fixed
		 * 
		 */

		//make sure the beta bar is in the absolute position
		if($('dr_betabar').style.position == "absolute") {
			offsets = document.viewport.getScrollOffsets();
			var topY = (parseFloat($('dr_betabar').style.top) - offsets[1]);
			Element.setStyle('dr_betabar', {position: 'fixed' , top: topY + 'px', left: 'auto', right: '0px', width: 'auto'});
		}
	},
	
	unAbsolutize: function() {
		/**
		 * moves beta bar to its default position:fixed position on the page (as originally specified in the CSS)
		 * 
		 * - used in standard-compliant browsers to return the beta bar to a fixed 
		 *   position when collapsed / closed
		 */

		var position 	   = $('dr_betabar').getStyle('position');

		if(position == "fixed") {
			var intOriginalTop = parseFloat($('dr_betabar').style.top);
			var intTargetTop   = Element.positionedOffset($('dr_betabar_slideto'))[1];
			
			
			new Effect.Tween('dr_betabar', intOriginalTop, intTargetTop, {duration: this.options.intAnimationLength, afterFinish: function() {
				$('dr_betabar').removeAttribute('style');
			}}, function(t) { this.style.top = t + "px"; } );
		}
	},
	
	showOverlay: function() {
		/**
		 * this fades out the page content to draw attention/focus to the beta bar
		 * 
		 */

		if(!this.options.overlayOpacity) {
			//get opacity from CSS
			intOpacity = $('dr_betabar_overlay').getStyle('opacity');
			this.options.overlayOpacity = intOpacity;
		}
		
		if(this.isIE6) {
			this.setOverlayDimensions_IE6();
			$('dr_betabar_overlay').show();
		}else{
			new Effect.Appear('dr_betabar_overlay',{ duration: this.options.intAnimationLength, from: 0.0, to: this.options.overlayOpacity});
		}
	},
	
	hideOverlay: function() {
		if(this.isIE6) {
			$('dr_betabar_overlay').hide();
		}else{
			new Effect.Fade('dr_betabar_overlay', { duration: this.options.intAnimationLength });
		}
	},
	
	setOverlayDimensions_IE6: function() {
		/**
		 * sets the overlay to the current page height / width
		 * 
		 * - used in IE6 to stretch the overlay across the entire page
		 *   to compensate for no position:fixed support in IE6
		 *   (called when the beta bar is opened and if the window is resized while open)
		 * 
		 */
		
		var dimensions = lampo.beta_bar.util.getPageSize();
		
		$('dr_betabar_overlay').style.width  = dimensions[0] + 'px';
		$('dr_betabar_overlay').style.height = dimensions[1] + 'px';
	},
	
	toggleSubmitButton: function() {
		//show or hide submit button based on current state
		//first, determine which step we are on...
		
		var buttonID = ($('dr_betabar_step1_head').visible()) ? 'dr_betabar_sendbtn' : 'dr_betabar_finishbtn';

		if($(buttonID).visible()) { 
			$(buttonID).hide();
		}else{
			$(buttonID).show();
		}		
	},
	
	submitForm: function() {
		if($('dr_betabar_step1_head').visible()) {
			/**
			 * step 1
			 * 
			 */
			
			this.hideError();
			
			if($('dr_betabar_strMessage').value == this.options.strDefaultCommentValue) {
				$('dr_betabar_strMessage').value = '';
			}
			
			/* display loading indicator */
			$('dr_betabar_loading_step1').show();
			
			/* fire off ajax request to post the form */
			$('dr_betabar_form').request({
				onCreate: function() {
					lpbb = lampo.beta_bar.getInstance();
					lpbb.toggleSubmitButton();
				},
			
				onComplete: function(transport) {
					lpbb = lampo.beta_bar.getInstance();
					lpbb.json = transport.responseText.evalJSON();
					if(typeof(lpbb.json.error) == "undefined") {
					//if (true) {
						if(typeof(lpbb.json.success) != "undefined") {
							$('dr_betabar_betabar_id').value = 'yes';						
//							$('dr_betabar_betabar_id').value = lpbb.json.success.intSubmissionID;
//							$('dr_betabar_date').value = lpbb.json.success.dteDateTime;
							
							//on a successful submit, fire submit function for analytics
//							if(typeof(BetaBar_Analytics.onSubmitComplete) == "function") {
//								BetaBar_Analytics.onSubmitComplete();
//							}
						}
						
						//transition to thank you screen				
						intTargetHeight 	= $('dr_betabar_step2_content').getHeight();
						intOriginalHeight	= $('dr_betabar_step1_content').getHeight();
						
						$('dr_betabar_step2_content').style.height = intOriginalHeight + "px";
				
						//swap headings from step 1 to step 2
						$('dr_betabar_step1_head').hide();
						$('dr_betabar_step2_head').show();
	
						//swap content from step 1 to step 2
						$('dr_betabar_step1_content').hide();
						$('dr_betabar_step2_content').show();
						
						if(Prototype.Browser.IE) {
							//IE seems to have an animation issue with the 24-bit PNG (IE6 - IE8), so just show it in these browsers.
							$('dr_betabar_step2_icon').show();
						}else{
							new Effect.Appear('dr_betabar_step2_icon');	
						}
						
						new Effect.Tween('dr_betabar_step2_content', intOriginalHeight, intTargetHeight, {duration: lpbb.options.intAnimationLength}, function(p) { this.style.height = p + "px"; } );
					
					}else{
						//display error
						lpbb.displayError();
					}
				}
			});			

			if($('dr_betabar_strMessage').value == '') {
				$('dr_betabar_strMessage').value = this.options.strDefaultCommentValue;
			}			
			
		}else{
			/**
			 * step 2
			 * 
			 */	
			if($('dr_betabar_strEmail').value !== this.options.strDefaultEmailValue) {
				//looks like they entered an email address to participate in our survey... send off an email
				//display loading indicator
				$('dr_betabar_loading_step2').show();
				$('dr_betabar_form').request({
					onCreate: function() {
						lpbb = lampo.beta_bar.getInstance();
						lpbb.toggleSubmitButton();
					},
					onComplete: function(transport) {
						lpbb.json = transport.responseText.evalJSON();
						if(typeof(lpbb.json.error) == "undefined") {		
							$('dr_betabar_loading_step2').className = "finished";
							$('dr_betabar_loading_step2').update("Email sent!");
							setTimeout("lpbb = lampo.beta_bar.getInstance(); lpbb.animate('collapse');", 1500);
						}else{
							//must be some sort of error...
							lpbb.displayError();
						}
					}
				});
			}else{
				//no email entered, close beta bar and reset
				this.animate("collapse");
			}
		}
		
		return false;		
	},
	
	hideError: function() {
		$$('#dr_betabar_errors ul').each(function(e) {
			//remove UL node
			e.remove();
		});
		
		$('dr_betabar_errors').hide();
	},
	
	displayError: function() {
		//hide loading indicator
		$('dr_betabar_loading_step1').hide();
		$('dr_betabar_loading_step2').hide();		

		this.hideError();
		this.toggleSubmitButton();
		
		objUL = Builder.node('ul');
		
		//display new errors
		for (i = 0; i < lpbb.json.error.length; i++) {
			arError = lpbb.json.error[i];
			objLI   = Builder.node('li', [arError.message]);
			Element.insert(objUL, objLI);
		}
		
		Element.insert('dr_betabar_errors', objUL);

		new Effect.BlindDown($('dr_betabar_errors'), {duration:this.options.intAnimationLength, afterFinish: function() {
			//make sure beta bar is still visible within the viewport. if not, absolute the position
			lpbb = lampo.beta_bar.getInstance();
			
			if(!lpbb.inViewport()) {
				lpbb.absolutize();
			}
		}
		});
	},
	
	resetStarRatings: function() {
		//unset the actively "checked" star rating
		$$('#dr_betabar_ratings a').each(function(e) {
			e.className = '';
		});
		
		$('dr_betabar_rating_legend').update('');
		$('dr_betabar_intStarRating').value = '';
	},
	
	resetForm: function() {
		/**
		 * this function is run after the beta bar is closed -- this resets the form fields and 
		 * makes sure that step 1 is being displayed
		 * 
		 */
		
		//make sure "step 1" of the form is shown
		$('dr_betabar_step1_head').show();
		$('dr_betabar_step2_head').hide();
		$('dr_betabar_step2_icon').hide();

		//swap content from step 1 to step 2
		$('dr_betabar_step1_content').show();
		$('dr_betabar_step2_content').hide();
		$('dr_betabar_step2_content').style.height  = "auto";

		$('dr_betabar_loading_step1').hide();
		$('dr_betabar_loading_step2').hide();
		
		//reset fields
		$('dr_betabar_strMessage').value 		= this.options.strDefaultCommentValue;
		$('dr_betabar_strMessage').className 	= "inactive";
		$('dr_betabar_strEmail').value			= this.options.strDefaultEmailValue;
		$('dr_betabar_strEmail').className		= "inactive";

		$('dr_betabar_betabar_id').value = '';
		$('dr_betabar_date').value = '';		
		
		$('dr_betabar_ratings').className = "";
		
		//show submit buttons
		$('dr_betabar_sendbtn').show();
		$('dr_betabar_finishbtn').show();
		
		this.hideError();
		this.resetStarRatings();
		this.updateCommentCharCount();
	},
	
	openClose: function() {
		if($('dr_betabar').className == "expand") {
			this.animate("collapse");

		}else{
			this.animate("expand");			
		}
		
		return false;		
	}
});

Object.extend(lampo.beta_bar, {
	util: {
		loadCSS: function(url) {
			var head = document.getElementsByTagName('head')[0];
			var l = document.createElement('link');
			l.rel = 'stylesheet';
			l.type = 'text/css';
			l.href = url;
			Element.insert(head, l);
		},
		
		mergeHash: function(dest, source) {
			for(var property in source) {
				dest[property] = source[property];
			}
			return dest;
		},
		
		getOptions: function(options, defaults) {
			return lampo.beta_bar.util.mergeHash(defaults || {}, options || {});
		},
		
		isIE6: function() {
			// do a quick browser check for IE6
			var w = window;
			var d = w.document;
			
			var ie  = w.VBArray;
			var ie6 = (ie && d.implementation);
			var ie7 = (ie && w.XMLHttpRequest); /* ie7 and newer */
			
			if(ie6 && !ie7) {
				return true;
			}else{
				return false;
			}
		},
		
		//
		// getPageSize()
		// Returns array with page width, height and window width, height
		// Core code from - quirksmode.org
		// Edit for Firefox by pHaez
		//
		getPageSize: function () {
			
			var xScroll, yScroll;
			
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = document.body.scrollWidth;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				windowWidth = self.innerWidth;
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}

			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = windowWidth;
			} else {
				pageWidth = xScroll;
			}


			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
			return arrayPageSize;
		}
	},
	
	getInstance: function() {
		return window.beta_bar;
	},
	
	defaults: {
		'intAnimationLength': 0.5,
		'strDefaultCommentValue': "Enter your comments and/or requests here...",
		'intCommentCharLimit': 200,
		'strDefaultEmailValue': "Enter your email here..."
	}
});



/**
 * below are some animation functions used in standard-compliant browsers
 * to make the beta bar slide out from the right side of the viewport
 * 
 * more info:
 * http://wiki.github.com/madrobby/scriptaculous/effect-blindup
 * http://wiki.github.com/madrobby/scriptaculous/effect-blinddown
 *  
 */
Effect.BlindRight = function(element) {
	  element = $(element);
	  var elementDimensions = element.getDimensions();
	  return new Effect.Scale(element, 100, Object.extend({
	    scaleContent: false,
	    scaleY: false,
	    scaleFrom: 0,
	    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
	    restoreAfterFinish: true,
	    afterSetup: function(effect) {
	      effect.element.makeClipping().setStyle({
	        width: '0px',
	        height: effect.dims[0] + 'px'
	      }).show();
	    },
	    afterFinishInternal: function(effect) {
	      effect.element.undoClipping();
	    }
	  }, arguments[1] || { }));
};

Effect.BlindLeft = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false,
      scaleY: false,
      scaleMode: 'box',
      scaleContent: false,
      restoreAfterFinish: true,
      afterSetup: function(effect) {
        effect.element.makeClipping().setStyle({
          height: effect.dims[0] + 'px'
        }).show();
      },
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      }
    }, arguments[1] || { })
  );
};

/**
 * Analytic Functions
 * 
 */

var BetaBar_Analytics = {
	onSubmitComplete: function() {
		if(typeof(Omniture) != "undefined") {
			if(Omniture.detectOmniture()) {
				if(typeof(s.pageName) != "undefined") {				
					var omnitureVars = {
										  'event': 21, 
										  'eVar40': $('dr_betabar_intStarRating').value, 
										  'eVar41': $('dr_betabar_strMessage').value
									   };
					
					var linkObj 	 = $('dr_betabar_sendbtn');
					var linkName 	 = "Send";
					var eventType	 = "o";
			
					Omniture.trackLink(linkObj, linkName, eventType, omnitureVars);
				}
			}
		}
	}
}

/**
 * DR09 Config Purposes Only
 * 
 */

document.observe("dom:loaded", function() {
	options = {
		stylesheet:   "/includes/javascript/ch_feedback/betabar.css",
		formAction:   "http://www.milleruniformsusa.com/commerce/ch_feedback.php",
		surveyURL:    "http://www.milleruniformsusa.com/commerce/limesurvey/index.php?sid=41764&lang=en"
	};

	window.beta_bar = new lampo.beta_bar(options);
});
