$(document).ready(function () {
        var functions_version = 3;
        //$('#content').prepend('<span style="display:block;">functions.js v ' + functions_version + '</span>');
    });
/****************************************************************************
 * jQuery 1.3.x plugin to shorten styled text to fit in a block, appending
 * an ellipsis ("...", &hellip;, Unicode: 2026) or other text.
 * (Only supports ltr text for now.)
 *
 * This is achieved by placing the text of the 'selected' element (eg. span or
 * div) inside a table and measuring its width. If it's too big to big to fit in
 * the element's parent block it's shortened and measured again until it (and
 * appended ellipsis or text) fits inside the block. A tooltip on the 'selected'
 * element displays the full original text.
 *
 * If the browser supports truncating text using the 'text-overflow:ellipsis'
 * CSS property then that will be used (if the text to append is the default
 * ellipsis).
 *
 * If the text is truncated by the plugin any markup in the text will be
 * stripped (eg: "<a" starts stripping, "< a" does not). This behaviour is
 * dictated by the jQuery .text(val) method.
 * The appended text may contain HTML however (a link or span for example).
 *
 * Usage Example ('selecting' a div with an id of "element"):

	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
	<script type="text/javascript" src="jquery.textTruncate.js"></script>
	<script type="text/javascript">
		$(function() {
			$("#element").textTruncate();
		});
	</script>

 * By default the plugin will use the parent block's width as maximum width and
 * an ellipsis as appended text when truncating.
 *
 * There are three ways of configuring the plugin:
 *
 * 1) Passing a configuration hash as the plugin's argument, eg:

	.textTruncate({
		width: 300,
		tail: ' <a href="#">more</a>',
		tooltip: false
	});

 * 2) Using two optional arguments (deprecated!):
 * width = the desired pixel width, integer
 * tail = text/html to append when truncating
 *
 * 3) By changing the plugin defaults, eg:

	$.fn.textTruncate.defaults.tail = ' <a href="#">more</a>';

 * Note: there is no default width (unless you create one).
 *
 * You may want to set the element's css to {visibility:hidden;} so it won't
 * initially flash at full width.
 *
 *
 * Created by M. David Green (www.mdavidgreen.com) in 2009. Free to use for
 * personal or commercial purposes under MIT (X11) license with no warranty
 *
 * Heavily modified/simplified/improved by Marc Diethelm (http://web5.me/).
 *
****************************************************************************/



(function ($) {

	$.fn.textTruncate = function() {

		var userOptions = {};
		var args = arguments; // for better minification
		var func = args.callee; // dito; and much shorter than $.fn.textTruncate

		if ( args.length ) {

			if ( args[0].constructor == Object ) {
				userOptions = args[0];
			} else if ( args[0] == "options" ) {
				return $(this).eq(0).data("options-truncate");
			} else {
				userOptions = {
					width: parseInt(args[0]),
					tail: args[1]
				};
			}
		}

		this.css("visibility","hidden"); // Hide the element(s) while manipulating them

		// apply options vs. defaults
		var options = $.extend({}, func.defaults, userOptions);


		/**
		 * HERE WE GO!
		 **/
		return this.each(function () {

			var $this = $(this);
			$this.data("options-truncate", options);

			/**
			 * If browser implements text-overflow:ellipsis in CSS and tail is "...", use it!
			 **/
			if ( options.tail == "..." && func._native ) {

				this.style[func._native] = "ellipsis";
				/*var css_obj = {}
				css_obj[func._native] = "ellipsis";
				$this.css(css_obj);*/
				$this.css("visibility","visible");

				return true;
			}

			var width = options.width || $this.parent().width();

			var text = $this.text();
			var textlength = text.length;
			var css = "padding:0; margin:0; border:none; font:inherit;";
			var $table = $('<table style="'+ css +'width:auto;zoom:1;position:absolute;"><tr style="'+ css +'"><td style="'+ css +'white-space:nowrap;">' + options.tail + '</td></tr></table>');
			var $td = $("td", $table);
			$this.html( $table );

			var tailwidth = $td.width();
			var targetWidth = width - tailwidth;

			$td.text( text );

			if ($td.width() > width) {
				if ( options.tooltip ) {
					$this.attr("title", text);
				}

				while ($td.width() >= targetWidth ) {
					textlength--;
					$td.html($td.html().substring(0, textlength)); // .html(val) is faster than .text(val) and we already used .text(val) to strip/escape html
				}

				text = $.trim( $td.html() );
				$this.html( text + options.tail );

			} else {
				$this.html( text );
			}

			this.style.visibility = "visible";

			return true;
		});

		return true;

	};


	var css = document.documentElement.style;
	var _native = false;

	if ( "textOverflow" in css ) {
		_native = "textOverflow";
	} else if ( "OTextOverflow" in css ) {
		_native = "OTextOverflow";
	}

	$.fn.textTruncate._native = _native;


	$.fn.textTruncate.defaults = {
		tail: "&hellip;",
		tooltip: true
	};

})(jQuery);



/**
 * jquery.scrollFollow.js
 * Copyright (c) 2008 Net Perspective (http://kitchen.net-perspective.com/)
 * Licensed under the MIT License (http://www.opensource.org/licenses/mit-license.php)
 * 
 * @author R.A. Ray
 *
 * @projectDescription	jQuery plugin for allowing an element to animate down as the user scrolls the page.
 * 
 * @version 0.4.0 
 * 
 * @requires jquery.js (tested with 1.2.6)
 * @requires ui.core.js (tested with 1.5.2)
 * 
 * @optional jquery.cookie.js (http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/)
 * @optional jquery.easing.js (http://gsgd.co.uk/sandbox/jquery/easing/ - tested with 1.3)
 * 
 * @param speed		int - Duration of animation (in milliseconds)
 * 								default: 500
 * @param offset			int - Number of pixels box should remain from top of viewport
 * 								default: 0
 * @param easing		string - Any one of the easing options from the easing plugin - Requires jQuery Easing Plugin < http://gsgd.co.uk/sandbox/jquery/easing/ >
 * 								default: 'linear'
 * @param container	string - ID of the containing div
 * 								default: box's immediate parent
 * @param killSwitch	string - ID of the On/Off toggle element
 * 								default: 'killSwitch'
 * @param onText		string - killSwitch text to be displayed if sliding is enabled
 * 								default: 'Turn Slide Off'
 * @param offText		string - killSwitch text to be displayed if sliding is disabled
 * 								default: 'Turn Slide On'
 * @param relativeTo	string - Scroll animation can be relative to either the 'top' or 'bottom' of the viewport
 * 								default: 'top'
 * @param delay			int - Time between the end of the scroll and the beginning of the animation in milliseconds
 * 								default: 0
 */



$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});


