var XHR;
var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
$(document).ready(function() {

    //fix pngs
    $("#bottomshadow, #maincontentcontainer, #featuredProductImage img").supersleight();

    //hover functions for products, service, about, etc. menu
    $(".menu > li").hover(
    	function() {
    	    $(this).addClass(this.id + "Hover").find("ul").show();
    	},
	    function() {
	        $(this).removeClass(this.id + "Hover").find("ul").hide();
	    });

    //hook up menu close buttons
    $(".closebtn").click(function() {
        $(this).parent().parent().parent().hide();
    });

    // Add GA cross-domain linking code to all <a> tags linking to Traulsen & Baxter
    $("a").each(function() {
        var href = $(this).attr("href");
        if (href && (href.indexOf("http://www.traulsen.com") > -1 || href.indexOf("http://www.baxterbakery.com") > -1)) {
        
            //following line doesn't work in IE
            //$(this).attr("onclick", "pageTracker._link('" + href + "'); return false;");
            
            $(this).click(function(){
            	pageTracker._link(href);
            	return false;
            });
        }
        
        //track all pdf downloads
        if(href && href.indexOf(".pdf") > -1){
          $(this).click(function(){
            pageTracker._trackEvent("PDF", "Download", href);
          });
        }
    });
    
    //track product nav dropdown clicks
    $("#ProductsSubMenu a").each(function(){
      var href = $(this).attr("href");
      if(href != "#"){
        $(this).attr("href", "#").click(function(e){
          e.preventDefault();
          pageTracker._trackEvent("Main Product Nav Dropdown", "Page View", href);
          setTimeout("window.location.href = '" + href + "'", 300);
        });
      }
    });
    
    //track segment nav dropdown clicks
    $("#AboutYouSubMenu a").each(function(){
      var href = $(this).attr("href");
      if(href != "#"){
        $(this).attr("href", "#").click(function(e){
          e.preventDefault();
          pageTracker._trackEvent("Main Segment Nav Dropdown", "Page View", href);
          setTimeout("window.location.href = '" + href + "'", 300);
        });
      }
    });
    
    //hook up search box / button
    $("#txtSearch").keypress(function(e) {
      if (e.which == 13) {
        window.location.href = "/search-results/?k=" + $("#txtSearch").val();
      }
    });
    
    $("#btnSearch").click(function(e){
      e.preventDefault();
      window.location.href = "/search-results/?k=" + $("#txtSearch").val();
    });
    
    //show lightbox via if query string variable is present
    var ekId = GetQueryStringValue("showlightbox");
    if(ekId != ""){
      playLightboxVideo(ekId);
    }

});

function IsValidEmail(str) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str)) {
        return (true)
    }
    return (false)
}
function GetQueryStringValue(Key) {
    var QStrArray = document.location.search.substring(1).split("&");
    for (var i = 0; i < QStrArray.length; i++) {
        var tempArray = QStrArray[i].split("=");
        if (tempArray[0] == Key) {
            return tempArray[1];
        }
    }

    return "";
}

function resizeSecondaryNav() {
    // Resize the secondary nav links to fill the secondary nav bar
    var availableWidth = 917;
    var links = $("#SecondLevelSubNavContainer > ul > li");
    // Get the total width of the links as they are now
    var totalWidth = 0;
    for (var i = 0; i < links.length; i++) {
        totalWidth += $(links[i]).width();
    }
    // If the total width is less than the available width, adjust the left/right padding of each item until the available width is consumed.
    if (totalWidth < availableWidth) {
        var totalExtra = availableWidth - totalWidth; // The number of available pixels to divide up
        var toAddPerItemPerSide = parseInt(totalExtra / (links.length * 2));
        var leftoverPixels = totalExtra % (links.length * 2);
        for (var i = 0; i < links.length; i++) {
            var toAddLeft = toAddPerItemPerSide;
            if (leftoverPixels > 0) {
                toAddLeft++;
                leftoverPixels--;
            }
            var toAddRight = toAddPerItemPerSide;
            if (leftoverPixels > 0) {
                toAddRight++;
                leftoverPixels--;
            }
            $("a", links[i]).css("padding-left", toAddLeft + "px").css("padding-right", toAddRight + "px");
        }
    }
    $("#SecondLevelSubNavContainer ul").css("position", "static");
    $("#SecondLevelSubNavContainer").show();
}

function playLightboxVideo(ekid) {
  $("#lb").remove();
    $.ajax({ url: "/ajaxcontent/LightboxVideo.aspx",
        type: "GET",
        data: { id: ekid },
        success: function(data) {
            $("<div id='lb'>").html($("#lightbox", data)).appendTo("body:first");
            sizeLightboxVideo();
            $("#lightboxBG").width(Math.max($("body:first").width(), $(window).width())).height(Math.max($("body:first").height(), $(window).height()));

            $("#lightboxBorder").height($("#lightboxContainer").height() + 46);
            $("#lightboxBG").fadeIn("fast", function() {
                $("#lightboxBorder").fadeIn("fast");
                $("#lightboxContainer").fadeIn("fast");
            });
            $(window).bind("resize", function() {
                setTimeout('$("#lightboxBG").width($(window).width()).height($(window).height());', 100);
            });
        }
    });
}

