// from http://james.padolsey.com/javascript/regex-selector-for-jquery/
jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}


$IE = ($.browser.msie) ? parseInt($.browser.version) : false;


$(document).ready(function () {
    //about page adjustment class for IE7
    $('.about #content .single-col .tabs-wrapper .tabs-nav li').eq(2).addClass('adjusted')

    /* = SEARCH - query string builder
    --------------------------------------------------------------------------------------------*/
    $('.top-form .search a.submit').click(function () {
        var query = "/search-results?q=" + $('.top-form .search input[type="text"]').val().split(' ').join('+');
        if ($('.top-form .search input[type="text"]').val() != '') {
            window.location = query;
        }
    })
    $('.top-form .search input[type="text"]').focus(function () {
        var code = null;
        $(this).keydown(function (e) {
            code = (e.keyCode ? e.keyCode : e.which);

            if (code == 13 || code == 10) {
                var query = "/search-results?q=" + $(this).val().split(' ').join('+');
                if ($(this).val() != '') {
                    window.location = query;
                }
                e.preventDefault();
            }
        });
    })
    /////
    // variables and initial setup
    ////
    //
    var $teamContacts = $('.team-contacts .data-table .contact');
    var $careersContacts = $('.featured-people li');
    /////
    // for IE lower than 9 do various CCS modifications
    /////
    if ($.browser.msie && parseInt($.browser.version) <= 8) {
        $('.content-area.data .data-table:not(.grid) tr:not(.header):nth-child(2n)').css({ 'background': '#f2f1f1' }); // color zebra rows via JS
        $('.insights .featured-insight:nth-child(3n-2)').css({ 'margin-left': 0 });
        //		$('.team-contacts .contact:nth-child(5n)').css({'margin-right': 0});
    }
    /////
    // assign rel and id to each contact element for filtering 
    /////
    $teamContacts.each(function () {
        var name = $(this).find('.title').text();
        $(this).attr('rel', name);
        $(this).attr('id', name);
        //$(this).find('.bio').attr('href', '#' + name);		// THIS WILL NEED TO BE MODIFIED WHEN REAL DATA COMES IN
    });
    $careersContacts.each(function () {
        var name = $(this).find('.title').text();
        //$(this).find('.bio').attr('href', '#' + name);		// THIS WILL NEED TO BE MODIFIED WHEN REAL DATA COMES IN
    });
    /////
    // remove value from contacts filter on page load
    /////
	function resetFilters(selector) {
		$(selector).val('').trigger('change');
		$('.select-replace ul').each(function() {
			$(this).find('a:first').trigger('click');
		});
//		$('.select-replace ul a:first').trigger('click');
		$teamContacts.show().addClass('group subgroup filtered');
		$('.empty-results').addClass('hidden');
	}
	resetFilters('.team-contacts .data-table .filter-name, .team-contacts .data-table .filter-lob-parent, .team-contacts .data-table .filter-lob');
	window.setTimeout(function() {
		if ($('.filter-lob-parent').length == 0)
			$('.filter-lob').next('.select-replace').show();
	}, 300);
    /////
    // event binds
    /////
    /////
    // login drowdown in header
    /////
    $('#login-area').click(function (e) {
        var height = $('.login-dropdown li').length * 20 + 'px';
        if ($('.login-dropdown').css('height') == '20px')
            $('.login-dropdown').css({ 'height': height }, 300);
        else
            $('.login-dropdown').css({ 'height': '20px' }, 300);
        e.stopPropagation();
        e.preventDefault();
    });
    /////	
    // hide dropdown and map popup if clicked outside (anywhere in body)
    /////
    $('body').click(function (e) {
        var height = $('.login-dropdown li').length * 20 + 'px';
        if ($('.login-dropdown').css('height') == height)
            $('.login-dropdown').css({ 'height': '20px' }, 300);
        $map.$mapPopup.addClass('off-screen');
        $map.$mapPopupPinTop.hide();
        $map.$mapPopupPinBottom.hide();
    });


    $('.main-nav li:not(.audience) .sub-nav').hover(function () {
        $(this).prev('a').addClass('hover');
    }, function () {
        $(this).prev('a').removeClass('hover');
    });
    /////
    // create the popup span in each icon wrapper's span
    /////
    /*
    $('a.full-story').each(function() {
    //		var txt = $.trim($(this).attr("class").replace("icon ", ""));
    var txt = 'View full story';
    $('<span class="popup">' + txt + "</span>").appendTo($(this));
    });
    $('a.full-story').hover(function() {				// hover state for popup
    $(this).find('.popup').fadeIn(100);
    }, function() {
    $(this).find('.popup').delay(200).fadeOut(200);
    });
    */
    /////
    // hover state for Team Contacts boxes
    /////
/*
    $('.team-contacts .contact').hover(function () {
        $(this).find('.contact-detail').stop(false, true).animate({ 'bottom': 0 }, 200);
    }, function () {
        $(this).find('.contact-detail').stop(false, true).animate({ 'bottom': -42 }, 200);
    });
*/
	/////
	// filter team contacts when typing into text field
	/////
	$('.team-contacts .data-table .filter-name').keyup(function() {
		var $this = $(this);
		var $contacts = $('li.contact');
//		window.setTimeout(function() {
//			c(obj.val());
//			c($contacts.filter(':not(:regex(rel, ' + obj.val() + '))'));
			$contacts.filter(':not(.group.subgroup:regex(rel, ' + $this.val() + '))').hide().removeClass('filtered');//hide();
			var c = $contacts.filter('.group.subgroup:regex(rel, ' + $this.val() + ')').show().addClass('filtered');//.show();
			$('.contacts-status').text(c.length).parent().contents()[2].data = c.length == 1 ? ' Contact' : ' Contacts';
			if ($contacts.filter(':visible').length == 0)
				$contacts.parent().prev('.empty-results').removeClass('hidden');
			else
				$contacts.parent().prev('.empty-results').addClass('hidden');
//		}, 200);
	});
	/////
	// filter team contacts from select
	/////
	$('.team-contacts .data-table .filter-lob-parent').change(function() {
		$('.team-contacts .data-table .filter-name').val('').trigger('keyup');
		var $this = $(this);
		var $contacts = $('li.contact');
		$('.filter-lob').next('.select-replace').hide().find('ul a:eq(0)').trigger('click')
		$('.filter-lob[rel=' + $this.val() +']').next('.select-replace').show();	
//		window.setTimeout(function() {
		var selectString =  $this.val();//[0].selectedIndex == 0 ? '' : $(':eq(' + $this[0].selectedIndex + ')', $this).attr('value');
//			console.log('filtering lobparent by: ' + selectString + ')');
			$contacts.filter(':not(:regex(lobparent, ' + selectString + '))').hide().removeClass('group');//.hide();
			var c = $contacts.filter(':regex(lobparent, ' + selectString + ')').show().addClass('group');//.show();
			$('.contacts-status').text(c.length).parent().contents()[2].data = c.length == 1 ? ' Contact' : ' Contacts';
			if ($contacts.filter(':visible').length == 0)
				$contacts.parent().prev('.empty-results').removeClass('hidden');
			else
				$contacts.parent().prev('.empty-results').addClass('hidden');
//		}, 200);
	});
	$('.team-contacts .data-table .filter-lob').change(function() {
		$('.team-contacts .data-table .filter-name').val('').trigger('keyup');
		var $this = $(this);
		var $contacts = $('li.contact');
//		window.setTimeout(function() {
			$contacts.filter(':not(.group:regex(lob, ' + ($this.val() || '') + '))').hide().removeClass('subgroup');//.hide();
			var c = $contacts.filter('.group:regex(lob, ' + ($this.val() || '') + ')').show().addClass('subgroup');//.show();
			$('.contacts-status').text(c.length).parent().contents()[2].data = c.length == 1 ? ' Contact' : ' Contacts';
			if ($contacts.filter(':visible').length == 0)
				$contacts.parent().prev('.empty-results').removeClass('hidden');
			else
				$contacts.parent().prev('.empty-results').addClass('hidden');
//		}, 200);
	});

	/////
	// clear filters
	/////
	$('.reset-filters').click(function(e) {
		resetFilters('.team-contacts .data-table .filter-name, .team-contacts .data-table .filter-lob-parent, .team-contacts .data-table .filter-lob');
//		resetFilters('.team-contacts .data-table #filter-name');
//		$('.team-contacts .data-table .filter-name').trigger('keyup');
		e.preventDefault();
	});
    /////
    // update the datatable for selected Financing Type
    /////
    $('#financing-type').change(function () {
        if ($(this).val() != '') {
            dataFilters = {};
            dataFilters.type = $(this).val();
            $('table#transactions').datatable({
                type: $(this).val(),
                q: dataFilters,
                display: DATA_DISPLAY
            });
            $('.empty-label').remove();
        }
    });
    /////
    // open popup on Careers page
    /////
/*
    $('.careers .big-link, .careers a.pod').click(function (e) {
        var popupId = $(this).attr('popup');
        $('#' + popupId + ' .tabs-wrapper.main .tabs-nav li a:eq(' + $(this).attr('rel') + ')').trigger('click');
        // close any open popups
        $('.popup[id!=' + popupId + ']')
			.animate({ 'opacity': 0 }, function () {
			    $('.popup[id!=' + popupId + ']').addClass('off-screen');
			});

        // open popup with this id
        if ($('.popup#' + popupId).hasClass('off-screen')) {
            $('.popup#' + popupId)
				.removeClass('off-screen')
				.css('z-index', 10)
				.animate({ 'opacity': 1 }, function () {
				    //					alert('z-index');
				    $('.popup#' + popupId).css('z-index', 0)
				});
        }
        e.preventDefault();
    });
*/
    /////
    // close popup on Careers page
    /////
    $('.careers .popup .close').click(function (e) {
        $('.popup')
			.animate({ 'opacity': 0 }, function () {
			    $('.popup').addClass('off-screen');
			});
        e.preventDefault();
    });
    /////
    // bind "leaving site" dialog to a tags
    /////
    $('a').live('click', function (e) {
        var bumper = false;
        if ($(this).attr('href') && $(this).attr('href').indexOf('http') > -1) {
            var count = 0;
            for (var i = 0; i < whiteListDomains.length; i++) {
                if ($(this).attr('href').indexOf(whiteListDomains[i]) > -1) {
                    count++;
                }
                bumper = count == 0 ? true : false;
            }
        }
        if (bumper) {
            return confirm('Attention: You are exiting www.williamblair.com.\n\nInformation contained on the Internet is not subject to William Blair & Company\'s control or review, \nand may not be accurate. For disclosure information, please visit www.williamblair.com.');
        }
    });
    /////
    // bind print
    /////
    $('a.print').click(function (e) {
        window.print();
        e.preventDefault();
    });


    /////
    // blinds
    /////
    /*
    args:
    hasTitle: does the node have a title whose height needs to be accounted for? (default: false)
    animationDuration: how long the slide animation lasts (default: 200ms)
    special: anything else that needs to be performed on hover on/off (default: {}) or the following JSON object:
    selector: jQuery selector for element to act upon
    css: an JSON object with CSS properties to animate
    */
       (function ($) {
       	$.fn.blinds = function (args) {
       		var defaults = {
       			hasTitle: false,
       			animationDuration: 200,
       			special: {}
       		};
       		var args = $.extend(defaults, args);
       		return this.each(function (_i, _item) {
       			var $this = $(_item),
				$detail = $this.find('.detail'),
				titleHeight = args.hasTitle ? $detail.find('.title').outerHeight() : 0;
       			args.special = args.special || false;
       			$this.hover(function () {
       				$detail.stop(false, true).animate({ 'top': '-=' + ($detail.outerHeight() - titleHeight) }, args.animationDuration);
       				if (!$.isEmptyObject(args.special)) {
       					$this.find(args.special.selector).stop(false, true).animate(args.special.cssOver, args.animationDuration);
       				}
       			}, function () {
       				$detail.stop(false, true).animate({ 'top': '+=' + ($detail.outerHeight() - titleHeight) }, args.animationDuration);
       				if (!$.isEmptyObject(args.special))
       					$this.find(args.special.selector).stop(false, true).animate(args.special.cssOut, args.animationDuration);
       			});

       		});
       	}
       })(jQuery);
       /////
    // form validator
    /////
    (function ($) {
        $.fn.validator = function () {
            var defaults = {
        };
        var args = $.extend(defaults, args);
        return this.each(function () {
            var $this = $(this),
				errors,
				$required = {
				    'text': $this.find('input[type=text].required, input[type=password].required, textarea.required'),
				    'select': $this.find('select.required'),
				    'checkbox': $this.find('input[type=checkbox].required'),
				    'radio': $this.find('input[type=radio].required')
				},
				validate,
				addErrorMarker,
				removeErrorMarker;
            // add "required" marker
            for (name in $required) {
                $required[name].each(function () {
                    //					c($this.find('.label[for=' + $(this).attr('name') + ']'))
                    if (name == 'radio' || name == 'checkbox') {
                        if ($this.find('.label[group=' + $(this).attr('name') + '] .required-mark').length == 0)
                            $this.find('.label[group=' + $(this).attr('name') + ']').prepend($('<span class="required-mark">*</span>'));
                    } else {
                        $(this).prev('label').prepend($('<span class="required-mark">*</span>'));
                    }
                });
            }
            // bind form submit
            $this.submit(function () {
//                return validate();
            });
            $this.find('.submit').bind('click', function (e) {
				return validate();
//                $this.trigger('submit');
//                e.preventDefault();
            });
            addErrorMarker = function ($obj, type) {
                var errorText;
                switch (type) {
                    case 'text':
                        errorText = $obj.attr('err') == undefined ? 'Please complete this field' : $obj.attr('err');
                        if ($obj.next('span.error').length == 0)
                            $('<span class="error">' + errorText + '</span>').insertAfter($obj).fadeIn(300);
                        break;
                    case 'select':
                        errorText = $obj.attr('err') == undefined ? 'Please select one' : $obj.attr('err');
                        if ($obj.next('span.error').length == 0)
                            $('<span class="error">' + errorText + '</span>').insertAfter($obj).fadeIn(300);
                        break;
                    case 'checkbox':
                        errorText = $obj.attr('err') == undefined ? 'Please check off at least one box' : $obj.attr('err');
                        if ($this.find('.label[group=' + $obj.attr('name') + ']').siblings('span.error').length == 0)
                            $('<span class="error">' + errorText + '</span>').insertAfter($this.find('.label[group=' + $obj.attr('name') + ']')).fadeIn(300);
                        break;
                    case 'radio':
                        errorText = $obj.attr('err') == undefined ? 'Please select one' : $obj.attr('err');
                        if ($this.find('.label[group=' + $obj.attr('name') + ']').siblings('span.error').length == 0)
                            $('<span class="error">' + errorText + '</span>').insertAfter($this.find('.label[group=' + $obj.attr('name') + ']')).fadeIn(300);
                        break;
                    default: ;
                }
            }
            removeErrorMarker = function ($obj, type) {
                switch (type) {
                    case 'text':
                    case 'select':
                        $obj.next('span.error').fadeOut(300, function () {
                            $(this).remove()
                        });
                        break;
                    case 'checkbox':
                    case 'radio':
                        $this.find('.label[group=' + $obj.attr('name') + ']').siblings('span.error').fadeOut(300, function () {
                            $(this).remove()
                        });
                        break;
                    default: ;
                }
            }
            validate = function (args) {
                errors = 0;
                $required.text.each(function (n) {
                    var $this = $(this);
                    if ($this.val() == '' ||
						($this.hasClass('email') && !/.+@.+\..+/.test($this.val())) ||
						($this.hasClass('confirm') && $this.val() != $required.text.filter($this.attr('with')).val())) {
                        errors++;
                        addErrorMarker($this, 'text');
                    } else {
                        removeErrorMarker($this, 'text');
                    }
                });
                $required.select.each(function (n) {
                    var $this = $(this);
                    if ($(this).val() == '') {
                        errors++;
                        addErrorMarker($this, 'select');
                    } else {
                        removeErrorMarker($this, 'select');
                    }
                });
                $required.checkbox.each(function (n) {
                    var $this = $(this);
                    name = $this.attr('name');
                    //						errorText = $this.attr('err') == undefined ? 'Please check off at least one box' : $this.attr('err');
                    filter = $required.checkbox.filter('[name=' + name + ']:checked');
                    if (filter.length == 0) {
                        errors++;
                        addErrorMarker($this, 'checkbox');
                    } else {
                        removeErrorMarker($this, 'checkbox');
                    }
                });
                $required.radio.each(function (n) {
                    var $this = $(this);
                    name = $this.attr('name');
                    //						errorText = $this.attr('err') == undefined ? 'Please select one' : $this.attr('err');
                    filter = $required.radio.filter('[name=' + name + ']:checked');
                    if (filter.length == 0) {
                        errors++;
                        addErrorMarker($this, 'radio');
                    } else {
                        removeErrorMarker($this, 'radio');
                    }
                });
                return errors == 0;
            }
        });
    }
})(jQuery);
/////
// tabs
/////
/*
args:
currentTab: which tab is selected first (default: 0)
tabsNavWidth: custom tab width (default: 0, inherited from CSS)
*/
(function ($) {
    $.fn.tabs = function (args) {
        var defaults = {
            'currentTab': 0,
            'tabsNavWidth': 0,
            'special': function () { return false; }
        },
			args = $.extend(defaults, args);
        return this.each(function (_i, _item) {
            // variables
            var $this = $(_item),
				$wrapper = $this,
				$tabsNav = $this.find(' >.tabs-nav li') || {},
				$tabsNavLinks = $this.find(' >.tabs-nav li a') || {},
				$tabsContent = $this.find('> .tabs-content-wrapper .tabs-content') || {},
				totalTabs = $tabsNavLinks.length || 0,
				currentTab = args.currentTab || 0,
				tabsNavWidth = args.tabsNavWidth || 0,
            // navigate function
				navigate = function (n) {
				    $tabsNav.filter(':eq(' + currentTab + ')').removeClass('selected');
				    $tabsNav.filter(':eq(' + n + ')').addClass('selected');
				    $tabsContent.filter(':eq(' + currentTab + ')').addClass('hidden');
				    $tabsContent.filter(':eq(' + n + ')').removeClass('hidden');
				    currentTab = n;
				    try {
				        args.special($tabsNavLinks.eq(n).attr('title'));
				    } catch (e) {
				        // don't care if this doesn't execute since it would only be defined as needed
				    }
				};
            // this should be init
			var maxTabWidth = Math.floor($wrapper.outerWidth() / $tabsNavLinks.length) - 3;
			if (isNaN(maxTabWidth) || maxTabWidth < 0)
				maxTabWidth = 0;
            $tabsNavLinks.each(function (n) {
                $(this).attr('rel', n);
				if (maxTabWidth > 0)
					$(this).css('max-width', maxTabWidth);
            });
			if(isNaN(currentTab)) {
				$tabsNavLinks.filter('[href=#' + currentTab + ']').parent().addClass('selected');
				$tabsContent.not('#' + currentTab).addClass('hidden');
				currentTab = $tabsNavLinks.filter('[href=#' + currentTab + ']').attr('rel');
			} else {
				$tabsNav.filter(':eq(' + currentTab + ')').addClass('selected');
				$tabsContent.not(':eq(' + currentTab + ')').addClass('hidden');
			}
            try {
                args.special($tabsNavLinks.eq(args.currentTab).attr('title'));
            } catch (e) {
                // don't care if this doesn't execute since it would only be defined as needed
            }
            $tabsNavLinks.click(function (e) {
                navigate($(this).attr('rel'));
                e.preventDefault();
            });
            if (tabsNavWidth != 0)
                $tabsNav.css('width', tabsNavWidth);
        });
    };
})(jQuery);
/////
// map setup
/////
/*
_init() needs to be called to initialize the map, accepts the following arguments, passed as an object:
small: is this the small version of the map? (default: false)
*/
$map = {
    $map: $('.map') || {},
    $mapPopup: $('.map-popup') || {},
    $mapPopupPinTop: $('.pin-big-top') || {},
    $mapPopupPinBottom: $('.pin-big-bottom') || {},
    zoomIn: {},
    zoomOut: {},
    ratio: 1.47, // for the small map, this ratio allows to reposition the pins without extra CSS
    small: false,
    _init: function (args) {
    	var _self = this;
        this.small = args.small || false;
        if (this.small)
            for (var i in pins) {
                pins[i].css.left = Math.floor(pins[i].css.left / this.ratio);
                pins[i].css.top = Math.floor(pins[i].css.top / this.ratio);
            }
        for (var i in pins) {
    		if ($IE && $IE < 9) {			// if < IE9 do not animate opacity
				//alert('ie case');
				$('<span class="pin" rel="' + i + '" id="' + pins[i].location + '"><img src="/resources/images/pin-small.png" /></span>')
					.appendTo(this.$map)
					//.css({ 'opacity': 1 })
					.css(pins[i].css);
				//					.css({'opacity': 1}, 1500)
				//					.css(pins[i].css, 500);
			} else {
				$('<span class="pin" rel="' + i + '" id="' + pins[i].location + '"><img src="/resources/images/pin-small.png" /></span>')
					.appendTo(this.$map)
					.animate({ 'opacity': 1 }, 1500)
					.animate(pins[i].css, 500);
				//					.css({'opacity': 1}, 1500)
				//					.css(pins[i].css, 500);
			}
        }
        // animate pins on hover
        var zoom = this.small ? 6 : 10;
        var move = this.small ? 3 : 5;
        this.zoomIn = {
            'width': '+=' + zoom,
            'height': '+=' + zoom,
            'left': '-=' + move,
            'top': '-=' + move
        };
        this.zoomOut = {
            'width': '-=' + zoom,
            'height': '-=' + zoom,
            'left': '+=' + move,
            'top': '+=' + move
        };
        this.$mapPopupPinTop.hide();
        this.$mapPopupPinBottom.hide();
        $('.pin').hover(function () {
            $(this).css('z-index', '11').stop(false, true).animate(_self.zoomIn, 200);
        }, function () {
            $(this).css('z-index', '10').stop(false, true).animate(_self.zoomOut, 200);
        });
        // show and move popup on pin click - some disgusting code follows :(
        $('.pin').click(function (e) {
            _self.$mapPopup.find('.content-area:visible').hide();
            _self.$mapPopup.find('.content-area#' + $(this).attr('id')).show();
            var moveZig = function () {
                var destination = {
                    left: pins[$(e.currentTarget).attr('rel')].css.left,
                    top: pins[$(e.currentTarget).attr('rel')].css.top,
                    adjustX: pins[$(e.currentTarget).attr('rel')].css.left > _self.$map.width() / 2 ? true : false,
                    adjustY: _self.$mapPopup.height() + pins[$(e.currentTarget).attr('rel')].css.top > _self.$map.height() ? true : false
                };
                _self.$mapPopupPinTop.css({
                    left: destination.left - (_self.small ? 33 : 30),
                    top: destination.top - (_self.small ? 33 : 30)
                });
                _self.$mapPopupPinBottom.css({
                    left: destination.left - (_self.small ? 33 : 30),
                    top: destination.top - (_self.small ? 64 : 61)
                });
                if (destination.adjustY) {
                    _self.$mapPopupPinTop.hide();
                    _self.$mapPopupPinBottom.show();
                } else {
                    _self.$mapPopupPinTop.show();
                    _self.$mapPopupPinBottom.hide();
                }
                _self.$mapPopup.removeClass('off-screen');
                //					c(_self.small ? destination.adjustY ? 'smallAdjust' : 'small' : destination.adjustY ? 'normalAdjust' : 'normal')					
                var coords = {
                    left: !destination.adjustX ? 0 : _self.small ? 260 : 'auto', // if not adjusting horizontally, position popup at left: 0, else left: 260 for small map and left:
                    right: !destination.adjustX ? 'auto' : 0, // if not adjusting horizontally, position popup at left: 0, else left: 260 for small map and left:
                    top: _self.small ? 										// refer to the comment a few lines above to understand this crazy logic (essentially a 4-way using ternary operators)
							destination.adjustY ?
								destination.top - _self.$mapPopup.height() - 40 : destination.top + 50 : destination.adjustY ?
									destination.top - _self.$mapPopup.height() - 60 : destination.top + 70

                };
                _self.$mapPopup.css(coords);
            };
            moveZig();

            e.stopPropagation();
            e.preventDefault();
        });
    }
};
/////
// carousel
/////
/*
args:
animationDuration: time for each node to complete its animation (default: 1000ms)
orientation: 'h' for horizontal or 'v' for vertical (default: 'v')
pagination: is pagination enabled? (default: false)
specialFirstElement: does the first element have a top border and thus has to be animated an extra pixel? (default: false)
autoscroll: does the carousel scroll automatically? (default: false)
autoscrollTimeout: how long each carousel node is displayed (default: 5000ms)
visibleNodes: how many nodes are initially visible (default: 1)
*/
(function ($) {
    $.fn.carousel = function (args) {
        var defaults = {
            'animationDuration': 1000,
            'orientation': 'v',
            'pagination': false,
            'visibleNodes': false,
            'specialFirstElement': false,
            'autoscroll': false,
            'autoscrollTimeout': 5000
        };
        var args = $.extend(defaults, args);
        return this.each(function (_i, _item) {
            var $this = $(_item),
				wrapper = $this,
				navigate,
				_updateCoords,
				_autoscroll,
				_updatePagination,
				obj = wrapper.find('.carousel') || {},
				next = wrapper.find('.next') || {},
				prev = wrapper.find('.prev') || {},
				width = obj.width(),
				height = obj.height(),
				animationDuration = args.animationDuration,
				orientation = args.orientation,
				pagination = args.pagination,
				visibleNodes = args.visibleNodes,
				specialFirstElement = args.specialFirstElement,
				autoscroll = args.autoscroll,
				autoscrollTimeout = args.autoscrollTimeout,
				paginationNodes = [],
				currentPosition = 0,
				lastPosition = 0,
            //			defaultAnimationDuration = 1000,
            //			defaultTimeout = 5000,
				outOfBounds = false,
				nodes = [],
				wrapperHeight = 0,
				wrapperWidth = 0,
				carouselWidth = 0;

            this.left = 0;
            this.top = 0;


            // update coordinates function
            _updateCoords = function () {
                $this.left = obj.position().left;
                $this.top = obj.position().top;
                outOfBounds = currentPosition + 1 > lastPosition ? 'next' : currentPosition - 1 < 0 ? 'prev' : false;
                if (outOfBounds == 'next')
                    next.addClass('inactive')
                else
                    next.removeClass('inactive')
                if (outOfBounds == 'prev')
                    prev.addClass('inactive')
                else
                    prev.removeClass('inactive')
                //			c(this.outOfBounds);
                //			c('left: ' + this.left);
                //			c('top: ' + this.left);
                //				c(obj.attr('id'));

            };
            _updatePagination = function (modifier) {
                if (!pagination)
                    return false;
                if (modifier == 'add')
                    paginationNodes[currentPosition].obj.addClass('selected');
                else
                    paginationNodes[currentPosition].obj.removeClass('selected');
            };
            // autoscroll function; accepts timeout argument or uses default from constructor or the global default
            _autoscroll = function (timeout) {
                timeout = autoscrollTimeout;
                //				c(timeout);
                window.setInterval(function () {
                    if (currentPosition + 1 > lastPosition) {
                        navigate({
                            direction: 'jump',
                            duration: animationDuration,
                            jumpTo: 0
                        });
                    } else {
                        navigate({
                            direction: 'next',
                            duration: animationDuration,
                            specialFirstElement: specialFirstElement
                        });
                    }
                }, timeout);
            }
            navigate = function (args) {
                //				c(obj.attr('id'));
                var direction = args.direction,
					duration = args.duration,
					specialFirstElement = args.specialFirstElement,
					jumpTo = args.jumpTo,
					distance = 0,
					_self = this,
					params = {};
                offset = {};
                offset.top = '0';
                offset.left = '0';
                dimension = orientation == 'v' ? 'height' : 'width';
                // if carousel is in motion, do not move
                if (obj.filter(":animated").length > 0)
                    return false;
                // handle navigation
                switch (direction) {
                    case 'next':
                        distance = outOfBounds == 'next' ? 30 : nodes[currentPosition][dimension] - (specialFirstElement && currentPosition == 0 ? 1 : 0);
                        offset[orientation == 'v' ? 'top' : 'left'] = '-=' + distance;
                        if (outOfBounds == 'next') {
                            obj.animate(offset, 300);
                            offset.left = offset.left.replace('-', '+');
                            offset.top = offset.top.replace('-', '+');
                            obj.animate(offset, 200);
                            return false;
                        }
                        _updatePagination('remove')
                        obj.animate(offset, duration, function () {
                            _updateCoords();
                        });
                        currentPosition++;
                        _updatePagination('add')
                        break;
                    case 'prev':
                        distance = outOfBounds == 'prev' ? 30 : nodes[currentPosition - 1][dimension] - (specialFirstElement && currentPosition - 1 == 0 ? 1 : 0);
                        offset[orientation == 'v' ? 'top' : 'left'] = '+=' + distance;
                        if (outOfBounds == 'prev') {
                            obj.animate(offset, 300);
                            offset.left = offset.left.replace('+', '-');
                            offset.top = offset.top.replace('+', '-');
                            obj.animate(offset, 200);
                            return false;
                        }
                        _updatePagination('remove')
                        currentPosition--;
                        obj.animate(offset, duration, function () {
                            _updateCoords();
                        });
                        _updatePagination('add')
                        break;
                    case 'jump':
                        if (jumpTo == currentPosition)
                            break;
                        if (pagination) {
                            paginationNodes[currentPosition].obj.removeClass('selected');
                        }
                        var from = jumpTo > currentPosition ? currentPosition : jumpTo,
							to = jumpTo > currentPosition ? jumpTo : currentPosition;
                        for (var i = from; i < to; i++) {
                            distance += nodes[i].width;
                        }
                        if (jumpTo < currentPosition)
                            distance = '-' + distance
                        obj.animate({ left: '-=' + distance }, duration, function () { _updateCoords(); });
                        currentPosition = jumpTo;
                        if (pagination) {
                            paginationNodes[currentPosition].obj.addClass('selected');
                        }
                        break;
                    default:
                        ;
                }
            };

            // pagination is enabled		
            if (pagination) {
                wrapper.find('.pagination a').each(function (n) {
                    paginationNodes.push({
                        obj: $(this),
                        index: n
                    });
                    $(this).click(function (e) {
                        navigate({
                            direction: 'jump',
                            duration: animationDuration,
                            jumpTo: n
                        });
                        e.preventDefault();
                    });
                });
            }
			if (wrapper.find('.pagination a').length < 2) {
				wrapper.find('.pagination').hide();
			}

            // populate carousel nodes object
            obj.find('> li').each(function (n) {
                nodes.push({
                    obj: $(this),
                    index: n,
                    width: $(this).outerWidth(),
                    height: $(this).outerHeight()
                });
            });

            // set up carousel wrapper width/height based on orientation
            switch (orientation) {
                case 'v':
                    wrapperHeight = 0;
                    for (var i = 0; i < visibleNodes; i++) {
                        wrapperHeight += nodes[i].height;
                    }
                    break;
                case 'h':
                    for (var i = 0; i < nodes.length; i++) {
                        carouselWidth += nodes[i].width;
                    }
                    obj.width(carouselWidth);
                    wrapperWidth = nodes[0].width;
                    break;
                default: ;
            }
            wrapperWidth = wrapperWidth != 0 ? wrapperWidth += 'px' : 'auto';
            wrapperHeight = wrapperHeight != 0 ? wrapperHeight += 'px' : 'auto';
            lastPosition = nodes.length - 1;
            obj.wrap('<div style="width: ' + wrapperWidth + '; height: ' + wrapperHeight + '; ' + (orientation == 'h' ? ' float: left;' : '') + ' overflow: hidden; position: relative;" />');

            // autoscroll
            if (autoscroll) {
                _autoscroll();
            }
            // initial update
            _updateCoords();

            // bind navigation clicks
            next.click(function (e) {
                navigate({
                    direction: 'next',
                    duration: $this.animationDuration,
                    specialFirstElement: specialFirstElement
                });
                e.preventDefault();
            });
            prev.click(function (e) {
                navigate({
                    direction: 'prev',
                    duration: $this.animationDuration,
                    specialFirstElement: specialFirstElement
                });
                e.preventDefault();
            });
        });

    };
})(jQuery);
/////
// datatable with sort
/////
(function ($) {
    $.fn.datatable = function (args) {
        var defaults = {
            animationDuration: 100
        };
        var args = $.extend(defaults, args);
        return this.each(function (_i, _item) {
            var $this = $(this),
				transactions = {},
				rows = [],
				sortOptions = {
				    col: 0,
				    dir: ''
				},
				ltIE9 = $.browser.msie && parseInt($.browser.version) <= 8,
				$overlay = $this.siblings('.overlay'),
				_loadData,
				_sortData,
				_showOverlay,
				_hideOverlay,
				_loadFilters,
				_zebra;
            _showOverlay = function () {
                //				$overlay = $('<div class="overlay"></div>');
                /*
                $overlay.animate({
                'opacity': 0.5,
                'z-index': '100'
                }, args.animationDuration);
                */
                $overlay.fadeTo(args.animationDuration, 0.5);
            };
            _hideOverlay = function () {
                /*
                $overlay.animate({
                'opacity': 0,
                'z-index': '-1'
                }, args.animationDuration), function() {
                //					$this.find('.overlay').remove();
                //				});
                */
                $overlay.fadeOut(args.animationDuration, 0);
            };
            _zebra = function () {
                if (ltIE9) {
                    $this.find('tr:not(.header):nth-child(n)').css({ 'background': '#fff' });
                    $this.find('tr:not(.header):nth-child(2n)').css({ 'background': '#f2f1f1' });
                }
            };
            _loadFilters = function (filters) {
                $('.filters').empty();
                for (var i in filters) {
                    $label = $('<label for="filter-' + filters[i].name.replace(' ', '-') + '">' + filters[i].name + '</label>');
                    options = '<option value="">All</option>';
                    for (var j in filters[i].values) {
                        options += '<option value="' + filters[i].values[j] + '"';
                        options += (filters[i].selected == filters[i].values[j] ? ' selected="selected"' : '');
                        options += '>' + filters[i].values[j] + '</option>';
                    }
                    $select = $('<select id="' + filters[i].name.replace(' ', '-') + '" name="' + filters[i].name.replace(' ', '') + '">' + options + '</select><br class="clear" />');
                    $label.appendTo($('.filters:eq(' + (i % 3) + ')'));
                    $select.appendTo($('.filters:eq(' + (i % 3) + ')'));
                }
                $('.filters select').unbind('change').bind('change', function () {
                    dataFilters[$(this).attr('name')] = $(this).val();
                    $('table#transactions').datatable({
                        type: 'public',
                        q: dataFilters,
                        display: DATA_DISPLAY
                    });
                });
            };
            _loadData = function (type, q, display) {
                DATA_DISPLAY = display;
                _showOverlay();
                $.ajax({
                    // the url will change based on the Sitecore service that generates the JSON
                    url: 'scripts/' + type + '-' + DATA_DISPLAY + '.js',
                    data: q,
                    dataType: 'json',
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('There was an error loading the data, please try again.');
                        //						c('jqXHR: ' + jqXHR);
                        //						c('textStatus: ' + textStatus);
                        //						c('errorThrown: ' + errorThrown);
                        _hideOverlay();
                    },
                    success: function (data) {
                        obj = [];
                        var transactions = data.rows,
							filters = data.filters,
							$label,
							$select,
							options

                        $this.find('tr:gt(0)').remove();

                        $this.find('#transactions-showing').text(data.transactionsShowing);
                        $this.find('#transactions-total').text(data.transactionsTotal);

                        _loadFilters(filters);

                        if (DATA_DISPLAY == 'list') {
                            var row = '<tr class="header">',
								type = data.type,
								counter = 0;
                            for (var i in data.headers) {
                                row += '<th style=""><a href="#" class="sort" rel="' + counter + '"><span>' + data.headers[i] + '</span></a></th>';
                                counter++;
                            }
                            row += '</tr>'
                            $(row).appendTo($this);
                            $this.find('.sort').click(function (e) {
                                _sortData($(this));
                                e.preventDefault();
                            });
                            row = '';
                            for (var i in transactions) {
                                row += '<tr id="data-row-' + i + '">';
                                for (var headerName in data.headers) {
                                    if (transactions[i][headerName] != null && typeof (transactions[i][headerName]) == 'object') {
                                        switch (type) {
                                            case 'public':
                                                row += '<td><span class="flag ' + data.rows[i][headerName].country.toLowerCase() + '"></span>';
                                                row += '<p>' + transactions[i][headerName].city + ', ' + transactions[i][headerName].state + '</p></td>';
                                                break;
                                            case 'mergers':
                                                row += '<td><span class="flag ' + transactions[i][headerName].country.toLowerCase() + '"></span>';
                                                row += '<p>' + transactions[i][headerName].company + '</p></td>';
                                                break;
                                            default: ;
                                        }
                                    } else if (headerName == 'amount') {
                                        if (typeof (transactions[i][headerName]) != 'string' || transactions[i][headerName] == "ND") {
                                            row += '<td class="currency"><span rel="' +
													(typeof (transactions[i][headerName]) != 'string' ? transactions[i][headerName] : '0') +
													'">' +
													(typeof (transactions[i][headerName]) != 'string' ? '$' : '') +
													transactions[i][headerName].toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + '</span></td>';
                                        } else {
                                            row += '<td>' + transactions[i][headerName] + '</td>';
                                        }
                                    } else {
                                        row += '<td>' + transactions[i][headerName] + '</td>';
                                    }
                                }
                                row += '</tr>';
                            }
                            if ($this.find('.placeholder').length > 0)
                                $this.find('.placeholder').parent().remove();
                            $(row).appendTo($this);
                            _zebra();
                        } else if (DATA_DISPLAY == 'grid') {
                            var filters = data.filters,
								tiles = data.tiles,
								tile = '<tr><td>';
                            tile += '<label for="filter-stories">Show only transactions with stories</label><input type="checkbox" id="filter-stories" /><br />'

                            for (var i in tiles) {
                                tile += '<div class="featured-case ' + data.type + '">';
                                tile += '<div class="title">' +

								(typeof (tiles[i].amount) != 'string' ? '$' : '') +
								tiles[i].amount.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

                                tile += tiles[i].hasOwnProperty('story') ? '<a href="' + tiles[i].story + '" class="full-story"><span class="popup">View full story</span></a>' : '';
                                tile += '</div>';
                                tile += '<div class="content">';
                                if (data.type == 'mergers') {
                                    tile += '<div class="target">';
                                    tile += tiles[i].target.hasOwnProperty('image') ? '<img src="' + tiles[i].target.image + '" />' : '';
                                    tile += tiles[i].target.hasOwnProperty('description') ? '<span class="description">' + tiles[i].target.description + '</span>' : '';
                                    tile += '</div>';
                                    tile += '<div class="action">has been acquired by</div>';
                                    tile += '<div class="acquirer">';
                                    tile += tiles[i].acquirer.hasOwnProperty('image') ? '<img src="' + tiles[i].acquirer.image + '" />' : '';
                                    tile += tiles[i].acquirer.hasOwnProperty('description') ? '<span class="description">' + tiles[i].acquirer.description + '</span>' : '';
                                    tile += '</div>';
                                } else if (data.type == 'public') {
                                    tile += '<div class="company">';
                                    tile += tiles[i].company.hasOwnProperty('image') ? '<img src="' + tiles[i].company.image + '" />' : '';
                                    tile += tiles[i].company.hasOwnProperty('description') ? '<span class="description">' + tiles[i].company.description + '</span>' : '';
                                    tile += '</div>';
                                    tile += '<div class="transaction-type">' + tiles[i].transactionType + '</div>';
                                }
                                tile += '</div><div class="date">' + tiles[i].date + '</div></div>';
                            }
                            tile += '</td></tr>';
                            $(tile).appendTo($this);
                            $('a.full-story').unbind('hover').hover(function () {
                                $(this).find('.popup').stop(false, true).fadeIn(100);
                            }, function () {
                                $(this).find('.popup').stop(false, true).delay(200).fadeOut(100);
                            });
                            $hasStory = $('.featured-case').filter(':not(:has(.popup))');
                            $this.find('#filter-stories').change(function () {
                                $hasStory.toggle();
                            });
                        }
                        _hideOverlay();
                    }
                });
            };
            _sortData = function ($col) {
                $this.find('tr.header th a').not($col).removeClass('desc asc');
                if ($col.hasClass('asc')) {
                    $col.removeClass('asc').addClass('desc');
                } else if ($col.hasClass('desc')) {
                    $col.removeClass('desc').addClass('asc');
                } else {
                    $col.addClass('asc');
                }
                sortOptions.col = $col.attr('rel');
                sortOptions.dir = $col.hasClass('asc') ? 'asc' : $col.hasClass('desc') ? 'desc' : '';
                rows = [];
                $this.find('tr:not(.header, .data-display)').each(function () {
                    rows.push($(this));
                });
                rows.sort(function (a, b) {
                    if (a.find('td:eq(' + sortOptions.col + ')').hasClass("currency")) {
                        if (sortOptions.dir == 'asc')
                            return (a.find('td:eq(' + sortOptions.col + ') span').attr('rel') - b.find('td:eq(' + sortOptions.col + ') span').attr('rel'))
                        else
                            return -(a.find('td:eq(' + sortOptions.col + ') span').attr('rel') - b.find('td:eq(' + sortOptions.col + ') span').attr('rel'))
                    } else {
                        if (a.find('td:eq(' + sortOptions.col + ')').text() < b.find('td:eq(' + sortOptions.col + ')').text())
                            return sortOptions.dir == 'asc' ? -1 : 1;
                        else
                            return sortOptions.dir == 'asc' ? 1 : -1;
                    }
                });

                for (var i in rows) {
                    rows[i].appendTo($this);
                }
                _zebra();
            };
            _loadData(args.type, args.q, DATA_DISPLAY);

        });
    }
})(jQuery);

/////
// replace selects
/////
(function ($) {
    $.fn.replaceSelect = function (args) {
        var defaults = {
    },
			args = $.extend(defaults, args);
    return this.each(function (_i, _item) {
        var $this = $(_item),
				$replacedSelect = $('<span class="select-replace" id="' + $this.attr('id') + '-replaced" rel="' + $this.attr('id') + '" />'),
				lis = '',
				$mainTrigger = $('<a href="#" class="selected">' + $this.find('option:selected').text() + '</a>').appendTo($replacedSelect),
				$dropdown = $('<ul />').appendTo($replacedSelect),
				_hide,
				_show;

        $this.after($replacedSelect);
		$replacedSelect.css('width', $this.outerWidth() + 15);
		$dropdown.css('width', $replacedSelect.outerWidth());
		if ($this.is(':hidden'))  {
			$replacedSelect.hide();
		}
        $this.find('option').each(function () {
//            lis += '<li><a href="#">' + $(this).text() + '</a></li>';
			lis += '<li><a href="#" rel="' +  $(this).val() + '">' + $(this).text() + '</a></li>';
        });
        $this.hide();
        $dropdown.append(lis);
        $replacedSelect.find('> a').click(function (e) {
            if ($dropdown.filter(':animated').length > 0)
                return false;
            if ($dropdown.height() == 0) {
                _show();
            } else {
                _hide();
            }
            e.preventDefault();
            e.stopPropagation();
        });
        $dropdown.find('a').click(function (e) {
			var $option = $(e.currentTarget);
            $replacedSelect.find('> a').text($option.text());
            $replacedSelect.find('a.selected').removeClass('open');
            //$this.val($(this).text());
			$this[0].selectedIndex = $dropdown.find('a').index($option);
			$this.trigger('change');
            _hide();
            e.preventDefault();
            e.stopPropagation();
        });
        _show = function () {
            var h = 0;
            $dropdown.find('li').each(function () {
                h += $(this).outerHeight(true);
            });
            $dropdown.animate({
                height: h,
                opacity: 1
            }, 200);
        };
        _hide = function () {
            $dropdown.animate({
                height: 0,
                opacity: 0
            }, 200);
        };
        $('body').click(function (e) {
            $('.select-replace ul').each(function () {
                if ($(this).height() != 0) {
                    $(this).animate({
                        height: 0,
                        opacity: 0
                    }, 200);
                }
            });
        });
        //custom drop down style toggling

        $replacedSelect.find('a.selected').click(function () {
            $(this).addClass('open');
        });
        // debug
        /*
        $this.show();
        $this.css({
        position: 'absolute',
        right: 5,
        top: 25 * (_i) + 5,
        opacity: 0.75
        });
        */
        // end debug
    });
};
})(jQuery);

(function ($) {
    $.fn.accordion = function (args) {
        var defaults = {
        	speed: 500
        },
	args = $.extend(defaults, args);
        return this.each(function (_i, _item) {
        	var $this = $(_item),
		$triggers = $this.find('li a.accordion-trigger'),
		$content = $this.find('li a.accordion-trigger + .accordion-content');
        	$('<div class="blocker">').appendTo($triggers.parent());
        	$('<div class="return">X</div>').appendTo($triggers);

        	$triggers.each(function () {
        		$(this).click(function (e) {
        			var $this = $(this);
        			// if content block is animating, do nothing
        			if ($content.filter(':animated').length > 0)
        				return false;
        			// if no content is visible
        			if ($content.filter(':visible').length == 0) {
        				// show content block in this
        				$(this).parent().addClass('selected');
        				$(this).next('.accordion-content').slideDown(args.speed);
        				// get blocker in parents (lis) of all triggers that are not this and animate
        				$triggers.not($(this)).parent().find('.blocker').show().animate({
        					'opacity': 0.75
        				}, args.speed);
        			} else {
        				// hide content
        				$(this).parent().removeClass('selected');
        				$content.filter(':visible:not(:animated)').slideUp(args.speed);
        				// fade out blocker and hide it
        				$triggers.not($(this)).parent().find('.blocker').animate({
        					'opacity': 0
        				}, args.speed, function () {
        					$(this).hide();
        				});
        			}
        			e.preventDefault();
        		});
        	});
        });
    };
})(jQuery);

//initialize filter dropdown group custom styling
if ($('#result-filter').length > 0) {
    $('#result-filter').jqTransform();
}

if($('.investment-banking.expertise .right-col').length>0){
    $('.investment-banking .right-col .filter-group').jqTransform();
}
/////
// fancybox related binds
/////
$teamContacts.find('.bio').click(function (e) {
    // this will be replaced with the actual URL of the bio page
    var href = $(this).attr('href');
    //		c(href);
    $.fancybox({
        'content': href,
        'type': 'iframe',
        'padding': 0,
        //			'scrolling': 'no',
        'width': 750,
        'height': 609,
		'autoScale': false
        /*
        for an external page use:
        'content': 'http://www.google.com',
        'type': 'iframe',
        */
    });
    e.preventDefault();
});
$careersContacts.find('.bio').click(function (e) {
    // this will be replaced with the actual URL of the bio page
    var href = $(this).attr('href');
    //		c(href);
    $.fancybox({
        'content': href,
        'type': 'iframe',
        'padding': 0,
        //			'scrolling': 'no',
        'width': 750,
        'height': 609,
		'autoScale': false
        /*
        for an external page use:
        'content': 'http://www.google.com',
        'type': 'iframe',
        */
    });
    e.preventDefault();
});
//	$('.insights .restricted a').fancybox({
//	});
/*
$.fancybox({
'content': $('#fb-request'),
'padding': 20
});
*/
$('#fb-request a.button').click(function (e) {
    // ajax call to submit the email goes here, on success will execute what's below
    $.fancybox($('#fb-confirm'));
    e.preventDefault();
});
$('#fb-confirm a.close').click(function (e) {
    $.fancybox.close();
    e.preventDefault();
});
$('a.request').click(function (e) {
    $.fancybox($($(this).attr('href')));
    e.preventDefault();
});
if ($('a.footer-popup').length > 0) {
    $('a.footer-popup').fancybox();
}
if ($('a.disclaimer-popup').length > 0) {
    $('a.disclaimer-popup').fancybox();
}

});

