﻿
$(function () {

    //=== fix ever 3 elements...
    $(".sub-hover-area").find("section:nth-child(3n+1)").each(function(){
        $(this).addClass("first");
    });                       


    //=== add scroll up functionality
    $('#backToTop').click(function () {
        $('html, body').animate({ scrollTop: '0px' }, 200);
        return false;
    });

  // If this bugs out randomly in IE6, it's because gzip is turned on for the json response.
  // Suggestive search for any charity search fields.
  if ($(".charity-suggest").length != 0) {
    $(".charity-suggest").autoSuggest({
      script: "/charity/search/suggest?limit=20&",
      maxentries: 4,
      imagePattern: "$1",
      urlPattern: "$1"
    });
  }

    initErasableInputs();
    initValidateNonBlankInputs();
    initAutoExpanders();

    $("body").tooltip({
        attachSelector: ".input.validation-error:not(.validation-disabled)",
        eventSubSelector: "input",
        beginEvent: "focus keydown",
        endEvent: "blur",
        cssClass: "error"
    });


    $("body").tooltip({
        attachSelector: ".slidingdoor-button",
        eventSubSelector: "input",
        beginEvent: "click",
        endEvent: "blur",
        cssClass: "error"
    });

});

// ============  Clearing default text input field  ============  
// === Rob says we should refactor this in the future.  Does anyone know a good way to use toggle these two functions under different events? - KCV

var initErasableInputs = function () {

    // on focus - grab and then remove the current value
    $(".erase-default").live('focus', function () {
        var originalValue = $(this).val();
        $(this).val("");
        $(this).removeClass("erase-default");
    // on leave focus (blur) - replace it with the original msg if the user has not edited it
        $(this).bind('blur', function () {
            // had to create a var to trim the value first then ask if it was equal to nothing...
            var originalValueTrimmed = $.trim($(this).val());              
            if (originalValueTrimmed  == "") {
                $(this).val(originalValue);
                $(this).addClass("erase-default");
            }
        });
    });
};

var initAutoExpanders = function (domElement, preExpanderHeight) {
    // coming up next iteration I'm going to pull out the show more from the html!  It doesn't make sense for the mark up to say show more... 
    if (!domElement) { var domElement = document; }
    if (!preExpanderHeight) { var preExpanderHeight = "50px"; }
    $(".auto-expand", $(domElement)).each(function () {
        var classNames = $(this).get(0).className.split(" ");
        var expandClass;
        $.each(classNames, function () {
            if (this.substr(0, 7) == "expand-") {
                expandClass = this.substr(7);
            }
        });
        var expandingElement = $("." + expandClass, $(this).parent());
        if (expandingElement.text().length > 200) {
            expandingElement.css("height", preExpanderHeight).css("overflow", "hidden");
        }
        if (parseInt(expandingElement.css("height")) + 5 < expandingElement.get(0).scrollHeight) {
            // Expander is useful here.
            $(this).css("display", "block");
            $(this).click(function () {
                expandingElement.animate({
                    height: expandingElement.get(0).scrollHeight + "px"
                });
                $(this).slideUp();
            });
        } else {
            $(this).hide();
        }
    });
};


// ================== Form input value :Validation
var initValidateNonBlankInputs = function () {
  var validInputSelector = ".input.validates-non-blank:not(.validation-disabled)";

  $("form").bind("submit", function () {
    if (checkForm(this)) {

      $(".input.validation-error:not(.validation-disabled):first", this).trigger("poke");
      return false;
    }
  });

  var checkForm = function (formElement) {
    var hasError = false;
    $.each($(validInputSelector, formElement), function () {
      var inputElement = $("input", this);
      if ($.trim(inputElement.context.value) == "") {
        $(this).addClass("validation-error");
        $(this).attr("title", "This field can't be left blank!");
        hasError = true;
      } else {
        $(this).removeClass("validation-error");
        $(this).attr("title", "");
      }
    });
    return hasError;
  };
};



(function ($) {

  $.fn.zebraStripe = function() {
    $(this).filter(":visible").each(function(idx) {
      if(idx % 2 == 0) {
        $(this).removeClass("alternate");
      } else {
        $(this).addClass("alternate");
      }
    });
  };

})(jQuery);


/* Tooltip jQuery plugin, by rob. */
(function($) {
  $.fn.tooltip = function(options) {

    /* Use mouseenter and mouseleave at your peril.
       It turns out jQuery sucks at dealing with these + event delegation/.live.
       Sucks. */
    var config = $.extend({
      attachSelector: "*",
      eventSubSelector: "",
      beginEvent: "focus",
      endEvent: "blur",
      cssClass: "regular"
    }, options);
    
    var self = this;
    var timer;

    $(document).ready(function() {
      
      // Binding to all children of the initial selector
      $("*", self).live(config.beginEvent + " poke", function(e) { 

        var eventElement = $(this);
        var attachElement = $(this).closest(config.attachSelector);

        if(attachElement.attr("title")) {
          attachElement.data("caption", attachElement.attr("title"));
          attachElement.attr("title", "");
        }

        // wtf jQuery? $(this).not("[title]")  !==   !$(this).is("[title"])
        if(!attachElement.data("caption") || !attachElement.is(config.attachSelector)) {
          return;
        }

        clearTimeout(timer);

        var tipElement = $("<div class='tooltip " + config.cssClass + "'><span class='tooltip-inner'>" + attachElement.data("caption") + "</span></div>");
        var x = attachElement.offset().left;
        var y = attachElement.offset().top + attachElement.outerHeight();

        // Make sure the tooltips go away!
        self.destroyAllTooltips(attachElement);
        timer = setTimeout(function() { self.destroyAllTooltips(); }, 3000);

        eventElement.bind(config.endEvent, function(e) {
          self.destroyAllTooltips();
        });

        tipElement.css("left", x);
        tipElement.css("top", y);
        tipElement.fadeIn();
        tipElement.appendTo($("body"));

      });

    });

    this.destroyAllTooltips = function() {
      $(".tooltip").stop().fadeOut();
    };

    return $(this);
  };
})(jQuery);


/*
    equalHeight jQuery plugin - Added by Sam 2011-01-13
    Sets the height of all elements selected to the height of the highest element selected.
    
    Options:
             minHeight - the minimum height for all the elements after this has run
                default: -1 (means no minimum height)
             maxHeight - the maximum height for all the elements after this has run
                default: -1 (means no maximum height)
    
*/
(function ($) {
    $.fn.equalHeight = function (options) {
        var highestHeight, settings;

        settings = {
            minHeight: -1,
            maxHeight: -1
        };
        
        if (options) { $.extend(settings, options); }

        highestHeight = settings.minHeight;

        $.each(this, function (i, element) {
            highestHeight = Math.max(highestHeight, $(element).height());
        });

        highestHeight =
            settings.maxHeight === -1 || highestHeight <= settings.maxHeight
            ? highestHeight
            : settings.maxHeight;

        this.height(highestHeight);

        return this;
    };
}(jQuery));

