﻿/* gigmasters.js  

SECTIONS
    
*1.0...GENERAL FUNCTIONS
1.1.....trim functions
1.2.....object valid?
1.3.....check or uncheck all
1.4.....non-AJAX browser popup
1.5.....target external links
1.6.....format currency

*2.0...AJAX
2.1.....unobtrusive JavaScript links
2.1.1.....window.onload()
2.1.2.....prepareLinks()
2.2.....AJAX XMLHttpRequest
2.3.....display AJAX content
2.3.1.....getContent()
2.3.2.....parseResponse()

*3.0...THIRD-PARTY SCRIPTS
3.1.....jquery.hoverIntent.js
3.2.....jquery.bgiframe.js     
3.3.....jquery.cluetip.js
3.4.....jquery.cookie.js
     
*4.0...TOOLTIPS USING JQUERY AND CLUETIP
4.1.....tooltip (was jquery-tooltip.js)
4.2.....tooltip fix for IE 6 (uses jQuery plugin "bgiframe")
4.3.....Autocomplete
     
*5.0...CUSTOM JAVASCRIPT
5.1.....Rising Star Awards
5.2.....Press Center
5.3.....Twitter feed
5.4.....Password length
5.5.....Login box (Contact Form)



***********************************************************/

/* SECTION 1.0 GENERAL FUNCTIONS */

// *1.1 trim functions 
function RTrim(strMyString) {
    return (strMyString.replace(/^\s*/, ""));
}

function LTrim(strMyString) {
    return (strMyString.replace(/\s*$/, ""));
}

function Trim(strMyString) {
    return (RTrim(LTrim(strMyString)));
}


// *1.2 object valid?
function isValidObject(objToTest) {
    //determine if object is valid (i.e. undefined or null) (aed 4/26/07)
    if (objToTest == null || objToTest == undefined) {
        return false;
    }
    return true;
}


// *1.3 check or uncheck all
function checkall() {
    for (counter = 0; counter < document.YourLeads.gigids.length; counter++) {
        document.YourLeads.gigids[counter].checked = true;
    }
}

function uncheckall() {
    for (counter = 0; counter < document.YourLeads.gigids.length; counter++) {
        document.YourLeads.gigids[counter].checked = false;
    }
}



// *1.4 non-AJAX browser popup
function popupBrowser(page, width, height) {
    popBox = window.open(page, 'page', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,width=' + width + ',height=' + height);
    popBox.focus()
}



// *1.5 target external links
$(function() {
    $("a[rel=external]").attr("target", "_blank");
});



// *1.6 format currency
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;

    return (((sign) ? '' : '-') + num + '.' + cents);
}



/* SECTION 2.0 AJAX */

// *2.1 create unobtrusive javascript links

// *2.1.1 
window.onload = prepareLinks;

// *2.1.2 
function prepareLinks() {
    if (!document.getElementById || !document.getElementsByTagName) {
        return;
    }
    if (!document.getElementById("trigger")) {     // div id: "trigger"
        return;
    }
    var list = document.getElementById("trigger"); // div id: "trigger"
    var links = list.getElementsByTagName("a");    // tag name: a ("trigger" div only)
    for (var i = 0; i < links.length; i++) {
        links[i].onclick = function() {
            getContent(this.href);
            return false;
        };
    }
}


// *2.2 AJAX XMLHttpRequest - cross-browser compatible
function getHTTPObject() {
    var xhr = false;
    if (window.XMLHttpRequest) {        // Object detection: modern browser
        xhr = new XMLHttpRequest();       // If true then create new instance
    } else if (window.ActiveXObject) {  // Detect ActiveX for older IE versions
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP"); // ActiveX detected so try to create new XMLHTTP object for IE 6
        } catch (e) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP"); // Must be IE 5 so try to create new XMLHTTP object for it
            } catch (e) {                                    // Failed - must be Mac IE 5, which is not supported so catch error and return false
                xhr = false;
            }
        }
    }
    return xhr;
}


// *2.3 Display AJAX content

// *2.3.1 
function getContent(contentFile) {
    var request = getHTTPObject(); // Create an instance of the XMLHttpRequest/XMLHTTP object if possible
    if (request) {                 // If successful, initiate AJAX request
        request.onreadystatechange = function() { // Wire to onreadystatechange event handler and pass the current instance of XMLHttpRequest 
            parseResponse(request);
        };
        request.open("GET", contentFile, true); // Browser request to server. Parameters: request method (get, post), file path or URL, asynchronous value (true/false)
        request.send(null);                 // Initiates request (use NULL for GET)
    }
}

// *2.3.2
function parseResponse(request) {
    if (request.readyState == 4) { // Current state of AJAX request. 4 means that server has finished sending the response
        if (request.status == 200 || request.status == 304) {  // HTTP status code: successful response 
            var ajaxContent = document.getElementById("ajaxContent");  // div id: "ajaxContent"
            ajaxContent.innerHTML = request.responseText;
        }
    }
}


/* SECTION 3.0 THIRD-PARTY SCRIPTS */

// *3.1 jquery.hoverIntent.js

/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
*	interval: 50,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 100,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @return    The object (aka "this") that called hoverIntent, and the event object
* @author    Brian Cherne <brian@cherne.net>
*/
(function($) {
    $.fn.hoverIntent = function(f, g) {
        // default configuration options
        var cfg = {
            sensitivity: 7,
            interval: 100,
            timeout: 0
        };
        // override configuration options with user supplied object
        cfg = $.extend(cfg, g ? { over: f, out: g} : f);

        // instantiate variables
        // cX, cY = current X and Y position of mouse, updated by mousemove event
        // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
        var cX, cY, pX, pY;

        // A private function for getting mouse position
        var track = function(ev) {
            cX = ev.pageX;
            cY = ev.pageY;
        };

        // A private function for comparing current and previous mouse position
        var compare = function(ev, ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            // compare mouse positions to see if they've crossed the threshold
            if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
                $(ob).unbind("mousemove", track);
                // set hoverIntent state to true (so mouseOut can be called)
                ob.hoverIntent_s = 1;
                return cfg.over.apply(ob, [ev]);
            } else {
                // set previous coordinates for next time
                pX = cX; pY = cY;
                // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
                ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval);
            }
        };

        // A private function for delaying the mouseOut function
        var delay = function(ev, ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            ob.hoverIntent_s = 0;
            return cfg.out.apply(ob, [ev]);
        };

        // A private function for handling mouse 'hovering'
        var handleHover = function(e) {
            // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
            var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
            while (p && p != this) { try { p = p.parentNode; } catch (e) { p = this; } }
            if (p == this) { return false; }

            // copy objects to be passed into t (required for event object to be passed in IE)
            var ev = jQuery.extend({}, e);
            var ob = this;

            // cancel hoverIntent timer if it exists
            if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

            // else e.type == "onmouseover"
            if (e.type == "mouseover") {
                // set "previous" X and Y position based on initial entry point
                pX = ev.pageX; pY = ev.pageY;
                // update "current" X and Y position based on mousemove
                $(ob).bind("mousemove", track);
                // start polling interval (self-calling timeout) to compare mouse coordinates over time
                if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval); }

                // else e.type == "onmouseout"
            } else {
                // unbind expensive mousemove event
                $(ob).unbind("mousemove", track);
                // if hoverIntent state is true, then call the mouseOut function after the specified delay
                if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout(function() { delay(ev, ob); }, cfg.timeout); }
            }
        };

        // bind the function to the two event listeners
        return this.mouseover(handleHover).mouseout(handleHover);
    };
})(jQuery);


