var commentFocus = {

  commentDefaultText: 'Add your comments',

  commentFocus: function() {
    var comment = $('#edit-comment');
    if (comment.val() == commentFocus.commentDefaultText) {
      comment.val('');
    }
  },

  commentBlur: function() {
    var comment = $('#edit-comment');
    if (comment.val() == '') {
      comment.val(commentFocus.commentDefaultText);
    }
  },

  init: function() {
    // Firefox remembers that the default text in the form field.
    var comment = $('#edit-comment');
    if (comment.val() == commentFocus.commentDefaultText) {
      // So we reset it.
      comment.val('');
    }

    // Attach the event handlers to swap the dummy text in and out as needed.
    $('#edit-comment')
      .bind('focus', commentFocus.commentFocus)
      .bind('blur', commentFocus.commentBlur)
      // And fire the blur event to intialize it.
      .blur();
  } // Note lack of a ,
};

// @todo Turn this into a jQuery plugin.  Abstract out the selectors and the
// default text so that they can be set by the caller of the plugin.  e.g.
// @code $('form#my-form input#edit-searchbox').inputFocus('Name, Address or Zip Code');

// course search default value
var courseSearchFocus = {

  courseSearchDefaultText: "Course Name",

  courseSearchQuery: "#views-exposed-form-course-search-default #edit-searchbox-wrapper input,\
  #views-exposed-form-course-search-page-1 #edit-searchbox-wrapper input",

  courseSearchFocus: function() {
    var search = $(courseSearchFocus.courseSearchQuery);
    if (search.val() == courseSearchFocus.courseSearchDefaultText) {
      search.val('');
    }
  },

  courseSearchBlur: function() {
    var search = $(courseSearchFocus.courseSearchQuery);
    if (search.val() == '') {
      search.val(courseSearchFocus.courseSearchDefaultText);
    }
  },

  init: function() {
    // Firefox remembers the default text in the form field.
    var search = $(courseSearchFocus.courseSearchQuery);
    if (search.val() == courseSearchFocus.courseSearchDefaultText) {
      // So we reset it.
      search.val('');
    }

    // Attach the event handlers to swap the dummy text in and out as needed.
    $(courseSearchFocus.courseSearchQuery)
      .bind('focus', courseSearchFocus.courseSearchFocus)
      .bind('blur', courseSearchFocus.courseSearchBlur)
      // And fire the blur event to intialize it.
      .blur();
  } // Note lack of a ,
};

//course zip search default value
var courseZipSearchFocus = {

  courseZipSearchDefaultText: "ZIP",

  courseSearchQuery: "#views-exposed-form-course-search-default #edit-searchbox-zip-wrapper input,\
  #views-exposed-form-course-search-page-1 #edit-searchbox-zip-wrapper input",

  courseZipSearchFocus: function() {
    var search = $(courseZipSearchFocus.courseSearchQuery);
    if (search.val() == courseZipSearchFocus.courseZipSearchDefaultText) {
      search.val('');
    }
  },

  courseSearchBlur: function() {
    var search = $(courseZipSearchFocus.courseSearchQuery);
    if (search.val() == '') {
      search.val(courseZipSearchFocus.courseZipSearchDefaultText);
    }
  },

  init: function() {
    // Firefox remembers the default text in the form field.
    var search = $(courseZipSearchFocus.courseSearchQuery);
    if (search.val() == courseZipSearchFocus.courseZipSearchDefaultText) {
      // So we reset it.
      search.val('');
    }

    // Attach the event handlers to swap the dummy text in and out as needed.
    $(courseZipSearchFocus.courseSearchQuery)
      .bind('focus', courseZipSearchFocus.courseZipSearchFocus)
      .bind('blur', courseZipSearchFocus.courseSearchBlur)
      // And fire the blur event to intialize it.
      .blur();
  } // Note lack of a ,
};
// professional search default query
var proSearchFocus = {

  proSearchDefaultText:"Last Name",

  proSearchQuery: '.not-front #views-exposed-form-instructor-search-default #edit-searchbox-wrapper input,\
  #views-exposed-form-instructor-search-page-1 #edit-searchbox-wrapper input,\
  #views-exposed-form-professional-search-default #edit-searchbox-wrapper input,\
  #views-exposed-form-professional-search-page-1 #edit-searchbox-wrapper input',

  proSearchFocus: function() {
    var search = $(proSearchFocus.proSearchQuery);
    if (search.val() == proSearchFocus.proSearchDefaultText) {
      search.val('');
    }
  },

  proSearchBlur: function() {
    var search = $(proSearchFocus.proSearchQuery);
    if (search.val() == '') {
      search.val(proSearchFocus.proSearchDefaultText);
    }
  },

  init: function() {
    // Firefox remembers the default text in the form field.
    var search = $(proSearchFocus.proSearchQuery);
    if (search.val() == proSearchFocus.proSearchDefaultText) {
      // So we reset it.
      search.val('');
    }

    // Attach the event handlers to swap the dummy text in and out as needed.
    $(proSearchFocus.proSearchQuery)
      .bind('focus', proSearchFocus.proSearchFocus)
      .bind('blur', proSearchFocus.proSearchBlur)
      // And fire the blur event to intialize it.
      .blur();
  } // Note lack of a ,
};


