document.observe('dom:loaded', main);

function main() {
  activeMenu();
  roundedCorners();
  newsletterSignUpInputToImage();
  newsletterSignUpText();
  normalizeHomeBoxHeight();
  contactSubmitInputToImage();
  observePrintLink();
  populateContactFormAddress();
  populateSearchFields();
  detailsImages();
}

/**
 * Set main menu item to 'active' based on page name.
 */
function activeMenu() {
  $$('ul#menu li a').each(function(a) {
    if(document.title.match(a.innerHTML)) {
     a.addClassName('active');
    }
  });
}

/**
 * Apply rounded corners to elements.
 */
function roundedCorners() {
  // Rounded elements
  var re = ['mainSideBar', 'testimonials', 'contact-errors', 'mainSearchFormContainer', 'pageControls']; 
  // Apply corner effect to each element unless Safari
  re.each(function(e) {
    if($(e) && !Prototype.Browser.WebKit) { new Effect.Corner($(e)); }
  });
}
  
/**
 * Make 'Go' Button on newsletter sign up pretty.
 */
function newsletterSignUpInputToImage() {
  inputToImage("go_button.png", "markupfactory-getnewslettersignup-submit"); 
}

/** 
 * Make 'Submit' Button on contact form pretty
 */
function contactSubmitInputToImage() {
  var form = 'contactForm';
  if ($(form)) {
    inputToImage("submit_button.gif", "submit"); 
  }
}

/**
 * Change a submit input to an image input (in browsers other than IE.)
 */
function inputToImage(image, div) {
  var imagePath = "/assets/gengroup/images/design/";
  image = imagePath + image;

  if($(div)) {
    div = $(div);
    if(!Prototype.Browser.IE) {
      div.type = "image";
      div.src = image;
    } else {
      div.setStyle({marginBottom: "-1px"}); // Adjust display in IE.
    }
  }
}

/**
 * Put helper text in newsletter signup input
 */
function newsletterSignUpText() {
  var defaultValue = 'enter your email address.';
  var div = 'markupfactory-getnewslettersignup-email';
  if($(div)) {
    $(div).value = defaultValue;
    $(div).observe('click', function () { // Blank out the box if clicked.
      $(div).value = '';
    });
  }
}

/**
 * Make all elements in the home page box the same height.
 */
function normalizeHomeBoxHeight() {
  if($('homeBox')) {
    // Elements being measured
    var els = ['search', 'featured', 'homeSideBar'];
    // Get the maximum height by comparing each element
    var maxHeight = els.map(function(el) { return $(el).getHeight(); }).max();
    // Set all elements to the max height
    els.each(function(el) { $(el).setStyle({height: maxHeight + 'px'})}); 
  }
}

/**
 * Observe the printlink element.
 */
function observePrintLink() {
  var link = "printLink";
  if($(link)) {
    $(link).observe('click', function () { window.print() });
  }
}

/**
 * Try to populate the address on the contact form if a hidden ID field is 
 * present.
 */
function populateContactFormAddress() {
  var field = "id"; // Hidden field
  var textArea = "address"; // Address field
  var url = "/scripts/gengroup/mls/admin/info.asp"; // Address service
  var id; // Contents of field
  if ($(field)) {
    id = Number($F(field));
    if (id > 0) { // Check if id is a valid number
      if ($(textArea)) {
        // Call service for address
        new Ajax.Request(url, {
          method : "GET",
          parameters: { id: id },
          onComplete: function (transport) { 
            // Update element with response and remove HTML
            $(textArea).update(transport.responseText.stripTags()); 
          }
        });
      }
    }
  }
}

/**
 * Set the values of the main search fields to match what was searched for in
 * the query string.
 */
function populateSearchFields() {
  var searchForm = 'mainSearchForm'; // Id of search form.
  var query = {}; // Query string
  var fieldName; // Name of field
  if ($(searchForm)) {
    // Convert query string to object  
    query = window.location.search.toQueryParams(); 
    // Iterate over form elements
    $(searchForm).getElements().each(function(field) {
      // Iterate over options
      if(field.type === "select-one") {
        $A(field.options).each(function(option) {
          // Set the field value to the item in the query. Replace + with space
          // except where we have 1+, 2+, 3+, etc.
          fieldValue = unescape(query[field.name]).gsub(/(\D)\+/, "#{1} ");
          // Set the option to selected if it matched the query string
          if (option.value != "") {
            if(option.value === fieldValue) {
              option.selected = true;
            }
          } else if (option.innerHTML != "") {
            if(option.innerHTML === fieldValue) {
              option.selected = true;
            }
          }
        });
      }
    }); 
    
  }
}
  
/**
 * Image swapper for listing details page
 */
function detailsImages() {
  var primaryImage = 'primaryImage';
  var src;
  if ($('details') && $(primaryImage)) {
    $$('#details .images ul li a').each(function(a) {
      a.observe("click", function (evt) {
        src = a.href;
        a.href= "";
        $(primaryImage).src = src;  
        evt.stop();
        a.href = src;
      });
    });
  }
}
