jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


var currentTextInputValue; // used to track value of text input fields

function clearTextBox(elem){
  currentTextInputValue=$(elem).attr("value");
  $(elem).attr("value","");
}

function checkTextBox(elem){
  var blanks=/^\s*$/;
  if(blanks.test($(elem).attr("value"))){
    $(elem).attr("value",currentTextInputValue);
  }
}



function validateEmail(email){
  if(! /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email)){
    $("#email_form_error_message").html(email + " is not a valid email address.").css("display","block");
    return false;
  }
}


var tempSizes=new Array();

function fontSize(container, target, minSize, defSize, maxSize) {
    
    var ii = 0;
    $(target).find("*").each( function() {
        if ( $(this).parents(".change_text_size").size() == 0 && $(this).parents("#footer").size() == 0 && $(this).hasClass("no-resize") == false ) {
            tempSizes[ii] = parseInt($(this).css("font-size"));
            ii++;
        }
    });
    // alert( tempSizes.length );
  /*Editable settings*/
  var minCaption = "Make font size smaller"; //title for smallFont button
  var defCaption = "Make font size default"; //title for defaultFont button
  var maxCaption = "Make font size larger"; //title for largefont button
 
  /*
  //Now we'll add the font size changer interface in container
  smallFontHtml = "<a href='javascript:void(0);' class='smallFont' title='" + minCaption +"'>" + minCaption + "</a> ";
  defFontHtml = "<a href='javascript:void(0);' class='defaultFont' title='" + defCaption +"'>" + defCaption + "</a> ";
  largeFontHtml = "<a href='javascript:void(0);' class='largeFont' title='" + maxCaption +"'>" + maxCaption + "</a> ";
  $(container).html(smallFontHtml + defFontHtml + largeFontHtml);
  */
  
  //Read cookie &amp; sets the fontsize
  if ( $.cookie != undefined && $.cookie('fontsize') != null ) {
        adjustFontSizeToCookieValue();
  }
  
  function writeDefaultFontSizes() {
      try {
        var iii = 0;
        $(target).find("*").each( function() {
            if ( ($(this).parents(".change_text_size").size() == 0) && ($(this).parents("#footer").size() == 0) && ($(this).hasClass("no-resize") == false) ) {
                $(this).css("font-size", parseInt( tempSizes[iii]) );
                iii++;
            }
        });
      }
        catch(err) {
	}
	
  }
  
  function adjustFontSizeToCookieValue() {
      var cValue = $.cookie('fontsize');
      if ( cValue != null ) {
            writeDefaultFontSizes();
        }
        if ( cValue > 0 ) {
          for ( var i=cValue;i>0;i--) {
              $(target).find("*").each( function() {
                    curSize = parseInt($(this).css("font-size"));
                    newSize = curSize + 1;
                    if ((newSize <= maxSize) && ($(this).parents(".change_text_size").size() == 0) && ($(this).parents("#footer").size() == 0) && ($(this).hasClass("no-resize") == false)) {
                        $(this).css('font-size', newSize);
                    }
                });
          }
      }
      else if ( cValue < 0 ) {
          for ( var i=cValue;i<0;i++) {
              $(target).find("*").each( function() {
                    curSize = parseInt($(this).css("font-size"));
                    newSize = curSize - 1;
                    if ((newSize >= minSize) && ($(this).parents(".change_text_size").size() == 0) && ($(this).parents("#footer").size() == 0) && ($(this).hasClass("no-resize") == false) ) {
                        $(this).css('font-size', newSize);
                    }
                });
          }
      }
  }
 
  //on clicking small font button, font size is decreased by 1px
  $("#text_smaller").click(function() {
      updatefontCookie('fontsize', 'smaller'); //sets the cookie
        $(target).find("*").each( function() {
            curSize = parseInt($(this).css("font-size"));
            newSize = curSize - 1;
            if ((newSize >= minSize) && ($(this).parents(".change_text_size").size() == 0) && ($(this).parents("#footer").size() == 0) && ($(this).hasClass("no-resize") == false) ) {
                $(this).css('font-size', newSize);
            }
        });
  });
 
  //on clicking default font size button, font size is reset
    $("#text_normal").click(function() {
        try {
            updatefontCookie('fontsize');
            var iii = 0;
            $(target).find("*").each( function() {
                if ( ($(this).parents(".change_text_size").size() == 0) && ($(this).parents("#footer").size() == 0) && ($(this).hasClass("no-resize") == false )) {
                    $(this).css("font-size", parseInt( tempSizes[iii]) );
                    iii++;
                }
            });
        }
        catch(err) {
	
	}
  });
 
  //on clicking large font size button, font size is incremented by 1 to the maximum limit
  $("#text_larger").click(function(){
        updatefontCookie('fontsize', 'larger');
        $(target).find("*").each( function() {
            curSize = parseInt($(this).css("font-size"));
            newSize = curSize + 1;
            if ((newSize <= maxSize) && ($(this).parents(".change_text_size").size() == 0) && ($(this).parents("#footer").size() == 0) && ($(this).hasClass("no-resize") == false)) {
                $(this).css('font-size', newSize);
            }
        });
  });
 
  function updatefontCookie(name, size) { //Private function for setting cookie
    if ($.cookie != undefined) { //If cookie plugin available, set a cookie
        var nSize = null;
        if ( $.cookie('fontsize') == null ) {
            writeDefaultFontSizes();
        }
        if ( size == 'larger' ) {
            nSize = Number($.cookie(name)) +1;
        }
        else if ( size == 'smaller' ) {
            nSize = Number($.cookie(name)) -1;
        }
      // var cookie = target.replace(/[#. ]/g,'');
      $.cookie(name, nSize, {path: '/'});
    }
  }
}


