/* Support bits
------------------------------------------------------------------ */
(function ($) {
    $.fn.toggleText = function(a, b) {
    	return this.each(function() {
    		$(this).text($(this).text() == a ? b : a);
    	});
    };
})(jQuery);


// Plugin that is jQuery.param() in reverse. It takes a querystring and
// returns an object.
(function ($) {
    $.extend({
        querystringToObject: function (str) {
            // Handle the following cases:
            //      '/foo/?bar=baz'
            //      '?bar=baz'
            //      'bar=baz'
            // Is there a `?` — if so, just grab what’s after it.
            var qsStart = str.indexOf('?');
            if (qsStart != -1) { str = str.substr(qsStart + 1); }
            // Now that we have a clean querystring, decode it.
            str = decodeURIComponent(str);
            var obj = {}; // For storing objectified str.
            var arr = str.split('&');

            for (var i = 0; i < arr.length; i++) {

                // Down to a single key/value.
                var bits = arr[i].split('=');
                var k = bits[0];
                var v = bits[1];

                // Handle RubyOnRails/PHP -style querystrings by removing any
                // `[]` that end a key.
                if (k.substr(-2, 2) === '[]') {
                    k = k.substr(0, k.length - 2);
                }

                if (!obj[k]) {
                    // This key is unique; just add it to the object.
                    obj[k] = v;
                } else {
                    // This key is not unique.
                    if (obj[k] instanceof Array) {
                        // This is at least the third instance of this key.
                        obj[k].push(v);
                    } else {
                        // This is the second instance of this key.
                        obj[k] = Array(obj[k], v);
                    }
                }
            } // end for loop

            // The querystring is now fully objectified.
            return obj;

        } // end function
    }); // end extend
})(jQuery);


// Handy plugin for moving an element from one place to another.
(function ($) {
  $.fn.moveElement = function(newParentSelector) {

    // Set the default selector if one was not passed.
    if (!newParentSelector) {
      var newParentSelector = '#page #body #primary .block .rail';
    }
    var newParent = $(newParentSelector);

    // Verify that the new parent exists before we go detaching the element.
    // Would rather fail safely and have the element still accessible than
    // have it detached only to sit in DOM purgatory, unable to be reattached.
    if (newParent.length > 0) {
      // Iterate and return each element selected for hoisting.
      return $(this).each(function () {
        $(this).detach();
        $(this).prependTo(newParent);
      }); // end each iteration.
    }
  }; // end moveElement function.
})(jQuery);


// Plug-in for making our send-to-latest-news links ajaxy.
(function ($) {
  $.fn.makeLatestNews = function () {

    // Iterate and return each element selected for make-latest-news linking.
    return this.each(function () {
        $(this).click(function (e) {
            e.preventDefault();

            var link = $(this);
            var title = link.attr('title');
            var url = link.attr('href');
            var path = url.split('?')[0];
            var qstring = $.querystringToObject(url.split('?')[1]);
            var is_latest_news = qstring['unfeature'] == "True" ? true : false;

            // Make the link non-functional while we’re working.
            link.attr('href', '');
            link.attr('title', 'Working …');
            link.text((is_latest_news ? 'Removing from' : 'Sending to') + ' latest news …');


            $.ajax({
               url: url,
               context: link,
               success: function () {
                    qstring['unfeature'] = qstring['unfeature'] == "True" ? "False" : "True";
                    $(this).text((is_latest_news ? 'Send to' : 'Remove from') + ' latest news')
                    $(this).attr('title', ''); // TODO: when you have time, add real feedback.
                    $(this).attr('href', path + '?' + $.param(qstring));
               },
               error: function () {
                   alert('There has been an error. The page will now reload.');
                   location.reload();
               }
            }); // end ajax
        }); // end click handler
    }); // end each iteration.
  }; // end makeLatestNews function.
})(jQuery);


// Google Analytics event tracker helper.
(function($) {
  $.fn.trackEvent = function(options) {

    // Settings
    var settings = $.extend({
      tracker: 'eventTracker',
      eventType: 'click',
      category: 'New features',
      action: 'click',
      label: undefined, // Must be a string or a function that returns a string.
      value: undefined // Must be an integer or a function that returns an integer.
                       // A function will be passed the event object.
    }, options);

    // Iterate and return each element selected for tracking.
    return $(this).each(function() {
      $(this).bind(settings.eventType, function(e) {

        if (typeof settings.label == 'function') {
          // If it is a function, call it.
          settings.label = settings.label(e);
          // Then verify that it returns a string. If not, coerce it so as not
          // to break Google Analytics.
          if (typeof settings.lagel != 'string') {
            settings.label = String(settings.label);
            // Should console.warn here that label function did not return a string.
          }
        }

        if (typeof settings.value == 'function') {
          // If it is a function, call it.
          settings.value = settings.value(e);
          // Then verify that it returns an integer. If not, set it to undefined
          // so as not to break Google Analytics.
          if (isNaN(settings.value)) {
            settings.value = undefined;
            // Should console.warn here that value function did not return an number.
          }
        }

        if (wol.debug == true) {
          console.log('Event tracked:');
          console.log(settings);
        } else {
          _gaq.push([settings.tracker + '._trackEvent', settings.category, settings.action, settings.label, settings.value]);
        }

      }); // end event bind/handler.
    }); // end each iteration.
  }; // end trackEvent function.
})(jQuery);


// Here we call/do stuff that needs done across all of our properties.
$(function () {
    // Autofocus for browsers that don’t yet support it.
    // $("[autofocus]").autofocus();

    // Magicify our make-latest-news buttons.
    // $('a.make_latest_news').makeLatestNews();

    // Set up recaptcha. (Will noop if not needed.)
    $('form[action^="/mailform/"]').addRecaptcha();
});

