(function($) {
  $(document).ready(function() {

    // All pages
    addBreadcrumbsBackgrounds();

    // Pages with sign in interface
    if ($("div.sign-in-interface").length) {
      setUpSignInInterfaces();
    }

    // Add Google Analytics to PDF files
    addGoogleAnalyticsToFiles();

    // Tait Partner Registration page
    if ($("#id35426").length) {
      populateCountryDropdown();
    }

    // News subscription box
    if ($("#bulkmail_subscribe_page_35986").length) {
      tidyUpNewsSubscriptionBox();
    }

    // News unsubscription page
    if ($("#bulkmail_subscribe_page_36017").length) {
      tidyUpNewsUnsubscriptionPage();
    }

  });  
})(jQuery);


function addBreadcrumbsBackgrounds() {

  // Add class to each <li> in the breadcrumbs <ol>. The class is prefixed by 'bread' and suffixed by the breadcrumb number.
  
  // First find number of crumbs
  var noOfCrumbs = $("#breadcrumbs ol li").length;
  
  var crumb = 1;
  $("#breadcrumbs ol li").each(function() {
    $(this).addClass("bread" + crumb);
    
    // Add a class of 'last' to the <a> tag within the <li> if the crumb is the last one.
    if (crumb == noOfCrumbs) {
      $(this).find("a").addClass("last");
    } else {
      $(this).find("a").removeClass("last");
    }
    
    crumb++;
  });

} // end of addBreadcrumbsBackgrounds



function setUpSignInInterfaces() {

  // If user presses the Enter key, either click the Get Access button or the Sign In button depending on which input element currently has the focus
  $('input.email-address').keypress(function(e){
    if (e.which == 13) {
      $("input.get-access-button").click();
    }
  });
  $('input.username, input.password').keypress(function(e){
    if (e.which == 13) {
      $("input.sign-in-button").click();
    }
  });

  // When 'Access this xxx' link is clicked, drop down the Sign in interface and show the Close button
  $("a.open-sign-in-interface").click(function() {
  
    var signInWrapper = $(this).parents("div.sign-in-interface-wrapper");
    signInWrapper.find("a.close-sign-in-interface").show();
    signInWrapper.find("div.sign-in-interface").slideDown();
  
  });

  // When the Close button is clicked, hide the Sign in interface and the Close button
  $("a.close-sign-in-interface").click(function() {
  
    $(this).hide();
    var signInWrapper = $(this).parents("div.sign-in-interface-wrapper");
    signInWrapper.find("div.sign-in-interface").slideUp();
  
  });
  
  // When the Get Access button is clicked, send the email address to Tait via a Custom Form.
  $("input.get-access-button").click(function() {

    var formName = "SQ_FORM_35038_PAGE";
    var formPage = "1";
    var formSubmitName = "form_email_35038_submit";
    var formSubmitVal = "Submit";

    var ajaxQuery = "&" + formName + "=" + formPage + "&" + formSubmitName + "=" + formSubmitVal;
    var emailAddress = $(this).parents("form").find("input.email-address").attr("value");
    var serializedData = "q35038:q1=" + emailAddress;
    
    var signInWrapper = $(this).parents("div.sign-in-interface-wrapper");
    
    // Client side check for valid email address
    if (isValidEmail(emailAddress)) {

      $.post("/guest-user-custom-form", serializedData + ajaxQuery, function(data) {

        // Server side check to see if custom form returned any errors (invalid email address)
        if (data.indexOf('Question "EmailAddress" is a required field; it must be filled in') > -1 ) {

          signInWrapper.find("div.new-visitors-error").text("Invalid email address");
        } else {
          signInWrapper.find("div.new-visitors-error").text("");

          // Now sign the user in using the Guest user account
          signInWrapper.find("input.username").attr("value", "guest");
          signInWrapper.find("input.password").attr("value", "transport");
          signInWrapper.find("input.sign-in-button").click();

        }

      });
    
    } else {

      signInWrapper.find("div.new-visitors-error").text("Invalid email address");

    }
    
  });
  
  // When the Sign in button is clicked, populate the hidden login form with the username and password and then click the Login button
  $("input.sign-in-button").click(function() {

    var signInWrapper = $(this).parents("div.sign-in-interface-wrapper");
    var username = signInWrapper.find("input.username").attr("value");
    var password = signInWrapper.find("input.password").attr("value");

    $("#SQ_LOGIN_USERNAME").attr("value", username);
    $("#SQ_LOGIN_PASSWORD").attr("value", password);
    $("#log_in_out_button").click();

  });
  
  // If there are any errors logging in, show these on the form
  var loginErrors = $("#login-form-errors").text();
  if (loginErrors.length) {
    $("div.registered-users-error").text(loginErrors);
  }

  // Ensure height of new-visitors and registered-users divs are the same. The height should be set to the maximum of the two.
  var newVisitors = $("div.new-visitors:first");
  var registeredUsers = $("div.regisitered-users:first");
  var newVisitorsHeight = newVisitors.css("height");
  var registeredUsersHeight = registeredUsers.css("height");
  
  if (newVisitorsHeight > registeredUsersHeight) {
    $(registeredUsers).css("height", newVisitorsHeight);
  } else {
    $(newVisitors).css("height", registeredUsersHeight);
  }
  

} // end of setUpSignInInterfaces()