// instructorHP search default query
var instructorHPSearchFocus = {

  instructorHPSearchDefaultText:"Instructor\'s Last Name",

  instructorHPSearchQuery: '.front #views-exposed-form-instructor-search-default #edit-searchbox-wrapper input,\
  #professional-instructor-count-search-form #edit-searchbox-wrapper input',

  instructorHPSearchFocus: function() {
    var search = $(instructorHPSearchFocus.instructorHPSearchQuery);
    if (search.val() == instructorHPSearchFocus.instructorHPSearchDefaultText) {
      search.val('');
    }
  },

  instructorHPSearchBlur: function() {
    var search = $(instructorHPSearchFocus.instructorHPSearchQuery);
    if (search.val() == '') {
      if (window.location.search.substring(1)==''&&window.location.search.substring(2)=='') {
        search.val(instructorHPSearchFocus.instructorHPSearchDefaultText);
      }
    }
  },

  init: function() {
    // Firefox remembers the default text in the form field.
    var search = $(instructorHPSearchFocus.instructorHPSearchQuery);
    if (search.val() == instructorHPSearchFocus.instructorHPSearchDefaultText) {
      // So we reset it.
      search.val('');
    }

    // Attach the event handlers to swap the dummy text in and out as needed.
    $(instructorHPSearchFocus.instructorHPSearchQuery)
      .bind('focus', instructorHPSearchFocus.instructorHPSearchFocus)
      .bind('blur', instructorHPSearchFocus.instructorHPSearchBlur)
      // And fire the blur event to intialize it.
      .blur();
  } // Note lack of a ,
};

// professional search default query
var proSearchFocus = {

  proSearchDefaultText:"Last Name",

  proSearchQuery: '.not-front #views-exposed-form-instructor-search-default #edit-searchbox-wrapper input,\
  #views-exposed-form-instructor-search-page-1 #edit-searchbox-wrapper input,\
  #views-exposed-form-professional-search-default #edit-searchbox-wrapper input,\
  #views-exposed-form-professional-search-page-1 #edit-searchbox-wrapper input',

  proSearchFocus: function() {
    var search = $(proSearchFocus.proSearchQuery);
    if (search.val() == proSearchFocus.proSearchDefaultText) {
      search.val('');
    }
  },

  proSearchBlur: function() {
    var search = $(proSearchFocus.proSearchQuery);
    if (search.val() == '') {
      if (window.location.search.substring(1)==''&&window.location.search.substring(2)=='') {
        search.val(proSearchFocus.proSearchDefaultText);
      }
    }
  },

  init: function() {
    // Firefox remembers the default text in the form field.
    var search = $(proSearchFocus.proSearchQuery);
    if (search.val() == proSearchFocus.proSearchDefaultText) {
      // So we reset it.
      search.val('');
    }

    // Attach the event handlers to swap the dummy text in and out as needed.
    $(proSearchFocus.proSearchQuery)
      .bind('focus', proSearchFocus.proSearchFocus)
      .bind('blur', proSearchFocus.proSearchBlur)
      // And fire the blur event to intialize it.
      .blur();
  } // Note lack of a ,
};