( function( $ ) {

	
	$.scrollFollow = function ( box, options )
	{ 
		// Convert box into a jQuery object
		box = $( box );
		
		// 'box' is the object to be animated
		var position = box.css( 'position' );
		
		function ani()
		{		
			// The script runs on every scroll which really means many times during a scroll.
			// We don't want multiple slides to queue up.
			box.queue( [ ] );
		
			// A bunch of values we need to determine where to animate to
			var viewportHeight = parseInt( $( window ).height() );	
			var pageScroll =  parseInt( $( document ).scrollTop() );
			var parentTop =  parseInt( box.cont.offset().top );
			var parentHeight = parseInt( box.cont.attr( 'offsetHeight' ) );
			var boxHeight = parseInt( box.attr( 'offsetHeight' ) + ( parseInt( box.css( 'marginTop' ) ) || 0 ) + ( parseInt( box.css( 'marginBottom' ) ) || 0 ) );
			var aniTop;
			
			// Make sure the user wants the animation to happen
			if ( isActive )
			{
				// If the box should animate relative to the top of the window
				if ( options.relativeTo == 'top' )
				{
					// Don't animate until the top of the window is close enough to the top of the box
					if ( box.initialOffsetTop >= ( pageScroll + options.offset ) )
					{
						aniTop = box.initialTop;
					}
					else
					{
						aniTop = Math.min( ( Math.max( ( -parentTop ), ( pageScroll - box.initialOffsetTop + box.initialTop ) ) + options.offset ), ( parentHeight - boxHeight - box.paddingAdjustment ) );
					}
				}
				// If the box should animate relative to the bottom of the window
				else if ( options.relativeTo == 'bottom' )
				{
					// Don't animate until the bottom of the window is close enough to the bottom of the box
					if ( ( box.initialOffsetTop + boxHeight ) >= ( pageScroll + options.offset + viewportHeight ) )
					{
						aniTop = box.initialTop;
					}
					else
					{
						aniTop = Math.min( ( pageScroll + viewportHeight - boxHeight - options.offset ), ( parentHeight - boxHeight ) );
					}
				}
				
				// Checks to see if the relevant scroll was the last one
				// "-20" is to account for inaccuracy in the timeout
				if ( ( new Date().getTime() - box.lastScroll ) >= ( options.delay - 20 ) )
				{
					box.animate(
						{
							top: aniTop
						}, options.speed, options.easing
					);
				}
			}
		};
		
		// For user-initiated stopping of the slide
		var isActive = true;
		
		if ( $.cookie != undefined )
		{
			if( $.cookie( 'scrollFollowSetting' + box.attr( 'id' ) ) == 'false' )
			{
				var isActive = false;
				
				$( '#' + options.killSwitch ).text( options.offText )
					.toggle( 
						function ()
						{
							isActive = true;
							
							$( this ).text( options.onText );
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), true, { expires: 365, path: '/'} );
							
							ani();
						},
						function ()
						{
							isActive = false;
							
							$( this ).text( options.offText );
							
							box.animate(
								{
									top: box.initialTop
								}, options.speed, options.easing
							);	
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), false, { expires: 365, path: '/'} );
						}
					);
			}
			else
			{
				$( '#' + options.killSwitch ).text( options.onText )
					.toggle( 
						function ()
						{
							isActive = false;
							
							$( this ).text( options.offText );
							
							box.animate(
								{
									top: box.initialTop
								}, 0
							);	
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), false, { expires: 365, path: '/'} );
						},
						function ()
						{
							isActive = true;
							
							$( this ).text( options.onText );
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), true, { expires: 365, path: '/'} );
							
							ani();
						}
					);
			}
		}
		
		// If no parent ID was specified, and the immediate parent does not have an ID
		// options.container will be undefined. So we need to figure out the parent element.
		if ( options.container == '')
		{
			box.cont = box.parent();
		}
		else
		{
			box.cont = $( '#' + options.container );
		}
		
		// Finds the default positioning of the box.
		box.initialOffsetTop =  parseInt( box.offset().top );
		box.initialTop = parseInt( box.css( 'top' ) ) || 0;
		
		// Hack to fix different treatment of boxes positioned 'absolute' and 'relative'
		if ( box.css( 'position' ) == 'relative' )
		{
			box.paddingAdjustment = parseInt( box.cont.css( 'paddingTop' ) ) + parseInt( box.cont.css( 'paddingBottom' ) );
		}
		else
		{
			box.paddingAdjustment = 0;
		}
		
		// Animate the box when the page is scrolled
		$( window ).scroll( function ()
			{
				// Sets up the delay of the animation
				$.fn.scrollFollow.interval = setTimeout( function(){ ani();} , options.delay );
				
				// To check against right before setting the animation
				box.lastScroll = new Date().getTime();
			}
		);
		
		// Animate the box when the page is resized
		$( window ).resize( function ()
			{
				// Sets up the delay of the animation
				$.fn.scrollFollow.interval = setTimeout( function(){ ani();} , options.delay );
				
				// To check against right before setting the animation
				box.lastScroll = new Date().getTime();
			}
		);

		// Run an initial animation on page load
		box.lastScroll = 0;
		
		ani();
	};
	
	$.fn.scrollFollow = function ( options )
	{
		options = options || {};
		options.relativeTo = options.relativeTo || 'top';
		options.speed = options.speed || 500;
		options.offset = options.offset || 0;
		options.easing = options.easing || 'swing';
		options.container = options.container || this.parent().attr( 'id' );
		options.killSwitch = options.killSwitch || 'killSwitch';
		options.onText = options.onText || 'Turn Slide Off';
		options.offText = options.offText || 'Turn Slide On';
		options.delay = options.delay || 0;
		
		this.each( function() 
			{
				new $.scrollFollow( this, options );
			}
		);
		
		return this;
	};

	$.fn.loadHelp = function(screen) {
		$.ajax( {
			url : 'help.html',
			cache : false,
			context : $('#context_help'),
			data : screen,
			success : function(data) {
				$(this).html(data);
			},
			error : function(o, s, e) {
				$(this).html('');
			}
		});
	};
	
})( jQuery );