// *3.2 jquery.bgiframe.js
//
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* $LastChangedDate: 2007-07-21 18:44:59 -0500 (Sat, 21 Jul 2007) $
* $Rev: 2446 $
*
* Version 2.1.1
*/

(function($) {

    /**
    * The bgiframe is chainable and applies the iframe hack to get 
    * around zIndex issues in IE6. It will only apply itself in IE6 
    * and adds a class to the iframe called 'bgiframe'. The iframe
    * is appeneded as the first child of the matched element(s) 
    * with a tabIndex and zIndex of -1.
    * 
    * By default the plugin will take borders, sized with pixel units,
    * into account. If a different unit is used for the border's width,
    * then you will need to use the top and left settings as explained below.
    *
    * NOTICE: This plugin has been reported to cause perfromance problems
    * when used on elements that change properties (like width, height and
    * opacity) a lot in IE6. Most of these problems have been caused by 
    * the expressions used to calculate the elements width, height and 
    * borders. Some have reported it is due to the opacity filter. All 
    * these settings can be changed if needed as explained below.
    *
    * @example $('div').bgiframe();
    * @before <div><p>Paragraph</p></div>
    * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
    *
    * @param Map settings Optional settings to configure the iframe.
    * @option String|Number top The iframe must be offset to the top
    * 		by the width of the top border. This should be a negative 
    *      number representing the border-top-width. If a number is 
    * 		is used here, pixels will be assumed. Otherwise, be sure
    *		to specify a unit. An expression could also be used. 
    * 		By default the value is "auto" which will use an expression 
    * 		to get the border-top-width if it is in pixels.
    * @option String|Number left The iframe must be offset to the left
    * 		by the width of the left border. This should be a negative 
    *      number representing the border-left-width. If a number is 
    * 		is used here, pixels will be assumed. Otherwise, be sure
    *		to specify a unit. An expression could also be used. 
    * 		By default the value is "auto" which will use an expression 
    * 		to get the border-left-width if it is in pixels.
    * @option String|Number width This is the width of the iframe. If
    *		a number is used here, pixels will be assume. Otherwise, be sure
    * 		to specify a unit. An experssion could also be used.
    *		By default the value is "auto" which will use an experssion
    * 		to get the offsetWidth.
    * @option String|Number height This is the height of the iframe. If
    *		a number is used here, pixels will be assume. Otherwise, be sure
    * 		to specify a unit. An experssion could also be used.
    *		By default the value is "auto" which will use an experssion
    * 		to get the offsetHeight.
    * @option Boolean opacity This is a boolean representing whether or not
    * 		to use opacity. If set to true, the opacity of 0 is applied. If
    *		set to false, the opacity filter is not applied. Default: true.
    * @option String src This setting is provided so that one could change 
    *		the src of the iframe to whatever they need.
    *		Default: "javascript:false;"
    *
    * @name bgiframe
    * @type jQuery
    * @cat Plugins/bgiframe
    * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
    */
    $.fn.bgIframe = $.fn.bgiframe = function(s) {
        // This is only for IE6
        if ($.browser.msie && ($.browser.version.substring(0, 1) == 6)) {
            s = $.extend({
                top: 'auto', // auto == .currentStyle.borderTopWidth
                left: 'auto', // auto == .currentStyle.borderLeftWidth
                width: 'auto', // auto == offsetWidth
                height: 'auto', // auto == offsetHeight
                opacity: true,
                src: 'javascript:false;'
            }, s || {});
            var prop = function(n) { return n && n.constructor == Number ? n + 'px' : n; },
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="' + s.src + '"' +
		               'style="display:block;position:absolute;z-index:-1;' +
			               (s.opacity !== false ? 'filter:Alpha(Opacity=\'0\');' : '') +
					       'top:' + (s.top == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')' : prop(s.top)) + ';' +
					       'left:' + (s.left == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')' : prop(s.left)) + ';' +
					       'width:' + (s.width == 'auto' ? 'expression(this.parentNode.offsetWidth+\'px\')' : prop(s.width)) + ';' +
					       'height:' + (s.height == 'auto' ? 'expression(this.parentNode.offsetHeight+\'px\')' : prop(s.height)) + ';' +
					'"/>';
            return this.each(function() {
                if ($('> iframe.bgiframe', this).length == 0)
                    this.insertBefore(document.createElement(html), this.firstChild);
            });
        }
        return this;
    };

})(jQuery);


// *3.3 jquery.cluetip.js