//professional zip search default query
var proZipSearchFocus = {

  proZipSearchDefaultText: "ZIP",

  proZipSearchQuery: 'form#views-exposed-form-instructor-search-default #edit-searchbox-zip-wrapper input,\
  #views-exposed-form-instructor-search-page-1 #edit-searchbox-zip-wrapper input,\
  #views-exposed-form-professional-search-default #edit-searchbox-zip-wrapper input,\
  #views-exposed-form-professional-search-page-1 #edit-searchbox-zip-wrapper input,\
  #professional-instructor-count-search-form #edit-searchbox-zip-wrapper input',

  proZipSearchFocus: function() {
    var search = $(proZipSearchFocus.proZipSearchQuery);
    if (search.val() == proZipSearchFocus.proZipSearchDefaultText) {
      search.val('');
    }
  },

  proZipSearchBlur: function() {
    var search = $(proZipSearchFocus.proZipSearchQuery);
    if (search.val() == '') {
      search.val(proZipSearchFocus.proZipSearchDefaultText);
    }
  },

  init: function() {
    // Firefox remembers the default text in the form field.
    var search = $(proZipSearchFocus.proZipSearchQuery);
    if (search.val() == proZipSearchFocus.proZipSearchDefaultText) {
      // So we reset it.
      search.val('');
    }

    // Attach the event handlers to swap the dummy text in and out as needed.
    $(proZipSearchFocus.proZipSearchQuery)
      .bind('focus', proZipSearchFocus.proZipSearchFocus)
      .bind('blur', proZipSearchFocus.proZipSearchBlur)
      // And fire the blur event to intialize it.
      .blur();
  } // Note lack of a ,
};
(function ($) {
  $(document).ready( function () {

  // Cufon replace
  Cufon.replace('h1');

  // Roundies are displaying incorrectly in IE8.
  if ($.browser.msie && parseInt($.browser.version) < 8) {
    DD_roundies.addRule('.region-header-widgets .block', '0 0 0 5px;'); // selector and multiple radii
    DD_roundies.addRule('#block-custom-login', '0 0 5px 5px;'); // selector and multiple radii
  }

  // Rounded corners for IE8 using jquery.corners.js "keep" keeps the border
  if ($.browser.msie && parseInt($.browser.version) == 8) {
    $('.region-header-widgets .block').corner('bl 5px');
    $('#block-custom-login').corner('bl br 5px');
  }


  $('.field-field-course-price-range, .field-field-course-price-range-scale').hover(
    function() {
    $(this).addClass("show-scale");
    },
    function() {
    $(this).removeClass("show-scale");
  });

  commentFocus.init();
  courseSearchFocus.init();
  courseZipSearchFocus.init();
  proSearchFocus.init();
  proZipSearchFocus.init();
  instructorHPSearchFocus.init();


   //identifies non-advertisement elements without title and adds class attribute
  $("div.region-sidebar-first").find("h2.title + .content").addClass("right-rail-content");
  $("div.panel-region-rail").find("h2.pane-title + .pane-content").addClass("right-rail-content-1");
  $("div.panel-region-rail").find("h2.title + .content").addClass("right-rail-content-1");

  //left notch
  $("div.panel-region-t2").find("h2.title + .content").prepend('<span class="left-notch"><img src="http://i2.cdn.turner.com/dr/pga/sites/default/themes/sitetheme/graphics/leftRail_titleArrow.png" alt="top notch" /></span>');
  $("div.panel-region-content").find("h2.title + .content").prepend('<span class="left-notch"><img src="http://i2.cdn.turner.com/dr/pga/sites/default/themes/sitetheme/graphics/leftRail_titleArrow.png" alt="top notch" /></span>');
  $("div.panel-region-content h2 + div.pane-content").prepend('<span class="left-notch"><img src="http://i2.cdn.turner.com/dr/pga/sites/default/themes/sitetheme/graphics/leftRail_titleArrow.png" alt="top notch" /></span>');
  $("div.region-content-top h2 + div.content").prepend('<span class="left-notch"><img src="http://i2.cdn.turner.com/dr/pga/sites/default/themes/sitetheme/graphics/leftRail_titleArrow.png" alt="top notch" /></span>');

  //right notch
  $("div.right-rail-content").prepend('<span class="notch"><img src="http://i2.cdn.turner.com/dr/pga/sites/default/themes/sitetheme/graphics/rightRail_titleArrow.png" alt="top notch" /></span>');
  $("div.right-rail-content-1").prepend('<span class="notch"><img src="http://i2.cdn.turner.com/dr/pga/sites/default/themes/sitetheme/graphics/rightRail_titleArrow.png" alt="top notch" /></span>');

  // I.E 7(xp) fix for Quicktabs module(not for IE 7 compatibility mode which works)
  if ($.browser.msie && $.browser.version == 7.0){
    
    //default tab for quick tab
    var attr = $('ul.quicktabs_tabs .qt_tab').attr('id');
    if (typeof attr !== 'undefined' && attr !== false) {
      default_id = $('ul.quicktabs_tabs .qt_tab').attr('id').slice(-3).split('-').join('_');
      $('div.quicktabs_main #quicktabs_tabpage_'+default_id).removeClass('quicktabs-hide');
    }
    
    $('ul.quicktabs_tabs .qt_tab').bind('click', function() {
      id = $(this).attr('id').slice(-3).split('-').join('_');
      $('quicktabs_main div.quicktabs_tabpage').each(function(){$(this).removeClass('quicktabs-hide').addClass('quicktabs-hide');});
      $('div.quicktabs_main #quicktabs_tabpage_'+id).removeClass('quicktabs-hide');
    });     
  } 
  
  //PRO- Services PGA EVENTS-
  $('.services .clickable').bind('click', function(){var id=$(this).next().attr('id'); 
    $(".services .clickable").each(function(){    
    $(this).next().removeClass('in-active').addClass('in-active');});
    $("#"+id).removeClass('in-active');     
  });
  
  // close button on the pro's service section PGA Event details block 
  $('.services .close_btn').click(function(){$(".services .clickable").next().addClass('in-active');}); 
  
  
 });
})(jQuery);