function constrain(text, ideal_width, className){
	var temp_item = ('<span class="'+className+'_hide" style="display:none;">'+ text +'</span>');
    $('body').append($(temp_item));
    var item_width = $('span.'+className+'_hide').width();
    var ideal = parseInt(ideal_width);
    var smaller_text = text;

    if (item_width>ideal_width){
        while (item_width > ideal) {
            smaller_text = smaller_text.substr(0, (smaller_text.length-5));
            $('span.'+className+'_hide').html(smaller_text);
            item_width = $('span.'+className+'_hide').width();
        }
        smaller_text = smaller_text + '&hellip;';
    }
    $('span.'+className+'_hide').remove();
    return smaller_text;
}

    (function ($) {
        var default_settings = {};
        var pluggin_name = 'et_message';
        $.fn[pluggin_name] = function (options) {
            var settings = $.extend({}, default_settings, options);
            return this.each(function () {
                var message_div = $(this);
                var api = message_div.data(pluggin_name);
                if (!api) {
                    api = {
                        add : function (msg, type_class) {
                            var new_message;
                            type_class = (type_class) ? ' ' + type_class : '';
                            new_message = $('<div class="message' + type_class + '"><div><div><div><div class="content">' + msg + ' <a class="hide">hide</a></div></div></div></div></div>');
                            message_div.append(new_message);
                            return new_message;
                        },
                        clear : function () {
                            message_div.empty();
                        },
                        clearAndAdd : function (msg, type_class) {
                            this.clear();
                            return this.add(msg, type_class);
                        },
                        get : function () {
                            return message_div.find('.message');
                        }
                    };
                    message_div.delegate('a.hide', 'click', statusHideScript);
                    message_div.data(pluggin_name, api);
                }
            });
        };
    })(jQuery);
    var status_messages;
    $(document).ready(function () {
        status_messages = $('#message_area').et_message().data('et_message');
        if (!status_messages || typeof status_messages.clearAndAdd !== 'function') {
            status_messages = {
                add : function () {},
                clear : function () {},
                clearAndAdd : function () {},
                get : function () {}
            };
        }
    });
    function statusHideScript () {
        var message = $(this).closest('.message');
        if (jQuery.support.cssFloat) {
            message.animate({
                opacity : 0
            }, function () {
                $(this).css('overflow', 'hidden').animate({
                    height : 0,
                    margin : 0
                }, function () {
                    $(this).remove();
                });
            });
        } else {
            message.remove();
        }
    }
    function AttachStatusHideScript () {
        $('.message .hide').click(statusHideScript);
    }
    function GetErrorDiv (msg, flag) {
        // if nothing passed in or non bool then default to true else use what was passed in
        if (typeof(flag) == "undefined" || typeof(flag) != "boolean") {
            flag = true;
        }
        return "<div class='message error'><div><div><div><div class='content'>" + msg + (flag ? "<a class='hide'>hide</a>" : "") + "</div></div></div></div></div>";
    }
    function GetSuccessDiv (msg, flag) {
        // if nothing passed in or non bool then default to true else use what was passed in
        if (typeof(flag) == "undefined" || typeof(flag) != "boolean") {
            flag = true;
        }
        return "<div class='message check'><div><div><div><div class='content'>" + msg + (flag ? "<a class='hide'>hide</a>" : "") + "</div></div></div></div></div>";
    }

function GetQueryStringParameter(ji)
{
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++)
	{
		ft = gy[i].split("=");
		if (ft[0] == ji)
		{
			return ft[1];
		}
	}
	return "";
}

