var findSortType       = '';
var findSortPrice       = '';
var findSortCommunity     = '';
var currentContactInputID   = '';
var communityID        = '';
var homePrice        = 0;

$(document).ready(function() {

  /***** BEGIN Homepage Unit Locator */

  // listen for every community "QUICK VIEW" link click event
  $('#community li div.list-img-wrap a.quick-view').click(function() {
    communityID = $(this).parent().parent().attr('id');
    communityQuickView(communityID,'');
    return false;
  });

  // reset all the units if the user clicks back on the community tab
  $('#map-tabs li.community a').click(function() {
    $('ul#units li').show();
  });

  // hide the fade div when they click on the units tab
  $('#map-tabs li.unit a').click(function() {
    $('#map-list-wrap div.fade').hide();
  });


  // show the fade div when they click on the community tab
  $('#map-tabs li.community a').click(function() {
    $('#map-list-wrap div.fade').show();
  });

  // send the user to the Find Your Home page when they click on the Price tab
  $('#map-tabs li.price a').click(function() {
    window.location = '/find/';
    return false;
  });


  /***** END Homepage Unit Locator */



  /***** BEGIN Find Your Home */

  // Clear out and reset the keyword field on focus / blur
  $('#find-home-search-input-keywords').focus(function() { if($(this).val() == 'Enter Keywords') $(this).val(''); });
  $('#find-home-search-input-keywords').blur(function() { if($(this).val() == '') $(this).val('Enter Keywords'); });

  // set the alternate rows
  setAltRows('#results-list-primary tr.result');

  // user selects a Community, Home Price or Unit Type
  $('#find-sort-by-community, #find-sort-by-price').change(function() {
    findSortCommunity = $('#find-sort-by-community option:selected').val();
    findSortPrice = $('#find-sort-by-price option:selected').val();
    performUnitSort();
  });

  $('#find-home-search-form').submit(function() {
    $('#find-home-search-error').addClass('hide');
    $("#find-home-search-form .inline input").fadeOut(250, function() {
      $("#find-home-search-load").fadeIn(250);
      $.ajax({
        type: "POST",
        url: $('#find-home-search-form').attr('action'),
        data: $('#find-home-search-form').serialize(),
        cache: false,
        dataType: "html",
        success: function(searchResults) {
          if(searchResults.match('<body>')) {
            var err = '<ul>'+searchResults.match('<li>[A-Za-z0-9- .*]+</li>')+'</ul><span></span>';
            $('#find-home-search-error').html(err);
            $("#find-home-search-load").fadeOut(250, function() {
              $("#find-home-search-form .inline input").fadeOut(250, function() {
                $('#find-home-search-error').fadeIn(250, function() {
                  setTimeout("$('#find-home-search-error').fadeOut(250, function() { $(\"#find-home-search-form .inline input\").fadeIn(); })",4000);
                });
              });
            });
          } else {
            $('#results-list-primary').fadeOut(250,function() {
              $('#results-list-primary tr.no-results').addClass('hide');
              if(!searchResults || searchResults == null) {
                $('#results-list-primary tr.result').addClass('hide');
                $('#results-list-primary tr.no-results').removeClass('hide');
                $("#find-home-search-load").fadeOut(250, function() {
                  $('#results-list-primary').fadeIn(250);
                  $("#find-home-search-form .inline input").fadeIn(250);
                });
                generateOtherUnitsList();
              } else {
                $('#results-list-primary tr.result').each(function() {
                  // first hide them all; we'll show if they meet a criterion
                  $(this).addClass('hide');
                  var splits = searchResults.split('|');
                  for(var i = 0; i < splits.length; i++) {
                    if(splits[i]) {
                      if($(this).hasClass('unit-id-'+splits[i])) $(this).removeClass('hide');
                    }
                  }
                });
                generateOtherUnitsList();
                setAltRows('#results-list-primary tr.result');
                $("#find-home-search-load").fadeOut(250, function() {
                  $('#results-list-primary').fadeIn(250);
                  $("#find-home-search-form .inline input").fadeIn(250);
                });
              }
            });
          }
        }
      });
    });
    setAltRows('#results-list-primary tr.result');
    return false;
  });

  /***** END Find Your Home */



  $("#map-area").tabs({ selected: 2 });
  $("#slideshow-pics").cycle({
    fx:   'fade',
    height: '320px',
      next:   '#slideshow-next',
      prev:   '#slideshow-previous'
  });

  // contact form instruction fields
  $(".instruct").hide();

  $("#contact-form :input").focus(function(){
    // find the ID
    var input_is_raw = $(this).attr("id");
    // remove the []
    var input_is = input_is_raw.replace(/\[]/,'');

    // check to see what the last input they clicked was. if is
    // a new input / set of inputs, then we'll do the tip fade again
    if(currentContactInputID != input_is) {
      $(".instruct").fadeOut();
      $("#"+input_is+"-instruct").fadeIn();
    }
  }).blur(function(){
    $(".instruct").fadeOut();
  });

  // hide realtor input
  $("#realtor-wrap").hide();
  // toggle realtor input
  $("#realtor-yes").click(function() {
    if( !$(this).hasClass("revealed") ){
      $("#realtor-wrap").slideDown("slow");
      $(this).addClass("revealed");
    }
  });
  $("#realtor-no").click(function() {
    $("#realtor-wrap").slideUp("slow");
    $("#realtor-yes").removeClass("revealed");
  });

  // Contact Form Validation
  $('#contact-form').RSV({
    displayType: "display-html",
    errorFieldClass: "f-error",
    errorTargetElementId: "contact-error",
    rules: [
    "required,name,Please provide your <b>first name</b>.",
    "required,lname,Please provide your <b>last name</b>.",
    "required,email,Please provide your <b>e-mail address</b>.",
    "valid_email,email,Please enter a valid <b>e-mail address</b>.",
    "required,street1,Please provide your <b>street address</b>.",
    "required,city,Please provide your <b>city</b>.",
    "required,state,Please provide your <b>state</b>.",
    "required,postalcode,Please provide your <b>zip code</b>.",
    "required,phone1,Please provide your <b>phone number</b>.",
    "if:realtor-choice=yes,required,realtor,Please provide a <b>Realtor</b>"
    ]
  });

  // Customer Service Request Form Validation
  $('#customer-service-request-form').RSV({
    displayType: "display-html",
    errorFieldClass: "f-error",
    errorTargetElementId: "contact-error",
    rules: [
    "required,name,Please provide your <b>first name</b>.",
    "required,lname,Please provide your <b>last name</b>.",
    "required,unit,Please provide your <b>unit number</b>.",
    "required,phone1,Please provide your <b>phone number</b>."
    ]
  });

  // Friendo Form Validation
  $('#friendo-form').RSV({
    displayType: "display-html",
    errorFieldClass: "f-error",
    errorTargetElementId: "friendo-error",
    rules: [
    "required,femail,Please provide your friend's <b>e-mail address</b>.",
    "required,name,Please provide your <b>name</b>.",
    "valid_email,femail,Please enter a valid <b>e-mail address</b>.",
    "required,email,Please provide your <b>e-mail address</b>.",
    "valid_email,email,Please enter a valid <b>e-mail address</b>."
    ]
  });



  /***** BEGIN Mortgage Calculator */

  $('#mcRate').val('5'); // default interest rate
  homePrice = $("#mcPriceClean").val(); // Unit Cost ($)
  var defaultDown = formatCurrency(homePrice * '.035');
  $('#mcDown').val(defaultDown); // default down payment amt - based on 3.5 percent of home total
  if(homePrice) getPayment();

  $('#mcPrice').keyup(function() {
    return false;
  })

  $("#mcTerm, #mcDown, #mcRate").keyup(function(){
    getPayment();
  })

  $("#mortgageCalc").submit(function(){
    getPayment();
    return false;
  });

  /***** END Mortgage Calculator */



  /***** BEGIN Unit Header IMGs */

/*
  $("div.magnify-img a, #unit-slideshow a.magnify-lrg").fancybox();

  $('#header-imgs li a').click(function() {
    var rel = $(this).attr('rel');
    var txt = $(this).text();
    var img_path_resized = '/content/unit/resized/';
    var img_path_large = '/content/unit/';
    $('#unit-slideshow div.magnify-img').fadeOut(250, function() {
      $('#unit-slideshow div.magnify-img img').attr('src', img_path_resized + rel);
      $('#unit-slideshow div.magnify-img a').attr('href', img_path_large + rel);
      $('#unit-slideshow a.magnify-lrg').attr('href', img_path_large + rel);
      $('#unit-slideshow div.magnify-img a').attr('title', txt);
      $('#unit-slideshow a.magnify-lrg').attr('title', txt);
      setTimeout("$('#unit-slideshow div.magnify-img').fadeIn(250);", 200);
    });
      return false;
  });
*/

  // Changes made on 10/21/2010 by Tom Harlin
  // To customize the plugin please refer to this website, http://fancybox.net/. There are alot of examples and options to choose from.
  $("a[class=magnify-lrg], div[class=magnify-img] a").fancybox({'overlayOpacity':'.95', 'overlayColor': '#00320E'});
  $("a[rel=group], a[rel=group2], a[rel=group3]").fancybox({'overlayOpacity':'.95', 'overlayColor': '#00320E'});
  $(".site-plan a").fancybox();
  $(".fframe").fancybox({
    'width'       : '85%',
    'height'      : '85%',
    'type'        : 'iframe',
    'overlayOpacity': '.95',
    'overlayColor': '#00320E'
  });

  /***** END Unit Header IMGs */


});

