$(document).ready(function(){
	
	var footer = $("#footer-inner.home");
	
	function getHeight() {
    if (document.documentElement) {
      return document.documentElement.offsetHeight;
    } else if (window.innerWidth && window.innerHeight) {
      return window.innerHeight;
    }
	}
	
	function positionFooter() {
	  var footerY = getHeight() - 54;
  	footer[0].style.top = footerY < 536 ? "536px" : footerY + "px";
  	footer[0].style.visibility = "visible";
	}
	
	if (footer.length > 0) {
	  positionFooter();
	}

	$('#zip_field').bind('keypress', function(e) {if(e.keyCode==13){searchProduct();}});
	$('#state_field').bind('keypress', function(e) {if(e.keyCode==13){searchProduct();}});
	$('#city_field').bind('keypress', function(e) {if(e.keyCode==13){searchProduct();}});
	$('#product_field').bind('keypress', function(e) {if(e.keyCode==13){searchProduct();}});

	$("#find-product-btn").click(function(){searchProduct();});
	
	
	function searchProduct() {
		
		$("#finder-info").show();
		
		var city = $("#city_field").attr("value");
		
	
		//state = document.getElementById("state_field").selectedIndex;
		
		
		var state = $("#state_field").attr("value");
		
		
		
		var zip = $("#zip_field").attr("value");

		if(zip != "")
		{
			city = "";
			state = "";
		}
		
		if(state == "--")
		{
			state = "";
		}
		var product_code = $("#product_field").attr("value");
		
		var txt = $("#product_field :selected").text();
	
		var product_name = "Results for \""+txt+"\"";
		
		var styleText = "<style type='text/css'>body{text-align:left; font-family: 'Trebuchet MS', sans-serif;color:#727272; font-size:10px;}a{color:#2a6b9e;} p{font-size:14px;} .HeadingCell {width: 200px;} .FieldCell{font-size:12px;}</style>";
		
    var url="http://www.itemlocator.net/scripts/cgiip.exe/WService=ils3/webspeed/locatorweb.w?customer=stremick&radius=30&city="+city+"&state="+state+"&zip="+zip+"&item="+product_code+"&item_desc="+escape(product_name)+"&body="+escape(styleText);
		var obj = "<object id='results' style='border: medium; overflow: hidden; width: 500px; height: 600px;'  data='"+url+"' ></object>"

		$("#results").attr("src",url);
		
		
	}
	
  $("#nutritional-facts-btn").click(function() {
    $("#nut-tranny").show();
    $("#nut-overlay").show();
  });
  
  $(".hider").click(function() {
    $("#nut-tranny").hide();
    $("#nut-overlay").hide();
  });
	
	$("#submit-btn").click(function(){
		$("#search-form").submit();
	});
	var searchDefault = "Search...";
	$("#search-field").focus(function(){  
	     if($(this).attr("value") == searchDefault) $(this).attr("value", "");  
	 });  
	$("#search-field").blur(function(){  
	     if($(this).attr("value") == "") $(this).attr("value", searchDefault);  
	 });
    


    $('.dropdown-menu').hover(
      function () {
        
        if (slowVersion) {
          $(this).css('marginTop', "0px");
          $('.down-list li', this).each(function(i) {
              $(this).css({"marginTop":"0px", "display":"block"})
          });
          
        } else {
          
          $(this).stop().animate({ 'marginTop': "0px" }, {duration: 1050, easing: 'easeOutElastic'});
          $('.down-list li', this).each(function(i) {
              $(this).stop(true,true).fadeIn(50*i).delay(25*i).animate({ 'marginTop': "0px"}, {duration: 820, easing: 'easeOutElastic'} );
          });
          
        };

      },
      function () {
        var dropID = $(this)[0].id;
        dropID = dropID.substr(0, dropID.indexOf("-drop"));
        
        if (slowVersion) {
          
          if ( !$("body").hasClass(dropID) || !dropID) {
            $(this).css( "marginTop", "-18px");
          }
          $('.down-list li', this).each(function(i) {
           $(this).css({"marginTop":"-30px", "display":"none"})
          });
          
        } else {
          
          if ( !$("body").hasClass(dropID) || !dropID) {
            $(this).stop().animate({ 'marginTop': "-18px" }, {duration: 1050, easing: 'easeOutElastic'});
          }
          $('.down-list li', this).each(function(i) {
            $(this).stop(true,true).fadeOut(50*i).delay(25*i).animate({ 'marginTop': "-30px" }, {duration: 820, easing: 'easeOutElastic'} );
          });
          
        };

      }
    );
	
	// subnav
  $(".secondary").hover(
    function () {
      srcPath = $(this).children(".typeBriteImage").attr("src").replace("_UP", "_OVER");
      $(this).children(".typeBriteImage").attr("src", srcPath);
    },
    function () {
      srcPath = $(this).children(".typeBriteImage").attr("src").replace("_OVER", "_UP");
      $(this).children(".typeBriteImage").attr("src", srcPath);
    }
  );

  // swap hover images on load for active state
  $(".typeBriteImage").each(function() {
    if (checkActiveState( $(this) )) {
      srcPath = $(this).attr("src").replace("_UP", "_OVER");
      $(this).attr("src", srcPath);
      $(this).parent().addClass("active");
	  $(this).parent().parent().addClass("active");
    }
  })
  
  // all other over states
  $(".typeBriteImage").hover(
    function () {
      if ($(this).parent().hasClass("secondary")) return;
      srcPath = $(this).attr("src").replace("_UP", "_OVER");
      $(this).attr("src", srcPath);
	  $(this).parent().parent().addClass("active");
    },
    function () {
      if (checkActiveState( $(this) )) return;
      var srcPath = $(this).attr("src").replace("_OVER", "_UP");
      $(this).attr("src", srcPath);
	  $(this).parent().parent().removeClass("active");
    }
  );
  
  function checkActiveState(el) {
    if (el.parent().hasClass("secondary")) return false;
    // get last URL element to match slug/class of body
    var classStr = el.parent().attr("href");
    classStr = classStr.substr(classStr.lastIndexOf("/") + 1);
    // don't switch to roll out state for active element
    if ( $("body").hasClass(classStr)) { return true; }
  }
	
	
	// product landing page
	$("#carton-container li").hover(
	  function() { 
	    $(this).children(".product-label-over").show();
	    $(this).children(".product-shimmer").show();
	  },
	  function() {
	    $(this).children(".product-label-over").hide();
	    $(this).children(".product-shimmer").hide();
	  }
	)
	
	if ( $("#email-btn").length > 0) {
	  var emailOver = false;
	}
	// email toggle vis
	$("#email-btn").toggle(
	  function() { $("#email").show(); $("#email input:text").focus(); },
	  function() { $("#email").hide(); }
	);
  
  // email from input when enter/return key pressed
  $("#email input:text").keyup(function(e) {
    if (e.keyCode == '13') {
      sendEmail();
    };
  });
  
  $("#email input:submit").click(function() {
    sendEmail();
  });
  
  function sendEmail() {
    if ( !$("#email input:text")[0].value ) return;
    document.location.href="mailto:"+$("#email input:text")[0].value
  }
  
  // product landing - fake links off cartons
  $(".product-landing-label").click(function() {
    var link = $(this).parent().children("a").attr("href")
    location.href = link;
  });
	
	
	// contact page
	$(".errorlist").each(function() {
	  var pos;
	  if ($(this).next().children("input").length > 0) {
	    
	    $(this).addClass( "error-" + $(this).next().children("input")[0].id.substr(3) );
	    
	    pos = $(this).next().children("input").position();
	  } else {
	    
	    $(this).addClass( "error-" + $(this).next().children("textarea")[0].id.substr(3) );
	    
	    pos = $(this).next().children("textarea").position();
	  }
	  
	  $(this)[0].style.left = "246px";
	  $(this)[0].style.top = pos.top + 5 + "px";
	  
	});
	
	// footer scroll fix
	if (footer.length > 0) {
    $(window).scroll(function() {
      positionFooter();
      //trace( $("#app").height() + " " + $(window).height() + " " + $(window).scrollTop() )
    });
  
    $(window).resize(function() {
      positionFooter();
    });
  }
  
	
});