/*
* jQuery clueTip plugin
* Version 1.0.4  (June 28, 2009)
* @requires jQuery v1.2.6+
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

; (function($) {
    $.cluetip = { version: '1.0.4' };
    var $cluetip, $cluetipInner, $cluetipOuter, $cluetipTitle, $cluetipArrows, $cluetipWait, $dropShadow, imgCount;
    $.fn.cluetip = function(js, options) {
        if (typeof js == 'object') {
            options = js;
            js = null;
        }
        if (js == 'destroy') {
            return this.unbind('.cluetip');
        }
        return this.each(function(index) {
            var link = this, $this = $(this);

            // support metadata plugin (v1.0 and 2.0)
            var opts = $.extend(true, {}, $.fn.cluetip.defaults, options || {}, $.metadata ? $this.metadata() : $.meta ? $this.data() : {});

            // start out with no contents (for ajax activation)
            var cluetipContents = false;
            var cluezIndex = +opts.cluezIndex;
            $this.data('thisInfo', { title: link.title, zIndex: cluezIndex });
            var isActive = false, closeOnDelay = 0;

            // create the cluetip divs
            if (!$('#cluetip').length) {
                $(['<div id="cluetip">',
          '<div id="cluetip-outer">',
            '<h3 id="cluetip-title"></h3>',
            '<div id="cluetip-inner"></div>',
          '</div>',
          '<div id="cluetip-extra"></div>',
          '<div id="cluetip-arrows" class="cluetip-arrows"></div>',
        '</div>'].join(''))
        [insertionType](insertionElement).hide();

                $cluetip = $('#cluetip').css({ position: 'absolute' });
                $cluetipOuter = $('#cluetip-outer').css({ position: 'relative', zIndex: cluezIndex });
                $cluetipInner = $('#cluetip-inner');
                $cluetipTitle = $('#cluetip-title');
                $cluetipArrows = $('#cluetip-arrows');
                $cluetipWait = $('<div id="cluetip-waitimage"></div>')
          .css({ position: 'absolute' }).insertBefore($cluetip).hide();
            }
            var dropShadowSteps = (opts.dropShadow) ? +opts.dropShadowSteps : 0;
            if (!$dropShadow) {
                $dropShadow = $([]);
                for (var i = 0; i < dropShadowSteps; i++) {
                    $dropShadow = $dropShadow.add($('<div></div>').css({ zIndex: cluezIndex - 1, opacity: .1, top: 1 + i, left: 1 + i }));
                };
                $dropShadow.css({ position: 'absolute', backgroundColor: '#000' })
        .prependTo($cluetip);
            }
            var tipAttribute = $this.attr(opts.attribute), ctClass = opts.cluetipClass;
            if (!tipAttribute && !opts.splitTitle && !js) return true;
            // if hideLocal is set to true, on DOM ready hide the local content that will be displayed in the clueTip
            if (opts.local && opts.localPrefix) { tipAttribute = opts.localPrefix + tipAttribute; }
            if (opts.local && opts.hideLocal) { $(tipAttribute + ':first').hide(); }
            var tOffset = parseInt(opts.topOffset, 10), lOffset = parseInt(opts.leftOffset, 10);
            // vertical measurement variables
            var tipHeight, wHeight,
          defHeight = isNaN(parseInt(opts.height, 10)) ? 'auto' : (/\D/g).test(opts.height) ? opts.height : opts.height + 'px';
            var sTop, linkTop, posY, tipY, mouseY, baseline;
            // horizontal measurement variables
            var tipInnerWidth = parseInt(opts.width, 10) || 275,
          tipWidth = tipInnerWidth + (parseInt($cluetip.css('paddingLeft'), 10) || 0) + (parseInt($cluetip.css('paddingRight'), 10) || 0) + dropShadowSteps,
          linkWidth = this.offsetWidth,
          linkLeft, posX, tipX, mouseX, winWidth;

            // parse the title
            var tipParts;
            var tipTitle = (opts.attribute != 'title') ? $this.attr(opts.titleAttribute) : '';
            if (opts.splitTitle) {
                if (tipTitle == undefined) { tipTitle = ''; }
                tipParts = tipTitle.split(opts.splitTitle);
                tipTitle = tipParts.shift();
            }
            if (opts.escapeTitle) {
                tipTitle = tipTitle.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;');
            }

            var localContent;
            function returnFalse() { return false; }

            /***************************************      
            * ACTIVATION
            ****************************************/

            //activate clueTip
            var activate = function(event) {
                if (!opts.onActivate($this)) {
                    return false;
                }
                isActive = true;
                $cluetip.removeClass().css({ width: tipInnerWidth });
                if (tipAttribute == $this.attr('href')) {
                    $this.css('cursor', opts.cursor);
                }
                if (opts.hoverClass) {
                    $this.addClass(opts.hoverClass);
                }
                linkTop = posY = $this.offset().top;
                linkLeft = $this.offset().left;
                mouseX = event.pageX;
                mouseY = event.pageY;
                if (link.tagName.toLowerCase() != 'area') {
                    sTop = $(document).scrollTop();
                    winWidth = $(window).width();
                }
                // position clueTip horizontally
                if (opts.positionBy == 'fixed') {
                    posX = linkWidth + linkLeft + lOffset;
                    $cluetip.css({ left: posX });
                } else {
                    posX = (linkWidth > linkLeft && linkLeft > tipWidth)
          || linkLeft + linkWidth + tipWidth + lOffset > winWidth
          ? linkLeft - tipWidth - lOffset
          : linkWidth + linkLeft + lOffset;
                    if (link.tagName.toLowerCase() == 'area' || opts.positionBy == 'mouse' || linkWidth + tipWidth > winWidth) { // position by mouse
                        if (mouseX + 20 + tipWidth > winWidth) {
                            $cluetip.addClass(' cluetip-' + ctClass);
                            posX = (mouseX - tipWidth - lOffset) >= 0 ? mouseX - tipWidth - lOffset - parseInt($cluetip.css('marginLeft'), 10) + parseInt($cluetipInner.css('marginRight'), 10) : mouseX - (tipWidth / 2);
                        } else {
                            posX = mouseX + lOffset;
                        }
                    }
                    var pY = posX < 0 ? event.pageY + tOffset : event.pageY;
                    $cluetip.css({
                        left: (posX > 0 && opts.positionBy != 'bottomTop') ? posX : (mouseX + (tipWidth / 2) > winWidth) ? winWidth / 2 - tipWidth / 2 : Math.max(mouseX - (tipWidth / 2), 0),
                        zIndex: $this.data('thisInfo').zIndex
                    });
                    $cluetipArrows.css({ zIndex: $this.data('thisInfo').zIndex + 1 });
                }
                wHeight = $(window).height();

                /***************************************
                * load a string from cluetip method's first argument
                ***************************************/
                if (js) {
                    if (typeof js == 'function') {
                        js = js(link);
                    }
                    $cluetipInner.html(js);
                    cluetipShow(pY);
                }
                /***************************************
                * load the title attribute only (or user-selected attribute). 
                * clueTip title is the string before the first delimiter
                * subsequent delimiters place clueTip body text on separate lines
                ***************************************/

                else if (tipParts) {
                    var tpl = tipParts.length;
                    $cluetipInner.html(tipParts[0]);
                    if (tpl > 1) {
                        for (var i = 1; i < tpl; i++) {
                            $cluetipInner.append('<div class="split-body">' + tipParts[i] + '</div>');
                        }
                    }
                    cluetipShow(pY);
                }
                /***************************************
                * load external file via ajax          
                ***************************************/

                else if (!opts.local && tipAttribute.indexOf('#') != 0) {
                    if (/\.(jpe?g|tiff?|gif|png)$/i.test(tipAttribute)) {
                        $cluetipInner.html('<img src="' + tipAttribute + '" alt="' + tipTitle + '" />');
                        cluetipShow(pY);
                    } else if (cluetipContents && opts.ajaxCache) {
                        $cluetipInner.html(cluetipContents);
                        cluetipShow(pY);
                    } else {
                        var optionBeforeSend = opts.ajaxSettings.beforeSend,
              optionError = opts.ajaxSettings.error,
              optionSuccess = opts.ajaxSettings.success,
              optionComplete = opts.ajaxSettings.complete;
                        var ajaxSettings = {
                            cache: false, // force requested page not to be cached by browser
                            url: tipAttribute,
                            beforeSend: function(xhr) {
                                if (optionBeforeSend) { optionBeforeSend.call(link, xhr, $cluetip, $cluetipInner); }
                                $cluetipOuter.children().empty();
                                if (opts.waitImage) {
                                    $cluetipWait
                .css({ top: mouseY + 20, left: mouseX + 20, zIndex: $this.data('thisInfo').zIndex - 1 })
                .show();
                                }
                            },
                            error: function(xhr, textStatus) {
                                if (isActive) {
                                    if (optionError) {
                                        optionError.call(link, xhr, textStatus, $cluetip, $cluetipInner);
                                    } else {
                                        $cluetipInner.html('<i>sorry, the contents could not be loaded</i>');
                                    }
                                }
                            },
                            success: function(data, textStatus) {
                                cluetipContents = opts.ajaxProcess.call(link, data);
                                if (isActive) {
                                    if (optionSuccess) { optionSuccess.call(link, data, textStatus, $cluetip, $cluetipInner); }
                                    $cluetipInner.html(cluetipContents);
                                }
                            },
                            complete: function(xhr, textStatus) {
                                if (optionComplete) { optionComplete.call(link, xhr, textStatus, $cluetip, $cluetipInner); }
                                imgCount = $('#cluetip-inner img').length;
                                if (imgCount && !$.browser.opera) {
                                    $('#cluetip-inner img').bind('load error', function() {
                                        imgCount--;
                                        if (imgCount < 1) {
                                            $cluetipWait.hide();
                                            if (isActive) cluetipShow(pY);
                                        }
                                    });
                                } else {
                                    $cluetipWait.hide();
                                    if (isActive) { cluetipShow(pY); }
                                }
                            }
                        };
                        var ajaxMergedSettings = $.extend(true, {}, opts.ajaxSettings, ajaxSettings);

                        $.ajax(ajaxMergedSettings);
                    }

                    /***************************************
                    * load an element from the same page
                    ***************************************/
                } else if (opts.local) {

                    var $localContent = $(tipAttribute + (/#\S+$/.test(tipAttribute) ? '' : ':eq(' + index + ')')).clone(true).show();
                    $cluetipInner.html($localContent);
                    cluetipShow(pY);
                }
            };

            // get dimensions and options for cluetip and prepare it to be shown
            var cluetipShow = function(bpY) {
                $cluetip.addClass('cluetip-' + ctClass);
                if (opts.truncate) {
                    var $truncloaded = $cluetipInner.text().slice(0, opts.truncate) + '...';
                    $cluetipInner.html($truncloaded);
                }
                function doNothing() { }; //empty function
                tipTitle ? $cluetipTitle.show().html(tipTitle) : (opts.showTitle) ? $cluetipTitle.show().html('&nbsp;') : $cluetipTitle.hide();
                if (opts.sticky) {
                    var $closeLink = $('<div id="cluetip-close"><a href="#">' + opts.closeText + '</a></div>');
                    (opts.closePosition == 'bottom') ? $closeLink.appendTo($cluetipInner) : (opts.closePosition == 'title') ? $closeLink.prependTo($cluetipTitle) : $closeLink.prependTo($cluetipInner);
                    $closeLink.bind('click.cluetip', function() {
                        cluetipClose();
                        return false;
                    });
                    if (opts.mouseOutClose) {
                        $cluetip.bind('mouseleave.cluetip', function() {
                            cluetipClose();
                        });
                    } else {
                        $cluetip.unbind('mouseleave.cluetip');
                    }
                }
                // now that content is loaded, finish the positioning 
                var direction = '';
                $cluetipOuter.css({ zIndex: $this.data('thisInfo').zIndex, overflow: defHeight == 'auto' ? 'visible' : 'auto', height: defHeight });
                tipHeight = defHeight == 'auto' ? Math.max($cluetip.outerHeight(), $cluetip.height()) : parseInt(defHeight, 10);
                tipY = posY;
                baseline = sTop + wHeight;
                if (opts.positionBy == 'fixed') {
                    tipY = posY - opts.dropShadowSteps + tOffset;
                } else if ((posX < mouseX && Math.max(posX, 0) + tipWidth > mouseX) || opts.positionBy == 'bottomTop') {
                    if (posY + tipHeight + tOffset > baseline && mouseY - sTop > tipHeight + tOffset) {
                        tipY = mouseY - tipHeight - tOffset;
                        direction = 'top';
                    } else {
                        tipY = mouseY + tOffset;
                        direction = 'bottom';
                    }
                } else if (posY + tipHeight + tOffset > baseline) {
                    tipY = (tipHeight >= wHeight) ? sTop : baseline - tipHeight - tOffset;
                } else if ($this.css('display') == 'block' || link.tagName.toLowerCase() == 'area' || opts.positionBy == "mouse") {
                    tipY = bpY - tOffset;
                } else {
                    tipY = posY - opts.dropShadowSteps;
                }
                if (direction == '') {
                    posX < linkLeft ? direction = 'left' : direction = 'right';
                }
                $cluetip.css({ top: tipY + 'px' }).removeClass().addClass('clue-' + direction + '-' + ctClass).addClass(' cluetip-' + ctClass);
                if (opts.arrows) { // set up arrow positioning to align with element
                    var bgY = (posY - tipY - opts.dropShadowSteps);
                    $cluetipArrows.css({ top: (/(left|right)/.test(direction) && posX >= 0 && bgY > 0) ? bgY + 'px' : /(left|right)/.test(direction) ? 0 : '' }).show();
                } else {
                    $cluetipArrows.hide();
                }

                // (first hide, then) ***SHOW THE CLUETIP***
                $dropShadow.hide();
                $cluetip.hide()[opts.fx.open](opts.fx.open != 'show' && opts.fx.openSpeed);
                if (opts.dropShadow) { $dropShadow.css({ height: tipHeight, width: tipInnerWidth, zIndex: $this.data('thisInfo').zIndex - 1 }).show(); }
                if ($.fn.bgiframe) { $cluetip.bgiframe(); }
                // delayed close (not fully tested)
                if (opts.delayedClose > 0) {
                    closeOnDelay = setTimeout(cluetipClose, opts.delayedClose);
                }
                // trigger the optional onShow function
                opts.onShow.call(link, $cluetip, $cluetipInner);
            };

            /***************************************
            =INACTIVATION
            -------------------------------------- */
            var inactivate = function(event) {
                isActive = false;
                $cluetipWait.hide();
                if (!opts.sticky || (/click|toggle/).test(opts.activation)) {
                    cluetipClose();
                    clearTimeout(closeOnDelay);
                };
                if (opts.hoverClass) {
                    $this.removeClass(opts.hoverClass);
                }
            };
            // close cluetip and reset some things
            var cluetipClose = function() {
                $cluetipOuter
      .parent().hide().removeClass();
                opts.onHide.call(link, $cluetip, $cluetipInner);
                $this.removeClass('cluetip-clicked');
                if (tipTitle) {
                    $this.attr(opts.titleAttribute, tipTitle);
                }
                $this.css('cursor', '');
                if (opts.arrows) $cluetipArrows.css({ top: '' });
            };

            $(document).bind('hideCluetip', function(e) {
                cluetipClose();
            });
            /***************************************
            =BIND EVENTS
            -------------------------------------- */
            // activate by click
            if ((/click|toggle/).test(opts.activation)) {
                $this.bind('click.cluetip', function(event) {
                    if ($cluetip.is(':hidden') || !$this.is('.cluetip-clicked')) {
                        activate(event);
                        $('.cluetip-clicked').removeClass('cluetip-clicked');
                        $this.addClass('cluetip-clicked');
                    } else {
                        inactivate(event);
                    }
                    this.blur();
                    return false;
                });
                // activate by focus; inactivate by blur    
            } else if (opts.activation == 'focus') {
                $this.bind('focus.cluetip', function(event) {
                    activate(event);
                });
                $this.bind('blur.cluetip', function(event) {
                    inactivate(event);
                });
                // activate by hover
            } else {
                // clicking is returned false if clickThrough option is set to false
                $this[opts.clickThrough ? 'unbind' : 'bind']('click', returnFalse);
                //set up mouse tracking
                var mouseTracks = function(evt) {
                    if (opts.tracking == true) {
                        var trackX = posX - evt.pageX;
                        var trackY = tipY ? tipY - evt.pageY : posY - evt.pageY;
                        $this.bind('mousemove.cluetip', function(evt) {
                            $cluetip.css({ left: evt.pageX + trackX, top: evt.pageY + trackY });
                        });
                    }
                };
                if ($.fn.hoverIntent && opts.hoverIntent) {
                    $this.hoverIntent({
                        sensitivity: opts.hoverIntent.sensitivity,
                        interval: opts.hoverIntent.interval,
                        over: function(event) {
                            activate(event);
                            mouseTracks(event);
                        },
                        timeout: opts.hoverIntent.timeout,
                        out: function(event) { inactivate(event); $this.unbind('mousemove.cluetip'); }
                    });
                } else {
                    $this.bind('mouseenter.cluetip', function(event) {
                        activate(event);
                        mouseTracks(event);
                    })
          .bind('mouseleave.cluetip', function(event) {
              inactivate(event);
              $this.unbind('mousemove.cluetip');
          });
                }
                // remove default title tooltip on hover
                $this.bind('mouseenter.cluetip', function(event) {
                    $this.attr('title', '');
                })
        .bind('mouseleave.cluetip', function(event) {
            $this.attr('title', $this.data('thisInfo').title);
        });
            }
        });
    };

    /*
    * options for clueTip
    *
    * each one can be explicitly overridden by changing its value. 
    * for example: $.fn.cluetip.defaults.width = 200; 
    * would change the default width for all clueTips to 200. 
    *
    * each one can also be overridden by passing an options map to the cluetip method.
    * for example: $('a.example').cluetip({width: 200}); 
    * would change the default width to 200 for clueTips invoked by a link with class of "example"
    *
    */

    $.fn.cluetip.defaults = {  // set up default options
        width: 275,      // The width of the clueTip
        height: 'auto',   // The height of the clueTip
        cluezIndex: 97,       // Sets the z-index style property of the clueTip
        positionBy: 'auto',   // Sets the type of positioning: 'auto', 'mouse','bottomTop', 'fixed'
        topOffset: 15,       // Number of px to offset clueTip from top of invoking element
        leftOffset: 15,       // Number of px to offset clueTip from left of invoking element
        local: false,    // Whether to use content from the same page for the clueTip's body
        localPrefix: null,       // string to be prepended to the tip attribute if local is true
        hideLocal: true,     // If local option is set to true, this determines whether local content
        // to be shown in clueTip should be hidden at its original location
        attribute: 'rel',    // the attribute to be used for fetching the clueTip's body content
        titleAttribute: 'title',  // the attribute to be used for fetching the clueTip's title
        splitTitle: '',       // A character used to split the title attribute into the clueTip title and divs
        // within the clueTip body. more info below [6]
        escapeTitle: false,    // whether to html escape the title attribute
        showTitle: true,     // show title bar of the clueTip, even if title attribute not set
        cluetipClass: 'default', // class added to outermost clueTip div in the form of 'cluetip-' + clueTipClass.
        hoverClass: '',       // class applied to the invoking element onmouseover and removed onmouseout
        waitImage: true,     // whether to show a "loading" img, which is set in jquery.cluetip.css
        cursor: 'help',
        arrows: false,    // if true, displays arrow on appropriate side of clueTip
        dropShadow: true,     // set to false if you don't want the drop-shadow effect on the clueTip
        dropShadowSteps: 6,        // adjusts the size of the drop shadow
        sticky: false,    // keep visible until manually closed
        mouseOutClose: false,    // close when clueTip is moused out
        activation: 'hover',  // set to 'click' to force user to click to show clueTip
        // set to 'focus' to show on focus of a form element and hide on blur
        clickThrough: false,    // if true, and activation is not 'click', then clicking on link will take user to the link's href,
        // even if href and tipAttribute are equal
        tracking: false,    // if true, clueTip will track mouse movement (experimental)
        delayedClose: 0,        // close clueTip on a timed delay (experimental)
        closePosition: 'top',    // location of close text for sticky cluetips; can be 'top' or 'bottom' or 'title'
        closeText: 'Close',  // text (or HTML) to to be clicked to close sticky clueTips
        truncate: 0,        // number of characters to truncate clueTip's contents. if 0, no truncation occurs

        // effect and speed for opening clueTips
        fx: {
            open: 'show', // can be 'show' or 'slideDown' or 'fadeIn'
            openSpeed: ''
        },

        // settings for when hoverIntent plugin is used             
        hoverIntent: {
            sensitivity: 3,
            interval: 50,
            timeout: 0
        },

        // short-circuit function to run just before clueTip is shown. 
        onActivate: function(e) { return true; },

        // function to run just after clueTip is shown. 
        onShow: function(ct, ci) { },
        // function to run just after clueTip is hidden.
        onHide: function(ct, ci) { },
        // whether to cache results of ajax request to avoid unnecessary hits to server    
        ajaxCache: true,

        // process data retrieved via xhr before it's displayed
        ajaxProcess: function(data) {
            data = data.replace(/<(script|style|title)[^<]+<\/(script|style|title)>/gm, '').replace(/<(link|meta)[^>]+>/g, '');
            return data;
        },

        // can pass in standard $.ajax() parameters. Callback functions, such as beforeSend, 
        // will be queued first within the default callbacks. 
        // The only exception is error, which overrides the default
        ajaxSettings: {
            // error: function(ct, ci) { /* override default error callback */ }
            // beforeSend: function(ct, ci) { /* called first within default beforeSend callback }
            dataType: 'html'
        },
        debug: false
    };


    /*
    * Global defaults for clueTips. Apply to all calls to the clueTip plugin.
    *
    * @example $.cluetip.setup({
    *   insertionType: 'prependTo',
    *   insertionElement: '#container'
    * });
    * 
    * @property
    * @name $.cluetip.setup
    * @type Map
    * @cat Plugins/tooltip
    * @option String insertionType: Default is 'appendTo'. Determines the method to be used for inserting the clueTip into the DOM. Permitted values are 'appendTo', 'prependTo', 'insertBefore', and 'insertAfter'
    * @option String insertionElement: Default is 'body'. Determines which element in the DOM the plugin will reference when inserting the clueTip.
    *
    */

    var insertionType = 'appendTo', insertionElement = 'body';

    $.cluetip.setup = function(options) {
        if (options && options.insertionType && (options.insertionType).match(/appendTo|prependTo|insertBefore|insertAfter/)) {
            insertionType = options.insertionType;
        }
        if (options && options.insertionElement) {
            insertionElement = options.insertionElement;
        }
    };

})(jQuery);