/* = RESULTS FILTER - simulate HTML5 placeholder attr
--------------------------------------------------------------------------------------------*/ 
$(document).ready(function() {
		$('.filter-group a.resetBtn').show().css('display','block');
		$('.filter-group input').each(function(){
			$(this).val($(this).attr('placeholder'));
		});
		$('.filter-group a.resetBtn').closest('tr').find('input').focus(function(){
			$('.filter-group a.resetBtn').show();
			$('.filter-group a.resetBtn').css('display','block');
			if($(this).val()==$(this).attr('placeholder')){
				$(this).val('');
			}
		});
		$('.filter-group input').blur(function(){
			if($(this).val()==''){
				$('.filter-group a.resetBtn').hide();
				$(this).val($(this).attr('placeholder'));
			}
		});
		
		$('.filter-group a.resetBtn').click(function(){
				var targetInput = $(this).closest('tr').find('input');
				(targetInput).val($(targetInput).attr('placeholder'));
				$(this).hide();
			})
		$('.filter-group a.submit').click(function(){
				$(this).closest('form').submit()
			})

/* = RESULTS FILTER - date picker
--------------------------------------------------------------------------------------------*/
		if($("#datepicker").length >0){
			$("#datepicker").datepicker();
		}
});

/* = IN THE NEWS - add matching input classes to each corresponding fake input element
--------------------------------------------------------------------------------------------*/
$(document).ready(function () {
    if ($('body.news').length > 0) {
        $('.filter-group #CategoryFilter').parent().find('span').addClass('category');
        $('.filter-group #YearFilter').parent().find('span').addClass('year');
    } 
});



