function initPageHeight() {
  var lch = $(".leftnav").height(); //lch - left column height
  var pbh = $(".page-body").height(); //pbh = page body height
  var rch = $(".rightnav").height(); //rch = right column height

  if (lch > rch && lch > pbh){
    $(".page-body").css("height", lch + "px");
    $(".rightnav").css("height", lch + "px");
  } else if (rch > lch && rch > pbh){
    $(".page-body").css("height", rch + "px");
    $(".leftnav").css("height", rch + "px");
  } else if (pbh > rch && pbh > lch){
    $(".leftnav").css("height", pbh + "px");
    $(".rightnav").css("height", pbh + "px");
  }

  $(".fill-height").each(function() {
    var regex = new RegExp("\\D", "g");

      $(this).height($(this).parent().height() -
          ( $(this).offset().top - $(this).parent().offset().top ) +
          $(this).parent().css("border-top-width").replace(regex,"") * 1  +
          ( $(this).parent().css("padding-top").replace(regex,"")  * 1 +
            $(this).parent().css("padding-bottom").replace(regex,"")  * 1 ) -
          ( $(this).css("padding-top").replace(regex,"")  * 1   +
            $(this).css("padding-bottom").replace(regex,"")  * 1  ) -
          ( $(this).css("border-top-width").replace(regex,"")  * 1  +
            $(this).css("border-bottom-width").replace(regex,"")  * 1)
      );
    });

}

String.prototype.trim = function() {
    var trimmedValue = this.replace(/^[\s]*/g, "");
    trimmedValue = trimmedValue.replace(/[\s]*$/g, "");
    return trimmedValue;
  };

(function($, undefined) {
    $.extend(
        $,
        {
            showPageLoadingMsg : function() {

                $(window).scrollTop(1);
                var loader = $("#ui-loader-cover");

                if (!loader[0]) {
                    loader = $("<div id='ui-loader-cover' class='ui-loader-cover'/>");
                    $("body").append(loader);
                }

                var loaderBar = $("#ui-loader-img-cont");
                loaderBar.css("top", ($(window).height() / 2) - loaderBar.height());
                loaderBar.css("left", ($(window).width() / 2) - 125);
                $("body").append(loaderBar);
                
                loader.height($("body").height() + 20);
                $("body").addClass("ui-loading");
                
            },

            hidePageLoadingMsg : function() {
                $("body").removeClass("ui-loading");
            }

        }
    );
})(jQuery);

$(document).ready(function(e) {
  
  $.hidePageLoadingMsg();
  
  $("input[type=text]").blur(function () {
    $this = $(this);
    $this.val(String($this.val()).trim());
  });
  
});

$(function(){
  // $(".button").assignMouseEvents();
  initPageHeight();

  $(".social").click(function() {
    omnitureSend("Follow Us - Home Page", 2, 5);
  });

});


// Old style functions
var searchInstructions = "Enter keyword or item #";

function submitSearchForm(theForm) {
     if(doSearchValidation (theForm)) theForm.submit();
}

function doSearchFocus(component) {
    var searchVal = component.value;
    if (searchVal == searchInstructions) {
        component.value = "";
    }
}

function doSearchBlur(component) {
    var searchVal = component.value;
    if (strTrim(searchVal) == '') {
        component.value = searchInstructions;
    }
}

function doSearchValidation (theForm) {
  var searchVal = theForm.keyword.value ;
  if (searchVal == "" || searchVal == searchInstructions) {
    alert ("Please enter a search term and try your search again.") ;
    return false ;
  }
  return true ;
}

function doControlFocus(component,defaultMessage) {
    var controlVal = component.value;
    if (controlVal == defaultMessage) {
        component.value = "";
    }
}

function doControlBlur(component,defaultMessage) {
    var controlVal = component.value;
    if (strTrim(controlVal) == '') {
        component.value = defaultMessage;
    }
}

function strTrim(s) {
    // Remove leading spaces and carriage returns
    while (s.substring(0,1) == ' ') {
        s = s.substring(1, s.length);
    }
    // Remove trailing spaces and carriage returns
    while (s.substring(s.length-1, s.length) == ' ') {
        s = s.substring(0, s.length-1);
    }
    return s;
}