// *3.4 jquery.cookie.js
// Cookie plugin
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/* SECTION 4.0 TOOLTIPS USING JQUERY AND CLUETIP */

// *4.1 tooltip 
// originally called jquery-tooltip.js
// works with jquery-x.x.x.min.js, jquery.cluetip.js, jquery.bgiframe.js, and jquery.hoverIntent.js
jQuery(document).ready(function() {
    // ClueTip using title attribute in <a> tag
    jQuery('a.title').cluetip({
        splitTitle: '|',
        clickThrough: true,
        arrows: true,
        showTitle: false
    });
    // ClueTip: jTip theme
    jQuery('a.jt').cluetip({
        cluezIndex: 3000,
        cluetipClass: 'jtip',
        arrows: true,
        dropShadow: true,
        sticky: false,
        mouseOutClose: true,
        showTitle: false,
        hoverIntent: {
            sensitivity: 1,
            interval: 500,
            timeout: 0
        }
    });

    //cluetip: popup theme
    $('a.popup').cluetip({
        cluetipClass: 'popup',
        sticky: true,
        waitImage: false,
        dropShadow: false,
        showTitle: false,
        activation: 'click',
        width: 730
    });

    // *4.2 tooltip fix for IE 6
    // bgiframe jQuery plugin solves the z-index issue that IE 6 has (where form elements appear over tooltip)
    jQuery('#cluetip').bgiframe();
});

