var XHR;
var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
$(document).ready(function() {
    
    //fix pngs
    if (isIE6) {
    $("#body_container, #body_footer, .static .background, .buttonCarousel .background, .imagecontainer img").supersleight();
    }
    
    var Path = window.location.pathname.toLowerCase().split("/");
    var MenuOnID;
    if (Path.length > 2) {
        MenuOnID = Path[1].replace("-", "");
        $("#" + MenuOnID).addClass(MenuOnID + "on");
    }

    //hook up hover states for IE6
    if (isIE6) {
        $("#nav li").hover(
    	function() {
    	    $(this).addClass(this.id + "on").addClass("on");
    	    $(this).children("ul").show();
    	},
    	function() {
    	    if (MenuOnID != this.id) {
    	        $(this).removeClass();
    	    }
    	    $(this).children("ul").hide();
    	});

        $("li.haschildren").hover(
    	function() {
    	$("#ie6frame").remove();
    	    $(this).children("a").css({ "background": "#bd461b url(/images/dd_arrow_hover.gif) no-repeat top right" });
    	    //$(this).addClass("on").children("ul").show();
    	    
    	    var tempheight = $(this).children("ul").height();
    	    $(this).children("ul").prepend("<iframe id='ie6frame'></iframe>");
    	    $("#ie6frame").height(tempheight);
    	},
    	function() {
    	    $(this).children("a").css({ "background": "url(/images/dd_arrow.png) no-repeat top right" });
    	    //$(this).removeClass("on").children("ul").hide();
    	});
    }

    // Add GA cross-domain linking code to all <a> tags linking to Hobart & Baxter
    $("a").each(function() {
        var href = $(this).attr("href");
        if (href && (href.indexOf("http://www.hobartcorp.com") > -1 || href.indexOf("http://www.baxterbakery.com") > -1)) {
            //$(this).attr("onclick", "pageTracker._link('" + href + "'); return false;");
            
	    $(this).click(function(){
		pageTracker._link(href);
		return false;
            });
        }
    });

    resizeSecondaryNav();
});


function resizeSecondaryNav() {
    // Resize the secondary nav links to fill the secondary nav bar
    var availableWidth = 917;
    var links = $("#SecondLevelSubNavContainer > ul > li");
    if(links.length > 0){

	    // 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();
	    }
	    $("#SecondLevelSubNavContainer").hide(); // To prevent resize flickering
	    // 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 IsValidEmail(str) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str)) {
        return (true)
    }
    return (false)
}

function playLightboxVideo(ekid) {
    $.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()));
            $("#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 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 "";
}
/* 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);
}
