$(document).ready(function(){

	// Scroll Pane
    $('.scroll').jScrollPane({wheelSpeed:120, showArrows:true, scrollbarWidth:18, arrowSize:22, animateTo:true, animateInterval:30, animateStep:12});
	$('.scrollTo').click(function() {
		var rel = $(this).attr('rel');
		if(rel.length > 0) {
			$('.scroll')[0].scrollTo('#'+rel);
			window.location.hash = '#scrollTo='+rel;
			return false;
		}
	});
	
	// Finder Menu
	$('#finder li, ul.dropdowns li').hover(
		function() {
			$(this).addClass('hover');
			$('#inset .search input')[0].blur();
		},
		function() {
			$(this).removeClass('hover');
		}
	);
	$('input').hover(function() {
		$('#finder li, ul.dropdowns li').removeClass('hover');
	});
	
	if(document.getElementById('overlay')) {
	    modal_init();
	}
	if(document.getElementById('topicMod')) {
		topicTabs_init();
	}
	if(document.getElementById('mainMods')) {
		rollup_init();
	}
	if(document.getElementById('discussionTabs')) {
		discussionTab_init();
	}
	if(document.getElementById('faqs')) {
		faqs_init();
	}
	if(document.getElementById('expertDockScroll')) {
		expertDock_init();
	}
	if(document.getElementById('videoSlider')) {
		filmstrip_init();
	}
	if(document.getElementById('blogArchiveMenu')) {
	    blogArchive_init();
	}
	if(document.getElementById('map_canvas')) {
        initMap();
    }
	
	$('.expandPost .headline a').click(function() {
		$(this).parent().parent().parent().toggleClass('showTeaser');
		return false;
	});
	
	$('ul.boards>li>a').click(function(e) {
	    e.preventDefault();
	    $(this.parentNode).toggleClass('open');
	});

});

function modal_init(area) {
    if(!area) area = document;
	// Modal Box
	$('#overlay, #modal .close a').click(function() {
	    return modal_close(this);
	});
	$(area).find('a.modal, a.modalLg').click(function(e) {
		e.preventDefault();
		if(this.rel.length > 0) {
		    var size = "modalMedium";
			if(this.className.indexOf('modalLg') >= 0) {
				size = "modalLarge";
			}
            modal_open(this.rel, size);
		}
	});
}
function modal_open(id, size) {
	// Reset the Fields in the Modal Window
    // clearModalFields();
	
	// Show the div that related to the anchor
    $('#'+id).removeClass('hide');
    //$('#modalContent>div').removeClass('hide');
	
	// Show the white overlay
	document.getElementById('overlay').className = "";
	
	// Show the modal window with the correct size
	var modal = document.getElementById('modal');
	if(size) {
	    modal.className = size;
	}
	else {
	    modal.className = "modalMedium";
	}
	
	// Reposition the modal on the window
	var modalContentHeight = document.getElementById('modalContent').clientHeight;
	var documentScroll = getScrollXY();
	var modalTop = documentScroll[1] + (document.documentElement.clientHeight / 2) - (modalContentHeight / 2) - 25;
	if(modalTop < documentScroll[1]) {
		modalTop = documentScroll[1];
	}
	modal.style.top = modalTop + "px";
	
	// Add jScrollPane
	$('#'+id+' .modalScroll').jScrollPane({wheelSpeed:120, showArrows:true, scrollbarWidth:18, arrowSize:22, animateTo:true, animateInterval:30, animateStep:12});
	
	// IE to hide old modal content
	$('#modalContent').toggleClass('changeClass');
}

// Modal Window Functions
function modal_close(object) {
    if(object) {
        object.focus();
    }
    else {
        this.focus();
    }
	$('#overlay, #modal').addClass('hide');
	$('#modalContent>div').addClass('hide');
	return false;
}

// Submit on Enter Key
// onkeypress="return enterKey(event,'id')"
function enterKey(event,code) {
	if(!event) {
		event = window.event;
	}
	if ((event.which || event.keyCode) && ((event.which == 13) || (event.keyCode == 13))) {
		var object = document.getElementById(code);
		if(object.tagName == 'A') {
		    eval(unescape(object.href.substr(11)));
		}
		else {
		    object.click();
		}
		return false;
	}
	else {
		return true;
	}
}