function ProFrameTabs() {
    if ($("#login-container").length && $("#pro-login").length) {
      $("#pro-login .pro-no").addClass('highlighted');
      
      $("#pro-login div").each(function() {
          $(this).click(function() {
            $("#pro-login div").removeClass('highlighted');
            $(this).addClass('highlighted');
          });
      });
      
      // @todo make this smarter in the future by adding it to the .each above
        $(".pro-yes").click(function() {
          $("#login-inner-container").css('display', 'none');
          $("#pro-frame").fadeIn(0);
        });
        $(".pro-no").click(function() {
          $("#login-container #pro-frame").css('display', 'none');
          $("#login-inner-container").fadeIn(0);
        });
    }
}

function CustomGigyaLogin(targetdiv) {
  // Apparently the button doesn't work when targeting the same
  // ID, so just use a different ID for within widget and modal
  $(targetdiv).click(function(){
    loginGigya();
  });
      
      // Gigya config
      var gigyaConfig = {
      "APIKey": Drupal.settings.gigya.conf.APIKey
      };
      
      // Gigya user
      var user = null;
      
      gigya.services.socialize.addEventHandlers(gigyaConfig, {
        onLogin: onLoginHandler
      });
      
      // Login via socialize.login
      function loginGigya() {
        gigya.services.socialize.login(gigyaConfig, {
          provider: "facebook"
        });
      }
      
      function onLoginHandler(e) {
        document.getElementById(targetdiv).setAttribute("style", "display: none;");
        document.getElementById("loggedIn").setAttribute("style", "");
      }
      
      function logout() {
        gigya.services.socialize.logout(gigyaConfig, {
          callback: function() {
            document.getElementById(targetdiv).setAttribute("style", "");
            document.getElementById("loggedIn").setAttribute("style", "display: none;");
          }
        });
      }
  
}