/*
 * This function launches a new web browser window to a specified width, height and features.
 * Features string is a comma separated window's feature needed for this new window. For Instance
 * If a new window needs a toolbar the feature string must be "toolbar" like needs scroll bar and
 * and toolbar then it must be "toolbar,scrollbar". Note that the order of the feature is not required.
 * Also it's case insensitive. Therefore, "scrollbar,toolbar" is identical to "Toolbar,ScrollBar".
 *
 * If the features string is ommitted then all the features are turned off. To turn all the features on
 * use the word "all" for features instead of specifying each feature.
 */

function openWindow(address, width, height,features)
{
  /* Find out what features need to be enable
   *
   */
  if(features)
    features = features.toLowerCase();
  else
    features = "";

  var toolbar = (features == "all" ? 1 : 0);
  var menubar = (features == "all" ? 1 : 0);
  var location = (features == "all" ? 1 : 0);
  var directories = (features == "all" ? 1 : 0);
  var status = (features == "all" ? 1 : 0);
  var scrollbars = (features == "all" ? 1 : 0);
  var resizable = (features == "all" ? 1 : 0);


  if(features != "all")
  {
    //split features
    var feature = features.split(",");
    for(i = 0; i < feature.length; i++)
    {
      if(feature[i] == "toolbar")
         toolbar = 1;
      else if(feature[i] == "menubar")
         menubar = 1;
      else if(feature[i] == "location")
         location = 1;
      else if(feature[i] == "directories")
         directories = 1;
      else if(feature[i] == "status")
         status = 1;
      else if(feature[i] == "scrollbars")
         scrollbars = 1;
      else if(feature[i] == "resizable")
         resizable = 1;
    }

  }
  features = "toolbar=" + toolbar + ",";
  features += "menubar=" + menubar + ",";
  features += "location=" + location + ",";
  features += "directories=" + directories + ",";
  features += "status=" + status + ",";
  features += "scrollbars=" + scrollbars + ",";
  features += "resizable=" + resizable;

  var newWindow = window.open(address, 'Popup_Window', 'width=' + width + ',height=' + height + ',"' + features + '"');
  newWindow.focus();
}

function trim(s)
{
  // Remove leading spaces and carriage returns
  while (s.substring(0,1) == ' '){
    s = s.substring(1,s.length);
  }
  // Remove trailing spaces and carriage returns
  while (s.substring(s.length-1,s.length) == ' '){
    s = s.substring(0,s.length-1);
  }
  return s;
}
/**
 * Check if the zip code is a US or APO/FPO or Canadian zip code
 */
function isZipCode(s) {
  return isUnitedStateZipCode(s) || isFPOorAPOZipCode(s) || isCanadianZipCode(s);
}

/**
 * Check if the zip code is a US zip code
 */
function isUnitedStateZipCode(s) {

  var reUSZip = new RegExp(/(^\d{5}$)|(^\d{5}(\-|\ )\d{4}$)/);

    if (!reUSZip.test(s)) {
         return false;
    }

    return true;
}

/**
 * Check if the zip code is a Canadian zip code
 */
function isCanadianZipCode(s) {

  var reCanZip = new RegExp(/(^[a-zA-Z]\d{1}[a-zA-Z](\-|\ )\d{1}[a-zA-Z]\d{1}$)/);

    if (!reCanZip.test(s)) {
         return false;
    }

    return true;
}

/**
 * Check if the zip code is a FPO or APO zip code
 */
function isFPOorAPOZipCode(s) {

  var reFPOorAPOZip = new RegExp(/(^[a-zA-Z]{3}(\-|\ )?[a-zA-Z]{2}(\-|\ )?\d{5}$)/);

    if (!reFPOorAPOZip.test(s)) {
         return false;
    }

    return true;
}

$(function(){
  $("input[type=text]").focus(function(){
    makeCurrent(this);
  });
  $("input[type=text]").blur(function(){
    makeNormal(this);
  });
  $("input[type=password]").focus(function(){
    makeCurrent(this);
  });
  $("input[type=password]").blur(function(){
    makeNormal(this);
  });
  $("textarea").focus(function(){
    makeCurrent(this);
  });
  $("textarea").blur(function(){
    makeNormal(this);
  });
});