function clearModalFields() {
    var inputs = $('#modal input, #modal textarea');
    for(var x=0;x<inputs.length;x++) {
		if(inputs[x].type == "text") {
			inputs[x].value = "";
		}
    }
    var selects = $('#modal select');
    for(var x=0;x<selects.length;x++) {
        selects[x].selectedIndex = "0";
    }
}


// Input Focus and Blur controls
function inputFocus(object, css, defaultValue) {
    var val;
    if(defaultValue) val = defaultValue;
    else val = object.defaultValue;
    if(val == object.value) {
        object.value = "";
    }
    if(css) renderCSS(object, css);
}
function inputBlur(object, css, defaultValue) {
    if(object.value.trim() == "") {
        var val;
        if(defaultValue) val = defaultValue;
        else val = object.defaultValue;
        object.value = val;
        if(css) renderCSS(object, css);
    }
}
function renderCSS(object, css) {
    var attributes = css.split(';');
    for(var x=0;x<attributes.length;x++) {
        var elem = attributes[x].split(':');
        if(elem[0].trim() == 'text-align') {
            object.style.textAlign = elem[1].trim();
        }
        if(elem[0].trim() == 'color') {
            object.style.color = elem[1].trim();
        }
		if(elem[0].trim() == 'class') {
			object.className = elem[1].trim();
		}
    }
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}


// Mod Topic Tabs
function topicTabs_init() {
	var ols = $('#topicMod ol.tagCloud');
	var newHeight = 0;
	for(var x=0;x<ols.length;x++) {
		if(ols[x].clientHeight > newHeight) {
			newHeight = ols[x].clientHeight;
		}
	}
	$('#topicMod .topicBody').height(newHeight);
	$('#homeMods, #mainMods').addClass('checkheight'); // ie6 crap
}
function topicTabs(tab) {
	document.getElementById('topicMod').className = "mod";
	$('#topicMod').addClass(tab);
	$('#homeMods, #mainMods').toggleClass('checkheight'); // ie6 crap
}



// Rollup Mods
var rollup_height = 130;
var colLoadedHeight = null;
var rollup_bottom = 0;
var rollup_start = 130;
var rollup_status = "closed";
var rollup_time;
function rollup_init() {
	rollup_height = $('#mainMods .wrap').height() + 59 - rollup_start;
}
function rollup_toggle() {
	if($('#rollupTab span').text() == "Expand") {
		rollup_expand();
	}
	else {
		rollup_hide();
	}
}
function rollup_expand() {
    
    colLoadedHeight = $("#columns").height();

	if(rollup_status == "closed") {
		var bodyHeight = $("#page").height();
		var wrapHeight = $("#mainMods .wrap").height();
		
		if (wrapHeight > bodyHeight) {
		    var wrapHeight = wrapHeight - 375;
			$("#columns").height(wrapHeight);
		}
		rollup_time = setInterval('rollup_open()', 30);
		rollup_status = "opening";
	}
	else {
		rollup_status = "open";
		$('#mainMods').css('height',rollup_height + rollup_start + 'px');
		$('#rollupTab span').text('Hide');
	}
}
function rollup_open() {
	rollup_bottom = Math.ceil(rollup_bottom + ((rollup_height - rollup_bottom) / 8) + 1);
	$('#mainMods').toggleClass('changeState');
	if(rollup_bottom >= rollup_height) {
		rollup_bottom = rollup_height;
		clearInterval(rollup_time);
		rollup_status = "open";
		$('#mainMods').css('height',rollup_height + rollup_start + 'px');
		$('#rollupTab span').text('Hide');
	}
	else {
		$('#mainMods').css('height',rollup_bottom + rollup_start + 'px');
	}
}
function rollup_hide() {
	if(rollup_status == "open") {
		rollup_time = setInterval('rollup_close()', 30);
		rollup_status = "closing";
		var dynamicColHeight = $("#columns").height();
		if (dynamicColHeight != colLoadedHeight){
			$("#columns").height(colLoadedHeight);
		}
	}
	else {
		rollup_status = "closed";
		$('#mainMods').css('height',rollup_start + 'px');
		$('#rollupTab span').text('Expand');
	}
}
function rollup_close() {
	rollup_bottom = Math.ceil(rollup_bottom - (rollup_bottom / 8) - 1);
	$('#mainMods').toggleClass('changeState');
	if(rollup_bottom <= 0) {
		rollup_bottom = 0;
		clearInterval(rollup_time);
		rollup_status = "closed";
		$('#mainMods').css('height',rollup_bottom + rollup_start + 'px');
		$('#rollupTab span').text('Expand');
	}
	else {
		$('#mainMods').css('height',rollup_bottom + rollup_start + 'px');
	}
}