Drupal.behaviors.facebox = function(context) {
  
  // If Drupal set message is an error that is already displayed within modal
  // then hide
  $("div.error:has(ul)").css('display','none');
  
    CustomGigyaLogin('#loginSocialHeader');
      
    // Load up Pro tabs config on regular user login page
    ProFrameTabs();
  
  // Attach jQuery form plugin so page doesn't refresh stays on form submit
  $(document).bind('reveal.facebox', context, function(){
    
      CustomGigyaLogin('#loginSocialModal');
      // Load up Pro tabs config on modal
      ProFrameTabs();
  
      var targetdiv = '.ajax-form';
      var options = {
        target: targetdiv,
        success: processAjaxForm
        };
      $(targetdiv).submit(function() {
        $(this).ajaxSubmit(options);
        return false;
      });
  });
  
  $(document).unbind("close.facebox", context);
  
  var signature = getUrlVars()["signature"];
  var UID = getUrlVars()["UID"];
  var timestamp = getUrlVars()["timestamp"];
  if (signature && UID && timestamp) {
    // Pull up Gigya registration form with parameters required for setUID to pass
    jQuery.facebox({ajax: Drupal.settings.basePath + 'authenticate/socialize-register?signature=' + signature + '&UID=' + UID + '&timestamp=' + timestamp + '&destination='});
  }

  function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
      vars[key] = value;
      });
    return vars;
  }
};


// Process modal form
function processAjaxForm(data) {
  
  var faceboxdiv = '#facebox .content';
  
  // If response is JSON string, it should be successful convert it to an object
  // and proceed if status is true
  if (data.substr(0,1) == '{') {
    
    jsonobj = eval("(" + data + ")");
    if (jsonobj.status == true) {
        // Return string checks for conditional modal manipulation before closing
        //console.log(jsonobj.form_id);
      if (jsonobj.form_id == 'user_login' || checkifEmpty(jsonobj.messages_status)) {
        $(faceboxdiv).empty();
        $.facebox.close();
        window.location.reload();
      }
      else if ("value" in jsonobj.messages_status[0]) {
        var strval = jsonobj.messages_status[0].value;
        /* Successful registration, refresh page without any URL parameters
         * No URL parameters is important because on Gigya registration there
         * are 3 params that need to be removed on successful modal
         * FB registration-so as to not refresh the page and get a faulty modal
         */
        if (strval == "Registration successful. You are now logged in."){
          $(faceboxdiv).empty();
          $(faceboxdiv).html('<div id="registration-success" class="success">Thanks for registering with PGA.com! You will be automatically logged in within a few seconds.</div>');
          // Set Facebox to close immediately so it doesn't seem delayed
          setTimeout("$.facebox.close()",3000);
          var url = window.location.href;
          var clean_url = url.split("?")[0];
          window.location = clean_url;
        }
        /* Forgot password */
        else if (strval == 'Further instructions have been sent to your e-mail address.') {
          $(faceboxdiv).empty();
          $(faceboxdiv).html('<div id="forgot-pass-success" class="success">' + strval + '</div>');
          setTimeout("$.facebox.close()",5000);
        }
      }
      else {
        $(faceboxdiv).empty();
        $.facebox.close();
        window.location.reload();
      }
    }
    else {
      $.facebox.close();
    }
  }
  
  // Else it must be an error
  else {
    $(faceboxdiv).html(data);
    
    validateBirthday();
    
    // If errors exists, add class to parent div of input to display arrows
    if ($("input").is(".error") || $("select").is(".error")) {
      $(".error").closest(".form-item").addClass("errors-present");
      $("#missing-fields").fadeIn(500);
      formErrorEvaluate();
      
      // Call ajaxSubmit again-otherwise will go to menu item on success
      var targetdiv = '.ajax-form';
      var options = {
        target: targetdiv,
        beforeSubmit: doubleValidate,
        success: processAjaxForm
        };
      $(targetdiv).submit(function() {
        $(this).ajaxSubmit(options);
        return false;
      });
    
    }
  }
}