/* DON'T DO IT THIS WAY BECAUSE YOU CAN'T SET THE COLOR IN CSS.

function makeCurrent(elem){
  $(elem).css("background-color", "yellow");
}
function makeNormal(elem){
  $(elem).css("background-color", "white");
}


*/

/* DO IT THIS WAY BECAUSE WE CAN UPDATE THE COLORS IN CSS. */
function makeCurrent(elem){
  $(elem).removeClass('defaultState').addClass('currentSelection');
}
function makeNormal(elem){
  $(elem).removeClass('currentSelection').addClass('defaultState');
}



function changeLanguage(elem, lang) {

  var pars = '';
  if(lang != '') {
    pars = 'languageId='+lang;
  }
  else {
    pars = 'languageId='+$(elem).val();
  }

  $.ajax({
    type:     "post",
    url:    "/sitelang/change_user_language.cmd",
    data:     pars,
    dataType:   "html",
    success:  function(msg) {
          window.location.href = "../home.jsp";
    }
  });
}

/*************************
  Footer Javascript
*************************/

function callEmailSignup() {
  var formAction = $("#subscribeForm").attr("action");
  if ($("#subscribeForm input[name=userEmail]").val() == "yourname@email.com")
    $("#emailSignUp").html("<div class='error localize-me'>Please enter your email address.</div>");
  else
    $("#emailSignUp").html("Saving...").load(formAction, {"userEmail":$("#subscribeForm input[name=userEmail]").val()});
}

$(function() {
  $("#subscribeForm input[name=userEmail]").keydown(function(event) {
    if (event.keyCode == 13)
    {
      callEmailSignup();
      return false;
    }
  });

  $(".email-signup-contianer .signup-button").click(function(){
    callEmailSignup();
  });
  $("#newsletter-email").focus(function() {
    if($(this).val()=='yourname@email.com') {
    $(this).val('');
    }
  });
  $("#newsletter-email").blur(function() {
    if($.trim($(this).val())=='') {
      $(this).val('yourname@email.com');
    }
  });
});

function setupImageSlides(selector, prev, next) {
  $(selector).cycle({
    fx: 'fade',
    prev: prev,
    next: next,
    timeout: 0,
    speed: 500
  });
}

function showViewer(selector, zoomContainer, imageURL, proxyURL) {
  var curImage = $(selector).attr("curImage");
  if (curImage && curImage != 'null' && curImage != '') {
    Seadragon.Config.imagePath = "/assets/images/seadragon/img/";
    Seadragon.Config.proxyUrl = proxyURL;
    var viewer = new Seadragon.Viewer(zoomContainer);
    viewer.openDzi(imageURL  + "/zoom/" + curImage + "/dzi.xml");
    var navControl = viewer.getNavControl();
    navControl.removeChild(navControl.lastChild);
    /* Create the close button */
    var closeButton = new Seadragon.Button(
          "Close",
          Seadragon.Config.imagePath + "/close_rest.png",
          Seadragon.Config.imagePath + "/close_grouphover.png",
          Seadragon.Config.imagePath + "/close_hover.png",
          Seadragon.Config.imagePath + "/close_pressed.png",
          null,
          null,
          function() {
            $(zoomContainer).hide();
            $(selector).show();
            /* for any element of class scrolling-on that is inside an iframe
             * turn scrolling back on when close zoom
             */
            $('iframe.scrolling-on', parent.document).attr ("scrolling", "on");
          },
          null,
          null
          );
    navControl.appendChild(closeButton.elmt);
    $(zoomContainer).fadeIn('slow');
    $(selector).hide();

    /* for any element of class scrolling-on that is inside an iframe
     * scroll to the top and turn scrolling off before zoom
     */
    if ($('iframe.scrolling-on', parent.document).length == 1) {
      $(document).scrollTop(0) ;
      $(document).scrollLeft(0) ;
      $('iframe.scrolling-on', parent.document).attr ("scrolling", "off");
    }
  }
}