function discussionTab_init() {
	$('#discussionTabs .tab a').click(function() {
		var object = this.parentNode.parentNode;
		if(object.className == "open") {
			object.className = "";
		}
		else {
			object.className = "open";
		}
		return false;
	});
	$('#expandBoards a').click(function() {
		$('#discussionTabs>li').addClass('open');
		return false;
	});
}

function faqs_init() {
	$('#faqs .question a').click(function() {
		var object = this.parentNode.parentNode;
		if(object.className == "active") {
			object.className = "";
		}
		else {
			object.className = "active";
		}
		return false;
	});
}


function HelpPopup(href) {
	var popup = window.open(href,"helpWin","scrollbars=1,menubar=0,resizable=1,width=400,height=200");
	popup.focus();
}

function expertDock_init() {
	var dockScroll = new filmstrip(document.getElementById('expertDockScroll'),document.getElementById('expertDockUp'),document.getElementById('expertDockDown'));
	dockScroll.settings.direction = 1;
	dockScroll.settings.totalVisible = 1;
	dockScroll.anim.duration = 30;
	dockScroll.events.onBeforeMove = function() {
		document.getElementById('expertDockSelected').style.display = "none";
		document.getElementById('expertDockImage').style.display = "none";
	};
	dockScroll.events.onMoveComplete = function() {
		var currentSlide = document.getElementById(dockScroll.settings.prefix + dockScroll.current);
		document.getElementById('expertDockAnchor').innerHTML = $(currentSlide).find('.anchor').html();
		document.getElementById('expertDockImage').innerHTML = $(currentSlide).find('.image').html();
		document.getElementById('expertDockSelected').style.display = "block";
		document.getElementById('expertDockImage').style.display = "block";
	};
	
	dockScroll.init();

}