/* = IN THE NEWS - query builder
--------------------------------------------------------------------------------------------*/
function rememberNewsDropdowns() {
    var category = queryValues("t=");
    var year = queryValues("f=");
    var keywords = queryValues("q=");
    if (year != undefined) {
        dropdownChanger('#Year', year)
    }
    if (category != undefined) {
        dropdownChanger('#CategoryFilter', category)
    }
    if (year != undefined) {
        dropdownChanger('#YearFilter', year)
    }
    if (keywords != undefined) {
        var newKeywords = keywords.replace('+', ' ');
        $('#result-filter .keywords').val(newKeywords)
    }
}
$(document).ready(function () {
    if ($('body').hasClass('news') && window.location.href.indexOf('?') != -1) {
        rememberNewsDropdowns();
    }
    $('.news #result-filter .submit,.news #result-filter .jqTransformSelectWrapper li a').click(function () {
        newsQuery();
    })
    $('.news #result-filter .keywords').keyup(function (e) {
        //alert(e.keyCode);
        if (e.keyCode == 13 && $(this).val()!="") {
            newsQuery();
        }
    });
    function newsQuery() {
        var currentURL = window.location.pathname;
        var category =
        $('.filter-group #CategoryFilter :selected').val() == '' ? ""
        : "t=" + $('.filter-group #CategoryFilter :selected').val() + "&";
        var year =
        $('.filter-group #YearFilter :selected').val() == '' ? ""
        : "f=" + $('.filter-group #YearFilter :selected').val() + "&";
        var keywords =
        $('.filter-group .keywords').val() == 'Enter Keyword' ? ""
        : "q=" + $('.filter-group .keywords').val().split(' ').join('+');
        var destination =
        category == '' && year == '' && keywords == '' ? currentURL
        : currentURL + "?" + category + year + keywords;
        if (destination.charAt(destination.length - 1) == "&") {
            destination = destination.substring(0, destination.length - 1);
        }

        if (destination != '') {
            window.location = destination
        }
    }
    function setMenuFromQuery() {
        var query = document.location.href.split('?')
        var queryString = query[1]
        var querySections = queryString.split('&')
        var dateFilter =
        queryString.search('f=') != -1 ? queryString.substring(queryString.search('f='), queryString.search('f=') + 3)
        : '';

    }
});