function omnitureSend(pageName, eVarNo, eventNo) {
  if(s) {
    s.pageName = pageName;
    s.linkTrackVars='prop1,eVar' + eVarNo + ',events';
    s.events='event' + eventNo;
    s.prop1=pageName;
    eval('s.eVar' + eVarNo + '= "' + pageName + '"');
    s.tl(this,'o',pageName);
  }
}

function openTerms(url, contextPath) {
  openWindow('',url, contextPath, 800, 510, true, 'iframe','centered', null);
}

function openWindow(el, url, contextPath, width, height, modal, windowsrc, position, event) {
  $(el).closeDOMWindow();
  $(el).openDOMWindow ({
    eventType: event,
    windowSource:windowsrc,
    loader:1,
    loaderImagePath: contextPath + '/assets/images/common/loading.gif',
    loaderHeight:50,
    loaderWidth:50,
    width:width,
    height:height,
    overlayOpacity:60,
    positionType: position,
    windowSourceURL: url,
    modal: modal
  });
}

//SHUAI display all promo if it is approved.
$(document).ready(function(){
  //for promo b c d e.
  //if having child element <a></a>, see if existing content contained in <a> element.
  $(".sm-promo").each(function(){
    var info;
    if($(this).find("a").size()>0){
      info = $.trim($(this).find("a").html());
    }else{
      info = $.trim($(this).html());
    }
    if(info){
      $(this).css({display:'block'});
    }
  });
  var info = "";
  if($("#promo-b")) {
    if($("#promo-b").size()>0){
      info = $.trim($("#promo-b").html());
    }
    if(info){
      $("#promo-b").css({display:'block'});
    }
  }
  info = "";
  if($("#promo-c")) {
    if($("#promo-c").size()>0){
      info = $.trim($("#promo-c").html());
    }
    if(info){
      $("#promo-c").css({display:'block'});
    }
  }
  info = "";
  if($("#promo-d")) {
    if($("#promo-d").size()>0){
      info = $.trim($("#promo-d").html());
    }
    if(info){
      $("#promo-d").css({display:'block'});
    }
  }
  info = "";
  if($("#promo-e")) {
    if($("#promo-e").size()>0){
      info = $.trim($("#promo-e").html());
    }
    if(info){
      $("#promo-e").css({display:'block'});
    }
  }
  info = "";
  if($(".main-nav")) {
    if($(".sub-nav")) {
      if($(".main-nav").size()>0 && $(".sub-nav").size()>0){
        info = $.trim($(".nav_promos").html());
      }
      if(info){
        $(".nav_promos").css({display:'block'});
      }
    }
  }
});

var Browser = {
        
    getIEVersion : function () {
        var ieVersion = -1; 
        var userAgent = String(navigator.userAgent);
        if (userAgent.indexOf("MSIE") != -1) {
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(userAgent) != null)
                ieVersion = parseFloat(RegExp.$1);
        }
        return ieVersion;
    },

    showIEBrowserWarningDisplay : function () {
        
        $(window).scrollTop(1);
        var loader = $("#ui-loader-cover");
        
        if (!loader[0]) {
            loader = $("<div id='ui-loader-cover' class='ui-loader-cover'/>");
            $("body").append(loader);
        }
        
        var warningDisplay = $("#ui-ie-browser-warning-display-container");
        warningDisplay.css("top", ($(window).height() / 2) - warningDisplay.height());
        warningDisplay.css("left", ($(window).width() / 2) - 200);
        $("body").append(warningDisplay);
        
        loader.height($("body").height() + 20);
        $("body").addClass("ui-ie-browser-warning-display");
        
    },
    
    hideIEBrowserWarningDisplay : function () {
        
        $("body").removeClass("ui-ie-browser-warning-display");
        
    },
    
    checkBrowserVersion : function () {
        var ieVersion = Browser.getIEVersion();
        if (ieVersion > 0) {
            var documentMode = document.documentMode;
            if ((ieVersion < 8) || (documentMode != null && documentMode < 8)) {
                Browser.showIEBrowserWarningDisplay();
            }
        }
    },
    
    close : function () {
        
        window.opener = window;
        window.close();
        
    }
    
}