// Filmstrip Slider
function filmstrip(frame, next, previous) {
	var self = this;
	this.current = 1;
	this.count = 1;
	this.settings = {direction:0, totalVisible:1, prefix:"", trimEnding:false, disableWrap:false, setRotate:0, scrollWheel:false};
	this.events = {onBeforeMove:null, onMoveComplete:null};
	this.frame = frame;
	this.next = next;
	this.previous = previous;
	this.anim = {time:0, begin:0, change:0.0, timer:null, duration:50, speed:15, rotate:null};
	this.init = function() {
		if(this.frame.id.length > 0 && this.settings.prefix.length < 1) {
			this.settings.prefix = this.frame.id + '_';
		}
		
		var slides = this.frame.getElementsByTagName('li');
		this.count = slides.length;
		for(var x=0;x<this.count;x++) {
			slides[x].id = this.settings.prefix + (x+1);
		}
		
		var wrapper = this.frame.getElementsByTagName('ul')[0];
		if(this.settings.direction == 0) {
			wrapper.style.width = slides[0].offsetWidth * (slides.length + this.settings.totalVisible) + "px";
			//wrapper.style.paddingRight = this.frame.offsetWidth + "px"
		}
		else {
			//wrapper.style.height = slides[0].offsetHeight * (slides.length + this.settings.totalVisible) + "px";
			wrapper.style.paddingBottom = this.frame.offsetHeight + "px"
		}
		
		if(this.settings.scrollWheel) {
			this.initWheel();
		}
		
		this.go(1);
		
		if(this.settings.setRotate > 0) {
			this.anim.rotate = setTimeout(function() { self.moveNext(); }, this.settings.setRotate);
		}
		
		if(this.next) {
			this.next.onclick = function() {
				self.moveNext();
				return false;
			}
		}
		if(this.previous) {
			this.previous.onclick = function() {
				self.movePrevious();
				return false;
			}
		}
	}
	this.go = function(num) {
		this.current = num;
		clearTimeout(this.anim.rotate);
		
		if(this.events.onBeforeMove) {
			this.events.onBeforeMove();
		}
		
		var position = this.findElementPos(document.getElementById(this.settings.prefix + this.current));
		var offsetPos = this.findElementPos(document.getElementById(this.settings.prefix + 1));
		position[this.settings.direction] = position[this.settings.direction] - offsetPos[this.settings.direction];
		
		var scrollOffset = 0;
		if(this.settings.direction == 0) {
			scrollOffset = this.frame.scrollLeft;
		}
		else if(this.settings.direction == 1) {
			scrollOffset = this.frame.scrollTop;
		}
		
		if (this.anim.timer != null) {
			clearInterval(this.anim.timer);
			this.anim.timer = null;
		}
		this.anim.time = 0;
		this.anim.begin = scrollOffset;
		this.anim.change = position[this.settings.direction] - scrollOffset;
		
		this.anim.timer = setInterval(function() { self.scroll(); }, this.anim.speed);
	}
	this.scroll = function() {
		if (this.anim.time > this.anim.duration) {
			clearInterval(this.anim.timer);
			this.anim.timer = null;
			
			if(this.settings.setRotate > 0) {
				this.anim.rotate = setTimeout(function() { self.moveNext(); }, this.settings.setRotate);
			}
			if(this.events.onMoveComplete) {
				this.events.onMoveComplete();
			}
		}
		else {
			var move = this.sineInOut(this.anim.time, this.anim.begin, this.anim.change, this.anim.duration);
			if(this.settings.direction == 0) {
				this.frame.scrollLeft = move;
			}
			else if(this.settings.direction == 1) {
				this.frame.scrollTop = move;
			}
			this.anim.time++;
		}
	}
	this.moveNext = function() {
		var num = this.current + 1;
		if((this.settings.trimEnding && num > this.count - this.settings.totalVisible + 1) || (!this.settings.trimEnding && num > this.count)) {
			if(this.settings.disableWrap) {
				return false;
			}
			else {
				num = 1;
			}
		}
		this.go(num);
	}
	this.movePrevious = function() {
		var num = this.current - 1;
		if(num < 1) {
			if(this.settings.disableWrap) {
				return false;
			}
			else {
				if(this.settings.trimEnding) {
					num = this.count - this.settings.totalVisible + 1;
				}
				else {
					num = this.count;
				}
			}
		}
		this.go(num);
	}
	this.initWheel = function() {
		if (this.frame.addEventListener) {
			/** DOMMouseScroll is for mozilla. */
			this.frame.addEventListener('DOMMouseScroll', this.slideEventWheel, false);
		}
		/** IE/Opera. */
		this.frame.onmousewheel = this.slideEventWheel;
	}
	this.slideEventWheel = function(event) {
        var delta = 0;
        if (!event) /* For IE. */
                event = window.event;
        if (event.wheelDelta) { /* IE/Opera. */
                delta = event.wheelDelta/120;
        } else if (event.detail) { /** Mozilla case. */
                delta = -event.detail/3;
        }
        if (delta) {
			if(delta < 0) {
				self.moveNext();
			}
			else {
				self.movePrevious();
			}
		}
        if (event.preventDefault)
			event.preventDefault();
		event.returnValue = false;
	}
}
filmstrip.prototype.findElementPos = function(elemFind) {
	var elemX = 0;
	var elemY = 0;
	do {
		elemX += elemFind.offsetLeft;
		elemY += elemFind.offsetTop;
	} while ( elemFind = elemFind.offsetParent )
	return Array(elemX, elemY);
}
filmstrip.prototype.sineInOut = function(t, b, c, d) {
	return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
}


function clearAddForm() {
    window.location = window.location;
}
function CommunityTabFix() {
    $('#mainMods').toggleClass('changeState');
    setTimeout(function() { $('#mainMods').toggleClass('changeState'); }, 3000);
}

function blogArchive_init() {
    $('#blogArchiveMenu span.year').click(function() {
        var parent = this.parentNode;
        if(parent.className == "closed") {
            parent.className = "opened";
        }
        else {
            parent.className = "closed";
        }
    });
}



/*
    BEGIN
    Script added for the AG Rss News on the Master page
*/
var headline_count;
var headline_interval;
var old_headline = 0;
var current_headline = 0;

$(document).ready(function() {
    headline_count = $("div.agHeadline").size();
    $("div.agHeadline:eq(" + current_headline + ")").css('top', '0px');

    headline_interval = setInterval(headline_rotate, 5000); //time in milliseconds
    $('.agHeadline a').hover(function() {
        clearInterval(headline_interval);
    }, function() {
        headline_interval = setInterval(headline_rotate, 5000); //time in milliseconds
        headline_rotate();
    });
});