if(typeof jQuery != 'undefined') {
	
	(function($) {
		
		$.fn.popupWindow = function(instanceSettings){
			
			return this.each(function(){
			
			$(this).click(function(){
			
			$.fn.popupWindow.defaultSettings = {
				centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
				centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
				height:500, // sets the height in pixels of the window.
				left:0, // left position when the window appears.
				location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
				menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
				resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
				scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
				status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
				width:500, // sets the width in pixels of the window.
				windowName:null, // name of window set from the name attribute of the element that invokes the click
				windowURL:null, // url used for the popup
				top:0, // top position when the window appears.
				toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
			};
			
			settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});
			
			var windowFeatures =    'height=' + settings.height +
									',width=' + settings.width +
									',toolbar=' + settings.toolbar +
									',scrollbars=' + settings.scrollbars +
									',status=' + settings.status + 
									',resizable=' + settings.resizable +
									',location=' + settings.location +
									',menuBar=' + settings.menubar;
	
					settings.windowName = this.name || settings.windowName;
					settings.windowURL = this.href || settings.windowURL;
					var centeredY,centeredX;
				
					if(settings.centerBrowser){
							
						if ($.browser.msie) {//hacked together for IE browsers
							centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
							centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
						}else{
							centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
							centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
						}
						window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
					}else if(settings.centerScreen){
						centeredY = (screen.height - settings.height)/2;
						centeredX = (screen.width - settings.width)/2;
						window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
					}else{
						window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();	
					}
					return false;
				});
				
			});	
		};
		
		$.ajaxSetup({
			beforeSend: function() {
				
			},
			complete: function() {
				 $("#loader").hide();
			}
		});
	})(jQuery);

	$(function() {
		
		$('body').addClass('jsenabled');
		$('th:last-child').addClass('last');
		// special treatment for IE 7
		if(!(jQuery.support.hrefNormalized)) {
			$('.button:not(.buttons .button)').wrap('<div style="text-align: center" />');
			//$('#notifications .messages > li:last-child').css('display','none');
		}
		// end special treatment for IE 7
		// replace submit and reset buttons with custom elements for better styling
		$('input[type=submit], input[type=reset]').each(function() {
			var inpVal = $(this).attr('value');
			if($(this).is(':submit')) {
				$(this).replaceWith('<a class="button submit">'+inpVal+'</a>');
			}
			else {
				$(this).hide().after('<a class="button reset">'+inpVal+'</a>');
			}
		});
		$('.button, button[type=submit], button[type=reset]').contents().wrap('<span />');
		// enable usual button functionality
		$('.button.submit').live('click',function() {
			$(this).closest('form').submit();
			return false;
		});
		$('.button.reset').live('click',function() {
			$(this).prev().click();
			return false;
		});
		$('.button.disabled').live('click',function() {return false;});
		$('input[type=text]:not(#s_input,#email_list_from_date,#email_list_to_date,#username,#num_days,#txtReminderDays,.nowrap)').wrap('<span class="input_text" />');
		$('input[type=password]:not(#password)').wrap('<span class="input_password" />');
		$('textarea').not('.emailEditor').wrap('<div class="textarea"><div><div><div></div></div></div></div>');
		
		// notification widget funcionality
			// pagination
		var items = $('#notifications .messages > li').length;
		if(items > 1) {
			$('#notifications .messages > li:first-child').addClass('current');
			var index = $('.current').index()+1;
			var pagination = '<div class="viewing"><a class="prev">&lt;</a><span>Viewing <span class="index">'+index+'</span> of ' + items + '</span><a class="next">&gt;</a></div>';
			$('#notifications').append(pagination);
			$('.viewing .prev').addClass('disabled').click(function() {
				$(this).siblings('.next').removeClass('disabled');
				if(index > 1) {
					$('#notifications .current').fadeOut('fast',function() {
						$(this).removeClass('current').prev().addClass('current').fadeIn('fast');
					});
					$(this).removeClass('disabled');
					$('.viewing .index').text(index-=1);
				}
				if(index == 1) {
					$(this).addClass('disabled');
				}
			});
			$('.viewing .next').click(function() {
				$(this).siblings('.prev').removeClass('disabled');
				if(index < items) {
					$('#notifications .current').fadeOut('fast',function() {
						$(this).removeClass('current').next().addClass('current').fadeIn('fast');
					});
					$(this).removeClass('disabled');
					$('.viewing .index').text(index+=1);
				}
				if (index == items) {$(this).addClass('disabled');}
			});
		}
			// cut off email notification text
		var message = $('#notifications .email a').text();
		$('#notifications .email a').text(message.substr(0,23)+'\u2026');
		$('#header #notifications .messages > li').click(function() {
			var link = $(this).find('a').attr('href');
			window.location.href = link;
		});
		$('#header #notifications .messages > li').hover(function() {
			var link = $(this).find('a').attr('href');
			window.status = link;
		},function() {
			window.status = '';
		});
		//$('#header #notifications li a').click(function() {return false;});
		$('#header #mainnav li:last-child').addClass('last');
		
		$('.section, .message:not(#overview_contacts .message)').each(function() {
			if (!$(this).hasClass('unbox')) {
				$(this).contents().wrapAll('<div><div><div><div class="content"></div></div></div></div>');
			}
		});
		$('.message:not(.email) .content, #messages > .message:not(.email) .content').append('<a class="hide">hide</a>');
		$('.message .hide').click(function() {
			if(jQuery.support.cssFloat) {
				$(this).closest('.message').animate({
					opacity: 0
				},function() {
					$(this).css('overflow','hidden').animate({
						height: 0,
						margin: 0
					},function() {
						$(this).remove();
					});
				});
			}
			else {
				$(this).closest('.message').remove();
			}
		});
		$('.section.sub:last-child').addClass('last');
		
		// overlay functionality
		if(jQuery().overlay) {
			// create generic overlay function - page variable is the body class (or any specific CSS selector), â€œtriggerâ€� is the ID of the element to be loaded inside the overlay
			function invokeOverlay(page, trigger) {
				if($('body').is(page)) {
					$('body:has(a[rel="overlay"])').append('<div id="overlay" class="'+trigger+'"><div class="overlay_content"></div></div>');
	            }
				
				var relValue =$('a[rel="overlay"]').attr('rel');
				$(page + ' a[rel="overlay"]').attr('rel', '#' + relValue).overlay({
				    closeOnClick: false,
					mask: {
						color: 'black',
						opacity: 0.5
					},
					onBeforeLoad: function() {
						var overlay = this.getOverlay();
						var wrap = overlay.find('.overlay_content');
						wrap.load(this.getTrigger().attr("href")+' #'+trigger, function() {
							overlay.append('<a class="bottom" />').find('.overlay_content > .style1').removeClass('style1');
							overlay.find('.sub').contents().wrapAll('<div><div><div><div class="content"></div></div></div></div>');
							overlay.find('.button').contents().wrap('<span />');
							var inpVal = overlay.find('input[type=submit]').attr('value');
							overlay.find('input[type=submit]').replaceWith('<a class="button submit"><span>'+inpVal+'</span></a>');
							// special treatment for all versions of IE (up until v.8 at time of writing)
							if(!(jQuery.support.cssFloat)) {$('#'+trigger).addClass('ie');}
							// end special treatment
							var viewportHeight = $(window).height();
		  				var overlayHeight = overlay.height();
		  				overlay.css({top: (viewportHeight/2)-(overlayHeight/2)+'px'});
			      	    var inp = overlay.find('input[type=radio]');
			      	    inp.change(function() {
			      		    if($(this).is(':checked')) {
			      			    $(this).closest('label').addClass('selected');
			      			    $(this).closest('li').siblings().find('label').removeClass('selected');
			      		    }
			      	    });
						});
					},
					onLoad: function() {
							var cancel = this.getOverlay().find('.cancel');												
							var trigger = this.getTrigger();
							cancel.live("click", function() {
								trigger.overlay().close();
								return false;
							});
							$('#delete_contact_form .delete').live("click",function() {
								$.ajax({
									type: "POST",
									url: "contacts-delete.html",
									data: "delete_key="+$('#delete_key').val(),
									success: function(msg){
											top.location.href = $('#delete_ref').val();
										}
								});
							});
						}
				});
			}
			// actually invoke overlays 
            // this method is being deprecated, see overlay.js
			invokeOverlay('.dashboard','industry');
		    invokeOverlay('.contacts_import','example_spreadsheet');
		    invokeOverlay('.settings.upgrade_plan', 'upgrade_plan');
		    invokeOverlay('.contacts', 'confirm_delete_user');
		}
		// end overlay functionality
		
		//standard search input values
		if(jQuery().defaultvalue) {
			$('.contacts form.search #s_input').not('#s_input[value]').defaultvalue('Search Email Addresses');
			$('.emails form.search #s_input').not('#s_input[value]').defaultvalue('Search Emails');
			$('.segments form.search #s_input').not('#s_input[value]').defaultvalue('Search Segments');
			$('.importLists form.search #s_input').not('#s_input[value]').defaultvalue('Search Lists');
            $('.exports form.search #s_input').not('#s_input[value]').defaultvalue('Search Exports');
			if ($('.contacts form.search #s_input').val()=='Search Email Addresses' || $('.emails form.search #s_input').val()=='Search Emails' || $('.segments form.search #s_input').val()=='Search Segments' || $('.importLists form.search #s_input').val()=='Search Lists') {
				$('.emails form.search input[type=image],.contacts form.search input[type=image],.segments form.search input[type=image],.importLists form.search input[type=image]').attr('src', 'img/search_submit2.png');
				$('.emails form.search input[type=image],.contacts form.search input[type=image],.segments form.search input[type=image],.importLists form.search input[type=image]').attr('class', 'btnDisabled');
				$('.emails form.search input[type=image],.contacts form.search input[type=image],.segments form.search input[type=image],.importLists form.search input[type=image]').attr('disabled', 'disabled');
			}
			$('#ta_emails').defaultvalue('Type or paste multiple addresses in this field. Separate multiple email addresses with a comma, e.\u00A0g. john.doe@email.com, jane.doe@email.com.');
			
			$('.emails form.search #s_input,.contacts form.search #s_input,.segments form.search #s_input,.importLists form.search #s_input').bind("keyup",
		        function(event) {
					if ($(this).val()) {
						$('.emails form.search input[type=image],.contacts form.search input[type=image],.segments form.search input[type=image],.importLists form.search input[type=image]').attr('src','img/search_submit.png');
						$('.emails form.search input[type=image],.contacts form.search input[type=image],.segments form.search input[type=image],.importLists form.search input[type=image]').attr('class','');
						$('.emails form.search input[type=image],.contacts form.search input[type=image],.segments form.search input[type=image],.importLists form.search input[type=image]').attr('disabled','');
					}
			});
			
			$('.emails form.search #s_input,.contacts form.search #s_input,.segments form.search #s_input,.importLists form.search #s_input').bind("blur",
		        function(event) {
					if ($(this).val()=='') {
						$('.emails form.search input[type=image],.contacts form.search input[type=image],.segments form.search input[type=image],.importLists form.search input[type=image]').attr('src','img/search_submit2.png');
						$('.emails form.search input[type=image],.contacts form.search input[type=image],.segments form.search input[type=image],.importLists form.search input[type=image]').attr('class','btnDisabled');
						$('.emails form.search input[type=image],.contacts form.search input[type=image],.segments form.search input[type=image],.importLists form.search input[type=image]').attr('disabled','disabled');
						$('.emails form.search #s_input').not('#s_input[value]').defaultvalue('Search Emails');
						$('.contacts form.search #s_input').not('#s_input[value]').defaultvalue('Search Email Addresses');
						$('.segments form.search #s_input').not('#s_input[value]').defaultvalue('Search Segments');
						$('.importLists form.search #s_input').not('#s_input[value]').defaultvalue('Search Lists');
					}
			});
		
		}
		
		// activity filter slider functionality
		if(jQuery().slider) {
			$('.filter .activity .content').empty().append('<div class="slider" />');
			var bars = ['bar1','bar2','bar3','bar4','bar5'];
			$.each(bars,function(){
				$('<div id="'+this+'" class="bars" />').appendTo('.filter .activity .slider');
			});
			$('.filter .activity .slider').append('<span class="val" style="bordeer: 1px solid red; position: absolute; z-index: 10;" />');
			$('.filter .activity .slider').slider({
				range: true,
				min: 0,
				max: 5,
				values: [0,5],
				step: 1,
				slide: function(event, ui) {
					if (ui.values[1]-ui.values[0] < 1){return false;}
					switch(ui.values[0]) {
						case 0:
							$('#bar1').css('background-position','-12px 0');
							break;
						case 1:
							$('#bar1').css('background-position','0 0');
							$('#bar2').css('background-position','-12px 0');
							break;
						case 2:
							$('#bar1,#bar2').css('background-position','0 0');
							$('#bar3').css('background-position','-12px 0');
							break;
						case 3:
							$('#bar1,#bar2,#bar3').css('background-position','0 0');
							$('#bar4').css('background-position','-12px 0');
							break;
						case 4:
							$('#bar1,#bar2,#bar3,#bar4').css('background-position','0 0');
							$('#bar5').css('background-position','-12px 0');
							break;
					}
					switch(ui.values[1]) {
						case 1:
							$('#bar2,#bar3,#bar4, #bar5').css('background-position','0 0');
							break;
						case 2:
							$('#bar2').css('background-position','-12px 0');
							$('#bar3,#bar4, #bar5').css('background-position','0 0');
							break;
						case 3:
							$('#bar3').css('background-position','-12px 0');
							$('#bar4, #bar5').css('background-position','0 0');
							break;
						case 4:
							$('#bar4').css('background-position','-12px 0');
							$('#bar5').css('background-position','0 0');
							break;
						case 5:
							$('#bar5').css('background-position','-12px 0');
							break;
					}
				}
			});
		}
		// end slider functionality

		
		//scroll follow functionality for resources sidebar
			/*$(window).scroll(function() {
		        var dynamicSidebarHeight = $('.scroll_follow').height();
		
		        if ($(window).height() > dynamicSidebarHeight) {
		            var fixedFooterOffset = 304;
		            var scrollTo = $(window).scrollTop()
		            var calculatedMaxTop = $('#footer').offset().top - dynamicSidebarHeight - fixedFooterOffset;
		            var fixedHeaderOffset = 150;
		
		            if (scrollTo > calculatedMaxTop) {
		                scrollTo = calculatedMaxTop;
		            }
		            else if (scrollTo < fixedHeaderOffset) {
		                scrollTo = 0;
		            }
		            else
		            {
		                scrollTo -= fixedHeaderOffset - 18; //18 is for a top margin
		            }
		
		            $('.scroll_follow')
		            .animate(
		                { top: scrollTo + 'px' },
		                { queue: false, duration: 500}
		            );
		        }
		    });
	
		*/
		//rounded corners for incorrectly added email addresses
		$('#enter_contacts.incorrect').removeAttr("id").removeClass("incorrect").wrap('<div id="enter_contacts" class="incorrect"><div><div></div></div></div>');
		
		//hide/reveal extra plans
		$('#list_plans .more').hide();
		$('#list_plans #more_link a').click( function() {
			$('#list_plans .more').fadeIn();
			$(this).parent().remove();
		});
		
		//input checks for plan upgarde sign-up forms
		$('#settings_plan, #user_details, #segment_details').submit( function() {
			return checkUserSignup($(this));												 
		});
		
		function checkUserSignup(m) {
			
			var passed = true;
			
			$('input.req, select.req, textarea.req').each(function() {
				var val = $.trim($(this).val());
				if (val.length == 0) {
					
					if ($(this).closest('.box.incorrect').length == 0) {
						$(this).closest('.box').removeClass('box').wrap('<div class="box incorrect"><div><div><div></div></div></div></div>');
						$(this).closest('.box').append('<span class="warning">Required field.</span>');
					} else {
						$(this).closest('.box').find('.warning').html("Required field.");
					}
					passed = false;
					
				} else if ($(this).hasClass('email') && !val.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
					
					if ($(this).closest('.box.incorrect').length == 0) {
						$(this).closest('.box').removeClass('box').wrap('<div class="box incorrect"><div><div><div></div></div></div></div>');
						$(this).closest('.box').append('<span class="warning">Email invalid.</span>');
					} else {
						$(this).closest('.box').find('.warning').html("Email invalid.");
					}
					passed = false;
					
/*				} else if ($(this).hasClass('name') && !val.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
					
					if ($(this).closest('.box.incorrect').length == 0) {
						$(this).closest('.box').removeClass('box').wrap('<div class="box incorrect"><div><div><div></div></div></div></div>');
						$(this).closest('.box').append('<span class="warning">Alphabetic characters only.</span>');
					} else {
						$(this).closest('.box').find('.warning').html("Alphabetic characters only.");
					}
					passed = false;
					
				} else if ($(this).hasClass('num') && !val.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
					
					if ($(this).closest('.box.incorrect').length == 0) {
						$(this).closest('.box').removeClass('box').wrap('<div class="box incorrect"><div><div><div></div></div></div></div>');
						$(this).closest('.box').append('<span class="warning">Numbers only.</span>');
					} else {
						$(this).closest('.box').find('.warning').html("Numbers only.");
					}
					passed = false;
					
				} else if ($(this).hasClass('street') && !val.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
					
					if ($(this).closest('.box.incorrect').length == 0) {
						$(this).closest('.box').removeClass('box').wrap('<div class="box incorrect"><div><div><div></div></div></div></div>');
						$(this).closest('.box').append('<span class="warning">Alpha-numeric only.</span>');
					} else {
						$(this).closest('.box').find('.warning').html("Alpha-numeric only.");
					}
					passed = false;
*/	
				} else if ($(this).hasClass('zip') && (val.lenght <= 50)) {
					// !val.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/)
					// Canadian or US zips (^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)
					// US zips ^\d{5}(-\d{4})?$  or /^\d{5}([\-]\d{4})?$/
					// Canadian zips ^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$
					// Australian zips (0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2}) 



					if ($(this).closest('.box.incorrect').length == 0) {
						$(this).closest('.box').removeClass('box').wrap('<div class="box incorrect"><div><div><div></div></div></div></div>');
						$(this).closest('.box').append('<span class="warning">Zip invalid.</span>');
					} else {
						$(this).closest('.box').find('.warning').html("Zip invalid.");
					}
					
					passed = false;
				
				} else {
					
					if ($(this).closest('.box.incorrect').length != 0) {
						$(this).closest('.box.incorrect > div > div > div > div').unwrap().unwrap().unwrap().unwrap().removeClass('incorrect').addClass('box');
						$(this).closest('.box').siblings('.warning').remove();
		            }
		            if ($(this).closest('.box.incorrectBig').length != 0) {
		                $(this).closest('.box.incorrectBig > div > div > div > div').unwrap().unwrap().unwrap().unwrap().removeClass('incorrectBig').addClass('box');
		                $(this).closest('.box').siblings('.warning').remove();
		            }
				}
		    });

		    $('input.password').each(function () {
		        if ($(this).closest('.box.incorrect').length != 0) {
		            $(this).closest('.box.incorrect > div > div > div > div').unwrap().unwrap().unwrap().unwrap().removeClass('incorrect').addClass('box');
		            $(this).closest('.box').siblings('.warning').remove();
		        }
		        if ($(this).closest('.box.incorrectBig').length != 0) {
		            $(this).closest('.box.incorrectBig > div > div > div > div').unwrap().unwrap().unwrap().unwrap().removeClass('incorrectBig').addClass('box');
		            $(this).closest('.box').siblings('.warning').remove();
		        }
		    });
			
			return passed;
		}
		
		// email list datepickers
		if(jQuery().datepicker) {
			$.datepicker.setDefaults({
				showOtherMonths: true, 
		   		selectOtherMonths: true, 
				dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
				dateFormat: 'MM d, yy',
				constrainInput: true				
			});		
			if($("#email_list_from_date").length != 0 && $("#email_list_from_date").attr("disabled")!="disabled") {
				$("#email_list_from_date").datepicker( {
					onSelect: function(dateText, inst) {
						$("#email_list_to_date").datepicker("option", "minDate", dateText);
					}, 
					maxDate:  new Date()
				});
				//$("#email_list_from_date").datepicker("setDate", "September 1, 2009");
			}
			if($("#email_list_to_date").length != 0 && $("#email_list_to_date").attr("disabled")!="disabled") {
				$("#email_list_to_date").datepicker( {
					onSelect: function(dateText, inst) {
						$("#email_list_from_date").datepicker("option", "maxDate", dateText);
					},
					minDate: $("#email_list_from_date").datepicker("getDate")
				});				
				//$("#email_list_to_date").datepicker("setDate", new Date());				
			}
			
		}
		
		if ($(".box_style1").length != 0) {
			$(".box_style1").wrapInner('<span class="box_style1_inner"></span>');
		}
		
		function subjectEditor(){
			$('.button.submit').click(function(){
				if ($(this).closest('.subject_editor').hasClass('empty_subject')) {
					return false;
				}
				else{
					window.location.href = $('form').attr('action');
				}
			});
			
			$("#email_subject").focus(function(){
				if ($(this).closest('.subject_editor').hasClass('empty_subject')) {
					$(this).val("");
				}
			});
			
			$("#email_subject").blur(function(){
				if (!$(this).val()) {
					$("#email_subject").val("Add subject line...");
					if (!$(this).closest('.subject_editor').hasClass('empty_subject')) {
						$(this).closest('.subject_editor').addClass('empty_subject');
					}
				}
			});
			
			$("#email_subject").bind("keyup",function(event) {
				var associatedFields = $(this).closest('.subject_editor');
				if ($(this).val()) {
					$(associatedFields).removeClass('empty_subject');
				}
			});
		}
		
		
		if ($(".replaceWrap").length != 0) {
			$(".replaceWrap").each( function(){
				var replaceWrap = $(this);
				var replaceTarget = $(replaceWrap).find('.replaceTarget');
				var replaceSource = $(this).find('.replaceSource');

				$(replaceWrap).find('.replaceSource').hide();
				$(replaceTarget).find('.replacer').click(function(){
					$(replaceTarget).replaceWith($('.replaceSource'));
					$(replaceWrap).find('.replaceSource').show();
					subjectEditor();
				});
				
				$('.replaceCancel').click(function(){
					$('.replaceSource').replaceWith($(replaceTarget));
				});
			});
		}
		
		/* toggles the visibility of div.contentSet# if input.rdoActivateSet# is checked */
		if ($("input.rdoActivateSet1").length) {
			
			$("div.fieldToggleWrap").each(function(){
				var v_contentSet1 = $(this).find('div.contentSet1');
				var v_contentSet1_parent = $(v_contentSet1).parent();
				var v_contentSet2 = $(this).find('div.contentSet2');
				var v_contentSet2_parent = $(v_contentSet2).parent();
				var toggleContentTarget = $(this);
				var v_rdoActivateSet1 = $(this).find("input.rdoActivateSet1");
				var v_rdoActivateSet2 = $(this).find("input.rdoActivateSet2");
				if ($(v_rdoActivateSet2).is(':checked')) {
					$(v_rdoActivateSet2).attr('defaultChecked', true);
					$(v_contentSet2).show();
					$(v_contentSet1).hide();
				}
				
				else if ($(v_rdoActivateSet1).is(':checked')) {
					$(v_contentSet2).hide();
					$(v_contentSet1).show();
					$(v_rdoActivateSet1).attr('defaultChecked',true);
				}
				
				else{
				    $(v_contentSet2).hide();
					$(v_contentSet1).show();
					$(v_rdoActivateSet1).attr('checked', true);
					$(v_rdoActivateSet1).attr('defaultChecked', true);
				}
				
				$(v_rdoActivateSet2).each(function(){
					$(this).bind("click", function(){
						if ($(this).is(':checked')) {
							$(v_contentSet1).hide();
							$(v_contentSet2).show();
							$(v_rdoActivateSet1).attr('checked', false);
							$(v_rdoActivateSet2).attr('checked', true);
							$(v_rdoActivateSet1).attr('defaultChecked', false);
							$(v_rdoActivateSet2).attr('defaultChecked', true);
						}
					});
				});
				
				$(v_rdoActivateSet1).each(function(){
					$(this).bind("click", function(){
						$(v_contentSet2).hide();
						$(v_contentSet1).show();
						$(v_rdoActivateSet2).attr('checked', false);
						$(v_rdoActivateSet1).attr('checked', true);
						$(v_rdoActivateSet2).attr('defaultChecked', false);
						$(v_rdoActivateSet1).attr('defaultChecked', true);
					});
					
				});
			});
		}
		
		if ($(".row_box").length) {
			$(".row_box:first").addClass("first-child");
		}
		
//		if ($('#links_graph_data .name').length) {
//			$("#links_graph_data .name").textTruncate({
//				width: 140,
//				tail: '...',
//				tooltip: true
//			});
//		}
/*		
		if ($('#links_graph_data .name').length) {
		
			$('#links_graph_data .name').each(function(){
				var item_text = $(this).text();
				var original_length = item_text.length;
				var constrained = constrain(item_text, 118,'name');
				$(this).attr('title',item_text);
				$(this).html(constrained);
			});
		}
		
		if ($('#links_graph_data .link a').length) {
			$('#links_graph_data .link a').each(function(){
				var item_text = $(this).text();
				var original_length = item_text.length;
				var constrained = constrain(item_text, 440, 'link1');
				$(this).attr('title',item_text);
				$(this).html(constrained);
			});
		}
*/
/*
		if($("#textarea_ed1").length){
			var editor = CodeMirror.fromTextArea('textarea_ed1', {
		    height: "450px",
		    parserfile: "parsexml.js",
		    stylesheet: "CodeMirror/css/xmlcolors.css",
		    path: "CodeMirror/js/",
		    continuousScanning: 500
		  });
		}*/
		
		/*
		if ($('#selViewMode').length) {

			var TextBody = "Text!"
			var HTMLBody = "&lt;b&gt;HTML!&lt;/b&gt;"
			//$('#textarea_ed1').html(HTMLBody);
			$('#selViewMode').change(function(){ 
		        var viewMode = $("#selViewMode").val(); 
		 
		        if (viewMode == "HTML View") {
					$('.control_placeholder').removeClass('plain_view');
					$('.control_placeholder').addClass('html_view');
					$('.CodeMirror-wrapping iframe').contents().find('.editbox').html();
					
					$('.CodeMirror-wrapping textarea').appendTo('#email_editor');
					$('.CodeMirror-wrapping').remove();
					
					editor = CodeMirror.fromTextArea('textarea_ed1', {
					    height: "450px",
					    parserfile: "parsexml.js",
					    stylesheet: "CodeMirror/css/xmlcolors.css",
					    path: "CodeMirror/js/",
					    continuousScanning: 500
					});
				}
				
				else if(viewMode == "Plain Text View"){
					$(".control_placeholder").removeClass('html_view');
					$(".control_placeholder").addClass('plain_view');
					newContent = editor.getCode();
					$('.CodeMirror-wrapping textarea').appendTo('#email_editor');

					$('#textarea_ed1').css('display','block');
					$('#textarea_ed1').val(newContent);
					$('.CodeMirror-wrapping').remove();
					
				}
		    }); 
		}*/

		// Context Help
		if ($('#context_help').length) {
			var screen = $('#screen_name').text();
			if ((typeof screen == 'string') && (screen.length > 0)) {
				$('#context_help').loadHelp(screen);
			}
		}

    // simple collapsible panel (understanding your results)
    $("a.twisty").click(function(){
      $(this).toggleClass("twisted").next().slideToggle("slow");
    });
    
    $("a").click(function() {
		var $this = $(this);
		//Verify the link has an href and is not disabled
		if($this.attr("href") && !$this.hasClass("disabled")) {
			$("#loader").show();
		}
    });

	});

}