function closeLightboxVideo() {
    $("#lightboxContainer").fadeOut("fast");
    $("#lightboxBorder").fadeOut("fast", function() {
        $("#lightboxBG").fadeOut("fast", function() {
            $("#lb").remove();
        });
    });
}

function showLightboxForm(ekid) {
  $("#lb").remove();
    $.ajax({ url: "/ajaxcontent/LightboxForm.aspx",
        type: "GET",
        data: { id: ekid },
        success: function(data) {

            $("<div id='lb'>").html($("#lightbox", data)).appendTo("body:first");

            $.getScript("/js/" + $("#jsfile", data).html());

            var lightBoxWidth = $("#lightboxContainer").width();
            $("#lightboxContainer").css("margin-left", -(lightBoxWidth / 2 + 20));
            $("#lightboxBorder").width(lightBoxWidth + 60).css("margin-left", -((lightBoxWidth + 60) / 2)).css("top", "91px");
            
            $("#lightboxBG").width(Math.max($("body:first").width(), $(window).width())).height(Math.max($("body:first").height(), $(window).height()));

            $("#lightboxBorder").height($("#lightboxContainer").height() + 46);
            $("#lightboxBG").fadeIn("fast", function() {
                $("#lightboxBorder").fadeIn("fast");
                $("#lightboxContainer").fadeIn("fast");
            });
            $(window).bind("resize", function() {
                setTimeout('$("#lightboxBG").width($(window).width()).height($(window).height());', 100);
            });
        }
    });
}

/* PROTOTYPES/EXTENSIONS */
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) {
            return i;
        }
    }
    return -1;
};

/****************************************************************
FILE: RegExpValidate.js

DESCRIPTION: This file contains a library of validation functions
  using javascript regular expressions.  Library also contains 
  functions that reformat fields for display or for storage.


  VALIDATION FUNCTIONS:

  validateEmail - checks format of email address
    validateUSPhone - checks format of US phone number
    validateNumeric - checks for valid numeric value
  validateInteger - checks for valid integer value
    validateNotEmpty - checks for blank form field
  validateUSZip - checks for valid US zip code
  validateUSDate - checks for valid date in US format
  validateValue - checks a string against supplied pattern

AUTHOR: Karen Gayda

DATE: 03/24/2000
*******************************************************************/

function validateEmail( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
  valid email pattern.

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/
var objRegExp  = /(^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6})/i;

  //check for valid email
  return objRegExp.test(strValue);
}

function validateUSPhone( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. (999) 999-9999 or (999)999-9999 or 999-999-9999 9999999999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
    var objRegExp = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$|\d{3}-\d{3}-\d{4}|\d{10}/;

  //check for valid us phone with or without space between
  //area code
  return objRegExp.test(strValue);
}

function  validateNumeric( strValue ) {
/*****************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
******************************************************************/
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;

  //check for numeric characters
  return objRegExp.test(strValue);
}

function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
**************************************************/
  var objRegExp  = /(^-?\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}

function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue.trim();
   if(strTemp.length > 0){
     return true;
   }
   return false;
}

function validateUSZip( strValue ) {
/************************************************
DESCRIPTION: Validates that a string a United
  States zip code in 5 digit format or zip+4
  format. 99999 or 99999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

*************************************************/
var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;

  //check for valid US Zipcode
  return objRegExp.test(strValue);
}

function validateCanadianPostalCode( strValue ) {
    var objRegExp = /^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/;

    return objRegExp.test(strValue);
}

function validateUSDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
 
  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return false; //doesn't match pattern, bad date
  else{
    var strSeparator = strValue.substring(2,3) 
    var arrayDate = strValue.split(strSeparator); 
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, 
                        '04' : 30,'05' : 31,
                        '06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,
                        '10' : 31,'11' : 30,'12' : 31}
    var intDay = parseInt(arrayDate[1],10); 

    //check if month value and day value agree
    if(arrayLookup[arrayDate[0]] != null) {
      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
        return true; //found in lookup table, good date
    }
    
    //check for February (bugfix 20050322)
    //bugfix  for parseInt kevin
    //bugfix  biss year  O.Jp Voutat
    var intMonth = parseInt(arrayDate[0],10);
    if (intMonth == 2) { 
       var intYear = parseInt(arrayDate[2]);
       if (intDay > 0 && intDay < 29) {
           return true;
       }
       else if (intDay == 29) {
         if ((intYear % 4 == 0) && (intYear % 100 != 0) || 
             (intYear % 400 == 0)) {
              // year div by 4 and ((not div by 100) or div by 400) ->ok
             return true;
         }   
       }
    }
  }  
  return false; //any other values, bad date
}

function validateValue( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Validates that a string a matches
  a valid regular expression value.

PARAMETERS:
   strValue - String to be tested for validity
   strMatchPattern - String containing a valid
      regular expression match pattern.

RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = new RegExp( strMatchPattern);

 //check if string matches pattern
 return objRegExp.test(strValue);
}