function headline_rotate() {
    current_headline = (old_headline + 1) % headline_count; //remainder will always equal old_headline until it reaches headline_count - at which point it becomes zero. clock arithmetic
    $("div.agHeadline:eq(" + old_headline + ")").animate({ top: -200 }, "slow", function() {
        $(this).css('top', '200px');
    });
    $("div.agHeadline:eq(" + current_headline + ")").show().animate({ top: 0 }, "slow");
    old_headline = current_headline;
}
/*
    END
    Script added for the AG Rss News on the Master page
*/

// md_EditProfile script.
var _editProfileHiddenClassName = "hide"; 
function showEditProfileSection(){
    $(".edit"+$(this).attr("section")).removeClass(_editProfileHiddenClassName);
    $(".display"+$(this).attr("section")).addClass(_editProfileHiddenClassName);
}
function hideEditProfileSection(){
    $(".edit"+$(this).attr("section")).addClass(_editProfileHiddenClassName);
    $(".display"+$(this).attr("section")).removeClass(_editProfileHiddenClassName);	
}
$(document).ready(function(){
    $(".EditTrigger").click(showEditProfileSection);
    $(".CancelTrigger").click(hideEditProfileSection);
});

/* Horizontal Video Scroll 
------------------------------------ */

var filmstrip_num = 1;
var filmstrip_count = 0;

function filmstrip_init() {
	$('.sliderWindow').scrollLeft = 0;
	var frames = $('.slide a');
	filmstrip_count = frames.length;
	
	if(filmstrip_count > 3) {
	    $('#slideLeft').css('display','block');
		$('#slideRight').css('display','block');
		$('#slideLeft').addClass('disabled');
	}
	
	for(var x=0;x<filmstrip_count;x++) {frames[x].id = 'film-frame'+(x+1);}
	
	$('#slideRight').click(function() {filmstrip_left(); return false;});
	$('#slideLeft').click(function() {filmstrip_right(); return false;});
	
}

function filmstrip_left() {
	filmstrip_num++;
	if(filmstrip_num > filmstrip_count - 2) {
		filmstrip_num = filmstrip_count - 2;
	}
	else {
		filmstrip_move(filmstrip_num);
	}
}
function filmstrip_right() {
	filmstrip_num--;
	
	if(filmstrip_num < 1) {
		filmstrip_num = 1;
	}
	else {
		filmstrip_move(filmstrip_num);
	}
}

function filmstrip_buttons() {
	if(filmstrip_num >= filmstrip_count - 2) {
		$('#slideRight').addClass('disabled');
		$('#slideLeft').removeClass('disabled');
	}
	else if(filmstrip_num <= 1) {
		$('#slideLeft').addClass('disabled');
		$('#slideRight').removeClass('disabled');
	} 
	else {
		$('#slideLeft').removeClass('disabled');
		$('#slideRight').removeClass('disabled');
	}
}

function filmstrip_move(num) {
	filmstrip_buttons();

	var theScroll = $(".sliderWindow")[0];
	var position = findElementPos(document.getElementById("film-frame" + num));
	var offsetPos = findElementPos(document.getElementById('film-frame1'));
	position[0] = position[0] - offsetPos[0];
	filmstrip_start(theScroll, theScroll.scrollLeft, position[0]);
}

var filmstrip_anim = {time:0, begin:0, change:0.0, duration:0.0, element:null, timer:null};

function filmstrip_start(elem, start, end)
{

	if (filmstrip_anim.timer != null) {
		clearInterval(filmstrip_anim.timer);
		filmstrip_anim.timer = null;
	}
	filmstrip_anim.time = 0;
	filmstrip_anim.begin = start;
	filmstrip_anim.change = end - start;
	filmstrip_anim.duration = 50;
	filmstrip_anim.element = elem;
	
	filmstrip_anim.timer = setInterval("filmstrip_scroll();", 15);

}
function filmstrip_scroll()
{
	if (filmstrip_anim.time > filmstrip_anim.duration) {
		clearInterval(filmstrip_anim.timer);
		filmstrip_anim.timer = null;
	}
	else {
		move = sineInOut(filmstrip_anim.time, filmstrip_anim.begin, filmstrip_anim.change, filmstrip_anim.duration);
		filmstrip_anim.element.scrollLeft = move;
		filmstrip_anim.time++;
	}
}

function findElementPos(elemFind)
{
	var elemX = 0;
	var elemY = 0;
	do {
		elemX += elemFind.offsetLeft;
		elemY += elemFind.offsetTop;
	} while ( elemFind = elemFind.offsetParent )
	return Array(elemX, elemY);
}

function sineInOut(t, b, c, d)
{
	return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
}