$(document).ready(function(){

    if($(".schedule_an_appointment_link").length>0){
      $(".schedule_an_appointment_link").fancybox({
	"autoDimensions":false,
	"overlayColor":"#000",
	"overlayOpacity":.7,
	"padding":30,
	"margin":0,
	"width":260,
	"height":375,
	"onStart":function(){
	  $("#fancybox-wrap").removeClass().addClass("fancybox_find_a_location");
	  }
	 });
      }

  /* init datepicker */
  $("#component_calendar").datepicker({
    dateFormat:'yy-mm-dd',
    showOtherMonths:true,
    selectOtherMonths:false,
    onSelect:function(dateText,inst){
      $("#calendar_selected_date").val(dateText);
    }
  });

  $("#hidden_component_calendar").datepicker({
    dateFormat:'yy-mm-dd',
    showOtherMonths:true,
    selectOtherMonths:false,
    onSelect:function(dateText,inst){
      $("#hidden_calendar_selected_date").val(dateText);
    }
  });
  var temp_date=$.datepicker.formatDate("yy-mm-dd",new Date());
  //$("#calendar_selected_date").val(temp_date);
  //$("#hidden_calendar_selected_date").val(temp_date);
  
  
  $("#zip_code_field").focus(function(){
      $("#zip_code_form_error_message").css("display","none");
  });

  $("#calendar_form_zip").focus(function(){
      $("#calendar_error_message").css("display","none");
  });

  $("#hidden_calendar_form_zip").focus(function(){
      $("#hidden_calendar_error_message").css("display","none");
  });

  $("#email_field").focus(function(){
      $("#email_form_error_message").css("display","none");
    });
  
  /* Brian added */

     $("#request_brochure_form").validate({
        errorClass: "invalid",
        validClass: "valid",
        focusCleanup: true,
        showErrors: false,
        errorElement: "span",
        /*success: function(label) {
         alert( label.html() );
       }, */
        highlight: function(element, errorClass, validClass) {
            $(element).addClass(errorClass).removeClass(validClass);
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).removeClass(errorClass).addClass(validClass);    
        },
        errorPlacement: function(error, element) {
            
            if ( element.attr("err_label") && $("label[for=" + element.attr("err_label") + "]").siblings("span.invalid").size() == 0 ) {
                error.insertBefore( $("label[for=" + element.attr("err_label") + "]") );
            }
            else {
                error.insertBefore( $("label[for=" + element.attr("id") + "]") );
            }
        }
    }); 
  
     $("#request_newsletter_form").validate({
        errorClass: "invalid",
        validClass: "valid",
        focusCleanup: true,
        showErrors: false,
        errorElement: "span",
        /*success: function(label) {
         alert( label.html() );
       }, */
        highlight: function(element, errorClass, validClass) {
            $(element).addClass(errorClass).removeClass(validClass);
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).removeClass(errorClass).addClass(validClass);    
        },
        errorPlacement: function(error, element) {
            
            if ( element.attr("err_label") && $("label[for=" + element.attr("err_label") + "]").siblings("span.invalid").size() == 0 ) {
                error.insertBefore( $("label[for=" + element.attr("err_label") + "]") );
            }
            else {
                error.insertBefore( $("label[for=" + element.attr("id") + "]") );
            }
        }
    }); 


  $("#calendar_form").validate({
        // debug: true,
        errorClass: "invalid",
        validClass: "valid",
        // focusCleanup: true,
        submitHandler: function(form) {
            var address = $("#calendar_form_zip").val() ;
	    var isValidZip = false;
	    if( /\d{5}(-\d{4})?/.test(address) || /[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d/.test(address)){
	      isValidZip = true;
	    }
	    var selectedDate=$("#calendar_selected_date").val();
	    if(selectedDate!=""){
	    selectedDate=$.datepicker.parseDate("yy-mm-dd",selectedDate);
	      selectedDate=new Date(selectedDate);
	      selectedDate=selectedDate.getTime();
	      var current_date=new Date();
	      current_date=current_date.getTime();
	      var two_days=current_date+(1*24*60*60*1000);
	      var sixty_days=current_date+(60*24*60*60*1000);
	      if((selectedDate<two_days)||(selectedDate>sixty_days)){
		$("#calendar_error_message").html("Please select a date that is at least one business day away but not more than sixty days away.").css("display","block");
		return false;
	      }
	    }
             if (isValidZip) {
                // THESE ARE THE RESULTS WE WANT SO DO THE REDIRECT HERE 
                    goZipComponentCalendar();

                } else {
                    //alert("Geocode was not successful for the following reason: " + status);
		    $("#calendar_error_message").html($("#calendar_form_zip").val() + " is not a valid U.S. or Canadian zip code.").css("display","block");
                    return false;
               }
	       
        },
        showErrors: false,
        errorElement: "span",
        highlight: function(element, errorClass, validClass) {
            $(element).addClass(errorClass).removeClass(validClass);
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).removeClass(errorClass).addClass(validClass);    
        },
        errorPlacement: function(error, element) {
            
            if ( element.attr("err_label") && $("label[for=" + element.attr("err_label") + "]").siblings("span.invalid").size() == 0 ) {
                error.insertBefore( $("label[for=" + element.attr("err_label") + "]") );
            }
            else {
                error.insertBefore( $("label[for=" + element.attr("id") + "]") );
            }
        }
    });
    
  $("#hidden_calendar_form").validate({
        // debug: true,
        errorClass: "invalid",
        validClass: "valid",
        // focusCleanup: true,
        submitHandler: function(form) {
            var address = $("#hidden_calendar_form_zip").val() ;
	    var isValidZip = false;
	    if( /\d{5}(-\d{4})?/.test(address) || /[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d/.test(address)){
	      isValidZip = true;
	    }
	    var selectedDate=$("#hidden_calendar_selected_date").val();
	    if(selectedDate!=""){
	    selectedDate=$.datepicker.parseDate("yy-mm-dd",selectedDate);
	      selectedDate=new Date(selectedDate);
	      selectedDate=selectedDate.getTime();
	      var current_date=new Date();
	      current_date=current_date.getTime();
	      var two_days=current_date+(2*24*60*60*1000);
	      var sixty_days=current_date+(60*24*60*60*1000);
	      if((selectedDate<two_days)||(selectedDate>sixty_days)){
		$("#hidden_calendar_error_message").html("Please select a date that is at least two days away but not more than sixty days away.").css("display","block");
		return false;
	      }
	    }
	    // Remove map call
	    if (isValidZip) {
                   goZipInlineCalendar();
                } else {
                    //alert("Geocode was not successful for the following reason: " + status);
		    $("#hidden_calendar_error_message").html($("#hidden_calendar_form_zip").val() + " is not a valid U.S. or Canadian zip code.").css("display","block");
                    return false;
               }
        },
        showErrors: false,
        errorElement: "span",
        highlight: function(element, errorClass, validClass) {
            $(element).addClass(errorClass).removeClass(validClass);
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).removeClass(errorClass).addClass(validClass);    
        },
        errorPlacement: function(error, element) {
            
            if ( element.attr("err_label") && $("label[for=" + element.attr("err_label") + "]").siblings("span.invalid").size() == 0 ) {
                error.insertBefore( $("label[for=" + element.attr("err_label") + "]") );
            }
            else {
                error.insertBefore( $("label[for=" + element.attr("id") + "]") );
            }
        }
    });
    
    // Extending validator to show messages as title attr instead of text
    $.validator.prototype.showLabel = function(element, message) {
        var label = this.errorsFor( element );
        if ( label.length ) {
            // refresh error/success class
            label.removeClass().addClass( this.settings.errorClass );
        
            // check if we have a generated label, replace the message then
            label.attr("generated") && label.html("").attr("title",message);
        } else {
            // create label
            label = $("<" + this.settings.errorElement + "/>")
                .attr({"for":  this.idOrName(element), generated: true})
                .addClass(this.settings.errorClass)
                .html("").attr("title",message);
            if ( this.settings.wrapper ) {
                // make sure the element is visible, even in IE
                // actually showing the wrapped element is handled elsewhere
                label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
            }
            if ( !this.labelContainer.append(label).length )
                this.settings.errorPlacement
                    ? this.settings.errorPlacement(label, $(element) )
                    : label.insertAfter(element);
        }
        if ( !message && this.settings.success ) {
            label.text("");
            typeof this.settings.success == "string"
                ? label.addClass( this.settings.success )
                : this.settings.success( label );
        }
        this.toShow = this.toShow.add(label);
        }
        

    
    /* end brian added */
  
  

  /* clear and insert value for text input fields on focus and onblur */
  $(".input_text").each(function(index){
    $(this).focus(function(){clearTextBox($(this));});
  });
  $(".input_text").each(function(index){
    $(this).blur(function(){checkTextBox($(this));});
  });



  /* initiate mbMenu on top nav */
  $(".main_nav").buildMenu(
    {
      containment:"page", // the id of the containment element
      openOnRight:false,
      openOnClick:false,
      fadeInTime:200,
      fadeOutTime:200,
      hasImages:false, // does menu items have images on the left?
      menuSelector:".menu_container", // css class applied to each menu container
      closeOnMouseOut:true, // close menu afon mouse out
      menuWidth:300,
      closeAfter:200
    }
  );

  /* initiate mbMenu on left nav */
  $(".nav_col .nav").buildMenu(
    {
      containment:"page", // the id of the containment element
      openOnRight:true,
      openOnClick:false,
      fadeInTime:200,
      fadeOutTime:200,
      hasImages:false, // does menu items have images on the left?
      menuSelector:".menu_container", // css class applied to each menu container
      closeOnMouseOut:true, // close menu afon mouse out
      menuWidth:300,
      closeAfter:200
    }
  );


  /* init sliders */
    $('.slider .head').toggle(
      function() {
        $(this).css("background",'url("/consumerUS/img/icon_down_arrow_9x6.gif") no-repeat left center');
        $(this).next().slideDown("fast");
      },
      function(){
        $(this).css("background",'url("/consumerUS/img/icon_right_arrow_6x9.gif") no-repeat left center');
        $(this).next().slideUp("fast");
      }
    ).next().hide();


fontSize("#container", "#page", 9, 12, 18);

});