/* Modal form validations */
// Success
function checkifEmpty(obj) {
    for ( var name in obj ) {
        return false;
    }
    return true;
}

// Errors
function doubleValidate() {
  
  if ($("#user-register").length) {
  
    if ($("input").is(".error")) {
      
      removeErrors();
      var passcount = $("#edit-pass").val().length;
      var statecount = $("#edit-profile-state").val().length;
      if (passcount >= 6 || statecount == '' || validateBirthday) {
        formErrorEvaluate();
        return false;
      }
    }
  }
}

// Helper function for double validation step to remove error wrappers
// if fields get filled with valid values
function removeErrors() {
  var email_selectors = '#edit-mail-mail1,#edit-mail-mail2';
  $(email_selectors).keyup(function(event) {
    if ($("#edit-mail-mail1").val() == $("#edit-mail-mail2").val()) {
      var fadeout_selectors = '#validate-email-confirm,#validate-email-valid,#validate-email-exists';
      removeError(email_selectors, fadeout_selectors);
    };
  });
  var fnametrigger = 0;
  $('#edit-profile-first-name').keyup(function(event) {
    fnametrigger++;
    if ($(this).val().length) {
      removeError(this);
    };
  });
  var lnametrigger = 0;
  $('#edit-profile-last-name').keyup(function(event) {
    lnametrigger++;
    if ($(this).val().length) {
      removeError(this);
    };
  });
  // This requires a bind command as there is usually no keystrokes in select lists/checkboxes
  $('#edit-profile-state').bind("change keyup", function(event) {
    if (event && $(this).val().length == 2) {
      removeError(this, '#validate-state');
    };
  });
  var ziplength = $('#edit-profile-zip').val().length;
  $('#edit-profile-zip').keyup(function(event) {
    ziplength++;
    if ($(this).val().length == 5) {
      removeError(this, '#validate-zip');
    };
  });
  var passlength = $('#edit-pass').val().length;
  $('#edit-pass').keyup(function(event) {
    passlength++;
    if ($(this).val().length >= 6) {
      removeError(this, '#validate-pass');
    };
  });
  $('#edit-terms').bind("change keyup", function(event) {
    if ($("#edit-terms:checked").val().length) {
      removeError(this);
      $("#edit-terms-wrapper").removeClass("error-terms");
    };
  });
  var birthday_selectors = '#edit-profile-birthday-month,#edit-profile-birthday-day,#edit-profile-birthday-year';
  $(birthday_selectors).bind("change keyup", function(event) {
    if (!validateBirthday()) {
      removeError(birthday_selectors, '#validate-birthday');
      $("#edit-profile-birthday-wrapper").removeClass("error-terms");
    };
  });
  
  
}

function removeError(selector, fadeout_selector) {
  $(selector).closest(".form-item").removeClass("errors-present");
  $(selector).removeClass('error');
  
  if (fadeout_selector == null) {
    fadeout_selector = '';
  }
  
  if (fadeout_selector) {
    $(fadeout_selector).fadeOut();
    if (!$("input").is(".error")) {
      $("#missing-fields").fadeOut();
    }
  }
}