// Homepage population functions
function populateGroups(d) {
	$("#groupDescription").html(d);
}

function populateSpotLight(d) {
	$("#spotLightDescription").html(d);
}

function clickOnce(object) {
	if (object.rel != "clicked")
	{
	    object.rel = "clicked";
	    return true;
	}
    else
    {
        return false;
    }	
}

// Groups Remove Functionality
function RemoveUserFromGroup(userId, groupId) {
    var DTO = { 'UserID' : userId, 'GroupID' : groupId };

    $.ajax({
        type:"POST",
        url:"md_Groups.asmx/RemoveUserFromGroup",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(DTO),
        dataType: "json",
        success: function(result, textStatus) {
            location.reload();
        }
    });
}

// Groups Invite Functionality
function SwitchInviteTab(tab) {
    switch(tab)
    {
        case 'friends':
            $('div.FriendsTab').css('display', 'block');
            $('div.SelectedTab').css('display', 'none');
            $('div.SearchTab').css('display', 'none');
            
            $('ul.friendsInvitation input:checkbox').unbind();
            $('ul.friendsInvitation input:checkbox').click(function(){
                $(this).parent().appendTo('ul.SelectedPeopleList');
                $('#selectedCount').text(parseInt($('#selectedCount').text()) + 1);
            });
            break;
        case 'search':
            $('div.SearchTab').css('display', 'block');
            $('div.FriendsTab').css('display', 'none');
            $('div.SelectedTab').css('display', 'none');
            break;
        case 'selected':
            $('div.SelectedTab').css('display', 'block');
            $('div.FriendsTab').css('display', 'none');
            $('div.SearchTab').css('display', 'none');
            
            $('ul.SelectedPeopleList input:checkbox').unbind();
            $('ul.SelectedPeopleList input:checkbox').click(function() {
                if ($(this).attr('id').indexOf('friend') >= 0) {
                    $(this).parent().appendTo('ul.friendsInvitation');
                    $('#selectedCount').text(parseInt($('#selectedCount').text()) - 1);
                }
                else {
                    $(this).parent().remove();
                    $('#selectedCount').text(parseInt($('#selectedCount').text()) - 1);        
                }
            });
            break;
    }
}

function RunInviteSearch(userId) {
    var DTO = { 'Term' : $('#txtSearch').val(), 'UserID' : userId, 'Page' : 1 };

    $.ajax( {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "md_Groups.asmx/RunInviteSearch",
        data: JSON.stringify(DTO),
        dataType: "json",
        success: function(result, textStatus) {
            $('#searchResults').html(result);
            
            $('ul.SearchList input:checkbox').unbind();
            $('ul.SearchList input:checkbox').click(function() {
                $(this).parent().appendTo('ul.SelectedPeopleList');
                $('#selectedCount').text(parseInt($('#selectedCount').text()) + 1);
            });                     
        }
    });
}

function SetInviteSearchPage(term, userId, page) {
    var DTO = { 'Term' : term, 'UserID' : userId, 'Page' : page };
    
    $.ajax( {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "md_Groups.asmx/RunInviteSearch",
        data: JSON.stringify(DTO),
        dataType: "json",
        success: function(result, textStatus) {
            $('#searchResults').html(result);
            
            $('ul.SearchList input:checkbox').unbind();
            $('ul.SearchList input:checkbox').click(function() {
                $(this).parent().appendTo('ul.SelectedPeopleList');
                $('#selectedCount').text(parseInt($('#selectedCount').text()) + 1);
            });                     
        }
    });
}

function SubmitInvitation(userId, groupId) {
    var users = new Array();
    var count = 0;
    
    $('ul.SelectedPeopleList input:checkbox').each(function() {
        var user = parseInt($(this).attr('id').substring($(this).attr('id').indexOf('_') + 1));
        users[count] = user;
        count++;
    });
    
    var DTO = { 'Users' : users, 'Group' : groupId, 'message' : $('#txtPersonalMessage').val(), 'loggedInUser' : userId };
    
    $.ajax( {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "md_Groups.asmx/SendInvitation",
        data: JSON.stringify(DTO),
        dataType: "json",
        success: function(result, textStatus) {
            $('#invitationResult').text('Your invitation has been sent.');
            modal_open('invitationResult', 'modalMedium');            
        },
        error: function(request, status, err) {
            $('#invitationResult').html('There was a problem with sending the invitation.<br /><br />');
            modal_open('invitationResult', 'modalMedium');
        }
    });
}