/////
// Investor Annex cookies
/////

/* = EMAIL SIGNUP - financial planning updates
--------------------------------------------------------------------------------------------*/

$(document).ready(function () {
    $('.subscription .form input').each(function () {
        //$(this).attr('name', $(this).attr('id'));
    });
//    $("body.subscription form").attr('onSubmit', 'return validateSignUp()');
    $("body.subscription .form.financial").closest('form').attr('onSubmit', 'return validateFinancial()');
    $('.subscription .form input[type="radio"]').each(function () {
        //$(this).attr('name', $(this).attr('id').substring(0, $(this).attr('id').length - 2));
    });
});

/* = EXPERTISE GRID VIEW - normalize all content item heights - style drop custom downs
--------------------------------------------------------------------------------------------*/

function equalHeight(group) {
    var tallest = 0;
    group.each(function () {
        var thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}
$(document).ready(function () {
    $("a.group").fancybox({
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'speedIn': 600,
        'speedOut': 200,
        'overlayShow': false
    });


    $('.featured-case a.full-story').click(function (e) {
        var href = $(this).attr('href');
        $.fancybox({
            'content': href,
            'type': 'iframe',
            'padding': 0,
            'width': 750,
            'height': 609
        });
        e.preventDefault();
    }); 
});
$(document).ready(function () {
    $('.content-area.data').first().jqTransform();
    $('#content .right-col .resultHeader').jqTransform();
/*
    $('#content .content-area.data .featured-case .company p').filter(function () {
        return $.trim($(this).text()) === ''
    })
    .remove();
    $('.featured-case .company p').each(function () {
        if ($(this).html() == '') {
            $(this).remove();
        }
    })
*/
    equalHeight($("#content .content-area.data .featured-case, .investment-banking #content .content-area .featured-case,  body.news .featured-case"));
    $("#content .content-area .featured-case .content").each(function () {
        $(this).height($(this).parent().height() - 45)
    });

    /* = EXPERTISE LIST VIEW - stripe every other row - reformat content
    --------------------------------------------------------------------------------------------*/
    $('#content .right-col .listview tr:even').addClass('stripe')
    $(".listview th:contains('Target')").width(175);
    $(".listview th:contains('Issuer')").width(125);
    $(".listview th:contains('Location')").width(95);
    $(".listview th:contains('Transaction')").width(130);
    $('.listview img').parent().css('padding', '8px 0');
    if ($('#content .right-col .listview table th').length < 8) {
        $(".listview th:contains('Target')").width(195);
    }
});

/* = EXPERTISE BY INDUSTRY - industry dropdown URL builder - matching featured items content switcher
--------------------------------------------------------------------------------------------*/
function guidSwitcher(a) {
    var guid = $(a).find('a').attr('href');
    guid = guid.substring(5, guid.length);
    var targetSet = "#featured-\\" + guid.slice(0, -1) + "\\" + guid.slice(-1);
    var targetRelated = "#related-\\" + guid.slice(0, -1) + "\\" + guid.slice(-1);
    $('.featured-case.public').parent().hide();
    $('div a:contains("View related")').parent().hide();
	if ($(targetSet).find('div.featured-case').length == 0) {
		$(targetSet).parent().parent().hide();
	} else {
		$(targetSet).parent().parent().show();
	}
    $(targetSet).show();
    $(targetRelated).show();
    return targetSet;
}

$(document).ready(function () {
    $('.investment-banking.expertise .jqTransformSelectWrapper li a').click(function () {
        var destination = window.location.pathname + "?i=" + $('#Industries :selected').val();
        window.location = destination
    });
    if ($('.investment-banking.expertise .tabs-wrapper .tabs-nav li').length > 6) {
        $('.investment-banking.expertise .tabs-wrapper .tabs-nav').addClass('smaller')
    }
    if ($('.investment-banking.expertise #Industries :selected').html() == "Public Finance") {
        $('.tabs-nav').addClass('smaller')
        $('.tabs-nav li').first().width(125);
        $('.tabs-nav li').eq(3).width(90);
        setTimeout("$('.tabs-nav li').first().find('a').removeAttr('style');", 100)
        $('.tabs-nav li').last().width(97);
    }
    $('.featured-case.public').parent().hide();
    $('div a:contains("View related")').parent().hide()
    $('div a:contains("View related")').first().parent().show()
    $('.featured-case.public').first().parent().show();

    $('.investment-banking.expertise .tabs-wrapper .tabs-nav li').each(function () {
        if (($(this).hasClass("selected"))) {
            guidSwitcher($(this))
        }
    })

    $('.investment-banking.expertise .tabs-wrapper .tabs-nav li').mouseup(function () {
        if (!($(this).hasClass("selected"))) {
            guidSwitcher($(this))
        }
    });
    $('#content .right-col .filters .jqTransformSelectWrapper').last().css('margin', 0)
});

/* = EXPERTISE BY TRANSACTIONS - filter and view dropdowns
--------------------------------------------------------------------------------------------*/
function getNewBaseURL() {
    var currentURL = window.location.pathname;
    var splitURL = window.location.href.split('?')
	splitURL[1] = splitURL[1] || 'type=ma&v=l';
    var viewStartsAt = splitURL[1].search('v=')
    var newQuery = splitURL[1].slice(0, viewStartsAt) + splitURL[1].slice(viewStartsAt + 3, splitURL[1].length);
    var newBaseURL = currentURL + "?" + newQuery;
    return newBaseURL;
}
function trimURL(i) {
    var currentURL = window.location.pathname;
    var splitURL = window.location.href.split('?');
	splitURL[1] = splitURL[1] || 'type=ma&v=l';
    var varStartsAt = splitURL[1].search("&" + i);
    var newQuery = varStartsAt == -1 ? splitURL[1]
        : splitURL[1].slice(0, varStartsAt) + splitURL[1].slice(varStartsAt + 4, splitURL[1].length);
    var newBaseURL = currentURL + "?" + newQuery;
    return newBaseURL;
}
function checkStories() {
    var splitURL = window.location.href.split('?');
	splitURL[1] = splitURL[1] || 'type=ma&v=l';
    var newsStoryChecked = window.location.href.indexOf('?') == -1 ? -1
        : splitURL[1].search("&l=1");
    if (newsStoryChecked != -1) {
        $('#transactions #filter-stories').attr('checked', 'checked');
    }
}
function urlBuilder() {
    var currentURL = window.location.pathname;
    var splitURL = window.location.href.split('?');
	splitURL[1] = splitURL[1] || 'type=ma&v=l';
    var viewStartsAt =
        window.location.href.indexOf('?') == -1 ? -1
        : splitURL[1].search('v=');
    var view =
        viewStartsAt == -1 ? "v=l"
        : splitURL[1].substring(viewStartsAt, viewStartsAt + 3) + "&";

    var type =
        $('#FinancingType :selected').val() == '' || $('#FinancingType :selected').val() == undefined ? ""
        : "type=" + $('#FinancingType :selected').val() + "&";
    var year =
        $('.filters #Year :selected').val() == '' ||$('.filters #Year :selected').val()==undefined  ? ""
        : "y=" + $('.filters #Year :selected').val() + "&";
    var target =
        $('.filters #Target :selected').val() == '' ||$('.filters #Target :selected').val() ==undefined ? ""
        : "t=" + $('.filters #Target :selected').val() + "&";
    var sector =
        $('.filters #Sector :selected').val() == '' ||$('.filters #Sector :selected').val() ==undefined ? ""
        : "s=" + $('.filters #Sector :selected').val() + "&";
    var issuer =
        $('.filters #Issuer :selected').val() == '' || $('.filters #Issuer :selected').val() ==undefined  ? ""
        : "i=" + $('.filters #Issuer :selected').val() + "&";
    var company =
        $('.filters #Company :selected').val() == '' ||$('.filters #Company :selected').val()==undefined ? ""
        : "c=" + $('.filters #Company :selected').val() + "&";
    var tenant =
        $('.filters #Tenant :selected').val() =='' ||$('.filters #Tenant :selected').val() ==undefined ? ""
        : "ten=" + $('.filters #Tenant :selected').val() + "&";
    var acquirer =
        $('.filters #Acquirer :selected').val() == '' ||$('.filters #Acquirer :selected').val() ==undefined ? ""
        : "a=" + $('.filters #Acquirer :selected').val() + "&";
    var destination =
        type == '' && year == '' && target == '' && sector == '' && issuer == '' && company == '' && tenant == '' && acquirer == '' ? ""
        : currentURL + "?" + type + year + target + sector + issuer + company + tenant + acquirer + view;
    if (destination.charAt(destination.length - 1) == "&") {
        destination = destination.substring(0, destination.length - 1);
    }
    if (destination != '') {
        window.location = destination
    }
}
function queryValues(i) {
    var splitURL = window.location.href.split('?')
    if (splitURL.length < 2) {
        splitURL[1] = '';
    }
    var varStartsAt = splitURL[1].search(i)
    var nextAnd = splitURL[1].indexOf("&", varStartsAt);
    var varString = 
    nextAnd == -1 ? splitURL[1].substring(varStartsAt, splitURL[1].length)
    : splitURL[1].substring(varStartsAt, nextAnd);
    var splitVar = varString.split('=')
    var varValue = varStartsAt == -1 ? '' : splitVar[1];
    return varValue;
}
function dropdownChanger(t,v) {
    $(t + ' option[value=' + v + ']').attr('selected', 'selected');
    $(t).closest('.jqTransformSelectWrapper').find('span').html($(t +' :selected').html());
}

function rememberDropdowns() {
    var year = queryValues("y=");
    var target = queryValues("t=");
    var sector = queryValues("s=");
    var issuer = queryValues("i=");
    var company = queryValues("c=");
    var tenant = queryValues("ten=");
    var acquirer = queryValues("a=");
    if (year != undefined) {
        dropdownChanger('#Year', year)
    }
    if (company != undefined) {
        dropdownChanger('#Company', company)
    }
    if (target != undefined) {
        dropdownChanger('#Target', target)
    }
    if (sector != undefined) {
        dropdownChanger('#Sector', sector)
    }
    if (issuer != undefined) {
        dropdownChanger('#Issuer', issuer)
    }
    if (tenant != undefined) {
        dropdownChanger('#Tenant', tenant)
    }
    if (acquirer != undefined) {
        dropdownChanger('#Acquirer', acquirer)
    }
}
$(document).ready(function () {
    //fix ie8's overflow:auto problem with the tombstone resized content
    if ($('.investment-banking #content table#transactions').length > 0) {
        $('body').addClass('transactions')
    }
    if ($('body').hasClass('investment-banking') && window.location.href.indexOf('?') != -1) {
        rememberDropdowns();
    }
    $('.investment-banking .jqTransformSelectWrapper ul li a').click(function () {
        urlBuilder();
    });
    $('.investment-banking a.change-view').mousedown(function () {
		var q = document.location.search.substring(1).split('&'),
			foundView = false;
		for (var i = 0; i < q.length; i++) {
			if (q[i].split('=')[0] == 'v') {
				q[i] = (q[i].split('=')[1] == 'l') ? 'v=g' : 'v=l';
				foundView = true;
			}
		}
		q = ('?' + q.join('&'));
		q += foundView ? '' : '&v=g';
		q = q.replace(/&+/g, '&');
//		alert(q);
        $(this).attr('href', q);
    });
    //hide the change view if user views all transaction types
    if (queryValues("type=") == "all") {
        $('a.change-view').parent().hide();
    }
    //fix z-index of the last result filter so it doesn't overlap the others
    $('.resultHeader .jqTransformSelectWrapper').css('z-index', 7);
    //show and hide transactions without stories
    $('#transactions #filter-stories').mouseup(function () {
		var q = document.location.search.substring(1).split('&'),
			foundStories = false;
		for (var i = 0; i < q.length; i++) {
			if (q[i].split('=')[0] == 'l') {
				q[i] = (q[i].split('=')[1] == '1') ? '' : 'l=1';
				foundStories = true;
			}
		}
		q = ('?' + q.join('&'));
		q += foundStories ? '' : '&l=1';
		q = q.replace(/&+/g, '&')
//		alert(q);
		window.location.href = q;
/*
		if (!$(this).is(':checked')) {
			
		} else {

		}
*/
/*
        var destination;
        if (!$(this).is(':checked')) {
            destination = trimURL('l=') + '&l=1';
        } else {
            destination = trimURL('l=');
        }
        window.location.href = destination;
*/
    });
    //re-check the check box if "only items with news stories" query is present
    checkStories()
});

//make about page callout the height of the content
$(document).ready(function () {
    setTimeout(" $('.about .callout').height($('.about #content .single-col').height() - 49)", 500)
		
//    setTimeout("$('.careers .callout').height($('.careers #content').height() - 83)", 500); ;

    $('.about .tabs-wrapper li a').click(function () {
        setTimeout(" $('.about .callout').height($('.about #content .single-col').height() - 49)", 50)
    });

    // bind accordions
    if ($('.accordion').length > 1)
		$('.accordion').accordion();

});


 /* = VALIDATION - defines all the rules and parameters for the validate plugin
--------------------------------------------------------------------------------------------*/

var scrolled;
function standardRules() {
    var rules = {
        errorClass: "invalid",
        errorElement: "span",
        onfocusout: false,
        onkeyup: false,
        onclick: false,
        errorPlacement: function (error, element) {
            if ($(element).is('input[type="radio"]')) {
                error.appendTo($(element).closest('table').closest('tr').prev().find('td'));
                $(element).closest('table').closest('tr').prev().find('td').addClass('invalid')
                error.css('display', 'block');
            } else {
                error.insertAfter(element);
            }
        },
        highlight: function (element, errorClass) {
            if ($('html, body').scrollTop() > 0 && scrolled == true) {
                scrolled = false;
                $('html, body').animate({ scrollTop: 0 }, 'fast')
            }
            $(element).addClass(errorClass);
            $(element).prev().addClass(errorClass);
        },
        unhighlight: function (element, errorClass) {
            $(element).removeClass(errorClass);
            $(element).prev().removeClass(errorClass);
        }
    };
        return rules;
    }

    function validateFormRules() {
        var rules = {
            errorClass: "invalid",
            errorElement: "span",
            onfocusout:false,
            onkeyup: false,
             errorPlacement: function(error, element) {
                if($(element).is('input[type="radio"]')){
                    error.appendTo($(element).closest('table').closest('tr').prev().find('td'));
                    $(element).closest('table').closest('tr').prev().find('td').addClass('invalid')
                    error.css('display','block');
                }else{
                    error.insertAfter(element);
                }             
            },
            highlight: function (element, errorClass) {
                $('html, body').animate({ scrollTop: 0 }, 'fast');
                $(element).addClass(errorClass);
                $(element).prev().addClass(errorClass);
            },
            unhighlight: function (element, errorClass) {
                $(element).removeClass(errorClass);
                $(element).prev().removeClass(errorClass);
            },
            rules: {
                firstName: {
                    required: true
                },
                lastName: {
                    required: true
                },
                email: {
                    required: true,
                    email: true
                },
                zip: {
                    required: true,
                    digits: true,
                    minlength: 5
                },
                currentMember: {
                required: true
            }
        },
        messages: {
            firstName: {
                required: 'Please provide your first name.'
            },
            lastName: {
                required: 'Please provide your last name.'
            },
            email: {
                required: "Please provide your email address.",
                email: "Please provide a valid email address."
            },
            zip: {
                required: "Please provide your zip code.",
                digits: "Please provide a valid zip code.",
                minlength: "Your zip code must be 5 digits."
            },
            currentMember:{
                required: "Please make a selection."
            }
        }
    };
        return rules;
    }

 /*
    function jqValidator() {
//        $("body.subscription form").validate(validateFormRules());
//        valid = $("body.subscription form").valid();
		return;
        return valid;
    }
    function validateSignUp() {
        $("body.subscription form").validate(standardRules());
        $('#firstName').rules("add", { required: true, messages: { required: "Please provide your first name."} });
        $('#lastName').rules("add", { required: true, messages: { required: "Please provide your last name."} });
        $('#company').rules("add", { required: true, messages: { required: "Please provide your company name."} });
        $('#address1').rules("add", { required: true, messages: { required: "Please provide your address."} });
        $('#city').rules("add", { required: true, messages: { required: "Please provide your city of residence."} });
        $('#state').rules("add", { required: true, messages: { required: "Please provide your state."} });
        $('#country').rules("add", { required: true, messages: { required: "Please provide your country."} });
        $('#phone').rules("add", {required: true, messages: { required: "Please provide your phone number."} });
        $('#email').rules("add", {required: true, email:true, messages: { required: "Please provide your email address.", email: "Please provide a valid email address."}});
        $('#emailConfirm').rules("add", { required: true, email:true, equalTo: '#email', messages: { required: "Please re-enter your email address.", equalTo:"Please enter the same email address in both fields.", email:"Please enter the same email address in both fields."} });
        valid = $("body.subscription form").valid();
		if (valid)
			_gaq.push(['_trackEvent', 'Outcome', 'Click', 'Click_Subscription']);
        return valid;
    }
*/
    function validateFinancial() {
        $("body.subscription .form.financial").closest('form').validate(standardRules());
            $('#firstName').rules("add", { required: true, messages: { required: "Please provide your first name."} });
            $('#lastName').rules("add", { required: true, messages: { required: "Please provide your last name."} })
            $('#email').rules("add", {required: true, email:true, messages: { required: "Please provide your email address.", email: "Please provide a valid email address."}});
            $('#zip').rules("add", { required: true, digits: true, minlength: 5, maxlength: 5, messages: { required: "Please provide your zip code.", minlength: "Zip code must be 5 characters", maxlength: "Zip code must be 5 characters"} });
            valid = $("body.subscription .form.financial").closest('form').valid();
			if (valid)
				_gaq.push(['_trackEvent', 'Outcome', 'Click', 'FP_Subscription']);
            return valid;
    }
    function setCookie(name, value, expires, path, domain, secure) {
        path = "/";
        document.cookie= name + "=" + escape(value) +
            ((expires) ? "; expires=" + expires.toGMTString() : "") +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "");
    }

/* = PAPERLESS SIGNUP - validation
--------------------------------------------------------------------------------------------*/
function paperlessRules() {
    var rules = {
        errorClass: "invalid",
        errorElement: "span",
        onkeyup: false,
        errorPlacement: function (error, element) {
            if ($(element).is('input[type="radio"]')) {
                error.appendTo($(element).closest('table').closest('tr').prev().find('td'));
                $(element).closest('table').closest('tr').prev().find('td').addClass('invalid')
                error.css('display', 'block');
            } else {
                error.insertAfter(element);
            }
        },
        highlight: function (element, errorClass) {
            $('html, body').animate({ scrollTop: 0 }, 'fast');
            $(element).addClass(errorClass);
            $(element).prev().addClass(errorClass);
        },
        unhighlight: function (element, errorClass) {
            $(element).removeClass(errorClass);
            $(element).prev().removeClass(errorClass);
        },
        rules: {
            txtFirstName: {
                required: true
            },
            txtLastName: {
                required: true
            },
            txtAdvisor: {
                required: true
            },
            txtEmail: {
                required: true,
                email: true
            }
        },
        messages: {
            firstName: {
                required: 'Please provide your first name.'
            },
            lastName: {
                required: 'Please provide your last name.'
            },
            txtAdvisor: {
                required: "Please provide the name of your financial advisor."
            },
            txtEmail: {
                required: "Please provide your email address.",
                email: "Please provide a valid email address."
            }
        }
    };
    return rules;
}

function jqFormValidator(f, r) {
    $(f).validate(r);
    valid = $(f).valid();
    return valid;
}
function validatePaperless() {
    $('body.paperless form').validate(standardRules());
        $('#txtFirstName').rules("add", { required: true, messages: { required: "Please provide your first name."} });
        $('#txtLastName').rules("add", { required: true, messages: { required: "Please provide your last name."} })
        $('#txtAdvisor').rules("add", { required: true, messages: { required: "Please provide the name of your financial advisor."} });
        $('#txtEmail').rules("add", { required: true, email: true, messages: { required: "Please provide your email address.", email: "Please provide a valid email address."
    }
    })
    valid = $('body.paperless form').valid();
    return valid;
}
$(document).ready(function () {
    $('a#Submit').mousedown(function () {
        scrolled = true;
    });
    if ($('.col-100').hasClass('paperless-signup')) {
        $('body').addClass('paperless')
    }
    $('.paperless form input').each(function () {
        //$(this).attr('name', $(this).attr('id'));
    });
//    $("body.paperless form").attr('onSubmit', 'return validatePaperless()');
    $('.subscription .form input[type="radio"]').each(function () {
        $(this).attr('required', 'required');
        //$(this).attr('name', $(this).attr('id').substring(0, $(this).attr('id').length - 2));
    });
});

function getCookie(name){
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}
function deleteCookie(name, path, domain){
    if (getCookie(name))
    {
        path = "/";
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}
/*
function iaLogin(theForm){
	if (theForm.rememberLogin.checked==true){
		var now = new Date();
		now.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 365);
		setCookie("un", escape(theForm.loginId.value), now);
	} else {
		deleteCookie("un");
	}
	alert('setting cookie: ' + getCookie('un'));
	_gaq.push(['_trackEvent', 'Outcome', 'Click', 'Portal_Login']);
	return (true);
}
*/

