(function ($) {
  
  var so_async = {
    items: [],
    defaults: {
      version: "9.0.0", // Flash 9
      installer: "/shower-head/swf/expressInstall.swf",
      flashvars: {},
      params: { wmode: 'transparent' },
      attributes: {},
      wrap: true // Adds an inner item to the ID specified
    },
    push: function (values) {
      this.items.push(values);
      this.process();
    },
    process: function () {
      var so = this;
      $.each(so.items, function (i, item) {
         var o = $.extend({}, so.defaults, item),
             wrap;
         
         if (o.wrap) {
           wrap = $("#" + o.id).wrapInner($('<div />', {id: o.id + "-inner"}));
           o.id += "-inner";
         }
         
         swfobject.embedSWF(o.swf, o.id, o.width, o.height, o.version, o.installer, o.flashvars, o.params, o.attributes);
      });
    }
  };
  
  
  if (window.so_async !== undefined) {
    so_async.items = window.so_async;
    window.so_async = so_async;
    
    $(function () {
      // Run when DOM is ready
      so_async.process();
    });
    
  } else {
    window.so_async = so_async;
  }
  
  
  $(function () {
    $("#footer .navigation a").append("<em>&rarr;</em>");
    
    // Enable Pseudo Submit Buttons
    $("form a.submit").live("click", function (e) {
      e.preventDefault();
      $(this).closest('form').submit();
    });
    
    var $footer_message;
    
    $("#footer form").submit(function (e) {
      e.preventDefault();
      
      var url = $(this).attr('action'),
          email = $.trim($("#email_address").val()),
          form = $(this);
      
      if (!email) {
        set_footer_message('You must enter an email address.', false);
        return;
      }
      
      form.addClass("loading");
      
      $.post(url, { email_address: email }, function (data) {
        form.removeClass("loading");
        if (data && data.success) {
          set_footer_message(signup_success);
          $("#email_address").val('').blur();
        } else {
          set_footer_message(data.error_message, false);
        }
      }, "json");
    });
    
    function set_footer_message(message, success) {
      if (success !== false) {
        success = true;
      };
      if(!$footer_message) {
        $footer_message = $("<p />", {id: "signup_message" }).appendTo("#footer form");
      }
      $footer_message[0].className = (success ? "signup-success" : "signup-error");
      $footer_message.html(message);
    }
    
    // Greate Pseduo Submit Buttons
    $("input:submit").each(function () {
      var submit = $(this);
      $("<a />", {
        className: "button submit",
        html: '<span>' + submit.val() + '</span>',
        href: '#join'
      }).insertAfter(submit);
    });
    
    // Cause Label to Fade
    $("#footer label").inFieldLabels();
    
    $("#qa").delegate('dt', 'click', function (e) {
      e.preventDefault();
      var dt   = $(this).closest('dt'),
          dd   = dt.next(),
          a    = dt.find('a.answer'),
          open = dd.is(':visible');
          
        a.toggleClass('open', !open);
        dd[open ? 'slideUp' : 'slideDown']();
    });
    
    $("<a />", {href: "#", className: "answer", html: "Answer<em></em>"}).appendTo("#qa dt");
    
    // Normalize Lists
    $("ul.normalized").each(function (i, el) {
      var ul     = $(el), 
          ul_alt = $("<ul />"),
          org_l  = ul.text().length,
          length = org_l / 2,
          count  = 0,
          data   = ul.attr('data-split');
      
      if (data) {
        count = parseInt(data, 10);
      } else {
        ul.children().each( function(j, li) {
          var text = $(li).text().length;
          length = length - text;
          if (length > 0) {
            count = count + 1;
          } else {
            if(length + (text * 0.85) < 0) {
              count = count + 1; 
            }
            return false; // Exit loop
          }
        });
      }
      
      ul
        .wrap("<div class='normalized'></div>")
        .removeClass('normalized')
        .after(ul_alt)
        .children()
          .slice(count)
          .appendTo(ul_alt);
          
    });
    
    // Create the More Info / Less Info Button
    var $more = $("#product div.more-info");
    $("<div />", {
      className: 'more-info-helper',
      html: $("<a />", {
        href: '#',
        html: '<span>More Info</span><em></em>',
        click: function (e) {
          e.preventDefault();
          
          var turn_off = $more.is(':visible');
          
          $more[turn_off ? 'slideUp' : 'slideDown'](); // Open/Close Extra
          $(this)
            .removeClass('hover') // Make sure hover style goes away
            .toggleClass('open', !turn_off) // Class to control arrow direction
            .find('span').text( turn_off ? 'More Info' : 'Less Info'); // Text
        }
      }).hover(function () {
        $(this).addClass('hover');
      }, function () {
        $(this).removeClass('hover');
      })
    }).insertAfter($more);
    
    // Enable Tout Scrolling
    var tout = $("#tout");
    
    if (tout.find('li').length > 1) {
      tout
        .addClass('anythingSlider')
        .wrapInner('<div class="wrapper" />')
        .anythingSlider({
          delay: 5000,
          buildNavigation: false,
          hashTags: false
        }).find('.thumbNav, .start-stop').remove();      
    }
  });



  $("#page .product-cell").live("click", function (e) {
    if ( $(e.target).closest(".checker").length ) {
      return; // Don't redirect checkboxes in the product selection tool
    }
    e.preventDefault();
    var href = $(this).find("a").attr("href");
    window.location = href;
  });
  
  $(".also-like li").live("click", function (e) {
    e.preventDefault();
    var href = $(this).find("a").attr("href");
    window.location = href;
  });
  
  $(function () {
    var is_home     = $("html").hasClass('home'),
        property    = is_home ? "top" : "bottom",
        $nav        = $("#product-nav"),
        $items      = $nav.children(),
        anim_open   = {},
        anim_closed = {},
        sub_menu_open = false,
        intent_timer  = null,
        previous = {},
        animate_previous = function () {
          previous.ul.stop(true, false).css('z-index', 5).animate(anim_closed, { duration: 300 });
          previous.bg.stop(true, false).animate(anim_closed, { duration: 300 });
        }
        
    anim_closed[property] = 0;
    anim_open[property]   = -43;
    
    $nav.hover(function () {
      $nav.addClass('other-hover');
    }, function () {
      $nav.removeClass('other-hover');
    });
    
    // Since a lot of traversal would happen with a delegated event
    // A normal loop + binding is done to cause this to happen only once.
    $nav.children().each(function () {
      var $li = $(this), 
          $ul = $li.find("ul"), 
          $bg;

      if ($ul.length) {
        $bg = $("<div />", { className: "bg" }).insertAfter($ul).show();
        
        $ul.show();
        
        $li.hover(function (e){ 
          
          if($(e.target).is("ul")) {
            if (previous.li && previous.li !== $li) {
              animate_previous();
            }

            window.clearTimeout(intent_timer);

            $li.addClass('menu-active');
            return;
          }
          
          intent_timer = window.setTimeout(function () {
            if (previous.li && previous.li !== $li) {
              animate_previous();
            }

            window.clearTimeout(intent_timer);

            $li.addClass('menu-active');
            $ul.stop(true, false).css('z-index', 5).animate( anim_open, 300, function () {
              // We need the links to sit on "top" of the pointer coming from the selected menu item
              $ul.css('z-index', 20);
            });
            $bg.stop(true, false).animate(anim_open, { duration: 300 });
          }, 200);
        }, function () {
          window.clearTimeout(intent_timer);
          
          previous = {
            li: $li,
            ul: $ul,
            bg: $bg
          };
          
          $li.removeClass('menu-active');
          
          intent_timer = window.setTimeout(animate_previous, 500);
        });
                // 
                // $ul.hover( function () {
                //   window.clearTimeout(intent_timer);
                // }, function () {
                //   intent_timer = window.setTimeout(animate_previous, 500);
                // });
        
      }
    });
  });
  
  $(function () {
	var initial_load    = true,
		$subnav         = $("#subnav"),
		$sections       = $(".section"),
		section_ids     = $sections.map(function (el, i) { return this.id }).get(),
		$links          = $subnav.find('li'),
		
		show_tab = function (tab) {
			var index = $sections.index(tab);
			
			$("#page .section").not(tab).hide();
			tab.show();
			
			$links
				.removeClass("active")
				.eq(index)
					.addClass("active");
		};
		
  	$("#subnav li a.internal").bind("click", function(e){
		var new_tab = $(this).attr("href").substr(1) + "-tab";
		window.location.hash = new_tab;
		e.preventDefault();
  	});

	if ($subnav.length) {
		$(window).hashchange(function () {
			var hash = location.hash.substr(1).replace('-tab', ''),
				el = hash ? $("#" + hash) : $();
			if ($.inArray(hash, section_ids) > -1) {
				show_tab( el );
			} else {
				if (el.length) {
					window.setTimeout(function () {
						$("html, body").scrollTop(el.offset().top);
						var parent = el.closest(".section");
					}, 100);
					show_tab(parent.length ? parent : $sections.first());
				} else {
					show_tab($sections.first());
				}
				
			}
		}).hashchange();
	}
	
	$("#page, #product").delegate(".quick-info-button:not(.popup-setup) strong, .also-like > li:not(.popup-setup)", "mouseenter", function () {
		var button = $(this).addClass('popup-setup'),
  			popup = button.closest("li, div").first().find(".popup"),
  			popuparrow = popup.next('.popup-arrow');
  		button.hover( function(){
  			popup.show();
  			popuparrow.show();
		}, function(){
			popup.hide();
  			popuparrow.hide();
		}).mouseenter();
	});

  	$("a.toplink").bind("click", function(){
  		$("html, body").animate({scrollTop: 0}, 200);
  		return false;
  	});
  	$(".thumbzoom-t").bind("click", function(){
  		$(this).siblings().fadeIn(150);
  		return false;
  	});
  	$(".thumbzoom-close").bind("click", function(){
  		$(this).parent().find(".thumbzoom-l").add(this).fadeOut(150);
  		return false;
  	});
  });
  
	function formatCommas(num) {
		return String(num).replace(/^\d+(?=\.|$)/, function (int) { return int.replace(/(?=(?:\d{3})+$)(?!^)/g, ","); });
	}
  	
  	$(function() {
		function simpleWaterCalc() {
			var showers = Number($showers.val()),
				minutes = Number($minutes.val()),
				gallons = Number($gallons.val()),
				flow    = Number($flow.val()),
				watersaved = "", gassaved = "", dollarssaved = "",
				
				gasperwater = 649331.31 / 1460000, 	// the conversion of units of gallons to cu-ft
				watercost   = 12100 / 1460000, 		// cost of water per gallon in dollars
				gascost     = 6053.24 / 649331.81 	// cost of gas per *water-gallon* (converted to per cu-ft below) in dollars
			;
		
			if (!isNaN(showers) && !isNaN(minutes) && !isNaN(gallons) && !isNaN(flow)) {
				watersaved 	 = (showers * minutes * 365) * (gallons - flow);
				gassaved     = watersaved * gasperwater;
				dollarssaved = (watersaved * watercost) + (gassaved * gascost);
				
				// format for output
				watersaved   = watersaved.toFixed(1).replace(/\.0$/,"");
				gassaved     = gassaved.toFixed(2).replace(/\.?0+$/,"");
				dollarssaved = dollarssaved.toFixed(2);
			}
			
			$watersaved.text( formatCommas(watersaved) );
			$gassaved.text( formatCommas(gassaved) );
			$dollarssaved.text( formatCommas(dollarssaved) );
		}
	  	
	  	if ( $('#calcShowers').length == 1 ) {
	  		// Cache our input elements
			var $showers      = $("#calcShowers"),
				$minutes      = $("#calcMinutes"),
				$gallons      = $("#calcGallons"),
				$flow         = $("#calcFlow").uniform(),
				$watersaved   = $("#calcWaterSaved"),
				$gassaved     = $("#calcGasSaved"),
				$dollarssaved = $("#calcDollarsSaved")
			;
			
			// Only allow numeric input
			$([ $showers[0], $minutes[0], $gallons[0] ]).bind('keypress', function(evt) {
				if ( !String.fromCharCode(evt.which).match(/\d|\./) ) {
					evt.preventDefault();
					return false;
				}
			})
			.bind('blur change mouseup keyup', simpleWaterCalc)
			.eq(0).trigger('keyup');
			
			$flow.bind("change", simpleWaterCalc);
		}
		
		function waterCalc(evt) {
			var avggascost   = Number($avggascost.val().replace("\$",'')),
				avgwatercost = Number($avgwatercost.val().replace("\$",'')),
				guestrooms   = Number($guestrooms.val()),
				occupants    = Number($occupants.val()),
				showerlength = Number($showerlength.val()),
				curflow      = Number($curflow.val()),
				occrate      = Number($occrate.val()),
				showerheads  = Number($showerheads.val()),
				perhead      = Number($perhead.val()),
				flow         = Number($flow.val()),
			
				annualcost = "", invcost = "", roi = "", watersaved = "", gassaved = "", dollarssaved = "",
				galperyear = 0, cuftperyear = 0, newgalperyear = 0, newcuperyear = 0,
				gasperwater = 6126.712125 / 13775.7159375 // the conversion of units of gallons to cu-ft
			;

			if (!isNaN(avggascost) && !isNaN(avgwatercost) && !isNaN(guestrooms) && !isNaN(occupants) && !isNaN(showerlength) && !isNaN(curflow) && !isNaN(occrate) && !isNaN(showerheads) && !isNaN(perhead) && !isNaN(flow)) {
				// can't upgrade more shower heads than guest rooms
				if (showerheads > guestrooms) showerheads = guestrooms;
			
				// water & gas costs are both specified as per 1000 unit costs
				avgwatercost /= 1000;
				avggascost /= 1000;
				
				// occupancy rate is a percentage
				occrate /= 100;

				// annual gallons of water and cu-ft of gas used for the whole facility				
				galperyear = (guestrooms * occupants * showerlength * curflow * occrate * 365);
				cuftperyear = galperyear * gasperwater; // using the water-to-gas conversion
				
				// annual total cost = water + gas
				annualcost = (galperyear * avgwatercost) + (cuftperyear * avggascost);

				// how many new shower heads upgraded, at what cost per head?
				invcost = showerheads * perhead;
			
				// new water and gas usage per year, with upgraded shower heads
				newgalperyear = (occupants * showerlength * occrate * 365) * (((guestrooms - showerheads) * curflow) + (showerheads * flow));
				newcuftperyear = (occupants * showerlength * occrate * 365 * gasperwater) * (((guestrooms - showerheads) * curflow) + (showerheads * flow));

				// calculate savings
				watersaved = galperyear - newgalperyear;
				gassaved = cuftperyear - newcuftperyear;
				dollarssaved = (watersaved * avgwatercost) + (gassaved * avggascost);
				
				// "ROI in months" is how long it takes to recover the investment cost with dollar savings
				if (dollarssaved != 0) {
					roi = invcost / (dollarssaved / 12);
				}
				
				// format for output
				annualcost = annualcost.toFixed(2);
				invcost = invcost.toFixed(2);
				roi = roi.toFixed(2);
				watersaved = watersaved.toFixed(2).replace(/\.?0+$/,"");
				gassaved = gassaved.toFixed(2).replace(/\.?0+$/,"");
				dollarssaved = dollarssaved.toFixed(2);
			}
			
			$annualcost.text( formatCommas(annualcost) );
			$invcost.text( formatCommas(invcost) );
			$roi.text( formatCommas(roi) );
			$watersaved.text( formatCommas(watersaved) );
			$gassaved.text( formatCommas(gassaved) );
			$dollarssaved.text( formatCommas(dollarssaved) );
		}
		
		if ( $('#avggascost').length == 1 ) {
			var $avggascost   = $("#avggascost"),
				$avgwatercost = $("#avgwatercost"),
				$guestrooms   = $("#guestrooms"),
				$occupants    = $("#occupants"),
				$showerlength = $("#showerlength"),
				$curflow      = $("#curflow"),
				$occrate      = $("#occrate"),
				$showerheads  = $("#showerheads"),
				$perhead      = $("#perhead"),
				$flow         = $("#flow").uniform(),
				
				$annualcost   = $("#annualcost"),
				$invcost      = $("#invcost"),
				$roi          = $("#roi"),
				$watersaved   = $("#watersaved"),
				$gassaved     = $("#gassaved"),
				$dollarssaved = $("#dollarssaved")
			;
			
			// allow only numeric input
			$([ $avggascost[0], $avgwatercost[0], $guestrooms[0], $occupants[0], $showerlength[0], $curflow[0], $occrate[0], $showerheads[0], $perhead[0] ])
			    .bind('keypress', function(evt) {
					if ( !String.fromCharCode(evt.which).match(/\d|\.|\$/)) {
						evt.preventDefault();
						return false;
					}
				})
				.bind('blur focus change mouseup keyup', waterCalc)
				.eq(0)
				.trigger('keyup');
				
				$flow.change(waterCalc);
		}
	});
	
	$(function(){
		$("#page.why-waterpik .testimonial .control").bind("click", function(e){
			var $t = $(this);
			var $active = $t.parent().find("img.active");
			var $target;
			if ( $t.hasClass("previous") ){
				$target = $active.prev("img");
				if ( $target.length === 0 ){
					$target = $t.parent().find("img:last");
				}
			} else {
				$target = $active.next("img");
				if ( $target.length === 0 ){
					$target = $t.parent().find("img:first");
				}
			}
			$active.fadeOut(200, function(){
				$target.fadeIn(200).addClass("active");
				$(this).removeClass("active");
			});
			e.preventDefault();
		});
	});
  		
}(jQuery));