// Too plural or not to plural, is the question
function s(num){
    return (num != 1) ? "s" : "";
}

function s_has(num) {
    return (num != 1) ? "have" : "has";
}

/// Converts a value of any supported type into a true boolean
///    Supported Type: [string, int, int as string]
function to_b(some_boolean) {
    var parsed_bool = null;
    if (typeof (some_boolean) === 'boolean') {
        parsed_bool = some_boolean === true ? true
            : some_boolean === false ? false
                : null;
    } else if (typeof (some_boolean) === 'string') {
        parsed_bool = some_boolean.toLowerCase() === 'true' ? true
            : some_boolean.toLowerCase() === 'false' ? false
                : some_boolean.toLowerCase() === '0' ? false
                    : some_boolean.toLowerCase() === '1' ? true
                        : null;
    } else if (typeof (some_boolean) === 'number') {
        parsed_bool = some_boolean === 0 ? false
            : some_boolean === 1 ? true
                : null;
    }

    return parsed_bool;
}

var MILLISECOND=1;
var SECOND=MILLISECOND*1000;
var MINUTE=SECOND*60;
var HOUR=MINUTE*60;
var DAY=HOUR*24;
var YEAR=DAY*365;

function DateDiff(d1, d2, typ)
{
  d1 = (typeof(d1) == 'string')?new Date(d1):d1;
  d2 = (typeof(d2) == 'string')?new Date(d2):d2;
  var diff = d1.valueOf() - d2.valueOf();
  switch(typ)
  {
    case 'y':
      return Math.floor(diff/YEAR);
      break;
    case 'd':
      return Math.floor(diff/DAY);
      break;
    case 'h':
      return Math.floor(diff/HOUR);
      break;
    case 'm':
      return Math.floor(diff/MINUTE);
      break;
    case 's':
      return Math.floor(diff/SECOND);
      break;    
  }
  // Default: MILLISECOND
  return diff;
}