// cpu test



var cpuTestInterval;
var startTime, oldTime, newTime;
var interval = 10;
var cpuCounter = 0;
var CPU_MAX_COUNT = 101; // throw out first count and divide by round 100
var avgSum = 0;
var slowVersion = false;
var MAX_AVG_ALLOWED = 28;

function testCPU() {
  // show footer
  $("#footer-inner.home").delay(1400).fadeIn();
  cpuTestInterval = setInterval(initTestCPU, interval);
}

// if on home page position footer and test cpu
function initTestCPU() {
  if (cpuCounter == CPU_MAX_COUNT) {
    killCPUTest();
    var result = avgSum/CPU_MAX_COUNT - 1;
    if (result > MAX_AVG_ALLOWED) { slowVersion = true; };
  }
  oldTime = newTime;
  var d = new Date();
  newTime = d.getTime();
  // see whether we should kill test early
  if (cpuCounter == 1) {
    startTime = newTime;
  }
  if (cpuCounter == 2) {
    if (startTime - newTime <= -MAX_AVG_ALLOWED) {
      killCPUTest();
      slowVersion = true;
      return;
    }
  }
  //
  if (newTime - oldTime) {
    avgSum += newTime - oldTime
  }
  cpuCounter++;
}

function killCPUTest() {
  clearInterval(cpuTestInterval);
  cpuTestInterval = null;
}

function trace(s) {
  if (typeof console != "undefined") {
    if (typeof console.debug != "undefined") {
      console.debug(s);
    }
    else if (typeof console.log != "undefined") {
      console.log(s);
    }
  }
}