// add any other non-jquery js here, including swf object

function generateOtherUnitsList() {
  $('#results-list-secondary').fadeOut(300, function() {
    var h = $('#results-list-primary').html();
    $('#results-list-secondary').html(h);
    $('#results-list-secondary tr.no-results').remove();
    $('#results-list-secondary tr.result').each(function() {
      $(this).removeClass('alt');
      if($(this).hasClass('hide')) {
        $(this).removeClass('hide');
      } else {
        $(this).addClass('hide');
      }
    });
    setAltRows('#results-list-secondary tr.result');
    $('#results-list-secondary').fadeIn(300);
  });
}

function getPayment() {
  var calculatedPrice,calculatedPriceFormatted,term,interestRate,downPayment,downPaymentPercentage;

  homePrice = $("#mcPriceClean").val(); // Unit Cost ($)
  term = parseInt($("#mcTerm").val()) * 12; // Term in Years (integer)
  interestRate = parseFloat($("#mcRate").val())/1200; // Interest Rate (%)
  downPayment = $("#mcDown").val(); // Down Payment ($)
  downPayment = downPayment.replace(/,/, '');
  downPayment = parseInt(downPayment.replace(/\$/, ''));
  if(downPayment != null && downPayment > 0) {
    downPaymentPercentage = 1 - parseFloat(downPayment)/100;
    homePrice = homePrice * (1 - (parseFloat(downPayment) / homePrice));
  }
  calculatedPrice = (homePrice*(interestRate*Math.pow(1+interestRate,term)))/(Math.pow(1+interestRate,term)-1);
  if(!isNaN(calculatedPrice)) {
    calculatedPriceFormatted = formatCurrency(calculatedPrice.toFixed(2));
    $("#mcPayment").text(calculatedPriceFormatted);
    $('#total-payment').show();
  } else {
    $('#total-payment').hide();
    $("#mcPayment").text('');
  }
}

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function communityQuickView(url_title,ID) {
  if(url_title != '') {
    communityID = url_title;
    $('ul#units li').hide(); // hide all units
    $('ul#units li').each(function() { // iterate through and only show the ones with the right class
      if($(this).hasClass(communityID)) {
        $(this).show();
      }
    });
    $('#map-tabs li.unit a').click(); // stimulate the unit tab click event
  }

  if(ID != '') {
    $('#find-sort-by-community option').each(function() {
      $(this).attr('selected','');
      if(ID == $(this).val()) $(this).attr('selected','selected');
    });
    $('#find-sort-by-community option').change();
  }
}