function DateAdd(d1, num, typ)
{
  d1 = (typeof(d1) == 'string')?new Date(d1):d1;
  return new Date(
      d1.getFullYear() + (typ=='y'?num:0)
      ,d1.getMonth() + (typ=='M'?num:0)
      ,d1.getDay() + (typ=='d'?num:0)
      ,d1.getHours() + (typ=='h'?num:0)
      ,d1.getMinutes() + (typ=='m'?num:0)
      ,d1.getSeconds() + (typ=='s'?num:0)
      ,d1.getMilliseconds() + (typ=='ms'?num:0)
    );
}

function validatePassword(password) {
    var result = {
        Success: 1,
        Message: "Validation Succeeded!"
    };

    // Verify that the password is the correct length
    if (password.length < 8) {
        result.Success = 0;
        result.Message = "Password must contain at least 8 characters";
        return result;
    }

    // Verify that the password is no more than 30 chars
    if (password.length > 30) {
        result.Success = 0;
        result.Message = "Password must not be greater than 30 characters";
        return result;
    }

    // Verify that the password contains at least 1 alpha character (case-insensitive)
    if (!password.match(/[a-zA-z]/)) {
        result.Success = 0;
        result.Message = "Password must contain at least 1 alpha character";
        return result;
    }

    // Verify that the password contains at least 1 numeric character
    if (!password.match(/[0-9]/)) {
        result.Success = 0;
        result.Message = "Password must contain at least 1 numeric character";
        return result;
    }

    // Verify that the password contains at least 1 special character [!"#$%&\()*+,/:;<=>?@[\]^`{|}~]
    var specialChars = /[!"#$%&()*+,\/:;<=>?@[\]^`{|}~]/;
    if (!password.match(specialChars)) {
        result.Success = 0;
        result.Message = "Password must contain at least 1 special character [!\"#$%&\()*+,/:;<=>?@[\]^`{|}~]";
        return result;
    }

    return result;
}

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;
	for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
		num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
	}
	return (((sign) ? "" : '-') + '$' + num + '.' + cents);
}






  
  (function($) {
    
    $.fn.extend({
      center: function() {
        this.css("position","absolute");
        this.css("top", ( $(window).height() - this.outerHeight() ) / 2+$(window).scrollTop() + "px");
        this.css("left", ( $(window).width() - this.outerWidth() ) / 2+$(window).scrollLeft() + "px");
        return this;
      }
    });
    
    
    if(typeof $.loader === "undefined") {
      $.loader = {
        init: function(params) {
          
          var defaults = {
            effect: "expand",
            duration: 500,
            overlay: true,
            status: "Loading. . .",
            message: "Please Wait"
          }
          
          this.visible = false;
          
          this.options = $.extend(defaults, params);
          this.overlay = $("<div class='ui-overlay'></div>");
          this.ui = $("<div class='ui-loading'></div>");
          this.message = $("<h3 class='ui-loading-message'></h3>").html(this.options.message);
          this.status = $("<h2 class='ui-loading-status'></h2>").text(this.options.status || "");
          this.indicator = $("<div class='ui-loading-indicator'></div>")
          
          //Center UI on window resize
          $(window).resize(function() {
            if($.loader.visible) {
              $.loader.ui.center();
              $.loader.overlay.css({height: "100%", width: "100%"});
            }
          }).unload(function() {
            if($.loader.visible) {
              $.loader.hide();
            }
          });
                    
          this.ui
              .append(this.message)
              .append(this.status)
              .append(this.indicator);
          
          return this;
          
        },
        show: function(params) {
          
          this.selfInit();
          this.visible = true;
          
          var defaults = {
            callback: null
          }
          
          var options = $.extend(defaults, params);
          
          this.overlay.appendTo(document.body).fadeTo(this.options.duration/2, 0.8, function() {
            
            //Lose the context of this, use $.load in place of this
            
            switch ($.loader.options.effect) {
              case "fade":
                $.loader.ui
                    .css("opacity", 0)
                    .appendTo(document.body)
                    .center()
                    .fadeTo($.loader.options.duration/2, 1, options.callback);
                break;
              case "animate":
                $.loader.ui
                    .appendTo(document.body)
                    .center()
                    .css("top", $.loader.ui.position().top - 25)
                    .animate({
                      top: $.loader.ui.position().top + 25,
                      opacity: 1
                    }, $.loader.options.duration/2, options.callback);
                break;
              case "expand":
              $.loader.ui.css("opacity", 0).appendTo(document.body);
                var ph = $.loader.ui.height();
                var pw = $.loader.ui.width();
                $.loader.ui
                    .center()
                    .css({height:"1px", width:"1px", opacity: 0})
                    .animate({
                      height: ph,
                      width: pw,
                      opacity: 1
                    }, $.loader.options.duration, options.callback)
                break;
              default:
                $.loader.hide();
                break;
            } // end switch
          
          });
          
          return this;
        },
        hide: function(params) {
          
          this.selfInit();
          this.visible = false;
          
          var defaults = {
            callback: function() {}
          }
          
          var options = $.extend(defaults, params);
          
          switch (this.options.effect) {
            case "fade":
              this.ui.fadeTo(this.options.duration/2, 0, function() {
                $.loader.overlay.fadeTo($.loader.options.duration/2, 0, function() {options.callback();$.loader.overlay.remove();});
                $.loader.ui.remove();
              });
              break;
            case "animate":
              this.ui.animate({
                top: $.loader.ui.position().top - 25,
                opacity: 0
              }, this.options.duration/2, function() {
                $.loader.overlay.fadeTo($.loader.options.duration/2, 0, function() {options.callback();$.loader.overlay.remove(); })
                $.loader.ui.remove();
              });
              break;
            case "expand":
              $.loader.ui.animate({
                height: 0,
                width: 0,
                opacity: 0
              }, $.loader.options.duration/2, function() {options.callback();$.loader.overlay.remove()});
              break;
            default:
              $.loader.ui.remove();
              $.loader.overlay.remove();
              options.callback();
              break;
          } // end Switch
          
          return this;
        },
        update: function(status) {
          this.selfInit();
          this.status.text(status);
          return this;
        },
        selfInit: function() {
          if(typeof this.ui === "undefined") { this.init(); }
          return this;
        }
      }
    }
  })(jQuery);