function formErrorEvaluate() {
  
  // Length checks are to make sure error message doesn't get loaded twice
  
      // User registration validation only
      if ($("#user-register").length) {
        
        var missed = '#missing-fields';
        removeErrors();
        
        // Adding this because doubleValidate() needs it
        if ($("input").is(".error")) {
          $(".error").closest(".form-item").addClass("errors-present");
        }
        
        // Make sure terms is checked
        if ($("#edit-terms-wrapper").is(".errors-present")) {
          $("#edit-terms-wrapper").addClass("error-terms");
        }
        
        if (!$("#socialize-register-facebox").length && !$('#validate-email-exists').length) {
          // Validate email
          var emailval = $('#edit-mail-mail1').val();
          if (emailval.length > 0) {
            $.ajax({
              type: "GET",
              url: Drupal.settings.basePath + "validate/registration",
              data: "mail=" + encodeURI(emailval),
              success: function(msg){
                jsonobj = eval("(" + msg + ")");
                if (jsonobj.user_email_exists == 1) {
                  $('#edit-mail-mail1').addClass('error');
                  var message = '<div id="validate-email-exists" class="modal-error">The e-mail address ' + emailval + ' already exists</div>';
                  $(missed).append(message);
                }
              }
            });
          }
        }
        
        if (!$("#socialize-register-facebox").length && !$('#validate-email-valid',missed).length) {
          var emailval = $('#edit-mail-mail1').val();
          if (emailval == '' || validateEmail(emailval) == false) {
            var message = '<div id="validate-email-valid" class="modal-error">The e-mail address ' + emailval + ' is not valid</div>';
            $(missed).append(message);
            
            // Client validation is different than Drupal validation, add the needed error classes
            //$('#edit-mail-wrapper').addClass('errors-present');
          }
        }
        
        var emailvalidators = !$('#validate-email-valid',missed).length || !$('#validate-email-exists',missed).length ? 1 : 0;
        if (!$("#socialize-register-facebox").length && !$("#validate-email-confirm").length && $("edit-mail-mail1").val() !== $("#edit-mail-mail2").val() && emailvalidators) {
          // Validate email
          var emailval1 = $("#edit-mail-mail1").val();
          var emailval2 = $("#edit-mail-mail2").val();
          if (emailval1 !== emailval2) {
            $("#edit-mail-mail2").addClass('error');
            var message = '<div id="validate-email-confirm" class="modal-error">Your emails do not match. Please try again.</div>';
            $(missed).append(message);
          }
        }
        
        if (!$('socialize-register-facebox').length && !$('#validate-pass',missed).length) {
          // Validate pass
          if ($("#edit-pass").is(".error") || $("#edit-pass").val().length < 6) {
            $('#edit-pass').addClass('error');
            var message = '<div id="validate-pass" class="modal-error">It is recommended to choose a password that contains at least six characters. It should include numbers, punctuation, and both upper and lowercase letters</div>';
            $(missed).append(message);
          }
        }
        
        if (!$('#validate-state',missed).length) {
          // Validate zip
          var stateval = $('#edit-profile-state').val().length;        
          if (stateval == '') {
            $('#edit-profile-state').addClass('error');
            var message = '<div id="validate-state" class="modal-error">The state entered is invalid.</div>';
            $(missed).append(message);
            $('#edit-profile-state-wrapper').addClass('errors-present');
          }
        }
        
        if (!$('#validate-zip',missed).length) {
          // Validate zip
          var zipval = $('#edit-profile-zip').val().length;        
          if (zipval == '' || zipval < 5) {
            $('#edit-profile-zip').addClass('error');
            var message = '<div id="validate-zip" class="modal-error">The specified zip code is invalid.</div>';
            $(missed).append(message);
            $('#edit-profile-zip-wrapper').addClass('errors-present');
          }
        }
        
        if (!$('#validate-birthday',missed).length) {
          if(validateBirthday()){
            $("#edit-profile-birthday-wrapper").addClass("error-terms");
            var message = '<div id="validate-birthday" class="modal-error">Sorry you are not old enough to register for the site.</div>';
            $(missed).append(message);
          }
        }
      
      }
}

function validateBirthday() {
  //Validating Access Restrictions (AGE>13)
  var day=$("#edit-profile-birthday-day").val();
  var month=$("#edit-profile-birthday-month").val();
  var year=$("#edit-profile-birthday-year").val();
  var age=13;
  var mydate = new Date();
  var currdate = new Date();
  mydate.setFullYear(year, month-1, day);
  currdate.setFullYear(currdate.getFullYear() - age);
    if ((currdate - mydate) < 0){
      $("#edit-profile-birthday-wrapper select").addClass("error");
      // true if birthday is wrong
      return true;
    }
    else {
      return false;
    }
}

function validateEmail($email) {
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if( !emailReg.test($email) ) {
      return false;
    } else {
      return true;
    }
}