// Find Your Home : set the alternate rows for
function setAltRows(target) {
  var counter = 0;
  $(target).removeClass('alt');
  $(target).each(function() {
    ++counter
    if(counter == 2) {
      $(this).addClass('alt');
      counter = 0;
    }
  });
}

function performUnitSort() {
  findSortPriceSplit = findSortPrice.split('|');
  var numFound = 0;

  $('#results-list-primary').fadeOut(300,function() {
    $('#results-list-primary tr.no-results').addClass('hide');
    $('#results-list-primary tr.result').each(function() {
      // first show them all; we'll hide if they don't meet a criterion
      $(this).removeClass('hide');

      // sort by community
      if(findSortCommunity && findSortCommunity != 'all') {
        if(findSortCommunity == null) {
          $('#results-list-primary tr.no-results').removeClass('hide');
        } else {
          if(findSortCommunity.match('|')) { // must be a pipe-delimited list
            var splits = findSortCommunity.split('|');
            for(var i = 0; i < splits.length; i++) {
              if(parseInt(splits[i])) {
                if(!$(this).hasClass('com-'+splits[i])) $(this).addClass('hide');
              }
            }
          } else { // must just be one ID
            if(!$(this).hasClass('com-'+findSortCommunity)) $(this).addClass('hide');
          }
        }
      }

      // set the ones who have a price in the selected range to visible
      if(findSortPriceSplit[0] != null && findSortPrice != 'all') {
        var price = $(this).attr('rel');
        if((price*1) < (findSortPriceSplit[0]*1) || (price*1) > (findSortPriceSplit[1]*1)) $(this).addClass('hide');
      }
    });

    // Now loop through and see how many were shown
    $('#results-list-primary tr.result').each(function() {
      if(!$(this).hasClass('hide')) numFound++;
    });
    if(numFound == 0) $('#results-list-primary tr.no-results').removeClass('hide');

    setAltRows('#results-list-primary tr.result');
    $('#results-list-primary').fadeIn(300);
    generateOtherUnitsList();
  });

}

jQuery.preloadImages = function() {
  for(var i = 0; i<arguments.length; i++) {
    jQuery("<img>").attr("src", arguments[i]);
  }
}