$(document).ready(function() {  
    $(".lazy-load").click(function () {
        $.loader.init().show();
    });
});

    function addCommas (num) {
        var i;
        if (typeof num === 'string') {
            num = parseInt(num);
        }
        num = num.toString();
        for (i = num.length - 3; i > 0; i -= 3) {
            num = num.substring(0, i) + ',' + num.substring(i);
        }
        return num;
    }
    function utcStringToDate (str) {
        if (typeof str === 'string') {
            if (navigator.appName === 'Microsoft Internet Explorer') {
                // account for the usual Microsoft silliness
                str = str.replace(/-/g, '/').replace(/T/g, ' ').replace(/\.\d*/g,'');
            }
            return new Date(str);
        }
    }

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		if (navigator.appName == 'Microsoft Internet Explorer') {
		    if (date) {
		    	if (typeof date === 'string') {
		    		date = date.replace(/-/g, '/').replace(/T/g, ' ').replace(/\.\d*/g,'');
		    	}
            }
        }

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};
    int_reg_ex = /^\d+$/; // matches strings made up entirely of digits
    function openAWindow (url, name, w, h) {
        var x = 0;
        var y = 0;
        var options;
        if ($.browser.msie) {//hacked together for IE browsers
            y = (document.documentElement.clientHeight + 120 - h) / 2 + (window.screenTop > 0 ? window.screenTop : 118) - 120;
            x = window.screenLeft + ((((document.body.offsetWidth + 20) / 2) - (w / 2)));
        } else {
            y = window.screenY + (((window.outerHeight / 2) - (h / 2)));
            x = window.screenX + (((window.outerWidth / 2) - (w / 2)));
        }
        x = Math.round(x);
        y = Math.round(y);
        options = 'height=' + h + ',width=' + w + ',toolbar=0,scrollbars=1,location=0,menubar=0,resizable=1,left=' + x + ',top=' + y;
        return window.open(url, name, options);
    };
    function conditionalExecute () {
        var funk;
        var i;
        try {
            if (arguments[0]) {
                funk = arguments[0];
                for (i = 1; i < arguments.length; i++) {
                    if (funk[arguments[i]]) {
                        funk = funk[arguments[i]];
                    } else {
                        throw new Error('arguments[' + i + '] is invalid');
                    }
                }
                if (typeof funk === 'function') {
                    funk();
                } else {
                    throw new Error('object produced is not a function');
                }
            }
        } catch (e) {
        }
    }
    var getConfirmationModal = (function ($) {
        var api = {
            close : function () {
                overlay_api.close();
            },
            open : function (options) {
                if (options) {
                    options = $.extend({}, settings, options);
                    confirmCallback = options.confirmCallback;
                    ui.heading.text(options.heading);
                    ui.body.html(options.body);
                    ui.button.text(options.button);
                    overlay_api.load();
                }
            }
        };
        var confirmCallback;
        var default_settings = {
            heading : 'Confirm?',
            body : 'Confirm or cancel?',
            button : 'Confirm',
            confirmCallback : function () {}
        };
        var overlay_api;
        var settings;
        var ui = {};
        return function (options) {
            if (!settings) {
                settings = $.extend({}, default_settings, options);
                buildModal();
            }
            return api;
        };
        function buildModal () {
            var html =  '<div id="overlay" class="confirm_delete_user"><a class="close"></a>' +
							'<div class="overlay_content">' +
								'<div id="confirm_delete_user" class="section">' +
		                            '<h2>Confirm?</h2>' +
		                            '<div class="section sub">' +
										'<div><div><div><div class="content">' +
		                                	'Confirm or cancel?' +
		                            	'</div></div></div></div>' +
									'</div>' +
		                            '<a id="delete_button" class="button confirm" href="javascript:void(0);"><span>Confirm</span></a>' +
		                            '<a id="cancel_button" class="cancel button" href="javascript:void(0);"><span>Cancel</span></a>' +
		                    	'</div>' +
							'</div>' +
							'<div class="bottom"></div>' +
						'</div>';
            ui.modal = $(html);
            $('body').append(ui.modal);
            ui.modal.hide();
            ui.heading = ui.modal.find('h2');
            ui.body = ui.modal.find('.section .content');
            ui.button = ui.modal.find('a.confirm span');
            ui.modal.find('a.cancel, a.close').click(function () {
                overlay_api.close();
            });
            ui.modal.find('a.confirm').click(function () {
                if (typeof confirmCallback == 'function') {
                    confirmCallback();
                }
                overlay_api.close();
            });
            overlay_api = ui.modal.overlay({
                top : '40%',
                mask : {
                    color : '#000000',
                    opacity : 0.5
                },
                load : false,
                closeOnEsc : true,
                closeOnClick : false,
                close : true
            }).data('overlay');
        }
    })(jQuery);