//* 4.3 Autocomplete
(function($) { var reEscape = new RegExp("(\\" + ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\"].join("|\\") + ")", "g"); function fnFormatResult(value, data, currentValue) { var pattern = "(" + currentValue.replace(reEscape, "\\$1") + ")"; return value.replace(new RegExp(pattern, "gi"), "<strong>$1</strong>"); } function Autocomplete(el, options) { this.el = $(el); this.el.attr("autocomplete", "off"); this.suggestions = []; this.data = []; this.badQueries = []; this.selectedIndex = -1; this.currentValue = this.el.val(); this.intervalId = 0; this.cachedResponse = []; this.onChangeInterval = null; this.ignoreValueChange = false; this.serviceUrl = options.serviceUrl; this.isLocal = false; this.options = { autoSubmit: false, minChars: 1, maxHeight: 300, deferRequestBy: 0, width: 0, highlight: true, params: {}, fnFormatResult: fnFormatResult, delimiter: null, zIndex: 9999 }; this.initialize(); this.setOptions(options); } $.fn.autocomplete = function(options) { return new Autocomplete(this.get(0), options); }; Autocomplete.prototype = { killerFn: null, initialize: function() { var me, uid, autocompleteElId; me = this; uid = new Date().getTime(); autocompleteElId = "Autocomplete_" + uid; this.killerFn = function(e) { if ($(e.target).parents(".autocomplete").size() === 0) { me.killSuggestions(); me.disableKillerFn(); } }; if (!this.options.width) { this.options.width = this.el.width(); } this.mainContainerId = "AutocompleteContainter_" + uid; $('<div id="' + this.mainContainerId + '" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none; width:300px;"></div></div></div>').appendTo("body"); this.container = $("#" + autocompleteElId); this.fixPosition(); if (window.opera) { this.el.keypress(function(e) { me.onKeyPress(e); }); } else { this.el.keydown(function(e) { me.onKeyPress(e); }); } this.el.keyup(function(e) { me.onKeyUp(e); }); this.el.blur(function() { me.enableKillerFn(); }); this.el.focus(function() { me.fixPosition(); }); }, setOptions: function(options) { var o = this.options; $.extend(o, options); if (o.lookup) { this.isLocal = true; if ($.isArray(o.lookup)) { o.lookup = { suggestions: o.lookup, data: [] }; } } $("#" + this.mainContainerId).css({ zIndex: o.zIndex }); this.container.css({ maxHeight: o.maxHeight + "px", width: o.width }); }, clearCache: function() { this.cachedResponse = []; this.badQueries = []; }, disable: function() { this.disabled = true; }, enable: function() { this.disabled = false; }, fixPosition: function() { var offset = this.el.offset(); $("#" + this.mainContainerId).css({ top: (offset.top + this.el.innerHeight()) + "px", left: offset.left + "px" }); }, enableKillerFn: function() { var me = this; $(document).bind("click", me.killerFn); }, disableKillerFn: function() { var me = this; $(document).unbind("click", me.killerFn); }, killSuggestions: function() { var me = this; this.stopKillSuggestions(); this.intervalId = window.setInterval(function() { me.hide(); me.stopKillSuggestions(); }, 300); }, stopKillSuggestions: function() { window.clearInterval(this.intervalId); }, onKeyPress: function(e) { if (this.disabled || !this.enabled) { return; } switch (e.keyCode) { case 27: this.el.val(this.currentValue); this.hide(); break; case 9: case 13: if (this.selectedIndex === -1) { this.hide(); return; } this.select(this.selectedIndex); if (e.keyCode === 9) { return; } break; case 38: this.moveUp(); break; case 40: this.moveDown(); break; default: return; } e.stopImmediatePropagation(); e.preventDefault(); }, onKeyUp: function(e) { if (this.disabled) { return; } switch (e.keyCode) { case 38: case 40: return; } clearInterval(this.onChangeInterval); if (this.currentValue !== this.el.val()) { if (this.options.deferRequestBy > 0) { var me = this; this.onChangeInterval = setInterval(function() { me.onValueChange(); }, this.options.deferRequestBy); } else { this.onValueChange(); } } }, onValueChange: function() { clearInterval(this.onChangeInterval); this.currentValue = this.el.val(); var q = this.getQuery(this.currentValue); this.selectedIndex = -1; if (this.ignoreValueChange) { this.ignoreValueChange = false; return; } if (q === "" || q.length < this.options.minChars) { this.hide(); } else { this.getSuggestions(q); } }, getQuery: function(val) { var d, arr; d = this.options.delimiter; if (!d) { return $.trim(val); } arr = val.split(d); return $.trim(arr[arr.length - 1]); }, getSuggestionsLocal: function(q) { var ret, arr, len, val, i; arr = this.options.lookup; len = arr.suggestions.length; ret = { suggestions: [], data: [] }; q = q.toLowerCase(); for (i = 0; i < len; i++) { val = arr.suggestions[i]; if (val.toLowerCase().indexOf(q) === 0) { ret.suggestions.push(val); ret.data.push(arr.data[i]); } } return ret; }, getSuggestions: function(q) { var cr, me; cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q]; if (cr && $.isArray(cr.suggestions)) { this.suggestions = cr.suggestions; this.data = cr.data; this.suggest(); } else { if (!this.isBadQuery(q)) { me = this; me.options.params.query = q; $.get(this.serviceUrl, me.options.params, function(txt) { me.processResponse(txt); }, "text"); } } }, isBadQuery: function(q) { var i = this.badQueries.length; while (i--) { if (q.indexOf(this.badQueries[i]) === 0) { return true; } } return false; }, hide: function() { this.enabled = false; this.selectedIndex = -1; this.container.hide(); }, suggest: function() { if (this.suggestions.length === 0) { this.hide(); return; } var me, len, div, f, v, i, s, mOver, mClick; me = this; len = this.suggestions.length; f = this.options.fnFormatResult; v = this.getQuery(this.currentValue); mOver = function(xi) { return function() { me.activate(xi); }; }; mClick = function(xi) { return function() { me.select(xi); }; }; this.container.hide().empty(); for (i = 0; i < len; i++) { s = this.suggestions[i]; div = $((me.selectedIndex === i ? '<div class="selected"' : "<div") + ' title="' + s + '">' + f(s, this.data[i], v) + "</div>"); div.mouseover(mOver(i)); div.click(mClick(i)); this.container.append(div); } this.enabled = true; this.container.show(); }, processResponse: function(text) { var response; try { response = eval("(" + text + ")"); } catch (err) { return; } if (!$.isArray(response.data)) { response.data = []; } this.cachedResponse[response.query] = response; if (response.suggestions.length === 0) { this.badQueries.push(response.query); } if (response.query === this.getQuery(this.currentValue)) { this.suggestions = response.suggestions; this.data = response.data; this.suggest(); } }, activate: function(index) { var divs, activeItem; divs = this.container.children(); if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) { $(divs.get(this.selectedIndex)).attr("class", ""); } this.selectedIndex = index; if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) { activeItem = divs.get(this.selectedIndex); $(activeItem).attr("class", "selected"); } return activeItem; }, deactivate: function(div, index) { div.className = ""; if (this.selectedIndex === index) { this.selectedIndex = -1; } }, select: function(i) { var selectedValue, f; selectedValue = this.suggestions[i]; if (selectedValue) { this.el.val(selectedValue); if (this.options.autoSubmit) { f = this.el.parents("form"); if (f.length > 0) { f.get(0).submit(); } } this.ignoreValueChange = true; this.hide(); this.onSelect(i); } }, moveUp: function() { if (this.selectedIndex === -1) { return; } if (this.selectedIndex === 0) { this.container.children().get(0).className = ""; this.selectedIndex = -1; this.el.val(this.currentValue); return; } this.adjustScroll(this.selectedIndex - 1); }, moveDown: function() { if (this.selectedIndex === (this.suggestions.length - 1)) { return; } this.adjustScroll(this.selectedIndex + 1); }, adjustScroll: function(i) { var activeItem, offsetTop, upperBound, lowerBound; activeItem = this.activate(i); offsetTop = activeItem.offsetTop; upperBound = this.container.scrollTop(); lowerBound = upperBound + this.options.maxHeight - 25; if (offsetTop < upperBound) { this.container.scrollTop(offsetTop); } else { if (offsetTop > lowerBound) { this.container.scrollTop(offsetTop - this.options.maxHeight + 25); } } }, onSelect: function(i) { var me, onSelect, getValue, s, d; me = this; onSelect = me.options.onSelect; getValue = function(value) { var del, currVal, arr; del = me.options.delimiter; if (!del) { return value; } currVal = me.currentValue; arr = currVal.split(del); if (arr.length === 1) { return value; } return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value; }; s = me.suggestions[i]; d = me.data[i]; me.el.val(getValue(s)); if ($.isFunction(onSelect)) { onSelect(s, d); } } }; } (jQuery));

//* SECTION 5.0 CUSTOM JAVASCRIPT

$(document).ready(function () {
    //* 5.1 Rising Star Awards
    $("body.about table.rs-tbl").css("display", "none");
    $("ul#rs-ul a.title").click(function () { $(this).toggleClass("open"); $(this).next("table").toggle(); });
    //* 5.2 Press Center
    $("#prLst").css("display", "block");
    $("#pr10").css("display", "none");
    $("#pr09").css("display", "none");
    $("#prLst a").click(function () { var yr = '#pr' + $(this).attr("id").substring(1); $("ul.prLnks").hide(); $(yr).show(); $("#prLst li").removeClass("act"); $(this).parent().addClass("act"); });
    // Press Kit
    $("div.titleDiv").click(function () { $(this).toggleClass("panelOpen"); $(this).next("div.contentDiv").toggle("medium"); });
    // Login box (Contact Form)
    $("#signinLnk p a").click(function () {
        $("p.rtnMsg").fadeOut("slow");
        $("a.closeX").fadeIn("slow");
        $("div.login-box").slideToggle();
        return false;
    });
    $("a.closeX").click(function () {
        $("#signinLnk p.error").css("display", "none");
        $("a.closeX").fadeOut("slow");
        $("p.rtnMsg").fadeIn("slow");
        $("div.login-box").slideToggle();
        return false;
    });
    $("#forgotLnk").click(function () {
        $("div.forgot-box").slideToggle();
        return false;
    });
    $("#loginBtn").click(function () {
        var un = $("#uname").val();
        var pw = $("#pword").val();
        $.getJSON('/api/Login.ashx?u=' + un + '&p=' + pw, function (login) {
            if (login.status === "0") {
                hideAll();
                $("#logSuccMsg").slideToggle();
                $("div.alert").slideToggle();
                $("#uname").val("");
                $("#pword").val("");
                var fn = login.firstname;
                if (fn.length > 0) {
                    if (fn.length < 10) {
                        var welcome = "<span class=\"greeting\">Welcome back, " + fn + "!</span>&nbsp;";
                    }
                    else {
                        var welcome = "<span class=\"greeting\">Welcome back!</span>&nbsp;";
                    }
                    $("#login a:first").attr("href", "/login.aspx?SignOut=1");
                    $("#login a:first").html("Sign Out");
                    $(".greeting").remove(); // Remove the previous login greeting if any.
                    $("#login").prepend(welcome);
                };
                $("#txtFirstName").val(login.firstname);
                $("#txtLastName").val(login.lastname);
                $("#txtEmail").val(login.email);
                $("#txtEmailAlt").val(login.email_alt);
                $("#txtPhone").val(login.phone);
                $("#ddlWhoAmI").val(login.whoami);
                $("#txtCompany").val(login.company);
            }
            else if (login.status === "-1") {
                hideAll();
                $("#invalidClientMsg").css("display", "block");
                $("#uname").val("");
                $("#pword").val("");
                $("#uname").focus();
            }
        });
        return false;
    });
    $("#forgotBtn").click(function () {
        if ($("#forgotTB").val() === "") {
            hideAll();
            $("#pwError1").css("display", "block");
        }
        else {
            var em = $("#forgotTB").val();
            $.getJSON('/api/Login.ashx?em=' + em, function (login) {
                if (login.status === "0") {
                    $("strong.em").html(login.email);
                    hideAll();
                    $("#pwordSuccMsg").css("display", "block");
                    $("#forgotTB").val("");
                    $("div.forgot-box").slideToggle();
                }
                else if (login.status === "-1") {
                    $("strong.em").html(login.email);
                    hideAll();
                    $("#pwError2").css("display", "block");
                    $("#forgotTB").val("");
                    $("#forgotTB").focus();
                }
                else if (login.status === "-2") {
                    hideAll();
                    $("#pwordErrMsg").css("display", "block");
                    $("#forgotTB").val("");
                    $("#forgotTB").focus();
                }
            })
        };
        return false;
    });
    // Help Center
    $("a.subNav").click(function () {
        $(this).next("ul").slideToggle("slow");
        return false;
    });
    $("#helpNav ul").css("display", "none");
    $(".topicContent dd").css("display", "none");
    $(".topicContent dt").click(function () {
        $(this).toggleClass("open");
        $(this).next("dd").slideToggle();
    });
    var url = document.location.href;
    if (url.indexOf("topics.aspx") > 0) {
        // show subnav w/ active link
        $("a.subNav strong").parent().next("ul").css("display", "block");
    };
});

//* 5.3 Twitter feed
function twitterCallback2(twitters) { var statusHTML = []; for (var i = 0; i < twitters.length; i++) { var username = twitters[i].user.screen_name; var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) { return '<a href="' + url + '">' + url + '</a>'; }).replace(/\B@([_a-z0-9]+)/ig, function(reply) { return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>'; }); statusHTML.push('<li>' + status + '<span>' + relative_time(twitters[i].created_at) + '</span></li>'); } document.getElementById('twitter_update_list').innerHTML = statusHTML.join(''); }
function relative_time(time_value) { var values = time_value.split(" "); time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3]; var parsed_date = Date.parse(time_value); var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); var delta = parseInt((relative_to.getTime() - parsed_date) / 1000); delta = delta + (relative_to.getTimezoneOffset() * 60); if (delta < 60) { return 'less than a minute ago'; } else if (delta < 120) { return 'about a minute ago'; } else if (delta < (60 * 60)) { return (parseInt(delta / 60)).toString() + ' minutes ago'; } else if (delta < (120 * 60)) { return 'about an hour ago'; } else if (delta < (24 * 60 * 60)) { return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago'; } else if (delta < (48 * 60 * 60)) { return '1 day ago'; } else { return (parseInt(delta / 86400)).toString() + ' days ago'; } }

//* 5.4 Password length
function chkPWLength() {
    var pw = document.getElementById("pw").value;
    if (pw.length < 5) {
        alert('Your password must contain at least 5 characters.');
        return false;
    }
    else {
        return true;
    }
};

//* 5.5 Login box (Contact Form)
function hideAll() {
    $("#logSuccMsg,#pwordSuccMsg,#pwordErrMsg,#invalidClientMsg,#pwError1,#pwError2").css("display", "none");
};
