/****************************************************************************/
/******************** HIGH LEVEL (onload type) calls *******************************/
/****************************************************************************/


// enable link rewriting for analytics
jQuery(document).ready(function() {
    setAnalyticsLinks();
});


// rotate mission partner images
jQuery(document).ready(function($) {
    rotatePartnerImages();
})


/****************************************************************************/
/******************** ROTATING functions *******************************/
/****************************************************************************/

function rotatePartnerImages() {
    var partner_logos = $("div#promos div#partners img");
    //alert (partner_logos.length);

    var counter = 0;
    var last_partner = $(partner_logos.get(counter++)).fadeIn("slow");

    function next_partner() {
        if (counter >= partner_logos.length) { counter = 0; }
        last_partner.fadeOut("slow");
        last_partner = $(partner_logos.get(counter++)).fadeIn("slow");
    }

    setInterval(next_partner, 5000);
}




/****************************************************************************/
/******************** ANALYTICS functions *******************************/
/****************************************************************************/



// high level calls to linking routines
function setAnalyticsLinks() {
    // add events for other external links not already handled
    rewriteAdditionalExternalLinks();
}


// rewrite other external links that aren't being tracked
function rewriteAdditionalExternalLinks() {
    // doesn't work in local environment - would be blank so we fake it
    var localSite = window.location.host.toLowerCase();
    if (localSite == "") {
        localSite = "localSite.com";
    }

    $("body a[href^='http:']").not("[href*='" + localSite + "']").each(function(i, ele) {

        // add page tracker to links without pagetracker already
        var onclickValue = $(ele).attr('onclick');
        if (onclickValue == undefined) {
            onclickValue = '';
        }
        else {
            // would be a  Function, not string
            onclickValue = onclickValue.toString();
        }
        // only add if onclick doesn't already have a pagetracker
        if (!(matchCiSub(onclickValue, "pageTracker"))) {
            //alert($(ele).attr('href') + "|" + $(ele).attr('onclick'));
            //$(ele).attr('onclick', 'alert("external link");'); TEST
            //var event = "pageTracker._trackPageview('/fake/' + this.href);";
            //$(ele).attr('onClick', event);
            $(ele).bind("click", function(e) { pageTracker._trackPageview('/fake/' + this.href); })
        }
    });
}


// case insensitive substring match
function matchCiSub(haystack, needle) {
    var value = "";
    if (haystack != undefined) {
        value = (haystack.toLowerCase().indexOf(needle.toLowerCase()) != -1);
    }
    return value;
}


function gainfo(category, action, label, href) {
    //alert(category + "|" + action + "|" + label + "|" + href);

    // record "event"
    pageTracker._trackEvent(category, action, label);

    // actually follows link with rewritten url
    if (href != undefined && href != "undefined") {
        pageTracker._link(href);
    }
}

/**
* jQuery.labelify - Display in-textbox hints
* Stuart Langridge, http://www.kryogenix.org/
* http://www.kryogenix.org/code/browser/labelify/
* Released into the public domain
* Date: 25th June 2008
* @author Stuart Langridge
* @version 1.3
*
*
* Basic calling syntax: $("input").labelify();
* Defaults to taking the in-field label from the field's title attribute
*
* You can also pass an options object with the following keys:
*   text
*     "title" to get the in-field label from the field's title attribute 
*      (this is the default)
*     "label" to get the in-field label from the inner text of the field's label
*      (note that the label must be attached to the field with for="fieldid")
*     a function which takes one parameter, the input field, and returns
*      whatever text it likes
*
*   labelledClass
*     a class that will be applied to the input field when it contains the
*      label and removed when it contains user input. Defaults to blank.
*  
*/
jQuery.fn.labelify = function(settings) {
    settings = jQuery.extend({
        text: "title",
        labelledClass: ""
    }, settings);
    var lookups = {
        title: function(input) {
            return $(input).attr("title");
        },
        label: function(input) {
            return $("label[for=" + input.id + "]").text();
        }
    };
    var lookup;
    var jQuery_labellified_elements = $(this);
    return $(this).each(function() {
        if (typeof settings.text === "string") {
            lookup = lookups[settings.text]; // what if not there?
        } else {
            lookup = settings.text; // what if not a fn?
        };
        // bail if lookup isn't a function or if it returns undefined
        if (typeof lookup !== "function") { return; }
        var lookupval = lookup(this);
        if (!lookupval) { return; }

        // need to strip newlines because the browser strips them
        // if you set textbox.value to a string containing them    
        $(this).data("label", lookup(this).replace(/\n/g, ''));
        $(this).focus(function() {
            if (this.value === $(this).data("label")) {
                this.value = this.defaultValue;
                $(this).removeClass(settings.labelledClass);
            }
        }).blur(function() {
            if (this.value === this.defaultValue) {
                this.value = $(this).data("label");
                $(this).addClass(settings.labelledClass);
            }
        });

        var removeValuesOnExit = function() {
            jQuery_labellified_elements.each(function() {
                if (this.value === $(this).data("label")) {
                    this.value = this.defaultValue;
                    $(this).removeClass(settings.labelledClass);
                }
            })
        };

        $(this).parents("form").submit(removeValuesOnExit);
        $(window).unload(removeValuesOnExit);

        if (this.value !== this.defaultValue) {
            // user already started typing; don't overwrite their work!
            return;
        }
        // actually set the value
        this.value = $(this).data("label");
        $(this).addClass(settings.labelledClass);

    });
};