function addGoogleAnalyticsToFiles() {

  // Add Google Analytics code to any PDF link. 
  $("a[href$='.pdf']").each(function() {

    var href = $(this).attr("href");

    // Extract the filename from the href string
    var lastSlashPos = href.lastIndexOf("/");
    href = href.substring(lastSlashPos);

    var onClickStr = "javascript: pageTracker._trackPageview('" + href + "'); ";

    $(this).attr("onclick", onClickStr);

  });

} // end addGoogleAnalyticsToFiles



function populateCountryDropdown() {

  // Populate the country list when the page loads
  $.ajax({
    type: "GET",
    url: "/__data/assets/text_file/0004/35968/country.xml",
    dataType: "xml",
    success: function(xml) {
      $(xml).find("country").each(function(){

        var country = $(this).text();
        var countryCode = $(this).attr("code");
        var optionStr = '<option value="' + countryCode + '">' + country + '</option>';

        $("#country-list").append(optionStr);

        // When page loads (if after errors found in form by server), select the correct option from the country list
        var countryTextBoxValue = $("#q35427_q11").attr("value");
        if (countryTextBoxValue > "") {

          // Loop through the country list until we find match with the hidden country text box
          $("#country-list option:contains(" + countryTextBoxValue + ")").each(function() {

            if ($(this).text() == countryTextBoxValue) {
              $(this).attr("selected","selected");
            }

          });

        }

      });

    }
  });

  // When user selects a country from the list, populate hidden country text field
  $("#country-list").change(function() {
  
    var country = $(this).find("option:selected");
    if (country.attr("value") > "") {
      $("#q35427_q11").attr("value", country.text());
    } else {
      $("#q35427_q11").attr("value", "");
    }
  
  });
  

} // end populateCountryDropdown



function tidyUpNewsSubscriptionBox() {

  // Show confirmation text if user has subscribed successfully
  if ($("#news-subscription-success ul li").length) {
    $("#news-subscription-success").append("<p>Thanks. You will now receive Tait news updates.</p>");
  }

  // Ensure email address is valid before submitting form
  $("#bulkmail_subscribe_page_35986_submit_button").click(function() {
  
    var emailAddress = $("#bulkmail_subscribe_page_35986_email_address").attr("value");
    if (!isValidEmail(emailAddress)) {
      $("#news-subscription-errors").html("<p>You must enter a valid email address</p>");
      return false;
    }
  
  });

} // end tidyUpNewsSubscriptionBox



function tidyUpNewsUnsubscriptionPage() {

  // Show confirmation text if user has unsubscribed successfully
  if ($("#news-subscription-success ul li").length) {
    $("#news-subscription-success").append("<p>You have been unsubscribed from Tait news updates.</p>");
  }

  // Ensure email address is valid before submitting form
  $("#bulkmail_subscribe_page_36017_submit_button").click(function() {
  
    var emailAddress = $("#bulkmail_subscribe_page_36017_email_address").attr("value");
    if (!isValidEmail(emailAddress)) {
      $("#news-subscription-errors").html("<p>You must enter a valid email address</p>");
      return false;
    }
  
  });

} // end tidyUpNewsUnsubscriptionPage



function isValidEmail(emailAddress) {

  var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
  return pattern.test(emailAddress);

} // end isValidEmail

